o
    ˷e                     @   sj  U d Z ddlZddl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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mZmZmZ ddlm Z  e!e"d< e!e"d< e!e"d< ee!ef e"d< e!e"d< e!e"d< e!e"d< e!e"d< e!e"d< e!e"d< ee"d< dZ#ej$j%Z&de&j'de&j(e#e&j)de&j*de&j+d e&j,d!e&j-d"e&j.d#e&j/d$e&j0i
Z1d%Z2d&Z3d'Z4d(Z5d)Z6d*Z7d+Z8d,Z9e: Z;G d-d. d.e:Z<d/e!d0e=fd1d2Z>d0e?fd3d4Z@d5e!d0e=fd6d7ZAd0ejBfd8d9ZCd:eeDe?f d0ee fd;d<ZEd=ed>e!d0ee
j  fd?d@ZFd=ed0ee
j  fdAdBZGG dCdD dDe<ZHG dEdF dFZIdS )Ga+  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.
    N)retry)wrappers_pb2)_helpers)document
field_path)
transforms)StructuredQuery)query)Cursor)RunQueryResponse)Order)	AnyDict	GeneratorIterableNoReturnOptionalTupleTypeUnion)DocumentSnapshot_BAD_DIR_STRING_BAD_OP_NAN_NULL_BAD_OP_STRING_COMPARISON_OPERATORS_EQ_OP_INVALID_CURSOR_TRANSFORM_INVALID_WHERE_TRANSFORM_MISMATCH_CURSOR_W_ORDER_BY_MISSING_ORDER_BY_NO_ORDERS_FOR_CURSOR_operator_enumz==<z<=z!=z>=>array_containsinznot-inarray_contains_anyz7Operator string {!r} is invalid. Valid choices are: {}.zBOnly an equality filter ("==") can be used with None or NaN valuesz*Transforms cannot be used as where values.z4Invalid direction {!r}. Must be one of {!r} or {!r}.z+Transforms cannot be used as cursor values.zThe "order by" field path {!r} is not present in the cursor data {!r}. All fields sent to ``order_by()`` must be present in the fields if passed to one of ``start_at()`` / ``start_after()`` / ``end_before()`` / ``end_at()`` to define a cursor.zAttempting to create a cursor with no fields to order on. When defining a cursor with one of ``start_at()`` / ``start_after()`` / ``end_before()`` / ``end_at()``, all fields in the cursor must come from fields set in ``order_by()``.z5The cursor {!r} does not match the order fields {!r}.c                   @   s<  e Zd ZdZdZ	 dZ	 										d\	d]dd	Zd
d Zedd Z	de
e dd fddZeeeeeeeeeed
deejj deeejj  deeejj  dee dee dee deeeef  deeeef  dee dee dd fddZdd Zd ed!edd fd"d#Zedejfd$d%Zefd ed&edd fd'd(Zd)edd fd*d+Zd)edd fd,d-Zd.ed/edefd0d1Z d2edd fd3d4Z!d]d5d6Z"d7e#e$ee%e&f d8ed9edd fd:d;Z'd7e#e$ee%e&f dd fd<d=Z(d7e#e$ee%e&f dd fd>d?Z)d7e#e$ee%e&f dd fd@dAZ*d7e#e$ee%e&f dd fdBdCZ+dej,fdDdEZ-edejfdFdGZ.de%fdHdIZ/deee0e0f  fdJdKZ1defdLdMZ2			d^dNe3j4dOe5de
e$ fdPdQZ6			d^dNe3j4dOe5deeeef fdRdSZ7			d^dNe3j4dOe5de8e9j$e0df fdTdUZ:de;fdVdWZ<d_dXdYZ=defdZd[Z>dS )`	BaseQuerya  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.
        limit_to_last (Optional[bool]):
            Denotes whether a provided limit is applied to the end of the result set.
        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.
    	ASCENDING
DESCENDINGN Freturnc                 C   sF   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	|| _
d S N)_parent_projection_field_filters_orders_limit_limit_to_last_offset	_start_at_end_at_all_descendants
_recursiveselfparent
projectionfield_filtersorderslimitlimit_to_lastoffsetstart_atend_atall_descendants	recursiver+   r+   [/var/www/ideatree/venv/lib/python3.10/site-packages/google/cloud/firestore_v1/base_query.py__init__   s   
zBaseQuery.__init__c                 C   s   t || jstS | j|jkoC| j|jkoC| j|jkoC| j|jkoC| j|jkoC| j|jkoC| j	|j	koC| j
|j
koC| j|jkoC| j|jkS r-   )
isinstance	__class__NotImplementedr.   r/   r0   r1   r2   r3   r4   r5   r6   r7   )r:   otherr+   r+   rF   __eq__   s*   








	zBaseQuery.__eq__c                 C   s   | j jS )zThe client of the parent collection.

        Returns:
            :class:`~google.cloud.firestore_v1.client.Client`:
            The client that owns this query.
        )r.   _clientr:   r+   r+   rF   rM      s   zBaseQuery._clientfield_pathsc                 C   s@   t |}|D ]}t| qtjjdd |D d}| j|dS )af  Project documents matching query to a limited set of fields.

        See :meth:`~google.cloud.firestore_v1.client.Client.field_path` for
        more information on **field paths**.

        If the current query already has a projection set (i.e. has already
        called :meth:`~google.cloud.firestore_v1.query.Query.select`), this
        will overwrite it.

        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. Acts as a copy of the current query,
            modified with the newly added projection.
        Raises:
            ValueError: If any ``field_path`` is invalid.
        c                 S   s   g | ]	}t jj|d qS )r   )r
   r	   FieldReference).0r   r+   r+   rF   
<listcomp>   s    z$BaseQuery.select.<locals>.<listcomp>fields)r<   )listfield_path_modulesplit_field_pathr
   r	   
Projection_copy)r:   rO   r   new_projectionr+   r+   rF   select   s   zBaseQuery.select
r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   c       
         C   s   | j | j| || j| || j| || j| || j| || j| || j| || j	| || j
| |	| j| |
| jdS )Nr\   )rI   r.   _evaluate_paramr/   r0   r1   r2   r3   r4   r5   r6   r7   r8   )r:   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   r+   r+   rF   rY      s   zBaseQuery._copyc                 C   s   |t ur|S |S )zHelper which allows `None` to be passed into `copy` and be set on the
        copy instead of being misinterpreted as an unpassed parameter.)_not_passed)r:   valuefallback_valuer+   r+   rF   r]     s   zBaseQuery._evaluate_paramr   	op_stringc                 C   s   t | |du r"|tkrtttjjtjj|dtjj	j
d}n=t|r?|tkr.tttjjtjj|dtjj	jd}n t|tjtjfrLtttjjtjj|dt|t|d}| j|f }| j|dS )aM  Filter the query on a field.

        See :meth:`~google.cloud.firestore_v1.client.Client.field_path` for
        more information on **field paths**.

        Returns a new :class:`~google.cloud.firestore_v1.query.Query` that
        filters on a specific field path, according to an operation (e.g.
        ``==`` or "equals") and a particular value to be paired with that
        operation.

        Args:
            field_path (str): A field path (``.``-delimited list of
                field names) for the field to filter on.
            op_string (str): A comparison operation in the form of a string.
                Acceptable values are ``<``, ``<=``, ``==``, ``!=``, ``>=``, ``>``,
                ``in``, ``not-in``, ``array_contains`` and ``array_contains_any``.
            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.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A filtered query. Acts as a copy of the current query,
            modified with the newly added filter.

        Raises:
            ValueError: If ``field_path`` is invalid.
            ValueError: If ``value`` is a NaN or :data:`None` and
                ``op_string`` is not ``==``.
        Nr   )fieldop)rb   rc   r_   )r=   )rV   rW   r   
ValueErrorr   r
   r	   UnaryFilterrP   OperatorIS_NULL_isnanIS_NANrH   r   Sentinel
_ValueListr   FieldFilter_enum_from_op_stringr   encode_valuer0   rY   )r:   r   ra   r_   	filter_pbnew_filtersr+   r+   rF   where   s0   
zBaseQuery.wherec                 C   s   t jjt jj| dt|dS )zHelper for :meth:`order_by`.r   rb   	direction)r
   r	   r   rP   _enum_from_direction)r   rs   r+   r+   rF   _make_order[  s   zBaseQuery._make_orderrs   c                 C   s.   t | | ||}| j|f }| j|dS )a|  Modify the query to add an order clause on a specific field.

        See :meth:`~google.cloud.firestore_v1.client.Client.field_path` for
        more information on **field paths**.

        Successive :meth:`~google.cloud.firestore_v1.query.Query.order_by`
        calls will further refine the ordering of results returned by the query
        (i.e. the new "order by" fields will be added to existing ones).

        Args:
            field_path (str): A field path (``.``-delimited list of
                field names) on which to order the query results.
            direction (Optional[str]): The direction to order by. Must be one
                of :attr:`ASCENDING` or :attr:`DESCENDING`, defaults to
                :attr:`ASCENDING`.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            An ordered query. Acts as a copy of the current query, modified
            with the newly added "order by" constraint.

        Raises:
            ValueError: If ``field_path`` is invalid.
            ValueError: If ``direction`` is not one of :attr:`ASCENDING` or
                :attr:`DESCENDING`.
        )r>   )rV   rW   ru   r1   rY   )r:   r   rs   order_pb
new_ordersr+   r+   rF   order_byc  s   
zBaseQuery.order_bycountc                 C      | j |ddS )ag  Limit a query to return at most `count` matching results.

        If the current query already has a `limit` set, this will override it.

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

        Args:
            count (int): Maximum number of documents to return that match
                the query.
        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A limited query. Acts as a copy of the current query, modified
            with the newly added "limit" filter.
        Fr?   r@   rY   r:   ry   r+   r+   rF   r?        zBaseQuery.limitc                 C   rz   )aw  Limit a query to return the last `count` matching results.
        If the current query already has a `limit_to_last`
        set, this will override it.

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

        Args:
            count (int): Maximum number of documents to return that match
                the query.
        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A limited query. Acts as a copy of the current query, modified
            with the newly added "limit" filter.
        Tr{   r|   r}   r+   r+   rF   r@     r~   zBaseQuery.limit_to_last
num_loaded
chunk_sizec                 C   s,   | j dur|| | j krt| j | dS |S )zUtility function for chunkify.Nr   )r2   max)r:   r   r   r+   r+   rF   _resolve_chunk_size  s   zBaseQuery._resolve_chunk_sizenum_to_skipc                 C   s   | j |dS )a  Skip to an offset in a query.

        If the current query already has specified an offset, this will
        overwrite it.

        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. Acts as a copy of the current query, modified
            with the newly added "offset" field.
        )rA   r|   )r:   r   r+   r+   rF   rA     s   zBaseQuery.offsetc                 C   s.   | j rdS |jjdd | jjkrtddS )zValidate local snapshots for non-collection-group queries.

        Raises:
            ValueError: for non-collection-group queries, if the snapshot
                is from a different collection.
        Nz8Cannot use snapshot from another collection as a cursor.)r7   	reference_pathr.   rd   )r:   document_snapshotr+   r+   rF   _check_snapshot  s
   zBaseQuery._check_snapshotdocument_fields_or_snapshotbeforestartc                 C   s   t |tr
t|}nt |tjr| | nt|}||f}| j| j	| j
| j| j| jd}|r:||d< | j|d< n	| j|d< ||d< | jdi |S )a  Set values to be used for a ``start_at`` or ``end_at`` cursor.

        The values will later be used in a query protobuf.

        When the query is sent to the server, the ``document_fields_or_snapshot`` will
        be used in the order given by fields set by
        :meth:`~google.cloud.firestore_v1.query.Query.order_by`.

        Args:
            document_fields_or_snapshot
                (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.
            before (bool): Flag indicating if the document in
                ``document_fields_or_snapshot`` should (:data:`False`) or
                shouldn't (:data:`True`) be included in the result set.
            start (Optional[bool]): determines if the cursor is a ``start_at``
                cursor (:data:`True`) or an ``end_at`` cursor (:data:`False`).

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A query with cursor. Acts as a copy of the current query, modified
            with the newly added "start at" cursor.
        )r<   r=   r>   r?   rA   rD   rB   rC   Nr+   )rH   tuplerU   r   r   r   copydeepcopyr/   r0   r1   r2   r4   r7   r6   r5   rY   )r:   r   r   r   cursor_pairquery_kwargsr+   r+   rF   _cursor_helper  s&   



zBaseQuery._cursor_helperc                 C      | j |dddS )a  Start query results at a particular document value.

        The result set will **include** the document specified by
        ``document_fields_or_snapshot``.

        If the current query already has specified a start cursor -- either
        via this method or
        :meth:`~google.cloud.firestore_v1.query.Query.start_after` -- this
        will overwrite it.

        When the query is sent to the server, the ``document_fields`` will
        be used in the order given by fields set by
        :meth:`~google.cloud.firestore_v1.query.Query.order_by`.

        Args:
            document_fields_or_snapshot
                (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. Acts as
            a copy of the current query, modified with the newly added
            "start at" cursor.
        Tr   r   r   r:   r   r+   r+   rF   rB     s   zBaseQuery.start_atc                 C      | j |dddS )a  Start query results after a particular document value.

        The result set will **exclude** the document specified by
        ``document_fields_or_snapshot``.

        If the current query already has specified a start cursor -- either
        via this method or
        :meth:`~google.cloud.firestore_v1.query.Query.start_at` -- this will
        overwrite it.

        When the query is sent to the server, the ``document_fields_or_snapshot`` will
        be used in the order given by fields set by
        :meth:`~google.cloud.firestore_v1.query.Query.order_by`.

        Args:
            document_fields_or_snapshot
                (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. Acts as a copy of the current query, modified
            with the newly added "start after" cursor.
        FTr   r   r   r+   r+   rF   start_after(     zBaseQuery.start_afterc                 C   r   )a  End query results before a particular document value.

        The result set will **exclude** the document specified by
        ``document_fields_or_snapshot``.

        If the current query already has specified an end cursor -- either
        via this method or
        :meth:`~google.cloud.firestore_v1.query.Query.end_at` -- this will
        overwrite it.

        When the query is sent to the server, the ``document_fields_or_snapshot`` will
        be used in the order given by fields set by
        :meth:`~google.cloud.firestore_v1.query.Query.order_by`.

        Args:
            document_fields_or_snapshot
                (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. Acts as a copy of the current query, modified
            with the newly added "end before" cursor.
        TFr   r   r   r+   r+   rF   
end_beforeI  r   zBaseQuery.end_beforec                 C   r   )a  End query results at a particular document value.

        The result set will **include** the document specified by
        ``document_fields_or_snapshot``.

        If the current query already has specified an end cursor -- either
        via this method or
        :meth:`~google.cloud.firestore_v1.query.Query.end_before` -- this will
        overwrite it.

        When the query is sent to the server, the ``document_fields_or_snapshot`` will
        be used in the order given by fields set by
        :meth:`~google.cloud.firestore_v1.query.Query.order_by`.

        Args:
            document_fields_or_snapshot
                (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. Acts as a copy of the current query, modified
            with the newly added "end at" cursor.
        Fr   r   r   r+   r+   rF   rC   j  r   zBaseQuery.end_atc                 C   s\   t | j}|dkrdS |dkrt| jd S tjjtjjjdd | jD d}tjj|dS )ac  Convert all the filters into a single generic Filter protobuf.

        This may be a lone field filter or unary filter, may be a composite
        filter or may be :data:`None`.

        Returns:
            :class:`google.cloud.firestore_v1.types.StructuredQuery.Filter`:
            A "generic" filter representing the current query's filters.
        r   N   c                 S   s   g | ]}t |qS r+   )
_filter_pb)rQ   filter_r+   r+   rF   rR         z)BaseQuery._filters_pb.<locals>.<listcomp>)rc   filters)composite_filter)	lenr0   r   r
   r	   CompositeFilterrf   ANDFilter)r:   num_filtersr   r+   r+   rF   _filters_pb  s   

zBaseQuery._filters_pbc                 C   s8   | durt | j}|stjjdd}tjj|gdS | S )z(Helper:  convert field paths to message.N__name__r   rS   )rU   rT   r
   r	   rP   rX   )r<   rT   	field_refr+   r+   rF   _normalize_projection  s   
zBaseQuery._normalize_projectionc                 C   s   t | j}d}| jrt| jd tjrd}| jr#t| jd tjr#d}|r}dd tD }dd |D }| jD ] }t|j	t
jjrV|jj}|j	|v rV||vrV|| |d q6|sd|| dd |S d	d |D }d|vr}|d
 j}|| d| |S )z7Helper:  adjust orders based on cursors, where clauses.Fr   Tc                 S   s    g | ]}|t d fvrt|qS )r%   )r   rm   )rQ   keyr+   r+   rF   rR     s
    z/BaseQuery._normalize_orders.<locals>.<listcomp>c                 S      g | ]}|j jqS r+   rb   r   rQ   orderr+   r+   rF   rR     r   r)   r   c                 S   r   r+   r   r   r+   r+   rF   rR     r   r   )rU   r1   r5   rH   r   r   r6   r   r0   rc   r	   rl   rf   rb   r   appendru   rs   )r:   r>   _has_snapshot_cursorshould_order
order_keysr   rb   rs   r+   r+   rF   _normalize_orders  s6   


zBaseQuery._normalize_ordersc              	   C   s`  |du rdS |st t|\}}dd |D }t|tjr(|}| }|j|d< t|trfg }|}|dt| D ]*}	z|	|v rH|	||	  n	|	t
|	| W q9 tyc   t|	|}
t |
w |}|rzt|t|krzt||}
t |
tjtjf}tt||D ]$\}}|\}}t||rt}
t |
|dkrt|tr| j|||< q||fS )z;Helper: convert cursor to a list of values based on orders.Nc                 S   r   r+   r   r   r+   r+   rF   rR     r   z/BaseQuery._normalize_cursor.<locals>.<listcomp>r   )rd   r!   rH   r   r   to_dictr   dictr   r   rV   get_nested_valueKeyErrorr    formatr   r   rj   rk   	enumeratezipr   strr.   )r:   cursorr>   document_fieldsr   r   snapshotvaluesdata	order_keymsg_transform_basesindex	key_fieldr   rb   r+   r+   rF   _normalize_cursor  sN   



