Debian Codegraph @

ansible_collections/community/clickhouse/plugins/modules/clickhouse_client.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2024, 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 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: clickhouse_client
13
14 short_description: Execute queries in a ClickHouse database using the clickhouse-driver Client interface
15
16 description:
17 - Execute arbitrary queries in a ClickHouse database using the
18 L(clickhouse-driver,https://clickhouse-driver.readthedocs.io/en/latest) Client interface.
19 - Always returns that the state changed.
20
21 version_added: '0.1.0'
22
23 author:
24 - Andrew Klychkov (@Andersson007)
25 - Aleks Vagachev (@aleksvagachev)
26
27 extends_documentation_fragment:
28 - community.clickhouse.client_inst_opts
29
30 notes:
31 - Does not support C(check_mode).
32
33 options:
34 execute:
35 description:
36 - A query to the V(Client.execute(\)) method.
37 type: str
38 required: true
39
40 execute_kwargs:
41 description:
42 - All additional keyword arguments you want to pass to
43 the V(Client.execute(\)) method. For example, you can pass
44 substitution parameters for the query you pass
45 through the I(execute) argument.
46 type: dict
47 default: {}
48
49 set_settings:
50 description:
51 - The dict of settings that need to be set in the session before executing the request.
52 type: dict
53 default: {}
54 version_added: '0.5.0'
55 '''
56
57 EXAMPLES = r'''
58 - name: Query DB using non-default user & DB to connect to
59 register: result
60 community.clickhouse.clickhouse_client:
61 execute: SELECT * FROM my_table
62 login_host: localhost
63 login_user: alice
64 login_db: foo
65 login_password: my_password
66
67 - name: Print returned rows
68 ansible.builtin.debug:
69 var: result.result
70
71 - name: Create table
72 register: result
73 community.clickhouse.clickhouse_client:
74 execute: CREATE TABLE test_table_1 (x String) ENGINE = Memory
75 set_settings:
76 flatten_nested: 0
77 short_circuit_function_evaluation: 'disable'
78
79 - name: Insert into test table using named parameters
80 register: result
81 community.clickhouse.clickhouse_client:
82 execute: "INSERT INTO test_table_1 (x) VALUES (%(a)s), (%(b)s), (%(c)s)"
83 execute_kwargs:
84 params:
85 a: one
86 b: two
87 c: three
88
89 - name: Check the result
90 ansible.builtin.assert:
91 that:
92 - result.substituted_query == "INSERT INTO test_table_1 (x) VALUES ('one'), ('two'), ('three')"
93 - result.statistics["processed_rows"] == 3
94
95 - name: Check rows were inserted into test table
96 register: result
97 community.clickhouse.clickhouse_client:
98 execute: "SELECT * FROM test_table_1"
99
100 - name: Check returned values
101 ansible.builtin.assert:
102 that:
103 - result.result == [["one"], ["two"], ["three"]]
104 '''
105
106 RETURN = r'''
107 substituted_query:
108 description:
109 - Executed query with substituted arguments if any.
110 returned: on success
111 sample: SELECT * FROM test_table_1
112 type: str
113 result:
114 description:
115 - Result returned by Client.execute().
116 returned: on success
117 type: list
118 sample: [["one"], ["two"], ["three"]]
119 statistics:
120 description:
121 - Last executed query statistics retrieved from the
122 L(last_query,https://clickhouse-driver.readthedocs.io/en/latest/features.html#query-execution-statistics)
123 attribute.
124 - Returned items depend on server version.
125 returned: on success
126 type: dict
127 '''
128 from decimal import Decimal
129
130 HAS_IPADDRESS = False
131 try:
132 from ipaddress import IPv4Address, IPv6Address
133 HAS_IPADDRESS = True
134 except ImportError:
135 pass
136
137 from uuid import UUID
138
139 from ansible.module_utils.basic import AnsibleModule
140 from ansible.module_utils._text import to_native
141
142 from ansible_collections.community.clickhouse.plugins.module_utils.clickhouse import (
143 check_clickhouse_driver,
144 client_common_argument_spec,
145 get_main_conn_kwargs,
146 connect_to_db_via_client,
147 execute_query,
148 )
149
150
151 def is_uuid(value):
152 """Checks if the value is valid UUID.
153
154 Returns True if yes, False otherwise.
155 """
156 try:
157 UUID(str(value))
158 return True
159 except ValueError:
160 return False
161
162
163 def vals_to_supported(result):
164 """Converts values of types unsupported by Ansible Core
165 to supported.
166
167 Ansible Core has a limited set of supported values.
168 This is intentional, and the docs says such values
169 have to be converted on the module's side.
170
171 Add more values here if needed.
172 """
173 for idx_row, row in enumerate(result):
174 for idx_val, val in enumerate(row):
175 if is_uuid(val):
176 # As tuple does not support change,
177 # we need some conversion here
178 row = replace_val_in_tuple(row, idx_val, str(val))
179 result[idx_row] = row
180
181 elif isinstance(val, Decimal):
182 row = replace_val_in_tuple(row, idx_val, float(val))
183 result[idx_row] = row
184
185 elif isinstance(val, IPv4Address) or isinstance(val, IPv6Address):
186 row = replace_val_in_tuple(row, idx_val, str(val))
187 result[idx_row] = row
188
189 return result
190
191
192 def replace_val_in_tuple(tup, idx, val):
193 """Creates another tuple from a tuple substituting a value.
194
195 Returns a new tuple.
196 """
197 tmp = list(tup)
198 tmp[idx] = val
199 return tuple(tmp)
200
201
202 def get_query_statistics(module, client):
203 """Retrieve query statistics from the Client() object.
204
205 Returns a dictionary with statistics.
206 """
207 statistics = {}
208 try:
209 # IMPORTANT: When adding new values, use hassattr() to check
210 # if supported as below! This is important for compatibility reasons.
211 if hasattr(client.last_query, 'elapsed'):
212 statistics['elapsed'] = client.last_query.elapsed
213
214 if not hasattr(client.last_query, 'progress'):
215 return statistics
216
217 if hasattr(client.last_query.progress, 'rows'):
218 statistics['processed_rows'] = client.last_query.progress.rows
219
220 if hasattr(client.last_query.progress, 'bytes'):
221 statistics['processed_bytes'] = client.last_query.progress.bytes
222
223 if hasattr(client.last_query.progress, 'total_rows'):
224 statistics['total_rows'] = client.last_query.progress.total_rows
225
226 if hasattr(client.last_query.progress, 'written_rows'):
227 # As supported since driver version 0.1.3
228 statistics['written_rows'] = client.last_query.progress.written_rows
229
230 if hasattr(client.last_query.progress, 'written_bytes'):
231 # As supported since driver version 0.1.3
232 statistics['written_bytes'] = client.last_query.progress.written_bytes
233
234 if hasattr(client.last_query.progress, 'elapsed_ns'):
235 # As supported since driver version 0.2.7
236 statistics['elapsed_ns'] = client.last_query.progress.elapsed_ns
237
238 except Exception as e:
239 module.fail_json(msg="Failed to retrieve statistics: %s" % to_native(e))
240
241 return statistics
242
243
244 def get_substituted_query(module, client, query, execute_kwargs):
245 """Substitute params in a query. If no params, just return the query as is.
246
247 Returns a query with substituted params.
248 """
249 substituted_query = None
250 if execute_kwargs.get("params"):
251 try:
252 substituted_query = client.substitute_params(query, execute_kwargs["params"],
253 context=client.connection.context)
254 except Exception as e:
255 module.fail_json(msg="Failed to substitute query params: %s" % to_native(e))
256 else:
257 # If no params were passed, no need to substitute.
258 # Return query as is.
259 substituted_query = query
260
261 return substituted_query
262
263
264 def main():
265 # Set up arguments.
266 # If there are common arguments shared across several modules,
267 # create the common_argument_spec() function under plugins/module_utils/*
268 # and invoke here to return a dict with those arguments
269 argument_spec = client_common_argument_spec()
270 argument_spec.update(
271 execute=dict(type='str', required=True),
272 execute_kwargs=dict(type='dict', default={}),
273 set_settings=dict(type='dict', default={})
274 )
275
276 # Instantiate an object of module class
277 module = AnsibleModule(
278 argument_spec=argument_spec,
279 supports_check_mode=False,
280 )
281
282 # Assign passed options to variables
283 client_kwargs = module.params['client_kwargs']
284 query = module.params['execute']
285 execute_kwargs = module.params['execute_kwargs']
286 set_settings = module.params['set_settings']
287 # The reason why these arguments are separate from client_kwargs
288 # is that we need to protect some sensitive data like passwords passed
289 # to the module from logging (see the arguments above with no_log=True);
290 # Such data must be passed as module arguments (not nested deep in values).
291 main_conn_kwargs = get_main_conn_kwargs(module)
292
293 # Will fail if no driver informing the user
294 check_clickhouse_driver(module)
295
296 # There's no ipaddress package in Python 2
297 if not HAS_IPADDRESS:
298 msg = ("If you use Python 2 on your target host, "
299 "make sure you have the py2-ipaddress Python package installed there to avoid "
300 "crashes while querying tables containing columns of IPv4|6Address types.")
301 module.warn(msg)
302
303 # Connect to DB
304 client = connect_to_db_via_client(module, main_conn_kwargs, client_kwargs)
305
306 # Substitute query params if needed for future return
307 substituted_query = get_substituted_query(module, client, query, execute_kwargs)
308
309 # Execute query
310 result = execute_query(module, client, query, execute_kwargs, set_settings)
311
312 # Convert values not supported by ansible-core
313 if result and isinstance(result, (list, tuple)):
314 result = vals_to_supported(result)
315
316 # Retreive statistics if present
317 statistics = get_query_statistics(module, client)
318
319 # Andersson007 doesn't see any way of checking if anything in DB was changed
320 # or not by the query using the Client() interface
321 # (considering all kinds of queries like DML, DDL, etc.)
322 # It is safer and easier to always return changed=True.
323 # Before changing this, think many times if you want to make
324 # the code more complex and to support this complexity
325 changed = True
326
327 # Close connection
328 client.disconnect_connection()
329
330 # Users will get this in JSON output after execution
331 kw = dict(
332 changed=changed,
333 result=result,
334 substituted_query=substituted_query,
335 statistics=statistics,
336 )
337
338 module.exit_json(**kw)
339
340
341 if __name__ == '__main__':
342 main()