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
pg/attrs.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
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
|
+
self._read_only = False
|
|
14
|
+
super().__init__(*args, **kw)
|
|
15
|
+
self._read_only = True
|
|
16
|
+
error = self._read_only_error
|
|
17
|
+
self.clear = self.update = error # type: ignore
|
|
18
|
+
self.pop = self.setdefault = self.popitem = error # type: ignore
|
|
19
|
+
|
|
20
|
+
def __setitem__(self, key: str, value: Any) -> None:
|
|
21
|
+
"""Set a value."""
|
|
22
|
+
if self._read_only:
|
|
23
|
+
self._read_only_error()
|
|
24
|
+
super().__setitem__(key, value)
|
|
25
|
+
|
|
26
|
+
def __delitem__(self, key: str) -> None:
|
|
27
|
+
"""Delete a value."""
|
|
28
|
+
if self._read_only:
|
|
29
|
+
self._read_only_error()
|
|
30
|
+
super().__delitem__(key)
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def _read_only_error(*_args: Any, **_kw: Any) -> Any:
|
|
34
|
+
"""Raise error for write operations."""
|
|
35
|
+
raise TypeError('This object is read-only')
|
pg/cast.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
"""Typecasting mechanisms."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import namedtuple
|
|
6
|
+
from datetime import date, datetime, timedelta
|
|
7
|
+
from functools import partial
|
|
8
|
+
from inspect import signature
|
|
9
|
+
from re import compile as regex
|
|
10
|
+
from typing import Any, Callable, ClassVar, Sequence
|
|
11
|
+
from uuid import UUID
|
|
12
|
+
|
|
13
|
+
from .attrs import AttrDict
|
|
14
|
+
from .core import (
|
|
15
|
+
Connection,
|
|
16
|
+
cast_array,
|
|
17
|
+
cast_hstore,
|
|
18
|
+
cast_record,
|
|
19
|
+
get_bool,
|
|
20
|
+
get_decimal,
|
|
21
|
+
get_decimal_point,
|
|
22
|
+
get_jsondecode,
|
|
23
|
+
unescape_bytea,
|
|
24
|
+
)
|
|
25
|
+
from .tz import timezone_as_offset
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
'Typecasts',
|
|
29
|
+
'cast_bool',
|
|
30
|
+
'cast_date',
|
|
31
|
+
'cast_int2vector',
|
|
32
|
+
'cast_interval',
|
|
33
|
+
'cast_json',
|
|
34
|
+
'cast_money',
|
|
35
|
+
'cast_num',
|
|
36
|
+
'cast_time',
|
|
37
|
+
'cast_timestamp',
|
|
38
|
+
'cast_timestamptz',
|
|
39
|
+
'cast_timetz',
|
|
40
|
+
'get_typecast',
|
|
41
|
+
'set_typecast'
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
def get_args(func: Callable) -> list:
|
|
45
|
+
"""Get the arguments of a function."""
|
|
46
|
+
return list(signature(func).parameters)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def cast_bool(value: str) -> Any:
|
|
50
|
+
"""Cast a boolean value."""
|
|
51
|
+
if not get_bool():
|
|
52
|
+
return value
|
|
53
|
+
return value[0] == 't'
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def cast_json(value: str) -> Any:
|
|
57
|
+
"""Cast a JSON value."""
|
|
58
|
+
cast = get_jsondecode()
|
|
59
|
+
if not cast:
|
|
60
|
+
return value
|
|
61
|
+
return cast(value)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def cast_num(value: str) -> Any:
|
|
65
|
+
"""Cast a numeric value."""
|
|
66
|
+
return (get_decimal() or float)(value)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def cast_money(value: str) -> Any:
|
|
70
|
+
"""Cast a money value."""
|
|
71
|
+
point = get_decimal_point()
|
|
72
|
+
if not point:
|
|
73
|
+
return value
|
|
74
|
+
if point != '.':
|
|
75
|
+
value = value.replace(point, '.')
|
|
76
|
+
value = value.replace('(', '-')
|
|
77
|
+
value = ''.join(c for c in value if c.isdigit() or c in '.-')
|
|
78
|
+
return (get_decimal() or float)(value)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def cast_int2vector(value: str) -> list[int]:
|
|
82
|
+
"""Cast an int2vector value."""
|
|
83
|
+
return [int(v) for v in value.split()]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def cast_date(value: str, connection: Connection) -> Any:
|
|
87
|
+
"""Cast a date value."""
|
|
88
|
+
# The output format depends on the server setting DateStyle. The default
|
|
89
|
+
# setting ISO and the setting for German are actually unambiguous. The
|
|
90
|
+
# order of days and months in the other two settings is however ambiguous,
|
|
91
|
+
# so at least here we need to consult the setting to properly parse values.
|
|
92
|
+
if value == '-infinity':
|
|
93
|
+
return date.min
|
|
94
|
+
if value == 'infinity':
|
|
95
|
+
return date.max
|
|
96
|
+
values = value.split()
|
|
97
|
+
if values[-1] == 'BC':
|
|
98
|
+
return date.min
|
|
99
|
+
value = values[0]
|
|
100
|
+
if len(value) > 10:
|
|
101
|
+
return date.max
|
|
102
|
+
format = connection.date_format()
|
|
103
|
+
return datetime.strptime(value, format).date()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def cast_time(value: str) -> Any:
|
|
107
|
+
"""Cast a time value."""
|
|
108
|
+
format = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
|
|
109
|
+
return datetime.strptime(value, format).time()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
_re_timezone = regex('(.*)([+-].*)')
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def cast_timetz(value: str) -> Any:
|
|
116
|
+
"""Cast a timetz value."""
|
|
117
|
+
m = _re_timezone.match(value)
|
|
118
|
+
if m:
|
|
119
|
+
value, tz = m.groups()
|
|
120
|
+
else:
|
|
121
|
+
tz = '+0000'
|
|
122
|
+
format = '%H:%M:%S.%f' if len(value) > 8 else '%H:%M:%S'
|
|
123
|
+
value += timezone_as_offset(tz)
|
|
124
|
+
format += '%z'
|
|
125
|
+
return datetime.strptime(value, format).timetz()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def cast_timestamp(value: str, connection: Connection) -> Any:
|
|
129
|
+
"""Cast a timestamp value."""
|
|
130
|
+
if value == '-infinity':
|
|
131
|
+
return datetime.min
|
|
132
|
+
if value == 'infinity':
|
|
133
|
+
return datetime.max
|
|
134
|
+
values = value.split()
|
|
135
|
+
if values[-1] == 'BC':
|
|
136
|
+
return datetime.min
|
|
137
|
+
format = connection.date_format()
|
|
138
|
+
if format.endswith('-%Y') and len(values) > 2:
|
|
139
|
+
values = values[1:5]
|
|
140
|
+
if len(values[3]) > 4:
|
|
141
|
+
return datetime.max
|
|
142
|
+
formats = ['%d %b' if format.startswith('%d') else '%b %d',
|
|
143
|
+
'%H:%M:%S.%f' if len(values[2]) > 8 else '%H:%M:%S', '%Y']
|
|
144
|
+
else:
|
|
145
|
+
if len(values[0]) > 10:
|
|
146
|
+
return datetime.max
|
|
147
|
+
formats = [format, '%H:%M:%S.%f' if len(values[1]) > 8 else '%H:%M:%S']
|
|
148
|
+
return datetime.strptime(' '.join(values), ' '.join(formats))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def cast_timestamptz(value: str, connection: Connection) -> Any:
|
|
152
|
+
"""Cast a timestamptz value."""
|
|
153
|
+
if value == '-infinity':
|
|
154
|
+
return datetime.min
|
|
155
|
+
if value == 'infinity':
|
|
156
|
+
return datetime.max
|
|
157
|
+
values = value.split()
|
|
158
|
+
if values[-1] == 'BC':
|
|
159
|
+
return datetime.min
|
|
160
|
+
format = connection.date_format()
|
|
161
|
+
if format.endswith('-%Y') and len(values) > 2:
|
|
162
|
+
values = values[1:]
|
|
163
|
+
if len(values[3]) > 4:
|
|
164
|
+
return datetime.max
|
|
165
|
+
formats = ['%d %b' if format.startswith('%d') else '%b %d',
|
|
166
|
+
'%H:%M:%S.%f' if len(values[2]) > 8 else '%H:%M:%S', '%Y']
|
|
167
|
+
values, tz = values[:-1], values[-1]
|
|
168
|
+
else:
|
|
169
|
+
if format.startswith('%Y-'):
|
|
170
|
+
m = _re_timezone.match(values[1])
|
|
171
|
+
if m:
|
|
172
|
+
values[1], tz = m.groups()
|
|
173
|
+
else:
|
|
174
|
+
tz = '+0000'
|
|
175
|
+
else:
|
|
176
|
+
values, tz = values[:-1], values[-1]
|
|
177
|
+
if len(values[0]) > 10:
|
|
178
|
+
return datetime.max
|
|
179
|
+
formats = [format, '%H:%M:%S.%f' if len(values[1]) > 8 else '%H:%M:%S']
|
|
180
|
+
values.append(timezone_as_offset(tz))
|
|
181
|
+
formats.append('%z')
|
|
182
|
+
return datetime.strptime(' '.join(values), ' '.join(formats))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
_re_interval_sql_standard = regex(
|
|
186
|
+
'(?:([+-])?([0-9]+)-([0-9]+) ?)?'
|
|
187
|
+
'(?:([+-]?[0-9]+)(?!:) ?)?'
|
|
188
|
+
'(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
|
|
189
|
+
|
|
190
|
+
_re_interval_postgres = regex(
|
|
191
|
+
'(?:([+-]?[0-9]+) ?years? ?)?'
|
|
192
|
+
'(?:([+-]?[0-9]+) ?mons? ?)?'
|
|
193
|
+
'(?:([+-]?[0-9]+) ?days? ?)?'
|
|
194
|
+
'(?:([+-])?([0-9]+):([0-9]+):([0-9]+)(?:\\.([0-9]+))?)?')
|
|
195
|
+
|
|
196
|
+
_re_interval_postgres_verbose = regex(
|
|
197
|
+
'@ ?(?:([+-]?[0-9]+) ?years? ?)?'
|
|
198
|
+
'(?:([+-]?[0-9]+) ?mons? ?)?'
|
|
199
|
+
'(?:([+-]?[0-9]+) ?days? ?)?'
|
|
200
|
+
'(?:([+-]?[0-9]+) ?hours? ?)?'
|
|
201
|
+
'(?:([+-]?[0-9]+) ?mins? ?)?'
|
|
202
|
+
'(?:([+-])?([0-9]+)(?:\\.([0-9]+))? ?secs?)? ?(ago)?')
|
|
203
|
+
|
|
204
|
+
_re_interval_iso_8601 = regex(
|
|
205
|
+
'P(?:([+-]?[0-9]+)Y)?'
|
|
206
|
+
'(?:([+-]?[0-9]+)M)?'
|
|
207
|
+
'(?:([+-]?[0-9]+)D)?'
|
|
208
|
+
'(?:T(?:([+-]?[0-9]+)H)?'
|
|
209
|
+
'(?:([+-]?[0-9]+)M)?'
|
|
210
|
+
'(?:([+-])?([0-9]+)(?:\\.([0-9]+))?S)?)?')
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def cast_interval(value: str) -> timedelta:
|
|
214
|
+
"""Cast an interval value."""
|
|
215
|
+
# The output format depends on the server setting IntervalStyle, but it's
|
|
216
|
+
# not necessary to consult this setting to parse it. It's faster to just
|
|
217
|
+
# check all possible formats, and there is no ambiguity here.
|
|
218
|
+
m = _re_interval_iso_8601.match(value)
|
|
219
|
+
if m:
|
|
220
|
+
s = [v or '0' for v in m.groups()]
|
|
221
|
+
secs_ago = s.pop(5) == '-'
|
|
222
|
+
d = [int(v) for v in s]
|
|
223
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
224
|
+
if secs_ago:
|
|
225
|
+
secs = -secs
|
|
226
|
+
usecs = -usecs
|
|
227
|
+
else:
|
|
228
|
+
m = _re_interval_postgres_verbose.match(value)
|
|
229
|
+
if m:
|
|
230
|
+
s, ago = [v or '0' for v in m.groups()[:8]], m.group(9)
|
|
231
|
+
secs_ago = s.pop(5) == '-'
|
|
232
|
+
d = [-int(v) for v in s] if ago else [int(v) for v in s]
|
|
233
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
234
|
+
if secs_ago:
|
|
235
|
+
secs = - secs
|
|
236
|
+
usecs = -usecs
|
|
237
|
+
else:
|
|
238
|
+
m = _re_interval_postgres.match(value)
|
|
239
|
+
if m and any(m.groups()):
|
|
240
|
+
s = [v or '0' for v in m.groups()]
|
|
241
|
+
hours_ago = s.pop(3) == '-'
|
|
242
|
+
d = [int(v) for v in s]
|
|
243
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
244
|
+
if hours_ago:
|
|
245
|
+
hours = -hours
|
|
246
|
+
mins = -mins
|
|
247
|
+
secs = -secs
|
|
248
|
+
usecs = -usecs
|
|
249
|
+
else:
|
|
250
|
+
m = _re_interval_sql_standard.match(value)
|
|
251
|
+
if m and any(m.groups()):
|
|
252
|
+
s = [v or '0' for v in m.groups()]
|
|
253
|
+
years_ago = s.pop(0) == '-'
|
|
254
|
+
hours_ago = s.pop(3) == '-'
|
|
255
|
+
d = [int(v) for v in s]
|
|
256
|
+
years, mons, days, hours, mins, secs, usecs = d
|
|
257
|
+
if years_ago:
|
|
258
|
+
years = -years
|
|
259
|
+
mons = -mons
|
|
260
|
+
if hours_ago:
|
|
261
|
+
hours = -hours
|
|
262
|
+
mins = -mins
|
|
263
|
+
secs = -secs
|
|
264
|
+
usecs = -usecs
|
|
265
|
+
else:
|
|
266
|
+
raise ValueError(f'Cannot parse interval: {value}')
|
|
267
|
+
days += 365 * years + 30 * mons
|
|
268
|
+
return timedelta(days=days, hours=hours, minutes=mins,
|
|
269
|
+
seconds=secs, microseconds=usecs)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
class Typecasts(dict):
|
|
273
|
+
"""Dictionary mapping database types to typecast functions.
|
|
274
|
+
|
|
275
|
+
The cast functions get passed the string representation of a value in
|
|
276
|
+
the database which they need to convert to a Python object. The
|
|
277
|
+
passed string will never be None since NULL values are already
|
|
278
|
+
handled before the cast function is called.
|
|
279
|
+
|
|
280
|
+
Note that the basic types are already handled by the C extension.
|
|
281
|
+
They only need to be handled here as record or array components.
|
|
282
|
+
"""
|
|
283
|
+
|
|
284
|
+
# the default cast functions
|
|
285
|
+
# (str functions are ignored but have been added for faster access)
|
|
286
|
+
defaults: ClassVar[dict[str, Callable]] = {
|
|
287
|
+
'char': str, 'bpchar': str, 'name': str,
|
|
288
|
+
'text': str, 'varchar': str, 'sql_identifier': str,
|
|
289
|
+
'bool': cast_bool, 'bytea': unescape_bytea,
|
|
290
|
+
'int2': int, 'int4': int, 'serial': int, 'int8': int, 'oid': int,
|
|
291
|
+
'hstore': cast_hstore, 'json': cast_json, 'jsonb': cast_json,
|
|
292
|
+
'float4': float, 'float8': float,
|
|
293
|
+
'numeric': cast_num, 'money': cast_money,
|
|
294
|
+
'date': cast_date, 'interval': cast_interval,
|
|
295
|
+
'time': cast_time, 'timetz': cast_timetz,
|
|
296
|
+
'timestamp': cast_timestamp, 'timestamptz': cast_timestamptz,
|
|
297
|
+
'int2vector': cast_int2vector, 'uuid': UUID,
|
|
298
|
+
'anyarray': cast_array, 'record': cast_record} # pyright: ignore
|
|
299
|
+
|
|
300
|
+
connection: Connection | None = None # set in connection specific instance
|
|
301
|
+
|
|
302
|
+
def __missing__(self, typ: str) -> Callable | None:
|
|
303
|
+
"""Create a cast function if it is not cached.
|
|
304
|
+
|
|
305
|
+
Note that this class never raises a KeyError,
|
|
306
|
+
but returns None when no special cast function exists.
|
|
307
|
+
"""
|
|
308
|
+
if not isinstance(typ, str):
|
|
309
|
+
raise TypeError(f'Invalid type: {typ}')
|
|
310
|
+
cast: Callable | None = self.defaults.get(typ)
|
|
311
|
+
if cast:
|
|
312
|
+
# store default for faster access
|
|
313
|
+
cast = self._add_connection(cast)
|
|
314
|
+
self[typ] = cast
|
|
315
|
+
elif typ.startswith('_'):
|
|
316
|
+
base_cast = self[typ[1:]]
|
|
317
|
+
cast = self.create_array_cast(base_cast)
|
|
318
|
+
if base_cast:
|
|
319
|
+
self[typ] = cast
|
|
320
|
+
else:
|
|
321
|
+
attnames = self.get_attnames(typ)
|
|
322
|
+
if attnames:
|
|
323
|
+
casts = [self[v.pgtype] for v in attnames.values()]
|
|
324
|
+
cast = self.create_record_cast(typ, attnames, casts)
|
|
325
|
+
self[typ] = cast
|
|
326
|
+
return cast
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def _needs_connection(func: Callable) -> bool:
|
|
330
|
+
"""Check if a typecast function needs a connection argument."""
|
|
331
|
+
try:
|
|
332
|
+
args = get_args(func)
|
|
333
|
+
except (TypeError, ValueError):
|
|
334
|
+
return False
|
|
335
|
+
return 'connection' in args[1:]
|
|
336
|
+
|
|
337
|
+
def _add_connection(self, cast: Callable) -> Callable:
|
|
338
|
+
"""Add a connection argument to the typecast function if necessary."""
|
|
339
|
+
if not self.connection or not self._needs_connection(cast):
|
|
340
|
+
return cast
|
|
341
|
+
return partial(cast, connection=self.connection)
|
|
342
|
+
|
|
343
|
+
def get(self, typ: str, default: Callable | None = None # type: ignore
|
|
344
|
+
) -> Callable | None:
|
|
345
|
+
"""Get the typecast function for the given database type."""
|
|
346
|
+
return self[typ] or default
|
|
347
|
+
|
|
348
|
+
def set(self, typ: str | Sequence[str], cast: Callable | None) -> None:
|
|
349
|
+
"""Set a typecast function for the specified database type(s)."""
|
|
350
|
+
if isinstance(typ, str):
|
|
351
|
+
typ = [typ]
|
|
352
|
+
if cast is None:
|
|
353
|
+
for t in typ:
|
|
354
|
+
self.pop(t, None)
|
|
355
|
+
self.pop(f'_{t}', None)
|
|
356
|
+
else:
|
|
357
|
+
if not callable(cast):
|
|
358
|
+
raise TypeError("Cast parameter must be callable")
|
|
359
|
+
for t in typ:
|
|
360
|
+
self[t] = self._add_connection(cast)
|
|
361
|
+
self.pop(f'_{t}', None)
|
|
362
|
+
|
|
363
|
+
def reset(self, typ: str | Sequence[str] | None = None) -> None:
|
|
364
|
+
"""Reset the typecasts for the specified type(s) to their defaults.
|
|
365
|
+
|
|
366
|
+
When no type is specified, all typecasts will be reset.
|
|
367
|
+
"""
|
|
368
|
+
if typ is None:
|
|
369
|
+
self.clear()
|
|
370
|
+
else:
|
|
371
|
+
if isinstance(typ, str):
|
|
372
|
+
typ = [typ]
|
|
373
|
+
for t in typ:
|
|
374
|
+
self.pop(t, None)
|
|
375
|
+
|
|
376
|
+
@classmethod
|
|
377
|
+
def get_default(cls, typ: str) -> Any:
|
|
378
|
+
"""Get the default typecast function for the given database type."""
|
|
379
|
+
return cls.defaults.get(typ)
|
|
380
|
+
|
|
381
|
+
@classmethod
|
|
382
|
+
def set_default(cls, typ: str | Sequence[str],
|
|
383
|
+
cast: Callable | None) -> None:
|
|
384
|
+
"""Set a default typecast function for the given database type(s)."""
|
|
385
|
+
if isinstance(typ, str):
|
|
386
|
+
typ = [typ]
|
|
387
|
+
defaults = cls.defaults
|
|
388
|
+
if cast is None:
|
|
389
|
+
for t in typ:
|
|
390
|
+
defaults.pop(t, None)
|
|
391
|
+
defaults.pop(f'_{t}', None)
|
|
392
|
+
else:
|
|
393
|
+
if not callable(cast):
|
|
394
|
+
raise TypeError("Cast parameter must be callable")
|
|
395
|
+
for t in typ:
|
|
396
|
+
defaults[t] = cast
|
|
397
|
+
defaults.pop(f'_{t}', None)
|
|
398
|
+
|
|
399
|
+
# noinspection PyMethodMayBeStatic,PyUnusedLocal
|
|
400
|
+
def get_attnames(self, typ: Any) -> AttrDict:
|
|
401
|
+
"""Return the fields for the given record type.
|
|
402
|
+
|
|
403
|
+
This method will be replaced with the get_attnames() method of DbTypes.
|
|
404
|
+
"""
|
|
405
|
+
return AttrDict()
|
|
406
|
+
|
|
407
|
+
# noinspection PyMethodMayBeStatic
|
|
408
|
+
def dateformat(self) -> str:
|
|
409
|
+
"""Return the current date format.
|
|
410
|
+
|
|
411
|
+
This method will be replaced with the dateformat() method of DbTypes.
|
|
412
|
+
"""
|
|
413
|
+
return '%Y-%m-%d'
|
|
414
|
+
|
|
415
|
+
def create_array_cast(self, basecast: Callable) -> Callable:
|
|
416
|
+
"""Create an array typecast for the given base cast."""
|
|
417
|
+
cast_array = self['anyarray']
|
|
418
|
+
|
|
419
|
+
def cast(v: Any) -> list:
|
|
420
|
+
return cast_array(v, basecast)
|
|
421
|
+
return cast
|
|
422
|
+
|
|
423
|
+
def create_record_cast(self, name: str, fields: AttrDict,
|
|
424
|
+
casts: list[Callable]) -> Callable:
|
|
425
|
+
"""Create a named record typecast for the given fields and casts."""
|
|
426
|
+
cast_record = self['record']
|
|
427
|
+
record = namedtuple(name, fields) # type: ignore
|
|
428
|
+
|
|
429
|
+
def cast(v: Any) -> record:
|
|
430
|
+
# noinspection PyArgumentList
|
|
431
|
+
return record(*cast_record(v, casts))
|
|
432
|
+
return cast
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def get_typecast(typ: str) -> Callable | None:
|
|
436
|
+
"""Get the global typecast function for the given database type."""
|
|
437
|
+
return Typecasts.get_default(typ)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def set_typecast(typ: str | Sequence[str], cast: Callable | None) -> None:
|
|
441
|
+
"""Set a global typecast function for the given database type(s).
|
|
442
|
+
|
|
443
|
+
Note that connections cache cast functions. To be sure a global change
|
|
444
|
+
is picked up by a running connection, call db.db_types.reset_typecast().
|
|
445
|
+
"""
|
|
446
|
+
Typecasts.set_default(typ, cast)
|
pg/core.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Core functionality from extension module."""
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
from ._pg import version
|
|
5
|
+
except ImportError as e: # noqa: F841
|
|
6
|
+
import os
|
|
7
|
+
libpq = 'libpq.'
|
|
8
|
+
if os.name == 'nt':
|
|
9
|
+
libpq += 'dll'
|
|
10
|
+
import sys
|
|
11
|
+
paths = [path for path in os.environ["PATH"].split(os.pathsep)
|
|
12
|
+
if os.path.exists(os.path.join(path, libpq))]
|
|
13
|
+
if sys.version_info >= (3, 8):
|
|
14
|
+
# see https://docs.python.org/3/whatsnew/3.8.html#ctypes
|
|
15
|
+
add_dll_dir = os.add_dll_directory # type: ignore
|
|
16
|
+
for path in paths:
|
|
17
|
+
with add_dll_dir(os.path.abspath(path)):
|
|
18
|
+
try:
|
|
19
|
+
from ._pg import version
|
|
20
|
+
except ImportError:
|
|
21
|
+
pass
|
|
22
|
+
else:
|
|
23
|
+
del version
|
|
24
|
+
e = None # type: ignore
|
|
25
|
+
break
|
|
26
|
+
if paths:
|
|
27
|
+
libpq = 'compatible ' + libpq
|
|
28
|
+
else:
|
|
29
|
+
libpq += 'so'
|
|
30
|
+
if e:
|
|
31
|
+
raise ImportError(
|
|
32
|
+
"Cannot import shared library for PyGreSQL,\n"
|
|
33
|
+
f"probably because no {libpq} is installed.\n{e}") from e
|
|
34
|
+
else:
|
|
35
|
+
del version
|
|
36
|
+
|
|
37
|
+
# import objects from extension module
|
|
38
|
+
from ._pg import (
|
|
39
|
+
INV_READ,
|
|
40
|
+
INV_WRITE,
|
|
41
|
+
POLLING_FAILED,
|
|
42
|
+
POLLING_OK,
|
|
43
|
+
POLLING_READING,
|
|
44
|
+
POLLING_WRITING,
|
|
45
|
+
RESULT_DDL,
|
|
46
|
+
RESULT_DML,
|
|
47
|
+
RESULT_DQL,
|
|
48
|
+
RESULT_EMPTY,
|
|
49
|
+
SEEK_CUR,
|
|
50
|
+
SEEK_END,
|
|
51
|
+
SEEK_SET,
|
|
52
|
+
TRANS_ACTIVE,
|
|
53
|
+
TRANS_IDLE,
|
|
54
|
+
TRANS_INERROR,
|
|
55
|
+
TRANS_INTRANS,
|
|
56
|
+
TRANS_UNKNOWN,
|
|
57
|
+
Connection,
|
|
58
|
+
DatabaseError,
|
|
59
|
+
DataError,
|
|
60
|
+
Error,
|
|
61
|
+
IntegrityError,
|
|
62
|
+
InterfaceError,
|
|
63
|
+
InternalError,
|
|
64
|
+
InvalidResultError,
|
|
65
|
+
LargeObject,
|
|
66
|
+
MultipleResultsError,
|
|
67
|
+
NoResultError,
|
|
68
|
+
NotSupportedError,
|
|
69
|
+
OperationalError,
|
|
70
|
+
ProgrammingError,
|
|
71
|
+
Query,
|
|
72
|
+
Warning,
|
|
73
|
+
cast_array,
|
|
74
|
+
cast_hstore,
|
|
75
|
+
cast_record,
|
|
76
|
+
connect,
|
|
77
|
+
escape_bytea,
|
|
78
|
+
escape_string,
|
|
79
|
+
get_array,
|
|
80
|
+
get_bool,
|
|
81
|
+
get_bytea_escaped,
|
|
82
|
+
get_datestyle,
|
|
83
|
+
get_decimal,
|
|
84
|
+
get_decimal_point,
|
|
85
|
+
get_defbase,
|
|
86
|
+
get_defhost,
|
|
87
|
+
get_defopt,
|
|
88
|
+
get_defport,
|
|
89
|
+
get_defuser,
|
|
90
|
+
get_jsondecode,
|
|
91
|
+
get_pqlib_version,
|
|
92
|
+
set_array,
|
|
93
|
+
set_bool,
|
|
94
|
+
set_bytea_escaped,
|
|
95
|
+
set_datestyle,
|
|
96
|
+
set_decimal,
|
|
97
|
+
set_decimal_point,
|
|
98
|
+
set_defbase,
|
|
99
|
+
set_defhost,
|
|
100
|
+
set_defopt,
|
|
101
|
+
set_defpasswd,
|
|
102
|
+
set_defport,
|
|
103
|
+
set_defuser,
|
|
104
|
+
set_jsondecode,
|
|
105
|
+
set_query_helpers,
|
|
106
|
+
unescape_bytea,
|
|
107
|
+
version,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
__all__ = [
|
|
111
|
+
'INV_READ',
|
|
112
|
+
'INV_WRITE',
|
|
113
|
+
'POLLING_FAILED',
|
|
114
|
+
'POLLING_OK',
|
|
115
|
+
'POLLING_READING',
|
|
116
|
+
'POLLING_WRITING',
|
|
117
|
+
'RESULT_DDL',
|
|
118
|
+
'RESULT_DML',
|
|
119
|
+
'RESULT_DQL',
|
|
120
|
+
'RESULT_EMPTY',
|
|
121
|
+
'SEEK_CUR',
|
|
122
|
+
'SEEK_END',
|
|
123
|
+
'SEEK_SET',
|
|
124
|
+
'TRANS_ACTIVE',
|
|
125
|
+
'TRANS_IDLE',
|
|
126
|
+
'TRANS_INERROR',
|
|
127
|
+
'TRANS_INTRANS',
|
|
128
|
+
'TRANS_UNKNOWN',
|
|
129
|
+
'Connection',
|
|
130
|
+
'DataError',
|
|
131
|
+
'DatabaseError',
|
|
132
|
+
'Error',
|
|
133
|
+
'IntegrityError',
|
|
134
|
+
'InterfaceError',
|
|
135
|
+
'InternalError',
|
|
136
|
+
'InvalidResultError',
|
|
137
|
+
'LargeObject',
|
|
138
|
+
'MultipleResultsError',
|
|
139
|
+
'NoResultError',
|
|
140
|
+
'NotSupportedError',
|
|
141
|
+
'OperationalError',
|
|
142
|
+
'ProgrammingError',
|
|
143
|
+
'Query',
|
|
144
|
+
'Warning',
|
|
145
|
+
'cast_array',
|
|
146
|
+
'cast_hstore',
|
|
147
|
+
'cast_record',
|
|
148
|
+
'connect',
|
|
149
|
+
'escape_bytea',
|
|
150
|
+
'escape_string',
|
|
151
|
+
'get_array',
|
|
152
|
+
'get_bool',
|
|
153
|
+
'get_bytea_escaped',
|
|
154
|
+
'get_datestyle',
|
|
155
|
+
'get_decimal',
|
|
156
|
+
'get_decimal_point',
|
|
157
|
+
'get_defbase',
|
|
158
|
+
'get_defhost',
|
|
159
|
+
'get_defopt',
|
|
160
|
+
'get_defport',
|
|
161
|
+
'get_defuser',
|
|
162
|
+
'get_jsondecode',
|
|
163
|
+
'get_pqlib_version',
|
|
164
|
+
'set_array',
|
|
165
|
+
'set_bool',
|
|
166
|
+
'set_bytea_escaped',
|
|
167
|
+
'set_datestyle',
|
|
168
|
+
'set_decimal',
|
|
169
|
+
'set_decimal_point',
|
|
170
|
+
'set_defbase',
|
|
171
|
+
'set_defhost',
|
|
172
|
+
'set_defopt',
|
|
173
|
+
'set_defpasswd',
|
|
174
|
+
'set_defport',
|
|
175
|
+
'set_defuser',
|
|
176
|
+
'set_jsondecode',
|
|
177
|
+
'set_query_helpers',
|
|
178
|
+
'unescape_bytea',
|
|
179
|
+
'version',
|
|
180
|
+
]
|