postgresql: moved function exec_sql from the modules to module_utils (#57603)

This commit is contained in:
Andrey Klychkov 2019-06-10 12:15:07 +03:00 committed by René Moser
parent 17c5e0e016
commit ffa172e3a6
3 changed files with 42 additions and 66 deletions

View file

@ -147,3 +147,35 @@ def connect_to_db(module, autocommit=False, fail_on_conn=True, warn_db_default=T
db_connection = None
return db_connection
def exec_sql(obj, query, ddl=False, add_to_executed=True):
"""Execute SQL.
Auxiliary function for PostgreSQL user classes.
Returns a query result if possible or True/False if ddl=True arg was passed.
It necessary for statements that don't return any result (like DDL queries).
Arguments:
obj (obj) -- must be an object of a user class.
The object must have module (AnsibleModule class object) and
cursor (psycopg cursor object) attributes
query (str) -- SQL query to execute
ddl (bool) -- must return True or False instead of rows (typical for DDL queries)
(default False)
add_to_executed (bool) -- append the query to obj.executed_queries attribute
"""
try:
obj.cursor.execute(query)
if add_to_executed:
obj.executed_queries.append(query)
if not ddl:
res = obj.cursor.fetchall()
return res
return True
except Exception as e:
obj.module.fail_json(msg="Cannot execute SQL '%s': %s" % (query, to_native(e)))
return False