
    (ph]                    <   S r SSKJr  SSKJrJrJrJrJrJ	r	J
r
  SSKJrJr  SSKJr  SSKJr  SSKJrJr  SSKJr  SS	KJr  SS
KJrJrJrJrJrJr  SSK J!r!  SSK"J#r#  SSK$J%r%  SSK&J'r'  \(       a  SSK(J)r)  SSK*J+r+  SSK,J-r-J.r.   " S S\5      r/ " S S\/\5      r0g)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Type)
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                    ^  \ rS rSrSr          S SU 4S jjjrS\R                  R                  S4SS.       SS jjjr	    SS jr
SS jrS	 rSSS
.             SS jjr S   SS jjr S     SS jjr S     SS jjrS\R                  R                  SS4         SS jjrS\R                  R                  S4SS.         SS jjjrSS jr\  SS j5       rSrU =r$ ) Query5   a	  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.
Nc                <   > [         [        U ]  UUUUUUUUU	U
US9  g 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/   r0   	__class__s               R/var/www/html/venv/lib/python3.13/site-packages/google/cloud/firestore_v1/query.pyr2   Query.__init__m   s:     	eT#!''+ 	$ 	
    )explain_optionsc                  SnU R                   nU R                   (       ad  U R                   HM  n[        UR                  R                  U R
                  :X  a  U R                  OU R
                  5      Ul        MO     SU l         U R                  UUUUS9n[        U5      n	U(       a  [        [        U	5      5      n	Uc  SnOUR                  5       n[        XU5      $ )aN  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   timeoutr9   )_limit_to_last_ordersr   	directionname	ASCENDING
DESCENDINGstreamlistreversedget_explain_metricsr   )
r4   r   r   r<   r9   explain_metricsis_limited_to_lastorderresultresult_lists
             r6   get	Query.get   s    B 26!00 "6++t~~= OO# & #(D#+	  
 6lx45K""O$88:OoNNr8   c              #  X  #    U R                   nSnU R                  5       nS n UR                  X15      nUR                  U5      nU(       a  UR	                  U5      nUR                  5       nU(       a  US   nU[        U5      -  nUv   [        U5      U:  d  U(       a  X2:  a  g M  7f)Nr   )_limit_copy_resolve_chunk_sizer*   start_afterrL   len)	r4   
chunk_sizemax_to_returnnum_returnedoriginallast_document_chunk_size_q	snapshotss	            r6   	_chunkifyQuery._chunkify   s      (,{{**,48  (;;LUK ,B^^M2I )"C	N*LO 9~+,"?9 s   B(B*c                    U R                  UUUU5      u  pVnU R                  R                  R                  " SUU R                  R                  S.UD6nX4$ )!Helper method for :meth:`stream`.requestmetadata )_prep_stream_client_firestore_api	run_query_rpc_metadata)	r4   r   r   r<   r9   rb   expected_prefixkwargsresponse_iterators	            r6   _get_stream_iteratorQuery._get_stream_iterator   sj    +/+<+<	,
(& !LL77AA 
\\//
 
 !11r8   c                    Ucf  U[         R                  R                  L a8  U R                  R                  R
                  nUR                  nUR                  nUR                  U5      $ g)r`   F)	r   methodDEFAULTrf   rg   
_transportrh   _retry
_predicate)r4   excr   r   	transportgapic_callables         r6   _retry_query_after_exception"Query._retry_query_after_exception  sY    /// LL77BB	!*!4!4&--##C((r8   )distance_result_fielddistance_thresholdc          	     <    [        U 5      R                  UUUUUUS9$ )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.
)vector_fieldquery_vectorr*   distance_measurerz   r{   )r   find_nearest)r4   r}   r~   r*   r   rz   r{   s          r6   r   Query.find_nearest  s3    < 4 --%%-"71 . 
 	
r8   c                H    [         R                  " U 5      R                  US9$ )z
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++>.
alias)r   AggregationQuerycount)r4   r   s     r6   r   Query.count4  s#     ++D177e7DDr8   c                H    [         R                  " U 5      R                  XS9$ )as  
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++>.
r   )r   r   sumr4   	field_refr   s      r6   r   	Query.sum@  #     ++D155i5MMr8   c                H    [         R                  " U 5      R                  XS9$ )au  
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++>.
r   )r   r   avgr   s      r6   r   	Query.avgO  r   r8   c              #    #    SnU R                  UUUU5      u  pgSn  [        US5      n	U	c   U$ Uc  U	R                  (       a  U	R                  nU R                  (       a  [        XR                  5      nO[        XR                  U5      nUb  UnUv   M{  ! [        R                   aI  n
U R	                  XU5      (       a,  U R                  U5      nUR                  UUU5      u  pl Sn
A
M  e Sn
A
ff = f7f)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)rm   nextr   GoogleAPICallErrorrx   rS   rG   _all_descendantsr   _parentr   )r4   r   r   r<   r9   metricsrl   rj   last_snapshotresponseru   	new_query_snapshots                 r6   _make_streamQuery._make_stream^  s    ` *.-1-F-F	.
*  148 "  8#;#;"22$$Gll 7llO # (?  00 
44SMM $ 0 0 ?I+4+I+I#,(%
 
s4   C9B A.C9C6-=C1*C90C11C66C9c               <    U R                  UUUUS9n[        XT5      $ )aR  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;   )r   r   )r4   r   r   r<   r9   inner_generators         r6   rC   Query.stream  s3    T ++#+	 , 
 @@r8   c                8    [         R                  " X[        5      $ )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   	for_queryr   )r4   callbacks     r6   on_snapshotQuery.on_snapshot  s    : t/?@@r8   c                     SSK Jn   U $ )Nr   CollectionReference)$google.cloud.firestore_v1.collectionr   r   s    r6   _get_collection_reference_class%Query._get_collection_reference_class  s     	M""r8   )r=   )
Nrd   rd   NFNNNFFreturnNone)r   retries.Retry | object | Noner<   Optional[float]r9   Optional[ExplainOptions]r   z"QueryResultsList[DocumentSnapshot])rU   intr   z-Generator[List[DocumentSnapshot], None, None]N)r}   strr~   r   r*   r   r   r   rz   zOptional[str]r{   r   r   z-Type['firestore_v1.vector_query.VectorQuery'])r   
str | Noner   1Type['firestore_v1.aggregation.AggregationQuery'])r   zstr | FieldPathr   r   r   r   )
r   z!Optional[transaction.Transaction]r   r   r<   float | Noner9   r   r   z:Generator[DocumentSnapshot, Any, Optional[ExplainMetrics]])
r   ztransaction.Transaction | Noner   r   r<   r   r9   r   r   z!StreamGenerator[DocumentSnapshot])r   r   r   r   )r   z3Type['firestore_v1.collection.CollectionReference'])__name__
__module____qualname____firstlineno____doc__r2   r   rp   rq   rL   r]   rm   rx   r   r   r   r   r   rC   r   staticmethodr   __static_attributes____classcell__r5   s   @r6   r"   r"   5   sF   5t 
 

 
< /7/F/F#'	@O 59@O -@O !	@O 2@O 
,@OD$$	6$L2"	$ 04.2%
%
 %
 	%

 *%
  -%
 ,%
 
