U
    $FZh9^                     @  s0  d Z ddlmZ ddlmZmZmZmZmZm	Z	m
Z
mZmZ ddl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 dd
l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' ddl(m)Z) er
ddl*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0 G dd deZ1G dd de1eZ2dS )a+  Classes for representing queries for the Google Cloud Firestore API.

A :class:`~google.cloud.firestore_v1.query.Query` can be created directly from
a :class:`~google.cloud.firestore_v1.collection.Collection` and that can be
a more common way to create a query than direct usage of the constructor.
    )annotations)	TYPE_CHECKINGAnyCallable	GeneratorListOptionalSequenceTypeUnion)
exceptionsgapic_v1)retry)firestore_v1)aggregationtransaction)QueryResultsList)DocumentSnapshot)BaseCollectionGroup	BaseQueryQueryPartition,_collection_group_query_response_to_snapshot_enum_from_direction_query_response_to_snapshot)StreamGenerator)Vector)VectorQuery)Watch)DistanceMeasure)	FieldPath)ExplainMetricsExplainOptionsc                
      s:  e Zd ZdZd@dd fddZdejjdfdd	d
ddddddZdddddZ	dAddZ
dd Zddddddddddd d!d"ZdBd#d$d%d&d'ZdCd(d#d$d)d*d+ZdDd(d#d$d)d,d-Zdejjddfd.d
d/dd0d1d2d3Zdejjdfdd	d4d
d/dd5d1d6d7Zd8d9d:d;d<Zed=dd>d?Z  ZS )EQuerya
  Represents a query to the Firestore API.

    Instances of this class are considered immutable: all methods that
    would modify an instance instead return a new instance.

    Args:
        parent (:class:`~google.cloud.firestore_v1.collection.CollectionReference`):
            The collection that this query applies to.
        projection (Optional[:class:`google.cloud.firestore_v1.            query.StructuredQuery.Projection`]):
            A projection of document fields to limit the query results to.
        field_filters (Optional[Tuple[:class:`google.cloud.firestore_v1.            query.StructuredQuery.FieldFilter`, ...]]):
            The filters to be applied in the query.
        orders (Optional[Tuple[:class:`google.cloud.firestore_v1.            query.StructuredQuery.Order`, ...]]):
            The "order by" entries to use in the query.
        limit (Optional[int]):
            The maximum number of documents the query is allowed to return.
        offset (Optional[int]):
            The number of results to skip.
        start_at (Optional[Tuple[dict, bool]]):
            Two-tuple of :

            * a mapping of fields. Any field that is present in this mapping
              must also be present in ``orders``
            * an ``after`` flag

            The fields and the flag combine to form a cursor used as
            a starting point in a query result set. If the ``after``
            flag is :data:`True`, the results will start just after any
            documents which have fields matching the cursor, otherwise
            any matching documents will be included in the result set.
            When the query is formed, the document values
            will be used in the order given by ``orders``.
        end_at (Optional[Tuple[dict, bool]]):
            Two-tuple of:

            * a mapping of fields. Any field that is present in this mapping
              must also be present in ``orders``
            * a ``before`` flag

            The fields and the flag combine to form a cursor used as
            an ending point in a query result set. If the ``before``
            flag is :data:`True`, the results will end just before any
            documents which have fields matching the cursor, otherwise
            any matching documents will be included in the result set.
            When the query is formed, the document values
            will be used in the order given by ``orders``.
        all_descendants (Optional[bool]):
            When false, selects only collections that are immediate children
            of the `parent` specified in the containing `RunQueryRequest`.
            When true, selects all descendant collections.
    N FNonereturnc                   s*   t t| j|||||||||	|
|d d S N)parent
projectionfield_filtersorderslimitlimit_to_lastoffsetstart_atend_atall_descendants	recursive)superr"   __init__selfr(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   	__class__r#   f/home/aprabhat/apps/x.techxrdev.in/venv/lib/python3.8/site-packages/google/cloud/firestore_v1/query.pyr4   w   s    
zQuery.__init__)explain_optionsretries.Retry | object | NonezOptional[float]zOptional[ExplainOptions]z"QueryResultsList[DocumentSnapshot])r   timeoutr:   r&   c          
      C  s   d}| j }| j rB| jD ]$}t|jj| jkr0| jn| j|_qd| _ | j||||d}t|}	|rltt	|	}	|dkrzd}n|
 }t|	||S )a  Read the documents in the collection that match this query.

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

        Returns:
            QueryResultsList[DocumentSnapshot]: The documents in the collection
            that match this query.
        NFr   r   r<   r:   )Z_limit_to_lastZ_ordersr   	directionnameZ	ASCENDINGZ
