
    Vhl~                     V   d dl mZmZmZ eZdZdZdZd dl	Z	d dl
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 d d
lmZmZmZmZmZmZmZ g Z G d de      Zd Z d Z!d Z"d Z#d Z$d Z%ddZ&d Z'd Z(d Z)	 	 	 	 	 	 	 d dZ*	 	 	 	 	 	 d!dZ+d"dZ,d Z-d Z.ddZ/d Z0e1dk(  r e0        yy)#    )absolute_importdivisionprint_functiona  
---
module: postgresql_db
short_description: Add or remove PostgreSQL databases from a remote host
description:
   - Add or remove PostgreSQL databases from a remote host.
options:
  name:
    description:
      - Name of the database to add or remove.
    type: str
    required: true
    aliases: [ db ]
  owner:
    description:
      - Name of the role to set as owner of the database.
    type: str
    default: ''
  template:
    description:
      - Template used to create the database.
    type: str
    default: ''
  encoding:
    description:
      - Encoding of the database.
    type: str
    default: ''
  lc_collate:
    description:
      - Collation order (LC_COLLATE) to use in the database
        must match collation order of template database unless C(template0) is used as template.
    type: str
    default: ''
  lc_ctype:
    description:
      - Character classification (LC_CTYPE) to use in the database (e.g. lower, upper, ...).
      - Must match LC_CTYPE of template database unless C(template0) is used as template.
    type: str
    default: ''
  icu_locale:
    description:
      - Specifies the ICU locale (ICU_LOCALE) for the database default collation order and character classification, overriding the setting locale.
      - The locale provider must be ICU. The default is the setting of locale if specified; otherwise the same setting as the template database.
    type: str
    default: ''
    version_added: '3.4.0'
  locale_provider:
    description:
      - Specifies the provider to use for the default collation in this database (LOCALE_PROVIDER).
      - Possible values are icu (if the server was built with ICU support) or libc.
      - By default, the provider is the same as that of the template.
    type: str
    default: ''
    version_added: '3.4.0'
  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 state.
    - C(present) implies that the database should be created if necessary.
    - C(absent) implies that the database should be removed if present.
    - C(dump) requires a target definition to which the database will be backed up. (Added in Ansible 2.4)
      Note that in some PostgreSQL versions of pg_dump, which is an embedded PostgreSQL utility and is used by the module,
      returns rc 0 even when errors occurred (e.g. the connection is forbidden by pg_hba.conf, etc.),
      so the module returns changed=True but the dump has not actually been done. Please, be sure that your version of
      pg_dump returns rc 1 in this case.
    - C(restore) also requires a target definition from which the database will be restored. (Added in Ansible 2.4).
    - The format of the backup will be detected based on the target name.
    - Supported compression formats for dump and restore determined by target file format C(.pgc) (custom), C(.bz2) (bzip2), C(.gz) (gzip/pigz) and C(.xz) (xz).
    - Supported formats for dump and restore determined by target file format C(.sql) (plain), C(.tar) (tar), C(.pgc) (custom) and C(.dir) (directory)
      For the directory format which is supported since collection version 1.4.0.
    - "Restore program is selected by target file format: C(.tar), C(.pgc), and C(.dir) are handled by pg_restore, other with pgsql."
    - "."
    - DEPRECATED (see the L(discussion,https://github.com/ansible-collections/community.postgresql/issues/820)).
      C(rename) is used to rename the database C(name) to C(target).
      To rename a database, use the M(community.postgresql.postgresql_query) module.
    type: str
    choices: [ absent, dump, present, rename, restore ]
    default: present
  force:
    description:
    - Used to forcefully drop a database when the I(state) is C(absent), ignored otherwise.
    type: bool
    default: False
  target:
    description:
    - File to back up or restore from.
    - Used when I(state) is C(dump) or C(restore).
    type: path
    default: ''
  target_opts:
    description:
    - Additional arguments for pg_dump or restore program (pg_restore or psql, depending on target's format).
    - Used when I(state) is C(dump) or C(restore).
    type: str
    default: ''
  maintenance_db:
    description:
      - The value specifies the initial database (which is also called as maintenance DB) that Ansible connects to.
    type: str
    default: postgres
  conn_limit:
    description:
      - Specifies the database connection limit.
    type: str
    default: ''
  tablespace:
    description:
      - The tablespace to set for the database
        U(https://www.postgresql.org/docs/current/sql-alterdatabase.html).
      - If you want to move the database back to the default tablespace,
        explicitly set this to pg_default.
    type: path
    default: ''
  dump_extra_args:
    description:
      - Provides additional arguments when I(state) is C(dump).
      - Cannot be used with dump-file-format-related arguments like ``--format=d``.
    type: str
    version_added: '0.2.0'
  trust_input:
    description:
    - If C(false), check whether values of parameters I(owner), I(conn_limit), I(encoding),
      I(db), I(template), I(tablespace), 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 database.
    - To reset the comment, pass an empty string.
    type: str
    version_added: '3.3.0'
seealso:
- name: CREATE DATABASE reference
  description: Complete reference of the CREATE DATABASE command documentation.
  link: https://www.postgresql.org/docs/current/sql-createdatabase.html
- name: DROP DATABASE reference
  description: Complete reference of the DROP DATABASE command documentation.
  link: https://www.postgresql.org/docs/current/sql-dropdatabase.html
- name: pg_dump reference
  description: Complete reference of pg_dump documentation.
  link: https://www.postgresql.org/docs/current/app-pgdump.html
- name: pg_restore reference
  description: Complete reference of pg_restore documentation.
  link: https://www.postgresql.org/docs/current/app-pgrestore.html
- module: community.postgresql.postgresql_tablespace
- module: community.postgresql.postgresql_info
- module: community.postgresql.postgresql_ping

notes:
- State C(dump) and C(restore) don't require I(psycopg) since ansible version 2.8.

attributes:
  check_mode:
    support: full

author: "Ansible Core Team"

extends_documentation_fragment:
- community.postgresql.postgres
a@
  
- name: Create a new database with name "acme"
  community.postgresql.postgresql_db:
    name: acme
    comment: My test DB

# Note: If a template different from "template0" is specified,
# encoding and locale settings must match those of the template.
- name: Create a new database with name "acme" and specific encoding and locale # settings
  community.postgresql.postgresql_db:
    name: acme
    encoding: UTF-8
    lc_collate: de_DE.UTF-8
    lc_ctype: de_DE.UTF-8
    locale_provider: icu
    icu_locale: de-DE-x-icu
    template: template0

# Note: Default limit for the number of concurrent connections to
# a specific database is "-1", which means "unlimited"
- name: Create a new database with name "acme" which has a limit of 100 concurrent connections
  community.postgresql.postgresql_db:
    name: acme
    conn_limit: "100"

- name: Dump an existing database to a file
  community.postgresql.postgresql_db:
    name: acme
    state: dump
    target: /tmp/acme.sql

- name: Dump an existing database to a file excluding the test table
  community.postgresql.postgresql_db:
    name: acme
    state: dump
    target: /tmp/acme.sql
    dump_extra_args: --exclude-table=test

- name: Dump an existing database to a file (with compression)
  community.postgresql.postgresql_db:
    name: acme
    state: dump
    target: /tmp/acme.sql.gz

- name: Dump a single schema for an existing database
  community.postgresql.postgresql_db:
    name: acme
    state: dump
    target: /tmp/acme.sql
    target_opts: "-n public"

- name: Dump only table1 and table2 from the acme database
  community.postgresql.postgresql_db:
    name: acme
    state: dump
    target: /tmp/table1_table2.sql
    target_opts: "-t table1 -t table2"

- name: Dump an existing database using the directory format
  community.postgresql.postgresql_db:
    name: acme
    state: dump
    target: /tmp/acme.dir

- name: Dump an existing database using the custom format
  community.postgresql.postgresql_db:
    name: acme
    state: dump
    target: /tmp/acme.pgc

# name: acme - the name of the database to connect through which the recovery will take place
- name: Restore database using the tar format
  community.postgresql.postgresql_db:
    name: acme
    state: restore
    target: /tmp/acme.tar

# Note: In the example below, if database foo exists and has another tablespace
# the tablespace will be changed to foo. Access to the database will be locked
# until the copying of database files is finished.
- name: Create a new database called foo in tablespace bar
  community.postgresql.postgresql_db:
    name: foo
    tablespace: bar
z
executed_commands:
  description: List of commands which tried to run.
  returned: success
  type: list
  sample: ["CREATE DATABASE acme"]
  version_added: '0.2.0'
N)	to_native)AnsibleModule)shlex_quote)SQLParseErrorcheck_input)connect_to_dbensure_required_libsget_conn_paramsget_server_versionpg_cursor_argspostgres_common_argument_specset_commentc                       e Zd Zy)NotSupportedErrorN)__name__
__module____qualname__     v/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/postgresql/plugins/modules/postgresql_db.pyr   r   -  s    r   r   c                 b    d|d|d}t         j                  |       | j                  |       y)NALTER DATABASE "z" OWNER TO ""Texecuted_commandsappendexecute)cursordbownerquerys       r   	set_ownerr%   5  s)    35u=EU#
NN5r   c                 `    d|d|}t         j                  |       | j                  |       y)Nr   z" CONNECTION LIMIT Tr   )r!   r"   
conn_limitr$   s       r   set_conn_limitr(   <  s)    9;ZHEU#
NN5r   c                 T    d}| j                  |d|i       | j                         d   S )Nz8SELECT pg_char_to_encoding(%(encoding)s) AS encoding_id;encodingencoding_id)r    fetchone)r!   r*   r$   s      r   get_encoding_idr-   C  s,    FE
NN5:x01??]++r   c                     t        | j                        }|dk\  rd}n|dk\  r|dk  rd}nd}| j                  |d|i       | j                         S )Ni az  
        SELECT rolname AS owner,
        pg_encoding_to_char(encoding) AS encoding, encoding AS encoding_id,
        datcollate AS lc_collate, datctype AS lc_ctype, datlocale AS icu_locale,
        CASE datlocprovider WHEN 'c' THEN 'libc' WHEN 'i' THEN 'icu' END AS locale_provider,
        pg_database.datconnlimit AS conn_limit, spcname AS tablespace,
        pg_catalog.shobj_description(pg_database.oid, 'pg_database') AS comment
        FROM pg_database
        JOIN pg_roles ON pg_roles.oid = pg_database.datdba
        JOIN pg_tablespace ON pg_tablespace.oid = pg_database.dattablespace
        WHERE datname = %(db)s
        I a}  
        SELECT rolname AS owner,
        pg_encoding_to_char(encoding) AS encoding, encoding AS encoding_id,
        datcollate AS lc_collate, datctype AS lc_ctype, daticulocale AS icu_locale,
        CASE datlocprovider WHEN 'c' THEN 'libc' WHEN 'i' THEN 'icu' END AS locale_provider,
        pg_database.datconnlimit AS conn_limit, spcname AS tablespace,
        pg_catalog.shobj_description(pg_database.oid, 'pg_database') AS comment
        FROM pg_database
        JOIN pg_roles ON pg_roles.oid = pg_database.datdba
        JOIN pg_tablespace ON pg_tablespace.oid = pg_database.dattablespace
        WHERE datname = %(db)s
        aE  
        SELECT rolname AS owner,
        pg_encoding_to_char(encoding) AS encoding, encoding AS encoding_id,
        datcollate AS lc_collate, datctype AS lc_ctype,
        null::char AS icu_locale, null::text AS locale_provider,
        pg_database.datconnlimit AS conn_limit, spcname AS tablespace,
        pg_catalog.shobj_description(pg_database.oid, 'pg_database') AS comment
        FROM pg_database
        JOIN pg_roles ON pg_roles.oid = pg_database.datdba
        JOIN pg_tablespace ON pg_tablespace.oid = pg_database.dattablespace
        WHERE datname = %(db)s
        r"   )r   
connectionr    r,   )r!   r"   server_versionr$   s       r   get_db_infor2   I  sa    '(9(9:N 
6	!nv&= NN54*%??r   c                 L    d}| j                  |d|i       | j                  dk(  S )Nz.SELECT * FROM pg_database WHERE datname=%(db)sr"      )r    rowcount)r!   r"   r$   s      r   	db_existsr6   v  s(    <E
NN54*%??ar   c                 ~    t        | j                        dk\  r	 d}n	 d}d}|dz   |z   }| j                  |d|i       y )NiX` zSELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname=%(db)s AND pid <> pg_backend_pid()zSELECT pg_terminate_backend(pg_stat_activity.procpid) FROM pg_stat_activity WHERE pg_stat_activity.datname=%(db)s AND procpid <> pg_backend_pid()z@UPDATE pg_database SET datallowconn = false WHERE datname=%(db)sz; r"   )r   r0   r    )r!   r"   query_terminatequery_blockr$   s        r   db_dropconnsr:   |  sS    &++,5=_ 	>cUK$0E
NN54*%r   c                     t        | |      rXd|z  }|r*t        | j                        dk\  rd|z  }nt        | |       t        j                  |       | j                  |       yy)NzDROP DATABASE "%s"i zDROP DATABASE "%s" WITH (FORCE)TF)r6   r   r0   r:   r   r   r    )r!   r"   forcer$   s       r   	db_deleter=     s`    $r)!&"3"34>:R?VR(  'ur   c           	         t        ||||||	|
      }t        | j                        dk\  }d|z  g}|r|j                  d|z         |r|j                  d|z         |r|j                  d       |r|j                  d       |r|j                  d       |r|r|j                  d	       |r|r|j                  d
       |
