o
    ˷e@H                     @   s   d 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mZmZmZmZmZmZ G dd deZG dd deZdee defddZdejfddZdedejfddZdS )zFClasses for representing documents for the Google Cloud Firestore API.    N)retry)Document)_helpers)
field_path)common)	firestore)write)AnyDictIterableNoReturnOptionalUnionTuplec                   @   s  e Zd ZdZdZd?ddZdd Zdd	 Zd
d Zdd Z	dd Z
edd Zedd Zedd Zedd ZdedefddZ		d@dedejdedeeef fddZ		d@dedejdedefd d!Z	"		dAded#edejdedeeef f
d$d%Z	"		dAded#edejdedef
d&d'Z			dBd(ed)ejdejdedeeef f
d*d+Z 			dBd(ed)ejdejdedef
d,d-Z!			dBd)ejdejdedeeef fd.d/Z"			dBd)ejdejdedefd0d1Z#				dCd2e$e dejdedeeef fd3d4Z%				dCd2e$e dejdedd5fd6d7Z&			dBd8e'dejdedeeef fd9d:Z(			dBd8e'dejdeddfd;d<Z)d?d=d>Z*dS )DBaseDocumentReferencea  A reference to a document in a Firestore database.

    The document may already exist or can be created by this class.

    Args:
        path (Tuple[str, ...]): The components in the document path.
            This is a series of strings representing each collection and
            sub-collection ID, as well as the document IDs for any documents
            that contain a sub-collection (as well as the base document).
        kwargs (dict): The keyword arguments for the constructor. The only
            supported keyword is ``client`` and it must be a
            :class:`~google.cloud.firestore_v1.client.Client`. It represents
            the client that created this document reference.

    Raises:
        ValueError: if

            * the ``path`` is empty
            * there are an even number of elements
            * a collection ID in ``path`` is not a string
            * a document ID in ``path`` is not a string
        TypeError: If a keyword other than ``client`` is used.
    Nreturnc                 O   s6   t j|dd || _|dd | _|rtd|dd S )NF)is_collectionclientzReceived unexpected argumentszOnly `client` is supported)r   verify_path_pathpop_client	TypeError)selfpathkwargs r   ^/var/www/ideatree/venv/lib/python3.10/site-packages/google/cloud/firestore_v1/base_document.py__init__;   s   zBaseDocumentReference.__init__c                 C   s    | j | jd| ji}| j|_|S )zShallow copy the instance.

        We leave the client "as-is" but tuple-unpack the path.

        Returns:
            .DocumentReference: A copy of the current document.
        r   )	__class__r   r   _document_path_internal)r   resultr   r   r   __copy__D   s   zBaseDocumentReference.__copy__c                 C   s   |   S )zDeep copy the instance.

        This isn't a true deep copy, wee leave the client "as-is" but
        tuple-unpack the path.

        Returns:
            .DocumentReference: A copy of the current document.
        )r"   )r   unused_memor   r   r   __deepcopy__P   s   	z"BaseDocumentReference.__deepcopy__c                 C   s(   t || jr| j|jko| j|jkS tS )zEquality check against another instance.

        Args:
            other (Any): A value to compare against.

        Returns:
            Union[bool, NotImplementedType]: Indicating if the values are
            equal.
        
isinstancer   r   r   NotImplementedr   otherr   r   r   __eq__[      
zBaseDocumentReference.__eq__c                 C      t | jt | j S N)hashr   r   r   r   r   r   __hash__j      zBaseDocumentReference.__hash__c                 C   s(   t || jr| j|jkp| j|jkS tS )zInequality check against another instance.

        Args:
            other (Any): A value to compare against.

        Returns:
            Union[bool, NotImplementedType]: Indicating if the values are
            not equal.
        r%   r(   r   r   r   __ne__m   r+   zBaseDocumentReference.__ne__c                 C   s   d | jS )znDatabase-relative for this document.

        Returns:
            str: The document's relative path.
        /)joinr   r/   r   r   r   r   |   s   zBaseDocumentReference.pathc                 C   s2   | j du r| jdu rtdt| j| j| _ | j S )aX  Create and cache the full path for this document.

        Of the form:

            ``projects/{project_id}/databases/{database_id}/...
                  documents/{document_path}``

        Returns:
            str: The full document path.

        Raises:
            ValueError: If the current document reference has no ``client``.
        Nz)A document reference requires a `client`.)r    r   
