U
    >i-                     @  s   d Z ddlmZ ddl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mZ ddlmZmZ ddlmZ erdd	lm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AsyncGeneratorOptionalTuple)gapic_v1)retry_async)async_aggregationasync_documentasync_queryasync_vector_querytransaction)BaseCollectionReference_item_to_document_ref)DocumentReference)AsyncStreamGenerator)DocumentSnapshot)ExplainOptions)QueryResultsListc                      s  e Zd ZdZdd fddZddddZd	dd
dZddddZddddZde	j
jdfddddddddZd0ddd fddZde	j
jdfd ddd!d"d#d$Zde	j
jdfdd%d&dd'd(d)d*d+d,Zde	j
jdfdd%d&dd'd(d-d*d.d/Z  ZS )1AsyncCollectionReferencea  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.
    None)returnc                   s   t t| j|| d S N)superr   __init__)selfpathkwargs	__class__ N/tmp/pip-unpacked-wheel-599y42ri/google/cloud/firestore_v1/async_collection.pyr   E   s    z!AsyncCollectionReference.__init__zasync_query.AsyncQueryc                 C  s
   t | S )zeQuery factory.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`
        )r   
AsyncQueryr   r!   r!   r"   _queryH   s    zAsyncCollectionReference._queryz'async_aggregation.AsyncAggregationQueryc                 C  s   t |  S )zAsyncAggregationQuery factory.

        Returns:
            :class:`~google.cloud.firestore_v1.async_aggregation.AsyncAggregationQuery
        )r
   ZAsyncAggregationQueryr%   r$   r!   r!   r"   _aggregation_queryP   s    z+AsyncCollectionReference._aggregation_queryz#async_vector_query.AsyncVectorQueryc                 C  s   t |  S )zAsyncVectorQuery factory.

        Returns:
            :class:`~google.cloud.firestore_v1.async_vector_query.AsyncVectorQuery`
        )r   ZAsyncVectorQueryr%   r$   r!   r!   r"   _vector_queryX   s    z&AsyncCollectionReference._vector_queryint)
chunk_sizec                 C s(   |   |2 z3 d H W }|V  q6 d S r   )r%   	_chunkify)r   r)   pager!   r!   r"   r*   `   s    z"AsyncCollectionReference._chunkifyNdictz
str | Nonez"retries.AsyncRetry | object | Nonezfloat | NonezTuple[Any, Any])document_datadocument_idretrytimeoutr   c                   s2   |  ||||\}}|j|f|I dH }|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.async_document.AsyncDocumentReference`]:
                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   r-   r.   r/   r0   Zdocument_refr   Zwrite_resultr!   r!   r"   addd   s    "zAsyncCollectionReference.addz%async_document.AsyncDocumentReference)r.   r   c                   s   t t| |S )a  Create a sub-document underneath the current collection.

        Args:
            document_id (Optional[str]): The document identifier
                within the current collection. If not provided, will default
                to a random 20 character string composed of digits,
                uppercase and lowercase and letters.

        Returns:
            :class:`~google.cloud.firestore_v1.document.async_document.AsyncDocumentReference`:
            The child document.
        )r   r   document)r   r.   r   r!   r"   r3      s    z!AsyncCollectionReference.documentz
int | Nonez'AsyncGenerator[DocumentReference, None])	page_sizer/   r0   r   c                 C sZ   |  |||\}}| jjjf || jjd|I dH }|2 z3 dH W }t| |V  q:6 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metadataN)Z_prep_list_documentsZ_clientZ_firestore_apilist_documentsZ_rpc_metadatar   )r   r4   r/   r0   r5   r   iteratorir!   r!   r"   r7      s    
z'AsyncCollectionReference.list_documents)explain_optionsz!Optional[transaction.Transaction]zOptional[float]zOptional[ExplainOptions]z"QueryResultsList[DocumentSnapshot])r   r/   r0   r:   r   c                  s:   |  ||\}}|dk	r ||d< |jf d|i|I dH 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`]):
                An existing transaction that this 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 (Otional[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.
        Nr:   r   )_prep_get_or_streamgetr   r   r/   r0   r:   queryr   r!   r!   r"   r<      s    "zAsyncCollectionReference.getz&AsyncStreamGenerator[DocumentSnapshot]c                C  s0   |  ||\}}|r||d< |jf d|i|S )a%  Read the documents in this collection.

        This sends a ``RunQuery`` RPC and then returns a generator 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`]):
                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:
            `AsyncStreamGenerator[DocumentSnapshot]`: A generator of the query
            results.
        r:   r   )r;   streamr=   r!   r!   r"   r?      s    +zAsyncCollectionReference.stream)N)__name__
__module____qualname____doc__r   r%   r&   r'   r*   r   methodDEFAULTr2   r3   r7   r<   r?   __classcell__r!   r!   r   r"   r   +   s8   , #*r   N)"rC   
__future__r   typingr   r   r   r   r   Zgoogle.api_corer   r	   retriesZgoogle.cloud.firestore_v1r
   r   r   r   r   Z)google.cloud.firestore_v1.base_collectionr   r   Z"google.cloud.firestore_v1.documentr   Z0google.cloud.firestore_v1.async_stream_generatorr   Z'google.cloud.firestore_v1.base_documentr   Z'google.cloud.firestore_v1.query_profiler   Z'google.cloud.firestore_v1.query_resultsr   r#   r   r!   r!   r!   r"   <module>   s   