r|j                  d|
z         |	r|j                  dd|	iz         dj	                  |      }t
        j                  | j                  ||             | j                  ||       |rt        | |d||t
               y)N)enccollatectype	iculocalelocaleproviderr'   
tablespacer/   zCREATE DATABASE "%s"z
OWNER "%s"zTEMPLATE "%s"zENCODING %(enc)szLC_COLLATE %(collate)szLC_CTYPE %(ctype)szICU_LOCALE %(iculocale)sz"LOCALE_PROVIDER %(localeprovider)szTABLESPACE "%s"zCONNECTION LIMIT %(conn_limit)sr'    databaseT)	dictr   r0   r   joinr   mogrifyr    r   )r!   r"   r#   templater*   
lc_collatelc_ctype
icu_localelocale_providerr'   rD   comment
check_modeparamsicu_supportedquery_fragmentsr$   s                    r   	db_createrT     sQ   h
(jix  FP')F 'v'8'89VCM-23O|e349:127834m9:=CD0:=>@LR\C]]^HH_%EV^^E6:;
NN5&!FGZZARSr   c                 0   t        | |      }|r#t        | |      |d   k7  rt        d|d   z        |r||d   k7  rt        d|d   z        |r||d   k7  rt        d|d   z        |r||d   k7  rt        d	|d   z        |r||d
   k7  rt        d|d
   z        d}|d   d|d<   |r||d   k7  rt        | ||      }|r|t	        |d         k7  rt        | ||      }|	r|	|d   k7  rt        | ||	      }|
