query.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. import ipaddress
  2. import logging
  3. import re
  4. import uuid
  5. import pytz
  6. from enum import Enum
  7. from typing import Any, Tuple, Dict, Sequence, Optional, Union, Generator
  8. from datetime import date, datetime, tzinfo
  9. from pytz.exceptions import UnknownTimeZoneError
  10. from clickhouse_connect import common
  11. from clickhouse_connect.driver.common import dict_copy, empty_gen, StreamContext
  12. from clickhouse_connect.driver.external import ExternalData
  13. from clickhouse_connect.driver.types import Matrix, Closable
  14. from clickhouse_connect.json_impl import any_to_json
  15. from clickhouse_connect.driver.exceptions import StreamClosedError, ProgrammingError
  16. from clickhouse_connect.driver.options import check_arrow, pd_extended_dtypes
  17. from clickhouse_connect.driver.context import BaseQueryContext
  18. logger = logging.getLogger(__name__)
  19. commands = 'CREATE|ALTER|SYSTEM|GRANT|REVOKE|CHECK|DETACH|ATTACH|DROP|DELETE|KILL|' + \
  20. 'OPTIMIZE|SET|RENAME|TRUNCATE|USE'
  21. limit_re = re.compile(r'\s+LIMIT($|\s)', re.IGNORECASE)
  22. select_re = re.compile(r'(^|\s)SELECT\s', re.IGNORECASE)
  23. insert_re = re.compile(r'(^|\s)INSERT\s*INTO', re.IGNORECASE)
  24. command_re = re.compile(r'(^\s*)(' + commands + r')\s', re.IGNORECASE)
  25. external_bind_re = re.compile(r'{.+:.+}')
  26. # pylint: disable=too-many-instance-attributes
  27. class QueryContext(BaseQueryContext):
  28. """
  29. Argument/parameter object for queries. This context is used to set thread/query specific formats
  30. """
  31. # pylint: disable=duplicate-code,too-many-arguments,too-many-locals
  32. def __init__(self,
  33. query: str = '',
  34. parameters: Optional[Dict[str, Any]] = None,
  35. settings: Optional[Dict[str, Any]] = None,
  36. query_formats: Optional[Dict[str, str]] = None,
  37. column_formats: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
  38. encoding: Optional[str] = None,
  39. server_tz: tzinfo = pytz.UTC,
  40. use_none: Optional[bool] = None,
  41. column_oriented: Optional[bool] = None,
  42. use_numpy: Optional[bool] = None,
  43. max_str_len: Optional[int] = 0,
  44. query_tz: Optional[Union[str, tzinfo]] = None,
  45. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  46. use_extended_dtypes: Optional[bool] = None,
  47. as_pandas: bool = False,
  48. streaming: bool = False,
  49. apply_server_tz: bool = False,
  50. external_data: Optional[ExternalData] = None):
  51. """
  52. Initializes various configuration settings for the query context
  53. :param query: Query string with Python style format value replacements
  54. :param parameters: Optional dictionary of substitution values
  55. :param settings: Optional ClickHouse settings for the query
  56. :param query_formats: Optional dictionary of query formats with the key of a ClickHouse type name
  57. (with * wildcards) and a value of valid query formats for those types.
  58. The value 'encoding' can be sent to change the expected encoding for this query, with a value of
  59. the desired encoding such as `latin-1`
  60. :param column_formats: Optional dictionary of column specific formats. The key is the column name,
  61. The value is either the format for the data column (such as 'string' for a UUID column) or a
  62. second level "format" dictionary of a ClickHouse type name and a value of query formats. This
  63. secondary dictionary can be used for nested column types such as Tuples or Maps
  64. :param encoding: Optional string encoding for this query, such as 'latin-1'
  65. :param column_formats: Optional dictionary
  66. :param use_none: Use a Python None for ClickHouse NULL values in nullable columns. Otherwise the default
  67. value of the column (such as 0 for numbers) will be returned in the result_set
  68. :param max_str_len Limit returned ClickHouse String values to this length, which allows a Numpy
  69. structured array even with ClickHouse variable length String columns. If 0, Numpy arrays for
  70. String columns will always be object arrays
  71. :param query_tz Either a string or a pytz tzinfo object. (Strings will be converted to tzinfo objects).
  72. Values for any DateTime or DateTime64 column in the query will be converted to Python datetime.datetime
  73. objects with the selected timezone
  74. :param column_tzs A dictionary of column names to tzinfo objects (or strings that will be converted to
  75. tzinfo objects). The timezone will be applied to datetime objects returned in the query
  76. """
  77. super().__init__(settings,
  78. query_formats,
  79. column_formats,
  80. encoding,
  81. use_extended_dtypes if use_extended_dtypes is not None else False,
  82. use_numpy if use_numpy is not None else False)
  83. self.query = query
  84. self.parameters = parameters or {}
  85. self.use_none = True if use_none is None else use_none
  86. self.column_oriented = False if column_oriented is None else column_oriented
  87. self.use_numpy = use_numpy
  88. self.max_str_len = 0 if max_str_len is None else max_str_len
  89. self.server_tz = server_tz
  90. self.apply_server_tz = apply_server_tz
  91. self.external_data = external_data
  92. if isinstance(query_tz, str):
  93. try:
  94. query_tz = pytz.timezone(query_tz)
  95. except UnknownTimeZoneError as ex:
  96. raise ProgrammingError(f'query_tz {query_tz} is not recognized') from ex
  97. self.query_tz = query_tz
  98. if column_tzs is not None:
  99. for col_name, timezone in column_tzs.items():
  100. if isinstance(timezone, str):
  101. try:
  102. timezone = pytz.timezone(timezone)
  103. column_tzs[col_name] = timezone
  104. except UnknownTimeZoneError as ex:
  105. raise ProgrammingError(f'column_tz {timezone} is not recognized') from ex
  106. self.column_tzs = column_tzs
  107. self.column_tz = None
  108. self.response_tz = None
  109. self.block_info = False
  110. self.as_pandas = as_pandas
  111. self.use_pandas_na = as_pandas and pd_extended_dtypes
  112. self.streaming = streaming
  113. self._update_query()
  114. @property
  115. def is_select(self) -> bool:
  116. return select_re.search(self.uncommented_query) is not None
  117. @property
  118. def has_limit(self) -> bool:
  119. return limit_re.search(self.uncommented_query) is not None
  120. @property
  121. def is_insert(self) -> bool:
  122. return insert_re.search(self.uncommented_query) is not None
  123. @property
  124. def is_command(self) -> bool:
  125. return command_re.search(self.uncommented_query) is not None
  126. def set_parameters(self, parameters: Dict[str, Any]):
  127. self.parameters = parameters
  128. self._update_query()
  129. def set_parameter(self, key: str, value: Any):
  130. if not self.parameters:
  131. self.parameters = {}
  132. self.parameters[key] = value
  133. self._update_query()
  134. def set_response_tz(self, response_tz: tzinfo):
  135. self.response_tz = response_tz
  136. def start_column(self, name: str):
  137. super().start_column(name)
  138. if self.column_tzs and name in self.column_tzs:
  139. self.column_tz = self.column_tzs[name]
  140. else:
  141. self.column_tz = None
  142. def active_tz(self, datatype_tz: Optional[tzinfo]):
  143. if self.column_tz:
  144. active_tz = self.column_tz
  145. elif datatype_tz:
  146. active_tz = datatype_tz
  147. elif self.query_tz:
  148. active_tz = self.query_tz
  149. elif self.response_tz:
  150. active_tz = self.response_tz
  151. elif self.apply_server_tz:
  152. active_tz = self.server_tz
  153. else:
  154. active_tz = self.local_tz
  155. # Special case where if everything is UTC, including the local timezone, we use naive timezones
  156. # for performance reasons
  157. if active_tz == pytz.UTC and active_tz.utcoffset(datetime.now()) == self.local_tz.utcoffset(datetime.now()):
  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. for row in block:
  276. yield row
  277. return StreamContext(self, stream())
  278. def named_results(self) -> Generator[dict, None, None]:
  279. for row in zip(*self.result_set) if self.column_oriented else self.result_set:
  280. yield dict(zip(self.column_names, row))
  281. @property
  282. def row_count(self) -> int:
  283. if self.column_oriented:
  284. return 0 if len(self.result_set) == 0 else len(self.result_set[0])
  285. return len(self.result_set)
  286. @property
  287. def first_item(self):
  288. if self.column_oriented:
  289. return {name: col[0] for name, col in zip(self.column_names, self.result_set)}
  290. return dict(zip(self.column_names, self.result_set[0]))
  291. @property
  292. def first_row(self):
  293. if self.column_oriented:
  294. return [col[0] for col in self.result_set]
  295. return self.result_set[0]
  296. def close(self):
  297. if self.source:
  298. self.source.close()
  299. self.source = None
  300. if self._block_gen is not None:
  301. self._block_gen.close()
  302. self._block_gen = None
  303. BS = '\\'
  304. must_escape = (BS, '\'', '`')
  305. def quote_identifier(identifier: str):
  306. first_char = identifier[0]
  307. if first_char in ('`', '"') and identifier[-1] == first_char:
  308. # Identifier is already quoted, assume that it's valid
  309. return identifier
  310. return f'`{escape_str(identifier)}`'
  311. def finalize_query(query: str, parameters: Optional[Union[Sequence, Dict[str, Any]]],
  312. server_tz: Optional[tzinfo] = None) -> str:
  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. if not parameters:
  321. return query, {}
  322. if external_bind_re.search(query) is None:
  323. return finalize_query(query, parameters, server_tz), {}
  324. return query, {f'param_{k}': format_bind_value(v, server_tz) for k, v in parameters.items()}
  325. def format_str(value: str):
  326. return f"'{escape_str(value)}'"
  327. def escape_str(value: str):
  328. return ''.join(f'{BS}{c}' if c in must_escape else c for c in value)
  329. # pylint: disable=too-many-return-statements
  330. def format_query_value(value: Any, server_tz: tzinfo = pytz.UTC):
  331. """
  332. Format Python values in a ClickHouse query
  333. :param value: Python object
  334. :param server_tz: Server timezone for adjusting datetime values
  335. :return: Literal string for python value
  336. """
  337. if value is None:
  338. return 'NULL'
  339. if isinstance(value, str):
  340. return format_str(value)
  341. if isinstance(value, datetime):
  342. if value.tzinfo is not None or server_tz != pytz.UTC:
  343. value = value.astimezone(server_tz)
  344. return f"'{value.strftime('%Y-%m-%d %H:%M:%S')}'"
  345. if isinstance(value, date):
  346. return f"'{value.isoformat()}'"
  347. if isinstance(value, list):
  348. return f"[{', '.join(format_query_value(x, server_tz) for x in value)}]"
  349. if isinstance(value, tuple):
  350. return f"({', '.join(format_query_value(x, server_tz) for x in value)})"
  351. if isinstance(value, dict):
  352. if common.get_setting('dict_parameter_format') == 'json':
  353. return format_str(any_to_json(value).decode())
  354. pairs = [format_query_value(k, server_tz) + ':' + format_query_value(v, server_tz)
  355. for k, v in value.items()]
  356. return f"{{{', '.join(pairs)}}}"
  357. if isinstance(value, Enum):
  358. return format_query_value(value.value, server_tz)
  359. if isinstance(value, (uuid.UUID, ipaddress.IPv4Address, ipaddress.IPv6Address)):
  360. return f"'{value}'"
  361. return str(value)
  362. # pylint: disable=too-many-branches
  363. def format_bind_value(value: Any, server_tz: tzinfo = pytz.UTC, top_level: bool = True):
  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. :param top_level: Flag for top level for nested structures
  369. :return: Literal string for python value
  370. """
  371. def recurse(x):
  372. return format_bind_value(x, server_tz, False)
  373. if value is None:
  374. return '\\N'
  375. if isinstance(value, str):
  376. if top_level:
  377. # At the top levels, strings must not be surrounded by quotes
  378. return escape_str(value)
  379. return format_str(value)
  380. if isinstance(value, datetime):
  381. if value.tzinfo is None:
  382. value = value.replace(tzinfo=server_tz)
  383. val = value.strftime('%Y-%m-%d %H:%M:%S')
  384. if top_level:
  385. return val
  386. return f"'{val}'"
  387. if isinstance(value, date):
  388. if top_level:
  389. return value.isoformat()
  390. return f"'{value.isoformat()}'"
  391. if isinstance(value, list):
  392. return f"[{', '.join(recurse(x) for x in value)}]"
  393. if isinstance(value, tuple):
  394. return f"({', '.join(recurse(x) for x in value)})"
  395. if isinstance(value, dict):
  396. if common.get_setting('dict_parameter_format') == 'json':
  397. return any_to_json(value).decode()
  398. pairs = [recurse(k) + ':' + recurse(v)
  399. for k, v in value.items()]
  400. return f"{{{', '.join(pairs)}}}"
  401. if isinstance(value, Enum):
  402. return recurse(value.value)
  403. return str(value)
  404. comment_re = re.compile(r"(\".*?\"|\'.*?\')|(/\*.*?\*/|(--\s)[^\n]*$)", re.MULTILINE | re.DOTALL)
  405. def remove_sql_comments(sql: str) -> str:
  406. """
  407. Remove SQL comments. This is useful to determine the type of SQL query, such as SELECT or INSERT, but we
  408. don't fully trust it to correctly ignore weird quoted strings, and other edge cases, so we always pass the
  409. original SQL to ClickHouse (which uses a full-fledged AST/ token parser)
  410. :param sql: SQL query
  411. :return: SQL Query without SQL comments
  412. """
  413. def replacer(match):
  414. # if the 2nd group (capturing comments) is not None, it means we have captured a
  415. # non-quoted, actual comment string, so return nothing to remove the comment
  416. if match.group(2):
  417. return ''
  418. # Otherwise we've actually captured a quoted string, so return it
  419. return match.group(1)
  420. return comment_re.sub(replacer, sql)
  421. def to_arrow(content: bytes):
  422. pyarrow = check_arrow()
  423. reader = pyarrow.ipc.RecordBatchFileReader(content)
  424. return reader.read_all()
  425. def arrow_buffer(table) -> Tuple[Sequence[str], bytes]:
  426. pyarrow = check_arrow()
  427. sink = pyarrow.BufferOutputStream()
  428. with pyarrow.RecordBatchFileWriter(sink, table.schema) as writer:
  429. writer.write(table)
  430. return table.schema.names, sink.getvalue()