ValueError_get_document_pathr   r/   r   r   r   _document_path   s
   

z$BaseDocumentReference._document_pathc                 C   s
   | j d S )z|The document identifier (within its collection).

        Returns:
            str: The last component of the path.
        )r   r/   r   r   r   id   s   
zBaseDocumentReference.idc                 C   s   | j dd }| jj| S )zCollection that owns the current document.

        Returns:
            :class:`~google.cloud.firestore_v1.collection.CollectionReference`:
            The parent collection.
        Nr8   r   r   
collection)r   parent_pathr   r   r   parent   s   zBaseDocumentReference.parentcollection_idc                 C   s   | j |f }| jj| S )aJ  Create a sub-collection underneath the current document.

        Args:
            collection_id (str): The sub-collection identifier (sometimes
                referred to as the "kind").

        Returns:
            :class:`~google.cloud.firestore_v1.collection.CollectionReference`:
            The child collection.
        r:   )r   r>   
child_pathr   r   r   r;      s   z BaseDocumentReference.collectiondocument_datar   timeoutc                 C   s*   | j  }|| | t||}||fS r-   )r   batchcreater   make_retry_timeout_kwargs)r   r@   r   rA   rB   r   r   r   r   _prep_create   s   
z"BaseDocumentReference._prep_createc                 C      t r-   NotImplementedError)r   r@   r   rA   r   r   r   rC         zBaseDocumentReference.createFmergec                 C   .   | j  }|j| ||d t||}||fS )N)rJ   )r   rB   setr   rD   )r   r@   rJ   r   rA   rB   r   r   r   r   	_prep_set      
zBaseDocumentReference._prep_setc                 C   rF   r-   rG   )r   r@   rJ   r   rA   r   r   r   rL         zBaseDocumentReference.setfield_updatesoptionc                 C   rK   )N)rQ   )r   rB   updater   rD   )r   rP   rQ   r   rA   rB   r   r   r   r   _prep_update   rN   z"BaseDocumentReference._prep_updatec                 C   rF   r-   rG   )r   rP   rQ   r   rA   r   r   r   rR      rO   zBaseDocumentReference.updatec                 C   s4   t | j|}| jj|gdd}t ||}||fS )z+Shared setup for async/sync :meth:`delete`.N)databasewritestransaction)r   pb_for_deleter7   r   _database_stringrD   )r   rQ   r   rA   write_pbrequestr   r   r   r   _prep_delete   s   z"BaseDocumentReference._prep_deletec                 C   rF   r-   rG   )r   rQ   r   rA   r   r   r   delete  rI   zBaseDocumentReference.deletefield_pathsc                 C   s`   t |tr	td|durtjt|d}nd}| jj| jg|t	
|d}t	||}||fS )z(Shared setup for async/sync :meth:`get`.z8'field_paths' must be a sequence of paths, not a string.N)r]   )rT   	documentsmaskrV   )r&   strr5   r   DocumentMasksortedr   rX   r7   r   get_transaction_idrD   )r   r]   rV   r   rA   r_   rZ   r   r   r   r   _prep_batch_get  s   
z%BaseDocumentReference._prep_batch_getDocumentSnapshotc                 C   rF   r-   rG   )r   r]   rV   r   rA   r   r   r   get0  rO   zBaseDocumentReference.get	page_sizec                 C   s    | j |d}t||}||fS )z0Shared setup for async/sync :meth:`collections`.)r=   rg   )r7   r   rD   )r   rg   r   rA   rZ   r   r   r   r   _prep_collections9  s   z'BaseDocumentReference._prep_collectionsc                 C   rF   r-   rG   )r   rg   r   rA   r   r   r   collectionsE  rI   z!BaseDocumentReference.collectionsc                 C   rF   r-   rG   )r   callbackr   r   r   on_snapshotM  s   z!BaseDocumentReference.on_snapshotr   N)NN)FNN)NNN)NNNN)+__name__
__module____qualname____doc__r    r   r"   r$   r*   r0   r2   propertyr   r7   r9   r=   r`   r	   r;   dictretriesRetryfloatr   rE   r   rC   boolrM   rL   r   WriteOptionrS   rR   r[   r\   r   rd   rf   intrh   ri   rk   r   r   r   r   r       sV   
	























r   c                   @   s   e Zd ZdZ		dddZdd Zdd	 Zed
d Zedd Z	edd Z
edd ZdedefddZdeeeef df fddZdee fddZdS )re   a  A snapshot of document data in a Firestore database.

    This represents data retrieved at a specific time and may not contain
    all fields stored for the document (i.e. a hand-picked selection of
    fields may have been retrieved).

    Instances of this class are not intended to be constructed by hand,
    rather they'll be returned as responses to various methods, such as
    :meth:`~google.cloud.DocumentReference.get`.

    Args:
        reference (:class:`~google.cloud.firestore_v1.document.DocumentReference`):
            A document reference corresponding to the document that contains
            the data in this snapshot.
        data (Dict[str, Any]):
            The data retrieved in the snapshot.
        exists (bool):
            Indicates if the document existed at the time the snapshot was
            retrieved.
        read_time (:class:`proto.datetime_helpers.DatetimeWithNanoseconds`):
            The time that this snapshot was read from the server.
        create_time (:class:`proto.datetime_helpers.DatetimeWithNanoseconds`):
            The time that this document was created.
        update_time (:class:`proto.datetime_helpers.DatetimeWithNanoseconds`):
            The time that this document was last updated.
    r   Nc                 C   s.   || _ t|| _|| _|| _|| _|| _d S r-   )
