Skip to content

Commit

Permalink
community_client: Add handling of types not supported by ansible-core
Browse files Browse the repository at this point in the history
  • Loading branch information
Andersson007 committed Feb 12, 2024
1 parent 13047b3 commit e1995d3
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
52 changes: 52 additions & 0 deletions plugins/modules/clickhouse_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@
returned: on success
type: dict
'''
from datetime import timedelta
from decimal import Decimal
from uuid import UUID

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
Expand All @@ -131,6 +134,51 @@
HAS_DB_DRIVER = False


def is_uuid(value):
"""Checks if the value is valid UUID.
Returns True if yes, False otherwise.
"""
try:
UUID(str(value))
return True
except ValueError:
return False


def vals_to_supported(result):
"""Converts values of types unsupported by Ansible Core
to supported.
Ansible Core has a limited set of supported values.
This is intentional, and the docs says such values
have to be converted on the module's side.
Add more values here if needed.
"""
for idx_row, row in enumerate(result):
for idx_val, val in enumerate(row):
if is_uuid(val) or isinstance(val, timedelta):
# As tuple does not support change,
# we need some conversion here
result[idx_row] = replace_val_in_tuple(row, idx_val, str(val))

elif isinstance(val, Decimal):
result[idx_row] = replace_val_in_tuple(row, idx_val, float(val))

return result


def replace_val_in_tuple(tup, idx, val):
"""Creates another tuple from a tuple substituting a value.
Returns a new tuple.
"""
tmp = list(tup)
tmp[idx] = val
return tuple(tmp)


def get_main_conn_kwargs(module):
"""Retrieves main connection arguments values and translates
them into corresponding clickhouse_driver.Client() arguments.
Expand Down Expand Up @@ -269,6 +317,10 @@ def main():
# Execute query
result = execute_query(module, client, query, execute_kwargs)

# Convert values not supported by ansible-core
if result:
result = vals_to_supported(result)

# Retreive statistics
statistics = get_query_statistics(module, client)

Expand Down
11 changes: 11 additions & 0 deletions tests/integration/targets/clickhouse_client/tasks/initial.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,14 @@
ansible.builtin.assert:
that:
- result.result == [["one"], ["two"], ["three"]]


- name: The system.users table contain UUID value
register: result
community.clickhouse.clickhouse_client:
execute: SELECT id FROM system.users LIMIT 1

- name: Print the result
ansible.builtin.assert:
that:
- result.result[0] != []

0 comments on commit e1995d3

Please sign in to comment.