o
    ˷eSW                     @   s  U d Z ddlZddlZddlmZ ddlZddl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mZ ddlmZ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' ddl(m)Z) ddl*m+Z+ dZ,	 dZ-dZ.dZ/e0e1d< dZ2e0e1d< dZ3e0e1d< ej4edZ5ee1d< dZ6e0e1d< G d d! d!eZ7d"e8d#e!e8e9f fd$d%Z:d&e0d'e9d#e%fd(d)Z;d*ej<d'e9d+e7d#efd,d-Z=d.ee0 d#e ej>j? fd/d0Z@d1eAd#e!e0 fd2d3ZBdS )4a  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`
    N)AnonymousCredentials)retry)client_info)ClientWithProject)_helpers)__version__)types)DocumentSnapshotrender_field_path)
BulkWriterBulkWriterOptions)AnyAsyncGenerator	GeneratorIterableListOptionalTupleUnion)BaseCollectionReference)BaseDocumentReference)BaseTransaction)BaseWriteBatch)	BaseQueryz	(default)zgoogle-cloud-firestore-emulatorzCExactly one of ``last_update_time`` or ``exists`` must be provided.zGDocument {!r} appeared in response but was not present among references_BAD_DOC_TEMPLATEz'There is already an active transaction._ACTIVE_TXNzThere is no active transaction._INACTIVE_TXN)client_library_version_CLIENT_INFOFIRESTORE_EMULATOR_HOST_FIRESTORE_EMULATOR_HOSTc                       sD  e Zd ZdZdZ	 dZdZdZddee	df	d: fddZ
defddZd	d
 ZdefddZedd Zedd ZdefddZdedefddZdedefddZdefddZd;dee defddZdee fddZ	d;de eef d ed! de!fd"d#Z"e#d$edefd%d&Z$e#de e%j&e%j'f fd'd(Z(				d<d)e)d*e*e d+e+d,e,j-d-e.de/e0e0e0f fd.d/Z1				d<d)e)d*e*e d+e+d,e,j-d-e.de e2e3ef e4e3eef f fd0d1Z5		d=d,e,j-d-e.de/e0e0f fd2d3Z6		d=d,e,j-d-e.de e2eef e4eeef f fd4d5Z7de8fd6d7Z9de+fd8d9Z:  Z;S )>
BaseClienta:  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.
    )z.https://www.googleapis.com/auth/cloud-platformz)https://www.googleapis.com/auth/datastoreNreturnc                    s|   t t| _| jd ur|d u rt }|d u rt}tt| j|||d d || _	|r6t
|tkr6tjj|}|| _|| _d S )N)projectcredentialsclient_options_http)osgetenvr!   _emulator_hostr   _DEFAULT_EMULATOR_PROJECTsuperr"   __init___client_infotypedictgoogleapi_corer&   	from_dict_client_options	_database)selfr$   r%   databaser   r&   	__class__ \/var/www/ideatree/venv/lib/python3.10/site-packages/google/cloud/firestore_v1/base_client.pyr-   t   s(   


zBaseClient.__init__c                 C   sl   | j du r3| jdur| |}n|j| j| jddi d}|| j|d| _|| j| jd| _ | j	|_	| j S )zLazy-loading getter GAPIC Firestore API.
        Returns:
            The GAPIC client with the credentials of the current client.
        Nzgrpc.keepalive_time_msi0u  )r%   options)hostchannel)	transportr&   )
_firestore_api_internalr*   _emulator_channelcreate_channel_target_credentialsitems
_transportr4   r.   )r6   r?   client_classclient_moduler>   r:   r:   r;   _firestore_api_helper   s   


z BaseClient._firestore_api_helperc                 C   sh   d}| j durt| j dddur| j j}dd| fg}dt|jv r,tjj| j|dS tj| j|dS )a]  
        Creates an insecure channel to communicate with the local emulator.
        If credentials are provided the token is extracted and added to the
        headers. This supports local testing of firestore rules if the credentials
        have been created from a signed custom token.

        :return: grpc.Channel or grpc.aio.Channel
        ownerNid_tokenAuthorizationzBearer GrpcAsyncIOTransport)r<   )	rD   getattrrK   str__name__grpcaioinsecure_channelr*   )r6   r?   tokenr<   r:   r:   r;   rA      s   
