o
    }l~iR]                     @  sZ  d Z ddlmZ ddlZddlmZmZmZmZm	Z	m
Z
mZmZmZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ erdd	lmZ dd
lmZ ddlmZmZ ddl m!Z! ddl"m#Z# ddl$m%Z% 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l0m1Z1 ddl2m3Z3 ddl4Z4dZ5G dd dee Z6dddZ7dd Z8dS ) zHClasses for representing collections for the Google Cloud Firestore API.    )annotationsN)TYPE_CHECKINGAnyAsyncGeneratorAsyncIterator	Coroutine	GeneratorGenericIterableSequenceTupleUnionOptional)retry)_helpers)BaseDocumentReference)	QueryType)BaseAggregationQuery)DocumentSnapshot)BaseVectorQueryDistanceMeasure)AsyncDocumentReference)DocumentReference)	FieldPath)PipelineSource)ExplainOptions)QueryResultsList)StreamGenerator)Transaction)Vector)VectorQuery>ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789c                   @  s  e Zd ZdZd}ddZdd Zedd	 Zed
d Zd~ddZ	dddZ
dddZddddZdddZ			ddd$d%Z			ddd'd(Z				ddd.d/Z			ddd0dd2d3Zd~d4d5Zdd8d9Z			ddd:dd=d>Zdd@dAZddDdEZddFdGZddIdJZddMdNZddOdPZddQdRZddSdTZ		dddVdWZ			ddddXdd^d_Z			ddddXddadbZdcdd Z ddedfZ!dddidjZ"dddkdlZ#dddmddwdxZ$dd{d|Z%dS )BaseCollectionReferencea  A reference to a collection in a Firestore database.

    The collection may already exist or this class can facilitate creation
    of documents within the collection.

    Args:
        path (Tuple[str, ...]): The components in the collection path.
            This is a series of strings representing each collection and
            sub-collection ID, as well as the document IDs for any documents
            that contain a sub-collection.
        kwargs (dict): The keyword arguments for the constructor. The only
            supported keyword is ``client`` and it must be a
            :class:`~google.cloud.firestore_v1.client.Client` if provided. It
            represents the client that created this collection reference.

    Raises:
        ValueError: if

            * the ``path`` is empty
            * there are an even number of elements
            * a collection ID in ``path`` is not a string
            * a document ID in ``path`` is not a string
        TypeError: If a keyword other than ``client`` is used.
    returnNonec                 O  s6   t j|dd || _|dd | _|rtd|dd S )NT)is_collectionclientzReceived unexpected argumentszOnly `client` is supported)r   verify_path_pathpop_client	TypeError)selfpathkwargs r/   p/var/www/newdalilibackend/backend/venv/lib/python3.10/site-packages/google/cloud/firestore_v1/base_collection.py__init__[   s   z BaseCollectionReference.__init__c                 C  s(   t || jstS | j|jko| j|jkS N)
isinstance	__class__NotImplementedr(   r*   )r,   otherr/   r/   r0   __eq__d   s   zBaseCollectionReference.__eq__c                 C  s
   | j d S )zfThe collection identifier.

        Returns:
            str: The last component of the path.
        )r(   r,   r/   r/   r0   idi   s   
zBaseCollectionReference.idc                 C  s,   t | jdkr	dS | jdd }| jj| S )a  Document that owns the current collection.

        Returns:
            Optional[:class:`~google.cloud.firestore_v1.document.DocumentReference`]:
            The parent document, if the current collection is not a
            top-level collection.
           Nr8   )lenr(   r*   document)r,   parent_pathr/   r/   r0   parentr   s   	zBaseCollectionReference.parentr   c                 C     t r2   NotImplementedErrorr9   r/   r/   r0   _query      zBaseCollectionReference._queryr   c                 C  r@   r2   rA   r9   r/   r/   r0   _aggregation_query   rD   z*BaseCollectionReference._aggregation_queryr   c                 C  r@   r2   rA   r9   r/   r/   r0   _vector_query   rD   z%BaseCollectionReference._vector_queryNdocument_idOptional[str]r   c                 C  s6   |du rt  }| jd r| j|f n|f}| jj| S )a  Create a sub-document underneath the current collection.

        Args:
            document_id (Optional[str]): The document identifier
                within the current collection. If not provided, will default
                to a random 20 character string composed of digits,
                uppercase and lowercase and letters.

        Returns:
            :class:`~google.cloud.firestore_v1.base_document.BaseDocumentReference`:
            The child document.
        Nr   )_auto_idr(   r*   r=   )r,   rG   
