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