U
    >iX                     @  s:  d Z ddlmZ ddlZddlmZmZmZmZ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 er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" 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Z/G dd dee Z0ddddZ1ddddZ2dS )zHClasses for representing collections for the Google Cloud Firestore API.    )annotationsN)TYPE_CHECKINGAnyAsyncGeneratorAsyncIterator	Coroutine	GeneratorGenericIterableSequenceTupleUnionOptional)retry)_helpers)	QueryType)BaseAggregationQuery)DocumentSnapshot)BaseVectorQueryDistanceMeasure)DocumentReference)	FieldPath)ExplainOptions)QueryResultsList)StreamGenerator)Transaction)Vector)VectorQueryZ>ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789c                	   @  s>  e Zd ZdZddddZdd Zedd	 Zed
d ZddddZ	ddddZ
ddddZdqdddddZddddZdrdddd d!d"d#d$Zdsdddd d%d"d&d'Zdtd(dd d)d*d+d,Zdud(dd d-d*d.d/Zddd0d1Zd2dd3d4d5Zdvdd6dddd7d8d9Zd:dd;d<d=Zd>dd?d@dAZd>dBdCdDZd>ddEdFdGZdHddIdJdKZdHddIdLdMZdHddIdNdOZdHddIdPdQZdwdd dRdSdTdUZdxddVdWdd dXdYdZd[d\ZdyddVdWdd dXd]dZd^d_Zd`da Z dzdbdcZ!d{dddedfdgZ"d|dddedhdiZ#dddjd:dkd>dldd dmdndodpZ$dS )}BaseCollectionReferencea  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                 O  s6   t j|dd || _|dd | _|r2td|dd S )NT)Zis_collectionclientzReceived unexpected argumentszOnly `client` is supported)r   Zverify_path_pathpop_client	TypeError)selfpathkwargs r*   M/tmp/pip-unpacked-wheel-599y42ri/google/cloud/firestore_v1/base_collection.py__init__U   s      z BaseCollectionReference.__init__c                 C  s(   t || jstS | j|jko&| j|jkS N)
isinstance	__class__NotImplementedr#   r%   )r'   otherr*   r*   r+   __eq__^   s    zBaseCollectionReference.__eq__c                 C  s
   | j d S )zfThe collection identifier.

        Returns:
            str: The last component of the path.
        )r#   r'   r*   r*   r+   idc   s    zBaseCollectionReference.idc                 C  s,   t | jdkrdS | jdd }| jj| S )a  Document that owns the current collection.

        Returns:
            Optional[:class:`~google.cloud.firestore_v1.document.DocumentReference`]:
            The parent document, if the current collection is not a
            top-level collection.
           Nr3   )lenr#   r%   document)r'   parent_pathr*   r*   r+   parentl   s    	zBaseCollectionReference.parentr   c                 C  s   t d S r-   NotImplementedErrorr4   r*   r*   r+   _query{   s    zBaseCollectionReference._queryr   c                 C  s   t d S r-   r;   r4   r*   r*   r+   _aggregation_query~   s    z*BaseCollectionReference._aggregation_queryr   c                 C  s   t d S r-   r;   r4   r*   r*   r+   _vector_query   s    z%BaseCollectionReference._vector_queryNzOptional[str]r   )document_idr!   c                 C  s6   |dkrt  }| jd r$| j|f n|f}| jj| 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.DocumentReference`:
            The child document.
        Nr   )_auto_idr#   r%   r8   )r'   r@   Z
child_pathr*   r*   r+   r8      s    z BaseCollectionReference.documentzTuple[Any, str]c                 C  sD   | j }|dkr$tj| jjdf}n|j}tj|| jf}||fS )ar  Get fully-qualified parent path and prefix for this collection.

        Returns:
            Tuple[str, str]: Pair of

            * the fully-qualified (with database and project) path to the
              parent of this collection (will either be the database path
              or a document path).
            * the prefix to a document in this collection.
        NZ	documents)r:   r   DOCUMENT_PATH_DELIMITERjoinr%   Z_database_stringZ_document_pathr5   )r'   Z