DESCENDINGstreamlistreversedZget_explain_metricsr   )
r6   r   r   r<   r:   explain_metricsZis_limited_to_lastorderresultZresult_listr#   r#   r9   get   s.    !
z	Query.getintz-Generator[List[DocumentSnapshot], None, None])
chunk_sizer&   c           	      c  s   | j }d}|  }d }|||}||}|r:||}| }|rN|d }|t|7 }|V  t||k sx|r||krd S qd S )Nr   )Z_limitZ_copyZ_resolve_chunk_sizer,   start_afterrF   len)	r6   rH   Zmax_to_returnZnum_returnedoriginalZlast_document_chunk_sizeZ_qZ	snapshotsr#   r#   r9   	_chunkify   s&    

zQuery._chunkifyc           	      C  s<   |  ||||\}}}| jjjf || jjd|}||fS )!Helper method for :meth:`stream`.requestmetadata)Z_prep_stream_client_firestore_api	run_query_rpc_metadata)	r6   r   r   r<   r:   rQ   expected_prefixkwargsresponse_iteratorr#   r#   r9   _get_stream_iterator   s    

zQuery._get_stream_iteratorc                 C  s8   |dkr4|t jjkr*| jjj}|j}|j}||S dS )rO   NF)	r   methodDEFAULTrS   rT   Z
_transportrU   Z_retryZ
_predicate)r6   excr   r   	transportZgapic_callabler#   r#   r9   _retry_query_after_exception  s    

z"Query._retry_query_after_exception)distance_result_fielddistance_thresholdstrzUnion[Vector, Sequence[float]]r   zOptional[str]z-Type['firestore_v1.vector_query.VectorQuery'])vector_fieldquery_vectorr,   distance_measurer`   ra   r&   c                C  s   t | j||||||dS )a9  
        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(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. If unset then the distance will not be returned.
            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.
        )rc   rd   r,   re   r`   ra   )r   find_nearest)r6   rc   rd   r,   re   r`   ra   r#   r#   r9   rf     s    zQuery.find_nearestz
str | Nonez1Type['firestore_v1.aggregation.AggregationQuery'])aliasr&   c                 C  s   t | j|dS )a  
        Adds a count over the query.

        :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++>.
        rg   )r   AggregationQuerycount)r6   rg   r#   r#   r9   rj   >  s    
zQuery.countzstr | FieldPath)	field_refrg   r&   c                 C  s   t | j||dS )a  
        Adds a sum over the 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++>.
        rh   )r   ri   sumr6   rk   rg   r#   r#   r9   rl   J  s    z	Query.sumc                 C  s   t | j||dS )a  
        Adds an avg over the 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++>.
        rh   )r   ri   avgrm   r#   r#   r9   rn   Y  s    z	Query.avgz!Optional[transaction.Transaction]float | Nonez:Generator[DocumentSnapshot, Any, Optional[ExplainMetrics]])r   r   r<   r:   r&   c              
   c  s   d}|  ||||\}}d}zt|d}	W nZ tjk
r }
 z:| |