zBaseQuery._normalize_cursorc                 C   s   |  | j}|  }| | j|}| | j|}|tjj| j	j
| jdg|  |t|t|d}| jdur;| j|d< | jdurItj| jd|d< tjdi |S )zConvert the current query into the equivalent protobuf.

        Returns:
            :class:`google.cloud.firestore_v1.types.StructuredQuery`:
            The query protobuf.
        )collection_idrD   )r[   from_rq   rx   rB   rC   NrA   r_   r?   r+   )r   r/   r   r   r5   r6   r
   r	   CollectionSelectorr.   idr7   r   
_cursor_pbr4   r2   r   
Int32Value)r:   r<   r>   rB   rC   r   r+   r+   rF   _to_protobuf  s&   



zBaseQuery._to_protobufr   timeoutc                 C      t r-   NotImplementedErrorr:   transactionr   r   r+   r+   rF   get)     zBaseQuery.getc                 C   sH   | j rtd| j \}}||  t|d}t||}|||fS )z,Shared setup for async / sync :meth:`stream`zoQuery results for queries that include limit_to_last() constraints cannot be streamed. Use Query.get() instead.)r;   structured_queryr   )r3   rd   r.   _parent_infor   r   get_transaction_idmake_retry_timeout_kwargs)r:   r   r   r   parent_pathexpected_prefixrequestkwargsr+   r+   rF   _prep_stream1  s   
zBaseQuery._prep_streamc                 C   r   r-   r   r   r+   r+   rF   streamH  r   zBaseQuery.streamc                 C   r   r-   r   )r:   callbackr+   r+   rF   on_snapshotP     zBaseQuery.on_snapshotc                 C   s   | j ddd}|jrN|jjrNd|jj}| d|_| jj|j_d}| d| }d}| | d| }|tj	
 tj	
 |itj	
 |i}|S )a  Returns a copy of this query whose iterator will yield all matching
        documents as well as each of their descendent subcollections and documents.

        This differs from the `all_descendents` flag, which only returns descendents
        whose subcollection names match the parent collection's name. To return
        all descendents, regardless of their subcollection name, use this.
        T)rE   rD   / z__id-9223372036854775808__ )rY   r.   r   joinr   _get_collection_reference_classrM   rx   rV   	FieldPathdocument_idrB   rC   )r:   copiedoriginal_collection_idREFERENCE_NAME_MIN_IDrB   nullCharrC   r+   r+   rF   rE   S  s   zBaseQuery.recursivec                 C   s  | j }t|dkrtj}n|d jdkrtj}ntj}t|}tjj	tjj
