query.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import logging
  2. import re
  3. import pytz
  4. from io import IOBase
  5. from typing import Any, Tuple, Dict, Sequence, Optional, Union, Generator
  6. from datetime import tzinfo
  7. from pytz.exceptions import UnknownTimeZoneError
  8. from clickhouse_connect.driver import tzutil
  9. from clickhouse_connect.driver.binding import bind_query
  10. from clickhouse_connect.driver.common import dict_copy, empty_gen, StreamContext
  11. from clickhouse_connect.driver.external import ExternalData
  12. from clickhouse_connect.driver.types import Matrix, Closable
  13. from clickhouse_connect.driver.exceptions import StreamClosedError, ProgrammingError
  14. from clickhouse_connect.driver.options import check_arrow, pd_extended_dtypes
  15. from clickhouse_connect.driver.context import BaseQueryContext
  16. logger = logging.getLogger(__name__)
  17. commands = 'CREATE|ALTER|SYSTEM|GRANT|REVOKE|CHECK|DETACH|ATTACH|DROP|DELETE|KILL|' + \
  18. 'OPTIMIZE|SET|RENAME|TRUNCATE|USE'
  19. limit_re = re.compile(r'\s+LIMIT($|\s)', re.IGNORECASE)
  20. select_re = re.compile(r'(^|\s)SELECT\s', re.IGNORECASE)
  21. insert_re = re.compile(r'(^|\s)INSERT\s*INTO', re.IGNORECASE)
  22. command_re = re.compile(r'(^\s*)(' + commands + r')\s', re.IGNORECASE)
  23. # pylint: disable=too-many-instance-attributes
  24. class QueryContext(BaseQueryContext):
  25. """
  26. Argument/parameter object for queries. This context is used to set thread/query specific formats
  27. """
  28. # pylint: disable=duplicate-code,too-many-arguments,too-many-positional-arguments,too-many-locals
  29. def __init__(self,
  30. query: Union[str, bytes] = '',
  31. parameters: Optional[Dict[str, Any]] = None,
  32. settings: Optional[Dict[str, Any]] = None,
  33. query_formats: Optional[Dict[str, str]] = None,
  34. column_formats: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
  35. encoding: Optional[str] = None,
  36. server_tz: tzinfo = pytz.UTC,
  37. use_none: Optional[bool] = None,
  38. column_oriented: Optional[bool] = None,
  39. use_numpy: Optional[bool] = None,
  40. max_str_len: Optional[int] = 0,
  41. query_tz: Optional[Union[str, tzinfo]] = None,
  42. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  43. use_extended_dtypes: Optional[bool] = None,
  44. as_pandas: bool = False,
  45. streaming: bool = False,
  46. apply_server_tz: bool = False,
  47. external_data: Optional[ExternalData] = None):
  48. """
  49. Initializes various configuration settings for the query context
  50. :param query: Query string with Python style format value replacements
  51. :param parameters: Optional dictionary of substitution values
  52. :param settings: Optional ClickHouse settings for the query
  53. :param query_formats: Optional dictionary of query formats with the key of a ClickHouse type name
  54. (with * wildcards) and a value of valid query formats for those types.
  55. The value 'encoding' can be sent to change the expected encoding for this query, with a value of
  56. the desired encoding such as `latin-1`
  57. :param column_formats: Optional dictionary of column specific formats. The key is the column name,
  58. The value is either the format for the data column (such as 'string' for a UUID column) or a
  59. second level "format" dictionary of a ClickHouse type name and a value of query formats. This
  60. secondary dictionary can be used for nested column types such as Tuples or Maps
  61. :param encoding: Optional string encoding for this query, such as 'latin-1'
  62. :param column_formats: Optional dictionary
  63. :param use_none: Use a Python None for ClickHouse NULL values in nullable columns. Otherwise the default
  64. value of the column (such as 0 for numbers) will be returned in the result_set
  65. :param max_str_len Limit returned ClickHouse String values to this length, which allows a Numpy
  66. structured array even with ClickHouse variable length String columns. If 0, Numpy arrays for
  67. String columns will always be object arrays
  68. :param query_tz Either a string or a pytz tzinfo object. (Strings will be converted to tzinfo objects).
  69. Values for any DateTime or DateTime64 column in the query will be converted to Python datetime.datetime
  70. objects with the selected timezone
  71. :param column_tzs A dictionary of column names to tzinfo objects (or strings that will be converted to
  72. tzinfo objects). The timezone will be applied to datetime objects returned in the query
  73. """
  74. super().__init__(settings,
  75. query_formats,
  76. column_formats,
  77. encoding,
  78. use_extended_dtypes if use_extended_dtypes is not None else False,
  79. use_numpy if use_numpy is not None else False)
  80. self.query = query
  81. self.parameters = parameters or {}
  82. self.use_none = True if use_none is None else use_none
  83. self.column_oriented = False if column_oriented is None else column_oriented
  84. self.use_numpy = use_numpy
  85. self.max_str_len = 0 if max_str_len is None else max_str_len
  86. self.server_tz = server_tz
  87. self.apply_server_tz = apply_server_tz
  88. self.external_data = external_data
  89. if isinstance(query_tz, str):
  90. try:
  91. query_tz = pytz.timezone(query_tz)
  92. except UnknownTimeZoneError as ex:
  93. raise ProgrammingError(f'query_tz {query_tz} is not recognized') from ex
  94. self.query_tz = query_tz
  95. if column_tzs is not None:
  96. for col_name, timezone in column_tzs.items():
  97. if isinstance(timezone, str):
  98. try:
  99. timezone = pytz.timezone(timezone)
  100. column_tzs[col_name] = timezone
  101. except UnknownTimeZoneError as ex:
  102. raise ProgrammingError(f'column_tz {timezone} is not recognized') from ex
  103. self.column_tzs = column_tzs
  104. self.column_tz = None
  105. self.response_tz = None
  106. self.block_info = False
  107. self.as_pandas = as_pandas
  108. self.use_pandas_na = as_pandas and pd_extended_dtypes
  109. self.streaming = streaming
  110. self._update_query()
  111. @property
  112. def is_select(self) -> bool:
  113. return select_re.search(self.uncommented_query) is not None
  114. @property
  115. def has_limit(self) -> bool:
  116. return limit_re.search(self.uncommented_query) is not None
  117. @property
  118. def is_insert(self) -> bool:
  119. return insert_re.search(self.uncommented_query) is not None
  120. @property
  121. def is_command(self) -> bool:
  122. return command_re.search(self.uncommented_query) is not None
  123. def set_parameters(self, parameters: Dict[str, Any]):
  124. self.parameters = parameters
  125. self._update_query()
  126. def set_parameter(self, key: str, value: Any):
  127. if not self.parameters:
  128. self.parameters = {}
  129. self.parameters[key] = value
  130. self._update_query()
  131. def set_response_tz(self, response_tz: tzinfo):
  132. self.response_tz = response_tz
  133. def start_column(self, name: str):
  134. super().start_column(name)
  135. if self.column_tzs and name in self.column_tzs:
  136. self.column_tz = self.column_tzs[name]
  137. else:
  138. self.column_tz = None
  139. def active_tz(self, datatype_tz: Optional[tzinfo]):
  140. if self.column_tz:
  141. active_tz = self.column_tz
  142. elif datatype_tz:
  143. active_tz = datatype_tz
  144. elif self.query_tz:
  145. active_tz = self.query_tz
  146. elif self.response_tz:
  147. active_tz = self.response_tz
  148. elif self.apply_server_tz:
  149. active_tz = self.server_tz
  150. else:
  151. active_tz = tzutil.local_tz
  152. if active_tz == pytz.UTC:
  153. return None
  154. return active_tz
  155. # pylint disable=too-many-positional-arguments
  156. def updated_copy(self,
  157. query: Optional[Union[str, bytes]] = None,
  158. parameters: Optional[Dict[str, Any]] = None,
  159. settings: Optional[Dict[str, Any]] = None,
  160. query_formats: Optional[Dict[str, str]] = None,
  161. column_formats: Optional[Dict[str, Union[str, Dict[str, str]]]] = None,
  162. encoding: Optional[str] = None,
  163. server_tz: Optional[tzinfo] = None,
  164. use_none: Optional[bool] = None,
  165. column_oriented: Optional[bool] = None,
  166. use_numpy: Optional[bool] = None,
  167. max_str_len: Optional[int] = None,
  168. query_tz: Optional[Union[str, tzinfo]] = None,
  169. column_tzs: Optional[Dict[str, Union[str, tzinfo]]] = None,
  170. use_extended_dtypes: Optional[bool] = None,
  171. as_pandas: bool = False,
  172. streaming: bool = False,
  173. external_data: Optional[ExternalData] = None) -> 'QueryContext':
  174. """
  175. Creates Query context copy with parameters overridden/updated as appropriate.
  176. """
  177. return QueryContext(query or self.query,
  178. dict_copy(self.parameters, parameters),
  179. dict_copy(self.settings, settings),
  180. dict_copy(self.query_formats, query_formats),
  181. dict_copy(self.column_formats, column_formats),
  182. encoding if encoding else self.encoding,
  183. server_tz if server_tz else self.server_tz,
  184. self.use_none if use_none is None else use_none,
  185. self.column_oriented if column_oriented is None else column_oriented,
  186. self.use_numpy if use_numpy is None else use_numpy,
  187. self.max_str_len if max_str_len is None else max_str_len,
  188. self.query_tz if query_tz is None else query_tz,
  189. self.column_tzs if column_tzs is None else column_tzs,
  190. self.use_extended_dtypes if use_extended_dtypes is None else use_extended_dtypes,
  191. as_pandas,
  192. streaming,
  193. self.apply_server_tz,
  194. self.external_data if external_data is None else external_data)
  195. def _update_query(self):
  196. self.final_query, self.bind_params = bind_query(self.query, self.parameters, self.server_tz)
  197. if isinstance(self.final_query, bytes):
  198. # If we've embedded binary data in the query, all bets are off, and we check the original query for comments
  199. self.uncommented_query = remove_sql_comments(self.query)
  200. else:
  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. comment_re = re.compile(r"(\".*?\"|\'.*?\')|(/\*.*?\*/|(--\s)[^\n]*$)", re.MULTILINE | re.DOTALL)
  303. def remove_sql_comments(sql: str) -> str:
  304. """
  305. Remove SQL comments. This is useful to determine the type of SQL query, such as SELECT or INSERT, but we
  306. don't fully trust it to correctly ignore weird quoted strings, and other edge cases, so we always pass the
  307. original SQL to ClickHouse (which uses a full-fledged AST/ token parser)
  308. :param sql: SQL query
  309. :return: SQL Query without SQL comments
  310. """
  311. def replacer(match):
  312. # if the 2nd group (capturing comments) is not None, it means we have captured a
  313. # non-quoted, actual comment string, so return nothing to remove the comment
  314. if match.group(2):
  315. return ''
  316. # Otherwise we've actually captured a quoted string, so return it
  317. return match.group(1)
  318. return comment_re.sub(replacer, sql)
  319. def to_arrow(content: bytes):
  320. pyarrow = check_arrow()
  321. reader = pyarrow.ipc.RecordBatchFileReader(content)
  322. return reader.read_all()
  323. def to_arrow_batches(buffer: IOBase) -> StreamContext:
  324. pyarrow = check_arrow()
  325. reader = pyarrow.ipc.open_stream(buffer)
  326. return StreamContext(buffer, reader)
  327. def arrow_buffer(table, compression: Optional[str] = None) -> Tuple[Sequence[str], bytes]:
  328. pyarrow = check_arrow()
  329. options = None
  330. if compression in ('zstd', 'lz4'):
  331. options = pyarrow.ipc.IpcWriteOptions(compression=pyarrow.Codec(compression=compression))
  332. sink = pyarrow.BufferOutputStream()
  333. with pyarrow.RecordBatchFileWriter(sink, table.schema, options=options) as writer:
  334. writer.write(table)
  335. return table.schema.names, sink.getvalue()