asynch 0.2.2__tar.gz → 0.2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. {asynch-0.2.2 → asynch-0.2.4}/CHANGELOG.md +7 -0
  2. {asynch-0.2.2 → asynch-0.2.4}/PKG-INFO +11 -2
  3. {asynch-0.2.2 → asynch-0.2.4}/README.md +7 -0
  4. {asynch-0.2.2 → asynch-0.2.4}/asynch/connection.py +2 -4
  5. {asynch-0.2.2 → asynch-0.2.4}/asynch/cursors.py +21 -20
  6. {asynch-0.2.2 → asynch-0.2.4}/asynch/pool.py +31 -8
  7. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/__init__.py +5 -2
  8. asynch-0.2.4/asynch/proto/columns/datecolumn.py +77 -0
  9. asynch-0.2.4/asynch/proto/columns/jsoncolumn.py +34 -0
  10. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/compression/__init__.py +14 -3
  11. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/connection.py +16 -10
  12. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/context.py +6 -2
  13. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/settings/__init__.py +0 -1
  14. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/streams/buffered.py +41 -52
  15. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/streams/compressed.py +2 -3
  16. {asynch-0.2.2 → asynch-0.2.4}/pyproject.toml +15 -11
  17. asynch-0.2.2/asynch/proto/columns/datecolumn.py +0 -48
  18. asynch-0.2.2/setup.py +0 -36
  19. {asynch-0.2.2 → asynch-0.2.4}/LICENSE +0 -0
  20. {asynch-0.2.2 → asynch-0.2.4}/asynch/__init__.py +0 -0
  21. {asynch-0.2.2 → asynch-0.2.4}/asynch/errors.py +0 -0
  22. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/__init__.py +0 -0
  23. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/block.py +0 -0
  24. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/arraycolumn.py +0 -0
  25. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/base.py +0 -0
  26. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/boolcolumn.py +0 -0
  27. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/datetimecolumn.py +0 -0
  28. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/decimalcolumn.py +0 -0
  29. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/enumcolumn.py +0 -0
  30. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/floatcolumn.py +0 -0
  31. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/intcolumn.py +0 -0
  32. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/intervalcolumn.py +0 -0
  33. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/ipcolumn.py +0 -0
  34. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/lowcardinalitycolumn.py +0 -0
  35. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/mapcolumn.py +0 -0
  36. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/nestedcolumn.py +0 -0
  37. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/nothingcolumn.py +0 -0
  38. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/nullablecolumn.py +0 -0
  39. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/nullcolumn.py +0 -0
  40. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/simpleaggregatefunctioncolumn.py +0 -0
  41. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/stringcolumn.py +0 -0
  42. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/tuplecolumn.py +0 -0
  43. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/util.py +0 -0
  44. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/columns/uuidcolumn.py +0 -0
  45. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/compression/lz4.py +0 -0
  46. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/compression/lz4hc.py +0 -0
  47. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/compression/zstd.py +0 -0
  48. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/constants.py +0 -0
  49. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/cs.py +0 -0
  50. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/opentelemetry.py +0 -0
  51. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/progress.py +0 -0
  52. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/protocol.py +0 -0
  53. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/result.py +0 -0
  54. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/settings/available.py +0 -0
  55. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/settings/types.py +0 -0
  56. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/streams/__init__.py +0 -0
  57. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/streams/block.py +0 -0
  58. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/utils/__init__.py +0 -0
  59. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/utils/compat.py +0 -0
  60. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/utils/escape.py +0 -0
  61. {asynch-0.2.2 → asynch-0.2.4}/asynch/proto/utils/helpers.py +0 -0
@@ -2,6 +2,13 @@
2
2
 
3
3
  ## 0.2
4
4
 
