| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2017, Felix Archambault |
| 5 |
# Copyright: (c) 2019, Andrew Klychkov (@Andersson007) <[email protected]> |
| 6 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
|
| 8 |
from __future__ import absolute_import, division, print_function |
| 9 |
|
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
DOCUMENTATION = r''' |
| 13 |
--- |
| 14 |
module: postgresql_query |
| 15 |
short_description: Run PostgreSQL queries |
| 16 |
description: |
| 17 |
- Runs arbitrary PostgreSQL queries. |
| 18 |
options: |
| 19 |
query: |
| 20 |
description: |
| 21 |
- SQL query string or list of queries to run. Variables can be escaped with psycopg syntax |
| 22 |
U(https://www.psycopg.org/psycopg3/docs/basic/params.html). |
| 23 |
type: raw |
| 24 |
positional_args: |
| 25 |
description: |
| 26 |
- List of values to be passed as positional arguments to the query. |
| 27 |
When the value is a list, it will be converted to PostgreSQL array. |
| 28 |
- Mutually exclusive with I(named_args). |
| 29 |
type: list |
| 30 |
elements: raw |
| 31 |
named_args: |
| 32 |
description: |
| 33 |
- Dictionary of key-value arguments to pass to the query. |
| 34 |
When the value is a list, it will be converted to PostgreSQL array. |
| 35 |
- Mutually exclusive with I(positional_args). |
| 36 |
type: dict |
| 37 |
session_role: |
| 38 |
description: |
| 39 |
- Switch to session_role after connecting. The specified session_role must |
| 40 |
be a role that the current login_user is a member of. |
| 41 |
- Permissions checking for SQL commands is carried out as though |
| 42 |
the session_role were the one that had logged in originally. |
| 43 |
type: str |
| 44 |
login_db: |
| 45 |
description: |
| 46 |
- Name of database to connect to and run queries against. |
| 47 |
- The V(db) alias is deprecated and will be removed in version 5.0.0. |
| 48 |
type: str |
| 49 |
aliases: |
| 50 |
- db |
| 51 |
autocommit: |
| 52 |
description: |
| 53 |
- Execute in autocommit mode when the query can't be run inside a transaction block |
| 54 |
(e.g., VACUUM). |
| 55 |
- Mutually exclusive with I(check_mode). |
| 56 |
type: bool |
| 57 |
default: false |
| 58 |
encoding: |
| 59 |
description: |
| 60 |
- Set the client encoding for the current session (e.g. C(UTF-8)). |
| 61 |
- The default is the encoding defined by the database. |
| 62 |
type: str |
| 63 |
version_added: '0.2.0' |
| 64 |
trust_input: |
| 65 |
description: |
| 66 |
- If C(false), check whether a value of I(session_role) is potentially dangerous. |
| 67 |
- It makes sense to use C(false) only when SQL injections via I(session_role) are possible. |
| 68 |
type: bool |
| 69 |
default: true |
| 70 |
version_added: '0.2.0' |
| 71 |
search_path: |
| 72 |
description: |
| 73 |
- List of schema names to look in. |
| 74 |
type: list |
| 75 |
elements: str |
| 76 |
version_added: '1.0.0' |
| 77 |
seealso: |
| 78 |
- module: community.postgresql.postgresql_script |
| 79 |
- module: community.postgresql.postgresql_db |
| 80 |
- name: PostgreSQL Schema reference |
| 81 |
description: Complete reference of the PostgreSQL schema documentation. |
| 82 |
link: https://www.postgresql.org/docs/current/ddl-schemas.html |
| 83 |
|
| 84 |
attributes: |
| 85 |
check_mode: |
| 86 |
support: full |
| 87 |
|
| 88 |
author: |
| 89 |
- Felix Archambault (@archf) |
| 90 |
- Andrew Klychkov (@Andersson007) |
| 91 |
- Will Rouesnel (@wrouesnel) |
| 92 |
|
| 93 |
extends_documentation_fragment: |
| 94 |
- community.postgresql.postgres |
| 95 |
''' |
| 96 |
|
| 97 |
EXAMPLES = r''' |
| 98 |
- name: Simple select query to acme db |
| 99 |
community.postgresql.postgresql_query: |
| 100 |
login_db: acme |
| 101 |
query: SELECT version() |
| 102 |
|
| 103 |
# The result of each query will be stored in query_all_results return value |
| 104 |
- name: Run several queries against acme db |
| 105 |
community.postgresql.postgresql_query: |
| 106 |
login_db: acme |
| 107 |
query: |
| 108 |
- SELECT version() |
| 109 |
- SELECT id FROM accounts |
| 110 |
|
| 111 |
- name: Select query to db acme with positional arguments and non-default credentials |
| 112 |
community.postgresql.postgresql_query: |
| 113 |
login_db: acme |
| 114 |
login_user: django |
| 115 |
login_password: mysecretpass |
| 116 |
query: SELECT * FROM acme WHERE id = %s AND story = %s |
| 117 |
positional_args: |
| 118 |
- 1 |
| 119 |
- test |
| 120 |
|
| 121 |
- name: Select query to test_db with named_args |
| 122 |
community.postgresql.postgresql_query: |
| 123 |
login_db: test_db |
| 124 |
query: SELECT * FROM test WHERE id = %(id_val)s AND story = %(story_val)s |
| 125 |
named_args: |
| 126 |
id_val: 1 |
| 127 |
story_val: test |
| 128 |
|
| 129 |
- name: Insert query to test_table in db test_db |
| 130 |
community.postgresql.postgresql_query: |
| 131 |
login_db: test_db |
| 132 |
query: INSERT INTO test_table (id, story) VALUES (2, 'my_long_story') |
| 133 |
|
| 134 |
- name: Use connect_params to add any additional connection parameters that libpg supports |
| 135 |
community.postgresql.postgresql_query: |
| 136 |
connect_params: |
| 137 |
target_session_attrs: read-write |
| 138 |
connect_timeout: 10 |
| 139 |
login_host: "host1,host2" |
| 140 |
login_user: "test" |
| 141 |
login_password: "test1234" |
| 142 |
login_db: "test" |
| 143 |
query: 'insert into test (test) values (now())' |
| 144 |
|
| 145 |
- name: Example of using autocommit parameter |
| 146 |
community.postgresql.postgresql_query: |
| 147 |
login_db: test_db |
| 148 |
query: VACUUM |
| 149 |
autocommit: true |
| 150 |
|
| 151 |
- name: > |
| 152 |
Insert data to the column of array type using positional_args. |
| 153 |
Note that we use quotes here, the same as for passing JSON, etc. |
| 154 |
community.postgresql.postgresql_query: |
| 155 |
query: INSERT INTO test_table (array_column) VALUES (%s) |
| 156 |
positional_args: |
| 157 |
- '{1,2,3}' |
| 158 |
|
| 159 |
# Pass list and string vars as positional_args |
| 160 |
- name: Set vars |
| 161 |
ansible.builtin.set_fact: |
| 162 |
my_list: |
| 163 |
- 1 |
| 164 |
- 2 |
| 165 |
- 3 |
| 166 |
my_arr: '{1, 2, 3}' |
| 167 |
|
| 168 |
- name: Select from test table by passing positional_args as arrays |
| 169 |
community.postgresql.postgresql_query: |
| 170 |
query: SELECT * FROM test_array_table WHERE arr_col1 = %s AND arr_col2 = %s |
| 171 |
positional_args: |
| 172 |
- '{{ my_list }}' |
| 173 |
- '{{ my_arr|string }}' |
| 174 |
|
| 175 |
# Select from test table looking into app1 schema first, then, |
| 176 |
# if the schema doesn't exist or the table hasn't been found there, |
| 177 |
# try to find it in the schema public |
| 178 |
- name: Select from test using search_path |
| 179 |
community.postgresql.postgresql_query: |
| 180 |
query: SELECT * FROM test_array_table |
| 181 |
search_path: |
| 182 |
- app1 |
| 183 |
- public |
| 184 |
|
| 185 |
# If you use a variable in positional_args / named_args that can |
| 186 |
# be undefined and you wish to set it as NULL, the constructions like |
| 187 |
# "{{ my_var if (my_var is defined) else none | default(none) }}" |
| 188 |
# will not work as expected substituting an empty string instead of NULL. |
| 189 |
# If possible, we suggest to use Ansible's DEFAULT_JINJA2_NATIVE configuration |
| 190 |
# (https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-jinja2-native). |
| 191 |
# Enabling it fixes this problem. If you cannot enable it, the following workaround |
| 192 |
# can be used. |
| 193 |
# You should precheck such a value and define it as NULL when undefined. |
| 194 |
# For example: |
| 195 |
- name: When undefined, set to NULL |
| 196 |
set_fact: |
| 197 |
my_var: NULL |
| 198 |
when: my_var is undefined |
| 199 |
|
| 200 |
# Then: |
| 201 |
- name: Insert a value using positional arguments |
| 202 |
community.postgresql.postgresql_query: |
| 203 |
query: INSERT INTO test_table (col1) VALUES (%s) |
| 204 |
positional_args: |
| 205 |
- '{{ my_var }}' |
| 206 |
''' |
| 207 |
|
| 208 |
RETURN = r''' |
| 209 |
query: |
| 210 |
description: |
| 211 |
- Executed query. |
| 212 |
- When reading several queries from a file, it contains only the last one. |
| 213 |
returned: success |
| 214 |
type: str |
| 215 |
sample: 'SELECT * FROM bar' |
| 216 |
statusmessage: |
| 217 |
description: |
| 218 |
- Attribute containing the message returned by the command. |
| 219 |
- When reading several queries from a file, it contains a message of the last one. |
| 220 |
returned: success |
| 221 |
type: str |
| 222 |
sample: 'INSERT 0 1' |
| 223 |
query_result: |
| 224 |
description: |
| 225 |
- List of dictionaries in column:value form representing returned rows. |
| 226 |
- When running queries from a file, returns result of the last query. |
| 227 |
returned: success |
| 228 |
type: list |
| 229 |
elements: dict |
| 230 |
sample: [{"Column": "Value1"},{"Column": "Value2"}] |
| 231 |
query_list: |
| 232 |
description: |
| 233 |
- List of executed queries. |
| 234 |
returned: success |
| 235 |
type: list |
| 236 |
elements: str |
| 237 |
sample: ['SELECT * FROM foo', 'SELECT * FROM bar'] |
| 238 |
query_all_results: |
| 239 |
description: |
| 240 |
- List containing results of all queries executed (one sublist for every query). |
| 241 |
returned: success |
| 242 |
type: list |
| 243 |
elements: list |
| 244 |
sample: [[{"Column": "Value1"},{"Column": "Value2"}], [{"Column": "Value1"},{"Column": "Value2"}]] |
| 245 |
rowcount: |
| 246 |
description: |
| 247 |
- Number of produced or affected rows. |
| 248 |
- When using a script with multiple queries, |
| 249 |
it contains a total number of produced or affected rows. |
| 250 |
returned: changed |
| 251 |
type: int |
| 252 |
sample: 5 |
| 253 |
execution_time_ms: |
| 254 |
description: |
| 255 |
- A list containing execution time per query in milliseconds. |
| 256 |
- The measurements are done right before and after passing |
| 257 |
the query to the driver for execution. |
| 258 |
returned: success |
| 259 |
type: list |
| 260 |
sample: [7104] |
| 261 |
version_added: '3.10.0' |
| 262 |
''' |
| 263 |
|
| 264 |
import re |
| 265 |
import time |
| 266 |
|
| 267 |
from ansible.module_utils.common.text.converters import to_native |
| 268 |
from ansible.module_utils.basic import AnsibleModule |
| 269 |
from ansible_collections.community.postgresql.plugins.module_utils.database import \ |
| 270 |
check_input |
| 271 |
from ansible_collections.community.postgresql.plugins.module_utils.postgres import ( |
| 272 |
HAS_PSYCOPG, |
| 273 |
PSYCOPG_VERSION, |
| 274 |
TYPES_NEED_TO_CONVERT, |
| 275 |
connect_to_db, |
| 276 |
convert_elements_to_pg_arrays, |
| 277 |
convert_to_supported, |
| 278 |
ensure_required_libs, |
| 279 |
get_conn_params, |
| 280 |
pg_cursor_args, |
| 281 |
postgres_common_argument_spec, |
| 282 |
set_search_path, |
| 283 |
) |
| 284 |
from ansible_collections.community.postgresql.plugins.module_utils.version import \ |
| 285 |
LooseVersion |
| 286 |
|
| 287 |
if HAS_PSYCOPG and PSYCOPG_VERSION < LooseVersion("3.0"): |
| 288 |
from psycopg2 import ProgrammingError as PsycopgProgrammingError |
| 289 |
elif HAS_PSYCOPG: |
| 290 |
from psycopg import ProgrammingError as PsycopgProgrammingError |
| 291 |
|
| 292 |
|
| 293 |
# =========================================== |
| 294 |
# Module execution. |
| 295 |
# |
| 296 |
|
| 297 |
|
| 298 |
def execute_and_return_time(cursor, query, args): |
| 299 |
# Measure query execution time in milliseconds as requested in |
| 300 |
# https://github.com/ansible-collections/community.postgresql/issues/787 |
| 301 |
start_time = time.perf_counter() |
| 302 |
|
| 303 |
cursor.execute(query, args) |
| 304 |
|
| 305 |
# Calculate the execution time rounding it to 4 decimal places |
| 306 |
exec_time_ms = round((time.perf_counter() - start_time) * 1000, 4) |
| 307 |
return cursor, exec_time_ms |
| 308 |
|
| 309 |
|
| 310 |
def insane_query(string): |
| 311 |
for c in string: |
| 312 |
if c not in (' ', '\n', '', '\t'): |
| 313 |
return False |
| 314 |
|
| 315 |
return True |
| 316 |
|
| 317 |
|
| 318 |
def main(): |
| 319 |
argument_spec = postgres_common_argument_spec() |
| 320 |
argument_spec.update( |
| 321 |
query=dict(type='raw'), |
| 322 |
login_db=dict(type='str', aliases=['db'], deprecated_aliases=[ |
| 323 |
{ |
| 324 |
'name': 'db', |
| 325 |
'version': '5.0.0', |
| 326 |
'collection_name': 'community.postgresql', |
| 327 |
}], |
| 328 |
), |
| 329 |
positional_args=dict(type='list', elements='raw'), |
| 330 |
named_args=dict(type='dict'), |
| 331 |
session_role=dict(type='str'), |
| 332 |
autocommit=dict(type='bool', default=False), |
| 333 |
encoding=dict(type='str'), |
| 334 |
trust_input=dict(type='bool', default=True), |
| 335 |
search_path=dict(type='list', elements='str'), |
| 336 |
) |
| 337 |
|
| 338 |
module = AnsibleModule( |
| 339 |
argument_spec=argument_spec, |
| 340 |
mutually_exclusive=(('positional_args', 'named_args'),), |
| 341 |
supports_check_mode=True, |
| 342 |
) |
| 343 |
|
| 344 |
query = module.params["query"] |
| 345 |
positional_args = module.params["positional_args"] |
| 346 |
named_args = module.params["named_args"] |
| 347 |
autocommit = module.params["autocommit"] |
| 348 |
encoding = module.params["encoding"] |
| 349 |
session_role = module.params["session_role"] |
| 350 |
trust_input = module.params["trust_input"] |
| 351 |
search_path = module.params["search_path"] |
| 352 |
|
| 353 |
if query and not isinstance(query, (str, list)): |
| 354 |
module.fail_json(msg="query argument must be of type string or list") |
| 355 |
|
| 356 |
if not trust_input: |
| 357 |
# Check input for potentially dangerous elements: |
| 358 |
check_input(module, session_role) |
| 359 |
|
| 360 |
if autocommit and module.check_mode: |
| 361 |
module.fail_json(msg="Using autocommit is mutually exclusive with check_mode") |
| 362 |
|
| 363 |
query_list = [] |
| 364 |
|
| 365 |
if isinstance(query, str): |
| 366 |
query_list.append(query) |
| 367 |
else: # if it's a list |
| 368 |
query_list = query |
| 369 |
|
| 370 |
# Ensure psycopg libraries are available before connecting to DB: |
| 371 |
ensure_required_libs(module) |
| 372 |
conn_params = get_conn_params(module, module.params) |
| 373 |
if encoding is not None: |
| 374 |
conn_params["client_encoding"] = encoding |
| 375 |
db_connection, dummy = connect_to_db(module, conn_params, autocommit=autocommit) |
| 376 |
cursor = db_connection.cursor(**pg_cursor_args) |
| 377 |
|
| 378 |
if search_path: |
| 379 |
set_search_path(cursor, '%s' % ','.join([x.strip(' ') for x in search_path])) |
| 380 |
|
| 381 |
# Prepare args: |
| 382 |
if positional_args: |
| 383 |
args = positional_args |
| 384 |
elif named_args: |
| 385 |
args = named_args |
| 386 |
else: |
| 387 |
args = None |
| 388 |
|
| 389 |
# Convert elements of type list to strings |
| 390 |
# representing PG arrays |
| 391 |
if args: |
| 392 |
args = convert_elements_to_pg_arrays(args) |
| 393 |
|
| 394 |
# Set defaults: |
| 395 |
changed = False |
| 396 |
|
| 397 |
query_all_results = [] |
| 398 |
execution_time_ms = [] |
| 399 |
rowcount = 0 |
| 400 |
statusmessage = '' |
| 401 |
|
| 402 |
# Execute query: |
| 403 |
for query in query_list: |
| 404 |
try: |
| 405 |
current_query_txt = cursor.mogrify(query, args) |
| 406 |
|
| 407 |
cursor, exec_time_ms = execute_and_return_time(cursor, query, args) |
| 408 |
|
| 409 |
execution_time_ms.append(exec_time_ms) |
| 410 |
|
| 411 |
statusmessage = cursor.statusmessage |
| 412 |
if cursor.rowcount > 0: |
| 413 |
rowcount += cursor.rowcount |
| 414 |
|
| 415 |
query_result = [] |
| 416 |
try: |
| 417 |
for row in cursor.fetchall(): |
| 418 |
# Ansible engine does not support decimals. |
| 419 |
# An explicit conversion is required on the module's side |
| 420 |
row = dict(row) |
| 421 |
for (key, val) in row.items(): |
| 422 |
if isinstance(val, TYPES_NEED_TO_CONVERT): |
| 423 |
row[key] = convert_to_supported(val) |
| 424 |
|
| 425 |
query_result.append(row) |
| 426 |
|
| 427 |
# Psycopg 3 doesn't fail with 'no results to fetch' |
| 428 |
# This exception will be triggered only in Psycopg 2 |
| 429 |
except PsycopgProgrammingError as e: |
| 430 |
if to_native(e) == 'no results to fetch': |
| 431 |
query_result = {} |
| 432 |
|
| 433 |
except Exception as e: |
| 434 |
module.fail_json(msg="Cannot fetch rows from cursor: %s" % to_native(e)) |
| 435 |
|
| 436 |
if query_result == []: |
| 437 |
query_result = {} |
| 438 |
|
| 439 |
query_all_results.append(query_result) |
| 440 |
|
| 441 |
if 'SELECT' not in statusmessage and 'SHOW' not in statusmessage: |
| 442 |
if re.search(re.compile(r'(UPDATE|INSERT|DELETE)'), statusmessage): |
| 443 |
s = statusmessage.split() |
| 444 |
if len(s) == 3: |
| 445 |
if s[2] != '0': |
| 446 |
changed = True |
| 447 |
|
| 448 |
elif len(s) == 2: |
| 449 |
if s[1] != '0': |
| 450 |
changed = True |
| 451 |
|
| 452 |
else: |
| 453 |
changed = True |
| 454 |
|
| 455 |
else: |
| 456 |
changed = True |
| 457 |
|
| 458 |
except Exception as e: |
| 459 |
if not autocommit: |
| 460 |
db_connection.rollback() |
| 461 |
|
| 462 |
cursor.close() |
| 463 |
db_connection.close() |
| 464 |
module.fail_json(msg="Cannot execute SQL '%s' %s: %s, query list: %s" % (query, args, to_native(e), query_list)) |
| 465 |
|
| 466 |
if module.check_mode: |
| 467 |
db_connection.rollback() |
| 468 |
else: |
| 469 |
if not autocommit: |
| 470 |
db_connection.commit() |
| 471 |
|
| 472 |
kw = dict( |
| 473 |
changed=changed, |
| 474 |
query=current_query_txt, |
| 475 |
query_list=query_list, |
| 476 |
statusmessage=statusmessage, |
| 477 |
query_result=query_result, |
| 478 |
query_all_results=query_all_results, |
| 479 |
rowcount=rowcount, |
| 480 |
execution_time_ms=execution_time_ms, |
| 481 |
) |
| 482 |
|
| 483 |
cursor.close() |
| 484 |
db_connection.close() |
| 485 |
|
| 486 |
module.exit_json(**kw) |
| 487 |
|
| 488 |
|
| 489 |
if __name__ == '__main__': |
| 490 |
main() |