PyGreSQL 6.1.0__cp313-cp313-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,1502 @@
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
+ cmd = (f'RESET{local_clause} {param}'
455
+ if param_value is None else
456
+ f'SET{local_clause} {param} TO {param_value}')
457
+ self._do_debug(cmd)
458
+ self._valid_db.query(cmd)
459
+
460
+ def query(self, command: str, *args: Any) -> Query:
461
+ """Execute a SQL command string.
462
+
463
+ This method simply sends a SQL query to the database. If the query is
464
+ an insert statement that inserted exactly one row into a table that
465
+ has OIDs, the return value is the OID of the newly inserted row.
466
+ If the query is an update or delete statement, or an insert statement
467
+ that did not insert exactly one row in a table with OIDs, then the
468
+ number of rows affected is returned as a string. If it is a statement
469
+ that returns rows as a result (usually a select statement, but maybe
470
+ also an "insert/update ... returning" statement), this method returns
471
+ a Query object that can be accessed via getresult() or dictresult()
472
+ or simply printed. Otherwise, it returns `None`.
473
+
474
+ The query can contain numbered parameters of the form $1 in place
475
+ of any data constant. Arguments given after the query string will
476
+ be substituted for the corresponding numbered parameter. Parameter
477
+ values can also be given as a single list or tuple argument.
478
+ """
479
+ # Wraps shared library function for debugging.
480
+ db = self._valid_db
481
+ if args:
482
+ self._do_debug(command, args)
483
+ return db.query(command, args)
484
+ self._do_debug(command)
485
+ return db.query(command)
486
+
487
+ def query_formatted(self, command: str,
488
+ parameters: tuple | list | dict | None = None,
489
+ types: tuple | list | dict | None = None,
490
+ inline: bool =False) -> Query:
491
+ """Execute a formatted SQL command string.
492
+
493
+ Similar to query, but using Python format placeholders of the form
494
+ %s or %(names)s instead of PostgreSQL placeholders of the form $1.
495
+ The parameters must be passed as a tuple, list or dict. You can
496
+ also pass a corresponding tuple, list or dict of database types in
497
+ order to format the parameters properly in case there is ambiguity.
498
+
499
+ If you set inline to True, the parameters will be sent to the database
500
+ embedded in the SQL command, otherwise they will be sent separately.
501
+ """
502
+ return self.query(*self.adapter.format_query(
503
+ command, parameters, types, inline))
504
+
505
+ def query_prepared(self, name: str, *args: Any) -> Query:
506
+ """Execute a prepared SQL statement.
507
+
508
+ This works like the query() method, except that instead of passing
509
+ the SQL command, you pass the name of a prepared statement. If you
510
+ pass an empty name, the unnamed statement will be executed.
511
+ """
512
+ if name is None:
513
+ name = ''
514
+ db = self._valid_db
515
+ if args:
516
+ self._do_debug('EXECUTE', name, args)
517
+ return db.query_prepared(name, args)
518
+ self._do_debug('EXECUTE', name)
519
+ return db.query_prepared(name)
520
+
521
+ def prepare(self, name: str, command: str) -> None:
522
+ """Create a prepared SQL statement.
523
+
524
+ This creates a prepared statement for the given command with the
525
+ given name for later execution with the query_prepared() method.
526
+
527
+ The name can be empty to create an unnamed statement, in which case
528
+ any pre-existing unnamed statement is automatically replaced;
529
+ otherwise it is an error if the statement name is already
530
+ defined in the current database session. We recommend always using
531
+ named queries, since unnamed queries have a limited lifetime and
532
+ can be automatically replaced or destroyed by various operations.
533
+ """
534
+ if name is None:
535
+ name = ''
536
+ self._do_debug('prepare', name, command)
537
+ self._valid_db.prepare(name, command)
538
+
539
+ def describe_prepared(self, name: str | None = None) -> Query:
540
+ """Describe a prepared SQL statement.
541
+
542
+ This method returns a Query object describing the result columns of
543
+ the prepared statement with the given name. If you omit the name,
544
+ the unnamed statement will be described if you created one before.
545
+ """
546
+ if name is None:
547
+ name = ''
548
+ return self._valid_db.describe_prepared(name)
549
+
550
+ def delete_prepared(self, name: str | None = None) -> Query:
551
+ """Delete a prepared SQL statement.
552
+
553
+ This deallocates a previously prepared SQL statement with the given
554
+ name, or deallocates all prepared statements if you do not specify a
555
+ name. Note that prepared statements are also deallocated automatically
556
+ when the current session ends.
557
+ """
558
+ if not name:
559
+ name = 'ALL'
560
+ cmd = f"DEALLOCATE {name}"
561
+ self._do_debug(cmd)
562
+ return self._valid_db.query(cmd)
563
+
564
+ def pkey(self, table: str, composite: bool = False, flush: bool = False
565
+ ) -> str | tuple[str, ...]:
566
+ """Get the primary key of a table.
567
+
568
+ Single primary keys are returned as strings unless you
569
+ set the composite flag. Composite primary keys are always
570
+ represented as tuples. Note that this raises a KeyError
571
+ if the table does not have a primary key.
572
+
573
+ If flush is set then the internal cache for primary keys will
574
+ be flushed. This may be necessary after the database schema or
575
+ the search path has been changed.
576
+ """
577
+ pkeys = self._pkeys
578
+ if flush:
579
+ pkeys.clear()
580
+ self._do_debug('The pkey cache has been flushed')
581
+ try: # cache lookup
582
+ pkey = pkeys[table]
583
+ except KeyError as e: # cache miss, check the database
584
+ cmd = ("SELECT" # noqa: S608
585
+ " a.attname, a.attnum, i.indkey"
586
+ " FROM pg_catalog.pg_index i"
587
+ " JOIN pg_catalog.pg_attribute a"
588
+ " ON a.attrelid OPERATOR(pg_catalog.=) i.indrelid"
589
+ " AND a.attnum OPERATOR(pg_catalog.=) ANY(i.indkey)"
590
+ " AND NOT a.attisdropped"
591
+ " WHERE i.indrelid OPERATOR(pg_catalog.=)"
592
+ " {}::pg_catalog.regclass"
593
+ " AND i.indisprimary ORDER BY a.attnum").format(
594
+ quote_if_unqualified('$1', table))
595
+ res = self._valid_db.query(cmd, (table,)).getresult()
596
+ if not res:
597
+ raise KeyError(f'Table {table} has no primary key') from e
598
+ # we want to use the order defined in the primary key index here,
599
+ # not the order as defined by the columns in the table
600
+ if len(res) > 1:
601
+ indkey = res[0][2]
602
+ pkey = tuple(row[0] for row in sorted(
603
+ res, key=lambda row: indkey.index(row[1])))
604
+ else:
605
+ pkey = res[0][0]
606
+ pkeys[table] = pkey # cache it
607
+ if composite and not isinstance(pkey, tuple):
608
+ pkey = (pkey,)
609
+ return pkey
610
+
611
+ def pkeys(self, table: str) -> tuple[str, ...]:
612
+ """Get the primary key of a table as a tuple.
613
+
614
+ Same as pkey() with 'composite' set to True.
615
+ """
616
+ return self.pkey(table, True) # type: ignore
617
+
618
+ def get_databases(self) -> list[str]:
619
+ """Get list of databases in the system."""
620
+ return [r[0] for r in self._valid_db.query(
621
+ 'SELECT datname FROM pg_catalog.pg_database').getresult()]
622
+
623
+ def get_relations(self, kinds: str | Sequence[str] | None = None,
624
+ system: bool = False) -> list[str]:
625
+ """Get list of relations in connected database of specified kinds.
626
+
627
+ If kinds is None or empty, all kinds of relations are returned.
628
+ Otherwise, kinds can be a string or sequence of type letters
629
+ specifying which kind of relations you want to list.
630
+
631
+ Set the system flag if you want to get the system relations as well.
632
+ """
633
+ where_parts = []
634
+ if kinds:
635
+ where_parts.append(
636
+ "r.relkind IN ({})".format(','.join(f"'{k}'" for k in kinds)))
637
+ if not system:
638
+ where_parts.append("s.nspname NOT SIMILAR"
639
+ " TO 'pg/_%|information/_schema' ESCAPE '/'")
640
+ where = " WHERE " + ' AND '.join(where_parts) if where_parts else ''
641
+ cmd = ("SELECT" # noqa: S608
642
+ " pg_catalog.quote_ident(s.nspname) OPERATOR(pg_catalog.||)"
643
+ " '.' OPERATOR(pg_catalog.||) pg_catalog.quote_ident(r.relname)"
644
+ " FROM pg_catalog.pg_class r"
645
+ " JOIN pg_catalog.pg_namespace s"
646
+ f" ON s.oid OPERATOR(pg_catalog.=) r.relnamespace{where}"
647
+ " ORDER BY s.nspname, r.relname")
648
+ return [r[0] for r in self._valid_db.query(cmd).getresult()]
649
+
650
+ def get_tables(self, system: bool = False) -> list[str]:
651
+ """Return list of tables in connected database.
652
+
653
+ Set the system flag if you want to get the system tables as well.
654
+ """
655
+ return self.get_relations('r', system)
656
+
657
+ def get_attnames(self, table: str, with_oid: bool=True, flush: bool=False
658
+ ) -> AttrDict:
659
+ """Given the name of a table, dig out the set of attribute names.
660
+
661
+ Returns a read-only dictionary of attribute names (the names are
662
+ the keys, the values are the names of the attributes' types)
663
+ with the column names in the proper order if you iterate over it.
664
+
665
+ If flush is set, then the internal cache for attribute names will
666
+ be flushed. This may be necessary after the database schema or
667
+ the search path has been changed.
668
+
669
+ By default, only a limited number of simple types will be returned.
670
+ You can get the registered types after calling use_regtypes(True).
671
+ """
672
+ attnames = self._attnames
673
+ if flush:
674
+ attnames.clear()
675
+ self._do_debug('The attnames cache has been flushed')
676
+ try: # cache lookup
677
+ names = attnames[table]
678
+ except KeyError: # cache miss, check the database
679
+ cmd = "a.attnum OPERATOR(pg_catalog.>) 0"
680
+ if with_oid:
681
+ cmd = f"({cmd} OR a.attname OPERATOR(pg_catalog.=) 'oid')"
682
+ cmd = self._query_attnames.format(
683
+ quote_if_unqualified('$1', table), cmd)
684
+ res = self._valid_db.query(cmd, (table,)).getresult()
685
+ types = self.dbtypes
686
+ names = AttrDict((name[0], types.add(*name[1:])) for name in res)
687
+ attnames[table] = names # cache it
688
+ return names
689
+
690
+ def get_generated(self, table: str, flush: bool = False) -> frozenset[str]:
691
+ """Given the name of a table, dig out the set of generated columns.
692
+
693
+ Returns a set of column names that are generated and unalterable.
694
+
695
+ If flush is set, then the internal cache for generated columns will
696
+ be flushed. This may be necessary after the database schema or
697
+ the search path has been changed.
698
+ """
699
+ generated = self._generated
700
+ if flush:
701
+ generated.clear()
702
+ self._do_debug('The generated cache has been flushed')
703
+ try: # cache lookup
704
+ names = generated[table]
705
+ except KeyError: # cache miss, check the database
706
+ cmd = "a.attnum OPERATOR(pg_catalog.>) 0"
707
+ cmd = f"{cmd} AND {self._query_generated}"
708
+ cmd = self._query_attnames.format(
709
+ quote_if_unqualified('$1', table), cmd)
710
+ res = self._valid_db.query(cmd, (table,)).getresult()
711
+ names = frozenset(name[0] for name in res)
712
+ generated[table] = names # cache it
713
+ return names
714
+
715
+ def use_regtypes(self, regtypes: bool | None = None) -> bool:
716
+ """Use registered type names instead of simplified type names."""
717
+ if regtypes is None:
718
+ return self.dbtypes._regtypes
719
+ regtypes = bool(regtypes)
720
+ if regtypes != self.dbtypes._regtypes:
721
+ self.dbtypes._regtypes = regtypes
722
+ self._attnames.clear()
723
+ self.dbtypes.clear()
724
+ return regtypes
725
+
726
+ def has_table_privilege(self, table: str, privilege: str = 'select',
727
+ flush: bool = False) -> bool:
728
+ """Check whether current user has specified table privilege.
729
+
730
+ If flush is set, then the internal cache for table privileges will
731
+ be flushed. This may be necessary after privileges have been changed.
732
+ """
733
+ privileges = self._privileges
734
+ if flush:
735
+ privileges.clear()
736
+ self._do_debug('The privileges cache has been flushed')
737
+ privilege = privilege.lower()
738
+ try: # ask cache
739
+ ret = privileges[table, privilege]
740
+ except KeyError: # cache miss, ask the database
741
+ cmd = "SELECT pg_catalog.has_table_privilege({}, $2)".format(
742
+ quote_if_unqualified('$1', table))
743
+ query = self._valid_db.query(cmd, (table, privilege))
744
+ ret = query.singlescalar() == self._make_bool(True)
745
+ privileges[table, privilege] = ret # cache it
746
+ return ret
747
+
748
+ def get(self, table: str, row: Any,
749
+ keyname: str | tuple[str, ...] | None = None) -> dict[str, Any]:
750
+ """Get a row from a database table or view.
751
+
752
+ This method is the basic mechanism to get a single row. It assumes
753
+ that the keyname specifies a unique row. It must be the name of a
754
+ single column or a tuple of column names. If the keyname is not
755
+ specified, then the primary key for the table is used.
756
+
757
+ If row is a dictionary, then the value for the key is taken from it.
758
+ Otherwise, the row must be a single value or a tuple of values
759
+ corresponding to the passed keyname or primary key. The fetched row
760
+ from the table will be returned as a new dictionary or used to replace
761
+ the existing values when row was passed as a dictionary.
762
+
763
+ The OID is also put into the dictionary if the table has one, but
764
+ in order to allow the caller to work with multiple tables, it is
765
+ munged as "oid(table)" using the actual name of the table.
766
+ """
767
+ if table.endswith('*'): # hint for descendant tables can be ignored
768
+ table = table[:-1].rstrip()
769
+ attnames = self.get_attnames(table)
770
+ qoid = oid_key(table) if 'oid' in attnames else None
771
+ if keyname and isinstance(keyname, str):
772
+ keyname = (keyname,)
773
+ if qoid and isinstance(row, dict) and qoid in row and 'oid' not in row:
774
+ row['oid'] = row[qoid]
775
+ if not keyname:
776
+ try: # if keyname is not specified, try using the primary key
777
+ keyname = self.pkeys(table)
778
+ except KeyError as e: # the table has no primary key
779
+ # try using the oid instead
780
+ if qoid and isinstance(row, dict) and 'oid' in row:
781
+ keyname = ('oid',)
782
+ else:
783
+ raise prg_error(
784
+ f'Table {table} has no primary key') from e
785
+ else: # the table has a primary key
786
+ # check whether all key columns have values
787
+ if isinstance(row, dict) and not set(keyname).issubset(row):
788
+ # try using the oid instead
789
+ if qoid and 'oid' in row:
790
+ keyname = ('oid',)
791
+ else:
792
+ raise KeyError(
793
+ 'Missing value in row for specified keyname')
794
+ if not isinstance(row, dict):
795
+ if not isinstance(row, (tuple, list)):
796
+ row = [row]
797
+ if len(keyname) != len(row):
798
+ raise KeyError(
799
+ 'Differing number of items in keyname and row')
800
+ row = dict(zip(keyname, row))
801
+ params = self.adapter.parameter_list()
802
+ adapt = params.add
803
+ col = self.escape_identifier
804
+ what = 'oid, *' if qoid else '*'
805
+ where = ' AND '.join(
806
+ f'{col(k)} OPERATOR(pg_catalog.=) {adapt(row[k], attnames[k])}'
807
+ for k in keyname)
808
+ if 'oid' in row:
809
+ if qoid:
810
+ row[qoid] = row['oid']
811
+ del row['oid']
812
+ t = self._escape_qualified_name(table)
813
+ cmd = f'SELECT {what} FROM {t} WHERE {where} LIMIT 1' # noqa: S608s
814
+ self._do_debug(cmd, params)
815
+ query = self._valid_db.query(cmd, params)
816
+ res = query.dictresult()
817
+ if not res:
818
+ # make where clause in error message better readable
819
+ where = where.replace('OPERATOR(pg_catalog.=)', '=')
820
+ raise db_error(
821
+ f'No such record in {table}\nwhere {where}\nwith '
822
+ + self._list_params(params))
823
+ for n, value in res[0].items():
824
+ if qoid and n == 'oid':
825
+ n = qoid
826
+ row[n] = value
827
+ return row
828
+
829
+ def insert(self, table: str, row: dict[str, Any] | None = None, **kw: Any
830
+ ) -> dict[str, Any]:
831
+ """Insert a row into a database table.
832
+
833
+ This method inserts a row into a table. The name of the table must
834
+ be passed as the first parameter. The other parameters are used for
835
+ providing the data of the row that shall be inserted into the table.
836
+ If a dictionary is supplied as the second parameter, it starts with
837
+ that. Otherwise, it uses a blank dictionary.
838
+ Either way the dictionary is updated from the keywords.
839
+
840
+ The dictionary is then reloaded with the values actually inserted in
841
+ order to pick up values modified by rules, triggers, etc.
842
+ """
843
+ if table.endswith('*'): # hint for descendant tables can be ignored
844
+ table = table[:-1].rstrip()
845
+ if row is None:
846
+ row = {}
847
+ row.update(kw)
848
+ if 'oid' in row:
849
+ del row['oid'] # do not insert oid
850
+ attnames = self.get_attnames(table)
851
+ generated = self.get_generated(table)
852
+ qoid = oid_key(table) if 'oid' in attnames else None
853
+ params = self.adapter.parameter_list()
854
+ adapt = params.add
855
+ col = self.escape_identifier
856
+ name_list, value_list = [], []
857
+ for n in attnames:
858
+ if n in row and n not in generated:
859
+ name_list.append(col(n))
860
+ value_list.append(adapt(row[n], attnames[n]))
861
+ if not name_list:
862
+ raise prg_error('No column found that can be inserted')
863
+ names, values = ', '.join(name_list), ', '.join(value_list)
864
+ ret = 'oid, *' if qoid else '*'
865
+ t = self._escape_qualified_name(table)
866
+ cmd = (f'INSERT INTO {t} ({names})' # noqa: S608
867
+ f' VALUES ({values}) RETURNING {ret}')
868
+ self._do_debug(cmd, params)
869
+ query = self._valid_db.query(cmd, params)
870
+ res = query.dictresult()
871
+ if res: # this should always be true
872
+ for n, value in res[0].items():
873
+ if qoid and n == 'oid':
874
+ n = qoid
875
+ row[n] = value
876
+ return row
877
+
878
+ def update(self, table: str, row: dict[str, Any] | None = None, **kw : Any
879
+ ) -> dict[str, Any]:
880
+ """Update an existing row in a database table.
881
+
882
+ Similar to insert, but updates an existing row. The update is based
883
+ on the primary key of the table or the OID value as munged by get()
884
+ or passed as keyword. The OID will take precedence if provided, so
885
+ that it is possible to update the primary key itself.
886
+
887
+ The dictionary is then modified to reflect any changes caused by the
888
+ update due to triggers, rules, default values, etc.
889
+ """
890
+ if table.endswith('*'):
891
+ table = table[:-1].rstrip() # need parent table name
892
+ attnames = self.get_attnames(table)
893
+ generated = self.get_generated(table)
894
+ qoid = oid_key(table) if 'oid' in attnames else None
895
+ if row is None:
896
+ row = {}
897
+ elif 'oid' in row:
898
+ del row['oid'] # only accept oid key from named args for safety
899
+ row.update(kw)
900
+ if qoid and qoid in row and 'oid' not in row:
901
+ row['oid'] = row[qoid]
902
+ if qoid and 'oid' in row: # try using the oid
903
+ keynames: tuple[str, ...] = ('oid',)
904
+ keyset = set(keynames)
905
+ else: # try using the primary key
906
+ try:
907
+ keynames = self.pkeys(table)
908
+ except KeyError as e: # the table has no primary key
909
+ raise prg_error(f'Table {table} has no primary key') from e
910
+ keyset = set(keynames)
911
+ # check whether all key columns have values
912
+ if not keyset.issubset(row):
913
+ raise KeyError('Missing value for primary key in row')
914
+ params = self.adapter.parameter_list()
915
+ adapt = params.add
916
+ col = self.escape_identifier
917
+ where = ' AND '.join(
918
+ f'{col(k)} OPERATOR(pg_catalog.=) {adapt(row[k], attnames[k])}'
919
+ for k in keynames)
920
+ if 'oid' in row:
921
+ if qoid:
922
+ row[qoid] = row['oid']
923
+ del row['oid']
924
+ values_list = []
925
+ for n in attnames:
926
+ if n in row and n not in keyset and n not in generated:
927
+ values_list.append(f'{col(n)} = {adapt(row[n], attnames[n])}')
928
+ if not values_list:
929
+ return row
930
+ values = ', '.join(values_list)
931
+ ret = 'oid, *' if qoid else '*'
932
+ t = self._escape_qualified_name(table)
933
+ cmd = (f'UPDATE {t} SET {values}' # noqa: S608
934
+ f' WHERE {where} RETURNING {ret}')
935
+ self._do_debug(cmd, params)
936
+ query = self._valid_db.query(cmd, params)
937
+ res = query.dictresult()
938
+ if res: # may be empty when row does not exist
939
+ for n, value in res[0].items():
940
+ if qoid and n == 'oid':
941
+ n = qoid
942
+ row[n] = value
943
+ return row
944
+
945
+ def upsert(self, table: str, row: dict[str, Any] | None = None, **kw: Any
946
+ ) -> dict[str, Any]:
947
+ """Insert a row into a database table with conflict resolution.
948
+
949
+ This method inserts a row into a table, but instead of raising a
950
+ ProgrammingError exception in case a row with the same primary key
951
+ already exists, an update will be executed instead. This will be
952
+ performed as a single atomic operation on the database, so race
953
+ conditions can be avoided.
954
+
955
+ Like the insert method, the first parameter is the name of the
956
+ table and the second parameter can be used to pass the values to
957
+ be inserted as a dictionary.
958
+
959
+ Unlike the insert und update statement, keyword parameters are not
960
+ used to modify the dictionary, but to specify which columns shall
961
+ be updated in case of a conflict, and in which way:
962
+
963
+ A value of False or None means the column shall not be updated,
964
+ a value of True means the column shall be updated with the value
965
+ that has been proposed for insertion, i.e. has been passed as value
966
+ in the dictionary. Columns that are not specified by keywords but
967
+ appear as keys in the dictionary are also updated like in the case
968
+ keywords had been passed with the value True.
969
+
970
+ So if in the case of a conflict you want to update every column
971
+ that has been passed in the dictionary row, you would call
972
+ upsert(table, row). If you don't want to do anything in case
973
+ of a conflict, i.e. leave the existing row as it is, call
974
+ upsert(table, row, **dict.fromkeys(row)).
975
+
976
+ If you need more fine-grained control of what gets updated, you can
977
+ also pass strings in the keyword parameters. These strings will
978
+ be used as SQL expressions for the update columns. In these
979
+ expressions you can refer to the value that already exists in
980
+ the table by prefixing the column name with "included.", and to
981
+ the value that has been proposed for insertion by prefixing the
982
+ column name with the "excluded."
983
+
984
+ The dictionary is modified in any case to reflect the values in
985
+ the database after the operation has completed.
986
+
987
+ Note: The method uses the PostgreSQL "upsert" feature which is
988
+ only available since PostgreSQL 9.5.
989
+ """
990
+ if table.endswith('*'): # hint for descendant tables can be ignored
991
+ table = table[:-1].rstrip()
992
+ if row is None:
993
+ row = {}
994
+ if 'oid' in row:
995
+ del row['oid'] # do not insert oid
996
+ if 'oid' in kw:
997
+ del kw['oid'] # do not update oid
998
+ attnames = self.get_attnames(table)
999
+ generated = self.get_generated(table)
1000
+ qoid = oid_key(table) if 'oid' in attnames else None
1001
+ params = self.adapter.parameter_list()
1002
+ adapt = params.add
1003
+ col = self.escape_identifier
1004
+ name_list, value_list = [], []
1005
+ for n in attnames:
1006
+ if n in row and n not in generated:
1007
+ name_list.append(col(n))
1008
+ value_list.append(adapt(row[n], attnames[n]))
1009
+ names, values = ', '.join(name_list), ', '.join(value_list)
1010
+ try:
1011
+ keynames = self.pkeys(table)
1012
+ except KeyError as e:
1013
+ raise prg_error(f'Table {table} has no primary key') from e
1014
+ target = ', '.join(col(k) for k in keynames)
1015
+ update = []
1016
+ keyset = set(keynames)
1017
+ keyset.add('oid')
1018
+ for n in attnames:
1019
+ if n not in keyset and n not in generated:
1020
+ value = kw.get(n, n in row)
1021
+ if value:
1022
+ if not isinstance(value, str):
1023
+ value = f'excluded.{col(n)}'
1024
+ update.append(f'{col(n)} = {value}')
1025
+ if not values:
1026
+ return row
1027
+ do = 'update set ' + ', '.join(update) if update else 'nothing'
1028
+ ret = 'oid, *' if qoid else '*'
1029
+ t = self._escape_qualified_name(table)
1030
+ cmd = (f'INSERT INTO {t} AS included ({names})' # noqa: S608
1031
+ f' VALUES ({values})'
1032
+ f' ON CONFLICT ({target}) DO {do} RETURNING {ret}')
1033
+ self._do_debug(cmd, params)
1034
+ query = self._valid_db.query(cmd, params)
1035
+ res = query.dictresult()
1036
+ if res: # may be empty with "do nothing"
1037
+ for n, value in res[0].items():
1038
+ if qoid and n == 'oid':
1039
+ n = qoid
1040
+ row[n] = value
1041
+ else:
1042
+ self.get(table, row)
1043
+ return row
1044
+
1045
+ def clear(self, table: str, row: dict[str, Any] | None = None
1046
+ ) -> dict[str, Any]:
1047
+ """Clear all the attributes to values determined by the types.
1048
+
1049
+ Numeric types are set to 0, Booleans are set to false, and everything
1050
+ else is set to the empty string. If the row argument is present,
1051
+ it is used as the row dictionary and any entries matching attribute
1052
+ names are cleared with everything else left unchanged.
1053
+ """
1054
+ # At some point we will need a way to get defaults from a table.
1055
+ if row is None:
1056
+ row = {} # empty if argument is not present
1057
+ attnames = self.get_attnames(table)
1058
+ for n, t in attnames.items():
1059
+ if n == 'oid':
1060
+ continue
1061
+ t = t.simple
1062
+ if t in DbTypes._num_types:
1063
+ row[n] = 0
1064
+ elif t == 'bool':
1065
+ row[n] = self._make_bool(False)
1066
+ else:
1067
+ row[n] = ''
1068
+ return row
1069
+
1070
+ def delete(self, table: str, row: dict[str, Any] | None = None, **kw: Any
1071
+ ) -> int:
1072
+ """Delete an existing row in a database table.
1073
+
1074
+ This method deletes the row from a table. It deletes based on the
1075
+ primary key of the table or the OID value as munged by get() or
1076
+ passed as keyword. The OID will take precedence if provided.
1077
+
1078
+ The return value is the number of deleted rows (i.e. 0 if the row
1079
+ did not exist and 1 if the row was deleted).
1080
+
1081
+ Note that if the row cannot be deleted because e.g. it is still
1082
+ referenced by another table, this method raises a ProgrammingError.
1083
+ """
1084
+ if table.endswith('*'): # hint for descendant tables can be ignored
1085
+ table = table[:-1].rstrip()
1086
+ attnames = self.get_attnames(table)
1087
+ qoid = oid_key(table) if 'oid' in attnames else None
1088
+ if row is None:
1089
+ row = {}
1090
+ elif 'oid' in row:
1091
+ del row['oid'] # only accept oid key from named args for safety
1092
+ row.update(kw)
1093
+ if qoid and qoid in row and 'oid' not in row:
1094
+ row['oid'] = row[qoid]
1095
+ if qoid and 'oid' in row: # try using the oid
1096
+ keynames: tuple[str, ...] = ('oid',)
1097
+ else: # try using the primary key
1098
+ try:
1099
+ keynames = self.pkeys(table)
1100
+ except KeyError as e: # the table has no primary key
1101
+ raise prg_error(f'Table {table} has no primary key') from e
1102
+ # check whether all key columns have values
1103
+ if not set(keynames).issubset(row):
1104
+ raise KeyError('Missing value for primary key in row')
1105
+ params = self.adapter.parameter_list()
1106
+ adapt = params.add
1107
+ col = self.escape_identifier
1108
+ where = ' AND '.join(
1109
+ f'{col(k)} OPERATOR(pg_catalog.=) {adapt(row[k], attnames[k])}'
1110
+ for k in keynames)
1111
+ if 'oid' in row:
1112
+ if qoid:
1113
+ row[qoid] = row['oid']
1114
+ del row['oid']
1115
+ t = self._escape_qualified_name(table)
1116
+ cmd = f'DELETE FROM {t} WHERE {where}' # noqa: S608
1117
+ self._do_debug(cmd, params)
1118
+ res = self._valid_db.query(cmd, params)
1119
+ return int(res) # type: ignore
1120
+
1121
+ def truncate(self, table: str | list[str] | tuple[str, ...] |
1122
+ set[str] | frozenset[str], restart: bool = False,
1123
+ cascade: bool = False, only: bool = False) -> Query:
1124
+ """Empty a table or set of tables.
1125
+
1126
+ This method quickly removes all rows from the given table or set
1127
+ of tables. It has the same effect as an unqualified DELETE on each
1128
+ table, but since it does not actually scan the tables it is faster.
1129
+ Furthermore, it reclaims disk space immediately, rather than requiring
1130
+ a subsequent VACUUM operation. This is most useful on large tables.
1131
+
1132
+ If restart is set to True, sequences owned by columns of the truncated
1133
+ table(s) are automatically restarted. If cascade is set to True, it
1134
+ also truncates all tables that have foreign-key references to any of
1135
+ the named tables. If the parameter 'only' is not set to True, all the
1136
+ descendant tables (if any) will also be truncated. Optionally, a '*'
1137
+ can be specified after the table name to explicitly indicate that
1138
+ descendant tables are included.
1139
+ """
1140
+ if isinstance(table, str):
1141
+ table_only = {table: only}
1142
+ table = [table]
1143
+ elif isinstance(table, (list, tuple)):
1144
+ if isinstance(only, (list, tuple)):
1145
+ table_only = dict(zip(table, only))
1146
+ else:
1147
+ table_only = dict.fromkeys(table, only)
1148
+ elif isinstance(table, (set, frozenset)):
1149
+ table_only = dict.fromkeys(table, only)
1150
+ else:
1151
+ raise TypeError('The table must be a string, list or set')
1152
+ if not (restart is None or isinstance(restart, (bool, int))):
1153
+ raise TypeError('Invalid type for the restart option')
1154
+ if not (cascade is None or isinstance(cascade, (bool, int))):
1155
+ raise TypeError('Invalid type for the cascade option')
1156
+ tables = []
1157
+ for t in table:
1158
+ u = table_only.get(t)
1159
+ if not (u is None or isinstance(u, (bool, int))):
1160
+ raise TypeError('Invalid type for the only option')
1161
+ if t.endswith('*'):
1162
+ if u:
1163
+ raise ValueError(
1164
+ 'Contradictory table name and only options')
1165
+ t = t[:-1].rstrip()
1166
+ t = self._escape_qualified_name(t)
1167
+ if u:
1168
+ t = f'ONLY {t}'
1169
+ tables.append(t)
1170
+ cmd_parts = ['TRUNCATE', ', '.join(tables)]
1171
+ if restart:
1172
+ cmd_parts.append('RESTART IDENTITY')
1173
+ if cascade:
1174
+ cmd_parts.append('CASCADE')
1175
+ cmd = ' '.join(cmd_parts)
1176
+ self._do_debug(cmd)
1177
+ return self._valid_db.query(cmd)
1178
+
1179
+ def get_as_list(
1180
+ self, table: str,
1181
+ what: str | list[str] | tuple[str, ...] | None = None,
1182
+ where: str | list[str] | tuple[str, ...] | None = None,
1183
+ order: str | list[str] | tuple[str, ...] | bool | None = None,
1184
+ limit: int | None = None, offset: int | None = None,
1185
+ scalar: bool = False) -> list:
1186
+ """Get a table as a list.
1187
+
1188
+ This gets a convenient representation of the table as a list
1189
+ of named tuples in Python. You only need to pass the name of
1190
+ the table (or any other SQL expression returning rows). Note that
1191
+ by default this will return the full content of the table which
1192
+ can be huge and overflow your memory. However, you can control
1193
+ the amount of data returned using the other optional parameters.
1194
+
1195
+ The parameter 'what' can restrict the query to only return a
1196
+ subset of the table columns. It can be a string, list or a tuple.
1197
+
1198
+ The parameter 'where' can restrict the query to only return a
1199
+ subset of the table rows. It can be a string, list or a tuple
1200
+ of SQL expressions that all need to be fulfilled.
1201
+
1202
+ The parameter 'order' specifies the ordering of the rows. It can
1203
+ also be a string, list or a tuple. If no ordering is specified,
1204
+ the result will be ordered by the primary key(s) or all columns if
1205
+ no primary key exists. You can set 'order' to False if you don't
1206
+ care about the ordering. The parameters 'limit' and 'offset' can be
1207
+ integers specifying the maximum number of rows returned and a number
1208
+ of rows skipped over.
1209
+
1210
+ If you set the 'scalar' option to True, then instead of the
1211
+ named tuples you will get the first items of these tuples.
1212
+ This is useful if the result has only one column anyway.
1213
+ """
1214
+ if not table:
1215
+ raise TypeError('The table name is missing')
1216
+ if what:
1217
+ if isinstance(what, (list, tuple)):
1218
+ what = ', '.join(map(str, what))
1219
+ if order is None:
1220
+ order = what
1221
+ else:
1222
+ what = '*'
1223
+ cmd_parts = ['SELECT', what, 'FROM', table]
1224
+ if where:
1225
+ if isinstance(where, (list, tuple)):
1226
+ where = ' AND '.join(map(str, where))
1227
+ cmd_parts.extend(['WHERE', where])
1228
+ if order is None or order is True:
1229
+ try:
1230
+ order = self.pkeys(table)
1231
+ except (KeyError, ProgrammingError):
1232
+ with suppress(KeyError, ProgrammingError):
1233
+ order = list(self.get_attnames(table))
1234
+ if order and not isinstance(order, bool):
1235
+ if isinstance(order, (list, tuple)):
1236
+ order = ', '.join(map(str, order))
1237
+ cmd_parts.extend(['ORDER BY', order])
1238
+ if limit:
1239
+ cmd_parts.append(f'LIMIT {limit}')
1240
+ if offset:
1241
+ cmd_parts.append(f'OFFSET {offset}')
1242
+ cmd = ' '.join(cmd_parts)
1243
+ self._do_debug(cmd)
1244
+ query = self._valid_db.query(cmd)
1245
+ res = query.namedresult()
1246
+ if res and scalar:
1247
+ res = [row[0] for row in res]
1248
+ return res
1249
+
1250
+ def get_as_dict(
1251
+ self, table: str,
1252
+ keyname: str | list[str] | tuple[str, ...] | None = None,
1253
+ what: str | list[str] | tuple[str, ...] | None = None,
1254
+ where: str | list[str] | tuple[str, ...] | None = None,
1255
+ order: str | list[str] | tuple[str, ...] | bool | None = None,
1256
+ limit: int | None = None, offset: int | None = None,
1257
+ scalar: bool = False) -> dict:
1258
+ """Get a table as a dictionary.
1259
+
1260
+ This method is similar to get_as_list(), but returns the table
1261
+ as a Python dict instead of a Python list, which can be even
1262
+ more convenient. The primary key column(s) of the table will
1263
+ be used as the keys of the dictionary, while the other column(s)
1264
+ will be the corresponding values. The keys will be named tuples
1265
+ if the table has a composite primary key. The rows will be also
1266
+ named tuples unless the 'scalar' option has been set to True.
1267
+ With the optional parameter 'keyname' you can specify an alternative
1268
+ set of columns to be used as the keys of the dictionary. It must
1269
+ be set as a string, list or a tuple.
1270
+
1271
+ The dictionary will be ordered using the order specified with the
1272
+ 'order' parameter or the key column(s) if not specified. You can
1273
+ set 'order' to False if you don't care about the ordering.
1274
+ """
1275
+ if not table:
1276
+ raise TypeError('The table name is missing')
1277
+ if not keyname:
1278
+ try:
1279
+ keyname = self.pkeys(table)
1280
+ except (KeyError, ProgrammingError) as e:
1281
+ raise prg_error(f'Table {table} has no primary key') from e
1282
+ if isinstance(keyname, str):
1283
+ keynames: list[str] | tuple[str, ...] = (keyname,)
1284
+ elif isinstance(keyname, (list, tuple)):
1285
+ keynames = keyname
1286
+ else:
1287
+ raise KeyError('The keyname must be a string, list or tuple')
1288
+ if what:
1289
+ if isinstance(what, (list, tuple)):
1290
+ what = ', '.join(map(str, what))
1291
+ if order is None:
1292
+ order = what
1293
+ else:
1294
+ what = '*'
1295
+ cmd_parts = ['SELECT', what, 'FROM', table]
1296
+ if where:
1297
+ if isinstance(where, (list, tuple)):
1298
+ where = ' AND '.join(map(str, where))
1299
+ cmd_parts.extend(['WHERE', where])
1300
+ if order is None or order is True:
1301
+ order = keyname
1302
+ if order and not isinstance(order, bool):
1303
+ if isinstance(order, (list, tuple)):
1304
+ order = ', '.join(map(str, order))
1305
+ cmd_parts.extend(['ORDER BY', order])
1306
+ if limit:
1307
+ cmd_parts.append(f'LIMIT {limit}')
1308
+ if offset:
1309
+ cmd_parts.append(f'OFFSET {offset}')
1310
+ cmd = ' '.join(cmd_parts)
1311
+ self._do_debug(cmd)
1312
+ query = self._valid_db.query(cmd)
1313
+ res = query.getresult()
1314
+ if not res:
1315
+ return {}
1316
+ keyset = set(keynames)
1317
+ fields = query.listfields()
1318
+ if not keyset.issubset(fields):
1319
+ raise KeyError('Missing keyname in row')
1320
+ key_index: list[int] = []
1321
+ row_index: list[int] = []
1322
+ for i, f in enumerate(fields):
1323
+ (key_index if f in keyset else row_index).append(i)
1324
+ key_tuple = len(key_index) > 1
1325
+ get_key = itemgetter(*key_index)
1326
+ keys = map(get_key, res)
1327
+ if scalar:
1328
+ row_index = row_index[:1]
1329
+ row_is_tuple = False
1330
+ else:
1331
+ row_is_tuple = len(row_index) > 1
1332
+ if scalar or row_is_tuple:
1333
+ get_row: Callable[[tuple], tuple] = itemgetter( # pyright: ignore
1334
+ *row_index)
1335
+ else:
1336
+ frst_index = row_index[0]
1337
+
1338
+ def get_row(row : tuple) -> tuple:
1339
+ return row[frst_index], # tuple with one item
1340
+
1341
+ row_is_tuple = True
1342
+ rows = map(get_row, res)
1343
+ if key_tuple or row_is_tuple:
1344
+ if key_tuple:
1345
+ keys = namediter(_MemoryQuery(keys, keynames)) # type: ignore
1346
+ if row_is_tuple:
1347
+ fields = tuple(f for f in fields if f not in keyset)
1348
+ rows = namediter(_MemoryQuery(rows, fields)) # type: ignore
1349
+ # noinspection PyArgumentList
1350
+ return dict(zip(keys, rows))
1351
+
1352
+ def notification_handler(self, event: str, callback: Callable,
1353
+ arg_dict: dict | None = None,
1354
+ timeout: int | float | None = None,
1355
+ stop_event: str | None = None
1356
+ ) -> NotificationHandler:
1357
+ """Get notification handler that will run the given callback."""
1358
+ return NotificationHandler(self, event, callback,
1359
+ arg_dict, timeout, stop_event)
1360
+
1361
+ # immediately wrapped methods
1362
+
1363
+ def send_query(self, cmd: str, args: Sequence | None = None) -> Query:
1364
+ """Create a new asynchronous query object for this connection."""
1365
+ if args is None:
1366
+ return self._valid_db.send_query(cmd)
1367
+ return self._valid_db.send_query(cmd, args)
1368
+
1369
+ def poll(self) -> int:
1370
+ """Complete an asynchronous connection and get its state."""
1371
+ return self._valid_db.poll()
1372
+
1373
+ def cancel(self) -> None:
1374
+ """Abandon processing of current SQL command."""
1375
+ self._valid_db.cancel()
1376
+
1377
+ def fileno(self) -> int:
1378
+ """Get the socket used to connect to the database."""
1379
+ return self._valid_db.fileno()
1380
+
1381
+ def get_cast_hook(self) -> Callable | None:
1382
+ """Get the function that handles all external typecasting."""
1383
+ return self._valid_db.get_cast_hook()
1384
+
1385
+ def set_cast_hook(self, hook: Callable | None) -> None:
1386
+ """Set a function that will handle all external typecasting."""
1387
+ self._valid_db.set_cast_hook(hook)
1388
+
1389
+ def get_notice_receiver(self) -> Callable | None:
1390
+ """Get the current notice receiver."""
1391
+ return self._valid_db.get_notice_receiver()
1392
+
1393
+ def set_notice_receiver(self, receiver: Callable | None) -> None:
1394
+ """Set a custom notice receiver."""
1395
+ self._valid_db.set_notice_receiver(receiver)
1396
+
1397
+ def getnotify(self) -> tuple[str, int, str] | None:
1398
+ """Get the last notify from the server."""
1399
+ return self._valid_db.getnotify()
1400
+
1401
+ def inserttable(self, table: str, values: Sequence[list|tuple],
1402
+ columns: list[str] | tuple[str, ...] | None = None) -> int:
1403
+ """Insert a Python iterable into a database table."""
1404
+ if columns is None:
1405
+ return self._valid_db.inserttable(table, values)
1406
+ return self._valid_db.inserttable(table, values, columns)
1407
+
1408
+ def transaction(self) -> int:
1409
+ """Get the current in-transaction status of the server.
1410
+
1411
+ The status returned by this method can be TRANS_IDLE (currently idle),
1412
+ TRANS_ACTIVE (a command is in progress), TRANS_INTRANS (idle, in a
1413
+ valid transaction block), or TRANS_INERROR (idle, in a failed
1414
+ transaction block). TRANS_UNKNOWN is reported if the connection is
1415
+ bad. The status TRANS_ACTIVE is reported only when a query has been
1416
+ sent to the server and not yet completed.
1417
+ """
1418
+ return self._valid_db.transaction()
1419
+
1420
+ def parameter(self, name: str) -> str | None:
1421
+ """Look up a current parameter setting of the server."""
1422
+ return self._valid_db.parameter(name)
1423
+
1424
+
1425
+ def date_format(self) -> str:
1426
+ """Look up the date format currently being used by the database."""
1427
+ return self._valid_db.date_format()
1428
+
1429
+ def escape_literal(self, s: AnyStr) -> AnyStr:
1430
+ """Escape a literal constant for use within SQL."""
1431
+ return self._valid_db.escape_literal(s)
1432
+
1433
+ def escape_identifier(self, s: AnyStr) -> AnyStr:
1434
+ """Escape an identifier for use within SQL."""
1435
+ return self._valid_db.escape_identifier(s)
1436
+
1437
+ def escape_string(self, s: AnyStr) -> AnyStr:
1438
+ """Escape a string for use within SQL."""
1439
+ return self._valid_db.escape_string(s)
1440
+
1441
+ def escape_bytea(self, s: AnyStr) -> AnyStr:
1442
+ """Escape binary data for use within SQL as type 'bytea'."""
1443
+ return self._valid_db.escape_bytea(s)
1444
+
1445
+ def putline(self, line: str) -> None:
1446
+ """Write a line to the server socket."""
1447
+ self._valid_db.putline(line)
1448
+
1449
+ def getline(self) -> str:
1450
+ """Get a line from server socket."""
1451
+ return self._valid_db.getline()
1452
+
1453
+ def endcopy(self) -> None:
1454
+ """Synchronize client and server."""
1455
+ self._valid_db.endcopy()
1456
+
1457
+ def set_non_blocking(self, nb: bool) -> None:
1458
+ """Set the non-blocking mode of the connection."""
1459
+ self._valid_db.set_non_blocking(nb)
1460
+
1461
+ def is_non_blocking(self) -> bool:
1462
+ """Get the non-blocking mode of the connection."""
1463
+ return self._valid_db.is_non_blocking()
1464
+
1465
+ def locreate(self, mode: int) -> LargeObject:
1466
+ """Create a large object in the database.
1467
+
1468
+ The valid values for 'mode' parameter are defined as the module level
1469
+ constants INV_READ and INV_WRITE.
1470
+ """
1471
+ return self._valid_db.locreate(mode)
1472
+
1473
+ def getlo(self, oid: int) -> LargeObject:
1474
+ """Build a large object from given oid."""
1475
+ return self._valid_db.getlo(oid)
1476
+
1477
+ def loimport(self, filename: str) -> LargeObject:
1478
+ """Import a file to a large object."""
1479
+ return self._valid_db.loimport(filename)
1480
+
1481
+
1482
+ class _MemoryQuery:
1483
+ """Class that embodies a given query result."""
1484
+
1485
+ result: Any
1486
+ fields: tuple[str, ...]
1487
+
1488
+ def __init__(self, result: Any, fields: Sequence[str]) -> None:
1489
+ """Create query from given result rows and field names."""
1490
+ self.result = result
1491
+ self.fields = tuple(fields)
1492
+
1493
+ def listfields(self) -> tuple[str, ...]:
1494
+ """Return the stored field names of this query."""
1495
+ return self.fields
1496
+
1497
+ def getresult(self) -> Any:
1498
+ """Return the stored result of this query."""
1499
+ return self.result
1500
+
1501
+ def __iter__(self) -> Iterator[Any]:
1502
+ return iter(self.result)