parent_docr9   Zexpected_prefixr*   r*   r+   _parent_info   s    
z$BaseCollectionReference._parent_infodictz2retries.Retry | retries.AsyncRetry | object | NonezOptional[float]zTuple[DocumentReference, dict])document_datar@   r   timeoutr!   c                 C  s,   |dkrt  }| |}t||}||fS )z+Shared setup for async / sync :method:`add`N)rA   r8   r   make_retry_timeout_kwargs)r'   rF   r@   r   rG   Zdocument_refr)   r*   r*   r+   	_prep_add   s
    
z!BaseCollectionReference._prep_addz<Union[Tuple[Any, Any], Coroutine[Any, Any, Tuple[Any, Any]]]c                 C  s   t d S r-   r;   )r'   rF   r@   r   rG   r*   r*   r+   add   s    zBaseCollectionReference.addzOptional[int]zTuple[dict, dict])	page_sizer   rG   r!   c                 C  s6   |   \}}|| j|dddid}t||}||fS )z6Shared setup for async / sync :method:`list_documents`Tfield_pathsN)r:   Zcollection_idrK   Zshow_missingmask)rD   r5   r   rH   )r'   rK   r   rG   r:   _requestr)   r*   r*   r+   _prep_list_documents   s    
z,BaseCollectionReference._prep_list_documentszUUnion[Generator[DocumentReference, Any, Any], AsyncGenerator[DocumentReference, Any]]c                 C  s   t d S r-   r;   )r'   rK   r   rG   r*   r*   r+   list_documents   s    z&BaseCollectionReference.list_documentsc                 C  s   |    S r-   )r=   	recursiver4   r*   r*   r+   rR      s    z!BaseCollectionReference.recursivezIterable[str])rL   r!   c                 C  s   |   }||S )a  Create a "select" query with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.select` for
        more information on this method.

        Args:
            field_paths (Iterable[str, ...]): An iterable of field paths
                (``.``-delimited list of field names) to use as a projection
                of document fields in the query results.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A "projected" query.
        )r=   select)r'   rL   queryr*   r*   r+   rS      s    zBaseCollectionReference.selectfilter)
field_path	op_stringr!   c                C  s~   |   }|rn|rn|dk	r td|dkr`|dkr`g }|D ]"}t|trP| |}|| q8|}||||S |j|dS dS )a  Create a "where" query with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.where` for
        more information on this method.

        Args:
            field_path (str): A field path (``.``-delimited list of
                field names) for the field to filter on. Optional.
            op_string (str): A comparison operation in the form of a string.
                Acceptable values are ``<``, ``<=``, ``==``, ``>=``, ``>``,
                and ``in``. Optional.
            value (Any): The value to compare the field against in the filter.
                If ``value`` is :data:`None` or a NaN, then ``==`` is the only
                allowed operation.  If ``op_string`` is ``in``, ``value``
                must be a sequence of values. Optional.
            filter (class:`~google.cloud.firestore_v1.base_query.BaseFilter`): an instance of a Filter.
                Either a FieldFilter or a CompositeFilter.
        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A filtered query.
        Raises:
            ValueError, if both the positional arguments (field_path, op_string, value)
                and the filter keyword argument are passed at the same time.
        NzICan't pass in both the positional arguments and 'filter' at the same time__name__inrU   )r=   
ValueErrorr.   strr8   appendwhere)r'   rW   rX   valuerV   rT   Zwrapped_namesnamer*   r*   r+   r^      s    !

