-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathpq3.py
More file actions
3201 lines (2872 loc) · 85.6 KB
/
Copy pathpq3.py
File metadata and controls
3201 lines (2872 loc) · 85.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
##
# copyright 2009, James William Pye
# http://python.projects.postgresql.org
##
"""
PG-API interface for PostgreSQL that support the PQ version 3.0 protocol.
"""
import sys
import os
import warnings
import weakref
import errno
import socket
import ssl
from operator import attrgetter, itemgetter, is_, is_not
get0 = itemgetter(0)
get1 = itemgetter(1)
from itertools import repeat, islice, chain
from functools import partial
from abc import abstractmethod, abstractproperty
import collections
from .. import versionstring as pg_version
from .. import iri as pg_iri
from .. import exceptions as pg_exc
from .. import string as pg_str
from ..encodings import aliases as pg_enc_aliases
from .. import api as pg_api
from ..python.itertools import interlace
from ..protocol.buffer import pq_message_stream
from ..protocol import xact3 as pq
from ..protocol import typio as pg_typio
from .. import types as pg_types
TypeLookup = """
SELECT
ns.nspname as namespace,
bt.typname,
bt.typtype,
bt.typlen,
bt.typelem,
bt.typrelid,
ae.oid AS ae_typid,
ae.typreceive::oid != 0 AS ae_hasbin_input,
ae.typsend::oid != 0 AS ae_hasbin_output
FROM pg_type bt
LEFT JOIN pg_type ae
ON (
bt.typlen = -1 AND
bt.typelem != 0 AND
bt.typelem = ae.oid
)
LEFT JOIN pg_namespace ns
ON (ns.oid = bt.typnamespace)
WHERE bt.oid = $1
"""
CompositeLookup = """
SELECT
CAST(atttypid AS oid) AS atttypid,
CAST(attname AS VARCHAR) AS attname
FROM
pg_type t LEFT JOIN pg_attribute a
ON (t.typrelid = a.attrelid)
WHERE
attrelid = $1 AND NOT attisdropped AND attnum > 0
ORDER BY attnum ASC
"""
ProcedureLookup = """
SELECT
pg_proc.oid,
pg_proc.*,
pg_proc.oid::regproc AS _proid,
pg_proc.oid::regprocedure as procedure_id,
-- mm, the pain. the sweet, sweet pain. oh it's portable.
-- it's so portable that it runs on BDB on win32.
COALESCE(
string_to_array(
replace(trim(textin(oidvectorout(proargtypes)), '{}'), ',', ' '), ' '
)::oid[],
'{}'::oid[]
) AS proargtypes,
(pg_type.oid = 'record'::regtype or pg_type.typtype = 'c') AS composite
FROM
pg_proc LEFT JOIN pg_type ON (
pg_proc.prorettype = pg_type.oid
)
"""
PreparedLookup = """
SELECT
COALESCE(ARRAY(
SELECT
gid::text
FROM
pg_catalog.pg_prepared_xacts
WHERE
database = current_database()
AND (
owner = $1::text
OR (
(SELECT rolsuper FROM pg_roles WHERE rolname = $1::text)
)
)
ORDER BY prepared ASC
), ('{}'::text[]))
"""
TransactionIsPrepared = """
SELECT TRUE FROM pg_catalog.pg_prepared_xacts
WHERE gid::text = $1
"""
GetPreparedStatement = """
SELECT
statement
FROM
pg_catalog.pg_prepared_statements
WHERE
statement_id = $1
"""
IDNS = '%s(py:%s)'
def ID(s, title = None):
'generate an id for a client statement or cursor'
return IDNS %(title or 'untitled', hex(id(s)))
def direction_str_to_bool(str):
s = str.upper()
if s == 'FORWARD':
return True
elif s == 'BACKWARD':
return False
else:
raise ValueError("invalid direction " + repr(str))
def direction_to_bool(v):
if isinstance(v, str):
return direction_str_to_bool(v)
elif v is not True and v is not False:
raise TypeError("invalid direction " + repr(v))
else:
return v
class ClosedConnection(pg_api.InterfaceElement):
ife_label = 'CLOSED'
ife_ancestor = attrgetter('connection')
_asyncs = ()
state = pq.Complete
fatal = True
def ife_snapshot_text(self):
return '(connection has been killed)'
def asyncs(self):
return self._asyncs
error_message = pq.element.Error(
severity = b'FATAL',
code = pg_exc.ConnectionDoesNotExistError.code.encode('ascii'),
message = b"operation on closed connection",
hint = b"Call the 'connect' method on the connection object.",
)
def __init__(self, connection):
self.connection = connection
class TypeIO(pg_typio.TypeIO):
def __init__(self, database):
self.database = database
super().__init__()
def lookup_type_info(self, typid):
return self.database.prepare(TypeLookup).first(typid)
def lookup_composite_type_info(self, typid):
return self.database.prepare(CompositeLookup)(typid)
class Chunks(pg_api.Chunks):
cursor = None
def __init__(self, cursor):
self.cursor = cursor
def __iter__(self):
return self
def __next__(self):
if self.cursor._last_reqsize == 0xFFFFFFFF:
raise StopIteration
self.cursor._expand()
# Grab the whole thing.
if self.cursor._offset == 0:
chunk = self.cursor._buffer
else:
chunk = self.cursor._buffer[self.cursor._offset:]
self.cursor.__dict__.update({
'_offset': 0,
'_buffer': [],
})
if not chunk:
self.cursor._buffer_more(self.cursor.chunksize or 128, self.cursor.direction)
if not self.cursor._buffer \
and self.cursor._last_increase != self.cursor._last_reqsize:
raise StopIteration
# offset is expected to be zero.
chunk = self.cursor._buffer
self.cursor.__dict__.update({
'_offset': 0,
'_buffer': [],
})
else:
self.cursor._dispatch_for_more(self.cursor.direction)
return chunk
##
# Base Cursor class and cursor creation entry points.
class Cursor(pg_api.Cursor):
ife_ancestor = None
closed = None
cursor_id = None
statement = None
parameters = None
with_hold = None
scroll = None
insensitive = None
chunksize = 64
_output = None
_output_io = None
_output_formats = None
_output_attmap = None
_complete_message = None
@classmethod
def from_statement(
typ,
parameters,
statement,
scroll = False,
with_hold = None,
insensitive = True,
):
if statement._input is not None:
if len(parameters) != len(statement._input):
raise TypeError("statement requires %d parameters, given %d" %(
len(statement._input), len(parameters)
))
c = super().__new__(typ)
c.parameters = parameters
c.statement = statement
c.with_hold = with_hold
c.scroll = scroll
c.insensitive = insensitive
c.__init__(ID(c), statement.database)
return c
def __init__(self, cursor_id, database):
self.closed = True
self.__dict__['direction'] = True
if not cursor_id:
# Driver uses the empty id(b'').
##
raise ValueError("invalid cursor identifier, " + repr(cursor_id))
self.cursor_id = str(cursor_id)
self._quoted_cursor_id = '"' + self.cursor_id.replace('"', '""') + '"'
self.database = database
self._pq_cursor_id = database.typio.encode(self.cursor_id)
if ID(self) == self.cursor_id:
addgarbage = self.database._closeportals.append
typio = self.database.typio
curid = self.cursor_id
self._del = weakref.ref(
self, lambda _: addgarbage(typio.encode(curid))
)
def __iter__(self):
return self
def get_direction(self):
return self.__dict__['direction']
def set_direction(self, value):
self.__dict__['direction'] = direction_to_bool(value)
direction = property(
fget = get_direction,
fset = set_direction,
)
del get_direction, set_direction
def _which_way(self, direction):
if direction is not None:
direction = direction_to_bool(direction)
# -1 * -1 = 1, -1 * 1 = -1, 1 * 1 = 1
return not ((not self.direction) ^ (not direction))
else:
return self.direction
def _statement_string(self):
if self.statement:
return self.statement.string
return None
@property
def state(self):
if self.closed:
return 'closed'
else:
return 'open'
@property
def column_names(self):
if self._output is not None:
return list(self.database.typio.decodes(self._output.keys()))
@property
def column_types(self):
if self._output is not None:
return [self.database.typio.type_from_oid(x[3]) for x in self._output]
@property
def pg_column_types(self):
if self._output is not None:
return [x[3] for x in self._output]
@property
def sql_column_types(self):
return [
pg_types.oid_to_sql_name.get(x) or \
self.database.typio.sql_type_from_oid(x)
for x in self.pg_column_types
]
def close(self):
if self.closed is False:
self.database._closeportals.append(
self.database.typio.encode(self.cursor_id)
)
self.closed = True
if hasattr(self, '_del'):
del self._del
def _raise_parameter_tuple_error(self, procs, tup, itemnum):
# The element traceback will include the full list of parameters.
data = repr(tup[itemnum])
if len(data) > 80:
# Be sure not to fill screen with noise.
data = data[:75] + ' ...'
te = pg_exc.ParameterError(
"failed to pack parameter %s::%s for transfer" %(
('$' + str(itemnum + 1)),
self.database.typio.sql_type_from_oid(
self.statement.pg_parameter_types[itemnum]
) or '<unknown>',
),
details = {
'data': data,
'hint' : "Try casting parameter to 'text', then to the target type."
},
)
te.index = itemnum
self.ife_descend(te)
te.raise_exception()
def _raise_column_tuple_error(self, procs, tup, itemnum):
'for column processing'
# The element traceback will include the full list of parameters.
data = repr(tup[itemnum])
if len(data) > 80:
# Be sure not to fill screen with noise.
data = data[:75] + ' ...'
te = pg_exc.ColumnError(
"failed to unpack column %r, %s::%s, from wire data" %(
itemnum,
self.column_names[itemnum],
self.database.typio.sql_type_from_oid(
self.statement.pg_column_types[itemnum]
) or '<unknown>',
),
details = {
'data': data,
'hint' : "Try casting the column to 'text'."
},
)
te.index = itemnum
self.ife_descend(te)
te.raise_exception()
def _pq_parameters(self):
return pg_typio.process_tuple(
self.statement._input_io, self.parameters,
self._raise_parameter_tuple_error
)
def _init(self):
"""
Based on the cursor parameters and the current transaction state,
select a cursor strategy for managing the response from the server.
"""
if self.statement is not None:
# If the cursor comes from a statement object, always
# get the output information from it.
self._output = self.statement._output
self._output_formats = self.statement._output_formats
self._output_io = self.statement._output_io
self._output_attmap = self.statement._output_attmap
if self._output is None:
self.__class__ = UtilityCursor
return self._init()
##
# Finish any outstanding transactions to identify
# the current transaction state.
if self.database._pq_xact is not None:
self.database._pq_complete()
##
# In auto-commit mode or with_hold is on?
if ((self.database._pq_state == b'I' and self.with_hold is None)\
or self.with_hold is True or self.scroll is True) \
and self.statement.string is not None:
##
# with_hold or scroll require a DeclaredCursor.
self.__class__ = DeclaredCursor
else:
self.__class__ = ProtocolCursor
else:
# If there's no statement, it's probably a server declared cursor.
# Treat it as an SQL declared cursor with special initialization.
self.__class__ = ServerDeclaredCursor
return self._init()
def _fini(self):
##
# Mark the Cursor as open.
self.closed = False
def ife_snapshot_text(self):
return self.cursor_id + ('' if self.parameters is None else (
os.linesep + ' PARAMETERS: ' + repr(self.parameters)
))
def _operation_error_(self, *args, **kw):
e = pg_exc.OperationError(
"cursor type does not support that operation"
)
self.ife_descend(e)
e.raise_exception()
__next__ = read = seek = _operation_error_
def command(self):
"The completion message's command identifier"
if self._complete_message is not None:
return self._complete_message.extract_command().decode('ascii')
def count(self):
"The completion message's count number"
if self._complete_message is not None:
return self._complete_message.extract_count()
class CursorStrategy(Cursor):
"""
It's a stretch to call this a strategy as the strategy selection occurs
after instantiation and by the Cursor class itself, not the caller.
It's more like a union-class where the ob_type is the current "selection".
"""
def __init__(self, *args, **kw):
raise TypeError("cannot instantiate CursorStrategy-types directly")
class ReadableCursor(CursorStrategy):
def _init(self):
self._offset = 0
self._buffer = []
self._this_reqsize = -1
self._this_direction = None
self._last_reqsize = 0
self._last_increase = 0
self._last_direction = self.direction
self._xact = None
@abstractmethod
def _expansion(self):
"""
Return a sequence of the new data provided by the transaction
_xact. "the expansion of data for the buffer"
"""
@abstractmethod
def _expand(self):
"""
For a given state, extract the data from the transaction and
append it to the buffer.
"""
def _contract(self):
"reduce the number of items in the buffer"
# when chunksize is zero, it will trim the entire buffer.
maxtrim = self._offset - self.chunksize
trim = self.chunksize or maxtrim
if trim >= self.chunksize:
self.__dict__.update({
'_offset' : self._offset - trim,
'_buffer' : self._buffer[trim:]
})
def _maintain(self, direction):
if self._last_direction is not None and direction is not self._last_direction:
# change in direction, reset buffer.
if self._xact is not None:
if self._xact.state is not pq.Complete \
and self._xact is self.database._pq_xact:
self.database._pq_complete()
self.__dict__.update({
'_offset' : 0,
'_buffer' : [],
'_last_increase' : 0,
'_last_reqsize' : 0,
# Don't identify a direction change again.
'_last_direction' : direction,
'_this_direction' : None,
'_xact' : None,
'_this_reqsize' : 0,
})
return
# Reduce the buffer, if need be.
if self._offset >= self.chunksize and len(self._buffer) >= (3 * self.chunksize):
self._contract()
# Expand it if reading-ahead,
# and the offset is nearing the end of the chunksize.
if self._xact is not None and \
(len(self._buffer) - self._offset) > (self.chunksize // 8):
# Transaction ready, but only attempt expanding if it
# will be needed soon.
##
self._expand()
def __next__(self):
self._maintain(self.direction)
if self._offset >= len(self._buffer):
if self._last_increase != self._last_reqsize \
or not (self._buffer_more(1, self.direction) > 0):
raise StopIteration
t = self._buffer[self._offset]
self._offset = self._offset + 1
return t
def read(self, quantity = None, direction = None):
dir = self._which_way(direction)
self._maintain(dir)
if quantity is None:
# Read all in the direction.
##
while self._last_increase == self._last_reqsize:
self._buffer_more(None, dir)
quantity = len(self._buffer) - self._offset
else:
# Read some.
##
left_to_read = (quantity - (len(self._buffer) - self._offset))
expanded = 0
while left_to_read > 0 and self._last_increase == self._last_reqsize:
# In scroll situations, there's no concern
# about reading already requested data as
# there is no pre-fetching going on.
expanded = self._buffer_more(left_to_read, dir)
left_to_read -= expanded
quantity = min(len(self._buffer) - self._offset, quantity)
end_of_block = self._offset + quantity
t = self._buffer[self._offset:end_of_block]
self._offset = end_of_block
return t
class TupleCursor(ReadableCursor):
def _init(self, setup):
super()._init()
##
# chunksize determines whether or not to pre-fetch.
# If the cursor is not scrollable, use the default.
if self.scroll:
# This restriction on scroll was set to insure
# any needed consistency with the cursor position.
# If this was not done, than compensation would need
# to be made when direction changes occur.
##
self.chunksize = 0
more = ()
else:
more = self._pq_xp_fetchmore(self.chunksize, self.direction)
x = pq.Instruction(
setup + more + (pq.element.SynchronizeMessage,)
)
self.__dict__.update({
'_xact' : x,
'_this_reqsize' : self.chunksize
})
self.database._pq_push(self._xact)
self._fini()
def _dispatch_for_more(self, direction):
if self._xact:
# didn't expand
raise RuntimeError("invalid state for dispatch")
more = self._pq_xp_fetchmore(self.chunksize, direction)
x = more + (pq.element.SynchronizeMessage,)
x = pq.Instruction(x)
self.ife_descend(x)
self.__dict__.update({
'_xact' : x,
'_this_reqsize' : self.chunksize,
'_this_direction' : direction,
})
self.database._pq_push(self._xact)
def _expand(self):
"""
[internal] Expand the _buffer using the data in _xact
"""
if self._xact is not None:
# complete the _xact
if self._xact.state is not pq.Complete:
self.database._pq_push(self._xact)
if self._xact.state is not pq.Complete:
self.database._pq_complete()
expansion = self._expansion()
self.__dict__.update({
'_buffer' : self._buffer + expansion,
'_xact' : None,
'_last_increase' : len(expansion),
'_last_reqsize' : self._this_reqsize,
'_last_direction' : self._this_direction,
'_this_reqsize' : None,
'_this_direction' : None,
})
def _buffer_more(self, quantity, direction):
"""
Expand the buffer with more tuples. Does *not* alter offset.
"""
##
# The final fallback of 64 is to handle scrollable cursors
# where read(None) is invoked.
rquantity = self.chunksize or quantity or 64
if rquantity < 0:
raise RuntimeError("cannot buffer negative quantities")
if self._xact is None:
# No previous transaction started, so make one.
##
##
# Use chunksize if it's non-zero. This will allow the cursor to
# complete the transaction and process the rows while more are
# coming in.
more = self._pq_xp_fetchmore(rquantity, direction)
x = pq.Instruction(more + (pq.element.SynchronizeMessage,))
self.ife_descend(x)
self.__dict__.update({
'_xact' : x,
'_this_reqsize' : rquantity,
'_this_direction' : direction,
})
self.database._pq_push(x)
self._expand()
if self.scroll is False and (
self._last_increase == self._last_reqsize \
and (
(len(self._buffer) - self._offset) >= (self.chunksize // 4) \
or quantity > rquantity
)
):
# If not scrolling and
# The last buffer increase was the same as the request and
# A quarter of the chunksize remains, dispatch for another.
# or, if the quantity is greater than the rquantity.
##
self._dispatch_for_more(direction)
return self._last_increase
def _expansion(self):
return [
pg_types.Row.from_sequence(
self._output_attmap,
pg_typio.process_tuple(
self._output_io, y, self._raise_column_tuple_error
),
)
for y in self._xact.messages_received()
if y.type is pq.element.Tuple.type
]
def _pq_xp_move(self, position, whence):
'make a command sequence for a MOVE single command'
return (
pq.element.Parse(b'',
b'MOVE ' + whence + b' ' + position + b' IN ' + \
self.database.typio.encode(self._quoted_cursor_id),
()
),
pq.element.Bind(b'', b'', (), (), ()),
pq.element.Execute(b'', 1),
)
def seek(self, offset, whence = 'ABSOLUTE'):
rwhence = self._seek_whence_map.get(whence, whence)
if rwhence is None or rwhence.upper() not in \
self._seek_whence_map.values():
raise TypeError(
"unknown whence parameter, %r" %(whence,)
)
rwhence = rwhence.upper()
if self.direction is False:
if rwhence == 'RELATIVE':
offset = -offset
elif rwhence == 'ABSOLUTE':
rwhence = 'FROM_END'
else:
rwhence = 'ABSOLUTE'
if rwhence == 'RELATIVE':
if offset < 0:
cmd = self._pq_xp_move(
str(-offset).encode('ascii'), b'BACKWARD'
)
else:
cmd = self._pq_xp_move(
str(offset).encode('ascii'), b'RELATIVE'
)
elif rwhence == 'ABSOLUTE':
cmd = self._pq_xp_move(str(offset).encode('ascii'), b'ABSOLUTE')
else:
# move to last record, then consume it to put the position at
# the very end of the cursor.
cmd = self._pq_xp_move(b'', b'LAST') + \
self._pq_xp_move(b'', b'NEXT') + \
self._pq_xp_move(str(offset).encode('ascii'), b'BACKWARD')
x = pq.Instruction(cmd + (pq.element.SynchronizeMessage,))
self.ife_descend(x)
# moves are a full reset
self.__dict__.update({
'_offset' : 0,
'_buffer' : [],
'_xact' : x,
'_this_reqsize' : 0,
'_this_direction' : None,
'_last_reqsize' : 0,
'_last_increase' : 0,
'_last_direction' : None,
})
self.database._pq_push(x)
class ProtocolCursor(TupleCursor):
cursor_type = 'protocol'
def _init(self):
# Protocol-bound cursor.
##
if self.scroll:
# That doesn't work.
##
e = pg_exc.OperationError("cannot bind cursor scroll = True")
self.ife_descend(e)
e.raise_exception()
if self.with_hold:
# That either.
##
e = pg_exc.OperationError("cannot bind cursor with_hold = True")
self.ife_descend(e)
e.raise_exception()
if self.database._pq_state == b'I':
# have to fetch them all. as soon as the next sync occurs, the
# cursor will be dropped.
self.chunksize = 0xFFFFFFFF
return super()._init((
pq.element.Bind(
self._pq_cursor_id,
self.statement._pq_statement_id,
self.statement._input_formats,
self._pq_parameters(),
self._output_formats,
),
))
def _pq_xp_fetchmore(self, quantity, direction):
if direction is not True:
err = pg_exc.OperationError(
"cannot read backwards with protocol cursors"
)
self.ife_descend(err)
err.raise_exception()
return (
pq.element.Execute(self._pq_cursor_id, quantity),
)
class DeclaredCursor(TupleCursor):
cursor_type = 'declared'
def _statement_string(self):
qstr = super()._statement_string()
return 'DECLARE {name}{insensitive} {scroll} '\
'CURSOR {hold} FOR {source}'.format(
name = self._quoted_cursor_id,
insensitive = ' INSENSITIVE' if self.insensitive else '',
scroll = 'SCROLL' if (self.scroll is True) else 'NO SCROLL',
hold = 'WITH HOLD' if (self.with_hold is True) else 'WITHOUT HOLD',
source = qstr
)
def _init(self):
##
# Force with_hold as there is no transaction block.
# If this were not forced, the cursor would disappear
# before the user had a chance to read rows from it.
# Of course, the alternative is to read all the rows like ProtocolCursor
# does. :(
if self.database._pq_state == b'I':
self.with_hold = True
return super()._init((
pq.element.Parse(b'', self.database.typio.encode(self._statement_string()), ()),
pq.element.Bind(
b'', b'', self.statement._input_formats, self._pq_parameters(), ()
),
pq.element.Execute(b'', 1),
))
def _pq_xp_fetchmore(self, quantity, direction):
##
# It's an SQL declared cursor, manually construct the fetch commands.
qstr = "FETCH " + ("FORWARD " if direction else "BACKWARD ")
if quantity is None:
qstr = qstr + "ALL IN " + self._quoted_cursor_id
else:
qstr = qstr \
+ str(quantity) + " IN " + self._quoted_cursor_id
return (
pq.element.Parse(b'', self.database.typio.encode(qstr), ()),
pq.element.Bind(b'', b'', (), (), self._output_formats),
# The "limit" is defined in the fetch query.
pq.element.Execute(b'', 0xFFFFFFFF),
)
class ServerDeclaredCursor(DeclaredCursor):
cursor_type = 'server'
def _init(self):
# scroll and hold are unknown, so assume them to be true.
# This means that fetch-ahead is disabled.
self.scroll = True
self.with_hold = True
self.chunksize = 0
##
# The portal description is needed, so get it.
return TupleCursor._init(
self, (pq.element.DescribePortal(self._pq_cursor_id),)
)
def _fini(self):
if self._xact.state is not pq.Complete:
if self.database._pq_xact is not self._xact:
self.database._pq_push(self._xact)
self.database._pq_complete()
for m in self._xact.messages_received():
if m.type is pq.element.TupleDescriptor.type:
self._output = m
self._output_attmap = \
self.database.typio.attribute_map(self._output)
# tuple output
self._output_io = self.database.typio.resolve_descriptor(
self._output, 1 # (input, output)[1]
)
self._output_formats = [
pq.element.StringFormat
if x is None
else pq.element.BinaryFormat
for x in self._output_io
]
self._output_io = tuple([
x or self.database.typio.decode for x in self._output_io
])
super()._fini()
# Done with the first transaction.
self._xact = None
if self.closed:
e = pg_exc.OperationError("failed to discover cursor output")
self.ife_descend(e)
e.raise_exception()
class UtilityCursor(CursorStrategy):
cursor_type = 'utility'
def _init(self):
self._xact = pq.Instruction((
pq.element.Bind(
b'',
self.statement._pq_statement_id,
self.statement._input_formats,
self._pq_parameters(),
(),
),
pq.element.Execute(b'', 1),
pq.element.SynchronizeMessage,
))
self.ife_descend(self._xact)
self.database._pq_push(self._xact)
while self._xact.state != pq.Complete:
# in case it's a copy
self.database._pq_step()
for x in self._xact.messages_received():
if x.type is pq.element.CopyToBegin.type:
self.__class__ = CopyCursor
return self._init()
# The COPY TO STDOUT transaction terminates the loop
# *without* finishing the transaction.
# Buffering all of the COPY data would be a bad idea(tm).
##
elif x.type in pq.element.Null.type:
break
elif x.type is pq.element.Complete.type:
self._complete_message = x
self._fini()
class CopyCursor(ReadableCursor):
cursor_type = 'copy'
def _init(self):
x = self._xact
super()._init()
self._xact = x
self._last_extension = None
self._last_direction = True
self._this_direction = True
self._fini()
def _expansion(self):
ms = self._xact.completed[0][1]
if ms:
if type(ms[0]) is bytes and type(ms[-1]) is bytes:
return ms
return [
y for y in ms if type(y) is bytes
]
def _expand(self):
if self._xact.completed:
if self._last_extension is self._xact.completed[0]:
del self._xact.completed[0]
if not self._xact.completed:
return
expansions = self._expansion()
if self._buffer:
buffer = self._buffer + expansions
else:
buffer = expansions
l = len(expansions)
# There is no reqsize, so reveal the end of the
# copy when the last_increase is zero *and*
# the transaction is over.
self.__dict__.update({
'_buffer' : buffer,
'_last_extension' : self._xact.completed[0],
'_last_increase' : l,
'_last_reqsize' : \
-1 if l == 0 and self._xact.state is pq.Complete else l
})
def _dispatch_for_more(self, direction):
# nothing to do for copies
pass
def _buffer_more(self, quantity, direction):
"""
[internal] helper function to put more copy data onto the buffer for
reading. This function will only append to the buffer and never
set the offset.
Used to support ``COPY ... TO STDOUT ...;``