o
    ˷e<                     @   s   d Z ddlmZ ddlmZ ddlmZmZmZm	Z	m
Z
 ddlmZ ddlmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z% e%rhddl&m'Z' G dd deZ(dS )a  Client for interacting with the Google Cloud Firestore API.

This is the base from which all interactions with the API occur.

In the hierarchy of API concepts

* a :class:`~google.cloud.firestore_v1.client.Client` owns a
  :class:`~google.cloud.firestore_v1.async_collection.AsyncCollectionReference`
* a :class:`~google.cloud.firestore_v1.client.Client` owns a
  :class:`~google.cloud.firestore_v1.async_document.AsyncDocumentReference`
    )gapic_v1)retry)
BaseClientDEFAULT_DATABASE_CLIENT_INFO_parse_batch_get_path_helper)AsyncCollectionGroupAsyncWriteBatch)AsyncCollectionReference)AsyncDocumentReferenceDocumentSnapshotAsyncTransaction)	FieldPath)async_client)grpc_asyncio)AnyAsyncGeneratorIterableListOptionalUnionTYPE_CHECKING)
BulkWriterc                       sn  e Zd ZdZddeedf	d. fddZdd Zedd	 Z	ed
d Z
dedefddZdedefddZdedefddZddejjdfdee dee dejdedeeef f
ddZejjdfdejdedeeef fddZddddeeef d e d! d"e e! fd#d$Z"dd%d&deeef d d!d"e e! d'e e! de!f
d(d)Z#de$fd*d+Z%de&fd,d-Z'  Z(S )/AsyncClienta:  Client for interacting with Google Cloud Firestore API.

    .. note::

        Since the Cloud Firestore API requires the gRPC transport, no
        ``_http`` argument is accepted by this class.

    Args:
        project (Optional[str]): The project which the client acts on behalf
            of. If not passed, falls back to the default inferred
            from the environment.
        credentials (Optional[~google.auth.credentials.Credentials]): The
            OAuth2 Credentials to use for this client. If not passed, falls
            back to the default inferred from the environment.
        database (Optional[str]): The database name that the client targets.
            For now, :attr:`DEFAULT_DATABASE` (the default value) is the
            only valid database.
        client_info (Optional[google.api_core.gapic_v1.client_info.ClientInfo]):
            The client info used to send a user-agent string along with API
            requests. If ``None``, then default info will be used. Generally,
            you only need to set this if you're developing your own library
            or partner tool.
        client_options (Union[dict, google.api_core.client_options.ClientOptions]):
            Client options used to set user options on the client. API Endpoint
            should be set through client_options.
    Nreturnc                    s   t t| j|||||d d S )Nprojectcredentialsdatabaseclient_infoclient_options)superr   __init__)selfr   r    r!   r"   r#   	__class__ ]/var/www/ideatree/venv/lib/python3.10/site-packages/google/cloud/firestore_v1/async_client.pyr%   W   s   

zAsyncClient.__init__c                 C   s<   ddl m} t| dd s|| j| j| j| j| jd| _| jS )Nr   )Client
_sync_copyr   )	 google.cloud.firestore_v1.clientr+   getattrr   _credentials	_database_client_info_client_optionsr,   )r&   r+   r)   r)   r*   _to_sync_copyg   s   zAsyncClient._to_sync_copyc                 C   s   |  tjtjtS )zLazy-loading getter GAPIC Firestore API.
        Returns:
            :class:`~google.cloud.gapic.firestore.v1`.async_firestore_client.FirestoreAsyncClient:
            The GAPIC client with the credentials of the current client.
        )_firestore_api_helperfirestore_grpc_transportFirestoreGrpcAsyncIOTransportfirestore_clientFirestoreAsyncClientr&   r)   r)   r*   _firestore_apit   s
   zAsyncClient._firestore_apic                 C   s   |  tjS )zReturn the target (where the API is).
        Eg. "firestore.googleapis.com"

        Returns:
            str: The location of the API.
        )_target_helperr7   r8   r9   r)   r)   r*   _target   s   zAsyncClient._targetcollection_pathc                 G   s   t t|d| iS )a  Get a reference to a collection.

        For a top-level collection:

        .. code-block:: python

            >>> client.collection('top')

        For a sub-collection:

        .. code-block:: python

            >>> client.collection('mydocs/doc/subcol')
            >>> # is the same as
            >>> client.collection('mydocs', 'doc', 'subcol')

        Sub-collections can be nested deeper in a similar fashion.

        Args:
            collection_path: Can either be

                * A single ``/``-delimited path to a collection
                * A tuple of collection path segments

        Returns:
            :class:`~google.cloud.firestore_v1.async_collection.AsyncCollectionReference`:
            A reference to a collection in the Firestore database.
        client)r   r   )r&   r=   r)   r)   r*   
