o
    ,=jŸ4  ã                   @  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mZ dd	lmZ dd
lmZ erdddlZddlmZ ddl m!Z! ddl"m#Z# G dd„ deej$ ƒZ%dS )zHClasses for representing collections for the Google Cloud Firestore API.é    )Úannotations)ÚTYPE_CHECKINGÚAnyÚCallableÚ	GeneratorÚOptionalÚTupleÚUnion)Úgapic_v1)Úretry)ÚaggregationÚdocumentÚtransactionÚvector_query)Úquery)ÚBaseCollectionReferenceÚ_item_to_document_ref)ÚQueryResultsList)ÚWatchN)ÚDocumentSnapshot)ÚExplainOptions)ÚStreamGeneratorc                      sÂ   e Zd ZdZd9‡ fdd„Zd:dd„Zd;d
d„Zd<dd„Zdej	j
dfd=dd„Zdej	j
dfddœd>d!d"„Zd?d%d&„Zdej	j
dfddd'œd@d-d.„Zdej	j
dfddd'œdAd2d3„ZdBd7d8„Z‡  ZS )CÚCollectionReferencea  A reference to a collection in a Firestore database.

    The collection may already exist or this class can facilitate creation
    of documents within the collection.

    Args:
        path (Tuple[str, ...]): The components in the collection 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.
        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` if provided. It
            represents the client that created this collection 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.
    ÚreturnÚNonec                   s   t t| ƒj|i |¤Ž d S ©N)Úsuperr   Ú__init__)ÚselfÚpathÚkwargs©Ú	__class__© únC:\Users\psant\Downloads\Anu Raj Backend\school\venv\Lib\site-packages\google/cloud/firestore_v1/collection.pyr   C   s   zCollectionReference.__init__úquery_mod.Queryc                 C  s
   t  | ¡S )zeQuery factory.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`
        N)Ú	query_modÚQuery©r   r#   r#   r$   Ú_queryF   s   
zCollectionReference._queryúaggregation.AggregationQueryc                 C  ó   t  |  ¡ ¡S )z‡AggregationQuery factory.

        Returns:
            :class:`~google.cloud.firestore_v1.aggregation_query.AggregationQuery`
        N)r   ZAggregationQueryr)   r(   r#   r#   r$   Ú_aggregation_queryN   ó   z&CollectionReference._aggregation_queryúvector_query.VectorQueryc                 C  r+   )zxVectorQuery factory.

        Returns:
            :class:`~google.cloud.firestore_v1.vector_query.VectorQuery`
        N)r   ZVectorQueryr)   r(   r#   r#   r$   Ú_vector_queryV   r-   z!CollectionReference._vector_queryNÚdocument_dataÚdictÚdocument_idúUnion[str, None]r   úretries.Retry | object | NoneÚtimeoutúUnion[float, None]úTuple[Any, Any]c                 C  s0   |   ||||¡\}}|j|fi |¤Ž}|j|fS )a  Create a document in the Firestore database with the provided data.

        Args:
            document_data (dict): Property names and values to use for
                creating the document.
            document_id (Optional[str]): The document identifier within the
                current collection. If not provided, an ID will be
                automatically assigned by the server (the assigned ID will be
                a random 20 character string composed of digits,
                uppercase and lowercase letters).
            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:
            Tuple[:class:`google.protobuf.timestamp_pb2.Timestamp`,                 :class:`~google.cloud.firestore_v1.document.DocumentReference`]:
                Pair of

                * The ``update_time`` when the document was created/overwritten.
                * A document reference for the created document.

        Raises:
            :class:`google.cloud.exceptions.Conflict`:
                If ``document_id`` is provided and the document already exists.
        N)Z	_prep_addÚcreateZupdate_time)r   r0   r2   r   r5   Zdocument_refr    Zwrite_resultr#   r#   r$   Úadd^   s   "ü