ddt|d}|| |D ]P}|jjdkrIt	 |jj|jj}n1|jj|jvsW|jj|jvr[td|j|jj }	|j|jj }
t|	}t|
}t	 ||}|dkr|j|   S q5dS )Nr   r   r   r   r   rr   zCan only compare fields that exist in the DocumentSnapshot. Please include the fields you are ordering on in your select() call.)r1   r   r(   r)   rs   r*   rU   r
   r	   r   rP   rt   r   rb   r   _compare_tor   r   _datard   r   rn   compare)r:   doc1doc2r1   lastDirectionorderBysrv   orderBycompv1v2
encoded_v1
encoded_v2r+   r+   rF   _comparator{  s:   


zBaseQuery._comparator)
Nr+   r+   NFNNNFFr,   N)NNN)r,   r(   )?r   
__module____qualname____doc__r)   r*   rG   rL   propertyrM   r   r   r[   r^   r   r
   r	   rX   r   rl   r   intboolr   rY   r]   rq   staticmethodru   rx   r?   r@   r   rA   r   r   r   rU   r   r   rB   r   r   rC   r   r   r   r   r   r   r   retriesRetryfloatr   r   r   r   r   r   r   rE   r   r+   r+   r+   rF   r(   e   s   <

	%
	

;"

9
 
!
!
!%8 




(r(   ra   r,   c                 C   s@   zt |  W S  ty   dtt  }t| |}t|w )a  Convert a string representation of a binary operator to an enum.

    These enums come from the protobuf message definition
    ``StructuredQuery.FieldFilter.Operator``.

    Args:
        op_string (str): A comparison operation in the form of a string.
            Acceptable values are ``<``, ``<=``, ``==``, ``!=``, ``>=``
            and ``>``.

    Returns:
        int: The enum corresponding to ``op_string``.

    Raises:
        ValueError: If ``op_string`` is not a valid operator.
    z, )r   r   r   sortedkeysr   r   rd   )ra   choicesr   r+   r+   rF   rm     s   
