PyGreSQL 6.2.0__cp314-cp314-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 +186 -0
- pg/_pg.cp314-win_amd64.pyd +0 -0
- pg/_pg.pyi +638 -0
- pg/adapt.py +687 -0
- pg/attrs.py +35 -0
- pg/cast.py +446 -0
- pg/core.py +178 -0
- pg/db.py +1506 -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
- pygresql-6.2.0.dist-info/METADATA +85 -0
- pygresql-6.2.0.dist-info/RECORD +27 -0
- pygresql-6.2.0.dist-info/WHEEL +5 -0
- pygresql-6.2.0.dist-info/licenses/LICENSE.txt +30 -0
- pygresql-6.2.0.dist-info/top_level.txt +2 -0
pg/adapt.py
ADDED
|
@@ -0,0 +1,687 @@
|
|
|
1
|
+
"""Adaptation of parameters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import weakref
|
|
6
|
+
from datetime import date, datetime, time, timedelta
|
|
7
|
+
from decimal import Decimal
|
|
8
|
+
from json import dumps as jsonencode
|
|
9
|
+
from math import isinf, isnan
|
|
10
|
+
from re import compile as regex
|
|
11
|
+
from types import MappingProxyType
|
|
12
|
+
from typing import TYPE_CHECKING, Any, Callable, List, Mapping, Sequence
|
|
13
|
+
from uuid import UUID
|
|
14
|
+
|
|
15
|
+
from .attrs import AttrDict
|
|
16
|
+
from .cast import Typecasts
|
|
17
|
+
from .core import InterfaceError, ProgrammingError
|
|
18
|
+
from .helpers import quote_if_unqualified
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from .db import DB
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
'UUID',
|
|
25
|
+
'Adapter',
|
|
26
|
+
'Bytea',
|
|
27
|
+
'DbType',
|
|
28
|
+
'DbTypes',
|
|
29
|
+
'Hstore',
|
|
30
|
+
'Json',
|
|
31
|
+
'Literal'
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Bytea(bytes):
|
|
36
|
+
"""Wrapper class for marking Bytea values."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Hstore(dict):
|
|
40
|
+
"""Wrapper class for marking hstore values."""
|
|
41
|
+
|
|
42
|
+
_re_quote = regex('^[Nn][Uu][Ll][Ll]$|[ ,=>]')
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def _quote(cls, s: Any) -> str:
|
|
46
|
+
if s is None:
|
|
47
|
+
return 'NULL'
|
|
48
|
+
if not isinstance(s, str):
|
|
49
|
+
s = str(s)
|
|
50
|
+
if not s:
|
|
51
|
+
return '""'
|
|
52
|
+
s = s.replace('"', '\\"')
|
|
53
|
+
if cls._re_quote.search(s):
|
|
54
|
+
s = f'"{s}"'
|
|
55
|
+
return s
|
|
56
|
+
|
|
57
|
+
def __str__(self) -> str:
|
|
58
|
+
"""Create a printable representation of the hstore value."""
|
|
59
|
+
q = self._quote
|
|
60
|
+
return ','.join(f'{q(k)}=>{q(v)}' for k, v in self.items())
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Json:
|
|
64
|
+
"""Wrapper class for marking Json values."""
|
|
65
|
+
|
|
66
|
+
def __init__(self, obj: Any,
|
|
67
|
+
encode: Callable[[Any], str] | None = None) -> None:
|
|
68
|
+
"""Initialize the JSON object."""
|
|
69
|
+
self.obj = obj
|
|
70
|
+
self.encode = encode or jsonencode
|
|
71
|
+
|
|
72
|
+
def __str__(self) -> str:
|
|
73
|
+
"""Create a printable representation of the JSON object."""
|
|
74
|
+
obj = self.obj
|
|
75
|
+
if isinstance(obj, str):
|
|
76
|
+
return obj
|
|
77
|
+
return self.encode(obj)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class Literal(str):
|
|
81
|
+
"""Wrapper class for marking literal SQL values."""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class _SimpleTypes(dict):
|
|
86
|
+
"""Dictionary mapping pg_type names to simple type names.
|
|
87
|
+
|
|
88
|
+
The corresponding Python types and simple names are also mapped.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
_type_aliases: Mapping[str, list[str | type]] = MappingProxyType({
|
|
92
|
+
'bool': [bool],
|
|
93
|
+
'bytea': [Bytea],
|
|
94
|
+
'date': ['interval', 'time', 'timetz', 'timestamp', 'timestamptz',
|
|
95
|
+
'abstime', 'reltime', # these are very old
|
|
96
|
+
'datetime', 'timedelta', # these do not really exist
|
|
97
|
+
date, time, datetime, timedelta],
|
|
98
|
+
'float': ['float4', 'float8', float],
|
|
99
|
+
'int': ['cid', 'int2', 'int4', 'int8', 'oid', 'xid', int],
|
|
100
|
+
'hstore': [Hstore], 'json': ['jsonb', Json], 'uuid': [UUID],
|
|
101
|
+
'num': ['numeric', Decimal], 'money': [],
|
|
102
|
+
'text': ['bpchar', 'char', 'name', 'varchar', bytes, str]
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
# noinspection PyMissingConstructor
|
|
106
|
+
def __init__(self) -> None:
|
|
107
|
+
"""Initialize type mapping."""
|
|
108
|
+
for typ, keys in self._type_aliases.items():
|
|
109
|
+
keys = [typ, *keys]
|
|
110
|
+
for key in keys:
|
|
111
|
+
self[key] = typ
|
|
112
|
+
if isinstance(key, str):
|
|
113
|
+
self[f'_{key}'] = f'{typ}[]'
|
|
114
|
+
elif not isinstance(key, tuple):
|
|
115
|
+
self[List[key]] = f'{typ}[]' # type: ignore
|
|
116
|
+
|
|
117
|
+
@staticmethod
|
|
118
|
+
def __missing__(key: str) -> str:
|
|
119
|
+
"""Unmapped types are interpreted as text."""
|
|
120
|
+
return 'text'
|
|
121
|
+
|
|
122
|
+
def get_type_dict(self) -> dict[type, str]:
|
|
123
|
+
"""Get a plain dictionary of only the types."""
|
|
124
|
+
return {key: typ for key, typ in self.items()
|
|
125
|
+
if not isinstance(key, (str, tuple))}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
_simpletypes = _SimpleTypes()
|
|
129
|
+
_simple_type_dict = _simpletypes.get_type_dict()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class _ParameterList(list):
|
|
133
|
+
"""Helper class for building typed parameter lists."""
|
|
134
|
+
|
|
135
|
+
adapt: Callable
|
|
136
|
+
|
|
137
|
+
def add(self, value: Any, typ:Any = None) -> str:
|
|
138
|
+
"""Typecast value with known database type and build parameter list.
|
|
139
|
+
|
|
140
|
+
If this is a literal value, it will be returned as is. Otherwise, a
|
|
141
|
+
placeholder will be returned and the parameter list will be augmented.
|
|
142
|
+
"""
|
|
143
|
+
# noinspection PyUnresolvedReferences
|
|
144
|
+
value = self.adapt(value, typ)
|
|
145
|
+
if isinstance(value, Literal):
|
|
146
|
+
return value
|
|
147
|
+
self.append(value)
|
|
148
|
+
return f'${len(self)}'
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class DbType(str):
|
|
153
|
+
"""Class augmenting the simple type name with additional info.
|
|
154
|
+
|
|
155
|
+
The following additional information is provided:
|
|
156
|
+
|
|
157
|
+
oid: the PostgreSQL type OID
|
|
158
|
+
pgtype: the internal PostgreSQL data type name
|
|
159
|
+
regtype: the registered PostgreSQL data type name
|
|
160
|
+
simple: the more coarse-grained PyGreSQL type name
|
|
161
|
+
typlen: the internal size, negative if variable
|
|
162
|
+
typtype: b = base type, c = composite type etc.
|
|
163
|
+
category: A = Array, b = Boolean, C = Composite etc.
|
|
164
|
+
delim: delimiter for array types
|
|
165
|
+
relid: corresponding table for composite types
|
|
166
|
+
attnames: attributes for composite types
|
|
167
|
+
"""
|
|
168
|
+
|
|
169
|
+
oid: int
|
|
170
|
+
pgtype: str
|
|
171
|
+
regtype: str
|
|
172
|
+
simple: str
|
|
173
|
+
typlen: int
|
|
174
|
+
typtype: str
|
|
175
|
+
category: str
|
|
176
|
+
delim: str
|
|
177
|
+
relid: int
|
|
178
|
+
|
|
179
|
+
_get_attnames: Callable[[DbType], AttrDict]
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def attnames(self) -> AttrDict:
|
|
183
|
+
"""Get names and types of the fields of a composite type."""
|
|
184
|
+
# noinspection PyUnresolvedReferences
|
|
185
|
+
return self._get_attnames(self)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class DbTypes(dict):
|
|
189
|
+
"""Cache for PostgreSQL data types.
|
|
190
|
+
|
|
191
|
+
This cache maps type OIDs and names to DbType objects containing
|
|
192
|
+
information on the associated database type.
|
|
193
|
+
"""
|
|
194
|
+
|
|
195
|
+
_num_types = frozenset([
|
|
196
|
+
'int', 'float', 'num', 'money', 'int2', 'int4', 'int8',
|
|
197
|
+
'float4', 'float8', 'numeric', 'money'])
|
|
198
|
+
|
|
199
|
+
def __init__(self, db: DB) -> None:
|
|
200
|
+
"""Initialize type cache for connection."""
|
|
201
|
+
super().__init__()
|
|
202
|
+
self._db = weakref.proxy(db)
|
|
203
|
+
self._regtypes = False
|
|
204
|
+
self._typecasts = Typecasts()
|
|
205
|
+
self._typecasts.get_attnames = self.get_attnames # type: ignore
|
|
206
|
+
self._typecasts.connection = self._db.db
|
|
207
|
+
self._query_pg_type = (
|
|
208
|
+
"SELECT oid, typname, oid::pg_catalog.regtype,"
|
|
209
|
+
" typlen, typtype, typcategory, typdelim, typrelid"
|
|
210
|
+
" FROM pg_catalog.pg_type"
|
|
211
|
+
" WHERE oid OPERATOR(pg_catalog.=) {}::pg_catalog.regtype")
|
|
212
|
+
|
|
213
|
+
def add(self, oid: int, pgtype: str, regtype: str,
|
|
214
|
+
typlen: int, typtype: str, category: str, delim: str, relid: int
|
|
215
|
+
) -> DbType:
|
|
216
|
+
"""Create a PostgreSQL type name with additional info."""
|
|
217
|
+
if oid in self:
|
|
218
|
+
return self[oid]
|
|
219
|
+
simple = 'record' if relid else _simpletypes[pgtype]
|
|
220
|
+
typ = DbType(regtype if self._regtypes else simple)
|
|
221
|
+
typ.oid = oid
|
|
222
|
+
typ.simple = simple
|
|
223
|
+
typ.pgtype = pgtype
|
|
224
|
+
typ.regtype = regtype
|
|
225
|
+
typ.typlen = typlen
|
|
226
|
+
typ.typtype = typtype
|
|
227
|
+
typ.category = category
|
|
228
|
+
typ.delim = delim
|
|
229
|
+
typ.relid = relid
|
|
230
|
+
typ._get_attnames = self.get_attnames # type: ignore
|
|
231
|
+
return typ
|
|
232
|
+
|
|
233
|
+
def __missing__(self, key: int | str) -> DbType:
|
|
234
|
+
"""Get the type info from the database if it is not cached."""
|
|
235
|
+
try:
|
|
236
|
+
cmd = self._query_pg_type.format(quote_if_unqualified('$1', key))
|
|
237
|
+
res = self._db.query(cmd, (key,)).getresult()
|
|
238
|
+
except ProgrammingError:
|
|
239
|
+
res = None
|
|
240
|
+
if not res:
|
|
241
|
+
raise KeyError(f'Type {key} could not be found')
|
|
242
|
+
res = res[0]
|
|
243
|
+
typ = self.add(*res)
|
|
244
|
+
self[typ.oid] = self[typ.pgtype] = typ
|
|
245
|
+
return typ
|
|
246
|
+
|
|
247
|
+
def get(self, key: int | str, # type: ignore
|
|
248
|
+
default: DbType | None = None) -> DbType | None:
|
|
249
|
+
"""Get the type even if it is not cached."""
|
|
250
|
+
try:
|
|
251
|
+
return self[key]
|
|
252
|
+
except KeyError:
|
|
253
|
+
return default
|
|
254
|
+
|
|
255
|
+
def get_attnames(self, typ: Any) -> AttrDict | None:
|
|
256
|
+
"""Get names and types of the fields of a composite type."""
|
|
257
|
+
if not isinstance(typ, DbType):
|
|
258
|
+
typ = self.get(typ)
|
|
259
|
+
if not typ:
|
|
260
|
+
return None
|
|
261
|
+
if not typ.relid:
|
|
262
|
+
return None
|
|
263
|
+
return self._db.get_attnames(typ.relid, with_oid=False)
|
|
264
|
+
|
|
265
|
+
def get_typecast(self, typ: Any) -> Callable | None:
|
|
266
|
+
"""Get the typecast function for the given database type."""
|
|
267
|
+
return self._typecasts.get(typ)
|
|
268
|
+
|
|
269
|
+
def set_typecast(self, typ: str | Sequence[str], cast: Callable) -> None:
|
|
270
|
+
"""Set a typecast function for the specified database type(s)."""
|
|
271
|
+
self._typecasts.set(typ, cast)
|
|
272
|
+
|
|
273
|
+
def reset_typecast(self, typ: str | Sequence[str] | None = None) -> None:
|
|
274
|
+
"""Reset the typecast function for the specified database type(s)."""
|
|
275
|
+
self._typecasts.reset(typ)
|
|
276
|
+
|
|
277
|
+
def typecast(self, value: Any, typ: str) -> Any:
|
|
278
|
+
"""Cast the given value according to the given database type."""
|
|
279
|
+
if value is None:
|
|
280
|
+
# for NULL values, no typecast is necessary
|
|
281
|
+
return None
|
|
282
|
+
if not isinstance(typ, DbType):
|
|
283
|
+
db_type = self.get(typ)
|
|
284
|
+
if db_type:
|
|
285
|
+
typ = db_type.pgtype
|
|
286
|
+
cast = self.get_typecast(typ) if typ else None
|
|
287
|
+
if not cast or cast is str:
|
|
288
|
+
# no typecast is necessary
|
|
289
|
+
return value
|
|
290
|
+
return cast(value)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
class Adapter:
|
|
294
|
+
"""Class providing methods for adapting parameters to the database."""
|
|
295
|
+
|
|
296
|
+
_bool_true_values = frozenset(['t', 'true', '1', 'y', 'yes', 'on'])
|
|
297
|
+
|
|
298
|
+
_date_literals = frozenset([
|
|
299
|
+
'current_date', 'current_time', 'current_timestamp',
|
|
300
|
+
'localtime', 'localtimestamp'])
|
|
301
|
+
|
|
302
|
+
_re_array_quote = regex(r'[{},"\\\s]|^[Nn][Uu][Ll][Ll]$')
|
|
303
|
+
_re_record_quote = regex(r'[(,"\\]')
|
|
304
|
+
_re_array_escape = _re_record_escape = regex(r'(["\\])')
|
|
305
|
+
|
|
306
|
+
def __init__(self, db: DB):
|
|
307
|
+
"""Initialize the adapter object with the given connection."""
|
|
308
|
+
self.db = weakref.proxy(db)
|
|
309
|
+
|
|
310
|
+
@classmethod
|
|
311
|
+
def _adapt_bool(cls, v: Any) -> str | None:
|
|
312
|
+
"""Adapt a boolean parameter."""
|
|
313
|
+
if isinstance(v, str):
|
|
314
|
+
if not v:
|
|
315
|
+
return None
|
|
316
|
+
v = v.lower() in cls._bool_true_values
|
|
317
|
+
return 't' if v else 'f'
|
|
318
|
+
|
|
319
|
+
@classmethod
|
|
320
|
+
def _adapt_date(cls, v: Any) -> Any:
|
|
321
|
+
"""Adapt a date parameter."""
|
|
322
|
+
if not v:
|
|
323
|
+
return None
|
|
324
|
+
if isinstance(v, str) and v.lower() in cls._date_literals:
|
|
325
|
+
return Literal(v)
|
|
326
|
+
return v
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def _adapt_num(v: Any) -> Any:
|
|
330
|
+
"""Adapt a numeric parameter."""
|
|
331
|
+
if not v and v != 0:
|
|
332
|
+
return None
|
|
333
|
+
return v
|
|
334
|
+
|
|
335
|
+
_adapt_int = _adapt_float = _adapt_money = _adapt_num
|
|
336
|
+
|
|
337
|
+
def _adapt_bytea(self, v: Any) -> str:
|
|
338
|
+
"""Adapt a bytea parameter."""
|
|
339
|
+
return self.db.escape_bytea(v)
|
|
340
|
+
|
|
341
|
+
def _adapt_json(self, v: Any) -> str | None:
|
|
342
|
+
"""Adapt a json parameter."""
|
|
343
|
+
if v is None:
|
|
344
|
+
return None
|
|
345
|
+
if isinstance(v, str):
|
|
346
|
+
return v
|
|
347
|
+
if isinstance(v, Json):
|
|
348
|
+
return str(v)
|
|
349
|
+
return self.db.encode_json(v)
|
|
350
|
+
|
|
351
|
+
def _adapt_hstore(self, v: Any) -> str | None:
|
|
352
|
+
"""Adapt a hstore parameter."""
|
|
353
|
+
if not v:
|
|
354
|
+
return None
|
|
355
|
+
if isinstance(v, str):
|
|
356
|
+
return v
|
|
357
|
+
if isinstance(v, Hstore):
|
|
358
|
+
return str(v)
|
|
359
|
+
if isinstance(v, dict):
|
|
360
|
+
return str(Hstore(v))
|
|
361
|
+
raise TypeError(f'Hstore parameter {v} has wrong type')
|
|
362
|
+
|
|
363
|
+
def _adapt_uuid(self, v: Any) -> str | None:
|
|
364
|
+
"""Adapt a UUID parameter."""
|
|
365
|
+
if not v:
|
|
366
|
+
return None
|
|
367
|
+
if isinstance(v, str):
|
|
368
|
+
return v
|
|
369
|
+
return str(v)
|
|
370
|
+
|
|
371
|
+
@classmethod
|
|
372
|
+
def _adapt_text_array(cls, v: Any) -> str:
|
|
373
|
+
"""Adapt a text type array parameter."""
|
|
374
|
+
if isinstance(v, list):
|
|
375
|
+
adapt = cls._adapt_text_array
|
|
376
|
+
return '{' + ','.join(adapt(v) for v in v) + '}'
|
|
377
|
+
if v is None:
|
|
378
|
+
return 'null'
|
|
379
|
+
if not v:
|
|
380
|
+
return '""'
|
|
381
|
+
v = str(v)
|
|
382
|
+
if cls._re_array_quote.search(v):
|
|
383
|
+
v = cls._re_array_escape.sub(r'\\\1', v)
|
|
384
|
+
v = f'"{v}"'
|
|
385
|
+
return v
|
|
386
|
+
|
|
387
|
+
_adapt_date_array = _adapt_text_array
|
|
388
|
+
|
|
389
|
+
@classmethod
|
|
390
|
+
def _adapt_bool_array(cls, v: Any) -> str:
|
|
391
|
+
"""Adapt a boolean array parameter."""
|
|
392
|
+
if isinstance(v, list):
|
|
393
|
+
adapt = cls._adapt_bool_array
|
|
394
|
+
return '{' + ','.join(adapt(v) for v in v) + '}'
|
|
395
|
+
if v is None:
|
|
396
|
+
return 'null'
|
|
397
|
+
if isinstance(v, str):
|
|
398
|
+
if not v:
|
|
399
|
+
return 'null'
|
|
400
|
+
v = v.lower() in cls._bool_true_values
|
|
401
|
+
return 't' if v else 'f'
|
|
402
|
+
|
|
403
|
+
@classmethod
|
|
404
|
+
def _adapt_num_array(cls, v: Any) -> str:
|
|
405
|
+
"""Adapt a numeric array parameter."""
|
|
406
|
+
if isinstance(v, list):
|
|
407
|
+
adapt = cls._adapt_num_array
|
|
408
|
+
v = '{' + ','.join(adapt(v) for v in v) + '}'
|
|
409
|
+
if not v and v != 0:
|
|
410
|
+
return 'null'
|
|
411
|
+
return str(v)
|
|
412
|
+
|
|
413
|
+
_adapt_int_array = _adapt_float_array = _adapt_money_array = \
|
|
414
|
+
_adapt_num_array
|
|
415
|
+
|
|
416
|
+
def _adapt_bytea_array(self, v: Any) -> bytes:
|
|
417
|
+
"""Adapt a bytea array parameter."""
|
|
418
|
+
if isinstance(v, list):
|
|
419
|
+
return b'{' + b','.join(
|
|
420
|
+
self._adapt_bytea_array(v) for v in v) + b'}'
|
|
421
|
+
if v is None:
|
|
422
|
+
return b'null'
|
|
423
|
+
return self.db.escape_bytea(v).replace(b'\\', b'\\\\')
|
|
424
|
+
|
|
425
|
+
def _adapt_json_array(self, v: Any) -> str:
|
|
426
|
+
"""Adapt a json array parameter."""
|
|
427
|
+
if isinstance(v, list):
|
|
428
|
+
adapt = self._adapt_json_array
|
|
429
|
+
return '{' + ','.join(adapt(v) for v in v) + '}'
|
|
430
|
+
if not v:
|
|
431
|
+
return 'null'
|
|
432
|
+
if not isinstance(v, str):
|
|
433
|
+
v = self.db.encode_json(v)
|
|
434
|
+
if self._re_array_quote.search(v):
|
|
435
|
+
v = self._re_array_escape.sub(r'\\\1', v)
|
|
436
|
+
v = f'"{v}"'
|
|
437
|
+
return v
|
|
438
|
+
|
|
439
|
+
def _adapt_record(self, v: Any, typ: Any) -> str:
|
|
440
|
+
"""Adapt a record parameter with given type."""
|
|
441
|
+
typ = self.get_attnames(typ).values()
|
|
442
|
+
if len(typ) != len(v):
|
|
443
|
+
raise TypeError(f'Record parameter {v} has wrong size')
|
|
444
|
+
adapt = self.adapt
|
|
445
|
+
value = []
|
|
446
|
+
for v, t in zip(v, typ): # noqa: B020
|
|
447
|
+
v = adapt(v, t)
|
|
448
|
+
if v is None:
|
|
449
|
+
v = ''
|
|
450
|
+
else:
|
|
451
|
+
if isinstance(v, bytes):
|
|
452
|
+
v = v.decode('ascii')
|
|
453
|
+
elif not isinstance(v, str):
|
|
454
|
+
v = str(v)
|
|
455
|
+
if v:
|
|
456
|
+
if self._re_record_quote.search(v):
|
|
457
|
+
v = self._re_record_escape.sub(r'\\\1', v)
|
|
458
|
+
v = f'"{v}"'
|
|
459
|
+
else:
|
|
460
|
+
v = '""'
|
|
461
|
+
value.append(v)
|
|
462
|
+
v = ','.join(value)
|
|
463
|
+
return f'({v})'
|
|
464
|
+
|
|
465
|
+
def adapt(self, value: Any, typ: Any = None) -> str:
|
|
466
|
+
"""Adapt a value with known database type."""
|
|
467
|
+
if value is not None and not isinstance(value, Literal):
|
|
468
|
+
if typ:
|
|
469
|
+
simple = self.get_simple_name(typ)
|
|
470
|
+
else:
|
|
471
|
+
typ = simple = self.guess_simple_type(value) or 'text'
|
|
472
|
+
pg_str = getattr(value, '__pg_str__', None)
|
|
473
|
+
if pg_str:
|
|
474
|
+
value = pg_str(typ)
|
|
475
|
+
if simple == 'text':
|
|
476
|
+
pass
|
|
477
|
+
elif simple == 'record':
|
|
478
|
+
if isinstance(value, tuple):
|
|
479
|
+
value = self._adapt_record(value, typ)
|
|
480
|
+
elif simple.endswith('[]'):
|
|
481
|
+
if isinstance(value, list):
|
|
482
|
+
adapt = getattr(self, f'_adapt_{simple[:-2]}_array')
|
|
483
|
+
value = adapt(value)
|
|
484
|
+
else:
|
|
485
|
+
adapt = getattr(self, f'_adapt_{simple}')
|
|
486
|
+
value = adapt(value)
|
|
487
|
+
return value
|
|
488
|
+
|
|
489
|
+
@staticmethod
|
|
490
|
+
def simple_type(name: str) -> DbType:
|
|
491
|
+
"""Create a simple database type with given attribute names."""
|
|
492
|
+
typ = DbType(name)
|
|
493
|
+
typ.simple = name
|
|
494
|
+
return typ
|
|
495
|
+
|
|
496
|
+
@staticmethod
|
|
497
|
+
def get_simple_name(typ: Any) -> str:
|
|
498
|
+
"""Get the simple name of a database type."""
|
|
499
|
+
if isinstance(typ, DbType):
|
|
500
|
+
# noinspection PyUnresolvedReferences
|
|
501
|
+
return typ.simple
|
|
502
|
+
return _simpletypes[typ]
|
|
503
|
+
|
|
504
|
+
@staticmethod
|
|
505
|
+
def get_attnames(typ: Any) -> dict[str, dict[str, str]]:
|
|
506
|
+
"""Get the attribute names of a composite database type."""
|
|
507
|
+
if isinstance(typ, DbType):
|
|
508
|
+
return typ.attnames
|
|
509
|
+
return {}
|
|
510
|
+
|
|
511
|
+
@classmethod
|
|
512
|
+
def guess_simple_type(cls, value: Any) -> str | None:
|
|
513
|
+
"""Try to guess which database type the given value has."""
|
|
514
|
+
# optimize for most frequent types
|
|
515
|
+
try:
|
|
516
|
+
return _simple_type_dict[type(value)]
|
|
517
|
+
except KeyError:
|
|
518
|
+
pass
|
|
519
|
+
if isinstance(value, (bytes, str)):
|
|
520
|
+
return 'text'
|
|
521
|
+
if isinstance(value, bool):
|
|
522
|
+
return 'bool'
|
|
523
|
+
if isinstance(value, int):
|
|
524
|
+
return 'int'
|
|
525
|
+
if isinstance(value, float):
|
|
526
|
+
return 'float'
|
|
527
|
+
if isinstance(value, Decimal):
|
|
528
|
+
return 'num'
|
|
529
|
+
if isinstance(value, (date, time, datetime, timedelta)):
|
|
530
|
+
return 'date'
|
|
531
|
+
if isinstance(value, Bytea):
|
|
532
|
+
return 'bytea'
|
|
533
|
+
if isinstance(value, Json):
|
|
534
|
+
return 'json'
|
|
535
|
+
if isinstance(value, Hstore):
|
|
536
|
+
return 'hstore'
|
|
537
|
+
if isinstance(value, UUID):
|
|
538
|
+
return 'uuid'
|
|
539
|
+
if isinstance(value, list):
|
|
540
|
+
return (cls.guess_simple_base_type(value) or 'text') + '[]'
|
|
541
|
+
if isinstance(value, tuple):
|
|
542
|
+
simple_type = cls.simple_type
|
|
543
|
+
guess = cls.guess_simple_type
|
|
544
|
+
|
|
545
|
+
# noinspection PyUnusedLocal
|
|
546
|
+
def get_attnames(self: DbType) -> AttrDict:
|
|
547
|
+
return AttrDict((str(n + 1), simple_type(guess(v) or 'text'))
|
|
548
|
+
for n, v in enumerate(value))
|
|
549
|
+
|
|
550
|
+
typ = simple_type('record')
|
|
551
|
+
typ._get_attnames = get_attnames
|
|
552
|
+
return typ
|
|
553
|
+
return None
|
|
554
|
+
|
|
555
|
+
@classmethod
|
|
556
|
+
def guess_simple_base_type(cls, value: Any) -> str | None:
|
|
557
|
+
"""Try to guess the base type of a given array."""
|
|
558
|
+
for v in value:
|
|
559
|
+
if isinstance(v, list):
|
|
560
|
+
typ = cls.guess_simple_base_type(v)
|
|
561
|
+
else:
|
|
562
|
+
typ = cls.guess_simple_type(v)
|
|
563
|
+
if typ:
|
|
564
|
+
return typ
|
|
565
|
+
return None
|
|
566
|
+
|
|
567
|
+
def adapt_inline(self, value: Any, nested: bool=False) -> Any:
|
|
568
|
+
"""Adapt a value that is put into the SQL and needs to be quoted."""
|
|
569
|
+
if value is None:
|
|
570
|
+
return 'NULL'
|
|
571
|
+
if isinstance(value, Literal):
|
|
572
|
+
return value
|
|
573
|
+
if isinstance(value, Bytea):
|
|
574
|
+
value = self.db.escape_bytea(value).decode('ascii')
|
|
575
|
+
elif isinstance(value, (datetime, date, time, timedelta)):
|
|
576
|
+
value = str(value)
|
|
577
|
+
if isinstance(value, (bytes, str)):
|
|
578
|
+
value = self.db.escape_string(value)
|
|
579
|
+
return f"'{value}'"
|
|
580
|
+
if isinstance(value, bool):
|
|
581
|
+
return 'true' if value else 'false'
|
|
582
|
+
if isinstance(value, float):
|
|
583
|
+
if isinf(value):
|
|
584
|
+
return "'-Infinity'" if value < 0 else "'Infinity'"
|
|
585
|
+
if isnan(value):
|
|
586
|
+
return "'NaN'"
|
|
587
|
+
return value
|
|
588
|
+
if isinstance(value, (int, Decimal)):
|
|
589
|
+
return value
|
|
590
|
+
if isinstance(value, list):
|
|
591
|
+
q = self.adapt_inline
|
|
592
|
+
s = '[{}]' if nested else 'ARRAY[{}]'
|
|
593
|
+
return s.format(','.join(str(q(v, nested=True)) for v in value))
|
|
594
|
+
if isinstance(value, tuple):
|
|
595
|
+
q = self.adapt_inline
|
|
596
|
+
return '({})'.format(','.join(str(q(v)) for v in value))
|
|
597
|
+
if isinstance(value, Json):
|
|
598
|
+
value = self.db.escape_string(str(value))
|
|
599
|
+
return f"'{value}'::json"
|
|
600
|
+
if isinstance(value, Hstore):
|
|
601
|
+
value = self.db.escape_string(str(value))
|
|
602
|
+
return f"'{value}'::hstore"
|
|
603
|
+
pg_repr = getattr(value, '__pg_repr__', None)
|
|
604
|
+
if not pg_repr:
|
|
605
|
+
raise InterfaceError(
|
|
606
|
+
f'Do not know how to adapt type {type(value)}')
|
|
607
|
+
value = pg_repr()
|
|
608
|
+
if isinstance(value, (tuple, list)):
|
|
609
|
+
value = self.adapt_inline(value)
|
|
610
|
+
return value
|
|
611
|
+
|
|
612
|
+
def parameter_list(self) -> _ParameterList:
|
|
613
|
+
"""Return a parameter list for parameters with known database types.
|
|
614
|
+
|
|
615
|
+
The list has an add(value, typ) method that will build up the
|
|
616
|
+
list and return either the literal value or a placeholder.
|
|
617
|
+
"""
|
|
618
|
+
params = _ParameterList()
|
|
619
|
+
params.adapt = self.adapt
|
|
620
|
+
return params
|
|
621
|
+
|
|
622
|
+
def format_query(self, command: str,
|
|
623
|
+
values: list | tuple | dict | None = None,
|
|
624
|
+
types: list | tuple | dict | None = None,
|
|
625
|
+
inline: bool=False
|
|
626
|
+
) -> tuple[str, _ParameterList]:
|
|
627
|
+
"""Format a database query using the given values and types.
|
|
628
|
+
|
|
629
|
+
The optional types describe the values and must be passed as a list,
|
|
630
|
+
tuple or string (that will be split on whitespace) when values are
|
|
631
|
+
passed as a list or tuple, or as a dict if values are passed as a dict.
|
|
632
|
+
|
|
633
|
+
If inline is set to True, then parameters will be passed inline
|
|
634
|
+
together with the query string.
|
|
635
|
+
"""
|
|
636
|
+
params = self.parameter_list()
|
|
637
|
+
if not values:
|
|
638
|
+
return command, params
|
|
639
|
+
if inline and types:
|
|
640
|
+
raise ValueError('Typed parameters must be sent separately')
|
|
641
|
+
if isinstance(values, (list, tuple)):
|
|
642
|
+
if inline:
|
|
643
|
+
adapt = self.adapt_inline
|
|
644
|
+
seq_literals = [adapt(value) for value in values]
|
|
645
|
+
else:
|
|
646
|
+
add = params.add
|
|
647
|
+
if types:
|
|
648
|
+
if isinstance(types, str):
|
|
649
|
+
types = types.split()
|
|
650
|
+
if (not isinstance(types, (list, tuple))
|
|
651
|
+
or len(types) != len(values)):
|
|
652
|
+
raise TypeError('The values and types do not match')
|
|
653
|
+
seq_literals = [add(value, typ)
|
|
654
|
+
for value, typ in zip(values, types)]
|
|
655
|
+
else:
|
|
656
|
+
seq_literals = [add(value) for value in values]
|
|
657
|
+
command %= tuple(seq_literals)
|
|
658
|
+
elif isinstance(values, dict):
|
|
659
|
+
# we want to allow extra keys in the dictionary,
|
|
660
|
+
# so we first must find the values actually used in the command
|
|
661
|
+
used_values = {}
|
|
662
|
+
map_literals = dict.fromkeys(values, '')
|
|
663
|
+
for key in values:
|
|
664
|
+
del map_literals[key]
|
|
665
|
+
try:
|
|
666
|
+
command % map_literals
|
|
667
|
+
except KeyError:
|
|
668
|
+
used_values[key] = values[key] # pyright: ignore
|
|
669
|
+
map_literals[key] = ''
|
|
670
|
+
if inline:
|
|
671
|
+
adapt = self.adapt_inline
|
|
672
|
+
map_literals = {key: adapt(value)
|
|
673
|
+
for key, value in used_values.items()}
|
|
674
|
+
else:
|
|
675
|
+
add = params.add
|
|
676
|
+
if types:
|
|
677
|
+
if not isinstance(types, dict):
|
|
678
|
+
raise TypeError('The values and types do not match')
|
|
679
|
+
map_literals = {key: add(used_values[key], types.get(key))
|
|
680
|
+
for key in sorted(used_values)}
|
|
681
|
+
else:
|
|
682
|
+
map_literals = {key: add(used_values[key])
|
|
683
|
+
for key in sorted(used_values)}
|
|
684
|
+
command %= map_literals
|
|
685
|
+
else:
|
|
686
|
+
raise TypeError('The values must be passed as tuple, list or dict')
|
|
687
|
+
return command, params
|