
    Ѯh~4                       d Z ddlmZ ddlmZ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 ddlmZ dd	lmZmZmZmZmZmZmZmZ erdd
lm Z  ddl!m"Z" ddl#m$Z$  G d dejJ                  e      Z& G d de      Z'	 	 	 	 ddZ(y)zEHelpers for applying Google Cloud Firestore changes in a transaction.    )annotations)TYPE_CHECKINGAnyAsyncGeneratorCallable	CoroutineOptional)
exceptionsgapic_v1)retry_async)_helpersasync_batch)AsyncDocumentReference)
AsyncQuery)_CANT_BEGIN_CANT_COMMIT_CANT_ROLLBACK_EXCEED_ATTEMPTS_TEMPLATE_WRITE_READ_ONLYMAX_ATTEMPTSBaseTransaction_BaseTransactional)AsyncStreamGenerator)DocumentSnapshot)ExplainOptionsc                       e Zd ZdZedfd fdZd fdZdddZddZddZ	e
j                  j                  df	 	 	 	 	 	 	 dd	Ze
j                  j                  dfdd
	 	 	 	 	 	 	 	 	 ddZ xZS )AsyncTransactionaO  Accumulate read-and-write operations to be sent in a transaction.

    Args:
        client (:class:`~google.cloud.firestore_v1.async_client.AsyncClient`):
            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`.
    Fc                Z    t         t        |   |       t        j                  | ||       y N)superr   __init__r   )selfclientmax_attempts	read_only	__class__s       }/home/www/academy-backend.kofcorporation.com/venv/lib/python3.12/site-packages/google/cloud/firestore_v1/async_transaction.pyr!   zAsyncTransaction.__init__:   s%    .v6  |Y?    c                b    | j                   rt        t              t        t        |   |       y)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"   	write_pbsr&   s     r'   r,   zAsyncTransaction._add_write_pbs>   s(     ??-..4Y?r(   Nc                p  K   | j                   r*t        j                  | j                        }t	        |      | j
                  j                  j                  | j
                  j                  | j                  |      d| j
                  j                         d{   }|j                  | _        y7 w)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"   retry_idmsgtransaction_responses       r'   _beginzAsyncTransaction._beginM   s      $$TXX.CS/!%)\\%@%@%R%R LL9911(; \\// &S &
  
 (33 
s   BB6B4B6c                Z  K   | j                   st        t              	 | j                  j                  j                  | j                  j                  | j                  d| j                  j                         d{    | j                          y7 # | j                          w xY w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"   s    r'   	_rollbackzAsyncTransaction._rollbackd   s      ^,,	,,--66 $ = =#'88 33 7    NN NNs/   B+AB >B?B B+B B((B+c                  K   | j                   st        t              | j                  j                  j                  | j                  j                  | j                  | j                  d| j                  j                         d{   }| j                          t        |j                        | _        |j                  | _        | j                  S 7 Kw)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   N)r4   r+   r   r7   r8   commitr:   
_write_pbsr6   r<   rD   listwrite_resultscommit_time)r"   commit_responses     r'   _commitzAsyncTransaction._commit{   s      \** $ ; ; B B LL99//#xx
 \\// !C !
 
 	!/"?"?@*66!!!
s   BCC	ACc                   K   t        j                  ||      } | j                  j                  |fd| i| d{   S 7 w)at  Retrieves multiple documents from Firestore.

        Args:
            references (List[.AsyncDocumentReference, ...]): 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.

        Yields:
            .DocumentSnapshot: The next document snapshot that fulfills the
            query, or :data:`None` if the document does not exist.
        r=   N)r   make_retry_timeout_kwargsr7   get_all)r"   
referencesretrytimeoutkwargss        r'   rQ   zAsyncTransaction.get_all   sA     ( 33E7C)T\\))*Q$Q&QQQQs   9AA A)explain_optionsc               0  K   t        j                  ||      }t        |t              r5|t	        d       | j
                  j                  |gfd| i| d{   S t        |t              r|||d<    |j                  dd| i|S t	        d      7 :w)a  
        Retrieve a document or a query result from the database.

        Args:
            ref_or_query (AsyncDocumentReference | AsyncQuery):
                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.

        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.
        Nz^When type of `ref_or_query` is `AsyncDocumentReference`, `explain_options` cannot be provided.r=   rV   zSValue for argument "ref_or_query" must be a AsyncDocumentReference or a AsyncQuery. )	r   rP   
isinstancer   r+   r7   rQ   r   stream)r"   ref_or_queryrS   rT   rV   rU   s         r'   getzAsyncTransaction.get   s     B 33E7Cl$:;* <  .--,04:   j1*,;()&<&&B4B6BBe s   ABB;BreturnNone)r-   rJ   r^   r_   r   )r>   zbytes | Noner^   r_   )r^   rJ   )rR   rJ   rS   "retries.AsyncRetry | object | NonerT   zfloat | Noner^   z%AsyncGenerator[DocumentSnapshot, Any])
r[   z#AsyncDocumentReference | AsyncQueryrS   r`   rT   zOptional[float]rV   zOptional[ExplainOptions]r^   zNAsyncGenerator[DocumentSnapshot, Any] | AsyncStreamGenerator[DocumentSnapshot])__name__
__module____qualname____doc__r   r!   r,   rA   rE   rN   r   methodDEFAULTrQ   r\   __classcell__r&   s   @r'   r   r   ,   s     -9E @@4.."@ 5=OO4K4K $	RR 2R 	R
 
