-
Notifications
You must be signed in to change notification settings - Fork 66
/
test_dbapi.py
1583 lines (1374 loc) · 56.7 KB
/
test_dbapi.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
# Copyright 2021 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
from collections import defaultdict
import pytest
import time
from google.cloud import spanner_v1
from google.cloud._helpers import UTC
from google.cloud.spanner_dbapi.connection import Connection, connect
from google.cloud.spanner_dbapi.exceptions import (
ProgrammingError,
OperationalError,
RetryAborted,
)
from google.cloud.spanner_dbapi.parsed_statement import AutocommitDmlMode
from google.cloud.spanner_v1 import JsonObject
from google.cloud.spanner_v1 import gapic_version as package_version
from google.api_core.datetime_helpers import DatetimeWithNanoseconds
from . import _helpers
DATABASE_NAME = "dbapi-txn"
SPANNER_RPC_PREFIX = "/google.spanner.v1.Spanner/"
EXECUTE_BATCH_DML_METHOD = SPANNER_RPC_PREFIX + "ExecuteBatchDml"
COMMIT_METHOD = SPANNER_RPC_PREFIX + "Commit"
EXECUTE_SQL_METHOD = SPANNER_RPC_PREFIX + "ExecuteSql"
EXECUTE_STREAMING_SQL_METHOD = SPANNER_RPC_PREFIX + "ExecuteStreamingSql"
DDL_STATEMENTS = (
"""CREATE TABLE contacts (
contact_id INT64,
first_name STRING(1024),
last_name STRING(1024),
email STRING(1024)
)
PRIMARY KEY (contact_id)""",
)
@pytest.fixture(scope="session")
def raw_database(shared_instance, database_operation_timeout, not_postgres):
database_id = _helpers.unique_id("dbapi-txn")
pool = spanner_v1.BurstyPool(labels={"testcase": "database_api"})
database = shared_instance.database(
database_id,
ddl_statements=DDL_STATEMENTS,
pool=pool,
enable_interceptors_in_tests=True,
)
op = database.create()
op.result(database_operation_timeout) # raises on failure / timeout.
yield database
database.drop()
class TestDbApi:
@staticmethod
def clear_table(transaction):
transaction.execute_update("DELETE FROM contacts WHERE true")
@pytest.fixture(scope="function")
def dbapi_database(self, raw_database):
# Resetting the count so that each test gives correct count of the api
# methods called during that test
raw_database._method_count_interceptor._counts = defaultdict(int)
raw_database.run_in_transaction(self.clear_table)
yield raw_database
raw_database.run_in_transaction(self.clear_table)
@pytest.fixture(autouse=True)
def init_connection(self, request, shared_instance, dbapi_database):
if "noautofixt" not in request.keywords:
self._conn = Connection(shared_instance, dbapi_database)
self._cursor = self._conn.cursor()
yield
if "noautofixt" not in request.keywords:
self._cursor.close()
self._conn.close()
def _execute_common_statements(self, cursor):
# execute several DML statements within one transaction
cursor.execute(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (1, 'first-name', 'last-name', '[email protected]')
"""
)
cursor.execute(
"""
UPDATE contacts
SET first_name = 'updated-first-name'
WHERE first_name = 'first-name'
"""
)
cursor.execute(
"""
UPDATE contacts
SET email = '[email protected]'
WHERE email = '[email protected]'
"""
)
return (
1,
"updated-first-name",
"last-name",
)
@pytest.mark.parametrize("client_side", [True, False])
def test_commit(self, client_side):
"""Test committing a transaction with several statements."""
updated_row = self._execute_common_statements(self._cursor)
if client_side:
self._cursor.execute("""COMMIT""")
else:
self._conn.commit()
# read the resulting data from the database
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
self._conn.commit()
assert got_rows == [updated_row]
@pytest.mark.skipif(
_helpers.USE_EMULATOR,
reason="Emulator does not support multiple parallel transactions.",
)
def test_commit_exception(self):
"""Test that if exception during commit method is caught, then
subsequent operations on same Cursor and Connection object works
properly."""
self._execute_common_statements(self._cursor)
# deleting the session to fail the commit
self._conn._session.delete()
try:
self._conn.commit()
except Exception:
pass
# Testing that the connection and Cursor are in proper state post commit
# and a new transaction is started
updated_row = self._execute_common_statements(self._cursor)
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
self._conn.commit()
assert got_rows == [updated_row]
@pytest.mark.skipif(
_helpers.USE_EMULATOR,
reason="Emulator does not support multiple parallel transactions.",
)
def test_rollback_exception(self):
"""Test that if exception during rollback method is caught, then
subsequent operations on same Cursor and Connection object works
properly."""
self._execute_common_statements(self._cursor)
# deleting the session to fail the rollback
self._conn._session.delete()
try:
self._conn.rollback()
except Exception:
pass
# Testing that the connection and Cursor are in proper state post
# exception in rollback and a new transaction is started
updated_row = self._execute_common_statements(self._cursor)
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
self._conn.commit()
assert got_rows == [updated_row]
def test_cursor_execute_exception(self):
"""Test that if exception in Cursor's execute method is caught when
Connection is not in autocommit mode, then subsequent operations on
same Cursor and Connection object works properly."""
updated_row = self._execute_common_statements(self._cursor)
try:
self._cursor.execute("SELECT * FROM unknown_table")
except Exception:
pass
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
self._conn.commit()
assert got_rows == [updated_row]
# Testing that the connection and Cursor are in proper state post commit
# and a new transaction is started
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
self._conn.commit()
assert got_rows == [updated_row]
def test_cursor_execute_exception_autocommit(self):
"""Test that if exception in Cursor's execute method is caught when
Connection is in autocommit mode, then subsequent operations on
same Cursor and Connection object works properly."""
self._conn.autocommit = True
updated_row = self._execute_common_statements(self._cursor)
try:
self._cursor.execute("SELECT * FROM unknown_table")
except Exception:
pass
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
assert got_rows == [updated_row]
def test_cursor_execute_exception_begin_client_side(self):
"""Test that if exception in Cursor's execute method is caught when
beginning a transaction using client side statement, then subsequent
operations on same Cursor and Connection object works properly."""
self._conn.autocommit = True
self._cursor.execute("begin transaction")
updated_row = self._execute_common_statements(self._cursor)
try:
self._cursor.execute("SELECT * FROM unknown_table")
except Exception:
pass
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
self._conn.commit()
assert got_rows == [updated_row]
# Testing that the connection and Cursor are in proper state post commit
self._conn.autocommit = False
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
self._conn.commit()
assert got_rows == [updated_row]
@pytest.mark.noautofixt
def test_begin_client_side(self, shared_instance, dbapi_database):
"""Test beginning a transaction using client side statement,
where connection is in autocommit mode."""
conn1 = Connection(shared_instance, dbapi_database)
conn1.autocommit = True
cursor1 = conn1.cursor()
cursor1.execute("begin transaction")
updated_row = self._execute_common_statements(cursor1)
assert conn1._transaction_begin_marked is True
conn1.commit()
assert conn1._transaction_begin_marked is False
cursor1.close()
conn1.close()
# As the connection conn1 is committed a new connection should see its results
conn3 = Connection(shared_instance, dbapi_database)
cursor3 = conn3.cursor()
cursor3.execute("SELECT * FROM contacts")
got_rows = cursor3.fetchall()
conn3.commit()
cursor3.close()
conn3.close()
assert got_rows == [updated_row]
def test_noop_sql_statements(self, dbapi_database):
"""Test beginning and then committing a transaction is a Noop"""
dbapi_database._method_count_interceptor.reset()
self._cursor.execute("begin transaction")
self._cursor.execute("commit transaction")
assert dbapi_database._method_count_interceptor._counts == {}
self._cursor.execute("SELECT * FROM contacts")
self._conn.commit()
assert self._cursor.fetchall() == []
"""Test beginning and then rolling back a transaction is a Noop"""
dbapi_database._method_count_interceptor.reset()
self._cursor.execute("begin transaction")
self._cursor.execute("rollback transaction")
assert dbapi_database._method_count_interceptor._counts == {}
self._cursor.execute("SELECT * FROM contacts")
assert self._cursor.fetchall() == []
self._conn.commit()
dbapi_database._method_count_interceptor.reset()
self._cursor.execute("start batch dml")
self._cursor.execute("run batch")
assert dbapi_database._method_count_interceptor._counts == {}
def test_read_and_commit_timestamps(self):
"""Test COMMIT_TIMESTAMP is not available after read statement and
READ_TIMESTAMP is not available after write statement in autocommit
mode."""
self._conn.autocommit = True
self._cursor.execute("SELECT * FROM contacts")
self._cursor.execute(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (1, 'first-name', 'last-name', '[email protected]')
"""
)
self._cursor.execute("SHOW VARIABLE COMMIT_TIMESTAMP")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 1
self._cursor.execute("SHOW VARIABLE READ_TIMESTAMP")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 0
self._cursor.execute("SELECT * FROM contacts")
self._cursor.execute("SHOW VARIABLE COMMIT_TIMESTAMP")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 0
self._cursor.execute("SHOW VARIABLE READ_TIMESTAMP")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 1
def test_commit_timestamp_client_side_transaction(self):
"""Test executing SHOW_COMMIT_TIMESTAMP client side statement in a
transaction."""
self._cursor.execute(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (1, 'first-name', 'last-name', '[email protected]')
"""
)
self._cursor.execute("SHOW VARIABLE COMMIT_TIMESTAMP")
got_rows = self._cursor.fetchall()
# As the connection is not committed we will get 0 rows
assert len(got_rows) == 0
assert len(self._cursor.description) == 1
self._cursor.execute(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (2, 'first-name', 'last-name', '[email protected]')
"""
)
self._conn.commit()
self._cursor.execute("SHOW VARIABLE COMMIT_TIMESTAMP")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 1
assert len(got_rows[0]) == 1
assert len(self._cursor.description) == 1
assert self._cursor.description[0].name == "SHOW_COMMIT_TIMESTAMP"
assert isinstance(got_rows[0][0], DatetimeWithNanoseconds)
def test_commit_timestamp_client_side_autocommit(self):
"""Test executing SHOW_COMMIT_TIMESTAMP client side statement in a
transaction when connection is in autocommit mode."""
self._conn.autocommit = True
self._cursor.execute(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (2, 'first-name', 'last-name', '[email protected]')
"""
)
self._cursor.execute("SHOW VARIABLE COMMIT_TIMESTAMP")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 1
assert len(got_rows[0]) == 1
assert len(self._cursor.description) == 1
assert self._cursor.description[0].name == "SHOW_COMMIT_TIMESTAMP"
assert isinstance(got_rows[0][0], DatetimeWithNanoseconds)
def test_read_timestamp_client_side(self):
"""Test executing SHOW_READ_TIMESTAMP client side statement in a
transaction."""
self._conn.read_only = True
self._cursor.execute("SELECT * FROM contacts")
assert self._cursor.fetchall() == []
self._cursor.execute("SHOW VARIABLE READ_TIMESTAMP")
read_timestamp_query_result_1 = self._cursor.fetchall()
self._cursor.execute("SELECT * FROM contacts")
assert self._cursor.fetchall() == []
self._cursor.execute("SHOW VARIABLE READ_TIMESTAMP")
read_timestamp_query_result_2 = self._cursor.fetchall()
self._conn.commit()
self._cursor.execute("SHOW VARIABLE READ_TIMESTAMP")
read_timestamp_query_result_3 = self._cursor.fetchall()
assert len(self._cursor.description) == 1
assert self._cursor.description[0].name == "SHOW_READ_TIMESTAMP"
assert (
read_timestamp_query_result_1
== read_timestamp_query_result_2
== read_timestamp_query_result_3
)
assert len(read_timestamp_query_result_1) == 1
assert len(read_timestamp_query_result_1[0]) == 1
assert isinstance(read_timestamp_query_result_1[0][0], DatetimeWithNanoseconds)
self._cursor.execute("SELECT * FROM contacts")
self._cursor.execute("SHOW VARIABLE READ_TIMESTAMP")
read_timestamp_query_result_4 = self._cursor.fetchall()
self._conn.commit()
assert read_timestamp_query_result_1 != read_timestamp_query_result_4
def test_read_timestamp_client_side_autocommit(self):
"""Test executing SHOW_READ_TIMESTAMP client side statement in a
transaction when connection is in autocommit mode."""
self._conn.autocommit = True
self._cursor.execute(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (2, 'first-name', 'last-name', '[email protected]')
"""
)
self._conn.read_only = True
self._cursor.execute("SELECT * FROM contacts")
assert self._cursor.fetchall() == [
(2, "first-name", "last-name", "[email protected]")
]
self._cursor.execute("SHOW VARIABLE READ_TIMESTAMP")
read_timestamp_query_result_1 = self._cursor.fetchall()
assert len(read_timestamp_query_result_1) == 1
assert len(read_timestamp_query_result_1[0]) == 1
assert len(self._cursor.description) == 1
assert self._cursor.description[0].name == "SHOW_READ_TIMESTAMP"
assert isinstance(read_timestamp_query_result_1[0][0], DatetimeWithNanoseconds)
self._conn.read_only = False
self._insert_row(3)
self._conn.read_only = True
self._cursor.execute("SELECT * FROM contacts")
self._cursor.execute("SHOW VARIABLE READ_TIMESTAMP")
read_timestamp_query_result_2 = self._cursor.fetchall()
assert read_timestamp_query_result_1 != read_timestamp_query_result_2
@pytest.mark.parametrize("auto_commit", [False, True])
def test_batch_dml(self, auto_commit, dbapi_database):
"""Test batch dml."""
method_count_interceptor = dbapi_database._method_count_interceptor
method_count_interceptor.reset()
if auto_commit:
self._conn.autocommit = True
self._insert_row(1)
self._cursor.execute("start batch dml")
self._insert_row(2)
self._insert_row(3)
self._cursor.execute("run batch")
self._insert_row(4)
# Test starting another dml batch in same transaction works
self._cursor.execute("start batch dml")
self._insert_row(5)
self._insert_row(6)
self._cursor.execute("run batch")
if not auto_commit:
self._conn.commit()
self._cursor.execute("SELECT * FROM contacts")
assert (
self._cursor.fetchall().sort()
== (
[
(1, "first-name-1", "last-name-1", "[email protected]"),
(2, "first-name-2", "last-name-2", "[email protected]"),
(3, "first-name-3", "last-name-3", "[email protected]"),
(4, "first-name-4", "last-name-4", "[email protected]"),
(5, "first-name-5", "last-name-5", "[email protected]"),
(6, "first-name-6", "last-name-6", "[email protected]"),
]
).sort()
)
# Test starting another dml batch in same connection post commit works
self._cursor.execute("start batch dml")
self._insert_row(7)
self._insert_row(8)
self._cursor.execute("run batch")
self._insert_row(9)
if not auto_commit:
self._conn.commit()
self._cursor.execute("SELECT * FROM contacts")
assert len(self._cursor.fetchall()) == 9
# Test that ExecuteBatchDml rpc is called
assert method_count_interceptor._counts[EXECUTE_BATCH_DML_METHOD] == 3
def test_abort_batch_dml(self):
"""Test abort batch dml."""
self._cursor.execute("start batch dml")
self._insert_row(1)
self._insert_row(2)
self._cursor.execute("abort batch")
self._insert_row(3)
self._conn.commit()
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 1
assert got_rows == [(3, "first-name-3", "last-name-3", "[email protected]")]
def test_batch_dml_invalid_statements(self):
"""Test batch dml having invalid statements."""
# Test first statement in batch is invalid
self._cursor.execute("start batch dml")
self._cursor.execute(
"""
INSERT INTO unknown_table (contact_id, first_name, last_name, email)
VALUES (2, 'first-name', 'last-name', '[email protected]')
"""
)
self._insert_row(1)
self._insert_row(2)
with pytest.raises(OperationalError):
self._cursor.execute("run batch")
# Test middle statement in batch is invalid
self._cursor.execute("start batch dml")
self._insert_row(1)
self._cursor.execute(
"""
INSERT INTO unknown_table (contact_id, first_name, last_name, email)
VALUES (2, 'first-name', 'last-name', '[email protected]')
"""
)
self._insert_row(2)
with pytest.raises(OperationalError):
self._cursor.execute("run batch")
# Test last statement in batch is invalid
self._cursor.execute("start batch dml")
self._insert_row(1)
self._insert_row(2)
self._cursor.execute(
"""
INSERT INTO unknown_table (contact_id, first_name, last_name, email)
VALUES (2, 'first-name', 'last-name', '[email protected]')
"""
)
with pytest.raises(OperationalError):
self._cursor.execute("run batch")
def test_partitioned_query(self):
"""Test partition query works in read-only mode."""
self._cursor.execute("start batch dml")
for i in range(1, 11):
self._insert_row(i)
self._cursor.execute("run batch")
self._conn.commit()
self._conn.read_only = True
self._cursor.execute("PARTITION SELECT * FROM contacts")
partition_id_rows = self._cursor.fetchall()
assert len(partition_id_rows) > 0
rows = []
for partition_id_row in partition_id_rows:
self._cursor.execute("RUN PARTITION " + partition_id_row[0])
rows = rows + self._cursor.fetchall()
assert len(rows) == 10
self._conn.commit()
def test_partitioned_query_in_rw_transaction(self):
"""Test partition query throws exception when connection is not in
read-only mode and neither in auto-commit mode."""
self._cursor.execute("start batch dml")
for i in range(1, 11):
self._insert_row(i)
self._cursor.execute("run batch")
self._conn.commit()
with pytest.raises(ProgrammingError):
self._cursor.execute("PARTITION SELECT * FROM contacts")
def test_partitioned_query_with_dml_query(self):
"""Test partition query throws exception when sql query is a DML query."""
self._cursor.execute("start batch dml")
for i in range(1, 11):
self._insert_row(i)
self._cursor.execute("run batch")
self._conn.commit()
self._conn.read_only = True
with pytest.raises(ProgrammingError):
self._cursor.execute(
"""
PARTITION INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (1111, 'first-name', 'last-name', '[email protected]')
"""
)
def test_partitioned_query_in_autocommit_mode(self):
"""Test partition query works when connection is not in read-only mode
but is in auto-commit mode."""
self._cursor.execute("start batch dml")
for i in range(1, 11):
self._insert_row(i)
self._cursor.execute("run batch")
self._conn.commit()
self._conn.autocommit = True
self._cursor.execute("PARTITION SELECT * FROM contacts")
partition_id_rows = self._cursor.fetchall()
assert len(partition_id_rows) > 0
rows = []
for partition_id_row in partition_id_rows:
self._cursor.execute("RUN PARTITION " + partition_id_row[0])
rows = rows + self._cursor.fetchall()
assert len(rows) == 10
self._conn.commit()
def test_partitioned_query_with_client_transaction_started(self):
"""Test partition query throws exception when connection is in
auto-commit mode but transaction started using client side statement."""
self._cursor.execute("start batch dml")
for i in range(1, 11):
self._insert_row(i)
self._cursor.execute("run batch")
self._conn.commit()
self._conn.autocommit = True
self._cursor.execute("begin transaction")
with pytest.raises(ProgrammingError):
self._cursor.execute("PARTITION SELECT * FROM contacts")
def test_run_partitioned_query(self):
"""Test run partitioned query works in read-only mode."""
self._cursor.execute("start batch dml")
for i in range(1, 11):
self._insert_row(i)
self._cursor.execute("run batch")
self._conn.commit()
self._conn.read_only = True
self._cursor.execute("RUN PARTITIONED QUERY SELECT * FROM contacts")
assert self._cursor.description is not None
assert self._cursor.rowcount == -1
rows = self._cursor.fetchall()
assert len(rows) == 10
self._conn.commit()
def test_partitioned_dml_query(self):
"""Test partitioned_dml query works in autocommit mode."""
self._cursor.execute("start batch dml")
for i in range(1, 11):
self._insert_row(i)
self._cursor.execute("run batch")
self._conn.commit()
self._conn.autocommit = True
self._cursor.execute("set autocommit_dml_mode = PARTITIONED_NON_ATOMIC")
self._cursor.execute("DELETE FROM contacts WHERE contact_id > 3")
assert self._cursor.rowcount == 7
self._cursor.execute("set autocommit_dml_mode = TRANSACTIONAL")
assert self._conn.autocommit_dml_mode == AutocommitDmlMode.TRANSACTIONAL
self._conn.autocommit = False
# Test changing autocommit_dml_mode is not allowed when connection is in autocommit mode
with pytest.raises(ProgrammingError):
self._cursor.execute("set autocommit_dml_mode = PARTITIONED_NON_ATOMIC")
def _insert_row(self, i):
self._cursor.execute(
f"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES ({i}, 'first-name-{i}', 'last-name-{i}', '[email protected]')
"""
)
def test_commit_abort_retry(self, dbapi_database):
"""Test that when commit failed with Abort exception, then the retry
succeeds with transaction having insert as well as query type of
statements along with batch dml statements.
We are trying to test all types of statements like execute, executemany,
fetchone, fetchmany, fetchall"""
method_count_interceptor = dbapi_database._method_count_interceptor
method_count_interceptor.reset()
# called 2 times
self._insert_row(1)
# called 2 times
self._cursor.execute("SELECT * FROM contacts")
self._cursor.fetchall()
self._cursor.execute("start batch dml")
self._insert_row(2)
self._insert_row(3)
# called 2 times for batch dml rpc
self._cursor.execute("run batch")
row_data = [
(4, "first-name4", "last-name4", "[email protected]"),
(5, "first-name5", "last-name5", "[email protected]"),
]
# called 2 times for batch dml rpc
self._cursor.executemany(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (%s, %s, %s, %s)
""",
row_data,
)
# called 2 times and as this would make 3 execute streaming sql calls
# so total 6 calls
self._cursor.executemany(
"""SELECT * FROM contacts WHERE contact_id = %s""",
((1,), (2,), (3,)),
)
self._cursor.fetchone()
self._cursor.fetchmany(2)
dbapi_database._method_abort_interceptor.set_method_to_abort(
COMMIT_METHOD, self._conn
)
# called 2 times
self._conn.commit()
dbapi_database._method_abort_interceptor.reset()
assert method_count_interceptor._counts[COMMIT_METHOD] == 2
assert method_count_interceptor._counts[EXECUTE_BATCH_DML_METHOD] == 4
assert method_count_interceptor._counts[EXECUTE_STREAMING_SQL_METHOD] == 10
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 5
@pytest.mark.skipif(
_helpers.USE_EMULATOR,
reason="Emulator does not support concurrent transactions.",
)
def test_retry_aborted_exception(self, shared_instance, dbapi_database):
"""Test that retry fails with RetryAborted error when rows are updated during retry."""
conn1 = Connection(shared_instance, dbapi_database)
cursor1 = conn1.cursor()
cursor1.execute(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (1, 'first-name', 'last-name', '[email protected]')
"""
)
conn1.commit()
cursor1.execute("SELECT * FROM contacts")
cursor1.fetchall()
conn2 = Connection(shared_instance, dbapi_database)
cursor2 = conn2.cursor()
cursor2.execute(
"""
UPDATE contacts
SET email = '[email protected]'
WHERE contact_id = 1
"""
)
conn2.commit()
dbapi_database._method_abort_interceptor.set_method_to_abort(
COMMIT_METHOD, conn1
)
with pytest.raises(RetryAborted):
conn1.commit()
dbapi_database._method_abort_interceptor.reset()
def test_execute_sql_abort_retry_multiple_times(self, dbapi_database):
"""Test that when execute sql failed 2 times with Abort exception, then
the retry succeeds 3rd time."""
method_count_interceptor = dbapi_database._method_count_interceptor
method_count_interceptor.reset()
self._cursor.execute("start batch dml")
self._insert_row(1)
self._insert_row(2)
self._cursor.execute("run batch")
# aborting method 2 times before succeeding
dbapi_database._method_abort_interceptor.set_method_to_abort(
EXECUTE_STREAMING_SQL_METHOD, self._conn, 2
)
self._cursor.execute("SELECT * FROM contacts")
self._cursor.fetchmany(2)
dbapi_database._method_abort_interceptor.reset()
self._conn.commit()
# Check that all rpcs except commit should be called 3 times the original
assert method_count_interceptor._counts[COMMIT_METHOD] == 1
assert method_count_interceptor._counts[EXECUTE_BATCH_DML_METHOD] == 3
assert method_count_interceptor._counts[EXECUTE_STREAMING_SQL_METHOD] == 3
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 2
def test_execute_batch_dml_abort_retry(self, dbapi_database):
"""Test that when any execute batch dml failed with Abort exception,
then the retry succeeds with transaction having insert as well as query
type of statements along with batch dml statements."""
method_count_interceptor = dbapi_database._method_count_interceptor
method_count_interceptor.reset()
# called 3 times
self._insert_row(1)
# called 3 times
self._cursor.execute("SELECT * FROM contacts")
self._cursor.fetchall()
self._cursor.execute("start batch dml")
self._insert_row(2)
self._insert_row(3)
dbapi_database._method_abort_interceptor.set_method_to_abort(
EXECUTE_BATCH_DML_METHOD, self._conn, 2
)
# called 3 times
self._cursor.execute("run batch")
dbapi_database._method_abort_interceptor.reset()
self._conn.commit()
assert method_count_interceptor._counts[COMMIT_METHOD] == 1
assert method_count_interceptor._counts[EXECUTE_BATCH_DML_METHOD] == 3
assert method_count_interceptor._counts[EXECUTE_STREAMING_SQL_METHOD] == 6
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 3
def test_multiple_aborts_in_transaction(self, dbapi_database):
"""Test that when there are multiple Abort exceptions in a transaction
on different statements, then the retry succeeds."""
method_count_interceptor = dbapi_database._method_count_interceptor
method_count_interceptor.reset()
# called 3 times
self._insert_row(1)
dbapi_database._method_abort_interceptor.set_method_to_abort(
EXECUTE_STREAMING_SQL_METHOD, self._conn
)
# called 3 times
self._cursor.execute("SELECT * FROM contacts")
dbapi_database._method_abort_interceptor.reset()
self._cursor.fetchall()
# called 2 times
self._insert_row(2)
# called 2 times
self._cursor.execute("SELECT * FROM contacts")
self._cursor.fetchone()
dbapi_database._method_abort_interceptor.set_method_to_abort(
COMMIT_METHOD, self._conn
)
# called 2 times
self._conn.commit()
dbapi_database._method_abort_interceptor.reset()
assert method_count_interceptor._counts[COMMIT_METHOD] == 2
assert method_count_interceptor._counts[EXECUTE_STREAMING_SQL_METHOD] == 10
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 2
def test_consecutive_aborted_transactions(self, dbapi_database):
"""Test 2 consecutive transactions with Abort exceptions on the same
connection works."""
method_count_interceptor = dbapi_database._method_count_interceptor
method_count_interceptor.reset()
self._insert_row(1)
self._insert_row(2)
self._cursor.execute("SELECT * FROM contacts")
self._cursor.fetchall()
dbapi_database._method_abort_interceptor.set_method_to_abort(
COMMIT_METHOD, self._conn
)
self._conn.commit()
dbapi_database._method_abort_interceptor.reset()
assert method_count_interceptor._counts[COMMIT_METHOD] == 2
assert method_count_interceptor._counts[EXECUTE_STREAMING_SQL_METHOD] == 6
method_count_interceptor = dbapi_database._method_count_interceptor
method_count_interceptor.reset()
self._insert_row(3)
self._insert_row(4)
self._cursor.execute("SELECT * FROM contacts")
self._cursor.fetchall()
dbapi_database._method_abort_interceptor.set_method_to_abort(
COMMIT_METHOD, self._conn
)
self._conn.commit()
dbapi_database._method_abort_interceptor.reset()
assert method_count_interceptor._counts[COMMIT_METHOD] == 2
assert method_count_interceptor._counts[EXECUTE_STREAMING_SQL_METHOD] == 6
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
assert len(got_rows) == 4
def test_abort_retry_multiple_cursors(self, dbapi_database):
"""Test that retry works when multiple cursors are involved in the transaction."""
self._insert_row(1)
self._insert_row(2)
self._insert_row(3)
self._insert_row(4)
self._conn.commit()
cur1 = self._conn.cursor()
cur1.execute("SELECT * FROM contacts WHERE contact_id IN (1, 2)")
cur2 = self._conn.cursor()
cur2.execute("SELECT * FROM contacts WHERE contact_id IN (3, 4)")
row1 = cur1.fetchone()
row2 = cur2.fetchone()
row3 = cur1.fetchone()
row4 = cur2.fetchone()
dbapi_database._method_abort_interceptor.set_method_to_abort(
COMMIT_METHOD, self._conn
)
self._conn.commit()
dbapi_database._method_abort_interceptor.reset()
assert set([row1, row3]) == set(
[
(1, "first-name-1", "last-name-1", "[email protected]"),
(2, "first-name-2", "last-name-2", "[email protected]"),
]
)
assert set([row2, row4]) == set(
[
(3, "first-name-3", "last-name-3", "[email protected]"),
(4, "first-name-4", "last-name-4", "[email protected]"),
]
)
def test_begin_success_post_commit(self):
"""Test beginning a new transaction post commiting an existing transaction
is possible on a connection, when connection is in autocommit mode."""
want_row = (2, "first-name", "last-name", "[email protected]")
self._conn.autocommit = True
self._cursor.execute("begin transaction")
self._cursor.execute(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (2, 'first-name', 'last-name', '[email protected]')
"""
)
self._conn.commit()
self._cursor.execute("begin transaction")
self._cursor.execute("SELECT * FROM contacts")
got_rows = self._cursor.fetchall()
self._conn.commit()
assert got_rows == [want_row]
def test_begin_error_before_commit(self):
"""Test beginning a new transaction before commiting an existing transaction is not possible on a connection, when connection is in autocommit mode."""
self._conn.autocommit = True
self._cursor.execute("begin transaction")
self._cursor.execute(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (2, 'first-name', 'last-name', '[email protected]')
"""
)
with pytest.raises(OperationalError):
self._cursor.execute("begin transaction")
@pytest.mark.parametrize("client_side", [False, True])
def test_rollback(self, client_side):
"""Test rollbacking a transaction with several statements."""
want_row = (2, "first-name", "last-name", "[email protected]")
self._cursor.execute(
"""
INSERT INTO contacts (contact_id, first_name, last_name, email)
VALUES (2, 'first-name', 'last-name', '[email protected]')
"""
)
self._conn.commit()