zBaseClient._emulator_channelc                 C   s,   | j dur| j S | jr| jjr| jjS |jS )zReturn the target (where the API is).
        Eg. "firestore.googleapis.com"

        Returns:
            str: The location of the API.
        N)r*   r4   api_endpointDEFAULT_ENDPOINT)r6   rG   r:   r:   r;   _target_helper   s
   
zBaseClient._target_helperc                 C   s.   | j du rtjjjd| j| jd}|| _ | j S )a  The database string corresponding to this client's project.

        This value is lazy-loaded and cached.

        Will be of the form

            ``projects/{project_id}/databases/{database_id}``

        but ``database_id == '(default)'`` for the time being.

        Returns:
            str: The fully-qualified database string for the current
            project. (The default database is also in this string.)
        Nz'projects/{project}/databases/{database})r$   r7   )_database_string_internalr1   r2   path_templateexpandr$   r5   )r6   db_strr:   r:   r;   _database_string   s   
zBaseClient._database_stringc                 C   s4   | j du rt| j| _ | jdur| j d | j S )zThe RPC metadata for this client's associated database.

        Returns:
            Sequence[Tuple(str, str)]: RPC metadata with resource prefix
            for the database associated with this client.
        N)authorizationzBearer owner)_rpc_metadata_internalr   metadata_with_prefixr\   r*   appendr6   r:   r:   r;   _rpc_metadata   s   

zBaseClient._rpc_metadatac                 G      t NNotImplementedError)r6   collection_pathr:   r:   r;   
collection     zBaseClient.collectioncollection_idc                 C   rc   rd   re   r6   rj   r:   r:   r;   collection_group  ri   zBaseClient.collection_groupc                 C   s"   d|v rt d| d | |S )a  Checks validity of collection_id and then uses subclasses collection implementation.

        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:
            The created collection.
        /zInvalid collection_id z&. Collection IDs must not contain '/'.)
ValueErrorrh   rk   r:   r:   r;   _get_collection_reference  s   
z$BaseClient._get_collection_referencec                 G   rc   rd   re   )r6   document_pathr:   r:   r;   document#  ri   zBaseClient.documentr<   c                 C   s   t | |dS )a  Get a BulkWriter instance from this client.

        Args:
            :class:`@google.cloud.firestore_v1.bulk_writer.BulkWriterOptions`:
            Optional control parameters for the
            :class:`@google.cloud.firestore_v1.bulk_writer.BulkWriter` returned.

        Returns:
            :class:`@google.cloud.firestore_v1.bulk_writer.BulkWriter`:
            A utility to efficiently create and save many `WriteBatch` instances
            to the server.
        )clientr<   )r   )r6   r<   r:   r:   r;   bulk_writer&  s   zBaseClient.bulk_writerc                 G   sD   t |}| jd }tj|}||r|t|d }|tjS )a2  Standardize the format of path to tuple of path segments and strip the database string from path if present.

        Args:
            document_path (Tuple[str, ...]): Can either be

                * A single ``/``-delimited path to a document
                * A tuple of document path segments
        z/documents/N)_path_helperr\   r   DOCUMENT_PATH_DELIMITERjoin
startswithlensplit)r6   rp   path	base_pathjoined_pathr:   r:   r;   _document_path_helper5  s   	

z BaseClient._document_path_helper	referencers   r   c                 C   rc   rd   re   )r6   r~   rs   r:   r:   r;   recursive_deleteE  s   zBaseClient.recursive_deletefield_namesc                  G   s   t | S )a  Create a **field path** from a list of nested field names.

        A **field path** is a ``.``-delimited concatenation of the field
        names. It is used to represent a nested field. For example,
        in the data

        .. code-block:: python

           data = {
              'aa': {
                  'bb': {
                      'cc': 10,
                  },
              },
           }

        the field path ``'aa.bb.cc'`` represents the data stored in
        ``data['aa']['bb']['cc']``.

        Args:
            field_names: The list of field names.

        Returns:
            str: The ``.``-delimited field path.
        r
   )r   r:   r:   r;   
