query.py 20 KB

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