PyGreSQL 6.1.0__cp313-cp313-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pgdb/adapt.py ADDED
@@ -0,0 +1,261 @@
1
+ """Type helpers for adaptation of parameters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, datetime, time, timedelta, tzinfo
6
+ from json import dumps as jsonencode
7
+ from re import compile as regex
8
+ from time import localtime
9
+ from typing import Any, Callable, Iterable
10
+ from uuid import UUID as Uuid # noqa: N811
11
+
12
+ from .typecode import TypeCode
13
+
14
+ __all__ = [
15
+ 'ARRAY',
16
+ 'BINARY',
17
+ 'BOOL',
18
+ 'DATE',
19
+ 'DATETIME',
20
+ 'FLOAT',
21
+ 'HSTORE',
22
+ 'INTEGER',
23
+ 'INTERVAL',
24
+ 'JSON',
25
+ 'LONG',
26
+ 'MONEY',
27
+ 'NUMBER',
28
+ 'NUMERIC',
29
+ 'RECORD',
30
+ 'ROWID',
31
+ 'SMALLINT',
32
+ 'STRING',
33
+ 'TIME',
34
+ 'TIMESTAMP',
35
+ 'UUID',
36
+ 'ArrayType',
37
+ 'Date',
38
+ 'DateFromTicks',
39
+ 'DbType',
40
+ 'RecordType',
41
+ 'Time',
42
+ 'TimeFromTicks',
43
+ 'Timestamp',
44
+ 'TimestampFromTicks'
45
+
46
+ ]
47
+
48
+
49
+ class DbType(frozenset):
50
+ """Type class for a couple of PostgreSQL data types.
51
+
52
+ PostgreSQL is object-oriented: types are dynamic.
53
+ We must thus use type names as internal type codes.
54
+ """
55
+
56
+ def __new__(cls, values: str | Iterable[str]) -> DbType:
57
+ """Create new type object."""
58
+ if isinstance(values, str):
59
+ values = values.split()
60
+ return super().__new__(cls, values)
61
+
62
+ def __eq__(self, other: Any) -> bool:
63
+ """Check whether types are considered equal."""
64
+ if isinstance(other, str):
65
+ if other.startswith('_'):
66
+ other = other[1:]
67
+ return other in self
68
+ return super().__eq__(other)
69
+
70
+ def __ne__(self, other: Any) -> bool:
71
+ """Check whether types are not considered equal."""
72
+ if isinstance(other, str):
73
+ if other.startswith('_'):
74
+ other = other[1:]
75
+ return other not in self
76
+ return super().__ne__(other)
77
+
78
+
79
+ class ArrayType:
80
+ """Type class for PostgreSQL array types."""
81
+
82
+ def __eq__(self, other: Any) -> bool:
83
+ """Check whether arrays are equal."""
84
+ if isinstance(other, str):
85
+ return other.startswith('_')
86
+ return isinstance(other, ArrayType)
87
+
88
+ def __ne__(self, other: Any) -> bool:
89
+ """Check whether arrays are different."""
90
+ if isinstance(other, str):
91
+ return not other.startswith('_')
92
+ return not isinstance(other, ArrayType)
93
+
94
+
95
+ class RecordType:
96
+ """Type class for PostgreSQL record types."""
97
+
98
+ def __eq__(self, other: Any) -> bool:
99
+ """Check whether records are equal."""
100
+ if isinstance(other, TypeCode):
101
+ return other.type == 'c'
102
+ if isinstance(other, str):
103
+ return other == 'record'
104
+ return isinstance(other, RecordType)
105
+
106
+ def __ne__(self, other: Any) -> bool:
107
+ """Check whether records are different."""
108
+ if isinstance(other, TypeCode):
109
+ return other.type != 'c'
110
+ if isinstance(other, str):
111
+ return other != 'record'
112
+ return not isinstance(other, RecordType)
113
+
114
+
115
+ # Mandatory type objects defined by DB-API 2 specs:
116
+
117
+ STRING = DbType('char bpchar name text varchar')
118
+ BINARY = DbType('bytea')
119
+ NUMBER = DbType('int2 int4 serial int8 float4 float8 numeric money')
120
+ DATETIME = DbType('date time timetz timestamp timestamptz interval'
121
+ ' abstime reltime') # these are very old
122
+ ROWID = DbType('oid')
123
+
124
+
125
+ # Additional type objects (more specific):
126
+
127
+ BOOL = DbType('bool')
128
+ SMALLINT = DbType('int2')
129
+ INTEGER = DbType('int2 int4 int8 serial')
130
+ LONG = DbType('int8')
131
+ FLOAT = DbType('float4 float8')
132
+ NUMERIC = DbType('numeric')
133
+ MONEY = DbType('money')
134
+ DATE = DbType('date')
135
+ TIME = DbType('time timetz')
136
+ TIMESTAMP = DbType('timestamp timestamptz')
137
+ INTERVAL = DbType('interval')
138
+ UUID = DbType('uuid')
139
+ HSTORE = DbType('hstore')
140
+ JSON = DbType('json jsonb')
141
+
142
+ # Type object for arrays (also equate to their base types):
143
+
144
+ ARRAY = ArrayType()
145
+
146
+ # Type object for records (encompassing all composite types):
147
+
148
+ RECORD = RecordType()
149
+
150
+
151
+ # Mandatory type helpers defined by DB-API 2 specs:
152
+
153
+ def Date(year: int, month: int, day: int) -> date: # noqa: N802
154
+ """Construct an object holding a date value."""
155
+ return date(year, month, day)
156
+
157
+
158
+ def Time(hour: int, minute: int = 0, # noqa: N802
159
+ second: int = 0, microsecond: int = 0,
160
+ tzinfo: tzinfo | None = None) -> time:
161
+ """Construct an object holding a time value."""
162
+ return time(hour, minute, second, microsecond, tzinfo)
163
+
164
+
165
+ def Timestamp(year: int, month: int, day: int, # noqa: N802
166
+ hour: int = 0, minute: int = 0,
167
+ second: int = 0, microsecond: int = 0,
168
+ tzinfo: tzinfo | None = None) -> datetime:
169
+ """Construct an object holding a time stamp value."""
170
+ return datetime(year, month, day, hour, minute,
171
+ second, microsecond, tzinfo)
172
+
173
+
174
+ def DateFromTicks(ticks: float | None) -> date: # noqa: N802
175
+ """Construct an object holding a date value from the given ticks value."""
176
+ return Date(*localtime(ticks)[:3])
177
+
178
+
179
+ def TimeFromTicks(ticks: float | None) -> time: # noqa: N802
180
+ """Construct an object holding a time value from the given ticks value."""
181
+ return Time(*localtime(ticks)[3:6])
182
+
183
+
184
+ def TimestampFromTicks(ticks: float | None) -> datetime: # noqa: N802
185
+ """Construct an object holding a time stamp from the given ticks value."""
186
+ return Timestamp(*localtime(ticks)[:6])
187
+
188
+
189
+ class Binary(bytes):
190
+ """Construct an object capable of holding a binary (long) string value."""
191
+
192
+
193
+ # Additional type helpers for PyGreSQL:
194
+
195
+ def Interval(days: int | float, # noqa: N802
196
+ hours: int | float = 0, minutes: int | float = 0,
197
+ seconds: int | float = 0, microseconds: int | float = 0
198
+ ) -> timedelta:
199
+ """Construct an object holding a time interval value."""
200
+ return timedelta(days, hours=hours, minutes=minutes,
201
+ seconds=seconds, microseconds=microseconds)
202
+
203
+
204
+ Uuid = Uuid # Construct an object holding a UUID value
205
+
206
+
207
+ class Hstore(dict):
208
+ """Wrapper class for marking hstore values."""
209
+
210
+ _re_quote = regex('^[Nn][Uu][Ll][Ll]$|[ ,=>]')
211
+ _re_escape = regex(r'(["\\])')
212
+
213
+ @classmethod
214
+ def _quote(cls, s: Any) -> Any:
215
+ if s is None:
216
+ return 'NULL'
217
+ if not isinstance(s, str):
218
+ s = str(s)
219
+ if not s:
220
+ return '""'
221
+ quote = cls._re_quote.search(s)
222
+ s = cls._re_escape.sub(r'\\\1', s)
223
+ if quote:
224
+ s = f'"{s}"'
225
+ return s
226
+
227
+ def __str__(self) -> str:
228
+ """Create a printable representation of the hstore value."""
229
+ q = self._quote
230
+ return ','.join(f'{q(k)}=>{q(v)}' for k, v in self.items())
231
+
232
+
233
+ class Json:
234
+ """Construct a wrapper for holding an object serializable to JSON."""
235
+
236
+ def __init__(self, obj: Any,
237
+ encode: Callable[[Any], str] | None = None) -> None:
238
+ """Initialize the JSON object."""
239
+ self.obj = obj
240
+ self.encode = encode or jsonencode
241
+
242
+ def __str__(self) -> str:
243
+ """Create a printable representation of the JSON object."""
244
+ obj = self.obj
245
+ if isinstance(obj, str):
246
+ return obj
247
+ return self.encode(obj)
248
+
249
+
250
+ class Literal:
251
+ """Construct a wrapper for holding a literal SQL string."""
252
+
253
+ def __init__(self, sql: str) -> None:
254
+ """Initialize literal SQL string."""
255
+ self.sql = sql
256
+
257
+ def __str__(self) -> str:
258
+ """Return a printable representation of the SQL string."""
259
+ return self.sql
260
+
261
+ __pg_repr__ = __str__