-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathpq3.py
More file actions
2417 lines (2165 loc) · 64.4 KB
/
Copy pathpq3.py
File metadata and controls
2417 lines (2165 loc) · 64.4 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 using PQ version 3.0.
"""
import os
import weakref
import socket
from traceback import format_exception
from operator import itemgetter
get0 = itemgetter(0)
get1 = itemgetter(1)
from itertools import repeat, chain
from abc import abstractmethod
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 ..encodings import aliases as pg_enc_aliases
from ..python.itertools import interlace, chunk
from ..python.socket import SocketFactory
from ..protocol import xact3 as xact
from ..protocol import element3 as element
from ..protocol import client3 as client
from ..protocol import typio as pg_typio
from .. import types as pg_types
IDNS = 'py:%s'
def ID(s, title = None):
'generate an id for a client statement or cursor'
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_typio.TypeIO):
def __init__(self, database):
self.database = database
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)
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
@abstractmethod
def _init(self):
"""
Bind a cursor based on the configured parameters.
"""
def __init__(self, cursor_id):
self.cursor_id = cursor_id
if self.statement is not None:
self._output = self.statement._output
self._output_io = self.statement._output_io
self._output_formats = self.statement._output_formats or ()
self._output_attmap = self.statement._output_attmap
if self.cursor_id == ID(self):
addgarbage = self.database.pq.garbage_cursors.append
typio = self.database.typio
self._del = weakref.ref(
self, lambda x: addgarbage(typio.encode(cursor_id))
)
self._quoted_cursor_id = '"' + self.cursor_id.replace('"', '""') + '"'
self._pq_cursor_id = self.database.typio.encode(self.cursor_id)
self._init()
def __iter__(self):
return self
def close(self):
if self.closed is False:
self.database.pq.garbage_cursors.append(
self.database.typio.encode(self.cursor_id)
)
self.closed = True
if hasattr(self, '_del'):
del self._del
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):
'make a command sequence for a MOVE single command'
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
def _process_tuple_chunk_Row(self, x):
"""
Process the Tuple messages in `x`.
"""
return [
pg_types.Row.from_sequence(self._output_attmap, y)
for y in pg_typio.process_chunk(
self._output_io, x, self._raise_column_tuple_error
)
]
def _process_tuple_chunk(self, x):
"""
Process the Tuple messages in `x`.
"""
return pg_typio.process_chunk(
self._output_io, x, self._raise_column_tuple_error
)
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] + ' ...'
em = element.ClientError(
code = "--CIO",
message = "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>',
),
detail = data,
hint = "Try casting the column to 'text'.",
position = str(itemnum),
)
self.database._raise_a_pq_error(em, controller = self)
# "can't happen"
raise RuntimeError("failed to raise client error")
@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 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
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,
):
expect = self._expect
self._xact = self._ins(
self._pq_xp_fetchall() + (element.SynchronizeMessage,)
)
self.database._pq_push(self._xact, self)
while self._xact.state != xact.Complete:
self.database._pq_step()
for x in self._xact.messages_received():
if x.type == null:
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.
self._xact = None
return
elif x.type == expect:
# no need to step once this is seen
return
elif x.type in (
element.BindComplete.type, element.ParseComplete.type
):
pass
else:
self.database._pq_complete()
if self._xact.fatal is None:
self._xact.fatal = False
self._xact.error_message = element.ClientError(
code = "--000",
message = "unexpected message type " + repr(x.type)
)
self.database._raise_pq_error(self._xact, controller = self)
return
def __next__(self):
x = self._xact
if x is None:
raise StopIteration
while x.state is not xact.Complete and not x.completed:
self.database._pq_step()
if x.fatal is not None:
self.database._raise_pq_error(x, controller = self)
if not x.completed:
# Transaction has been cleaned out of completed? iterator is done.
self._xact = None
raise StopIteration
chunk = x.completed[0][1]
r = self._process_chunk(chunk)
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
_process_chunk_ = FetchAll._process_tuple_chunk_Row
def _process_chunk(self, x,
tuple_type = element.Tuple.type
):
return self._process_chunk_((
y for y in x if y.type == tuple_type
))
class MultiXactStream(Chunks):
chunksize = 512
# only tuple streams
_process_chunk = Output._process_tuple_chunk_Row
def _e_metas(self):
yield ('chunksize', self.chunksize)
yield ('type', type(self).__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))
@abstractmethod
def _bind(self):
"""
Generate the commands needed to bind the cursor.
"""
@abstractmethod
def _fetch(self):
"""
Generate the commands needed to bind the cursor.
"""
def _init(self):
self._command = self._fetch()
self._xact = self._ins(self._bind() + self._command)
self.database._pq_push(self._xact, self)
def __next__(self):
x = self._xact
if x is None:
raise StopIteration
if self.database.pq.xact is x:
self.database._pq_complete()
chunk = [
y for y in x.messages_received() if y.type == element.Tuple.type
]
if len(chunk) == self.chunksize:
# there may be more, dispatch the request for the next chunk
self._xact = self._ins(self._command)
self.database._pq_push(self._xact, self)
else:
# it's done.
self._xact = None
if not chunk:
raise StopIteration
chunk = self._process_chunk(chunk)
return chunk
class MultiXactInsideBlock(MultiXactStream):
_bind = MultiXactStream._pq_xp_bind
def _fetch(self):
return self._pq_xp_execute(self.chunksize) + \
(element.SynchronizeMessage,)
class MultiXactOutsideBlock(MultiXactStream):
_bind = MultiXactStream._pq_xp_declare
def _fetch(self):
return self._pq_xp_fetch(True, self.chunksize) + \
(element.SynchronizeMessage,)
##
# Base Cursor class and cursor creation entry points.
class Cursor(Output, pg_api.Cursor):
_process_tuple = Output._process_tuple_chunk_Row
def _e_metas(self):
yield ('direction', 'FORWARD' if self.direction else 'BACKWORD')
yield ('type', 'Cursor')
def clone(self):
return type(self)(self.statement, self.parameters, self.database, None)
def __init__(self, statement, parameters, database, cursor_id):
self.database = database or statement.database
self.statement = statement
self.parameters = parameters
self.__dict__['direction'] = True
if self.statement is None:
self._e_factors = ('database', 'cursor_id')
Output.__init__(self, cursor_id or ID(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 _init(self,
tupledesc = element.TupleDescriptor.type,
):
"""
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:
x = self._ins(self._pq_xp_declare() + (element.SynchronizeMessage,))
self.database._pq_push(x, self)
self.database._pq_complete()
else:
x = self._ins(self._pq_xp_describe() + (element.SynchronizeMessage,))
self.database._pq_push(x, self)
self.database._pq_complete()
for m in x.messages_received():
if m.type == tupledesc:
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 = [
element.StringFormat
if x is None
else element.BinaryFormat
for x in self._output_io
]
self._output_io = tuple([
x or self.database.typio.decode for x in self._output_io
])
def __next__(self):
return self._fetch(self.direction, 1)
def read(self, quantity = None, direction = None):
if quantity == 0:
return []
dir = self._which_way(direction)
return self._fetch(dir, quantity)
def _fetch(self, direction, quantity):
x = self._ins(
self._pq_xp_fetch(direction, quantity) + \
(element.SynchronizeMessage,)
)
self.database._pq_push(x, self)
self.database._pq_complete()
return self._process_tuple((
y for y in x.messages_received() if y.type == element.Tuple.type
))
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 = self._ins(cmd + (element.SynchronizeMessage,),)
self.database._pq_push(x, self)
self.database._pq_complete()
class PreparedStatement(pg_api.PreparedStatement):
string = None
database = None
statement_id = None
_input = None
_output = None
_output_io = None
_output_formats = None
_output_attmap = None
def _e_metas(self):
yield (None, '[' + self.state + ']')
if hasattr(self._xact, 'error_message'):
# be very careful not to trigger an exception.
# even in the cases of effective protocol errors,
# it is important not to bomb out.
pos = self._xact.error_message.get('position')
if pos is not None and pos.isdigit():
try:
pos = int(pos)
# get the statement source
q = str(self.string)
# normalize position..
pos = len('\n'.join(q[:pos].splitlines()))
# normalize newlines
q = '\n'.join(q.splitlines())
line_no = q.count('\n', 0, pos) + 1
# replace tabs with spaces because there is no way to identify
# the tab size of the final display. (ie, marker will be wrong)
q = q.replace('\t', ' ')
# grab the relevant part of the query string.
# the full source will be printed elsewhere.
# beginning of string or the newline before the position
bov = q.rfind('\n', 0, pos) + 1
# end of string or the newline after the position
eov = q.find('\n', pos)
if eov == -1:
eov = len(q)
view = q[bov:eov]
# position relative to the beginning of the view
pos = pos-bov
# analyze lines prior to position
dlines = view.splitlines()
marker = ((pos-1) * ' ') + '^' + (
' [line %d, character %d] ' %(line_no, pos)
)
# insert marker
dlines.append(marker)
yield ('LINE', os.linesep.join(dlines))
except:
import traceback
yield ('LINE', traceback.format_exc(chain=False))
spt = self.sql_parameter_types
if spt is not None:
yield ('sql_parameter_types', spt)
cn = self.column_names
ct = self.sql_column_types
if cn is not None:
if ct is not None:
yield (
'results',
'(' + ', '.join([
n + ' ' + t for n,t in zip(cn,ct)
]) + ')'
)
else:
yield ('sql_column_names', cn)
elif ct is not None:
yield ('sql_column_types', ct)
def clone(self):
ps = type(self)(self.database, None, self.string)
ps._init()
ps._fini()
return ps
def __init__(self, database, statement_id, string):
self.database = database
self.statement_id = statement_id or ID(self)
self.string = string
self._xact = None
self._pq_statement_id = None
self.closed = None
if not statement_id:
addgarbage = database.pq.garbage_statements.append
typio = database.typio
sid = self.statement_id
self._del = weakref.ref(
self, lambda x: addgarbage(typio.encode(sid))
)
def __repr__(self):
return '<{mod}.{name}[{ci}] {state}>'.format(
mod = type(self).__module__,
name = type(self).__name__,
ci = self.database.connector._pq_iri,
state = self.state,
)
def _pq_parameters(self, parameters):
return pg_typio.process_tuple(
self._input_io, parameters,
self._raise_parameter_tuple_error
)
def _raise_parameter_tuple_error(self, procs, tup, itemnum):
typ = self.database.typio.sql_type_from_oid(
self.pg_parameter_types[itemnum]
) or '<unknown>'
data = repr(tup[itemnum])
if len(data) > 80:
# Be sure not to fill screen with noise.
data = data[:75] + ' ...'
em = element.ClientError(
message = "failed to pack parameter %s::%s for transfer" %(
('$' + str(itemnum + 1)), typ,
),
code = '--PIO',
detail = data,
hint = "Try casting the parameter to 'text', then to the target type.",
position = str(itemnum)
)
self.database._raise_a_pq_error(em, controller = self)
raise RuntimeError("failed to raise client error")
def _raise_column_tuple_error(self, procs, tup, itemnum):
typ = self.database.typio.sql_type_from_oid(
self.pg_column_types(itemnum)
) or '<unknown>'
data = repr(tup[itemnum])
if len(data) > 80:
# Be sure not to fill screen with noise.
data = data[:75] + ' ...'
em = element.ClientError(
message = "failed to unpack column %r, %s::%s, from wire data" %(
itemnum, self.column_names[itemnum], typ
),
code = "--CIO",
detail = data,
hint = "Try casting the column to 'text'.",
position = str(itemnum),
)
self.database._raise_a_pq_error(em, controller = self)
# "can't happen"
raise RuntimeError("failed to raise client error")
@property
def state(self) -> str:
if self.closed:
if self._xact is not None:
if self.string is not None:
return 'parsing'
else:
return 'describing'
return 'closed'
return 'prepared'
@property
def column_names(self):
if self.closed is None:
self._fini()
if self._output is not None:
return list(self.database.typio.decodes(self._output.keys()))
@property
def parameter_types(self):
if self.closed is None:
self._fini()
if self._input is not None:
return [self.database.typio.type_from_oid(x) for x in self._input]
@property
def column_types(self):
if self.closed is None:
self._fini()
if self._output is not None:
return [
self.database.typio.type_from_oid(x[3]) for x in self._output
]
@property
def pg_parameter_types(self):
if self.closed is None:
self._fini()
return self._input
@property
def pg_column_types(self):
if self.closed is None:
self._fini()
if self._output is not None:
return [x[3] for x in self._output]
@property
def sql_column_types(self):
if self.closed is None:
self._fini()
if self._output is not None:
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
]
@property
def sql_parameter_types(self):
if self.closed is None:
self._fini()
if self._input is not None:
return [
pg_types.oid_to_sql_name.get(x) or \
self.database.typio.sql_type_from_oid(x)
for x in self.pg_parameter_types
]
def close(self):
if self.closed is False:
self.database.pq.garbage_statements.append(self._pq_statement_id)
self.closed = True
if hasattr(self, '_del'):
del self._del
def _init(self):
"""
Push initialization messages to the server, but don't wait for
the return as there may be things that can be done while waiting
for the return. Use the _fini() to complete.
"""
self._pq_statement_id = self.database.typio._encode(
self.statement_id
)[0]
if self.string is not None:
q = self.database.typio._encode(str(self.string))[0]
cmd = [
element.CloseStatement(self._pq_statement_id),
element.Parse(self._pq_statement_id, q, ()),
]
else:
cmd = []
cmd.extend(
(
element.DescribeStatement(self._pq_statement_id),
element.SynchronizeMessage,
)
)
self._xact = xact.Instruction(cmd, asynchook = self.database._receive_async)
self.database._pq_push(self._xact, self)
def _fini(self):
"""
Complete initialization that the _init() method started.
"""
# assume that the transaction has been primed.
if self._xact is None:
raise RuntimeError("_fini called prior to _init; invalid state")
if self._xact is self.database.pq.xact:
try:
self.database._pq_complete()
except Exception:
self.closed = True
raise
(*head, argtypes, tupdesc, last) = self._xact.messages_received()
if tupdesc is None or tupdesc is element.NoDataMessage:
# Not typed output.
self._output = None
self._output_attmap = None
self._output_io = None
self._output_formats = None
else:
self._output = tupdesc
self._output_attmap = dict(
self.database.typio.attribute_map(tupdesc)
)
# tuple output
self._output_io = \
self.database.typio.resolve_descriptor(tupdesc, 1)
self._output_formats = [
element.StringFormat
if x is None
else element.BinaryFormat
for x in self._output_io
]
self._output_io = tuple([
x or self.database.typio.decode for x in self._output_io
])
self._input = argtypes
packs = []
formats = []
for x in argtypes:
pack = (self.database.typio.resolve(x) or (None,None))[0]
packs.append(pack or self.database.typio.encode)
formats.append(
element.StringFormat
if x is None
else element.BinaryFormat
)
self._input_io = tuple(packs)
self._input_formats = formats
self.closed = False
self._xact = None
def __call__(self, *parameters):
if self._input is not None:
if len(parameters) != len(self._input):
raise TypeError("statement requires %d parameters, given %d" %(
len(self._input), len(parameters)
))
# get em' all!
if self._output is None:
# might be a copy.
c = SingleXactCopy(self, parameters)
else:
c = SingleXactFetch(self, parameters)
# iff output is None, it's not a tuple returning query.
# however, if it's a copy, detect that fact by SingleXactCopy's
# immediate return after finding the copy begin message(no complete).
if self._output is None and c.command() is not None:
return (c.command(), c.count())
else:
r = []
for x in c:
r.extend(x)
return r
def declare(self, *parameters):
if self.closed is None:
self._fini()
if self._input is not None:
if len(parameters) != len(self._input):
raise TypeError("statement requires %d parameters, given %d" %(
len(self._input), len(parameters)
))
return Cursor(self, parameters, self.database, None)
def rows(self, *parameters, **kw):
return chain.from_iterable(self.chunks(*parameters, **kw))
__iter__ = rows
def chunks(self, *parameters):
if self.closed is None:
self._fini()
if self._input is not None:
if len(parameters) != len(self._input):
raise TypeError("statement requires %d parameters, given %d" %(
len(self._input), len(parameters)
))
if self._output is None:
return SingleXactCopy(self, parameters)
if self.database.pq.state == b'I':
if self.string is not None:
return MultiXactOutsideBlock(self, parameters, None)
else:
# statement source unknown, so it can't be DECLARE'd.
return SingleXactFetch(self, parameters)
else:
return MultiXactInsideBlock(self, parameters, None)
def first(self, *parameters):
if self.closed is None:
self._fini()
if self._input is not None:
if len(parameters) != len(self._input):
raise TypeError("statement requires %d parameters, given %d" %(
len(self._input), len(parameters)
))
# Parameters? Build em'.
db = self.database
if self._input_io:
params = pg_typio.process_tuple(
self._input_io, parameters,
self._raise_parameter_tuple_error
)
else:
params = ()
# Run the statement
x = xact.Instruction((
element.Bind(
b'',
self._pq_statement_id,
self._input_formats,
params,
self._output_formats or (),
),
# Get all
element.Execute(b'', 0xFFFFFFFF),
element.SynchronizeMessage
),
asynchook = db._receive_async
)
db._pq_push(x, self)
db._pq_complete()
if self._output_io:
##
# Look for the first tuple.
tuple_type = element.Tuple.type
for xt in x.messages_received():