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.
Files changed (119) hide show
  1. google/cloud/spanner.py +47 -0
  2. google/cloud/spanner_admin_database_v1/__init__.py +146 -0
  3. google/cloud/spanner_admin_database_v1/gapic_metadata.json +418 -0
  4. google/cloud/spanner_admin_database_v1/gapic_version.py +16 -0
  5. google/cloud/spanner_admin_database_v1/py.typed +2 -0
  6. google/cloud/spanner_admin_database_v1/services/__init__.py +15 -0
  7. google/cloud/spanner_admin_database_v1/services/database_admin/__init__.py +22 -0
  8. google/cloud/spanner_admin_database_v1/services/database_admin/async_client.py +4097 -0
  9. google/cloud/spanner_admin_database_v1/services/database_admin/client.py +4602 -0
  10. google/cloud/spanner_admin_database_v1/services/database_admin/pagers.py +989 -0
  11. google/cloud/spanner_admin_database_v1/services/database_admin/transports/__init__.py +38 -0
  12. google/cloud/spanner_admin_database_v1/services/database_admin/transports/base.py +820 -0
  13. google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc.py +1303 -0
  14. google/cloud/spanner_admin_database_v1/services/database_admin/transports/grpc_asyncio.py +1688 -0
  15. google/cloud/spanner_admin_database_v1/services/database_admin/transports/rest.py +6512 -0
  16. google/cloud/spanner_admin_database_v1/services/database_admin/transports/rest_base.py +1650 -0
  17. google/cloud/spanner_admin_database_v1/types/__init__.py +144 -0
  18. google/cloud/spanner_admin_database_v1/types/backup.py +1106 -0
  19. google/cloud/spanner_admin_database_v1/types/backup_schedule.py +369 -0
  20. google/cloud/spanner_admin_database_v1/types/common.py +180 -0
  21. google/cloud/spanner_admin_database_v1/types/spanner_database_admin.py +1303 -0
  22. google/cloud/spanner_admin_instance_v1/__init__.py +110 -0
  23. google/cloud/spanner_admin_instance_v1/gapic_metadata.json +343 -0
  24. google/cloud/spanner_admin_instance_v1/gapic_version.py +16 -0
  25. google/cloud/spanner_admin_instance_v1/py.typed +2 -0
  26. google/cloud/spanner_admin_instance_v1/services/__init__.py +15 -0
  27. google/cloud/spanner_admin_instance_v1/services/instance_admin/__init__.py +22 -0
  28. google/cloud/spanner_admin_instance_v1/services/instance_admin/async_client.py +3466 -0
  29. google/cloud/spanner_admin_instance_v1/services/instance_admin/client.py +3881 -0
  30. google/cloud/spanner_admin_instance_v1/services/instance_admin/pagers.py +856 -0
  31. google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/__init__.py +38 -0
  32. google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/base.py +545 -0
  33. google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc.py +1347 -0
  34. google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/grpc_asyncio.py +1539 -0
  35. google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/rest.py +4834 -0
  36. google/cloud/spanner_admin_instance_v1/services/instance_admin/transports/rest_base.py +1198 -0
  37. google/cloud/spanner_admin_instance_v1/types/__init__.py +104 -0
  38. google/cloud/spanner_admin_instance_v1/types/common.py +99 -0
  39. google/cloud/spanner_admin_instance_v1/types/spanner_instance_admin.py +2375 -0
  40. google/cloud/spanner_dbapi/__init__.py +93 -0
  41. google/cloud/spanner_dbapi/_helpers.py +113 -0
  42. google/cloud/spanner_dbapi/batch_dml_executor.py +135 -0
  43. google/cloud/spanner_dbapi/checksum.py +80 -0
  44. google/cloud/spanner_dbapi/client_side_statement_executor.py +140 -0
  45. google/cloud/spanner_dbapi/client_side_statement_parser.py +106 -0
  46. google/cloud/spanner_dbapi/connection.py +818 -0
  47. google/cloud/spanner_dbapi/cursor.py +609 -0
  48. google/cloud/spanner_dbapi/exceptions.py +172 -0
  49. google/cloud/spanner_dbapi/parse_utils.py +392 -0
  50. google/cloud/spanner_dbapi/parsed_statement.py +63 -0
  51. google/cloud/spanner_dbapi/parser.py +258 -0
  52. google/cloud/spanner_dbapi/partition_helper.py +41 -0
  53. google/cloud/spanner_dbapi/transaction_helper.py +294 -0
  54. google/cloud/spanner_dbapi/types.py +106 -0
  55. google/cloud/spanner_dbapi/utils.py +147 -0
  56. google/cloud/spanner_dbapi/version.py +20 -0
  57. google/cloud/spanner_v1/__init__.py +154 -0
  58. google/cloud/spanner_v1/_helpers.py +751 -0
  59. google/cloud/spanner_v1/_opentelemetry_tracing.py +165 -0
  60. google/cloud/spanner_v1/backup.py +397 -0
  61. google/cloud/spanner_v1/batch.py +433 -0
  62. google/cloud/spanner_v1/client.py +538 -0
  63. google/cloud/spanner_v1/data_types.py +350 -0
  64. google/cloud/spanner_v1/database.py +1968 -0
  65. google/cloud/spanner_v1/database_sessions_manager.py +249 -0
  66. google/cloud/spanner_v1/gapic_metadata.json +268 -0
  67. google/cloud/spanner_v1/gapic_version.py +16 -0
  68. google/cloud/spanner_v1/instance.py +735 -0
  69. google/cloud/spanner_v1/keyset.py +193 -0
  70. google/cloud/spanner_v1/merged_result_set.py +146 -0
  71. google/cloud/spanner_v1/metrics/constants.py +71 -0
  72. google/cloud/spanner_v1/metrics/metrics_capture.py +75 -0
  73. google/cloud/spanner_v1/metrics/metrics_exporter.py +384 -0
  74. google/cloud/spanner_v1/metrics/metrics_interceptor.py +156 -0
  75. google/cloud/spanner_v1/metrics/metrics_tracer.py +588 -0
  76. google/cloud/spanner_v1/metrics/metrics_tracer_factory.py +328 -0
  77. google/cloud/spanner_v1/metrics/spanner_metrics_tracer_factory.py +172 -0
  78. google/cloud/spanner_v1/param_types.py +110 -0
  79. google/cloud/spanner_v1/pool.py +813 -0
  80. google/cloud/spanner_v1/py.typed +2 -0
  81. google/cloud/spanner_v1/request_id_header.py +64 -0
  82. google/cloud/spanner_v1/services/__init__.py +15 -0
  83. google/cloud/spanner_v1/services/spanner/__init__.py +22 -0
  84. google/cloud/spanner_v1/services/spanner/async_client.py +2205 -0
  85. google/cloud/spanner_v1/services/spanner/client.py +2624 -0
  86. google/cloud/spanner_v1/services/spanner/pagers.py +196 -0
  87. google/cloud/spanner_v1/services/spanner/transports/__init__.py +38 -0
  88. google/cloud/spanner_v1/services/spanner/transports/base.py +520 -0
  89. google/cloud/spanner_v1/services/spanner/transports/grpc.py +911 -0
  90. google/cloud/spanner_v1/services/spanner/transports/grpc_asyncio.py +1144 -0
  91. google/cloud/spanner_v1/services/spanner/transports/rest.py +3468 -0
  92. google/cloud/spanner_v1/services/spanner/transports/rest_base.py +981 -0
  93. google/cloud/spanner_v1/session.py +631 -0
  94. google/cloud/spanner_v1/session_options.py +133 -0
  95. google/cloud/spanner_v1/snapshot.py +1057 -0
  96. google/cloud/spanner_v1/streamed.py +402 -0
  97. google/cloud/spanner_v1/table.py +181 -0
  98. google/cloud/spanner_v1/testing/__init__.py +0 -0
  99. google/cloud/spanner_v1/testing/database_test.py +121 -0
  100. google/cloud/spanner_v1/testing/interceptors.py +118 -0
  101. google/cloud/spanner_v1/testing/mock_database_admin.py +38 -0
  102. google/cloud/spanner_v1/testing/mock_spanner.py +261 -0
  103. google/cloud/spanner_v1/testing/spanner_database_admin_pb2_grpc.py +1267 -0
  104. google/cloud/spanner_v1/testing/spanner_pb2_grpc.py +882 -0
  105. google/cloud/spanner_v1/transaction.py +747 -0
  106. google/cloud/spanner_v1/types/__init__.py +118 -0
  107. google/cloud/spanner_v1/types/commit_response.py +94 -0
  108. google/cloud/spanner_v1/types/keys.py +248 -0
  109. google/cloud/spanner_v1/types/mutation.py +201 -0
  110. google/cloud/spanner_v1/types/query_plan.py +220 -0
  111. google/cloud/spanner_v1/types/result_set.py +379 -0
  112. google/cloud/spanner_v1/types/spanner.py +1815 -0
  113. google/cloud/spanner_v1/types/transaction.py +818 -0
  114. google/cloud/spanner_v1/types/type.py +288 -0
  115. google_cloud_spanner-3.55.0.dist-info/LICENSE +202 -0
  116. google_cloud_spanner-3.55.0.dist-info/METADATA +318 -0
  117. google_cloud_spanner-3.55.0.dist-info/RECORD +119 -0
  118. google_cloud_spanner-3.55.0.dist-info/WHEEL +5 -0
  119. google_cloud_spanner-3.55.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2624 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright 2025 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ from collections import OrderedDict
