o
     ij.                     @  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 ddlmZ ddlmZmZ dd	lmZmZ dd
lmZ ddlmZ erdd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)query)transactionvector_query)BaseCollectionReference_item_to_document_ref)QueryResultsList)Watch)DocumentSnapshot)ExplainOptions)StreamGeneratorc                      s   e Zd ZdZd6 fddZd7ddZd8d
dZd9ddZdej	j
dfd:ddZdej	j
dfd;ddZd<d"d#Zdej	j
dfdd$d=d*d+Zdej	j
dfdd$d>d/d0Zd?d4d5Z  ZS )@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__ /var/www/snowflake_co_dev_github/snow_flake_back_end_deploy/env/lib/python3.10/site-packages/google/cloud/firestore_v1/collection.pyr   A   s   zCollectionReference.__init__query_mod.Queryc                 C  s
   t | S )zeQuery factory.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`
        )	query_modQueryr   r#   r#   r$   _queryD   s   
zCollectionReference._queryaggregation.AggregationQueryc                 C     t |  S )zAggregationQuery factory.

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

        Returns:
            :class:`~google.cloud.firestore_v1.vector_query.VectorQuery`
        )r   VectorQueryr)   r(   r#   r#   r$   _vector_queryT   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.
        )	_prep_addcreateupdate_time)r   r2   r4   r   r7   document_refr    write_resultr#   r#   r$   add\   s   "
zCollectionReference.add	page_sizeUnion[int, None]Generator[Any, Any, None]c                   sB     |||\}} 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.

        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#   )_prep_list_documents_client_firestore_apilist_documents_rpc_metadata)r   r@   r   r7   rC   r    iteratorr#   r(   r$   rK      s   
z"CollectionReference.list_documents
chunk_sizeintc                 C  s   |   |S r   )r)   	_chunkify)r   rN   r#   r#   r$   rP      s   zCollectionReference._chunkify)explain_optionsr   $Union[transaction.Transaction, None]rQ   Optional[ExplainOptions]"QueryResultsList[DocumentSnapshot]c                C  s4   |  ||\}}|dur||d< |jdd|i|S )a  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.

        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.
        NrQ   r   r#   )_prep_get_or_streamgetr   r   r   r7   rQ   r   r    r#   r#   r$   rV      s   "zCollectionReference.get!Optional[transaction.Transaction]Optional[float]!StreamGenerator[DocumentSnapshot]c                C  s0   |  ||\}}|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.

        Returns:
            `StreamGenerator[DocumentSnapshot]`: A generator of the query results.
        rQ   r   Nr#   )rU   streamrW   r#   r#   r$   r[      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()
        )r)   r   	for_queryr   r   )r   r\   r   r#   r#   r$   on_snapshot  s   zCollectionReference.on_snapshot)r   r   )r   r%   )r   r*   )r   r/   )
r2   r3   r4   r5   r   r6   r7   r8   r   r9   )r@   rA   r   r6   r7   r8   r   rB   )rN   rO   )
r   rR   r   r6   r7   r8   rQ   rS   r   rT   )
r   rX   r   r6   r7   rY   rQ   rS   r   rZ   )r\   r   r   r   )__name__
__module____qualname____doc__r   r)   r-   r1   r
   methodDEFAULTr?   rK   rP   rV   r[   r^   __classcell__r#   r#   r!   r$   r   '   s8    


-
 *0r   N)%rb   
__future__r   typingr   r   r   r   r   r   r	   google.api_corer
   r   retriesgoogle.cloud.firestore_v1r   r   r   r&   r   r   )google.cloud.firestore_v1.base_collectionr   r   'google.cloud.firestore_v1.query_resultsr   google.cloud.firestore_v1.watchr   'google.cloud.firestore_v1.base_documentr   'google.cloud.firestore_v1.query_profiler   *google.cloud.firestore_v1.stream_generatorr   r'   r   r#   r#   r#   r$   <module>   s    $