Debian Codegraph @

src/harlequin_postgres/loaders.py

raw
1 from __future__ import annotations
2
3 from datetime import date, datetime
4 from typing import TYPE_CHECKING
5
6 import psycopg
7 from psycopg.errors import DataError
8
9 # Subclass existing adapters so that the base case is handled normally.
10 from psycopg.types.datetime import (
11 DateBinaryLoader,
12 DateLoader,
13 TimestampBinaryLoader,
14 TimestampLoader,
15 TimestamptzBinaryLoader,
16 TimestamptzLoader,
17 )
18
19 if TYPE_CHECKING:
20 from psycopg.adapt import Buffer, Loader
21
22
23 class InfDateLoader(DateLoader):
24 def load(self, data: "Buffer") -> date:
25 if data == b"infinity":
26 return date.max
27 elif data == b"-infinity":
28 return date.min
29 else:
30 return super().load(data)
31
32
33 class InfDateBinaryLoader(DateBinaryLoader):
34 def load(self, data: "Buffer") -> date:
35 try:
36 return super().load(data)
37 except DataError as e:
38 if "date too small" in str(e):
39 return date.min
40 elif "date too large" in str(e):
41 return date.max
42 raise e
43
44
45 class InfTimestampLoader(TimestampLoader):
46 def load(self, data: "Buffer") -> datetime:
47 if data == b"infinity":
48 return datetime.max
49 elif data == b"-infinity":
50 return datetime.min
51 else:
52 return super().load(data)
53
54
55 class InfTimestampBinaryLoader(TimestampBinaryLoader):
56 def load(self, data: "Buffer") -> datetime:
57 try:
58 return super().load(data)
59 except DataError as e:
60 if "timestamp too small" in str(e):
61 return datetime.min
62 elif "timestamp too large" in str(e):
63 return datetime.max
64 raise e
65
66
67 class InfTimestamptzLoader(TimestamptzLoader):
68 def load(self, data: "Buffer") -> datetime:
69 if data == b"infinity":
70 return datetime.max
71 elif data == b"-infinity":
72 return datetime.min
73 else:
74 return super().load(data)
75
76
77 class InfTimestamptzBinaryLoader(TimestamptzBinaryLoader):
78 def load(self, data: "Buffer") -> datetime:
79 try:
80 return super().load(data)
81 except DataError as e:
82 if "timestamp too small" in str(e):
83 return datetime.min
84 elif "timestamp too large" in str(e):
85 return datetime.max
86 raise e
87
88
89 INF_LOADERS: list[tuple[str, type["Loader"]]] = [
90 ("date", InfDateLoader),
91 ("date", InfDateBinaryLoader),
92 ("timestamp", InfTimestampLoader),
93 ("timestamp", InfTimestampBinaryLoader),
94 ("timestamptz", InfTimestamptzLoader),
95 ("timestamptz", InfTimestamptzBinaryLoader),
96 ]
97
98
99 def register_inf_loaders() -> None:
100 """
101 Register updated date/datetime loaders in the global types
102 registry, so that any connections created afterwards will use
103 the updated loaders (that allow infinity date/timestamps)
104 """
105 for type_name, loader in INF_LOADERS:
106 psycopg.adapters.register_loader(type_name, loader)