google-cloud-spanner 3.55.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- google/cloud/spanner.py +47 -0
- google/cloud/spanner_admin_database_v1/__init__.py +146 -0
- google/cloud/spanner_admin_database_v1/gapic_metadata.json +418 -0
- google/cloud/spanner_admin_database_v1/gapic_version.py +16 -0
- google/cloud/spanner_admin_database_v1/py.typed +2 -0
- google/cloud/spanner_admin_database_v1/services/__init__.py +15 -0
- google/cloud/spanner_admin_database_v1/services/database_admin/__init__.py +22 -0
- google/cloud/spanner_admin_database_v1/services/database_admin/async_client.py +4097 -0
- google/cloud/spanner_admin_database_v1/services/database_admin/client.py +4602 -0
- google/cloud/spanner_admin_database_v1/services/database_admin/pagers.py +989 -0
- google/cloud/spanner_admin_database_v1/services/database_admin/transports/__init__.py +38 -0
- google/cloud/spanner_admin_database_v1/services/database_admin/transports/base.py +820 -0
- google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc.py +1303 -0
- google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc_asyncio.py +1688 -0
- google/cloud/spanner_admin_database_v1/services/database_admin/transports/rest.py +6512 -0
- google/cloud/spanner_admin_database_v1/services/database_admin/transports/rest_base.py +1650 -0
- google/cloud/spanner_admin_database_v1/types/__init__.py +144 -0
- google/cloud/spanner_admin_database_v1/types/backup.py +1106 -0
- google/cloud/spanner_admin_database_v1/types/backup_schedule.py +369 -0
- google/cloud/spanner_admin_database_v1/types/common.py +180 -0
- google/cloud/spanner_admin_database_v1/types/spanner_database_admin.py +1303 -0
- google/cloud/spanner_admin_instance_v1/__init__.py +110 -0
- google/cloud/spanner_admin_instance_v1/gapic_metadata.json +343 -0
- google/cloud/spanner_admin_instance_v1/gapic_version.py +16 -0
- google/cloud/spanner_admin_instance_v1/py.typed +2 -0
- google/cloud/spanner_admin_instance_v1/services/__init__.py +15 -0
- google/cloud/spanner_admin_instance_v1/services/instance_admin/__init__.py +22 -0
- google/cloud/spanner_admin_instance_v1/services/instance_admin/async_client.py +3466 -0
- google/cloud/spanner_admin_instance_v1/services/instance_admin/client.py +3881 -0
- google/cloud/spanner_admin_instance_v1/services/instance_admin/pagers.py +856 -0
- google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/__init__.py +38 -0
- google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/base.py +545 -0
- google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc.py +1347 -0
- google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc_asyncio.py +1539 -0
- google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/rest.py +4834 -0
- google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/rest_base.py +1198 -0
- google/cloud/spanner_admin_instance_v1/types/__init__.py +104 -0
- google/cloud/spanner_admin_instance_v1/types/common.py +99 -0
- google/cloud/spanner_admin_instance_v1/types/spanner_instance_admin.py +2375 -0
- google/cloud/spanner_dbapi/__init__.py +93 -0
- google/cloud/spanner_dbapi/_helpers.py +113 -0
- google/cloud/spanner_dbapi/batch_dml_executor.py +135 -0
- google/cloud/spanner_dbapi/checksum.py +80 -0
- google/cloud/spanner_dbapi/client_side_statement_executor.py +140 -0
- google/cloud/spanner_dbapi/client_side_statement_parser.py +106 -0
- google/cloud/spanner_dbapi/connection.py +818 -0
- google/cloud/spanner_dbapi/cursor.py +609 -0
- google/cloud/spanner_dbapi/exceptions.py +172 -0
- google/cloud/spanner_dbapi/parse_utils.py +392 -0
- google/cloud/spanner_dbapi/parsed_statement.py +63 -0
- google/cloud/spanner_dbapi/parser.py +258 -0
- google/cloud/spanner_dbapi/partition_helper.py +41 -0
- google/cloud/spanner_dbapi/transaction_helper.py +294 -0
- google/cloud/spanner_dbapi/types.py +106 -0
- google/cloud/spanner_dbapi/utils.py +147 -0
- google/cloud/spanner_dbapi/version.py +20 -0
- google/cloud/spanner_v1/__init__.py +154 -0
- google/cloud/spanner_v1/_helpers.py +751 -0
- google/cloud/spanner_v1/_opentelemetry_tracing.py +165 -0
- google/cloud/spanner_v1/backup.py +397 -0
- google/cloud/spanner_v1/batch.py +433 -0
- google/cloud/spanner_v1/client.py +538 -0
- google/cloud/spanner_v1/data_types.py +350 -0
- google/cloud/spanner_v1/database.py +1968 -0
- google/cloud/spanner_v1/database_sessions_manager.py +249 -0
- google/cloud/spanner_v1/gapic_metadata.json +268 -0
- google/cloud/spanner_v1/gapic_version.py +16 -0
- google/cloud/spanner_v1/instance.py +735 -0
- google/cloud/spanner_v1/keyset.py +193 -0
- google/cloud/spanner_v1/merged_result_set.py +146 -0
- google/cloud/spanner_v1/metrics/constants.py +71 -0
- google/cloud/spanner_v1/metrics/metrics_capture.py +75 -0
- google/cloud/spanner_v1/metrics/metrics_exporter.py +384 -0
- google/cloud/spanner_v1/metrics/metrics_interceptor.py +156 -0
- google/cloud/spanner_v1/metrics/metrics_tracer.py +588 -0
- google/cloud/spanner_v1/metrics/metrics_tracer_factory.py +328 -0
- google/cloud/spanner_v1/metrics/spanner_metrics_tracer_factory.py +172 -0
- google/cloud/spanner_v1/param_types.py +110 -0
- google/cloud/spanner_v1/pool.py +813 -0
- google/cloud/spanner_v1/py.typed +2 -0
- google/cloud/spanner_v1/request_id_header.py +64 -0
- google/cloud/spanner_v1/services/__init__.py +15 -0
- google/cloud/spanner_v1/services/spanner/__init__.py +22 -0
- google/cloud/spanner_v1/services/spanner/async_client.py +2205 -0
- google/cloud/spanner_v1/services/spanner/client.py +2624 -0
- google/cloud/spanner_v1/services/spanner/pagers.py +196 -0
- google/cloud/spanner_v1/services/spanner/transports/__init__.py +38 -0
- google/cloud/spanner_v1/services/spanner/transports/base.py +520 -0
- google/cloud/spanner_v1/services/spanner/transports/grpc.py +911 -0
- google/cloud/spanner_v1/services/spanner/transports/grpc_asyncio.py +1144 -0
- google/cloud/spanner_v1/services/spanner/transports/rest.py +3468 -0
- google/cloud/spanner_v1/services/spanner/transports/rest_base.py +981 -0
- google/cloud/spanner_v1/session.py +631 -0
- google/cloud/spanner_v1/session_options.py +133 -0
- google/cloud/spanner_v1/snapshot.py +1057 -0
- google/cloud/spanner_v1/streamed.py +402 -0
- google/cloud/spanner_v1/table.py +181 -0
- google/cloud/spanner_v1/testing/__init__.py +0 -0
- google/cloud/spanner_v1/testing/database_test.py +121 -0
- google/cloud/spanner_v1/testing/interceptors.py +118 -0
- google/cloud/spanner_v1/testing/mock_database_admin.py +38 -0
- google/cloud/spanner_v1/testing/mock_spanner.py +261 -0
- google/cloud/spanner_v1/testing/spanner_database_admin_pb2_grpc.py +1267 -0
- google/cloud/spanner_v1/testing/spanner_pb2_grpc.py +882 -0
- google/cloud/spanner_v1/transaction.py +747 -0
- google/cloud/spanner_v1/types/__init__.py +118 -0
- google/cloud/spanner_v1/types/commit_response.py +94 -0
- google/cloud/spanner_v1/types/keys.py +248 -0
- google/cloud/spanner_v1/types/mutation.py +201 -0
- google/cloud/spanner_v1/types/query_plan.py +220 -0
- google/cloud/spanner_v1/types/result_set.py +379 -0
- google/cloud/spanner_v1/types/spanner.py +1815 -0
- google/cloud/spanner_v1/types/transaction.py +818 -0
- google/cloud/spanner_v1/types/type.py +288 -0
- google_cloud_spanner-3.55.0.dist-info/LICENSE +202 -0
- google_cloud_spanner-3.55.0.dist-info/METADATA +318 -0
- google_cloud_spanner-3.55.0.dist-info/RECORD +119 -0
- google_cloud_spanner-3.55.0.dist-info/WHEEL +5 -0
- google_cloud_spanner-3.55.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
# Copyright 2016 Google LLC All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Wrapper for Cloud Spanner Session objects."""
|
|
16
|
+
|
|
17
|
+
from functools import total_ordering
|
|
18
|
+
import time
|
|
19
|
+
from datetime import datetime
|
|
20
|
+
|
|
21
|
+
from google.api_core.exceptions import Aborted
|
|
22
|
+
from google.api_core.exceptions import GoogleAPICallError
|
|
23
|
+
from google.api_core.exceptions import NotFound
|
|
24
|
+
from google.api_core.gapic_v1 import method
|
|
25
|
+
from google.cloud.spanner_v1._helpers import _delay_until_retry
|
|
26
|
+
from google.cloud.spanner_v1._helpers import _get_retry_delay
|
|
27
|
+
|
|
28
|
+
from google.cloud.spanner_v1 import ExecuteSqlRequest
|
|
29
|
+
from google.cloud.spanner_v1 import CreateSessionRequest
|
|
30
|
+
from google.cloud.spanner_v1._helpers import (
|
|
31
|
+
_metadata_with_prefix,
|
|
32
|
+
_metadata_with_leader_aware_routing,
|
|
33
|
+
)
|
|
34
|
+
from google.cloud.spanner_v1._opentelemetry_tracing import (
|
|
35
|
+
add_span_event,
|
|
36
|
+
get_current_span,
|
|
37
|
+
trace_call,
|
|
38
|
+
)
|
|
39
|
+
from google.cloud.spanner_v1.batch import Batch
|
|
40
|
+
from google.cloud.spanner_v1.snapshot import Snapshot
|
|
41
|
+
from google.cloud.spanner_v1.transaction import Transaction
|
|
42
|
+
from google.cloud.spanner_v1.metrics.metrics_capture import MetricsCapture
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
DEFAULT_RETRY_TIMEOUT_SECS = 30
|
|
46
|
+
"""Default timeout used by :meth:`Session.run_in_transaction`."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@total_ordering
|
|
50
|
+
class Session(object):
|
|
51
|
+
"""Representation of a Cloud Spanner Session.
|
|
52
|
+
|
|
53
|
+
We can use a :class:`Session` to:
|
|
54
|
+
|
|
55
|
+
* :meth:`create` the session
|
|
56
|
+
* Use :meth:`exists` to check for the existence of the session
|
|
57
|
+
* :meth:`drop` the session
|
|
58
|
+
|
|
59
|
+
:type database: :class:`~google.cloud.spanner_v1.database.Database`
|
|
60
|
+
:param database: The database to which the session is bound.
|
|
61
|
+
|
|
62
|
+
:type labels: dict (str -> str)
|
|
63
|
+
:param labels: (Optional) User-assigned labels for the session.
|
|
64
|
+
|
|
65
|
+
:type database_role: str
|
|
66
|
+
:param database_role: (Optional) user-assigned database_role for the session.
|
|
67
|
+
|
|
68
|
+
:type is_multiplexed: bool
|
|
69
|
+
:param is_multiplexed: (Optional) whether this session is a multiplexed session.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
_session_id = None
|
|
73
|
+
_transaction = None
|
|
74
|
+
|
|
75
|
+
def __init__(self, database, labels=None, database_role=None, is_multiplexed=False):
|
|
76
|
+
self._database = database
|
|
77
|
+
if labels is None:
|
|
78
|
+
labels = {}
|
|
79
|
+
self._labels = labels
|
|
80
|
+
self._database_role = database_role
|
|
81
|
+
self._is_multiplexed = is_multiplexed
|
|
82
|
+
self._last_use_time = datetime.utcnow()
|
|
83
|
+
|
|
84
|
+
def __lt__(self, other):
|
|
85
|
+
return self._session_id < other._session_id
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def session_id(self):
|
|
89
|
+
"""Read-only ID, set by the back-end during :meth:`create`."""
|
|
90
|
+
return self._session_id
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def is_multiplexed(self):
|
|
94
|
+
"""Whether this session is a multiplexed session.
|
|
95
|
+
|
|
96
|
+
:rtype: bool
|
|
97
|
+
:returns: True if this is a multiplexed session, False otherwise.
|
|
98
|
+
"""
|
|
99
|
+
return self._is_multiplexed
|
|
100
|
+
|
|
101
|
+
@property
|
|
102
|
+
def last_use_time(self):
|
|
103
|
+
""" "Approximate last use time of this session
|
|
104
|
+
|
|
105
|
+
:rtype: datetime
|
|
106
|
+
:returns: the approximate last use time of this session"""
|
|
107
|
+
return self._last_use_time
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def database_role(self):
|
|
111
|
+
"""User-assigned database-role for the session.
|
|
112
|
+
|
|
113
|
+
:rtype: str
|
|
114
|
+
:returns: the database role str (None if no database role were assigned)."""
|
|
115
|
+
return self._database_role
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def labels(self):
|
|
119
|
+
"""User-assigned labels for the session.
|
|
120
|
+
|
|
121
|
+
:rtype: dict (str -> str)
|
|
122
|
+
:returns: the labels dict (empty if no labels were assigned.
|
|
123
|
+
"""
|
|
124
|
+
return self._labels
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def name(self):
|
|
128
|
+
"""Session name used in requests.
|
|
129
|
+
|
|
130
|
+
.. note::
|
|
131
|
+
|
|
132
|
+
This property will not change if ``session_id`` does not, but the
|
|
133
|
+
return value is not cached.
|
|
134
|
+
|
|
135
|
+
The session name is of the form
|
|
136
|
+
|
|
137
|
+
``"projects/../instances/../databases/../sessions/{session_id}"``
|
|
138
|
+
|
|
139
|
+
:rtype: str
|
|
140
|
+
:returns: The session name.
|
|
141
|
+
:raises ValueError: if session is not yet created
|
|
142
|
+
"""
|
|
143
|
+
if self._session_id is None:
|
|
144
|
+
raise ValueError("No session ID set by back-end")
|
|
145
|
+
return self._database.name + "/sessions/" + self._session_id
|
|
146
|
+
|
|
147
|
+
def create(self):
|
|
148
|
+
"""Create this session, bound to its database.
|
|
149
|
+
|
|
150
|
+
See
|
|
151
|
+
https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.CreateSession
|
|
152
|
+
|
|
153
|
+
:raises ValueError: if :attr:`session_id` is already set.
|
|
154
|
+
"""
|
|
155
|
+
current_span = get_current_span()
|
|
156
|
+
add_span_event(current_span, "Creating Session")
|
|
157
|
+
|
|
158
|
+
if self._session_id is not None:
|
|
159
|
+
raise ValueError("Session ID already set by back-end")
|
|
160
|
+
api = self._database.spanner_api
|
|
161
|
+
metadata = _metadata_with_prefix(self._database.name)
|
|
162
|
+
if self._database._route_to_leader_enabled:
|
|
163
|
+
metadata.append(
|
|
164
|
+
_metadata_with_leader_aware_routing(
|
|
165
|
+
self._database._route_to_leader_enabled
|
|
166
|
+
)
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
request = CreateSessionRequest(database=self._database.name)
|
|
170
|
+
if self._database.database_role is not None:
|
|
171
|
+
request.session.creator_role = self._database.database_role
|
|
172
|
+
|
|
173
|
+
if self._labels:
|
|
174
|
+
request.session.labels = self._labels
|
|
175
|
+
|
|
176
|
+
# Set the multiplexed field for multiplexed sessions
|
|
177
|
+
if self._is_multiplexed:
|
|
178
|
+
request.session.multiplexed = True
|
|
179
|
+
|
|
180
|
+
observability_options = getattr(self._database, "observability_options", None)
|
|
181
|
+
span_name = (
|
|
182
|
+
"CloudSpanner.CreateMultiplexedSession"
|
|
183
|
+
if self._is_multiplexed
|
|
184
|
+
else "CloudSpanner.CreateSession"
|
|
185
|
+
)
|
|
186
|
+
with trace_call(
|
|
187
|
+
span_name,
|
|
188
|
+
self,
|
|
189
|
+
self._labels,
|
|
190
|
+
observability_options=observability_options,
|
|
191
|
+
metadata=metadata,
|
|
192
|
+
) as span, MetricsCapture():
|
|
193
|
+
session_pb = api.create_session(
|
|
194
|
+
request=request,
|
|
195
|
+
metadata=self._database.metadata_with_request_id(
|
|
196
|
+
self._database._next_nth_request,
|
|
197
|
+
1,
|
|
198
|
+
metadata,
|
|
199
|
+
span,
|
|
200
|
+
),
|
|
201
|
+
)
|
|
202
|
+
self._session_id = session_pb.name.split("/")[-1]
|
|
203
|
+
|
|
204
|
+
def exists(self):
|
|
205
|
+
"""Test for the existence of this session.
|
|
206
|
+
|
|
207
|
+
See
|
|
208
|
+
https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.GetSession
|
|
209
|
+
|
|
210
|
+
:rtype: bool
|
|
211
|
+
:returns: True if the session exists on the back-end, else False.
|
|
212
|
+
"""
|
|
213
|
+
current_span = get_current_span()
|
|
214
|
+
if self._session_id is None:
|
|
215
|
+
add_span_event(
|
|
216
|
+
current_span,
|
|
217
|
+
"Checking session existence: Session does not exist as it has not been created yet",
|
|
218
|
+
)
|
|
219
|
+
return False
|
|
220
|
+
|
|
221
|
+
add_span_event(
|
|
222
|
+
current_span, "Checking if Session exists", {"session.id": self._session_id}
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
database = self._database
|
|
226
|
+
api = database.spanner_api
|
|
227
|
+
metadata = _metadata_with_prefix(self._database.name)
|
|
228
|
+
if self._database._route_to_leader_enabled:
|
|
229
|
+
metadata.append(
|
|
230
|
+
_metadata_with_leader_aware_routing(
|
|
231
|
+
self._database._route_to_leader_enabled
|
|
232
|
+
)
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
observability_options = getattr(self._database, "observability_options", None)
|
|
236
|
+
with trace_call(
|
|
237
|
+
"CloudSpanner.GetSession",
|
|
238
|
+
self,
|
|
239
|
+
observability_options=observability_options,
|
|
240
|
+
metadata=metadata,
|
|
241
|
+
) as span, MetricsCapture():
|
|
242
|
+
try:
|
|
243
|
+
api.get_session(
|
|
244
|
+
name=self.name,
|
|
245
|
+
metadata=database.metadata_with_request_id(
|
|
246
|
+
database._next_nth_request,
|
|
247
|
+
1,
|
|
248
|
+
metadata,
|
|
249
|
+
span,
|
|
250
|
+
),
|
|
251
|
+
)
|
|
252
|
+
if span:
|
|
253
|
+
span.set_attribute("session_found", True)
|
|
254
|
+
except NotFound:
|
|
255
|
+
if span:
|
|
256
|
+
span.set_attribute("session_found", False)
|
|
257
|
+
return False
|
|
258
|
+
|
|
259
|
+
return True
|
|
260
|
+
|
|
261
|
+
def delete(self):
|
|
262
|
+
"""Delete this session.
|
|
263
|
+
|
|
264
|
+
See
|
|
265
|
+
https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.GetSession
|
|
266
|
+
|
|
267
|
+
:raises ValueError: if :attr:`session_id` is not already set.
|
|
268
|
+
:raises NotFound: if the session does not exist
|
|
269
|
+
"""
|
|
270
|
+
current_span = get_current_span()
|
|
271
|
+
if self._session_id is None:
|
|
272
|
+
add_span_event(
|
|
273
|
+
current_span, "Deleting Session failed due to unset session_id"
|
|
274
|
+
)
|
|
275
|
+
raise ValueError("Session ID not set by back-end")
|
|
276
|
+
|
|
277
|
+
add_span_event(
|
|
278
|
+
current_span, "Deleting Session", {"session.id": self._session_id}
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
database = self._database
|
|
282
|
+
api = database.spanner_api
|
|
283
|
+
metadata = _metadata_with_prefix(database.name)
|
|
284
|
+
observability_options = getattr(self._database, "observability_options", None)
|
|
285
|
+
with trace_call(
|
|
286
|
+
"CloudSpanner.DeleteSession",
|
|
287
|
+
self,
|
|
288
|
+
extra_attributes={
|
|
289
|
+
"session.id": self._session_id,
|
|
290
|
+
"session.name": self.name,
|
|
291
|
+
},
|
|
292
|
+
observability_options=observability_options,
|
|
293
|
+
metadata=metadata,
|
|
294
|
+
) as span, MetricsCapture():
|
|
295
|
+
api.delete_session(
|
|
296
|
+
name=self.name,
|
|
297
|
+
metadata=database.metadata_with_request_id(
|
|
298
|
+
database._next_nth_request,
|
|
299
|
+
1,
|
|
300
|
+
metadata,
|
|
301
|
+
span,
|
|
302
|
+
),
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
def ping(self):
|
|
306
|
+
"""Ping the session to keep it alive by executing "SELECT 1".
|
|
307
|
+
|
|
308
|
+
:raises ValueError: if :attr:`session_id` is not already set.
|
|
309
|
+
"""
|
|
310
|
+
if self._session_id is None:
|
|
311
|
+
raise ValueError("Session ID not set by back-end")
|
|
312
|
+
database = self._database
|
|
313
|
+
api = database.spanner_api
|
|
314
|
+
request = ExecuteSqlRequest(session=self.name, sql="SELECT 1")
|
|
315
|
+
api.execute_sql(
|
|
316
|
+
request=request,
|
|
317
|
+
metadata=database.metadata_with_request_id(
|
|
318
|
+
database._next_nth_request,
|
|
319
|
+
1,
|
|
320
|
+
_metadata_with_prefix(database.name),
|
|
321
|
+
),
|
|
322
|
+
)
|
|
323
|
+
self._last_use_time = datetime.now()
|
|
324
|
+
|
|
325
|
+
def snapshot(self, **kw):
|
|
326
|
+
"""Create a snapshot to perform a set of reads with shared staleness.
|
|
327
|
+
|
|
328
|
+
See
|
|
329
|
+
https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.TransactionOptions.ReadOnly
|
|
330
|
+
|
|
331
|
+
:type kw: dict
|
|
332
|
+
:param kw: Passed through to
|
|
333
|
+
:class:`~google.cloud.spanner_v1.snapshot.Snapshot` ctor.
|
|
334
|
+
|
|
335
|
+
:rtype: :class:`~google.cloud.spanner_v1.snapshot.Snapshot`
|
|
336
|
+
:returns: a snapshot bound to this session
|
|
337
|
+
:raises ValueError: if the session has not yet been created.
|
|
338
|
+
"""
|
|
339
|
+
if self._session_id is None:
|
|
340
|
+
raise ValueError("Session has not been created.")
|
|
341
|
+
|
|
342
|
+
return Snapshot(self, **kw)
|
|
343
|
+
|
|
344
|
+
def read(self, table, columns, keyset, index="", limit=0, column_info=None):
|
|
345
|
+
"""Perform a ``StreamingRead`` API request for rows in a table.
|
|
346
|
+
|
|
347
|
+
:type table: str
|
|
348
|
+
:param table: name of the table from which to fetch data
|
|
349
|
+
|
|
350
|
+
:type columns: list of str
|
|
351
|
+
:param columns: names of columns to be retrieved
|
|
352
|
+
|
|
353
|
+
:type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet`
|
|
354
|
+
:param keyset: keys / ranges identifying rows to be retrieved
|
|
355
|
+
|
|
356
|
+
:type index: str
|
|
357
|
+
:param index: (Optional) name of index to use, rather than the
|
|
358
|
+
table's primary key
|
|
359
|
+
|
|
360
|
+
:type limit: int
|
|
361
|
+
:param limit: (Optional) maximum number of rows to return
|
|
362
|
+
|
|
363
|
+
:type column_info: dict
|
|
364
|
+
:param column_info: (Optional) dict of mapping between column names and additional column information.
|
|
365
|
+
An object where column names as keys and custom objects as corresponding
|
|
366
|
+
values for deserialization. It's specifically useful for data types like
|
|
367
|
+
protobuf where deserialization logic is on user-specific code. When provided,
|
|
368
|
+
the custom object enables deserialization of backend-received column data.
|
|
369
|
+
If not provided, data remains serialized as bytes for Proto Messages and
|
|
370
|
+
integer for Proto Enums.
|
|
371
|
+
|
|
372
|
+
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
|
|
373
|
+
:returns: a result set instance which can be used to consume rows.
|
|
374
|
+
"""
|
|
375
|
+
return self.snapshot().read(
|
|
376
|
+
table, columns, keyset, index, limit, column_info=column_info
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
def execute_sql(
|
|
380
|
+
self,
|
|
381
|
+
sql,
|
|
382
|
+
params=None,
|
|
383
|
+
param_types=None,
|
|
384
|
+
query_mode=None,
|
|
385
|
+
query_options=None,
|
|
386
|
+
request_options=None,
|
|
387
|
+
retry=method.DEFAULT,
|
|
388
|
+
timeout=method.DEFAULT,
|
|
389
|
+
column_info=None,
|
|
390
|
+
):
|
|
391
|
+
"""Perform an ``ExecuteStreamingSql`` API request.
|
|
392
|
+
|
|
393
|
+
:type sql: str
|
|
394
|
+
:param sql: SQL query statement
|
|
395
|
+
|
|
396
|
+
:type params: dict, {str -> column value}
|
|
397
|
+
:param params: values for parameter replacement. Keys must match
|
|
398
|
+
the names used in ``sql``.
|
|
399
|
+
|
|
400
|
+
:type param_types:
|
|
401
|
+
dict, {str -> :class:`~google.spanner.v1.types.TypeCode`}
|
|
402
|
+
:param param_types: (Optional) explicit types for one or more param
|
|
403
|
+
values; overrides default type detection on the
|
|
404
|
+
back-end.
|
|
405
|
+
|
|
406
|
+
:type query_mode:
|
|
407
|
+
:class:`~google.spanner.v1.types.ExecuteSqlRequest.QueryMode`
|
|
408
|
+
:param query_mode: Mode governing return of results / query plan. See:
|
|
409
|
+
`QueryMode <https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode>`_.
|
|
410
|
+
|
|
411
|
+
:type query_options:
|
|
412
|
+
:class:`~google.cloud.spanner_v1.types.ExecuteSqlRequest.QueryOptions`
|
|
413
|
+
or :class:`dict`
|
|
414
|
+
:param query_options: (Optional) Options that are provided for query plan stability.
|
|
415
|
+
|
|
416
|
+
:type request_options:
|
|
417
|
+
:class:`google.cloud.spanner_v1.types.RequestOptions`
|
|
418
|
+
:param request_options:
|
|
419
|
+
(Optional) Common options for this request.
|
|
420
|
+
If a dict is provided, it must be of the same form as the protobuf
|
|
421
|
+
message :class:`~google.cloud.spanner_v1.types.RequestOptions`.
|
|
422
|
+
|
|
423
|
+
:type retry: :class:`~google.api_core.retry.Retry`
|
|
424
|
+
:param retry: (Optional) The retry settings for this request.
|
|
425
|
+
|
|
426
|
+
:type timeout: float
|
|
427
|
+
:param timeout: (Optional) The timeout for this request.
|
|
428
|
+
|
|
429
|
+
:type column_info: dict
|
|
430
|
+
:param column_info: (Optional) dict of mapping between column names and additional column information.
|
|
431
|
+
An object where column names as keys and custom objects as corresponding
|
|
432
|
+
values for deserialization. It's specifically useful for data types like
|
|
433
|
+
protobuf where deserialization logic is on user-specific code. When provided,
|
|
434
|
+
the custom object enables deserialization of backend-received column data.
|
|
435
|
+
If not provided, data remains serialized as bytes for Proto Messages and
|
|
436
|
+
integer for Proto Enums.
|
|
437
|
+
|
|
438
|
+
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
|
|
439
|
+
:returns: a result set instance which can be used to consume rows.
|
|
440
|
+
"""
|
|
441
|
+
return self.snapshot().execute_sql(
|
|
442
|
+
sql,
|
|
443
|
+
params,
|
|
444
|
+
param_types,
|
|
445
|
+
query_mode,
|
|
446
|
+
query_options=query_options,
|
|
447
|
+
request_options=request_options,
|
|
448
|
+
retry=retry,
|
|
449
|
+
timeout=timeout,
|
|
450
|
+
column_info=column_info,
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
def batch(self):
|
|
454
|
+
"""Factory to create a batch for this session.
|
|
455
|
+
|
|
456
|
+
:rtype: :class:`~google.cloud.spanner_v1.batch.Batch`
|
|
457
|
+
:returns: a batch bound to this session
|
|
458
|
+
:raises ValueError: if the session has not yet been created.
|
|
459
|
+
"""
|
|
460
|
+
if self._session_id is None:
|
|
461
|
+
raise ValueError("Session has not been created.")
|
|
462
|
+
|
|
463
|
+
return Batch(self)
|
|
464
|
+
|
|
465
|
+
def transaction(self):
|
|
466
|
+
"""Create a transaction to perform a set of reads with shared staleness.
|
|
467
|
+
|
|
468
|
+
:rtype: :class:`~google.cloud.spanner_v1.transaction.Transaction`
|
|
469
|
+
:returns: a transaction bound to this session
|
|
470
|
+
:raises ValueError: if the session has not yet been created.
|
|
471
|
+
"""
|
|
472
|
+
if self._session_id is None:
|
|
473
|
+
raise ValueError("Session has not been created.")
|
|
474
|
+
|
|
475
|
+
if self._transaction is not None:
|
|
476
|
+
self._transaction.rolled_back = True
|
|
477
|
+
del self._transaction
|
|
478
|
+
|
|
479
|
+
txn = self._transaction = Transaction(self)
|
|
480
|
+
return txn
|
|
481
|
+
|
|
482
|
+
def run_in_transaction(self, func, *args, **kw):
|
|
483
|
+
"""Perform a unit of work in a transaction, retrying on abort.
|
|
484
|
+
|
|
485
|
+
:type func: callable
|
|
486
|
+
:param func: takes a required positional argument, the transaction,
|
|
487
|
+
and additional positional / keyword arguments as supplied
|
|
488
|
+
by the caller.
|
|
489
|
+
|
|
490
|
+
:type args: tuple
|
|
491
|
+
:param args: additional positional arguments to be passed to ``func``.
|
|
492
|
+
|
|
493
|
+
:type kw: dict
|
|
494
|
+
:param kw: (Optional) keyword arguments to be passed to ``func``.
|
|
495
|
+
If passed:
|
|
496
|
+
"timeout_secs" will be removed and used to
|
|
497
|
+
override the default retry timeout which defines maximum timestamp
|
|
498
|
+
to continue retrying the transaction.
|
|
499
|
+
"commit_request_options" will be removed and used to set the
|
|
500
|
+
request options for the commit request.
|
|
501
|
+
"max_commit_delay" will be removed and used to set the max commit delay for the request.
|
|
502
|
+
"transaction_tag" will be removed and used to set the transaction tag for the request.
|
|
503
|
+
"exclude_txn_from_change_streams" if true, instructs the transaction to be excluded
|
|
504
|
+
from being recorded in change streams with the DDL option `allow_txn_exclusion=true`.
|
|
505
|
+
This does not exclude the transaction from being recorded in the change streams with
|
|
506
|
+
the DDL option `allow_txn_exclusion` being false or unset.
|
|
507
|
+
"isolation_level" sets the isolation level for the transaction.
|
|
508
|
+
|
|
509
|
+
:rtype: Any
|
|
510
|
+
:returns: The return value of ``func``.
|
|
511
|
+
|
|
512
|
+
:raises Exception:
|
|
513
|
+
reraises any non-ABORT exceptions raised by ``func``.
|
|
514
|
+
"""
|
|
515
|
+
deadline = time.time() + kw.pop("timeout_secs", DEFAULT_RETRY_TIMEOUT_SECS)
|
|
516
|
+
default_retry_delay = kw.pop("default_retry_delay", None)
|
|
517
|
+
commit_request_options = kw.pop("commit_request_options", None)
|
|
518
|
+
max_commit_delay = kw.pop("max_commit_delay", None)
|
|
519
|
+
transaction_tag = kw.pop("transaction_tag", None)
|
|
520
|
+
exclude_txn_from_change_streams = kw.pop(
|
|
521
|
+
"exclude_txn_from_change_streams", None
|
|
522
|
+
)
|
|
523
|
+
isolation_level = kw.pop("isolation_level", None)
|
|
524
|
+
|
|
525
|
+
attempts = 0
|
|
526
|
+
|
|
527
|
+
observability_options = getattr(self._database, "observability_options", None)
|
|
528
|
+
with trace_call(
|
|
529
|
+
"CloudSpanner.Session.run_in_transaction",
|
|
530
|
+
self,
|
|
531
|
+
observability_options=observability_options,
|
|
532
|
+
) as span, MetricsCapture():
|
|
533
|
+
while True:
|
|
534
|
+
if self._transaction is None:
|
|
535
|
+
txn = self.transaction()
|
|
536
|
+
txn.transaction_tag = transaction_tag
|
|
537
|
+
txn.exclude_txn_from_change_streams = (
|
|
538
|
+
exclude_txn_from_change_streams
|
|
539
|
+
)
|
|
540
|
+
txn.isolation_level = isolation_level
|
|
541
|
+
else:
|
|
542
|
+
txn = self._transaction
|
|
543
|
+
|
|
544
|
+
span_attributes = dict()
|
|
545
|
+
|
|
546
|
+
try:
|
|
547
|
+
attempts += 1
|
|
548
|
+
span_attributes["attempt"] = attempts
|
|
549
|
+
txn_id = getattr(txn, "_transaction_id", "") or ""
|
|
550
|
+
if txn_id:
|
|
551
|
+
span_attributes["transaction.id"] = txn_id
|
|
552
|
+
|
|
553
|
+
return_value = func(txn, *args, **kw)
|
|
554
|
+
|
|
555
|
+
except Aborted as exc:
|
|
556
|
+
del self._transaction
|
|
557
|
+
if span:
|
|
558
|
+
delay_seconds = _get_retry_delay(
|
|
559
|
+
exc.errors[0],
|
|
560
|
+
attempts,
|
|
561
|
+
default_retry_delay=default_retry_delay,
|
|
562
|
+
)
|
|
563
|
+
attributes = dict(delay_seconds=delay_seconds, cause=str(exc))
|
|
564
|
+
attributes.update(span_attributes)
|
|
565
|
+
add_span_event(
|
|
566
|
+
span,
|
|
567
|
+
"Transaction was aborted in user operation, retrying",
|
|
568
|
+
attributes,
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
_delay_until_retry(
|
|
572
|
+
exc, deadline, attempts, default_retry_delay=default_retry_delay
|
|
573
|
+
)
|
|
574
|
+
continue
|
|
575
|
+
except GoogleAPICallError:
|
|
576
|
+
del self._transaction
|
|
577
|
+
add_span_event(
|
|
578
|
+
span,
|
|
579
|
+
"User operation failed due to GoogleAPICallError, not retrying",
|
|
580
|
+
span_attributes,
|
|
581
|
+
)
|
|
582
|
+
raise
|
|
583
|
+
except Exception:
|
|
584
|
+
add_span_event(
|
|
585
|
+
span,
|
|
586
|
+
"User operation failed. Invoking Transaction.rollback(), not retrying",
|
|
587
|
+
span_attributes,
|
|
588
|
+
)
|
|
589
|
+
txn.rollback()
|
|
590
|
+
raise
|
|
591
|
+
|
|
592
|
+
try:
|
|
593
|
+
txn.commit(
|
|
594
|
+
return_commit_stats=self._database.log_commit_stats,
|
|
595
|
+
request_options=commit_request_options,
|
|
596
|
+
max_commit_delay=max_commit_delay,
|
|
597
|
+
)
|
|
598
|
+
except Aborted as exc:
|
|
599
|
+
del self._transaction
|
|
600
|
+
if span:
|
|
601
|
+
delay_seconds = _get_retry_delay(
|
|
602
|
+
exc.errors[0],
|
|
603
|
+
attempts,
|
|
604
|
+
default_retry_delay=default_retry_delay,
|
|
605
|
+
)
|
|
606
|
+
attributes = dict(delay_seconds=delay_seconds)
|
|
607
|
+
attributes.update(span_attributes)
|
|
608
|
+
add_span_event(
|
|
609
|
+
span,
|
|
610
|
+
"Transaction got aborted during commit, retrying afresh",
|
|
611
|
+
attributes,
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
_delay_until_retry(
|
|
615
|
+
exc, deadline, attempts, default_retry_delay=default_retry_delay
|
|
616
|
+
)
|
|
617
|
+
except GoogleAPICallError:
|
|
618
|
+
del self._transaction
|
|
619
|
+
add_span_event(
|
|
620
|
+
span,
|
|
621
|
+
"Transaction.commit failed due to GoogleAPICallError, not retrying",
|
|
622
|
+
span_attributes,
|
|
623
|
+
)
|
|
624
|
+
raise
|
|
625
|
+
else:
|
|
626
|
+
if self._database.log_commit_stats and txn.commit_stats:
|
|
627
|
+
self._database.logger.info(
|
|
628
|
+
"CommitStats: {}".format(txn.commit_stats),
|
|
629
|
+
extra={"commit_stats": txn.commit_stats},
|
|
630
|
+
)
|
|
631
|
+
return return_value
|