PyGreSQL 6.3.0b1__cp315-cp315-win_amd64.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.
- pg/__init__.py +192 -0
- pg/_pg.cp315-win_amd64.pyd +0 -0
- pg/_pg.pyi +739 -0
- pg/adapt.py +1033 -0
- pg/attrs.py +29 -0
- pg/cast.py +544 -0
- pg/core.py +180 -0
- pg/db.py +1557 -0
- pg/error.py +59 -0
- pg/helpers.py +283 -0
- pg/notify.py +158 -0
- pg/py.typed +4 -0
- pg/tz.py +21 -0
- pgdb/__init__.py +153 -0
- pgdb/adapt.py +329 -0
- pgdb/cast.py +775 -0
- pgdb/connect.py +73 -0
- pgdb/connection.py +164 -0
- pgdb/constants.py +14 -0
- pgdb/cursor.py +861 -0
- pgdb/py.typed +1 -0
- pgdb/typecode.py +40 -0
- pygresql-6.3.0b1.dist-info/METADATA +81 -0
- pygresql-6.3.0b1.dist-info/RECORD +27 -0
- pygresql-6.3.0b1.dist-info/WHEEL +5 -0
- pygresql-6.3.0b1.dist-info/licenses/LICENSE.txt +30 -0
- pygresql-6.3.0b1.dist-info/top_level.txt +2 -0
pg/attrs.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Helpers for memorizing attributes."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
__all__ = ['AttrDict']
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AttrDict(dict):
|
|
9
|
+
"""Simple read-only ordered dictionary for storing attribute names."""
|
|
10
|
+
|
|
11
|
+
def __init__(self, *args: Any, **kw: Any) -> None:
|
|
12
|
+
"""Initialize the dictionary."""
|
|
13
|
+
super().__init__(*args, **kw) # this does not call __setitem__
|
|
14
|
+
error = self._read_only_error
|
|
15
|
+
self.clear = self.update = error # type: ignore[method-assign]
|
|
16
|
+
self.pop = self.setdefault = self.popitem = error # type: ignore[method-assign]
|
|
17
|
+
|
|
18
|
+
def __setitem__(self, key: str, value: Any) -> None:
|
|
19
|
+
"""Set a value (not allowed)."""
|
|
20
|
+
self._read_only_error()
|
|
21
|
+
|
|
22
|
+
def __delitem__(self, key: str) -> None:
|
|
23
|
+
"""Delete a value (not allowed)."""
|
|
24
|
+
self._read_only_error()
|
|
25
|
+
|
|
26
|
+
@staticmethod
|
|
27
|
+
def _read_only_error(*_args: Any, **_kw: Any) -> Any:
|
|
28
|
+
"""Raise error for write operations."""
|
|
29
|
+
raise TypeError('This object is read-only')
|
pg/cast.py
ADDED
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
"""Typecasting mechanisms."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import namedtuple
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
from datetime import date, datetime, timedelta
|
|
8
|
+
from functools import partial
|
|
9
|
+
from inspect import signature
|
|
10
|
+
from ipaddress import (
|
|
11
|
+
IPv4Address,
|
|
12
|
+
IPv4Interface,
|
|
13
|
+
IPv4Network,
|
|
14
|
+
IPv6Address,
|
|
15
|
+
IPv6Interface,
|
|
16
|
+
IPv6Network,
|
|
17
|
+
ip_address,
|
|
18
|
+
ip_interface,
|
|
19
|
+
ip_network,
|
|
20
|
+
)
|
|
21
|
+
from keyword import iskeyword
|
|
22
|
+
from re import compile as regex
|
|
23
|
+
from typing import Any, ClassVar
|
|
24
|
+
from uuid import UUID
|
|
25
|
+
from warnings import warn
|
|
26
|
+
|
|
27
|
+
from .attrs import AttrDict
|
|
28
|
+
from .core import (
|
|
29
|
+
Connection,
|
|
30
|
+
cast_array,
|
|
31
|
+
cast_hstore,
|
|
32
|
+
cast_record,
|
|
33
|
+
get_bool,
|
|
34
|
+
get_decimal,
|
|
35
|
+
get_decimal_point,
|
|
36
|
+
get_jsondecode,
|
|
37
|
+
unescape_bytea,
|
|
38
|
+
)
|
|
39
|
+
from .tz import timezone_as_offset
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
'Typecasts',
|
|
43
|
+
'cast_bool',
|
|
44
|
+
'cast_cidr',
|
|
45
|
+
'cast_date',
|
|
46
|
+
'cast_inet',
|
|
47
|
+
'cast_int2vector',
|
|
48
|
+
'cast_interval',
|
|
49
|
+
'cast_json',
|
|
50
|
+
'cast_money',
|
|
51
|
+
'cast_num',
|
|
52
|
+
'cast_time',
|
|
53
|
+
'cast_timestamp',
|
|
54
|
+
'cast_timestamptz',
|
|
55
|
+
'cast_timetz',
|
|
56
|
+
'get_typecast',
|
|
57
|
+
'set_typecast'
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
def get_args(func: Callable) -> list:
|
|
61
|
+
"""Get the arguments of a function."""
|
|
62
|
+
return list(signature(func).parameters)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def cast_bool(value: str) -> Any:
|
|
66
|
+
"""Cast a boolean value."""
|
|
67
|
+
if not get_bool():
|
|
68
|
+
return value
|
|
69
|
+
return value[0] == 't'
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def cast_json(value: str) -> Any:
|
|
73
|
+
"""Cast a JSON value."""
|
|
74
|
+
cast = get_jsondecode()
|
|
75
|
+
if not cast:
|
|
76
|
+
return value
|
|
77
|
+
return cast(value)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def cast_num(value: str) -> Any:
|
|
81
|
+
"""Cast a numeric value."""
|
|
82
|
+
return (get_decimal() or float)(value)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def cast_money(value: str) -> Any:
|
|
86
|
+
"""Cast a money value."""
|
|
87
|
+
point = get_decimal_point()
|
|
88
|
+
if not point:
|
|
89
|
+
return value
|
|
90
|
+
# like in the C extension, keep only the digits, the decimal point
|
|
91
|
+
# and the sign, so that thousands separators are also removed
|
|
92
|
+
value = ''.join(
|
|
93
|
+
'.' if c == point else '-' if c in '(-' else c
|
|
94
|
+
for c in value if c.isdigit() or c == point or c in '(-')
|
|
95
|
+
return (get_decimal() or float)(value)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def cast_int2vector(value: str) -> list[int]:
|
|
99
|
+
"""Cast an int2vector value."""
|
|
100
|
+
return [int(v) for v in value.split()]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def cast_date(value: str, connection: Connection) -> Any:
|
|
104
|
+
"""Cast a date value."""
|
|
105
|
+
# The output format depends on the server setting DateStyle. The default
|
|
106
|
+
# setting ISO and the setting for German are actually unambiguous. The
|
|
107
|
+
# order of days and months in the other two settings is however ambiguous,
|
|
108
|
+
# so at least here we need to consult the setting to properly parse values.
|
|
109
|
+
if value == '-infinity':
|
|
110
|
+
return date.min
|
|
111
|
+
if value == 'infinity':
|
|
112
|
+
return date.max
|
|
113
|
+
values = value.split()
|
|
114
|
+
if values[-1] == 'BC':
|
|
115
|
+
return date.min
|
|
116
|
+
value = values[0]
|
|
117
|
+
if len(value) > 10:
|
|
118
|
+
return date.max
|
|
119
|
+
format = connection.date_format()
|
|
120
|
+
return datetime.strptime(value, format).date()
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cast_time(value: str) -> Any:
|
|
124
|
+
"""Cast a time value."""
|
|
125
|
+
format = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
|
|
126
|
+
return datetime.strptime(value, format).time()
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
_re_timezone = regex('(.*)([+-].*)')
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def cast_timetz(value: str) -> Any:
|
|
133
|
+
"""Cast a timetz value."""
|
|
134
|
+
m = _re_timezone.match(value)
|
|
135
|
+
if m:
|
|
136
|
+
value, tz = m.groups()
|
|
137
|
+
else:
|
|
138
|
+
tz = '+0000'
|
|
139
|
+
format = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
|
|
140
|
+
value += timezone_as_offset(tz)
|
|
141
|
+
format += '%z'
|
|
142
|
+
return datetime.strptime(value, format).timetz()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def cast_timestamp(value: str, connection: Connection) -> Any:
|
|
146
|
+
"""Cast a timestamp value."""
|
|
147
|
+
if value == '-infinity':
|
|
148
|
+
return datetime.min
|
|
149
|
+
if value == 'infinity':
|
|
150
|
+
return datetime.max
|
|
151
|
+
values = value.split()
|
|
152
|
+
if values[-1] == 'BC':
|
|
153
|
+
return datetime.min
|
|
154
|
+
format = connection.date_format()
|
|
155
|
+
if format.endswith('-%Y') and len(values) > 2:
|
|
156
|
+
values = values[1:5]
|
|
157
|
+
if len(values[3]) > 4:
|
|
158
|
+
return datetime.max
|
|
159
|
+
formats = ['%d %b' if format.startswith('%d') else '%b %d',
|
|
160
|
+
'%H:%M:%S.%f' if len(values[2]) > 8 else '%H:%M:%S', '%Y']
|
|
161
|
+
else:
|
|
162
|
+
if len(values[0]) > 10:
|
|
163
|
+
return datetime.max
|
|
164
|
+
formats = [format, '%H:%M:%S.%f' if len(values[1]) > 8 else '%H:%M:%S']
|
|
165
|
+
return datetime.strptime(' '.join(values), ' '.join(formats))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def cast_timestamptz(value: str, connection: Connection) -> Any:
|
|
169
|
+
"""Cast a timestamptz value."""
|
|
170
|
+
if value == '-infinity':
|
|
171
|
+
return datetime.min
|
|
172
|
+
if value == 'infinity':
|
|
173
|
+
return datetime.max
|
|
174
|
+
values = value.split()
|
|
175
|
+
if values[-1] == 'BC':
|
|
176
|
+
return datetime.min
|
|
177
|
+
format = connection.date_format()
|
|
178
|
+
if format.endswith('-%Y') and len(values) > 2:
|
|
179
|
+
values = values[1:]
|
|
180
|
+
if len(values[3]) > 4:
|
|
181
|
+
return datetime.max
|
|
182
|
+
formats = ['%d %b' if format.startswith('%d') else '%b %d',
|
|
183
|
+
'%H:%M:%S.%f' if len(values[2]) > 8 else '%H:%M:%S', '%Y']
|
|
184
|
+
values, tz = values[:-1], values[-1]
|
|
185
|
+
else:
|
|
186
|
+
if format.startswith('%Y-'):
|
|
187
|
+
m = _re_timezone.match(values[1])
|
|
188
|
+
if m:
|
|
189
|
+
values[1], tz = m.groups()
|
|
190
|
+
else:
|
|
191
|
+
tz = '+0000'
|
|
192
|
+
else:
|
|
193
|
+
values, tz = values[:-1], values[-1]
|
|
194
|
+
if len(values[0]) > 10:
|
|
195
|
+
return datetime.max
|
|
196
|
+
formats = [format, '%H:%M:%S.%f' if len(values[1]) > 8 else '%H:%M:%S']
|
|
197
|
+
values.append(timezone_as_offset(tz))
|
|
198
|
+
formats.append('%z')
|
|
199
|
+
return datetime.strptime(' '.join(values), ' '.join(formats))
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
_re_interval_sql_standard = regex(
|
|
203
|
+
'(?:([+-])?([0-9]+)-([0-9]+) ?)?'
|
|
204
|
+
'(?:([+-]?[0-9]+)(?!:) ?)?'
|
|
205
|
+
'(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
|
|
206
|
+
|
|
207
|
+
_re_interval_postgres = regex(
|
|
208
|
+
'(?:([+-]?[0-9]+) ?years? ?)?'
|
|
209
|
+
'(?:([+-]?[0-9]+) ?mons? ?)?'
|
|
210
|
+
'(?:([+-]?[0-9]+) ?days? ?)?'
|
|
211
|
+
'(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
|
|
212
|
+
|
|
213
|
+
_re_interval_postgres_verbose = regex(
|
|
214
|
+
'@ ?(?:([+-]?[0-9]+) ?years? ?)?'
|
|
215
|
+
'(?:([+-]?[0-9]+) ?mons? ?)?'
|
|
216
|
+
'(?:([+-]?[0-9]+) ?days? ?)?'
|
|
217
|
+
'(?:([+-]?[0-9]+) ?hours? ?)?'
|
|
218
|
+
'(?:([+-]?[0-9]+) ?mins? ?)?'
|
|
219
|
+
'(?:([+-])?([0-9]+)(?:\\.([0-9]+))? ?secs?)? ?(ago)?')
|
|
220
|
+
|
|
221
|
+
_re_interval_iso_8601 = regex(
|
|
222
|
+
'P(?:([+-]?[0-9]+)Y)?'
|
|
223
|
+
'(?:([+-]?[0-9]+)M)?'
|
|
224
|
+
'(?:([+-]?[0-9]+)D)?'
|
|
225
|
+
'(?:T(?:([+-]?[0-9]+)H)?'
|
|
226
|
+
'(?:([+-]?[0-9]+)M)?'
|
|
227
|
+
'(?:([+-])?([0-9]+)(?:\\.([0-9]+))?S)?)?')
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def cast_interval(value: str) -> timedelta:
|
|
231
|
+
"""Cast an interval value."""
|
|
232
|
+
# The output format depends on the server setting IntervalStyle, but it's
|
|
233
|
+
# not necessary to consult this setting to parse it. It's faster to just
|
|
234
|
+
# check all possible formats, and there is no ambiguity here.
|
|
235
|
+
if value == 'infinity': # possible since PostgreSQL 17
|
|
236
|
+
return timedelta.max
|
|
237
|
+
if value == '-infinity':
|
|
238
|
+
return timedelta.min
|
|
239
|
+
m = _re_interval_iso_8601.match(value)
|
|
240
|
+
if m:
|
|
241
|
+
s = [v or '0' for v in m.groups()]
|
|
242
|
+
secs_ago = s.pop(5) == '-'
|
|
243
|
+
d = [int(v) for v in s]
|
|
244
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
245
|
+
if secs_ago:
|
|
246
|
+
secs = -secs
|
|
247
|
+
usecs = -usecs
|
|
248
|
+
else:
|
|
249
|
+
m = _re_interval_postgres_verbose.match(value)
|
|
250
|
+
if m:
|
|
251
|
+
s, ago = [v or '0' for v in m.groups()[:8]], m.group(9)
|
|
252
|
+
secs_ago = s.pop(5) == '-'
|
|
253
|
+
d = [-int(v) for v in s] if ago else [int(v) for v in s]
|
|
254
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
255
|
+
if secs_ago:
|
|
256
|
+
secs = - secs
|
|
257
|
+
usecs = -usecs
|
|
258
|
+
else:
|
|
259
|
+
m = _re_interval_postgres.match(value)
|
|
260
|
+
if m and any(m.groups()):
|
|
261
|
+
s = [v or '0' for v in m.groups()]
|
|
262
|
+
hours_ago = s.pop(3) == '-'
|
|
263
|
+
d = [int(v) for v in s]
|
|
264
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
265
|
+
if hours_ago:
|
|
266
|
+
hours = -hours
|
|
267
|
+
mins = -mins
|
|
268
|
+
secs = -secs
|
|
269
|
+
usecs = -usecs
|
|
270
|
+
else:
|
|
271
|
+
m = _re_interval_sql_standard.match(value)
|
|
272
|
+
if m and any(m.groups()):
|
|
273
|
+
s = [v or '0' for v in m.groups()]
|
|
274
|
+
years_ago = s.pop(0) == '-'
|
|
275
|
+
hours_ago = s.pop(3) == '-'
|
|
276
|
+
d = [int(v) for v in s]
|
|
277
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
278
|
+
if years_ago:
|
|
279
|
+
years = -years
|
|
280
|
+
mons = -mons
|
|
281
|
+
if hours_ago:
|
|
282
|
+
hours = -hours
|
|
283
|
+
mins = -mins
|
|
284
|
+
secs = -secs
|
|
285
|
+
usecs = -usecs
|
|
286
|
+
else:
|
|
287
|
+
raise ValueError(f'Cannot parse interval: {value}')
|
|
288
|
+
days += 365 * years + 30 * mons
|
|
289
|
+
return timedelta(days=days, hours=hours, minutes=mins,
|
|
290
|
+
seconds=secs, microseconds=usecs)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def cast_inet(value: str) -> (IPv4Address | IPv6Address
|
|
294
|
+
| IPv4Interface | IPv6Interface):
|
|
295
|
+
"""Cast an inet value to an IP address or interface.
|
|
296
|
+
|
|
297
|
+
Values with a prefix length are cast to an interface, other values
|
|
298
|
+
to an address, like in psycopg 3. This cast function is not used by
|
|
299
|
+
default, but can be set with set_typecast('inet', cast_inet).
|
|
300
|
+
"""
|
|
301
|
+
return ip_interface(value) if '/' in value else ip_address(value)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def cast_cidr(value: str) -> IPv4Network | IPv6Network:
|
|
305
|
+
"""Cast a cidr value to an IP network.
|
|
306
|
+
|
|
307
|
+
This cast function is not used by default, but can be set with
|
|
308
|
+
set_typecast('cidr', cast_cidr).
|
|
309
|
+
"""
|
|
310
|
+
return ip_network(value)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class Typecasts(dict):
|
|
314
|
+
"""Dictionary mapping database types to typecast functions.
|
|
315
|
+
|
|
316
|
+
The cast functions get passed the string representation of a value in
|
|
317
|
+
the database which they need to convert to a Python object. The
|
|
318
|
+
passed string will never be None since NULL values are already
|
|
319
|
+
handled before the cast function is called.
|
|
320
|
+
|
|
321
|
+
Note that the basic types are already handled by the C extension.
|
|
322
|
+
They only need to be handled here as record or array components.
|
|
323
|
+
"""
|
|
324
|
+
|
|
325
|
+
# the default cast functions
|
|
326
|
+
# (str functions are ignored but have been added for faster access)
|
|
327
|
+
defaults: ClassVar[dict[str, Callable]] = {
|
|
328
|
+
'char': str, 'bpchar': str, 'name': str,
|
|
329
|
+
'text': str, 'varchar': str, 'sql_identifier': str,
|
|
330
|
+
'bool': cast_bool, 'bytea': unescape_bytea,
|
|
331
|
+
'int2': int, 'int4': int, 'serial': int, 'int8': int, 'oid': int,
|
|
332
|
+
'oid8': int,
|
|
333
|
+
'hstore': cast_hstore, 'json': cast_json, 'jsonb': cast_json,
|
|
334
|
+
'float4': float, 'float8': float,
|
|
335
|
+
'numeric': cast_num, 'money': cast_money,
|
|
336
|
+
'date': cast_date, 'interval': cast_interval,
|
|
337
|
+
'time': cast_time, 'timetz': cast_timetz,
|
|
338
|
+
'timestamp': cast_timestamp, 'timestamptz': cast_timestamptz,
|
|
339
|
+
'int2vector': cast_int2vector, 'uuid': UUID,
|
|
340
|
+
'anyarray': cast_array, 'record': cast_record}
|
|
341
|
+
|
|
342
|
+
connection: Connection | None = None # set in connection specific instance
|
|
343
|
+
|
|
344
|
+
# incremented when the defaults change, so that connections can drop
|
|
345
|
+
# the typecasts they have derived from the old defaults
|
|
346
|
+
defaults_changed: ClassVar[int] = 0
|
|
347
|
+
|
|
348
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
349
|
+
"""Initialize the typecasts."""
|
|
350
|
+
super().__init__(*args, **kwargs)
|
|
351
|
+
self._records: set[str] = set() # types with cached record casts
|
|
352
|
+
|
|
353
|
+
def _drop_record_casts(self) -> None:
|
|
354
|
+
"""Drop the cached casts for composite types.
|
|
355
|
+
|
|
356
|
+
These casts use the casts for their fields, which may change.
|
|
357
|
+
They will be created again when needed.
|
|
358
|
+
"""
|
|
359
|
+
for typ in self._records:
|
|
360
|
+
self.pop(typ, None)
|
|
361
|
+
self._records.clear()
|
|
362
|
+
|
|
363
|
+
def __missing__(self, typ: str) -> Callable | None:
|
|
364
|
+
"""Create a cast function if it is not cached.
|
|
365
|
+
|
|
366
|
+
Note that this class never raises a KeyError,
|
|
367
|
+
but returns None when no special cast function exists.
|
|
368
|
+
"""
|
|
369
|
+
if not isinstance(typ, str):
|
|
370
|
+
raise TypeError(f'Invalid type: {typ}')
|
|
371
|
+
cast: Callable | None = self.defaults.get(typ)
|
|
372
|
+
if cast:
|
|
373
|
+
# store default for faster access
|
|
374
|
+
cast = self._add_connection(cast)
|
|
375
|
+
self[typ] = cast
|
|
376
|
+
elif typ.startswith('_'):
|
|
377
|
+
# array casts derived from the name are not cached,
|
|
378
|
+
# since the name might not be the name of an array type
|
|
379
|
+
cast = self.create_array_cast(self[typ[1:]])
|
|
380
|
+
else:
|
|
381
|
+
attnames = self.get_attnames(typ)
|
|
382
|
+
if attnames:
|
|
383
|
+
casts = [self[v.pgtype] for v in attnames.values()]
|
|
384
|
+
cast = self.create_record_cast(typ, attnames, casts)
|
|
385
|
+
self[typ] = cast
|
|
386
|
+
self._records.add(typ)
|
|
387
|
+
return cast
|
|
388
|
+
|
|
389
|
+
@staticmethod
|
|
390
|
+
def _needs_connection(func: Callable) -> bool:
|
|
391
|
+
"""Check if a typecast function needs a connection argument."""
|
|
392
|
+
try:
|
|
393
|
+
args = get_args(func)
|
|
394
|
+
except (TypeError, ValueError):
|
|
395
|
+
return False
|
|
396
|
+
return 'connection' in args[1:]
|
|
397
|
+
|
|
398
|
+
def _add_connection(self, cast: Callable) -> Callable:
|
|
399
|
+
"""Add a connection argument to the typecast function if necessary."""
|
|
400
|
+
if not self.connection or not self._needs_connection(cast):
|
|
401
|
+
return cast
|
|
402
|
+
return partial(cast, connection=self.connection)
|
|
403
|
+
|
|
404
|
+
def get(self, typ: str, default: Callable | None = None # type: ignore[override]
|
|
405
|
+
) -> Callable | None:
|
|
406
|
+
"""Get the typecast function for the given database type."""
|
|
407
|
+
return self[typ] or default
|
|
408
|
+
|
|
409
|
+
def set(self, typ: str | Sequence[str], cast: Callable | None) -> None:
|
|
410
|
+
"""Set a typecast function for the specified database type(s)."""
|
|
411
|
+
self._drop_record_casts()
|
|
412
|
+
if isinstance(typ, str):
|
|
413
|
+
typ = [typ]
|
|
414
|
+
if cast is None:
|
|
415
|
+
for t in typ:
|
|
416
|
+
self.pop(t, None)
|
|
417
|
+
else:
|
|
418
|
+
if not callable(cast):
|
|
419
|
+
raise TypeError("Cast parameter must be callable")
|
|
420
|
+
for t in typ:
|
|
421
|
+
self[t] = self._add_connection(cast)
|
|
422
|
+
|
|
423
|
+
def reset(self, typ: str | Sequence[str] | None = None) -> None:
|
|
424
|
+
"""Reset the typecasts for the specified type(s) to their defaults.
|
|
425
|
+
|
|
426
|
+
When no type is specified, all typecasts will be reset.
|
|
427
|
+
"""
|
|
428
|
+
self._drop_record_casts()
|
|
429
|
+
if typ is None:
|
|
430
|
+
self.clear()
|
|
431
|
+
else:
|
|
432
|
+
if isinstance(typ, str):
|
|
433
|
+
typ = [typ]
|
|
434
|
+
for t in typ:
|
|
435
|
+
self.pop(t, None)
|
|
436
|
+
|
|
437
|
+
@classmethod
|
|
438
|
+
def get_default(cls, typ: str) -> Any:
|
|
439
|
+
"""Get the default typecast function for the given database type."""
|
|
440
|
+
return cls.defaults.get(typ)
|
|
441
|
+
|
|
442
|
+
@classmethod
|
|
443
|
+
def set_default(cls, typ: str | Sequence[str],
|
|
444
|
+
cast: Callable | None) -> None:
|
|
445
|
+
"""Set a default typecast function for the given database type(s)."""
|
|
446
|
+
if isinstance(typ, str):
|
|
447
|
+
typ = [typ]
|
|
448
|
+
defaults = cls.defaults
|
|
449
|
+
Typecasts.defaults_changed += 1
|
|
450
|
+
if cast is None:
|
|
451
|
+
for t in typ:
|
|
452
|
+
defaults.pop(t, None)
|
|
453
|
+
else:
|
|
454
|
+
if not callable(cast):
|
|
455
|
+
raise TypeError("Cast parameter must be callable")
|
|
456
|
+
for t in typ:
|
|
457
|
+
defaults[t] = cast
|
|
458
|
+
|
|
459
|
+
# noinspection PyMethodMayBeStatic,PyUnusedLocal
|
|
460
|
+
def get_attnames(self, typ: Any) -> AttrDict:
|
|
461
|
+
"""Return the fields for the given record type.
|
|
462
|
+
|
|
463
|
+
This method can be overridden in subclasses to support casting
|
|
464
|
+
composite types by name. Connections do not use it, since DbTypes
|
|
465
|
+
creates the typecasts for composite types from their type objects.
|
|
466
|
+
"""
|
|
467
|
+
return AttrDict()
|
|
468
|
+
|
|
469
|
+
# noinspection PyMethodMayBeStatic
|
|
470
|
+
def dateformat(self) -> str:
|
|
471
|
+
"""Return the ISO date format (deprecated).
|
|
472
|
+
|
|
473
|
+
This method has never been used and does not consider the DateStyle
|
|
474
|
+
of the connection. Use Connection.date_format() instead. It will be
|
|
475
|
+
removed in version 7.0.
|
|
476
|
+
"""
|
|
477
|
+
warn('Typecasts.dateformat() is deprecated,'
|
|
478
|
+
' use Connection.date_format() instead',
|
|
479
|
+
DeprecationWarning, stacklevel=2)
|
|
480
|
+
return '%Y-%m-%d'
|
|
481
|
+
|
|
482
|
+
def create_array_cast(self, basecast: Callable | None,
|
|
483
|
+
delim: str = ',') -> Callable:
|
|
484
|
+
"""Create an array typecast for the given base cast and delimiter."""
|
|
485
|
+
cast_array = self['anyarray']
|
|
486
|
+
# values that cannot be decoded are passed as bytes, keep them
|
|
487
|
+
elemcast = None if basecast is str else basecast
|
|
488
|
+
|
|
489
|
+
if delim != ',':
|
|
490
|
+
delim_bytes = delim.encode('ascii')
|
|
491
|
+
|
|
492
|
+
def cast(v: Any) -> list:
|
|
493
|
+
return cast_array(v, elemcast, delim_bytes)
|
|
494
|
+
else:
|
|
495
|
+
def cast(v: Any) -> list:
|
|
496
|
+
return cast_array(v, elemcast)
|
|
497
|
+
return cast
|
|
498
|
+
|
|
499
|
+
def create_record_cast(self, name: str, fields: AttrDict,
|
|
500
|
+
casts: Sequence[Callable | None]) -> Callable:
|
|
501
|
+
"""Create a named record typecast for the given fields and casts."""
|
|
502
|
+
cast_record = self['record']
|
|
503
|
+
if not name.isidentifier() or iskeyword(name):
|
|
504
|
+
name = 'Record' # the type name cannot be used in Python
|
|
505
|
+
# field names that cannot be used in Python are renamed
|
|
506
|
+
record = namedtuple(name, fields, rename=True) # type: ignore[misc]
|
|
507
|
+
# values that cannot be decoded are passed as bytes, keep them
|
|
508
|
+
fieldcasts = [None if c is str else c for c in casts]
|
|
509
|
+
|
|
510
|
+
def cast(v: Any) -> record:
|
|
511
|
+
# noinspection PyArgumentList
|
|
512
|
+
return record(*cast_record(v, fieldcasts))
|
|
513
|
+
return cast
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
# the built-in default typecasts, before they can be changed
|
|
517
|
+
_builtin_typecasts = dict(Typecasts.defaults)
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def is_builtin_typecast(typ: str, cast: Callable | None) -> bool:
|
|
521
|
+
"""Check whether this is the built-in default typecast for the type.
|
|
522
|
+
|
|
523
|
+
The built-in default typecasts are made for the base types of
|
|
524
|
+
PostgreSQL. They should not be used for composite types, domains,
|
|
525
|
+
enums and ranges that happen to have the same name in another schema,
|
|
526
|
+
unlike typecasts that have been set explicitly for the name.
|
|
527
|
+
"""
|
|
528
|
+
if isinstance(cast, partial): # with an added connection
|
|
529
|
+
cast = cast.func
|
|
530
|
+
return cast is not None and cast is _builtin_typecasts.get(typ)
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def get_typecast(typ: str) -> Callable | None:
|
|
534
|
+
"""Get the global typecast function for the given database type."""
|
|
535
|
+
return Typecasts.get_default(typ)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def set_typecast(typ: str | Sequence[str], cast: Callable | None) -> None:
|
|
539
|
+
"""Set a global typecast function for the given database type(s).
|
|
540
|
+
|
|
541
|
+
Note that connections cache cast functions. To be sure a global change
|
|
542
|
+
is picked up by a running connection, call db.dbtypes.reset_typecast().
|
|
543
|
+
"""
|
|
544
|
+
Typecasts.set_default(typ, cast)
|