_referencecopydeepcopy_data_exists	read_timecreate_timeupdate_time)r   	referencedataexistsr~   r   r   r   r   r   r   m  s   
zDocumentSnapshot.__init__c                 C   s(   t || jstS | j|jko| j|jkS r-   )r&   r   r'   ry   r|   r(   r   r   r   r*   y  s   zDocumentSnapshot.__eq__c                 C   r,   r-   )r.   ry   r   r/   r   r   r   r0   ~  r1   zDocumentSnapshot.__hash__c                 C      | j jS )zThe client that owns the document reference for this snapshot.

        Returns:
            :class:`~google.cloud.firestore_v1.client.Client`:
            The client that owns this document.
        )ry   r   r/   r   r   r   r     s   zDocumentSnapshot._clientc                 C      | j S )zExistence flag.

        Indicates if the document existed at the time this snapshot
        was retrieved.

        Returns:
            bool: The existence flag.
        )r}   r/   r   r   r   r     s   
zDocumentSnapshot.existsc                 C   r   )zThe document identifier (within its collection).

        Returns:
            str: The last component of the path of the document.
        )ry   r9   r/   r   r   r   r9     s   zDocumentSnapshot.idc                 C   r   )zDocument reference corresponding to document that owns this data.

        Returns:
            :class:`~google.cloud.firestore_v1.document.DocumentReference`:
            A document reference corresponding to this document.
        )ry   r/   r   r   r   r     s   zDocumentSnapshot.referencer   c                 C   s"   | j sdS t|| j}t|S )aN  Get a value from the snapshot data.

        If the data is nested, for example:

        .. code-block:: python

           >>> snapshot.to_dict()
           {
               'top1': {
                   'middle2': {
                       'bottom3': 20,
                       'bottom4': 22,
                   },
                   'middle5': True,
               },
               'top6': b'  foo',
           }

        a **field path** can be used to access the nested data. For
        example:

        .. code-block:: python

           >>> snapshot.get('top1')
           {
               'middle2': {
                   'bottom3': 20,
                   'bottom4': 22,
               },
               'middle5': True,
           }
           >>> snapshot.get('top1.middle2')
           {
               'bottom3': 20,
               'bottom4': 22,
           }
           >>> snapshot.get('top1.middle2.bottom3')
           20

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

        A copy is returned since the data may contain mutable values,
        but the data stored in the snapshot must remain immutable.

        Args:
            field_path (str): A field path (``.``-delimited list of
                field names).

        Returns:
            Any or None:
                (A copy of) the value stored for the ``field_path`` or
                None if snapshot document does not exist.

        Raises:
            KeyError: If the ``field_path`` does not match nested data
                in the snapshot.
        N)r}   field_path_moduleget_nested_valuer|   rz   r{   )r   r   nested_datar   r   r   rf     s   ;