rm   c                 C   s   t | tr
t| S dS )zCheck if a value is NaN.

    This differs from ``math.isnan`` in that **any** input type is
    allowed.

    Args:
        value (Any): A value to check for NaN-ness.

    Returns:
        bool: Indicates if the value is the NaN float.
    F)rH   r  mathisnanr   r+   r+   rF   rh     s   

rh   rs   c                 C   sL   t | tr| S | tjkrtjjS | tjkrtjjS t| tjtj}t	|)a  Convert a string representation of a direction to an enum.

    Args:
        direction (str): A direction to order by. Must be one of
            :attr:`~google.cloud.firestore.BaseQuery.ASCENDING` or
            :attr:`~google.cloud.firestore.BaseQuery.DESCENDING`.

    Returns:
        int: The enum corresponding to ``direction``.

    Raises:
        ValueError: If ``direction`` is not a valid direction.
    )
rH   r  r(   r)   r	   	Directionr*   r   r   rd   )rs   r   r+   r+   rF   rt     s   



rt   c                 C   sH   t | tjjrtjj| dS t | tjjrtjj| dS tdt| | )a  Convert a specific protobuf filter to the generic filter type.

    Args:
        field_or_unary (Union[google.cloud.proto.firestore.v1.            query.StructuredQuery.FieldFilter, google.cloud.proto.            firestore.v1.query.StructuredQuery.FieldFilter]): A
            field or unary filter to convert to a generic filter.

    Returns:
        google.cloud.firestore_v1.types.        StructuredQuery.Filter: A "generic" filter.

    Raises:
        ValueError: If ``field_or_unary`` is not a field or unary filter.
    )field_filter)unary_filterzUnexpected filter type)rH   r
   r	   rl   r   re   rd   type)field_or_unaryr+   r+   rF   r     s
   r   r   c                 C   s0   | dur| \}}dd |D }t j||dS dS )a~  Convert a cursor pair to a protobuf.

    If ``cursor_pair`` is :data:`None`, just returns :data:`None`.

    Args:
        cursor_pair (Optional[Tuple[list, bool]]): Two-tuple of

            * a list of field values.
            * a ``before`` flag

    Returns:
        Optional[google.cloud.firestore_v1.types.Cursor]: A
        protobuf cursor corresponding to the values.
    Nc                 S   s   g | ]}t |qS r+   )r   rn   )rQ   r_   r+   r+   rF   rR     s    z_cursor_pb.<locals>.<listcomp>)r   r   )r
   r   )r   r   r   	value_pbsr+   r+   rF   r   	  s
   r   response_pbr   c                 C   s^   | j dsdS t| j|}||}t| jj|j}tj||d| j	| jj
