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.
- PyGreSQL-6.1.0.dist-info/LICENSE.txt +30 -0
- PyGreSQL-6.1.0.dist-info/METADATA +112 -0
- PyGreSQL-6.1.0.dist-info/RECORD +27 -0
- PyGreSQL-6.1.0.dist-info/WHEEL +5 -0
- PyGreSQL-6.1.0.dist-info/top_level.txt +2 -0
- pg/__init__.py +186 -0
- pg/_pg.cp313-win32.pyd +0 -0
- pg/_pg.pyi +638 -0
- pg/adapt.py +686 -0
- pg/attrs.py +35 -0
- pg/cast.py +446 -0
- pg/core.py +180 -0
- pg/db.py +1502 -0
- pg/error.py +59 -0
- pg/helpers.py +124 -0
- pg/notify.py +149 -0
- pg/py.typed +4 -0
- pg/tz.py +21 -0
- pgdb/__init__.py +182 -0
- pgdb/adapt.py +261 -0
- pgdb/cast.py +594 -0
- pgdb/connect.py +74 -0
- pgdb/connection.py +156 -0
- pgdb/constants.py +14 -0
- pgdb/cursor.py +645 -0
- pgdb/py.typed +1 -0
- pgdb/typecode.py +34 -0
pgdb/cast.py
ADDED
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
"""Internal type handling."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import namedtuple
|
|
6
|
+
from datetime import date, datetime, time, timedelta
|
|
7
|
+
from decimal import Decimal as _Decimal
|
|
8
|
+
from functools import partial
|
|
9
|
+
from inspect import signature
|
|
10
|
+
from json import loads as jsondecode
|
|
11
|
+
from re import compile as regex
|
|
12
|
+
from typing import Any, Callable, ClassVar, Sequence
|
|
13
|
+
from uuid import UUID as Uuid # noqa: N811
|
|
14
|
+
|
|
15
|
+
from pg.core import Connection as Cnx
|
|
16
|
+
from pg.core import (
|
|
17
|
+
ProgrammingError,
|
|
18
|
+
cast_array,
|
|
19
|
+
cast_hstore,
|
|
20
|
+
cast_record,
|
|
21
|
+
unescape_bytea,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
from .typecode import TypeCode
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
'Decimal',
|
|
28
|
+
'FieldInfo',
|
|
29
|
+
'LocalTypecasts',
|
|
30
|
+
'TypeCache',
|
|
31
|
+
'Typecasts',
|
|
32
|
+
'cast_bool',
|
|
33
|
+
'cast_date',
|
|
34
|
+
'cast_int2vector',
|
|
35
|
+
'cast_interval',
|
|
36
|
+
'cast_money',
|
|
37
|
+
'cast_time',
|
|
38
|
+
'cast_timestamp',
|
|
39
|
+
'cast_timestamptz',
|
|
40
|
+
'cast_timetz',
|
|
41
|
+
'decimal_type',
|
|
42
|
+
'get_typecast',
|
|
43
|
+
'reset_typecast',
|
|
44
|
+
'set_typecast'
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
Decimal: type = _Decimal
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def get_args(func: Callable) -> list:
|
|
52
|
+
return list(signature(func).parameters)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# time zones used in Postgres timestamptz output
|
|
56
|
+
_timezones: dict[str, str] = {
|
|
57
|
+
'CET': '+0100', 'EET': '+0200', 'EST': '-0500',
|
|
58
|
+
'GMT': '+0000', 'HST': '-1000', 'MET': '+0100', 'MST': '-0700',
|
|
59
|
+
'UCT': '+0000', 'UTC': '+0000', 'WET': '+0000'
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _timezone_as_offset(tz: str) -> str:
|
|
64
|
+
if tz.startswith(('+', '-')):
|
|
65
|
+
if len(tz) < 5:
|
|
66
|
+
return tz + '00'
|
|
67
|
+
return tz.replace(':', '')
|
|
68
|
+
return _timezones.get(tz, '+0000')
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def decimal_type(decimal_type: type | None = None) -> type:
|
|
72
|
+
"""Get or set global type to be used for decimal values.
|
|
73
|
+
|
|
74
|
+
Note that connections cache cast functions. To be sure a global change
|
|
75
|
+
is picked up by a running connection, call con.type_cache.reset_typecast().
|
|
76
|
+
"""
|
|
77
|
+
global Decimal
|
|
78
|
+
if decimal_type is not None:
|
|
79
|
+
Decimal = decimal_type
|
|
80
|
+
set_typecast('numeric', decimal_type)
|
|
81
|
+
return Decimal
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def cast_bool(value: str) -> bool | None:
|
|
85
|
+
"""Cast boolean value in database format to bool."""
|
|
86
|
+
return value[0] in ('t', 'T') if value else None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cast_money(value: str) -> _Decimal | None:
|
|
90
|
+
"""Cast money value in database format to Decimal."""
|
|
91
|
+
if not value:
|
|
92
|
+
return None
|
|
93
|
+
value = value.replace('(', '-')
|
|
94
|
+
return Decimal(''.join(c for c in value if c.isdigit() or c in '.-'))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cast_int2vector(value: str) -> list[int]:
|
|
98
|
+
"""Cast an int2vector value."""
|
|
99
|
+
return [int(v) for v in value.split()]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def cast_date(value: str, cnx: Cnx) -> date:
|
|
103
|
+
"""Cast a date value."""
|
|
104
|
+
# The output format depends on the server setting DateStyle. The default
|
|
105
|
+
# setting ISO and the setting for German are actually unambiguous. The
|
|
106
|
+
# order of days and months in the other two settings is however ambiguous,
|
|
107
|
+
# so at least here we need to consult the setting to properly parse values.
|
|
108
|
+
if value == '-infinity':
|
|
109
|
+
return date.min
|
|
110
|
+
if value == 'infinity':
|
|
111
|
+
return date.max
|
|
112
|
+
values = value.split()
|
|
113
|
+
if values[-1] == 'BC':
|
|
114
|
+
return date.min
|
|
115
|
+
value = values[0]
|
|
116
|
+
if len(value) > 10:
|
|
117
|
+
return date.max
|
|
118
|
+
format = cnx.date_format()
|
|
119
|
+
return datetime.strptime(value, format).date()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def cast_time(value: str) -> time:
|
|
123
|
+
"""Cast a time value."""
|
|
124
|
+
fmt = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
|
|
125
|
+
return datetime.strptime(value, fmt).time()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
_re_timezone = regex('(.*)([+-].*)')
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def cast_timetz(value: str) -> time:
|
|
132
|
+
"""Cast a timetz value."""
|
|
133
|
+
m = _re_timezone.match(value)
|
|
134
|
+
if m:
|
|
135
|
+
value, tz = m.groups()
|
|
136
|
+
else:
|
|
137
|
+
tz = '+0000'
|
|
138
|
+
format = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
|
|
139
|
+
value += _timezone_as_offset(tz)
|
|
140
|
+
format += '%z'
|
|
141
|
+
return datetime.strptime(value, format).timetz()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def cast_timestamp(value: str, cnx: Cnx) -> datetime:
|
|
145
|
+
"""Cast a timestamp value."""
|
|
146
|
+
if value == '-infinity':
|
|
147
|
+
return datetime.min
|
|
148
|
+
if value == 'infinity':
|
|
149
|
+
return datetime.max
|
|
150
|
+
values = value.split()
|
|
151
|
+
if values[-1] == 'BC':
|
|
152
|
+
return datetime.min
|
|
153
|
+
format = cnx.date_format()
|
|
154
|
+
if format.endswith('-%Y') and len(values) > 2:
|
|
155
|
+
values = values[1:5]
|
|
156
|
+
if len(values[3]) > 4:
|
|
157
|
+
return datetime.max
|
|
158
|
+
formats = ['%d %b' if format.startswith('%d') else '%b %d',
|
|
159
|
+
'%H:%M:%S.%f' if len(values[2]) > 8 else '%H:%M:%S', '%Y']
|
|
160
|
+
else:
|
|
161
|
+
if len(values[0]) > 10:
|
|
162
|
+
return datetime.max
|
|
163
|
+
formats = [format, '%H:%M:%S.%f' if len(values[1]) > 8 else '%H:%M:%S']
|
|
164
|
+
return datetime.strptime(' '.join(values), ' '.join(formats))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def cast_timestamptz(value: str, cnx: Cnx) -> datetime:
|
|
168
|
+
"""Cast a timestamptz value."""
|
|
169
|
+
if value == '-infinity':
|
|
170
|
+
return datetime.min
|
|
171
|
+
if value == 'infinity':
|
|
172
|
+
return datetime.max
|
|
173
|
+
values = value.split()
|
|
174
|
+
if values[-1] == 'BC':
|
|
175
|
+
return datetime.min
|
|
176
|
+
format = cnx.date_format()
|
|
177
|
+
if format.endswith('-%Y') and len(values) > 2:
|
|
178
|
+
values = values[1:]
|
|
179
|
+
if len(values[3]) > 4:
|
|
180
|
+
return datetime.max
|
|
181
|
+
formats = ['%d %b' if format.startswith('%d') else '%b %d',
|
|
182
|
+
'%H:%M:%S.%f' if len(values[2]) > 8 else '%H:%M:%S', '%Y']
|
|
183
|
+
values, tz = values[:-1], values[-1]
|
|
184
|
+
else:
|
|
185
|
+
if format.startswith('%Y-'):
|
|
186
|
+
m = _re_timezone.match(values[1])
|
|
187
|
+
if m:
|
|
188
|
+
values[1], tz = m.groups()
|
|
189
|
+
else:
|
|
190
|
+
tz = '+0000'
|
|
191
|
+
else:
|
|
192
|
+
values, tz = values[:-1], values[-1]
|
|
193
|
+
if len(values[0]) > 10:
|
|
194
|
+
return datetime.max
|
|
195
|
+
formats = [format, '%H:%M:%S.%f' if len(values[1]) > 8 else '%H:%M:%S']
|
|
196
|
+
values.append(_timezone_as_offset(tz))
|
|
197
|
+
formats.append('%z')
|
|
198
|
+
return datetime.strptime(' '.join(values), ' '.join(formats))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
_re_interval_sql_standard = regex(
|
|
202
|
+
'(?:([+-])?([0-9]+)-([0-9]+) ?)?'
|
|
203
|
+
'(?:([+-]?[0-9]+)(?!:) ?)?'
|
|
204
|
+
'(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
|
|
205
|
+
|
|
206
|
+
_re_interval_postgres = regex(
|
|
207
|
+
'(?:([+-]?[0-9]+) ?years? ?)?'
|
|
208
|
+
'(?:([+-]?[0-9]+) ?mons? ?)?'
|
|
209
|
+
'(?:([+-]?[0-9]+) ?days? ?)?'
|
|
210
|
+
'(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
|
|
211
|
+
|
|
212
|
+
_re_interval_postgres_verbose = regex(
|
|
213
|
+
'@ ?(?:([+-]?[0-9]+) ?years? ?)?'
|
|
214
|
+
'(?:([+-]?[0-9]+) ?mons? ?)?'
|
|
215
|
+
'(?:([+-]?[0-9]+) ?days? ?)?'
|
|
216
|
+
'(?:([+-]?[0-9]+) ?hours? ?)?'
|
|
217
|
+
'(?:([+-]?[0-9]+) ?mins? ?)?'
|
|
218
|
+
'(?:([+-])?([0-9]+)(?:\\.([0-9]+))? ?secs?)? ?(ago)?')
|
|
219
|
+
|
|
220
|
+
_re_interval_iso_8601 = regex(
|
|
221
|
+
'P(?:([+-]?[0-9]+)Y)?'
|
|
222
|
+
'(?:([+-]?[0-9]+)M)?'
|
|
223
|
+
'(?:([+-]?[0-9]+)D)?'
|
|
224
|
+
'(?:T(?:([+-]?[0-9]+)H)?'
|
|
225
|
+
'(?:([+-]?[0-9]+)M)?'
|
|
226
|
+
'(?:([+-])?([0-9]+)(?:\\.([0-9]+))?S)?)?')
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def cast_interval(value: str) -> timedelta:
|
|
230
|
+
"""Cast an interval value."""
|
|
231
|
+
# The output format depends on the server setting IntervalStyle, but it's
|
|
232
|
+
# not necessary to consult this setting to parse it. It's faster to just
|
|
233
|
+
# check all possible formats, and there is no ambiguity here.
|
|
234
|
+
m = _re_interval_iso_8601.match(value)
|
|
235
|
+
if m:
|
|
236
|
+
s = [v or '0' for v in m.groups()]
|
|
237
|
+
secs_ago = s.pop(5) == '-'
|
|
238
|
+
d = [int(v) for v in s]
|
|
239
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
240
|
+
if secs_ago:
|
|
241
|
+
secs = -secs
|
|
242
|
+
usecs = -usecs
|
|
243
|
+
else:
|
|
244
|
+
m = _re_interval_postgres_verbose.match(value)
|
|
245
|
+
if m:
|
|
246
|
+
s, ago = [v or '0' for v in m.groups()[:8]], m.group(9)
|
|
247
|
+
secs_ago = s.pop(5) == '-'
|
|
248
|
+
d = [-int(v) for v in s] if ago else [int(v) for v in s]
|
|
249
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
250
|
+
if secs_ago:
|
|
251
|
+
secs = - secs
|
|
252
|
+
usecs = -usecs
|
|
253
|
+
else:
|
|
254
|
+
m = _re_interval_postgres.match(value)
|
|
255
|
+
if m and any(m.groups()):
|
|
256
|
+
s = [v or '0' for v in m.groups()]
|
|
257
|
+
hours_ago = s.pop(3) == '-'
|
|
258
|
+
d = [int(v) for v in s]
|
|
259
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
260
|
+
if hours_ago:
|
|
261
|
+
hours = -hours
|
|
262
|
+
mins = -mins
|
|
263
|
+
secs = -secs
|
|
264
|
+
usecs = -usecs
|
|
265
|
+
else:
|
|
266
|
+
m = _re_interval_sql_standard.match(value)
|
|
267
|
+
if m and any(m.groups()):
|
|
268
|
+
s = [v or '0' for v in m.groups()]
|
|
269
|
+
years_ago = s.pop(0) == '-'
|
|
270
|
+
hours_ago = s.pop(3) == '-'
|
|
271
|
+
d = [int(v) for v in s]
|
|
272
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
273
|
+
if years_ago:
|
|
274
|
+
years = -years
|
|
275
|
+
mons = -mons
|
|
276
|
+
if hours_ago:
|
|
277
|
+
hours = -hours
|
|
278
|
+
mins = -mins
|
|
279
|
+
secs = -secs
|
|
280
|
+
usecs = -usecs
|
|
281
|
+
else:
|
|
282
|
+
raise ValueError(f'Cannot parse interval: {value}')
|
|
283
|
+
days += 365 * years + 30 * mons
|
|
284
|
+
return timedelta(days=days, hours=hours, minutes=mins,
|
|
285
|
+
seconds=secs, microseconds=usecs)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class Typecasts(dict):
|
|
289
|
+
"""Dictionary mapping database types to typecast functions.
|
|
290
|
+
|
|
291
|
+
The cast functions get passed the string representation of a value in
|
|
292
|
+
the database which they need to convert to a Python object. The
|
|
293
|
+
passed string will never be None since NULL values are already
|
|
294
|
+
handled before the cast function is called.
|
|
295
|
+
"""
|
|
296
|
+
|
|
297
|
+
# the default cast functions
|
|
298
|
+
# (str functions are ignored but have been added for faster access)
|
|
299
|
+
defaults: ClassVar[dict[str, Callable]] = {
|
|
300
|
+
'char': str, 'bpchar': str, 'name': str,
|
|
301
|
+
'text': str, 'varchar': str, 'sql_identifier': str,
|
|
302
|
+
'bool': cast_bool, 'bytea': unescape_bytea,
|
|
303
|
+
'int2': int, 'int4': int, 'serial': int, 'int8': int, 'oid': int,
|
|
304
|
+
'hstore': cast_hstore, 'json': jsondecode, 'jsonb': jsondecode,
|
|
305
|
+
'float4': float, 'float8': float,
|
|
306
|
+
'numeric': Decimal, 'money': cast_money,
|
|
307
|
+
'date': cast_date, 'interval': cast_interval,
|
|
308
|
+
'time': cast_time, 'timetz': cast_timetz,
|
|
309
|
+
'timestamp': cast_timestamp, 'timestamptz': cast_timestamptz,
|
|
310
|
+
'int2vector': cast_int2vector, 'uuid': Uuid,
|
|
311
|
+
'anyarray': cast_array, 'record': cast_record}
|
|
312
|
+
|
|
313
|
+
cnx: Cnx | None = None # for local connection specific instances
|
|
314
|
+
|
|
315
|
+
def __missing__(self, typ: str) -> Callable | None:
|
|
316
|
+
"""Create a cast function if it is not cached.
|
|
317
|
+
|
|
318
|
+
Note that this class never raises a KeyError,
|
|
319
|
+
but returns None when no special cast function exists.
|
|
320
|
+
"""
|
|
321
|
+
if not isinstance(typ, str):
|
|
322
|
+
raise TypeError(f'Invalid type: {typ}')
|
|
323
|
+
cast = self.defaults.get(typ)
|
|
324
|
+
if cast:
|
|
325
|
+
# store default for faster access
|
|
326
|
+
cast = self._add_connection(cast)
|
|
327
|
+
self[typ] = cast
|
|
328
|
+
elif typ.startswith('_'):
|
|
329
|
+
# create array cast
|
|
330
|
+
base_cast = self[typ[1:]]
|
|
331
|
+
cast = self.create_array_cast(base_cast)
|
|
332
|
+
if base_cast:
|
|
333
|
+
# store only if base type exists
|
|
334
|
+
self[typ] = cast
|
|
335
|
+
return cast
|
|
336
|
+
|
|
337
|
+
@staticmethod
|
|
338
|
+
def _needs_connection(func: Callable) -> bool:
|
|
339
|
+
"""Check if a typecast function needs a connection argument."""
|
|
340
|
+
try:
|
|
341
|
+
args = get_args(func)
|
|
342
|
+
except (TypeError, ValueError):
|
|
343
|
+
return False
|
|
344
|
+
return 'cnx' in args[1:]
|
|
345
|
+
|
|
346
|
+
def _add_connection(self, cast: Callable) -> Callable:
|
|
347
|
+
"""Add a connection argument to the typecast function if necessary."""
|
|
348
|
+
if not self.cnx or not self._needs_connection(cast):
|
|
349
|
+
return cast
|
|
350
|
+
return partial(cast, cnx=self.cnx)
|
|
351
|
+
|
|
352
|
+
def get(self, typ: str, default: Callable | None = None # type: ignore
|
|
353
|
+
) -> Callable | None:
|
|
354
|
+
"""Get the typecast function for the given database type."""
|
|
355
|
+
return self[typ] or default
|
|
356
|
+
|
|
357
|
+
def set(self, typ: str | Sequence[str], cast: Callable | None) -> None:
|
|
358
|
+
"""Set a typecast function for the specified database type(s)."""
|
|
359
|
+
if isinstance(typ, str):
|
|
360
|
+
typ = [typ]
|
|
361
|
+
if cast is None:
|
|
362
|
+
for t in typ:
|
|
363
|
+
self.pop(t, None)
|
|
364
|
+
self.pop(f'_{t}', None)
|
|
365
|
+
else:
|
|
366
|
+
if not callable(cast):
|
|
367
|
+
raise TypeError("Cast parameter must be callable")
|
|
368
|
+
for t in typ:
|
|
369
|
+
self[t] = self._add_connection(cast)
|
|
370
|
+
self.pop(f'_{t}', None)
|
|
371
|
+
|
|
372
|
+
def reset(self, typ: str | Sequence[str] | None = None) -> None:
|
|
373
|
+
"""Reset the typecasts for the specified type(s) to their defaults.
|
|
374
|
+
|
|
375
|
+
When no type is specified, all typecasts will be reset.
|
|
376
|
+
"""
|
|
377
|
+
defaults = self.defaults
|
|
378
|
+
if typ is None:
|
|
379
|
+
self.clear()
|
|
380
|
+
self.update(defaults)
|
|
381
|
+
else:
|
|
382
|
+
if isinstance(typ, str):
|
|
383
|
+
typ = [typ]
|
|
384
|
+
for t in typ:
|
|
385
|
+
cast = defaults.get(t)
|
|
386
|
+
if cast:
|
|
387
|
+
self[t] = self._add_connection(cast)
|
|
388
|
+
t = f'_{t}'
|
|
389
|
+
cast = defaults.get(t)
|
|
390
|
+
if cast:
|
|
391
|
+
self[t] = self._add_connection(cast)
|
|
392
|
+
else:
|
|
393
|
+
self.pop(t, None)
|
|
394
|
+
else:
|
|
395
|
+
self.pop(t, None)
|
|
396
|
+
self.pop(f'_{t}', None)
|
|
397
|
+
|
|
398
|
+
def create_array_cast(self, basecast: Callable) -> Callable:
|
|
399
|
+
"""Create an array typecast for the given base cast."""
|
|
400
|
+
cast_array = self['anyarray']
|
|
401
|
+
|
|
402
|
+
def cast(v: Any) -> list:
|
|
403
|
+
return cast_array(v, basecast)
|
|
404
|
+
return cast
|
|
405
|
+
|
|
406
|
+
def create_record_cast(self, name: str, fields: Sequence[str],
|
|
407
|
+
casts: Sequence[str]) -> Callable:
|
|
408
|
+
"""Create a named record typecast for the given fields and casts."""
|
|
409
|
+
cast_record = self['record']
|
|
410
|
+
record = namedtuple(name, fields) # type: ignore
|
|
411
|
+
|
|
412
|
+
def cast(v: Any) -> record:
|
|
413
|
+
# noinspection PyArgumentList
|
|
414
|
+
return record(*cast_record(v, casts))
|
|
415
|
+
return cast
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
_typecasts = Typecasts() # this is the global typecast dictionary
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def get_typecast(typ: str) -> Callable | None:
|
|
422
|
+
"""Get the global typecast function for the given database type."""
|
|
423
|
+
return _typecasts.get(typ)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def set_typecast(typ: str | Sequence[str], cast: Callable | None) -> None:
|
|
427
|
+
"""Set a global typecast function for the given database type(s).
|
|
428
|
+
|
|
429
|
+
Note that connections cache cast functions. To be sure a global change
|
|
430
|
+
is picked up by a running connection, call con.type_cache.reset_typecast().
|
|
431
|
+
"""
|
|
432
|
+
_typecasts.set(typ, cast)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def reset_typecast(typ: str | Sequence[str] | None = None) -> None:
|
|
436
|
+
"""Reset the global typecasts for the given type(s) to their default.
|
|
437
|
+
|
|
438
|
+
When no type is specified, all typecasts will be reset.
|
|
439
|
+
|
|
440
|
+
Note that connections cache cast functions. To be sure a global change
|
|
441
|
+
is picked up by a running connection, call con.type_cache.reset_typecast().
|
|
442
|
+
"""
|
|
443
|
+
_typecasts.reset(typ)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
class LocalTypecasts(Typecasts):
|
|
447
|
+
"""Map typecasts, including local composite types, to cast functions."""
|
|
448
|
+
|
|
449
|
+
defaults = _typecasts
|
|
450
|
+
|
|
451
|
+
cnx: Cnx | None = None # set in connection specific instances
|
|
452
|
+
|
|
453
|
+
def __missing__(self, typ: str) -> Callable | None:
|
|
454
|
+
"""Create a cast function if it is not cached."""
|
|
455
|
+
cast: Callable | None
|
|
456
|
+
if typ.startswith('_'):
|
|
457
|
+
base_cast = self[typ[1:]]
|
|
458
|
+
cast = self.create_array_cast(base_cast)
|
|
459
|
+
if base_cast:
|
|
460
|
+
self[typ] = cast
|
|
461
|
+
else:
|
|
462
|
+
cast = self.defaults.get(typ)
|
|
463
|
+
if cast:
|
|
464
|
+
cast = self._add_connection(cast)
|
|
465
|
+
self[typ] = cast
|
|
466
|
+
else:
|
|
467
|
+
fields = self.get_fields(typ)
|
|
468
|
+
if fields:
|
|
469
|
+
casts = [self[field.type] for field in fields]
|
|
470
|
+
field_names = [field.name for field in fields]
|
|
471
|
+
cast = self.create_record_cast(typ, field_names, casts)
|
|
472
|
+
self[typ] = cast
|
|
473
|
+
return cast
|
|
474
|
+
|
|
475
|
+
# noinspection PyMethodMayBeStatic,PyUnusedLocal
|
|
476
|
+
def get_fields(self, typ: str) -> list[FieldInfo]:
|
|
477
|
+
"""Return the fields for the given record type.
|
|
478
|
+
|
|
479
|
+
This method will be replaced with a method that looks up the fields
|
|
480
|
+
using the type cache of the connection.
|
|
481
|
+
"""
|
|
482
|
+
return []
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
FieldInfo = namedtuple('FieldInfo', ('name', 'type'))
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
class TypeCache(dict):
|
|
489
|
+
"""Cache for database types.
|
|
490
|
+
|
|
491
|
+
This cache maps type OIDs and names to TypeCode strings containing
|
|
492
|
+
important information on the associated database type.
|
|
493
|
+
"""
|
|
494
|
+
|
|
495
|
+
def __init__(self, cnx: Cnx) -> None:
|
|
496
|
+
"""Initialize type cache for connection."""
|
|
497
|
+
super().__init__()
|
|
498
|
+
self._escape_string = cnx.escape_string
|
|
499
|
+
self._src = cnx.source()
|
|
500
|
+
self._typecasts = LocalTypecasts()
|
|
501
|
+
self._typecasts.get_fields = self.get_fields # type: ignore
|
|
502
|
+
self._typecasts.cnx = cnx
|
|
503
|
+
self._query_pg_type = (
|
|
504
|
+
"SELECT oid, typname,"
|
|
505
|
+
" typlen, typtype, typcategory, typdelim, typrelid"
|
|
506
|
+
" FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) {}")
|
|
507
|
+
|
|
508
|
+
def __missing__(self, key: int | str) -> TypeCode:
|
|
509
|
+
"""Get the type info from the database if it is not cached."""
|
|
510
|
+
oid: int | str
|
|
511
|
+
if isinstance(key, int):
|
|
512
|
+
oid = key
|
|
513
|
+
else:
|
|
514
|
+
if '.' not in key and '"' not in key:
|
|
515
|
+
key = f'"{key}"'
|
|
516
|
+
oid = f"'{self._escape_string(key)}'::pg_catalog.regtype"
|
|
517
|
+
try:
|
|
518
|
+
self._src.execute(self._query_pg_type.format(oid))
|
|
519
|
+
except ProgrammingError:
|
|
520
|
+
res = None
|
|
521
|
+
else:
|
|
522
|
+
res = self._src.fetch(1)
|
|
523
|
+
if not res:
|
|
524
|
+
raise KeyError(f'Type {key} could not be found')
|
|
525
|
+
r = res[0]
|
|
526
|
+
type_code = TypeCode.create(
|
|
527
|
+
int(r[0]), r[1], int(r[2]), r[3], r[4], r[5], int(r[6]))
|
|
528
|
+
# noinspection PyUnresolvedReferences
|
|
529
|
+
self[type_code.oid] = self[str(type_code)] = type_code
|
|
530
|
+
return type_code
|
|
531
|
+
|
|
532
|
+
def get(self, key: int | str, # type: ignore
|
|
533
|
+
default: TypeCode | None = None) -> TypeCode | None:
|
|
534
|
+
"""Get the type even if it is not cached."""
|
|
535
|
+
try:
|
|
536
|
+
return self[key]
|
|
537
|
+
except KeyError:
|
|
538
|
+
return default
|
|
539
|
+
|
|
540
|
+
def get_fields(self, typ: int | str | TypeCode) -> list[FieldInfo] | None:
|
|
541
|
+
"""Get the names and types of the fields of composite types."""
|
|
542
|
+
if isinstance(typ, TypeCode):
|
|
543
|
+
relid = typ.relid
|
|
544
|
+
else:
|
|
545
|
+
type_code = self.get(typ)
|
|
546
|
+
if not type_code:
|
|
547
|
+
return None
|
|
548
|
+
relid = type_code.relid
|
|
549
|
+
if not relid:
|
|
550
|
+
return None # this type is not composite
|
|
551
|
+
self._src.execute(
|
|
552
|
+
"SELECT attname, atttypid" # noqa: S608
|
|
553
|
+
" FROM pg_catalog.pg_attribute"
|
|
554
|
+
f" WHERE attrelid OPERATOR(pg_catalog.=) {relid}"
|
|
555
|
+
" AND attnum OPERATOR(pg_catalog.>) 0"
|
|
556
|
+
" AND NOT attisdropped ORDER BY attnum")
|
|
557
|
+
return [FieldInfo(name, self.get(int(oid)))
|
|
558
|
+
for name, oid in self._src.fetch(-1)]
|
|
559
|
+
|
|
560
|
+
def get_typecast(self, typ: str) -> Callable | None:
|
|
561
|
+
"""Get the typecast function for the given database type."""
|
|
562
|
+
return self._typecasts[typ]
|
|
563
|
+
|
|
564
|
+
def set_typecast(self, typ: str | Sequence[str],
|
|
565
|
+
cast: Callable | None) -> None:
|
|
566
|
+
"""Set a typecast function for the specified database type(s)."""
|
|
567
|
+
self._typecasts.set(typ, cast)
|
|
568
|
+
|
|
569
|
+
def reset_typecast(self, typ: str | Sequence[str] | None = None) -> None:
|
|
570
|
+
"""Reset the typecast function for the specified database type(s)."""
|
|
571
|
+
self._typecasts.reset(typ)
|
|
572
|
+
|
|
573
|
+
def typecast(self, value: Any, typ: str) -> Any:
|
|
574
|
+
"""Cast the given value according to the given database type."""
|
|
575
|
+
if value is None:
|
|
576
|
+
# for NULL values, no typecast is necessary
|
|
577
|
+
return None
|
|
578
|
+
cast = self._typecasts[typ]
|
|
579
|
+
if cast is None or cast is str:
|
|
580
|
+
# no typecast is necessary
|
|
581
|
+
return value
|
|
582
|
+
return cast(value)
|
|
583
|
+
|
|
584
|
+
def get_row_caster(self, types: Sequence[str]) -> Callable:
|
|
585
|
+
"""Get a typecast function for a complete row of values."""
|
|
586
|
+
typecasts = self._typecasts
|
|
587
|
+
casts = [typecasts[typ] for typ in types]
|
|
588
|
+
casts = [cast if cast is not str else None for cast in casts]
|
|
589
|
+
|
|
590
|
+
def row_caster(row: Sequence) -> Sequence:
|
|
591
|
+
return [value if cast is None or value is None else cast(value)
|
|
592
|
+
for cast, value in zip(casts, row)]
|
|
593
|
+
|
|
594
|
+
return row_caster
|
pgdb/connect.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""The DB API 2 connect function."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from pg.core import connect as get_cnx
|
|
8
|
+
|
|
9
|
+
from .connection import Connection
|
|
10
|
+
|
|
11
|
+
__all__ = ['connect']
|
|
12
|
+
|
|
13
|
+
def connect(dsn: str | None = None,
|
|
14
|
+
user: str | None = None, password: str | None = None,
|
|
15
|
+
host: str | None = None, database: str | None = None,
|
|
16
|
+
**kwargs: Any) -> Connection:
|
|
17
|
+
"""Connect to a database."""
|
|
18
|
+
# first get params from DSN
|
|
19
|
+
dbport = -1
|
|
20
|
+
dbhost: str | None = ""
|
|
21
|
+
dbname: str | None = ""
|
|
22
|
+
dbuser: str | None = ""
|
|
23
|
+
dbpasswd: str | None = ""
|
|
24
|
+
dbopt: str | None = ""
|
|
25
|
+
if dsn:
|
|
26
|
+
try:
|
|
27
|
+
params = dsn.split(":", 4)
|
|
28
|
+
dbhost = params[0]
|
|
29
|
+
dbname = params[1]
|
|
30
|
+
dbuser = params[2]
|
|
31
|
+
dbpasswd = params[3]
|
|
32
|
+
dbopt = params[4]
|
|
33
|
+
except (AttributeError, IndexError, TypeError):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
# override if necessary
|
|
37
|
+
if user is not None:
|
|
38
|
+
dbuser = user
|
|
39
|
+
if password is not None:
|
|
40
|
+
dbpasswd = password
|
|
41
|
+
if database is not None:
|
|
42
|
+
dbname = database
|
|
43
|
+
if host:
|
|
44
|
+
try:
|
|
45
|
+
params = host.split(":", 1)
|
|
46
|
+
dbhost = params[0]
|
|
47
|
+
dbport = int(params[1])
|
|
48
|
+
except (AttributeError, IndexError, TypeError, ValueError):
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
# empty host is localhost
|
|
52
|
+
if dbhost == "":
|
|
53
|
+
dbhost = None
|
|
54
|
+
if dbuser == "":
|
|
55
|
+
dbuser = None
|
|
56
|
+
|
|
57
|
+
# pass keyword arguments as connection info string
|
|
58
|
+
if kwargs:
|
|
59
|
+
kwarg_list = list(kwargs.items())
|
|
60
|
+
kw_parts = []
|
|
61
|
+
if dbname and '=' in dbname:
|
|
62
|
+
kw_parts.append(dbname)
|
|
63
|
+
else:
|
|
64
|
+
kwarg_list.insert(0, ('dbname', dbname))
|
|
65
|
+
for kw, value in kwarg_list:
|
|
66
|
+
value = str(value)
|
|
67
|
+
if not value or ' ' in value:
|
|
68
|
+
value = value.replace('\\', '\\\\').replace("'", "\\'")
|
|
69
|
+
value = f"'{value}'"
|
|
70
|
+
kw_parts.append(f'{kw}={value}')
|
|
71
|
+
dbname = ' '.join(kw_parts)
|
|
72
|
+
# open the connection
|
|
73
|
+
cnx = get_cnx(dbname, dbhost, dbport, dbopt, dbuser, dbpasswd)
|
|
74
|
+
return Connection(cnx)
|