o
    ,=j]7  ã                   @  sú   d Z ddlmZ ddlmZmZmZmZmZ ddl	m
Z
mZ ddl	mZ ddlmZ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 erddd
lZddlm Z  ddl!m"Z" ddl#m$Z$ G dd„ dej%eƒZ&G dd„ deƒZ'ddd„Z(d
S )zEHelpers for applying Google Cloud Firestore changes in a transaction.é    )Úannotations)ÚTYPE_CHECKINGÚAnyÚCallableÚ	GeneratorÚOptional)Ú
exceptionsÚgapic_v1)Úretry)Ú_helpersÚbatch)Ú_CANT_BEGINÚ_CANT_COMMITÚ_CANT_ROLLBACKÚ_EXCEED_ATTEMPTS_TEMPLATEÚ_WRITE_READ_ONLYÚMAX_ATTEMPTSÚBaseTransactionÚ_BaseTransactional)ÚDocumentReference)ÚQueryN)ÚDocumentSnapshot)ÚExplainOptions)ÚStreamGeneratorc                      sŒ   e Zd ZdZedfd)‡ fdd„Zd*‡ fd	d
„Zd+d,dd„Zd)dd„Zd-dd„Z	e
jjdfddœd.dd„Ze
jjdfdddœd/d'd(„Z‡  ZS )0ÚTransactionaD  Accumulate read-and-write operations to be sent in a transaction.

    Args:
        client (:class:`~google.cloud.firestore_v1.client.Client`):
            The client that created this transaction.
        max_attempts (Optional[int]): The maximum number of attempts for
            the transaction (i.e. allowing retries). Defaults to
            :attr:`~google.cloud.firestore_v1.transaction.MAX_ATTEMPTS`.
        read_only (Optional[bool]): Flag indicating if the transaction
            should be read-only or should allow writes. Defaults to
            :data:`False`.
    FÚreturnÚNonec                   s"   t t| ƒ |¡ t | ||¡ d S ©N)Úsuperr   Ú__init__r   )ÚselfÚclientZmax_attemptsZ	read_only©Ú	__class__© úoC:\Users\psant\Downloads\Anu Raj Backend\school\venv\Lib\site-packages\google/cloud/firestore_v1/transaction.pyr   =   s   zTransaction.__init__Ú	write_pbsÚlistc                   s"   | j rttƒ‚tt| ƒ |¡ dS )a
  Add `Write`` protobufs to this transaction.

        Args:
            write_pbs (List[google.cloud.firestore_v1.                write.Write]): A list of write protobufs to be added.

        Raises:
            ValueError: If this transaction is read-only.
        N)Ú
_read_onlyÚ
ValueErrorr   r   r   Ú_add_write_pbs)r    r&   r"   r$   r%   r*   A   s   
zTransaction._add_write_pbsNÚretry_idúbytes | Nonec                 C  sL   | j rt | j¡}t|ƒ‚| jjj| jj|  	|¡dœ| jj
d�}|j| _dS )zìBegin the transaction.

        Args:
            retry_id (Optional[bytes]): Transaction ID of a transaction to be
                retried.

        Raises:
            ValueError: If the current transaction has already begun.
        )ÚdatabaseÚoptions©ÚrequestÚmetadataN)Úin_progressr   ÚformatÚ_idr)   Ú_clientÚ_firestore_apiZbegin_transactionÚ_database_stringZ_options_protobufÚ_rpc_metadataÚtransaction)r    r+   ÚmsgZtransaction_responser$   r$   r%   Ú_beginP   s   
þûzTransaction._beginc                 C  sJ   | j sttƒ‚z| jjj| jj| jdœ| jjd� W |  	¡  dS |  	¡  w )zÀRoll back the transaction.

        Raises:
            ValueError: If no transaction is in progress.
            google.api_core.exceptions.GoogleAPICallError: If the rollback fails.
        )r-   r9   r/   N)
r2   r)   r   r5   r6   Úrollbackr7   r4   r8   Ú	_clean_up)r    r$   r$   r%   Ú	_rollbackg   s   þû	zTransaction._rollbackc                 C  sV   | j sttƒ‚| jjj| jj| j| jdœ| jj	d�}|  
¡  t|jƒ| _|j| _| jS )a¾  Transactionally commit the changes accumulated.

        Returns:
            List[:class:`google.cloud.firestore_v1.write.WriteResult`, ...]:
            The write results corresponding to the changes committed, returned
            in the same order as the changes were applied to this transaction.
            A write result contains an ``update_time`` field.

        Raises:
            ValueError: If no transaction is in progress.
        )r-   Zwritesr9   r/   N)r2   r)   r   r5   r6   Úcommitr7   Z
_write_pbsr4   r8   r=   r'   Zwrite_resultsZcommit_time)r    Zcommit_responser$   r$   r%   Ú_commit~   s   ýú	zTransaction._commit)Ú	read_timeÚ
referencesr
   úretries.Retry | object | NoneÚtimeoutúfloat | NonerA   údatetime.datetime | Noneú&Generator[DocumentSnapshot, Any, None]c                C  s4   t  ||¡}|dur||d< | jj|fd| i|¤ŽS )a  Retrieves multiple documents from Firestore.

        Args:
            references (List[.DocumentReference, ...]): Iterable of document
                references to be retrieved.
            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.
            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.

        Yields:
            .DocumentSnapshot: The next document snapshot that fulfills the
            query, or :data:`None` if the document does not exist.
        NrA   r9   )r   Úmake_retry_timeout_kwargsr5   Úget_all)r    rB   r
   rD   rA   Úkwargsr$   r$   r%   rI   ›   s   zTransaction.get_all)Úexplain_optionsrA   Úref_or_queryúDocumentReference | QueryúOptional[float]rK   úOptional[ExplainOptions]úOptional[datetime.datetime]úJStreamGenerator[DocumentSnapshot] | Generator[DocumentSnapshot, Any, None]c                C  s†   t  ||¡}|dur||d< t|tƒr(|durtdƒ‚| jj|gfd| i|¤ŽS t|tƒr?|dur5||d< |jdd| i|¤ŽS tdƒ‚)a>  Retrieve a document or a query result from the database.

        Args:
            ref_or_query (DocumentReference | Query):
                The document references or query object to return.
            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.
                Can only be used when running a query, not a document reference.
            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.

        Yields:
            .DocumentSnapshot: The next document snapshot that fulfills the
            query, or :data:`None` if the document does not exist.

        Raises:
            ValueError: if `ref_or_query` is not one of the supported types, or
            explain_options is provided when `ref_or_query` is a document
            reference.
        NrA   z^When type of `ref_or_query` is `AsyncDocumentReference`, `explain_options` cannot be provided.r9   rK   zIValue for argument "ref_or_query" must be a DocumentReference or a Query.r$   )	r   rH   Ú
isinstancer   r)   r5   rI   r   Ústream)r    rL   r
   rD   rK   rA   rJ   r$   r$   r%   Úgetº   s    %
ÿ
ÿzTransaction.get©r   r   )r&   r'   r   r   r   )r+   r,   r   r   )r   r'   )
rB   r'   r
   rC   rD   rE   rA   rF   r   rG   )rL   rM   r
   rC   rD   rN   rK   rO   rA   rP   r   rQ   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r*   r;   r>   r@   r	   ÚmethodÚDEFAULTrI   rT   Ú__classcell__r$   r$   r"   r%   r   /   s$    

 üú"üùr   c                      s6   e Zd ZdZd‡ fdd„Zdd	d
„Zddd„Z‡  ZS )Ú_TransactionalaY  Provide a callable object to use as a transactional decorater.

    This is surfaced via
    :func:`~google.cloud.firestore_v1.transaction.transactional`.

    Args:
        to_wrap (Callable[[:class:`~google.cloud.firestore_v1.transaction.Transaction`, ...], Any]):
            A callable that should be run (and retried) in a transaction.
    r   r   c                   s   t t| ƒ |¡ d S r   )r   r]   r   )r    Úto_wrapr"   r$   r%   r   þ   s   z_Transactional.__init__r9   r   r   c                 O  sH   |  ¡  |j| jd� |j| _| jdu r| j| _| j|g|¢R i |¤ŽS )am  Begin transaction and call the wrapped callable.

        Args:
            transaction
                (:class:`~google.cloud.firestore_v1.transaction.Transaction`):
                A transaction to execute the callable within.
            args (Tuple[Any, ...]): The extra positional arguments to pass
                along to the wrapped callable.
            kwargs (Dict[str, Any]): The extra keyword arguments to pass
                along to the wrapped callable.

        Returns:
            Any: result of the wrapped callable.

        Raises:
            Exception: Any failure caused by ``to_wrap``.
        )r+   N)r=   r;   r+   r4   Z
current_idr^   )r    r9   ÚargsrJ   r$   r$   r%   Ú_pre_commit  s   
z_Transactional._pre_commitc           
      O  s°   |   ¡  |js
tjnd}d}z=t|jƒD ],}| j|g|¢R i |¤Ž}z
| ¡  |W   W S  |y@ } z|}W Y d}~qd}~ww t 	|j¡}	t
|	ƒ|‚ tyW   | ¡  ‚ w )aš  Execute the wrapped callable within a transaction.

        Args:
            transaction
                (:class:`~google.cloud.firestore_v1.transaction.Transaction`):
                A transaction to execute the callable within.
            args (Tuple[Any, ...]): The extra positional arguments to pass
                along to the wrapped callable.
            kwargs (Dict[str, Any]): The extra keyword arguments to pass
                along to the wrapped callable.

        Returns:
            Any: The result of the wrapped callable.

        Raises:
            ValueError: If the transaction does not succeed in
                ``max_attempts``.
        r$   N)Z_resetr(   r   ZAbortedÚrangeZ_max_attemptsr`   r@   r   r3   r)   ÚBaseExceptionr>   )
