Debian Codegraph @

ansible_collections/community/general/plugins/modules/mssql_script.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2021, Kris Budde <[email protected]
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: mssql_script
11
12 short_description: Execute SQL scripts on a MSSQL database
13
14 version_added: "4.0.0"
15
16 description:
17 - Execute SQL scripts on a MSSQL database.
18 extends_documentation_fragment:
19 - community.general._attributes
20
21 attributes:
22 check_mode:
23 support: partial
24 details:
25 - The script is not be executed in check mode.
26 diff_mode:
27 support: none
28
29 options:
30 name:
31 description: Database to run script against.
32 aliases: [db]
33 default: ''
34 type: str
35 login_user:
36 description: The username used to authenticate with.
37 type: str
38 login_password:
39 description: The password used to authenticate with.
40 type: str
41 login_host:
42 description:
43 - Host running the database.
44 - For named instances, use the format V(server\\instance). In that case, do not use O(login_port).
45 type: str
46 required: true
47 login_port:
48 description:
49 - Port of the MSSQL server. Requires O(login_host) to be defined as well.
50 - Cannot be used together with a named instance in O(login_host) (that is, V(server\\instance) format).
51 - If O(login_host) is not a named instance and O(login_port) is not specified, it defaults to V(1433).
52 type: int
53 script:
54 description:
55 - The SQL script to be executed.
56 - Script can contain multiple SQL statements. Multiple Batches can be separated by V(GO) command.
57 - Each batch must return at least one result set.
58 required: true
59 type: str
60 transaction:
61 description:
62 - If transactional mode is requested, start a transaction and commit the change only if the script succeed. Otherwise,
63 rollback the transaction.
64 - If transactional mode is not requested (default), automatically commit the change.
65 type: bool
66 default: false
67 version_added: 8.4.0
68 output:
69 description:
70 - With V(default) each row is returned as a list of values. See RV(query_results).
71 - Output format V(dict) returns dictionary with the column names as keys. See RV(query_results_dict).
72 - V(dict) requires named columns to be returned by each query otherwise an error is thrown.
73 choices: ["dict", "default"]
74 default: 'default'
75 type: str
76 params:
77 description: |-
78 Parameters passed to the script as SQL parameters.
79 (Query V('SELECT %(name\)s"') with V(example: '{"name": "John Doe"}).)'.
80 type: dict
81 notes:
82 - Requires the pymssql Python package on the remote host. For Ubuntu, this is as easy as C(pip install pymssql) (See M(ansible.builtin.pip)).
83 requirements:
84 - pymssql
85
86 author:
87 - Kris Budde (@kbudde)
88 """
89
90 EXAMPLES = r"""
91 - name: Check DB connection
92 community.general.mssql_script:
93 login_user: "{{ mssql_login_user }}"
94 login_password: "{{ mssql_login_password }}"
95 login_host: "{{ mssql_host }}"
96 login_port: "{{ mssql_port }}"
97 db: master
98 script: "SELECT 1"
99
100 - name: Query with parameter
101 community.general.mssql_script:
102 login_user: "{{ mssql_login_user }}"
103 login_password: "{{ mssql_login_password }}"
104 login_host: "{{ mssql_host }}"
105 login_port: "{{ mssql_port }}"
106 script: |
107 SELECT name, state_desc FROM sys.databases WHERE name = %(dbname)s
108 params:
109 dbname: msdb
110 register: result_params
111 - assert:
112 that:
113 - result_params.query_results[0][0][0][0] == 'msdb'
114 - result_params.query_results[0][0][0][1] == 'ONLINE'
115
116 - name: Query within a transaction
117 community.general.mssql_script:
118 login_user: "{{ mssql_login_user }}"
119 login_password: "{{ mssql_login_password }}"
120 login_host: "{{ mssql_host }}"
121 login_port: "{{ mssql_port }}"
122 script: |
123 UPDATE sys.SomeTable SET desc = 'some_table_desc' WHERE name = %(dbname)s
124 UPDATE sys.AnotherTable SET desc = 'another_table_desc' WHERE name = %(dbname)s
125 transaction: true
126 params:
127 dbname: msdb
128
129 - name: two batches with default output
130 community.general.mssql_script:
131 login_user: "{{ mssql_login_user }}"
132 login_password: "{{ mssql_login_password }}"
133 login_host: "{{ mssql_host }}"
134 login_port: "{{ mssql_port }}"
135 script: |
136 SELECT 'Batch 0 - Select 0'
137 SELECT 'Batch 0 - Select 1'
138 GO
139 SELECT 'Batch 1 - Select 0'
140 register: result_batches
141 - assert:
142 that:
143 - result_batches.query_results | length == 2 # two batch results
144 - result_batches.query_results[0] | length == 2 # two selects in first batch
145 - result_batches.query_results[0][0] | length == 1 # one row in first select
146 - result_batches.query_results[0][0][0] | length == 1 # one column in first row
147 - result_batches.query_results[0][0][0][0] == 'Batch 0 - Select 0' # each row contains a list of values.
148
149 - name: two batches with dict output
150 community.general.mssql_script:
151 login_user: "{{ mssql_login_user }}"
152 login_password: "{{ mssql_login_password }}"
153 login_host: "{{ mssql_host }}"
154 login_port: "{{ mssql_port }}"
155 output: dict
156 script: |
157 SELECT 'Batch 0 - Select 0' as b0s0
158 SELECT 'Batch 0 - Select 1' as b0s1
159 GO
160 SELECT 'Batch 1 - Select 0' as b1s0
161 register: result_batches_dict
162 - assert:
163 that:
164 - result_batches_dict.query_results_dict | length == 2 # two batch results
165 - result_batches_dict.query_results_dict[0] | length == 2 # two selects in first batch
166 - result_batches_dict.query_results_dict[0][0] | length == 1 # one row in first select
167 - result_batches_dict.query_results_dict[0][0][0]['b0s0'] == 'Batch 0 - Select 0' # column 'b0s0' of first row
168 """
169
170 RETURN = r"""
171 query_results:
172 description: List of batches (queries separated by V(GO) keyword).
173 type: list
174 elements: list
175 returned: success and O(output=default)
176 sample:
177 [
178 [
179 [
180 [
181 "Batch 0 - Select 0"
182 ]
183 ],
184 [
185 [
186 "Batch 0 - Select 1"
187 ]
188 ]
189 ],
190 [
191 [
192 [
193 "Batch 1 - Select 0"
194 ]
195 ]
196 ]
197 ]
198 contains:
199 queries:
200 description:
201 - List of result sets of each query.
202 - If a query returns no results, the results of this and all the following queries are not included in the output.
203 - Use the V(GO) keyword in O(script) to separate queries.
204 type: list
205 elements: list
206 contains:
207 rows:
208 description: List of rows returned by query.
209 type: list
210 elements: list
211 contains:
212 column_value:
213 description:
214 - List of column values.
215 - Any non-standard JSON type is converted to string.
216 type: list
217 example: ["Batch 0 - Select 0"]
218 returned: success, if output is default
219 query_results_dict:
220 description: List of batches (queries separated by V(GO) keyword).
221 type: list
222 elements: list
223 returned: success and O(output=dict)
224 sample:
225 [
226 [
227 [
228 [
229 "Batch 0 - Select 0"
230 ]
231 ],
232 [
233 [
234 "Batch 0 - Select 1"
235 ]
236 ]
237 ],
238 [
239 [
240 [
241 "Batch 1 - Select 0"
242 ]
243 ]
244 ]
245 ]
246 contains:
247 queries:
248 description:
249 - List of result sets of each query.
250 - If a query returns no results, the results of this and all the following queries are not included in the output.
251 Use V(GO) keyword to separate queries.
252 type: list
253 elements: list
254 contains:
255 rows:
256 description: List of rows returned by query.
257 type: list
258 elements: list
259 contains:
260 column_dict:
261 description:
262 - Dictionary of column names and values.
263 - Any non-standard JSON type is converted to string.
264 type: dict
265 example: {"col_name": "Batch 0 - Select 0"}
266 returned: success, if output is dict
267 """
268
269 import json
270 import traceback
271
272 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
273
274 PYMSSQL_IMP_ERR = None
275 try:
276 import pymssql
277 except ImportError:
278 PYMSSQL_IMP_ERR = traceback.format_exc()
279 MSSQL_FOUND = False
280 else:
281 MSSQL_FOUND = True
282
283
284 def clean_output(o):
285 return str(o)
286
287
288 def run_module():
289 module_args = dict(
290 name=dict(aliases=["db"], default=""),
291 login_user=dict(),
292 login_password=dict(no_log=True),
293 login_host=dict(required=True),
294 login_port=dict(type="int"),
295 script=dict(required=True),
296 output=dict(default="default", choices=["dict", "default"]),
297 params=dict(type="dict"),
298 transaction=dict(type="bool", default=False),
299 )
300
301 result = dict(
302 changed=False,
303 )
304
305 module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
306 if not MSSQL_FOUND:
307 module.fail_json(msg=missing_required_lib("pymssql"), exception=PYMSSQL_IMP_ERR)
308
309 db = module.params["name"]
310 login_user = module.params["login_user"]
311 login_password = module.params["login_password"]
312 login_host = module.params["login_host"]
313 login_port = module.params["login_port"]
314 script = module.params["script"]
315 output = module.params["output"]
316 sql_params = module.params["params"]
317 # Added param to set the transactional mode (true/false)
318 transaction = module.params["transaction"]
319
320 if "\\" in login_host and login_port is not None:
321 module.fail_json(
322 msg=r"login_port cannot be used with a named instance in login_host (server\instance format). "
323 "Named instances use the SQL Server Browser service to resolve the port automatically."
324 )
325
326 login_querystring = login_host
327 if "\\" not in login_host and login_port is not None:
328 login_querystring = f"{login_host}:{login_port}"
329
330 if login_user is not None and login_password is None:
331 module.fail_json(msg="when supplying login_user argument, login_password must also be provided")
332
333 try:
334 conn = pymssql.connect(user=login_user, password=login_password, host=login_querystring, database=db)
335 cursor = conn.cursor()
336 except Exception as e:
337 if "Unknown database" in str(e):
338 errno, errstr = e.args
339 module.fail_json(msg=f"ERROR: {errno} {errstr}")
340 else:
341 module.fail_json(
342 msg="unable to connect, check login_user and login_password are correct, or alternatively check your "
343 "@sysconfdir@/freetds.conf / ${HOME}/.freetds.conf"
344 )
345
346 # If transactional mode is requested, start a transaction
347 conn.autocommit(not transaction)
348
349 query_results_key = "query_results"
350 if output == "dict":
351 cursor = conn.cursor(as_dict=True)
352 query_results_key = "query_results_dict"
353
354 # Process the script into batches
355 queries = []
356 current_batch = []
357 for statement in script.splitlines(True):
358 # Ignore the Byte Order Mark, if found
359 if statement.strip() == "\ufeff":
360 continue
361
362 # Assume each 'GO' is on its own line but may have leading/trailing whitespace
363 # and be of mixed-case
364 if statement.strip().upper() != "GO":
365 current_batch.append(statement)
366 else:
367 queries.append("".join(current_batch))
368 current_batch = []
369 if len(current_batch) > 0:
370 queries.append("".join(current_batch))
371
372 result["changed"] = True
373 if module.check_mode:
374 module.exit_json(**result)
375
376 query_results = []
377 for query in queries:
378 # Catch and exit on any bad query errors
379 try:
380 if sql_params:
381 cursor.execute(query, sql_params)
382 else:
383 cursor.execute(query)
384 qry_result = []
385 rows = cursor.fetchall()
386 while rows:
387 qry_result.append(rows)
388 rows = cursor.fetchall()
389 query_results.append(qry_result)
390 except Exception as e:
391 # We know we executed the statement so this error just means we have no resultset
392 # which is ok (eg UPDATE/INSERT)
393 if (
394 type(e).__name__ == "OperationalError"
395 and str(e) == "Statement not executed or executed statement has no resultset"
396 ):
397 query_results.append([])
398 else:
399 # Rollback transaction before failing the module in case of error
400 if transaction:
401 conn.rollback()
402 error_msg = f"{type(e).__name__}: {e}"
403 module.fail_json(msg="query failed", query=query, error=error_msg, **result)
404
405 # Commit transaction before exiting the module in case of no error
406 if transaction:
407 conn.commit()
408
409 # ensure that the result is json serializable
410 qry_results = json.loads(json.dumps(query_results, default=clean_output))
411
412 result[query_results_key] = qry_results
413 module.exit_json(**result)
414
415
416 def main():
417 run_module()
418
419
420 if __name__ == "__main__":
421 main()