o
    }l~i):                     @  s  d Z ddlmZ ddlZddl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 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 erddlmZ ddlm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)Z)G dd de*Z+G dd deZ,G dd de,Z-G dd de,Z.G dd de,Z/d%d!d"Z0G d#d$ d$eZ1dS )&aU  Classes for representing aggregation queries for the Google Cloud Firestore API.

A :class:`~google.cloud.firestore_v1.aggregation.AggregationQuery` can be created directly from
a :class:`~google.cloud.firestore_v1.collection.Collection` and that can be
a more common way to create an aggregation query than direct usage of the constructor.
    )annotationsN)ABC)TYPE_CHECKINGAny	CoroutineListOptionalTupleUnionIterable)gapic_v1)retry)_helpers)	FieldPath)StructuredAggregationQuery)AggregateFunction)Count)AliasedExpression)Field)transaction)AsyncStreamGenerator)ExplainOptions)QueryResultsList)StreamGenerator)PipelineSourcec                   @  s,   e Zd ZdZddddZd	d
 Zdd ZdS )AggregationResulta  
    A class representing result from Aggregation Query
    :type alias: str
    :param alias: The alias for the aggregation.
    :type value: int
    :param value: The resulting value from the aggregation.
    :type read_time:
    :param value: The resulting read_time
    Naliasstrvaluefloatc                 C  s   || _ || _|| _d S Nr   r   	read_time)selfr   r   r"    r$   q/var/www/newdalilibackend/backend/venv/lib/python3.10/site-packages/google/cloud/firestore_v1/base_aggregation.py__init__C   s   
zAggregationResult.__init__c                 C  s   d| j  d| j d| j dS )Nz<Aggregation alias=z, value=z, readtime=>r!   r#   r$   r$   r%   __repr__H   s   zAggregationResult.__repr__c                 C  s   | j | jiS r    )r   r   r(   r$   r$   r%   _to_dictK   s   zAggregationResult._to_dictr    )r   r   r   r   )__name__
__module____qualname____doc__r&   r)   r*   r$   r$   r$   r%   r   8   s
    
r   c                   @  s>   e Zd ZddddZejdd ZejdddZdd ZdS )BaseAggregationNr   
str | Nonec                 C  s
   || _ d S r    r   r#   r   r$   r$   r%   r&   P   s   
zBaseAggregation.__init__c                 C     dS )4Convert this instance to the protobuf representationNr$   r(   r$   r$   r%   _to_protobufS       zBaseAggregation._to_protobufautoindexerIterable[int]return$AliasedExpression[AggregateFunction]c                 C  r3   )a6  
        Convert this instance to a pipeline expression for use with pipeline.aggregate()

        Args:
          autoindexer: If an alias isn't supplied, one should be created with the format "field_n"
            The autoindexer is an iterable that provides the `n` value to use for each expression
        Nr$   r#   r7   r$   r$   r%   _to_pipeline_exprW   r6   z!BaseAggregation._to_pipeline_exprc                 C  s   | j dur| j S dt| S )zG
        Helper to build the alias for the pipeline expression
        Nfield_)r   nextr;   r$   r$   r%   _pipeline_aliasc   s   
zBaseAggregation._pipeline_aliasr    r   r0   )r7   r8   r9   r:   )	r+   r,   r-   r&   abcabstractmethodr5   r<   r?   r$   r$   r$   r%   r/   O   s    
r/   c                      s2   e Zd Zdd fddZdd Zdd
dZ  ZS )CountAggregationNr   r0   c                   s   t t| j|d d S Nr1   )superrC   r&   r2   	__class__r$   r%   r&   n   s   zCountAggregation.__init__c                 C  s&   t  }| jr| j|_t j |_|S r4   )r   Aggregationr   r   countr#   aggregation_pbr$   r$   r%   r5   q   s
   zCountAggregation._to_protobufr7   r8   c                 C  s   t  | |S r    )r   as_r?   r;   r$   r$   r%   r<   y   s   z"CountAggregation._to_pipeline_exprr    r@   r7   r8   r+   r,   r-   r&   r5   r<   __classcell__r$   r$   rF   r%   rC   m   s    rC   c                      2   e Zd Zdd fddZdd	 ZdddZ  ZS )SumAggregationN	field_refstr | FieldPathr   r0   c                   2   t |tr	| n|}|| _tt| j|d d S rD   )
