o
     i.X                     @  s8  d 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 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 erddlm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(m)Z) ddl*m+  m  m,  m-Z. ddl/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AsyncGeneratorListOptionalType)gapic_v1)retry_async)firestore_v1)AsyncAggregationQuery)AsyncStreamGenerator)AsyncVectorQuery)BaseCollectionGroup	BaseQueryQueryPartition,_collection_group_query_response_to_snapshot_enum_from_direction_query_response_to_snapshot)QueryResultsList)AsyncTransaction)DocumentSnapshot)DistanceMeasure)	FieldPath)ExplainMetricsExplainOptionsN)Vectorc                      s   e Zd ZdZ										d<d= fddZd>ddZdejjdfddd?ddZ	dddd@d&d'Z
	dAdBd+d,Z	dAdCd/d0Z	dAdCd1d2ZdejjddfdDd4d5ZdejjdfdddEd7d8ZedFd:d;Z  ZS )G
AsyncQuerya5  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.
        recursive (Optional[bool]):
            When true, returns all documents and all documents in any subcollections
            below them. Defaults to false.
    N FreturnNonec                   *   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*   r+   r,   r-   	__class__r   /var/www/snowflake_co_dev_github/snow_flake_back_end_deploy/env/lib/python3.10/site-packages/google/cloud/firestore_v1/async_query.pyr/   p      

zAsyncQuery.__init__
chunk_sizeint,AsyncGenerator[List[DocumentSnapshot], None]c           	      C s   | j }d}|  }d }	 |||}||}|r||}| I d H }|r,|d }|t|7 }|V  t||k sA|rC||krCd S q)Nr   T)_limit_copy_resolve_chunk_sizer'   start_aftergetlen)	r1   r6   max_to_returnnum_returnedoriginallast_document_chunk_size_q	snapshotsr   r   r4   	_chunkify   s*   

zAsyncQuery._chunkify)explain_optionstransactionOptional[AsyncTransaction]retry"retries.AsyncRetry | object | NonetimeoutOptional[float]rH   Optional[ExplainOptions]"QueryResultsList[DocumentSnapshot]c          
        s   d}| j }| j r!| jD ]}t|j| jkr| jn| j|_qd| _ | j||||d}z)dd |2 I dH }	|r=tt|	}	|du rDd}n|	 I dH }W |
 I dH  n|
 I dH  w 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.
            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 the collection
            that match this query.
        NFrI   rK   rM   rH   c                   s   g | z3 d H W }|q6 S Nr   ).0dr   r   r4   
<listcomp>   s    z"AsyncQuery.get.<locals>.<listcomp>)_limit_to_last_ordersr   	direction	ASCENDING
DESCENDINGstreamlistreversedget_explain_metricsacloser   )
r1   rI   rK   rM   rH   explain_metricsis_limited_to_lastorderresultresult_listr   r   r4   r>      s6   #
 zAsyncQuery.get)distance_result_fielddistance_thresholdvector_fieldstrquery_vectorr   r'   distance_measurer   re   Optional[str]rf   r   c                C  s   t | 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 (Vector): 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.
        )rg   ri   r'   rj   re   rf   )r   find_nearest)r1   rg   ri   r'   rj   re   rf   r   r   r4   rl      s   zAsyncQuery.find_nearestalias
str | None<Type['firestore_v1.async_aggregation.AsyncAggregationQuery']c                 C  s   t | j|dS )a  Adds a count over the nested query.

        Args:
            alias(Optional[str]): 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++>.

        Returns:
            :class:`~google.cloud.firestore_v1.async_aggregation.AsyncAggregationQuery`:
            An instance of an AsyncAggregationQuery object
        rm   )r   count)r1   rm   r   r   r4   rq     s   zAsyncQuery.count	field_refstr | FieldPathc                 C     t | j||dS )a.  Adds a sum over the nested query.

        Args:
            field_ref(Union[str, google.cloud.firestore_v1.field_path.FieldPath]): The field to aggregate across.
            alias(Optional[str]): 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++>.

        Returns:
            :class:`~google.cloud.firestore_v1.async_aggregation.AsyncAggregationQuery`:
            An instance of an AsyncAggregationQuery object
        rp   )r   sumr1   rr   rm   r   r   r4   ru   -     zAsyncQuery.sumc                 C  rt   )a/  Adds an avg over the nested query.

        Args:
            field_ref(Union[str, google.cloud.firestore_v1.field_path.FieldPath]): The field to aggregate across.
            alias(Optional[str]): 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++>.

        Returns:
            :class:`~google.cloud.firestore_v1.async_aggregation.AsyncAggregationQuery`:
            An instance of an AsyncAggregationQuery object
        rp   )r   avgrv   r   r   r4   rx   =  rw   zAsyncQuery.avgGAsyncGenerator[DocumentSnapshot | query_profile_pb.ExplainMetrics, Any]c                 C s   |  ||||\}}}| jjjd|| jjd|I dH }|2 z'3 dH W }	| jr0t|	| j}
