-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathsparsevec.py
More file actions
54 lines (37 loc) · 1.64 KB
/
Copy pathsparsevec.py
File metadata and controls
54 lines (37 loc) · 1.64 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 SparseVector
Buffer: TypeAlias = bytes | bytearray | memoryview
class SparseVectorDumper(Dumper):
format = Format.TEXT
def dump(self, obj: SparseVector) -> Buffer | None:
return obj.to_text().encode('utf8')
class SparseVectorBinaryDumper(SparseVectorDumper):
format = Format.BINARY
def dump(self, obj: SparseVector) -> Buffer | None:
return obj.to_binary()
class SparseVectorLoader(Loader):
format = Format.TEXT
def load(self, data: Buffer) -> SparseVector | None:
if isinstance(data, memoryview):
data = bytes(data)
return SparseVector.from_text(data.decode('utf8'))
class SparseVectorBinaryLoader(SparseVectorLoader):
format = Format.BINARY
def load(self, data: Buffer) -> SparseVector | None:
if isinstance(data, (bytearray, memoryview)):
data = bytes(data)
return SparseVector.from_binary(data)
def register_sparsevec_info(context: BaseConnection[Any], info: TypeInfo) -> None:
info.register(context)
# add oid to anonymous class for set_types
text_dumper = type('', (SparseVectorDumper,), {'oid': info.oid})
binary_dumper = type('', (SparseVectorBinaryDumper,), {'oid': info.oid})
adapters = context.adapters
adapters.register_dumper(SparseVector, text_dumper)
adapters.register_dumper(SparseVector, binary_dumper)
adapters.register_loader(info.oid, SparseVectorLoader)
adapters.register_loader(info.oid, SparseVectorBinaryLoader)