zBaseCollectionReference.wherer\   )rW   r!   c                 K  s   |   }|j|f|S )a  Create an "order by" query with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.order_by` for
        more information on this method.

        Args:
            field_path (str): A field path (``.``-delimited list of
                field names) on which to order the query results.
            kwargs (Dict[str, Any]): The keyword arguments to pass along
                to the query. The only supported keyword is ``direction``,
                see :meth:`~google.cloud.firestore_v1.query.Query.order_by`
                for more information.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            An "order by" query.
        )r=   order_by)r'   rW   r)   rT   r*   r*   r+   ra   4  s    z BaseCollectionReference.order_byint)countr!   c                 C  s   |   }||S )a-  Create a limited query with this collection as parent.

        .. note::
           `limit` and `limit_to_last` are mutually exclusive.
           Setting `limit` will drop previously set `limit_to_last`.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.limit` for
        more information on this method.

        Args:
            count (int): Maximum number of documents to return that match
                the query.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A limited query.
        )r=   limitr'   rc   rT   r*   r*   r+   rd   J  s    zBaseCollectionReference.limit)rc   c                 C  s   |   }||S )aD  Create a limited to last query with this collection as parent.

        .. note::
           `limit` and `limit_to_last` are mutually exclusive.
           Setting `limit_to_last` will drop previously set `limit`.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.limit_to_last`
        for more information on this method.

        Args:
            count (int): Maximum number of documents to return that
                match the query.
        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A limited to last query.
        )r=   limit_to_lastre   r*   r*   r+   rf   `  s    z%BaseCollectionReference.limit_to_last)num_to_skipr!   c                 C  s   |   }||S )a  Skip to an offset in a query with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.offset` for
        more information on this method.

        Args:
            num_to_skip (int): The number of results to skip at the beginning
                of query results. (Must be non-negative.)

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            An offset query.
        )r=   offset)r'   rg   rT   r*   r*   r+   rh   u  s    zBaseCollectionReference.offsetz*Union[DocumentSnapshot, dict, list, tuple])document_fieldsr!   c                 C  s   |   }||S )a  Start query at a cursor with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.start_at` for
        more information on this method.

        Args:
            document_fields (Union[:class:`~google.cloud.firestore_v1.                document.DocumentSnapshot`, dict, list, tuple]):
                A document snapshot or a dictionary/list/tuple of fields
                representing a query results cursor. A cursor is a collection
                of values that represent a position in a query result set.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A query with cursor.
        )r=   start_atr'   ri   rT   r*   r*   r+   rj     s    z BaseCollectionReference.start_atc                 C  s   |   }||S )a  Start query after a cursor with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.start_after` for
        more information on this method.

        Args:
            document_fields (Union[:class:`~google.cloud.firestore_v1.                document.DocumentSnapshot`, dict, list, tuple]):
                A document snapshot or a dictionary/list/tuple of fields
                representing a query results cursor. A cursor is a collection
                of values that represent a position in a query result set.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A query with cursor.
        )r=   start_afterrk   r*   r*   r+   rl     s    z#BaseCollectionReference.start_afterc                 C  s   |   }||S )a  End query before a cursor with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.end_before` for
        more information on this method.

        Args:
            document_fields (Union[:class:`~google.cloud.firestore_v1.                document.DocumentSnapshot`, dict, list, tuple]):
                A document snapshot or a dictionary/list/tuple of fields
                representing a query results cursor. A cursor is a collection
                of values that represent a position in a query result set.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A query with cursor.
        )r=   
