
    .
0h2                       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rdd
lmZ ddl m!Z! ddl"m#Z#  G d dej$        e          Z% G d de          Z&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)StreamGeneratorc                       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 )%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                    t          t          |                               |           t          j        | ||           d S N)superr   __init__r   )selfclientmax_attempts	read_only	__class__s       `/var/www/html/nourish/venv/lib/python3.11/site-packages/google/cloud/firestore_v1/transaction.pyr"   zTransaction.__init__:   s<    k4  ))&111 |Y?????    	write_pbslistc                    | 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'   s     r(   r/   zTransaction._add_write_pbs>   sB     ? 	/-...k4  //	:::::r)   Nretry_idbytes | Nonec                   | j         r(t          j        | j                  }t	          |          | j        j                            | j        j        | 	                    |          d| j        j
                  }|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#   r0   msgtransaction_responses       r(   _beginzTransaction._beginM   s      	"$TX..CS//!#|:LL L911(;;  \/  M  
  
 (3r)   c                   | j         st          t                    	 | j        j                            | j        j        | j        d| j        j                   | 	                                 dS # | 	                                 w xY w)zRoll back the transaction.

        Raises:
            ValueError: If no transaction is in progress.
            google.api_core.exceptions.GoogleAPICallError: If the rollback fails.
        )r3   rA   r5   N)
r8   r.   r   r;   r<   rollbackr>   r:   r@   	_clean_up)r#   s    r(   	_rollbackzTransaction._rollbackd   s      	-^,,,	L'00 $ =#'8  3 1    NNDNNs   =A0 0Bc                >   | j         st          t                    | j        j                            | j        j        | j        | j        d| j        j	                  }| 
                                 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.
        )r3   writesrA   r5   )r8   r.   r   r;   r<   commitr>   
_write_pbsr:   r@   rG   r+   write_resultscommit_time)r#   commit_responses     r(   _commitzTransaction._commit{   s      	+\***,5<< L9/#x 
 \/ = 
 
 	!/"?@@*6!!r)   
referencesr   retries.Retry | object | Nonetimeoutfloat | None&Generator[DocumentSnapshot, Any, None]c                V    t          j        ||          } | j        j        |fd| i|S )ao  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.

        Yields:
            .DocumentSnapshot: The next document snapshot that fulfills the
            query, or :data:`None` if the document does not exist.
        rA   )r   make_retry_timeout_kwargsr;   get_all)r#   rQ   r   rS   kwargss        r(   rX   zTransaction.get_all   s8    ( 3E7CC#t|#JKKDKFKKKr)   )explain_optionsref_or_queryDocumentReference | QueryOptional[float]rZ   Optional[ExplainOptions]JStreamGenerator[DocumentSnapshot] | Generator[DocumentSnapshot, Any, None]c                  t          j        ||          }t          |t                    r'|t	          d           | j        j        |gfd| i|S t          |t                    r|||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.

        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.rA   rZ   zIValue for argument "ref_or_query" must be a DocumentReference or a Query. )	r   rW   
isinstancer   r.   r;   rX   r   stream)r#   r[   r   rS   rZ   rY   s         r(   getzTransaction.get   s    @ 3E7CCl$566 	* <   (4<'SSDSFSSSe,, 	*,;()&<&BB4B6BBB[  r)   r   r   )r*   r+   r   r   r    )r0   r1   r   r   )r   r+   )rQ   r+   r   rR   rS   rT   r   rU   )
r[   r\   r   rR   rS   r]   rZ   r^   r   r_   )__name__
__module____qualname____doc__r   r"   r/   rD   rH   rP   r
   methodDEFAULTrX   rd   __classcell__r'   s   @r(   r   r   ,   s         -9E @ @ @ @ @ @ @; ; ; ; ; ;4 4 4 4 4.   ." " " "@ 08/F $	L L L L L4 08/F#'	/ 59/ / / / / / / / / /r)   r   c                  4     e Zd ZdZd
 fdZddZdd	Z x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                X    t          t          |                               |           d S r    )r!   ro   r"   )r#   to_wrapr'   s     r(   r"   z_Transactional.__init__   s'    nd##,,W55555r)   rA   r   r   c                    |                                  |                    | j                   |j        | _        | j        | 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``.
        )r0   )rG   rD   r0   r:   
current_idrq   )r#   rA   argsrY   s       r(   _pre_commitz_Transactional._pre_commit   sm    & 	DM222 &/=  ODMt|K9$999&999r)   c                   |                                   |j        st          j        nd}d}	 t	          |j                  D ]?} | j        |g|R i |}	 |                                 |c S # |$ r}|}Y d}~8d}~ww xY wt          j	        |j                  }	t          |	          |# t          $ r |                                  w xY 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``.
        ra   N)_resetr-   r	   Abortedrange_max_attemptsru   rP   r   r9   r.   BaseExceptionrH   )
r#   rA   rt   rY   retryable_exceptionslast_excattemptresultexcrB   s
             r(   __call__z_Transactional.__call__  s   & 	(3(>FZB 	 	 !:;; # #))+GGGGGG#'')))!MMM+ # # #"HHHHHH# ,2;3LMMCS//x/ 	 	 	 !!###		s5   'B* A-*B* -A>2A94B* 9A>>,B* * C
re   )rA   r   r   r   )rA   r   )rf   rg   rh   ri   r"   ru   r   rl   rm   s   @r(   ro   ro      so         6 6 6 6 6 6: : : :8/ / / / / / / /r)   ro   rq   r   r   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.
    )ro   )rq   s    r(   transactionalr   =  s     '"""r)   N)rq   r   r   ro   )(ri   
__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   
WriteBatchr   ro   r   ra   r)   r(   <module>r      s   L K " " " " " " D D D D D D D D D D D D D D 0 0 0 0 0 0 0 0 , , , , , , 5 5 5 5 5 5 5 5	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 A @ @ @ @ @ 1 1 1 1 1 1  KHHHHHHFFFFFFJJJJJJr r r r r%"O r r rjY Y Y Y Y' Y Y Yx# # # # # #r)   