PyGreSQL 6.3.0b1__cp315-cp315-win_amd64.whl

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