Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2022, 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_script
14
15 short_description: Run PostgreSQL statements from a file
16
17 description:
18 - Runs arbitrary PostgreSQL statements from a file.
19 - The module always reports that the state has changed.
20 - Do NOT run the module against files generated by C(pg_dump),
21 C(pg_dumpall), C(pg_restore) and other PostgreSQL utilities.
22 - Use M(community.postgresql.postgresql_db) with I(state=restore)
23 to run queries from files generated by C(pg_dump/pg_dumpall).
24
25 version_added: '2.1.0'
26
27 options:
28 positional_args:
29 description:
30 - List of values to substitute variable placeholders within the file content.
31 - When the value is a list, it will be converted to PostgreSQL array.
32 - Mutually exclusive with I(named_args).
33 type: list
34 elements: raw
35 named_args:
36 description:
37 - Dictionary of key-value arguments to substitute
38 variable placeholders within the file content.
39 - When the value is a list, it will be converted to PostgreSQL array.
40 - Mutually exclusive with I(positional_args).
41 type: dict
42 path:
43 description:
44 - Path to a SQL script on the target machine.
45 - To upload dumps, the preferable way
46 is to use the M(community.postgresql.postgresql_db) module with I(state=restore).
47 type: path
48 session_role:
49 description:
50 - Switch to C(session_role) after connecting. The specified role must
51 be a role that the current C(login_user) is a member of.
52 - Permissions checking for SQL commands is carried out as though
53 the C(session_role) were the one that had logged in originally.
54 type: str
55 login_db:
56 description:
57 - Name of database to connect to and run queries against.
58 - The V(db) alias is deprecated and will be removed in version 5.0.0.
59 type: str
60 aliases:
61 - db
62 encoding:
63 description:
64 - Set the client encoding for the current session (e.g. C(UTF-8)).
65 - The default is the encoding defined by the database.
66 type: str
67 trust_input:
68 description:
69 - If C(false), check whether a value of I(session_role) is potentially dangerous.
70 - It makes sense to use C(false) only when SQL injections
71 via I(session_role) are possible.
72 type: bool
73 default: true
74 search_path:
75 description:
76 - Overrides the list of schemas to search for db objects in.
77 type: list
78 elements: str
79
80 seealso:
81 - module: community.postgresql.postgresql_db
82 - module: community.postgresql.postgresql_query
83 - name: PostgreSQL Schema reference
84 description: Complete reference of the PostgreSQL schema documentation.
85 link: https://www.postgresql.org/docs/current/ddl-schemas.html
86
87 attributes:
88 check_mode:
89 support: none
90
91 author:
92 - Douglas J Hunley (@hunleyd)
93 - A. Hart (@jtelcontar)
94 - Daniel Scharon (@DanScharon)
95 - Andrew Klychkov (@Andersson007)
96
97 extends_documentation_fragment:
98 - community.postgresql.postgres
99 '''
100
101 EXAMPLES = r'''
102 # Assuming that the file contains
103 # SELECT * FROM id_talbe WHERE id = %s,
104 # '%s' will be substituted with 1
105 - name: Run query from SQL script using UTF-8 client encoding for session and positional args
106 community.postgresql.postgresql_script:
107 login_db: test_db
108 path: /var/lib/pgsql/test.sql
109 positional_args:
110 - 1
111 encoding: UTF-8
112
113 # Assuming that the file contains
114 # SELECT * FROM test WHERE id = %(id_val)s AND story = %(story_val)s,
115 # %-values will be substituted with 1 and 'test'
116 - name: Select query to test_db with named_args
117 community.postgresql.postgresql_script:
118 login_db: test_db
119 path: /var/lib/pgsql/test.sql
120 named_args:
121 id_val: 1
122 story_val: test
123
124 - block:
125 # Assuming that the the file contains
126 # SELECT * FROM test_array_table WHERE arr_col1 = %s AND arr_col2 = %s
127 # Pass list and string vars as positional_args
128 - name: Set vars
129 ansible.builtin.set_fact:
130 my_list:
131 - 1
132 - 2
133 - 3
134 my_arr: '{1, 2, 3}'
135 - name: Passing positional_args as arrays
136 community.postgresql.postgresql_script:
137 path: /var/lib/pgsql/test.sql
138 positional_args:
139 - '{{ my_list }}'
140 - '{{ my_arr|string }}'
141
142 # Assuming that the the file contains
143 # SELECT * FROM test_table,
144 # look into app1 schema first, then,
145 # if the schema doesn't exist or the table hasn't been found there,
146 # try to find it in the schema public
147 - name: Select from test using search_path
148 community.postgresql.postgresql_script:
149 path: /var/lib/pgsql/test.sql
150 search_path:
151 - app1
152 - public
153
154 - block:
155 # If you use a variable in positional_args/named_args that can
156 # be undefined and you wish to set it as NULL, constructions like
157 # "{{ my_var if (my_var is defined) else none | default(none) }}"
158 # will not work as expected substituting an empty string instead of NULL.
159 # If possible, we suggest using Ansible's DEFAULT_JINJA2_NATIVE configuration
160 # (https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-jinja2-native).
161 # Enabling it fixes this problem. If you cannot enable it, the following workaround
162 # can be used.
163 # You should precheck such a value and define it as NULL when undefined.
164 # For example:
165 - name: When undefined, set to NULL
166 set_fact:
167 my_var: NULL
168 when: my_var is undefined
169
170 # Then, assuming that the file contains
171 # INSERT INTO test_table (col1) VALUES (%s)
172 - name: Insert a value using positional arguments
173 community.postgresql.postgresql_script:
174 path: /var/lib/pgsql/test.sql
175 positional_args:
176 - '{{ my_var }}'
177 '''
178
179 RETURN = r'''
180 query:
181 description:
182 - Executed query.
183 - When the C(positional_args) or C(named_args) options are used,
184 the query contains all variables that were substituted
185 inside the database connector.
186 returned: success
187 type: str
188 sample: 'SELECT * FROM bar'
189 statusmessage:
190 description:
191 - Attribute containing the message returned by the database connector
192 after executing the script content.
193 - When there are several statements in the script, returns a message
194 related to the last statement.
195 returned: success
196 type: str
197 sample: 'INSERT 0 1'
198 query_result:
199 description:
200 - List of dictionaries in the column:value form representing returned rows.
201 - When there are several statements in the script,
202 returns result of the last statement.
203 returned: success
204 type: list
205 elements: dict
206 sample: [{"Column": "Value1"},{"Column": "Value2"}]
207 rowcount:
208 description:
209 - Number of produced or affected rows.
210 - When there are several statements in the script,
211 returns a number of rows affected by the last statement.
212 returned: changed
213 type: int
214 sample: 5
215 '''
216
217 from ansible.module_utils.common.text.converters import to_native
218 from ansible.module_utils.basic import AnsibleModule
219 from ansible_collections.community.postgresql.plugins.module_utils.database import \
220 check_input
221 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
222 HAS_PSYCOPG,
223 PSYCOPG_VERSION,
224 TYPES_NEED_TO_CONVERT,
225 connect_to_db,
226 convert_elements_to_pg_arrays,
227 convert_to_supported,
228 ensure_required_libs,
229 get_conn_params,
230 pg_cursor_args,
231 postgres_common_argument_spec,
232 set_search_path,
233 )
234 from ansible_collections.community.postgresql.plugins.module_utils.version import \
235 LooseVersion
236
237 if HAS_PSYCOPG and PSYCOPG_VERSION < LooseVersion("3.0"):
238 from psycopg2 import ProgrammingError as PsycopgProgrammingError
239 elif HAS_PSYCOPG:
240 from psycopg import ProgrammingError as PsycopgProgrammingError
241
242 # ===========================================
243 # Module execution.
244 #
245
246
247 def main():
248 argument_spec = postgres_common_argument_spec()
249 argument_spec.update(
250 path=dict(type='path'),
251 login_db=dict(type='str', aliases=['db'], deprecated_aliases=[
252 {
253 'name': 'db',
254 'version': '5.0.0',
255 'collection_name': 'community.postgresql',
256 }],
257 ),
258 positional_args=dict(type='list', elements='raw'),
259 named_args=dict(type='dict'),
260 session_role=dict(type='str'),
261 encoding=dict(type='str'),
262 trust_input=dict(type='bool', default=True),
263 search_path=dict(type='list', elements='str'),
264 )
265
266 module = AnsibleModule(
267 argument_spec=argument_spec,
268 mutually_exclusive=(('positional_args', 'named_args'),),
269 supports_check_mode=False,
270 )
271
272 path = module.params["path"]
273 positional_args = module.params["positional_args"]
274 named_args = module.params["named_args"]
275 encoding = module.params["encoding"]
276 session_role = module.params["session_role"]
277 trust_input = module.params["trust_input"]
278 search_path = module.params["search_path"]
279
280 if not trust_input:
281 # Check input for potentially dangerous elements:
282 check_input(module, session_role)
283
284 try:
285 with open(path, 'rb') as f:
286 script_content = to_native(f.read())
287
288 except Exception as e:
289 module.fail_json(msg="Cannot read file '%s' : %s" % (path, to_native(e)))
290
291 # Ensure psycopg libraries are available before connecting to DB:
292 ensure_required_libs(module)
293 conn_params = get_conn_params(module, module.params)
294 if encoding is not None:
295 conn_params["client_encoding"] = encoding
296 db_connection, dummy = connect_to_db(module, conn_params, autocommit=True)
297 cursor = db_connection.cursor(**pg_cursor_args)
298
299 if search_path:
300 set_search_path(cursor, '%s' % ','.join([x.strip(' ') for x in search_path]))
301
302 # Prepare args:
303 if positional_args:
304 args = positional_args
305 elif named_args:
306 args = named_args
307 else:
308 args = None
309
310 # Convert elements of type list to strings
311 # representing PG arrays
312 if args:
313 args = convert_elements_to_pg_arrays(args)
314
315 # Execute script content:
316 try:
317 current_query_txt = cursor.mogrify(script_content, args)
318 cursor.execute(script_content, args)
319 except Exception as e:
320 cursor.close()
321 db_connection.close()
322 module.fail_json(msg="Cannot execute SQL '%s' %s: %s" % (script_content, args, to_native(e)))
323
324 statusmessage = cursor.statusmessage
325
326 rowcount = cursor.rowcount
327
328 # In Psycopg 2, only the result of the last statement is returned.
329 # In Psycopg 3, all the results are available.
330 # https://www.psycopg.org/psycopg3/docs/basic/from_pg2.html#multiple-results-returned-from-multiple-statements
331 query_result = []
332 try:
333 result_set = cursor.fetchall()
334 if PSYCOPG_VERSION >= LooseVersion("3.0"):
335 while cursor.nextset() is not None:
336 result_set = cursor.fetchall()
337 for row in result_set:
338 # Ansible engine does not support decimals.
339 # An explicit conversion is required on the module's side
340 row = dict(row)
341 for (key, val) in row.items():
342 if isinstance(val, TYPES_NEED_TO_CONVERT):
343 row[key] = convert_to_supported(val)
344
345 query_result.append(row)
346
347 # Psycopg 3 doesn't fail with 'no results to fetch'
348 # This exception will be triggered only in Psycopg 2
349 except PsycopgProgrammingError as e:
350 if to_native(e) == "no results to fetch":
351 query_result = {}
352
353 except Exception as e:
354 module.fail_json(msg="Cannot fetch rows from cursor: %s" % to_native(e))
355
356 if query_result == []:
357 query_result = {}
358
359 kw = dict(
360 changed=True,
361 query=current_query_txt,
362 statusmessage=statusmessage,
363 query_result=query_result,
364 rowcount=rowcount,
365 )
366
367 cursor.close()
368 db_connection.close()
369
370 module.exit_json(**kw)
371
372
373 if __name__ == '__main__':
374 main()