5
+ ### 0.2.3
6
+
7
+ - Support json column. (#73)
8
+ - Fix connection with `secure=True` and `verify=False`.
9
+ - Fix compression.
10
+ - Fix exception `Cannot set verify_mode to CERT_NONE when check_hostname is enabled`.
11
+
5
12
  ### 0.2.2
6
13
 
7
14
  - Add `Int128Column`, `Int256Column`, `UInt128Column`, `UInt256Column`, `Decimal256Column`. (#57)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: asynch
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: A asyncio driver for ClickHouse with native tcp protocol
5
5
  Home-page: https://github.com/long2ice/asynch
6
6
  License: Apache-2.0
@@ -15,8 +15,10 @@ Classifier: Programming Language :: Python :: 3.8
15
15
  Classifier: Programming Language :: Python :: 3.9
16
16
  Classifier: Programming Language :: Python :: 3.10
17
17
  Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Provides-Extra: compression
18
20
  Requires-Dist: ciso8601
19
- Requires-Dist: clickhouse-cityhash
21
+ Requires-Dist: clickhouse-cityhash ; extra == "compression"
20
22
  Requires-Dist: leb128
21
23
  Requires-Dist: lz4
22
24
  Requires-Dist: pytz
@@ -43,6 +45,13 @@ Description-Content-Type: text/markdown
43
45
  > pip install asynch
44
46
  ```
45
47
 
48
+ or if you want to install [`clickhouse-cityhash`](https://pypi.org/project/clickhouse-cityhash/) to enable
49
+ transport compression
50
+
51
+ ```shell
52
+ > pip install asynch[compression]
53
+ ```
54
+
46
55
  ## Usage
47
56
 
48
57
  Connect to ClickHouse
@@ -15,6 +15,13 @@
15
15
  > pip install asynch
16
16
  ```
17
17
 
18
+ or if you want to install [`clickhouse-cityhash`](https://pypi.org/project/clickhouse-cityhash/) to enable
19
+ transport compression
20
+
21
+ ```shell
22
+ > pip install asynch[compression]
23
+ ```
24
+
18
25
  ## Usage
19
26
 
20
27
  Connect to ClickHouse
@@ -33,7 +33,6 @@ class Connection:
33
33
  self._is_closed = False
34
34
  self._echo = echo
35
35
  self._cursor_cls = cursor_cls
36
- self._connected = False
37
36
  if dsn:
38
37
  self._connection = ProtoConnection(
39
38
  **self._parse_dsn(dsn), stack_track=stack_track, **kwargs
@@ -54,7 +53,7 @@ class Connection:
54
53
 
55
54
  @property
56
55
  def connected(self):
57
- return self._connected
56
+ return self._connection.connected
58
57
 
59
58
  @property
60
59
  def host(self):
@@ -93,10 +92,9 @@ class Connection:
93
92
  raise errors.NotSupportedError
94
93
 
95
94
  async def connect(self):
96
- if self._connected:
95
+ if self.connected:
97
96
  return
98
97
  await self._connection.connect()
99
- self._connected = True
100
98
 
101
99
  def cursor(self, cursor: Type[Cursor] = None) -> Cursor:
102
100
  cursor_cls = cursor or self._cursor_cls
@@ -43,11 +43,7 @@ class Cursor:
43
43
  """Does nothing, required by DB API."""
44
44
 
45
45
  async def close(self):
46
- conn = self._connection
47
- if conn is None:
48
- return
49
- await self._connection.close()
50
- self._connection = None
46
+ self._state = self._states.CURSOR_CLOSED
51
47
 
52
48
  async def execute(
53
49
  self,
@@ -249,12 +245,15 @@ class Cursor:
249
245
 
250
246
  return execute, execute_kwargs
251
247
 
252
- def __iter__(self):
248
+ def __aiter__(self):
249
+ return self
250
+
251
+ async def __anext__(self):
253
252
  while True:
254
- one = self.fetchone()
253
+ one = await self.fetchone()
255
254
  if one is None:
256
- return
257
- yield one
255
+ raise StopAsyncIteration
256
+ return one
258
257
 
259
258
  async def __aexit__(self, exc_type, exc_val, exc_tb):
260
259
  await self.close()
@@ -281,11 +280,13 @@ class Cursor:
281
280
 
282
281
  def _check_query_executing(self):
283
282
  if self._connection._connection.is_query_executing:
284
- raise ProgrammingError("records have not fetched, fetch all before execute next")
283
+ raise ProgrammingError(
284
+ "some records have not been fetched. fetch the remaining records before executing the next query"
285
+ )
285
286
 
286
287
  def _check_cursor_closed(self):
287
288
  if self._state == self._states.CURSOR_CLOSED:
288
- raise InterfaceError("cursor already closed")
289
+ raise InterfaceError("cursor is already closed")
289
290
 
290
291
  def _begin_query(self):
291
292
  self._state = self._states.RUNNING
@@ -355,21 +356,21 @@ class Cursor:
355
356
  class DictCursor(Cursor):
356
357
  async def fetchone(self):
357
358
  row = await super(DictCursor, self).fetchone()
358
- if self._columns and row:
359
- return dict(zip(self._columns, row))
359
+ if self._columns:
360
+ return dict(zip(self._columns, row)) if row else {}
360
361
  else:
361
- raise AttributeError("Not fould valid columns")
362
+ raise AttributeError("Invalid columns.")
362
363
 
363
364
  async def fetchmany(self, size: int):
364
365
  rows = await super(DictCursor, self).fetchmany(size)
365
- if self._columns and rows:
366
- return [dict(zip(self._columns, item)) for item in rows]
366
+ if self._columns:
367
+ return [dict(zip(self._columns, item)) for item in rows] if rows else []
367
368
  else:
368
- raise AttributeError("Not fould valid columns")
369
+ raise AttributeError("Invalid columns.")
369
370
 
370
371
  async def fetchall(self):
371
372
  rows = await super(DictCursor, self).fetchall()
372
- if self._columns and rows:
373
- return [dict(zip(self._columns, item)) for item in rows]
373
+ if self._columns:
374
+ return [dict(zip(self._columns, item)) for item in rows] if rows else []
374
375
  else:
375
- raise AttributeError("Not fould valid columns")
376
+ raise AttributeError("Invalid columns.")
@@ -1,11 +1,14 @@
1
1
  import asyncio
2
2
  import collections
3
+ import logging
3
4
  from asyncio import Condition
4
5
  from collections.abc import Coroutine
5
6
  from typing import Deque, Set
6
7
 
7
8
  from asynch.connection import Connection, connect
8
9
 
10
+ logger = logging.getLogger(__name__)
11
+
9
12
 
10
13
  class _ContextManager(Coroutine):
11
14
  __slots__ = ("_coro", "_obj")
@@ -144,8 +147,9 @@ class Pool(asyncio.AbstractServer):
144
147
  if self._closing:
145
148
  await connection.close()
146
149
  else:
150
+ connection._connection.reset_state()
147
151
  self._free.append(connection)
148
- fut = self._loop.create_task(self._wakeup())
152
+ fut = self._loop.create_task(self._wakeup())
149
153
  return fut
150
154
 
151
155
  async def _wakeup(self):
@@ -155,6 +159,15 @@ class Pool(asyncio.AbstractServer):
155
159
  def _wait(self):
156
160
  return len(self._terminated) > 0
157
161
 
162
+ async def _check_conn(self, conn) -> bool:
163
+ try:
164
+ async with conn.cursor() as cursor:
165
+ await cursor.execute("SELECT 1")
166
+ return True
167
+ except Exception as e:
168
+ logger.warning(e)
169
+ return False
170
+
158
171
  def acquire(self):
159
172
  return _PoolAcquireContextManager(self._acquire(), self)
160
173
 
@@ -163,19 +176,29 @@ class Pool(asyncio.AbstractServer):
163
176
  raise RuntimeError("Cannot acquire connection after closing pool")
164
177
  async with self._cond:
165
178
  while True:
166
- await self.initialize()
179
+ await self.initialize() # Restore minsize
180
+
181
+ if not self._free and self.size < self.maxsize:
182
+ await self.init_one_connection()
183
+
167
184
  if self._free:
168
185
  conn = self._free.popleft()
169
- self._used.add(conn)
170
- return conn
186
+ if await self._check_conn(conn):
187
+ self._used.add(conn)
188
+ return conn
189
+ else:
190
+ continue
171
191
  else:
172
192
  await self._cond.wait()
173
193
 
174
194
  async def initialize(self):
175
- while self.size < self.minsize:
176
- conn = await connect(**self._connection_kwargs)
177
- self._free.append(conn)
178
- self._cond.notify()
195
+ while self.freesize < self.minsize and self.size <= self.maxsize:
196
+ await self.init_one_connection()
197
+
198
+ async def init_one_connection(self):
199
+ conn = await connect(**self._connection_kwargs)
200
+ self._free.append(conn)
201
+ self._cond.notify()
179
202
 
180
203
  async def clear(self):
181
204
  """Close all free connections in pool."""
@@ -7,7 +7,7 @@ from ...errors import (
7
7
  from ..streams.buffered import BufferedReader, BufferedWriter
8
8
  from .arraycolumn import create_array_column
9
9
  from .boolcolumn import BoolColumn
10
- from .datecolumn import DateColumn
10
+ from .datecolumn import Date32Column, DateColumn
11
11
  from .datetimecolumn import create_datetime_column
12
12
  from .decimalcolumn import create_decimal_column
13
13
  from .enumcolumn import create_enum_column
@@ -36,6 +36,7 @@ from .intervalcolumn import (
36
36
  IntervalYearColumn,
37
37
  )
38
38
  from .ipcolumn import IPv4Column, IPv6Column
39
+ from .jsoncolumn import create_json_column
39
40
  from .lowcardinalitycolumn import create_low_cardinality_column
40
41
  from .mapcolumn import create_map_column
41
42
  from .nestedcolumn import create_nested_column
@@ -51,6 +52,7 @@ column_by_type = {
51
52
  c.ch_type: c
52
53
  for c in [
53
54
  DateColumn,
55
+ Date32Column,
54
56
  Float32,
55
57
  Float64,
56
58
  BoolColumn,
@@ -128,7 +130,8 @@ def get_column_by_spec(spec, column_options):
128
130
 
129
131
  elif spec.startswith("Map"):
130
132
  return create_map_column(spec, create_column_with_options, column_options)
131
-
133
+ elif spec.startswith("Object('json')"):
134
+ return create_json_column(spec, create_column_with_options, column_options)
132
135
  else:
133
136
  for alias, primitive in aliases:
134
137
  if spec.startswith(alias):
@@ -0,0 +1,77 @@
1
+ from datetime import date, timedelta
2
+
3
+ import ciso8601
4
+
5
+ from .base import FormatColumn
6
+
7
+ epoch_start = date(1970, 1, 1)
8
+ epoch_end = date(2149, 6, 6)
9
+
10
+ epoch_start_date32 = date(1900, 1, 1)
11
+ epoch_end_date32 = date(2299, 12, 31)
12
+
13
+
14
+ class LazyLUT(dict):
15
+ def __init__(self, *args, _factory, **kwargs):
16
+ super().__init__(*args, **kwargs)
17
+ self._default_factory = _factory
18
+
19
+ def __missing__(self, key):
20
+ return self.setdefault(key, self._default_factory(key))
21
+
22
+
23
+ lazy_date_lut = LazyLUT(_factory=lambda x: epoch_start + timedelta(x))
24
+ lazy_date_lut_reverse = LazyLUT(_factory=lambda x: (x - epoch_start).days)
25
+
26
+
27
+ class DateColumn(FormatColumn):
28
+ ch_type = "Date"
29
+ py_types = (date,)
30
+ format = "H"
31
+
32
+ min_value = epoch_start
33
+ max_value = epoch_end
34
+
35
+ date_lut = lazy_date_lut
36
+ date_lut_reverse = lazy_date_lut_reverse
37
+
38
+ def before_write_items(self, items, nulls_map=None):
39
+ null_value = self.null_value
40
+
41
+ date_lut_reverse = self.date_lut_reverse
42
+ min_value = self.min_value
43
+ max_value = self.max_value
44
+
45
+ for i, item in enumerate(items):
46
+ if nulls_map and nulls_map[i]:
47
+ items[i] = null_value
48
+ continue
49
+ if isinstance(item, str):
50
+ item = ciso8601.parse_datetime(item).date()
51
+ if item is not date:
52
+ item = date(item.year, item.month, item.day)
53
+ if min_value <= item <= max_value:
54
+ items[i] = date_lut_reverse[item]
55
+ else:
56
+ items[i] = 0
57
+
58
+ def after_read_items(self, items, nulls_map=None):
59
+ date_lut = self.date_lut
60
+
61
+ if nulls_map is None:
62
+ return tuple(date_lut[item] for item in items)
63
+ else:
64
+ return tuple(
65
+ (None if is_null else date_lut[items[i]]) for i, is_null in enumerate(nulls_map)
66
+ )
67
+
68
+
69
+ class Date32Column(DateColumn):
70
+ ch_type = "Date32"
71
+ format = "i"
72
+
73
+ min_value = epoch_start_date32
74
+ max_value = epoch_end_date32
75
+
76
+ date_lut = lazy_date_lut
77
+ date_lut_reverse = lazy_date_lut_reverse
@@ -0,0 +1,34 @@
1
+ import json
2
+
3
+ from .base import Column
4
+ from .stringcolumn import String
5
+
6
+
7
+ class JsonColumn(Column):
8
+ py_types = (dict,)
9
+
10
+ # No NULL value actually
11
+ null_value = {}
12
+
13
+ def __init__(self, column_by_spec_getter, **kwargs):
14
+ self.column_by_spec_getter = column_by_spec_getter
15
+ self.string_column = String(**kwargs)
16
+ super(JsonColumn, self).__init__(**kwargs)
17
+
18
+ async def write_state_prefix(self):
19
+ await self.writer.write_uint8(1)
20
+
21
+ async def read_items(self, n_items):
22
+ await self.reader.read_uint8()
23
+ spec = await self.reader.read_str()
24
+ col = self.column_by_spec_getter(spec)
25
+ await col.read_state_prefix()
26
+ return await col.read_data(n_items)
27
+
28
+ async def write_items(self, items):
29
+ items = [x if isinstance(x, str) else json.dumps(x) for x in items]
30
+ await self.string_column.write_items(items)
31
+
32
+
33
+ def create_json_column(spec, column_by_spec_getter, column_options):
34
+ return JsonColumn(column_by_spec_getter, **column_options)
@@ -1,8 +1,6 @@
1
1
  import importlib
2
2
  from typing import TYPE_CHECKING, Type
3
3
 
4
- from clickhouse_cityhash.cityhash import CityHash128
5
-
6
4
  from asynch.errors import ChecksumDoesntMatchError, UnknownCompressionMethod
7
5
  from asynch.proto.protocol import CompressionMethodByte
8
6
 
@@ -57,7 +55,9 @@ class BaseCompressor:
57
55
  await self.writer.write_uint32(header_size + len(compressed))
58
56
  await self.writer.write_uint32(len(data))
59
57
  await self.writer.write_bytes(compressed)
60
- return self.writer.buffer
58
+ result = self.writer.buffer
59
+ self.writer.buffer = bytearray()
60
+ return result
61
61
 
62
62
 
63
63
  class BaseDecompressor:
@@ -72,6 +72,8 @@ class BaseDecompressor:
72
72
  raise NotImplementedError
73
73
 
74
74
  async def get_decompressed_data(self, method_byte, compressed_hash, extra_header_size):
75
+ CityHash128 = import_cityhash()
76
+
75
77
  size_with_header = await self.reader.read_uint32()
76
78
  compressed_size = size_with_header - extra_header_size - 4
77
79
 
@@ -88,3 +90,12 @@ class BaseDecompressor:
88
90
  uncompressed_size = await reader.read_uint32()
89
91
  compressed = compressed[4:compressed_size]
90
92
  return self.decompress_data(compressed, uncompressed_size)
93
+
94
+
95
+ def import_cityhash():
96
+ try:
97
+ from clickhouse_cityhash.cityhash import CityHash128
98
+ except ImportError as e:
99
+ raise ImportError("Please install clickhouse-cityhash to enable compression") from e
100
+ else:
101
+ return CityHash128
@@ -13,13 +13,22 @@ from asynch.errors import (
13
13
  UnknownPacketFromServerError,
14
14
  )
15
15
  from asynch.proto import constants
16
- from asynch.proto.block import BlockStreamProfileInfo, ColumnOrientedBlock, RowOrientedBlock
16
+ from asynch.proto.block import (
17
+ BlockStreamProfileInfo,
18
+ ColumnOrientedBlock,
19
+ RowOrientedBlock,
20
+ )
17
21
  from asynch.proto.compression import get_compressor_cls
18
22
  from asynch.proto.context import Context, ExecuteContext
19
23
  from asynch.proto.cs import ClientInfo, QueryKind, ServerInfo
20
24
  from asynch.proto.progress import Progress
21
25
  from asynch.proto.protocol import ClientPacket, Compression, ServerPacket
22
- from asynch.proto.result import IterQueryResult, ProgressQueryResult, QueryInfo, QueryResult
26
+ from asynch.proto.result import (
27
+ IterQueryResult,
28
+ ProgressQueryResult,
29
+ QueryInfo,
30
+ QueryResult,
31
+ )
23
32
  from asynch.proto.settings import write_settings
24
33
  from asynch.proto.streams.block import BlockReader, BlockWriter
25
34
  from asynch.proto.streams.buffered import BufferedReader, BufferedWriter
@@ -108,7 +117,7 @@ class Connection:
108
117
  self.settings_is_important = settings_is_important
109
118
  self._lock = asyncio.Lock()
110
119
  self.secure_socket = secure
111
- self.verify_cert = verify
120
+ self.verify = verify
112
121
 
113
122
  ssl_options = {}
114
123
  if ssl_version is not None:
@@ -286,8 +295,11 @@ class Connection:
286
295
  ciphers = self.ssl_options.get("ciphers")
287
296
  if ciphers:
288
297
  ssl_ctx.set_ciphers(ciphers)
289
- if self.verify_cert:
298
+ if self.verify:
290
299
  ssl_ctx.verify_mode = ssl.VerifyMode.CERT_REQUIRED
300
+ else:
301
+ ssl_ctx.check_hostname = False
302
+ ssl_ctx.verify_mode = ssl.VerifyMode.CERT_NONE
291
303
  return ssl_ctx
292
304
 
293
305
  async def ping(self):
@@ -472,7 +484,6 @@ class Connection:
472
484
  yield packet
473
485
 
474
486
  async def receive_result(self, with_column_types=False, progress=False, columnar=False):
475
-
476
487
  generator = self.packet_generator()
477
488
 
478
489
  if progress:
@@ -539,7 +550,6 @@ class Connection:
539
550
  await self.receive_hello()
540
551
 
541
552
  def reset_state(self):
542
-
543
553
  self.writer = None
544
554
  self.reader = None
545
555
  self.block_reader = None
@@ -621,7 +631,6 @@ class Connection:
621
631
 
622
632
  start_time = time()
623
633
  async with ExecuteContext(self, query, settings):
624
-
625
634
  # INSERT queries can use list/tuple/generator of list/tuples/dicts.
626
635
  # For SELECT parameters can be passed in only in dict right now.
627
636
  is_insert = isinstance(args, (list, tuple, GeneratorType))
@@ -706,7 +715,6 @@ class Connection:
706
715
  types_check=False,
707
716
  columnar=False,
708
717
  ):
709
-
710
718
  if params is not None:
711
719
  query = self.substitute_params(query, params)
712
720
 
@@ -759,7 +767,6 @@ class Connection:
759
767
  types_check=False,
760
768
  columnar=False,
761
769
  ):
762
-
763
770
  if params is not None:
764
771
  query = self.substitute_params(query, params)
765
772
 
@@ -867,7 +874,6 @@ class Connection:
867
874
  query_id=None,
868
875
  types_check=False,
869
876
  ):
870
-
871
877
  if params is not None:
872
878
  query = self.substitute_params(query, params)
873
879
 
@@ -46,8 +46,12 @@ class ExecuteContext:
46
46
  self._connection.make_query_settings(settings)
47
47
 
48
48
  async def __aenter__(self):
49
- await self._connection.force_connect()
50
- self._connection.last_query = QueryInfo(self._connection.reader)
49
+ try:
50
+ await self._connection.force_connect()
51
+ self._connection.last_query = QueryInfo(self._connection.reader)
52
+ except (Exception, KeyboardInterrupt):
53
+ await self._connection.disconnect()
54
+ raise
51
55
 
52
56
  async def __aexit__(self, exc_type, exc_val, exc_tb):
53
57
  if exc_type:
@@ -10,7 +10,6 @@ logger = logging.getLogger(__name__)
10
10
  async def write_settings(
11
11
  writer: BufferedWriter, settings: Dict, settings_as_strings, settings_is_important: bool
12
12
  ):
13
-
14
13
  for setting, value in (settings or {}).items():
15
14
  # If the server support settings as string we do not need to know
16
15
  # anything about them, so we can write any setting.
@@ -111,6 +111,24 @@ class BufferedReader:
111
111
  self.current_buffer_size = 0
112
112
  self.position = 0
113
113
 
114
+ async def _refill_buffer(self):
115
+ if self.position == self.current_buffer_size:
116
+ self._reset_buffer()
117
+ await self._read_into_buffer()
118
+
119
+ def _is_buffer_empty(self):
120
+ return not (self.buffer or self.position)
121
+
122
+ async def _is_buffer_readable(self) -> bool:
123
+ await self._refill_buffer()
124
+ if self._is_buffer_empty():
125
+ return False
126
+ return True
127
+
128
+ def _reset_buffer(self):
129
+ self.position = 0
130
+ self.buffer = bytearray()
131
+
114
132
  async def _read_into_buffer(self):
115
133
  packet = await self.reader.read(self.buffer_max_size)
116
134
  self.buffer.extend(packet)
@@ -122,97 +140,68 @@ class BufferedReader:
122
140
  return packet
123
141
 
124
142
  async def read_varint(self):
125
- if self.position == self.current_buffer_size:
126
- self._reset_buffer()
127
- await self._read_into_buffer()
128
143
  packets = bytearray()
129
144
  while True:
145
+ if not (await self._is_buffer_readable()):
146
+ break
130
147
  packet = self._read_one()
131
148
  packets.append(packet)
132
149
  if packet < 0x80:
133
150
  break
134
151
  return leb128.u.decode(packets)
135
152
 
136
- def _reset_buffer(self):
137
- self.position = 0
138
- self.buffer = bytearray()
139
-
140
- async def read_str(self, as_bytes: bool = False):
141
- length = await self.read_varint()
142
- packet = await self.read_bytes(length)
143
- if as_bytes:
144
- return packet
145
- return packet.decode()
146
-
147
- async def read_fixed_str(self, length: int, as_bytes: bool = False):
148
- packet = await self.read_bytes(length)
149
- if as_bytes:
150
- return packet
151
- return packet.decode()
152
-
153
153
  async def read_bytes(self, length: int):
154
154
  packets = bytearray()
155
155
  while length > 0:
156
- if self.position == self.current_buffer_size:
157
- self._reset_buffer()
158
- await self._read_into_buffer()
159
-
156
+ if not (await self._is_buffer_readable()):
157
+ break
160
158
  read_position = self.position + length
161
159
  packet = self.buffer[self.position : read_position] # noqa: E203
162
160
  length -= len(packet)
163
161
  self.position += len(packet)
164
162
  packets.extend(packet)
165
-
166
163
  return packets
167
164
 
165
+ async def read_fixed_str(self, length: int, as_bytes: bool = False):
166
+ packet = await self.read_bytes(length)
167
+ if as_bytes:
168
+ return packet
169
+ return packet.decode()
170
+
171
+ async def read_str(self, as_bytes: bool = False):
172
+ length = await self.read_varint()
173
+ return await self.read_fixed_str(length=length, as_bytes=as_bytes)
174
+
168
175
  async def read_int(self, fmt: str):
169
176
  s = struct.Struct("<" + fmt)
170
177
  packet = await self.read_bytes(s.size)
171
178
  return s.unpack(packet)[0]
172
179
 
173
- async def read_int8(
174
- self,
175
- ):
180
+ async def read_int8(self):
176
181
  return await self.read_int("b")
177
182
 
178
- async def read_int16(
179
- self,
180
- ):
183
+ async def read_int16(self):
181
184
  return await self.read_int("h")
182
185
 
183
- async def read_int32(
184
- self,
185
- ):
186
+ async def read_int32(self):
186
187
  return await self.read_int("i")
187
188
 
188
- async def read_int64(
189
- self,
190
- ):
189
+ async def read_int64(self):
191
190
  return await self.read_int("q")
192
191
 
193
- async def read_uint8(
194
- self,
195
- ):
192
+ async def read_uint8(self):
196
193
  return await self.read_int("B")
197
194
 
198
- async def read_uint16(
199
- self,
200
- ):
195
+ async def read_uint16(self):
201
196
  return await self.read_int("H")
202
197
 
203
- async def read_uint32(
204
- self,
205
- ):
198
+ async def read_uint32(self):
206
199
  return await self.read_int("I")
207
200
 
208
- async def read_uint64(
209
- self,
210
- ):
201
+ async def read_uint64(self):
211
202
  return await self.read_int("Q")
212
203
 
213
- async def read_uint128(
214
- self,
215
- ):
204
+ async def read_uint128(self):
216
205
  hi = await self.read_int("Q")
217
206
  lo = await self.read_int("Q")
218
207
  return (hi << 64) + lo
@@ -1,7 +1,5 @@
1
- from clickhouse_cityhash.cityhash import CityHash128
2
-
3
1
  from asynch.proto import constants
4
- from asynch.proto.compression import BaseCompressor
2
+ from asynch.proto.compression import BaseCompressor, import_cityhash
5
3
  from asynch.proto.context import Context
6
4
  from asynch.proto.streams.block import BlockReader, BlockWriter
7
5
  from asynch.proto.streams.buffered import (
@@ -28,6 +26,7 @@ class CompressedBlockWriter(BlockWriter):
28
26
  super().__init__(reader, self.writer, context)
29
27
 
30
28
  async def finalize(self):
29
+ CityHash128 = import_cityhash()
31
30
  await self.writer.flush()
32
31
 
33
32
  compressed = await self.get_compressed()
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "asynch"
3
- version = "0.2.2"
3
+ version = "0.2.4"
4
4
  description = "A asyncio driver for ClickHouse with native tcp protocol"
5
5
  authors = ["long2ice <long2ice@gmail.com>"]
6
6
  license = "Apache-2.0"
@@ -19,14 +19,16 @@ python = "^3.7"
19
19
  leb128 = "*"
20
20
  pytz = "*"
21
21
  lz4 = "*"
22
- clickhouse-cityhash = "*"
22
+ clickhouse-cityhash = { version = "*", optional = true }
23
23
  zstd = "*"
24
24
  tzlocal = "*"
25
25
  ciso8601 = "*"
26
26
 
27
+ [tool.poetry.extras]
28
+ compression = ["clickhouse-cityhash"]
29
+
27
30
  [tool.poetry.dev-dependencies]
28
- flake8 = "*"
29
- pyproject-flake8 = "*"
31
+ ruff = "*"
30
32
  isort = "*"
31
33
  black = "*"
32
34
  pytest = "*"
@@ -37,16 +39,18 @@ clickhouse-driver = "*"
37
39
  uvloop = "*"
38
40
 
39
41
  [build-system]
40
- requires = ["poetry>=0.12"]
41
- build-backend = "poetry.masonry.api"
42
+ build-backend = "poetry.core.masonry.api"
43
+ requires = ["poetry-core"]
44
+
45
+ [tool.isort]
46
+ profile = "black"
42
47
 
43
48
  [tool.black]
44
49
  line-length = 100
45
- target-version = ["py36", "py37", "py38", "py39"]
46
-
47
- [tool.flake8]
48
- ignore = "E501,W503,DAR101,DAR201,DAR402"
49
- max-line-length = 100
50
+ target-version = ['py38', 'py39', 'py310', 'py311']
50
51
 
51
52
  [tool.pytest.ini_options]
52
53
  asyncio_mode = "auto"
54
+
55
+ [tool.ruff]
56
+ line-length = 100
@@ -1,48 +0,0 @@
1
- from datetime import date, timedelta
2
-
3
- import ciso8601
4
-
5
- from .base import FormatColumn
6
-
7
- epoch_start = date(1970, 1, 1)
8
-
9
-
10
- class DateColumn(FormatColumn):
11
- ch_type = "Date"
12
- py_types = (date,)
13
- format = "H"
14
-
15
- epoch_start = epoch_start
16
- epoch_end = date(2105, 12, 31)
17
-
18
- date_lut = {x: epoch_start + timedelta(x) for x in range(65535)}
19
- date_lut_reverse = {value: key for key, value in date_lut.items()}
20
-
21
- def before_write_items(self, items, nulls_map=None):
22
- null_value = self.null_value
23
-
24
- date_lut_reverse = self.date_lut_reverse
25
- epoch_start = self.epoch_start
26
- epoch_end = self.epoch_end
27
-
28
- for i, item in enumerate(items):
29
- if nulls_map and nulls_map[i]:
30
- items[i] = null_value
31
- continue
32
-
33
- if isinstance(item, str):
34
- item = ciso8601.parse_datetime(item).date()
35
- if item > epoch_end or item < epoch_start:
36
- items[i] = 0
37
- else:
38
- items[i] = date_lut_reverse[item]
39
-
40
- def after_read_items(self, items, nulls_map=None):
41
- date_lut = self.date_lut
42
-
43
- if nulls_map is None:
44
- return tuple(date_lut[item] for item in items)
45
- else:
46
- return tuple(
47
- (None if is_null else date_lut[items[i]]) for i, is_null in enumerate(nulls_map)
48
- )
asynch-0.2.2/setup.py DELETED
@@ -1,36 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- from setuptools import setup
3
-
4
- packages = \
5
- ['asynch',
6
- 'asynch.proto',
7
- 'asynch.proto.columns',
8
- 'asynch.proto.compression',
9
- 'asynch.proto.settings',
10
- 'asynch.proto.streams',
11
- 'asynch.proto.utils']
12
-
13
- package_data = \
14
- {'': ['*']}
15
-
16
- install_requires = \
17
- ['ciso8601', 'clickhouse-cityhash', 'leb128', 'lz4', 'pytz', 'tzlocal', 'zstd']
18
-
19
- setup_kwargs = {
20
- 'name': 'asynch',
21
- 'version': '0.2.2',
22
- 'description': 'A asyncio driver for ClickHouse with native tcp protocol',
23
- 'long_description': '# asynch\n\n![pypi](https://img.shields.io/pypi/v/asynch.svg?style=flat)\n![license](https://img.shields.io/github/license/long2ice/asynch)\n![workflows](https://github.com/long2ice/asynch/workflows/pypi/badge.svg)\n![workflows](https://github.com/long2ice/asynch/workflows/ci/badge.svg)\n\n## Introduction\n\n`asynch` is an asyncio ClickHouse Python Driver with native (TCP) interface support, which reuse most of [clickhouse-driver](https://github.com/mymarilyn/clickhouse-driver) and comply with [PEP249](https://www.python.org/dev/peps/pep-0249/).\n\n## Install\n\n```shell\n> pip install asynch\n```\n\n## Usage\n\nConnect to ClickHouse\n\n```python\nfrom asynch import connect\n\nasync def connect_database():\n conn = await connect(\n host = "127.0.0.1",\n port = 9000,\n database = "default",\n user = "default",\n password = "",\n )\n```\n\nCreate table by sql\n\n```python\nasync def create_table():\n async with conn.cursor(cursor=DictCursor) as cursor:\n await cursor.execute(\'create database if not exists test\')\n await cursor.execute("""\n CREATE TABLE if not exists test.asynch\n (\n `id` Int32,\n `decimal` Decimal(10, 2),\n `date` Date,\n `datetime` DateTime,\n `float` Float32,\n `uuid` UUID,\n `string` String,\n `ipv4` IPv4,\n `ipv6` IPv6\n\n )\n ENGINE = MergeTree\n ORDER BY id"""\n )\n```\n\nUse `fetchone`\n\n```python\nasync def fetchone():\n async with conn.cursor() as cursor:\n await cursor.execute("SELECT 1")\n ret = await cursor.fetchone()\n assert ret == (1,)\n```\n\nUse `fetchmany`\n\n```python\nasync def fetchall():\n async with conn.cursor() as cursor:\n await cursor.execute("SELECT 1")\n ret = await cursor.fetchall()\n assert ret == [(1,)]\n```\n\nUse `DictCursor` to get result with dict\n\n```python\nasync def dict_cursor():\n async with conn.cursor(cursor=DictCursor) as cursor:\n await cursor.execute("SELECT 1")\n ret = await cursor.fetchall()\n assert ret == [{"1": 1}]\n```\n\nInsert data with dict\n\n```python\nfrom asynch.cursors import DictCursor\n\nasync def insert_dict():\n async with conn.cursor(cursor=DictCursor) as cursor:\n ret = await cursor.execute(\n """INSERT INTO test.asynch(id,decimal,date,datetime,float,uuid,string,ipv4,ipv6) VALUES""",\n [\n {\n "id": 1,\n "decimal": 1,\n "date": "2020-08-08",\n "datetime": "2020-08-08 00:00:00",\n "float": 1,\n "uuid": "59e182c4-545d-4f30-8b32-cefea2d0d5ba",\n "string": "1",\n "ipv4": "0.0.0.0",\n "ipv6": "::",\n }\n ],\n )\n assert ret == 1\n```\n\nInsert data with tuple\n\n```python\nasync def insert_tuple():\n async with conn.cursor(cursor=DictCursor) as cursor:\n ret = await cursor.execute(\n """INSERT INTO test.asynch(id,decimal,date,datetime,float,uuid,string,ipv4,ipv6) VALUES""",\n [\n (\n 1,\n 1,\n "2020-08-08",\n "2020-08-08 00:00:00",\n 1,\n "59e182c4-545d-4f30-8b32-cefea2d0d5ba",\n "1",\n "0.0.0.0",\n "::",\n )\n ],\n )\n assert ret == 1\n```\n\nUse connection pool\n\n```python\nasync def use_pool():\n pool = await asynch.create_pool()\n async with pool.acquire() as conn:\n async with conn.cursor() as cursor:\n await cursor.execute("SELECT 1")\n ret = await cursor.fetchone()\n assert ret == (1,)\n pool.close()\n await pool.wait_closed()\n```\n\n## ThanksTo\n\n- [clickhouse-driver](https://github.com/mymarilyn/clickhouse-driver), ClickHouse Python Driver with native interface support.\n\n## License\n\nThis project is licensed under the [Apache-2.0](https://github.com/long2ice/asynch/blob/master/LICENSE) License.\n',
24
- 'author': 'long2ice',
25
- 'author_email': 'long2ice@gmail.com',
26
- 'maintainer': 'None',
27
- 'maintainer_email': 'None',
28
- 'url': 'https://github.com/long2ice/asynch',
29
- 'packages': packages,
30
- 'package_data': package_data,
31
- 'install_requires': install_requires,
32
- 'python_requires': '>=3.7,<4.0',
33
- }
34
-
35
-
36
- setup(**setup_kwargs)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes