Ë
    V¼Sf¾?  ã                  óâ   — d 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 ddlmZ dd	lmZ dd
lmZmZmZmZmZ erddlmZ ddlmZ  G d„ de«      Z  G d„ de e
«      Z!y)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)Úgapic_v1)Úretry_async)Úfirestore_v1)ÚBaseCollectionGroupÚ	BaseQueryÚQueryPartitionÚ_query_response_to_snapshotÚ,_collection_group_query_response_to_snapshotÚ_enum_from_direction)Úasync_document)ÚAsyncAggregationQuery)ÚDocumentSnapshot)ÚAsyncGeneratorÚListÚOptionalÚTypeÚTYPE_CHECKING)ÚTransaction)Ú	FieldPathc                  ó(  ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 	 	 d	 dˆ fd„Z	 	 	 	 dd„Zdej                  j                  df	 	 	 	 	 	 	 dd„Z		 d	 	 	 dd„Z
	 d	 	 	 	 	 dd„Z	 d	 	 	 	 	 dd„Zdej                  j                  df	 	 	 	 	 dd	„Ze	 	 dd
„«       Zˆ xZS )Ú
AsyncQueryaG  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.proto.firestore.v1.            query.StructuredQuery.Projection`]):
            A projection of document fields to limit the query results to.
        field_filters (Optional[Tuple[:class:`google.cloud.proto.firestore.v1.            query.StructuredQuery.FieldFilter`, ...]]):
            The filters to be applied in the query.
        orders (Optional[Tuple[:class:`google.cloud.proto.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.
    Nc                óB   •— t         t        | �  |||||||||	|
|¬«       y ©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__s               €údC:\Users\user\Documents\project_loop\venv\Lib\site-packages\google/cloud/firestore_v1/async_query.pyr'   zAsyncQuery.__init__j   s:   ø€ ô 	Œj˜$Ñ(ØØ!Ø'ØØØ'ØØØØ+Øð 	)õ 	
ó    c               óN  K  — | j                   }d}| j                  «       }d }	 |j                  ||«      }|j                  |«      }|r|j	                  |«      }|j                  «       ƒ d {  –—† }|r|d   }|t        |«      z  }|­–— t        |«      |k  s|r||k\  ry Œ7 Œ5­w)Nr   éÿÿÿÿ)Ú_limitÚ_copyÚ_resolve_chunk_sizer   Ústart_afterÚgetÚlen)	r)   Ú
chunk_sizeÚmax_to_returnÚnum_returnedÚoriginalÚlast_documentÚ_chunk_sizeÚ_qÚ	snapshotss	            r+   Ú	_chunkifyzAsyncQuery._chunkify†   s¯   è ø€ ð (,§{¡{ˆØˆØ#Ÿz™z›|ˆØ48ˆàð  (×;Ñ;¸LÈ*ÓUˆKð —‘ Ó,ˆBáØ—^‘^ MÓ2�à Ÿf™f›hŸˆIáØ )¨"¡�àœC 	›NÑ*ˆLà‹Oô �9‹~ Ò+Ù ,°-Ò"?àð9 ð 'ús   ‚A+B%Á-B#Á.6B%c              ƒ  óz  K  — | j                   }| j                   rW| j                  D ]A  }t        |j                  | j                  k(  r| j
                  n| j                  «      |_        ŒC d| _         | j                  |||¬«      }|2 �cg c3 d{  –—† }|‘Œ7 Œ6 nc c}w }}|rt        t        |«      «      }|S ­w)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 (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.

        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:
            list: The documents in the collection that match this query.
        F)ÚtransactionÚretryÚtimeoutN)	Ú_limit_to_lastÚ_ordersr   Ú	directionÚ	ASCENDINGÚ
DESCENDINGÚstreamÚlistÚreversed)r)   r?   r@   rA   Úis_limited_to_lastÚorderÚresultÚds           r+   r3   zAsyncQuery.get¬   s°   è ø€ ð6 "×0Ñ0Ðà×Òð Ÿ™ò �Ü"6à—‘¨$¯.©.Ò8ð —O’OàŸ™ó#�•ðð #(ˆDÔà—‘¨¸EÈ7�ÓSˆØ#)×*Ô*˜a’!Ð*øÑ*ùÒ*ˆÐ*ÙÜœ( 6Ó*Ó+ˆFàˆùs6   ‚BB;Â
BÂBÂB
ÂBÂBÂBÂBÂ B;c                ó8   — t        | «      j                  |¬«      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
        ©Úalias)r   Úcount)r)   rP   s     r+   rQ   zAsyncQuery.countÜ   s   € ô % TÓ*×0Ñ0°uÐ0Ó=Ð=r,   c                ó:   — t        | «      j                  ||¬«      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
        rO   )r   Úsum©r)   Ú	field_refrP   s      r+   rS   zAsyncQuery.sumë   ó   € ô % TÓ*×.Ñ.¨yÀÐ.ÓFÐFr,   c                ó:   — t        | «      j                  ||¬«      S )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
        rO   )r   ÚavgrT   s      r+   rX   zAsyncQuery.avgû   rV   r,   c               ój  K  — | j                  |||«      \  }}} | j                  j                  j                  d|| j                  j                  dœ|¤Žƒ d{  –—† }|2 3 d{  –—† }| j
                  rt        || j                  «      }	nt        || j                  |«      }	|	€ŒF|	­–— ŒL7 ŒR7 ŒI6 y­w)a(  Read the documents in the collection that match this query.

        This sends a ``RunQuery`` RPC and then returns an iterator 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 (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.

        Yields:
            :class:`~google.cloud.firestore_v1.async_document.DocumentSnapshot`:
            The next document that fulfills the query.
        ©ÚrequestÚmetadataN© )	Ú_prep_streamÚ_clientÚ_firestore_apiÚ	run_queryÚ_rpc_metadataÚ_all_descendantsr   Ú_parentr
   )
