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/adapt.py
ADDED
|
@@ -0,0 +1,1033 @@
|
|
|
1
|
+
"""Adaptation of parameters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import weakref
|
|
6
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
7
|
+
from datetime import date, datetime, time, timedelta
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
from functools import partial
|
|
10
|
+
from ipaddress import IPv4Address, IPv4Network, IPv6Address, IPv6Network
|
|
11
|
+
from json import dumps as jsonencode
|
|
12
|
+
from math import isinf, isnan
|
|
13
|
+
from re import compile as regex
|
|
14
|
+
from types import MappingProxyType
|
|
15
|
+
from typing import TYPE_CHECKING, Any, List # noqa: UP035
|
|
16
|
+
from uuid import UUID
|
|
17
|
+
|
|
18
|
+
from .attrs import AttrDict
|
|
19
|
+
from .cast import Typecasts, is_builtin_typecast
|
|
20
|
+
from .core import Connection, InterfaceError
|
|
21
|
+
from .helpers import (
|
|
22
|
+
adapt_error,
|
|
23
|
+
format_text,
|
|
24
|
+
is_array_type,
|
|
25
|
+
join_text,
|
|
26
|
+
type_lookup_condition,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from .db import DB
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
'UUID',
|
|
34
|
+
'Adapter',
|
|
35
|
+
'Bytea',
|
|
36
|
+
'DbType',
|
|
37
|
+
'DbTypes',
|
|
38
|
+
'Hstore',
|
|
39
|
+
'Json',
|
|
40
|
+
'Literal'
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Bytea(bytes):
|
|
45
|
+
"""Wrapper class for marking Bytea values."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _reject_buffer(value: Any) -> None:
|
|
49
|
+
"""Raise a TypeError for bytearray and memoryview objects.
|
|
50
|
+
|
|
51
|
+
These cannot be adapted yet, and their str() must not be sent instead,
|
|
52
|
+
like it is done for objects of other types.
|
|
53
|
+
"""
|
|
54
|
+
if isinstance(value, (bytearray, memoryview)):
|
|
55
|
+
raise TypeError(f'Cannot adapt {type(value).__name__},'
|
|
56
|
+
' convert it to bytes or Bytea')
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Hstore(dict):
|
|
60
|
+
"""Wrapper class for marking hstore values."""
|
|
61
|
+
|
|
62
|
+
_re_quote = regex(r'^[Nn][Uu][Ll][Ll]$|[\s,=>]')
|
|
63
|
+
_re_escape = regex(r'(["\\])')
|
|
64
|
+
_re_quote_bytes = regex(rb'^[Nn][Uu][Ll][Ll]$|[\s,=>]')
|
|
65
|
+
_re_escape_bytes = regex(rb'(["\\])')
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def _quote(cls, s: Any) -> str | bytes:
|
|
69
|
+
if s is None:
|
|
70
|
+
return 'NULL'
|
|
71
|
+
if isinstance(s, bytes): # raw text in the client encoding
|
|
72
|
+
if not s:
|
|
73
|
+
return b'""'
|
|
74
|
+
quote_bytes = cls._re_quote_bytes.search(s)
|
|
75
|
+
s = cls._re_escape_bytes.sub(rb'\\\1', s)
|
|
76
|
+
return b'"' + s + b'"' if quote_bytes else s
|
|
77
|
+
if not isinstance(s, str):
|
|
78
|
+
_reject_buffer(s)
|
|
79
|
+
s = str(s)
|
|
80
|
+
if not s:
|
|
81
|
+
return '""'
|
|
82
|
+
quote = cls._re_quote.search(s)
|
|
83
|
+
s = cls._re_escape.sub(r'\\\1', s)
|
|
84
|
+
if quote:
|
|
85
|
+
s = f'"{s}"'
|
|
86
|
+
return s
|
|
87
|
+
|
|
88
|
+
def __str__(self) -> str:
|
|
89
|
+
"""Create a printable representation of the hstore value."""
|
|
90
|
+
value = self._literal(lambda: 'utf-8')
|
|
91
|
+
if isinstance(value, bytes): # show raw bytes with escapes
|
|
92
|
+
value = value.decode('utf-8', 'backslashreplace')
|
|
93
|
+
return value
|
|
94
|
+
|
|
95
|
+
def _literal(self, encoding: Callable[[], str]) -> str | bytes:
|
|
96
|
+
"""Create the hstore literal, as bytes if it contains bytes.
|
|
97
|
+
|
|
98
|
+
Keys and values given as bytes are raw text in the client encoding,
|
|
99
|
+
and the encoding function returns the codec for this encoding.
|
|
100
|
+
"""
|
|
101
|
+
q = self._quote
|
|
102
|
+
return join_text([join_text([q(k), q(v)], '=>', encoding)
|
|
103
|
+
for k, v in self.items()], ',', encoding)
|
|
104
|
+
|
|
105
|
+
def _pg_text(self, codec: str) -> str | bytes:
|
|
106
|
+
"""Create the hstore literal for the given Python codec.
|
|
107
|
+
|
|
108
|
+
This is used by the C extension for values that are sent as text.
|
|
109
|
+
"""
|
|
110
|
+
return self._literal(lambda: codec)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class Json:
|
|
114
|
+
"""Wrapper class for marking Json values."""
|
|
115
|
+
|
|
116
|
+
def __init__(self, obj: Any,
|
|
117
|
+
encode: Callable[[Any], str] | None = None) -> None:
|
|
118
|
+
"""Initialize the JSON object."""
|
|
119
|
+
self.obj = obj
|
|
120
|
+
self.encode = encode or jsonencode
|
|
121
|
+
|
|
122
|
+
def __str__(self) -> str:
|
|
123
|
+
"""Create a printable representation of the JSON object."""
|
|
124
|
+
obj = self.obj
|
|
125
|
+
if isinstance(obj, str):
|
|
126
|
+
return obj
|
|
127
|
+
return self.encode(obj)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class Literal(str):
|
|
131
|
+
"""Wrapper class for marking literal SQL values."""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class _SimpleTypes(dict):
|
|
136
|
+
"""Dictionary mapping pg_type names to simple type names.
|
|
137
|
+
|
|
138
|
+
The corresponding Python types and simple names are also mapped.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
_type_aliases: Mapping[str, list[str | type]] = MappingProxyType({
|
|
142
|
+
'bool': [bool],
|
|
143
|
+
'bytea': [Bytea, bytes],
|
|
144
|
+
'date': ['interval', 'time', 'timetz', 'timestamp', 'timestamptz',
|
|
145
|
+
'abstime', 'reltime', # these are very old
|
|
146
|
+
'datetime', 'timedelta', # these do not really exist
|
|
147
|
+
date, time, datetime, timedelta],
|
|
148
|
+
'float': ['float4', 'float8', float],
|
|
149
|
+
'int': ['cid', 'int2', 'int4', 'int8', 'oid', 'oid8', 'xid', int],
|
|
150
|
+
'hstore': [Hstore], 'json': ['jsonb', Json], 'uuid': [UUID],
|
|
151
|
+
'num': ['numeric', Decimal], 'money': [], 'record': [],
|
|
152
|
+
'text': ['bpchar', 'char', 'name', 'varchar', str]
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
# noinspection PyMissingConstructor
|
|
156
|
+
def __init__(self) -> None:
|
|
157
|
+
"""Initialize type mapping."""
|
|
158
|
+
for typ, keys in self._type_aliases.items():
|
|
159
|
+
keys = [typ, *keys]
|
|
160
|
+
for key in keys:
|
|
161
|
+
self[key] = typ
|
|
162
|
+
if isinstance(key, str):
|
|
163
|
+
self[f'_{key}'] = f'{typ}[]'
|
|
164
|
+
else: # the aliases are type names or Python types
|
|
165
|
+
# support builtin and legacy typing generics
|
|
166
|
+
array = f'{typ}[]'
|
|
167
|
+
self[list[key]] = array # type: ignore[valid-type]
|
|
168
|
+
self[List[key]] = array # type: ignore[valid-type] # noqa: UP006
|
|
169
|
+
|
|
170
|
+
def __missing__(self, key: Any) -> str:
|
|
171
|
+
"""Unmapped types are interpreted as text.
|
|
172
|
+
|
|
173
|
+
Array type names like "int[]" or "_int4" are mapped to arrays of
|
|
174
|
+
the simple type of the element, arrays of records to "record[]".
|
|
175
|
+
"""
|
|
176
|
+
if isinstance(key, str):
|
|
177
|
+
if key.endswith('[]'):
|
|
178
|
+
base = key[:-2]
|
|
179
|
+
while base.endswith('[]'):
|
|
180
|
+
base = base[:-2]
|
|
181
|
+
if base == 'record':
|
|
182
|
+
return 'record[]'
|
|
183
|
+
simple = self[base]
|
|
184
|
+
return simple if simple.endswith('[]') else f'{simple}[]'
|
|
185
|
+
if key.startswith('_'): # PostgreSQL name of an array type
|
|
186
|
+
return self[f'{key[1:]}[]']
|
|
187
|
+
return 'text'
|
|
188
|
+
|
|
189
|
+
def get_type_dict(self) -> dict[type, str]:
|
|
190
|
+
"""Get a plain dictionary of only the types."""
|
|
191
|
+
return {key: typ for key, typ in self.items()
|
|
192
|
+
if not isinstance(key, (str, tuple))}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
_simpletypes = _SimpleTypes()
|
|
196
|
+
_simple_type_dict = _simpletypes.get_type_dict()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class _ParameterList(list):
|
|
200
|
+
"""Helper class for building typed parameter lists."""
|
|
201
|
+
|
|
202
|
+
adapt: Callable
|
|
203
|
+
|
|
204
|
+
def add(self, value: Any, typ:Any = None) -> str:
|
|
205
|
+
"""Typecast value with known database type and build parameter list.
|
|
206
|
+
|
|
207
|
+
If this is a literal value, it will be returned as is. Otherwise, a
|
|
208
|
+
placeholder will be returned and the parameter list will be augmented.
|
|
209
|
+
"""
|
|
210
|
+
# noinspection PyUnresolvedReferences
|
|
211
|
+
value = self.adapt(value, typ)
|
|
212
|
+
if isinstance(value, Literal):
|
|
213
|
+
return value
|
|
214
|
+
self.append(value)
|
|
215
|
+
return f'${len(self)}'
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class DbType(str):
|
|
220
|
+
"""Class augmenting the simple type name with additional info.
|
|
221
|
+
|
|
222
|
+
The following additional information is provided:
|
|
223
|
+
|
|
224
|
+
oid: the PostgreSQL type OID
|
|
225
|
+
pgtype: the internal PostgreSQL data type name
|
|
226
|
+
regtype: the registered PostgreSQL data type name
|
|
227
|
+
simple: the more coarse-grained PyGreSQL type name
|
|
228
|
+
typlen: the internal size, negative if variable
|
|
229
|
+
typtype: b = base type, c = composite type etc.
|
|
230
|
+
category: A = Array, b = Boolean, C = Composite etc.
|
|
231
|
+
delim: delimiter for array types
|
|
232
|
+
relid: corresponding table for composite types
|
|
233
|
+
elem: the type OID of the elements for array types
|
|
234
|
+
base: the base type for domains, None for other types
|
|
235
|
+
attnames: attributes for composite types
|
|
236
|
+
|
|
237
|
+
Domains take simple, delim, relid and elem from their base type.
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
oid: int
|
|
241
|
+
pgtype: str
|
|
242
|
+
regtype: str
|
|
243
|
+
simple: str
|
|
244
|
+
typlen: int
|
|
245
|
+
typtype: str
|
|
246
|
+
category: str
|
|
247
|
+
delim: str
|
|
248
|
+
relid: int
|
|
249
|
+
elem: int
|
|
250
|
+
base: DbType | None = None
|
|
251
|
+
|
|
252
|
+
_get_attnames: Callable[[DbType], AttrDict]
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def attnames(self) -> AttrDict:
|
|
256
|
+
"""Get names and types of the fields of a composite type."""
|
|
257
|
+
# noinspection PyUnresolvedReferences
|
|
258
|
+
return self._get_attnames(self)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
class DbTypes(dict):
|
|
262
|
+
"""Cache for PostgreSQL data types.
|
|
263
|
+
|
|
264
|
+
This cache maps type OIDs and names to DbType objects containing
|
|
265
|
+
information on the associated database type.
|
|
266
|
+
"""
|
|
267
|
+
|
|
268
|
+
_num_types = frozenset([
|
|
269
|
+
'int', 'float', 'num', 'money', 'int2', 'int4', 'int8',
|
|
270
|
+
'float4', 'float8', 'numeric', 'money'])
|
|
271
|
+
|
|
272
|
+
def __init__(self, db: DB) -> None:
|
|
273
|
+
"""Initialize type cache for connection."""
|
|
274
|
+
super().__init__()
|
|
275
|
+
self._db = weakref.proxy(db)
|
|
276
|
+
self._regtypes = False
|
|
277
|
+
self._typecasts = Typecasts()
|
|
278
|
+
self._typecasts.connection = self._db.db
|
|
279
|
+
# typecasts for type objects, cached by OID
|
|
280
|
+
self._type_casts: dict[int, Callable | None] = {}
|
|
281
|
+
self._defaults_changed = Typecasts.defaults_changed
|
|
282
|
+
self._query_pg_type = (
|
|
283
|
+
"SELECT t.oid, t.typname, t.oid::pg_catalog.regtype,"
|
|
284
|
+
" t.typlen, t.typtype, t.typcategory, t.typdelim, t.typrelid,"
|
|
285
|
+
" t.typelem, t.typbasetype"
|
|
286
|
+
" FROM pg_catalog.pg_type t WHERE {}")
|
|
287
|
+
|
|
288
|
+
def add(self, oid: int, pgtype: str, regtype: str,
|
|
289
|
+
typlen: int, typtype: str, category: str, delim: str, relid: int,
|
|
290
|
+
elem: int = 0, basetype: int = 0) -> DbType:
|
|
291
|
+
"""Create a PostgreSQL type name with additional info."""
|
|
292
|
+
if oid in self:
|
|
293
|
+
return self[oid]
|
|
294
|
+
base = None
|
|
295
|
+
if typtype == 'd' and basetype:
|
|
296
|
+
# domains are handled like their base types
|
|
297
|
+
base = self[basetype]
|
|
298
|
+
base = base.base or base # resolve domains over domains
|
|
299
|
+
simple = base.simple
|
|
300
|
+
delim, relid, elem = base.delim, base.relid, base.elem
|
|
301
|
+
elif relid:
|
|
302
|
+
simple = 'record'
|
|
303
|
+
elif typtype not in 'bp':
|
|
304
|
+
# enums and ranges, the names of built-in types do not apply
|
|
305
|
+
simple = 'text'
|
|
306
|
+
else:
|
|
307
|
+
simple = _simpletypes[pgtype]
|
|
308
|
+
if simple.endswith('[]'):
|
|
309
|
+
if not elem or (category != 'A' and pgtype != '_record'):
|
|
310
|
+
# not an array, only named like one (the pseudo type
|
|
311
|
+
# for arrays of anonymous records is an exception)
|
|
312
|
+
simple = 'text'
|
|
313
|
+
else:
|
|
314
|
+
# the element type might not be the type with the name
|
|
315
|
+
# of the array type without the underscore
|
|
316
|
+
elem_type = self.get(elem)
|
|
317
|
+
# the element type of an array type always exists
|
|
318
|
+
if elem_type: # pragma: no branch
|
|
319
|
+
if elem_type.relid:
|
|
320
|
+
simple = 'record[]'
|
|
321
|
+
elif elem_type.base:
|
|
322
|
+
# arrays of domains over arrays are not
|
|
323
|
+
# multidimensional arrays, keep them as text
|
|
324
|
+
simple = ('text[]' if elem_type.base.elem
|
|
325
|
+
else f'{elem_type.simple}[]')
|
|
326
|
+
elif elem_type.typtype not in 'bp':
|
|
327
|
+
simple = 'text[]'
|
|
328
|
+
typ = DbType(regtype if self._regtypes else simple)
|
|
329
|
+
typ.oid = oid
|
|
330
|
+
typ.simple = simple
|
|
331
|
+
typ.pgtype = pgtype
|
|
332
|
+
typ.regtype = regtype
|
|
333
|
+
typ.typlen = typlen
|
|
334
|
+
typ.typtype = typtype
|
|
335
|
+
typ.category = category
|
|
336
|
+
typ.delim = delim
|
|
337
|
+
typ.relid = relid
|
|
338
|
+
typ.elem = elem
|
|
339
|
+
typ.base = base
|
|
340
|
+
typ._get_attnames = self.get_attnames # type: ignore[assignment]
|
|
341
|
+
return typ
|
|
342
|
+
|
|
343
|
+
def __missing__(self, key: int | str | bytes) -> DbType:
|
|
344
|
+
"""Get the type info from the database if it is not cached."""
|
|
345
|
+
try:
|
|
346
|
+
condition, params = type_lookup_condition(key)
|
|
347
|
+
except ValueError:
|
|
348
|
+
res = None
|
|
349
|
+
else:
|
|
350
|
+
cmd = self._query_pg_type.format(condition)
|
|
351
|
+
res = self._db.query(cmd, params).getresult()
|
|
352
|
+
if not res:
|
|
353
|
+
raise KeyError(f'Type {key!r} could not be found')
|
|
354
|
+
res = res[0]
|
|
355
|
+
typ = self.add(*res)
|
|
356
|
+
# a type found by OID is not cached under its name, since this name
|
|
357
|
+
# could refer to a different type that comes first in the search path
|
|
358
|
+
self[typ.oid] = self[key] = typ
|
|
359
|
+
return typ
|
|
360
|
+
|
|
361
|
+
def get(self, key: int | str, # type: ignore[override]
|
|
362
|
+
default: DbType | None = None) -> DbType | None:
|
|
363
|
+
"""Get the type even if it is not cached."""
|
|
364
|
+
try:
|
|
365
|
+
return self[key]
|
|
366
|
+
except KeyError:
|
|
367
|
+
return default
|
|
368
|
+
|
|
369
|
+
def get_attnames(self, typ: Any) -> AttrDict | None:
|
|
370
|
+
"""Get names and types of the fields of a composite type."""
|
|
371
|
+
if not isinstance(typ, DbType):
|
|
372
|
+
typ = self.get(typ)
|
|
373
|
+
if not typ:
|
|
374
|
+
return None
|
|
375
|
+
if not typ.relid:
|
|
376
|
+
return None
|
|
377
|
+
return self._db.get_attnames(typ.relid)
|
|
378
|
+
|
|
379
|
+
def _get_cast(self, typ: DbType) -> Callable | None:
|
|
380
|
+
"""Get the typecast function for the given type object.
|
|
381
|
+
|
|
382
|
+
A typecast set for the name of the type is used first, but the
|
|
383
|
+
built-in default typecasts only for base types. Otherwise,
|
|
384
|
+
the typecast is created from the base type of domains, the fields
|
|
385
|
+
of composite types or the element type of arrays. These are
|
|
386
|
+
looked up by their OIDs, not by their names, which might be
|
|
387
|
+
ambiguous. The result is cached under the OID of the type until
|
|
388
|
+
typecasts are set or reset.
|
|
389
|
+
"""
|
|
390
|
+
type_casts = self._type_casts
|
|
391
|
+
if self._defaults_changed != Typecasts.defaults_changed:
|
|
392
|
+
# the typecasts may depend on changed defaults
|
|
393
|
+
type_casts.clear()
|
|
394
|
+
self._defaults_changed = Typecasts.defaults_changed
|
|
395
|
+
oid = typ.oid
|
|
396
|
+
try:
|
|
397
|
+
return type_casts[oid]
|
|
398
|
+
except KeyError:
|
|
399
|
+
pass
|
|
400
|
+
typecasts = self._typecasts
|
|
401
|
+
name = typ.pgtype
|
|
402
|
+
cast = None
|
|
403
|
+
if name in typecasts or name in typecasts.defaults:
|
|
404
|
+
cast = typecasts[name]
|
|
405
|
+
if typ.typtype not in 'bp' and is_builtin_typecast(name, cast):
|
|
406
|
+
# built-in typecasts are only used for base types
|
|
407
|
+
cast = None
|
|
408
|
+
if cast is None:
|
|
409
|
+
cast = self._create_cast(typ)
|
|
410
|
+
type_casts[oid] = cast
|
|
411
|
+
return cast
|
|
412
|
+
|
|
413
|
+
def _create_cast(self, typ: DbType) -> Callable | None:
|
|
414
|
+
"""Create a typecast function from the structure of the given type."""
|
|
415
|
+
if typ.base:
|
|
416
|
+
# domains are cast like their base types,
|
|
417
|
+
# unless a typecast has been set for the domain
|
|
418
|
+
return self._get_cast(typ.base)
|
|
419
|
+
typecasts = self._typecasts
|
|
420
|
+
if typ.relid:
|
|
421
|
+
attnames = self.get_attnames(typ)
|
|
422
|
+
if not attnames:
|
|
423
|
+
return None
|
|
424
|
+
casts = [self._get_cast(t) for t in attnames.values()]
|
|
425
|
+
return typecasts.create_record_cast(typ.pgtype, attnames, casts)
|
|
426
|
+
if is_array_type(typ.pgtype, typ.typlen, typ.elem):
|
|
427
|
+
elem_type = self.get(typ.elem)
|
|
428
|
+
if not elem_type: # pragma: no cover (always exists)
|
|
429
|
+
return typecasts.create_array_cast(None)
|
|
430
|
+
return typecasts.create_array_cast(
|
|
431
|
+
self._get_cast(elem_type), elem_type.delim)
|
|
432
|
+
return None
|
|
433
|
+
|
|
434
|
+
def get_typecast(self, typ: Any) -> Callable | None:
|
|
435
|
+
"""Get the typecast function for the given database type."""
|
|
436
|
+
if isinstance(typ, DbType) and hasattr(typ, 'oid'):
|
|
437
|
+
return self._get_cast(typ)
|
|
438
|
+
typecasts = self._typecasts
|
|
439
|
+
if isinstance(typ, str) and (
|
|
440
|
+
typ in typecasts or typ in typecasts.defaults):
|
|
441
|
+
return typecasts[typ]
|
|
442
|
+
db_type = self.get(typ)
|
|
443
|
+
if db_type:
|
|
444
|
+
return self._get_cast(db_type)
|
|
445
|
+
return typecasts.get(typ) if isinstance(typ, str) else None
|
|
446
|
+
|
|
447
|
+
def set_typecast(self, typ: str | Sequence[str], cast: Callable) -> None:
|
|
448
|
+
"""Set a typecast function for the specified database type(s)."""
|
|
449
|
+
self._typecasts.set(typ, cast)
|
|
450
|
+
self._type_casts.clear()
|
|
451
|
+
|
|
452
|
+
def _clear_type_casts(self) -> None:
|
|
453
|
+
"""Clear the typecasts created for type objects.
|
|
454
|
+
|
|
455
|
+
These depend on the fields of composite types, which may change.
|
|
456
|
+
"""
|
|
457
|
+
self._type_casts.clear()
|
|
458
|
+
|
|
459
|
+
def _set_connection(self, cnx: Connection) -> None:
|
|
460
|
+
"""Use a new database connection, e.g. after reopening it.
|
|
461
|
+
|
|
462
|
+
Types are looked up again, since they may differ in the new session,
|
|
463
|
+
e.g. temporary types, and typecasts that have been bound to the old
|
|
464
|
+
connection are bound to the new one.
|
|
465
|
+
"""
|
|
466
|
+
self.clear()
|
|
467
|
+
self._type_casts.clear()
|
|
468
|
+
typecasts = self._typecasts
|
|
469
|
+
old_cnx, typecasts.connection = typecasts.connection, cnx
|
|
470
|
+
for typ, cast in list(typecasts.items()):
|
|
471
|
+
if (isinstance(cast, partial)
|
|
472
|
+
and cast.keywords.get('connection') is old_cnx):
|
|
473
|
+
typecasts[typ] = partial(
|
|
474
|
+
cast.func, *cast.args, **{**cast.keywords,
|
|
475
|
+
'connection': cnx})
|
|
476
|
+
|
|
477
|
+
def reset_typecast(self, typ: str | Sequence[str] | None = None) -> None:
|
|
478
|
+
"""Reset the typecast function for the specified database type(s)."""
|
|
479
|
+
self._typecasts.reset(typ)
|
|
480
|
+
self._type_casts.clear()
|
|
481
|
+
|
|
482
|
+
def typecast(self, value: Any, typ: Any) -> Any:
|
|
483
|
+
"""Cast the given value according to the given database type."""
|
|
484
|
+
if value is None:
|
|
485
|
+
# for NULL values, no typecast is necessary
|
|
486
|
+
return None
|
|
487
|
+
db_type = typ if isinstance(typ, DbType) and hasattr(
|
|
488
|
+
typ, 'oid') else self.get(typ)
|
|
489
|
+
if db_type:
|
|
490
|
+
cast = self._get_cast(db_type)
|
|
491
|
+
elif isinstance(typ, str) and typ:
|
|
492
|
+
cast = self._typecasts.get(typ)
|
|
493
|
+
else:
|
|
494
|
+
cast = None
|
|
495
|
+
if not cast or cast is str:
|
|
496
|
+
# no typecast is necessary
|
|
497
|
+
return value
|
|
498
|
+
return cast(value)
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
class Adapter:
|
|
502
|
+
"""Class providing methods for adapting parameters to the database."""
|
|
503
|
+
|
|
504
|
+
_bool_true_values = frozenset(['t', 'true', '1', 'y', 'yes', 'on'])
|
|
505
|
+
|
|
506
|
+
_date_literals = frozenset([
|
|
507
|
+
'current_date', 'current_time', 'current_timestamp',
|
|
508
|
+
'localtime', 'localtimestamp'])
|
|
509
|
+
|
|
510
|
+
_re_array_quote = regex(r'[{},"\\\s]|^[Nn][Uu][Ll][Ll]$')
|
|
511
|
+
_re_record_quote = regex(r'[(),"\\]')
|
|
512
|
+
_re_array_escape = _re_record_escape = regex(r'(["\\])')
|
|
513
|
+
|
|
514
|
+
def __init__(self, db: DB):
|
|
515
|
+
"""Initialize the adapter object with the given connection."""
|
|
516
|
+
self.db = weakref.proxy(db)
|
|
517
|
+
|
|
518
|
+
@classmethod
|
|
519
|
+
def _adapt_bool(cls, v: Any) -> str | None:
|
|
520
|
+
"""Adapt a boolean parameter."""
|
|
521
|
+
if isinstance(v, str):
|
|
522
|
+
if not v:
|
|
523
|
+
return None
|
|
524
|
+
v = v.lower() in cls._bool_true_values
|
|
525
|
+
return 't' if v else 'f'
|
|
526
|
+
|
|
527
|
+
@classmethod
|
|
528
|
+
def _adapt_date(cls, v: Any) -> Any:
|
|
529
|
+
"""Adapt a date parameter."""
|
|
530
|
+
if not v:
|
|
531
|
+
return None
|
|
532
|
+
if isinstance(v, str) and v.lower() in cls._date_literals:
|
|
533
|
+
return Literal(v)
|
|
534
|
+
return v
|
|
535
|
+
|
|
536
|
+
@staticmethod
|
|
537
|
+
def _adapt_num(v: Any) -> Any:
|
|
538
|
+
"""Adapt a numeric parameter."""
|
|
539
|
+
if not v and v != 0:
|
|
540
|
+
return None
|
|
541
|
+
return v
|
|
542
|
+
|
|
543
|
+
_adapt_int = _adapt_float = _adapt_money = _adapt_num
|
|
544
|
+
|
|
545
|
+
def _adapt_bytea(self, v: Any) -> str:
|
|
546
|
+
"""Adapt a bytea parameter."""
|
|
547
|
+
return self.db.escape_bytea(v)
|
|
548
|
+
|
|
549
|
+
def _adapt_json(self, v: Any) -> str:
|
|
550
|
+
"""Adapt a json parameter (None has been handled by the caller)."""
|
|
551
|
+
if isinstance(v, str):
|
|
552
|
+
return v
|
|
553
|
+
if isinstance(v, Json):
|
|
554
|
+
return str(v)
|
|
555
|
+
return self.db.encode_json(v)
|
|
556
|
+
|
|
557
|
+
def _adapt_hstore(self, v: Any) -> str | bytes:
|
|
558
|
+
"""Adapt a hstore parameter (None has been handled by the caller)."""
|
|
559
|
+
if isinstance(v, (str, bytes)):
|
|
560
|
+
return v
|
|
561
|
+
if isinstance(v, dict):
|
|
562
|
+
if not isinstance(v, Hstore):
|
|
563
|
+
v = Hstore(v)
|
|
564
|
+
return v._literal(self._encoding)
|
|
565
|
+
raise TypeError(f'Hstore parameter {v} has wrong type')
|
|
566
|
+
|
|
567
|
+
def _adapt_uuid(self, v: Any) -> str | None:
|
|
568
|
+
"""Adapt a UUID parameter."""
|
|
569
|
+
if not v:
|
|
570
|
+
return None
|
|
571
|
+
if isinstance(v, str):
|
|
572
|
+
return v
|
|
573
|
+
return str(v)
|
|
574
|
+
|
|
575
|
+
def _encoding(self) -> str:
|
|
576
|
+
"""Get the Python codec name of the client encoding."""
|
|
577
|
+
return self.db.encoding
|
|
578
|
+
|
|
579
|
+
def _join(self, parts: list[str | bytes], sep: str = ',',
|
|
580
|
+
start: str = '', end: str = '') -> str | bytes:
|
|
581
|
+
"""Join parts of a literal, as bytes if any of the parts is bytes."""
|
|
582
|
+
return join_text(parts, sep, self._encoding, start, end)
|
|
583
|
+
|
|
584
|
+
def _to_text(self, v: Any) -> str | bytes:
|
|
585
|
+
"""Convert a value to text, like the C extension does.
|
|
586
|
+
|
|
587
|
+
Hstore values are converted to their literal, as bytes if they
|
|
588
|
+
contain raw text given as bytes, all other values with str().
|
|
589
|
+
"""
|
|
590
|
+
if isinstance(v, Hstore):
|
|
591
|
+
return v._literal(self._encoding)
|
|
592
|
+
return str(v)
|
|
593
|
+
|
|
594
|
+
_re_array_quote_bytes = regex(rb'[{},"\\\s]|^[Nn][Uu][Ll][Ll]$')
|
|
595
|
+
_re_record_quote_bytes = regex(rb'[(),"\\]')
|
|
596
|
+
_re_escape_bytes = regex(rb'(["\\])')
|
|
597
|
+
|
|
598
|
+
@classmethod
|
|
599
|
+
def _quote_array_element(cls, v: str | bytes) -> str | bytes:
|
|
600
|
+
"""Quote an adapted element of an array if necessary."""
|
|
601
|
+
if isinstance(v, bytes):
|
|
602
|
+
if not v:
|
|
603
|
+
return b'""'
|
|
604
|
+
if cls._re_array_quote_bytes.search(v):
|
|
605
|
+
v = b'"' + cls._re_escape_bytes.sub(rb'\\\1', v) + b'"'
|
|
606
|
+
return v
|
|
607
|
+
if not v:
|
|
608
|
+
return '""'
|
|
609
|
+
if cls._re_array_quote.search(v):
|
|
610
|
+
v = cls._re_array_escape.sub(r'\\\1', v)
|
|
611
|
+
v = f'"{v}"'
|
|
612
|
+
return v
|
|
613
|
+
|
|
614
|
+
@classmethod
|
|
615
|
+
def _quote_record_field(cls, v: str | bytes) -> str | bytes:
|
|
616
|
+
"""Quote an adapted field of a record if necessary."""
|
|
617
|
+
if isinstance(v, bytes):
|
|
618
|
+
if not v:
|
|
619
|
+
return b'""'
|
|
620
|
+
if cls._re_record_quote_bytes.search(v):
|
|
621
|
+
v = b'"' + cls._re_escape_bytes.sub(rb'\\\1', v) + b'"'
|
|
622
|
+
return v
|
|
623
|
+
if not v:
|
|
624
|
+
return '""'
|
|
625
|
+
if cls._re_record_quote.search(v):
|
|
626
|
+
v = cls._re_record_escape.sub(r'\\\1', v)
|
|
627
|
+
v = f'"{v}"'
|
|
628
|
+
return v
|
|
629
|
+
|
|
630
|
+
def _adapt_array(self, v: Any,
|
|
631
|
+
adapt: Callable[[Any], str | bytes | None],
|
|
632
|
+
reject_buffers: bool = True) -> str | bytes:
|
|
633
|
+
"""Adapt an array parameter using the given element adapter.
|
|
634
|
+
|
|
635
|
+
Elements given as bytes are raw text in the client encoding,
|
|
636
|
+
which is passed unchanged. Elements of the types bytearray and
|
|
637
|
+
memoryview raise a TypeError, unless reject_buffers is false.
|
|
638
|
+
"""
|
|
639
|
+
if isinstance(v, list):
|
|
640
|
+
return self._join(
|
|
641
|
+
[self._adapt_array(v, adapt, reject_buffers) for v in v],
|
|
642
|
+
',', '{', '}')
|
|
643
|
+
if v is None:
|
|
644
|
+
return 'null'
|
|
645
|
+
if isinstance(v, bytes):
|
|
646
|
+
return self._quote_array_element(v)
|
|
647
|
+
if reject_buffers:
|
|
648
|
+
_reject_buffer(v)
|
|
649
|
+
v = adapt(v)
|
|
650
|
+
return 'null' if v is None else v
|
|
651
|
+
|
|
652
|
+
def _adapt_text_array(self, v: Any) -> str | bytes:
|
|
653
|
+
"""Adapt a text type array parameter."""
|
|
654
|
+
return self._adapt_array(
|
|
655
|
+
v, lambda v: self._quote_array_element(self._to_text(v)))
|
|
656
|
+
|
|
657
|
+
_adapt_date_array = _adapt_text_array
|
|
658
|
+
|
|
659
|
+
def _adapt_bool_array(self, v: Any) -> str | bytes:
|
|
660
|
+
"""Adapt a boolean array parameter."""
|
|
661
|
+
def adapt(v: Any) -> str | None:
|
|
662
|
+
if isinstance(v, str):
|
|
663
|
+
if not v:
|
|
664
|
+
return None
|
|
665
|
+
v = v.lower() in self._bool_true_values
|
|
666
|
+
return 't' if v else 'f'
|
|
667
|
+
return self._adapt_array(v, adapt)
|
|
668
|
+
|
|
669
|
+
def _adapt_num_array(self, v: Any) -> str | bytes:
|
|
670
|
+
"""Adapt a numeric array parameter."""
|
|
671
|
+
return self._adapt_array(
|
|
672
|
+
v, lambda v: None if not v and v != 0 else str(v))
|
|
673
|
+
|
|
674
|
+
_adapt_int_array = _adapt_float_array = _adapt_money_array = \
|
|
675
|
+
_adapt_num_array
|
|
676
|
+
|
|
677
|
+
def _adapt_bytea_array(self, v: Any) -> bytes:
|
|
678
|
+
"""Adapt a bytea array parameter."""
|
|
679
|
+
if isinstance(v, list):
|
|
680
|
+
return b'{' + b','.join(
|
|
681
|
+
self._adapt_bytea_array(v) for v in v) + b'}'
|
|
682
|
+
if v is None:
|
|
683
|
+
return b'null'
|
|
684
|
+
_reject_buffer(v)
|
|
685
|
+
return self.db.escape_bytea(v).replace(b'\\', b'\\\\')
|
|
686
|
+
|
|
687
|
+
def _adapt_json_array(self, v: Any) -> str | bytes:
|
|
688
|
+
"""Adapt a json array parameter."""
|
|
689
|
+
def adapt(v: Any) -> str | bytes | None:
|
|
690
|
+
if v == '': # empty strings are adapted as null
|
|
691
|
+
return None
|
|
692
|
+
return self._quote_array_element(self._adapt_json(v))
|
|
693
|
+
# the JSON encoder may handle bytearray and memoryview objects
|
|
694
|
+
return self._adapt_array(v, adapt, reject_buffers=False)
|
|
695
|
+
|
|
696
|
+
def _adapt_hstore_array(self, v: Any) -> str | bytes:
|
|
697
|
+
"""Adapt a hstore array parameter."""
|
|
698
|
+
def adapt(v: Any) -> str | bytes:
|
|
699
|
+
return self._quote_array_element(self._adapt_hstore(v))
|
|
700
|
+
return self._adapt_array(v, adapt)
|
|
701
|
+
|
|
702
|
+
def _adapt_uuid_array(self, v: Any) -> str | bytes:
|
|
703
|
+
"""Adapt a UUID array parameter."""
|
|
704
|
+
def adapt(v: Any) -> str | bytes | None:
|
|
705
|
+
v = self._adapt_uuid(v)
|
|
706
|
+
return None if v is None else self._quote_array_element(v)
|
|
707
|
+
return self._adapt_array(v, adapt)
|
|
708
|
+
|
|
709
|
+
def _adapt_record_array(self, v: Any, typ: Any) -> str | bytes:
|
|
710
|
+
"""Adapt a record array parameter with given type."""
|
|
711
|
+
elem = getattr(typ, 'elem', None)
|
|
712
|
+
elem_type = self.db.dbtypes.get(elem) if elem else None
|
|
713
|
+
|
|
714
|
+
def adapt(v: Any) -> str | bytes:
|
|
715
|
+
if isinstance(v, tuple):
|
|
716
|
+
v = self._adapt_record(
|
|
717
|
+
v, elem_type or self.guess_simple_type(v))
|
|
718
|
+
else:
|
|
719
|
+
v = self._to_text(v)
|
|
720
|
+
return self._quote_array_element(v)
|
|
721
|
+
return self._adapt_array(v, adapt)
|
|
722
|
+
|
|
723
|
+
def _adapt_record(self, v: Any, typ: Any) -> str | bytes:
|
|
724
|
+
"""Adapt a record parameter with given type.
|
|
725
|
+
|
|
726
|
+
For anonymous records, the types of the fields are guessed.
|
|
727
|
+
"""
|
|
728
|
+
attnames = self.get_attnames(typ) or self.get_attnames(
|
|
729
|
+
self.guess_simple_type(v))
|
|
730
|
+
typ = attnames.values()
|
|
731
|
+
if len(typ) != len(v):
|
|
732
|
+
raise TypeError(f'Record parameter {v} has wrong size')
|
|
733
|
+
adapt = self.adapt
|
|
734
|
+
value: list[str | bytes] = []
|
|
735
|
+
for v, t in zip(v, typ, strict=True): # noqa: B020
|
|
736
|
+
v = adapt(v, t)
|
|
737
|
+
if v is None:
|
|
738
|
+
v = ''
|
|
739
|
+
else:
|
|
740
|
+
if not isinstance(v, (str, bytes)):
|
|
741
|
+
v = self._to_text(v)
|
|
742
|
+
v = self._quote_record_field(v)
|
|
743
|
+
value.append(v)
|
|
744
|
+
return self._join(value, ',', '(', ')')
|
|
745
|
+
|
|
746
|
+
def adapt(self, value: Any, typ: Any = None) -> Any:
|
|
747
|
+
"""Adapt a value with known database type.
|
|
748
|
+
|
|
749
|
+
Values given as bytes for other types than bytea are raw text in
|
|
750
|
+
the client encoding, which is passed unchanged.
|
|
751
|
+
"""
|
|
752
|
+
if value is not None and not isinstance(value, Literal):
|
|
753
|
+
if typ:
|
|
754
|
+
simple = self.get_simple_name(typ)
|
|
755
|
+
else:
|
|
756
|
+
typ = simple = self.guess_simple_type(value) or 'text'
|
|
757
|
+
if isinstance(value, bytes) and simple != 'bytea':
|
|
758
|
+
return value
|
|
759
|
+
pg_str = getattr(value, '__pg_str__', None)
|
|
760
|
+
if pg_str:
|
|
761
|
+
value = pg_str(typ)
|
|
762
|
+
if not (simple == 'json' or (
|
|
763
|
+
simple == 'json[]' and isinstance(value, list))):
|
|
764
|
+
# the JSON encoder may handle bytearray and memoryview
|
|
765
|
+
_reject_buffer(value)
|
|
766
|
+
if simple == 'text':
|
|
767
|
+
pass
|
|
768
|
+
elif simple == 'record':
|
|
769
|
+
if isinstance(value, tuple):
|
|
770
|
+
value = self._adapt_record(value, typ)
|
|
771
|
+
elif simple.endswith('[]'):
|
|
772
|
+
if isinstance(value, list):
|
|
773
|
+
if simple == 'record[]':
|
|
774
|
+
value = self._adapt_record_array(value, typ)
|
|
775
|
+
else:
|
|
776
|
+
adapt = getattr(self, f'_adapt_{simple[:-2]}_array')
|
|
777
|
+
value = adapt(value)
|
|
778
|
+
else:
|
|
779
|
+
adapt = getattr(self, f'_adapt_{simple}')
|
|
780
|
+
value = adapt(value)
|
|
781
|
+
return value
|
|
782
|
+
|
|
783
|
+
def _adapt_parameter(self, value: Any, typ: Any = None) -> Any:
|
|
784
|
+
"""Adapt a value that is passed as a separate parameter.
|
|
785
|
+
|
|
786
|
+
Binary data for bytea is passed as Bytea, which is sent to the
|
|
787
|
+
server in binary format. Values nested in other values and values
|
|
788
|
+
put into the SQL inline are still adapted as text.
|
|
789
|
+
"""
|
|
790
|
+
if isinstance(value, bytes) and not hasattr(value, '__pg_str__'):
|
|
791
|
+
simple = (self.get_simple_name(typ) if typ
|
|
792
|
+
else self.guess_simple_type(value))
|
|
793
|
+
if simple == 'bytea':
|
|
794
|
+
return value if isinstance(value, Bytea) else Bytea(value)
|
|
795
|
+
return self.adapt(value, typ)
|
|
796
|
+
|
|
797
|
+
@staticmethod
|
|
798
|
+
def simple_type(name: str) -> DbType:
|
|
799
|
+
"""Create a simple database type object with the given name."""
|
|
800
|
+
typ = DbType(name)
|
|
801
|
+
typ.simple = name
|
|
802
|
+
return typ
|
|
803
|
+
|
|
804
|
+
@staticmethod
|
|
805
|
+
def get_simple_name(typ: Any) -> str:
|
|
806
|
+
"""Get the simple name of a database type."""
|
|
807
|
+
if isinstance(typ, DbType):
|
|
808
|
+
# noinspection PyUnresolvedReferences
|
|
809
|
+
return typ.simple
|
|
810
|
+
return _simpletypes[typ]
|
|
811
|
+
|
|
812
|
+
@staticmethod
|
|
813
|
+
def get_attnames(typ: Any) -> dict[str, dict[str, str]]:
|
|
814
|
+
"""Get the attribute names of a composite database type."""
|
|
815
|
+
if isinstance(typ, DbType):
|
|
816
|
+
return typ.attnames
|
|
817
|
+
return {}
|
|
818
|
+
|
|
819
|
+
@classmethod
|
|
820
|
+
def guess_simple_type(cls, value: Any) -> str | None:
|
|
821
|
+
"""Try to guess which database type the given value has."""
|
|
822
|
+
# optimize for most frequent types
|
|
823
|
+
try:
|
|
824
|
+
return _simple_type_dict[type(value)]
|
|
825
|
+
except KeyError:
|
|
826
|
+
pass
|
|
827
|
+
if isinstance(value, str):
|
|
828
|
+
return 'text'
|
|
829
|
+
if isinstance(value, bytes):
|
|
830
|
+
return 'bytea'
|
|
831
|
+
# bool cannot be subclassed and has been found above
|
|
832
|
+
if isinstance(value, int):
|
|
833
|
+
return 'int'
|
|
834
|
+
if isinstance(value, float):
|
|
835
|
+
return 'float'
|
|
836
|
+
if isinstance(value, Decimal):
|
|
837
|
+
return 'num'
|
|
838
|
+
if isinstance(value, (date, time, datetime, timedelta)):
|
|
839
|
+
return 'date'
|
|
840
|
+
if isinstance(value, Json):
|
|
841
|
+
return 'json'
|
|
842
|
+
if isinstance(value, Hstore):
|
|
843
|
+
return 'hstore'
|
|
844
|
+
if isinstance(value, UUID):
|
|
845
|
+
return 'uuid'
|
|
846
|
+
if isinstance(value, list):
|
|
847
|
+
return (cls.guess_simple_base_type(value) or 'text') + '[]'
|
|
848
|
+
if isinstance(value, tuple):
|
|
849
|
+
simple_type = cls.simple_type
|
|
850
|
+
guess = cls.guess_simple_type
|
|
851
|
+
|
|
852
|
+
# noinspection PyUnusedLocal
|
|
853
|
+
def get_attnames(self: DbType) -> AttrDict:
|
|
854
|
+
return AttrDict((str(n + 1), simple_type(guess(v) or 'text'))
|
|
855
|
+
for n, v in enumerate(value))
|
|
856
|
+
|
|
857
|
+
typ = simple_type('record')
|
|
858
|
+
typ._get_attnames = get_attnames
|
|
859
|
+
return typ
|
|
860
|
+
if isinstance(value, dict) and not hasattr(value, '__pg_str__'):
|
|
861
|
+
# do not guess between json and hstore or adapt as text
|
|
862
|
+
raise adapt_error(value)
|
|
863
|
+
return None
|
|
864
|
+
|
|
865
|
+
@classmethod
|
|
866
|
+
def guess_simple_base_type(cls, value: Any) -> str | None:
|
|
867
|
+
"""Try to guess the base type of a given array."""
|
|
868
|
+
for v in value:
|
|
869
|
+
if isinstance(v, list):
|
|
870
|
+
typ = cls.guess_simple_base_type(v)
|
|
871
|
+
else:
|
|
872
|
+
typ = cls.guess_simple_type(v)
|
|
873
|
+
if typ:
|
|
874
|
+
return typ
|
|
875
|
+
return None
|
|
876
|
+
|
|
877
|
+
def adapt_inline(self, value: Any, nested: bool=False) -> Any:
|
|
878
|
+
"""Adapt a value that is put into the SQL and needs to be quoted."""
|
|
879
|
+
if value is None:
|
|
880
|
+
return 'NULL'
|
|
881
|
+
if isinstance(value, Literal):
|
|
882
|
+
return value
|
|
883
|
+
if isinstance(value, bytes):
|
|
884
|
+
value = self.db.escape_bytea(value).decode('ascii')
|
|
885
|
+
value = self.db.escape_string(value)
|
|
886
|
+
return f"'{value}'::bytea"
|
|
887
|
+
if isinstance(value, (datetime, date, time, timedelta)):
|
|
888
|
+
value = str(value)
|
|
889
|
+
if isinstance(value, str):
|
|
890
|
+
value = self.db.escape_string(value)
|
|
891
|
+
return f"'{value}'"
|
|
892
|
+
if isinstance(value, bool):
|
|
893
|
+
return 'true' if value else 'false'
|
|
894
|
+
if isinstance(value, float):
|
|
895
|
+
if isinf(value):
|
|
896
|
+
return "'-Infinity'" if value < 0 else "'Infinity'"
|
|
897
|
+
if isnan(value):
|
|
898
|
+
return "'NaN'"
|
|
899
|
+
return value
|
|
900
|
+
if isinstance(value, (int, Decimal)):
|
|
901
|
+
return value
|
|
902
|
+
if isinstance(value, list):
|
|
903
|
+
q = self.adapt_inline
|
|
904
|
+
return self._join(
|
|
905
|
+
[self._inline_part(q(v, nested=True)) for v in value],
|
|
906
|
+
',', '[' if nested else 'ARRAY[', ']')
|
|
907
|
+
if isinstance(value, tuple):
|
|
908
|
+
q = self.adapt_inline
|
|
909
|
+
return self._join(
|
|
910
|
+
[self._inline_part(q(v)) for v in value], ',', '(', ')')
|
|
911
|
+
if isinstance(value, Json):
|
|
912
|
+
value = self.db.escape_string(str(value))
|
|
913
|
+
return f"'{value}'::json"
|
|
914
|
+
if isinstance(value, Hstore):
|
|
915
|
+
try:
|
|
916
|
+
value = value._literal(self._encoding)
|
|
917
|
+
except TypeError as e: # e.g. bytearray as key or value
|
|
918
|
+
raise InterfaceError(str(e)) from e
|
|
919
|
+
if isinstance(value, bytes):
|
|
920
|
+
return b"'" + self.db.escape_string(value) + b"'::hstore"
|
|
921
|
+
value = self.db.escape_string(value)
|
|
922
|
+
return f"'{value}'::hstore"
|
|
923
|
+
if isinstance(value, UUID):
|
|
924
|
+
return f"'{value}'::uuid"
|
|
925
|
+
if isinstance(value, (IPv4Address, IPv6Address)): # or interface
|
|
926
|
+
value = self.db.escape_string(str(value))
|
|
927
|
+
return f"'{value}'::inet"
|
|
928
|
+
if isinstance(value, (IPv4Network, IPv6Network)):
|
|
929
|
+
value = self.db.escape_string(str(value))
|
|
930
|
+
return f"'{value}'::cidr"
|
|
931
|
+
pg_repr = getattr(value, '__pg_repr__', None)
|
|
932
|
+
if not pg_repr:
|
|
933
|
+
raise adapt_error(value)
|
|
934
|
+
value = pg_repr()
|
|
935
|
+
if isinstance(value, (tuple, list)):
|
|
936
|
+
value = self.adapt_inline(value)
|
|
937
|
+
return value
|
|
938
|
+
|
|
939
|
+
@staticmethod
|
|
940
|
+
def _inline_part(value: Any) -> str | bytes:
|
|
941
|
+
"""Convert an adapted inline value to a part of a literal."""
|
|
942
|
+
return value if isinstance(value, (str, bytes)) else str(value)
|
|
943
|
+
|
|
944
|
+
def parameter_list(self) -> _ParameterList:
|
|
945
|
+
"""Return a parameter list for parameters with known database types.
|
|
946
|
+
|
|
947
|
+
The list has an add(value, typ) method that will build up the
|
|
948
|
+
list and return either the literal value or a placeholder.
|
|
949
|
+
"""
|
|
950
|
+
params = _ParameterList()
|
|
951
|
+
params.adapt = self._adapt_parameter
|
|
952
|
+
return params
|
|
953
|
+
|
|
954
|
+
def format_query(self, command: str | bytes,
|
|
955
|
+
values: list | tuple | dict | None = None,
|
|
956
|
+
types: list | tuple | dict | None = None,
|
|
957
|
+
inline: bool=False
|
|
958
|
+
) -> tuple[str | bytes, _ParameterList]:
|
|
959
|
+
"""Format a database query using the given values and types.
|
|
960
|
+
|
|
961
|
+
The optional types describe the values and must be passed as a list,
|
|
962
|
+
tuple or string (that will be split on whitespace) when values are
|
|
963
|
+
passed as a list or tuple, or as a dict if values are passed as a dict.
|
|
964
|
+
|
|
965
|
+
If inline is set to True, then parameters will be passed inline
|
|
966
|
+
together with the query string.
|
|
967
|
+
"""
|
|
968
|
+
params = self.parameter_list()
|
|
969
|
+
if not values:
|
|
970
|
+
return command, params
|
|
971
|
+
if inline and types:
|
|
972
|
+
raise ValueError('Typed parameters must be sent separately')
|
|
973
|
+
if isinstance(values, (list, tuple)):
|
|
974
|
+
if inline:
|
|
975
|
+
adapt = self.adapt_inline
|
|
976
|
+
seq_literals = [adapt(value) for value in values]
|
|
977
|
+
else:
|
|
978
|
+
add = params.add
|
|
979
|
+
if types:
|
|
980
|
+
if isinstance(types, str):
|
|
981
|
+
types = types.split()
|
|
982
|
+
if (not isinstance(types, (list, tuple))
|
|
983
|
+
or len(types) != len(values)):
|
|
984
|
+
raise TypeError('The values and types do not match')
|
|
985
|
+
seq_literals = [
|
|
986
|
+
add(value, typ)
|
|
987
|
+
for value, typ in zip(values, types, strict=True)]
|
|
988
|
+
else:
|
|
989
|
+
seq_literals = [add(value) for value in values]
|
|
990
|
+
formatted = format_text(
|
|
991
|
+
command, tuple(seq_literals), self._encoding)
|
|
992
|
+
elif isinstance(values, dict):
|
|
993
|
+
# we want to allow extra keys in the dictionary,
|
|
994
|
+
# so we first must find the values actually used in the command;
|
|
995
|
+
# in a command given as bytes, the keys are encoded like the
|
|
996
|
+
# command is encoded for keys given as str
|
|
997
|
+
empty: str | bytes
|
|
998
|
+
if isinstance(command, bytes):
|
|
999
|
+
codec = self._encoding()
|
|
1000
|
+
names = {key.encode(codec) if isinstance(key, str) else key:
|
|
1001
|
+
key for key in values}
|
|
1002
|
+
empty = b''
|
|
1003
|
+
else:
|
|
1004
|
+
names = {key: key for key in values}
|
|
1005
|
+
empty = ''
|
|
1006
|
+
used_values = {}
|
|
1007
|
+
map_literals: dict = dict.fromkeys(names, empty)
|
|
1008
|
+
for name, key in names.items():
|
|
1009
|
+
del map_literals[name]
|
|
1010
|
+
try:
|
|
1011
|
+
command % map_literals
|
|
1012
|
+
except KeyError:
|
|
1013
|
+
used_values[name] = values[key]
|
|
1014
|
+
map_literals[name] = empty
|
|
1015
|
+
if inline:
|
|
1016
|
+
adapt = self.adapt_inline
|
|
1017
|
+
map_literals = {key: adapt(value)
|
|
1018
|
+
for key, value in used_values.items()}
|
|
1019
|
+
else:
|
|
1020
|
+
add = params.add
|
|
1021
|
+
if types:
|
|
1022
|
+
if not isinstance(types, dict):
|
|
1023
|
+
raise TypeError('The values and types do not match')
|
|
1024
|
+
map_literals = {
|
|
1025
|
+
name: add(used_values[name], types.get(names[name]))
|
|
1026
|
+
for name in sorted(used_values)}
|
|
1027
|
+
else:
|
|
1028
|
+
map_literals = {key: add(used_values[key])
|
|
1029
|
+
for key in sorted(used_values)}
|
|
1030
|
+
formatted = format_text(command, map_literals, self._encoding)
|
|
1031
|
+
else:
|
|
1032
|
+
raise TypeError('The values must be passed as tuple, list or dict')
|
|
1033
|
+
return formatted, params
|