end_beforerk   r*   r*   r+   rm     s    z"BaseCollectionReference.end_beforec                 C  s   |   }||S )a  End query at a cursor with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.end_at` for
        more information on this method.

        Args:
            document_fields (Union[:class:`~google.cloud.firestore_v1.                document.DocumentSnapshot`, dict, list, tuple]):
                A document snapshot or a dictionary/list/tuple of fields
                representing a query results cursor. A cursor is a collection
                of values that represent a position in a query result set.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A query with cursor.
        )r=   end_atrk   r*   r*   r+   rn     s    zBaseCollectionReference.end_atzTuple[Any, dict])r   rG   r!   c                 C  s   |   }t||}||fS )z:Shared setup for async / sync :meth:`get` / :meth:`stream`)r=   r   rH   )r'   r   rG   rT   r)   r*   r*   r+   _prep_get_or_stream  s    z+BaseCollectionReference._prep_get_or_stream)explain_optionszOptional[Transaction]zOptional[ExplainOptions]z\QueryResultsList[DocumentSnapshot] | Coroutine[Any, Any, QueryResultsList[DocumentSnapshot]])transactionr   rG   rp   r!   c                C  s   t d S r-   r;   r'   rq   r   rG   rp   r*   r*   r+   get  s    zBaseCollectionReference.getzCStreamGenerator[DocumentSnapshot] | AsyncIterator[DocumentSnapshot]c                C  s   t d S r-   r;   rr   r*   r*   r+   stream  s    zBaseCollectionReference.streamc                 C  s   t d S r-   r;   )r'   callbackr*   r*   r+   on_snapshot  s    z#BaseCollectionReference.on_snapshotc                 C  s   |   j|dS )z
        Adds a count over the nested query.

        :type alias: str
        :param alias: (Optional) The alias for the count
        alias)r>   rc   )r'   rx   r*   r*   r+   rc     s    zBaseCollectionReference.countzstr | FieldPath)	field_refc                 C  s   |   j||dS )a  
        Adds a sum over the nested query.

        :type field_ref: Union[str, google.cloud.firestore_v1.field_path.FieldPath]
        :param field_ref: The field to aggregate across.

        :type alias: Optional[str]
        :param alias: Optional name of the field to store the result of the aggregation into.
            If not provided, Firestore will pick a default name following the format field_<incremental_id++>.

        rw   )r>   sumr'   ry   rx   r*   r*   r+   rz     s    zBaseCollectionReference.sumc                 C  s   |   j||dS )a  
        Adds an avg over the nested query.

        :type field_ref: Union[str, google.cloud.firestore_v1.field_path.FieldPath]
        :param field_ref: The field to aggregate across.

        :type alias: Optional[str]
        :param alias: Optional name of the field to store the result of the aggregation into.
            If not provided, Firestore will pick a default name following the format field_<incremental_id++>.
        rw   )r>   avgr{   r*   r*   r+   r|     s    zBaseCollectionReference.avgdistance_result_fielddistance_thresholdzUnion[Vector, Sequence[float]]r   r   )vector_fieldquery_vectorrd   distance_measurer~   r   r!   c                C  s   |   j||||||dS )a  
        Finds the closest vector embeddings to the given query vector.

        Args:
            vector_field (str): An indexed vector field to search upon. Only documents which contain
                vectors whose dimensionality match the query_vector can be returned.
            query_vector(Union[Vector, Sequence[float]]): The query vector that we are searching on. Must be a vector of no more
                than 2048 dimensions.
            limit (int): The number of nearest neighbors to return. Must be a positive integer of no more than 1000.
            distance_measure (:class:`DistanceMeasure`): The Distance Measure to use.
            distance_result_field (Optional[str]):
                Name of the field to output the result of the vector distance calculation
            distance_threshold (Optional[float]):
                A threshold for which no less similar documents will be returned.

        Returns:
            :class`~firestore_v1.vector_query.VectorQuery`: the vector query.
        r}   )r?   find_nearest)r'   r   r   rd   r   r~   r   r*   r*   r+   r   ,  s    z$BaseCollectionReference.find_nearest)N)NNN)NNN)NNN)NNN)NNN)NN)NNN)NNN)N)N)N)%rY   
__module____qualname____doc__r,   r2   propertyr5   r:   r=   r>   r?   r8   rD   rI   rJ   rP   rQ   rR   rS   r^   ra   rd   rf   rh   rj   rl   rm   rn   ro   rs   rt   rv   rc   rz   r|   r   r*   r*   r*   r+   r   ;   s   	

            
   5        

	r   r\   r    c                   C  s   d dd tdD S )zGenerate a "random" automatically generated ID.

    Returns:
        str: A 20 character string composed of digits, uppercase and
        lowercase and letters.
     c                 s  s   | ]}t tV  qd S r-   )randomchoice_AUTO_ID_CHARS).0rN   r*   r*   r+   	<genexpr>Z  s     z_auto_id.<locals>.<genexpr>   )rC   ranger*   r*   r*   r+   rA   R  s    rA   r   c                 C  s   |j tjd }| |S )zConvert Document resource to document ref.

    Args:
        collection_reference (google.api_core.page_iterator.GRPCIterator):
            iterator response
        item (dict): document resource
    r3   )r`   splitr   rB   r8   )Zcollection_referenceitemr@   r*   r*   r+   _item_to_document_ref]  s    r   )3r   
__future__r   r   typingr   r   r   r   r   r   r	   r
   r   r   r   r   Zgoogle.api_corer   retriesZgoogle.cloud.firestore_v1r   Z$google.cloud.firestore_v1.base_queryr   Z*google.cloud.firestore_v1.base_aggregationr   Z'google.cloud.firestore_v1.base_documentr   Z+google.cloud.firestore_v1.base_vector_queryr   r   Z"google.cloud.firestore_v1.documentr   Z$google.cloud.firestore_v1.field_pathr   Z'google.cloud.firestore_v1.query_profiler   Z'google.cloud.firestore_v1.query_resultsr   Z*google.cloud.firestore_v1.stream_generatorr   Z%google.cloud.firestore_v1.transactionr   Z google.cloud.firestore_v1.vectorr   Z&google.cloud.firestore_v1.vector_queryr   r   r   rA   r   r*   r*   r*   r+   <module>   s4   8    