-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathpq3.py
3060 lines (2704 loc) · 84.5 KB
/
pq3.py
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
##
# .driver.pq3 - interface to PostgreSQL using PQ v3.0.
##
"""
PG-API interface for PostgreSQL using PQ version 3.0.
"""
import os
import weakref
import socket
from traceback import format_exception
from itertools import repeat, chain, count
from functools import partial
from codecs import lookup as lookup_codecs
from operator import itemgetter
get0 = itemgetter(0)
get1 = itemgetter(1)
from .. import lib as pg_lib
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 .. import api as pg_api
from .. import message as pg_msg
from ..encodings.aliases import get_python_name
from ..string import quote_ident
from ..python.itertools import interlace, chunk
from ..python.socket import SocketFactory
from ..python.functools import process_tuple, process_chunk
from ..python.functools import Composition as compose
from ..protocol import xact3 as xact
from ..protocol import element3 as element
from ..protocol import client3 as client
from ..protocol.message_types import message_types
from ..notifyman import NotificationManager
from .. import types as pg_types
from ..types import io as pg_types_io
from ..types.io import lib as io_lib
import warnings
# Map element3.Notice field identifiers
# to names used by message.Message.
notice_field_to_name = {
message_types[b'S'[0]] : 'severity',
message_types[b'C'[0]] : 'code',
message_types[b'M'[0]] : 'message',
message_types[b'D'[0]] : 'detail',
message_types[b'H'[0]] : 'hint',
message_types[b'W'[0]] : 'context',
message_types[b'P'[0]] : 'position',
message_types[b'p'[0]] : 'internal_position',
message_types[b'q'[0]] : 'internal_query',
message_types[b'F'[0]] : 'file',
message_types[b'L'[0]] : 'line',
message_types[b'R'[0]] : 'function',
}
del message_types
notice_field_from_name = dict(
(v, k) for (k, v) in notice_field_to_name.items()
)
could_not_connect = element.ClientError((
(b'S', 'FATAL'),
(b'C', '08001'),
(b'M', "could not establish connection to server"),
))
# generate an id for a client statement or cursor
def ID(s, title = None, IDNS = 'py:'):
return IDNS + hex(id(s))
def declare_statement_string(
cursor_id,
statement_string,
insensitive = True,
scroll = True,
hold = True
):
s = 'DECLARE ' + cursor_id
if insensitive is True:
s += ' INSENSITIVE'
if scroll is True:
s += ' SCROLL'
s += ' CURSOR'
if hold is True:
s += ' WITH HOLD'
else:
s += ' WITHOUT HOLD'
return s + ' FOR ' + statement_string
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 TypeIO(pg_api.TypeIO):
"""
A class that manages I/O for a given configuration. Normally, a connection
would create an instance, and configure it based upon the version and
configuration of PostgreSQL that it is connected to.
"""
_e_factors = ('database',)
strio = (None, None, str)
def __init__(self, database):
self.database = database
self.encoding = None
strio = self.strio
self._cache = {
# Encoded character strings
pg_types.ACLITEMOID : strio, # No binary functions.
pg_types.NAMEOID : strio,
pg_types.BPCHAROID : strio,
pg_types.VARCHAROID : strio,
pg_types.CSTRINGOID : strio,
pg_types.TEXTOID : strio,
pg_types.REGTYPEOID : strio,
pg_types.REGPROCOID : strio,
pg_types.REGPROCEDUREOID : strio,
pg_types.REGOPEROID : strio,
pg_types.REGOPERATOROID : strio,
pg_types.REGCLASSOID : strio,
}
self.typinfo = {}
super().__init__()
def lookup_type_info(self, typid):
return self.database.sys.lookup_type(typid)
def lookup_composite_type_info(self, typid):
return self.database.sys.lookup_composite(typid)
def lookup_domain_basetype(self, typid):
if self.database.version_info[:2] >= (8, 4):
return self.lookup_domain_basetype_84(typid)
while typid:
r = self.database.sys.lookup_basetype(typid)
if not r[0][0]:
return typid
else:
typid = r[0][0]
def lookup_domain_basetype_84(self, typid):
r = self.database.sys.lookup_basetype_recursive(typid)
return r[0][0]
def set_encoding(self, value):
"""
Set a new client encoding.
"""
self.encoding = value.lower().strip()
enc = get_python_name(self.encoding)
ci = lookup_codecs(enc or self.encoding)
self._encode, self._decode, *_ = ci
def encode(self, string_data):
return self._encode(string_data)[0]
def decode(self, bytes_data):
return self._decode(bytes_data)[0]
def encodes(self, iter, get0 = get0):
"""
Encode the items in the iterable in the configured encoding.
"""
return map(compose((self._encode, get0)), iter)
def decodes(self, iter, get0 = get0):
"""
Decode the items in the iterable from the configured encoding.
"""
return map(compose((self._decode, get0)), iter)
def resolve_pack(self, typid):
return self.resolve(typid)[0] or self.encode
def resolve_unpack(self, typid):
return self.resolve(typid)[1] or self.decode
def attribute_map(self, pq_descriptor):
return zip(self.decodes(pq_descriptor.keys()), count())
def sql_type_from_oid(self, oid, qi = quote_ident):
if oid in pg_types.oid_to_sql_name:
return pg_types.oid_to_sql_name[oid]
if oid in self.typinfo:
nsp, name, *_ = self.typinfo[oid]
return qi(nsp) + '.' + qi(name)
name = pg_types.oid_to_name.get(oid)
if name:
return 'pg_catalog.%s' % name
else:
return None
def type_from_oid(self, oid):
if oid in self._cache:
typ = self._cache[oid][2]
return typ
def resolve_descriptor(self, desc, index):
"""
Create a sequence of I/O routines from a pq descriptor.
"""
return [
(self.resolve(x[3]) or (None, None))[index] for x in desc
]
# lookup a type's IO routines from a given typid
def resolve(self,
typid : int,
from_resolution_of : [int] = (),
builtins = pg_types_io.resolve,
quote_ident = quote_ident
):
if from_resolution_of and typid in from_resolution_of:
raise TypeError(
"type, %d, is already being looked up: %r" %(
typid, from_resolution_of
)
)
typid = int(typid)
typio = None
if typid in self._cache:
typio = self._cache[typid]
else:
typio = builtins(typid)
if typio is not None:
# If typio is a tuple, it's a constant pair: (pack, unpack)
# otherwise, it's an I/O pair constructor.
if typio.__class__ is not tuple:
typio = typio(typid, self)
self._cache[typid] = typio
if typio is None:
# Lookup the type information for the typid as it's not cached.
##
ti = self.lookup_type_info(typid)
if ti is not None:
typnamespace, typname, typtype, typlen, typelem, typrelid, \
ae_typid, ae_hasbin_input, ae_hasbin_output = ti
self.typinfo[typid] = (
typnamespace, typname, typrelid, int(typelem) if ae_typid else None
)
if typrelid:
# Row type
#
# The attribute name map,
# column I/O,
# column type Oids
# are needed to build the packing pair.
attmap = {}
cio = []
typids = []
attnames = []
i = 0
for x in self.lookup_composite_type_info(typrelid):
attmap[x[1]] = i
attnames.append(x[1])
if x[2]:
# This is a domain
fieldtypid = self.lookup_domain_basetype(x[0])
else:
fieldtypid = x[0]
typids.append(x[0])
te = self.resolve(
fieldtypid, list(from_resolution_of) + [typid]
)
cio.append((te[0] or self.encode, te[1] or self.decode))
i += 1
self._cache[typid] = typio = self.record_io_factory(
cio, typids, attmap, list(
map(self.sql_type_from_oid, typids)
), attnames,
typrelid,
quote_ident(typnamespace) + '.' + \
quote_ident(typname),
)
elif ae_typid is not None:
# resolve the element type and I/O pair
te = self.resolve(
int(typelem),
from_resolution_of = list(from_resolution_of) + [typid]
) or (None, None)
typio = self.array_io_factory(
te[0] or self.encode,
te[1] or self.decode,
typelem,
ae_hasbin_input,
ae_hasbin_output
)
self._cache[typid] = typio
else:
typio = None
if typtype == b'd':
basetype = self.lookup_domain_basetype(typid)
typio = self.resolve(
basetype,
from_resolution_of = list(from_resolution_of) + [typid]
)
elif typtype == b'p' and typnamespace == 'pg_catalog' and typname == 'record':
# anonymous record type
typio = self.anon_record_io_factory()
if not typio:
typio = self.strio
self._cache[typid] = typio
else:
# Throw warning about type without entry in pg_type?
typio = self.strio
return typio
def identify(self, **identity_mappings):
"""
Explicitly designate the I/O handler for the specified type.
Primarily used in cases involving UDTs.
"""
# get them ordered; we process separately, then recombine.
id = list(identity_mappings.items())
ios = [pg_types_io.resolve(x[0]) for x in id]
oids = list(self.database.sys.regtypes([x[1] for x in id]))
self._cache.update([
(oid, io if io.__class__ is tuple else io(oid, self))
for oid, io in zip(oids, ios)
])
def array_parts(self, array, ArrayType = pg_types.Array):
if array.__class__ is not ArrayType:
# Assume the data is a nested list.
array = ArrayType(array)
return (
array.elements(),
array.dimensions,
array.lowerbounds
)
def array_from_parts(self, parts, ArrayType = pg_types.Array):
elements, dimensions, lowerbounds = parts
return ArrayType.from_elements(
elements,
lowerbounds = lowerbounds,
upperbounds = [x + lb - 1 for x, lb in zip(dimensions, lowerbounds)]
)
##
# array_io_factory - build I/O pair for ARRAYs
##
def array_io_factory(
self,
pack_element, unpack_element,
typoid, # array element id
hasbin_input, hasbin_output,
array_pack = io_lib.array_pack,
array_unpack = io_lib.array_unpack,
):
packed_typoid = io_lib.ulong_pack(typoid)
if hasbin_input:
def pack_an_array(data, get_parts = self.array_parts):
elements, dimensions, lowerbounds = get_parts(data)
return array_pack((
0, # unused flags
typoid, dimensions, lowerbounds,
(x if x is None else pack_element(x) for x in elements),
))
else:
# signals string formatting
pack_an_array = None
if hasbin_output:
def unpack_an_array(data, array_from_parts = self.array_from_parts):
flags, typoid, dims, lbs, elements = array_unpack(data)
return array_from_parts(((x if x is None else unpack_element(x) for x in elements), dims, lbs))
else:
# signals string formatting
unpack_an_array = None
return (pack_an_array, unpack_an_array, pg_types.Array)
def RowTypeFactory(self, attribute_map = {}, _Row = pg_types.Row.from_sequence, composite_relid = None):
return partial(_Row, attribute_map)
##
# record_io_factory - Build an I/O pair for RECORDs
##
def record_io_factory(self,
column_io, typids, attmap, typnames, attnames, composite_relid, composite_name,
get0 = get0,
get1 = get1,
fmt_errmsg = "failed to {0} attribute {1}, {2}::{3}, of composite {4} from wire data".format
):
# column_io: sequence (pack,unpack) tuples corresponding to the columns.
# typids: sequence of type Oids; index must correspond to the composite's.
# attmap: mapping of column name to index number.
# typnames: sequence of sql type names in order.
# attnames: sequence of attribute names in order.
# composite_relid: oid of the composite relation.
# composite_name: the name of the composite type.
fpack = tuple(map(get0, column_io))
funpack = tuple(map(get1, column_io))
row_constructor = self.RowTypeFactory(attribute_map = attmap, composite_relid = composite_relid)
def raise_pack_tuple_error(cause, procs, tup, itemnum):
data = repr(tup[itemnum])
if len(data) > 80:
# Be sure not to fill screen with noise.
data = data[:75] + ' ...'
self.raise_client_error(element.ClientError((
(b'C', '--cIO',),
(b'S', 'ERROR',),
(b'M', fmt_errmsg('pack', itemnum, attnames[itemnum], typnames[itemnum], composite_name),),
(b'W', data,),
(b'P', str(itemnum),)
)), cause = cause)
def raise_unpack_tuple_error(cause, procs, tup, itemnum):
data = repr(tup[itemnum])
if len(data) > 80:
# Be sure not to fill screen with noise.
data = data[:75] + ' ...'
self.raise_client_error(element.ClientError((
(b'C', '--cIO',),
(b'S', 'ERROR',),
(b'M', fmt_errmsg('unpack', itemnum, attnames[itemnum], typnames[itemnum], composite_name),),
(b'W', data,),
(b'P', str(itemnum),),
)), cause = cause)
def unpack_a_record(data,
unpack = io_lib.record_unpack,
process_tuple = process_tuple,
row_constructor = row_constructor
):
data = tuple([x[1] for x in unpack(data)])
return row_constructor(process_tuple(funpack, data, raise_unpack_tuple_error))
sorted_atts = sorted(attmap.items(), key = get1)
def pack_a_record(data,
pack = io_lib.record_pack,
process_tuple = process_tuple,
):
if isinstance(data, dict):
data = [data.get(k) for k,_ in sorted_atts]
return pack(
tuple(zip(
typids,
process_tuple(fpack, tuple(data), raise_pack_tuple_error)
))
)
return (pack_a_record, unpack_a_record, tuple)
def anon_record_io_factory(self):
def raise_unpack_tuple_error(cause, procs, tup, itemnum):
data = repr(tup[itemnum])
if len(data) > 80:
# Be sure not to fill screen with noise.
data = data[:75] + ' ...'
self.raise_client_error(element.ClientError((
(b'C', '--cIO',),
(b'S', 'ERROR',),
(b'M', 'Could not unpack element {} from anonymous record'.format(itemnum)),
(b'W', data,),
(b'P', str(itemnum),)
)), cause = cause)
def _unpack_record(data, unpack = io_lib.record_unpack, process_tuple = process_tuple):
record = list(unpack(data))
coloids = tuple(x[0] for x in record)
colio = map(self.resolve, coloids)
column_unpack = tuple(c[1] or self.decode for c in colio)
data = tuple(x[1] for x in record)
return process_tuple(column_unpack, data, raise_unpack_tuple_error)
return (None, _unpack_record)
def raise_client_error(self, error_message, cause = None, creator = None):
m = {
notice_field_to_name[k] : v
for k, v in error_message.items()
# don't include unknown messages in this list.
if k in notice_field_to_name
}
c = m.pop('code')
ms = m.pop('message')
client_error = self.lookup_exception(c)
client_error = client_error(ms, code = c, details = m, source = 'CLIENT', creator = creator or self.database)
client_error.database = self.database
if cause is not None:
raise client_error from cause
else:
raise client_error
def lookup_exception(self, code, errorlookup = pg_exc.ErrorLookup,):
return errorlookup(code)
def lookup_warning(self, code, warninglookup = pg_exc.WarningLookup,):
return warninglookup(code)
def raise_server_error(self, error_message, cause = None, creator = None):
m = dict(self.decode_notice(error_message))
c = m.pop('code')
ms = m.pop('message')
server_error = self.lookup_exception(c)
server_error = server_error(ms, code = c, details = m, source = 'SERVER', creator = creator or self.database)
server_error.database = self.database
if cause is not None:
raise server_error from cause
else:
raise server_error
def raise_error(self, error_message, ClientError = element.ClientError, **kw):
if 'creator' not in kw:
kw['creator'] = getattr(self.database, '_controller', self.database) or self.database
if error_message.__class__ is ClientError:
self.raise_client_error(error_message, **kw)
else:
self.raise_server_error(error_message, **kw)
##
# Used by decode_notice()
def _decode_failsafe(self, data):
decode = self._decode
i = iter(data)
for x in i:
try:
# prematurely optimized for your viewing displeasure.
v = x[1]
yield (x[0], decode(v)[0])
for x in i:
v = x[1]
yield (x[0], decode(v)[0])
except UnicodeDecodeError:
# Fallback to the bytes representation.
# This should be sufficiently informative in most cases,
# and in the cases where it isn't, an element traceback should
# ultimately yield the pertinent information
yield (x[0], repr(x[1])[2:-1])
def decode_notice(self, notice):
notice = self._decode_failsafe(notice.items())
return {
notice_field_to_name[k] : v
for k, v in notice
# don't include unknown messages in this list.
if k in notice_field_to_name
}
def emit_server_message(self, message, creator = None,
MessageType = pg_msg.Message
):
fields = self.decode_notice(message)
m = fields.pop('message')
c = fields.pop('code')
if fields['severity'].upper() == 'WARNING':
MessageType = self.lookup_warning(c)
message = MessageType(m, code = c, details = fields,
creator = creator, source = 'SERVER')
message.database = self.database
message.emit()
return message
def emit_client_message(self, message, creator = None,
MessageType = pg_msg.Message
):
fields = {
notice_field_to_name[k] : v
for k, v in message.items()
# don't include unknown messages in this list.
if k in notice_field_to_name
}
m = fields.pop('message')
c = fields.pop('code')
if fields['severity'].upper() == 'WARNING':
MessageType = self.lookup_warning(c)
message = MessageType(m, code = c, details = fields,
creator = creator, source = 'CLIENT')
message.database = self.database
message.emit()
return message
def emit_message(self, message, ClientNotice = element.ClientNotice, **kw):
if message.__class__ is ClientNotice:
return self.emit_client_message(message, **kw)
else:
return self.emit_server_message(message, **kw)
##
# This class manages all the functionality used to get
# rows from a PostgreSQL portal/cursor.
class Output(object):
_output = None
_output_io = None
_output_formats = None
_output_attmap = None
closed = False
cursor_id = None
statement = None
parameters = None
_complete_message = None
def _init(self):
"""
Bind a cursor based on the configured parameters.
"""
# The local initialization for the specific cursor.
raise NotImplementedError
def __init__(self, cursor_id, wref = weakref.ref, ID = ID):
self.cursor_id = cursor_id
if self.statement is not None:
stmt = self.statement
self._output = stmt._output
self._output_io = stmt._output_io
self._row_constructor = stmt._row_constructor
self._output_formats = stmt._output_formats or ()
self._output_attmap = stmt._output_attmap
self._pq_cursor_id = self.database.typio.encode(cursor_id)
# If the cursor's id was generated, it should be garbage collected.
if cursor_id == ID(self):
self.database.pq.register_cursor(self, self._pq_cursor_id)
self._quoted_cursor_id = '"' + cursor_id.replace('"', '""') + '"'
self._init()
def __iter__(self):
return self
def close(self):
if self.closed is False:
self.database.pq.trash_cursor(self._pq_cursor_id)
self.closed = True
def _ins(self, *args):
return xact.Instruction(*args, asynchook = self.database._receive_async)
def _pq_xp_describe(self):
return (element.DescribePortal(self._pq_cursor_id),)
def _pq_xp_bind(self):
return (
element.Bind(
self._pq_cursor_id,
self.statement._pq_statement_id,
self.statement._input_formats,
self.statement._pq_parameters(self.parameters),
self._output_formats,
),
)
def _pq_xp_fetchall(self):
return (
element.Bind(
b'',
self.statement._pq_statement_id,
self.statement._input_formats,
self.statement._pq_parameters(self.parameters),
self._output_formats,
),
element.Execute(b'', 0xFFFFFFFF),
)
def _pq_xp_declare(self):
return (
element.Parse(b'', self.database.typio.encode(
declare_statement_string(
str(self._quoted_cursor_id),
str(self.statement.string)
)
), ()
),
element.Bind(
b'', b'', self.statement._input_formats,
self.statement._pq_parameters(self.parameters), ()
),
element.Execute(b'', 1),
)
def _pq_xp_execute(self, quantity):
return (
element.Execute(self._pq_cursor_id, quantity),
)
def _pq_xp_fetch(self, direction, quantity):
##
# 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 (
element.Parse(b'', self.database.typio.encode(qstr), ()),
element.Bind(b'', b'', (), (), self._output_formats),
# The "limit" is defined in the fetch query.
element.Execute(b'', 0xFFFFFFFF),
)
def _pq_xp_move(self, position, whence):
return (
element.Parse(b'',
b'MOVE ' + whence + b' ' + position + b' IN ' + \
self.database.typio.encode(self._quoted_cursor_id),
()
),
element.Bind(b'', b'', (), (), ()),
element.Execute(b'', 1),
)
def _process_copy_chunk(self, x):
if x:
if x[0].__class__ is not bytes or x[-1].__class__ is not bytes:
return [
y for y in x if y.__class__ is bytes
]
return x
# Process the element.Tuple message in x for column()
def _process_tuple_chunk_Column(self, x, range = range):
unpack = self._output_io[0]
# get the raw data for the first column
l = [y[0] for y in x]
# iterate over the range to keep track
# of which item we're processing.
r = range(len(l))
try:
return [unpack(l[i]) for i in r]
except Exception:
cause = sys.exc_info()[1]
try:
i = next(r)
except StopIteration:
i = len(l)
self._raise_column_tuple_error(cause, self._output_io, (l[i],), 0)
# Process the element.Tuple message in x for rows()
def _process_tuple_chunk_Row(self, x,
proc = process_chunk,
):
rc = self._row_constructor
return [
rc(y)
for y in proc(self._output_io, x, self._raise_column_tuple_error)
]
# Process the elemnt.Tuple messages in `x` for chunks()
def _process_tuple_chunk(self, x, proc = process_chunk):
return proc(self._output_io, x, self._raise_column_tuple_error)
def _raise_column_tuple_error(self, cause, 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] + ' ...'
em = element.ClientError((
(b'S', 'ERROR'),
(b'C', "--CIO"),
(b'M', "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>',
)
),
(b'D', data),
(b'H', "Try casting the column to 'text'."),
(b'P', str(itemnum)),
))
self.database.typio.raise_client_error(em, creator = self, cause = cause)
@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()))
# `None` if _output does not exist; not row data
@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]
# `None` if _output does not exist; not row data
@property
def pg_column_types(self):
if self._output is not None:
return [x[3] for x in self._output]
# `None` if _output does not exist; not row data
@property
def sql_column_types(self):
return [
self.database.typio.sql_type_from_oid(x)
for x in self.pg_column_types
]
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 Chunks(Output, pg_api.Chunks):
pass
##
# FetchAll - A Chunks cursor that gets *all* the records in the cursor.
#
# It has added complexity over other variants as in order to stream results,
# chunks have to be removed from the protocol transaction's received messages.
# If this wasn't done, the entire result set would be fully buffered prior
# to processing.
class FetchAll(Chunks):
_e_factors = ('statement', 'parameters',)
def _e_metas(self):
yield ('type', type(self).__name__)
def __init__(self, statement, parameters):
self.statement = statement
self.parameters = parameters
self.database = statement.database
Output.__init__(self, '')
def _init(self,
null = element.Null.type,
complete = element.Complete.type,
bindcomplete = element.BindComplete.type,
parsecomplete = element.ParseComplete.type,
):
expect = self._expect
self._xact = self._ins(
self._pq_xp_fetchall() + (element.SynchronizeMessage,)
)
self.database._pq_push(self._xact, self)
# Get more messages until the first Tuple is seen.
STEP = self.database._pq_step
while self._xact.state != xact.Complete:
STEP()
for x in self._xact.messages_received():
if x.__class__ is tuple or expect == x.type:
# No need to step anymore once this is seen.
return
elif x.type == null:
# The protocol transaction is going to be complete..
self.database._pq_complete()
self._xact = None
return
elif x.type == complete:
self._complete_message = x
self.database._pq_complete()
# If this was a select/copy cursor,
# the data messages would have caused an earlier
# return. It's empty.
self._xact = None
return
elif x.type in (bindcomplete, parsecomplete):
# Noise.
pass
else:
# This should have been caught by the protocol transaction.
# "Can't happen".
self.database._pq_complete()
if self._xact.fatal is None:
self._xact.fatal = False
self._xact.error_message = element.ClientError((
(b'S', 'ERROR'),
(b'C', "--000"),
(b'M', "unexpected message type " + repr(x.type))
))
self.database.typio.raise_client_error(self._xact.error_message, creator = self)
return
def __next__(self,
data_types = (tuple,bytes),
complete = element.Complete.type,
):
x = self._xact
# self._xact = None; means that the cursor has been exhausted.
if x is None:
raise StopIteration
# Finish the protocol transaction.
STEP = self.database._pq_step
while x.state is not xact.Complete and not x.completed:
STEP()
# fatal is None == no error
# fatal is True == dead connection
# fatal is False == dead transaction
if x.fatal is not None:
self.database.typio.raise_error(x.error_message, creator = getattr(self, '_controller', self) or self)
# no messages to process?
if not x.completed:
# Transaction has been cleaned out of completed? iterator is done.
self._xact = None
self.close()
raise StopIteration
# Get the chunk to be processed.
chunk = [
y for y in x.completed[0][1]
if y.__class__ in data_types
]
r = self._process_chunk(chunk)
# Scan for _complete_message.
# Arguably, this can fail, but it would be a case
# where multiple sync messages were issued. Something that's
# not naturally occurring.
for y in x.completed[0][1][-3:]:
if getattr(y, 'type', None) == complete:
self._complete_message = y
# Remove it, it's been processed.
del x.completed[0]
return r
class SingleXactCopy(FetchAll):
_expect = element.CopyToBegin.type
_process_chunk = FetchAll._process_copy_chunk
class SingleXactFetch(FetchAll):
_expect = element.Tuple.type
class MultiXactStream(Chunks):
chunksize = 1024 * 4
# only tuple streams
_process_chunk = Output._process_tuple_chunk
def _e_metas(self):
yield ('chunksize', self.chunksize)
yield ('type', self.__class__.__name__)
def __init__(self, statement, parameters, cursor_id):
self.statement = statement
self.parameters = parameters
self.database = statement.database
Output.__init__(self, cursor_id or ID(self))
def _bind(self):
"""
Generate the commands needed to bind the cursor.
"""
raise NotImplementedError
def _fetch(self):
"""
Generate the commands needed to bind the cursor.