/
coreproto.pyx
1153 lines (899 loc) · 37.1 KB
/
coreproto.pyx
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 (C) 2016-present the asyncpg authors and contributors
# <see AUTHORS file>
#
# This module is part of asyncpg and is released under
# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0
import hashlib
include "scram.pyx"
cdef class CoreProtocol:
def __init__(self, con_params):
# type of `con_params` is `_ConnectionParameters`
self.buffer = ReadBuffer()
self.user = con_params.user
self.password = con_params.password
self.auth_msg = None
self.con_params = con_params
self.con_status = CONNECTION_BAD
self.state = PROTOCOL_IDLE
self.xact_status = PQTRANS_IDLE
self.encoding = 'utf-8'
# type of `scram` is `SCRAMAuthentcation`
self.scram = None
self._reset_result()
cpdef is_in_transaction(self):
# PQTRANS_INTRANS = idle, within transaction block
# PQTRANS_INERROR = idle, within failed transaction
return self.xact_status in (PQTRANS_INTRANS, PQTRANS_INERROR)
cdef _read_server_messages(self):
cdef:
char mtype
ProtocolState state
pgproto.take_message_method take_message = \
<pgproto.take_message_method>self.buffer.take_message
pgproto.get_message_type_method get_message_type= \
<pgproto.get_message_type_method>self.buffer.get_message_type
while take_message(self.buffer) == 1:
mtype = get_message_type(self.buffer)
state = self.state
try:
if mtype == b'S':
# ParameterStatus
self._parse_msg_parameter_status()
elif mtype == b'A':
# NotificationResponse
self._parse_msg_notification()
elif mtype == b'N':
# 'N' - NoticeResponse
self._on_notice(self._parse_msg_error_response(False))
elif state == PROTOCOL_AUTH:
self._process__auth(mtype)
elif state == PROTOCOL_PREPARE:
self._process__prepare(mtype)
elif state == PROTOCOL_BIND_EXECUTE:
self._process__bind_execute(mtype)
elif state == PROTOCOL_BIND_EXECUTE_MANY:
self._process__bind_execute_many(mtype)
elif state == PROTOCOL_EXECUTE:
self._process__bind_execute(mtype)
elif state == PROTOCOL_BIND:
self._process__bind(mtype)
elif state == PROTOCOL_CLOSE_STMT_PORTAL:
self._process__close_stmt_portal(mtype)
elif state == PROTOCOL_SIMPLE_QUERY:
self._process__simple_query(mtype)
elif state == PROTOCOL_COPY_OUT:
self._process__copy_out(mtype)
elif (state == PROTOCOL_COPY_OUT_DATA or
state == PROTOCOL_COPY_OUT_DONE):
self._process__copy_out_data(mtype)
elif state == PROTOCOL_COPY_IN:
self._process__copy_in(mtype)
elif state == PROTOCOL_COPY_IN_DATA:
self._process__copy_in_data(mtype)
elif state == PROTOCOL_CANCELLED:
# discard all messages until the sync message
if mtype == b'E':
self._parse_msg_error_response(True)
elif mtype == b'Z':
self._parse_msg_ready_for_query()
self._push_result()
else:
self.buffer.discard_message()
elif state == PROTOCOL_ERROR_CONSUME:
# Error in protocol (on asyncpg side);
# discard all messages until sync message
if mtype == b'Z':
# Sync point, self to push the result
if self.result_type != RESULT_FAILED:
self.result_type = RESULT_FAILED
self.result = apg_exc.InternalClientError(
'unknown error in protocol implementation')
self._parse_msg_ready_for_query()
self._push_result()
else:
self.buffer.discard_message()
elif state == PROTOCOL_TERMINATING:
# The connection is being terminated.
# discard all messages until connection
# termination.
self.buffer.discard_message()
else:
raise apg_exc.InternalClientError(
f'cannot process message {chr(mtype)!r}: '
f'protocol is in an unexpected state {state!r}.')
except Exception as ex:
self.result_type = RESULT_FAILED
self.result = ex
if mtype == b'Z':
self._push_result()
else:
self.state = PROTOCOL_ERROR_CONSUME
finally:
self.buffer.finish_message()
cdef _process__auth(self, char mtype):
if mtype == b'R':
# Authentication...
try:
self._parse_msg_authentication()
except Exception as ex:
# Exception in authentication parsing code
# is usually either malformed authentication data
# or missing support for cryptographic primitives
# in the hashlib module.
self.result_type = RESULT_FAILED
self.result = apg_exc.InternalClientError(
f"unexpected error while performing authentication: {ex}")
self.result.__cause__ = ex
self.con_status = CONNECTION_BAD
self._push_result()
else:
if self.result_type != RESULT_OK:
self.con_status = CONNECTION_BAD
self._push_result()
elif self.auth_msg is not None:
# Server wants us to send auth data, so do that.
self._write(self.auth_msg)
self.auth_msg = None
elif mtype == b'K':
# BackendKeyData
self._parse_msg_backend_key_data()
elif mtype == b'E':
# ErrorResponse
self.con_status = CONNECTION_BAD
self._parse_msg_error_response(True)
self._push_result()
elif mtype == b'Z':
# ReadyForQuery
self._parse_msg_ready_for_query()
self.con_status = CONNECTION_OK
self._push_result()
cdef _process__prepare(self, char mtype):
if mtype == b't':
# Parameters description
self.result_param_desc = self.buffer.consume_message()
elif mtype == b'1':
# ParseComplete
self.buffer.discard_message()
elif mtype == b'T':
# Row description
self.result_row_desc = self.buffer.consume_message()
self._push_result()
elif mtype == b'E':
# ErrorResponse
self._parse_msg_error_response(True)
# we don't send a sync during the parse/describe sequence
# but send a FLUSH instead. If an error happens we need to
# send a SYNC explicitly in order to mark the end of the transaction.
# this effectively clears the error and we then wait until we get a
# ready for new query message
self._write(SYNC_MESSAGE)
self.state = PROTOCOL_ERROR_CONSUME
elif mtype == b'n':
# NoData
self.buffer.discard_message()
self._push_result()
cdef _process__bind_execute(self, char mtype):
if mtype == b'D':
# DataRow
self._parse_data_msgs()
elif mtype == b's':
# PortalSuspended
self.buffer.discard_message()
elif mtype == b'C':
# CommandComplete
self.result_execute_completed = True
self._parse_msg_command_complete()
elif mtype == b'E':
# ErrorResponse
self._parse_msg_error_response(True)
elif mtype == b'1':
# ParseComplete, in case `_bind_execute()` is reparsing
self.buffer.discard_message()
elif mtype == b'2':
# BindComplete
self.buffer.discard_message()
elif mtype == b'Z':
# ReadyForQuery
self._parse_msg_ready_for_query()
self._push_result()
elif mtype == b'I':
# EmptyQueryResponse
self.buffer.discard_message()
cdef _process__bind_execute_many(self, char mtype):
cdef WriteBuffer buf
if mtype == b'D':
# DataRow
self._parse_data_msgs()
elif mtype == b's':
# PortalSuspended
self.buffer.discard_message()
elif mtype == b'C':
# CommandComplete
self._parse_msg_command_complete()
elif mtype == b'E':
# ErrorResponse
self._parse_msg_error_response(True)
elif mtype == b'1':
# ParseComplete, in case `_bind_execute_many()` is reparsing
self.buffer.discard_message()
elif mtype == b'2':
# BindComplete
self.buffer.discard_message()
elif mtype == b'Z':
# ReadyForQuery
self._parse_msg_ready_for_query()
self._push_result()
elif mtype == b'I':
# EmptyQueryResponse
self.buffer.discard_message()
elif mtype == b'1':
# ParseComplete
self.buffer.discard_message()
cdef _process__bind(self, char mtype):
if mtype == b'E':
# ErrorResponse
self._parse_msg_error_response(True)
elif mtype == b'2':
# BindComplete
self.buffer.discard_message()
elif mtype == b'Z':
# ReadyForQuery
self._parse_msg_ready_for_query()
self._push_result()
cdef _process__close_stmt_portal(self, char mtype):
if mtype == b'E':
# ErrorResponse
self._parse_msg_error_response(True)
elif mtype == b'3':
# CloseComplete
self.buffer.discard_message()
elif mtype == b'Z':
# ReadyForQuery
self._parse_msg_ready_for_query()
self._push_result()
cdef _process__simple_query(self, char mtype):
if mtype in {b'D', b'I', b'T'}:
# 'D' - DataRow
# 'I' - EmptyQueryResponse
# 'T' - RowDescription
self.buffer.discard_message()
elif mtype == b'E':
# ErrorResponse
self._parse_msg_error_response(True)
elif mtype == b'Z':
# ReadyForQuery
self._parse_msg_ready_for_query()
self._push_result()
elif mtype == b'C':
# CommandComplete
self._parse_msg_command_complete()
else:
# We don't really care about COPY IN etc
self.buffer.discard_message()
cdef _process__copy_out(self, char mtype):
if mtype == b'E':
self._parse_msg_error_response(True)
elif mtype == b'H':
# CopyOutResponse
self._set_state(PROTOCOL_COPY_OUT_DATA)
self.buffer.discard_message()
elif mtype == b'Z':
# ReadyForQuery
self._parse_msg_ready_for_query()
self._push_result()
cdef _process__copy_out_data(self, char mtype):
if mtype == b'E':
self._parse_msg_error_response(True)
elif mtype == b'd':
# CopyData
self._parse_copy_data_msgs()
elif mtype == b'c':
# CopyDone
self.buffer.discard_message()
self._set_state(PROTOCOL_COPY_OUT_DONE)
elif mtype == b'C':
# CommandComplete
self._parse_msg_command_complete()
elif mtype == b'Z':
# ReadyForQuery
self._parse_msg_ready_for_query()
self._push_result()
cdef _process__copy_in(self, char mtype):
if mtype == b'E':
self._parse_msg_error_response(True)
elif mtype == b'G':
# CopyInResponse
self._set_state(PROTOCOL_COPY_IN_DATA)
self.buffer.discard_message()
elif mtype == b'Z':
# ReadyForQuery
self._parse_msg_ready_for_query()
self._push_result()
cdef _process__copy_in_data(self, char mtype):
if mtype == b'E':
self._parse_msg_error_response(True)
elif mtype == b'C':
# CommandComplete
self._parse_msg_command_complete()
elif mtype == b'Z':
# ReadyForQuery
self._parse_msg_ready_for_query()
self._push_result()
cdef _parse_msg_command_complete(self):
cdef:
const char* cbuf
ssize_t cbuf_len
cbuf = self.buffer.try_consume_message(&cbuf_len)
if cbuf != NULL and cbuf_len > 0:
msg = cpython.PyBytes_FromStringAndSize(cbuf, cbuf_len - 1)
else:
msg = self.buffer.read_null_str()
self.result_status_msg = msg
cdef _parse_copy_data_msgs(self):
cdef:
ReadBuffer buf = self.buffer
self.result = buf.consume_messages(b'd')
# By this point we have consumed all CopyData messages
# in the inbound buffer. If there are no messages left
# in the buffer, we need to push the accumulated data
# out to the caller in anticipation of the new CopyData
# batch. If there _are_ non-CopyData messages left,
# we must not push the result here and let the
# _process__copy_out_data subprotocol do the job.
if not buf.take_message():
self._on_result()
self.result = None
else:
# If there is a message in the buffer, put it back to
# be processed by the next protocol iteration.
buf.put_message()
cdef _write_copy_data_msg(self, object data):
cdef:
WriteBuffer buf
object mview
Py_buffer *pybuf
mview = cpythonx.PyMemoryView_GetContiguous(
data, cpython.PyBUF_READ, b'C')
try:
pybuf = cpythonx.PyMemoryView_GET_BUFFER(mview)
buf = WriteBuffer.new_message(b'd')
buf.write_cstr(<const char *>pybuf.buf, pybuf.len)
buf.end_message()
finally:
mview.release()
self._write(buf)
cdef _write_copy_done_msg(self):
cdef:
WriteBuffer buf
buf = WriteBuffer.new_message(b'c')
buf.end_message()
self._write(buf)
cdef _write_copy_fail_msg(self, str cause):
cdef:
WriteBuffer buf
buf = WriteBuffer.new_message(b'f')
buf.write_str(cause or '', self.encoding)
buf.end_message()
self._write(buf)
cdef _parse_data_msgs(self):
cdef:
ReadBuffer buf = self.buffer
list rows
decode_row_method decoder = <decode_row_method>self._decode_row
pgproto.try_consume_message_method try_consume_message = \
<pgproto.try_consume_message_method>buf.try_consume_message
pgproto.take_message_type_method take_message_type = \
<pgproto.take_message_type_method>buf.take_message_type
const char* cbuf
ssize_t cbuf_len
object row
bytes mem
if PG_DEBUG:
if buf.get_message_type() != b'D':
raise apg_exc.InternalClientError(
'_parse_data_msgs: first message is not "D"')
if self._discard_data:
while take_message_type(buf, b'D'):
buf.discard_message()
return
if PG_DEBUG:
if type(self.result) is not list:
raise apg_exc.InternalClientError(
'_parse_data_msgs: result is not a list, but {!r}'.
format(self.result))
rows = self.result
while take_message_type(buf, b'D'):
cbuf = try_consume_message(buf, &cbuf_len)
if cbuf != NULL:
row = decoder(self, cbuf, cbuf_len)
else:
mem = buf.consume_message()
row = decoder(
self,
cpython.PyBytes_AS_STRING(mem),
cpython.PyBytes_GET_SIZE(mem))
cpython.PyList_Append(rows, row)
cdef _parse_msg_backend_key_data(self):
self.backend_pid = self.buffer.read_int32()
self.backend_secret = self.buffer.read_int32()
cdef _parse_msg_parameter_status(self):
name = self.buffer.read_null_str()
name = name.decode(self.encoding)
val = self.buffer.read_null_str()
val = val.decode(self.encoding)
self._set_server_parameter(name, val)
cdef _parse_msg_notification(self):
pid = self.buffer.read_int32()
channel = self.buffer.read_null_str().decode(self.encoding)
payload = self.buffer.read_null_str().decode(self.encoding)
self._on_notification(pid, channel, payload)
cdef _parse_msg_authentication(self):
cdef:
int32_t status
bytes md5_salt
list sasl_auth_methods
list unsupported_sasl_auth_methods
status = self.buffer.read_int32()
if status == AUTH_SUCCESSFUL:
# AuthenticationOk
self.result_type = RESULT_OK
elif status == AUTH_REQUIRED_PASSWORD:
# AuthenticationCleartextPassword
self.result_type = RESULT_OK
self.auth_msg = self._auth_password_message_cleartext()
elif status == AUTH_REQUIRED_PASSWORDMD5:
# AuthenticationMD5Password
# Note: MD5 salt is passed as a four-byte sequence
md5_salt = self.buffer.read_bytes(4)
self.auth_msg = self._auth_password_message_md5(md5_salt)
elif status == AUTH_REQUIRED_SASL:
# AuthenticationSASL
# This requires making additional requests to the server in order
# to follow the SCRAM protocol defined in RFC 5802.
# get the SASL authentication methods that the server is providing
sasl_auth_methods = []
unsupported_sasl_auth_methods = []
# determine if the advertised authentication methods are supported,
# and if so, add them to the list
auth_method = self.buffer.read_null_str()
while auth_method:
if auth_method in SCRAMAuthentication.AUTHENTICATION_METHODS:
sasl_auth_methods.append(auth_method)
else:
unsupported_sasl_auth_methods.append(auth_method)
auth_method = self.buffer.read_null_str()
# if none of the advertised authentication methods are supported,
# raise an error
# otherwise, initialize the SASL authentication exchange
if not sasl_auth_methods:
unsupported_sasl_auth_methods = [m.decode("ascii")
for m in unsupported_sasl_auth_methods]
self.result_type = RESULT_FAILED
self.result = apg_exc.InterfaceError(
'unsupported SASL Authentication methods requested by the '
'server: {!r}'.format(
", ".join(unsupported_sasl_auth_methods)))
else:
self.auth_msg = self._auth_password_message_sasl_initial(
sasl_auth_methods)
elif status == AUTH_SASL_CONTINUE:
# AUTH_SASL_CONTINUE
# this requeires sending the second part of the SASL exchange, where
# the client parses information back from the server and determines
# if this is valid.
# The client builds a challenge response to the server
server_response = self.buffer.consume_message()
self.auth_msg = self._auth_password_message_sasl_continue(
server_response)
elif status == AUTH_SASL_FINAL:
# AUTH_SASL_FINAL
server_response = self.buffer.consume_message()
if not self.scram.verify_server_final_message(server_response):
self.result_type = RESULT_FAILED
self.result = apg_exc.InterfaceError(
'could not verify server signature for '
'SCRAM authentciation: scram-sha-256',
)
elif status in (AUTH_REQUIRED_KERBEROS, AUTH_REQUIRED_SCMCRED,
AUTH_REQUIRED_GSS, AUTH_REQUIRED_GSS_CONTINUE,
AUTH_REQUIRED_SSPI):
self.result_type = RESULT_FAILED
self.result = apg_exc.InterfaceError(
'unsupported authentication method requested by the '
'server: {!r}'.format(AUTH_METHOD_NAME[status]))
else:
self.result_type = RESULT_FAILED
self.result = apg_exc.InterfaceError(
'unsupported authentication method requested by the '
'server: {}'.format(status))
if status not in [AUTH_SASL_CONTINUE, AUTH_SASL_FINAL]:
self.buffer.discard_message()
cdef _auth_password_message_cleartext(self):
cdef:
WriteBuffer msg
msg = WriteBuffer.new_message(b'p')
msg.write_bytestring(self.password.encode('ascii'))
msg.end_message()
return msg
cdef _auth_password_message_md5(self, bytes salt):
cdef:
WriteBuffer msg
msg = WriteBuffer.new_message(b'p')
# 'md5' + md5(md5(password + username) + salt))
userpass = ((self.password or '') + (self.user or '')).encode('ascii')
hash = hashlib.md5(hashlib.md5(userpass).hexdigest().\
encode('ascii') + salt).hexdigest().encode('ascii')
msg.write_bytestring(b'md5' + hash)
msg.end_message()
return msg
cdef _auth_password_message_sasl_initial(self, list sasl_auth_methods):
cdef:
WriteBuffer msg
# use the first supported advertized mechanism
self.scram = SCRAMAuthentication(sasl_auth_methods[0])
# this involves a call and response with the server
msg = WriteBuffer.new_message(b'p')
msg.write_bytes(self.scram.create_client_first_message(self.user or ''))
msg.end_message()
return msg
cdef _auth_password_message_sasl_continue(self, bytes server_response):
cdef:
WriteBuffer msg
# determine if there is a valid server response
self.scram.parse_server_first_message(server_response)
# this involves a call and response with the server
msg = WriteBuffer.new_message(b'p')
client_final_message = self.scram.create_client_final_message(
self.password or '')
msg.write_bytes(client_final_message)
msg.end_message()
return msg
cdef _parse_msg_ready_for_query(self):
cdef char status = self.buffer.read_byte()
if status == b'I':
self.xact_status = PQTRANS_IDLE
elif status == b'T':
self.xact_status = PQTRANS_INTRANS
elif status == b'E':
self.xact_status = PQTRANS_INERROR
else:
self.xact_status = PQTRANS_UNKNOWN
cdef _parse_msg_error_response(self, is_error):
cdef:
char code
bytes message
dict parsed = {}
while True:
code = self.buffer.read_byte()
if code == 0:
break
message = self.buffer.read_null_str()
parsed[chr(code)] = message.decode()
if is_error:
self.result_type = RESULT_FAILED
self.result = parsed
else:
return parsed
cdef _push_result(self):
try:
self._on_result()
finally:
self._set_state(PROTOCOL_IDLE)
self._reset_result()
cdef _reset_result(self):
self.result_type = RESULT_OK
self.result = None
self.result_param_desc = None
self.result_row_desc = None
self.result_status_msg = None
self.result_execute_completed = False
self._discard_data = False
# executemany support data
self._execute_iter = None
self._execute_portal_name = None
self._execute_stmt_name = None
cdef _set_state(self, ProtocolState new_state):
if new_state == PROTOCOL_IDLE:
if self.state == PROTOCOL_FAILED:
raise apg_exc.InternalClientError(
'cannot switch to "idle" state; '
'protocol is in the "failed" state')
elif self.state == PROTOCOL_IDLE:
pass
else:
self.state = new_state
elif new_state == PROTOCOL_FAILED:
self.state = PROTOCOL_FAILED
elif new_state == PROTOCOL_CANCELLED:
self.state = PROTOCOL_CANCELLED
elif new_state == PROTOCOL_TERMINATING:
self.state = PROTOCOL_TERMINATING
else:
if self.state == PROTOCOL_IDLE:
self.state = new_state
elif (self.state == PROTOCOL_COPY_OUT and
new_state == PROTOCOL_COPY_OUT_DATA):
self.state = new_state
elif (self.state == PROTOCOL_COPY_OUT_DATA and
new_state == PROTOCOL_COPY_OUT_DONE):
self.state = new_state
elif (self.state == PROTOCOL_COPY_IN and
new_state == PROTOCOL_COPY_IN_DATA):
self.state = new_state
elif self.state == PROTOCOL_FAILED:
raise apg_exc.InternalClientError(
'cannot switch to state {}; '
'protocol is in the "failed" state'.format(new_state))
else:
raise apg_exc.InternalClientError(
'cannot switch to state {}; '
'another operation ({}) is in progress'.format(
new_state, self.state))
cdef _ensure_connected(self):
if self.con_status != CONNECTION_OK:
raise apg_exc.InternalClientError('not connected')
cdef WriteBuffer _build_parse_message(self, str stmt_name, str query):
cdef WriteBuffer buf
buf = WriteBuffer.new_message(b'P')
buf.write_str(stmt_name, self.encoding)
buf.write_str(query, self.encoding)
buf.write_int16(0)
buf.end_message()
return buf
cdef WriteBuffer _build_bind_message(self, str portal_name,
str stmt_name,
WriteBuffer bind_data):
cdef WriteBuffer buf
buf = WriteBuffer.new_message(b'B')
buf.write_str(portal_name, self.encoding)
buf.write_str(stmt_name, self.encoding)
# Arguments
buf.write_buffer(bind_data)
buf.end_message()
return buf
cdef WriteBuffer _build_empty_bind_data(self):
cdef WriteBuffer buf
buf = WriteBuffer.new()
buf.write_int16(0) # The number of parameter format codes
buf.write_int16(0) # The number of parameter values
buf.write_int16(0) # The number of result-column format codes
return buf
cdef WriteBuffer _build_execute_message(self, str portal_name,
int32_t limit):
cdef WriteBuffer buf
buf = WriteBuffer.new_message(b'E')
buf.write_str(portal_name, self.encoding) # name of the portal
buf.write_int32(limit) # number of rows to return; 0 - all
buf.end_message()
return buf
# API for subclasses
cdef _connect(self):
cdef:
WriteBuffer buf
WriteBuffer outbuf
if self.con_status != CONNECTION_BAD:
raise apg_exc.InternalClientError('already connected')
self._set_state(PROTOCOL_AUTH)
self.con_status = CONNECTION_STARTED
# Assemble a startup message
buf = WriteBuffer()
# protocol version
buf.write_int16(3)
buf.write_int16(0)
buf.write_bytestring(b'client_encoding')
buf.write_bytestring("'{}'".format(self.encoding).encode('ascii'))
buf.write_str('user', self.encoding)
buf.write_str(self.con_params.user, self.encoding)
buf.write_str('database', self.encoding)
buf.write_str(self.con_params.database, self.encoding)
if self.con_params.server_settings is not None:
for k, v in self.con_params.server_settings.items():
buf.write_str(k, self.encoding)
buf.write_str(v, self.encoding)
buf.write_bytestring(b'')
# Send the buffer
outbuf = WriteBuffer()
outbuf.write_int32(buf.len() + 4)
outbuf.write_buffer(buf)
self._write(outbuf)
cdef _send_parse_message(self, str stmt_name, str query):
cdef:
WriteBuffer msg
self._ensure_connected()
msg = self._build_parse_message(stmt_name, query)
self._write(msg)
cdef _prepare_and_describe(self, str stmt_name, str query):
cdef:
WriteBuffer packet
WriteBuffer buf
self._ensure_connected()
self._set_state(PROTOCOL_PREPARE)
packet = self._build_parse_message(stmt_name, query)
buf = WriteBuffer.new_message(b'D')
buf.write_byte(b'S')
buf.write_str(stmt_name, self.encoding)
buf.end_message()
packet.write_buffer(buf)
packet.write_bytes(FLUSH_MESSAGE)
self._write(packet)
cdef _send_bind_message(self, str portal_name, str stmt_name,
WriteBuffer bind_data, int32_t limit):
cdef:
WriteBuffer packet
WriteBuffer buf
buf = self._build_bind_message(portal_name, stmt_name, bind_data)
packet = buf
buf = self._build_execute_message(portal_name, limit)
packet.write_buffer(buf)
packet.write_bytes(SYNC_MESSAGE)
self._write(packet)
cdef _bind_execute(self, str portal_name, str stmt_name,
WriteBuffer bind_data, int32_t limit):
cdef WriteBuffer buf
self._ensure_connected()
self._set_state(PROTOCOL_BIND_EXECUTE)
self.result = []
self._send_bind_message(portal_name, stmt_name, bind_data, limit)
cdef bint _bind_execute_many(self, str portal_name, str stmt_name,
object bind_data):
self._ensure_connected()
self._set_state(PROTOCOL_BIND_EXECUTE_MANY)
self.result = None
self._discard_data = True
self._execute_iter = bind_data
self._execute_portal_name = portal_name
self._execute_stmt_name = stmt_name
return self._bind_execute_many_more(True)
cdef bint _bind_execute_many_more(self, bint first=False):
cdef:
WriteBuffer packet
WriteBuffer buf
list buffers = []
# as we keep sending, the server may return an error early
if self.result_type == RESULT_FAILED:
self._write(SYNC_MESSAGE)
return False
# collect up to four 32KB buffers to send
# https://github.com/MagicStack/asyncpg/pull/289#issuecomment-391215051
while len(buffers) < _EXECUTE_MANY_BUF_NUM:
packet = WriteBuffer.new()
# fill one 32KB buffer
while packet.len() < _EXECUTE_MANY_BUF_SIZE:
try:
# grab one item from the input
buf = <WriteBuffer>next(self._execute_iter)
# reached the end of the input
except StopIteration:
if first:
# if we never send anything, simply set the result
self._push_result()
else:
# otherwise, append SYNC and send the buffers
packet.write_bytes(SYNC_MESSAGE)
buffers.append(memoryview(packet))
self._writelines(buffers)
return False
# error in input, give up the buffers and cleanup
except Exception as ex:
self._bind_execute_many_fail(ex, first)
return False
# all good, write to the buffer
first = False
packet.write_buffer(
self._build_bind_message(
self._execute_portal_name,
self._execute_stmt_name,
buf,
)