collection   s   zAsyncClient.collectioncollection_idc                 C   s   t | |S )a  
        Creates and returns a new AsyncQuery that includes all documents in the
        database that are contained in a collection or subcollection with the
        given collection_id.

        .. code-block:: python

            >>> query = client.collection_group('mygroup')

        Args:
            collection_id (str) Identifies the collections to query over.

                Every collection or subcollection with this ID as the last segment of its
                path will be included. Cannot contain a slash.

        Returns:
            :class:`~google.cloud.firestore_v1.async_query.AsyncCollectionGroup`:
            The created AsyncQuery.
        )r	   _get_collection_reference)r&   r@   r)   r)   r*   collection_group   s   zAsyncClient.collection_groupdocument_pathc                 G   s   t | j| d| iS )a  Get a reference to a document in a collection.

        For a top-level document:

        .. code-block:: python

            >>> client.document('collek/shun')
            >>> # is the same as
            >>> client.document('collek', 'shun')

        For a document in a sub-collection:

        .. code-block:: python

            >>> client.document('mydocs/doc/subcol/child')
            >>> # is the same as
            >>> client.document('mydocs', 'doc', 'subcol', 'child')

        Documents in sub-collections can be nested deeper in a similar fashion.

        Args:
            document_path: Can either be

                * A single ``/``-delimited path to a document
                * A tuple of document path segments

        Returns:
            :class:`~google.cloud.firestore_v1.document.AsyncDocumentReference`:
            A reference to a document in a collection.
        r>   )r   _document_path_helper)r&   rC   r)   r)   r*   document   s
   zAsyncClient.document
referencesfield_pathsr   timeoutc                 C  s`   |  |||||\}}}| jjd|| jd|I dH }	|	2 z3 dH W }
t|
|| V  q6 dS )a  Retrieve a batch of documents.

        .. note::

           Documents returned by this method are not guaranteed to be
           returned in the same order that they are given in ``references``.

        .. note::

           If multiple ``references`` refer to the same document, the server
           will only return one result.

        See :meth:`~google.cloud.firestore_v1.client.Client.field_path` for
        more information on **field paths**.

        If a ``transaction`` is used and it already has write operations
        added, this method cannot be used (i.e. read-after-write is not
        allowed).

        Args:
            references (List[.AsyncDocumentReference, ...]): Iterable of document
                references to be retrieved.
            field_paths (Optional[Iterable[str, ...]]): An iterable of field
                paths (``.``-delimited list of field names) to use as a
                projection of document fields in the returned results. If
                no value is provided, all fields will be returned.
            transaction (Optional[:class:`~google.cloud.firestore_v1.async_transaction.AsyncTransaction`]):
                An existing transaction that these ``references`` will be
                retrieved in.
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.  Defaults to a system-specified policy.
            timeout (float): The timeout for this request.  Defaults to a
                system-specified value.

        Yields:
            .DocumentSnapshot: The next document snapshot that fulfills the
            query, or :data:`None` if the document does not exist.
        requestmetadataNr)   )_prep_get_allr:   batch_get_documents_rpc_metadatar   )r&   rF   rG   transactionr   rH   rJ   reference_mapkwargsresponse_iteratorget_doc_responser)   r)   r*   get_all   s   .

zAsyncClient.get_allc                 C  sV   |  ||\}}| jjd|| jd|I dH }|2 z3 dH W }| |V  q6 dS )a  List top-level collections of the client's database.

        Args:
            retry (google.api_core.retry.Retry): Designation of what errors, if any,
                should be retried.  Defaults to a system-specified policy.
            timeout (float): The timeout for this request.  Defaults to a
                system-specified value.

        Returns:
            Sequence[:class:`~google.cloud.firestore_v1.async_collection.AsyncCollectionReference`]:
                iterator of subcollections of the current document.
        rI   Nr)   )_prep_collectionsr:   list_collection_idsrN   r?   )r&   r   rH   rJ   rQ   iteratorr@   r)   r)   r*   collections  s   zAsyncClient.collectionsi  bulk_writer
chunk_size	referencerZ   r   r[   c                   s(   |du r	|   }| j|||dI dH S )al  Deletes documents and their subcollections, regardless of collection
        name.

        Passing an AsyncCollectionReference leads to each document in the
        collection getting deleted, as well as all of their descendents.

        Passing an AsyncDocumentReference deletes that one document and all of
        its descendents.

        Args:
            reference (Union[
                :class:`@google.cloud.firestore_v1.async_collection.CollectionReference`,
                :class:`@google.cloud.firestore_v1.async_document.DocumentReference`,
            ])
                The reference to be deleted.

            bulk_writer (Optional[:class:`@google.cloud.firestore_v1.bulk_writer.BulkWriter`])
                The BulkWriter used to delete all matching documents. Supply this
                if you want to override the default throttling behavior.
        NrY   )rZ   _recursive_delete)r&   r\   rZ   r[   r)   r)   r*   recursive_delete9  s   zAsyncClient.recursive_deleter   )r[   depthr_   c          	         s   d}t |tr-| t g|2 z3 dH W }|D ]}|d7 }||j qq6 n4t |t	rX|
 2 z3 dH W }|| j|||d |dI dH 7 }q66 |d7 }|| n	td|jj |dkri|  |S )z'Recursion helper for `recursive_delete.r   N   )rZ   r_   r[   zUnexpected type for reference: )
