Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018-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_idx
14 short_description: Create or drop indexes from a PostgreSQL database
15 description:
16 - Create or drop indexes from a PostgreSQL database.
17
18 options:
19 idxname:
20 description:
21 - Name of the index to create or drop.
22 type: str
23 required: true
24 aliases:
25 - name
26 login_db:
27 description:
28 - Name of database to connect to and where the index will be created/dropped.
29 - The V(db) alias is deprecated and will be removed in version 5.0.0.
30 type: str
31 aliases:
32 - db
33 session_role:
34 description:
35 - Switch to session_role after connecting.
36 The specified session_role must be a role that the current login_user is a member of.
37 - Permissions checking for SQL commands is carried out as though
38 the session_role were the one that had logged in originally.
39 type: str
40 schema:
41 description:
42 - Name of a database schema where the index will be created.
43 type: str
44 state:
45 description:
46 - Index state.
47 - C(present) implies the index will be created if it does not exist.
48 - C(absent) implies the index will be dropped if it exists.
49 type: str
50 default: present
51 choices: [ absent, present ]
52 table:
53 description:
54 - Table to create index on it.
55 - Mutually exclusive with I(state=absent).
56 type: str
57 columns:
58 description:
59 - List of index columns that need to be covered by index.
60 - Mutually exclusive with I(state=absent).
61 type: list
62 elements: str
63 aliases:
64 - column
65 cond:
66 description:
67 - Index conditions.
68 - Mutually exclusive with I(state=absent).
69 type: str
70 idxtype:
71 description:
72 - Index type (like btree, gist, gin, etc.).
73 - Mutually exclusive with I(state=absent).
74 type: str
75 aliases:
76 - type
77 concurrent:
78 description:
79 - Enable or disable concurrent mode (CREATE / DROP INDEX CONCURRENTLY).
80 - Pay attention, if I(concurrent=false), the table will be locked (ACCESS EXCLUSIVE) during the building process.
81 For more information about the lock levels see U(https://www.postgresql.org/docs/current/explicit-locking.html).
82 - If the building process was interrupted for any reason when I(cuncurrent=true), the index becomes invalid.
83 In this case it should be dropped and created again.
84 - Mutually exclusive with I(cascade=true).
85 type: bool
86 default: true
87 unique:
88 description:
89 - Enable unique index.
90 - Only btree currently supports unique indexes.
91 type: bool
92 default: false
93 version_added: '0.2.0'
94 tablespace:
95 description:
96 - Set a tablespace for the index.
97 - Mutually exclusive with I(state=absent).
98 type: str
99 storage_params:
100 description:
101 - Storage parameters like fillfactor, vacuum_cleanup_index_scale_factor, etc.
102 - Mutually exclusive with I(state=absent).
103 type: list
104 elements: str
105 cascade:
106 description:
107 - Automatically drop objects that depend on the index,
108 and in turn all objects that depend on those objects.
109 - It used only with I(state=absent).
110 - Mutually exclusive with I(concurrent=true).
111 type: bool
112 default: false
113 trust_input:
114 description:
115 - If C(false), check whether values of parameters I(idxname), I(session_role),
116 I(schema), I(table), I(columns), I(tablespace), I(storage_params),
117 I(cond) are potentially dangerous.
118 - It makes sense to use C(false) only when SQL injections via the parameters are possible.
119 type: bool
120 default: true
121 version_added: '0.2.0'
122
123 seealso:
124 - module: community.postgresql.postgresql_table
125 - module: community.postgresql.postgresql_tablespace
126 - name: PostgreSQL indexes reference
127 description: General information about PostgreSQL indexes.
128 link: https://www.postgresql.org/docs/current/indexes.html
129 - name: CREATE INDEX reference
130 description: Complete reference of the CREATE INDEX command documentation.
131 link: https://www.postgresql.org/docs/current/sql-createindex.html
132 - name: ALTER INDEX reference
133 description: Complete reference of the ALTER INDEX command documentation.
134 link: https://www.postgresql.org/docs/current/sql-alterindex.html
135 - name: DROP INDEX reference
136 description: Complete reference of the DROP INDEX command documentation.
137 link: https://www.postgresql.org/docs/current/sql-dropindex.html
138
139 notes:
140 - The index building process can affect database performance.
141 - To avoid table locks on production databases, use I(concurrent=true) (default behavior).
142
143 attributes:
144 check_mode:
145 support: full
146
147 author:
148 - Andrew Klychkov (@Andersson007)
149 - Thomas O'Donnell (@andytom)
150
151 extends_documentation_fragment:
152 - community.postgresql.postgres
153 '''
154
155 EXAMPLES = r'''
156 - name: Create btree index if not exists test_idx concurrently covering columns id and name of table products
157 community.postgresql.postgresql_idx:
158 login_db: acme
159 table: products
160 columns: id,name
161 name: test_idx
162
163 - name: Create btree index test_idx concurrently with tablespace called ssd and storage parameter
164 community.postgresql.postgresql_idx:
165 login_db: acme
166 table: products
167 columns:
168 - id
169 - name
170 idxname: test_idx
171 tablespace: ssd
172 storage_params:
173 - fillfactor=90
174
175 - name: Create gist index test_gist_idx concurrently on column geo_data of table map
176 community.postgresql.postgresql_idx:
177 login_db: somedb
178 table: map
179 idxtype: gist
180 columns: geo_data
181 idxname: test_gist_idx
182
183 # Note: for the example below pg_trgm extension must be installed for gin_trgm_ops
184 - name: Create gin index gin0_idx not concurrently on column comment of table test
185 community.postgresql.postgresql_idx:
186 idxname: gin0_idx
187 table: test
188 columns: comment gin_trgm_ops
189 concurrent: false
190 idxtype: gin
191
192 - name: Drop btree test_idx concurrently
193 community.postgresql.postgresql_idx:
194 login_db: mydb
195 idxname: test_idx
196 state: absent
197
198 - name: Drop test_idx cascade
199 community.postgresql.postgresql_idx:
200 login_db: mydb
201 idxname: test_idx
202 state: absent
203 cascade: true
204 concurrent: false
205
206 - name: Create btree index test_idx concurrently on columns id,comment where column id > 1
207 community.postgresql.postgresql_idx:
208 login_db: mydb
209 table: test
210 columns: id,comment
211 idxname: test_idx
212 cond: id > 1
213
214 - name: Create unique btree index if not exists test_unique_idx on column name of table products
215 community.postgresql.postgresql_idx:
216 login_db: acme
217 table: products
218 columns: name
219 name: test_unique_idx
220 unique: true
221 concurrent: false
222 '''
223
224 RETURN = r'''
225 name:
226 description: Index name.
227 returned: success
228 type: str
229 sample: 'foo_idx'
230 state:
231 description: Index state.
232 returned: success
233 type: str
234 sample: 'present'
235 schema:
236 description: Schema where index exists.
237 returned: success
238 type: str
239 sample: 'public'
240 tablespace:
241 description: Tablespace where index exists.
242 returned: success
243 type: str
244 sample: 'ssd'
245 query:
246 description: Query that was tried to be executed.
247 returned: success
248 type: str
249 sample: 'CREATE INDEX CONCURRENTLY foo_idx ON test_table USING BTREE (id)'
250 storage_params:
251 description: Index storage parameters.
252 returned: success
253 type: list
254 sample: [ "fillfactor=90" ]
255 valid:
256 description: Index validity.
257 returned: success
258 type: bool
259 sample: true
260 '''
261
262 from ansible.module_utils.basic import AnsibleModule
263 from ansible_collections.community.postgresql.plugins.module_utils.database import \
264 check_input
265 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
266 connect_to_db,
267 ensure_required_libs,
268 exec_sql,
269 get_conn_params,
270 pg_cursor_args,
271 postgres_common_argument_spec,
272 )
273
274 VALID_IDX_TYPES = ('BTREE', 'HASH', 'GIST', 'SPGIST', 'GIN', 'BRIN')
275
276
277 # ===========================================
278 # PostgreSQL module specific support methods.
279 #
280
281 class Index(object):
282
283 """Class for working with PostgreSQL indexes.
284
285 TODO:
286 1. Add possibility to change ownership
287 2. Add possibility to change tablespace
288 3. Add list called executed_queries (executed_query should be left too)
289 4. Use self.module instead of passing arguments to the methods whenever possible
290
291 Args:
292 module (AnsibleModule) -- object of AnsibleModule class
293 cursor (cursor) -- cursor object of psycopg library
294 schema (str) -- name of the index schema
295 name (str) -- name of the index
296
297 Attrs:
298 module (AnsibleModule) -- object of AnsibleModule class
299 cursor (cursor) -- cursor object of psycopg library
300 schema (str) -- name of the index schema
301 name (str) -- name of the index
302 exists (bool) -- flag the index exists in the DB or not
303 info (dict) -- dict that contents information about the index
304 executed_query (str) -- executed query
305 """
306
307 def __init__(self, module, cursor, schema, name):
308 self.name = name
309 if schema:
310 self.schema = schema
311 else:
312 self.schema = 'public'
313 self.module = module
314 self.cursor = cursor
315 self.info = {
316 'name': self.name,
317 'state': 'absent',
318 'schema': '',
319 'tblname': '',
320 'tblspace': '',
321 'valid': True,
322 'storage_params': [],
323 }
324 self.exists = False
325 self.__exists_in_db()
326 self.executed_query = ''
327
328 def get_info(self):
329 """Refresh index info.
330
331 Return self.info dict.
332 """
333 self.__exists_in_db()
334 return self.info
335
336 def __exists_in_db(self):
337 """Check index existence, collect info, add it to self.info dict.
338
339 Return True if the index exists, otherwise, return False.
340 """
341 query = ("SELECT i.schemaname, i.tablename, i.tablespace, "
342 "pi.indisvalid, c.reloptions "
343 "FROM pg_catalog.pg_indexes AS i "
344 "JOIN pg_catalog.pg_class AS c "
345 "ON i.indexname = c.relname "
346 "JOIN pg_catalog.pg_index AS pi "
347 "ON c.oid = pi.indexrelid "
348 "WHERE i.schemaname = %(schema)s "
349 "AND i.indexname = %(name)s")
350
351 res = exec_sql(self, query, query_params={'schema': self.schema, 'name': self.name}, add_to_executed=False)
352 if res:
353 self.exists = True
354 self.info = dict(
355 name=self.name,
356 state='present',
357 schema=res[0]["schemaname"],
358 tblname=res[0]["tablename"],
359 tblspace=res[0]["tablespace"] if res[0]["tablespace"] else '',
360 valid=res[0]["indisvalid"],
361 storage_params=res[0]["reloptions"] if res[0]["reloptions"] else [],
362 )
363 return True
364
365 else:
366 self.exists = False
367 return False
368
369 def create(self, tblname, idxtype, columns, cond, tblspace,
370 storage_params, concurrent=True, unique=False):
371 """Create PostgreSQL index.
372
373 Return True if success, otherwise, return False.
374
375 Args:
376 tblname (str) -- name of a table for the index
377 idxtype (str) -- type of the index like BTREE, BRIN, etc
378 columns (str) -- string of comma-separated columns that need to be covered by index
379 tblspace (str) -- tablespace for storing the index
380 storage_params (str) -- string of comma-separated storage parameters
381
382 Kwargs:
383 concurrent (bool) -- build index in concurrent mode, default True
384 """
385 if self.exists:
386 return False
387
388 if idxtype is None:
389 idxtype = "BTREE"
390
391 query = 'CREATE'
392
393 if unique:
394 query += ' UNIQUE'
395
396 query += ' INDEX'
397
398 if concurrent:
399 query += ' CONCURRENTLY'
400
401 query += ' "%s"' % self.name
402
403 query += ' ON "%s"."%s" ' % (self.schema, tblname)
404
405 query += 'USING %s (%s)' % (idxtype, columns)
406
407 if storage_params:
408 query += ' WITH (%s)' % storage_params
409
410 if tblspace:
411 query += ' TABLESPACE "%s"' % tblspace
412
413 if cond:
414 query += ' WHERE %s' % cond
415
416 self.executed_query = query
417
418 return exec_sql(self, query, return_bool=True, add_to_executed=False)
419
420 def drop(self, cascade=False, concurrent=True):
421 """Drop PostgreSQL index.
422
423 Return True if success, otherwise, return False.
424
425 Args:
426 schema (str) -- name of the index schema
427
428 Kwargs:
429 cascade (bool) -- automatically drop objects that depend on the index,
430 default False
431 concurrent (bool) -- build index in concurrent mode, default True
432 """
433 if not self.exists:
434 return False
435
436 query = 'DROP INDEX'
437
438 if concurrent:
439 query += ' CONCURRENTLY'
440
441 query += ' "%s"."%s"' % (self.schema, self.name)
442
443 if cascade:
444 query += ' CASCADE'
445
446 self.executed_query = query
447
448 return exec_sql(self, query, return_bool=True, add_to_executed=False)
449
450
451 # ===========================================
452 # Module execution.
453 #
454
455
456 def main():
457 argument_spec = postgres_common_argument_spec()
458 argument_spec.update(
459 idxname=dict(type='str', required=True, aliases=['name']),
460 login_db=dict(type='str', aliases=['db'], deprecated_aliases=[
461 {
462 'name': 'db',
463 'version': '5.0.0',
464 'collection_name': 'community.postgresql',
465 }],
466 ),
467 state=dict(type='str', default='present', choices=['absent', 'present']),
468 concurrent=dict(type='bool', default=True),
469 unique=dict(type='bool', default=False),
470 table=dict(type='str'),
471 idxtype=dict(type='str', aliases=['type']),
472 columns=dict(type='list', elements='str', aliases=['column']),
473 cond=dict(type='str'),
474 session_role=dict(type='str'),
475 tablespace=dict(type='str'),
476 storage_params=dict(type='list', elements='str'),
477 cascade=dict(type='bool', default=False),
478 schema=dict(type='str'),
479 trust_input=dict(type='bool', default=True),
480 )
481 module = AnsibleModule(
482 argument_spec=argument_spec,
483 supports_check_mode=True,
484 )
485
486 idxname = module.params["idxname"]
487 state = module.params["state"]
488 concurrent = module.params["concurrent"]
489 unique = module.params["unique"]
490 table = module.params["table"]
491 idxtype = module.params["idxtype"]
492 columns = module.params["columns"]
493 cond = module.params["cond"]
494 tablespace = module.params["tablespace"]
495 storage_params = module.params["storage_params"]
496 cascade = module.params["cascade"]
497 schema = module.params["schema"]
498 session_role = module.params["session_role"]
499 trust_input = module.params["trust_input"]
500
501 if not trust_input:
502 # Check input for potentially dangerous elements:
503 check_input(module, idxname, session_role, schema, table, columns,
504 tablespace, storage_params, cond)
505
506 if concurrent and cascade:
507 module.fail_json(msg="Concurrent mode and cascade parameters are mutually exclusive")
508
509 if unique and (idxtype and idxtype != 'btree'):
510 module.fail_json(msg="Only btree currently supports unique indexes")
511
512 if state == 'present':
513 if not table:
514 module.fail_json(msg="Table must be specified")
515 if not columns:
516 module.fail_json(msg="At least one column must be specified")
517 else:
518 if table or columns or cond or idxtype or tablespace:
519 module.fail_json(msg="Index %s is going to be removed, so it does not "
520 "make sense to pass a table name, columns, conditions, "
521 "index type, or tablespace" % idxname)
522
523 if cascade and state != 'absent':
524 module.fail_json(msg="cascade parameter used only with state=absent")
525
526 # Ensure psycopg libraries are available before connecting to DB:
527 ensure_required_libs(module)
528 conn_params = get_conn_params(module, module.params)
529 db_connection, dummy = connect_to_db(module, conn_params, autocommit=True)
530 cursor = db_connection.cursor(**pg_cursor_args)
531
532 # Set defaults:
533 changed = False
534
535 # Do job:
536 index = Index(module, cursor, schema, idxname)
537 kw = index.get_info()
538 kw['query'] = ''
539
540 #
541 # check_mode start
542 if module.check_mode:
543 if state == 'present' and index.exists:
544 kw['changed'] = False
545 module.exit_json(**kw)
546
547 elif state == 'present' and not index.exists:
548 kw['changed'] = True
549 module.exit_json(**kw)
550
551 elif state == 'absent' and not index.exists:
552 kw['changed'] = False
553 module.exit_json(**kw)
554
555 elif state == 'absent' and index.exists:
556 kw['changed'] = True
557 module.exit_json(**kw)
558 # check_mode end
559 #
560
561 if state == "present":
562 if idxtype and idxtype.upper() not in VALID_IDX_TYPES:
563 module.fail_json(msg="Index type '%s' of %s is not in valid types" % (idxtype, idxname))
564
565 columns = ','.join(columns)
566
567 if storage_params:
568 storage_params = ','.join(storage_params)
569
570 changed = index.create(table, idxtype, columns, cond, tablespace, storage_params, concurrent, unique)
571
572 if changed:
573 kw = index.get_info()
574 kw['state'] = 'present'
575 kw['query'] = index.executed_query
576
577 else:
578 changed = index.drop(cascade, concurrent)
579
580 if changed:
581 kw['state'] = 'absent'
582 kw['query'] = index.executed_query
583
584 if not kw['valid']:
585 db_connection.rollback()
586 module.warn("Index %s is invalid! ROLLBACK" % idxname)
587
588 if not concurrent:
589 db_connection.commit()
590
591 kw['changed'] = changed
592 db_connection.close()
593 module.exit_json(**kw)
594
595
596 if __name__ == '__main__':
597 main()