client.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. import io
  2. import logging
  3. from datetime import tzinfo, datetime
  4. import pytz
  5. from abc import ABC, abstractmethod
  6. from typing import Iterable, Optional, Any, Union, Sequence, Dict, Generator, BinaryIO
  7. from pytz.exceptions import UnknownTimeZoneError
  8. from clickhouse_connect import common
  9. from clickhouse_connect.common import version
  10. from clickhouse_connect.datatypes.registry import get_from_name
  11. from clickhouse_connect.datatypes.base import ClickHouseType
  12. from clickhouse_connect.driver.common import dict_copy, StreamContext, coerce_int, coerce_bool
  13. from clickhouse_connect.driver.constants import CH_VERSION_WITH_PROTOCOL, PROTOCOL_VERSION_WITH_LOW_CARD
  14. from clickhouse_connect.driver.exceptions import ProgrammingError, OperationalError
  15. from clickhouse_connect.driver.external import ExternalData
  16. from clickhouse_connect.driver.insert import InsertContext
  17. from clickhouse_connect.driver.summary import QuerySummary
  18. from clickhouse_connect.driver.models import ColumnDef, SettingDef, SettingStatus
  19. from clickhouse_connect.driver.query import QueryResult, to_arrow, to_arrow_batches, QueryContext, arrow_buffer, \
  20. quote_identifier
  21. io.DEFAULT_BUFFER_SIZE = 1024 * 256
  22. logger = logging.getLogger(__name__)
  23. arrow_str_setting = 'output_format_arrow_string_as_string'
  24. # pylint: disable=too-many-public-methods, too-many-instance-attributes
  25. class Client(ABC):
  26. """
  27. Base ClickHouse Connect client
  28. """
  29. compression: str = None
  30. write_compression: str = None
  31. protocol_version = 0
  32. valid_transport_settings = set()
  33. optional_transport_settings = set()
  34. database = None
  35. max_error_message = 0
  36. def __init__(self,
  37. database: str,
  38. query_limit: int,
  39. uri: str,
  40. query_retries: int,
  41. server_host_name: Optional[str],
  42. apply_server_timezone: Optional[Union[str, bool]]):
  43. """
  44. Shared initialization of ClickHouse Connect client
  45. :param database: database name
  46. :param query_limit: default LIMIT for queries
  47. :param uri: uri for error messages
  48. """
  49. self.query_limit = coerce_int(query_limit)
  50. self.query_retries = coerce_int(query_retries)
  51. self.server_host_name = server_host_name
  52. self.server_tz = pytz.UTC
  53. self.server_version, server_tz = \
  54. tuple(self.command('SELECT version(), timezone()', use_database=False))
  55. try:
  56. self.server_tz = pytz.timezone(server_tz)
  57. except UnknownTimeZoneError:
  58. logger.warning('Warning, server is using an unrecognized timezone %s, will use UTC default', server_tz)
  59. offsets_differ = datetime.now().astimezone().utcoffset() != datetime.now(tz=self.server_tz).utcoffset()
  60. self.apply_server_timezone = apply_server_timezone == 'always' or (
  61. coerce_bool(apply_server_timezone) and offsets_differ)
  62. readonly = 'readonly'
  63. if not self.min_version('19.17'):
  64. readonly = common.get_setting('readonly')
  65. server_settings = self.query(f'SELECT name, value, {readonly} as readonly FROM system.settings LIMIT 10000')
  66. self.server_settings = {row['name']: SettingDef(**row) for row in server_settings.named_results()}
  67. if database and not database == '__default__':
  68. self.database = database
  69. if self.min_version(CH_VERSION_WITH_PROTOCOL):
  70. # Unfortunately we have to validate that the client protocol version is actually used by ClickHouse
  71. # since the query parameter could be stripped off (in particular, by CHProxy)
  72. test_data = self.raw_query('SELECT 1 AS check', fmt='Native', settings={
  73. 'client_protocol_version': PROTOCOL_VERSION_WITH_LOW_CARD
  74. })
  75. if test_data[8:16] == b'\x01\x01\x05check':
  76. self.protocol_version = PROTOCOL_VERSION_WITH_LOW_CARD
  77. self.uri = uri
  78. def _validate_settings(self, settings: Optional[Dict[str, Any]]) -> Dict[str, str]:
  79. """
  80. This strips any ClickHouse settings that are not recognized or are read only.
  81. :param settings: Dictionary of setting name and values
  82. :return: A filtered dictionary of settings with values rendered as strings
  83. """
  84. validated = {}
  85. invalid_action = common.get_setting('invalid_setting_action')
  86. for key, value in settings.items():
  87. str_value = self._validate_setting(key, value, invalid_action)
  88. if str_value is not None:
  89. validated[key] = value
  90. return validated
  91. def _validate_setting(self, key: str, value: Any, invalid_action: str) -> Optional[str]:
  92. if key not in self.valid_transport_settings:
  93. setting_def = self.server_settings.get(key)
  94. if setting_def is None or setting_def.readonly:
  95. if key in self.optional_transport_settings:
  96. return None
  97. if invalid_action == 'send':
  98. logger.warning('Attempting to send unrecognized or readonly setting %s', key)
  99. elif invalid_action == 'drop':
  100. logger.warning('Dropping unrecognized or readonly settings %s', key)
  101. return None
  102. else:
  103. raise ProgrammingError(f'Setting {key} is unknown or readonly') from None
  104. if isinstance(value, bool):
  105. return '1' if value else '0'
  106. return str(value)
  107. def _setting_status(self, key: str) -> SettingStatus:
  108. comp_setting = self.server_settings.get(key)
  109. if not comp_setting:
  110. return SettingStatus(False, False)
  111. return SettingStatus(comp_setting.value != '0', comp_setting.readonly != 1)
  112. def _prep_query(self, context: QueryContext):
  113. if context.is_select and not context.has_limit and self.query_limit:
  114. return f'{context.final_query}\n LIMIT {self.query_limit}'
  115. return context.final_query
  116. def _check_tz_change(self, new_tz) -> Optional[tzinfo]:
  117. if new_tz:
  118. try:
  119. new_tzinfo = pytz.timezone(new_tz)
  120. if new_tzinfo != self.server_tz:
  121. return new_tzinfo
  122. except UnknownTimeZoneError:
  123. logger.warning('Unrecognized timezone %s received from ClickHouse', new_tz)
  124. return None
  125. @abstractmethod
  126. def _query_with_context(self, context: QueryContext):
  127. pass
  128. @abstractmethod
  129. def set_client_setting(self, key, value):
  130. """
  131. Set a clickhouse setting for the client after initialization. If a setting is not recognized by ClickHouse,
  132. or the setting is identified as "read_only", this call will either throw a Programming exception or attempt
  133. to send the setting anyway based on the common setting 'invalid_setting_action'
  134. :param key: ClickHouse setting name
  135. :param value: ClickHouse setting value
  136. """
  137. @abstractmethod
  138. def get_client_setting(self, key) -> Optional[str]:
  139. """
  140. :param key: The setting key
  141. :return: The string value of the setting, if it exists, or None
  142. """
  143. # pylint: disable=too-many-arguments,unused-argument,too-many-locals
  144. def query(self,
  145. query: Optional[str] = None,
  146. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  147. settings: Optional[Dict[str, Any]] = None,
  148. query_formats: Optional[Dict[str, str]] = None,
  149. column_formats: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
  150. encoding: Optional[str] = None,
  151. use_none: Optional[bool] = None,
  152. column_oriented: Optional[bool] = None,
  153. use_numpy: Optional[bool] = None,
  154. max_str_len: Optional[int] = None,
  155. context: QueryContext = None,
  156. query_tz: Optional[Union[str, tzinfo]] = None,
  157. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  158. external_data: Optional[ExternalData] = None) -> QueryResult:
  159. """
  160. Main query method for SELECT, DESCRIBE and other SQL statements that return a result matrix. For
  161. parameters, see the create_query_context method
  162. :return: QueryResult -- data and metadata from response
  163. """
  164. if query and query.lower().strip().startswith('select __connect_version__'):
  165. return QueryResult([[f'ClickHouse Connect v.{version()} ⓒ ClickHouse Inc.']], None,
  166. ('connect_version',), (get_from_name('String'),))
  167. kwargs = locals().copy()
  168. del kwargs['self']
  169. query_context = self.create_query_context(**kwargs)
  170. if query_context.is_command:
  171. response = self.command(query,
  172. parameters=query_context.parameters,
  173. settings=query_context.settings,
  174. external_data=query_context.external_data)
  175. if isinstance(response, QuerySummary):
  176. return response.as_query_result()
  177. return QueryResult([response] if isinstance(response, list) else [[response]])
  178. return self._query_with_context(query_context)
  179. def query_column_block_stream(self,
  180. query: Optional[str] = None,
  181. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  182. settings: Optional[Dict[str, Any]] = None,
  183. query_formats: Optional[Dict[str, str]] = None,
  184. column_formats: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
  185. encoding: Optional[str] = None,
  186. use_none: Optional[bool] = None,
  187. context: QueryContext = None,
  188. query_tz: Optional[Union[str, tzinfo]] = None,
  189. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  190. external_data: Optional[ExternalData] = None) -> StreamContext:
  191. """
  192. Variation of main query method that returns a stream of column oriented blocks. For
  193. parameters, see the create_query_context method.
  194. :return: StreamContext -- Iterable stream context that returns column oriented blocks
  195. """
  196. return self._context_query(locals(), use_numpy=False, streaming=True).column_block_stream
  197. def query_row_block_stream(self,
  198. query: Optional[str] = None,
  199. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  200. settings: Optional[Dict[str, Any]] = None,
  201. query_formats: Optional[Dict[str, str]] = None,
  202. column_formats: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
  203. encoding: Optional[str] = None,
  204. use_none: Optional[bool] = None,
  205. context: QueryContext = None,
  206. query_tz: Optional[Union[str, tzinfo]] = None,
  207. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  208. external_data: Optional[ExternalData] = None) -> StreamContext:
  209. """
  210. Variation of main query method that returns a stream of row oriented blocks. For
  211. parameters, see the create_query_context method.
  212. :return: StreamContext -- Iterable stream context that returns blocks of rows
  213. """
  214. return self._context_query(locals(), use_numpy=False, streaming=True).row_block_stream
  215. def query_rows_stream(self,
  216. query: Optional[str] = None,
  217. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  218. settings: Optional[Dict[str, Any]] = None,
  219. query_formats: Optional[Dict[str, str]] = None,
  220. column_formats: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
  221. encoding: Optional[str] = None,
  222. use_none: Optional[bool] = None,
  223. context: QueryContext = None,
  224. query_tz: Optional[Union[str, tzinfo]] = None,
  225. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  226. external_data: Optional[ExternalData] = None) -> StreamContext:
  227. """
  228. Variation of main query method that returns a stream of row oriented blocks. For
  229. parameters, see the create_query_context method.
  230. :return: StreamContext -- Iterable stream context that returns blocks of rows
  231. """
  232. return self._context_query(locals(), use_numpy=False, streaming=True).rows_stream
  233. @abstractmethod
  234. def raw_query(self, query: str,
  235. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  236. settings: Optional[Dict[str, Any]] = None,
  237. fmt: str = None,
  238. use_database: bool = True,
  239. external_data: Optional[ExternalData] = None,
  240. stream: bool = False) -> Union[bytes, io.IOBase]:
  241. """
  242. Query method that simply returns the raw ClickHouse format bytes
  243. :param query: Query statement/format string
  244. :param parameters: Optional dictionary used to format the query
  245. :param settings: Optional dictionary of ClickHouse settings (key/string values)
  246. :param fmt: ClickHouse output format
  247. :param use_database Send the database parameter to ClickHouse so the command will be executed in the client
  248. database context.
  249. :param external_data External data to send with the query
  250. :return: bytes representing raw ClickHouse return value based on format
  251. """
  252. # pylint: disable=duplicate-code,too-many-arguments,unused-argument
  253. def query_np(self,
  254. query: Optional[str] = None,
  255. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  256. settings: Optional[Dict[str, Any]] = None,
  257. query_formats: Optional[Dict[str, str]] = None,
  258. column_formats: Optional[Dict[str, str]] = None,
  259. encoding: Optional[str] = None,
  260. use_none: Optional[bool] = None,
  261. max_str_len: Optional[int] = None,
  262. context: QueryContext = None,
  263. external_data: Optional[ExternalData] = None):
  264. """
  265. Query method that returns the results as a numpy array. For parameter values, see the
  266. create_query_context method
  267. :return: Numpy array representing the result set
  268. """
  269. return self._context_query(locals(), use_numpy=True).np_result
  270. # pylint: disable=duplicate-code,too-many-arguments,unused-argument
  271. def query_np_stream(self,
  272. query: Optional[str] = None,
  273. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  274. settings: Optional[Dict[str, Any]] = None,
  275. query_formats: Optional[Dict[str, str]] = None,
  276. column_formats: Optional[Dict[str, str]] = None,
  277. encoding: Optional[str] = None,
  278. use_none: Optional[bool] = None,
  279. max_str_len: Optional[int] = None,
  280. context: QueryContext = None,
  281. external_data: Optional[ExternalData] = None) -> StreamContext:
  282. """
  283. Query method that returns the results as a stream of numpy arrays. For parameter values, see the
  284. create_query_context method
  285. :return: Generator that yield a numpy array per block representing the result set
  286. """
  287. return self._context_query(locals(), use_numpy=True, streaming=True).np_stream
  288. # pylint: disable=duplicate-code,too-many-arguments,unused-argument
  289. def query_df(self,
  290. query: Optional[str] = None,
  291. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  292. settings: Optional[Dict[str, Any]] = None,
  293. query_formats: Optional[Dict[str, str]] = None,
  294. column_formats: Optional[Dict[str, str]] = None,
  295. encoding: Optional[str] = None,
  296. use_none: Optional[bool] = None,
  297. max_str_len: Optional[int] = None,
  298. use_na_values: Optional[bool] = None,
  299. query_tz: Optional[str] = None,
  300. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  301. context: QueryContext = None,
  302. external_data: Optional[ExternalData] = None,
  303. use_extended_dtypes: Optional[bool] = None):
  304. """
  305. Query method that results the results as a pandas dataframe. For parameter values, see the
  306. create_query_context method
  307. :return: Pandas dataframe representing the result set
  308. """
  309. return self._context_query(locals(), use_numpy=True, as_pandas=True).df_result
  310. # pylint: disable=duplicate-code,too-many-arguments,unused-argument
  311. def query_df_stream(self,
  312. query: Optional[str] = None,
  313. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  314. settings: Optional[Dict[str, Any]] = None,
  315. query_formats: Optional[Dict[str, str]] = None,
  316. column_formats: Optional[Dict[str, str]] = None,
  317. encoding: Optional[str] = None,
  318. use_none: Optional[bool] = None,
  319. max_str_len: Optional[int] = None,
  320. use_na_values: Optional[bool] = None,
  321. query_tz: Optional[str] = None,
  322. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  323. context: QueryContext = None,
  324. external_data: Optional[ExternalData] = None,
  325. use_extended_dtypes: Optional[bool] = None) -> StreamContext:
  326. """
  327. Query method that returns the results as a StreamContext. For parameter values, see the
  328. create_query_context method
  329. :return: Generator that yields a Pandas dataframe per block representing the result set
  330. """
  331. return self._context_query(locals(), use_numpy=True,
  332. as_pandas=True,
  333. streaming=True).df_stream
  334. def create_query_context(self,
  335. query: Optional[str] = None,
  336. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  337. settings: Optional[Dict[str, Any]] = None,
  338. query_formats: Optional[Dict[str, str]] = None,
  339. column_formats: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
  340. encoding: Optional[str] = None,
  341. use_none: Optional[bool] = None,
  342. column_oriented: Optional[bool] = None,
  343. use_numpy: Optional[bool] = False,
  344. max_str_len: Optional[int] = 0,
  345. context: Optional[QueryContext] = None,
  346. query_tz: Optional[Union[str, tzinfo]] = None,
  347. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  348. use_na_values: Optional[bool] = None,
  349. streaming: bool = False,
  350. as_pandas: bool = False,
  351. external_data: Optional[ExternalData] = None,
  352. use_extended_dtypes: Optional[bool] = None) -> QueryContext:
  353. """
  354. Creates or updates a reusable QueryContext object
  355. :param query: Query statement/format string
  356. :param parameters: Optional dictionary used to format the query
  357. :param settings: Optional dictionary of ClickHouse settings (key/string values)
  358. :param query_formats: See QueryContext __init__ docstring
  359. :param column_formats: See QueryContext __init__ docstring
  360. :param encoding: See QueryContext __init__ docstring
  361. :param use_none: Use None for ClickHouse NULL instead of default values. Note that using None in Numpy
  362. arrays will force the numpy array dtype to 'object', which is often inefficient. This effect also
  363. will impact the performance of Pandas dataframes.
  364. :param column_oriented: Deprecated. Controls orientation of the QueryResult result_set property
  365. :param use_numpy: Return QueryResult columns as one-dimensional numpy arrays
  366. :param max_str_len: Limit returned ClickHouse String values to this length, which allows a Numpy
  367. structured array even with ClickHouse variable length String columns. If 0, Numpy arrays for
  368. String columns will always be object arrays
  369. :param context: An existing QueryContext to be updated with any provided parameter values
  370. :param query_tz Either a string or a pytz tzinfo object. (Strings will be converted to tzinfo objects).
  371. Values for any DateTime or DateTime64 column in the query will be converted to Python datetime.datetime
  372. objects with the selected timezone.
  373. :param column_tzs A dictionary of column names to tzinfo objects (or strings that will be converted to
  374. tzinfo objects). The timezone will be applied to datetime objects returned in the query
  375. :param use_na_values: Deprecated alias for use_advanced_dtypes
  376. :param as_pandas Return the result columns as pandas.Series objects
  377. :param streaming Marker used to correctly configure streaming queries
  378. :param external_data ClickHouse "external data" to send with query
  379. :param use_extended_dtypes: Only relevant to Pandas Dataframe queries. Use Pandas "missing types", such as
  380. pandas.NA and pandas.NaT for ClickHouse NULL values, as well as extended Pandas dtypes such as IntegerArray
  381. and StringArray. Defaulted to True for query_df methods
  382. :return: Reusable QueryContext
  383. """
  384. if context:
  385. return context.updated_copy(query=query,
  386. parameters=parameters,
  387. settings=settings,
  388. query_formats=query_formats,
  389. column_formats=column_formats,
  390. encoding=encoding,
  391. server_tz=self.server_tz,
  392. use_none=use_none,
  393. column_oriented=column_oriented,
  394. use_numpy=use_numpy,
  395. max_str_len=max_str_len,
  396. query_tz=query_tz,
  397. column_tzs=column_tzs,
  398. as_pandas=as_pandas,
  399. use_extended_dtypes=use_extended_dtypes,
  400. streaming=streaming,
  401. external_data=external_data)
  402. if use_numpy and max_str_len is None:
  403. max_str_len = 0
  404. if use_extended_dtypes is None:
  405. use_extended_dtypes = use_na_values
  406. if as_pandas and use_extended_dtypes is None:
  407. use_extended_dtypes = True
  408. return QueryContext(query=query,
  409. parameters=parameters,
  410. settings=settings,
  411. query_formats=query_formats,
  412. column_formats=column_formats,
  413. encoding=encoding,
  414. server_tz=self.server_tz,
  415. use_none=use_none,
  416. column_oriented=column_oriented,
  417. use_numpy=use_numpy,
  418. max_str_len=max_str_len,
  419. query_tz=query_tz,
  420. column_tzs=column_tzs,
  421. use_extended_dtypes=use_extended_dtypes,
  422. as_pandas=as_pandas,
  423. streaming=streaming,
  424. apply_server_tz=self.apply_server_timezone,
  425. external_data=external_data)
  426. def query_arrow(self,
  427. query: str,
  428. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  429. settings: Optional[Dict[str, Any]] = None,
  430. use_strings: Optional[bool] = None,
  431. external_data: Optional[ExternalData] = None):
  432. """
  433. Query method using the ClickHouse Arrow format to return a PyArrow table
  434. :param query: Query statement/format string
  435. :param parameters: Optional dictionary used to format the query
  436. :param settings: Optional dictionary of ClickHouse settings (key/string values)
  437. :param use_strings: Convert ClickHouse String type to Arrow string type (instead of binary)
  438. :param external_data ClickHouse "external data" to send with query
  439. :return: PyArrow.Table
  440. """
  441. settings = self._update_arrow_settings(settings, use_strings)
  442. return to_arrow(self.raw_query(query,
  443. parameters,
  444. settings,
  445. fmt='Arrow',
  446. external_data=external_data))
  447. def query_arrow_stream(self,
  448. query: str,
  449. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  450. settings: Optional[Dict[str, Any]] = None,
  451. use_strings: Optional[bool] = None,
  452. external_data: Optional[ExternalData] = None) -> StreamContext:
  453. """
  454. Query method that returns the results as a stream of Arrow tables
  455. :param query: Query statement/format string
  456. :param parameters: Optional dictionary used to format the query
  457. :param settings: Optional dictionary of ClickHouse settings (key/string values)
  458. :param use_strings: Convert ClickHouse String type to Arrow string type (instead of binary)
  459. :param external_data ClickHouse "external data" to send with query
  460. :return: Generator that yields a PyArrow.Table for per block representing the result set
  461. """
  462. settings = self._update_arrow_settings(settings, use_strings)
  463. return to_arrow_batches(self.raw_query(query,
  464. parameters,
  465. settings,
  466. fmt='ArrowStream',
  467. external_data=external_data,
  468. stream=True))
  469. def _update_arrow_settings(self,
  470. settings: Optional[Dict[str, Any]],
  471. use_strings: Optional[bool]) -> Dict[str, Any]:
  472. settings = dict_copy(settings)
  473. if self.database:
  474. settings['database'] = self.database
  475. str_status = self._setting_status(arrow_str_setting)
  476. if use_strings is None:
  477. if str_status.is_writable and not str_status.is_set:
  478. settings[arrow_str_setting] = '1' # Default to returning strings if possible
  479. elif use_strings != str_status.is_set:
  480. if not str_status.is_writable:
  481. raise OperationalError(f'Cannot change readonly {arrow_str_setting} to {use_strings}')
  482. settings[arrow_str_setting] = '1' if use_strings else '0'
  483. return settings
  484. @abstractmethod
  485. def command(self,
  486. cmd: str,
  487. parameters: Optional[Union[Sequence, Dict[str, Any]]] = None,
  488. data: Union[str, bytes] = None,
  489. settings: Dict[str, Any] = None,
  490. use_database: bool = True,
  491. external_data: Optional[ExternalData] = None) -> Union[str, int, Sequence[str], QuerySummary]:
  492. """
  493. Client method that returns a single value instead of a result set
  494. :param cmd: ClickHouse query/command as a python format string
  495. :param parameters: Optional dictionary of key/values pairs to be formatted
  496. :param data: Optional 'data' for the command (for INSERT INTO in particular)
  497. :param settings: Optional dictionary of ClickHouse settings (key/string values)
  498. :param use_database: Send the database parameter to ClickHouse so the command will be executed in the client
  499. database context. Otherwise, no database will be specified with the command. This is useful for determining
  500. the default user database
  501. :param external_data ClickHouse "external data" to send with command/query
  502. :return: Decoded response from ClickHouse as either a string, int, or sequence of strings, or QuerySummary
  503. if no data returned
  504. """
  505. @abstractmethod
  506. def ping(self) -> bool:
  507. """
  508. Validate the connection, does not throw an Exception (see debug logs)
  509. :return: ClickHouse server is up and reachable
  510. """
  511. # pylint: disable=too-many-arguments
  512. def insert(self,
  513. table: Optional[str] = None,
  514. data: Sequence[Sequence[Any]] = None,
  515. column_names: Union[str, Iterable[str]] = '*',
  516. database: Optional[str] = None,
  517. column_types: Sequence[ClickHouseType] = None,
  518. column_type_names: Sequence[str] = None,
  519. column_oriented: bool = False,
  520. settings: Optional[Dict[str, Any]] = None,
  521. context: InsertContext = None) -> QuerySummary:
  522. """
  523. Method to insert multiple rows/data matrix of native Python objects. If context is specified arguments
  524. other than data are ignored
  525. :param table: Target table
  526. :param data: Sequence of sequences of Python data
  527. :param column_names: Ordered list of column names or '*' if column types should be retrieved from the
  528. ClickHouse table definition
  529. :param database: Target database -- will use client default database if not specified.
  530. :param column_types: ClickHouse column types. If set then column data does not need to be retrieved from
  531. the server
  532. :param column_type_names: ClickHouse column type names. If set then column data does not need to be
  533. retrieved from the server
  534. :param column_oriented: If true the data is already "pivoted" in column form
  535. :param settings: Optional dictionary of ClickHouse settings (key/string values)
  536. :param context: Optional reusable insert context to allow repeated inserts into the same table with
  537. different data batches
  538. :return: QuerySummary with summary information, throws exception if insert fails
  539. """
  540. if (context is None or context.empty) and data is None:
  541. raise ProgrammingError('No data specified for insert') from None
  542. if context is None:
  543. context = self.create_insert_context(table,
  544. column_names,
  545. database,
  546. column_types,
  547. column_type_names,
  548. column_oriented,
  549. settings)
  550. if data is not None:
  551. if not context.empty:
  552. raise ProgrammingError('Attempting to insert new data with non-empty insert context') from None
  553. context.data = data
  554. return self.data_insert(context)
  555. def insert_df(self, table: str = None,
  556. df=None,
  557. database: Optional[str] = None,
  558. settings: Optional[Dict] = None,
  559. column_names: Optional[Sequence[str]] = None,
  560. column_types: Sequence[ClickHouseType] = None,
  561. column_type_names: Sequence[str] = None,
  562. context: InsertContext = None) -> QuerySummary:
  563. """
  564. Insert a pandas DataFrame into ClickHouse. If context is specified arguments other than df are ignored
  565. :param table: ClickHouse table
  566. :param df: two-dimensional pandas dataframe
  567. :param database: Optional ClickHouse database
  568. :param settings: Optional dictionary of ClickHouse settings (key/string values)
  569. :param column_names: An optional list of ClickHouse column names. If not set, the DataFrame column names
  570. will be used
  571. :param column_types: ClickHouse column types. If set then column data does not need to be retrieved from
  572. the server
  573. :param column_type_names: ClickHouse column type names. If set then column data does not need to be
  574. retrieved from the server
  575. :param context: Optional reusable insert context to allow repeated inserts into the same table with
  576. different data batches
  577. :return: QuerySummary with summary information, throws exception if insert fails
  578. """
  579. if context is None:
  580. if column_names is None:
  581. column_names = df.columns
  582. elif len(column_names) != len(df.columns):
  583. raise ProgrammingError('DataFrame column count does not match insert_columns') from None
  584. return self.insert(table,
  585. df,
  586. column_names,
  587. database,
  588. column_types=column_types,
  589. column_type_names=column_type_names,
  590. settings=settings, context=context)
  591. def insert_arrow(self, table: str,
  592. arrow_table, database: str = None,
  593. settings: Optional[Dict] = None) -> QuerySummary:
  594. """
  595. Insert a PyArrow table DataFrame into ClickHouse using raw Arrow format
  596. :param table: ClickHouse table
  597. :param arrow_table: PyArrow Table object
  598. :param database: Optional ClickHouse database
  599. :param settings: Optional dictionary of ClickHouse settings (key/string values)
  600. :return: QuerySummary with summary information, throws exception if insert fails
  601. """
  602. full_table = table if '.' in table or not database else f'{database}.{table}'
  603. column_names, insert_block = arrow_buffer(arrow_table)
  604. return self.raw_insert(full_table, column_names, insert_block, settings, 'Arrow')
  605. def create_insert_context(self,
  606. table: str,
  607. column_names: Optional[Union[str, Sequence[str]]] = None,
  608. database: Optional[str] = None,
  609. column_types: Sequence[ClickHouseType] = None,
  610. column_type_names: Sequence[str] = None,
  611. column_oriented: bool = False,
  612. settings: Optional[Dict[str, Any]] = None,
  613. data: Optional[Sequence[Sequence[Any]]] = None) -> InsertContext:
  614. """
  615. Builds a reusable insert context to hold state for a duration of an insert
  616. :param table: Target table
  617. :param database: Target database. If not set, uses the client default database
  618. :param column_names: Optional ordered list of column names. If not set, all columns ('*') will be assumed
  619. in the order specified by the table definition
  620. :param database: Target database -- will use client default database if not specified
  621. :param column_types: ClickHouse column types. Optional Sequence of ClickHouseType objects. If neither column
  622. types nor column type names are set, actual column types will be retrieved from the server.
  623. :param column_type_names: ClickHouse column type names. Specified column types by name string
  624. :param column_oriented: If true the data is already "pivoted" in column form
  625. :param settings: Optional dictionary of ClickHouse settings (key/string values)
  626. :param data: Initial dataset for insert
  627. :return Reusable insert context
  628. """
  629. full_table = table
  630. if '.' not in table:
  631. if database:
  632. full_table = f'{quote_identifier(database)}.{quote_identifier(table)}'
  633. else:
  634. full_table = quote_identifier(table)
  635. column_defs = []
  636. if column_types is None and column_type_names is None:
  637. describe_result = self.query(f'DESCRIBE TABLE {full_table}')
  638. column_defs = [ColumnDef(**row) for row in describe_result.named_results()
  639. if row['default_type'] not in ('ALIAS', 'MATERIALIZED')]
  640. if column_names is None or isinstance(column_names, str) and column_names == '*':
  641. column_names = [cd.name for cd in column_defs]
  642. column_types = [cd.ch_type for cd in column_defs]
  643. elif isinstance(column_names, str):
  644. column_names = [column_names]
  645. if len(column_names) == 0:
  646. raise ValueError('Column names must be specified for insert')
  647. if not column_types:
  648. if column_type_names:
  649. column_types = [get_from_name(name) for name in column_type_names]
  650. else:
  651. column_map = {d.name: d for d in column_defs}
  652. try:
  653. column_types = [column_map[name].ch_type for name in column_names]
  654. except KeyError as ex:
  655. raise ProgrammingError(f'Unrecognized column {ex} in table {table}') from None
  656. if len(column_names) != len(column_types):
  657. raise ProgrammingError('Column names do not match column types') from None
  658. return InsertContext(full_table,
  659. column_names,
  660. column_types,
  661. column_oriented=column_oriented,
  662. settings=settings,
  663. data=data)
  664. def min_version(self, version_str: str) -> bool:
  665. """
  666. Determine whether the connected server is at least the submitted version
  667. For Altinity Stable versions like 22.8.15.25.altinitystable
  668. the last condition in the first list comprehension expression is added
  669. :param version_str: A version string consisting of up to 4 integers delimited by dots
  670. :return: True if version_str is greater than the server_version, False if less than
  671. """
  672. try:
  673. server_parts = [int(x) for x in self.server_version.split('.') if x.isnumeric()]
  674. server_parts.extend([0] * (4 - len(server_parts)))
  675. version_parts = [int(x) for x in version_str.split('.')]
  676. version_parts.extend([0] * (4 - len(version_parts)))
  677. except ValueError:
  678. logger.warning('Server %s or requested version %s does not match format of numbers separated by dots',
  679. self.server_version, version_str)
  680. return False
  681. for x, y in zip(server_parts, version_parts):
  682. if x > y:
  683. return True
  684. if x < y:
  685. return False
  686. return True
  687. @abstractmethod
  688. def data_insert(self, context: InsertContext) -> QuerySummary:
  689. """
  690. Subclass implementation of the data insert
  691. :context: InsertContext parameter object
  692. :return: No return, throws an exception if the insert fails
  693. """
  694. @abstractmethod
  695. def raw_insert(self, table: str,
  696. column_names: Optional[Sequence[str]] = None,
  697. insert_block: Union[str, bytes, Generator[bytes, None, None], BinaryIO] = None,
  698. settings: Optional[Dict] = None,
  699. fmt: Optional[str] = None,
  700. compression: Optional[str] = None) -> QuerySummary:
  701. """
  702. Insert data already formatted in a bytes object
  703. :param table: Table name (whether qualified with the database name or not)
  704. :param column_names: Sequence of column names
  705. :param insert_block: Binary or string data already in a recognized ClickHouse format
  706. :param settings: Optional dictionary of ClickHouse settings (key/string values)
  707. :param compression: Recognized ClickHouse `Accept-Encoding` header compression value
  708. :param fmt: Valid clickhouse format
  709. """
  710. def close(self):
  711. """
  712. Subclass implementation to close the connection to the server/deallocate the client
  713. """
  714. def _context_query(self, lcls: dict, **overrides):
  715. kwargs = lcls.copy()
  716. kwargs.pop('self')
  717. kwargs.update(overrides)
  718. return self._query_with_context((self.create_query_context(**kwargs)))
  719. def __enter__(self):
  720. return self
  721. def __exit__(self, exc_type, exc_value, exc_traceback):
  722. self.close()