zCollectionReference.add)Ú	read_timeÚ	page_sizeúUnion[int, None]r:   úOptional[datetime.datetime]úGenerator[Any, Any, None]c                  sD   ˆ   ||||¡\}}ˆ jjjd|ˆ jjdœ|¤Ž}‡ fdd„|D ƒS )aý  List all subdocuments of the current collection.

        Args:
            page_size (Optional[int]]): The maximum number of documents
                in each page of results from this request. Non-positive values
                are ignored. Defaults to a sensible value set by the API.
            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.DocumentReference`]:
                iterator of subdocuments of the current collection. If the
                collection does not exist at the time of `snapshot`, the
                iterator will be empty
        )ÚrequestÚmetadatac                 3  s   � | ]}t ˆ |ƒV  qd S r   )r   )Ú.0Úir(   r#   r$   Ú	<genexpr>¯   s   € z5CollectionReference.list_documents.<locals>.<genexpr>Nr#   )Z_prep_list_documentsZ_clientZ_firestore_apiÚlist_documentsZ_rpc_metadata)r   r;   r   r5   r:   r?   r    Úiteratorr#   r(   r$   rD   ‰   s   ÿ
þýz"CollectionReference.list_documentsÚ
chunk_sizeÚintc                 C  s   |   ¡  |¡S r   )r)   Ú	_chunkify)r   rF   r#   r#   r$   rH   ±   s   zCollectionReference._chunkify)Úexplain_optionsr:   r   ú$Union[transaction.Transaction, None]rI   úOptional[ExplainOptions]ú"QueryResultsList[DocumentSnapshot]c                C  sD   |   ||¡\}}|dur||d< |dur||d< |jdd|i|¤ŽS )as  Read the documents in this collection.

        This sends a ``RunQuery`` RPC and returns a list of documents
        returned in the stream of ``RunQueryResponse`` messages.

        Args:
            transaction
                (Optional[:class:`~google.cloud.firestore_v1.transaction.transaction.Transaction`]):
                An existing transaction that this query will run 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.
            explain_options
                (Optional[:class:`~google.cloud.firestore_v1.query_profile.ExplainOptions`]):
                Options to enable query profiling for this query. When set,
                explain_metrics will be available on the returned generator.
            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.

        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).

        Returns:
            QueryResultsList[DocumentSnapshot]: The documents in this collection
            that match the query.
        NrI   r:   r   r#   )Ú_prep_get_or_streamÚget©r   r   r   r5   rI   r:   r   r    r#   r#   r$   rN   ´   s   'zCollectionReference.getú!Optional[transaction.Transaction]úOptional[float]ú!StreamGenerator[DocumentSnapshot]c                C  s@   |   ||¡\}}|r||d< |dur||d< |jdd|i|¤ŽS )a½  Read the documents in this collection.

        This sends a ``RunQuery`` RPC and then returns an iterator which
        consumes each document returned in the stream of ``RunQueryResponse``
        messages.

        .. note::

           The underlying stream of responses will time out after
           the ``max_rpc_timeout_millis`` value set in the GAPIC
           client configuration for the ``RunQuery`` API.  Snapshots
           not consumed from the iterator before that point will be lost.

        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:
            transaction (Optional[:class:`~google.cloud.firestore_v1.transaction.                transaction.Transaction`]):
                An existing transaction that the query will run in.
            retry (Optional[google.api_core.retry.Retry]): Designation of what
                errors, if any, should be retried.  Defaults to a
                system-specified policy.
            timeout (Optional[float]): The timeout for this request. Defaults
                to a system-specified value.
            explain_options
                (Optional[:class:`~google.cloud.firestore_v1.query_profile.ExplainOptions`]):
                Options to enable query profiling for this query. When set,
                explain_metrics will be available on the returned generator.
            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:
            `StreamGenerator[DocumentSnapshot]`: A generator of the query results.
        rI   Nr:   r   r#   )rM   ÚstreamrO   r#   r#   r$   rS   ã   s   /zCollectionReference.streamÚcallbackr   r   c                 C  s   |   ¡ }t ||tj¡S )aš  Monitor the documents in this collection.

        This starts a watch on this collection using a background thread. The
        provided callback is run on the snapshot of the documents.

        Args:
            callback (Callable[[:class:`~google.cloud.firestore.collection.CollectionSnapshot`], NoneType]):
                a callback to run when a change occurs.

        Example:
            from google.cloud import firestore_v1

            db = firestore_v1.Client()
            collection_ref = db.collection(u'users')

            def on_snapshot(collection_snapshot, changes, read_time):
                for doc in collection_snapshot.documents:
                    print(u'{} => {}'.format(doc.id, doc.to_dict()))

            # Watch this collection
            collection_watch = collection_ref.on_snapshot(on_snapshot)

            # Terminate this watch
            collection_watch.unsubscribe()
        N)r)   r   Z	for_queryr   r   )r   rT   r   r#   r#   r$   Úon_snapshot  s   zCollectionReference.on_snapshot)r   r   )r   r%   )r   r*   )r   r.   )
r0   r1   r2   r3   r   r4   r5   r6   r   r7   )
r;   r<   r   r4   r5   r6   r:   r=   r   r>   )rF   rG   )r   rJ   r   r4   r5   r6   rI   rK   r:   r=   r   rL   )r   rP   r   r4   r5   rQ   rI   rK   r:   r=   r   rR   )rT   r   r   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r)   r,   r/   r
   ÚmethodÚDEFAULTr9   rD   rH   rN   rS   rU   Ú__classcell__r#   r#   r!   r$   r   )   s@    


û-üú
(üù1üù7r   )&rY   Ú
__future__r   Útypingr   r   r   r   r   r   r	   Zgoogle.api_corer
   r   ÚretriesZgoogle.cloud.firestore_v1r   r   r   r   r   r&   Z)google.cloud.firestore_v1.base_collectionr   r   Z'google.cloud.firestore_v1.query_resultsr   Zgoogle.cloud.firestore_v1.watchr   ÚdatetimeZ'google.cloud.firestore_v1.base_documentr   Z'google.cloud.firestore_v1.query_profiler   Z*google.cloud.firestore_v1.stream_generatorr   r'   r   r#   r#   r#   r$   Ú<module>   s    $