isinstancer   	recursiveselectr   document_id	_chunkifydeleter\   r   rX   r]   	TypeErrorr(   __name__close)	r&   r\   rZ   r[   r_   num_deletedchunkdoc_snapcol_refr)   r)   r*   r]   ]  s<   


zAsyncClient._recursive_deletec                 C   s   t | S )a  Get a batch instance from this client.

        Returns:
            :class:`~google.cloud.firestore_v1.async_batch.AsyncWriteBatch`:
            A "write" batch to be used for accumulating document changes and
            sending the changes all at once.
        r
   r9   r)   r)   r*   batch  s   zAsyncClient.batchc                 K   s   t | fi |S )ae  Get a transaction that uses this client.

        See :class:`~google.cloud.firestore_v1.async_transaction.AsyncTransaction` for
        more information on transactions and the constructor arguments.

        Args:
            kwargs (Dict[str, Any]): The keyword arguments (other than
                ``client``) to pass along to the
                :class:`~google.cloud.firestore_v1.async_transaction.AsyncTransaction`
                constructor.

        Returns:
            :class:`~google.cloud.firestore_v1.async_transaction.AsyncTransaction`:
            A transaction attached to this client.
        r   )r&   rQ   r)   r)   r*   rO     s   zAsyncClient.transaction)r   N))rh   
__module____qualname____doc__r   r   r%   r3   propertyr:   r<   strr   r?   r	   rB   r   rE   r   methodDEFAULTr   r   retriesRetryfloatr   r   r   rT   rX   r   r   intr^   r]   r   rn   r   rO   __classcell__r)   r)   r'   r*   r   ;   s    

	&

=



)

,
r   N))rq   google.api_corer   r   rv   %google.cloud.firestore_v1.base_clientr   r   r   r   r   %google.cloud.firestore_v1.async_queryr	   %google.cloud.firestore_v1.async_batchr   *google.cloud.firestore_v1.async_collectionr   (google.cloud.firestore_v1.async_documentr   r   +google.cloud.firestore_v1.async_transactionr   $google.cloud.firestore_v1.field_pathr   ,google.cloud.firestore_v1.services.firestorer   r7   7google.cloud.firestore_v1.services.firestore.transportsr   r5   typingr   r   r   r   r   r   r   %google.cloud.firestore_v1.bulk_writerr   r   r)   r)   r)   r*   <module>   s    $