| jjd}|S )a  Parse a query response protobuf to a document snapshot.

    Args:
        response_pb (google.cloud.proto.firestore.v1.            firestore.RunQueryResponse): A
        collection (:class:`~google.cloud.firestore_v1.collection.CollectionReference`):
            A reference to the collection that initiated the query.
        expected_prefix (str): The expected prefix for fully-qualified
            document names returned in the query results. This can be computed
            directly from ``collection`` via :meth:`_parent_info`.

    Returns:
        Optional[:class:`~google.cloud.firestore.document.DocumentSnapshot`]:
        A snapshot of the data returned in the query. If
        ``response_pb.document`` is not set, the snapshot will be :data:`None`.
    r   NTexists	read_timecreate_timeupdate_time)_pbHasFieldr   
get_doc_idr   decode_dictrT   rM   r   r  r  r  )r  
collectionr   r   r   r   r   r+   r+   rF   _query_response_to_snapshot  s   
r  c                 C   s\   | j dsdS |j| jj}t| jj|j}tj||d| j j	| j jj
| j jjd}|S )a)  Parse a query response protobuf to a document snapshot.

    Args:
        response_pb (google.cloud.proto.firestore.v1.            firestore.RunQueryResponse): A
        collection (:class:`~google.cloud.firestore_v1.collection.CollectionReference`):
            A reference to the collection that initiated the query.

    Returns:
        Optional[:class:`~google.cloud.firestore.document.DocumentSnapshot`]:
        A snapshot of the data returned in the query. If
        ``response_pb.document`` is not set, the snapshot will be :data:`None`.
    r   NTr  )r  r  rM   r   namer   r  rT   r   r  r  r  )r  r  r   r   r   r+   r+   rF   ,_collection_group_query_response_to_snapshotB  s   r  c                	       s   e Zd ZdZeej ej	fZ
										d	d fddZd	d
 Zdd Z		ddejdedeeef fddZ		ddejdedefddZeded  fddZ  ZS )BaseCollectionGroupa}  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,   c                    s6   |
