o
    ABi\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mZ ddl m!Z! ddl"m#Z# ddl$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)Query)DocumentSnapshot)ExplainOptions)StreamGeneratorNc                      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clientmax_attempts	read_only	__class__ e/var/www/html/Trade-python/venv/lib/python3.10/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,   @   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 )zBegin 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_apibegin_transaction_database_string_options_protobuf_rpc_metadatatransaction)r    r-   msgtransaction_responser&   r&   r'   _beginO   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 )zRoll back the transaction.

        Raises:
            ValueError: If no transaction is in progress.
            google.api_core.exceptions.GoogleAPICallError: If the rollback fails.
        )r/   r=   r1   N)
r4   r+   r   r7   r8   rollbackr:   r6   r<   	_clean_up)r    r&   r&   r'   	_rollbackf   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/   writesr=   r1   )r4   r+   r   r7   r8   commitr:   
_write_pbsr6   r<   rB   r)   write_resultscommit_time)r    commit_responser&   r&   r'   _commit}   s   	zTransaction._commit)	read_time
referencesr
   retries.Retry | object | Nonetimeoutfloat | NonerK   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.
        NrK   r=   )r   make_retry_timeout_kwargsr7   get_all)r    rL   r
   rN   rK   kwargsr&   r&   r'   rS      s   zTransaction.get_all)explain_optionsrK   ref_or_queryDocumentReference | QueryOptional[float]rU   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.
        NrK   z^When type of `ref_or_query` is `AsyncDocumentReference`, `explain_options` cannot be provided.r=   rU   zIValue for argument "ref_or_query" must be a DocumentReference or a Query.r&   )	r   rR   
isinstancer   r+   r7   rS   r   stream)r    rV   r
   rN   rU   rK   rT   r&   r&   r'   get   s    %

zTransaction.getr   r   )r(   r)   r   r   r   )r-   r.   r   r   )r   r)   )
rL   r)   r
   rM   rN   rO   rK   rP   r   rQ   )rV   rW   r
   rM   rN   rX   rU   rY   rK   rZ   r   r[   )__name__
__module____qualname____doc__r   r   r,   r@   rC   rJ   r	   methodDEFAULTrS   r^   __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   rg   r   )r    to_wrapr$   r&   r'   r      s   z_Transactional.__init__r=   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)rB   r@   r-   r6   
current_idrh   )r    r=   argsrT   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)_resetr*   r   Abortedrange_max_attemptsrk   rJ   r   r5   r+   BaseExceptionrC   )
r    r=   rj   rT   retryable_exceptionslast_excattemptresultexcr>   r&   r&   r'   __call__  s(   

z_Transactional.__call__r_   )r=   r   r   r   )r=   r   )r`   ra   rb   rc   r   rk   rv   rf   r&   r&   r$   r'   rg      s
    

rg   rh   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.
    )rg   )rh   r&   r&   r'   transactionalN  s   rw   )rh   r   r   rg   ))rc   
__future__r   typingr   r   r   r   r   google.api_corer   r	   r
   retriesgoogle.cloud.firestore_v1r   r   *google.cloud.firestore_v1.base_transactionr   r   r   r   r   r   r   r   "google.cloud.firestore_v1.documentr   google.cloud.firestore_v1.queryr   'google.cloud.firestore_v1.base_documentr   'google.cloud.firestore_v1.query_profiler   *google.cloud.firestore_v1.stream_generatorr   datetime
WriteBatchr   rg   rw   r&   r&   r&   r'   <module>   s$   (
 E\