|
1 | | -from sqlalchemy.dialects.postgresql.base import ischema_names |
2 | | -from sqlalchemy.types import UserDefinedType, TypeEngine, Float |
3 | | -from sqlalchemy import Dialect, Operators |
| 1 | +from sqlalchemy.dialects.postgresql.base import PGBit |
| 2 | +from sqlalchemy.types import TypeDecorator, Float |
| 3 | +from sqlalchemy import Operators |
4 | 4 | from typing import Any |
5 | 5 |
|
6 | 6 |
|
7 | | -class BIT(UserDefinedType[Any]): |
| 7 | +class BIT(TypeDecorator[Any]): |
| 8 | + impl = PGBit |
8 | 9 | cache_ok = True |
9 | 10 |
|
10 | | - def __init__(self, length: int | None = None) -> None: |
11 | | - super().__init__() |
12 | | - self.length = length |
13 | | - |
14 | | - def get_col_spec(self, **kw: Any) -> str: |
15 | | - if self.length is None: |
16 | | - return 'BIT' |
17 | | - return 'BIT(%d)' % self.length |
18 | | - |
19 | | - def bind_processor(self, dialect: Dialect) -> Any: |
20 | | - if dialect.__class__.__name__ == 'PGDialect_asyncpg': |
| 11 | + def process_bind_param(self, value: Any, dialect: Any) -> Any: |
| 12 | + if dialect.__class__.__name__ == 'PGDialect_asyncpg' and isinstance(value, str): |
21 | 13 | import asyncpg |
| 14 | + return asyncpg.BitString(value) # type: ignore |
| 15 | + return value |
22 | 16 |
|
23 | | - def process(value: Any) -> Any: |
24 | | - if isinstance(value, str): |
25 | | - return asyncpg.BitString(value) # type: ignore |
26 | | - return value |
27 | | - return process |
28 | | - else: |
29 | | - return super().bind_processor(dialect) |
30 | | - |
31 | | - class Comparator(TypeEngine.Comparator[Any]): |
| 17 | + class Comparator(TypeDecorator.Comparator[Any]): |
32 | 18 | def hamming_distance(self, other: object) -> Operators: |
33 | 19 | return self.op('<~>', return_type=Float)(other) |
34 | 20 |
|
35 | 21 | def jaccard_distance(self, other: object) -> Operators: |
36 | 22 | return self.op('<%>', return_type=Float)(other) |
37 | 23 |
|
38 | | - comparator_factory = Comparator |
39 | | - |
40 | | - |
41 | | -# for reflection |
42 | | -ischema_names['bit'] = BIT # type: ignore |
| 24 | + comparator_factory = Comparator # type: ignore |
0 commit comments