field_pathL  s   zBaseClient.field_pathc                  K   sX   t | dkr
tt|  \}}|dkrt|S |dkr"t|S d|}tt|)a,  Create a write option for write operations.

        Write operations include :meth:`~google.cloud.DocumentReference.set`,
        :meth:`~google.cloud.DocumentReference.update` and
        :meth:`~google.cloud.DocumentReference.delete`.

        One of the following keyword arguments must be provided:

        * ``last_update_time`` (:class:`google.protobuf.timestamp_pb2.               Timestamp`): A timestamp. When set, the target document must
               exist and have been last updated at that time. Protobuf
               ``update_time`` timestamps are typically returned from methods
               that perform write operations as part of a "write result"
               protobuf or directly.
        * ``exists`` (:class:`bool`): Indicates if the document being modified
              should already exist.

        Providing no argument would make the option have no effect (so
        it is not allowed). Providing multiple would be an apparent
        contradiction, since ``last_update_time`` assumes that the
        document **was** updated (it can't have been updated if it
        doesn't exist) and ``exists`` indicate that it is unknown if the
        document exists or not.

        Args:
            kwargs (Dict[str, Any]): The keyword arguments described above.

        Raises:
            TypeError: If anything other than exactly one argument is
                provided by the caller.

        Returns:
            :class:`~google.cloud.firestore_v1.client.WriteOption`:
            The option to be used to configure a write message.
           last_update_timeexistsz{!r} was provided)rx   	TypeError_BAD_OPTION_ERRpopitemr   LastUpdateOptionExistsOptionformat)kwargsnamevalueextrar:   r:   r;   write_optioni  s   '



zBaseClient.write_option
referencesfield_pathstransactionr   timeoutc                 C   s@   t |\}}t|}| j||t|d}	t||}
|	||
fS )z,Shared setup for async/sync :meth:`get_all`.)r7   	documentsmaskr   )_reference_info_get_doc_maskr\   r   get_transaction_idmake_retry_timeout_kwargs)r6   r   r   r   r   r   document_pathsreference_mapr   requestr   r:   r:   r;   _prep_get_all  s   	
zBaseClient._prep_get_allc                 C   rc   rd   re   )r6   r   r   r   r   r   r:   r:   r;   get_all  s   
zBaseClient.get_allc                 C   s$   dd | ji}t||}||fS )z0Shared setup for async/sync :meth:`collections`.parentz{}/documents)r   r\   r   r   )r6   r   r   r   r   r:   r:   r;   _prep_collections  s   zBaseClient._prep_collectionsc                 C   rc   rd   re   )r6   r   r   r:   r:   r;   collections  s   zBaseClient.collectionsc                 C   rc   rd   re   ra   r:   r:   r;   batch  ri   zBaseClient.batchc                 K   rc   rd   re   )r6   r   r:   r:   r;   r     ri   zBaseClient.transaction)r#   Nrd   )NNNN)NN)<rP   
__module____qualname____doc__SCOPEr@   rX   r^   DEFAULT_DATABASEr   r-   r   rI   rA   rO   rW   propertyr\   rb   r   rh   r   rl   ro   r   rq   r   r   r   rs   r   r}   r   intr   staticmethodr   r   r   r   r   listr   r   retriesRetryfloatr   r0   r   r   r	   r   r   r   r   r   r   r   __classcell__r:   r:   r8   r;   r"   N   s    #



5






