#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright: (c) 2018-2019, Andrew Klychkov (@Andersson007) <aaklychkov@mail.ru>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}

DOCUMENTATION = r'''
---
module: postgresql_idx
short_description: Create or drop indexes from a PostgreSQL database
description:
- Create or drop indexes from a PostgreSQL database.
version_added: '2.8'

options:
  idxname:
    description:
    - Name of the index to create or drop.
    type: str
    required: true
    aliases:
    - name
  db:
    description:
    - Name of database to connect to and where the index will be created/dropped.
    type: str
    aliases:
    - login_db
  session_role:
    description:
    - Switch to session_role after connecting.
      The specified session_role must be a role that the current login_user is a member of.
    - Permissions checking for SQL commands is carried out as though
      the session_role were the one that had logged in originally.
    type: str
  schema:
    description:
    - Name of a database schema where the index will be created.
    type: str
  state:
    description:
    - Index state.
    - C(present) implies the index will be created if it does not exist.
    - C(absent) implies the index will be dropped if it exists.
    - C(stat) returns index statistics information from the ``pg_stat_user_indexes`` standard view.
      Supported from Ansible 2.10.
    - "When C(stat) following parameters will be ignored:"
    - I(schema), I(table), I(columns), I(cond), I(idxtype), I(tablespace), I(concurrent), I(cascade).
    type: str
    default: present
    choices: [ absent, present, stat ]
  table:
    description:
    - Table to create index on it.
    - Mutually exclusive with I(state=absent).
    type: str
    required: true
  columns:
    description:
    - List of index columns that need to be covered by index.
    - Mutually exclusive with I(state=absent).
    type: list
    elements: str
    aliases:
    - column
  cond:
    description:
    - Index conditions.
    - Mutually exclusive with I(state=absent).
    type: str
  idxtype:
    description:
    - Index type (like btree, gist, gin, etc.).
    - Mutually exclusive with I(state=absent).
    type: str
    aliases:
    - type
  concurrent:
    description:
    - Enable or disable concurrent mode (CREATE / DROP INDEX CONCURRENTLY).
    - Pay attention, if I(concurrent=no), the table will be locked (ACCESS EXCLUSIVE) during the building process.
      For more information about the lock levels see U(https://www.postgresql.org/docs/current/explicit-locking.html).
    - If the building process was interrupted for any reason when I(cuncurrent=yes), the index becomes invalid.
      In this case it should be dropped and created again.
    - Mutually exclusive with I(cascade=yes).
    type: bool
    default: yes
  unique:
    description:
    - Enable unique index.
    - Only btree currently supports unique indexes.
    type: bool
    default: no
    version_added: '2.10'
  tablespace:
    description:
    - Set a tablespace for the index.
    - Mutually exclusive with I(state=absent).
    required: false
    type: str
  storage_params:
    description:
    - Storage parameters like fillfactor, vacuum_cleanup_index_scale_factor, etc.
    - Mutually exclusive with I(state=absent).
    type: list
    elements: str
  cascade:
    description:
    - Automatically drop objects that depend on the index,
      and in turn all objects that depend on those objects.
    - It used only with I(state=absent).
    - Mutually exclusive with I(concurrent=yes)
    type: bool
    default: no

seealso:
- module: postgresql_table
- module: postgresql_tablespace
- name: PostgreSQL indexes reference
  description: General information about PostgreSQL indexes.
  link: https://www.postgresql.org/docs/current/indexes.html
- name: CREATE INDEX reference
  description: Complete reference of the CREATE INDEX command documentation.
  link: https://www.postgresql.org/docs/current/sql-createindex.html
- name: ALTER INDEX reference
  description: Complete reference of the ALTER INDEX command documentation.
  link: https://www.postgresql.org/docs/current/sql-alterindex.html
- name: DROP INDEX reference
  description: Complete reference of the DROP INDEX command documentation.
  link: https://www.postgresql.org/docs/current/sql-dropindex.html

notes:
- The index building process can affect database perf
ormance.
- To avoid table locks on production databases, use I(concurrent=yes) (default behavior).

author:
- Andrew Klychkov (@Andersson007)

extends_documentation_fragment: postgres
'''

EXAMPLES = r'''
- name: Create btree index if not exists test_idx concurrently covering columns id and name 
of table products
  postgresql_idx:
    db: acme
    table: products
    columns: id,name
    name: test_idx

- name: Create btree index test_idx concurrently with tablespace called ssd and storage parameter
  postgresql_idx:
    db: acme
    table: products
    columns:
    - id
    - name
    idxname: test_idx
    tablespace: ssd
    storage_params:
    - fillfactor=90

- name: Create gist index test_gist_idx concurrently on column geo_data of table map
  postgresql_idx:
    db: somedb
    table: map
    idxtype: gist
    columns: geo_data
    idxname: test_gist_idx

# Note: for the example below pg_trgm extension must be installed for gin_trgm_ops
- name: Create gin index gin0_idx not concurrently on column comment of table test
  postgresql_idx:
    idxname: gin0_idx
    table: test
    columns: comment gin_trgm_ops
    concurrent: no
    idxtype: gin

- name: Drop btree test_idx concurrently
  postgresql_idx:
    db: mydb
    idxname: test_idx
    state: absent

- name: Drop test_idx cascade
  postgresql_idx:
    db: mydb
    idxname: test_idx
    state: absent
    cascade: yes
    concurrent: no

- name: Create btree index test_idx concurrently on columns id,comment where column id > 1
  postgresql_idx:
    db: mydb
    table: test
    columns: id,comment
    idxname: test_idx
    cond: id > 1

- name: Get index statistics of test_idx from mydb
  postgresql_idx:
    db: mydb
    idxname: test_idx
    state: stat

- name: Create unique btree index if not exists test_unique_idx on column name of table products
  postgresql_idx:
    db: acme
    table: products
    columns: name
    name: test_unique_idx
    unique: yes
    concurrent: no
'''

RETURN = r'''
name:
  description: Index name.
  returned: always
  type: str
  sample: 'foo_idx'
state:
  description: Index state.
  returned: always
  type: str
  sample: 'present'
schema:
  description: Schema where index exists.
  returned: always
  type: str
  sample: 'public'
tablespace:
  description: Tablespace where index exists.
  returned: always
  type: str
  sample: 'ssd'
query:
  description: Query that was tried to be executed.
  returned: always
  type: str
  sample: 'CREATE INDEX CONCURRENTLY foo_idx ON test_table USING BTREE (id)'
storage_params:
  description: Index storage parameters.
  returned: always
  type: list
  sample: [ "fillfactor=90" ]
valid:
  description: Index validity.
  returned: always
  type: bool
  sample: true
stat:
  description: Index statistics.
  returned: if state is stat
  type: bool
  sample: { 'idx_scan': 19239, 'idx_tup_read': 929329, 'idx_tup_fetch': 4949459 }
'''

try:
    from psycopg2.extras import DictCursor
except ImportError:
    # psycopg2 is checked by connect_to_db()
    # from ansible.module_utils.postgres
    pass

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.postgres import (
    connect_to_db,
    exec_sql,
    get_conn_params,
    postgres_common_argument_spec,
)


VALID_IDX_TYPES = ('BTREE', 'HASH', 'GIST', 'SPGIST', 'GIN', 'BRIN')


# ===========================================
# PostgreSQL module specific support methods.
#

class Index(object):

    """Class for working with PostgreSQL indexes.

    TODO:
   