|
| 1 | +import numpy as np |
| 2 | +from psycopg3.adapt import Loader, Dumper |
| 3 | +from psycopg3.pq import Format |
| 4 | +from ..utils import from_db, from_db_binary, to_db, to_db_binary |
| 5 | + |
| 6 | +__all__ = ['register_vector'] |
| 7 | + |
| 8 | + |
| 9 | +class VectorDumper(Dumper): |
| 10 | + |
| 11 | + format = Format.TEXT |
| 12 | + |
| 13 | + def dump(self, obj): |
| 14 | + return to_db(obj).encode("utf8") |
| 15 | + |
| 16 | + |
| 17 | +class VectorBinaryDumper(VectorDumper): |
| 18 | + |
| 19 | + format = Format.BINARY |
| 20 | + |
| 21 | + def dump(self, obj): |
| 22 | + return to_db_binary(obj) |
| 23 | + |
| 24 | + |
| 25 | +class VectorLoader(Loader): |
| 26 | + |
| 27 | + format = Format.TEXT |
| 28 | + |
| 29 | + def load(self, data): |
| 30 | + if isinstance(data, memoryview): |
| 31 | + data = bytes(data) |
| 32 | + return from_db(data.decode("utf8")) |
| 33 | + |
| 34 | + |
| 35 | +class VectorBinaryLoader(VectorLoader): |
| 36 | + |
| 37 | + format = Format.BINARY |
| 38 | + |
| 39 | + def load(self, data): |
| 40 | + if isinstance(data, memoryview): |
| 41 | + data = bytes(data) |
| 42 | + return from_db_binary(data) |
| 43 | + |
| 44 | + |
| 45 | +def register_vector(ctx): |
| 46 | + cur = ctx.cursor() if hasattr(ctx, 'cursor') else ctx |
| 47 | + |
| 48 | + try: |
| 49 | + cur.execute('SELECT NULL::vector') |
| 50 | + oid = cur.description[0][1] |
| 51 | + except psycopg3.errors.UndefinedObject: |
| 52 | + raise psycopg3.ProgrammingError('vector type not found in the database') |
| 53 | + |
| 54 | + VectorDumper.register('numpy.ndarray', ctx) |
| 55 | + VectorBinaryDumper.register('numpy.ndarray', ctx) |
| 56 | + VectorLoader.register(oid, ctx) |
| 57 | + VectorBinaryLoader.register(oid, ctx) |
0 commit comments