-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathhalfvec.py
More file actions
54 lines (37 loc) · 1.6 KB
/
Copy pathhalfvec.py
File metadata and controls
54 lines (37 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from psycopg import BaseConnection
from psycopg.adapt import Loader, Dumper
from psycopg.pq import Format
from psycopg.types import TypeInfo
from typing import Any, TypeAlias
from .. import HalfVector
Buffer: TypeAlias = bytes | bytearray | memoryview
class HalfVectorDumper(Dumper):
format = Format.TEXT
def dump(self, obj: HalfVector) -> Buffer | None:
return obj.to_text().encode('utf8')
class HalfVectorBinaryDumper(HalfVectorDumper):
format = Format.BINARY
def dump(self, obj: HalfVector) -> Buffer | None:
return obj.to_binary()
class HalfVectorLoader(Loader):
format = Format.TEXT
def load(self, data: Buffer) -> HalfVector | None:
if isinstance(data, memoryview):
data = bytes(data)
return HalfVector.from_text(data.decode('utf8'))
class HalfVectorBinaryLoader(HalfVectorLoader):
format = Format.BINARY
def load(self, data: Buffer) -> HalfVector | None:
if isinstance(data, (bytearray, memoryview)):
data = bytes(data)
return HalfVector.from_binary(data)
def register_halfvec_info(context: BaseConnection[Any], info: TypeInfo) -> None:
info.register(context)
# add oid to anonymous class for set_types
text_dumper = type('', (HalfVectorDumper,), {'oid': info.oid})
binary_dumper = type('', (HalfVectorBinaryDumper,), {'oid': info.oid})
adapters = context.adapters
adapters.register_dumper(HalfVector, text_dumper)
adapters.register_dumper(HalfVector, binary_dumper)
adapters.register_loader(info.oid, HalfVectorLoader)
adapters.register_loader(info.oid, HalfVectorBinaryLoader)