o
    ,=jë=  ã                   @  s   d Z ddlmZ ddlmZmZ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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 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% ddl&m'Z( ddl)m*Z+ ddl,m-Z- er†ddl.Z.ddl/m0Z0 G dd„ deƒZ1d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.collection.CollectionReference`
* a :class:`~google.cloud.firestore_v1.client.Client` owns a
  :class:`~google.cloud.firestore_v1.document.DocumentReference`
é    )Úannotations)ÚTYPE_CHECKINGÚAnyÚ	GeneratorÚIterableÚListÚOptionalÚUnion)Úgapic_v1)Úretry)Ú_CLIENT_INFOÚ
BaseClientÚ_parse_batch_getÚ_path_helper)ÚDocumentSnapshot)ÚMAX_ATTEMPTS©Ú
WriteBatch)ÚCollectionReference)ÚDocumentReference)Ú	FieldPath©ÚPipeline©ÚPipelineSource)ÚCollectionGroup)Úclient)Úgrpc©ÚTransactionN)Ú
BulkWriterc                      sä   e Zd ZdZdddedfdH‡ fdd„Zedd„ ƒZdIdd„ZdJdd„Z	dKdd„Z
ddejjdfddœdLd$d%„ZejjdfddœdMd'd(„Zdd)d*œdNd1d2„Zd)d3d4œdOd7d8„ZdPd:d;„Zed<fdQdAdB„ZedCdD„ ƒZdRdFdG„Z‡  ZS )SÚClienta  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.
            If not passed, falls back to :attr:`DEFAULT_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ÚreturnÚNonec                   s   t t| ƒj|||||d� d S )N)ÚprojectÚcredentialsÚdatabaseÚclient_infoÚclient_options)Úsuperr!   Ú__init__)Úselfr$   r%   r&   r'   r(   ©Ú	__class__© újC:\Users\psant\Downloads\Anu Raj Backend\school\venv\Lib\site-packages\google/cloud/firestore_v1/client.pyr*   Z   s   

ûzClient.__init__c                 C  s   |   tjtjt¡S )zãLazy-loading getter GAPIC Firestore API.
        Returns:
            :class:`~google.cloud.gapic.firestore.v1`.firestore_client.FirestoreClient:
            The GAPIC client with the credentials of the current client.
        N)Z_firestore_api_helperÚfirestore_grpc_transportZFirestoreGrpcTransportÚfirestore_clientZFirestoreClient©r+   r.   r.   r/   Ú_firestore_apij   s
   ýzClient._firestore_apiÚcollection_pathÚstrr   c                 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.collection.CollectionReference`:
            A reference to a collection in the Firestore database.
        r   N)r   r   )r+   r4   r.   r.   r/   Ú
collectionw   s   zClient.collectionÚcollection_idr   c                 C  s   t |  |¡ƒS )a†  
        Creates and returns a new Query 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.query.CollectionGroup`:
            The created Query.
        N)r   Z_get_collection_reference)r+   r7   r.   r.   r/   Úcollection_group–   s   zClient.collection_groupÚdocument_pathr   c                 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.DocumentReference`:
            A reference to a document in a collection.
        r   N)r   Z_document_path_helper)r+   r9   r.   r.   r/   Údocument¬   s
   ÿÿzClient.document)Ú	read_timeÚ
referencesÚlistÚfield_pathsúIterable[str] | NoneÚtransactionúTransaction | Noner   úretries.Retry | object | NoneÚtimeoutúfloat | Noner;   údatetime.datetime | Noneú&Generator[DocumentSnapshot, Any, None]c                c  sR   � |   ||||||¡\}}}	| jjd|| jdœ|	¤Ž}
|
D ]	}t||| ƒV  qdS )a7  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[.DocumentReference, ...]): 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.transaction.Transaction`]):
                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.
            read_time (Optional[datetime.datetime]): If set, reads documents as they were at the given
                time. This must be a timestamp within the past one hour, or if Point-in-Time Recovery
                is enabled, can additionally be a whole minute timestamp within the past 7 days. If no
                timezone is specified in the :class:`datetime.datetime` object, it is assumed to be UTC.

        Yields:
            .DocumentSnapshot: The next document snapshot that fulfills the
            query, or :data:`None` if the document does not exist.
        ©ÚrequestÚmetadataNr.   )Z_prep_get_allr3   Zbatch_get_documentsÚ_rpc_metadatar   )r+   r<   r>   r@   r   rC   r;   rH   Zreference_mapÚkwargsZresponse_iteratorZget_doc_responser.   r.   r/   Úget_allÏ   s   €4
ÿþýÿzClient.get_allúGenerator[Any, Any, None]c                c  sH   � |   |||¡\}}| jjd|| jdœ|¤Ž}|D ]}|  |¡V  q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.
            read_time (Optional[datetime.datetime]): If set, reads documents as they were at the given
                time. This must be a timestamp within the past one hour, or if Point-in-Time Recovery
                is enabled, can additionally be a whole minute timestamp within the past 7 days. If no
                timezone is specified in the :class:`datetime.datetime` object, it is assumed to be UTC.

        Returns:
            Sequence[:class:`~google.cloud.firestore_v1.collection.CollectionReference`]:
                iterator of subcollections of the current document.
        rG   Nr.   )Z_prep_collectionsr3   Zlist_collection_idsrJ   r6   )r+   r   rC   r;   rH   rK   Úiteratorr7   r.   r.   r/   Úcollections  s   €þýÿzClient.collectionsiˆ  )Úbulk_writerÚ
chunk_sizeÚ	referenceú-Union[CollectionReference, DocumentReference]rP   úOptional['BulkWriter']rQ   Úintc                C  s    |du r|   ¡ }| j|||d�S )aU  Deletes documents and their subcollections, regardless of collection
        name.

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

        Passing a DocumentReference deletes that one document and all of its
        descendents.

        Args:
            reference (Union[
                :class:`@google.cloud.firestore_v1.collection.CollectionReference`,
                :class:`@google.cloud.firestore_v1.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.

        N)rQ   )rP   Ú_recursive_delete)r+   rR   rP   rQ   r.   r.   r/   Úrecursive_delete2  s   ýzClient.recursive_deleter   ©rQ   Údepthú'BulkWriter'rY   c          	      C  s¸   d}t |tƒr&| ¡  t ¡ g¡ |¡D ]=}|D ]}|d7 }| |j¡ qqt |t	ƒrI| 
