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/db.py
ADDED
|
@@ -0,0 +1,1506 @@
|
|
|
1
|
+
"""Connection wrapper."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import suppress
|
|
6
|
+
from json import dumps as jsonencode
|
|
7
|
+
from json import loads as jsondecode
|
|
8
|
+
from operator import itemgetter
|
|
9
|
+
from typing import (
|
|
10
|
+
TYPE_CHECKING,
|
|
11
|
+
Any,
|
|
12
|
+
Callable,
|
|
13
|
+
Iterator,
|
|
14
|
+
Sequence,
|
|
15
|
+
TypeVar,
|
|
16
|
+
overload,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from . import Connection, connect
|
|
20
|
+
from .adapt import Adapter, DbTypes
|
|
21
|
+
from .attrs import AttrDict
|
|
22
|
+
from .core import (
|
|
23
|
+
InternalError,
|
|
24
|
+
LargeObject,
|
|
25
|
+
ProgrammingError,
|
|
26
|
+
Query,
|
|
27
|
+
get_bool,
|
|
28
|
+
get_jsondecode,
|
|
29
|
+
unescape_bytea,
|
|
30
|
+
)
|
|
31
|
+
from .error import db_error, int_error, prg_error
|
|
32
|
+
from .helpers import namediter, oid_key, quote_if_unqualified
|
|
33
|
+
from .notify import NotificationHandler
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from pgdb.connection import Connection as DbApi2Connection
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
AnyStr = TypeVar('AnyStr', str, bytes, str | bytes)
|
|
40
|
+
except TypeError: # Python < 3.10
|
|
41
|
+
AnyStr = Any # type: ignore
|
|
42
|
+
|
|
43
|
+
__all__ = ['DB']
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# The actual PostgreSQL database connection interface:
|
|
47
|
+
|
|
48
|
+
class DB:
|
|
49
|
+
"""Wrapper class for the core connection type."""
|
|
50
|
+
|
|
51
|
+
dbname: str
|
|
52
|
+
host: str
|
|
53
|
+
port: int
|
|
54
|
+
options: str
|
|
55
|
+
error: str
|
|
56
|
+
status: int
|
|
57
|
+
user : str
|
|
58
|
+
protocol_version: int
|
|
59
|
+
server_version: int
|
|
60
|
+
socket: int
|
|
61
|
+
backend_pid: int
|
|
62
|
+
ssl_in_use: bool
|
|
63
|
+
ssl_attributes: dict[str, str | None]
|
|
64
|
+
|
|
65
|
+
db: Connection | None = None # invalid fallback for underlying connection
|
|
66
|
+
_db_args: Any # either the connect args or the underlying connection
|
|
67
|
+
|
|
68
|
+
@overload
|
|
69
|
+
def __init__(self, dbname: str | None = None,
|
|
70
|
+
host: str | None = None, port: int = -1,
|
|
71
|
+
opt: str | None = None,
|
|
72
|
+
user: str | None = None, passwd: str | None = None,
|
|
73
|
+
nowait: bool = False) -> None:
|
|
74
|
+
... # create a new connection using the specified parameters
|
|
75
|
+
|
|
76
|
+
@overload
|
|
77
|
+
def __init__(self, db: Connection | DB | DbApi2Connection) -> None:
|
|
78
|
+
... # create a connection wrapper based on an existing connection
|
|
79
|
+
|
|
80
|
+
def __init__(self, *args: Any, **kw: Any) -> None:
|
|
81
|
+
"""Create a new connection.
|
|
82
|
+
|
|
83
|
+
You can pass either the connection parameters or an existing
|
|
84
|
+
pg or pgdb Connection. This allows you to use the methods
|
|
85
|
+
of the classic pg interface with a DB-API 2 pgdb Connection.
|
|
86
|
+
"""
|
|
87
|
+
if kw:
|
|
88
|
+
db = kw.get('db')
|
|
89
|
+
if db is not None and (args or len(kw) > 1):
|
|
90
|
+
raise TypeError("Conflicting connection parameters")
|
|
91
|
+
elif len(args) == 1 and not isinstance(args[0], str):
|
|
92
|
+
db = args[0]
|
|
93
|
+
else:
|
|
94
|
+
db = None
|
|
95
|
+
if db:
|
|
96
|
+
if isinstance(db, DB):
|
|
97
|
+
db = db.db # allow db to be a wrapped Connection
|
|
98
|
+
else:
|
|
99
|
+
with suppress(AttributeError):
|
|
100
|
+
db = db._cnx # allow db to be a pgdb Connection
|
|
101
|
+
if not isinstance(db, Connection):
|
|
102
|
+
raise TypeError(
|
|
103
|
+
"The 'db' argument must be a valid database connection.")
|
|
104
|
+
self._db_args = db
|
|
105
|
+
self._closeable = False
|
|
106
|
+
else:
|
|
107
|
+
db = connect(*args, **kw)
|
|
108
|
+
self._db_args = args, kw
|
|
109
|
+
self._closeable = True
|
|
110
|
+
self.db = db
|
|
111
|
+
self.dbname = db.db
|
|
112
|
+
self._regtypes = False
|
|
113
|
+
self._attnames: dict[str, AttrDict] = {}
|
|
114
|
+
self._generated: dict[str, frozenset[str]] = {}
|
|
115
|
+
self._pkeys: dict[str, str | tuple[str, ...]] = {}
|
|
116
|
+
self._privileges: dict[tuple[str, str], bool] = {}
|
|
117
|
+
self.adapter = Adapter(self)
|
|
118
|
+
self.dbtypes = DbTypes(self)
|
|
119
|
+
self._query_attnames = (
|
|
120
|
+
"SELECT a.attname,"
|
|
121
|
+
" t.oid, t.typname, t.oid::pg_catalog.regtype,"
|
|
122
|
+
" t.typlen, t.typtype, t.typcategory, t.typdelim, t.typrelid"
|
|
123
|
+
" FROM pg_catalog.pg_attribute a"
|
|
124
|
+
" JOIN pg_catalog.pg_type t"
|
|
125
|
+
" ON t.oid OPERATOR(pg_catalog.=) a.atttypid"
|
|
126
|
+
" WHERE a.attrelid OPERATOR(pg_catalog.=)"
|
|
127
|
+
" {}::pg_catalog.regclass"
|
|
128
|
+
" AND {} AND NOT a.attisdropped ORDER BY a.attnum")
|
|
129
|
+
if db.server_version < 120000:
|
|
130
|
+
self._query_generated = (
|
|
131
|
+
"a.attidentity OPERATOR(pg_catalog.=) 'a'"
|
|
132
|
+
)
|
|
133
|
+
else:
|
|
134
|
+
self._query_generated = (
|
|
135
|
+
"(a.attidentity OPERATOR(pg_catalog.=) 'a' OR"
|
|
136
|
+
" a.attgenerated OPERATOR(pg_catalog.!=) '')"
|
|
137
|
+
)
|
|
138
|
+
db.set_cast_hook(self.dbtypes.typecast)
|
|
139
|
+
# For debugging scripts, self.debug can be set
|
|
140
|
+
# * to a string format specification (e.g. in CGI set to "%s<BR>"),
|
|
141
|
+
# * to a file object to write debug statements or
|
|
142
|
+
# * to a callable object which takes a string argument
|
|
143
|
+
# * to any other true value to just print debug statements
|
|
144
|
+
self.debug: Any = None
|
|
145
|
+
|
|
146
|
+
def __getattr__(self, name: str) -> Any:
|
|
147
|
+
"""Get the specified attribute of the connection."""
|
|
148
|
+
# All undefined members are same as in underlying connection:
|
|
149
|
+
if self.db:
|
|
150
|
+
return getattr(self.db, name)
|
|
151
|
+
else:
|
|
152
|
+
raise int_error('Connection is not valid')
|
|
153
|
+
|
|
154
|
+
def __dir__(self) -> list[str]:
|
|
155
|
+
"""List all attributes of the connection."""
|
|
156
|
+
# Custom dir function including the attributes of the connection:
|
|
157
|
+
attrs = set(self.__class__.__dict__)
|
|
158
|
+
attrs.update(self.__dict__)
|
|
159
|
+
attrs.update(dir(self.db))
|
|
160
|
+
return sorted(attrs)
|
|
161
|
+
|
|
162
|
+
# Context manager methods
|
|
163
|
+
|
|
164
|
+
def __enter__(self) -> DB:
|
|
165
|
+
"""Enter the runtime context. This will start a transaction."""
|
|
166
|
+
self.begin()
|
|
167
|
+
return self
|
|
168
|
+
|
|
169
|
+
def __exit__(self, et: type[BaseException] | None,
|
|
170
|
+
ev: BaseException | None, tb: Any) -> None:
|
|
171
|
+
"""Exit the runtime context. This will end the transaction."""
|
|
172
|
+
if et is None and ev is None and tb is None:
|
|
173
|
+
self.commit()
|
|
174
|
+
else:
|
|
175
|
+
self.rollback()
|
|
176
|
+
|
|
177
|
+
def __del__(self) -> None:
|
|
178
|
+
"""Delete the connection."""
|
|
179
|
+
try:
|
|
180
|
+
db = self.db
|
|
181
|
+
except AttributeError:
|
|
182
|
+
db = None
|
|
183
|
+
if db:
|
|
184
|
+
with suppress(TypeError): # when already closed
|
|
185
|
+
db.set_cast_hook(None)
|
|
186
|
+
if self._closeable:
|
|
187
|
+
with suppress(InternalError): # when already closed
|
|
188
|
+
db.close()
|
|
189
|
+
|
|
190
|
+
# Auxiliary methods
|
|
191
|
+
|
|
192
|
+
def _do_debug(self, *args: Any) -> None:
|
|
193
|
+
"""Print a debug message."""
|
|
194
|
+
if self.debug:
|
|
195
|
+
s = '\n'.join(str(arg) for arg in args)
|
|
196
|
+
if isinstance(self.debug, str):
|
|
197
|
+
print(self.debug % s)
|
|
198
|
+
elif hasattr(self.debug, 'write'):
|
|
199
|
+
# noinspection PyCallingNonCallable
|
|
200
|
+
self.debug.write(s + '\n')
|
|
201
|
+
elif callable(self.debug):
|
|
202
|
+
self.debug(s)
|
|
203
|
+
else:
|
|
204
|
+
print(s)
|
|
205
|
+
|
|
206
|
+
def _escape_qualified_name(self, s: str) -> str:
|
|
207
|
+
"""Escape a qualified name.
|
|
208
|
+
|
|
209
|
+
Escapes the name for use as an SQL identifier, unless the
|
|
210
|
+
name contains a dot, in which case the name is ambiguous
|
|
211
|
+
(could be a qualified name or just a name with a dot in it)
|
|
212
|
+
and must be quoted manually by the caller.
|
|
213
|
+
"""
|
|
214
|
+
if '.' not in s:
|
|
215
|
+
s = self.escape_identifier(s)
|
|
216
|
+
return s
|
|
217
|
+
|
|
218
|
+
@staticmethod
|
|
219
|
+
def _make_bool(d: Any) -> bool | str:
|
|
220
|
+
"""Get boolean value corresponding to d."""
|
|
221
|
+
return bool(d) if get_bool() else ('t' if d else 'f')
|
|
222
|
+
|
|
223
|
+
@staticmethod
|
|
224
|
+
def _list_params(params: Sequence) -> str:
|
|
225
|
+
"""Create a human readable parameter list."""
|
|
226
|
+
return ', '.join(f'${n}={v!r}' for n, v in enumerate(params, 1))
|
|
227
|
+
|
|
228
|
+
@property
|
|
229
|
+
def _valid_db(self) -> Connection:
|
|
230
|
+
"""Get underlying connection and make sure it is not closed."""
|
|
231
|
+
db = self.db
|
|
232
|
+
if not db:
|
|
233
|
+
raise int_error('Connection already closed')
|
|
234
|
+
return db
|
|
235
|
+
|
|
236
|
+
# Public methods
|
|
237
|
+
|
|
238
|
+
# escape_string and escape_bytea exist as methods,
|
|
239
|
+
# so we define unescape_bytea as a method as well
|
|
240
|
+
unescape_bytea = staticmethod(unescape_bytea)
|
|
241
|
+
|
|
242
|
+
@staticmethod
|
|
243
|
+
def decode_json(s: str) -> Any:
|
|
244
|
+
"""Decode a JSON string coming from the database."""
|
|
245
|
+
return (get_jsondecode() or jsondecode)(s)
|
|
246
|
+
|
|
247
|
+
@staticmethod
|
|
248
|
+
def encode_json(d: Any) -> str:
|
|
249
|
+
"""Encode a JSON string for use within SQL."""
|
|
250
|
+
return jsonencode(d)
|
|
251
|
+
|
|
252
|
+
def close(self) -> None:
|
|
253
|
+
"""Close the database connection."""
|
|
254
|
+
# Wraps shared library function so we can track state.
|
|
255
|
+
db = self._valid_db
|
|
256
|
+
with suppress(TypeError): # when already closed
|
|
257
|
+
db.set_cast_hook(None)
|
|
258
|
+
if self._closeable:
|
|
259
|
+
db.close()
|
|
260
|
+
self.db = None
|
|
261
|
+
|
|
262
|
+
def reset(self) -> None:
|
|
263
|
+
"""Reset connection with current parameters.
|
|
264
|
+
|
|
265
|
+
All derived queries and large objects derived from this connection
|
|
266
|
+
will not be usable after this call.
|
|
267
|
+
"""
|
|
268
|
+
self._valid_db.reset()
|
|
269
|
+
|
|
270
|
+
def reopen(self) -> None:
|
|
271
|
+
"""Reopen connection to the database.
|
|
272
|
+
|
|
273
|
+
Used in case we need another connection to the same database.
|
|
274
|
+
Note that we can still reopen a database that we have closed.
|
|
275
|
+
"""
|
|
276
|
+
# There is no such shared library function.
|
|
277
|
+
if self._closeable:
|
|
278
|
+
args, kw = self._db_args
|
|
279
|
+
db = connect(*args, **kw)
|
|
280
|
+
if self.db:
|
|
281
|
+
self.db.set_cast_hook(None)
|
|
282
|
+
self.db.close()
|
|
283
|
+
db.set_cast_hook(self.dbtypes.typecast)
|
|
284
|
+
self.db = db
|
|
285
|
+
else:
|
|
286
|
+
self.db = self._db_args
|
|
287
|
+
|
|
288
|
+
def begin(self, mode: str | None = None) -> Query:
|
|
289
|
+
"""Begin a transaction."""
|
|
290
|
+
qstr = 'BEGIN'
|
|
291
|
+
if mode:
|
|
292
|
+
qstr += ' ' + mode
|
|
293
|
+
return self.query(qstr)
|
|
294
|
+
|
|
295
|
+
start = begin
|
|
296
|
+
|
|
297
|
+
def commit(self) -> Query:
|
|
298
|
+
"""Commit the current transaction."""
|
|
299
|
+
return self.query('COMMIT')
|
|
300
|
+
|
|
301
|
+
end = commit
|
|
302
|
+
|
|
303
|
+
def rollback(self, name: str | None = None) -> Query:
|
|
304
|
+
"""Roll back the current transaction."""
|
|
305
|
+
qstr = 'ROLLBACK'
|
|
306
|
+
if name:
|
|
307
|
+
qstr += ' TO ' + name
|
|
308
|
+
return self.query(qstr)
|
|
309
|
+
|
|
310
|
+
abort = rollback
|
|
311
|
+
|
|
312
|
+
def savepoint(self, name: str) -> Query:
|
|
313
|
+
"""Define a new savepoint within the current transaction."""
|
|
314
|
+
return self.query('SAVEPOINT ' + name)
|
|
315
|
+
|
|
316
|
+
def release(self, name: str) -> Query:
|
|
317
|
+
"""Destroy a previously defined savepoint."""
|
|
318
|
+
return self.query('RELEASE ' + name)
|
|
319
|
+
|
|
320
|
+
def get_parameter(self,
|
|
321
|
+
parameter: str | list[str] | tuple[str, ...] |
|
|
322
|
+
set[str] | frozenset[str] | dict[str, Any]
|
|
323
|
+
) -> str | list[str] | dict[str, str]:
|
|
324
|
+
"""Get the value of a run-time parameter.
|
|
325
|
+
|
|
326
|
+
If the parameter is a string, the return value will also be a string
|
|
327
|
+
that is the current setting of the run-time parameter with that name.
|
|
328
|
+
|
|
329
|
+
You can get several parameters at once by passing a list, set or dict.
|
|
330
|
+
When passing a list of parameter names, the return value will be a
|
|
331
|
+
corresponding list of parameter settings. When passing a set of
|
|
332
|
+
parameter names, a new dict will be returned, mapping these parameter
|
|
333
|
+
names to their settings. Finally, if you pass a dict as parameter,
|
|
334
|
+
its values will be set to the current parameter settings corresponding
|
|
335
|
+
to its keys.
|
|
336
|
+
|
|
337
|
+
By passing the special name 'all' as the parameter, you can get a dict
|
|
338
|
+
of all existing configuration parameters.
|
|
339
|
+
"""
|
|
340
|
+
values: Any
|
|
341
|
+
if isinstance(parameter, str):
|
|
342
|
+
parameter = [parameter]
|
|
343
|
+
values = None
|
|
344
|
+
elif isinstance(parameter, (list, tuple)):
|
|
345
|
+
values = []
|
|
346
|
+
elif isinstance(parameter, (set, frozenset)):
|
|
347
|
+
values = {}
|
|
348
|
+
elif isinstance(parameter, dict):
|
|
349
|
+
values = parameter
|
|
350
|
+
else:
|
|
351
|
+
raise TypeError(
|
|
352
|
+
'The parameter must be a string, list, set or dict')
|
|
353
|
+
if not parameter:
|
|
354
|
+
raise TypeError('No parameter has been specified')
|
|
355
|
+
query = self._valid_db.query
|
|
356
|
+
params: Any = {} if isinstance(values, dict) else []
|
|
357
|
+
for param_key in parameter:
|
|
358
|
+
param = param_key.strip().lower() if isinstance(
|
|
359
|
+
param_key, (bytes, str)) else None
|
|
360
|
+
if not param:
|
|
361
|
+
raise TypeError('Invalid parameter')
|
|
362
|
+
if param == 'all':
|
|
363
|
+
cmd = 'SHOW ALL'
|
|
364
|
+
values = query(cmd).getresult()
|
|
365
|
+
values = {value[0]: value[1] for value in values}
|
|
366
|
+
break
|
|
367
|
+
if isinstance(params, dict):
|
|
368
|
+
params[param] = param_key
|
|
369
|
+
else:
|
|
370
|
+
params.append(param)
|
|
371
|
+
else:
|
|
372
|
+
for param in params:
|
|
373
|
+
cmd = f'SHOW {param}'
|
|
374
|
+
value = query(cmd).singlescalar()
|
|
375
|
+
if values is None:
|
|
376
|
+
values = value
|
|
377
|
+
elif isinstance(values, list):
|
|
378
|
+
values.append(value)
|
|
379
|
+
else:
|
|
380
|
+
values[params[param]] = value
|
|
381
|
+
return values
|
|
382
|
+
|
|
383
|
+
def set_parameter(self,
|
|
384
|
+
parameter: str | list[str] | tuple[str, ...] |
|
|
385
|
+
set[str] | frozenset[str] | dict[str, Any],
|
|
386
|
+
value: str | list[str] | tuple[str, ...] |
|
|
387
|
+
set[str] | frozenset[str]| None = None,
|
|
388
|
+
local: bool = False) -> None:
|
|
389
|
+
"""Set the value of a run-time parameter.
|
|
390
|
+
|
|
391
|
+
If the parameter and the value are strings, the run-time parameter
|
|
392
|
+
will be set to that value. If no value or None is passed as a value,
|
|
393
|
+
then the run-time parameter will be restored to its default value.
|
|
394
|
+
|
|
395
|
+
You can set several parameters at once by passing a list of parameter
|
|
396
|
+
names, together with a single value that all parameters should be
|
|
397
|
+
set to or with a corresponding list of values. You can also pass
|
|
398
|
+
the parameters as a set if you only provide a single value.
|
|
399
|
+
Finally, you can pass a dict with parameter names as keys. In this
|
|
400
|
+
case, you should not pass a value, since the values for the parameters
|
|
401
|
+
will be taken from the dict.
|
|
402
|
+
|
|
403
|
+
By passing the special name 'all' as the parameter, you can reset
|
|
404
|
+
all existing settable run-time parameters to their default values.
|
|
405
|
+
|
|
406
|
+
If you set local to True, then the command takes effect for only the
|
|
407
|
+
current transaction. After commit() or rollback(), the session-level
|
|
408
|
+
setting takes effect again. Setting local to True will appear to
|
|
409
|
+
have no effect if it is executed outside a transaction, since the
|
|
410
|
+
transaction will end immediately.
|
|
411
|
+
"""
|
|
412
|
+
if isinstance(parameter, str):
|
|
413
|
+
parameter = {parameter: value}
|
|
414
|
+
elif isinstance(parameter, (list, tuple)):
|
|
415
|
+
if isinstance(value, (list, tuple)):
|
|
416
|
+
parameter = dict(zip(parameter, value))
|
|
417
|
+
else:
|
|
418
|
+
parameter = dict.fromkeys(parameter, value)
|
|
419
|
+
elif isinstance(parameter, (set, frozenset)):
|
|
420
|
+
if isinstance(value, (list, tuple, set, frozenset)):
|
|
421
|
+
value = set(value)
|
|
422
|
+
if len(value) == 1:
|
|
423
|
+
value = next(iter(value))
|
|
424
|
+
if not (value is None or isinstance(value, str)):
|
|
425
|
+
raise ValueError(
|
|
426
|
+
'A single value must be specified'
|
|
427
|
+
' when parameter is a set')
|
|
428
|
+
parameter = dict.fromkeys(parameter, value)
|
|
429
|
+
elif isinstance(parameter, dict):
|
|
430
|
+
if value is not None:
|
|
431
|
+
raise ValueError(
|
|
432
|
+
'A value must not be specified'
|
|
433
|
+
' when parameter is a dictionary')
|
|
434
|
+
else:
|
|
435
|
+
raise TypeError(
|
|
436
|
+
'The parameter must be a string, list, set or dict')
|
|
437
|
+
if not parameter:
|
|
438
|
+
raise TypeError('No parameter has been specified')
|
|
439
|
+
params: dict[str, str | None] = {}
|
|
440
|
+
for param, param_value in parameter.items():
|
|
441
|
+
param = param.strip().lower() if isinstance(param, str) else None
|
|
442
|
+
if not param:
|
|
443
|
+
raise TypeError('Invalid parameter')
|
|
444
|
+
if param == 'all':
|
|
445
|
+
if param_value is not None:
|
|
446
|
+
raise ValueError(
|
|
447
|
+
'A value must not be specified'
|
|
448
|
+
" when parameter is 'all'")
|
|
449
|
+
params = {'all': None}
|
|
450
|
+
break
|
|
451
|
+
params[param] = param_value
|
|
452
|
+
local_clause = ' LOCAL' if local else ''
|
|
453
|
+
for param, param_value in params.items():
|
|
454
|
+
if param_value is None:
|
|
455
|
+
cmd = f'RESET{local_clause} {param}'
|
|
456
|
+
else:
|
|
457
|
+
if isinstance(param_value, str) and (
|
|
458
|
+
not param_value.isalnum() or
|
|
459
|
+
param_value.upper() != param_value.lower()):
|
|
460
|
+
param_value = f"'{param_value}'"
|
|
461
|
+
cmd = f'SET{local_clause} {param} TO {param_value}'
|
|
462
|
+
self._do_debug(cmd)
|
|
463
|
+
self._valid_db.query(cmd)
|
|
464
|
+
|
|
465
|
+
def query(self, command: str, *args: Any) -> Query:
|
|
466
|
+
"""Execute a SQL command string.
|
|
467
|
+
|
|
468
|
+
This method simply sends a SQL query to the database. If the query is
|
|
469
|
+
an insert statement that inserted exactly one row into a table that
|
|
470
|
+
has OIDs, the return value is the OID of the newly inserted row.
|
|
471
|
+
If the query is an update or delete statement, or an insert statement
|
|
472
|
+
that did not insert exactly one row in a table with OIDs, then the
|
|
473
|
+
number of rows affected is returned as a string. If it is a statement
|
|
474
|
+
that returns rows as a result (usually a select statement, but maybe
|
|
475
|
+
also an "insert/update ... returning" statement), this method returns
|
|
476
|
+
a Query object that can be accessed via getresult() or dictresult()
|
|
477
|
+
or simply printed. Otherwise, it returns `None`.
|
|
478
|
+
|
|
479
|
+
The query can contain numbered parameters of the form $1 in place
|
|
480
|
+
of any data constant. Arguments given after the query string will
|
|
481
|
+
be substituted for the corresponding numbered parameter. Parameter
|
|
482
|
+
values can also be given as a single list or tuple argument.
|
|
483
|
+
"""
|
|
484
|
+
# Wraps shared library function for debugging.
|
|
485
|
+
db = self._valid_db
|
|
486
|
+
if args:
|
|
487
|
+
self._do_debug(command, args)
|
|
488
|
+
return db.query(command, args)
|
|
489
|
+
self._do_debug(command)
|
|
490
|
+
return db.query(command)
|
|
491
|
+
|
|
492
|
+
def query_formatted(self, command: str,
|
|
493
|
+
parameters: tuple | list | dict | None = None,
|
|
494
|
+
types: tuple | list | dict | None = None,
|
|
495
|
+
inline: bool =False) -> Query:
|
|
496
|
+
"""Execute a formatted SQL command string.
|
|
497
|
+
|
|
498
|
+
Similar to query, but using Python format placeholders of the form
|
|
499
|
+
%s or %(names)s instead of PostgreSQL placeholders of the form $1.
|
|
500
|
+
The parameters must be passed as a tuple, list or dict. You can
|
|
501
|
+
also pass a corresponding tuple, list or dict of database types in
|
|
502
|
+
order to format the parameters properly in case there is ambiguity.
|
|
503
|
+
|
|
504
|
+
If you set inline to True, the parameters will be sent to the database
|
|
505
|
+
embedded in the SQL command, otherwise they will be sent separately.
|
|
506
|
+
"""
|
|
507
|
+
return self.query(*self.adapter.format_query(
|
|
508
|
+
command, parameters, types, inline))
|
|
509
|
+
|
|
510
|
+
def query_prepared(self, name: str, *args: Any) -> Query:
|
|
511
|
+
"""Execute a prepared SQL statement.
|
|
512
|
+
|
|
513
|
+
This works like the query() method, except that instead of passing
|
|
514
|
+
the SQL command, you pass the name of a prepared statement. If you
|
|
515
|
+
pass an empty name, the unnamed statement will be executed.
|
|
516
|
+
"""
|
|
517
|
+
if name is None:
|
|
518
|
+
name = ''
|
|
519
|
+
db = self._valid_db
|
|
520
|
+
if args:
|
|
521
|
+
self._do_debug('EXECUTE', name, args)
|
|
522
|
+
return db.query_prepared(name, args)
|
|
523
|
+
self._do_debug('EXECUTE', name)
|
|
524
|
+
return db.query_prepared(name)
|
|
525
|
+
|
|
526
|
+
def prepare(self, name: str, command: str) -> None:
|
|
527
|
+
"""Create a prepared SQL statement.
|
|
528
|
+
|
|
529
|
+
This creates a prepared statement for the given command with the
|
|
530
|
+
given name for later execution with the query_prepared() method.
|
|
531
|
+
|
|
532
|
+
The name can be empty to create an unnamed statement, in which case
|
|
533
|
+
any pre-existing unnamed statement is automatically replaced;
|
|
534
|
+
otherwise it is an error if the statement name is already
|
|
535
|
+
defined in the current database session. We recommend always using
|
|
536
|
+
named queries, since unnamed queries have a limited lifetime and
|
|
537
|
+
can be automatically replaced or destroyed by various operations.
|
|
538
|
+
"""
|
|
539
|
+
if name is None:
|
|
540
|
+
name = ''
|
|
541
|
+
self._do_debug('prepare', name, command)
|
|
542
|
+
self._valid_db.prepare(name, command)
|
|
543
|
+
|
|
544
|
+
def describe_prepared(self, name: str | None = None) -> Query:
|
|
545
|
+
"""Describe a prepared SQL statement.
|
|
546
|
+
|
|
547
|
+
This method returns a Query object describing the result columns of
|
|
548
|
+
the prepared statement with the given name. If you omit the name,
|
|
549
|
+
the unnamed statement will be described if you created one before.
|
|
550
|
+
"""
|
|
551
|
+
if name is None:
|
|
552
|
+
name = ''
|
|
553
|
+
return self._valid_db.describe_prepared(name)
|
|
554
|
+
|
|
555
|
+
def delete_prepared(self, name: str | None = None) -> Query:
|
|
556
|
+
"""Delete a prepared SQL statement.
|
|
557
|
+
|
|
558
|
+
This deallocates a previously prepared SQL statement with the given
|
|
559
|
+
name, or deallocates all prepared statements if you do not specify a
|
|
560
|
+
name. Note that prepared statements are also deallocated automatically
|
|
561
|
+
when the current session ends.
|
|
562
|
+
"""
|
|
563
|
+
if not name:
|
|
564
|
+
name = 'ALL'
|
|
565
|
+
cmd = f"DEALLOCATE {name}"
|
|
566
|
+
self._do_debug(cmd)
|
|
567
|
+
return self._valid_db.query(cmd)
|
|
568
|
+
|
|
569
|
+
def pkey(self, table: str, composite: bool = False, flush: bool = False
|
|
570
|
+
) -> str | tuple[str, ...]:
|
|
571
|
+
"""Get the primary key of a table.
|
|
572
|
+
|
|
573
|
+
Single primary keys are returned as strings unless you
|
|
574
|
+
set the composite flag. Composite primary keys are always
|
|
575
|
+
represented as tuples. Note that this raises a KeyError
|
|
576
|
+
if the table does not have a primary key.
|
|
577
|
+
|
|
578
|
+
If flush is set then the internal cache for primary keys will
|
|
579
|
+
be flushed. This may be necessary after the database schema or
|
|
580
|
+
the search path has been changed.
|
|
581
|
+
"""
|
|
582
|
+
pkeys = self._pkeys
|
|
583
|
+
if flush:
|
|
584
|
+
pkeys.clear()
|
|
585
|
+
self._do_debug('The pkey cache has been flushed')
|
|
586
|
+
try: # cache lookup
|
|
587
|
+
pkey = pkeys[table]
|
|
588
|
+
except KeyError as e: # cache miss, check the database
|
|
589
|
+
cmd = ("SELECT" # noqa: S608
|
|
590
|
+
" a.attname, a.attnum, i.indkey"
|
|
591
|
+
" FROM pg_catalog.pg_index i"
|
|
592
|
+
" JOIN pg_catalog.pg_attribute a"
|
|
593
|
+
" ON a.attrelid OPERATOR(pg_catalog.=) i.indrelid"
|
|
594
|
+
" AND a.attnum OPERATOR(pg_catalog.=) ANY(i.indkey)"
|
|
595
|
+
" AND NOT a.attisdropped"
|
|
596
|
+
" WHERE i.indrelid OPERATOR(pg_catalog.=)"
|
|
597
|
+
" {}::pg_catalog.regclass"
|
|
598
|
+
" AND i.indisprimary ORDER BY a.attnum").format(
|
|
599
|
+
quote_if_unqualified('$1', table))
|
|
600
|
+
res = self._valid_db.query(cmd, (table,)).getresult()
|
|
601
|
+
if not res:
|
|
602
|
+
raise KeyError(f'Table {table} has no primary key') from e
|
|
603
|
+
# we want to use the order defined in the primary key index here,
|
|
604
|
+
# not the order as defined by the columns in the table
|
|
605
|
+
if len(res) > 1:
|
|
606
|
+
indkey = res[0][2]
|
|
607
|
+
pkey = tuple(row[0] for row in sorted(
|
|
608
|
+
res, key=lambda row: indkey.index(row[1])))
|
|
609
|
+
else:
|
|
610
|
+
pkey = res[0][0]
|
|
611
|
+
pkeys[table] = pkey # cache it
|
|
612
|
+
if composite and not isinstance(pkey, tuple):
|
|
613
|
+
pkey = (pkey,)
|
|
614
|
+
return pkey
|
|
615
|
+
|
|
616
|
+
def pkeys(self, table: str) -> tuple[str, ...]:
|
|
617
|
+
"""Get the primary key of a table as a tuple.
|
|
618
|
+
|
|
619
|
+
Same as pkey() with 'composite' set to True.
|
|
620
|
+
"""
|
|
621
|
+
return self.pkey(table, True) # type: ignore
|
|
622
|
+
|
|
623
|
+
def get_databases(self) -> list[str]:
|
|
624
|
+
"""Get list of databases in the system."""
|
|
625
|
+
return [r[0] for r in self._valid_db.query(
|
|
626
|
+
'SELECT datname FROM pg_catalog.pg_database').getresult()]
|
|
627
|
+
|
|
628
|
+
def get_relations(self, kinds: str | Sequence[str] | None = None,
|
|
629
|
+
system: bool = False) -> list[str]:
|
|
630
|
+
"""Get list of relations in connected database of specified kinds.
|
|
631
|
+
|
|
632
|
+
If kinds is None or empty, all kinds of relations are returned.
|
|
633
|
+
Otherwise, kinds can be a string or sequence of type letters
|
|
634
|
+
specifying which kind of relations you want to list.
|
|
635
|
+
|
|
636
|
+
Set the system flag if you want to get the system relations as well.
|
|
637
|
+
"""
|
|
638
|
+
where_parts = []
|
|
639
|
+
if kinds:
|
|
640
|
+
where_parts.append(
|
|
641
|
+
"r.relkind IN ({})".format(','.join(f"'{k}'" for k in kinds)))
|
|
642
|
+
if not system:
|
|
643
|
+
where_parts.append("s.nspname NOT SIMILAR"
|
|
644
|
+
" TO 'pg/_%|information/_schema' ESCAPE '/'")
|
|
645
|
+
where = " WHERE " + ' AND '.join(where_parts) if where_parts else ''
|
|
646
|
+
cmd = ("SELECT" # noqa: S608
|
|
647
|
+
" pg_catalog.quote_ident(s.nspname) OPERATOR(pg_catalog.||)"
|
|
648
|
+
" '.' OPERATOR(pg_catalog.||) pg_catalog.quote_ident(r.relname)"
|
|
649
|
+
" FROM pg_catalog.pg_class r"
|
|
650
|
+
" JOIN pg_catalog.pg_namespace s"
|
|
651
|
+
f" ON s.oid OPERATOR(pg_catalog.=) r.relnamespace{where}"
|
|
652
|
+
" ORDER BY s.nspname, r.relname")
|
|
653
|
+
return [r[0] for r in self._valid_db.query(cmd).getresult()]
|
|
654
|
+
|
|
655
|
+
def get_tables(self, system: bool = False) -> list[str]:
|
|
656
|
+
"""Return list of tables in connected database.
|
|
657
|
+
|
|
658
|
+
Set the system flag if you want to get the system tables as well.
|
|
659
|
+
"""
|
|
660
|
+
return self.get_relations('r', system)
|
|
661
|
+
|
|
662
|
+
def get_attnames(self, table: str, with_oid: bool=True, flush: bool=False
|
|
663
|
+
) -> AttrDict:
|
|
664
|
+
"""Given the name of a table, dig out the set of attribute names.
|
|
665
|
+
|
|
666
|
+
Returns a read-only dictionary of attribute names (the names are
|
|
667
|
+
the keys, the values are the names of the attributes' types)
|
|
668
|
+
with the column names in the proper order if you iterate over it.
|
|
669
|
+
|
|
670
|
+
If flush is set, then the internal cache for attribute names will
|
|
671
|
+
be flushed. This may be necessary after the database schema or
|
|
672
|
+
the search path has been changed.
|
|
673
|
+
|
|
674
|
+
By default, only a limited number of simple types will be returned.
|
|
675
|
+
You can get the registered types after calling use_regtypes(True).
|
|
676
|
+
"""
|
|
677
|
+
attnames = self._attnames
|
|
678
|
+
if flush:
|
|
679
|
+
attnames.clear()
|
|
680
|
+
self._do_debug('The attnames cache has been flushed')
|
|
681
|
+
try: # cache lookup
|
|
682
|
+
names = attnames[table]
|
|
683
|
+
except KeyError: # cache miss, check the database
|
|
684
|
+
cmd = "a.attnum OPERATOR(pg_catalog.>) 0"
|
|
685
|
+
if with_oid:
|
|
686
|
+
cmd = f"({cmd} OR a.attname OPERATOR(pg_catalog.=) 'oid')"
|
|
687
|
+
cmd = self._query_attnames.format(
|
|
688
|
+
quote_if_unqualified('$1', table), cmd)
|
|
689
|
+
res = self._valid_db.query(cmd, (table,)).getresult()
|
|
690
|
+
types = self.dbtypes
|
|
691
|
+
names = AttrDict((name[0], types.add(*name[1:])) for name in res)
|
|
692
|
+
attnames[table] = names # cache it
|
|
693
|
+
return names
|
|
694
|
+
|
|
695
|
+
def get_generated(self, table: str, flush: bool = False) -> frozenset[str]:
|
|
696
|
+
"""Given the name of a table, dig out the set of generated columns.
|
|
697
|
+
|
|
698
|
+
Returns a set of column names that are generated and unalterable.
|
|
699
|
+
|
|
700
|
+
If flush is set, then the internal cache for generated columns will
|
|
701
|
+
be flushed. This may be necessary after the database schema or
|
|
702
|
+
the search path has been changed.
|
|
703
|
+
"""
|
|
704
|
+
generated = self._generated
|
|
705
|
+
if flush:
|
|
706
|
+
generated.clear()
|
|
707
|
+
self._do_debug('The generated cache has been flushed')
|
|
708
|
+
try: # cache lookup
|
|
709
|
+
names = generated[table]
|
|
710
|
+
except KeyError: # cache miss, check the database
|
|
711
|
+
cmd = "a.attnum OPERATOR(pg_catalog.>) 0"
|
|
712
|
+
cmd = f"{cmd} AND {self._query_generated}"
|
|
713
|
+
cmd = self._query_attnames.format(
|
|
714
|
+
quote_if_unqualified('$1', table), cmd)
|
|
715
|
+
res = self._valid_db.query(cmd, (table,)).getresult()
|
|
716
|
+
names = frozenset(name[0] for name in res)
|
|
717
|
+
generated[table] = names # cache it
|
|
718
|
+
return names
|
|
719
|
+
|
|
720
|
+
def use_regtypes(self, regtypes: bool | None = None) -> bool:
|
|
721
|
+
"""Use registered type names instead of simplified type names."""
|
|
722
|
+
if regtypes is None:
|
|
723
|
+
return self.dbtypes._regtypes
|
|
724
|
+
regtypes = bool(regtypes)
|
|
725
|
+
if regtypes != self.dbtypes._regtypes:
|
|
726
|
+
self.dbtypes._regtypes = regtypes
|
|
727
|
+
self._attnames.clear()
|
|
728
|
+
self.dbtypes.clear()
|
|
729
|
+
return regtypes
|
|
730
|
+
|
|
731
|
+
def has_table_privilege(self, table: str, privilege: str = 'select',
|
|
732
|
+
flush: bool = False) -> bool:
|
|
733
|
+
"""Check whether current user has specified table privilege.
|
|
734
|
+
|
|
735
|
+
If flush is set, then the internal cache for table privileges will
|
|
736
|
+
be flushed. This may be necessary after privileges have been changed.
|
|
737
|
+
"""
|
|
738
|
+
privileges = self._privileges
|
|
739
|
+
if flush:
|
|
740
|
+
privileges.clear()
|
|
741
|
+
self._do_debug('The privileges cache has been flushed')
|
|
742
|
+
privilege = privilege.lower()
|
|
743
|
+
try: # ask cache
|
|
744
|
+
ret = privileges[table, privilege]
|
|
745
|
+
except KeyError: # cache miss, ask the database
|
|
746
|
+
cmd = "SELECT pg_catalog.has_table_privilege({}, $2)".format(
|
|
747
|
+
quote_if_unqualified('$1', table))
|
|
748
|
+
query = self._valid_db.query(cmd, (table, privilege))
|
|
749
|
+
ret = query.singlescalar() == self._make_bool(True)
|
|
750
|
+
privileges[table, privilege] = ret # cache it
|
|
751
|
+
return ret
|
|
752
|
+
|
|
753
|
+
def get(self, table: str, row: Any,
|
|
754
|
+
keyname: str | tuple[str, ...] | None = None) -> dict[str, Any]:
|
|
755
|
+
"""Get a row from a database table or view.
|
|
756
|
+
|
|
757
|
+
This method is the basic mechanism to get a single row. It assumes
|
|
758
|
+
that the keyname specifies a unique row. It must be the name of a
|
|
759
|
+
single column or a tuple of column names. If the keyname is not
|
|
760
|
+
specified, then the primary key for the table is used.
|
|
761
|
+
|
|
762
|
+
If row is a dictionary, then the value for the key is taken from it.
|
|
763
|
+
Otherwise, the row must be a single value or a tuple of values
|
|
764
|
+
corresponding to the passed keyname or primary key. The fetched row
|
|
765
|
+
from the table will be returned as a new dictionary or used to replace
|
|
766
|
+
the existing values when row was passed as a dictionary.
|
|
767
|
+
|
|
768
|
+
The OID is also put into the dictionary if the table has one, but
|
|
769
|
+
in order to allow the caller to work with multiple tables, it is
|
|
770
|
+
munged as "oid(table)" using the actual name of the table.
|
|
771
|
+
"""
|
|
772
|
+
if table.endswith('*'): # hint for descendant tables can be ignored
|
|
773
|
+
table = table[:-1].rstrip()
|
|
774
|
+
attnames = self.get_attnames(table)
|
|
775
|
+
qoid = oid_key(table) if 'oid' in attnames else None
|
|
776
|
+
if keyname and isinstance(keyname, str):
|
|
777
|
+
keyname = (keyname,)
|
|
778
|
+
if qoid and isinstance(row, dict) and qoid in row and 'oid' not in row:
|
|
779
|
+
row['oid'] = row[qoid]
|
|
780
|
+
if not keyname:
|
|
781
|
+
try: # if keyname is not specified, try using the primary key
|
|
782
|
+
keyname = self.pkeys(table)
|
|
783
|
+
except KeyError as e: # the table has no primary key
|
|
784
|
+
# try using the oid instead
|
|
785
|
+
if qoid and isinstance(row, dict) and 'oid' in row:
|
|
786
|
+
keyname = ('oid',)
|
|
787
|
+
else:
|
|
788
|
+
raise prg_error(
|
|
789
|
+
f'Table {table} has no primary key') from e
|
|
790
|
+
else: # the table has a primary key
|
|
791
|
+
# check whether all key columns have values
|
|
792
|
+
if isinstance(row, dict) and not set(keyname).issubset(row):
|
|
793
|
+
# try using the oid instead
|
|
794
|
+
if qoid and 'oid' in row:
|
|
795
|
+
keyname = ('oid',)
|
|
796
|
+
else:
|
|
797
|
+
raise KeyError(
|
|
798
|
+
'Missing value in row for specified keyname')
|
|
799
|
+
if not isinstance(row, dict):
|
|
800
|
+
if not isinstance(row, (tuple, list)):
|
|
801
|
+
row = [row]
|
|
802
|
+
if len(keyname) != len(row):
|
|
803
|
+
raise KeyError(
|
|
804
|
+
'Differing number of items in keyname and row')
|
|
805
|
+
row = dict(zip(keyname, row))
|
|
806
|
+
params = self.adapter.parameter_list()
|
|
807
|
+
adapt = params.add
|
|
808
|
+
col = self.escape_identifier
|
|
809
|
+
what = 'oid, *' if qoid else '*'
|
|
810
|
+
where = ' AND '.join(
|
|
811
|
+
f'{col(k)} OPERATOR(pg_catalog.=) {adapt(row[k], attnames[k])}'
|
|
812
|
+
for k in keyname)
|
|
813
|
+
if 'oid' in row:
|
|
814
|
+
if qoid:
|
|
815
|
+
row[qoid] = row['oid']
|
|
816
|
+
del row['oid']
|
|
817
|
+
t = self._escape_qualified_name(table)
|
|
818
|
+
cmd = f'SELECT {what} FROM {t} WHERE {where} LIMIT 1' # noqa: S608
|
|
819
|
+
self._do_debug(cmd, params)
|
|
820
|
+
query = self._valid_db.query(cmd, params)
|
|
821
|
+
res = query.dictresult()
|
|
822
|
+
if not res:
|
|
823
|
+
# make where clause in error message better readable
|
|
824
|
+
where = where.replace('OPERATOR(pg_catalog.=)', '=')
|
|
825
|
+
raise db_error(
|
|
826
|
+
f'No such record in {table}\nwhere {where}\nwith '
|
|
827
|
+
+ self._list_params(params))
|
|
828
|
+
for n, value in res[0].items():
|
|
829
|
+
if qoid and n == 'oid':
|
|
830
|
+
n = qoid
|
|
831
|
+
row[n] = value
|
|
832
|
+
return row
|
|
833
|
+
|
|
834
|
+
def insert(self, table: str, row: dict[str, Any] | None = None, **kw: Any
|
|
835
|
+
) -> dict[str, Any]:
|
|
836
|
+
"""Insert a row into a database table.
|
|
837
|
+
|
|
838
|
+
This method inserts a row into a table. The name of the table must
|
|
839
|
+
be passed as the first parameter. The other parameters are used for
|
|
840
|
+
providing the data of the row that shall be inserted into the table.
|
|
841
|
+
If a dictionary is supplied as the second parameter, it starts with
|
|
842
|
+
that. Otherwise, it uses a blank dictionary.
|
|
843
|
+
Either way the dictionary is updated from the keywords.
|
|
844
|
+
|
|
845
|
+
The dictionary is then reloaded with the values actually inserted in
|
|
846
|
+
order to pick up values modified by rules, triggers, etc.
|
|
847
|
+
"""
|
|
848
|
+
if table.endswith('*'): # hint for descendant tables can be ignored
|
|
849
|
+
table = table[:-1].rstrip()
|
|
850
|
+
if row is None:
|
|
851
|
+
row = {}
|
|
852
|
+
row.update(kw)
|
|
853
|
+
if 'oid' in row:
|
|
854
|
+
del row['oid'] # do not insert oid
|
|
855
|
+
attnames = self.get_attnames(table)
|
|
856
|
+
generated = self.get_generated(table)
|
|
857
|
+
qoid = oid_key(table) if 'oid' in attnames else None
|
|
858
|
+
params = self.adapter.parameter_list()
|
|
859
|
+
adapt = params.add
|
|
860
|
+
col = self.escape_identifier
|
|
861
|
+
name_list, value_list = [], []
|
|
862
|
+
for n in attnames:
|
|
863
|
+
if n in row and n not in generated:
|
|
864
|
+
name_list.append(col(n))
|
|
865
|
+
value_list.append(adapt(row[n], attnames[n]))
|
|
866
|
+
if not name_list:
|
|
867
|
+
raise prg_error('No column found that can be inserted')
|
|
868
|
+
names, values = ', '.join(name_list), ', '.join(value_list)
|
|
869
|
+
ret = 'oid, *' if qoid else '*'
|
|
870
|
+
t = self._escape_qualified_name(table)
|
|
871
|
+
cmd = (f'INSERT INTO {t} ({names})' # noqa: S608
|
|
872
|
+
f' VALUES ({values}) RETURNING {ret}')
|
|
873
|
+
self._do_debug(cmd, params)
|
|
874
|
+
query = self._valid_db.query(cmd, params)
|
|
875
|
+
res = query.dictresult()
|
|
876
|
+
if res: # this should always be true
|
|
877
|
+
for n, value in res[0].items():
|
|
878
|
+
if qoid and n == 'oid':
|
|
879
|
+
n = qoid
|
|
880
|
+
row[n] = value
|
|
881
|
+
return row
|
|
882
|
+
|
|
883
|
+
def update(self, table: str, row: dict[str, Any] | None = None, **kw : Any
|
|
884
|
+
) -> dict[str, Any]:
|
|
885
|
+
"""Update an existing row in a database table.
|
|
886
|
+
|
|
887
|
+
Similar to insert, but updates an existing row. The update is based
|
|
888
|
+
on the primary key of the table or the OID value as munged by get()
|
|
889
|
+
or passed as keyword. The OID will take precedence if provided, so
|
|
890
|
+
that it is possible to update the primary key itself.
|
|
891
|
+
|
|
892
|
+
The dictionary is then modified to reflect any changes caused by the
|
|
893
|
+
update due to triggers, rules, default values, etc.
|
|
894
|
+
"""
|
|
895
|
+
if table.endswith('*'):
|
|
896
|
+
table = table[:-1].rstrip() # need parent table name
|
|
897
|
+
attnames = self.get_attnames(table)
|
|
898
|
+
generated = self.get_generated(table)
|
|
899
|
+
qoid = oid_key(table) if 'oid' in attnames else None
|
|
900
|
+
if row is None:
|
|
901
|
+
row = {}
|
|
902
|
+
elif 'oid' in row:
|
|
903
|
+
del row['oid'] # only accept oid key from named args for safety
|
|
904
|
+
row.update(kw)
|
|
905
|
+
if qoid and qoid in row and 'oid' not in row:
|
|
906
|
+
row['oid'] = row[qoid]
|
|
907
|
+
if qoid and 'oid' in row: # try using the oid
|
|
908
|
+
keynames: tuple[str, ...] = ('oid',)
|
|
909
|
+
keyset = set(keynames)
|
|
910
|
+
else: # try using the primary key
|
|
911
|
+
try:
|
|
912
|
+
keynames = self.pkeys(table)
|
|
913
|
+
except KeyError as e: # the table has no primary key
|
|
914
|
+
raise prg_error(f'Table {table} has no primary key') from e
|
|
915
|
+
keyset = set(keynames)
|
|
916
|
+
# check whether all key columns have values
|
|
917
|
+
if not keyset.issubset(row):
|
|
918
|
+
raise KeyError('Missing value for primary key in row')
|
|
919
|
+
params = self.adapter.parameter_list()
|
|
920
|
+
adapt = params.add
|
|
921
|
+
col = self.escape_identifier
|
|
922
|
+
where = ' AND '.join(
|
|
923
|
+
f'{col(k)} OPERATOR(pg_catalog.=) {adapt(row[k], attnames[k])}'
|
|
924
|
+
for k in keynames)
|
|
925
|
+
if 'oid' in row:
|
|
926
|
+
if qoid:
|
|
927
|
+
row[qoid] = row['oid']
|
|
928
|
+
del row['oid']
|
|
929
|
+
values_list = []
|
|
930
|
+
for n in attnames:
|
|
931
|
+
if n in row and n not in keyset and n not in generated:
|
|
932
|
+
values_list.append(f'{col(n)} = {adapt(row[n], attnames[n])}')
|
|
933
|
+
if not values_list:
|
|
934
|
+
return row
|
|
935
|
+
values = ', '.join(values_list)
|
|
936
|
+
ret = 'oid, *' if qoid else '*'
|
|
937
|
+
t = self._escape_qualified_name(table)
|
|
938
|
+
cmd = (f'UPDATE {t} SET {values}' # noqa: S608
|
|
939
|
+
f' WHERE {where} RETURNING {ret}')
|
|
940
|
+
self._do_debug(cmd, params)
|
|
941
|
+
query = self._valid_db.query(cmd, params)
|
|
942
|
+
res = query.dictresult()
|
|
943
|
+
if res: # may be empty when row does not exist
|
|
944
|
+
for n, value in res[0].items():
|
|
945
|
+
if qoid and n == 'oid':
|
|
946
|
+
n = qoid
|
|
947
|
+
row[n] = value
|
|
948
|
+
return row
|
|
949
|
+
|
|
950
|
+
def upsert(self, table: str, row: dict[str, Any] | None = None, **kw: Any
|
|
951
|
+
) -> dict[str, Any]:
|
|
952
|
+
"""Insert a row into a database table with conflict resolution.
|
|
953
|
+
|
|
954
|
+
This method inserts a row into a table, but instead of raising a
|
|
955
|
+
ProgrammingError exception in case a row with the same primary key
|
|
956
|
+
already exists, an update will be executed instead. This will be
|
|
957
|
+
performed as a single atomic operation on the database, so race
|
|
958
|
+
conditions can be avoided.
|
|
959
|
+
|
|
960
|
+
Like the insert method, the first parameter is the name of the
|
|
961
|
+
table and the second parameter can be used to pass the values to
|
|
962
|
+
be inserted as a dictionary.
|
|
963
|
+
|
|
964
|
+
Unlike the insert und update statement, keyword parameters are not
|
|
965
|
+
used to modify the dictionary, but to specify which columns shall
|
|
966
|
+
be updated in case of a conflict, and in which way:
|
|
967
|
+
|
|
968
|
+
A value of False or None means the column shall not be updated,
|
|
969
|
+
a value of True means the column shall be updated with the value
|
|
970
|
+
that has been proposed for insertion, i.e. has been passed as value
|
|
971
|
+
in the dictionary. Columns that are not specified by keywords but
|
|
972
|
+
appear as keys in the dictionary are also updated like in the case
|
|
973
|
+
keywords had been passed with the value True.
|
|
974
|
+
|
|
975
|
+
So if in the case of a conflict you want to update every column
|
|
976
|
+
that has been passed in the dictionary row, you would call
|
|
977
|
+
upsert(table, row). If you don't want to do anything in case
|
|
978
|
+
of a conflict, i.e. leave the existing row as it is, call
|
|
979
|
+
upsert(table, row, **dict.fromkeys(row)).
|
|
980
|
+
|
|
981
|
+
If you need more fine-grained control of what gets updated, you can
|
|
982
|
+
also pass strings in the keyword parameters. These strings will
|
|
983
|
+
be used as SQL expressions for the update columns. In these
|
|
984
|
+
expressions you can refer to the value that already exists in
|
|
985
|
+
the table by prefixing the column name with "included.", and to
|
|
986
|
+
the value that has been proposed for insertion by prefixing the
|
|
987
|
+
column name with the "excluded."
|
|
988
|
+
|
|
989
|
+
The dictionary is modified in any case to reflect the values in
|
|
990
|
+
the database after the operation has completed.
|
|
991
|
+
|
|
992
|
+
Note: The method uses the PostgreSQL "upsert" feature which is
|
|
993
|
+
only available since PostgreSQL 9.5.
|
|
994
|
+
"""
|
|
995
|
+
if table.endswith('*'): # hint for descendant tables can be ignored
|
|
996
|
+
table = table[:-1].rstrip()
|
|
997
|
+
if row is None:
|
|
998
|
+
row = {}
|
|
999
|
+
if 'oid' in row:
|
|
1000
|
+
del row['oid'] # do not insert oid
|
|
1001
|
+
kw.pop('oid', None) # do not update oid
|
|
1002
|
+
attnames = self.get_attnames(table)
|
|
1003
|
+
generated = self.get_generated(table)
|
|
1004
|
+
qoid = oid_key(table) if 'oid' in attnames else None
|
|
1005
|
+
params = self.adapter.parameter_list()
|
|
1006
|
+
adapt = params.add
|
|
1007
|
+
col = self.escape_identifier
|
|
1008
|
+
name_list, value_list = [], []
|
|
1009
|
+
for n in attnames:
|
|
1010
|
+
if n in row and n not in generated:
|
|
1011
|
+
name_list.append(col(n))
|
|
1012
|
+
value_list.append(adapt(row[n], attnames[n]))
|
|
1013
|
+
names, values = ', '.join(name_list), ', '.join(value_list)
|
|
1014
|
+
try:
|
|
1015
|
+
keynames = self.pkeys(table)
|
|
1016
|
+
except KeyError as e:
|
|
1017
|
+
raise prg_error(f'Table {table} has no primary key') from e
|
|
1018
|
+
target = ', '.join(col(k) for k in keynames)
|
|
1019
|
+
update = []
|
|
1020
|
+
keyset = set(keynames)
|
|
1021
|
+
keyset.add('oid')
|
|
1022
|
+
for n in attnames:
|
|
1023
|
+
if n not in keyset and n not in generated:
|
|
1024
|
+
value = kw.get(n, n in row)
|
|
1025
|
+
if value:
|
|
1026
|
+
if not isinstance(value, str):
|
|
1027
|
+
value = f'excluded.{col(n)}'
|
|
1028
|
+
update.append(f'{col(n)} = {value}')
|
|
1029
|
+
if not values:
|
|
1030
|
+
return row
|
|
1031
|
+
do = 'update set ' + ', '.join(update) if update else 'nothing'
|
|
1032
|
+
ret = 'oid, *' if qoid else '*'
|
|
1033
|
+
t = self._escape_qualified_name(table)
|
|
1034
|
+
cmd = (f'INSERT INTO {t} AS included ({names})' # noqa: S608
|
|
1035
|
+
f' VALUES ({values})'
|
|
1036
|
+
f' ON CONFLICT ({target}) DO {do} RETURNING {ret}')
|
|
1037
|
+
self._do_debug(cmd, params)
|
|
1038
|
+
query = self._valid_db.query(cmd, params)
|
|
1039
|
+
res = query.dictresult()
|
|
1040
|
+
if res: # may be empty with "do nothing"
|
|
1041
|
+
for n, value in res[0].items():
|
|
1042
|
+
if qoid and n == 'oid':
|
|
1043
|
+
n = qoid
|
|
1044
|
+
row[n] = value
|
|
1045
|
+
else:
|
|
1046
|
+
self.get(table, row)
|
|
1047
|
+
return row
|
|
1048
|
+
|
|
1049
|
+
def clear(self, table: str, row: dict[str, Any] | None = None
|
|
1050
|
+
) -> dict[str, Any]:
|
|
1051
|
+
"""Clear all the attributes to values determined by the types.
|
|
1052
|
+
|
|
1053
|
+
Numeric types are set to 0, Booleans are set to false, and everything
|
|
1054
|
+
else is set to the empty string. If the row argument is present,
|
|
1055
|
+
it is used as the row dictionary and any entries matching attribute
|
|
1056
|
+
names are cleared with everything else left unchanged.
|
|
1057
|
+
"""
|
|
1058
|
+
# At some point we will need a way to get defaults from a table.
|
|
1059
|
+
if row is None:
|
|
1060
|
+
row = {} # empty if argument is not present
|
|
1061
|
+
attnames = self.get_attnames(table)
|
|
1062
|
+
for n, t in attnames.items():
|
|
1063
|
+
if n == 'oid':
|
|
1064
|
+
continue
|
|
1065
|
+
t = t.simple
|
|
1066
|
+
if t in DbTypes._num_types:
|
|
1067
|
+
row[n] = 0
|
|
1068
|
+
elif t == 'bool':
|
|
1069
|
+
row[n] = self._make_bool(False)
|
|
1070
|
+
else:
|
|
1071
|
+
row[n] = ''
|
|
1072
|
+
return row
|
|
1073
|
+
|
|
1074
|
+
def delete(self, table: str, row: dict[str, Any] | None = None, **kw: Any
|
|
1075
|
+
) -> int:
|
|
1076
|
+
"""Delete an existing row in a database table.
|
|
1077
|
+
|
|
1078
|
+
This method deletes the row from a table. It deletes based on the
|
|
1079
|
+
primary key of the table or the OID value as munged by get() or
|
|
1080
|
+
passed as keyword. The OID will take precedence if provided.
|
|
1081
|
+
|
|
1082
|
+
The return value is the number of deleted rows (i.e. 0 if the row
|
|
1083
|
+
did not exist and 1 if the row was deleted).
|
|
1084
|
+
|
|
1085
|
+
Note that if the row cannot be deleted because e.g. it is still
|
|
1086
|
+
referenced by another table, this method raises a ProgrammingError.
|
|
1087
|
+
"""
|
|
1088
|
+
if table.endswith('*'): # hint for descendant tables can be ignored
|
|
1089
|
+
table = table[:-1].rstrip()
|
|
1090
|
+
attnames = self.get_attnames(table)
|
|
1091
|
+
qoid = oid_key(table) if 'oid' in attnames else None
|
|
1092
|
+
if row is None:
|
|
1093
|
+
row = {}
|
|
1094
|
+
elif 'oid' in row:
|
|
1095
|
+
del row['oid'] # only accept oid key from named args for safety
|
|
1096
|
+
row.update(kw)
|
|
1097
|
+
if qoid and qoid in row and 'oid' not in row:
|
|
1098
|
+
row['oid'] = row[qoid]
|
|
1099
|
+
if qoid and 'oid' in row: # try using the oid
|
|
1100
|
+
keynames: tuple[str, ...] = ('oid',)
|
|
1101
|
+
else: # try using the primary key
|
|
1102
|
+
try:
|
|
1103
|
+
keynames = self.pkeys(table)
|
|
1104
|
+
except KeyError as e: # the table has no primary key
|
|
1105
|
+
raise prg_error(f'Table {table} has no primary key') from e
|
|
1106
|
+
# check whether all key columns have values
|
|
1107
|
+
if not set(keynames).issubset(row):
|
|
1108
|
+
raise KeyError('Missing value for primary key in row')
|
|
1109
|
+
params = self.adapter.parameter_list()
|
|
1110
|
+
adapt = params.add
|
|
1111
|
+
col = self.escape_identifier
|
|
1112
|
+
where = ' AND '.join(
|
|
1113
|
+
f'{col(k)} OPERATOR(pg_catalog.=) {adapt(row[k], attnames[k])}'
|
|
1114
|
+
for k in keynames)
|
|
1115
|
+
if 'oid' in row:
|
|
1116
|
+
if qoid:
|
|
1117
|
+
row[qoid] = row['oid']
|
|
1118
|
+
del row['oid']
|
|
1119
|
+
t = self._escape_qualified_name(table)
|
|
1120
|
+
cmd = f'DELETE FROM {t} WHERE {where}' # noqa: S608
|
|
1121
|
+
self._do_debug(cmd, params)
|
|
1122
|
+
res = self._valid_db.query(cmd, params)
|
|
1123
|
+
return int(res) # type: ignore
|
|
1124
|
+
|
|
1125
|
+
def truncate(self, table: str | list[str] | tuple[str, ...] |
|
|
1126
|
+
set[str] | frozenset[str], restart: bool = False,
|
|
1127
|
+
cascade: bool = False, only: bool = False) -> Query:
|
|
1128
|
+
"""Empty a table or set of tables.
|
|
1129
|
+
|
|
1130
|
+
This method quickly removes all rows from the given table or set
|
|
1131
|
+
of tables. It has the same effect as an unqualified DELETE on each
|
|
1132
|
+
table, but since it does not actually scan the tables it is faster.
|
|
1133
|
+
Furthermore, it reclaims disk space immediately, rather than requiring
|
|
1134
|
+
a subsequent VACUUM operation. This is most useful on large tables.
|
|
1135
|
+
|
|
1136
|
+
If restart is set to True, sequences owned by columns of the truncated
|
|
1137
|
+
table(s) are automatically restarted. If cascade is set to True, it
|
|
1138
|
+
also truncates all tables that have foreign-key references to any of
|
|
1139
|
+
the named tables. If the parameter 'only' is not set to True, all the
|
|
1140
|
+
descendant tables (if any) will also be truncated. Optionally, a '*'
|
|
1141
|
+
can be specified after the table name to explicitly indicate that
|
|
1142
|
+
descendant tables are included.
|
|
1143
|
+
"""
|
|
1144
|
+
if isinstance(table, str):
|
|
1145
|
+
table_only = {table: only}
|
|
1146
|
+
table = [table]
|
|
1147
|
+
elif isinstance(table, (list, tuple)):
|
|
1148
|
+
if isinstance(only, (list, tuple)):
|
|
1149
|
+
table_only = dict(zip(table, only))
|
|
1150
|
+
else:
|
|
1151
|
+
table_only = dict.fromkeys(table, only)
|
|
1152
|
+
elif isinstance(table, (set, frozenset)):
|
|
1153
|
+
table_only = dict.fromkeys(table, only)
|
|
1154
|
+
else:
|
|
1155
|
+
raise TypeError('The table must be a string, list or set')
|
|
1156
|
+
if not (restart is None or isinstance(restart, (bool, int))):
|
|
1157
|
+
raise TypeError('Invalid type for the restart option')
|
|
1158
|
+
if not (cascade is None or isinstance(cascade, (bool, int))):
|
|
1159
|
+
raise TypeError('Invalid type for the cascade option')
|
|
1160
|
+
tables = []
|
|
1161
|
+
for t in table:
|
|
1162
|
+
u = table_only.get(t)
|
|
1163
|
+
if not (u is None or isinstance(u, (bool, int))):
|
|
1164
|
+
raise TypeError('Invalid type for the only option')
|
|
1165
|
+
if t.endswith('*'):
|
|
1166
|
+
if u:
|
|
1167
|
+
raise ValueError(
|
|
1168
|
+
'Contradictory table name and only options')
|
|
1169
|
+
t = t[:-1].rstrip()
|
|
1170
|
+
t = self._escape_qualified_name(t)
|
|
1171
|
+
if u:
|
|
1172
|
+
t = f'ONLY {t}'
|
|
1173
|
+
tables.append(t)
|
|
1174
|
+
cmd_parts = ['TRUNCATE', ', '.join(tables)]
|
|
1175
|
+
if restart:
|
|
1176
|
+
cmd_parts.append('RESTART IDENTITY')
|
|
1177
|
+
if cascade:
|
|
1178
|
+
cmd_parts.append('CASCADE')
|
|
1179
|
+
cmd = ' '.join(cmd_parts)
|
|
1180
|
+
self._do_debug(cmd)
|
|
1181
|
+
return self._valid_db.query(cmd)
|
|
1182
|
+
|
|
1183
|
+
def get_as_list(
|
|
1184
|
+
self, table: str,
|
|
1185
|
+
what: str | list[str] | tuple[str, ...] | None = None,
|
|
1186
|
+
where: str | list[str] | tuple[str, ...] | None = None,
|
|
1187
|
+
order: str | list[str] | tuple[str, ...] | bool | None = None,
|
|
1188
|
+
limit: int | None = None, offset: int | None = None,
|
|
1189
|
+
scalar: bool = False) -> list:
|
|
1190
|
+
"""Get a table as a list.
|
|
1191
|
+
|
|
1192
|
+
This gets a convenient representation of the table as a list
|
|
1193
|
+
of named tuples in Python. You only need to pass the name of
|
|
1194
|
+
the table (or any other SQL expression returning rows). Note that
|
|
1195
|
+
by default this will return the full content of the table which
|
|
1196
|
+
can be huge and overflow your memory. However, you can control
|
|
1197
|
+
the amount of data returned using the other optional parameters.
|
|
1198
|
+
|
|
1199
|
+
The parameter 'what' can restrict the query to only return a
|
|
1200
|
+
subset of the table columns. It can be a string, list or a tuple.
|
|
1201
|
+
|
|
1202
|
+
The parameter 'where' can restrict the query to only return a
|
|
1203
|
+
subset of the table rows. It can be a string, list or a tuple
|
|
1204
|
+
of SQL expressions that all need to be fulfilled.
|
|
1205
|
+
|
|
1206
|
+
The parameter 'order' specifies the ordering of the rows. It can
|
|
1207
|
+
also be a string, list or a tuple. If no ordering is specified,
|
|
1208
|
+
the result will be ordered by the primary key(s) or all columns if
|
|
1209
|
+
no primary key exists. You can set 'order' to False if you don't
|
|
1210
|
+
care about the ordering. The parameters 'limit' and 'offset' can be
|
|
1211
|
+
integers specifying the maximum number of rows returned and a number
|
|
1212
|
+
of rows skipped over.
|
|
1213
|
+
|
|
1214
|
+
If you set the 'scalar' option to True, then instead of the
|
|
1215
|
+
named tuples you will get the first items of these tuples.
|
|
1216
|
+
This is useful if the result has only one column anyway.
|
|
1217
|
+
"""
|
|
1218
|
+
if not table:
|
|
1219
|
+
raise TypeError('The table name is missing')
|
|
1220
|
+
if what:
|
|
1221
|
+
if isinstance(what, (list, tuple)):
|
|
1222
|
+
what = ', '.join(map(str, what))
|
|
1223
|
+
if order is None:
|
|
1224
|
+
order = what
|
|
1225
|
+
else:
|
|
1226
|
+
what = '*'
|
|
1227
|
+
cmd_parts = ['SELECT', what, 'FROM', table]
|
|
1228
|
+
if where:
|
|
1229
|
+
if isinstance(where, (list, tuple)):
|
|
1230
|
+
where = ' AND '.join(map(str, where))
|
|
1231
|
+
cmd_parts.extend(['WHERE', where])
|
|
1232
|
+
if order is None or order is True:
|
|
1233
|
+
try:
|
|
1234
|
+
order = self.pkeys(table)
|
|
1235
|
+
except (KeyError, ProgrammingError):
|
|
1236
|
+
with suppress(KeyError, ProgrammingError):
|
|
1237
|
+
order = list(self.get_attnames(table))
|
|
1238
|
+
if order and not isinstance(order, bool):
|
|
1239
|
+
if isinstance(order, (list, tuple)):
|
|
1240
|
+
order = ', '.join(map(str, order))
|
|
1241
|
+
cmd_parts.extend(['ORDER BY', order])
|
|
1242
|
+
if limit:
|
|
1243
|
+
cmd_parts.append(f'LIMIT {limit}')
|
|
1244
|
+
if offset:
|
|
1245
|
+
cmd_parts.append(f'OFFSET {offset}')
|
|
1246
|
+
cmd = ' '.join(cmd_parts)
|
|
1247
|
+
self._do_debug(cmd)
|
|
1248
|
+
query = self._valid_db.query(cmd)
|
|
1249
|
+
res = query.namedresult()
|
|
1250
|
+
if res and scalar:
|
|
1251
|
+
res = [row[0] for row in res]
|
|
1252
|
+
return res
|
|
1253
|
+
|
|
1254
|
+
def get_as_dict(
|
|
1255
|
+
self, table: str,
|
|
1256
|
+
keyname: str | list[str] | tuple[str, ...] | None = None,
|
|
1257
|
+
what: str | list[str] | tuple[str, ...] | None = None,
|
|
1258
|
+
where: str | list[str] | tuple[str, ...] | None = None,
|
|
1259
|
+
order: str | list[str] | tuple[str, ...] | bool | None = None,
|
|
1260
|
+
limit: int | None = None, offset: int | None = None,
|
|
1261
|
+
scalar: bool = False) -> dict:
|
|
1262
|
+
"""Get a table as a dictionary.
|
|
1263
|
+
|
|
1264
|
+
This method is similar to get_as_list(), but returns the table
|
|
1265
|
+
as a Python dict instead of a Python list, which can be even
|
|
1266
|
+
more convenient. The primary key column(s) of the table will
|
|
1267
|
+
be used as the keys of the dictionary, while the other column(s)
|
|
1268
|
+
will be the corresponding values. The keys will be named tuples
|
|
1269
|
+
if the table has a composite primary key. The rows will be also
|
|
1270
|
+
named tuples unless the 'scalar' option has been set to True.
|
|
1271
|
+
With the optional parameter 'keyname' you can specify an alternative
|
|
1272
|
+
set of columns to be used as the keys of the dictionary. It must
|
|
1273
|
+
be set as a string, list or a tuple.
|
|
1274
|
+
|
|
1275
|
+
The dictionary will be ordered using the order specified with the
|
|
1276
|
+
'order' parameter or the key column(s) if not specified. You can
|
|
1277
|
+
set 'order' to False if you don't care about the ordering.
|
|
1278
|
+
"""
|
|
1279
|
+
if not table:
|
|
1280
|
+
raise TypeError('The table name is missing')
|
|
1281
|
+
if not keyname:
|
|
1282
|
+
try:
|
|
1283
|
+
keyname = self.pkeys(table)
|
|
1284
|
+
except (KeyError, ProgrammingError) as e:
|
|
1285
|
+
raise prg_error(f'Table {table} has no primary key') from e
|
|
1286
|
+
if isinstance(keyname, str):
|
|
1287
|
+
keynames: list[str] | tuple[str, ...] = (keyname,)
|
|
1288
|
+
elif isinstance(keyname, (list, tuple)):
|
|
1289
|
+
keynames = keyname
|
|
1290
|
+
else:
|
|
1291
|
+
raise KeyError('The keyname must be a string, list or tuple')
|
|
1292
|
+
if what:
|
|
1293
|
+
if isinstance(what, (list, tuple)):
|
|
1294
|
+
what = ', '.join(map(str, what))
|
|
1295
|
+
if order is None:
|
|
1296
|
+
order = what
|
|
1297
|
+
else:
|
|
1298
|
+
what = '*'
|
|
1299
|
+
cmd_parts = ['SELECT', what, 'FROM', table]
|
|
1300
|
+
if where:
|
|
1301
|
+
if isinstance(where, (list, tuple)):
|
|
1302
|
+
where = ' AND '.join(map(str, where))
|
|
1303
|
+
cmd_parts.extend(['WHERE', where])
|
|
1304
|
+
if order is None or order is True:
|
|
1305
|
+
order = keyname
|
|
1306
|
+
if order and not isinstance(order, bool):
|
|
1307
|
+
if isinstance(order, (list, tuple)):
|
|
1308
|
+
order = ', '.join(map(str, order))
|
|
1309
|
+
cmd_parts.extend(['ORDER BY', order])
|
|
1310
|
+
if limit:
|
|
1311
|
+
cmd_parts.append(f'LIMIT {limit}')
|
|
1312
|
+
if offset:
|
|
1313
|
+
cmd_parts.append(f'OFFSET {offset}')
|
|
1314
|
+
cmd = ' '.join(cmd_parts)
|
|
1315
|
+
self._do_debug(cmd)
|
|
1316
|
+
query = self._valid_db.query(cmd)
|
|
1317
|
+
res = query.getresult()
|
|
1318
|
+
if not res:
|
|
1319
|
+
return {}
|
|
1320
|
+
keyset = set(keynames)
|
|
1321
|
+
fields = query.listfields()
|
|
1322
|
+
if not keyset.issubset(fields):
|
|
1323
|
+
raise KeyError('Missing keyname in row')
|
|
1324
|
+
key_index: list[int] = []
|
|
1325
|
+
row_index: list[int] = []
|
|
1326
|
+
for i, f in enumerate(fields):
|
|
1327
|
+
(key_index if f in keyset else row_index).append(i)
|
|
1328
|
+
key_tuple = len(key_index) > 1
|
|
1329
|
+
get_key = itemgetter(*key_index)
|
|
1330
|
+
keys = map(get_key, res)
|
|
1331
|
+
if scalar:
|
|
1332
|
+
row_index = row_index[:1]
|
|
1333
|
+
row_is_tuple = False
|
|
1334
|
+
else:
|
|
1335
|
+
row_is_tuple = len(row_index) > 1
|
|
1336
|
+
if scalar or row_is_tuple:
|
|
1337
|
+
get_row: Callable[[tuple], tuple] = itemgetter( # pyright: ignore
|
|
1338
|
+
*row_index)
|
|
1339
|
+
else:
|
|
1340
|
+
frst_index = row_index[0]
|
|
1341
|
+
|
|
1342
|
+
def get_row(row : tuple) -> tuple:
|
|
1343
|
+
return row[frst_index], # tuple with one item
|
|
1344
|
+
|
|
1345
|
+
row_is_tuple = True
|
|
1346
|
+
rows = map(get_row, res)
|
|
1347
|
+
if key_tuple or row_is_tuple:
|
|
1348
|
+
if key_tuple:
|
|
1349
|
+
keys = namediter(_MemoryQuery(keys, keynames)) # type: ignore
|
|
1350
|
+
if row_is_tuple:
|
|
1351
|
+
fields = tuple(f for f in fields if f not in keyset)
|
|
1352
|
+
rows = namediter(_MemoryQuery(rows, fields)) # type: ignore
|
|
1353
|
+
# noinspection PyArgumentList
|
|
1354
|
+
return dict(zip(keys, rows))
|
|
1355
|
+
|
|
1356
|
+
def notification_handler(self, event: str, callback: Callable,
|
|
1357
|
+
arg_dict: dict | None = None,
|
|
1358
|
+
timeout: int | float | None = None,
|
|
1359
|
+
stop_event: str | None = None
|
|
1360
|
+
) -> NotificationHandler:
|
|
1361
|
+
"""Get notification handler that will run the given callback."""
|
|
1362
|
+
return NotificationHandler(self, event, callback,
|
|
1363
|
+
arg_dict, timeout, stop_event)
|
|
1364
|
+
|
|
1365
|
+
# immediately wrapped methods
|
|
1366
|
+
|
|
1367
|
+
def send_query(self, cmd: str, args: Sequence | None = None) -> Query:
|
|
1368
|
+
"""Create a new asynchronous query object for this connection."""
|
|
1369
|
+
if args is None:
|
|
1370
|
+
return self._valid_db.send_query(cmd)
|
|
1371
|
+
return self._valid_db.send_query(cmd, args)
|
|
1372
|
+
|
|
1373
|
+
def poll(self) -> int:
|
|
1374
|
+
"""Complete an asynchronous connection and get its state."""
|
|
1375
|
+
return self._valid_db.poll()
|
|
1376
|
+
|
|
1377
|
+
def cancel(self) -> None:
|
|
1378
|
+
"""Abandon processing of current SQL command."""
|
|
1379
|
+
self._valid_db.cancel()
|
|
1380
|
+
|
|
1381
|
+
def fileno(self) -> int:
|
|
1382
|
+
"""Get the socket used to connect to the database."""
|
|
1383
|
+
return self._valid_db.fileno()
|
|
1384
|
+
|
|
1385
|
+
def get_cast_hook(self) -> Callable | None:
|
|
1386
|
+
"""Get the function that handles all external typecasting."""
|
|
1387
|
+
return self._valid_db.get_cast_hook()
|
|
1388
|
+
|
|
1389
|
+
def set_cast_hook(self, hook: Callable | None) -> None:
|
|
1390
|
+
"""Set a function that will handle all external typecasting."""
|
|
1391
|
+
self._valid_db.set_cast_hook(hook)
|
|
1392
|
+
|
|
1393
|
+
def get_notice_receiver(self) -> Callable | None:
|
|
1394
|
+
"""Get the current notice receiver."""
|
|
1395
|
+
return self._valid_db.get_notice_receiver()
|
|
1396
|
+
|
|
1397
|
+
def set_notice_receiver(self, receiver: Callable | None) -> None:
|
|
1398
|
+
"""Set a custom notice receiver."""
|
|
1399
|
+
self._valid_db.set_notice_receiver(receiver)
|
|
1400
|
+
|
|
1401
|
+
def getnotify(self) -> tuple[str, int, str] | None:
|
|
1402
|
+
"""Get the last notify from the server."""
|
|
1403
|
+
return self._valid_db.getnotify()
|
|
1404
|
+
|
|
1405
|
+
def inserttable(self, table: str, values: Sequence[list|tuple],
|
|
1406
|
+
columns: list[str] | tuple[str, ...] | None = None) -> int:
|
|
1407
|
+
"""Insert a Python iterable into a database table."""
|
|
1408
|
+
if columns is None:
|
|
1409
|
+
return self._valid_db.inserttable(table, values)
|
|
1410
|
+
return self._valid_db.inserttable(table, values, columns)
|
|
1411
|
+
|
|
1412
|
+
def transaction(self) -> int:
|
|
1413
|
+
"""Get the current in-transaction status of the server.
|
|
1414
|
+
|
|
1415
|
+
The status returned by this method can be TRANS_IDLE (currently idle),
|
|
1416
|
+
TRANS_ACTIVE (a command is in progress), TRANS_INTRANS (idle, in a
|
|
1417
|
+
valid transaction block), or TRANS_INERROR (idle, in a failed
|
|
1418
|
+
transaction block). TRANS_UNKNOWN is reported if the connection is
|
|
1419
|
+
bad. The status TRANS_ACTIVE is reported only when a query has been
|
|
1420
|
+
sent to the server and not yet completed.
|
|
1421
|
+
"""
|
|
1422
|
+
return self._valid_db.transaction()
|
|
1423
|
+
|
|
1424
|
+
def parameter(self, name: str) -> str | None:
|
|
1425
|
+
"""Look up a current parameter setting of the server."""
|
|
1426
|
+
return self._valid_db.parameter(name)
|
|
1427
|
+
|
|
1428
|
+
|
|
1429
|
+
def date_format(self) -> str:
|
|
1430
|
+
"""Look up the date format currently being used by the database."""
|
|
1431
|
+
return self._valid_db.date_format()
|
|
1432
|
+
|
|
1433
|
+
def escape_literal(self, s: AnyStr) -> AnyStr:
|
|
1434
|
+
"""Escape a literal constant for use within SQL."""
|
|
1435
|
+
return self._valid_db.escape_literal(s)
|
|
1436
|
+
|
|
1437
|
+
def escape_identifier(self, s: AnyStr) -> AnyStr:
|
|
1438
|
+
"""Escape an identifier for use within SQL."""
|
|
1439
|
+
return self._valid_db.escape_identifier(s)
|
|
1440
|
+
|
|
1441
|
+
def escape_string(self, s: AnyStr) -> AnyStr:
|
|
1442
|
+
"""Escape a string for use within SQL."""
|
|
1443
|
+
return self._valid_db.escape_string(s)
|
|
1444
|
+
|
|
1445
|
+
def escape_bytea(self, s: AnyStr) -> AnyStr:
|
|
1446
|
+
"""Escape binary data for use within SQL as type 'bytea'."""
|
|
1447
|
+
return self._valid_db.escape_bytea(s)
|
|
1448
|
+
|
|
1449
|
+
def putline(self, line: str) -> None:
|
|
1450
|
+
"""Write a line to the server socket."""
|
|
1451
|
+
self._valid_db.putline(line)
|
|
1452
|
+
|
|
1453
|
+
def getline(self) -> str:
|
|
1454
|
+
"""Get a line from server socket."""
|
|
1455
|
+
return self._valid_db.getline()
|
|
1456
|
+
|
|
1457
|
+
def endcopy(self) -> None:
|
|
1458
|
+
"""Synchronize client and server."""
|
|
1459
|
+
self._valid_db.endcopy()
|
|
1460
|
+
|
|
1461
|
+
def set_non_blocking(self, nb: bool) -> None:
|
|
1462
|
+
"""Set the non-blocking mode of the connection."""
|
|
1463
|
+
self._valid_db.set_non_blocking(nb)
|
|
1464
|
+
|
|
1465
|
+
def is_non_blocking(self) -> bool:
|
|
1466
|
+
"""Get the non-blocking mode of the connection."""
|
|
1467
|
+
return self._valid_db.is_non_blocking()
|
|
1468
|
+
|
|
1469
|
+
def locreate(self, mode: int) -> LargeObject:
|
|
1470
|
+
"""Create a large object in the database.
|
|
1471
|
+
|
|
1472
|
+
The valid values for 'mode' parameter are defined as the module level
|
|
1473
|
+
constants INV_READ and INV_WRITE.
|
|
1474
|
+
"""
|
|
1475
|
+
return self._valid_db.locreate(mode)
|
|
1476
|
+
|
|
1477
|
+
def getlo(self, oid: int) -> LargeObject:
|
|
1478
|
+
"""Build a large object from given oid."""
|
|
1479
|
+
return self._valid_db.getlo(oid)
|
|
1480
|
+
|
|
1481
|
+
def loimport(self, filename: str) -> LargeObject:
|
|
1482
|
+
"""Import a file to a large object."""
|
|
1483
|
+
return self._valid_db.loimport(filename)
|
|
1484
|
+
|
|
1485
|
+
|
|
1486
|
+
class _MemoryQuery:
|
|
1487
|
+
"""Class that embodies a given query result."""
|
|
1488
|
+
|
|
1489
|
+
result: Any
|
|
1490
|
+
fields: tuple[str, ...]
|
|
1491
|
+
|
|
1492
|
+
def __init__(self, result: Any, fields: Sequence[str]) -> None:
|
|
1493
|
+
"""Create query from given result rows and field names."""
|
|
1494
|
+
self.result = result
|
|
1495
|
+
self.fields = tuple(fields)
|
|
1496
|
+
|
|
1497
|
+
def listfields(self) -> tuple[str, ...]:
|
|
1498
|
+
"""Return the stored field names of this query."""
|
|
1499
|
+
return self.fields
|
|
1500
|
+
|
|
1501
|
+
def getresult(self) -> Any:
|
|
1502
|
+
"""Return the stored result of this query."""
|
|
1503
|
+
return self.result
|
|
1504
|
+
|
|
1505
|
+
def __iter__(self) -> Iterator[Any]:
|
|
1506
|
+
return iter(self.result)
|