st dtt| j|||||||||	|
|d d S )Nz8all_descendants must be True for collection group query.)r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   )rd   superr   rG   r9   rI   r+   rF   rG   t  s   

zBaseCollectionGroup.__init__c                 C   s<   | j rtd| jrtd| jrtd| jrtdd S )Nz#Can't partition query with filters.z&Can't partition query with projection.z!Can't partition query with limit.z"Can't partition query with offset.)r0   rd   r/   r2   r4   rN   r+   r+   rF   _validate_partition_query  s   z-BaseCollectionGroup._validate_partition_queryc                 C   r   r-   r   rN   r+   r+   rF   _get_query_class  r   z$BaseCollectionGroup._get_query_classr   r   c           
      C   s^   |    | j \}}|  }|| j| j| j| j| jd}|| |d}t	
||}	||	fS )N)r>   rB   rC   rD   )r;   r   partition_count)r#  r.   r   r$  _PARTITION_QUERY_ORDERr5   r6   r7   r   r   r   )
r:   r%  r   r   r   r   klassr
   r   r   r+   r+   rF   _prep_get_partitions  s    z(BaseCollectionGroup._prep_get_partitionsc                 C   r   r-   r   )r:   r%  r   r   r+   r+   rF   get_partitions  r   z"BaseCollectionGroup.get_partitionsc                   C   r   r-   r   r+   r+   r+   rF   r     s   z3BaseCollectionGroup._get_collection_reference_class)