isinstancer   to_api_reprrS   rE   rR   r&   r#   rS   r   	field_strrF   r$   r%   r&   ~      zSumAggregation.__init__c                 C  2   t  }| jr| j|_t j |_| j|jj_|S rH   )r   rI   r   SumsumrS   field
field_pathrK   r$   r$   r%   r5         zSumAggregation._to_protobufr7   r8   c                 C     t | j | |S r    )r   ofrS   r]   rM   r?   r;   r$   r$   r%   r<         z SumAggregation._to_pipeline_exprr    rS   rT   r   r0   rN   rO   r$   r$   rF   r%   rR   }       	rR   c                      rQ   )AvgAggregationNrS   rT   r   r0   c                   rU   rD   )rV   r   rW   rS   rE   rf   r&   rX   rF   r$   r%   r&      rZ   zAvgAggregation.__init__c                 C  r[   rH   )r   rI   r   AvgavgrS   r^   r_   rK   r$   r$   r%   r5      r`   zAvgAggregation._to_protobufr7   r8   c                 C  ra   r    )r   rb   rS   averagerM   r?   r;   r$   r$   r%   r<      rc   z AvgAggregation._to_pipeline_exprr    rd   rN   rO   r$   r$   rF   r%   rf      re   rf   r9   List[AggregationResult]c                   s     fdd j jj D }|S )Nc                   s4   g | ]}t | jj| jp jj| j jd qS )r!   )r   resultaggregate_fieldsinteger_valuedouble_valuer"   ).0keyresponse_pbr$   r%   
<listcomp>   s    z-_query_response_to_result.<locals>.<listcomp>)rk   rl   pbkeys)rr   resultsr$   rq   r%   _query_response_to_result   s   

rw   c                   @  s   e Zd ZdZd8d9ddZed	d
 Zd8d:ddZd8d;ddZd8d;ddZ	d<ddZ
d=ddZd>ddZ					d?d@d'd(Zejdejjdfddd)dAd+d,Zejdejjdfddd)dBd2d3ZdCd6d7ZdS )DBaseAggregationQueryz5Represents an aggregation query to the Firestore API.Nr   r0   r9   Nonec                 C  s   || _ || _|j| _g | _d S r    )_nested_query_alias_parent_collection_ref_aggregations)r#   nested_queryr   r$   r$   r%   r&      s   
zBaseAggregationQuery.__init__c                 C  s   | j jS r    )r}   _clientr(   r$   r$   r%   r      s   zBaseAggregationQuery._clientc                 C  s   t |d}| j| | S )z4
        Adds a count over the nested query
        r1   )rC   r~   append)r#   r   count_aggregationr$   r$   r%   rJ      s   
zBaseAggregationQuery.countrS   rT   c                 C     t ||d}| j| | S )z2
        Adds a sum over the nested query
        r1   )rR   r~   r   )r#   rS   r   sum_aggregationr$   r$   r%   r]         zBaseAggregationQuery.sumc                 C  r   )z3
        Adds an avg over the nested query
        r1   )rf   r~   r   )r#   rS   r   avg_aggregationr$   r$   r%   rh      r   zBaseAggregationQuery.avgaggregationr/   c                 C     | j | dS )z
        Adds an aggregation operation to the nested query

        :type aggregation: :class:`google.cloud.firestore_v1.aggregation.BaseAggregation`
        :param aggregation: An aggregation operation, e.g. a CountAggregation
        N)r~   r   )r#   r   r$   r$   r%   add_aggregation      z$BaseAggregationQuery.add_aggregationaggregationsList[BaseAggregation]c                 C  r   )z
        Adds a list of aggregations to the nested query

        :type aggregations: list
        :param aggregations: a list of aggregation operations
        N)r~   extend)r#   r   r$   r$   r%   add_aggregations   r   z%BaseAggregationQuery.add_aggregationsr   c                 C  s6   t  }| j |_| jD ]}| }|j| q|S r    )r   rz   r5   structured_queryr~   r   r   )r#   rt   r   rL   r$   r$   r%   r5      s   
z!BaseAggregationQuery._to_protobufr   6Union[retries.Retry, retries.AsyncRetry, None, object]timeoutfloat | Noneexplain_optionsOptional[ExplainOptions]r"   Optional[datetime.datetime]Tuple[dict, dict]c           
      C  sX   | j  \}}||  t|d}|r| |d< |d ur"||d< t||}	||	fS )N)parentstructured_aggregation_queryr   r   r"   )r}   _parent_infor5   r   get_transaction_idr*   make_retry_timeout_kwargs)
r#   r   r   r   r   r"   parent_pathexpected_prefixrequestkwargsr$   r$   r%   _prep_stream   s   z!BaseAggregationQuery._prep_stream)r   r"   XQueryResultsList[AggregationResult] | Coroutine[Any, Any, List[List[AggregationResult]]]c                C  r3   )a  Runs the aggregation query.

        This sends a ``RunAggregationQuery`` RPC and returns a list of
        aggregation results in the stream of ``RunAggregationQueryResponse``
        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.
            read_time (Optional[datetime.datetime]): If set, reads documents as they were at the given
                time. This must be a timestamp within the past one hour, or if Point-in-Time Recovery
                is enabled, can additionally be a whole minute timestamp within the past 7 days. If no
                timezone is specified in the :class:`datetime.datetime` object, it is assumed to be UTC.

        Returns:
            (QueryResultsList[List[AggregationResult]] | Coroutine[Any, Any, List[List[AggregationResult]]]):
            The aggregation query results.
        Nr$   r#   r   r   r   r   r"   r$   r$   r%   get  r6   zBaseAggregationQuery.getr   !Optional[transaction.Transaction]2retries.Retry | retries.AsyncRetry | object | NoneOptional[float]XStreamGenerator[List[AggregationResult]] | AsyncStreamGenerator[List[AggregationResult]]c                C  r3   )a  Runs the aggregation query.

        This sends a``RunAggregationQuery`` RPC and returns a generator in the stream of ``RunAggregationQueryResponse`` messages.

        Args:
            transaction
                (Optional[:class:`~google.cloud.firestore_v1.transaction.Transaction`]):
                An existing transaction that this query will run in.
            retry (Optional[google.api_core.retry.Retry]): Designation of what
                errors, if any, should be retried.  Defaults to a
                system-specified policy.
            timeout (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.
            read_time (Optional[datetime.datetime]): If set, reads documents as they were at the given
                time. This must be a timestamp within the past one hour, or if Point-in-Time Recovery
                is enabled, can additionally be a whole minute timestamp within the past 7 days. If no
                timezone is specified in the :class:`datetime.datetime` object, it is assumed to be UTC.

        Returns:
            StreamGenerator[List[AggregationResult]] | AsyncStreamGenerator[List[AggregationResult]]:
            A generator of the query results.
        Nr$   r   r$   r$   r%   stream=  r6   zBaseAggregationQuery.streamsource'PipelineSource'c                   s2   t jdd  fdd| jD }| j|j| 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 of
        Raises:
            - NotImplementedError: raised if the query contains a `cursor` or `limit_to_last`
        Returns:
            a Pipeline representing the query
           )startc                   s   g | ]}|  qS r$   )r<   )ro   ar7   r$   r%   rs   w  s    z8BaseAggregationQuery._build_pipeline.<locals>.<listcomp>)	itertoolsrJ   r~   rz   _build_pipeline	aggregate)r#   r   exprsr$   r   r%   r   h  s   z$BaseAggregationQuery._build_pipeliner    )r   r0   r9   ry   r@   rd   )r   r/   r9   ry   )r   r   r9   ry   )r9   r   )NNNNN)
r   r   r   r   r   r   r"   r   r9   r   )
r   r   r   r   r   r   r"   r   r9   r   )r   r   r   r   r   r   r   r   r"   r   r9   r   )r   r   )r+   r,   r-   r.   r&   propertyr   rJ   r]   rh   r   r   r5   r   rA   rB   r   methodDEFAULTr   r   r   r$   r$   r$   r%   rx      sD    


	
	-	*rx   )r9   rj   )2r.   
__future__r   rA   r   r   typingr   r   r   r   r   r	   r
   r   google.api_corer   r   retriesgoogle.cloud.firestore_v1r   $google.cloud.firestore_v1.field_pathr   google.cloud.firestore_v1.typesr   .google.cloud.firestore_v1.pipeline_expressionsr   r   r   r   r   0google.cloud.firestore_v1.async_stream_generatorr   'google.cloud.firestore_v1.query_profiler   'google.cloud.firestore_v1.query_resultsr   *google.cloud.firestore_v1.stream_generatorr   )google.cloud.firestore_v1.pipeline_sourcer   datetimeobjectr   r/   rC   rR   rf   rw   rx   r$   r$   r$   r%   <module>   s<   (
