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