¡ D ]}|| j||||d d�7 }q/|d7 }| |¡ n	td|jj› �ƒ‚|dkrZ| ¡  |S )z'Recursion helper for `recursive_delete.r   é   rX   zUnexpected type for reference: N)Ú
isinstancer   Ú	recursiveÚselectr   Zdocument_idZ	_chunkifyÚdeleterR   r   rO   rV   Ú	TypeErrorr-   Ú__name__Úclose)	r+   rR   rP   rQ   rY   Znum_deletedÚchunkZdoc_snapZcol_refr.   r.   r/   rV   W  s4   

ýþ

üÿzClient._recursive_deleter   c                 C  ó   t | ƒS )zýGet a batch instance from this client.

        Returns:
            :class:`~google.cloud.firestore_v1.batch.WriteBatch`:
            A "write" batch to be used for accumulating document changes and
            sending the changes all at once.
        Nr   r2   r.   r.   r/   Úbatch…  s   zClient.batchFÚmax_attemptsÚ	read_onlyÚboolr   c                 C  s   t | ||d�S )aD  Get a transaction that uses this client.

        See :class:`~google.cloud.firestore_v1.transaction.Transaction` 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.transaction.Transaction`
                constructor.

        Returns:
            :class:`~google.cloud.firestore_v1.transaction.Transaction`:
            A transaction attached to this client.
        )rf   rg   Nr   )r+   rf   rg   r.   r.   r/   r@   �  s   zClient.transactionc                 C  s   t S ©Nr   r2   r.   r.   r/   Ú_pipeline_cls£  s   zClient._pipeline_clsr   c                 C  rd   ri   r   r2   r.   r.   r/   Úpipeline§  s   zClient.pipeline)r"   r#   )r4   r5   r"   r   )r7   r5   r"   r   )r9   r5   r"   r   )r<   r=   r>   r?   r@   rA   r   rB   rC   rD   r;   rE   r"   rF   )r   rB   rC   rD   r;   rE   r"   rM   )rR   rS   rP   rT   rQ   rU   r"   rU   )
rR   rS   rP   rZ   rQ   rU   rY   rU   r"   rU   )r"   r   )rf   rU   rg   rh   r"   r   )r"   r   )ra   Ú
__module__Ú__qualname__Ú__doc__r   r*   Úpropertyr3   r6   r8   r:   r
   ÚmethodÚDEFAULTrL   rO   rW   rV   re   r   r@   rj   rk   Ú__classcell__r.   r.   r,   r/   r!   ?   sJ    ú



&úøCýû&û*ú
.ÿ
r!   )2rn   Ú
__future__r   Útypingr   r   r   r   r   r   r	   Zgoogle.api_corer
   r   ÚretriesZ%google.cloud.firestore_v1.base_clientr   r   r   r   Z'google.cloud.firestore_v1.base_documentr   Z*google.cloud.firestore_v1.base_transactionr   Zgoogle.cloud.firestore_v1.batchr   Z$google.cloud.firestore_v1.collectionr   Z"google.cloud.firestore_v1.documentr   Z$google.cloud.firestore_v1.field_pathr   Z"google.cloud.firestore_v1.pipeliner   Z)google.cloud.firestore_v1.pipeline_sourcer   Zgoogle.cloud.firestore_v1.queryr   Z,google.cloud.firestore_v1.services.firestorer   r1   Z7google.cloud.firestore_v1.services.firestore.transportsr   r0   Z%google.cloud.firestore_v1.transactionr   ÚdatetimeZ%google.cloud.firestore_v1.bulk_writerr    r!   r.   r.   r.   r/   Ú<module>   s,   $