7%
P #'
E
E	:
E ?CN(N1;N	:N  ?CN(N1;N	:N" :>/7/F/F $48\6\ -\ 	\
 2\ 
D\@ 7;/7/F/F $	0A 590A30A -0A 	0A 20A 
+0AdA> #;# #r8   r"   c                     ^  \ rS rSrSr          S S	U 4S jjjr\S 5       r\R                  R                  S4     S
S jjrSrU =r$ )CollectionGroupi  aa  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.
Nrd   c                <   > [         [        U ]  UUUUUUUUU	U
US9  g r%   )r1   r   r2   r3   s               r6   r2   CollectionGroup.__init__"  s:     	ot-!''+ 	. 	
r8   c                     [         $ r   )r"   rd   r8   r6   _get_query_class CollectionGroup._get_query_class>  s    r8   c              #  d  #    U R                  XU5      u  pEU R                  R                  R                  " SUU R                  R                  S.UD6nSnU HE  nU R                  R                  UR                  S   R                  5      n	[        XU	5      v   U	nMG     [        XS5      v   g7f)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.
ra   Nr   rd   )	_prep_get_partitionsrf   rg   partition_queryri   documentvaluesreference_valuer   )
r4   partition_countr   r<   rb   rk   pagerr-   	cursor_pbcursors
             r6   get_partitionsCollectionGroup.get_partitionsB  s     * 33OGT++;; 
\\//
 
 I\\**9+;+;A+>+N+NOF 88H 
 TT22s   B.B0)
Nrd   rd   NFNNNTFr   )r   r   r<   r   r   z%Generator[QueryPartition, None, None])r   r   r   r   r   r2   r   r   r   rp   rq   r   r   r   r   s   @r6   r   r     s    	 
 

 
8   08/F/F $	#3 -#3 	#3
 
/#3 #3r8   r   N)1r   
__future__r   typingr   r   r   r   r   r	   r
   google.api_corer   r   r   retriesgoogle.cloudr   google.cloud.firestore_v1r   r   'google.cloud.firestore_v1.query_resultsr   'google.cloud.firestore_v1.base_documentr   $google.cloud.firestore_v1.base_queryr   r   r   r   r   r   *google.cloud.firestore_v1.stream_generatorr    google.cloud.firestore_v1.vectorr   &google.cloud.firestore_v1.vector_queryr   google.cloud.firestore_v1.watchr   +google.cloud.firestore_v1.base_vector_queryr   $google.cloud.firestore_v1.field_pathr   'google.cloud.firestore_v1.query_profiler   r    r"   r   rd   r8   r6   <module>r      sq    # P P P 0 , % > D  G 3 > 1K>V^#I ^#BO3e0 O3r8   