|
|d   k7  rt        | |
d||t              }|S )Nr+   zAChanging database encoding is not supported. Current encoding: %sr*   rK   z<Changing LC_COLLATE is not supported. Current LC_COLLATE: %srL   z7Changing LC_CTYPE is not supported.Current LC_CTYPE: %srM   z;Changing ICU_LOCALE is not supported.Current ICU_LOCALE: %srN   zEChanging LOCALE_PROVIDER is not supported.Current LOCALE_PROVIDER: %sFrO    r#   r'   rD   rF   )	r2   r-   r   r%   strr(   set_tablespacer   r   )r!   r"   r#   r*   rK   rL   rM   rN   r'   rD   rO   rP   db_infochangeds                 r   	db_updater[     s   &"%G_VX6'-:PP#%,Z%89
 	
 

gl&;;%'.|'<=
 	
 
h'*"55#%,Z%89
 	
 

gl&;;%'.|'<=
 	
 
_8I0JJ*,34E,FG
 	

 Gy!	''**FB.jC(=$>> Z8jGL$99 Z8w')*<<fgz2zK\]Nr   c                 6   t        | |      syt        | |      }|d   d|d<   |rt        | |      |d   k7  ry|r	||d   k7  ry|r	||d   k7  ry|r	||d   k7  ry|r	||d   k7  ry|r	||d	   k7  ry|	r|	t        |d
         k7  ry|
r	|
|d   k7  ry|	||d   k7  ryy)NFrO   rV   r+   rK   rL   rM   rN   r#   r'   rD   T)r6   r2   r-   rW   )r!   r"   r#   rJ   r*   rK   rL   rM   rN   r'   rD   rO   rY   s                r   
db_matchesr]     s    VR fb)9%!#GI:gm>TTJ',*??(gj&99J',*??G<M4N!Nu 00J#gl.C*DDJ',*?? W	0B%Br   c	                    t        ||||d      }
| j                  dd      }d }t        j                  j	                  |      d   dk(  r|
j                  d       nmt        j                  j	                  |      d   dk(  r|
j                  d	       n6t        j                  j	                  |      d   d
k(  r|
j                  d       t        j                  j	                  |      d   dk(  r7| j                  d      r| j                  dd      }n| j                  dd      }not        j                  j	                  |      d   dk(  r| j                  dd      }n7t        j                  j	                  |      d   dk(  r| j                  dd      }|dj                  |
      z  }|r|dj                  |      z  }|r|dj                  |      z  }|r]t        j                  j                  | j                  d      }t        j                  |       dj                  ||t        |      |      }n;d|v rdj                  |t        |            }ndj                  |t        |            }t        | ||      S )NF)	db_prefixpg_dumpT.tarz --format=t.pgcz --format=c.dirz --format=d.gzpigzgzip.bz2bzip2.xzxzrV    {0} pg_fifoz{1} <{3} > {2} & {0} >{3}z
{0} -f {1}z	{0} > {1})login_flagsget_bin_pathospathsplitextr   rH   formattmpdirmkfifor   do_with_password)moduletargettarget_optsr"   dump_extra_argsuserpasswordhostportkwflagscmdcomp_prog_pathfifos                 r   db_dumpr     s    D$>E