r"   r   r#   c                 C   s2   g }i }| D ]}|j }|| |||< q||fS )a^  Get information about document references.

    Helper for :meth:`~google.cloud.firestore_v1.client.Client.get_all`.

    Args:
        references (List[.DocumentReference, ...]): Iterable of document
            references.

    Returns:
        Tuple[List[str, ...], Dict[str, .DocumentReference]]: A two-tuple of

        * fully-qualified documents paths for each reference in ``references``
        * a mapping from the paths to the original reference. (If multiple
          ``references`` contains multiple references to the same document,
          that key will be overwritten in the result.)
    )_document_pathr`   )r   r   r   r~   doc_pathr:   r:   r;   r     s   

r   rp   r   c                 C   s,   z||  W S  t y   t| }t|w )a  Get a document reference from a dictionary.

    This just wraps a simple dictionary look-up with a helpful error that is
    specific to :meth:`~google.cloud.firestore.client.Client.get_all`, the
    **public** caller of this function.

    Args:
        document_path (str): A fully-qualified document path.
        reference_map (Dict[str, .DocumentReference]): A mapping (produced
            by :func:`_reference_info`) of fully-qualified document paths to
            document references.

    Returns:
        .DocumentReference: The matching reference.

    Raises:
        ValueError: If ``document_path`` has not been encountered.
    )KeyErrorr   r   rn   )rp   r   msgr:   r:   r;   _get_reference  s   

r   get_doc_responserr   c                 C   s   | j d}|dkr*t| jj|}t| jj|}t||d| j	| jj
| jjd}|S |dkrAt| j|}t|dd| j	ddd}|S td)	a  Parse a `BatchGetDocumentsResponse` protobuf.

    Args:
        get_doc_response (~google.cloud.proto.firestore.v1.            firestore.BatchGetDocumentsResponse): A single response (from
            a stream) containing the "get" response for a document.
        reference_map (Dict[str, .DocumentReference]): A mapping (produced
            by :func:`_reference_info`) of fully-qualified document paths to
            document references.
        client (:class:`~google.cloud.firestore_v1.client.Client`):
            A client that has a document factory.

    Returns:
       [.DocumentSnapshot]: The retrieved snapshot.

    Raises:
        ValueError: If the response has a ``result`` field (a oneof) other
            than ``found`` or ``missing``.
    resultfoundT)r   	read_timecreate_timeupdate_timemissingNFzj`BatchGetDocumentsResponse.result` (a oneof) had a field other than `found` or `missing` set, or was unset)_pb
WhichOneofr   r   r   r   decode_dictfieldsr	   r   r   r   r   rn   )r   r   rr   result_typer~   datasnapshotr:   r:   r;   _parse_batch_get  s6   r   r   c                 C   s   | du rdS t j| dS )a  Get a document mask if field paths are provided.

    Args:
        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.

    Returns:
        Optional[google.cloud.firestore_v1.types.common.DocumentMask]: A mask
            to project documents to a restricted set of field paths.
    Nr   )r   DocumentMaskr   r:   r:   r;   r   D  s   r   rz   c                 C   s    t | dkr| d tjS | S )zStandardize path into a tuple of path segments.

    Args:
        path (Tuple[str, ...]): Can either be

            * A single ``/``-delimited path
            * A tuple of path segments
    r   r   )rx   ry   r   ru   )rz   r:   r:   r;   rt   V  s   	rt   )Cr   r(   rQ   google.auth.credentialsr   google.api_core.client_optionsr1   google.api_core.path_templategoogle.api_corer   r   google.api_core.gapic_v1r   google.cloud.clientr   google.cloud.firestore_v1r   r   r   'google.cloud.firestore_v1.base_documentr	   $google.cloud.firestore_v1.field_pathr   %google.cloud.firestore_v1.bulk_writerr   r   typingr   r   r   r   r   r   r   r   )google.cloud.firestore_v1.base_collectionr   r   *google.cloud.firestore_v1.base_transactionr   $google.cloud.firestore_v1.base_batchr   $google.cloud.firestore_v1.base_queryr   r   r+   r   r   rO   __annotations__r   r   
ClientInfor   r!   r"   r   r0   r   r   BatchGetDocumentsResponser   commonr   r   tuplert   r:   r:   r:   r;   <module>   sb   (
   
6