Debian Codegraph @

ansible_collections/community/clickhouse/plugins/module_utils/clickhouse.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Simplified BSD License (see simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
8
9 from __future__ import absolute_import, division, print_function
10
11 __metaclass__ = type
12
13 from ansible.module_utils.basic import missing_required_lib
14 from ansible.module_utils._text import to_native
15
16 Client = None
17 try:
18 from clickhouse_driver import Client
19 from clickhouse_driver import __version__ as driver_version
20 HAS_DB_DRIVER = True
21 except ImportError:
22 HAS_DB_DRIVER = False
23
24 PRIV_ERR_CODE = 497
25
26
27 def client_common_argument_spec():
28 """
29 Return a dictionary with connection options.
30
31 The options are commonly used by many modules.
32 """
33 return dict(
34 login_host=dict(type='str', default='localhost'),
35 login_port=dict(type='int', default=None),
36 login_db=dict(type='str', default=None),
37 login_user=dict(type='str', default=None),
38 login_password=dict(type='str', default=None, no_log=True),
39 client_kwargs=dict(type='dict', default={}),
40 )
41
42
43 def get_main_conn_kwargs(module):
44 """Retrieves main connection arguments values and translates
45 them into corresponding clickhouse_driver.Client() arguments.
46
47 Returns a dictionary of arguments with values to pass to Client().
48 """
49 main_conn_kwargs = {}
50 main_conn_kwargs['host'] = module.params['login_host'] # Has a default value
51 if module.params['login_port']:
52 main_conn_kwargs['port'] = module.params['login_port']
53 if module.params['login_db']:
54 main_conn_kwargs['database'] = module.params['login_db']
55 if module.params['login_user']:
56 main_conn_kwargs['user'] = module.params['login_user']
57 if module.params['login_password']:
58 main_conn_kwargs['password'] = module.params['login_password']
59 return main_conn_kwargs
60
61
62 def check_clickhouse_driver(module):
63 """Checks if the driver is present.
64
65 Informs user if no driver and fails.
66 """
67 if not HAS_DB_DRIVER:
68 module.fail_json(msg=missing_required_lib('clickhouse_driver'))
69
70
71 def version_clickhouse_driver():
72 """
73 Returns the current version of clickhouse_driver.
74 """
75 return driver_version
76
77
78 def connect_to_db_via_client(module, main_conn_kwargs, client_kwargs):
79 """Connects to DB using the Client() class.
80
81 Returns Client() object.
82 """
83 try:
84 # Merge the kwargs as Python 2 would throw an error
85 # when unpacking them separately to Client()
86 client_kwargs.update(main_conn_kwargs)
87 client = Client(**client_kwargs)
88 except Exception as e:
89 module.fail_json(msg="Failed to connect to database: %s" % to_native(e))
90
91 return client
92
93
94 def execute_query(module, client, query, execute_kwargs=None, set_settings=None):
95 """Execute query.
96
97 Returns rows returned in response.
98
99 set_settings - The list of settings that need to be set before executing the request.
100 """
101 # Some modules do not pass this argument
102 if execute_kwargs is None:
103 execute_kwargs = {}
104
105 if set_settings is None:
106 set_settings = {}
107
108 try:
109 if len(set_settings) != 0:
110 for setting in set_settings:
111 client.execute("SET %s = '%s'" % (setting, set_settings[setting]))
112 result = client.execute(query, **execute_kwargs)
113 except Exception as e:
114 if "Not enough privileges" in to_native(e):
115 return PRIV_ERR_CODE
116 module.fail_json(msg="Failed to execute query: %s" % to_native(e))
117
118 return result
119
120
121 def get_server_version(module, client):
122 """Get server version.
123
124 Returns a dictionary with server version.
125 """
126 result = execute_query(module, client, "SELECT version()")
127
128 if result == PRIV_ERR_CODE:
129 return {PRIV_ERR_CODE: "Not enough privileges"}
130
131 raw = result[0][0]
132 split_raw = raw.split('.')
133
134 version = {}
135 version["raw"] = raw
136
137 version["year"] = int(split_raw[0])
138 version["feature"] = int(split_raw[1])
139 version["maintenance"] = int(split_raw[2])
140
141 if '-' in split_raw[3]:
142 tmp = split_raw[3].split('-')
143 version["build"] = int(tmp[0])
144 version["type"] = tmp[1]
145 else:
146 version["build"] = int(split_raw[3])
147 version["type"] = None
148
149 return version