r    r9   r_   rJ   Zretryable_exceptionsÚlast_excÚattemptÚresultÚexcr:   r$   r$   r%   Ú__call__  s(   ÿ€ÿ

üz_Transactional.__call__rU   )r9   r   r   r   )r9   r   )rV   rW   rX   rY   r   r`   rg   r\   r$   r$   r"   r%   r]   ó   s
    

r]   r^   r   r   c                 C  s   t | ƒS )a‡  Decorate a callable so that it runs in a transaction.

    Args:
        to_wrap
            (Callable[[:class:`~google.cloud.firestore_v1.transaction.Transaction`, ...], Any]):
            A callable that should be run (and retried) in a transaction.

    Returns:
        Callable[[:class:`~google.cloud.firestore_v1.transaction.Transaction`, ...], Any]:
        the wrapped callable.
    N)r]   )r^   r$   r$   r%   ÚtransactionalO  s   rh   )r^   r   r   r]   ))rY   Ú
__future__r   Útypingr   r   r   r   r   Zgoogle.api_corer   r	   r
   ÚretriesZgoogle.cloud.firestore_v1r   r   Z*google.cloud.firestore_v1.base_transactionr   r   r   r   r   r   r   r   Z"google.cloud.firestore_v1.documentr   Zgoogle.cloud.firestore_v1.queryr   ÚdatetimeZ'google.cloud.firestore_v1.base_documentr   Z'google.cloud.firestore_v1.query_profiler   Z*google.cloud.firestore_v1.stream_generatorr   Z
WriteBatchr   r]   rh   r$   r$   r$   r%   Ú<module>   s$   (
 E\