Debian Codegraph @

ansible_collections/community/postgresql/plugins/modules/postgresql_db.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11 DOCUMENTATION = r'''
12 ---
13 module: postgresql_db
14 short_description: Add or remove PostgreSQL databases from a remote host
15 description:
16 - Add or remove PostgreSQL databases from a remote host.
17 options:
18 name:
19 description:
20 - Name of the database to add or remove.
21 type: str
22 required: true
23 aliases: [ db ]
24 owner:
25 description:
26 - Name of the role to set as owner of the database.
27 type: str
28 default: ''
29 template:
30 description:
31 - Template used to create the database.
32 type: str
33 default: ''
34 encoding:
35 description:
36 - Encoding of the database.
37 type: str
38 default: ''
39 lc_collate:
40 description:
41 - Collation order (LC_COLLATE) to use in the database
42 must match collation order of template database unless C(template0) is used as template.
43 type: str
44 default: ''
45 lc_ctype:
46 description:
47 - Character classification (LC_CTYPE) to use in the database (e.g. lower, upper, ...).
48 - Must match LC_CTYPE of template database unless C(template0) is used as template.
49 type: str
50 default: ''
51 icu_locale:
52 description:
53 - Specifies the ICU locale (ICU_LOCALE) for the database default collation order and character classification, overriding the setting locale.
54 - The locale provider must be ICU. The default is the setting of locale if specified; otherwise the same setting as the template database.
55 type: str
56 default: ''
57 version_added: '3.4.0'
58 locale_provider:
59 description:
60 - Specifies the provider to use for the default collation in this database (LOCALE_PROVIDER).
61 - Possible values are icu (if the server was built with ICU support) or libc.
62 - By default, the provider is the same as that of the template.
63 type: str
64 default: ''
65 version_added: '3.4.0'
66 session_role:
67 description:
68 - Switch to session_role after connecting.
69 - The specified session_role must be a role that the current login_user is a member of.
70 - Permissions checking for SQL commands is carried out as though the session_role
71 were the one that had logged in originally.
72 type: str
73 state:
74 description:
75 - The database state.
76 - C(present) implies that the database should be created if necessary.
77 - C(absent) implies that the database should be removed if present.
78 - C(dump) requires a target definition to which the database will be backed up. (Added in Ansible 2.4)
79 Note that in some PostgreSQL versions of pg_dump, which is an embedded PostgreSQL utility and is used by the module,
80 returns rc 0 even when errors occurred (e.g. the connection is forbidden by pg_hba.conf, etc.),
81 so the module returns changed=True but the dump has not actually been done. Please, be sure that your version of
82 pg_dump returns rc 1 in this case.
83 - C(restore) also requires a target definition from which the database will be restored. (Added in Ansible 2.4).
84 - The format of the backup will be detected based on the target name.
85 - 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).
86 - Supported formats for dump and restore determined by target file format C(.sql) (plain), C(.tar) (tar), C(.pgc) (custom) and C(.dir) (directory)
87 For the directory format which is supported since collection version 1.4.0.
88 - "Restore program is selected by target file format: C(.tar), C(.pgc), and C(.dir) are handled by pg_restore, other with pgsql."
89 - "."
90 - DEPRECATED (see the L(discussion,https://github.com/ansible-collections/community.postgresql/issues/820)).
91 C(rename) is used to rename the database C(name) to C(target).
92 To rename a database, use the M(community.postgresql.postgresql_query) module.
93 type: str
94 choices: [ absent, dump, present, rename, restore ]
95 default: present
96 force:
97 description:
98 - Used to forcefully drop a database when the I(state) is C(absent), ignored otherwise.
99 type: bool
100 default: False
101 target:
102 description:
103 - File to back up or restore from.
104 - Used when I(state) is C(dump) or C(restore).
105 type: path
106 default: ''
107 target_opts:
108 description:
109 - Additional arguments for pg_dump or restore program (pg_restore or psql, depending on target's format).
110 - Used when I(state) is C(dump) or C(restore).
111 type: str
112 default: ''
113 maintenance_db:
114 description:
115 - The value specifies the initial database (which is also called as maintenance DB) that Ansible connects to.
116 type: str
117 default: postgres
118 conn_limit:
119 description:
120 - Specifies the database connection limit.
121 type: str
122 default: ''
123 tablespace:
124 description:
125 - The tablespace to set for the database
126 U(https://www.postgresql.org/docs/current/sql-alterdatabase.html).
127 - If you want to move the database back to the default tablespace,
128 explicitly set this to pg_default.
129 type: path
130 default: ''
131 dump_extra_args:
132 description:
133 - Provides additional arguments when I(state) is C(dump).
134 - Cannot be used with dump-file-format-related arguments like ``--format=d``.
135 type: str
136 version_added: '0.2.0'
137 trust_input:
138 description:
139 - If C(false), check whether values of parameters I(owner), I(conn_limit), I(encoding),
140 I(db), I(template), I(tablespace), I(session_role) are potentially dangerous.
141 - It makes sense to use C(false) only when SQL injections via the parameters are possible.
142 type: bool
143 default: true
144 version_added: '0.2.0'
145 comment:
146 description:
147 - Sets a comment on the database.
148 - To reset the comment, pass an empty string.
149 type: str
150 version_added: '3.3.0'
151 seealso:
152 - name: CREATE DATABASE reference
153 description: Complete reference of the CREATE DATABASE command documentation.
154 link: https://www.postgresql.org/docs/current/sql-createdatabase.html
155 - name: DROP DATABASE reference
156 description: Complete reference of the DROP DATABASE command documentation.
157 link: https://www.postgresql.org/docs/current/sql-dropdatabase.html
158 - name: pg_dump reference
159 description: Complete reference of pg_dump documentation.
160 link: https://www.postgresql.org/docs/current/app-pgdump.html
161 - name: pg_restore reference
162 description: Complete reference of pg_restore documentation.
163 link: https://www.postgresql.org/docs/current/app-pgrestore.html
164 - module: community.postgresql.postgresql_tablespace
165 - module: community.postgresql.postgresql_info
166 - module: community.postgresql.postgresql_ping
167
168 notes:
169 - State C(dump) and C(restore) don't require I(psycopg) since ansible version 2.8.
170
171 attributes:
172 check_mode:
173 support: full
174
175 author: "Ansible Core Team"
176
177 extends_documentation_fragment:
178 - community.postgresql.postgres
179 '''
180
181 EXAMPLES = r'''
182 - name: Create a new database with name "acme"
183 community.postgresql.postgresql_db:
184 name: acme
185 comment: My test DB
186
187 # Note: If a template different from "template0" is specified,
188 # encoding and locale settings must match those of the template.
189 - name: Create a new database with name "acme" and specific encoding and locale # settings
190 community.postgresql.postgresql_db:
191 name: acme
192 encoding: UTF-8
193 lc_collate: de_DE.UTF-8
194 lc_ctype: de_DE.UTF-8
195 locale_provider: icu
196 icu_locale: de-DE-x-icu
197 template: template0
198
199 # Note: Default limit for the number of concurrent connections to
200 # a specific database is "-1", which means "unlimited"
201 - name: Create a new database with name "acme" which has a limit of 100 concurrent connections
202 community.postgresql.postgresql_db:
203 name: acme
204 conn_limit: "100"
205
206 - name: Dump an existing database to a file
207 community.postgresql.postgresql_db:
208 name: acme
209 state: dump
210 target: /tmp/acme.sql
211
212 - name: Dump an existing database to a file excluding the test table
213 community.postgresql.postgresql_db:
214 name: acme
215 state: dump
216 target: /tmp/acme.sql
217 dump_extra_args: --exclude-table=test
218
219 - name: Dump an existing database to a file (with compression)
220 community.postgresql.postgresql_db:
221 name: acme
222 state: dump
223 target: /tmp/acme.sql.gz
224
225 - name: Dump a single schema for an existing database
226 community.postgresql.postgresql_db:
227 name: acme
228 state: dump
229 target: /tmp/acme.sql
230 target_opts: "-n public"
231
232 - name: Dump only table1 and table2 from the acme database
233 community.postgresql.postgresql_db:
234 name: acme
235 state: dump
236 target: /tmp/table1_table2.sql
237 target_opts: "-t table1 -t table2"
238
239 - name: Dump an existing database using the directory format
240 community.postgresql.postgresql_db:
241 name: acme
242 state: dump
243 target: /tmp/acme.dir
244
245 - name: Dump an existing database using the custom format
246 community.postgresql.postgresql_db:
247 name: acme
248 state: dump
249 target: /tmp/acme.pgc
250
251 # name: acme - the name of the database to connect through which the recovery will take place
252 - name: Restore database using the tar format
253 community.postgresql.postgresql_db:
254 name: acme
255 state: restore
256 target: /tmp/acme.tar
257
258 # Note: In the example below, if database foo exists and has another tablespace
259 # the tablespace will be changed to foo. Access to the database will be locked
260 # until the copying of database files is finished.
261 - name: Create a new database called foo in tablespace bar
262 community.postgresql.postgresql_db:
263 name: foo
264 tablespace: bar
265 '''
266
267 RETURN = r'''
268 executed_commands:
269 description: List of commands which tried to run.
270 returned: success
271 type: list
272 sample: ["CREATE DATABASE acme"]
273 version_added: '0.2.0'
274 '''
275
276
277 import os
278 import subprocess
279 import traceback
280
281 from ansible.module_utils.common.text.converters import to_native
282 from ansible.module_utils.basic import AnsibleModule
283 from ansible.module_utils.six.moves import shlex_quote
284 from ansible_collections.community.postgresql.plugins.module_utils.database import (
285 SQLParseError,
286 check_input,
287 )
288 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
289 connect_to_db,
290 ensure_required_libs,
291 get_conn_params,
292 get_server_version,
293 pg_cursor_args,
294 postgres_common_argument_spec,
295 set_comment,
296 )
297
298 executed_commands = []
299
300
301 class NotSupportedError(Exception):
302 pass
303
304 # ===========================================
305 # PostgreSQL module specific support methods.
306 #
307
308
309 def set_owner(cursor, db, owner):
310 query = 'ALTER DATABASE "%s" OWNER TO "%s"' % (db, owner)
311 executed_commands.append(query)
312 cursor.execute(query)
313 return True
314
315
316 def set_conn_limit(cursor, db, conn_limit):
317 query = 'ALTER DATABASE "%s" CONNECTION LIMIT %s' % (db, conn_limit)
318 executed_commands.append(query)
319 cursor.execute(query)
320 return True
321
322
323 def get_encoding_id(cursor, encoding):
324 query = "SELECT pg_char_to_encoding(%(encoding)s) AS encoding_id;"
325 cursor.execute(query, {'encoding': encoding})
326 return cursor.fetchone()['encoding_id']
327
328
329 def get_db_info(cursor, db):
330 server_version = get_server_version(cursor.connection)
331 if server_version >= 170000:
332 query = """
333 SELECT rolname AS owner,
334 pg_encoding_to_char(encoding) AS encoding, encoding AS encoding_id,
335 datcollate AS lc_collate, datctype AS lc_ctype, datlocale AS icu_locale,
336 CASE datlocprovider WHEN 'c' THEN 'libc' WHEN 'i' THEN 'icu' END AS locale_provider,
337 pg_database.datconnlimit AS conn_limit, spcname AS tablespace,
338 pg_catalog.shobj_description(pg_database.oid, 'pg_database') AS comment
339 FROM pg_database
340 JOIN pg_roles ON pg_roles.oid = pg_database.datdba
341 JOIN pg_tablespace ON pg_tablespace.oid = pg_database.dattablespace
342 WHERE datname = %(db)s
343 """
344 elif server_version >= 150000 and server_version < 170000:
345 query = """
346 SELECT rolname AS owner,
347 pg_encoding_to_char(encoding) AS encoding, encoding AS encoding_id,
348 datcollate AS lc_collate, datctype AS lc_ctype, daticulocale AS icu_locale,
349 CASE datlocprovider WHEN 'c' THEN 'libc' WHEN 'i' THEN 'icu' END AS locale_provider,
350 pg_database.datconnlimit AS conn_limit, spcname AS tablespace,
351 pg_catalog.shobj_description(pg_database.oid, 'pg_database') AS comment
352 FROM pg_database
353 JOIN pg_roles ON pg_roles.oid = pg_database.datdba
354 JOIN pg_tablespace ON pg_tablespace.oid = pg_database.dattablespace
355 WHERE datname = %(db)s
356 """
357 else:
358 query = """
359 SELECT rolname AS owner,
360 pg_encoding_to_char(encoding) AS encoding, encoding AS encoding_id,
361 datcollate AS lc_collate, datctype AS lc_ctype,
362 null::char AS icu_locale, null::text AS locale_provider,
363 pg_database.datconnlimit AS conn_limit, spcname AS tablespace,
364 pg_catalog.shobj_description(pg_database.oid, 'pg_database') AS comment
365 FROM pg_database
366 JOIN pg_roles ON pg_roles.oid = pg_database.datdba
367 JOIN pg_tablespace ON pg_tablespace.oid = pg_database.dattablespace
368 WHERE datname = %(db)s
369 """
370 cursor.execute(query, {'db': db})
371 return cursor.fetchone()
372
373
374 def db_exists(cursor, db):
375 query = "SELECT * FROM pg_database WHERE datname=%(db)s"
376 cursor.execute(query, {'db': db})
377 return cursor.rowcount == 1
378
379
380 def db_dropconns(cursor, db):
381 if get_server_version(cursor.connection) >= 90200:
382 """ Drop DB connections in Postgres 9.2 and above """
383 query_terminate = ("SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity "
384 "WHERE pg_stat_activity.datname=%(db)s AND pid <> pg_backend_pid()")
385 else:
386 """ Drop DB connections in Postgres 9.1 and below """
387 query_terminate = ("SELECT pg_terminate_backend(pg_stat_activity.procpid) FROM pg_stat_activity "
388 "WHERE pg_stat_activity.datname=%(db)s AND procpid <> pg_backend_pid()")
389 query_block = ("UPDATE pg_database SET datallowconn = false WHERE datname=%(db)s")
390 query = query_block + '; ' + query_terminate
391
392 cursor.execute(query, {'db': db})
393
394
395 def db_delete(cursor, db, force=False):
396 if db_exists(cursor, db):
397 query = 'DROP DATABASE "%s"' % db
398 if force:
399 if get_server_version(cursor.connection) >= 130000:
400 query = ('DROP DATABASE "%s" WITH (FORCE)' % db)
401 else:
402 db_dropconns(cursor, db)
403 executed_commands.append(query)
404 cursor.execute(query)
405 return True
406 else:
407 return False
408
409
410 def db_create(cursor, db, owner, template, encoding, lc_collate, lc_ctype, icu_locale, locale_provider, conn_limit, tablespace, comment, check_mode):
411
412 params = dict(enc=encoding, collate=lc_collate, ctype=lc_ctype, iculocale=icu_locale, localeprovider=locale_provider, conn_limit=conn_limit,
413 tablespace=tablespace)
414
415 icu_supported = get_server_version(cursor.connection) >= 150000
416
417 query_fragments = ['CREATE DATABASE "%s"' % db]
418 if owner:
419 query_fragments.append('OWNER "%s"' % owner)
420 if template:
421 query_fragments.append('TEMPLATE "%s"' % template)
422 if encoding:
423 query_fragments.append('ENCODING %(enc)s')
424 if lc_collate:
425 query_fragments.append('LC_COLLATE %(collate)s')
426 if lc_ctype:
427 query_fragments.append('LC_CTYPE %(ctype)s')
428 if icu_locale and icu_supported:
429 query_fragments.append('ICU_LOCALE %(iculocale)s')
430 if locale_provider and icu_supported:
431 query_fragments.append('LOCALE_PROVIDER %(localeprovider)s')
432 if tablespace:
433 query_fragments.append('TABLESPACE "%s"' % tablespace)
434 if conn_limit:
435 query_fragments.append("CONNECTION LIMIT %(conn_limit)s" % {"conn_limit": conn_limit})
436 query = ' '.join(query_fragments)
437 executed_commands.append(cursor.mogrify(query, params))
438 cursor.execute(query, params)
439 if comment:
440 set_comment(cursor, comment, 'database', db, check_mode, executed_commands)
441 return True
442
443
444 def db_update(cursor, db, owner, encoding, lc_collate, lc_ctype, icu_locale, locale_provider, conn_limit, tablespace, comment, check_mode):
445 db_info = get_db_info(cursor, db)
446
447 if (encoding and get_encoding_id(cursor, encoding) != db_info['encoding_id']):
448 raise NotSupportedError(
449 'Changing database encoding is not supported. '
450 'Current encoding: %s' % db_info['encoding']
451 )
452 elif lc_collate and lc_collate != db_info['lc_collate']:
453 raise NotSupportedError(
454 'Changing LC_COLLATE is not supported. '
455 'Current LC_COLLATE: %s' % db_info['lc_collate']
456 )
457 elif lc_ctype and lc_ctype != db_info['lc_ctype']:
458 raise NotSupportedError(
459 'Changing LC_CTYPE is not supported.'
460 'Current LC_CTYPE: %s' % db_info['lc_ctype']
461 )
462 elif icu_locale and icu_locale != db_info['icu_locale']:
463 raise NotSupportedError(
464 'Changing ICU_LOCALE is not supported.'
465 'Current ICU_LOCALE: %s' % db_info['icu_locale']
466 )
467 elif locale_provider and locale_provider != db_info['locale_provider']:
468 raise NotSupportedError(
469 'Changing LOCALE_PROVIDER is not supported.'
470 'Current LOCALE_PROVIDER: %s' % db_info['locale_provider']
471 )
472
473 changed = False
474
475 if db_info['comment'] is None:
476 # For the resetting comment feature (comment: '') to work correctly
477 db_info['comment'] = ''
478
479 if owner and owner != db_info['owner']:
480 changed = set_owner(cursor, db, owner)
481
482 if conn_limit != '' and conn_limit != str(db_info['conn_limit']):
483 changed = set_conn_limit(cursor, db, conn_limit)
484
485 if tablespace and tablespace != db_info['tablespace']:
486 changed = set_tablespace(cursor, db, tablespace)
487
488 if comment is not None and comment != db_info['comment']:
489 changed = set_comment(cursor, comment, 'database', db, check_mode, executed_commands)
490
491 return changed
492
493
494 def db_matches(cursor, db, owner, template, encoding, lc_collate, lc_ctype, icu_locale, locale_provider, conn_limit, tablespace, comment):
495 if not db_exists(cursor, db):
496 return False
497 else:
498 db_info = get_db_info(cursor, db)
499
500 if db_info['comment'] is None:
501 # For the resetting comment feature (comment: '') to work correctly
502 db_info['comment'] = ''
503
504 if (encoding and get_encoding_id(cursor, encoding) != db_info['encoding_id']):
505 return False
506 elif lc_collate and lc_collate != db_info['lc_collate']:
507 return False
508 elif lc_ctype and lc_ctype != db_info['lc_ctype']:
509 return False
510 elif icu_locale and icu_locale != db_info['icu_locale']:
511 return False
512 elif locale_provider and locale_provider != db_info['locale_provider']:
513 return False
514 elif owner and owner != db_info['owner']:
515 return False
516 elif conn_limit != '' and conn_limit != str(db_info['conn_limit']):
517 return False
518 elif tablespace and tablespace != db_info['tablespace']:
519 return False
520 elif comment is not None and comment != db_info['comment']:
521 return False
522 else:
523 return True
524
525
526 def db_dump(module, target, target_opts="",
527 db=None,
528 dump_extra_args=None,
529 user=None,
530 password=None,
531 host=None,
532 port=None,
533 session_role=None,
534 **kw):
535
536 flags = login_flags(db, host, port, user, db_prefix=False)
537 cmd = module.get_bin_path('pg_dump', True)
538 comp_prog_path = None
539
540 if os.path.splitext(target)[-1] == '.tar':
541 flags.append(' --format=t')
542 elif os.path.splitext(target)[-1] == '.pgc':
543 flags.append(' --format=c')
544 elif os.path.splitext(target)[-1] == '.dir':
545 flags.append(' --format=d')
546
547 if os.path.splitext(target)[-1] == '.gz':
548 if module.get_bin_path('pigz'):
549 comp_prog_path = module.get_bin_path('pigz', True)
550 else:
551 comp_prog_path = module.get_bin_path('gzip', True)
552 elif os.path.splitext(target)[-1] == '.bz2':
553 comp_prog_path = module.get_bin_path('bzip2', True)
554 elif os.path.splitext(target)[-1] == '.xz':
555 comp_prog_path = module.get_bin_path('xz', True)
556
557 if session_role:
558 flags.append(' --role={0}'.format(shlex_quote(session_role)))
559
560 cmd += "".join(flags)
561
562 if dump_extra_args:
563 cmd += " {0} ".format(dump_extra_args)
564
565 if target_opts:
566 cmd += " {0} ".format(target_opts)
567
568 if comp_prog_path:
569 # Use a fifo to be notified of an error in pg_dump
570 # Using shell pipe has no way to return the code of the first command
571 # in a portable way.
572 fifo = os.path.join(module.tmpdir, 'pg_fifo')
573 os.mkfifo(fifo)
574 cmd = '{1} <{3} > {2} & {0} >{3}'.format(cmd, comp_prog_path, shlex_quote(target), fifo)
575 else:
576 if ' --format=d' in cmd:
577 cmd = '{0} -f {1}'.format(cmd, shlex_quote(target))
578 else:
579 cmd = '{0} > {1}'.format(cmd, shlex_quote(target))
580
581 return do_with_password(module, cmd, password)
582
583
584 def db_restore(module, target, target_opts="",
585 db=None,
586 user=None,
587 password=None,
588 host=None,
589 port=None,
590 session_role=None,
591 **kw):
592
593 flags = login_flags(db, host, port, user)
594 comp_prog_path = None
595 cmd = module.get_bin_path('psql', True)
596 pg_restore = False
597
598 if os.path.splitext(target)[-1] == '.sql':
599 flags.append(' --file={0}'.format(target))
600
601 elif os.path.splitext(target)[-1] == '.tar':
602 flags.append(' --format=Tar')
603 cmd = module.get_bin_path('pg_restore', True)
604 pg_restore = True
605
606 elif os.path.splitext(target)[-1] == '.pgc':
607 flags.append(' --format=Custom')
608 cmd = module.get_bin_path('pg_restore', True)
609 pg_restore = True
610
611 elif os.path.splitext(target)[-1] == '.dir':
612 flags.append(' --format=Directory')
613 cmd = module.get_bin_path('pg_restore', True)
614 pg_restore = True
615
616 elif os.path.splitext(target)[-1] == '.gz':
617 comp_prog_path = module.get_bin_path('zcat', True)
618
619 elif os.path.splitext(target)[-1] == '.bz2':
620 comp_prog_path = module.get_bin_path('bzcat', True)
621
622 elif os.path.splitext(target)[-1] == '.xz':
623 comp_prog_path = module.get_bin_path('xzcat', True)
624
625 if pg_restore and session_role:
626 flags.append(' --role={0}'.format(shlex_quote(session_role)))
627
628 cmd += "".join(flags)
629 if target_opts:
630 cmd += " {0} ".format(target_opts)
631
632 if comp_prog_path:
633 env = os.environ.copy()
634 if password:
635 env = {"PGPASSWORD": password}
636 p1 = subprocess.Popen([comp_prog_path, target], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
637 p2 = subprocess.Popen(cmd, stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=env)
638 (stdout2, stderr2) = p2.communicate()
639 p1.stdout.close()
640 p1.wait()
641 if p1.returncode != 0:
642 stderr1 = p1.stderr.read()
643 return p1.returncode, '', stderr1, 'cmd: ****'
644 else:
645 return p2.returncode, '', stderr2, 'cmd: ****'
646 else:
647 if any(substring in cmd for substring in ['--format=Directory', '--format=Custom']):
648 cmd = '{0} {1}'.format(cmd, shlex_quote(target))
649 elif '--file=' not in cmd:
650 cmd = '{0} < {1}'.format(cmd, shlex_quote(target))
651
652 return do_with_password(module, cmd, password)
653
654
655 def login_flags(db, host, port, user, db_prefix=True):
656 """
657 returns a list of connection argument strings each prefixed
658 with a space and quoted where necessary to later be combined
659 in a single shell string with `"".join(rv)`
660
661 db_prefix determines if "--dbname" is prefixed to the db argument,
662 since the argument was introduced in 9.3.
663 """
664 flags = []
665 if db:
666 if db_prefix:
667 flags.append(' --dbname={0}'.format(shlex_quote(db)))
668 else:
669 flags.append(' {0}'.format(shlex_quote(db)))
670 if host:
671 flags.append(' --host={0}'.format(host))
672 if port:
673 flags.append(' --port={0}'.format(port))
674 if user:
675 flags.append(' --username={0}'.format(user))
676 return flags
677
678
679 def do_with_password(module, cmd, password):
680 env = {}
681 if password:
682 env = {"PGPASSWORD": password}
683 executed_commands.append(cmd)
684 rc, stderr, stdout = module.run_command(cmd, use_unsafe_shell=True, environ_update=env)
685 return rc, stderr, stdout, cmd
686
687
688 def set_tablespace(cursor, db, tablespace):
689 query = 'ALTER DATABASE "%s" SET TABLESPACE "%s"' % (db, tablespace)
690 executed_commands.append(query)
691 cursor.execute(query)
692 return True
693
694
695 def rename_db(module, cursor, db, target, check_mode=False):
696 source_db = db_exists(cursor, db)
697 target_db = db_exists(cursor, target)
698
699 if source_db and target_db:
700 module.fail_json(msg='Both the source and the target databases exist.')
701
702 if not source_db and target_db:
703 # If the source db doesn't exist and
704 # the target db exists, we assume that
705 # the desired state has been reached and
706 # respectively nothing needs to be changed
707 return False
708
709 if not source_db and not target_db:
710 module.fail_json(msg='The source and the target databases do not exist.')
711
712 if source_db and not target_db:
713 if check_mode:
714 return True
715
716 query = 'ALTER DATABASE "%s" RENAME TO "%s"' % (db, target)
717 executed_commands.append(query)
718 cursor.execute(query)
719 return True
720
721 # ===========================================
722 # Module execution.
723 #
724
725
726 def main():
727 argument_spec = postgres_common_argument_spec()
728 argument_spec.update(
729 db=dict(type='str', required=True, aliases=['name']),
730 owner=dict(type='str', default=''),
731 template=dict(type='str', default=''),
732 encoding=dict(type='str', default=''),
733 lc_collate=dict(type='str', default=''),
734 lc_ctype=dict(type='str', default=''),
735 icu_locale=dict(type='str', default=''),
736 locale_provider=dict(type='str', default=''),
737 state=dict(type='str', default='present',
738 choices=['absent', 'dump', 'present', 'rename', 'restore']),
739 target=dict(type='path', default=''),
740 target_opts=dict(type='str', default=''),
741 maintenance_db=dict(type='str', default="postgres"),
742 session_role=dict(type='str'),
743 conn_limit=dict(type='str', default=''),
744 tablespace=dict(type='path', default=''),
745 dump_extra_args=dict(type='str', default=None),
746 trust_input=dict(type='bool', default=True),
747 force=dict(type='bool', default=False),
748 comment=dict(type='str', default=None),
749 )
750
751 module = AnsibleModule(
752 argument_spec=argument_spec,
753 supports_check_mode=True
754 )
755
756 db = module.params["db"]
757 owner = module.params["owner"]
758 template = module.params["template"]
759 encoding = module.params["encoding"]
760 lc_collate = module.params["lc_collate"]
761 lc_ctype = module.params["lc_ctype"]
762 icu_locale = module.params["icu_locale"]
763 locale_provider = module.params["locale_provider"]
764 target = module.params["target"]
765 target_opts = module.params["target_opts"]
766 state = module.params["state"]
767 changed = False
768 maintenance_db = module.params['maintenance_db']
769 session_role = module.params["session_role"]
770 conn_limit = module.params['conn_limit']
771 tablespace = module.params['tablespace']
772 dump_extra_args = module.params['dump_extra_args']
773 trust_input = module.params['trust_input']
774 force = module.params['force']
775 comment = module.params['comment']
776
777 if state == 'rename':
778 module.warn('The rename choice of the state option is deprecated and will be removed '
779 'in version 5.0.0. Use the community.postgresql.postgresql_query module instead.')
780
781 if not target:
782 module.fail_json(msg='The "target" option must be defined when the "rename" option is used.')
783
784 if db == target:
785 module.fail_json(msg='The "name/db" option and the "target" option cannot be the same.')
786
787 if maintenance_db == db:
788 module.fail_json(msg='The "maintenance_db" option and the "name/db" option cannot be the same.')
789
790 # Check input
791 if not trust_input:
792 # Check input for potentially dangerous elements:
793 check_input(module, owner, conn_limit, encoding, db,
794 template, tablespace, session_role, comment)
795
796 raw_connection = state in ("dump", "restore")
797
798 if not raw_connection:
799 ensure_required_libs(module)
800
801 if target == "":
802 target = "{0}/{1}.sql".format(os.getcwd(), db)
803 target = os.path.expanduser(target)
804
805 # Such a transformation is used, since the connection should go to 'maintenance_db'
806 params_dict = module.params
807 params_dict["db"] = module.params["maintenance_db"]
808
809 # Parameters for connecting to the database
810 conn_params = get_conn_params(module, params_dict, warn_db_default=False)
811
812 if not raw_connection:
813 db_connection, dummy = connect_to_db(module, conn_params, autocommit=True)
814 cursor = db_connection.cursor(**pg_cursor_args)
815
816 if session_role:
817 try:
818 cursor.execute('SET ROLE "%s"' % session_role)
819 except Exception as e:
820 module.fail_json(msg="Could not switch role: %s" % to_native(e), exception=traceback.format_exc())
821
822 try:
823 # Handle check mode
824 if module.check_mode:
825 if state == "absent":
826 changed = db_exists(cursor, db)
827
828 elif state == "present":
829 changed = not db_matches(cursor, db, owner, template, encoding, lc_collate, lc_ctype,
830 icu_locale, locale_provider, conn_limit, tablespace, comment)
831
832 elif state == "rename":
833 changed = rename_db(module, cursor, db, target, check_mode=True)
834
835 module.exit_json(changed=changed, db=db, executed_commands=executed_commands)
836
837 # Handle real mode
838 if state == "absent":
839 changed = db_delete(cursor, db, force)
840
841 elif state == "present":
842 if not db_exists(cursor, db):
843 changed = db_create(cursor, db, owner, template, encoding, lc_collate,
844 lc_ctype, icu_locale, locale_provider, conn_limit,
845 tablespace, comment, module.check_mode)
846 else:
847 changed = db_update(cursor, db, owner, encoding, lc_collate,
848 lc_ctype, icu_locale, locale_provider, conn_limit,
849 tablespace, comment, module.check_mode)
850
851 elif raw_connection:
852 # Parameters for performing dump/restore
853 conn_params = get_conn_params(module, module.params, warn_db_default=False)
854
855 method = state == "dump" and db_dump or db_restore
856
857 if state == 'dump':
858 rc, stdout, stderr, cmd = method(
859 module, target, target_opts, db, dump_extra_args, session_role=session_role, **conn_params
860 )
861 else:
862 rc, stdout, stderr, cmd = method(
863 module, target, target_opts, db, session_role=session_role, **conn_params
864 )
865
866 if rc != 0:
867 module.fail_json(msg=stderr, stdout=stdout, rc=rc, cmd=cmd)
868 else:
869 module.exit_json(changed=True, msg=stdout, stderr=stderr, rc=rc, cmd=cmd,
870 executed_commands=executed_commands)
871
872 elif state == 'rename':
873 changed = rename_db(module, cursor, db, target)
874
875 except (SQLParseError, NotSupportedError) as e:
876 module.fail_json(msg=to_native(e), exception=traceback.format_exc())
877 except SystemExit:
878 # Avoid catching this on Python 2.4
879 raise
880 except Exception as e:
881 module.fail_json(msg="Database query failed: %s" % to_native(e), exception=traceback.format_exc())
882
883 if not raw_connection:
884 cursor.close()
885 db_connection.close()
886
887 module.exit_json(changed=changed, db=db, executed_commands=executed_commands)
888
889
890 if __name__ == '__main__':
891 main()