Nr+   r+   NFNNNTFr   )NN)r   r   r   r   r(   ru   rV   r   r   r)   r&  rG   r#  r$  r  r  r  r   r   r(  r   r)  r  r   r   __classcell__r+   r+   r"  rF   r   a  sT    



r   c                   @   s8   e Zd ZdZdd Zedd Zedd Zdd	 Zd
S )QueryPartitionaM  Represents a bounded partition of a collection group query.

    Contains cursors that can be used in a query as a starting and/or end point for the
    collection group query. The cursors may only be used in a query that matches the
    constraints of the query that produced this partition.

    Args:
        query (BaseQuery): The original query that this is a partition of.
        start_at (Optional[~google.cloud.firestore_v1.document.DocumentSnapshot]):
            Cursor for first query result to include. If `None`, the partition starts at
            the beginning of the result set.
        end_at (Optional[~google.cloud.firestore_v1.document.DocumentSnapshot]):
            Cursor for first query result after the last result included in the
            partition. If `None`, the partition runs to the end of the result set.

    c                 C   s   || _ || _|| _d S r-   )_queryr5   r6   r:   r
   rB   rC   r+   r+   rF   rG     s   
zQueryPartition.__init__c                 C      | j S r-   )r5   rN   r+   r+   rF   rB        zQueryPartition.start_atc                 C   r.  r-   )r6   rN   r+   r+   rF   rC     r/  zQueryPartition.end_atc                 C   sN   | j }| jr| jgdfnd}| jr| jgdfnd}t||j|j|j||dS )zGenerate a new query using this partition's bounds.

        Returns:
            BaseQuery: Copy of the original query with start and end bounds set by the
                cursors from this partition.
        TN)rD   r>   rB   rC   )r,  rB   rC   r  r.   r7   r&  r-  r+   r+   rF   r
     s   zQueryPartition.queryN)	r   r   r   r   rG   r   rB   rC   r
   r+   r+   r+   rF   r+    s    

r+  )Jr   r   r
  google.api_corer   r  google.protobufr   google.cloud.firestore_v1r   r   r   rV   r   google.cloud.firestore_v1.typesr	   r
   r   r   google.cloud.firestore_v1.orderr   typingr   r   r   r   r   r   r   r   r   'google.cloud.firestore_v1.base_documentr   r   __annotations__r   rl   rf   r"   	LESS_THANLESS_THAN_OR_EQUALEQUAL	NOT_EQUALGREATER_THAN_OR_EQUALGREATER_THANARRAY_CONTAINSINNOT_INARRAY_CONTAINS_ANYr   r   r   r   r   r   r    r!   r   objectr^   r(   r  rm   r  rh   rt   r   r   rU   r   r  r  r   r+  r+   r+   r+   rF   <module>   s   ,      K
$
h