|
| 1 | +from sqlalchemy.dialects.postgresql.base import ischema_names |
| 2 | +from sqlalchemy.types import UserDefinedType, Float, String |
| 3 | +from ..utils import SparseVec |
| 4 | + |
| 5 | + |
| 6 | +class Sparsevec(UserDefinedType): |
| 7 | + cache_ok = True |
| 8 | + _string = String() |
| 9 | + |
| 10 | + def __init__(self, dim=None): |
| 11 | + super(UserDefinedType, self).__init__() |
| 12 | + self.dim = dim |
| 13 | + |
| 14 | + def get_col_spec(self, **kw): |
| 15 | + if self.dim is None: |
| 16 | + return 'SPARSEVEC' |
| 17 | + return 'SPARSEVEC(%d)' % self.dim |
| 18 | + |
| 19 | + def bind_processor(self, dialect): |
| 20 | + def process(value): |
| 21 | + return SparseVec.to_db(value, self.dim) |
| 22 | + return process |
| 23 | + |
| 24 | + def literal_processor(self, dialect): |
| 25 | + string_literal_processor = self._string._cached_literal_processor(dialect) |
| 26 | + |
| 27 | + def process(value): |
| 28 | + return string_literal_processor(SparseVec.to_db(value, self.dim)) |
| 29 | + return process |
| 30 | + |
| 31 | + def result_processor(self, dialect, coltype): |
| 32 | + def process(value): |
| 33 | + return SparseVec.from_db(value) |
| 34 | + return process |
| 35 | + |
| 36 | + class comparator_factory(UserDefinedType.Comparator): |
| 37 | + def l2_distance(self, other): |
| 38 | + return self.op('<->', return_type=Float)(other) |
| 39 | + |
| 40 | + def max_inner_product(self, other): |
| 41 | + return self.op('<#>', return_type=Float)(other) |
| 42 | + |
| 43 | + def cosine_distance(self, other): |
| 44 | + return self.op('<=>', return_type=Float)(other) |
| 45 | + |
| 46 | + def l1_distance(self, other): |
| 47 | + return self.op('<+>', return_type=Float)(other) |
| 48 | + |
| 49 | + |
| 50 | +# for reflection |
| 51 | +ischema_names['sparsevec'] = Sparsevec |
0 commit comments