query.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. import ipaddress
  2. import logging
  3. import re
  4. import uuid
  5. import pytz
  6. from enum import Enum
  7. from io import IOBase
  8. from typing import Any, Tuple, Dict, Sequence, Optional, Union, Generator
  9. from datetime import date, datetime, tzinfo
  10. from pytz.exceptions import UnknownTimeZoneError
  11. from clickhouse_connect import common
  12. from clickhouse_connect.driver import tzutil
  13. from clickhouse_connect.driver.common import dict_copy, empty_gen, StreamContext
  14. from clickhouse_connect.driver.external import ExternalData
  15. from clickhouse_connect.driver.types import Matrix, Closable
  16. from clickhouse_connect.json_impl import any_to_json
  17. from clickhouse_connect.driver.exceptions import StreamClosedError, ProgrammingError
  18. from clickhouse_connect.driver.options import check_arrow, pd_extended_dtypes
  19. from clickhouse_connect.driver.context import BaseQueryContext
  20. logger = logging.getLogger(__name__)
  21. commands = 'CREATE|ALTER|SYSTEM|GRANT|REVOKE|CHECK|DETACH|ATTACH|DROP|DELETE|KILL|' + \
  22. 'OPTIMIZE|SET|RENAME|TRUNCATE|USE'
  23. limit_re = re.compile(r'\s+LIMIT($|\s)', re.IGNORECASE)
  24. select_re = re.compile(r'(^|\s)SELECT\s', re.IGNORECASE)
  25. insert_re = re.compile(r'(^|\s)INSERT\s*INTO', re.IGNORECASE)
  26. command_re = re.compile(r'(^\s*)(' + commands + r')\s', re.IGNORECASE)
  27. external_bind_re = re.compile(r'{.+:.+}')
  28. # pylint: disable=too-many-instance-attributes
  29. class QueryContext(BaseQueryContext):
  30. """
  31. Argument/parameter object for queries. This context is used to set thread/query specific formats
  32. """
  33. # pylint: disable=duplicate-code,too-many-arguments,too-many-locals
  34. def __init__(self,
  35. query: Union[str, bytes] = '',
  36. parameters: Optional[Dict[str, Any]] = None,
  37. settings: Optional[Dict[str, Any]] = None,
  38. query_formats: Optional[Dict[str, str]] = None,
  39. column_formats: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
  40. encoding: Optional[str] = None,
  41. server_tz: tzinfo = pytz.UTC,
  42. use_none: Optional[bool] = None,
  43. column_oriented: Optional[bool] = None,
  44. use_numpy: Optional[bool] = None,
  45. max_str_len: Optional[int] = 0,
  46. query_tz: Optional[Union[str, tzinfo]] = None,
  47. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  48. use_extended_dtypes: Optional[bool] = None,
  49. as_pandas: bool = False,
  50. streaming: bool = False,
  51. apply_server_tz: bool = False,
  52. external_data: Optional[ExternalData] = None):
  53. """
  54. Initializes various configuration settings for the query context
  55. :param query: Query string with Python style format value replacements
  56. :param parameters: Optional dictionary of substitution values
  57. :param settings: Optional ClickHouse settings for the query
  58. :param query_formats: Optional dictionary of query formats with the key of a ClickHouse type name
  59. (with * wildcards) and a value of valid query formats for those types.
  60. The value 'encoding' can be sent to change the expected encoding for this query, with a value of
  61. the desired encoding such as `latin-1`
  62. :param column_formats: Optional dictionary of column specific formats. The key is the column name,
  63. The value is either the format for the data column (such as 'string' for a UUID column) or a
  64. second level "format" dictionary of a ClickHouse type name and a value of query formats. This
  65. secondary dictionary can be used for nested column types such as Tuples or Maps
  66. :param encoding: Optional string encoding for this query, such as 'latin-1'
  67. :param column_formats: Optional dictionary
  68. :param use_none: Use a Python None for ClickHouse NULL values in nullable columns. Otherwise the default
  69. value of the column (such as 0 for numbers) will be returned in the result_set
  70. :param max_str_len Limit returned ClickHouse String values to this length, which allows a Numpy
  71. structured array even with ClickHouse variable length String columns. If 0, Numpy arrays for
  72. String columns will always be object arrays
  73. :param query_tz Either a string or a pytz tzinfo object. (Strings will be converted to tzinfo objects).
  74. Values for any DateTime or DateTime64 column in the query will be converted to Python datetime.datetime
  75. objects with the selected timezone
  76. :param column_tzs A dictionary of column names to tzinfo objects (or strings that will be converted to
  77. tzinfo objects). The timezone will be applied to datetime objects returned in the query
  78. """
  79. super().__init__(settings,
  80. query_formats,
  81. column_formats,
  82. encoding,
  83. use_extended_dtypes if use_extended_dtypes is not None else False,
  84. use_numpy if use_numpy is not None else False)
  85. self.query = query
  86. self.parameters = parameters or {}
  87. self.use_none = True if use_none is None else use_none
  88. self.column_oriented = False if column_oriented is None else column_oriented
  89. self.use_numpy = use_numpy
  90. self.max_str_len = 0 if max_str_len is None else max_str_len
  91. self.server_tz = server_tz
  92. self.apply_server_tz = apply_server_tz
  93. self.external_data = external_data
  94. if isinstance(query_tz, str):
  95. try:
  96. query_tz = pytz.timezone(query_tz)
  97. except UnknownTimeZoneError as ex:
  98. raise ProgrammingError(f'query_tz {query_tz} is not recognized') from ex
  99. self.query_tz = query_tz
  100. if column_tzs is not None:
  101. for col_name, timezone in column_tzs.items():
  102. if isinstance(timezone, str):
  103. try:
  104. timezone = pytz.timezone(timezone)
  105. column_tzs[col_name] = timezone
  106. except UnknownTimeZoneError as ex:
  107. raise ProgrammingError(f'column_tz {timezone} is not recognized') from ex
  108. self.column_tzs = column_tzs
  109. self.column_tz = None
  110. self.response_tz = None
  111. self.block_info = False
  112. self.as_pandas = as_pandas
  113. self.use_pandas_na = as_pandas and pd_extended_dtypes
  114. self.streaming = streaming
  115. self._update_query()
  116. @property
  117. def is_select(self) -> bool:
  118. return select_re.search(self.uncommented_query) is not None
  119. @property
  120. def has_limit(self) -> bool:
  121. return limit_re.search(self.uncommented_query) is not None
  122. @property
  123. def is_insert(self) -> bool:
  124. return insert_re.search(self.uncommented_query) is not None
  125. @property
  126. def is_command(self) -> bool:
  127. return command_re.search(self.uncommented_query) is not None
  128. def set_parameters(self, parameters: Dict[str, Any]):
  129. self.parameters = parameters
  130. self._update_query()
  131. def set_parameter(self, key: str, value: Any):
  132. if not self.parameters:
  133. self.parameters = {}
  134. self.parameters[key] = value
  135. self._update_query()
  136. def set_response_tz(self, response_tz: tzinfo):
  137. self.response_tz = response_tz
  138. def start_column(self, name: str):
  139. super().start_column(name)
  140. if self.column_tzs and name in self.column_tzs:
  141. self.column_tz = self.column_tzs[name]
  142. else:
  143. self.column_tz = None
  144. def active_tz(self, datatype_tz: Optional[tzinfo]):
  145. if self.column_tz:
  146. active_tz = self.column_tz
  147. elif datatype_tz:
  148. active_tz = datatype_tz
  149. elif self.query_tz:
  150. active_tz = self.query_tz
  151. elif self.response_tz:
  152. active_tz = self.response_tz
  153. elif self.apply_server_tz:
  154. active_tz = self.server_tz
  155. else:
  156. active_tz = tzutil.local_tz
  157. if active_tz == pytz.UTC:
  158. return None
  159. return active_tz
  160. def updated_copy(self,
  161. query: Optional[Union[str, bytes]] = None,
  162. parameters: Optional[Dict[str, Any]] = None,
  163. settings: Optional[Dict[str, Any]] = None,
  164. query_formats: Optional[Dict[str, str]] = None,
  165. column_formats: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
  166. encoding: Optional[str] = None,
  167. server_tz: Optional[tzinfo] = None,
  168. use_none: Optional[bool] = None,
  169. column_oriented: Optional[bool] = None,
  170. use_numpy: Optional[bool] = None,
  171. max_str_len: Optional[int] = None,
  172. query_tz: Optional[Union[str, tzinfo]] = None,
  173. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  174. use_extended_dtypes: Optional[bool] = None,
  175. as_pandas: bool = False,
  176. streaming: bool = False,
  177. external_data: Optional[ExternalData] = None) -> 'QueryContext':
  178. """
  179. Creates Query context copy with parameters overridden/updated as appropriate.
  180. """
  181. return QueryContext(query or self.query,
  182. dict_copy(self.parameters, parameters),
  183. dict_copy(self.settings, settings),
  184. dict_copy(self.query_formats, query_formats),
  185. dict_copy(self.column_formats, column_formats),
  186. encoding if encoding else self.encoding,
  187. server_tz if server_tz else self.server_tz,
  188. self.use_none if use_none is None else use_none,
  189. self.column_oriented if column_oriented is None else column_oriented,
  190. self.use_numpy if use_numpy is None else use_numpy,
  191. self.max_str_len if max_str_len is None else max_str_len,
  192. self.query_tz if query_tz is None else query_tz,
  193. self.column_tzs if column_tzs is None else column_tzs,
  194. self.use_extended_dtypes if use_extended_dtypes is None else use_extended_dtypes,
  195. as_pandas,
  196. streaming,
  197. self.apply_server_tz,
  198. self.external_data if external_data is None else external_data)
  199. def _update_query(self):
  200. self.final_query, self.bind_params = bind_query(self.query, self.parameters, self.server_tz)
  201. if isinstance(self.final_query, bytes):
  202. # If we've embedded binary data in the query, all bets are off, and we check the original query for comments
  203. self.uncommented_query = remove_sql_comments(self.query)
  204. else:
  205. self.uncommented_query = remove_sql_comments(self.final_query)
  206. class QueryResult(Closable):
  207. """
  208. Wrapper class for query return values and metadata
  209. """
  210. # pylint: disable=too-many-arguments
  211. def __init__(self,
  212. result_set: Matrix = None,
  213. block_gen: Generator[Matrix, None, None] = None,
  214. column_names: Tuple = (),
  215. column_types: Tuple = (),
  216. column_oriented: bool = False,
  217. source: Closable = None,
  218. query_id: str = None,
  219. summary: Dict[str, Any] = None):
  220. self._result_rows = result_set
  221. self._result_columns = None
  222. self._block_gen = block_gen or empty_gen()
  223. self._in_context = False
  224. self._query_id = query_id
  225. self.column_names = column_names
  226. self.column_types = column_types
  227. self.column_oriented = column_oriented
  228. self.source = source
  229. self.summary = {} if summary is None else summary
  230. @property
  231. def result_set(self) -> Matrix:
  232. if self.column_oriented:
  233. return self.result_columns
  234. return self.result_rows
  235. @property
  236. def result_columns(self) -> Matrix:
  237. if self._result_columns is None:
  238. result = [[] for _ in range(len(self.column_names))]
  239. with self.column_block_stream as stream:
  240. for block in stream:
  241. for base, added in zip(result, block):
  242. base.extend(added)
  243. self._result_columns = result
  244. return self._result_columns
  245. @property
  246. def result_rows(self) -> Matrix:
  247. if self._result_rows is None:
  248. result = []
  249. with self.row_block_stream as stream:
  250. for block in stream:
  251. result.extend(block)
  252. self._result_rows = result
  253. return self._result_rows
  254. @property
  255. def query_id(self) -> str:
  256. query_id = self.summary.get('query_id')
  257. if query_id:
  258. return query_id
  259. return self._query_id
  260. def _column_block_stream(self):
  261. if self._block_gen is None:
  262. raise StreamClosedError
  263. block_stream = self._block_gen
  264. self._block_gen = None
  265. return block_stream
  266. def _row_block_stream(self):
  267. for block in self._column_block_stream():
  268. yield list(zip(*block))
  269. @property
  270. def column_block_stream(self) -> StreamContext:
  271. return StreamContext(self, self._column_block_stream())
  272. @property
  273. def row_block_stream(self):
  274. return StreamContext(self, self._row_block_stream())
  275. @property
  276. def rows_stream(self) -> StreamContext:
  277. def stream():
  278. for block in self._row_block_stream():
  279. yield from block
  280. return StreamContext(self, stream())
  281. def named_results(self) -> Generator[dict, None, None]:
  282. for row in zip(*self.result_set) if self.column_oriented else self.result_set:
  283. yield dict(zip(self.column_names, row))
  284. @property
  285. def row_count(self) -> int:
  286. if self.column_oriented:
  287. return 0 if len(self.result_set) == 0 else len(self.result_set[0])
  288. return len(self.result_set)
  289. @property
  290. def first_item(self):
  291. if self.column_oriented:
  292. return {name: col[0] for name, col in zip(self.column_names, self.result_set)}
  293. return dict(zip(self.column_names, self.result_set[0]))
  294. @property
  295. def first_row(self):
  296. if self.column_oriented:
  297. return [col[0] for col in self.result_set]
  298. return self.result_set[0]
  299. def close(self):
  300. if self.source:
  301. self.source.close()
  302. self.source = None
  303. if self._block_gen is not None:
  304. self._block_gen.close()
  305. self._block_gen = None
  306. BS = '\\'
  307. must_escape = (BS, '\'', '`', '\t', '\n')
  308. def quote_identifier(identifier: str):
  309. first_char = identifier[0]
  310. if first_char in ('`', '"') and identifier[-1] == first_char:
  311. # Identifier is already quoted, assume that it's valid
  312. return identifier
  313. return f'`{escape_str(identifier)}`'
  314. def finalize_query(query: str, parameters: Optional[Union[Sequence, Dict[str, Any]]],
  315. server_tz: Optional[tzinfo] = None) -> str:
  316. while query.endswith(';'):
  317. query = query[:-1]
  318. if not parameters:
  319. return query
  320. if hasattr(parameters, 'items'):
  321. return query % {k: format_query_value(v, server_tz) for k, v in parameters.items()}
  322. return query % tuple(format_query_value(v) for v in parameters)
  323. def bind_query(query: str, parameters: Optional[Union[Sequence, Dict[str, Any]]],
  324. server_tz: Optional[tzinfo] = None) -> Tuple[str, Dict[str, str]]:
  325. while query.endswith(';'):
  326. query = query[:-1]
  327. if not parameters:
  328. return query, {}
  329. binary_binds = None
  330. if isinstance(parameters, dict):
  331. binary_binds = {k: v for k, v in parameters.items() if k.startswith('$') and k.endswith('$') and len(k) > 1}
  332. for key in binary_binds.keys():
  333. del parameters[key]
  334. if external_bind_re.search(query) is None:
  335. query, bound_params = finalize_query(query, parameters, server_tz), {}
  336. else:
  337. bound_params = {f'param_{k}': format_bind_value(v, server_tz) for k, v in parameters.items()}
  338. if binary_binds:
  339. binary_query = query.encode()
  340. binary_indexes = {}
  341. for k, v in binary_binds.items():
  342. key = k.encode()
  343. item_index = 0
  344. while True:
  345. item_index = binary_query.find(key, item_index)
  346. if item_index == -1:
  347. break
  348. binary_indexes[item_index + len(key)] = key, v
  349. item_index += len(key)
  350. query = b''
  351. start = 0
  352. for loc in sorted(binary_indexes.keys()):
  353. key, value = binary_indexes[loc]
  354. query += binary_query[start:loc] + value + key
  355. start = loc
  356. query += binary_query[start:]
  357. return query, bound_params
  358. def format_str(value: str):
  359. return f"'{escape_str(value)}'"
  360. def escape_str(value: str):
  361. return ''.join(f'{BS}{c}' if c in must_escape else c for c in value)
  362. # pylint: disable=too-many-return-statements
  363. def format_query_value(value: Any, server_tz: tzinfo = pytz.UTC):
  364. """
  365. Format Python values in a ClickHouse query
  366. :param value: Python object
  367. :param server_tz: Server timezone for adjusting datetime values
  368. :return: Literal string for python value
  369. """
  370. if value is None:
  371. return 'NULL'
  372. if isinstance(value, str):
  373. return format_str(value)
  374. if isinstance(value, datetime):
  375. if value.tzinfo is not None or server_tz != pytz.UTC:
  376. value = value.astimezone(server_tz)
  377. return f"'{value.strftime('%Y-%m-%d %H:%M:%S')}'"
  378. if isinstance(value, date):
  379. return f"'{value.isoformat()}'"
  380. if isinstance(value, list):
  381. return f"[{', '.join(str_query_value(x, server_tz) for x in value)}]"
  382. if isinstance(value, tuple):
  383. return f"({', '.join(str_query_value(x, server_tz) for x in value)})"
  384. if isinstance(value, dict):
  385. if common.get_setting('dict_parameter_format') == 'json':
  386. return format_str(any_to_json(value).decode())
  387. pairs = [str_query_value(k, server_tz) + ':' + str_query_value(v, server_tz)
  388. for k, v in value.items()]
  389. return f"{{{', '.join(pairs)}}}"
  390. if isinstance(value, Enum):
  391. return format_query_value(value.value, server_tz)
  392. if isinstance(value, (uuid.UUID, ipaddress.IPv4Address, ipaddress.IPv6Address)):
  393. return f"'{value}'"
  394. return value
  395. def str_query_value(value: Any, server_tz: tzinfo = pytz.UTC):
  396. return str(format_query_value(value, server_tz))
  397. # pylint: disable=too-many-branches
  398. def format_bind_value(value: Any, server_tz: tzinfo = pytz.UTC, top_level: bool = True):
  399. """
  400. Format Python values in a ClickHouse query
  401. :param value: Python object
  402. :param server_tz: Server timezone for adjusting datetime values
  403. :param top_level: Flag for top level for nested structures
  404. :return: Literal string for python value
  405. """
  406. def recurse(x):
  407. return format_bind_value(x, server_tz, False)
  408. if value is None:
  409. return '\\N'
  410. if isinstance(value, str):
  411. if top_level:
  412. # At the top levels, strings must not be surrounded by quotes
  413. return escape_str(value)
  414. return format_str(value)
  415. if isinstance(value, datetime):
  416. value = value.astimezone(server_tz)
  417. val = value.strftime('%Y-%m-%d %H:%M:%S')
  418. if top_level:
  419. return val
  420. return f"'{val}'"
  421. if isinstance(value, date):
  422. if top_level:
  423. return value.isoformat()
  424. return f"'{value.isoformat()}'"
  425. if isinstance(value, list):
  426. return f"[{', '.join(recurse(x) for x in value)}]"
  427. if isinstance(value, tuple):
  428. return f"({', '.join(recurse(x) for x in value)})"
  429. if isinstance(value, dict):
  430. if common.get_setting('dict_parameter_format') == 'json':
  431. return any_to_json(value).decode()
  432. pairs = [recurse(k) + ':' + recurse(v)
  433. for k, v in value.items()]
  434. return f"{{{', '.join(pairs)}}}"
  435. if isinstance(value, Enum):
  436. return recurse(value.value)
  437. return str(value)
  438. comment_re = re.compile(r"(\".*?\"|\'.*?\')|(/\*.*?\*/|(--\s)[^\n]*$)", re.MULTILINE | re.DOTALL)
  439. def remove_sql_comments(sql: str) -> str:
  440. """
  441. Remove SQL comments. This is useful to determine the type of SQL query, such as SELECT or INSERT, but we
  442. don't fully trust it to correctly ignore weird quoted strings, and other edge cases, so we always pass the
  443. original SQL to ClickHouse (which uses a full-fledged AST/ token parser)
  444. :param sql: SQL query
  445. :return: SQL Query without SQL comments
  446. """
  447. def replacer(match):
  448. # if the 2nd group (capturing comments) is not None, it means we have captured a
  449. # non-quoted, actual comment string, so return nothing to remove the comment
  450. if match.group(2):
  451. return ''
  452. # Otherwise we've actually captured a quoted string, so return it
  453. return match.group(1)
  454. return comment_re.sub(replacer, sql)
  455. def to_arrow(content: bytes):
  456. pyarrow = check_arrow()
  457. reader = pyarrow.ipc.RecordBatchFileReader(content)
  458. return reader.read_all()
  459. def to_arrow_batches(buffer: IOBase) -> StreamContext:
  460. pyarrow = check_arrow()
  461. reader = pyarrow.ipc.open_stream(buffer)
  462. return StreamContext(buffer, reader)
  463. def arrow_buffer(table) -> Tuple[Sequence[str], bytes]:
  464. pyarrow = check_arrow()
  465. sink = pyarrow.BufferOutputStream()
  466. with pyarrow.RecordBatchFileWriter(sink, table.schema) as writer:
  467. writer.write(table)
  468. return table.schema.names, sink.getvalue()