U
    >i,                     @  s6  d Z ddlm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 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 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dZ&G dd deZ'd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)gapic_v1)retry)_helpers)	FieldPath)StructuredAggregationQuery)transaction)AsyncStreamGenerator)ExplainOptions)QueryResultsList)StreamGeneratorc                   @  s*   e Zd ZdZd
ddd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strfloat)aliasvaluec                 C  s   || _ || _|| _d S Nr   r   	read_time)selfr   r   r    r   N/tmp/pip-unpacked-wheel-599y42ri/google/cloud/firestore_v1/base_aggregation.py__init__:   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__?   s    zAggregationResult.__repr__)N)__name__
__module____qualname____doc__r    r#   r   r   r   r   r   /   s   
r   c                   @  s*   e Zd ZdddddZejdd ZdS )	BaseAggregationN
str | Noner   c                 C  s
   || _ d S r   r*   r   r   r   r   r   r    D   s    zBaseAggregation.__init__c                 C  s   dS )4Convert this instance to the protobuf representationNr   r"   r   r   r   _to_protobufG   s    zBaseAggregation._to_protobuf)N)r$   r%   r&   r    abcabstractmethodr-   r   r   r   r   r(   C   s   r(   c                      s,   e Zd Zddd fddZdd Z  ZS )	CountAggregationNr)   r*   c                   s   t t| j|d d S Nr*   )superr0   r    r+   	__class__r   r   r    M   s    zCountAggregation.__init__c                 C  s    t  }| j|_t j |_|S r,   )r   Aggregationr   ZCountcountr   aggregation_pbr   r   r   r-   P   s    zCountAggregation._to_protobuf)Nr$   r%   r&   r    r-   __classcell__r   r   r3   r   r0   L   s   r0   c                      s.   e Zd Zd	ddd fddZdd Z  ZS )
SumAggregationNstr | FieldPathr)   	field_refr   c                   s.   t |tr| }|| _tt| j|d d S r1   )
isinstancer   to_api_reprr?   r2   r<   r    r   r?   r   r3   r   r   r    Y   s    
zSumAggregation.__init__c                 C  s,   t  }| j|_t j |_| j|jj_|S r5   )r   r6   r   ZSumsumr?   field
field_pathr8   r   r   r   r-   `   s
    zSumAggregation._to_protobuf)Nr:   r   r   r3   r   r<   X   s   r<   c                      s.   e Zd Zd	ddd fddZdd Z  ZS )
AvgAggregationNr=   r)   r>   c                   s.   t |tr| }|| _tt| j|d d S r1   )r@   r   rA   r?   r2   rF   r    rB   r3   r   r   r    j   s    
zAvgAggregation.__init__c                 C  s,   t  }| j|_t j |_| j|jj_|S r5   )r   r6   r   ZAvgavgr?   rD   rE   r8   r   r   r   r-   q   s
    zAvgAggregation._to_protobuf)Nr:   r   r   r3   r   rF   i   s   rF   zList[AggregationResult]returnc                   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_fieldsZinteger_valueZdouble_valuer   ).0keyresponse_pbr   r   
<listcomp>}   s   z-_query_response_to_result.<locals>.<listcomp>)rJ   rK   pbkeys)rO   resultsr   rN   r   _query_response_to_resultz   s    

rT   c                	   @  s   e Zd ZdZd1dddddZedd	 Zd2dd
ddZd3dddddZd4dddddZ	dddddZ
dddddZddddZd5dd d!d"d#d$d%Zejdejjdfdd&dd d!d'd#d(d)Zejdejjdfdd&d*d+d,d!d-d.d/d0ZdS )6BaseAggregationQueryz5Represents an aggregation query to the Firestore API.Nr)   None)r   rI   c                 C  s   || _ || _|j| _g | _d S r   )_nested_query_alias_parent_collection_ref_aggregations)r   Znested_queryr   r   r   r   r       s    zBaseAggregationQuery.__init__c                 C  s   | j jS r   )rZ   _clientr"   r   r   r   r\      s    zBaseAggregationQuery._clientr*   c                 C  s   t |d}| j| | S )z4
        Adds a count over the nested query
        r*   )r0   r[   append)r   r   Zcount_aggregationr   r   r   r7      s    
zBaseAggregationQuery.countr=   r>   c                 C  s   t ||d}| j| | S )z2
        Adds a sum over the nested query
        r*   )r<   r[   r]   )r   r?   r   Zsum_aggregationr   r   r   rC      s    zBaseAggregationQuery.sumc                 C  s   t ||d}| j| | S )z3
        Adds an avg over the nested query
        r*   )rF   r[   r]   )r   r?   r   Zavg_aggregationr   r   r   rG      s    zBaseAggregationQuery.avgr(   )aggregationrI   c                 C  s   | 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   s    z$BaseAggregationQuery.add_aggregationzList[BaseAggregation])aggregationsrI   c                 C  s   | j | dS )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   s    z%BaseAggregationQuery.add_aggregationsr   rH   c                 C  s6   t  }| j |_| jD ]}| }|j| q|S r   )r   rW   r-   Zstructured_queryr[   r`   r]   )r   rQ   r^   r9   r   r   r   r-      s    
z!BaseAggregationQuery._to_protobufz6Union[retries.Retry, retries.AsyncRetry, None, object]zfloat | NonezOptional[ExplainOptions]zTuple[dict, dict])r   timeoutexplain_optionsrI   c           	      C  sH   | j  \}}||  t|d}|r4| |d< t||}||fS )N)parentZstructured_aggregation_queryr   rd   )rZ   Z_parent_infor-   r   Zget_transaction_idZ_to_dictZmake_retry_timeout_kwargs)	r   r   r   rc   rd   parent_pathZexpected_prefixrequestkwargsr   r   r   _prep_stream   s    z!BaseAggregationQuery._prep_stream)rd   zXQueryResultsList[AggregationResult] | Coroutine[Any, Any, List[List[AggregationResult]]]c                C  s   dS )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.

        Returns:
            (QueryResultsList[List[AggregationResult]] | Coroutine[Any, Any, List[List[AggregationResult]]]):
            The aggregation query results.
        Nr   r   r   r   rc   rd   r   r   r   get   s    zBaseAggregationQuery.getz!Optional[transaction.Transaction]z2retries.Retry | retries.AsyncRetry | object | NonezOptional[float]zXStreamGenerator[List[AggregationResult]] | AsyncStreamGenerator[List[AggregationResult]])r   r   rc   rd   rI   c                C  s   dS )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.

        Returns:
            StreamGenerator[List[AggregationResult]] | AsyncStreamGenerator[List[AggregationResult]]:
            A generator of the query results.
        Nr   rj   r   r   r   stream  s    zBaseAggregationQuery.stream)N)N)N)N)NNNN)r$   r%   r&   r'   r    propertyr\   r7   rC   rG   r_   rb   r-   ri   r.   r/   r   methodDEFAULTrk   rl   r   r   r   r   rU      s:   
		    (	rU   )(r'   
__future__r   r.   r   typingr   r   r   r   r   r	   r
   Zgoogle.api_corer   r   retriesZgoogle.cloud.firestore_v1r   Z$google.cloud.firestore_v1.field_pathr   Zgoogle.cloud.firestore_v1.typesr   r   Z0google.cloud.firestore_v1.async_stream_generatorr   Z'google.cloud.firestore_v1.query_profiler   Z'google.cloud.firestore_v1.query_resultsr   Z*google.cloud.firestore_v1.stream_generatorr   objectr   r(   r0   r<   rF   rT   rU   r   r   r   r   <module>   s,   $	