child_pathr/   r/   r0   r=      s   z BaseCollectionReference.documentTuple[Any, str]c                 C  sD   | j }|du rtj| jjdf}n|j}tj|| jf}||fS )ar  Get fully-qualified parent path and prefix for this collection.

        Returns:
            Tuple[str, str]: Pair of

            * the fully-qualified (with database and project) path to the
              parent of this collection (will either be the database path
              or a document path).
            * the prefix to a document in this collection.
        N	documents)r?   r   DOCUMENT_PATH_DELIMITERjoinr*   _database_string_document_pathr:   )r,   
parent_docr>   expected_prefixr/   r/   r0   _parent_info   s   
z$BaseCollectionReference._parent_infodocument_datadictr   2retries.Retry | retries.AsyncRetry | object | NonetimeoutOptional[float]c                 C  s,   |du rt  }| |}t||}||fS )z+Shared setup for async / sync :method:`add`N)rI   r=   r   make_retry_timeout_kwargs)r,   rT   rG   r   rW   document_refr.   r/   r/   r0   	_prep_add   s
   
z!BaseCollectionReference._prep_add<Union[Tuple[Any, Any], Coroutine[Any, Any, Tuple[Any, Any]]]c                 C  r@   r2   rA   )r,   rT   rG   r   rW   r/   r/   r0   add   s   zBaseCollectionReference.add	page_sizeOptional[int]	read_timeOptional[datetime.datetime]Tuple[dict, dict]c           	      C  sF   |   \}}|| j|dddid}|dur||d< t||}||fS )z6Shared setup for async / sync :method:`list_documents`Tfield_pathsN)r?   collection_idr^   show_missingmaskr`   )rS   r:   r   rY   )	r,   r^   r   rW   r`   r?   _requestr.   r/   r/   r0   _prep_list_documents   s   
z,BaseCollectionReference._prep_list_documents)r`   ZUnion[Generator[DocumentReference, Any, Any], AsyncGenerator[AsyncDocumentReference, Any]]c                C  r@   r2   rA   )r,   r^   r   rW   r`   r/   r/   r0   list_documents   s   z&BaseCollectionReference.list_documentsc                 C  s   |    S r2   )rC   	recursiver9   r/   r/   r0   rl      s   z!BaseCollectionReference.recursiverc   Iterable[str]c                 C     |   }||S )a  Create a "select" query with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.select` for
        more information on this method.

        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.
        )rC   select)r,   rc   queryr/   r/   r0   ro      s   
zBaseCollectionReference.selectfilter
field_path	op_stringc                C  sz   |   }|r7|r7|durtd|dkr0|dkr0g }|D ]}t|tr(| |}|| q|}||||S |j|dS )a  Create a "where" query with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.where` for
        more information on this method.

        Args:
            field_path (str): A field path (``.``-delimited list of
                field names) for the field to filter on. Optional.
            op_string (str): A comparison operation in the form of a string.
                Acceptable values are ``<``, ``<=``, ``==``, ``>=``, ``>``,
                and ``in``. Optional.
            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.  If ``op_string`` is ``in``, ``value``
                must be a sequence of values. Optional.
            filter (class:`~google.cloud.firestore_v1.base_query.BaseFilter`): an instance of a Filter.
                Either a FieldFilter or a CompositeFilter.
        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A filtered query.
        Raises:
            ValueError, if both the positional arguments (field_path, op_string, value)
                and the filter keyword argument are passed at the same time.
        NzICan't pass in both the positional arguments and 'filter' at the same time__name__inrq   )rC   
ValueErrorr3   strr=   appendwhere)r,   rs   rt   valuerr   rp   wrapped_namesnamer/   r/   r0   rz     s   !

