
    VhM                         d dl mZmZmZ eZdZdZdZd dl	Z	d dl
mZ d dlmZ d dlmZ d d	lmZmZmZmZmZmZmZ g Zd
 Zd Zd Zd Zd Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functiona  
---
module: postgresql_ext
short_description: Add or remove PostgreSQL extensions from a database
description:
- Add or remove PostgreSQL extensions from a database.
options:
  name:
    description:
    - Name of the extension to add or remove.
    required: true
    type: str
    aliases:
    - ext
  login_db:
    description:
    - Name of the database to add or remove the extension to/from.
    - The V(db) alias is deprecated and will be removed in version 5.0.0.
    required: true
    type: str
    aliases:
    - db
  schema:
    description:
    - Name of the schema to add the extension to.
    type: str
  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
  state:
    description:
    - The database extension state.
    default: present
    choices: [ absent, present ]
    type: str
  cascade:
    description:
    - Automatically install/remove any extensions that this extension depends on
      that are not already installed/removed (supported since PostgreSQL 9.6).
    type: bool
    default: false
  login_unix_socket:
    description:
      - Path to a Unix domain socket for local connections.
    type: str
  ssl_mode:
    description:
      - Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server.
      - See U(https://www.postgresql.org/docs/current/static/libpq-ssl.html) for more information on the modes.
      - Default of C(prefer) matches libpq default.
    type: str
    default: prefer
    choices: [ allow, disable, prefer, require, verify-ca, verify-full ]
  ca_cert:
    description:
      - Specifies the name of a file containing SSL certificate authority (CA) certificate(s).
      - If the file exists, the server's certificate will be verified to be signed by one of these authorities.
    type: str
    aliases: [ ssl_rootcert ]
  version:
    description:
      - Extension version to add or update to. Has effect with I(state=present) only.
      - If not specified and extension is not installed in the database,
        the latest version available will be created.
      - If extension is already installed, will update to the given version if a valid update
        path exists.
      - Downgrading is only supported if the extension provides a downgrade path otherwise
        the extension must be removed and a lower version of the extension must be made available.
      - Set I(version=latest) to update the extension to the latest available version.
    type: str
  trust_input:
    description:
    - If C(false), check whether values of parameters I(ext), I(schema),
      I(version), I(session_role) are potentially dangerous.
    - It makes sense to use C(false) only when SQL injections via the parameters are possible.
    type: bool
    default: true
    version_added: '0.2.0'
  comment:
    description:
    - Sets a comment on the extension.
    - To reset the comment, pass an empty string.
    type: str
    version_added: '3.3.0'

seealso:
- name: PostgreSQL extensions
  description: General information about PostgreSQL extensions.
  link: https://www.postgresql.org/docs/current/external-extensions.html
- name: CREATE EXTENSION reference
  description: Complete reference of the CREATE EXTENSION command documentation.
  link: https://www.postgresql.org/docs/current/sql-createextension.html
- name: ALTER EXTENSION reference
  description: Complete reference of the ALTER EXTENSION command documentation.
  link: https://www.postgresql.org/docs/current/sql-alterextension.html
- name: DROP EXTENSION reference
  description: Complete reference of the DROP EXTENSION command documentation.
  link: https://www.postgresql.org/docs/current/sql-droppublication.html

notes:
- Incomparable versions, for example PostGIS ``unpackaged``, cannot be installed.

attributes:
  check_mode:
    support: full

author:
- Daniel Schep (@dschep)
- Thomas O'Donnell (@andytom)
- Sandro Santilli (@strk)
- Andrew Klychkov (@Andersson007)
- Keith Fiske (@keithf4)
- Daniele Giudice (@RealGreenDragon)

extends_documentation_fragment:
- community.postgresql.postgres
a  
- name: Adds postgis extension to the database acme in the schema foo
  community.postgresql.postgresql_ext:
    name: postgis
    login_db: acme
    schema: foo
    comment: Test extension

- name: Removes postgis extension to the database acme
  community.postgresql.postgresql_ext:
    name: postgis
    login_db: acme
    state: absent

- name: Adds earthdistance extension to the database template1 cascade
  community.postgresql.postgresql_ext:
    name: earthdistance
    login_db: template1
    cascade: true

# In the example below, if earthdistance extension is installed,
# it will be removed too because it depends on cube:
- name: Removes cube extension from the database acme cascade
  community.postgresql.postgresql_ext:
    name: cube
    login_db: acme
    cascade: true
    state: absent

- name: Create extension foo of version 1.2 or update it to that version if it's already created and a valid update path exists
  community.postgresql.postgresql_ext:
    login_db: acme
    name: foo
    version: 1.2

- name: Create the latest available version of extension foo. If already installed, update it to the latest version
  community.postgresql.postgresql_ext:
    login_db: acme
    name: foo
    version: latest
a  
queries:
  description: List of executed queries.
  returned: success
  type: list
  sample: ["DROP EXTENSION \"acme\""]
prev_version:
  description: Previous installed extension version or empty string if the extension was not installed.
  returned: success
  type: str
  sample: '1.0'
  version_added: '3.1.0'
version:
  description: Current installed extension version or empty string if the extension is not installed.
  returned: success
  type: str
  sample: '2.0'
  version_added: '3.1.0'
N)	to_native)AnsibleModule)check_input)connect_to_dbensure_required_libsget_commentget_conn_paramspg_cursor_argspostgres_common_argument_specset_commentc                     d|z  }|r|dz  }| s|j                  |       t        j                  |j                  |             y)zRemove the extension from the database.

    Return True if success.

    Args:
      cursor (cursor) -- cursor object of psycopg library
      ext (str) -- extension name
      cascade (boolean) -- Pass the CASCADE flag to the DROP command
    zDROP EXTENSION "%s" CASCADETexecuteexecuted_queriesappendmogrify)