i
.CN	ww#v-]#			&	!"	%	/]#			&	!"	%	/]#	ww#u,v&#00>N#00>N			&	!"	%	/,,Wd;			&	!"	%	.,,T482775>Cw~~o..w~~k** ww||FMM95
		$)00nkRXFY[_`C%%c;v+>?C$$S+f*=>CFC22r   c                 (   t        ||||      }	d }
| j                  dd      t        j                  j	                  |      d   dk(  r"|	j                  dj                  |             nt        j                  j	                  |      d   dk(  r%|	j                  d       | j                  dd      n9t        j                  j	                  |      d   d	k(  r$|	j                  d
       | j                  dd      nt        j                  j	                  |      d   dk(  r$|	j                  d       | j                  dd      nt        j                  j	                  |      d   dk(  r| j                  dd      }
not        j                  j	                  |      d   dk(  r| j                  dd      }
n7t        j                  j	                  |      d   dk(  r| j                  dd      }
dj                  |	      z  |rdj                  |      z  |
r!t        j                  j                         }|rd|i}t        j                  |
|gt        j                  t        j                        }t        j                  |j                  t        j                  t        j                  d|      }|j                         \  }}|j                  j                          |j!                          |j"                  dk7  r*|j$                  j'                         }|j"                  d|dfS |j"                  d|dfS t)        fddD              rdj                  t+        |            ndj                  t+        |            t-        | |      S )NpsqlTra   z.sqlz --file={0}rb   z --format=Tar
pg_restorerc   z --format=Customrd   z --format=Directoryre   zcatrh   bzcatrj   xzcatrV   rl   
PGPASSWORD)stdoutstderr)stdinr   r   shellenvr   z	cmd: ****c              3   &   K   | ]  }|v  
 y w)Nr   ).0	substringr   s     r   	<genexpr>zdb_restore.<locals>.<genexpr>{  s     [IyC[s   )z--format=Directoryz--format=Customz{0} {1}z	{0} < {1})rn   ro   rp   rq   rr   r   rs   rH   environcopy
subprocessPopenPIPEr   communicateclosewait
returncoder   readanyr   rv   )rw   rx   ry   r"   r{   r|   r}   r~   r   r   r   r   p1p2stdout2stderr2stderr1r   s                    @r   
db_restorer   D  s    D$-EN


fd
+C	ww#v-]))&12			&	!"	%	/_%!!,5			&	!"	%	/'(!!,5			&	!"	%	/*+!!,5			&	!"	%	.,,VT:			&	!"	%	/,,Wd;			&	!"	%	.,,Wd;2775>Cw~~k**jjoo*C~v6zWaWfWfgc:??S]SbSbjntwx^^-'
		
	==Aiinn&G=="g{::=="g{::[1Z[[""3F(;<C$$S+f*=>CFC22r   c                    g }| rU|r*|j                  dj                  t        |                    n)|j                  dj                  t        |                    |r |j                  dj                  |             |r |j                  dj                  |             |r |j                  dj                  |             |S )a,  
    returns a list of connection argument strings each prefixed
    with a space and quoted where necessary to later be combined
    in a single shell string with `"".join(rv)`

    db_prefix determines if "--dbname" is prefixed to the db argument,
    since the argument was introduced in 9.3.
    z --dbname={0}z {0}z --host={0}z --port={0}z --username={0})r   rs   r   )r"   r}   r~   r{   r_   r   s         r   rn   rn     s     E	LL//B@ALL{278]))$/0]))$/0&--d34Lr   c                 x    i }|rd|i}t         j                  |       | j                  |d|      \  }}}||||fS )Nr   T)use_unsafe_shellenviron_update)r   r   run_command)rw   r   r|   r   rcr   r   s          r   rv   rv     sP    
CX&S!++C$WZ+[Bvvs""r   c                 b    d|d|d}t         j                  |       | j                  |       y)Nr   z" SET TABLESPACE "r   Tr   )r!   r"   rD   r$   s       r   rX   rX     s)    9;ZHEU#
NN5r   c                    t        ||      }t        ||      }|r|r| j                  d       |s|ry|s|s| j                  d       |r6|s3|ryd|d|d}t        j                  |       |j	                  |       yy y )	Nz/Both the source and the target databases exist.msgFz1The source and the target databases do not exist.Tr   z" RENAME TO "r   )r6   	fail_jsonr   r   r    )rw   r!   r"   rx   rP   	source_db	target_dbr$   s           r   	rename_dbr     s    &"%I&&)IYNO
 YPQ  9;FC  'u #yr   c                     t               } | j                  t        dddg      t        dd      t        dd      t        dd      t        dd      t        dd      t        dd      t        dd      t        ddg d	      t        d
d      t        dd      t        dd      t        d      t        dd      t        d
d      t        dd       t        d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   }	|j                  d   }
|j                  d   }|j                  d   }d}|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  d    }|j                  d!   }|j                  d"   }|j                  d#   }|d$k(  rS|j                  d%       |
s|j                  d&'       ||
k(  r|j                  d('       ||k(  r|j                  d)'       |st        |||||||||	       |d*v }|st        |       |
dk(  rCd+j                  t        j                         |      }
t        j                  j                  |
      }
|j                  }|j                  d   |d<   t        ||d,      }|s>t        ||d-      \  }} |j                   d9i t"        }|r	 |j%                  d.|z         	 |j.                  r\|d1k(  rt1        |      }n2|dk(  rt3        ||||||||	|||       }n|d$k(  rt5        |||
d2      }|j7                  ||t8        3       |d1k(  rt;        ||      }n|dk(  rOt1        |      s"t=        |||||||||	||||j.                        }nt?        ||||||||	||||j.                        }n|rt        ||j                  d,      }|d4k(  xr t@        xs tB        }|d4k(  r |||
|||fi |\  }}} }!n |||
||fi |\  }}} }!|d5k7  r|j                  | |||!6       n/|j7                  d|| ||!t8        7       n|d$k(  rt5        |||
      }|s jK                          jK                          |j7                  ||t8        3       y # t&        $ r<}|j                  d/t)        |      z  t+        j,                         0       Y d }~d }~ww xY w# tD        tF        f$ r8}|j                  t)        |      t+        j,                         0       Y d }~d }~wtH        $ r  t&        $ r<}|j                  d8t)        |      z  t+        j,                         0       Y d }~d }~ww xY w):NrW   Tname)typerequiredaliasesrV   )r   defaultpresent)absentdumpr   renamerestore)r   r   choicesrq   postgres)r   boolF)r"   r#   rJ   r*   rK   rL   rM   rN   staterx   ry   maintenance_dbsession_roler'   rD   rz   trust_inputr<   rO   )argument_specsupports_check_moder"   r#   rJ   r*   rK   rL   rM   rN   rx   ry   r   r   r   r'   rD   rz   r   r<   rO   r   zThe rename choice of the state option is deprecated and will be removed in version 5.0.0. Use the community.postgresql.postgresql_query module instead.zEThe "target" option must be defined when the "rename" option is used.r   z@The "name/db" option and the "target" option cannot be the same.zHThe "maintenance_db" option and the "name/db" option cannot be the same.)r   r   z{0}/{1}.sql)warn_db_default)
autocommitzSET ROLE "%s"zCould not switch role: %s)r   	exceptionr   )rP   )rZ   r"   r   r   r   )r   r   r   r   )rZ   r   r   r   r   r   zDatabase query failed: %sr   )&r   updaterG   r   rQ   warnr   r
   r   rs   rp   getcwdrq   
expanduserr   r   r!   r   r    	Exceptionr   	traceback
format_excrP   r6   r]   r   	exit_jsonr   r=   rT   r[   r   r   r	   r   
SystemExitr   )"r   rw   r"   r#   rJ   r*   rK   rL   rM   rN   rx   ry   r   rZ   r   r   r'   rD   rz   r   r<   rO   raw_connectionparams_dictconn_paramsdb_connectiondummyr!   emethodr   r   r   r   s"                                     r   mainr     s   13MUTF8<r*5"-5"-UB/5"-UB/%4yMO,eR0
;u%UB/VR0%6fd3.%.)  . # F
 
t	BMM'"E}}Z(H}}Z(H|,J}}Z(H|,Jmm$56O]]8$F--.KMM'"EG]]#34N==0L|,J|,Jmm$56O--.KMM'"EmmI&G f 	g !hi<!cdR!kl FE:xj,	A 11NV$|%%biik26##F+ --K&67K "&+uMK,V[TRu%%%77s=>7k #FB/)#(UHhPZ\d)3_jR\^eg g ("#FFB4PWGXY HE2GiVR(#FBx:$,j/:$.9J9JL $FBx$,j/:$.9J9JL )&&--QVWKf_0>JF*0bRa*qep*q'FFC*0b*`T_*`'FFCQw  VFrs K  6&RUX3D ! F hF;G 
W?PQA  s  %@9Q<%O[d[o[o[q rrsh ,- MYq\Y5I5I5KLL  k89Q<GS\SgSgSijjks=   T #E1U 	U1UUW*&.VW*.1W%%W*__main__)F)rV   NNNNNN)rV   NNNNN)T)2
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNrp   r   r   ansible.module_utils._textr   ansible.module_utils.basicr   ansible.module_utils.six.movesr   Fansible_collections.community.postgresql.plugins.module_utils.databaser	   r
   Fansible_collections.community.postgresql.plugins.module_utils.postgresr   r   r   r   r   r   r   r   r   r   r%   r(   r-   r2   r6   r:   r=   rT   r[   r]   r   r   rn   rv   rX   r   r   r   r   r   r   <module>r      s   A @hTTl
 
   0 4 6    		 	,*Z &D/d@ )+ 33l ,.<3~0#>]R@ zF r   