nt|	| j|}
|
dur>|
V  |	j	rG|	j	}|V  q 6 dS )a  Internal method for stream(). 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 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:
            [:class:`~google.cloud.firestore_v1.base_document.DocumentSnapshot`                 | google.cloud.firestore_v1.types.query_profile.ExplainMetrtics]:
            The next document that fulfills the query. Query results will be
            yielded as `DocumentSnapshot`. When the result contains returned
            explain metrics, yield `query_profile_pb.ExplainMetrics` individually.
        requestmetadataNr   )
_prep_stream_client_firestore_api	run_query_rpc_metadata_all_descendantsr   _parentr   r`   )r1   rI   rK   rM   rH   r{   expected_prefixkwargsresponse_iteratorresponsesnapshotmetricsr   r   r4   _make_streamM  s8   .

zAsyncQuery._make_stream&AsyncStreamGenerator[DocumentSnapshot]c                C  s   | j ||||d}t||S )aG  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 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]`:
            An asynchronous generator of the queryresults.
        rQ   )r   r   )r1   rI   rK   rM   rH   inner_generatorr   r   r4   r[     s   +
zAsyncQuery.stream>Type['firestore_v1.async_collection.AsyncCollectionReference']c                  C  s   ddl m}  | S )Nr   AsyncCollectionReference)*google.cloud.firestore_v1.async_collectionr   r   r   r   r4   _get_collection_reference_class  s   z*AsyncQuery._get_collection_reference_class)
Nr   r   NFNNNFFr   r    )r6   r7   r   r8   )
rI   rJ   rK   rL   rM   rN   rH   rO   r   rP   )rg   rh   ri   r   r'   r7   rj   r   re   rk   rf   rN   r   r   rR   )rm   rn   r   ro   )rr   rs   rm   rn   r   ro   )
rI   rJ   rK   rL   rM   rN   rH   rO   r   ry   )
rI   rJ   rK   rL   rM   rN   rH   rO   r   r   )r   r   )__name__
__module____qualname____doc__r/   rG   r	   methodDEFAULTr>   rl   rq   ru   rx   r   r[   staticmethodr   __classcell__r   r   r2   r4   r   5   sT    =
(M'M3r   c                      sX   e Zd ZdZ										dd fdd	Zed
d Zejj	dfdddZ
  ZS )AsyncCollectionGroupa  Represents a Collection Group in the Firestore API.

    This is a specialization of :class:`.AsyncQuery` 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                   r!   r"   )r.   r   r/   r0   r2   r   r4   r/     r5   zAsyncCollectionGroup.__init__c                   C  s   t S rR   )r   r   r   r   r4   _get_query_class  s   z%AsyncCollectionGroup._get_query_classrK   rL   rM   float | None$AsyncGenerator[QueryPartition, None]c           
      C s   |  |||\}}| jjjd|| jjd|I dH }d}|2 z3 dH W }| j|jd j}	t| ||	V  |	}q 6 t| |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.
        rz   Nr   r   )	_prep_get_partitionsr~   r   partition_queryr   documentvaluesreference_valuer   )
r1   partition_countrK   rM   r{   r   pagerr*   	cursor_pbcursorr   r   r4   get_partitions   s   
z#AsyncCollectionGroup.get_partitions)
Nr   r   NFNNNTFr   )rK   rL   rM   r   r   r   )r   r   r   r   r/   r   r   r	   r   r   r   r   r   r   r2   r4   r     s$    
r   )3r   
__future__r   typingr   r   r   r   r   r   google.api_corer	   r
   retriesgoogle.cloudr   +google.cloud.firestore_v1.async_aggregationr   0google.cloud.firestore_v1.async_stream_generatorr   ,google.cloud.firestore_v1.async_vector_queryr   $google.cloud.firestore_v1.base_queryr   r   r   r   r   r   'google.cloud.firestore_v1.query_resultsr   +google.cloud.firestore_v1.async_transactionr   'google.cloud.firestore_v1.base_documentr   +google.cloud.firestore_v1.base_vector_queryr   $google.cloud.firestore_v1.field_pathr   'google.cloud.firestore_v1.query_profiler   r   -google.cloud.firestore_v1.types.query_profilecloudtypesquery_profilequery_profile_pb google.cloud.firestore_v1.vectorr   r   r   r   r   r   r4   <module>   s0        "