zBaseCollectionReference.whererx   c                 K  s   |   }|j|fi |S )a  Create an "order by" query with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.order_by` for
        more information on this method.

        Args:
            field_path (str): A field path (``.``-delimited list of
                field names) on which to order the query results.
            kwargs (Dict[str, Any]): The keyword arguments to pass along
                to the query. The only supported keyword is ``direction``,
                see :meth:`~google.cloud.firestore_v1.query.Query.order_by`
                for more information.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            An "order by" query.
        )rC   order_by)r,   rs   r.   rp   r/   r/   r0   r~   @  s   z BaseCollectionReference.order_bycountintc                 C  rn   )a-  Create a limited query with this collection as parent.

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

        See
        :meth:`~google.cloud.firestore_v1.query.Query.limit` for
        more information on this method.

        Args:
            count (int): Maximum number of documents to return that match
                the query.

        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A limited query.
        )rC   limitr,   r   rp   r/   r/   r0   r   V  s   
zBaseCollectionReference.limitc                 C  rn   )aD  Create a limited to last query with this collection as parent.

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

        See
        :meth:`~google.cloud.firestore_v1.query.Query.limit_to_last`
        for more information on this method.

        Args:
            count (int): Maximum number of documents to return that
                match the query.
        Returns:
            :class:`~google.cloud.firestore_v1.query.Query`:
            A limited to last query.
        )rC   limit_to_lastr   r/   r/   r0   r   l  s   
z%BaseCollectionReference.limit_to_lastnum_to_skipc                 C  rn   )a  Skip to an offset in a query with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.offset` for
        more information on this method.

        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.
        )rC   offset)r,   r   rp   r/   r/   r0   r     s   
zBaseCollectionReference.offsetdocument_fields*Union[DocumentSnapshot, dict, list, tuple]c                 C  rn   )a  Start query at a cursor with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.start_at` for
        more information on this method.

        Args:
            document_fields (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.
        )rC   start_atr,   r   rp   r/   r/   r0   r        
z BaseCollectionReference.start_atc                 C  rn   )a  Start query after a cursor with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.start_after` for
        more information on this method.

        Args:
            document_fields (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.
        )rC   start_afterr   r/   r/   r0   r     r   z#BaseCollectionReference.start_afterc                 C  rn   )a  End query before a cursor with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.end_before` for
        more information on this method.

        Args:
            document_fields (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.
        )rC   
end_beforer   r/   r/   r0   r     r   z"BaseCollectionReference.end_beforec                 C  rn   )a  End query at a cursor with this collection as parent.

        See
        :meth:`~google.cloud.firestore_v1.query.Query.end_at` for
        more information on this method.

        Args:
            document_fields (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.
        )rC   end_atr   r/   r/   r0   r     r   zBaseCollectionReference.end_atTuple[Any, dict]c                 C  s   |   }t||}||fS )z:Shared setup for async / sync :meth:`get` / :meth:`stream`)rC   r   rY   )r,   r   rW   rp   r.   r/   r/   r0   _prep_get_or_stream  s   z+BaseCollectionReference._prep_get_or_stream)explain_optionsr`   transactionOptional[Transaction]r   Optional[ExplainOptions]\QueryResultsList[DocumentSnapshot] | Coroutine[Any, Any, QueryResultsList[DocumentSnapshot]]c                C  r@   r2   rA   r,   r   r   rW   r   r`   r/   r/   r0   get  s   zBaseCollectionReference.getCStreamGenerator[DocumentSnapshot] | AsyncIterator[DocumentSnapshot]c                C  r@   r2   rA   r   r/   r/   r0   stream  s   	zBaseCollectionReference.streamc                 C  r@   r2   rA   )r,   callbackr/   r/   r0   on_snapshot  rD   z#BaseCollectionReference.on_snapshotc                 C  s   |   j|dS )z
        Adds a count over the nested query.

        :type alias: str
        :param alias: (Optional) The alias for the count
        alias)rE   r   )r,   r   r/   r/   r0   r     s   zBaseCollectionReference.count	field_refstr | FieldPathc                 C     |   j||dS )a  
        Adds a sum over the nested 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   )rE   sumr,   r   r   r/   r/   r0   r     s   zBaseCollectionReference.sumc                 C  r   )a  
        Adds an avg over the nested 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   )rE   avgr   r/   r/   r0   r   -  s   zBaseCollectionReference.avgdistance_result_fielddistance_thresholdvector_fieldquery_vectorUnion[Vector, Sequence[float]]r   distance_measurer   r   r   r    c                C  s   |   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(Union[Vector, Sequence[float]]): The query vector that we are searching on. Must be a vector of no more
                than 2048 dimensions.
            limit (int): The number of nearest neighbors to return. Must be a positive integer of no more than 1000.
            distance_measure (:class:`DistanceMeasure`): The Distance Measure to use.
            distance_result_field (Optional[str]):
                Name of the field to output the result of the vector distance calculation
            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.
        r   )rF   find_nearest)r,   r   r   r   r   r   r   r/   r/   r0   r   :  s   z$BaseCollectionReference.find_nearestsource'PipelineSource'c                 C  s   |   |S )a  
        Convert this query into a Pipeline

        Queries containing a `cursor` or `limit_to_last` are not currently supported

        Args:
            source: the PipelineSource to build the pipeline off o
        Raises:
            - NotImplementedError: raised if the query contains a `cursor` or `limit_to_last`
        Returns:
            a Pipeline representing the query
        )rC   _build_pipeline)r,   r   r/   r/   r0   r   _  s   z'BaseCollectionReference._build_pipeline)r#   r$   )r#   r   )r#   r   )r#   r   r2   )rG   rH   r#   r   )r#   rK   )NNN)rT   rU   rG   rH   r   rV   rW   rX   )
