common.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import sys
  2. from dataclasses import dataclass
  3. from typing import Any, Sequence, Optional, Dict
  4. from clickhouse_connect import __version__
  5. from clickhouse_connect.driver.exceptions import ProgrammingError
  6. def version():
  7. return __version__.version
  8. def format_error(msg: str) -> str:
  9. max_size = _common_settings['max_error_size'].value
  10. if max_size:
  11. return msg[:max_size]
  12. return msg
  13. @dataclass
  14. class CommonSetting:
  15. name: str
  16. options: Sequence[Any]
  17. default: Any
  18. value: Optional[Any] = None
  19. _common_settings: Dict[str, CommonSetting] = {}
  20. def build_client_name(client_name: str):
  21. product_name = get_setting('product_name')
  22. product_name = product_name.strip() + ' ' if product_name else ''
  23. client_name = client_name.strip() + ' ' if client_name else ''
  24. py_version = sys.version.split(' ', maxsplit=1)[0]
  25. return f'{client_name}{product_name}clickhouse-connect/{version()} (lv:py/{py_version}; os:{sys.platform})'
  26. def get_setting(name: str):
  27. setting = _common_settings.get(name)
  28. if setting is None:
  29. raise ProgrammingError(f'Unrecognized common setting {name}')
  30. return setting.value if setting.value is not None else setting.default
  31. def set_setting(name: str, value: Any):
  32. setting = _common_settings.get(name)
  33. if setting is None:
  34. raise ProgrammingError(f'Unrecognized common setting {name}')
  35. if setting.options and value not in setting.options:
  36. raise ProgrammingError(f'Unrecognized option {value} for setting {name})')
  37. if value == setting.default:
  38. setting.value = None
  39. else:
  40. setting.value = value
  41. def _init_common(name: str, options: Sequence[Any], default: Any):
  42. _common_settings[name] = CommonSetting(name, options, default)
  43. _init_common('autogenerate_session_id', (True, False), True)
  44. _init_common('dict_parameter_format', ('json', 'map'), 'json')
  45. _init_common('invalid_setting_action', ('send', 'drop', 'error'), 'error')
  46. _init_common('max_connection_age', (), 10 * 60) # Max time in seconds to keep reusing a database TCP connection
  47. _init_common('product_name', (), '') # Product name used as part of client identification for ClickHouse query_log
  48. _init_common('readonly', (0, 1), 0) # Implied "read_only" ClickHouse settings for versions prior to 19.17
  49. # Use the client protocol version This is needed for DateTime timezone columns but breaks with current version of
  50. # chproxy
  51. _init_common('use_protocol_version', (True, False), True)
  52. _init_common('max_error_size', (), 1024)