-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathapi.py
More file actions
1380 lines (1117 loc) · 34.6 KB
/
api.py
File metadata and controls
1380 lines (1117 loc) · 34.6 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
##
# .api - ABCs for database interface elements
##
"""
Application Programmer Interfaces for PostgreSQL.
``postgresql.api`` is a collection of Python APIs 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 collections.abc
import abc
from .python.element import Element
__all__ = [
'Message',
'Statement',
'Chunks',
'Cursor',
'Connector',
'Category',
'Database',
'TypeIO',
'Connection',
'Transaction',
'Settings',
'StoredProcedure',
'Driver',
'Installation',
'Cluster',
]
class Message(Element):
"""
A message emitted by PostgreSQL.
A message being a NOTICE, WARNING, INFO, etc.
"""
_e_label = 'MESSAGE'
severities = (
'DEBUG',
'INFO',
'NOTICE',
'WARNING',
'ERROR',
'FATAL',
'PANIC',
)
sources = (
'SERVER',
'CLIENT',
)
@property
@abc.abstractmethod
def source(self) -> str:
"""
Where the message originated from. Normally, 'SERVER', but sometimes
'CLIENT'.
"""
@property
@abc.abstractmethod
def code(self) -> str:
"""
The SQL state code of the message.
"""
@property
@abc.abstractmethod
def message(self) -> str:
"""
The primary message string.
"""
@property
@abc.abstractmethod
def details(self) -> dict:
"""
The additional details given with the message. Common keys *should* be the
following:
* 'severity'
* 'context'
* 'detail'
* 'hint'
* 'file'
* 'line'
* 'function'
* 'position'
* 'internal_position'
* 'internal_query'
"""
@abc.abstractmethod
def isconsistent(self, other) -> bool:
"""
Whether the fields of the `other` Message object is consistent with the
fields of `self`.
This *must* return the result of the comparison of code, source, message,
and details.
This method is provided as the alternative to overriding equality;
often, pointer equality is the desirable means for comparison, but
equality of the fields is also necessary.
"""
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')
@abc.abstractmethod
def close(self) -> None:
"""
Close the Result discarding any supporting resources and causing
future read operations to emit empty record sets.
"""
@property
@abc.abstractmethod
def cursor_id(self) -> str:
"""
The cursor's identifier.
"""
@property
@abc.abstractmethod
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']
"""
@property
@abc.abstractmethod
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]
"""
@property
@abc.abstractmethod
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']
"""
@property
@abc.abstractmethod
def column_types(self) -> [str]:
"""
The Python types of the columns produced by the cursor.
A sequence of type objects::
[<class 'int'>, <class 'str'>]
"""
@property
@abc.abstractmethod
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`.
"""
@property
@abc.abstractmethod
def statement(self) -> ("Statement", 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`.
"""
@collections.abc.Iterator.register
class Chunks(Result):
pass
@collections.abc.Iterator.register
class Cursor(Result):
"""
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 `Statement.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',
3 : 'FORWARD',
4 : 'BACKWARD'
}
_direction_map = {
True : 'FORWARD',
False : 'BACKWARD',
}
@abc.abstractmethod
def clone(self) -> "Cursor":
"""
Create a new cursor using the same factors as `self`.
"""
def __iter__(self):
return self
@property
@abc.abstractmethod
def direction(self) -> bool:
"""
The default `direction` argument for read().
When `True` reads are FORWARD.
When `False` reads are BACKWARD.
Cursor operation option.
"""
@abc.abstractmethod
def read(self, quantity = None, 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.
"""
@abc.abstractmethod
def __next__(self) -> "Row":
"""
Get the next tuple in the cursor.
Advances the cursor position by one.
"""
@abc.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.
``3`` or ``"FORWARD"``
Relative forward.
``4`` or ``"BACKWARD"``
Relative backward.
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 Execution(metaclass = abc.ABCMeta):
"""
The abstract class of execution methods.
"""
@abc.abstractmethod
def __call__(self, *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')
[...]
"""
@abc.abstractmethod
def column(self, *parameters) -> collections.abc.Iterable:
"""
Return an iterator producing the values of first column of the
rows produced by the cursor created from the statement bound with the
given parameters.
Column iterators are never scrollable.
Supporting cursors will be WITH HOLD when outside of a transaction to
allow cross-transaction access.
`column` is designed for the situations involving large data sets.
Each iteration returns a single value.
column expressed in sibling terms::
return map(operator.itemgetter(0), self.rows(*parameters))
"""
@abc.abstractmethod
def chunks(self, *parameters) -> collections.abc.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 moving large data sets efficiently.
Each iteration returns sequences of rows *normally* of length(seq) ==
chunksize. If chunksize is unspecified, a default, positive integer will
be filled in. The rows contained in the sequences are only required to
support the basic `collections.abc.Sequence` interfaces; simple and quick
sequence types should be used.
"""
@abc.abstractmethod
def rows(self, *parameters) -> collections.abc.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 to
allow cross-transaction access.
`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))
"""
@abc.abstractmethod
def column(self, *parameters) -> collections.abc.Iterable:
"""
Return an iterator producing the values of the first column in
the cursor created from the statement bound with the given parameters.
Column iterators are never scrollable.
Supporting cursors will be WITH HOLD when outside of a transaction to
allow cross-transaction access.
`column` is designed for the situations involving large data sets.
Each iteration returns a single value. `column` is equivalent to::
return map(operator.itemgetter(0), self.rows(*parameters))
"""
@abc.abstractmethod
def declare(self, *parameters) -> Cursor:
"""
Return a scrollable cursor with hold using the statement bound with the
given parameters.
"""
@abc.abstractmethod
def first(self, *parameters):
"""
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
"""
@abc.abstractmethod
def load_rows(self, iterable):
"""
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.
"""
@abc.abstractmethod
def load_chunks(self, iterable):
"""
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.
"""
@collections.abc.Iterator.register
@collections.abc.Callable.register
@Execution.register
class Statement(Element):
"""
Instances of `Statement` are returned by the `prepare` method of
`Database` instances.
A Statement is an Iterable as well as Callable.
The Iterable interface is supported for queries that take no arguments at
all. It allows the syntax::
>>> for x in db.prepare('select * FROM table'):
... pass
"""
_e_label = 'STATEMENT'
_e_factors = ('database', 'statement_id', 'string',)
@property
@abc.abstractmethod
def statement_id(self) -> str:
"""
The statment's identifier.
"""
@property
@abc.abstractmethod
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.
"""
@property
@abc.abstractmethod
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']
"""
@property
@abc.abstractmethod
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']
"""
@property
@abc.abstractmethod
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]
"""
@property
@abc.abstractmethod
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]
"""
@property
@abc.abstractmethod
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']
"""
@property
@abc.abstractmethod
def column_types(self) -> [type]:
"""
The Python types of the columns produced by the statement.
A sequence of type objects::
[<class 'int'>, <class 'str'>]
"""
@property
@abc.abstractmethod
def parameter_types(self) -> [type]:
"""
The Python types expected of parameters given to the statement.
A sequence of type objects::
[<class 'int'>, <class 'str'>]
"""
@abc.abstractmethod
def clone(self) -> "Statement":
"""
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.
"""
@abc.abstractmethod
def close(self) -> None:
"""
Close the prepared statement releasing resources associated with it.
"""
PreparedStatement = Statement
@collections.abc.Callable.register
class StoredProcedure(Element):
"""
A function stored on the database.
"""
_e_label = 'FUNCTION'
_e_factors = ('database',)
@abc.abstractmethod
def __call__(self, *args, **kw) -> (object, Cursor, collections.abc.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, 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():
... ...
"""
_e_label = 'XACT'
_e_factors = ('database',)
@property
@abc.abstractmethod
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.
"""
@property
@abc.abstractmethod
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.
"""
@abc.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 already open, do nothing.
If the transaction has been committed or aborted, raise an
`postgresql.exceptions.OperationError`.
"""
begin = start
@abc.abstractmethod
def commit(self) -> None:
"""
Commit the transaction.
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.
"""
@abc.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.
"""
abort = rollback
@abc.abstractmethod
def __enter__(self):
"""
Run the `start` method and return self.
"""
@abc.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.
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.
"""
@collections.abc.MutableMapping.register
class Settings(Element):
"""
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'
@abc.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.
"""
@abc.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.
"""
@abc.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'):
... ...
"""
@abc.abstractmethod
def get(self, key, default = None):
"""
Get the setting with the corresponding key. If the setting does not
exist, return the `default`.
"""
@abc.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.
"""
@abc.abstractmethod
def update(self, mapping):
"""
For each key-value pair, incur the effect of the `__setitem__` method.
"""
@abc.abstractmethod
def keys(self):
"""
Return an iterator to all of the settings' keys.
"""
@abc.abstractmethod
def values(self):
"""
Return an iterator to all of the settings' values.
"""
@abc.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'
@property
@abc.abstractmethod
def backend_id(self) -> (int, None):
"""
The backend's process identifier.
"""
@property
@abc.abstractmethod
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)
"""
@property
@abc.abstractmethod
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.
"""
@property
@abc.abstractmethod
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.
"""
@property
@abc.abstractmethod
def xact(self, isolation = None, mode = None) -> Transaction:
"""
Create a `Transaction` object using the given keyword arguments as its
configuration.
"""
@property
@abc.abstractmethod
def settings(self) -> Settings:
"""
A `Settings` instance bound to the `Database`.
"""
@abc.abstractmethod
def do(language, source) -> None:
"""
Execute a DO statement using the given language and source.
Always returns `None`.
Likely to be a function of Connection.execute.
"""
@abc.abstractmethod
def execute(sql) -> None:
"""
Execute an arbitrary block of SQL. Always returns `None` and raise
an exception on error.
"""
@abc.abstractmethod
def prepare(self, sql : str) -> Statement:
"""
Create a new `Statement` instance bound to the connection
using the given SQL.
>>> s = db.prepare("SELECT 1")
>>> c = s()
>>> c.next()
(1,)
"""
@abc.abstractmethod
def query(self, sql : str, *args) -> Execution:
"""
Prepare and execute the statement, `sql`, with the given arguments.
Equivalent to ``db.prepare(sql)(*args)``.
"""
@abc.abstractmethod
def statement_from_id(self, statement_id) -> Statement:
"""
Create a `Statement` 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
instantiated using the statement identifier as opposed to the SQL
statement itself.
"""
@abc.abstractmethod
def cursor_from_id(self, cursor_id) -> Cursor:
"""
Create a `Cursor` object from the given `cursor_id` that was already
declared on the server.
`Cursor` objects created this way must *not* be closed when the object
is garbage collected. Rather, the user must explicitly close it for
the server resources to be released. This is in contrast to `Cursor`
objects that are created by invoking a `Statement` or a SRF
`StoredProcedure`.
"""
@abc.abstractmethod
def proc(self, procedure_id) -> StoredProcedure:
"""
Create a `StoredProcedure` instance using the given identifier.
The `proc_id` given can be either an ``Oid``, or a ``regprocedure``
that identifies the stored procedure to create the interface for.
>>> p = db.proc('version()')
>>> p()
'PostgreSQL 8.3.0'
>>> qstr = "select oid from pg_proc where proname = 'generate_series'"
>>> db.prepare(qstr).first()
1069
>>> generate_series = db.proc(1069)
>>> list(generate_series(1,5))
[1, 2, 3, 4, 5]
"""
@abc.abstractmethod
def reset(self) -> None:
"""
Reset the connection into it's original state.
Issues a ``RESET ALL`` to the database. If the database supports
removing temporary tables created in the session, then remove them.
Reapply initial configuration settings such as path.
The purpose behind this method is to provide a soft-reconnect method
that re-initializes the connection into its original state. One
obvious use of this would be in a connection pool where the connection
is being recycled.
"""
@abc.abstractmethod
def notify(self, *channels, **channel_and_payload) -> int:
"""
NOTIFY the channels with the given payload.
Equivalent to issuing "NOTIFY <channel>" or "NOTIFY <channel>, <payload>"
for each item in `channels` and `channel_and_payload`. All NOTIFYs issued
*must* occur in the same transaction.
The items in `channels` can either be a string or a tuple. If a string,
no payload is given, but if an item is a `builtins.tuple`, the second item
will be given as the payload. `channels` offers a means to issue NOTIFYs
in guaranteed order.
The items in `channel_and_payload` are all payloaded NOTIFYs where the
keys are the channels and the values are the payloads. Order is undefined.
"""
@abc.abstractmethod
def listen(self, *channels) -> None:
"""
Start listening to the given channels.
Equivalent to issuing "LISTEN <x>" for x in channels.
"""
@abc.abstractmethod
def unlisten(self, *channels) -> None:
"""
Stop listening to the given channels.