/R4 5=OO4K4K#'	2 59292 22 !	2 22 
X2r(   r   c                  :     e Zd ZdZd fdZ	 	 	 	 ddZd Z xZS )_AsyncTransactionalal  Provide a callable object to use as a transactional decorater.

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

    Args:
        to_wrap (Coroutine[[:class:`~google.cloud.firestore_v1.async_transaction.AsyncTransaction`, ...], Any]):
            A coroutine that should be run (and retried) in a transaction.
    c                ,    t         t        |   |       y r   )r    rj   r!   )r"   to_wrapr&   s     r'   r!   z_AsyncTransactional.__init__   s    !41':r(   c                  K   |j                          |j                  | j                         d{    |j                  | _        | j                  | j                  | _         | j
                  |g|i | d{   S 7 P7 w)a}  Begin transaction and call the wrapped coroutine.

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

        Returns:
            Any: result of the wrapped coroutine.

        Raises:
            Exception: Any failure caused by ``to_wrap``.
        )r>   N)rD   rA   r>   r6   
current_idrl   )r"   r=   argsrU   s       r'   _pre_commitz_AsyncTransactional._pre_commit   s{     * 	  $-- 888 &//==  OODM!T\\+????? 	9 @s"   0BBAB>B?BBc                  K   | j                          |j                  st        j                  nd}d}	 t	        |j
                        D ]<  } | j                  |g|i | d{   }	 |j                          d{    |c S  t        j                  |j
                        }	t        |	      |7 M7 6# |$ r}|}Y d}~zd}~ww xY w# t        $ r |j                          d{  7    w xY w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``.
        rX   N)_resetr*   r
   Abortedrange_max_attemptsrp   rN   r   r5   r+   BaseExceptionrE   )
r"   r=   ro   rU   retryable_exceptionslast_excattemptresultexcr?   s
             r'   __call__z_AsyncTransactional.__call__  s     & 	(3(>(>ZB 	 	 !:!:; #/t//MdMfMM#%--///!M	# ,22;3L3LMCS/x/ N/+ #"H#  	 '')))		sv   1C21C %B3&C +B7>B5?B7C C2-C 5B77C<C>C CC C/'C*(C//C2r]   )r=   r   r^   r   )ra   rb   rc   rd   r!   rp   r|   rg   rh   s   @r'   rj   rj      s*    ;@+@	@<0r(   rj   c                    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.
    )rj   )rl   s    r'   async_transactionalr~   C  s     w''r(   N)rl   z!Callable[[AsyncTransaction], Any]r^   rj   ))rd   
__future__r   typingr   r   r   r   r   r	   google.api_corer
   r   r   retriesgoogle.cloud.firestore_v1r   r   (google.cloud.firestore_v1.async_documentr   %google.cloud.firestore_v1.async_queryr   *google.cloud.firestore_v1.base_transactionr   r   r   r   r   r   r   r   0google.cloud.firestore_v1.async_stream_generatorr   'google.cloud.firestore_v1.base_documentr   'google.cloud.firestore_v1.query_profiler   AsyncWriteBatchr   rj   r~   rX   r(   r'   <module>r      s|    L " T T 0 2 ; K <	 	 	 UHFu{22O up\, \~(.((r(   