1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

Refactor postgresql modules (#291)

* Refactor postgresql_idx to simplify code

Have refactored the postgresql_idx module to:
* Use the class schema in the drop function rather than a passed in one
* Remove the if/else and just return the bool in the drop and create
  functions

* Refactor postgresql_ext module

Have refactored the postgresql_ext module to:
* Remove an unused exception
* Simplify logic in the create and update functions
* Use list comprehension to simplify getting the available version

* Refactor postgresql_user_obj_stat_info module

Have refactored the postgresql_user_obj_stat_info module to:
* Simplify the logic in some of the functions
* Reduce duplicate code

* Add changelog fragment
This commit is contained in:
Thomas O'Donnell 2020-05-12 08:32:06 +02:00 committed by GitHub
parent 2319d928c4
commit 51b8e79203
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 57 additions and 75 deletions

View file

@ -0,0 +1,5 @@
---
minor_changes:
- postgresql_ext - refactor to simplify and remove dead code (https://github.com/ansible-collections/community.general/pull/291)
- postgresql_idx - refactor to simplify code (https://github.com/ansible-collections/community.general/pull/291)
- postgresql_user_obj_stat_info - refactor to simplify code (https://github.com/ansible-collections/community.general/pull/291)

View file

@ -195,10 +195,6 @@ from ansible.module_utils._text import to_native
executed_queries = [] executed_queries = []
class NotSupportedError(Exception):
pass
# =========================================== # ===========================================
# PostgreSQL module specific support methods. # PostgreSQL module specific support methods.
# #
@ -231,32 +227,33 @@ def ext_update_version(cursor, ext, version):
ext (str) -- extension name ext (str) -- extension name
version (str) -- extension version version (str) -- extension version
""" """
query = "ALTER EXTENSION \"%s\" UPDATE" % ext
params = {}
if version != 'latest': if version != 'latest':
query = ("ALTER EXTENSION \"%s\"" % ext) query += " TO %(ver)s"
cursor.execute(query + " UPDATE TO %(ver)s", {'ver': version}) params['ver'] = version
executed_queries.append(cursor.mogrify(query + " UPDATE TO %(ver)s", {'ver': version}))
else: cursor.execute(query, params)
query = ("ALTER EXTENSION \"%s\" UPDATE" % ext) executed_queries.append(cursor.mogrify(query, params))
cursor.execute(query)
executed_queries.append(query)
return True return True
def ext_create(cursor, ext, schema, cascade, version): def ext_create(cursor, ext, schema, cascade, version):
query = "CREATE EXTENSION \"%s\"" % ext query = "CREATE EXTENSION \"%s\"" % ext
params = {}
if schema: if schema:
query += " WITH SCHEMA \"%s\"" % schema query += " WITH SCHEMA \"%s\"" % schema
if version: if version:
query += " VERSION %(ver)s" query += " VERSION %(ver)s"
params['ver'] = version
if cascade: if cascade:
query += " CASCADE" query += " CASCADE"
if version: cursor.execute(query, params)
cursor.execute(query, {'ver': version}) executed_queries.append(cursor.mogrify(query, params))
executed_queries.append(cursor.mogrify(query, {'ver': version}))
else:
cursor.execute(query)
executed_queries.append(query)
return True return True
@ -292,12 +289,11 @@ def ext_get_versions(cursor, ext):
cursor.execute(query, {'ext': ext}) cursor.execute(query, {'ext': ext})
res = cursor.fetchall() res = cursor.fetchall()
available_versions = [] available_versions = [
if res: line['version']
# Make the list of available versions: for line in res
for line in res: if LooseVersion(line['version']) > LooseVersion(current_version)
if LooseVersion(line[0]) > LooseVersion(current_version): ]
available_versions.append(line['version'])
if current_version == '0': if current_version == '0':
current_version = False current_version = False
@ -372,7 +368,7 @@ def main():
"the passed version is not available" % (version, curr_version)) "the passed version is not available" % (version, curr_version))
# If the specific version is passed and it is higher that the current version: # If the specific version is passed and it is higher that the current version:
if curr_version and version: if curr_version:
if LooseVersion(curr_version) < LooseVersion(version): if LooseVersion(curr_version) < LooseVersion(version):
if module.check_mode: if module.check_mode:
changed = True changed = True

View file

@ -145,6 +145,7 @@ notes:
author: author:
- Andrew Klychkov (@Andersson007) - Andrew Klychkov (@Andersson007)
- Thomas O'Donnell (@andytom)
extends_documentation_fragment: extends_documentation_fragment:
- community.general.postgres - community.general.postgres
@ -418,12 +419,9 @@ class Index(object):
self.executed_query = query self.executed_query = query
if exec_sql(self, query, return_bool=True, add_to_executed=False): return exec_sql(self, query, return_bool=True, add_to_executed=False)
return True
return False def drop(self, cascade=False, concurrent=True):
def drop(self, schema, cascade=False, concurrent=True):
"""Drop PostgreSQL index. """Drop PostgreSQL index.
Return True if success, otherwise, return False. Return True if success, otherwise, return False.
@ -444,20 +442,14 @@ class Index(object):
if concurrent: if concurrent:
query += ' CONCURRENTLY' query += ' CONCURRENTLY'
if not schema: query += ' "%s"."%s"' % (self.schema, self.name)
query += ' "public"."%s"' % self.name
else:
query += ' "%s"."%s"' % (schema, self.name)
if cascade: if cascade:
query += ' CASCADE' query += ' CASCADE'
self.executed_query = query self.executed_query = query
if exec_sql(self, query, return_bool=True, add_to_executed=False): return exec_sql(self, query, return_bool=True, add_to_executed=False)
return True
return False
# =========================================== # ===========================================
@ -579,7 +571,7 @@ def main():
kw['query'] = index.executed_query kw['query'] = index.executed_query
else: else:
changed = index.drop(schema, cascade, concurrent) changed = index.drop(cascade, concurrent)
if changed: if changed:
kw['state'] = 'absent' kw['state'] = 'absent'

View file

@ -191,11 +191,10 @@ class PgUserObjStatInfo():
def get_func_stat(self): def get_func_stat(self):
"""Get function statistics and fill out self.info dictionary.""" """Get function statistics and fill out self.info dictionary."""
if not self.schema:
query = "SELECT * FROM pg_stat_user_functions" query = "SELECT * FROM pg_stat_user_functions"
result = exec_sql(self, query, add_to_executed=False) if self.schema:
else:
query = "SELECT * FROM pg_stat_user_functions WHERE schemaname = %s" query = "SELECT * FROM pg_stat_user_functions WHERE schemaname = %s"
result = exec_sql(self, query, query_params=(self.schema,), result = exec_sql(self, query, query_params=(self.schema,),
add_to_executed=False) add_to_executed=False)
@ -209,11 +208,10 @@ class PgUserObjStatInfo():
def get_idx_stat(self): def get_idx_stat(self):
"""Get index statistics and fill out self.info dictionary.""" """Get index statistics and fill out self.info dictionary."""
if not self.schema:
query = "SELECT * FROM pg_stat_user_indexes" query = "SELECT * FROM pg_stat_user_indexes"
result = exec_sql(self, query, add_to_executed=False) if self.schema:
else:
query = "SELECT * FROM pg_stat_user_indexes WHERE schemaname = %s" query = "SELECT * FROM pg_stat_user_indexes WHERE schemaname = %s"
result = exec_sql(self, query, query_params=(self.schema,), result = exec_sql(self, query, query_params=(self.schema,),
add_to_executed=False) add_to_executed=False)
@ -227,11 +225,10 @@ class PgUserObjStatInfo():
def get_tbl_stat(self): def get_tbl_stat(self):
"""Get table statistics and fill out self.info dictionary.""" """Get table statistics and fill out self.info dictionary."""
if not self.schema:
query = "SELECT * FROM pg_stat_user_tables" query = "SELECT * FROM pg_stat_user_tables"
result = exec_sql(self, query, add_to_executed=False) if self.schema:
else:
query = "SELECT * FROM pg_stat_user_tables WHERE schemaname = %s" query = "SELECT * FROM pg_stat_user_tables WHERE schemaname = %s"
result = exec_sql(self, query, query_params=(self.schema,), result = exec_sql(self, query, query_params=(self.schema,),
add_to_executed=False) add_to_executed=False)
@ -262,13 +259,12 @@ class PgUserObjStatInfo():
self.info[info_key][elem[schema_key]][elem[name_key]][key] = val self.info[info_key][elem[schema_key]][elem[name_key]][key] = val
if info_key in ('tables', 'indexes'): if info_key in ('tables', 'indexes'):
relname = elem[name_key]
schemaname = elem[schema_key] schemaname = elem[schema_key]
if not self.schema: if self.schema:
result = exec_sql(self, "SELECT pg_relation_size ('%s.%s')" % (schemaname, relname), schemaname = self.schema
add_to_executed=False)
else: relname = '%s.%s' % (schemaname, elem[name_key])
relname = '%s.%s' % (self.schema, relname)
result = exec_sql(self, "SELECT pg_relation_size (%s)", result = exec_sql(self, "SELECT pg_relation_size (%s)",
query_params=(relname,), query_params=(relname,),
add_to_executed=False) add_to_executed=False)
@ -276,13 +272,6 @@ class PgUserObjStatInfo():
self.info[info_key][elem[schema_key]][elem[name_key]]['size'] = result[0][0] self.info[info_key][elem[schema_key]][elem[name_key]]['size'] = result[0][0]
if info_key == 'tables': if info_key == 'tables':
relname = elem[name_key]
schemaname = elem[schema_key]
if not self.schema:
result = exec_sql(self, "SELECT pg_total_relation_size ('%s.%s')" % (schemaname, relname),
add_to_executed=False)
else:
relname = '%s.%s' % (self.schema, relname)
result = exec_sql(self, "SELECT pg_total_relation_size (%s)", result = exec_sql(self, "SELECT pg_total_relation_size (%s)",
query_params=(relname,), query_params=(relname,),
add_to_executed=False) add_to_executed=False)