zDocumentSnapshot.getc                 C   s   | j sdS t| jS )a[  Retrieve the data contained in this snapshot.

        A copy is returned since the data may contain mutable values,
        but the data stored in the snapshot must remain immutable.

        Returns:
            Dict[str, Any] or None:
                The data in the snapshot.  Returns None if reference
                does not exist.
        N)r}   rz   r{   r|   r/   r   r   r   to_dict  s   zDocumentSnapshot.to_dictc                 C   s
   t | S r-   )r   document_snapshot_to_protobufr/   r   r   r   _to_protobuf  s   
zDocumentSnapshot._to_protobufrl   )rm   rn   ro   rp   r   r*   r0   rq   r   r   r9   r   r`   r	   rf   r   r
   r   r   r   r   r   r   r   r   re   Q  s$    

	


	@re   r   r   c                 C   s   | j df| }tj|S )a  Convert a path tuple into a full path string.

    Of the form:

        ``projects/{project_id}/databases/{database_id}/...
              documents/{document_path}``

    Args:
        client (:class:`~google.cloud.firestore_v1.client.Client`):
            The client that holds configuration details and a GAPIC client
            object.
        path (Tuple[str, ...]): The components in a document path.

    Returns:
        str: The fully-qualified document path.
    r^   )rX   r   DOCUMENT_PATH_DELIMITERr4   )r   r   partsr   r   r   r6     s   r6   c                 C   s(   t | }t|dkrtd|d|d S )aB  Consume a gRPC stream that should contain a single response.

    The stream will correspond to a ``BatchGetDocuments`` request made
    for a single document.

    Args:
        response_iterator (~google.cloud.exceptions.GrpcRendezvous): A
            streaming iterator returned from a ``BatchGetDocuments``
            request.

    Returns:
        ~google.cloud.proto.firestore.v1.            firestore.BatchGetDocumentsResponse: The single "get"
        response in the batch.

    Raises:
        ValueError: If anything other than exactly one response is returned.
       z4Unexpected response from `BatchGetDocumentsResponse`zExpected only one resultr   )listlenr5   )response_iteratorall_responsesr   r   r   _consume_single_get  s   r   write_resultsc                 C   s   | st d| d S )a  Get first write result from list.

    For cases where ``len(write_results) > 1``, this assumes the writes
    occurred at the same time (e.g. if an update and transform are sent
    at the same time).

    Args:
        write_results (List[google.cloud.proto.firestore.v1.            write.WriteResult, ...]: The write results from a
            ``CommitResponse``.

    Returns:
        google.cloud.firestore_v1.types.WriteResult: The
        lone write result from ``write_results``.

    Raises:
        ValueError: If there are zero write results. This is likely to
            **never** occur, since the backend should be stable.
    z"Expected at least one write resultr   )r5   )r   r   r   r   _first_write_result1  s   r   ) rp   rz   google.api_corer   rs   google.cloud.firestore_v1.typesr   google.cloud.firestore_v1r   r   r   r   r   r   typingr	   r
   r   r   r   r   r   objectr   re   r`   r6   BatchGetDocumentsResponser   r   WriteResultr   r   r   r   r   <module>   s$   $  3 -