17
+ from http import HTTPStatus
18
+ import json
19
+ import logging as std_logging
20
+ import os
21
+ import re
22
+ from typing import (
23
+ Dict,
24
+ Callable,
25
+ Mapping,
26
+ MutableMapping,
27
+ MutableSequence,
28
+ Optional,
29
+ Iterable,
30
+ Sequence,
31
+ Tuple,
32
+ Type,
33
+ Union,
34
+ cast,
35
+ )
36
+ import warnings
37
+
38
+ from google.cloud.spanner_v1 import gapic_version as package_version
39
+
40
+ from google.api_core import client_options as client_options_lib
41
+ from google.api_core import exceptions as core_exceptions
42
+ from google.api_core import gapic_v1
43
+ from google.api_core import retry as retries
44
+ from google.auth import credentials as ga_credentials # type: ignore
45
+ from google.auth.transport import mtls # type: ignore
46
+ from google.auth.transport.grpc import SslCredentials # type: ignore
47
+ from google.auth.exceptions import MutualTLSChannelError # type: ignore
48
+ from google.oauth2 import service_account # type: ignore
49
+ import google.protobuf
50
+
51
+ try:
52
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
53
+ except AttributeError: # pragma: NO COVER
54
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
55
+
56
+ try:
57
+ from google.api_core import client_logging # type: ignore
58
+
59
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
60
+ except ImportError: # pragma: NO COVER
61
+ CLIENT_LOGGING_SUPPORTED = False
62
+
63
+ _LOGGER = std_logging.getLogger(__name__)
64
+
65
+ from google.cloud.spanner_v1.services.spanner import pagers
66
+ from google.cloud.spanner_v1.types import commit_response
67
+ from google.cloud.spanner_v1.types import mutation
68
+ from google.cloud.spanner_v1.types import result_set
69
+ from google.cloud.spanner_v1.types import spanner
70
+ from google.cloud.spanner_v1.types import transaction
71
+ from google.cloud.spanner_v1.metrics.metrics_interceptor import MetricsInterceptor
72
+ from google.protobuf import struct_pb2 # type: ignore
73
+ from google.protobuf import timestamp_pb2 # type: ignore
74
+ from google.rpc import status_pb2 # type: ignore
75
+ from .transports.base import SpannerTransport, DEFAULT_CLIENT_INFO
76
+ from .transports.grpc import SpannerGrpcTransport
77
+ from .transports.grpc_asyncio import SpannerGrpcAsyncIOTransport
78
+ from .transports.rest import SpannerRestTransport
79
+
80
+
81
+ class SpannerClientMeta(type):
82
+ """Metaclass for the Spanner client.
83
+
84
+ This provides class-level methods for building and retrieving
85
+ support objects (e.g. transport) without polluting the client instance
86
+ objects.
87
+ """
88
+
89
+ _transport_registry = OrderedDict() # type: Dict[str, Type[SpannerTransport]]
90
+ _transport_registry["grpc"] = SpannerGrpcTransport
91
+ _transport_registry["grpc_asyncio"] = SpannerGrpcAsyncIOTransport
92
+ _transport_registry["rest"] = SpannerRestTransport
93
+
94
+ def get_transport_class(
95
+ cls,
96
+ label: Optional[str] = None,
97
+ ) -> Type[SpannerTransport]:
98
+ """Returns an appropriate transport class.
99
+
100
+ Args:
101
+ label: The name of the desired transport. If none is
102
+ provided, then the first transport in the registry is used.
103
+
104
+ Returns:
105
+ The transport class to use.
106
+ """
107
+ # If a specific transport is requested, return that one.
108
+ if label:
109
+ return cls._transport_registry[label]
110
+
111
+ # No transport is requested; return the default (that is, the first one
112
+ # in the dictionary).
113
+ return next(iter(cls._transport_registry.values()))
114
+
115
+
116
+ class SpannerClient(metaclass=SpannerClientMeta):
117
+ """Cloud Spanner API
118
+
119
+ The Cloud Spanner API can be used to manage sessions and execute
120
+ transactions on data stored in Cloud Spanner databases.
121
+ """
122
+
123
+ @staticmethod
124
+ def _get_default_mtls_endpoint(api_endpoint):
125
+ """Converts api endpoint to mTLS endpoint.
126
+
127
+ Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
128
+ "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
129
+ Args:
130
+ api_endpoint (Optional[str]): the api endpoint to convert.
131
+ Returns:
132
+ str: converted mTLS api endpoint.
133
+ """
134
+ if not api_endpoint:
135
+ return api_endpoint
136
+
137
+ mtls_endpoint_re = re.compile(
138
+ r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
139
+ )
140
+
141
+ m = mtls_endpoint_re.match(api_endpoint)
142
+ name, mtls, sandbox, googledomain = m.groups()
143
+ if mtls or not googledomain:
144
+ return api_endpoint
145
+
146
+ if sandbox:
147
+ return api_endpoint.replace(
148
+ "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
149
+ )
150
+
151
+ return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
152
+
153
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
154
+ DEFAULT_ENDPOINT = "spanner.googleapis.com"
155
+ DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
156
+ DEFAULT_ENDPOINT
157
+ )
158
+
159
+ _DEFAULT_ENDPOINT_TEMPLATE = "spanner.{UNIVERSE_DOMAIN}"
160
+ _DEFAULT_UNIVERSE = "googleapis.com"
161
+
162
+ @classmethod
163
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
164
+ """Creates an instance of this client using the provided credentials
165
+ info.
166
+
167
+ Args:
168
+ info (dict): The service account private key info.
169
+ args: Additional arguments to pass to the constructor.
170
+ kwargs: Additional arguments to pass to the constructor.
171
+
172
+ Returns:
173
+ SpannerClient: The constructed client.
174
+ """
175
+ credentials = service_account.Credentials.from_service_account_info(info)
176
+ kwargs["credentials"] = credentials
177
+ return cls(*args, **kwargs)
178
+
179
+ @classmethod
180
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
181
+ """Creates an instance of this client using the provided credentials
182
+ file.
183
+
184
+ Args:
185
+ filename (str): The path to the service account private key json
186
+ file.
187
+ args: Additional arguments to pass to the constructor.
188
+ kwargs: Additional arguments to pass to the constructor.
189
+
190
+ Returns:
191
+ SpannerClient: The constructed client.
192
+ """
193
+ credentials = service_account.Credentials.from_service_account_file(filename)
194
+ kwargs["credentials"] = credentials
195
+ return cls(*args, **kwargs)
196
+
197
+ from_service_account_json = from_service_account_file
198
+
199
+ @property
200
+ def transport(self) -> SpannerTransport:
201
+ """Returns the transport used by the client instance.
202
+
203
+ Returns:
204
+ SpannerTransport: The transport used by the client
205
+ instance.
206
+ """
207
+ return self._transport
208
+
209
+ @staticmethod
210
+ def database_path(
211
+ project: str,
212
+ instance: str,
213
+ database: str,
214
+ ) -> str:
215
+ """Returns a fully-qualified database string."""
216
+ return "projects/{project}/instances/{instance}/databases/{database}".format(
217
+ project=project,
218
+ instance=instance,
219
+ database=database,
220
+ )
221
+
222
+ @staticmethod
223
+ def parse_database_path(path: str) -> Dict[str, str]:
224
+ """Parses a database path into its component segments."""
225
+ m = re.match(
226
+ r"^projects/(?P<project>.+?)/instances/(?P<instance>.+?)/databases/(?P<database>.+?)$",
227
+ path,
228
+ )
229
+ return m.groupdict() if m else {}
230
+
231
+ @staticmethod
232
+ def session_path(
233
+ project: str,
234
+ instance: str,
235
+ database: str,
236
+ session: str,
237
+ ) -> str:
238
+ """Returns a fully-qualified session string."""
239
+ return "projects/{project}/instances/{instance}/databases/{database}/sessions/{session}".format(
240
+ project=project,
241
+ instance=instance,
242
+ database=database,
243
+ session=session,
244
+ )
245
+
246
+ @staticmethod
247
+ def parse_session_path(path: str) -> Dict[str, str]:
248
+ """Parses a session path into its component segments."""
249
+ m = re.match(
250
+ r"^projects/(?P<project>.+?)/instances/(?P<instance>.+?)/databases/(?P<database>.+?)/sessions/(?P<session>.+?)$",
251
+ path,
252
+ )
253
+ return m.groupdict() if m else {}
254
+
255
+ @staticmethod
256
+ def common_billing_account_path(
257
+ billing_account: str,
258
+ ) -> str:
259
+ """Returns a fully-qualified billing_account string."""
260
+ return "billingAccounts/{billing_account}".format(
261
+ billing_account=billing_account,
262
+ )
263
+
264
+ @staticmethod
265
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
266
+ """Parse a billing_account path into its component segments."""
267
+ m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
268
+ return m.groupdict() if m else {}
269
+
270
+ @staticmethod
271
+ def common_folder_path(
272
+ folder: str,
273
+ ) -> str:
274
+ """Returns a fully-qualified folder string."""
275
+ return "folders/{folder}".format(
276
+ folder=folder,
277
+ )
278
+
279
+ @staticmethod
280
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
281
+ """Parse a folder path into its component segments."""
282
+ m = re.match(r"^folders/(?P<folder>.+?)$", path)
283
+ return m.groupdict() if m else {}
284
+
285
+ @staticmethod
286
+ def common_organization_path(
287
+ organization: str,
288
+ ) -> str:
289
+ """Returns a fully-qualified organization string."""
290
+ return "organizations/{organization}".format(
291
+ organization=organization,
292
+ )
293
+
294
+ @staticmethod
295
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
296
+ """Parse a organization path into its component segments."""
297
+ m = re.match(r"^organizations/(?P<organization>.+?)$", path)
298
+ return m.groupdict() if m else {}
299
+
300
+ @staticmethod
301
+ def common_project_path(
302
+ project: str,
303
+ ) -> str:
304
+ """Returns a fully-qualified project string."""
305
+ return "projects/{project}".format(
306
+ project=project,
307
+ )
308
+
309
+ @staticmethod
310
+ def parse_common_project_path(path: str) -> Dict[str, str]:
311
+ """Parse a project path into its component segments."""
312
+ m = re.match(r"^projects/(?P<project>.+?)$", path)
313
+ return m.groupdict() if m else {}
314
+
315
+ @staticmethod
316
+ def common_location_path(
317
+ project: str,
318
+ location: str,
319
+ ) -> str:
320
+ """Returns a fully-qualified location string."""
321
+ return "projects/{project}/locations/{location}".format(
322
+ project=project,
323
+ location=location,
324
+ )
325
+
326
+ @staticmethod
327
+ def parse_common_location_path(path: str) -> Dict[str, str]:
328
+ """Parse a location path into its component segments."""
329
+ m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
330
+ return m.groupdict() if m else {}
331
+
332
+ @classmethod
333
+ def get_mtls_endpoint_and_cert_source(
334
+ cls, client_options: Optional[client_options_lib.ClientOptions] = None
335
+ ):
336
+ """Deprecated. Return the API endpoint and client cert source for mutual TLS.
337
+
338
+ The client cert source is determined in the following order:
339
+ (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
340
+ client cert source is None.
341
+ (2) if `client_options.client_cert_source` is provided, use the provided one; if the
342
+ default client cert source exists, use the default one; otherwise the client cert
343
+ source is None.
344
+
345
+ The API endpoint is determined in the following order:
346
+ (1) if `client_options.api_endpoint` if provided, use the provided one.
347
+ (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
348
+ default mTLS endpoint; if the environment variable is "never", use the default API
349
+ endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
350
+ use the default API endpoint.
351
+
352
+ More details can be found at https://google.aip.dev/auth/4114.
353
+
354
+ Args:
355
+ client_options (google.api_core.client_options.ClientOptions): Custom options for the
356
+ client. Only the `api_endpoint` and `client_cert_source` properties may be used
357
+ in this method.
358
+
359
+ Returns:
360
+ Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
361
+ client cert source to use.
362
+
363
+ Raises:
364
+ google.auth.exceptions.MutualTLSChannelError: If any errors happen.
365
+ """
366
+
367
+ warnings.warn(
368
+ "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
369
+ DeprecationWarning,
370
+ )
371
+ if client_options is None:
372
+ client_options = client_options_lib.ClientOptions()
373
+ use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
374
+ use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
375
+ if use_client_cert not in ("true", "false"):
376
+ raise ValueError(
377
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
378
+ )
379
+ if use_mtls_endpoint not in ("auto", "never", "always"):
380
+ raise MutualTLSChannelError(
381
+ "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
382
+ )
383
+
384
+ # Figure out the client cert source to use.
385
+ client_cert_source = None
386
+ if use_client_cert == "true":
387
+ if client_options.client_cert_source:
388
+ client_cert_source = client_options.client_cert_source
389
+ elif mtls.has_default_client_cert_source():
390
+ client_cert_source = mtls.default_client_cert_source()
391
+
392
+ # Figure out which api endpoint to use.
393
+ if client_options.api_endpoint is not None:
394
+ api_endpoint = client_options.api_endpoint
395
+ elif use_mtls_endpoint == "always" or (
396
+ use_mtls_endpoint == "auto" and client_cert_source
397
+ ):
398
+ api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
399
+ else:
400
+ api_endpoint = cls.DEFAULT_ENDPOINT
401
+
402
+ return api_endpoint, client_cert_source
403
+
404
+ @staticmethod
405
+ def _read_environment_variables():
406
+ """Returns the environment variables used by the client.
407
+
408
+ Returns:
409
+ Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
410
+ GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
411
+
412
+ Raises:
413
+ ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
414
+ any of ["true", "false"].
415
+ google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
416
+ is not any of ["auto", "never", "always"].
417
+ """
418
+ use_client_cert = os.getenv(
419
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
420
+ ).lower()
421
+ use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
422
+ universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
423
+ if use_client_cert not in ("true", "false"):
424
+ raise ValueError(
425
+ "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
426
+ )
427
+ if use_mtls_endpoint not in ("auto", "never", "always"):
428
+ raise MutualTLSChannelError(
429
+ "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
430
+ )
431
+ return use_client_cert == "true", use_mtls_endpoint, universe_domain_env
432
+
433
+ @staticmethod
434
+ def _get_client_cert_source(provided_cert_source, use_cert_flag):
435
+ """Return the client cert source to be used by the client.
436
+
437
+ Args:
438
+ provided_cert_source (bytes): The client certificate source provided.
439
+ use_cert_flag (bool): A flag indicating whether to use the client certificate.
440
+
441
+ Returns:
442
+ bytes or None: The client cert source to be used by the client.
443
+ """
444
+ client_cert_source = None
445
+ if use_cert_flag:
446
+ if provided_cert_source:
447
+ client_cert_source = provided_cert_source
448
+ elif mtls.has_default_client_cert_source():
449
+ client_cert_source = mtls.default_client_cert_source()
450
+ return client_cert_source
451
+
452
+ @staticmethod
453
+ def _get_api_endpoint(
454
+ api_override, client_cert_source, universe_domain, use_mtls_endpoint
455
+ ):
456
+ """Return the API endpoint used by the client.
457
+
458
+ Args:
459
+ api_override (str): The API endpoint override. If specified, this is always
460
+ the return value of this function and the other arguments are not used.
461
+ client_cert_source (bytes): The client certificate source used by the client.
462
+ universe_domain (str): The universe domain used by the client.
463
+ use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
464
+ Possible values are "always", "auto", or "never".
465
+
466
+ Returns:
467
+ str: The API endpoint to be used by the client.
468
+ """
469
+ if api_override is not None:
470
+ api_endpoint = api_override
471
+ elif use_mtls_endpoint == "always" or (
472
+ use_mtls_endpoint == "auto" and client_cert_source
473
+ ):
474
+ _default_universe = SpannerClient._DEFAULT_UNIVERSE
475
+ if universe_domain != _default_universe:
476
+ raise MutualTLSChannelError(
477
+ f"mTLS is not supported in any universe other than {_default_universe}."
478
+ )
479
+ api_endpoint = SpannerClient.DEFAULT_MTLS_ENDPOINT
480
+ else:
481
+ api_endpoint = SpannerClient._DEFAULT_ENDPOINT_TEMPLATE.format(
482
+ UNIVERSE_DOMAIN=universe_domain
483
+ )
484
+ return api_endpoint
485
+
486
+ @staticmethod
487
+ def _get_universe_domain(
488
+ client_universe_domain: Optional[str], universe_domain_env: Optional[str]
489
+ ) -> str:
490
+ """Return the universe domain used by the client.
491
+
492
+ Args:
493
+ client_universe_domain (Optional[str]): The universe domain configured via the client options.
494
+ universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
495
+
496
+ Returns:
497
+ str: The universe domain to be used by the client.
498
+
499
+ Raises:
500
+ ValueError: If the universe domain is an empty string.
501
+ """
502
+ universe_domain = SpannerClient._DEFAULT_UNIVERSE
503
+ if client_universe_domain is not None:
504
+ universe_domain = client_universe_domain
505
+ elif universe_domain_env is not None:
506
+ universe_domain = universe_domain_env
507
+ if len(universe_domain.strip()) == 0:
508
+ raise ValueError("Universe Domain cannot be an empty string.")
509
+ return universe_domain
510
+
511
+ def _validate_universe_domain(self):
512
+ """Validates client's and credentials' universe domains are consistent.
513
+
514
+ Returns:
515
+ bool: True iff the configured universe domain is valid.
516
+
517
+ Raises:
518
+ ValueError: If the configured universe domain is not valid.
519
+ """
520
+
521
+ # NOTE (b/349488459): universe validation is disabled until further notice.
522
+ return True
523
+
524
+ def _add_cred_info_for_auth_errors(
525
+ self, error: core_exceptions.GoogleAPICallError
526
+ ) -> None:
527
+ """Adds credential info string to error details for 401/403/404 errors.
528
+
529
+ Args:
530
+ error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info.
531
+ """
532
+ if error.code not in [
533
+ HTTPStatus.UNAUTHORIZED,
534
+ HTTPStatus.FORBIDDEN,
535
+ HTTPStatus.NOT_FOUND,
536
+ ]:
537
+ return
538
+
539
+ cred = self._transport._credentials
540
+
541
+ # get_cred_info is only available in google-auth>=2.35.0
542
+ if not hasattr(cred, "get_cred_info"):
543
+ return
544
+
545
+ # ignore the type check since pypy test fails when get_cred_info
546
+ # is not available
547
+ cred_info = cred.get_cred_info() # type: ignore
548
+ if cred_info and hasattr(error._details, "append"):
549
+ error._details.append(json.dumps(cred_info))
550
+
551
+ @property
552
+ def api_endpoint(self):
553
+ """Return the API endpoint used by the client instance.
554
+
555
+ Returns:
556
+ str: The API endpoint used by the client instance.
557
+ """
558
+ return self._api_endpoint
559
+
560
+ @property
561
+ def universe_domain(self) -> str:
562
+ """Return the universe domain used by the client instance.
563
+
564
+ Returns:
565
+ str: The universe domain used by the client instance.
566
+ """
567
+ return self._universe_domain
568
+
569
+ def __init__(
570
+ self,
571
+ *,
572
+ credentials: Optional[ga_credentials.Credentials] = None,
573
+ transport: Optional[
574
+ Union[str, SpannerTransport, Callable[..., SpannerTransport]]
575
+ ] = None,
576
+ client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
577
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
578
+ ) -> None:
579
+ """Instantiates the spanner client.
580
+
581
+ Args:
582
+ credentials (Optional[google.auth.credentials.Credentials]): The
583
+ authorization credentials to attach to requests. These
584
+ credentials identify the application to the service; if none
585
+ are specified, the client will attempt to ascertain the
586
+ credentials from the environment.
587
+ transport (Optional[Union[str,SpannerTransport,Callable[..., SpannerTransport]]]):
588
+ The transport to use, or a Callable that constructs and returns a new transport.
589
+ If a Callable is given, it will be called with the same set of initialization
590
+ arguments as used in the SpannerTransport constructor.
591
+ If set to None, a transport is chosen automatically.
592
+ client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
593
+ Custom options for the client.
594
+
595
+ 1. The ``api_endpoint`` property can be used to override the
596
+ default endpoint provided by the client when ``transport`` is
597
+ not explicitly provided. Only if this property is not set and
598
+ ``transport`` was not explicitly provided, the endpoint is
599
+ determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
600
+ variable, which have one of the following values:
601
+ "always" (always use the default mTLS endpoint), "never" (always
602
+ use the default regular endpoint) and "auto" (auto-switch to the
603
+ default mTLS endpoint if client certificate is present; this is
604
+ the default value).
605
+
606
+ 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
607
+ is "true", then the ``client_cert_source`` property can be used
608
+ to provide a client certificate for mTLS transport. If
609
+ not provided, the default SSL client certificate will be used if
610
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
611
+ set, no client certificate will be used.
612
+
613
+ 3. The ``universe_domain`` property can be used to override the
614
+ default "googleapis.com" universe. Note that the ``api_endpoint``
615
+ property still takes precedence; and ``universe_domain`` is
616
+ currently not supported for mTLS.
617
+
618
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
619
+ The client info used to send a user-agent string along with
620
+ API requests. If ``None``, then default info will be used.
621
+ Generally, you only need to set this if you're developing
622
+ your own client library.
623
+
624
+ Raises:
625
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
626
+ creation failed for any reason.
627
+ """
628
+ self._client_options = client_options
629
+ if isinstance(self._client_options, dict):
630
+ self._client_options = client_options_lib.from_dict(self._client_options)
631
+ if self._client_options is None:
632
+ self._client_options = client_options_lib.ClientOptions()
633
+ self._client_options = cast(
634
+ client_options_lib.ClientOptions, self._client_options
635
+ )
636
+
637
+ universe_domain_opt = getattr(self._client_options, "universe_domain", None)
638
+
639
+ (
640
+ self._use_client_cert,
641
+ self._use_mtls_endpoint,
642
+ self._universe_domain_env,
643
+ ) = SpannerClient._read_environment_variables()
644
+ self._client_cert_source = SpannerClient._get_client_cert_source(
645
+ self._client_options.client_cert_source, self._use_client_cert
646
+ )
647
+ self._universe_domain = SpannerClient._get_universe_domain(
648
+ universe_domain_opt, self._universe_domain_env
649
+ )
650
+ self._api_endpoint = None # updated below, depending on `transport`
651
+
652
+ # Initialize the universe domain validation.
653
+ self._is_universe_domain_valid = False
654
+
655
+ if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
656
+ # Setup logging.
657
+ client_logging.initialize_logging()
658
+
659
+ api_key_value = getattr(self._client_options, "api_key", None)
660
+ if api_key_value and credentials:
661
+ raise ValueError(
662
+ "client_options.api_key and credentials are mutually exclusive"
663
+ )
664
+
665
+ # Save or instantiate the transport.
666
+ # Ordinarily, we provide the transport, but allowing a custom transport
667
+ # instance provides an extensibility point for unusual situations.
668
+ transport_provided = isinstance(transport, SpannerTransport)
669
+ if transport_provided:
670
+ # transport is a SpannerTransport instance.
671
+ if credentials or self._client_options.credentials_file or api_key_value:
672
+ raise ValueError(
673
+ "When providing a transport instance, "
674
+ "provide its credentials directly."
675
+ )
676
+ if self._client_options.scopes:
677
+ raise ValueError(
678
+ "When providing a transport instance, provide its scopes "
679
+ "directly."
680
+ )
681
+ self._transport = cast(SpannerTransport, transport)
682
+ self._api_endpoint = self._transport.host
683
+
684
+ self._api_endpoint = self._api_endpoint or SpannerClient._get_api_endpoint(
685
+ self._client_options.api_endpoint,
686
+ self._client_cert_source,
687
+ self._universe_domain,
688
+ self._use_mtls_endpoint,
689
+ )
690
+
691
+ if not transport_provided:
692
+ import google.auth._default # type: ignore
693
+
694
+ if api_key_value and hasattr(
695
+ google.auth._default, "get_api_key_credentials"
696
+ ):
697
+ credentials = google.auth._default.get_api_key_credentials(
698
+ api_key_value
699
+ )
700
+
701
+ transport_init: Union[
702
+ Type[SpannerTransport], Callable[..., SpannerTransport]
703
+ ] = (
704
+ SpannerClient.get_transport_class(transport)
705
+ if isinstance(transport, str) or transport is None
706
+ else cast(Callable[..., SpannerTransport], transport)
707
+ )
708
+ # initialize with the provided callable or the passed in class
709
+ self._transport = transport_init(
710
+ credentials=credentials,
711
+ credentials_file=self._client_options.credentials_file,
712
+ host=self._api_endpoint,
713
+ scopes=self._client_options.scopes,
714
+ client_cert_source_for_mtls=self._client_cert_source,
715
+ quota_project_id=self._client_options.quota_project_id,
716
+ client_info=client_info,
717
+ always_use_jwt_access=True,
718
+ api_audience=self._client_options.api_audience,
719
+ metrics_interceptor=MetricsInterceptor(),
720
+ )
721
+
722
+ if "async" not in str(self._transport):
723
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
724
+ std_logging.DEBUG
725
+ ): # pragma: NO COVER
726
+ _LOGGER.debug(
727
+ "Created client `google.spanner_v1.SpannerClient`.",
728
+ extra={
729
+ "serviceName": "google.spanner.v1.Spanner",
730
+ "universeDomain": getattr(
731
+ self._transport._credentials, "universe_domain", ""
732
+ ),
733
+ "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
734
+ "credentialsInfo": getattr(
735
+ self.transport._credentials, "get_cred_info", lambda: None
736
+ )(),
737
+ }
738
+ if hasattr(self._transport, "_credentials")
739
+ else {
740
+ "serviceName": "google.spanner.v1.Spanner",
741
+ "credentialsType": None,
742
+ },
743
+ )
744
+
745
+ def create_session(
746
+ self,
747
+ request: Optional[Union[spanner.CreateSessionRequest, dict]] = None,
748
+ *,
749
+ database: Optional[str] = None,
750
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
751
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
752
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
753
+ ) -> spanner.Session:
754
+ r"""Creates a new session. A session can be used to perform
755
+ transactions that read and/or modify data in a Cloud Spanner
756
+ database. Sessions are meant to be reused for many consecutive
757
+ transactions.
758
+
759
+ Sessions can only execute one transaction at a time. To execute
760
+ multiple concurrent read-write/write-only transactions, create
761
+ multiple sessions. Note that standalone reads and queries use a
762
+ transaction internally, and count toward the one transaction
763
+ limit.
764
+
765
+ Active sessions use additional server resources, so it is a good
766
+ idea to delete idle and unneeded sessions. Aside from explicit
767
+ deletes, Cloud Spanner may delete sessions for which no
768
+ operations are sent for more than an hour. If a session is
769
+ deleted, requests to it return ``NOT_FOUND``.
770
+
771
+ Idle sessions can be kept alive by sending a trivial SQL query
772
+ periodically, e.g., ``"SELECT 1"``.
773
+
774
+ .. code-block:: python
775
+
776
+ # This snippet has been automatically generated and should be regarded as a
777
+ # code template only.
778
+ # It will require modifications to work:
779
+ # - It may require correct/in-range values for request initialization.
780
+ # - It may require specifying regional endpoints when creating the service
781
+ # client as shown in:
782
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
783
+ from google.cloud import spanner_v1
784
+
785
+ def sample_create_session():
786
+ # Create a client
787
+ client = spanner_v1.SpannerClient()
788
+
789
+ # Initialize request argument(s)
790
+ request = spanner_v1.CreateSessionRequest(
791
+ database="database_value",
792
+ )
793
+
794
+ # Make the request
795
+ response = client.create_session(request=request)
796
+
797
+ # Handle the response
798
+ print(response)
799
+
800
+ Args:
801
+ request (Union[google.cloud.spanner_v1.types.CreateSessionRequest, dict]):
802
+ The request object. The request for
803
+ [CreateSession][google.spanner.v1.Spanner.CreateSession].
804
+ database (str):
805
+ Required. The database in which the
806
+ new session is created.
807
+
808
+ This corresponds to the ``database`` field
809
+ on the ``request`` instance; if ``request`` is provided, this
810
+ should not be set.
811
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
812
+ should be retried.
813
+ timeout (float): The timeout for this request.
814
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
815
+ sent along with the request as metadata. Normally, each value must be of type `str`,
816
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
817
+ be of type `bytes`.
818
+
819
+ Returns:
820
+ google.cloud.spanner_v1.types.Session:
821
+ A session in the Cloud Spanner API.
822
+ """
823
+ # Create or coerce a protobuf request object.
824
+ # - Quick check: If we got a request object, we should *not* have
825
+ # gotten any keyword arguments that map to the request.
826
+ flattened_params = [database]
827
+ has_flattened_params = (
828
+ len([param for param in flattened_params if param is not None]) > 0
829
+ )
830
+ if request is not None and has_flattened_params:
831
+ raise ValueError(
832
+ "If the `request` argument is set, then none of "
833
+ "the individual field arguments should be set."
834
+ )
835
+
836
+ # - Use the request object if provided (there's no risk of modifying the input as
837
+ # there are no flattened fields), or create one.
838
+ if not isinstance(request, spanner.CreateSessionRequest):
839
+ request = spanner.CreateSessionRequest(request)
840
+ # If we have keyword arguments corresponding to fields on the
841
+ # request, apply these.
842
+ if database is not None:
843
+ request.database = database
844
+
845
+ # Wrap the RPC method; this adds retry and timeout information,
846
+ # and friendly error handling.
847
+ rpc = self._transport._wrapped_methods[self._transport.create_session]
848
+
849
+ # Certain fields should be provided within the metadata header;
850
+ # add these here.
851
+ metadata = tuple(metadata) + (
852
+ gapic_v1.routing_header.to_grpc_metadata((("database", request.database),)),
853
+ )
854
+
855
+ # Validate the universe domain.
856
+ self._validate_universe_domain()
857
+
858
+ # Send the request.
859
+ response = rpc(
860
+ request,
861
+ retry=retry,
862
+ timeout=timeout,
863
+ metadata=metadata,
864
+ )
865
+
866
+ # Done; return the response.
867
+ return response
868
+
869
+ def batch_create_sessions(
870
+ self,
871
+ request: Optional[Union[spanner.BatchCreateSessionsRequest, dict]] = None,
872
+ *,
873
+ database: Optional[str] = None,
874
+ session_count: Optional[int] = None,
875
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
876
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
877
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
878
+ ) -> spanner.BatchCreateSessionsResponse:
879
+ r"""Creates multiple new sessions.
880
+
881
+ This API can be used to initialize a session cache on
882
+ the clients. See https://goo.gl/TgSFN2 for best
883
+ practices on session cache management.
884
+
885
+ .. code-block:: python
886
+
887
+ # This snippet has been automatically generated and should be regarded as a
888
+ # code template only.
889
+ # It will require modifications to work:
890
+ # - It may require correct/in-range values for request initialization.
891
+ # - It may require specifying regional endpoints when creating the service
892
+ # client as shown in:
893
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
894
+ from google.cloud import spanner_v1
895
+
896
+ def sample_batch_create_sessions():
897
+ # Create a client
898
+ client = spanner_v1.SpannerClient()
899
+
900
+ # Initialize request argument(s)
901
+ request = spanner_v1.BatchCreateSessionsRequest(
902
+ database="database_value",
903
+ session_count=1420,
904
+ )
905
+
906
+ # Make the request
907
+ response = client.batch_create_sessions(request=request)
908
+
909
+ # Handle the response
910
+ print(response)
911
+
912
+ Args:
913
+ request (Union[google.cloud.spanner_v1.types.BatchCreateSessionsRequest, dict]):
914
+ The request object. The request for
915
+ [BatchCreateSessions][google.spanner.v1.Spanner.BatchCreateSessions].
916
+ database (str):
917
+ Required. The database in which the
918
+ new sessions are created.
919
+
920
+ This corresponds to the ``database`` field
921
+ on the ``request`` instance; if ``request`` is provided, this
922
+ should not be set.
923
+ session_count (int):
924
+ Required. The number of sessions to be created in this
925
+ batch call. The API may return fewer than the requested
926
+ number of sessions. If a specific number of sessions are
927
+ desired, the client can make additional calls to
928
+ BatchCreateSessions (adjusting
929
+ [session_count][google.spanner.v1.BatchCreateSessionsRequest.session_count]
930
+ as necessary).
931
+
932
+ This corresponds to the ``session_count`` field
933
+ on the ``request`` instance; if ``request`` is provided, this
934
+ should not be set.
935
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
936
+ should be retried.
937
+ timeout (float): The timeout for this request.
938
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
939
+ sent along with the request as metadata. Normally, each value must be of type `str`,
940
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
941
+ be of type `bytes`.
942
+
943
+ Returns:
944
+ google.cloud.spanner_v1.types.BatchCreateSessionsResponse:
945
+ The response for
946
+ [BatchCreateSessions][google.spanner.v1.Spanner.BatchCreateSessions].
947
+
948
+ """
949
+ # Create or coerce a protobuf request object.
950
+ # - Quick check: If we got a request object, we should *not* have
951
+ # gotten any keyword arguments that map to the request.
952
+ flattened_params = [database, session_count]
953
+ has_flattened_params = (
954
+ len([param for param in flattened_params if param is not None]) > 0
955
+ )
956
+ if request is not None and has_flattened_params:
957
+ raise ValueError(
958
+ "If the `request` argument is set, then none of "
959
+ "the individual field arguments should be set."
960
+ )
961
+
962
+ # - Use the request object if provided (there's no risk of modifying the input as
963
+ # there are no flattened fields), or create one.
964
+ if not isinstance(request, spanner.BatchCreateSessionsRequest):
965
+ request = spanner.BatchCreateSessionsRequest(request)
966
+ # If we have keyword arguments corresponding to fields on the
967
+ # request, apply these.
968
+ if database is not None:
969
+ request.database = database
970
+ if session_count is not None:
971
+ request.session_count = session_count
972
+
973
+ # Wrap the RPC method; this adds retry and timeout information,
974
+ # and friendly error handling.
975
+ rpc = self._transport._wrapped_methods[self._transport.batch_create_sessions]
976
+
977
+ # Certain fields should be provided within the metadata header;
978
+ # add these here.
979
+ metadata = tuple(metadata) + (
980
+ gapic_v1.routing_header.to_grpc_metadata((("database", request.database),)),
981
+ )
982
+
983
+ # Validate the universe domain.
984
+ self._validate_universe_domain()
985
+
986
+ # Send the request.
987
+ response = rpc(
988
+ request,
989
+ retry=retry,
990
+ timeout=timeout,
991
+ metadata=metadata,
992
+ )
993
+
994
+ # Done; return the response.
995
+ return response
996
+
997
+ def get_session(
998
+ self,
999
+ request: Optional[Union[spanner.GetSessionRequest, dict]] = None,
1000
+ *,
1001
+ name: Optional[str] = None,
1002
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1003
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1004
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1005
+ ) -> spanner.Session:
1006
+ r"""Gets a session. Returns ``NOT_FOUND`` if the session does not
1007
+ exist. This is mainly useful for determining whether a session
1008
+ is still alive.
1009
+
1010
+ .. code-block:: python
1011
+
1012
+ # This snippet has been automatically generated and should be regarded as a
1013
+ # code template only.
1014
+ # It will require modifications to work:
1015
+ # - It may require correct/in-range values for request initialization.
1016
+ # - It may require specifying regional endpoints when creating the service
1017
+ # client as shown in:
1018
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1019
+ from google.cloud import spanner_v1
1020
+
1021
+ def sample_get_session():
1022
+ # Create a client
1023
+ client = spanner_v1.SpannerClient()
1024
+
1025
+ # Initialize request argument(s)
1026
+ request = spanner_v1.GetSessionRequest(
1027
+ name="name_value",
1028
+ )
1029
+
1030
+ # Make the request
1031
+ response = client.get_session(request=request)
1032
+
1033
+ # Handle the response
1034
+ print(response)
1035
+
1036
+ Args:
1037
+ request (Union[google.cloud.spanner_v1.types.GetSessionRequest, dict]):
1038
+ The request object. The request for
1039
+ [GetSession][google.spanner.v1.Spanner.GetSession].
1040
+ name (str):
1041
+ Required. The name of the session to
1042
+ retrieve.
1043
+
1044
+ This corresponds to the ``name`` field
1045
+ on the ``request`` instance; if ``request`` is provided, this
1046
+ should not be set.
1047
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1048
+ should be retried.
1049
+ timeout (float): The timeout for this request.
1050
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1051
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1052
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1053
+ be of type `bytes`.
1054
+
1055
+ Returns:
1056
+ google.cloud.spanner_v1.types.Session:
1057
+ A session in the Cloud Spanner API.
1058
+ """
1059
+ # Create or coerce a protobuf request object.
1060
+ # - Quick check: If we got a request object, we should *not* have
1061
+ # gotten any keyword arguments that map to the request.
1062
+ flattened_params = [name]
1063
+ has_flattened_params = (
1064
+ len([param for param in flattened_params if param is not None]) > 0
1065
+ )
1066
+ if request is not None and has_flattened_params:
1067
+ raise ValueError(
1068
+ "If the `request` argument is set, then none of "
1069
+ "the individual field arguments should be set."
1070
+ )
1071
+
1072
+ # - Use the request object if provided (there's no risk of modifying the input as
1073
+ # there are no flattened fields), or create one.
1074
+ if not isinstance(request, spanner.GetSessionRequest):
1075
+ request = spanner.GetSessionRequest(request)
1076
+ # If we have keyword arguments corresponding to fields on the
1077
+ # request, apply these.
1078
+ if name is not None:
1079
+ request.name = name
1080
+
1081
+ # Wrap the RPC method; this adds retry and timeout information,
1082
+ # and friendly error handling.
1083
+ rpc = self._transport._wrapped_methods[self._transport.get_session]
1084
+
1085
+ # Certain fields should be provided within the metadata header;
1086
+ # add these here.
1087
+ metadata = tuple(metadata) + (
1088
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1089
+ )
1090
+
1091
+ # Validate the universe domain.
1092
+ self._validate_universe_domain()
1093
+
1094
+ # Send the request.
1095
+ response = rpc(
1096
+ request,
1097
+ retry=retry,
1098
+ timeout=timeout,
1099
+ metadata=metadata,
1100
+ )
1101
+
1102
+ # Done; return the response.
1103
+ return response
1104
+
1105
+ def list_sessions(
1106
+ self,
1107
+ request: Optional[Union[spanner.ListSessionsRequest, dict]] = None,
1108
+ *,
1109
+ database: Optional[str] = None,
1110
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1111
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1112
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1113
+ ) -> pagers.ListSessionsPager:
1114
+ r"""Lists all sessions in a given database.
1115
+
1116
+ .. code-block:: python
1117
+
1118
+ # This snippet has been automatically generated and should be regarded as a
1119
+ # code template only.
1120
+ # It will require modifications to work:
1121
+ # - It may require correct/in-range values for request initialization.
1122
+ # - It may require specifying regional endpoints when creating the service
1123
+ # client as shown in:
1124
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1125
+ from google.cloud import spanner_v1
1126
+
1127
+ def sample_list_sessions():
1128
+ # Create a client
1129
+ client = spanner_v1.SpannerClient()
1130
+
1131
+ # Initialize request argument(s)
1132
+ request = spanner_v1.ListSessionsRequest(
1133
+ database="database_value",
1134
+ )
1135
+
1136
+ # Make the request
1137
+ page_result = client.list_sessions(request=request)
1138
+
1139
+ # Handle the response
1140
+ for response in page_result:
1141
+ print(response)
1142
+
1143
+ Args:
1144
+ request (Union[google.cloud.spanner_v1.types.ListSessionsRequest, dict]):
1145
+ The request object. The request for
1146
+ [ListSessions][google.spanner.v1.Spanner.ListSessions].
1147
+ database (str):
1148
+ Required. The database in which to
1149
+ list sessions.
1150
+
1151
+ This corresponds to the ``database`` field
1152
+ on the ``request`` instance; if ``request`` is provided, this
1153
+ should not be set.
1154
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1155
+ should be retried.
1156
+ timeout (float): The timeout for this request.
1157
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1158
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1159
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1160
+ be of type `bytes`.
1161
+
1162
+ Returns:
1163
+ google.cloud.spanner_v1.services.spanner.pagers.ListSessionsPager:
1164
+ The response for
1165
+ [ListSessions][google.spanner.v1.Spanner.ListSessions].
1166
+
1167
+ Iterating over this object will yield results and
1168
+ resolve additional pages automatically.
1169
+
1170
+ """
1171
+ # Create or coerce a protobuf request object.
1172
+ # - Quick check: If we got a request object, we should *not* have
1173
+ # gotten any keyword arguments that map to the request.
1174
+ flattened_params = [database]
1175
+ has_flattened_params = (
1176
+ len([param for param in flattened_params if param is not None]) > 0
1177
+ )
1178
+ if request is not None and has_flattened_params:
1179
+ raise ValueError(
1180
+ "If the `request` argument is set, then none of "
1181
+ "the individual field arguments should be set."
1182
+ )
1183
+
1184
+ # - Use the request object if provided (there's no risk of modifying the input as
1185
+ # there are no flattened fields), or create one.
1186
+ if not isinstance(request, spanner.ListSessionsRequest):
1187
+ request = spanner.ListSessionsRequest(request)
1188
+ # If we have keyword arguments corresponding to fields on the
1189
+ # request, apply these.
1190
+ if database is not None:
1191
+ request.database = database
1192
+
1193
+ # Wrap the RPC method; this adds retry and timeout information,
1194
+ # and friendly error handling.
1195
+ rpc = self._transport._wrapped_methods[self._transport.list_sessions]
1196
+
1197
+ # Certain fields should be provided within the metadata header;
1198
+ # add these here.
1199
+ metadata = tuple(metadata) + (
1200
+ gapic_v1.routing_header.to_grpc_metadata((("database", request.database),)),
1201
+ )
1202
+
1203
+ # Validate the universe domain.
1204
+ self._validate_universe_domain()
1205
+
1206
+ # Send the request.
1207
+ response = rpc(
1208
+ request,
1209
+ retry=retry,
1210
+ timeout=timeout,
1211
+ metadata=metadata,
1212
+ )
1213
+
1214
+ # This method is paged; wrap the response in a pager, which provides
1215
+ # an `__iter__` convenience method.
1216
+ response = pagers.ListSessionsPager(
1217
+ method=rpc,
1218
+ request=request,
1219
+ response=response,
1220
+ retry=retry,
1221
+ timeout=timeout,
1222
+ metadata=metadata,
1223
+ )
1224
+
1225
+ # Done; return the response.
1226
+ return response
1227
+
1228
+ def delete_session(
1229
+ self,
1230
+ request: Optional[Union[spanner.DeleteSessionRequest, dict]] = None,
1231
+ *,
1232
+ name: Optional[str] = None,
1233
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1234
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1235
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1236
+ ) -> None:
1237
+ r"""Ends a session, releasing server resources associated
1238
+ with it. This will asynchronously trigger cancellation
1239
+ of any operations that are running with this session.
1240
+
1241
+ .. code-block:: python
1242
+
1243
+ # This snippet has been automatically generated and should be regarded as a
1244
+ # code template only.
1245
+ # It will require modifications to work:
1246
+ # - It may require correct/in-range values for request initialization.
1247
+ # - It may require specifying regional endpoints when creating the service
1248
+ # client as shown in:
1249
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1250
+ from google.cloud import spanner_v1
1251
+
1252
+ def sample_delete_session():
1253
+ # Create a client
1254
+ client = spanner_v1.SpannerClient()
1255
+
1256
+ # Initialize request argument(s)
1257
+ request = spanner_v1.DeleteSessionRequest(
1258
+ name="name_value",
1259
+ )
1260
+
1261
+ # Make the request
1262
+ client.delete_session(request=request)
1263
+
1264
+ Args:
1265
+ request (Union[google.cloud.spanner_v1.types.DeleteSessionRequest, dict]):
1266
+ The request object. The request for
1267
+ [DeleteSession][google.spanner.v1.Spanner.DeleteSession].
1268
+ name (str):
1269
+ Required. The name of the session to
1270
+ delete.
1271
+
1272
+ This corresponds to the ``name`` field
1273
+ on the ``request`` instance; if ``request`` is provided, this
1274
+ should not be set.
1275
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1276
+ should be retried.
1277
+ timeout (float): The timeout for this request.
1278
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1279
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1280
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1281
+ be of type `bytes`.
1282
+ """
1283
+ # Create or coerce a protobuf request object.
1284
+ # - Quick check: If we got a request object, we should *not* have
1285
+ # gotten any keyword arguments that map to the request.
1286
+ flattened_params = [name]
1287
+ has_flattened_params = (
1288
+ len([param for param in flattened_params if param is not None]) > 0
1289
+ )
1290
+ if request is not None and has_flattened_params:
1291
+ raise ValueError(
1292
+ "If the `request` argument is set, then none of "
1293
+ "the individual field arguments should be set."
1294
+ )
1295
+
1296
+ # - Use the request object if provided (there's no risk of modifying the input as
1297
+ # there are no flattened fields), or create one.
1298
+ if not isinstance(request, spanner.DeleteSessionRequest):
1299
+ request = spanner.DeleteSessionRequest(request)
1300
+ # If we have keyword arguments corresponding to fields on the
1301
+ # request, apply these.
1302
+ if name is not None:
1303
+ request.name = name
1304
+
1305
+ # Wrap the RPC method; this adds retry and timeout information,
1306
+ # and friendly error handling.
1307
+ rpc = self._transport._wrapped_methods[self._transport.delete_session]
1308
+
1309
+ # Certain fields should be provided within the metadata header;
1310
+ # add these here.
1311
+ metadata = tuple(metadata) + (
1312
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1313
+ )
1314
+
1315
+ # Validate the universe domain.
1316
+ self._validate_universe_domain()
1317
+
1318
+ # Send the request.
1319
+ rpc(
1320
+ request,
1321
+ retry=retry,
1322
+ timeout=timeout,
1323
+ metadata=metadata,
1324
+ )
1325
+
1326
+ def execute_sql(
1327
+ self,
1328
+ request: Optional[Union[spanner.ExecuteSqlRequest, dict]] = None,
1329
+ *,
1330
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1331
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1332
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1333
+ ) -> result_set.ResultSet:
1334
+ r"""Executes an SQL statement, returning all results in a single
1335
+ reply. This method cannot be used to return a result set larger
1336
+ than 10 MiB; if the query yields more data than that, the query
1337
+ fails with a ``FAILED_PRECONDITION`` error.
1338
+
1339
+ Operations inside read-write transactions might return
1340
+ ``ABORTED``. If this occurs, the application should restart the
1341
+ transaction from the beginning. See
1342
+ [Transaction][google.spanner.v1.Transaction] for more details.
1343
+
1344
+ Larger result sets can be fetched in streaming fashion by
1345
+ calling
1346
+ [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql]
1347
+ instead.
1348
+
1349
+ .. code-block:: python
1350
+
1351
+ # This snippet has been automatically generated and should be regarded as a
1352
+ # code template only.
1353
+ # It will require modifications to work:
1354
+ # - It may require correct/in-range values for request initialization.
1355
+ # - It may require specifying regional endpoints when creating the service
1356
+ # client as shown in:
1357
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1358
+ from google.cloud import spanner_v1
1359
+
1360
+ def sample_execute_sql():
1361
+ # Create a client
1362
+ client = spanner_v1.SpannerClient()
1363
+
1364
+ # Initialize request argument(s)
1365
+ request = spanner_v1.ExecuteSqlRequest(
1366
+ session="session_value",
1367
+ sql="sql_value",
1368
+ )
1369
+
1370
+ # Make the request
1371
+ response = client.execute_sql(request=request)
1372
+
1373
+ # Handle the response
1374
+ print(response)
1375
+
1376
+ Args:
1377
+ request (Union[google.cloud.spanner_v1.types.ExecuteSqlRequest, dict]):
1378
+ The request object. The request for
1379
+ [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and
1380
+ [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql].
1381
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1382
+ should be retried.
1383
+ timeout (float): The timeout for this request.
1384
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1385
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1386
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1387
+ be of type `bytes`.
1388
+
1389
+ Returns:
1390
+ google.cloud.spanner_v1.types.ResultSet:
1391
+ Results from [Read][google.spanner.v1.Spanner.Read] or
1392
+ [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].
1393
+
1394
+ """
1395
+ # Create or coerce a protobuf request object.
1396
+ # - Use the request object if provided (there's no risk of modifying the input as
1397
+ # there are no flattened fields), or create one.
1398
+ if not isinstance(request, spanner.ExecuteSqlRequest):
1399
+ request = spanner.ExecuteSqlRequest(request)
1400
+
1401
+ # Wrap the RPC method; this adds retry and timeout information,
1402
+ # and friendly error handling.
1403
+ rpc = self._transport._wrapped_methods[self._transport.execute_sql]
1404
+
1405
+ # Certain fields should be provided within the metadata header;
1406
+ # add these here.
1407
+ metadata = tuple(metadata) + (
1408
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
1409
+ )
1410
+
1411
+ # Validate the universe domain.
1412
+ self._validate_universe_domain()
1413
+
1414
+ # Send the request.
1415
+ response = rpc(
1416
+ request,
1417
+ retry=retry,
1418
+ timeout=timeout,
1419
+ metadata=metadata,
1420
+ )
1421
+
1422
+ # Done; return the response.
1423
+ return response
1424
+
1425
+ def execute_streaming_sql(
1426
+ self,
1427
+ request: Optional[Union[spanner.ExecuteSqlRequest, dict]] = None,
1428
+ *,
1429
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1430
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1431
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1432
+ ) -> Iterable[result_set.PartialResultSet]:
1433
+ r"""Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except
1434
+ returns the result set as a stream. Unlike
1435
+ [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there is no
1436
+ limit on the size of the returned result set. However, no
1437
+ individual row in the result set can exceed 100 MiB, and no
1438
+ column value can exceed 10 MiB.
1439
+
1440
+ .. code-block:: python
1441
+
1442
+ # This snippet has been automatically generated and should be regarded as a
1443
+ # code template only.
1444
+ # It will require modifications to work:
1445
+ # - It may require correct/in-range values for request initialization.
1446
+ # - It may require specifying regional endpoints when creating the service
1447
+ # client as shown in:
1448
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1449
+ from google.cloud import spanner_v1
1450
+
1451
+ def sample_execute_streaming_sql():
1452
+ # Create a client
1453
+ client = spanner_v1.SpannerClient()
1454
+
1455
+ # Initialize request argument(s)
1456
+ request = spanner_v1.ExecuteSqlRequest(
1457
+ session="session_value",
1458
+ sql="sql_value",
1459
+ )
1460
+
1461
+ # Make the request
1462
+ stream = client.execute_streaming_sql(request=request)
1463
+
1464
+ # Handle the response
1465
+ for response in stream:
1466
+ print(response)
1467
+
1468
+ Args:
1469
+ request (Union[google.cloud.spanner_v1.types.ExecuteSqlRequest, dict]):
1470
+ The request object. The request for
1471
+ [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and
1472
+ [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql].
1473
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1474
+ should be retried.
1475
+ timeout (float): The timeout for this request.
1476
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1477
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1478
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1479
+ be of type `bytes`.
1480
+
1481
+ Returns:
1482
+ Iterable[google.cloud.spanner_v1.types.PartialResultSet]:
1483
+ Partial results from a streaming read
1484
+ or SQL query. Streaming reads and SQL
1485
+ queries better tolerate large result
1486
+ sets, large rows, and large values, but
1487
+ are a little trickier to consume.
1488
+
1489
+ """
1490
+ # Create or coerce a protobuf request object.
1491
+ # - Use the request object if provided (there's no risk of modifying the input as
1492
+ # there are no flattened fields), or create one.
1493
+ if not isinstance(request, spanner.ExecuteSqlRequest):
1494
+ request = spanner.ExecuteSqlRequest(request)
1495
+
1496
+ # Wrap the RPC method; this adds retry and timeout information,
1497
+ # and friendly error handling.
1498
+ rpc = self._transport._wrapped_methods[self._transport.execute_streaming_sql]
1499
+
1500
+ # Certain fields should be provided within the metadata header;
1501
+ # add these here.
1502
+ metadata = tuple(metadata) + (
1503
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
1504
+ )
1505
+
1506
+ # Validate the universe domain.
1507
+ self._validate_universe_domain()
1508
+
1509
+ # Send the request.
1510
+ response = rpc(
1511
+ request,
1512
+ retry=retry,
1513
+ timeout=timeout,
1514
+ metadata=metadata,
1515
+ )
1516
+
1517
+ # Done; return the response.
1518
+ return response
1519
+
1520
+ def execute_batch_dml(
1521
+ self,
1522
+ request: Optional[Union[spanner.ExecuteBatchDmlRequest, dict]] = None,
1523
+ *,
1524
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1525
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1526
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1527
+ ) -> spanner.ExecuteBatchDmlResponse:
1528
+ r"""Executes a batch of SQL DML statements. This method allows many
1529
+ statements to be run with lower latency than submitting them
1530
+ sequentially with
1531
+ [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].
1532
+
1533
+ Statements are executed in sequential order. A request can
1534
+ succeed even if a statement fails. The
1535
+ [ExecuteBatchDmlResponse.status][google.spanner.v1.ExecuteBatchDmlResponse.status]
1536
+ field in the response provides information about the statement
1537
+ that failed. Clients must inspect this field to determine
1538
+ whether an error occurred.
1539
+
1540
+ Execution stops after the first failed statement; the remaining
1541
+ statements are not executed.
1542
+
1543
+ .. code-block:: python
1544
+
1545
+ # This snippet has been automatically generated and should be regarded as a
1546
+ # code template only.
1547
+ # It will require modifications to work:
1548
+ # - It may require correct/in-range values for request initialization.
1549
+ # - It may require specifying regional endpoints when creating the service
1550
+ # client as shown in:
1551
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1552
+ from google.cloud import spanner_v1
1553
+
1554
+ def sample_execute_batch_dml():
1555
+ # Create a client
1556
+ client = spanner_v1.SpannerClient()
1557
+
1558
+ # Initialize request argument(s)
1559
+ statements = spanner_v1.Statement()
1560
+ statements.sql = "sql_value"
1561
+
1562
+ request = spanner_v1.ExecuteBatchDmlRequest(
1563
+ session="session_value",
1564
+ statements=statements,
1565
+ seqno=550,
1566
+ )
1567
+
1568
+ # Make the request
1569
+ response = client.execute_batch_dml(request=request)
1570
+
1571
+ # Handle the response
1572
+ print(response)
1573
+
1574
+ Args:
1575
+ request (Union[google.cloud.spanner_v1.types.ExecuteBatchDmlRequest, dict]):
1576
+ The request object. The request for
1577
+ [ExecuteBatchDml][google.spanner.v1.Spanner.ExecuteBatchDml].
1578
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1579
+ should be retried.
1580
+ timeout (float): The timeout for this request.
1581
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1582
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1583
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1584
+ be of type `bytes`.
1585
+
1586
+ Returns:
1587
+ google.cloud.spanner_v1.types.ExecuteBatchDmlResponse:
1588
+ The response for
1589
+ [ExecuteBatchDml][google.spanner.v1.Spanner.ExecuteBatchDml].
1590
+ Contains a list of
1591
+ [ResultSet][google.spanner.v1.ResultSet] messages,
1592
+ one for each DML statement that has successfully
1593
+ executed, in the same order as the statements in the
1594
+ request. If a statement fails, the status in the
1595
+ response body identifies the cause of the failure.
1596
+
1597
+ To check for DML statements that failed, use the
1598
+ following approach:
1599
+
1600
+ 1. Check the status in the response message. The
1601
+ [google.rpc.Code][google.rpc.Code] enum value OK
1602
+ indicates that all statements were executed
1603
+ successfully. 2. If the status was not OK, check the
1604
+ number of result sets in the response. If the
1605
+ response contains N
1606
+ [ResultSet][google.spanner.v1.ResultSet] messages,
1607
+ then statement N+1 in the request failed.
1608
+
1609
+ Example 1:
1610
+
1611
+ - Request: 5 DML statements, all executed
1612
+ successfully.
1613
+
1614
+ \* Response: 5
1615
+ [ResultSet][google.spanner.v1.ResultSet] messages,
1616
+ with the status OK.
1617
+
1618
+ Example 2:
1619
+
1620
+ - Request: 5 DML statements. The third statement has
1621
+ a syntax error.
1622
+
1623
+ \* Response: 2
1624
+ [ResultSet][google.spanner.v1.ResultSet] messages,
1625
+ and a syntax error (INVALID_ARGUMENT) status. The
1626
+ number of [ResultSet][google.spanner.v1.ResultSet]
1627
+ messages indicates that the third statement failed,
1628
+ and the fourth and fifth statements were not
1629
+ executed.
1630
+
1631
+ """
1632
+ # Create or coerce a protobuf request object.
1633
+ # - Use the request object if provided (there's no risk of modifying the input as
1634
+ # there are no flattened fields), or create one.
1635
+ if not isinstance(request, spanner.ExecuteBatchDmlRequest):
1636
+ request = spanner.ExecuteBatchDmlRequest(request)
1637
+
1638
+ # Wrap the RPC method; this adds retry and timeout information,
1639
+ # and friendly error handling.
1640
+ rpc = self._transport._wrapped_methods[self._transport.execute_batch_dml]
1641
+
1642
+ # Certain fields should be provided within the metadata header;
1643
+ # add these here.
1644
+ metadata = tuple(metadata) + (
1645
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
1646
+ )
1647
+
1648
+ # Validate the universe domain.
1649
+ self._validate_universe_domain()
1650
+
1651
+ # Send the request.
1652
+ response = rpc(
1653
+ request,
1654
+ retry=retry,
1655
+ timeout=timeout,
1656
+ metadata=metadata,
1657
+ )
1658
+
1659
+ # Done; return the response.
1660
+ return response
1661
+
1662
+ def read(
1663
+ self,
1664
+ request: Optional[Union[spanner.ReadRequest, dict]] = None,
1665
+ *,
1666
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1667
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1668
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1669
+ ) -> result_set.ResultSet:
1670
+ r"""Reads rows from the database using key lookups and scans, as a
1671
+ simple key/value style alternative to
1672
+ [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method
1673
+ cannot be used to return a result set larger than 10 MiB; if the
1674
+ read matches more data than that, the read fails with a
1675
+ ``FAILED_PRECONDITION`` error.
1676
+
1677
+ Reads inside read-write transactions might return ``ABORTED``.
1678
+ If this occurs, the application should restart the transaction
1679
+ from the beginning. See
1680
+ [Transaction][google.spanner.v1.Transaction] for more details.
1681
+
1682
+ Larger result sets can be yielded in streaming fashion by
1683
+ calling [StreamingRead][google.spanner.v1.Spanner.StreamingRead]
1684
+ instead.
1685
+
1686
+ .. code-block:: python
1687
+
1688
+ # This snippet has been automatically generated and should be regarded as a
1689
+ # code template only.
1690
+ # It will require modifications to work:
1691
+ # - It may require correct/in-range values for request initialization.
1692
+ # - It may require specifying regional endpoints when creating the service
1693
+ # client as shown in:
1694
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1695
+ from google.cloud import spanner_v1
1696
+
1697
+ def sample_read():
1698
+ # Create a client
1699
+ client = spanner_v1.SpannerClient()
1700
+
1701
+ # Initialize request argument(s)
1702
+ request = spanner_v1.ReadRequest(
1703
+ session="session_value",
1704
+ table="table_value",
1705
+ columns=['columns_value1', 'columns_value2'],
1706
+ )
1707
+
1708
+ # Make the request
1709
+ response = client.read(request=request)
1710
+
1711
+ # Handle the response
1712
+ print(response)
1713
+
1714
+ Args:
1715
+ request (Union[google.cloud.spanner_v1.types.ReadRequest, dict]):
1716
+ The request object. The request for [Read][google.spanner.v1.Spanner.Read]
1717
+ and
1718
+ [StreamingRead][google.spanner.v1.Spanner.StreamingRead].
1719
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1720
+ should be retried.
1721
+ timeout (float): The timeout for this request.
1722
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1723
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1724
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1725
+ be of type `bytes`.
1726
+
1727
+ Returns:
1728
+ google.cloud.spanner_v1.types.ResultSet:
1729
+ Results from [Read][google.spanner.v1.Spanner.Read] or
1730
+ [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql].
1731
+
1732
+ """
1733
+ # Create or coerce a protobuf request object.
1734
+ # - Use the request object if provided (there's no risk of modifying the input as
1735
+ # there are no flattened fields), or create one.
1736
+ if not isinstance(request, spanner.ReadRequest):
1737
+ request = spanner.ReadRequest(request)
1738
+
1739
+ # Wrap the RPC method; this adds retry and timeout information,
1740
+ # and friendly error handling.
1741
+ rpc = self._transport._wrapped_methods[self._transport.read]
1742
+
1743
+ # Certain fields should be provided within the metadata header;
1744
+ # add these here.
1745
+ metadata = tuple(metadata) + (
1746
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
1747
+ )
1748
+
1749
+ # Validate the universe domain.
1750
+ self._validate_universe_domain()
1751
+
1752
+ # Send the request.
1753
+ response = rpc(
1754
+ request,
1755
+ retry=retry,
1756
+ timeout=timeout,
1757
+ metadata=metadata,
1758
+ )
1759
+
1760
+ # Done; return the response.
1761
+ return response
1762
+
1763
+ def streaming_read(
1764
+ self,
1765
+ request: Optional[Union[spanner.ReadRequest, dict]] = None,
1766
+ *,
1767
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1768
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1769
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1770
+ ) -> Iterable[result_set.PartialResultSet]:
1771
+ r"""Like [Read][google.spanner.v1.Spanner.Read], except returns the
1772
+ result set as a stream. Unlike
1773
+ [Read][google.spanner.v1.Spanner.Read], there is no limit on the
1774
+ size of the returned result set. However, no individual row in
1775
+ the result set can exceed 100 MiB, and no column value can
1776
+ exceed 10 MiB.
1777
+
1778
+ .. code-block:: python
1779
+
1780
+ # This snippet has been automatically generated and should be regarded as a
1781
+ # code template only.
1782
+ # It will require modifications to work:
1783
+ # - It may require correct/in-range values for request initialization.
1784
+ # - It may require specifying regional endpoints when creating the service
1785
+ # client as shown in:
1786
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1787
+ from google.cloud import spanner_v1
1788
+
1789
+ def sample_streaming_read():
1790
+ # Create a client
1791
+ client = spanner_v1.SpannerClient()
1792
+
1793
+ # Initialize request argument(s)
1794
+ request = spanner_v1.ReadRequest(
1795
+ session="session_value",
1796
+ table="table_value",
1797
+ columns=['columns_value1', 'columns_value2'],
1798
+ )
1799
+
1800
+ # Make the request
1801
+ stream = client.streaming_read(request=request)
1802
+
1803
+ # Handle the response
1804
+ for response in stream:
1805
+ print(response)
1806
+
1807
+ Args:
1808
+ request (Union[google.cloud.spanner_v1.types.ReadRequest, dict]):
1809
+ The request object. The request for [Read][google.spanner.v1.Spanner.Read]
1810
+ and
1811
+ [StreamingRead][google.spanner.v1.Spanner.StreamingRead].
1812
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1813
+ should be retried.
1814
+ timeout (float): The timeout for this request.
1815
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1816
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1817
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1818
+ be of type `bytes`.
1819
+
1820
+ Returns:
1821
+ Iterable[google.cloud.spanner_v1.types.PartialResultSet]:
1822
+ Partial results from a streaming read
1823
+ or SQL query. Streaming reads and SQL
1824
+ queries better tolerate large result
1825
+ sets, large rows, and large values, but
1826
+ are a little trickier to consume.
1827
+
1828
+ """
1829
+ # Create or coerce a protobuf request object.
1830
+ # - Use the request object if provided (there's no risk of modifying the input as
1831
+ # there are no flattened fields), or create one.
1832
+ if not isinstance(request, spanner.ReadRequest):
1833
+ request = spanner.ReadRequest(request)
1834
+
1835
+ # Wrap the RPC method; this adds retry and timeout information,
1836
+ # and friendly error handling.
1837
+ rpc = self._transport._wrapped_methods[self._transport.streaming_read]
1838
+
1839
+ # Certain fields should be provided within the metadata header;
1840
+ # add these here.
1841
+ metadata = tuple(metadata) + (
1842
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
1843
+ )
1844
+
1845
+ # Validate the universe domain.
1846
+ self._validate_universe_domain()
1847
+
1848
+ # Send the request.
1849
+ response = rpc(
1850
+ request,
1851
+ retry=retry,
1852
+ timeout=timeout,
1853
+ metadata=metadata,
1854
+ )
1855
+
1856
+ # Done; return the response.
1857
+ return response
1858
+
1859
+ def begin_transaction(
1860
+ self,
1861
+ request: Optional[Union[spanner.BeginTransactionRequest, dict]] = None,
1862
+ *,
1863
+ session: Optional[str] = None,
1864
+ options: Optional[transaction.TransactionOptions] = None,
1865
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1866
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1867
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1868
+ ) -> transaction.Transaction:
1869
+ r"""Begins a new transaction. This step can often be skipped:
1870
+ [Read][google.spanner.v1.Spanner.Read],
1871
+ [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and
1872
+ [Commit][google.spanner.v1.Spanner.Commit] can begin a new
1873
+ transaction as a side-effect.
1874
+
1875
+ .. code-block:: python
1876
+
1877
+ # This snippet has been automatically generated and should be regarded as a
1878
+ # code template only.
1879
+ # It will require modifications to work:
1880
+ # - It may require correct/in-range values for request initialization.
1881
+ # - It may require specifying regional endpoints when creating the service
1882
+ # client as shown in:
1883
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
1884
+ from google.cloud import spanner_v1
1885
+
1886
+ def sample_begin_transaction():
1887
+ # Create a client
1888
+ client = spanner_v1.SpannerClient()
1889
+
1890
+ # Initialize request argument(s)
1891
+ request = spanner_v1.BeginTransactionRequest(
1892
+ session="session_value",
1893
+ )
1894
+
1895
+ # Make the request
1896
+ response = client.begin_transaction(request=request)
1897
+
1898
+ # Handle the response
1899
+ print(response)
1900
+
1901
+ Args:
1902
+ request (Union[google.cloud.spanner_v1.types.BeginTransactionRequest, dict]):
1903
+ The request object. The request for
1904
+ [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction].
1905
+ session (str):
1906
+ Required. The session in which the
1907
+ transaction runs.
1908
+
1909
+ This corresponds to the ``session`` field
1910
+ on the ``request`` instance; if ``request`` is provided, this
1911
+ should not be set.
1912
+ options (google.cloud.spanner_v1.types.TransactionOptions):
1913
+ Required. Options for the new
1914
+ transaction.
1915
+
1916
+ This corresponds to the ``options`` field
1917
+ on the ``request`` instance; if ``request`` is provided, this
1918
+ should not be set.
1919
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
1920
+ should be retried.
1921
+ timeout (float): The timeout for this request.
1922
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1923
+ sent along with the request as metadata. Normally, each value must be of type `str`,
1924
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
1925
+ be of type `bytes`.
1926
+
1927
+ Returns:
1928
+ google.cloud.spanner_v1.types.Transaction:
1929
+ A transaction.
1930
+ """
1931
+ # Create or coerce a protobuf request object.
1932
+ # - Quick check: If we got a request object, we should *not* have
1933
+ # gotten any keyword arguments that map to the request.
1934
+ flattened_params = [session, options]
1935
+ has_flattened_params = (
1936
+ len([param for param in flattened_params if param is not None]) > 0
1937
+ )
1938
+ if request is not None and has_flattened_params:
1939
+ raise ValueError(
1940
+ "If the `request` argument is set, then none of "
1941
+ "the individual field arguments should be set."
1942
+ )
1943
+
1944
+ # - Use the request object if provided (there's no risk of modifying the input as
1945
+ # there are no flattened fields), or create one.
1946
+ if not isinstance(request, spanner.BeginTransactionRequest):
1947
+ request = spanner.BeginTransactionRequest(request)
1948
+ # If we have keyword arguments corresponding to fields on the
1949
+ # request, apply these.
1950
+ if session is not None:
1951
+ request.session = session
1952
+ if options is not None:
1953
+ request.options = options
1954
+
1955
+ # Wrap the RPC method; this adds retry and timeout information,
1956
+ # and friendly error handling.
1957
+ rpc = self._transport._wrapped_methods[self._transport.begin_transaction]
1958
+
1959
+ # Certain fields should be provided within the metadata header;
1960
+ # add these here.
1961
+ metadata = tuple(metadata) + (
1962
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
1963
+ )
1964
+
1965
+ # Validate the universe domain.
1966
+ self._validate_universe_domain()
1967
+
1968
+ # Send the request.
1969
+ response = rpc(
1970
+ request,
1971
+ retry=retry,
1972
+ timeout=timeout,
1973
+ metadata=metadata,
1974
+ )
1975
+
1976
+ # Done; return the response.
1977
+ return response
1978
+
1979
+ def commit(
1980
+ self,
1981
+ request: Optional[Union[spanner.CommitRequest, dict]] = None,
1982
+ *,
1983
+ session: Optional[str] = None,
1984
+ transaction_id: Optional[bytes] = None,
1985
+ mutations: Optional[MutableSequence[mutation.Mutation]] = None,
1986
+ single_use_transaction: Optional[transaction.TransactionOptions] = None,
1987
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
1988
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1989
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1990
+ ) -> commit_response.CommitResponse:
1991
+ r"""Commits a transaction. The request includes the mutations to be
1992
+ applied to rows in the database.
1993
+
1994
+ ``Commit`` might return an ``ABORTED`` error. This can occur at
1995
+ any time; commonly, the cause is conflicts with concurrent
1996
+ transactions. However, it can also happen for a variety of other
1997
+ reasons. If ``Commit`` returns ``ABORTED``, the caller should
1998
+ re-attempt the transaction from the beginning, re-using the same
1999
+ session.
2000
+
2001
+ On very rare occasions, ``Commit`` might return ``UNKNOWN``.
2002
+ This can happen, for example, if the client job experiences a 1+
2003
+ hour networking failure. At that point, Cloud Spanner has lost
2004
+ track of the transaction outcome and we recommend that you
2005
+ perform another read from the database to see the state of
2006
+ things as they are now.
2007
+
2008
+ .. code-block:: python
2009
+
2010
+ # This snippet has been automatically generated and should be regarded as a
2011
+ # code template only.
2012
+ # It will require modifications to work:
2013
+ # - It may require correct/in-range values for request initialization.
2014
+ # - It may require specifying regional endpoints when creating the service
2015
+ # client as shown in:
2016
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
2017
+ from google.cloud import spanner_v1
2018
+
2019
+ def sample_commit():
2020
+ # Create a client
2021
+ client = spanner_v1.SpannerClient()
2022
+
2023
+ # Initialize request argument(s)
2024
+ request = spanner_v1.CommitRequest(
2025
+ transaction_id=b'transaction_id_blob',
2026
+ session="session_value",
2027
+ )
2028
+
2029
+ # Make the request
2030
+ response = client.commit(request=request)
2031
+
2032
+ # Handle the response
2033
+ print(response)
2034
+
2035
+ Args:
2036
+ request (Union[google.cloud.spanner_v1.types.CommitRequest, dict]):
2037
+ The request object. The request for
2038
+ [Commit][google.spanner.v1.Spanner.Commit].
2039
+ session (str):
2040
+ Required. The session in which the
2041
+ transaction to be committed is running.
2042
+
2043
+ This corresponds to the ``session`` field
2044
+ on the ``request`` instance; if ``request`` is provided, this
2045
+ should not be set.
2046
+ transaction_id (bytes):
2047
+ Commit a previously-started
2048
+ transaction.
2049
+
2050
+ This corresponds to the ``transaction_id`` field
2051
+ on the ``request`` instance; if ``request`` is provided, this
2052
+ should not be set.
2053
+ mutations (MutableSequence[google.cloud.spanner_v1.types.Mutation]):
2054
+ The mutations to be executed when
2055
+ this transaction commits. All mutations
2056
+ are applied atomically, in the order
2057
+ they appear in this list.
2058
+
2059
+ This corresponds to the ``mutations`` field
2060
+ on the ``request`` instance; if ``request`` is provided, this
2061
+ should not be set.
2062
+ single_use_transaction (google.cloud.spanner_v1.types.TransactionOptions):
2063
+ Execute mutations in a temporary transaction. Note that
2064
+ unlike commit of a previously-started transaction,
2065
+ commit with a temporary transaction is non-idempotent.
2066
+ That is, if the ``CommitRequest`` is sent to Cloud
2067
+ Spanner more than once (for instance, due to retries in
2068
+ the application, or in the transport library), it is
2069
+ possible that the mutations are executed more than once.
2070
+ If this is undesirable, use
2071
+ [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction]
2072
+ and [Commit][google.spanner.v1.Spanner.Commit] instead.
2073
+
2074
+ This corresponds to the ``single_use_transaction`` field
2075
+ on the ``request`` instance; if ``request`` is provided, this
2076
+ should not be set.
2077
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
2078
+ should be retried.
2079
+ timeout (float): The timeout for this request.
2080
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2081
+ sent along with the request as metadata. Normally, each value must be of type `str`,
2082
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
2083
+ be of type `bytes`.
2084
+
2085
+ Returns:
2086
+ google.cloud.spanner_v1.types.CommitResponse:
2087
+ The response for
2088
+ [Commit][google.spanner.v1.Spanner.Commit].
2089
+
2090
+ """
2091
+ # Create or coerce a protobuf request object.
2092
+ # - Quick check: If we got a request object, we should *not* have
2093
+ # gotten any keyword arguments that map to the request.
2094
+ flattened_params = [session, transaction_id, mutations, single_use_transaction]
2095
+ has_flattened_params = (
2096
+ len([param for param in flattened_params if param is not None]) > 0
2097
+ )
2098
+ if request is not None and has_flattened_params:
2099
+ raise ValueError(
2100
+ "If the `request` argument is set, then none of "
2101
+ "the individual field arguments should be set."
2102
+ )
2103
+
2104
+ # - Use the request object if provided (there's no risk of modifying the input as
2105
+ # there are no flattened fields), or create one.
2106
+ if not isinstance(request, spanner.CommitRequest):
2107
+ request = spanner.CommitRequest(request)
2108
+ # If we have keyword arguments corresponding to fields on the
2109
+ # request, apply these.
2110
+ if session is not None:
2111
+ request.session = session
2112
+ if transaction_id is not None:
2113
+ request.transaction_id = transaction_id
2114
+ if mutations is not None:
2115
+ request.mutations = mutations
2116
+ if single_use_transaction is not None:
2117
+ request.single_use_transaction = single_use_transaction
2118
+
2119
+ # Wrap the RPC method; this adds retry and timeout information,
2120
+ # and friendly error handling.
2121
+ rpc = self._transport._wrapped_methods[self._transport.commit]
2122
+
2123
+ # Certain fields should be provided within the metadata header;
2124
+ # add these here.
2125
+ metadata = tuple(metadata) + (
2126
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
2127
+ )
2128
+
2129
+ # Validate the universe domain.
2130
+ self._validate_universe_domain()
2131
+
2132
+ # Send the request.
2133
+ response = rpc(
2134
+ request,
2135
+ retry=retry,
2136
+ timeout=timeout,
2137
+ metadata=metadata,
2138
+ )
2139
+
2140
+ # Done; return the response.
2141
+ return response
2142
+
2143
+ def rollback(
2144
+ self,
2145
+ request: Optional[Union[spanner.RollbackRequest, dict]] = None,
2146
+ *,
2147
+ session: Optional[str] = None,
2148
+ transaction_id: Optional[bytes] = None,
2149
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
2150
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2151
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2152
+ ) -> None:
2153
+ r"""Rolls back a transaction, releasing any locks it holds. It is a
2154
+ good idea to call this for any transaction that includes one or
2155
+ more [Read][google.spanner.v1.Spanner.Read] or
2156
+ [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and
2157
+ ultimately decides not to commit.
2158
+
2159
+ ``Rollback`` returns ``OK`` if it successfully aborts the
2160
+ transaction, the transaction was already aborted, or the
2161
+ transaction is not found. ``Rollback`` never returns
2162
+ ``ABORTED``.
2163
+
2164
+ .. code-block:: python
2165
+
2166
+ # This snippet has been automatically generated and should be regarded as a
2167
+ # code template only.
2168
+ # It will require modifications to work:
2169
+ # - It may require correct/in-range values for request initialization.
2170
+ # - It may require specifying regional endpoints when creating the service
2171
+ # client as shown in:
2172
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
2173
+ from google.cloud import spanner_v1
2174
+
2175
+ def sample_rollback():
2176
+ # Create a client
2177
+ client = spanner_v1.SpannerClient()
2178
+
2179
+ # Initialize request argument(s)
2180
+ request = spanner_v1.RollbackRequest(
2181
+ session="session_value",
2182
+ transaction_id=b'transaction_id_blob',
2183
+ )
2184
+
2185
+ # Make the request
2186
+ client.rollback(request=request)
2187
+
2188
+ Args:
2189
+ request (Union[google.cloud.spanner_v1.types.RollbackRequest, dict]):
2190
+ The request object. The request for
2191
+ [Rollback][google.spanner.v1.Spanner.Rollback].
2192
+ session (str):
2193
+ Required. The session in which the
2194
+ transaction to roll back is running.
2195
+
2196
+ This corresponds to the ``session`` field
2197
+ on the ``request`` instance; if ``request`` is provided, this
2198
+ should not be set.
2199
+ transaction_id (bytes):
2200
+ Required. The transaction to roll
2201
+ back.
2202
+
2203
+ This corresponds to the ``transaction_id`` field
2204
+ on the ``request`` instance; if ``request`` is provided, this
2205
+ should not be set.
2206
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
2207
+ should be retried.
2208
+ timeout (float): The timeout for this request.
2209
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2210
+ sent along with the request as metadata. Normally, each value must be of type `str`,
2211
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
2212
+ be of type `bytes`.
2213
+ """
2214
+ # Create or coerce a protobuf request object.
2215
+ # - Quick check: If we got a request object, we should *not* have
2216
+ # gotten any keyword arguments that map to the request.
2217
+ flattened_params = [session, transaction_id]
2218
+ has_flattened_params = (
2219
+ len([param for param in flattened_params if param is not None]) > 0
2220
+ )
2221
+ if request is not None and has_flattened_params:
2222
+ raise ValueError(
2223
+ "If the `request` argument is set, then none of "
2224
+ "the individual field arguments should be set."
2225
+ )
2226
+
2227
+ # - Use the request object if provided (there's no risk of modifying the input as
2228
+ # there are no flattened fields), or create one.
2229
+ if not isinstance(request, spanner.RollbackRequest):
2230
+ request = spanner.RollbackRequest(request)
2231
+ # If we have keyword arguments corresponding to fields on the
2232
+ # request, apply these.
2233
+ if session is not None:
2234
+ request.session = session
2235
+ if transaction_id is not None:
2236
+ request.transaction_id = transaction_id
2237
+
2238
+ # Wrap the RPC method; this adds retry and timeout information,
2239
+ # and friendly error handling.
2240
+ rpc = self._transport._wrapped_methods[self._transport.rollback]
2241
+
2242
+ # Certain fields should be provided within the metadata header;
2243
+ # add these here.
2244
+ metadata = tuple(metadata) + (
2245
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
2246
+ )
2247
+
2248
+ # Validate the universe domain.
2249
+ self._validate_universe_domain()
2250
+
2251
+ # Send the request.
2252
+ rpc(
2253
+ request,
2254
+ retry=retry,
2255
+ timeout=timeout,
2256
+ metadata=metadata,
2257
+ )
2258
+
2259
+ def partition_query(
2260
+ self,
2261
+ request: Optional[Union[spanner.PartitionQueryRequest, dict]] = None,
2262
+ *,
2263
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
2264
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2265
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2266
+ ) -> spanner.PartitionResponse:
2267
+ r"""Creates a set of partition tokens that can be used to execute a
2268
+ query operation in parallel. Each of the returned partition
2269
+ tokens can be used by
2270
+ [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql]
2271
+ to specify a subset of the query result to read. The same
2272
+ session and read-only transaction must be used by the
2273
+ PartitionQueryRequest used to create the partition tokens and
2274
+ the ExecuteSqlRequests that use the partition tokens.
2275
+
2276
+ Partition tokens become invalid when the session used to create
2277
+ them is deleted, is idle for too long, begins a new transaction,
2278
+ or becomes too old. When any of these happen, it is not possible
2279
+ to resume the query, and the whole operation must be restarted
2280
+ from the beginning.
2281
+
2282
+ .. code-block:: python
2283
+
2284
+ # This snippet has been automatically generated and should be regarded as a
2285
+ # code template only.
2286
+ # It will require modifications to work:
2287
+ # - It may require correct/in-range values for request initialization.
2288
+ # - It may require specifying regional endpoints when creating the service
2289
+ # client as shown in:
2290
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
2291
+ from google.cloud import spanner_v1
2292
+
2293
+ def sample_partition_query():
2294
+ # Create a client
2295
+ client = spanner_v1.SpannerClient()
2296
+
2297
+ # Initialize request argument(s)
2298
+ request = spanner_v1.PartitionQueryRequest(
2299
+ session="session_value",
2300
+ sql="sql_value",
2301
+ )
2302
+
2303
+ # Make the request
2304
+ response = client.partition_query(request=request)
2305
+
2306
+ # Handle the response
2307
+ print(response)
2308
+
2309
+ Args:
2310
+ request (Union[google.cloud.spanner_v1.types.PartitionQueryRequest, dict]):
2311
+ The request object. The request for
2312
+ [PartitionQuery][google.spanner.v1.Spanner.PartitionQuery]
2313
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
2314
+ should be retried.
2315
+ timeout (float): The timeout for this request.
2316
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2317
+ sent along with the request as metadata. Normally, each value must be of type `str`,
2318
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
2319
+ be of type `bytes`.
2320
+
2321
+ Returns:
2322
+ google.cloud.spanner_v1.types.PartitionResponse:
2323
+ The response for [PartitionQuery][google.spanner.v1.Spanner.PartitionQuery]
2324
+ or
2325
+ [PartitionRead][google.spanner.v1.Spanner.PartitionRead]
2326
+
2327
+ """
2328
+ # Create or coerce a protobuf request object.
2329
+ # - Use the request object if provided (there's no risk of modifying the input as
2330
+ # there are no flattened fields), or create one.
2331
+ if not isinstance(request, spanner.PartitionQueryRequest):
2332
+ request = spanner.PartitionQueryRequest(request)
2333
+
2334
+ # Wrap the RPC method; this adds retry and timeout information,
2335
+ # and friendly error handling.
2336
+ rpc = self._transport._wrapped_methods[self._transport.partition_query]
2337
+
2338
+ # Certain fields should be provided within the metadata header;
2339
+ # add these here.
2340
+ metadata = tuple(metadata) + (
2341
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
2342
+ )
2343
+
2344
+ # Validate the universe domain.
2345
+ self._validate_universe_domain()
2346
+
2347
+ # Send the request.
2348
+ response = rpc(
2349
+ request,
2350
+ retry=retry,
2351
+ timeout=timeout,
2352
+ metadata=metadata,
2353
+ )
2354
+
2355
+ # Done; return the response.
2356
+ return response
2357
+
2358
+ def partition_read(
2359
+ self,
2360
+ request: Optional[Union[spanner.PartitionReadRequest, dict]] = None,
2361
+ *,
2362
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
2363
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2364
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2365
+ ) -> spanner.PartitionResponse:
2366
+ r"""Creates a set of partition tokens that can be used to execute a
2367
+ read operation in parallel. Each of the returned partition
2368
+ tokens can be used by
2369
+ [StreamingRead][google.spanner.v1.Spanner.StreamingRead] to
2370
+ specify a subset of the read result to read. The same session
2371
+ and read-only transaction must be used by the
2372
+ PartitionReadRequest used to create the partition tokens and the
2373
+ ReadRequests that use the partition tokens. There are no
2374
+ ordering guarantees on rows returned among the returned
2375
+ partition tokens, or even within each individual StreamingRead
2376
+ call issued with a partition_token.
2377
+
2378
+ Partition tokens become invalid when the session used to create
2379
+ them is deleted, is idle for too long, begins a new transaction,
2380
+ or becomes too old. When any of these happen, it is not possible
2381
+ to resume the read, and the whole operation must be restarted
2382
+ from the beginning.
2383
+
2384
+ .. code-block:: python
2385
+
2386
+ # This snippet has been automatically generated and should be regarded as a
2387
+ # code template only.
2388
+ # It will require modifications to work:
2389
+ # - It may require correct/in-range values for request initialization.
2390
+ # - It may require specifying regional endpoints when creating the service
2391
+ # client as shown in:
2392
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
2393
+ from google.cloud import spanner_v1
2394
+
2395
+ def sample_partition_read():
2396
+ # Create a client
2397
+ client = spanner_v1.SpannerClient()
2398
+
2399
+ # Initialize request argument(s)
2400
+ request = spanner_v1.PartitionReadRequest(
2401
+ session="session_value",
2402
+ table="table_value",
2403
+ )
2404
+
2405
+ # Make the request
2406
+ response = client.partition_read(request=request)
2407
+
2408
+ # Handle the response
2409
+ print(response)
2410
+
2411
+ Args:
2412
+ request (Union[google.cloud.spanner_v1.types.PartitionReadRequest, dict]):
2413
+ The request object. The request for
2414
+ [PartitionRead][google.spanner.v1.Spanner.PartitionRead]
2415
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
2416
+ should be retried.
2417
+ timeout (float): The timeout for this request.
2418
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2419
+ sent along with the request as metadata. Normally, each value must be of type `str`,
2420
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
2421
+ be of type `bytes`.
2422
+
2423
+ Returns:
2424
+ google.cloud.spanner_v1.types.PartitionResponse:
2425
+ The response for [PartitionQuery][google.spanner.v1.Spanner.PartitionQuery]
2426
+ or
2427
+ [PartitionRead][google.spanner.v1.Spanner.PartitionRead]
2428
+
2429
+ """
2430
+ # Create or coerce a protobuf request object.
2431
+ # - Use the request object if provided (there's no risk of modifying the input as
2432
+ # there are no flattened fields), or create one.
2433
+ if not isinstance(request, spanner.PartitionReadRequest):
2434
+ request = spanner.PartitionReadRequest(request)
2435
+
2436
+ # Wrap the RPC method; this adds retry and timeout information,
2437
+ # and friendly error handling.
2438
+ rpc = self._transport._wrapped_methods[self._transport.partition_read]
2439
+
2440
+ # Certain fields should be provided within the metadata header;
2441
+ # add these here.
2442
+ metadata = tuple(metadata) + (
2443
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
2444
+ )
2445
+
2446
+ # Validate the universe domain.
2447
+ self._validate_universe_domain()
2448
+
2449
+ # Send the request.
2450
+ response = rpc(
2451
+ request,
2452
+ retry=retry,
2453
+ timeout=timeout,
2454
+ metadata=metadata,
2455
+ )
2456
+
2457
+ # Done; return the response.
2458
+ return response
2459
+
2460
+ def batch_write(
2461
+ self,
2462
+ request: Optional[Union[spanner.BatchWriteRequest, dict]] = None,
2463
+ *,
2464
+ session: Optional[str] = None,
2465
+ mutation_groups: Optional[
2466
+ MutableSequence[spanner.BatchWriteRequest.MutationGroup]
2467
+ ] = None,
2468
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
2469
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2470
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2471
+ ) -> Iterable[spanner.BatchWriteResponse]:
2472
+ r"""Batches the supplied mutation groups in a collection
2473
+ of efficient transactions. All mutations in a group are
2474
+ committed atomically. However, mutations across groups
2475
+ can be committed non-atomically in an unspecified order
2476
+ and thus, they must be independent of each other.
2477
+ Partial failure is possible, i.e., some groups may have
2478
+ been committed successfully, while some may have failed.
2479
+ The results of individual batches are streamed into the
2480
+ response as the batches are applied.
2481
+
2482
+ BatchWrite requests are not replay protected, meaning
2483
+ that each mutation group may be applied more than once.
2484
+ Replays of non-idempotent mutations may have undesirable
2485
+ effects. For example, replays of an insert mutation may
2486
+ produce an already exists error or if you use generated
2487
+ or commit timestamp-based keys, it may result in
2488
+ additional rows being added to the mutation's table. We
2489
+ recommend structuring your mutation groups to be
2490
+ idempotent to avoid this issue.
2491
+
2492
+ .. code-block:: python
2493
+
2494
+ # This snippet has been automatically generated and should be regarded as a
2495
+ # code template only.
2496
+ # It will require modifications to work:
2497
+ # - It may require correct/in-range values for request initialization.
2498
+ # - It may require specifying regional endpoints when creating the service
2499
+ # client as shown in:
2500
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
2501
+ from google.cloud import spanner_v1
2502
+
2503
+ def sample_batch_write():
2504
+ # Create a client
2505
+ client = spanner_v1.SpannerClient()
2506
+
2507
+ # Initialize request argument(s)
2508
+ mutation_groups = spanner_v1.MutationGroup()
2509
+ mutation_groups.mutations.insert.table = "table_value"
2510
+
2511
+ request = spanner_v1.BatchWriteRequest(
2512
+ session="session_value",
2513
+ mutation_groups=mutation_groups,
2514
+ )
2515
+
2516
+ # Make the request
2517
+ stream = client.batch_write(request=request)
2518
+
2519
+ # Handle the response
2520
+ for response in stream:
2521
+ print(response)
2522
+
2523
+ Args:
2524
+ request (Union[google.cloud.spanner_v1.types.BatchWriteRequest, dict]):
2525
+ The request object. The request for
2526
+ [BatchWrite][google.spanner.v1.Spanner.BatchWrite].
2527
+ session (str):
2528
+ Required. The session in which the
2529
+ batch request is to be run.
2530
+
2531
+ This corresponds to the ``session`` field
2532
+ on the ``request`` instance; if ``request`` is provided, this
2533
+ should not be set.
2534
+ mutation_groups (MutableSequence[google.cloud.spanner_v1.types.BatchWriteRequest.MutationGroup]):
2535
+ Required. The groups of mutations to
2536
+ be applied.
2537
+
2538
+ This corresponds to the ``mutation_groups`` field
2539
+ on the ``request`` instance; if ``request`` is provided, this
2540
+ should not be set.
2541
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
2542
+ should be retried.
2543
+ timeout (float): The timeout for this request.
2544
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2545
+ sent along with the request as metadata. Normally, each value must be of type `str`,
2546
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
2547
+ be of type `bytes`.
2548
+
2549
+ Returns:
2550
+ Iterable[google.cloud.spanner_v1.types.BatchWriteResponse]:
2551
+ The result of applying a batch of
2552
+ mutations.
2553
+
2554
+ """
2555
+ # Create or coerce a protobuf request object.
2556
+ # - Quick check: If we got a request object, we should *not* have
2557
+ # gotten any keyword arguments that map to the request.
2558
+ flattened_params = [session, mutation_groups]
2559
+ has_flattened_params = (
2560
+ len([param for param in flattened_params if param is not None]) > 0
2561
+ )
2562
+ if request is not None and has_flattened_params:
2563
+ raise ValueError(
2564
+ "If the `request` argument is set, then none of "
2565
+ "the individual field arguments should be set."
2566
+ )
2567
+
2568
+ # - Use the request object if provided (there's no risk of modifying the input as
2569
+ # there are no flattened fields), or create one.
2570
+ if not isinstance(request, spanner.BatchWriteRequest):
2571
+ request = spanner.BatchWriteRequest(request)
2572
+ # If we have keyword arguments corresponding to fields on the
2573
+ # request, apply these.
2574
+ if session is not None:
2575
+ request.session = session
2576
+ if mutation_groups is not None:
2577
+ request.mutation_groups = mutation_groups
2578
+
2579
+ # Wrap the RPC method; this adds retry and timeout information,
2580
+ # and friendly error handling.
2581
+ rpc = self._transport._wrapped_methods[self._transport.batch_write]
2582
+
2583
+ # Certain fields should be provided within the metadata header;
2584
+ # add these here.
2585
+ metadata = tuple(metadata) + (
2586
+ gapic_v1.routing_header.to_grpc_metadata((("session", request.session),)),
2587
+ )
2588
+
2589
+ # Validate the universe domain.
2590
+ self._validate_universe_domain()
2591
+
2592
+ # Send the request.
2593
+ response = rpc(
2594
+ request,
2595
+ retry=retry,
2596
+ timeout=timeout,
2597
+ metadata=metadata,
2598
+ )
2599
+
2600
+ # Done; return the response.
2601
+ return response
2602
+
2603
+ def __enter__(self) -> "SpannerClient":
2604
+ return self
2605
+
2606
+ def __exit__(self, type, value, traceback):
2607
+ """Releases underlying transport's resources.
2608
+
2609
+ .. warning::
2610
+ ONLY use as a context manager if the transport is NOT shared
2611
+ with other clients! Exiting the with block will CLOSE the transport
2612
+ and may cause errors in other clients!
2613
+ """
2614
+ self.transport.close()
2615
+
2616
+
2617
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
2618
+ gapic_version=package_version.__version__
2619
+ )
2620
+
2621
+ if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
2622
+ DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
2623
+
2624
+ __all__ = ("SpannerClient",)