check_modecursorextcascadequerys        w/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_ext.py
ext_deleter      sD     $c)EuFNN512    c                     d|z  }i }|dk7  r
|dz  }||d<   | s|j                  ||       t        j                  |j                  ||             y)zUpdate extension version.

    Return True if success.

    Args:
      cursor (cursor) -- cursor object of psycopg library
      ext (str) -- extension name
      version (str) -- extension version
    zALTER EXTENSION "%s" UPDATElatestz TO %(ver)sverTr   )r   r   r   versionr   paramss         r   ext_update_versionr$      s[     ,c1EF(uuf%FNN5&9:r   c                     d|z  }i }|r|d|z  z  }|dk7  r
|dz  }||d<   |r|dz  }| s|j                  ||       t        j                  |j                  ||             y)ai  
    Create the extension objects inside the database.

    Return True if success.

    Args:
      cursor (cursor) -- cursor object of psycopg library
      ext (str) -- extension name
      schema (str) -- target schema for extension objects
      cascade (boolean) -- Pass the CASCADE flag to the CREATE command
      version (str) -- extension version
    zCREATE EXTENSION "%s"z WITH SCHEMA "%s"r    z VERSION %(ver)sr!   r   Tr   )r   r   r   schemar   r"   r   r#   s           r   
ext_creater'     s|     &+EF&//(##uuf%FNN5&9:r   c                 F   d}d}i }||d<   d}| j                  ||       | j                         }|r|d   }d}| j                  ||       | j                         }|r|d   }d}| j                  ||       t        d | j                         D              }|d	}|d	}|||fS )
am  
    Get the currently created extension version if it is installed
    in the database, its default version (used to update to 'latest'),
    and versions that are available if it is installed on the system.

    Return tuple (current_version, default_version, [list of available versions]).

    Note: the list of available versions contains only versions
          that higher than the current created version.
          If the extension is not created, this list will contain all
          available versions.

    Args:
      cursor (cursor) -- cursor object of psycopg library
      ext (str) -- extension name
    Nr   zFSELECT extversion FROM pg_catalog.pg_extension WHERE extname = %(ext)s
extversionzSSELECT default_version FROM pg_catalog.pg_available_extensions WHERE name = %(ext)sdefault_versionzSSELECT version FROM pg_catalog.pg_available_extension_versions WHERE name = %(ext)sc              3   &   K   | ]	  }|d      yw)r"   N ).0rs     r   	<genexpr>z#ext_get_versions.<locals>.<genexpr>X  s     EaQy\Es   F)r   fetchonesetfetchall)r   r   current_versionr*   r#   r   resavailable_versionss           r   ext_get_versionsr6   '  s    $ OOFF5M'E NN5&!
//
C
l+$E NN5&!
//
C
/0$E NN5&!E6??3DEE_.@AAr   c                 |    d}i }d}||d<   ||d<   ||d<   | j                  ||       | j                         }|d}|S )a(  
    Check to see if the installed extension version has a valid update
    path to the given version.

    Return True if a valid path exists. Otherwise return False.

    Note: 'latest' is not a valid value for version here as it can be
          replaced with default_version specified in extension control file.

    Args:
      cursor (cursor) -- cursor object of psycopg library
      ext (str) -- extension name
      current_version (str) -- installed version of the extension.
      version (str) -- target extension version to update to.
    Fz^SELECT path FROM pg_extension_update_paths(%(ext)s) WHERE source = %(cv)s AND target = %(ver)sr   cvr!   T)r   r0   )r   r   r3   r"   
