-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathapi.py
More file actions
1422 lines (1168 loc) · 36 KB
/
api.py
File metadata and controls
1422 lines (1168 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##
# copyright 2009, James William Pye
# http://python.projects.postgresql.org
##
"""
Application Programmer Interface specifications for PostgreSQL (ABCs).
PG-API
======
``postgresql.api`` is a Python API for the PostgreSQL DBMS. It is designed to take
full advantage of PostgreSQL's features to provide the Python programmer with
substantial convenience.
This module is used to define PG-API. It creates a set of ABCs
that makes up the basic interfaces used to work with a PostgreSQL server.
"""
import os
import sys
import warnings
import collections
from abc import abstractproperty, abstractmethod
from operator import itemgetter
from . import sys as pg_sys
from .python.element import Element, prime_factor
from .python.doc import Doc
from .python.decorlib import propertydoc
__all__ = [
'Message',
'PreparedStatement',
'Chunks',
'Rows',
'Cursor',
'Connector',
'Category',
'Database',
'Connection',
'Transaction',
'Settings',
'StoredProcedure',
'Driver',
'Installation',
'Cluster',
]
class Message(Element):
"""
A message emitted by PostgreSQL. This element is universal, so
`postgresql.api.Message` is a complete implementation for representing a
message. Any interface should produce these objects.
"""
_e_label = property(lambda x: getattr(x, 'details').get('severity', 'MESSAGE'))
_e_factors = ('creator',)
severities = (
'DEBUG',
'INFO',
'NOTICE',
'WARNING',
'ERROR',
'FATAL',
'PANIC',
)
sources = (
'SERVER',
'CLIENT',
)
# What generated the message?
source = 'SERVER'
code = "00000"
message = None
details = None
def __init__(self,
message : "The primary information of the message",
code : "Message code to attach (SQL state)" = None,
details : "additional information associated with the message" = {},
source : "Which side generated the message(SERVER, CLIENT)" = None,
creator : "The interface element that called for instantiation" = None,
):
self.message = message
self.details = details
self.creator = creator
if code is not None and self.code != code:
self.code = code
if source is not None and self.source != source:
self.source = source
def __repr__(self):
return "{mod}.{typname}({message!r}{code}{details}{source}{creator})".format(
mod = self.__module__,
typname = self.__class__.__name__,
message = self.message,
code = (
"" if self.code == type(self).code
else ", code = " + repr(self.code)
),
details = (
"" if not self.details
else ", details = " + repr(self.details)
),
source = (
"" if self.source is None
else ", source = " + repr(self.source)
),
creator = (
"" if self.creator is None
else ", creator = " + repr(self.creator)
)
)
@property
def location_string(self):
details = self.details
loc = [
details.get(k, '?') for k in ('file', 'line', 'function')
]
return (
"" if loc == ['?', '?', '?']
else "File {0!r}, "\
"line {1!s}, in {2!s}".format(*loc)
)
# keys to filter in .details
standard_detail_coverage = frozenset(['message', 'severity', 'file', 'function', 'line',])
def _e_metas(self):
yield (None, self.message)
if self.code and self.code != "00000":
yield ('CODE', self.code)
locstr = self.location_string
if locstr:
yield ('LOCATION', locstr + ' from ' + self.source)
else:
yield ('LOCATION', self.source)
for k, v in sorted(self.details.items(), key = itemgetter(0)):
if k not in self.standard_detail_coverage:
yield (k.upper(), str(v))
def raise_message(self, starting_point = None):
"""
Take the given message object and hand it to all the primary
factors(creator) with a msghook callable.
"""
if starting_point is not None:
f = starting_point
else:
f = self.creator
while f is not None:
if getattr(f, 'msghook', None) is not None:
if f.msghook(self):
# the trap returned a nonzero value,
# so don't continue raising. (like with's __exit__)
return f
f = prime_factor(f)
if f:
f = f[1]
# if the next primary factor is without a raise or does not exist,
# send the message to postgresql.sys.msghook
pg_sys.msghook(self)
class Result(Element):
"""
A result is an object managing the results of a prepared statement.
These objects represent a binding of parameters to a given statement object.
For results that were constructed on the server and a reference passed back
to the client, statement and parameters may be None.
"""
_e_label = 'RESULT'
_e_factors = ('statement', 'parameters', 'cursor_id')
@abstractmethod
def close(self) -> None:
"""
Close the Result handle.
"""
@propertydoc
@abstractproperty
def cursor_id(self) -> str:
"""
The cursor's identifier.
"""
@propertydoc
@abstractproperty
def sql_column_types(self) -> [str]:
"""
The type of the columns produced by the cursor.
A sequence of `str` objects stating the SQL type name::
['INTEGER', 'CHARACTER VARYING', 'INTERVAL']
"""
@propertydoc
@abstractproperty
def pg_column_types(self) -> [int]:
"""
The type Oids of the columns produced by the cursor.
A sequence of `int` objects stating the SQL type name::
[27, 28]
"""
@propertydoc
@abstractproperty
def column_names(self) -> [str]:
"""
The attribute names of the columns produced by the cursor.
A sequence of `str` objects stating the column name::
['column1', 'column2', 'emp_name']
"""
@propertydoc
@abstractproperty
def column_types(self) -> [str]:
"""
The Python types of the columns produced by the cursor.
A sequence of type objects::
[<class 'int'>, <class 'str'>]
"""
@propertydoc
@abstractproperty
def parameters(self) -> (tuple, None):
"""
The parameters bound to the cursor. `None`, if unknown and an empty tuple
`()`, if no parameters were given.
These should be the *original* parameters given to the invoked statement.
This should only be `None` when the cursor is created from an identifier,
`postgresql.api.Database.cursor_from_id`.
"""
@propertydoc
@abstractproperty
def statement(self) -> ("PreparedStatement", None):
"""
The query object used to create the cursor. `None`, if unknown.
This should only be `None` when the cursor is created from an identifier,
`postgresql.api.Database.cursor_from_id`.
"""
class Chunks(
Result,
collections.Iterator,
collections.Iterable,
):
pass
class Cursor(
Result,
collections.Iterator,
collections.Iterable,
):
"""
A `Cursor` object is an interface to a sequence of tuples(rows). A result
set. Cursors publish a file-like interface for reading tuples from a cursor
declared on the database.
`Cursor` objects are created by invoking the `PreparedStatement.declare`
method or by opening a cursor using an identifier via the
`Database.cursor_from_id` method.
"""
_e_label = 'CURSOR'
_seek_whence_map = {
0 : 'ABSOLUTE',
1 : 'RELATIVE',
2 : 'FROM_END',
}
_direction_map = {
True : 'FORWARD',
False : 'BACKWARD',
}
@abstractmethod
def clone(self) -> "Cursor":
"""
Create a new cursor using the same factors as `self`.
"""
def __iter__(self):
return self
@propertydoc
@abstractproperty
def direction(self) -> bool:
"""
The default `direction` argument for read().
When `True` reads are FORWARD.
When `False` reads are BACKWARD.
Cursor operation option.
"""
@abstractmethod
def read(self,
quantity : "Number of rows to read" = None,
direction : "Direction to fetch in, defaults to `self.direction`" = None,
) -> ["Row"]:
"""
Read, fetch, the specified number of rows and return them in a list.
If quantity is `None`, all records will be fetched.
`direction` can be used to override the default configured direction.
This alters the cursor's position.
Read does not directly correlate to FETCH. If zero is given as the
quantity, an empty sequence *must* be returned.
"""
@abstractmethod
def __next__(self) -> "Row":
"""
Get the next tuple in the cursor.
Advances the cursor position by one.
"""
@abstractmethod
def seek(self, offset, whence = 'ABSOLUTE'):
"""
Set the cursor's position to the given offset with respect to the
whence parameter and the configured direction.
Whence values:
``0`` or ``"ABSOLUTE"``
Absolute.
``1`` or ``"RELATIVE"``
Relative.
``2`` or ``"FROM_END"``
Absolute from end.
Direction effects whence. If direction is BACKWARD, ABSOLUTE positioning
will effectively be FROM_END, RELATIVE's position will be negated, and
FROM_END will effectively be ABSOLUTE.
"""
class PreparedStatement(
Element,
collections.Callable,
collections.Iterable,
):
"""
Instances of `PreparedStatement` are returned by the `prepare` method of
`Database` instances.
A PreparedStatement is an Iterable as well as Callable. This feature is
supported for queries that have the default arguments filled in or take no
arguments at all. It allows for things like:
>>> for x in db.prepare('select * FROM table'):
... pass
"""
_e_label = 'STATEMENT'
_e_factors = ('database', 'statement_id', 'string',)
@propertydoc
@abstractproperty
def statement_id(self) -> str:
"""
The statment's identifier.
"""
@propertydoc
@abstractproperty
def string(self) -> object:
"""
The SQL string of the prepared statement.
`None` if not available. This can happen in cases where a statement is
prepared on the server and a reference to the statement is sent to the
client which subsequently uses the statement via the `Database`'s
`statement` constructor.
"""
@propertydoc
@abstractproperty
def sql_parameter_types(self) -> [str]:
"""
The type of the parameters required by the statement.
A sequence of `str` objects stating the SQL type name::
['INTEGER', 'VARCHAR', 'INTERVAL']
"""
@propertydoc
@abstractproperty
def sql_column_types(self) -> [str]:
"""
The type of the columns produced by the statement.
A sequence of `str` objects stating the SQL type name::
['INTEGER', 'VARCHAR', 'INTERVAL']
"""
@propertydoc
@abstractproperty
def pg_parameter_types(self) -> [int]:
"""
The type Oids of the parameters required by the statement.
A sequence of `int` objects stating the PostgreSQL type Oid::
[27, 28]
"""
@propertydoc
@abstractproperty
def pg_column_types(self) -> [int]:
"""
The type Oids of the columns produced by the statement.
A sequence of `int` objects stating the SQL type name::
[27, 28]
"""
@propertydoc
@abstractproperty
def column_names(self) -> [str]:
"""
The attribute names of the columns produced by the statement.
A sequence of `str` objects stating the column name::
['column1', 'column2', 'emp_name']
"""
@propertydoc
@abstractproperty
def column_types(self) -> [type]:
"""
The Python types of the columns produced by the statement.
A sequence of type objects::
[<class 'int'>, <class 'str'>]
"""
@propertydoc
@abstractproperty
def parameter_types(self) -> [type]:
"""
The Python types expected of parameters given to the statement.
A sequence of type objects::
[<class 'int'>, <class 'str'>]
"""
@abstractmethod
def clone(self) -> "PreparedStatement":
"""
Create a new statement object using the same factors as `self`.
When used for refreshing plans, the new clone should replace references to
the original.
"""
@abstractmethod
def __call__(self, *parameters : "Positional Parameters") -> ["Row"]:
"""
Execute the prepared statement with the given arguments as parameters.
Usage:
>>> p=db.prepare("SELECT column FROM ttable WHERE key = $1")
>>> p('identifier')
[...]
"""
@abstractmethod
def rows(self, *parameters) -> collections.Iterable:
"""
Return an iterator producing rows produced by the cursor
created from the statement bound with the given parameters.
Row iterators are never scrollable.
Supporting cursors will be WITH HOLD when outside of a transaction.
`rows` is designed for the situations involving large data sets.
Each iteration returns a single row. Arguably, best implemented:
return itertools.chain.from_iterable(self.chunks(*parameters))
"""
@abstractmethod
def chunks(self, *parameters) -> collections.Iterable:
"""
Return an iterator producing sequences of rows produced by the cursor
created from the statement bound with the given parameters.
Chunking iterators are *never* scrollable.
Supporting cursors will be WITH HOLD when outside of a transaction.
`chunks` is designed for the situations involving large data sets.
Each iteration returns sequences of rows *normally* of length(seq) ==
chunksize. If chunksize is unspecified, a default, positive integer will
be filled in.
"""
@abstractmethod
def declare(self, *parameters) -> Cursor:
"""
Return a scrollable cursor with hold using the statement bound with the
given parameters.
"""
@abstractmethod
def first(self, *parameters) -> "'First' object that is returned by the query":
"""
Execute the prepared statement with the given arguments as parameters.
If the statement returns rows with multiple columns, return the first
row. If the statement returns rows with a single column, return the
first column in the first row. If the query does not return rows at all,
return the count or `None` if no count exists in the completion message.
Usage:
>>> db.prepare("SELECT * FROM ttable WHERE key = $1").first("somekey")
('somekey', 'somevalue')
>>> db.prepare("SELECT 'foo'").first()
'foo'
>>> db.prepare("INSERT INTO atable (col) VALUES (1)").first()
1
"""
@abstractmethod
def load_rows(self,
iterable : "A iterable of tuples to execute the statement with"
):
"""
Given an iterable, `iterable`, feed the produced parameters to the
query. This is a bulk-loading interface for parameterized queries.
Effectively, it is equivalent to:
>>> q = db.prepare(sql)
>>> for i in iterable:
... q(*i)
Its purpose is to allow the implementation to take advantage of the
knowledge that a series of parameters are to be loaded so that the
operation can be optimized.
"""
@abstractmethod
def load_chunks(self,
iterable : "A iterable of chunks of tuples to execute the statement with"
):
"""
Given an iterable, `iterable`, feed the produced parameters of the chunks
produced by the iterable to the query. This is a bulk-loading interface
for parameterized queries.
Effectively, it is equivalent to:
>>> ps = db.prepare(...)
>>> for c in iterable:
... for i in c:
... q(*i)
Its purpose is to allow the implementation to take advantage of the
knowledge that a series of chunks of parameters are to be loaded so
that the operation can be optimized.
"""
@abstractmethod
def close(self) -> None:
"""
Close the prepared statement releasing resources associated with it.
"""
class StoredProcedure(
Element,
collections.Callable,
):
"""
A function stored on the database.
"""
_e_label = 'FUNCTION'
_e_factors = ('database',)
@abstractmethod
def __call__(self, *args, **kw) -> (object, Cursor, collections.Iterable):
"""
Execute the procedure with the given arguments. If keyword arguments are
passed they must be mapped to the argument whose name matches the key.
If any positional arguments are given, they must fill in gaps created by
the stated keyword arguments. If too few or too many arguments are
given, a TypeError must be raised. If a keyword argument is passed where
the procedure does not have a corresponding argument name, then,
likewise, a TypeError must be raised.
In the case where the `StoredProcedure` references a set returning
function(SRF), the result *must* be an iterable. SRFs that return single
columns *must* return an iterable of that column; not row data. If the
SRF returns a composite(OUT parameters), it *should* return a `Cursor`.
"""
##
# Arguably, it would be wiser to isolate blocks, prepared transactions, and
# savepoints, but the utility of the separation is not significant. It's really
# more interesting as a formality that the user may explicitly state the
# type of the transaction. However, this capability is not completely absent
# from the current interface as the configuration parameters, or lack thereof,
# help imply the expectations.
class Transaction(Element):
"""
A `Tranaction` is an element that represents a transaction in the session.
Once created, it's ready to be started, and subsequently committed or
rolled back.
Read-only transaction:
>>> with db.xact(mode = 'read only'):
... ...
Read committed isolation:
>>> with db.xact(isolation = 'READ COMMITTED'):
... ...
Savepoints are created if inside a transaction block:
>>> with db.xact():
... with db.xact():
... ...
[DEPRECATED]
Or, in cases where two-phase commit is desired:
>>> with db.xact(gid = 'gid') as gxact:
... with gxact:
... # phase 1 block
... ...
>>> # fully committed at this point
Considering that transactions decide what's saved and what's not saved, it is
important that they are used properly. In most situations, when an action is
performed where state of the transaction is unexpected, an exception should
occur.
"""
_e_label = 'XACT'
_e_factors = ('database',)
@propertydoc
@abstractproperty
def mode(self) -> (None, str):
"""
The mode of the transaction block:
START TRANSACTION [ISOLATION] <mode>;
The `mode` property is a string and will be directly interpolated into the
START TRANSACTION statement.
"""
@propertydoc
@abstractproperty
def isolation(self) -> (None, str):
"""
The isolation level of the transaction block:
START TRANSACTION <isolation> [MODE];
The `isolation` property is a string and will be directly interpolated into
the START TRANSACTION statement.
"""
@propertydoc
@abstractproperty
def gid(self) -> (None, str):
"""
[DEPRECATED]
The global identifier of the transaction block:
PREPARE TRANSACTION <gid>;
The `gid` property is a string that indicates that the block is a prepared
transaction.
"""
@abstractmethod
def start(self) -> None:
"""
Start the transaction.
If the database is in a transaction block, the transaction should be
configured as a savepoint. If any transaction block configuration was
applied to the transaction, raise a `postgresql.exceptions.OperationError`.
If the database is not in a transaction block, start one using the
configuration where:
`self.isolation` specifies the ``ISOLATION LEVEL``. Normally, ``READ
COMMITTED``, ``SERIALIZABLE``, or ``READ UNCOMMITTED``.
`self.mode` specifies the mode of the transaction. Normally, ``READ
ONLY`` or ``READ WRITE``.
If the transaction is open--started or prepared, do nothing.
If the transaction has been committed or aborted, raise an
`postgresql.exceptions.OperationError`.
"""
begin = start
@abstractmethod
def commit(self) -> None:
"""
Commit the transaction.
If the transaction is configured with a `gid` issue a COMMIT PREPARED
statement with the configured `gid`.
If the transaction is a block, issue a COMMIT statement.
If the transaction was started inside a transaction block, it should be
identified as a savepoint, and the savepoint should be released.
If the transaction has already been committed, do nothing.
"""
@abstractmethod
def rollback(self) -> None:
"""
Abort the transaction.
If the transaction is a savepoint, ROLLBACK TO the savepoint identifier.
If the transaction is a transaction block, issue an ABORT.
If the transaction has already been aborted, do nothing.
[DEPRECATED]
If the transaction is configured with a `gid` *and* has been prepared, issue
a ROLLBACK PREPARE statement with the configured `gid`.
"""
abort = rollback
@abstractmethod
def recover(self) -> None:
"""
[DEPRECATED]
If the transaction is assigned a `gid`, recover may be used to identify
the transaction as prepared and ready for committing or aborting.
This method is used in recovery procedures where a prepared transaction
needs to be committed or rolled back.
If no prepared transaction with the configured `gid` exists, a
`postgresql.exceptions.UndefinedObjectError` must be raised.
[This is consistent with the error raised by ROLLBACK/COMMIT PREPARED]
Once this method has been ran, it should identify the transaction as being
prepared so that subsequent invocations to `commit` or `rollback` should
cause the appropriate ROLLBACK PREPARED or COMMIT PREPARED statements to
be executed.
"""
@abstractmethod
def prepare(self) -> None:
"""
[DEPRECATED]
Explicitly prepare the transaction with the configured `gid` by issuing a
PREPARE TRANSACTION statement with the configured `gid`.
This *must* be called for the first phase of the commit.
If the transaction is already prepared, do nothing.
"""
@abstractmethod
def __enter__(self):
"""
Run the `start` method and return self.
"""
def __context__(self):
'Return self.'
return self
@abstractmethod
def __exit__(self, typ, obj, tb):
"""
If an exception is indicated by the parameters, run the transaction's
`rollback` method iff the database is still available(not closed), and
return a `False` value.
If an exception is not indicated, but the database's transaction state is
in error, run the transaction's `rollback` method and raise a
`postgresql.exceptions.InFailedTransactionError`. If the database is
unavailable, the `rollback` method should cause a
`postgresql.exceptions.ConnectionDoesNotExistError` exception to occur.
Otherwise, run the transaction's `commit` method. If the commit fails,
a `gid` is configured, and the connection is still available, run the
transaction's `rollback` method.
When the `commit` is ultimately unsuccessful or not ran at all, the purpose
of __exit__ is to resolve the error state of the database iff the
database is available(not closed) so that more commands can be after the
block's exit.
"""
class Settings(
Element,
collections.MutableMapping
):
"""
A mapping interface to the session's settings. This provides a direct
interface to ``SHOW`` or ``SET`` commands. Identifiers and values need
not be quoted specially as the implementation must do that work for the
user.
"""
_e_label = 'SETTINGS'
@abstractmethod
def __getitem__(self, key):
"""
Return the setting corresponding to the given key. The result should be
consistent with what the ``SHOW`` command returns. If the key does not
exist, raise a KeyError.
"""
@abstractmethod
def __setitem__(self, key, value):
"""
Set the setting with the given key to the given value. The action should
be consistent with the effect of the ``SET`` command.
"""
@abstractmethod
def __call__(self, **kw):
"""
Create a context manager applying the given settings on __enter__ and
restoring the old values on __exit__.
>>> with db.settings(search_path = 'local,public'):
... ...
"""
@abstractmethod
def get(self, key, default = None):
"""
Get the setting with the corresponding key. If the setting does not
exist, return the `default`.
"""
@abstractmethod
def getset(self, keys):
"""
Return a dictionary containing the key-value pairs of the requested
settings. If *any* of the keys do not exist, a `KeyError` must be raised
with the set of keys that did not exist.
"""
@abstractmethod
def update(self, mapping):
"""
For each key-value pair, incur the effect of the `__setitem__` method.
"""
@abstractmethod
def keys(self):
"""
Return an iterator to all of the settings' keys.
"""
@abstractmethod
def values(self):
"""
Return an iterator to all of the settings' values.
"""
@abstractmethod
def items(self):
"""
Return an iterator to all of the setting value pairs.
"""
class Database(Element):
"""
The interface to an individual database. `Connection` objects inherit from
this
"""
_e_label = 'DATABASE'
@propertydoc
@abstractproperty
def backend_id(self) -> (int, None):
"""
The backend's process identifier.
"""
@propertydoc
@abstractproperty
def version_info(self) -> tuple:
"""
A version tuple of the database software similar Python's `sys.version_info`.
>>> db.version_info
(8, 1, 3, '', 0)
"""
@propertydoc
@abstractproperty
def client_address(self) -> (str, None):
"""
The client address that the server sees. This is obtainable by querying
the ``pg_catalog.pg_stat_activity`` relation.
`None` if unavailable.
"""
@propertydoc
@abstractproperty
def client_port(self) -> (int, None):
"""
The client port that the server sees. This is obtainable by querying
the ``pg_catalog.pg_stat_activity`` relation.
`None` if unavailable.
"""
@propertydoc
@abstractproperty
def xact(self,
gid : "global identifier to configure" = None,
isolation : "ISOLATION LEVEL to use with the transaction" = None,
mode : "Mode of the transaction, READ ONLY or READ WRITE" = None,
) -> Transaction:
"""
Create a `Transaction` object using the given keyword arguments as its
configuration.
"""
@propertydoc
@abstractproperty
def settings(self) -> Settings:
"""
A `Settings` instance bound to the `Database`.
"""
@abstractmethod
def execute(sql) -> None:
"""
Execute an arbitrary block of SQL. Always returns `None` and raise
a `postgresql.exceptions.Error` subclass on error.
"""
@abstractmethod
def prepare(self, sql : str) -> PreparedStatement:
"""
Create a new `PreparedStatement` instance bound to the connection
using the given SQL.
>>> s = db.prepare("SELECT 1")
>>> c = s()
>>> c.next()
(1,)
"""
@abstractmethod
def statement_from_id(self,
statement_id : "The statement's identification string.",
) -> PreparedStatement:
"""
Create a `PreparedStatement` object that was already prepared on the
server. The distinction between this and a regular query is that it
must be explicitly closed if it is no longer desired, and it is