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