r)   r?   r@   rA   r[   Úexpected_prefixÚkwargsÚresponse_iteratorÚresponseÚsnapshots
             r+   rG   zAsyncQuery.stream  sÍ   è ø€ ðH ,0×+<Ñ+<ØØØó,
Ñ(ˆ� &ð #H $§,¡,×"=Ñ"=×"GÑ"Gð #
ØØ—\‘\×/Ñ/ñ#
ð ñ#
÷ 
Ðð 0÷ 
	ð 
	�(Ø×$Ò$ÜGØ˜dŸl™ló‘ô 7Ø˜dŸl™l¨Oó�ð Ñ#Ø”ð!
øð
	øÑ/ùs<   ‚AB3ÁB-ÁB3Á!B1Á%B/Á&B1Á)=B3Â'B3Â/B1Â1B3c                 ó   — ddl m}  | S )Nr   ©ÚAsyncCollectionReference)Ú*google.cloud.firestore_v1.async_collectionrl   rk   s    r+   Ú_get_collection_reference_classz*AsyncQuery._get_collection_reference_classG  s   € õ 	Xà'Ð'r,   )
Nr]   r]   NFNNNFF©ÚreturnÚNone)r5   Úintrp   z,AsyncGenerator[List[DocumentSnapshot], None])r?   r   r@   úretries.AsyncRetryrA   Úfloatrp   rH   ©N)rP   ú
str | Nonerp   ú<Type['firestore_v1.async_aggregation.AsyncAggregationQuery'])rU   zstr | FieldPathrP   rv   rp   rw   )r@   rs   rA   rt   rp   z5AsyncGenerator[async_document.DocumentSnapshot, None])rp   z>Type['firestore_v1.async_collection.AsyncCollectionReference'])Ú__name__Ú
__module__Ú__qualname__Ú__doc__r'   r=   r   ÚmethodÚDEFAULTr3   rQ   rS   rX   rG   Ústaticmethodrn   Ú__classcell__©r*   s   @r+   r   r   /   sL  ø„ ñ8ðz ØØØØØØØØØð
ð 
õ
ð8$Øð$à	5ó$ðP $(Ø$,§O¡O×$;Ñ$;Øð	.à ð.ð "ð.ð ð	.ð
 
ó.ðb #'ð>Øð>à	Eó>ð  ?CðGØ(ðGØ1;ðGà	EóGð" ?CðGØ(ðGØ1;ðGà	EóGð$ Ø$,§O¡O×$;Ñ$;Øð	:ð "ð:ð ð	:ð
 
?ó:ðx ð(ØFò(ó ô(r,   r   c                  óŒ   ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 	 	 d	 dˆ fd„Zed„ «       Zej                  j                  df	 	 	 	 	 dd„Z
ˆ x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.
    Nc                óB   •— t         t        | �  |||||||||	|
|¬«       y r   )r&   r‚   r'   r(   s               €r+   r'   zAsyncCollectionGroup.__init__\  s;   ø€ ô 	Ô" DÑ2ØØ!Ø'ØØØ'ØØØØ+Øð 	3õ 	
r,   c                 ó   — t         S ru   )r   r]   r,   r+   Ú_get_query_classz%AsyncCollectionGroup._get_query_classx  s   € äÐr,   c               ó�  K  — | j                  |||«      \  }} | j                  j                  j                  d|| j                  j                  dœ|¤Žƒ d{  –—† }d}|2 3 d{  –—† }| j                  j                  |j                  d   j                  «      }	t        | ||	«      ­–— |	}ŒN7 ŒV7 ŒK6 t        | |d«      ­–— y­w)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_queryrb   ÚdocumentÚvaluesÚreference_valuer	   )
r)   Úpartition_countr@   rA   r[   rf   Úpagerr"   Ú	cursor_pbÚcursors
             r+   Úget_partitionsz#AsyncCollectionGroup.get_partitions|  sÎ   è ø€ ð* ×3Ñ3°OÀUÈGÓT‰ˆ�ØA�d—l‘l×1Ñ1×AÑAð 
ØØ—\‘\×/Ñ/ñ
ð ñ
÷ 
ˆð ˆØ$÷ 	ð 	�)Ø—\‘\×*Ñ*¨9×+;Ñ+;¸AÑ+>×+NÑ+NÓOˆFÜ   x°Ó8Ó8Ø‰Hð
øð	ø˜uô
 ˜T 8¨TÓ2Ô2ùs7   ‚ACÁB0ÁCÁ"B4Á&B2Á'B4Á*ACÂ2B4Â4C)
Nr]   r]   NFNNNTFro   )r@   rs   rA   rt   rp   z$AsyncGenerator[QueryPartition, None])rx   ry   rz   r{   r'   r~   r…   r   r|   r}   r�   r   r€   s   @r+   r‚   r‚   P  s€   ø„ ñ	ð ØØØØØØØØØð
ð 
õ
ð8 ñó ðð %-§O¡O×$;Ñ$;Øð	"3ð "ð"3ð ð	"3ð
 
.÷"3r,   r‚   N)"r{   Ú
__future__r   Úgoogle.api_corer   r   ÚretriesÚgoogle.cloudr   Ú$google.cloud.firestore_v1.base_queryr   r   r	   r
   r   r   Úgoogle.cloud.firestore_v1r   Ú+google.cloud.firestore_v1.async_aggregationr   Ú'google.cloud.firestore_v1.base_documentr   Útypingr   r   r   r   r   Ú%google.cloud.firestore_v1.transactionr   Ú$google.cloud.firestore_v1.field_pathr   r   r‚   r]   r,   r+   ú<module>rœ      s\   ðñõ #å $Ý 2å %÷÷ õ 5Ý MÝ Dß FÕ FáåAÝ>ô^(�ô ^(ôB	N3˜:Ð':õ N3r,   