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