||rr| |}| |||\}}W Y 
qn W 5 d}
~
X Y nX |	dkrq|dkr|	jr|	j}| jrt|	| j	}nt
|	| j	|}|dk	r|}|V  q|S )a(  Internal method for stream(). Read the documents in the collection
        that match this query.

        Internal method for stream().
        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.

        Yields:
            DocumentSnapshot:
            The next document that fulfills the query.

        Returns:
            ([google.cloud.firestore_v1.types.query_profile.ExplainMetrtics | None]):
            The results of query profiling, if received from the service.
        N)rZ   nextr   ZGoogleAPICallErrorr_   rJ   rC   Z_all_descendantsr   Z_parentr   )r6   r   r   r<   r:   ZmetricsrY   rW   Zlast_snapshotresponser]   Z	new_query_Zsnapshotr#   r#   r9   _make_streamh  sL    0

   zQuery._make_streamztransaction.Transaction | Nonez!StreamGenerator[DocumentSnapshot]c                C  s   | j ||||d}t||S )a*  Read the documents in the collection that match this query.

        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 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 (Optinal[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.
        r=   )rs   r   )r6   r   r   r<   r:   Zinner_generatorr#   r#   r9   r@     s    *zQuery.streamr   r   )callbackr&   c                 C  s   t | |tS )a  Monitor the documents in this collection that match this query.

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

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

        Example:

        .. code-block:: python

            from google.cloud import firestore_v1

            db = firestore_v1.Client()
            query_ref = db.collection(u'users').where("user", "==", u'Ada')

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

            # Watch this query
            query_watch = query_ref.on_snapshot(on_snapshot)

            # Terminate this watch
            query_watch.unsubscribe()
        )r   Z	for_queryr   )r6   rt   r#   r#   r9   on_snapshot  s    zQuery.on_snapshotz3Type['firestore_v1.collection.CollectionReference']c                  C  s   ddl m}  | S )Nr   CollectionReference)Z$google.cloud.firestore_v1.collectionrw   rv   r#   r#   r9   _get_collection_reference_class  s    z%Query._get_collection_reference_class)
Nr#   r#   NFNNNFF)N)N)N)N)__name__
__module____qualname____doc__r4   r   r[   r\   rF   rN   rZ   r_   rf   rj   rl   rn   rs   r@   ru   staticmethodrx   __classcell__r#   r#   r7   r9   r"   ?   sX   :          B&
(   `2r"   c                
      sP   e Zd ZdZddd fdd	Zed
d Zejj	dfddddddZ
  ZS )CollectionGroupa}  Represents a Collection Group in the Firestore API.

    This is a specialization of :class:`.Query` that includes all documents in the
    database that are contained in a collection or subcollection of the given
    parent.

    Args:
        parent (:class:`~google.cloud.firestore_v1.collection.CollectionReference`):
            The collection that this query applies to.
    Nr#   FTr$   r%   c                   s*   t t| j|||||||||	|
|d d S r'   )r3   r   r4   r5   r7   r#   r9   r4   ,  s    
zCollectionGroup.__init__c                   C  s   t S )N)r"   r#   r#   r#   r9   _get_query_classH  s    z CollectionGroup._get_query_classr;   ro   z%Generator[QueryPartition, None, None])r   r<   r&   c           
      c  sv   |  |||\}}| jjjf || jjd|}d}|D ]*}| j|jd j}	t| ||	V  |	}q8t| |dV  dS )a	  Partition a query for parallelization.

        Partitions a query by returning partition cursors that can be used to run the
        query in parallel. The returned partition cursors are split points that can be
        used as starting/end points for the query results.

        Args:
            partition_count (int): The desired maximum number of partition points. The
                number must be strictly positive. The actual number of partitions
                returned may be fewer.
            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.
        rP   Nr   )	Z_prep_get_partitionsrS   rT   Zpartition_queryrV   ZdocumentvaluesZreference_valuer   )
r6   Zpartition_countr   r<   rQ   rX   pagerr/   Z	cursor_pbcursorr#   r#   r9   get_partitionsL  s    
zCollectionGroup.get_partitions)
Nr#   r#   NFNNNTF)ry   rz   r{   r|   r4   r}   r   r   r[   r\   r   r~   r#   r#   r7   r9   r      s"             
r   N)3r|   
__future__r   typingr   r   r   r   r   r   r	   r
   r   Zgoogle.api_corer   r   r   retriesZgoogle.cloudr   Zgoogle.cloud.firestore_v1r   r   Z'google.cloud.firestore_v1.query_resultsr   Z'google.cloud.firestore_v1.base_documentr   Z$google.cloud.firestore_v1.base_queryr   r   r   r   r   r   Z*google.cloud.firestore_v1.stream_generatorr   Z google.cloud.firestore_v1.vectorr   Z&google.cloud.firestore_v1.vector_queryr   Zgoogle.cloud.firestore_v1.watchr   Z+google.cloud.firestore_v1.base_vector_queryr   Z$google.cloud.firestore_v1.field_pathr   Z'google.cloud.firestore_v1.query_profiler    r!   r"   r   r#   r#   r#   r9   <module>   s,   ,    d