-
Notifications
You must be signed in to change notification settings - Fork 88
/
test_session_api.py
2864 lines (2344 loc) · 91.5 KB
/
test_session_api.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 base64
import collections
import datetime
import decimal
import math
import struct
import threading
import time
import pytest
import grpc
from google.rpc import code_pb2
from google.api_core import datetime_helpers
from google.api_core import exceptions
from google.cloud import spanner_v1
from google.cloud.spanner_admin_database_v1 import DatabaseDialect
from google.cloud._helpers import UTC
from google.cloud.spanner_v1.data_types import JsonObject
from .testdata import singer_pb2
from tests import _helpers as ot_helpers
from . import _helpers
from . import _sample_data
SOME_DATE = datetime.date(2011, 1, 17)
SOME_TIME = datetime.datetime(1989, 1, 17, 17, 59, 12, 345612)
NANO_TIME = datetime_helpers.DatetimeWithNanoseconds(1995, 8, 31, nanosecond=987654321)
POS_INF = float("+inf")
NEG_INF = float("-inf")
(OTHER_NAN,) = struct.unpack("<d", b"\x01\x00\x01\x00\x00\x00\xf8\xff")
BYTES_1 = b"Ymlu"
BYTES_2 = b"Ym9vdHM="
NUMERIC_1 = decimal.Decimal("0.123456789")
NUMERIC_2 = decimal.Decimal("1234567890")
JSON_1 = JsonObject(
{
"sample_boolean": True,
"sample_int": 872163,
"sample float": 7871.298,
"sample_null": None,
"sample_string": "abcdef",
"sample_array": [23, 76, 19],
}
)
JSON_2 = JsonObject(
{"sample_object": {"name": "Anamika", "id": 2635}},
)
SINGER_INFO = _sample_data.SINGER_INFO_1
SINGER_GENRE = _sample_data.SINGER_GENRE_1
COUNTERS_TABLE = "counters"
COUNTERS_COLUMNS = ("name", "value")
ALL_TYPES_TABLE = "all_types"
LIVE_ALL_TYPES_COLUMNS = (
"pkey",
"int_value",
"int_array",
"bool_value",
"bool_array",
"bytes_value",
"bytes_array",
"date_value",
"date_array",
"float_value",
"float_array",
"string_value",
"string_array",
"timestamp_value",
"timestamp_array",
"numeric_value",
"numeric_array",
"json_value",
"json_array",
"proto_message_value",
"proto_message_array",
"proto_enum_value",
"proto_enum_array",
)
EMULATOR_ALL_TYPES_COLUMNS = LIVE_ALL_TYPES_COLUMNS[:-8]
# ToDo: Clean up generation of POSTGRES_ALL_TYPES_COLUMNS
POSTGRES_ALL_TYPES_COLUMNS = LIVE_ALL_TYPES_COLUMNS[:17] + (
"jsonb_value",
"jsonb_array",
)
QUERY_ALL_TYPES_COLUMNS = LIVE_ALL_TYPES_COLUMNS[1:17:2]
AllTypesRowData = collections.namedtuple("AllTypesRowData", LIVE_ALL_TYPES_COLUMNS)
AllTypesRowData.__new__.__defaults__ = tuple([None for colum in LIVE_ALL_TYPES_COLUMNS])
EmulatorAllTypesRowData = collections.namedtuple(
"EmulatorAllTypesRowData", EMULATOR_ALL_TYPES_COLUMNS
)
EmulatorAllTypesRowData.__new__.__defaults__ = tuple(
[None for colum in EMULATOR_ALL_TYPES_COLUMNS]
)
PostGresAllTypesRowData = collections.namedtuple(
"PostGresAllTypesRowData", POSTGRES_ALL_TYPES_COLUMNS
)
PostGresAllTypesRowData.__new__.__defaults__ = tuple(
[None for colum in POSTGRES_ALL_TYPES_COLUMNS]
)
LIVE_ALL_TYPES_ROWDATA = (
# all nulls
AllTypesRowData(pkey=0),
# Non-null values
AllTypesRowData(pkey=101, int_value=123),
AllTypesRowData(pkey=102, bool_value=False),
AllTypesRowData(pkey=103, bytes_value=BYTES_1),
AllTypesRowData(pkey=104, date_value=SOME_DATE),
AllTypesRowData(pkey=105, float_value=1.4142136),
AllTypesRowData(pkey=106, string_value="VALUE"),
AllTypesRowData(pkey=107, timestamp_value=SOME_TIME),
AllTypesRowData(pkey=108, timestamp_value=NANO_TIME),
AllTypesRowData(pkey=109, numeric_value=NUMERIC_1),
AllTypesRowData(pkey=110, json_value=JSON_1),
AllTypesRowData(pkey=111, json_value=JsonObject([JSON_1, JSON_2])),
AllTypesRowData(pkey=112, proto_message_value=SINGER_INFO),
AllTypesRowData(pkey=113, proto_enum_value=SINGER_GENRE),
# empty array values
AllTypesRowData(pkey=201, int_array=[]),
AllTypesRowData(pkey=202, bool_array=[]),
AllTypesRowData(pkey=203, bytes_array=[]),
AllTypesRowData(pkey=204, date_array=[]),
AllTypesRowData(pkey=205, float_array=[]),
AllTypesRowData(pkey=206, string_array=[]),
AllTypesRowData(pkey=207, timestamp_array=[]),
AllTypesRowData(pkey=208, numeric_array=[]),
AllTypesRowData(pkey=209, json_array=[]),
AllTypesRowData(pkey=210, proto_message_array=[]),
AllTypesRowData(pkey=211, proto_enum_array=[]),
# non-empty array values, including nulls
AllTypesRowData(pkey=301, int_array=[123, 456, None]),
AllTypesRowData(pkey=302, bool_array=[True, False, None]),
AllTypesRowData(pkey=303, bytes_array=[BYTES_1, BYTES_2, None]),
AllTypesRowData(pkey=304, date_array=[SOME_DATE, None]),
AllTypesRowData(
pkey=305, float_array=[3.1415926, 2.71828, math.inf, -math.inf, None]
),
AllTypesRowData(pkey=306, string_array=["One", "Two", None]),
AllTypesRowData(pkey=307, timestamp_array=[SOME_TIME, NANO_TIME, None]),
AllTypesRowData(pkey=308, numeric_array=[NUMERIC_1, NUMERIC_2, None]),
AllTypesRowData(pkey=309, json_array=[JSON_1, JSON_2, None]),
AllTypesRowData(pkey=310, proto_message_array=[SINGER_INFO, None]),
AllTypesRowData(pkey=311, proto_enum_array=[SINGER_GENRE, None]),
)
EMULATOR_ALL_TYPES_ROWDATA = (
# all nulls
EmulatorAllTypesRowData(pkey=0),
# Non-null values
EmulatorAllTypesRowData(pkey=101, int_value=123),
EmulatorAllTypesRowData(pkey=102, bool_value=False),
EmulatorAllTypesRowData(pkey=103, bytes_value=BYTES_1),
EmulatorAllTypesRowData(pkey=104, date_value=SOME_DATE),
EmulatorAllTypesRowData(pkey=105, float_value=1.4142136),
EmulatorAllTypesRowData(pkey=106, string_value="VALUE"),
EmulatorAllTypesRowData(pkey=107, timestamp_value=SOME_TIME),
EmulatorAllTypesRowData(pkey=108, timestamp_value=NANO_TIME),
# empty array values
EmulatorAllTypesRowData(pkey=201, int_array=[]),
EmulatorAllTypesRowData(pkey=202, bool_array=[]),
EmulatorAllTypesRowData(pkey=203, bytes_array=[]),
EmulatorAllTypesRowData(pkey=204, date_array=[]),
EmulatorAllTypesRowData(pkey=205, float_array=[]),
EmulatorAllTypesRowData(pkey=206, string_array=[]),
EmulatorAllTypesRowData(pkey=207, timestamp_array=[]),
# non-empty array values, including nulls
EmulatorAllTypesRowData(pkey=301, int_array=[123, 456, None]),
EmulatorAllTypesRowData(pkey=302, bool_array=[True, False, None]),
EmulatorAllTypesRowData(pkey=303, bytes_array=[BYTES_1, BYTES_2, None]),
EmulatorAllTypesRowData(pkey=304, date_array=[SOME_DATE, None]),
EmulatorAllTypesRowData(pkey=305, float_array=[3.1415926, -2.71828, None]),
EmulatorAllTypesRowData(pkey=306, string_array=["One", "Two", None]),
EmulatorAllTypesRowData(pkey=307, timestamp_array=[SOME_TIME, NANO_TIME, None]),
)
POSTGRES_ALL_TYPES_ROWDATA = (
# all nulls
PostGresAllTypesRowData(pkey=0),
# Non-null values
PostGresAllTypesRowData(pkey=101, int_value=123),
PostGresAllTypesRowData(pkey=102, bool_value=False),
PostGresAllTypesRowData(pkey=103, bytes_value=BYTES_1),
PostGresAllTypesRowData(pkey=104, date_value=SOME_DATE),
PostGresAllTypesRowData(pkey=105, float_value=1.4142136),
PostGresAllTypesRowData(pkey=106, string_value="VALUE"),
PostGresAllTypesRowData(pkey=107, timestamp_value=SOME_TIME),
PostGresAllTypesRowData(pkey=108, timestamp_value=NANO_TIME),
PostGresAllTypesRowData(pkey=109, numeric_value=NUMERIC_1),
PostGresAllTypesRowData(pkey=110, jsonb_value=JSON_1),
# empty array values
PostGresAllTypesRowData(pkey=201, int_array=[]),
PostGresAllTypesRowData(pkey=202, bool_array=[]),
PostGresAllTypesRowData(pkey=203, bytes_array=[]),
PostGresAllTypesRowData(pkey=204, date_array=[]),
PostGresAllTypesRowData(pkey=205, float_array=[]),
PostGresAllTypesRowData(pkey=206, string_array=[]),
PostGresAllTypesRowData(pkey=207, timestamp_array=[]),
PostGresAllTypesRowData(pkey=208, numeric_array=[]),
PostGresAllTypesRowData(pkey=209, jsonb_array=[]),
# non-empty array values, including nulls
PostGresAllTypesRowData(pkey=301, int_array=[123, 456, None]),
PostGresAllTypesRowData(pkey=302, bool_array=[True, False, None]),
PostGresAllTypesRowData(pkey=303, bytes_array=[BYTES_1, BYTES_2, None]),
PostGresAllTypesRowData(pkey=304, date_array=[SOME_DATE, SOME_DATE, None]),
PostGresAllTypesRowData(
pkey=305, float_array=[3.1415926, -2.71828, math.inf, -math.inf, None]
),
PostGresAllTypesRowData(pkey=306, string_array=["One", "Two", None]),
PostGresAllTypesRowData(pkey=307, timestamp_array=[SOME_TIME, NANO_TIME, None]),
PostGresAllTypesRowData(pkey=308, numeric_array=[NUMERIC_1, NUMERIC_2, None]),
PostGresAllTypesRowData(pkey=309, jsonb_array=[JSON_1, JSON_2, None]),
)
QUERY_ALL_TYPES_DATA = (
123,
False,
BYTES_1,
SOME_DATE,
1.4142136,
"VALUE",
SOME_TIME,
NUMERIC_1,
)
if _helpers.USE_EMULATOR:
ALL_TYPES_COLUMNS = EMULATOR_ALL_TYPES_COLUMNS
ALL_TYPES_ROWDATA = EMULATOR_ALL_TYPES_ROWDATA
elif _helpers.DATABASE_DIALECT == "POSTGRESQL":
ALL_TYPES_COLUMNS = POSTGRES_ALL_TYPES_COLUMNS
ALL_TYPES_ROWDATA = POSTGRES_ALL_TYPES_ROWDATA
else:
ALL_TYPES_COLUMNS = LIVE_ALL_TYPES_COLUMNS
ALL_TYPES_ROWDATA = LIVE_ALL_TYPES_ROWDATA
COLUMN_INFO = {
"proto_message_value": singer_pb2.SingerInfo(),
"proto_message_array": singer_pb2.SingerInfo(),
}
@pytest.fixture(scope="session")
def sessions_database(
shared_instance, database_operation_timeout, database_dialect, proto_descriptor_file
):
database_name = _helpers.unique_id("test_sessions", separator="_")
pool = spanner_v1.BurstyPool(labels={"testcase": "session_api"})
if database_dialect == DatabaseDialect.POSTGRESQL:
sessions_database = shared_instance.database(
database_name,
pool=pool,
database_dialect=database_dialect,
)
operation = sessions_database.create()
operation.result(database_operation_timeout)
operation = sessions_database.update_ddl(ddl_statements=_helpers.DDL_STATEMENTS)
operation.result(database_operation_timeout)
else:
sessions_database = shared_instance.database(
database_name,
ddl_statements=_helpers.DDL_STATEMENTS,
pool=pool,
proto_descriptors=proto_descriptor_file,
)
operation = sessions_database.create()
operation.result(database_operation_timeout)
_helpers.retry_has_all_dll(sessions_database.reload)()
# Some tests expect there to be a session present in the pool.
pool.put(pool.get())
yield sessions_database
sessions_database.drop()
@pytest.fixture(scope="function")
def sessions_to_delete():
to_delete = []
yield to_delete
for session in to_delete:
session.delete()
@pytest.fixture(scope="function")
def ot_exporter():
if ot_helpers.HAS_OPENTELEMETRY_INSTALLED:
ot_helpers.use_test_ot_exporter()
ot_exporter = ot_helpers.get_test_ot_exporter()
ot_exporter.clear() # XXX?
yield ot_exporter
ot_exporter.clear()
else:
yield None
def assert_no_spans(ot_exporter):
if ot_exporter is not None:
span_list = ot_exporter.get_finished_spans()
assert len(span_list) == 0
def assert_span_attributes(
ot_exporter, name, status=ot_helpers.StatusCode.OK, attributes=None, span=None
):
if ot_exporter is not None:
if not span:
span_list = ot_exporter.get_finished_spans()
assert len(span_list) == 1
span = span_list[0]
assert span.name == name
assert span.status.status_code == status
assert dict(span.attributes) == attributes
def _make_attributes(db_instance, **kwargs):
attributes = {
"db.type": "spanner",
"db.url": "spanner.googleapis.com",
"net.host.name": "spanner.googleapis.com",
"db.instance": db_instance,
}
ot_helpers.enrich_with_otel_scope(attributes)
attributes.update(kwargs)
return attributes
class _ReadAbortTrigger(object):
"""Helper for tests provoking abort-during-read."""
KEY1 = "key1"
KEY2 = "key2"
def __init__(self):
self.provoker_started = threading.Event()
self.provoker_done = threading.Event()
self.handler_running = threading.Event()
self.handler_done = threading.Event()
def _provoke_abort_unit_of_work(self, transaction):
keyset = spanner_v1.KeySet(keys=[(self.KEY1,)])
rows = list(transaction.read(COUNTERS_TABLE, COUNTERS_COLUMNS, keyset))
assert len(rows) == 1
row = rows[0]
value = row[1]
self.provoker_started.set()
self.handler_running.wait()
transaction.update(COUNTERS_TABLE, COUNTERS_COLUMNS, [[self.KEY1, value + 1]])
def provoke_abort(self, database):
database.run_in_transaction(self._provoke_abort_unit_of_work)
self.provoker_done.set()
def _handle_abort_unit_of_work(self, transaction):
keyset_1 = spanner_v1.KeySet(keys=[(self.KEY1,)])
rows_1 = list(transaction.read(COUNTERS_TABLE, COUNTERS_COLUMNS, keyset_1))
assert len(rows_1) == 1
row_1 = rows_1[0]
value_1 = row_1[1]
self.handler_running.set()
self.provoker_done.wait()
keyset_2 = spanner_v1.KeySet(keys=[(self.KEY2,)])
rows_2 = list(transaction.read(COUNTERS_TABLE, COUNTERS_COLUMNS, keyset_2))
assert len(rows_2) == 1
row_2 = rows_2[0]
value_2 = row_2[1]
transaction.update(
COUNTERS_TABLE, COUNTERS_COLUMNS, [[self.KEY2, value_1 + value_2]]
)
def handle_abort(self, database):
database.run_in_transaction(self._handle_abort_unit_of_work)
self.handler_done.set()
def test_session_crud(sessions_database):
session = sessions_database.session()
assert not session.exists()
session.create()
_helpers.retry_true(session.exists)()
session.delete()
_helpers.retry_false(session.exists)()
def test_batch_insert_then_read(sessions_database, ot_exporter):
db_name = sessions_database.name
sd = _sample_data
with sessions_database.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
batch.insert(sd.TABLE, sd.COLUMNS, sd.ROW_DATA)
with sessions_database.snapshot(read_timestamp=batch.committed) as snapshot:
rows = list(snapshot.read(sd.TABLE, sd.COLUMNS, sd.ALL))
sd._check_rows_data(rows)
if ot_exporter is not None:
span_list = ot_exporter.get_finished_spans()
assert len(span_list) == 4
assert_span_attributes(
ot_exporter,
"CloudSpanner.GetSession",
attributes=_make_attributes(db_name, session_found=True),
span=span_list[0],
)
assert_span_attributes(
ot_exporter,
"CloudSpanner.Commit",
attributes=_make_attributes(db_name, num_mutations=2),
span=span_list[1],
)
assert_span_attributes(
ot_exporter,
"CloudSpanner.GetSession",
attributes=_make_attributes(db_name, session_found=True),
span=span_list[2],
)
assert_span_attributes(
ot_exporter,
"CloudSpanner.ReadOnlyTransaction",
attributes=_make_attributes(db_name, columns=sd.COLUMNS, table_id=sd.TABLE),
span=span_list[3],
)
def test_batch_insert_then_read_string_array_of_string(sessions_database, not_postgres):
table = "string_plus_array_of_string"
columns = ["id", "name", "tags"]
rowdata = [
(0, None, None),
(1, "phred", ["yabba", "dabba", "do"]),
(2, "bharney", []),
(3, "wylma", ["oh", None, "phred"]),
]
sd = _sample_data
with sessions_database.batch() as batch:
batch.delete(table, sd.ALL)
batch.insert(table, columns, rowdata)
with sessions_database.snapshot(read_timestamp=batch.committed) as snapshot:
rows = list(snapshot.read(table, columns, sd.ALL))
sd._check_rows_data(rows, expected=rowdata)
def test_batch_insert_then_read_all_datatypes(sessions_database):
sd = _sample_data
with sessions_database.batch() as batch:
batch.delete(ALL_TYPES_TABLE, sd.ALL)
batch.insert(ALL_TYPES_TABLE, ALL_TYPES_COLUMNS, ALL_TYPES_ROWDATA)
with sessions_database.snapshot(read_timestamp=batch.committed) as snapshot:
rows = list(
snapshot.read(
ALL_TYPES_TABLE, ALL_TYPES_COLUMNS, sd.ALL, column_info=COLUMN_INFO
)
)
sd._check_rows_data(rows, expected=ALL_TYPES_ROWDATA)
def test_batch_insert_or_update_then_query(sessions_database):
sd = _sample_data
with sessions_database.batch() as batch:
batch.insert_or_update(sd.TABLE, sd.COLUMNS, sd.ROW_DATA)
with sessions_database.snapshot(read_timestamp=batch.committed) as snapshot:
rows = list(snapshot.execute_sql(sd.SQL))
sd._check_rows_data(rows)
def test_batch_insert_then_read_wo_param_types(
sessions_database, database_dialect, not_emulator
):
sd = _sample_data
with sessions_database.batch() as batch:
batch.delete(ALL_TYPES_TABLE, sd.ALL)
batch.insert(ALL_TYPES_TABLE, ALL_TYPES_COLUMNS, ALL_TYPES_ROWDATA)
with sessions_database.snapshot(multi_use=True) as snapshot:
for column_type, value in list(
zip(QUERY_ALL_TYPES_COLUMNS, QUERY_ALL_TYPES_DATA)
):
placeholder = (
"$1" if database_dialect == DatabaseDialect.POSTGRESQL else "@value"
)
sql = (
"SELECT * FROM "
+ ALL_TYPES_TABLE
+ " WHERE "
+ column_type
+ " = "
+ placeholder
)
param = (
{"p1": value}
if database_dialect == DatabaseDialect.POSTGRESQL
else {"value": value}
)
rows = list(snapshot.execute_sql(sql, params=param))
assert len(rows) == 1
def test_batch_insert_w_commit_timestamp(sessions_database, not_postgres):
table = "users_history"
columns = ["id", "commit_ts", "name", "email", "deleted"]
user_id = 1234
name = "phred"
email = "[email protected]"
row_data = [[user_id, spanner_v1.COMMIT_TIMESTAMP, name, email, False]]
sd = _sample_data
with sessions_database.batch() as batch:
batch.delete(table, sd.ALL)
batch.insert(table, columns, row_data)
with sessions_database.snapshot(read_timestamp=batch.committed) as snapshot:
rows = list(snapshot.read(table, columns, sd.ALL))
assert len(rows) == 1
r_id, commit_ts, r_name, r_email, deleted = rows[0]
assert r_id == user_id
assert commit_ts == batch.committed
assert r_name == name
assert r_email == email
assert not deleted
@_helpers.retry_mabye_aborted_txn
def test_transaction_read_and_insert_then_rollback(
sessions_database,
ot_exporter,
sessions_to_delete,
):
sd = _sample_data
db_name = sessions_database.name
session = sessions_database.session()
session.create()
sessions_to_delete.append(session)
with sessions_database.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
transaction = session.transaction()
transaction.begin()
rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert rows == []
transaction.insert(sd.TABLE, sd.COLUMNS, sd.ROW_DATA)
# Inserted rows can't be read until after commit.
rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert rows == []
transaction.rollback()
rows = list(session.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert rows == []
if ot_exporter is not None:
span_list = ot_exporter.get_finished_spans()
assert len(span_list) == 8
assert_span_attributes(
ot_exporter,
"CloudSpanner.CreateSession",
attributes=_make_attributes(db_name),
span=span_list[0],
)
assert_span_attributes(
ot_exporter,
"CloudSpanner.GetSession",
attributes=_make_attributes(db_name, session_found=True),
span=span_list[1],
)
assert_span_attributes(
ot_exporter,
"CloudSpanner.Commit",
attributes=_make_attributes(db_name, num_mutations=1),
span=span_list[2],
)
assert_span_attributes(
ot_exporter,
"CloudSpanner.BeginTransaction",
attributes=_make_attributes(db_name),
span=span_list[3],
)
assert_span_attributes(
ot_exporter,
"CloudSpanner.ReadOnlyTransaction",
attributes=_make_attributes(
db_name,
table_id=sd.TABLE,
columns=sd.COLUMNS,
),
span=span_list[4],
)
assert_span_attributes(
ot_exporter,
"CloudSpanner.ReadOnlyTransaction",
attributes=_make_attributes(
db_name,
table_id=sd.TABLE,
columns=sd.COLUMNS,
),
span=span_list[5],
)
assert_span_attributes(
ot_exporter,
"CloudSpanner.Rollback",
attributes=_make_attributes(db_name),
span=span_list[6],
)
assert_span_attributes(
ot_exporter,
"CloudSpanner.ReadOnlyTransaction",
attributes=_make_attributes(
db_name,
table_id=sd.TABLE,
columns=sd.COLUMNS,
),
span=span_list[7],
)
@_helpers.retry_mabye_conflict
def test_transaction_read_and_insert_then_exception(sessions_database):
class CustomException(Exception):
pass
sd = _sample_data
def _transaction_read_then_raise(transaction):
rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert len(rows) == 0
transaction.insert(sd.TABLE, sd.COLUMNS, sd.ROW_DATA)
raise CustomException()
with sessions_database.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
with pytest.raises(CustomException):
sessions_database.run_in_transaction(_transaction_read_then_raise)
# Transaction was rolled back.
with sessions_database.snapshot() as snapshot:
rows = list(snapshot.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert rows == []
@_helpers.retry_mabye_conflict
def test_transaction_read_and_insert_or_update_then_commit(
sessions_database,
sessions_to_delete,
):
# [START spanner_test_dml_read_your_writes]
sd = _sample_data
session = sessions_database.session()
session.create()
sessions_to_delete.append(session)
with session.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
with session.transaction() as transaction:
rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert rows == []
transaction.insert_or_update(sd.TABLE, sd.COLUMNS, sd.ROW_DATA)
# Inserted rows can't be read until after commit.
rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert rows == []
rows = list(session.read(sd.TABLE, sd.COLUMNS, sd.ALL))
sd._check_rows_data(rows)
# [END spanner_test_dml_read_your_writes]
def _generate_insert_statements():
for row in _sample_data.ROW_DATA:
yield _generate_insert_statement(row)
def _generate_insert_statement(row):
table = _sample_data.TABLE
column_list = ", ".join(_sample_data.COLUMNS)
row_data = "{}, '{}', '{}', '{}'".format(*row)
return f"INSERT INTO {table} ({column_list}) VALUES ({row_data})"
@pytest.mark.skipif(
_helpers.USE_EMULATOR, reason="Emulator does not support DML Returning."
)
def _generate_insert_returning_statement(row, database_dialect):
table = _sample_data.TABLE
column_list = ", ".join(_sample_data.COLUMNS)
row_data = "{}, '{}', '{}', '{}'".format(*row)
returning = (
f"RETURNING {column_list}"
if database_dialect == DatabaseDialect.POSTGRESQL
else f"THEN RETURN {column_list}"
)
return f"INSERT INTO {table} ({column_list}) VALUES ({row_data}) {returning}"
@_helpers.retry_mabye_conflict
@_helpers.retry_mabye_aborted_txn
def test_transaction_execute_sql_w_dml_read_rollback(
sessions_database,
sessions_to_delete,
):
# [START spanner_test_dml_rollback_txn_not_committed]
sd = _sample_data
session = sessions_database.session()
session.create()
sessions_to_delete.append(session)
with session.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
transaction = session.transaction()
transaction.begin()
rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert rows == []
for insert_statement in _generate_insert_statements():
result = transaction.execute_sql(insert_statement)
list(result) # iterate to get stats
assert result.stats.row_count_exact == 1
# Rows inserted via DML *can* be read before commit.
during_rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
sd._check_rows_data(during_rows)
transaction.rollback()
rows = list(session.read(sd.TABLE, sd.COLUMNS, sd.ALL))
sd._check_rows_data(rows, [])
# [END spanner_test_dml_rollback_txn_not_committed]
@_helpers.retry_mabye_conflict
def test_transaction_execute_update_read_commit(sessions_database, sessions_to_delete):
# [START spanner_test_dml_read_your_writes]
sd = _sample_data
session = sessions_database.session()
session.create()
sessions_to_delete.append(session)
with session.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
with session.transaction() as transaction:
rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert rows == []
for insert_statement in _generate_insert_statements():
row_count = transaction.execute_update(insert_statement)
assert row_count == 1
# Rows inserted via DML *can* be read before commit.
during_rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
sd._check_rows_data(during_rows)
rows = list(session.read(sd.TABLE, sd.COLUMNS, sd.ALL))
sd._check_rows_data(rows)
# [END spanner_test_dml_read_your_writes]
@_helpers.retry_mabye_conflict
def test_transaction_execute_update_then_insert_commit(
sessions_database, sessions_to_delete
):
# [START spanner_test_dml_with_mutation]
# [START spanner_test_dml_update]
sd = _sample_data
session = sessions_database.session()
session.create()
sessions_to_delete.append(session)
with session.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
insert_statement = list(_generate_insert_statements())[0]
with session.transaction() as transaction:
rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert rows == []
row_count = transaction.execute_update(insert_statement)
assert row_count == 1
transaction.insert(sd.TABLE, sd.COLUMNS, sd.ROW_DATA[1:])
rows = list(session.read(sd.TABLE, sd.COLUMNS, sd.ALL))
sd._check_rows_data(rows)
# [END spanner_test_dml_update]
# [END spanner_test_dml_with_mutation]
@_helpers.retry_mabye_conflict
@pytest.mark.skipif(
_helpers.USE_EMULATOR, reason="Emulator does not support DML Returning."
)
def test_transaction_execute_sql_dml_returning(
sessions_database, sessions_to_delete, database_dialect
):
sd = _sample_data
session = sessions_database.session()
session.create()
sessions_to_delete.append(session)
with session.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
with session.transaction() as transaction:
for row in sd.ROW_DATA:
insert_statement = _generate_insert_returning_statement(
row, database_dialect
)
results = transaction.execute_sql(insert_statement)
returned = results.one()
assert list(row) == list(returned)
row_count = results.stats.row_count_exact
assert row_count == 1
rows = list(session.read(sd.TABLE, sd.COLUMNS, sd.ALL))
sd._check_rows_data(rows)
@_helpers.retry_mabye_conflict
@pytest.mark.skipif(
_helpers.USE_EMULATOR, reason="Emulator does not support DML Returning."
)
def test_transaction_execute_update_dml_returning(
sessions_database, sessions_to_delete, database_dialect
):
sd = _sample_data
session = sessions_database.session()
session.create()
sessions_to_delete.append(session)
with session.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
with session.transaction() as transaction:
for row in sd.ROW_DATA:
insert_statement = _generate_insert_returning_statement(
row, database_dialect
)
row_count = transaction.execute_update(insert_statement)
assert row_count == 1
rows = list(session.read(sd.TABLE, sd.COLUMNS, sd.ALL))
sd._check_rows_data(rows)
@_helpers.retry_mabye_conflict
@pytest.mark.skipif(
_helpers.USE_EMULATOR, reason="Emulator does not support DML Returning."
)
def test_transaction_batch_update_dml_returning(
sessions_database, sessions_to_delete, database_dialect
):
sd = _sample_data
session = sessions_database.session()
session.create()
sessions_to_delete.append(session)
with session.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
with session.transaction() as transaction:
insert_statements = [
_generate_insert_returning_statement(row, database_dialect)
for row in sd.ROW_DATA
]
status, row_counts = transaction.batch_update(insert_statements)
_check_batch_status(status.code)
assert len(row_counts) == 3
for row_count in row_counts:
assert row_count == 1
rows = list(session.read(sd.TABLE, sd.COLUMNS, sd.ALL))
sd._check_rows_data(rows)
def test_transaction_batch_update_success(
sessions_database, sessions_to_delete, database_dialect
):
# [START spanner_test_dml_with_mutation]
# [START spanner_test_dml_update]
sd = _sample_data
param_types = spanner_v1.param_types
session = sessions_database.session()
session.create()
sessions_to_delete.append(session)
with session.batch() as batch:
batch.delete(sd.TABLE, sd.ALL)
keys = (
["p1", "p2"]
if database_dialect == DatabaseDialect.POSTGRESQL
else ["contact_id", "email"]
)
placeholders = (
["$1", "$2"]
if database_dialect == DatabaseDialect.POSTGRESQL
else [f"@{key}" for key in keys]
)
insert_statement = list(_generate_insert_statements())[0]
update_statement = (
f"UPDATE contacts SET email = {placeholders[1]} WHERE contact_id = {placeholders[0]};",
{keys[0]: 1, keys[1]: "[email protected]"},
{keys[0]: param_types.INT64, keys[1]: param_types.STRING},
)
delete_statement = (
f"DELETE FROM contacts WHERE contact_id = {placeholders[0]};",
{keys[0]: 1},
{keys[0]: param_types.INT64},
)
def unit_of_work(transaction):
rows = list(transaction.read(sd.TABLE, sd.COLUMNS, sd.ALL))
assert rows == []
status, row_counts = transaction.batch_update(
[insert_statement, update_statement, delete_statement]
)
_check_batch_status(status.code)
assert len(row_counts) == 3
for row_count in row_counts:
assert row_count == 1