rT   rU   rG   rH   r   rV   rW   rX   r#   r\   )NNNN)
r^   r_   r   rV   rW   rX   r`   ra   r#   rb   )
r^   r_   r   rV   rW   rX   r`   ra   r#   rj   )rc   rm   r#   r   )rs   rH   rt   rH   r#   r   )rs   rx   r#   r   )r   r   r#   r   )r   r   )r   r   r#   r   )r   r   r#   r   )NN)r   rV   rW   rX   r#   r   )r   r   r   rV   rW   rX   r   r   r`   ra   r#   r   )r   r   r   rV   rW   rX   r   r   r`   ra   r#   r   )r   r   )r   rx   r   r   r   r   r   r   r   rH   r   rX   r#   r    )r   r   )&ru   
__module____qualname____doc__r1   r7   propertyr:   r?   rC   rE   rF   r=   rS   r[   r]   ri   rk   rl   ro   rz   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r/   r/   r/   r0   r"   A   s    
	








5







	%r"   r#   rx   c                   C  s   d dd tdD S )zGenerate a "random" automatically generated ID.

    Returns:
        str: A 20 character string composed of digits, uppercase and
        lowercase and letters.
     c                 s  s    | ]}t tV  qd S r2   )randomchoice_AUTO_ID_CHARS).0rg   r/   r/   r0   	<genexpr>w  s    z_auto_id.<locals>.<genexpr>   )rN   ranger/   r/   r/   r0   rI   o  s   rI   c                 C  s   |j tjd }| |S )aL  Convert Document resource to document ref.

    Args:
        collection_reference (google.api_core.page_iterator.GRPCIterator):
            iterator response
        item (dict): document resource

    Returns:
            :class:`~google.cloud.firestore_v1.base_document.BaseDocumentReference`:
            The child document
    r8   )r}   splitr   rM   r=   )collection_referenceitemrG   r/   r/   r0   _item_to_document_refz  s   
r   )r#   rx   )9r   
__future__r   r   typingr   r   r   r   r   r   r	   r
   r   r   r   r   google.api_corer   retriesgoogle.cloud.firestore_v1r   'google.cloud.firestore_v1.base_documentr   $google.cloud.firestore_v1.base_queryr   *google.cloud.firestore_v1.base_aggregationr   r   +google.cloud.firestore_v1.base_vector_queryr   r   (google.cloud.firestore_v1.async_documentr   "google.cloud.firestore_v1.documentr   $google.cloud.firestore_v1.field_pathr   )google.cloud.firestore_v1.pipeline_sourcer   'google.cloud.firestore_v1.query_profiler   'google.cloud.firestore_v1.query_resultsr   *google.cloud.firestore_v1.stream_generatorr   %google.cloud.firestore_v1.transactionr    google.cloud.firestore_v1.vectorr   &google.cloud.firestore_v1.vector_queryr    datetimer   r"   rI   r   r/   r/   r/   r0   <module>   s>   8    
2