query.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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: str = '',
  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[str] = 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. self.uncommented_query = remove_sql_comments(self.final_query)
  202. class QueryResult(Closable):
  203. """
  204. Wrapper class for query return values and metadata
  205. """
  206. # pylint: disable=too-many-arguments
  207. def __init__(self,
  208. result_set: Matrix = None,
  209. block_gen: Generator[Matrix, None, None] = None,
  210. column_names: Tuple = (),
  211. column_types: Tuple = (),
  212. column_oriented: bool = False,
  213. source: Closable = None,
  214. query_id: str = None,
  215. summary: Dict[str, Any] = None):
  216. self._result_rows = result_set
  217. self._result_columns = None
  218. self._block_gen = block_gen or empty_gen()
  219. self._in_context = False
  220. self._query_id = query_id
  221. self.column_names = column_names
  222. self.column_types = column_types
  223. self.column_oriented = column_oriented
  224. self.source = source
  225. self.summary = {} if summary is None else summary
  226. @property
  227. def result_set(self) -> Matrix:
  228. if self.column_oriented:
  229. return self.result_columns
  230. return self.result_rows
  231. @property
  232. def result_columns(self) -> Matrix:
  233. if self._result_columns is None:
  234. result = [[] for _ in range(len(self.column_names))]
  235. with self.column_block_stream as stream:
  236. for block in stream:
  237. for base, added in zip(result, block):
  238. base.extend(added)
  239. self._result_columns = result
  240. return self._result_columns
  241. @property
  242. def result_rows(self) -> Matrix:
  243. if self._result_rows is None:
  244. result = []
  245. with self.row_block_stream as stream:
  246. for block in stream:
  247. result.extend(block)
  248. self._result_rows = result
  249. return self._result_rows
  250. @property
  251. def query_id(self) -> str:
  252. query_id = self.summary.get('query_id')
  253. if query_id:
  254. return query_id
  255. return self._query_id
  256. def _column_block_stream(self):
  257. if self._block_gen is None:
  258. raise StreamClosedError
  259. block_stream = self._block_gen
  260. self._block_gen = None
  261. return block_stream
  262. def _row_block_stream(self):
  263. for block in self._column_block_stream():
  264. yield list(zip(*block))
  265. @property
  266. def column_block_stream(self) -> StreamContext:
  267. return StreamContext(self, self._column_block_stream())
  268. @property
  269. def row_block_stream(self):
  270. return StreamContext(self, self._row_block_stream())
  271. @property
  272. def rows_stream(self) -> StreamContext:
  273. def stream():
  274. for block in self._row_block_stream():
  275. yield from block
  276. return StreamContext(self, stream())
  277. def named_results(self) -> Generator[dict, None, None]:
  278. for row in zip(*self.result_set) if self.column_oriented else self.result_set:
  279. yield dict(zip(self.column_names, row))
  280. @property
  281. def row_count(self) -> int:
  282. if self.column_oriented:
  283. return 0 if len(self.result_set) == 0 else len(self.result_set[0])
  284. return len(self.result_set)
  285. @property
  286. def first_item(self):
  287. if self.column_oriented:
  288. return {name: col[0] for name, col in zip(self.column_names, self.result_set)}
  289. return dict(zip(self.column_names, self.result_set[0]))
  290. @property
  291. def first_row(self):
  292. if self.column_oriented:
  293. return [col[0] for col in self.result_set]
  294. return self.result_set[0]
  295. def close(self):
  296. if self.source:
  297. self.source.close()
  298. self.source = None
  299. if self._block_gen is not None:
  300. self._block_gen.close()
  301. self._block_gen = None
  302. BS = '\\'
  303. must_escape = (BS, '\'', '`', '\t', '\n')
  304. def quote_identifier(identifier: str):
  305. first_char = identifier[0]
  306. if first_char in ('`', '"') and identifier[-1] == first_char:
  307. # Identifier is already quoted, assume that it's valid
  308. return identifier
  309. return f'`{escape_str(identifier)}`'
  310. def finalize_query(query: str, parameters: Optional[Union[Sequence, Dict[str, Any]]],
  311. server_tz: Optional[tzinfo] = None) -> str:
  312. while query.endswith(';'):
  313. query = query[:-1]
  314. if not parameters:
  315. return query
  316. if hasattr(parameters, 'items'):
  317. return query % {k: format_query_value(v, server_tz) for k, v in parameters.items()}
  318. return query % tuple(format_query_value(v) for v in parameters)
  319. def bind_query(query: str, parameters: Optional[Union[Sequence, Dict[str, Any]]],
  320. server_tz: Optional[tzinfo] = None) -> Tuple[str, Dict[str, str]]:
  321. while query.endswith(';'):
  322. query = query[:-1]
  323. if not parameters:
  324. return query, {}
  325. if external_bind_re.search(query) is None:
  326. return finalize_query(query, parameters, server_tz), {}
  327. return query, {f'param_{k}': format_bind_value(v, server_tz) for k, v in parameters.items()}
  328. def format_str(value: str):
  329. return f"'{escape_str(value)}'"
  330. def escape_str(value: str):
  331. return ''.join(f'{BS}{c}' if c in must_escape else c for c in value)
  332. # pylint: disable=too-many-return-statements
  333. def format_query_value(value: Any, server_tz: tzinfo = pytz.UTC):
  334. """
  335. Format Python values in a ClickHouse query
  336. :param value: Python object
  337. :param server_tz: Server timezone for adjusting datetime values
  338. :return: Literal string for python value
  339. """
  340. if value is None:
  341. return 'NULL'
  342. if isinstance(value, str):
  343. return format_str(value)
  344. if isinstance(value, datetime):
  345. if value.tzinfo is not None or server_tz != pytz.UTC:
  346. value = value.astimezone(server_tz)
  347. return f"'{value.strftime('%Y-%m-%d %H:%M:%S')}'"
  348. if isinstance(value, date):
  349. return f"'{value.isoformat()}'"
  350. if isinstance(value, list):
  351. return f"[{', '.join(str_query_value(x, server_tz) for x in value)}]"
  352. if isinstance(value, tuple):
  353. return f"({', '.join(str_query_value(x, server_tz) for x in value)})"
  354. if isinstance(value, dict):
  355. if common.get_setting('dict_parameter_format') == 'json':
  356. return format_str(any_to_json(value).decode())
  357. pairs = [str_query_value(k, server_tz) + ':' + str_query_value(v, server_tz)
  358. for k, v in value.items()]
  359. return f"{{{', '.join(pairs)}}}"
  360. if isinstance(value, Enum):
  361. return format_query_value(value.value, server_tz)
  362. if isinstance(value, (uuid.UUID, ipaddress.IPv4Address, ipaddress.IPv6Address)):
  363. return f"'{value}'"
  364. return value
  365. def str_query_value(value: Any, server_tz: tzinfo = pytz.UTC):
  366. return str(format_query_value(value, server_tz))
  367. # pylint: disable=too-many-branches
  368. def format_bind_value(value: Any, server_tz: tzinfo = pytz.UTC, top_level: bool = True):
  369. """
  370. Format Python values in a ClickHouse query
  371. :param value: Python object
  372. :param server_tz: Server timezone for adjusting datetime values
  373. :param top_level: Flag for top level for nested structures
  374. :return: Literal string for python value
  375. """
  376. def recurse(x):
  377. return format_bind_value(x, server_tz, False)
  378. if value is None:
  379. return '\\N'
  380. if isinstance(value, str):
  381. if top_level:
  382. # At the top levels, strings must not be surrounded by quotes
  383. return escape_str(value)
  384. return format_str(value)
  385. if isinstance(value, datetime):
  386. value = value.astimezone(server_tz)
  387. val = value.strftime('%Y-%m-%d %H:%M:%S')
  388. if top_level:
  389. return val
  390. return f"'{val}'"
  391. if isinstance(value, date):
  392. if top_level:
  393. return value.isoformat()
  394. return f"'{value.isoformat()}'"
  395. if isinstance(value, list):
  396. return f"[{', '.join(recurse(x) for x in value)}]"
  397. if isinstance(value, tuple):
  398. return f"({', '.join(recurse(x) for x in value)})"
  399. if isinstance(value, dict):
  400. if common.get_setting('dict_parameter_format') == 'json':
  401. return any_to_json(value).decode()
  402. pairs = [recurse(k) + ':' + recurse(v)
  403. for k, v in value.items()]
  404. return f"{{{', '.join(pairs)}}}"
  405. if isinstance(value, Enum):
  406. return recurse(value.value)
  407. return str(value)
  408. comment_re = re.compile(r"(\".*?\"|\'.*?\')|(/\*.*?\*/|(--\s)[^\n]*$)", re.MULTILINE | re.DOTALL)
  409. def remove_sql_comments(sql: str) -> str:
  410. """
  411. Remove SQL comments. This is useful to determine the type of SQL query, such as SELECT or INSERT, but we
  412. don't fully trust it to correctly ignore weird quoted strings, and other edge cases, so we always pass the
  413. original SQL to ClickHouse (which uses a full-fledged AST/ token parser)
  414. :param sql: SQL query
  415. :return: SQL Query without SQL comments
  416. """
  417. def replacer(match):
  418. # if the 2nd group (capturing comments) is not None, it means we have captured a
  419. # non-quoted, actual comment string, so return nothing to remove the comment
  420. if match.group(2):
  421. return ''
  422. # Otherwise we've actually captured a quoted string, so return it
  423. return match.group(1)
  424. return comment_re.sub(replacer, sql)
  425. def to_arrow(content: bytes):
  426. pyarrow = check_arrow()
  427. reader = pyarrow.ipc.RecordBatchFileReader(content)
  428. return reader.read_all()
  429. def to_arrow_batches(buffer: IOBase) -> StreamContext:
  430. pyarrow = check_arrow()
  431. reader = pyarrow.ipc.open_stream(buffer)
  432. return StreamContext(buffer, reader)
  433. def arrow_buffer(table) -> Tuple[Sequence[str], bytes]:
  434. pyarrow = check_arrow()
  435. sink = pyarrow.BufferOutputStream()
  436. with pyarrow.RecordBatchFileWriter(sink, table.schema) as writer:
  437. writer.write(table)
  438. return table.schema.names, sink.getvalue()