valid_pathr#   r   r4   s           r   ext_valid_update_pathr:   b  s\    " JF$E F5M"F4LF5M
NN5&!
//
C

r   c                  r   t               } | j                  t        ddgdddddg      t        dddg	      t        d
      t        ddddg      t        dd      t        d
      t        d
      t        dd      t        dd       	       t        | d      }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d   }	d}
|st        ||||||	       |r|dk(  r|j                  d       t        |       t        ||j                        }t        ||d      \  }} |j                  d.i t        }	 t        ||      \  }}}|r|dk(  r/|s|j                  d|z         |r|}n|j                  d        n|}|dk(  rs|r |r|k(  rd}
n,t        ||||      }|r\|j                  s7|j!                          t        ||d      \  }} |j                  d.i t        }t#        |j                  |||      }
n|dk(  r|j                  d!|d"|d#       n|j                  d$|d"|d%       n|vr1|dk(  r|j                  d&|z         nh|j                  d'|z         nRt%        |j                  |||||      }
n7|rd}
n2|rt%        |j                  ||||d      }
n|j                  d|z         |	Yt'        |d(|      }||nd)}|	|k7  rAt)        ||	d(||j                  t*              }
n"|dk(  r|rt-        |j                  |||      }
nd}
t        ||      \  }}}|r|nd)}|j                  r|
r|dk(  r}n|dk(  r	d)}n|r|nd)}|j!                          |j7                  |
|j                  d,   |t*        -       y # t.        $ rK}|j!                          |j                  d*t1        |      z  t3        j4                         +       Y d }~d }~ww xY w)/NstrdbTz5.0.0zcommunity.postgresql)namer"   collection_name)typealiasesrequireddeprecated_aliasesr>   )r@   rB   rA   )r@   presentabsent)r@   defaultchoicesboolF)r@   rF   )	login_dbr   r&   stater   session_roler"   trust_inputcomment)argument_specsupports_check_moder   r&   rJ   r   r"   rK   rL   rM   z.Parameter version is ignored when state=absent)
autocommitr    zExtension %s is not available)msgzRPassed version 'latest' but no default_version available in extension control filezLatest version 'zA' has no valid update path from the currently installed version ''zPassed version 'z(' or the passed version is not availablez$Latest version '%s' is not availablez$Passed version '%s' is not available	extension z-Management of PostgreSQL extension failed: %s)rQ   	exceptionrI   )changedr=   r   prev_versionr"   queriesr,   )r   updatedictr   r#   r   warnr
   r   r	   r   r   r6   	fail_jsonr:   r   closer$   r'   r   r   r   r   	Exceptionr   	traceback
format_exc	exit_json)rN   moduler   r&   rJ   r   r"   rK   rL   rM   rV   conn_paramsdb_connectiondummyr   curr_versionr*   r5   real_versionvalid_update_pathcurrent_commentnew_versionnew_default_versionnew_available_versionsout_prev_versionout_versiones                              r   mainrp     s   13M54&4"#9U 
 edVH=y8Y:OP&%0u%% fd3%.  $ # F
 --
C]]8$FMM'"EmmI&GmmI&G==0L--.KmmI&GGFC,H5H$DE  !&&--8K(NM5!]!!3N3Fl<LVUX<Y9o'9
 'X-%  %Ds%J K.
    &A  B #LI #|3"' -B&#|]i,j),#)#4#4 - 3 3 57DV[ei7j 4u)=)=)=)O)O&89J9JFTWY`&aG&(2 !' 0 0_kmy6{ 0 !| !' 0 0^egs6u 0 !v $+=="h.",,1WZf1f,g",,1WZf1f,g #-V->->VU\^e"f
  #G *",V->->VU\^f"g ((-Ls-R(S""-fk3"G5D5P/VXo-)&';VM^M^`pqGh$V%6%6WM DTTZ\_C`@(*@ ,8<R	!*(" )4+"K 
==$%     LyYZ|[gpg{g{g}~~s   HO" "	P6+AP11P6__main__) 
__future__r   r   r   r@   __metaclass__DOCUMENTATIONEXAMPLESRETURNr_   ansible.module_utils._textr   ansible.module_utils.basicr   Fansible_collections.community.postgresql.plugins.module_utils.databaser   Fansible_collections.community.postgresql.plugins.module_utils.postgresr	   r
   r   r   r   r   r   r   r   r$   r'   r6   r:   rp   __name__r,   r   r   <module>r|      s    A @wr(T
(  0 4    ,0>8Bv PfR zF r   