This repository was archived by the owner on Mar 31, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathsnapshot.py
More file actions
1188 lines (994 loc) · 45.2 KB
/
snapshot.py
File metadata and controls
1188 lines (994 loc) · 45.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2016 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.
"""Model a set of read-only queries to a database as a snapshot."""
import functools
import threading
from typing import List, Union, Optional
from google.protobuf.struct_pb2 import Struct
from google.cloud.spanner_v1 import (
ExecuteSqlRequest,
PartialResultSet,
ResultSet,
Transaction,
Mutation,
BeginTransactionRequest,
)
from google.cloud.spanner_v1 import ReadRequest
from google.cloud.spanner_v1 import TransactionOptions
from google.cloud.spanner_v1 import TransactionSelector
from google.cloud.spanner_v1 import PartitionOptions
from google.cloud.spanner_v1 import PartitionQueryRequest
from google.cloud.spanner_v1 import PartitionReadRequest
from google.api_core.exceptions import InternalServerError, Aborted
from google.api_core.exceptions import ServiceUnavailable
from google.api_core.exceptions import InvalidArgument
from google.api_core import gapic_v1
from google.cloud.spanner_v1._helpers import (
_make_value_pb,
_merge_query_options,
_metadata_with_prefix,
_metadata_with_leader_aware_routing,
_retry,
_check_rst_stream_error,
_SessionWrapper,
AtomicCounter,
)
from google.cloud.spanner_v1._opentelemetry_tracing import trace_call, add_span_event
from google.cloud.spanner_v1.streamed import StreamedResultSet
from google.cloud.spanner_v1 import RequestOptions
from google.cloud.spanner_v1.metrics.metrics_capture import MetricsCapture
from google.cloud.spanner_v1.types import MultiplexedSessionPrecommitToken
_STREAM_RESUMPTION_INTERNAL_ERROR_MESSAGES = (
"RST_STREAM",
"Received unexpected EOS on DATA frame from server",
)
def _restart_on_unavailable(
method,
request,
metadata=None,
trace_name=None,
session=None,
attributes=None,
transaction=None,
transaction_selector=None,
observability_options=None,
request_id_manager=None,
):
"""Restart iteration after :exc:`.ServiceUnavailable`.
:type method: callable
:param method: function returning iterator
:type request: proto
:param request: request proto to call the method with
:type transaction: :class:`google.cloud.spanner_v1.snapshot._SnapshotBase`
:param transaction: Snapshot or Transaction class object based on the type of transaction
:type transaction_selector: :class:`transaction_pb2.TransactionSelector`
:param transaction_selector: Transaction selector object to be used in request if transaction is not passed,
if both transaction_selector and transaction are passed, then transaction is given priority.
"""
resume_token: bytes = b""
item_buffer: List[PartialResultSet] = []
if transaction is not None:
transaction_selector = transaction._build_transaction_selector_pb()
elif transaction_selector is None:
raise InvalidArgument(
"Either transaction or transaction_selector should be set"
)
request.transaction = transaction_selector
iterator = None
attempt = 1
nth_request = getattr(request_id_manager, "_next_nth_request", 0)
while True:
try:
# Get results iterator.
if iterator is None:
with trace_call(
trace_name,
session,
attributes,
observability_options=observability_options,
metadata=metadata,
) as span, MetricsCapture():
iterator = method(
request=request,
metadata=request_id_manager.metadata_with_request_id(
nth_request,
attempt,
metadata,
span,
),
)
# Add items from iterator to buffer.
item: PartialResultSet
for item in iterator:
item_buffer.append(item)
# Update the transaction from the response.
if transaction is not None:
transaction._update_for_result_set_pb(item)
if (
item._pb is not None
and item._pb.HasField("precommit_token")
and transaction is not None
):
transaction._update_for_precommit_token_pb(item.precommit_token)
if item.resume_token:
resume_token = item.resume_token
break
except ServiceUnavailable:
del item_buffer[:]
with trace_call(
trace_name,
session,
attributes,
observability_options=observability_options,
metadata=metadata,
) as span, MetricsCapture():
request.resume_token = resume_token
if transaction is not None:
transaction_selector = transaction._build_transaction_selector_pb()
request.transaction = transaction_selector
attempt += 1
iterator = method(
request=request,
metadata=request_id_manager.metadata_with_request_id(
nth_request,
attempt,
metadata,
span,
),
)
continue
except InternalServerError as exc:
resumable_error = any(
resumable_message in exc.message
for resumable_message in _STREAM_RESUMPTION_INTERNAL_ERROR_MESSAGES
)
if not resumable_error:
raise
del item_buffer[:]
with trace_call(
trace_name,
session,
attributes,
observability_options=observability_options,
metadata=metadata,
) as span, MetricsCapture():
request.resume_token = resume_token
if transaction is not None:
transaction_selector = transaction._build_transaction_selector_pb()
attempt += 1
request.transaction = transaction_selector
iterator = method(
request=request,
metadata=request_id_manager.metadata_with_request_id(
nth_request,
attempt,
metadata,
span,
),
)
continue
if len(item_buffer) == 0:
break
for item in item_buffer:
yield item
del item_buffer[:]
class _SnapshotBase(_SessionWrapper):
"""Base class for Snapshot.
Allows reuse of API request methods with different transaction selector.
:type session: :class:`~google.cloud.spanner_v1.session.Session`
:param session: the session used to perform transaction operations.
"""
_read_only: bool = True
_multi_use: bool = False
def __init__(self, session):
super().__init__(session)
# Counts for execute SQL requests and total read requests (including
# execute SQL requests). Used to provide sequence numbers for
# :class:`google.cloud.spanner_v1.types.ExecuteSqlRequest` and to
# verify that single-use transactions are not used more than once,
# respectively.
self._execute_sql_request_count: int = 0
self._read_request_count: int = 0
# Identifier for the transaction.
self._transaction_id: Optional[bytes] = None
# Precommit tokens are returned for transactions with
# multiplexed sessions. The precommit token with the
# highest sequence number is included in the commit request.
self._precommit_token: Optional[MultiplexedSessionPrecommitToken] = None
# Operations within a transaction can be performed using multiple
# threads, so we need to use a lock when updating the transaction.
self._lock: threading.Lock = threading.Lock()
def begin(self) -> bytes:
"""Begins a transaction on the database.
:rtype: bytes
:returns: identifier for the transaction.
:raises ValueError: if the transaction has already begun.
"""
return self._begin_transaction()
def read(
self,
table,
columns,
keyset,
index="",
limit=0,
partition=None,
request_options=None,
data_boost_enabled=False,
directed_read_options=None,
*,
retry=gapic_v1.method.DEFAULT,
timeout=gapic_v1.method.DEFAULT,
column_info=None,
lazy_decode=False,
):
"""Perform a ``StreamingRead`` API request for rows in a table.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type limit: int
:param limit: (Optional) maximum number of rows to return.
Incompatible with ``partition``.
:type partition: bytes
:param partition: (Optional) one of the partition tokens returned
from :meth:`partition_read`. Incompatible with
``limit``.
:type request_options:
:class:`google.cloud.spanner_v1.types.RequestOptions`
:param request_options:
(Optional) Common options for this request.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.RequestOptions`.
Please note, the `transactionTag` setting will be ignored for
snapshot as it's not supported for read-only transactions.
:type retry: :class:`~google.api_core.retry.Retry`
:param retry: (Optional) The retry settings for this request.
:type timeout: float
:param timeout: (Optional) The timeout for this request.
:type data_boost_enabled:
:param data_boost_enabled:
(Optional) If this is for a partitioned read and this field is
set ``true``, the request will be executed via offline access.
If the field is set to ``true`` but the request does not set
``partition_token``, the API will return an
``INVALID_ARGUMENT`` error.
:type directed_read_options: :class:`~google.cloud.spanner_v1.DirectedReadOptions`
or :class:`dict`
:param directed_read_options: (Optional) Request level option used to set the directed_read_options
for all ReadRequests and ExecuteSqlRequests that indicates which replicas
or regions should be used for non-transactional reads or queries.
:type column_info: dict
:param column_info: (Optional) dict of mapping between column names and additional column information.
An object where column names as keys and custom objects as corresponding
values for deserialization. It's specifically useful for data types like
protobuf where deserialization logic is on user-specific code. When provided,
the custom object enables deserialization of backend-received column data.
If not provided, data remains serialized as bytes for Proto Messages and
integer for Proto Enums.
:type lazy_decode: bool
:param lazy_decode:
(Optional) If this argument is set to ``true``, the iterator
returns the underlying protobuf values instead of decoded Python
objects. This reduces the time that is needed to iterate through
large result sets. The application is responsible for decoding
the data that is needed. The returned row iterator contains two
functions that can be used for this. ``iterator.decode_row(row)``
decodes all the columns in the given row to an array of Python
objects. ``iterator.decode_column(row, column_index)`` decodes one
specific column in the given row.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError: if the Transaction already used to execute a
read request, but is not a multi-use transaction or has not begun.
"""
if self._read_request_count > 0:
if not self._multi_use:
raise ValueError("Cannot re-use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction has not begun.")
session = self._session
database = session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
if not self._read_only and database._route_to_leader_enabled:
metadata.append(
_metadata_with_leader_aware_routing(database._route_to_leader_enabled)
)
if request_options is None:
request_options = RequestOptions()
elif type(request_options) is dict:
request_options = RequestOptions(request_options)
if self._read_only:
# Transaction tags are not supported for read only transactions.
request_options.transaction_tag = None
if (
directed_read_options is None
and database._directed_read_options is not None
):
directed_read_options = database._directed_read_options
elif self.transaction_tag is not None:
request_options.transaction_tag = self.transaction_tag
read_request = ReadRequest(
session=session.name,
table=table,
columns=columns,
key_set=keyset._to_pb(),
index=index,
limit=limit,
partition_token=partition,
request_options=request_options,
data_boost_enabled=data_boost_enabled,
directed_read_options=directed_read_options,
)
streaming_read_method = functools.partial(
api.streaming_read,
request=read_request,
metadata=metadata,
retry=retry,
timeout=timeout,
)
return self._get_streamed_result_set(
method=streaming_read_method,
request=read_request,
metadata=metadata,
trace_attributes={
"table_id": table,
"columns": columns,
"request_options": request_options,
},
column_info=column_info,
lazy_decode=lazy_decode,
)
def execute_sql(
self,
sql,
params=None,
param_types=None,
query_mode=None,
query_options=None,
request_options=None,
last_statement=False,
partition=None,
retry=gapic_v1.method.DEFAULT,
timeout=gapic_v1.method.DEFAULT,
data_boost_enabled=False,
directed_read_options=None,
column_info=None,
lazy_decode=False,
):
"""Perform an ``ExecuteStreamingSql`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type query_mode:
:class:`~google.cloud.spanner_v1.types.ExecuteSqlRequest.QueryMode`
:param query_mode: Mode governing return of results / query plan.
See:
`QueryMode <https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode>`_.
:type query_options:
:class:`~google.cloud.spanner_v1.types.ExecuteSqlRequest.QueryOptions`
or :class:`dict`
:param query_options:
(Optional) Query optimizer configuration to use for the given query.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.QueryOptions`
:type request_options:
:class:`google.cloud.spanner_v1.types.RequestOptions`
:param request_options:
(Optional) Common options for this request.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.RequestOptions`.
:type last_statement: bool
:param last_statement:
If set to true, this option marks the end of the transaction. The
transaction should be committed or aborted after this statement
executes, and attempts to execute any other requests against this
transaction (including reads and queries) will be rejected. Mixing
mutations with statements that are marked as the last statement is
not allowed.
For DML statements, setting this option may cause some error
reporting to be deferred until commit time (e.g. validation of
unique constraints). Given this, successful execution of a DML
statement should not be assumed until the transaction commits.
:type partition: bytes
:param partition: (Optional) one of the partition tokens returned
from :meth:`partition_query`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:type retry: :class:`~google.api_core.retry.Retry`
:param retry: (Optional) The retry settings for this request.
:type timeout: float
:param timeout: (Optional) The timeout for this request.
:type data_boost_enabled:
:param data_boost_enabled:
(Optional) If this is for a partitioned query and this field is
set ``true``, the request will be executed via offline access.
If the field is set to ``true`` but the request does not set
``partition_token``, the API will return an
``INVALID_ARGUMENT`` error.
:type directed_read_options: :class:`~google.cloud.spanner_v1.DirectedReadOptions`
or :class:`dict`
:param directed_read_options: (Optional) Request level option used to set the directed_read_options
for all ReadRequests and ExecuteSqlRequests that indicates which replicas
or regions should be used for non-transactional reads or queries.
:type column_info: dict
:param column_info: (Optional) dict of mapping between column names and additional column information.
An object where column names as keys and custom objects as corresponding
values for deserialization. It's specifically useful for data types like
protobuf where deserialization logic is on user-specific code. When provided,
the custom object enables deserialization of backend-received column data.
If not provided, data remains serialized as bytes for Proto Messages and
integer for Proto Enums.
:type lazy_decode: bool
:param lazy_decode:
(Optional) If this argument is set to ``true``, the iterator
returns the underlying protobuf values instead of decoded Python
objects. This reduces the time that is needed to iterate through
large result sets. The application is responsible for decoding
the data that is needed. The returned row iterator contains two
functions that can be used for this. ``iterator.decode_row(row)``
decodes all the columns in the given row to an array of Python
objects. ``iterator.decode_column(row, column_index)`` decodes one
specific column in the given row.
:raises ValueError: if the Transaction already used to execute a
read request, but is not a multi-use transaction or has not begun.
"""
if self._read_request_count > 0:
if not self._multi_use:
raise ValueError("Cannot re-use single-use snapshot.")
if self._transaction_id is None:
raise ValueError("Transaction has not begun.")
if params is not None:
params_pb = Struct(
fields={key: _make_value_pb(value) for key, value in params.items()}
)
else:
params_pb = {}
session = self._session
database = session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
if not self._read_only and database._route_to_leader_enabled:
metadata.append(
_metadata_with_leader_aware_routing(database._route_to_leader_enabled)
)
# Query-level options have higher precedence than client-level and
# environment-level options
default_query_options = database._instance._client._query_options
query_options = _merge_query_options(default_query_options, query_options)
if request_options is None:
request_options = RequestOptions()
elif type(request_options) is dict:
request_options = RequestOptions(request_options)
if self._read_only:
# Transaction tags are not supported for read only transactions.
request_options.transaction_tag = None
if (
directed_read_options is None
and database._directed_read_options is not None
):
directed_read_options = database._directed_read_options
elif self.transaction_tag is not None:
request_options.transaction_tag = self.transaction_tag
execute_sql_request = ExecuteSqlRequest(
session=session.name,
sql=sql,
params=params_pb,
param_types=param_types,
query_mode=query_mode,
partition_token=partition,
seqno=self._execute_sql_request_count,
query_options=query_options,
request_options=request_options,
last_statement=last_statement,
data_boost_enabled=data_boost_enabled,
directed_read_options=directed_read_options,
)
execute_streaming_sql_method = functools.partial(
api.execute_streaming_sql,
request=execute_sql_request,
metadata=metadata,
retry=retry,
timeout=timeout,
)
return self._get_streamed_result_set(
method=execute_streaming_sql_method,
request=execute_sql_request,
metadata=metadata,
trace_attributes={"db.statement": sql, "request_options": request_options},
column_info=column_info,
lazy_decode=lazy_decode,
)
def _get_streamed_result_set(
self,
method,
request,
metadata,
trace_attributes,
column_info,
lazy_decode,
):
"""Returns the streamed result set for a read or execute SQL request with the given arguments."""
session = self._session
database = session._database
is_execute_sql_request = isinstance(request, ExecuteSqlRequest)
trace_method_name = "execute_sql" if is_execute_sql_request else "read"
trace_name = f"CloudSpanner.{type(self).__name__}.{trace_method_name}"
# If this request begins the transaction, we need to lock
# the transaction until the transaction ID is updated.
is_inline_begin = False
if self._transaction_id is None:
is_inline_begin = True
self._lock.acquire()
iterator = _restart_on_unavailable(
method=method,
request=request,
session=session,
metadata=metadata,
trace_name=trace_name,
attributes=trace_attributes,
transaction=self,
observability_options=getattr(database, "observability_options", None),
request_id_manager=database,
)
if is_inline_begin:
self._lock.release()
if is_execute_sql_request:
self._execute_sql_request_count += 1
self._read_request_count += 1
streamed_result_set_args = {
"response_iterator": iterator,
"column_info": column_info,
"lazy_decode": lazy_decode,
}
if self._multi_use:
streamed_result_set_args["source"] = self
return StreamedResultSet(**streamed_result_set_args)
def partition_read(
self,
table,
columns,
keyset,
index="",
partition_size_bytes=None,
max_partitions=None,
*,
retry=gapic_v1.method.DEFAULT,
timeout=gapic_v1.method.DEFAULT,
):
"""Perform a ``PartitionRead`` API request for rows in a table.
:type table: str
:param table: name of the table from which to fetch data
:type columns: list of str
:param columns: names of columns to be retrieved
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
:param keyset: keys / ranges identifying rows to be retrieved
:type index: str
:param index: (Optional) name of index to use, rather than the
table's primary key
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:type retry: :class:`~google.api_core.retry.Retry`
:param retry: (Optional) The retry settings for this request.
:type timeout: float
:param timeout: (Optional) The timeout for this request.
:rtype: iterable of bytes
:returns: a sequence of partition tokens
:raises ValueError: if the transaction has not begun or is single-use.
"""
if self._transaction_id is None:
raise ValueError("Transaction has not begun.")
if not self._multi_use:
raise ValueError("Cannot partition a single-use transaction.")
session = self._session
database = session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
if database._route_to_leader_enabled:
metadata.append(
_metadata_with_leader_aware_routing(database._route_to_leader_enabled)
)
transaction = self._build_transaction_selector_pb()
partition_options = PartitionOptions(
partition_size_bytes=partition_size_bytes, max_partitions=max_partitions
)
partition_read_request = PartitionReadRequest(
session=session.name,
table=table,
columns=columns,
key_set=keyset._to_pb(),
transaction=transaction,
index=index,
partition_options=partition_options,
)
trace_attributes = {"table_id": table, "columns": columns}
can_include_index = (index != "") and (index is not None)
if can_include_index:
trace_attributes["index"] = index
with trace_call(
f"CloudSpanner.{type(self).__name__}.partition_read",
session,
extra_attributes=trace_attributes,
observability_options=getattr(database, "observability_options", None),
metadata=metadata,
) as span, MetricsCapture():
nth_request = getattr(database, "_next_nth_request", 0)
attempt = AtomicCounter()
def attempt_tracking_method():
all_metadata = database.metadata_with_request_id(
nth_request,
attempt.increment(),
metadata,
span,
)
partition_read_method = functools.partial(
api.partition_read,
request=partition_read_request,
metadata=all_metadata,
retry=retry,
timeout=timeout,
)
return partition_read_method()
response = _retry(
attempt_tracking_method,
allowed_exceptions={InternalServerError: _check_rst_stream_error},
)
return [partition.partition_token for partition in response.partitions]
def partition_query(
self,
sql,
params=None,
param_types=None,
partition_size_bytes=None,
max_partitions=None,
*,
retry=gapic_v1.method.DEFAULT,
timeout=gapic_v1.method.DEFAULT,
):
"""Perform a ``PartitionQuery`` API request.
:type sql: str
:param sql: SQL query statement
:type params: dict, {str -> column value}
:param params: values for parameter replacement. Keys must match
the names used in ``sql``.
:type param_types: dict[str -> Union[dict, .types.Type]]
:param param_types:
(Optional) maps explicit types for one or more param values;
required if parameters are passed.
:type partition_size_bytes: int
:param partition_size_bytes:
(Optional) desired size for each partition generated. The service
uses this as a hint, the actual partition size may differ.
:type max_partitions: int
:param max_partitions:
(Optional) desired maximum number of partitions generated. The
service uses this as a hint, the actual number of partitions may
differ.
:type retry: :class:`~google.api_core.retry.Retry`
:param retry: (Optional) The retry settings for this request.
:type timeout: float
:param timeout: (Optional) The timeout for this request.
:rtype: iterable of bytes
:returns: a sequence of partition tokens
:raises ValueError: if the transaction has not begun or is single-use.
"""
if self._transaction_id is None:
raise ValueError("Transaction has not begun.")
if not self._multi_use:
raise ValueError("Cannot partition a single-use transaction.")
if params is not None:
params_pb = Struct(
fields={key: _make_value_pb(value) for (key, value) in params.items()}
)
else:
params_pb = Struct()
session = self._session
database = session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
if database._route_to_leader_enabled:
metadata.append(
_metadata_with_leader_aware_routing(database._route_to_leader_enabled)
)
transaction = self._build_transaction_selector_pb()
partition_options = PartitionOptions(
partition_size_bytes=partition_size_bytes, max_partitions=max_partitions
)
partition_query_request = PartitionQueryRequest(
session=session.name,
sql=sql,
transaction=transaction,
params=params_pb,
param_types=param_types,
partition_options=partition_options,
)
trace_attributes = {"db.statement": sql}
with trace_call(
f"CloudSpanner.{type(self).__name__}.partition_query",
session,
trace_attributes,
observability_options=getattr(database, "observability_options", None),
metadata=metadata,
) as span, MetricsCapture():
nth_request = getattr(database, "_next_nth_request", 0)
attempt = AtomicCounter()
def attempt_tracking_method():
all_metadata = database.metadata_with_request_id(
nth_request,
attempt.increment(),
metadata,
span,
)
partition_query_method = functools.partial(
api.partition_query,
request=partition_query_request,
metadata=all_metadata,
retry=retry,
timeout=timeout,
)
return partition_query_method()
response = _retry(
attempt_tracking_method,
allowed_exceptions={InternalServerError: _check_rst_stream_error},
)
return [partition.partition_token for partition in response.partitions]
def _begin_transaction(
self, mutation: Mutation = None, transaction_tag: str = None
) -> bytes:
"""Begins a transaction on the database.
:type mutation: :class:`~google.cloud.spanner_v1.mutation.Mutation`
:param mutation: (Optional) Mutation to include in the begin transaction
request. Required for mutation-only transactions with multiplexed sessions.
:type transaction_tag: str
:param transaction_tag: (Optional) Transaction tag to include in the begin transaction
request.
:rtype: bytes
:returns: identifier for the transaction.
:raises ValueError: if the transaction has already begun or is single-use.
"""
if self._transaction_id is not None:
raise ValueError("Transaction has already begun.")
if not self._multi_use:
raise ValueError("Cannot begin a single-use transaction.")
if self._read_request_count > 0:
raise ValueError("Read-only transaction already pending")
session = self._session
database = session._database
api = database.spanner_api
metadata = _metadata_with_prefix(database.name)
if not self._read_only and database._route_to_leader_enabled:
metadata.append(
(_metadata_with_leader_aware_routing(database._route_to_leader_enabled))
)
begin_request_kwargs = {
"session": session.name,
"options": self._build_transaction_selector_pb().begin,
"mutation_key": mutation,
}
if transaction_tag:
begin_request_kwargs["request_options"] = RequestOptions(
transaction_tag=transaction_tag
)
with trace_call(
name=f"CloudSpanner.{type(self).__name__}.begin",
session=session,
observability_options=getattr(database, "observability_options", None),
metadata=metadata,
) as span, MetricsCapture():
nth_request = getattr(database, "_next_nth_request", 0)
attempt = AtomicCounter()
def wrapped_method():
begin_transaction_request = BeginTransactionRequest(
**begin_request_kwargs
)
begin_transaction_method = functools.partial(
api.begin_transaction,
request=begin_transaction_request,
metadata=database.metadata_with_request_id(
nth_request,
attempt.increment(),
metadata,
span,
),
)
return begin_transaction_method()
def before_next_retry(nth_retry, delay_in_seconds):
add_span_event(
span=span,
event_name="Transaction Begin Attempt Failed. Retrying",
event_attributes={
"attempt": nth_retry,
"sleep_seconds": delay_in_seconds,
},
)
# An aborted transaction may be raised by a mutations-only
# transaction with a multiplexed session.
transaction_pb: Transaction = _retry(
wrapped_method,
before_next_retry=before_next_retry,
allowed_exceptions={
InternalServerError: _check_rst_stream_error,
Aborted: None,
},
)
self._update_for_transaction_pb(transaction_pb)
return self._transaction_id
def _build_transaction_options_pb(self) -> TransactionOptions: