Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2019, Andrew Klychkov (@Andersson007) <[email protected]>
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_table
14 short_description: Create, drop, or modify a PostgreSQL table
15 description:
16 - Allows to create, drop, truncate a table, or change some table attributes.
17 options:
18 table:
19 description:
20 - Table name.
21 required: true
22 aliases:
23 - name
24 type: str
25 state:
26 description:
27 - The table state. I(state=absent) is mutually exclusive with I(tablespace), I(owner), I(unlogged),
28 I(like), I(including), I(columns), I(truncate), I(storage_params) and, I(rename).
29 type: str
30 default: present
31 choices: [ absent, present ]
32 tablespace:
33 description:
34 - Set a tablespace for the table.
35 type: str
36 owner:
37 description:
38 - Set a table owner.
39 type: str
40 unlogged:
41 description:
42 - Create an unlogged table.
43 type: bool
44 default: false
45 like:
46 description:
47 - Create a table like another table (with similar DDL).
48 Mutually exclusive with I(columns), I(rename), and I(truncate).
49 type: str
50 including:
51 description:
52 - Keywords that are used with like parameter, may be DEFAULTS, CONSTRAINTS, INDEXES, STORAGE, COMMENTS or ALL.
53 Needs I(like) specified. Mutually exclusive with I(columns), I(rename), and I(truncate).
54 type: str
55 columns:
56 description:
57 - Columns that are needed.
58 type: list
59 elements: str
60 rename:
61 description:
62 - DEPRECATED (see the L(discussion,https://github.com/ansible-collections/community.postgresql/issues/820)). This option will be removed in version 5.0.0.
63 To rename a table, use the M(community.postgresql.postgresql_query) module.
64 - New table name. Mutually exclusive with I(tablespace), I(owner),
65 I(unlogged), I(like), I(including), I(columns), I(truncate), and I(storage_params).
66 type: str
67 truncate:
68 description:
69 - Truncate a table. Mutually exclusive with I(tablespace), I(owner), I(unlogged),
70 I(like), I(including), I(columns), I(rename), and I(storage_params).
71 type: bool
72 default: false
73 storage_params:
74 description:
75 - Storage parameters like fillfactor, autovacuum_vacuum_treshold, etc.
76 Mutually exclusive with I(rename) and I(truncate).
77 type: list
78 elements: str
79 login_db:
80 description:
81 - Name of database to connect and where the table will be created.
82 - The V(db) alias is deprecated and will be removed in version 5.0.0.
83 type: str
84 default: ''
85 aliases:
86 - db
87 session_role:
88 description:
89 - Switch to session_role after connecting.
90 The specified session_role must be a role that the current login_user is a member of.
91 - Permissions checking for SQL commands is carried out as though
92 the session_role were the one that had logged in originally.
93 type: str
94 cascade:
95 description:
96 - Automatically drop objects that depend on the table (such as views).
97 Used with I(state=absent) only.
98 type: bool
99 default: false
100 trust_input:
101 description:
102 - If C(false), check whether values of parameters are potentially dangerous.
103 - It makes sense to use C(false) only when SQL injections are possible.
104 type: bool
105 default: true
106 version_added: '0.2.0'
107
108 notes:
109 - If you do not pass db parameter, tables will be created in the database
110 named postgres.
111 - PostgreSQL allows to create columnless table, so columns param is optional.
112 - Unlogged tables are available from PostgreSQL server version 9.1.
113 - If the table already exists and columns are specified they will be ignored.
114 Columns can not be altered on an existing table.
115
116 attributes:
117 check_mode:
118 support: full
119
120 seealso:
121 - module: community.postgresql.postgresql_sequence
122 - module: community.postgresql.postgresql_idx
123 - module: community.postgresql.postgresql_info
124 - module: community.postgresql.postgresql_tablespace
125 - module: community.postgresql.postgresql_owner
126 - module: community.postgresql.postgresql_privs
127 - module: community.postgresql.postgresql_copy
128 - name: CREATE TABLE reference
129 description: Complete reference of the CREATE TABLE command documentation.
130 link: https://www.postgresql.org/docs/current/sql-createtable.html
131 - name: ALTER TABLE reference
132 description: Complete reference of the ALTER TABLE command documentation.
133 link: https://www.postgresql.org/docs/current/sql-altertable.html
134 - name: DROP TABLE reference
135 description: Complete reference of the DROP TABLE command documentation.
136 link: https://www.postgresql.org/docs/current/sql-droptable.html
137 - name: PostgreSQL data types
138 description: Complete reference of the PostgreSQL data types documentation.
139 link: https://www.postgresql.org/docs/current/datatype.html
140 author:
141 - Andrei Klychkov (@Andersson007)
142 extends_documentation_fragment:
143 - community.postgresql.postgres
144 '''
145
146 EXAMPLES = r'''
147 - name: Create tbl2 in the acme database with the DDL like tbl1 with testuser as an owner
148 community.postgresql.postgresql_table:
149 login_db: acme
150 name: tbl2
151 like: tbl1
152 owner: testuser
153
154 - name: Create tbl2 in the acme database and tablespace ssd with the DDL like tbl1 including comments and indexes
155 community.postgresql.postgresql_table:
156 login_db: acme
157 table: tbl2
158 like: tbl1
159 including: comments, indexes
160 tablespace: ssd
161
162 - name: Create test_table with several columns in ssd tablespace with fillfactor=10 and autovacuum_analyze_threshold=1
163 community.postgresql.postgresql_table:
164 name: test_table
165 columns:
166 - id bigserial primary key
167 - num bigint
168 - stories text
169 tablespace: ssd
170 storage_params:
171 - fillfactor=10
172 - autovacuum_analyze_threshold=1
173
174 - name: Create an unlogged table in schema acme
175 community.postgresql.postgresql_table:
176 name: acme.useless_data
177 columns: waste_id int
178 unlogged: true
179
180 - name: Set owner to someuser
181 community.postgresql.postgresql_table:
182 name: foo
183 owner: someuser
184
185 - name: Change tablespace of foo table to new_tablespace and set owner to new_user
186 community.postgresql.postgresql_table:
187 name: foo
188 tablespace: new_tablespace
189 owner: new_user
190
191 - name: Truncate table foo
192 community.postgresql.postgresql_table:
193 name: foo
194 truncate: true
195
196 - name: Drop table foo from schema acme
197 community.postgresql.postgresql_table:
198 name: acme.foo
199 state: absent
200
201 - name: Drop table bar cascade
202 community.postgresql.postgresql_table:
203 name: bar
204 state: absent
205 cascade: true
206
207 - name: Create table with composite primary key
208 community.postgresql.postgresql_table:
209 name: composite_pk_table
210 columns:
211 - id bigserial
212 - num bigint
213 - primary key (id, num)
214 '''
215
216 RETURN = r'''
217 table:
218 description: Name of a table.
219 returned: success
220 type: str
221 sample: 'foo'
222 state:
223 description: Table state.
224 returned: success
225 type: str
226 sample: 'present'
227 owner:
228 description: Table owner.
229 returned: success
230 type: str
231 sample: 'postgres'
232 tablespace:
233 description: Tablespace.
234 returned: success
235 type: str
236 sample: 'ssd_tablespace'
237 queries:
238 description: List of executed queries.
239 returned: success
240 type: str
241 sample: [ 'CREATE TABLE "test_table" (id bigint)' ]
242 storage_params:
243 description: Storage parameters.
244 returned: success
245 type: list
246 sample: [ "fillfactor=100", "autovacuum_analyze_threshold=1" ]
247 '''
248
249 from ansible.module_utils.basic import AnsibleModule
250 from ansible_collections.community.postgresql.plugins.module_utils.database import (
251 check_input,
252 pg_quote_identifier,
253 )
254 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
255 connect_to_db,
256 ensure_required_libs,
257 exec_sql,
258 get_conn_params,
259 pg_cursor_args,
260 postgres_common_argument_spec,
261 )
262
263 # ===========================================
264 # PostgreSQL module specific support methods.
265 #
266
267
268 class Table(object):
269 def __init__(self, name, module, cursor):
270 self.name = name
271 self.module = module
272 self.cursor = cursor
273 self.info = {
274 'owner': '',
275 'tblspace': '',
276 'storage_params': [],
277 }
278 self.exists = False
279 self.__exists_in_db()
280 self.executed_queries = []
281
282 def get_info(self):
283 """Getter to refresh and get table info"""
284 self.__exists_in_db()
285
286 def __exists_in_db(self):
287 """Check table exists and refresh info"""
288 if "." in self.name:
289 schema = self.name.split('.')[-2]
290 tblname = self.name.split('.')[-1]
291 else:
292 schema = 'public'
293 tblname = self.name
294
295 query = ("SELECT t.tableowner, t.tablespace, c.reloptions "
296 "FROM pg_tables AS t "
297 "INNER JOIN pg_class AS c ON c.relname = t.tablename "
298 "INNER JOIN pg_namespace AS n ON t.schemaname = n.nspname AND c.relnamespace = n.oid "
299 "WHERE t.tablename = %(tblname)s "
300 "AND n.nspname = %(schema)s")
301 res = exec_sql(self, query, query_params={'tblname': tblname, 'schema': schema},
302 add_to_executed=False)
303 if res:
304 self.exists = True
305 self.info = dict(
306 owner=res[0]["tableowner"],
307 tblspace=res[0]["tablespace"] if res[0]["tablespace"] else '',
308 storage_params=res[0]["reloptions"] if res[0]["reloptions"] else [],
309 )
310
311 return True
312 else:
313 self.exists = False
314 return False
315
316 def create(self, columns='', params='', tblspace='',
317 unlogged=False, owner=''):
318 """
319 Create table.
320 If table exists, check passed args (params, tblspace, owner) and,
321 if they're different from current, change them.
322 Arguments:
323 params - storage params (passed by "WITH (...)" in SQL),
324 comma separated.
325 tblspace - tablespace.
326 owner - table owner.
327 unlogged - create unlogged table.
328 columns - column string (comma separated).
329 """
330 name = pg_quote_identifier(self.name, 'table')
331
332 changed = False
333
334 if self.exists:
335 if tblspace == 'pg_default' and self.info['tblspace'] is None:
336 pass # Because they have the same meaning
337 elif tblspace and self.info['tblspace'] != tblspace:
338 self.set_tblspace(tblspace)
339 changed = True
340
341 if owner and self.info['owner'] != owner:
342 self.set_owner(owner)
343 changed = True
344
345 if params:
346 param_list = [p.strip(' ') for p in params.split(',')]
347
348 new_param = False
349 for p in param_list:
350 if p not in self.info['storage_params']:
351 new_param = True
352
353 if new_param:
354 self.set_stor_params(params)
355 changed = True
356
357 if changed:
358 return True
359 return False
360
361 query = "CREATE"
362 if unlogged:
363 query += " UNLOGGED TABLE %s" % name
364 else:
365 query += " TABLE %s" % name
366
367 if columns:
368 query += " (%s)" % columns
369 else:
370 query += " ()"
371
372 if params:
373 query += " WITH (%s)" % params
374
375 if tblspace:
376 query += ' TABLESPACE "%s"' % tblspace
377
378 if exec_sql(self, query, return_bool=True):
379 changed = True
380
381 if owner:
382 changed = self.set_owner(owner)
383
384 return changed
385
386 def create_like(self, src_table, including='', tblspace='',
387 unlogged=False, params='', owner=''):
388 """
389 Create table like another table (with similar DDL).
390 Arguments:
391 src_table - source table.
392 including - corresponds to optional INCLUDING expression
393 in CREATE TABLE ... LIKE statement.
394 params - storage params (passed by "WITH (...)" in SQL),
395 comma separated.
396 tblspace - tablespace.
397 owner - table owner.
398 unlogged - create unlogged table.
399 """
400 changed = False
401
402 name = pg_quote_identifier(self.name, 'table')
403
404 query = "CREATE"
405 if unlogged:
406 query += " UNLOGGED TABLE %s" % name
407 else:
408 query += " TABLE %s" % name
409
410 query += " (LIKE %s" % pg_quote_identifier(src_table, 'table')
411
412 if including:
413 including = including.split(',')
414 for i in including:
415 query += " INCLUDING %s" % i
416
417 query += ')'
418
419 if params:
420 query += " WITH (%s)" % params
421
422 if tblspace:
423 query += ' TABLESPACE "%s"' % tblspace
424
425 if exec_sql(self, query, return_bool=True):
426 changed = True
427
428 if owner:
429 changed = self.set_owner(owner)
430
431 return changed
432
433 def truncate(self):
434 query = "TRUNCATE TABLE %s" % pg_quote_identifier(self.name, 'table')
435 return exec_sql(self, query, return_bool=True)
436
437 def rename(self, newname):
438 query = "ALTER TABLE %s RENAME TO %s" % (pg_quote_identifier(self.name, 'table'),
439 pg_quote_identifier(newname, 'table'))
440 return exec_sql(self, query, return_bool=True)
441
442 def set_owner(self, username):
443 query = 'ALTER TABLE %s OWNER TO "%s"' % (pg_quote_identifier(self.name, 'table'), username)
444 return exec_sql(self, query, return_bool=True)
445
446 def drop(self, cascade=False):
447 if not self.exists:
448 return False
449
450 query = "DROP TABLE %s" % pg_quote_identifier(self.name, 'table')
451 if cascade:
452 query += " CASCADE"
453 return exec_sql(self, query, return_bool=True)
454
455 def set_tblspace(self, tblspace):
456 query = 'ALTER TABLE %s SET TABLESPACE "%s"' % (pg_quote_identifier(self.name, 'table'), tblspace)
457 return exec_sql(self, query, return_bool=True)
458
459 def set_stor_params(self, params):
460 query = "ALTER TABLE %s SET (%s)" % (pg_quote_identifier(self.name, 'table'), params)
461 return exec_sql(self, query, return_bool=True)
462
463
464 # ===========================================
465 # Module execution.
466 #
467
468
469 def main():
470 argument_spec = postgres_common_argument_spec()
471 argument_spec.update(
472 table=dict(type='str', required=True, aliases=['name']),
473 state=dict(type='str', default='present', choices=['absent', 'present']),
474 login_db=dict(type='str', default='', aliases=['db'], deprecated_aliases=[
475 {
476 'name': 'db',
477 'version': '5.0.0',
478 'collection_name': 'community.postgresql',
479 }],
480 ),
481 tablespace=dict(type='str'),
482 owner=dict(type='str'),
483 unlogged=dict(type='bool', default=False),
484 like=dict(type='str'),
485 including=dict(type='str'),
486 rename=dict(type='str', removed_in_version='5.0.0',
487 removed_from_collection='community.postgresql'),
488 truncate=dict(type='bool', default=False),
489 columns=dict(type='list', elements='str'),
490 storage_params=dict(type='list', elements='str'),
491 session_role=dict(type='str'),
492 cascade=dict(type='bool', default=False),
493 trust_input=dict(type='bool', default=True),
494 )
495 module = AnsibleModule(
496 argument_spec=argument_spec,
497 supports_check_mode=True,
498 )
499
500 table = module.params['table']
501 state = module.params['state']
502 tablespace = module.params['tablespace']
503 owner = module.params['owner']
504 unlogged = module.params['unlogged']
505 like = module.params['like']
506 including = module.params['including']
507 newname = module.params['rename']
508 storage_params = module.params['storage_params']
509 truncate = module.params['truncate']
510 columns = module.params['columns']
511 cascade = module.params['cascade']
512 session_role = module.params['session_role']
513 trust_input = module.params['trust_input']
514
515 if not trust_input:
516 # Check input for potentially dangerous elements:
517 check_input(module, table, tablespace, owner, like, including,
518 newname, storage_params, columns, session_role)
519
520 if state == 'present' and cascade:
521 module.warn("cascade=true is ignored when state=present")
522
523 # Check mutual exclusive parameters:
524 if state == 'absent' and (truncate or newname or columns or tablespace or like or storage_params or unlogged or owner or including):
525 module.fail_json(msg="%s: state=absent is mutually exclusive with: "
526 "truncate, rename, columns, tablespace, "
527 "including, like, storage_params, unlogged, owner" % table)
528
529 if truncate and (newname or columns or like or unlogged or storage_params or owner or tablespace or including):
530 module.fail_json(msg="%s: truncate is mutually exclusive with: "
531 "rename, columns, like, unlogged, including, "
532 "storage_params, owner, tablespace" % table)
533
534 if newname and (columns or like or unlogged or storage_params or owner or tablespace or including):
535 module.fail_json(msg="%s: rename is mutually exclusive with: "
536 "columns, like, unlogged, including, "
537 "storage_params, owner, tablespace" % table)
538
539 if like and columns:
540 module.fail_json(msg="%s: like and columns params are mutually exclusive" % table)
541 if including and not like:
542 module.fail_json(msg="%s: including param needs like param specified" % table)
543
544 # Ensure psycopg libraries are available before connecting to DB:
545 ensure_required_libs(module)
546 conn_params = get_conn_params(module, module.params)
547 db_connection, dummy = connect_to_db(module, conn_params, autocommit=False)
548 cursor = db_connection.cursor(**pg_cursor_args)
549
550 if storage_params:
551 storage_params = ','.join(storage_params)
552
553 if columns:
554 columns = ','.join(columns)
555
556 ##############
557 # Do main job:
558 table_obj = Table(table, module, cursor)
559
560 # Set default returned values:
561 changed = False
562 kw = {}
563 kw['table'] = table
564 kw['state'] = ''
565 if table_obj.exists:
566 kw = dict(
567 table=table,
568 state='present',
569 owner=table_obj.info['owner'],
570 tablespace=table_obj.info['tblspace'],
571 storage_params=table_obj.info['storage_params'],
572 )
573
574 if state == 'absent':
575 changed = table_obj.drop(cascade=cascade)
576
577 elif truncate:
578 changed = table_obj.truncate()
579
580 elif newname:
581 changed = table_obj.rename(newname)
582 q = table_obj.executed_queries
583 table_obj = Table(newname, module, cursor)
584 table_obj.executed_queries = q
585
586 elif state == 'present' and not like:
587 changed = table_obj.create(columns, storage_params,
588 tablespace, unlogged, owner)
589
590 elif state == 'present' and like:
591 changed = table_obj.create_like(like, including, tablespace,
592 unlogged, storage_params)
593
594 if changed:
595 if module.check_mode:
596 db_connection.rollback()
597 else:
598 db_connection.commit()
599
600 # Refresh table info for RETURN.
601 # Note, if table has been renamed, it gets info by newname:
602 table_obj.get_info()
603 db_connection.commit()
604 if table_obj.exists:
605 kw = dict(
606 table=table,
607 state='present',
608 owner=table_obj.info['owner'],
609 tablespace=table_obj.info['tblspace'],
610 storage_params=table_obj.info['storage_params'],
611 )
612 else:
613 # We just change the table state here
614 # to keep other information about the dropped table:
615 kw['state'] = 'absent'
616
617 kw['queries'] = table_obj.executed_queries
618 kw['changed'] = changed
619 db_connection.close()
620 module.exit_json(**kw)
621
622
623 if __name__ == '__main__':
624 main()