o
    g                     @  s  d dl mZ d dl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 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 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 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 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! 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( dd#l)m*Z* dd$l)m+Z+ erudd%lm,Z, dd&lm-Z- dd'lm.Z. dd(lm/Z/ dd)lm0Z0 dd*lm1Z1 dd+lm2Z2 dd,lm3Z3 dd-lm4Z4 dd.l5m6Z6 dd/l5m7Z7 dd0l8m9Z9 dd1l:m;Z; dd2l:m<Z< dd3l:m=Z= dd4l>m?Z? dd5l@mAZA dd6lBmCZC dd7lBmDZD dd8lBmEZE dd9lBmFZF dd:lBmGZG dd;lHmIZI dd<lJmKZK dd=lLmMZM dd>lNmOZO dd?lPmQZQ dd@lPmRZR edA ZSe+dBZTedCedDZUeVdEdFiZWeVdGdFiZXG dHdI dIZYejZe#dJdKdLdMgg dNg dOdPG dQdR dRee# Z[edSdRdDZ\G dTdU dUe	e\ Z]G dVdW dWe	e\ Z^G dXdY dYee$ edY Z_dgd^d_Z`dhdbdcZadidedfZ eae&_bdS )j    )annotationsN)Any)	Awaitable)Callable)cast)Dict)Generic)Iterable)Iterator)NoReturn)Optional)overload)Sequence)Tuple)Type)TYPE_CHECKING)TypeVar)Union   )engine)ReversibleProxy)StartableContext)_ensure_sync_result)AsyncResult)AsyncScalarResult   )utilclose_all_sessions)object_session)Session)SessionTransaction)state)greenlet_spawn)Concatenate)	ParamSpec)AsyncConnection)AsyncEngine)
Connection)CursorResult)Engine)Result)Row)
RowMapping)ScalarResult)_CoreAnyExecuteParams)CoreExecuteOptionsParameter)
dispatcher)_IdentityKeyType)_O)OrmExecuteOptionsParameter)IdentityMap)	ORMOption)_BindArguments)_EntityBindKey)_PKIdentityArgument)_SessionBind)_SessionBindKey)	_InfoType)
Executable)
UpdateBase)ClauseElement)ForUpdateParameter)TypedReturnsRows)r'   r&   _P_T)boundprebuffer_rowsTstream_resultsc                   @  s,   e Zd ZdZG dd dZed	ddZdS )

AsyncAttrsa0  Mixin class which provides an awaitable accessor for all attributes.

    E.g.::

        from __future__ import annotations

        from typing import List

        from sqlalchemy import ForeignKey
        from sqlalchemy import func
        from sqlalchemy.ext.asyncio import AsyncAttrs
        from sqlalchemy.orm import DeclarativeBase
        from sqlalchemy.orm import Mapped
        from sqlalchemy.orm import mapped_column
        from sqlalchemy.orm import relationship


        class Base(AsyncAttrs, DeclarativeBase):
            pass


        class A(Base):
            __tablename__ = "a"

            id: Mapped[int] = mapped_column(primary_key=True)
            data: Mapped[str]
            bs: Mapped[List[B]] = relationship()


        class B(Base):
            __tablename__ = "b"
            id: Mapped[int] = mapped_column(primary_key=True)
            a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
            data: Mapped[str]

    In the above example, the :class:`_asyncio.AsyncAttrs` mixin is applied to
    the declarative ``Base`` class where it takes effect for all subclasses.
    This mixin adds a single new attribute
    :attr:`_asyncio.AsyncAttrs.awaitable_attrs` to all classes, which will
    yield the value of any attribute as an awaitable. This allows attributes
    which may be subject to lazy loading or deferred / unexpiry loading to be
    accessed such that IO can still be emitted::

        a1 = (await async_session.scalars(select(A).where(A.id == 5))).one()

        # use the lazy loader on ``a1.bs`` via the ``.awaitable_attrs``
        # interface, so that it may be awaited
        for b1 in await a1.awaitable_attrs.bs:
            print(b1)

    The :attr:`_asyncio.AsyncAttrs.awaitable_attrs` performs a call against the
    attribute that is approximately equivalent to using the
    :meth:`_asyncio.AsyncSession.run_sync` method, e.g.::

        for b1 in await async_session.run_sync(lambda sess: a1.bs):
            print(b1)

    .. versionadded:: 2.0.13

    .. seealso::

        :ref:`asyncio_orm_avoid_lazyloads`

    c                   @  s$   e Zd ZdZdddZdd	d
ZdS )AsyncAttrs._AsyncAttrGetitem	_instancer   c                 C  
   || _ d S N)rI   )selfrI    rM   `/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/sqlalchemy/ext/asyncio/session.py__init__      
z%AsyncAttrs._AsyncAttrGetitem.__init__namestrreturnAwaitable[Any]c                 C  s   t t| j|S rK   )r#   getattrrI   )rL   rQ   rM   rM   rN   __getattr__   s   z(AsyncAttrs._AsyncAttrGetitem.__getattr__N)rI   r   )rQ   rR   rS   rT   )__name__
__module____qualname__	__slots__rO   rV   rM   rM   rM   rN   _AsyncAttrGetitem   s    
r[   rS   rH   c                 C  s
   t | S )aV  provide a namespace of all attributes on this object wrapped
        as awaitables.

        e.g.::


            a1 = (await async_session.scalars(select(A).where(A.id == 5))).one()

            some_attribute = await a1.awaitable_attrs.some_deferred_attribute
            some_collection = await a1.awaitable_attrs.some_collection

        )rG   r[   rL   rM   rM   rN   awaitable_attrs   s   
zAsyncAttrs.awaitable_attrsN)rS   rH   )rW   rX   rY   __doc__r[   propertyr]   rM   rM   rM   rN   rG   U   s
    A	rG   z:class:`_orm.Session`z:class:`_asyncio.AsyncSession`r   identity_key)__contains____iter__addadd_allexpire
expire_allexpungeexpunge_allis_modifiedin_transactionin_nested_transaction)dirtydeletednewidentity_map	is_active	autoflushno_autoflushinfo)classmethodsmethods
attributesc                   @  s  e Zd ZU dZdZded< 	dddddddZeZded< 	 ded< 	 e	dddZ
		dddd Zdd'd(Ze	dejdddd)dd6d7Ze	dejdddd)dd:d7Ze	dejdddd)dd=d7Z	dejdd>dd?d7Ze	dejdd>ddBdCZe	dejdd>ddDdCZ	dejdd>ddEdCZe	dejdd>ddGdHZe	dejdd>ddJdHZ	dejdd>ddKdHZddLddejdMddXdYZddLddejdMdd[d\Ze	dejdd>dd^d_Ze	dejdd>ddad_Z	dejdd>ddbd_Ze	dejdd>ddddeZe	dejdd>ddgdeZ	dejdd>ddhdeZddidjZdddkddmdnZdddqdrZddtduZddvdwZ			ddd~dZ		ddddZdddZdddZdddZ dddZ!dddZ"dddZ#dddZ$dddZ%e	e&dddddZ'dddZ(dddZ)dddZ*d ddZ+dddZ,ddddZ-dddZ.	ddddZ/dddZ0dddZ1dddZ2	ddddZ3dddZ4dddZ5e6dddZ7e6dddÄZ8e6dddńZ9e6d	ddȄZ:e:j;d
ddȄZ:e6ddd̄Z<e6ddd΄Z=e=j;ddd΄Z=e6dddфZ>e6dddӄZ?e	dddքZ@e			dddddלddd߄ZAdS (  AsyncSessiona  Asyncio version of :class:`_orm.Session`.

    The :class:`_asyncio.AsyncSession` is a proxy for a traditional
    :class:`_orm.Session` instance.

    The :class:`_asyncio.AsyncSession` is **not safe for use in concurrent
    tasks.**.  See :ref:`session_faq_threadsafe` for background.

    .. versionadded:: 1.4

    To use an :class:`_asyncio.AsyncSession` with custom :class:`_orm.Session`
    implementations, see the
    :paramref:`_asyncio.AsyncSession.sync_session_class` parameter.


    Tzdispatcher[Session]dispatchN)bindssync_session_classbindOptional[_AsyncSessionBind]ry   2Optional[Dict[_SessionBindKey, _AsyncSessionBind]]rz   Optional[Type[Session]]kwr   c                K  sj   d }}|r|| _ t|}|r|| _dd | D }|r!|| _| | jd||d| | _| _dS )a  Construct a new :class:`_asyncio.AsyncSession`.

        All parameters other than ``sync_session_class`` are passed to the
        ``sync_session_class`` callable directly to instantiate a new
        :class:`_orm.Session`. Refer to :meth:`_orm.Session.__init__` for
        parameter documentation.

        :param sync_session_class:
          A :class:`_orm.Session` subclass or other callable which will be used
          to construct the :class:`_orm.Session` which will be proxied. This
          parameter may be used to provide custom :class:`_orm.Session`
          subclasses. Defaults to the
          :attr:`_asyncio.AsyncSession.sync_session_class` class-level
          attribute.

          .. versionadded:: 1.4.24

        Nc                 S  s   i | ]
\}}|t |qS rM   )r   _get_sync_engine_or_connection).0keybrM   rM   rN   
<dictcomp>  s    
z)AsyncSession.__init__.<locals>.<dictcomp>)r{   ry   rM   )	r{   r   r   ry   itemsrz   _assign_proxiedsync_session_proxied)rL   r{   ry   rz   r   	sync_bind
sync_bindsrM   rM   rN   rO      s   
zAsyncSession.__init__zType[Session]r    r   rS   r   c                 C  s   t d)Nztasynchronous events are not implemented at this time.  Apply synchronous listeners to the AsyncSession.sync_session.)NotImplementedErrorclsrM   rM   rN   _no_async_engine_events0  s   z$AsyncSession._no_async_engine_eventsinstanceobjectattribute_namesOptional[Iterable[str]]with_for_updater@   Nonec                   s    t | jj|||dI dH  dS )a  Expire and refresh the attributes on the given instance.

        A query will be issued to the database and all attributes will be
        refreshed with their current database value.

        This is the async version of the :meth:`_orm.Session.refresh` method.
        See that method for a complete description of all options.

        .. seealso::

            :meth:`_orm.Session.refresh` - main documentation for refresh

        )r   r   N)r#   r   refresh)rL   r   r   r   rM   rM   rN   r   7  s   zAsyncSession.refreshfn&Callable[Concatenate[Session, _P], _T]arg_P.args	_P.kwargsrC   c                   s&   t || jg|R ddi|I dH S )a  Invoke the given synchronous (i.e. not async) callable,
        passing a synchronous-style :class:`_orm.Session` as the first
        argument.

        This method allows traditional synchronous SQLAlchemy functions to
        run within the context of an asyncio application.

        E.g.::

            def some_business_method(session: Session, param: str) -> str:
                """A synchronous function that does not require awaiting

                :param session: a SQLAlchemy Session, used synchronously

                :return: an optional return value is supported

                """
                session.add(MyObject(param=param))
                session.flush()
                return "success"


            async def do_something_async(async_engine: AsyncEngine) -> None:
                """an async function that uses awaiting"""

                with AsyncSession(async_engine) as async_session:
                    # run some_business_method() with a sync-style
                    # Session, proxied into an awaitable
                    return_code = await async_session.run_sync(
                        some_business_method, param="param1"
                    )
                    print(return_code)

        This method maintains the asyncio event loop all the way through
        to the database connection by running the given callable in a
        specially instrumented greenlet.

        .. tip::

            The provided callable is invoked inline within the asyncio event
            loop, and will block on traditional IO calls.  IO within this
            callable should only call into SQLAlchemy's asyncio database
            APIs which will be properly adapted to the greenlet context.

        .. seealso::

            :class:`.AsyncAttrs`  - a mixin for ORM mapped classes that provides
            a similar feature more succinctly on a per-attribute basis

            :meth:`.AsyncConnection.run_sync`

            :ref:`session_run_sync`
        _require_awaitFN)r#   r   )rL   r   r   r   rM   rM   rN   run_syncR  s   <zAsyncSession.run_sync)execution_optionsbind_arguments_parent_execute_state
_add_event	statementTypedReturnsRows[_T]paramsOptional[_CoreAnyExecuteParams]r   r4   r   Optional[_BindArguments]r   Optional[Any]r   
Result[_T]c                     d S rK   rM   rL   r   r   r   r   r   r   rM   rM   rN   execute     
zAsyncSession.executer>   CursorResult[Any]c                  r   rK   rM   r   rM   rM   rN   r     r   r=   Result[Any]c                  r   rK   rM   r   rM   rM   rN   r     r   )r   r   c                  sR   |rt |t}nt}t| jj|f|||d|I dH }t|| jI dH S )zExecute a statement and return a buffered
        :class:`_engine.Result` object.

        .. seealso::

            :meth:`_orm.Session.execute` - main documentation for execute

        r   r   r   N)r   immutabledictunion_EXECUTE_OPTIONSr#   r   r   r   rL   r   r   r   r   r   resultrM   rM   rN   r     s"   
TypedReturnsRows[Tuple[_T]]Optional[_T]c                  r   rK   rM   rL   r   r   r   r   r   rM   rM   rN   scalar     	zAsyncSession.scalarc                  r   rK   rM   r   rM   rM   rN   r     r   c                  s@   |rt |t}nt}t| jj|f|||d|I dH S )zExecute a statement and return a scalar result.

        .. seealso::

            :meth:`_orm.Session.scalar` - main documentation for scalar

        r   N)r   r   r   r   r#   r   r   r   rM   rM   rN   r     s    
ScalarResult[_T]c                  r   rK   rM   r   rM   rM   rN   scalars  r   zAsyncSession.scalarsScalarResult[Any]c                  r   rK   rM   r   rM   rM   rN   r     r   c                  *   | j |f|||d|I dH }| S )a  Execute a statement and return scalar results.

        :return: a :class:`_result.ScalarResult` object

        .. versionadded:: 1.4.24 Added :meth:`_asyncio.AsyncSession.scalars`

        .. versionadded:: 1.4.26 Added
           :meth:`_asyncio.async_scoped_session.scalars`

        .. seealso::

            :meth:`_orm.Session.scalars` - main documentation for scalars

            :meth:`_asyncio.AsyncSession.stream_scalars` - streaming version

        r   N)r   r   r   rM   rM   rN   r   &  s   Foptionspopulate_existingr   identity_tokenr   entity_EntityBindKey[_O]identr9   r   Optional[Sequence[ORMOption]]r   boolr   Union[_O, None]c             
     *   t td| jj|||||||dI dH S )zReturn an instance based on the given primary key identifier,
        or ``None`` if not found.

        .. seealso::

            :meth:`_orm.Session.get` - main documentation for get


        Callable[..., _O]r   N)r#   r   r   getrL   r   r   r   r   r   r   r   rM   rM   rN   r   I  s   zAsyncSession.getr3   c             
     r   )aO  Return an instance based on the given primary key identifier,
        or raise an exception if not found.

        Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects
        no rows.

        ..versionadded: 2.0.22

        .. seealso::

            :meth:`_orm.Session.get_one` - main documentation for get_one

        r   r   N)r#   r   r   get_oner   rM   rM   rN   r   i  s   zAsyncSession.get_oneAsyncResult[_T]c                  r   rK   rM   r   rM   rM   rN   stream  r   zAsyncSession.streamAsyncResult[Any]c                  r   rK   rM   r   rM   rM   rN   r     r   c                  sH   |rt |t}nt}t| jj|f|||d|I dH }t|S )zbExecute a statement and return a streaming
        :class:`_asyncio.AsyncResult` object.

        r   N)r   r   r   _STREAM_OPTIONSr#   r   r   r   r   rM   rM   rN   r     s"   
AsyncScalarResult[_T]c                  r   rK   rM   r   rM   rM   rN   stream_scalars  r   zAsyncSession.stream_scalarsAsyncScalarResult[Any]c                  r   rK   rM   r   rM   rM   rN   r     r   c                  r   )aR  Execute a statement and return a stream of scalar results.

        :return: an :class:`_asyncio.AsyncScalarResult` object

        .. versionadded:: 1.4.24

        .. seealso::

            :meth:`_orm.Session.scalars` - main documentation for scalars

            :meth:`_asyncio.AsyncSession.scalars` - non streaming version

        r   N)r   r   r   rM   rM   rN   r     s   c                   s   t | jj|I dH  dS )aT  Mark an instance as deleted.

        The database delete operation occurs upon ``flush()``.

        As this operation may need to cascade along unloaded relationships,
        it is awaitable to allow for those queries to take place.

        .. seealso::

            :meth:`_orm.Session.delete` - main documentation for delete

        N)r#   r   deleterL   r   rM   rM   rN   r     s   zAsyncSession.deleteloadr   r   c                  s   t | jj|||dI dH S )zCopy the state of a given instance into a corresponding instance
        within this :class:`_asyncio.AsyncSession`.

        .. seealso::

            :meth:`_orm.Session.merge` - main documentation for merge

        r   N)r#   r   merge)rL   r   r   r   rM   rM   rN   r     s   zAsyncSession.mergeobjectsOptional[Sequence[Any]]c                   s   t | jj|dI dH  dS )zFlush all the object changes to the database.

        .. seealso::

            :meth:`_orm.Session.flush` - main documentation for flush

        )r   N)r#   r   flush)rL   r   rM   rM   rN   r     s   zAsyncSession.flush!Optional[AsyncSessionTransaction]c                 C      | j  }|durt|S dS )zReturn the current root transaction in progress, if any.

        :return: an :class:`_asyncio.AsyncSessionTransaction` object, or
         ``None``.

        .. versionadded:: 1.4.18

        N)r   get_transactionAsyncSessionTransaction_retrieve_proxy_for_targetrL   transrM   rM   rN   r   $  s   
	
zAsyncSession.get_transactionc                 C  r   )zReturn the current nested transaction in progress, if any.

        :return: an :class:`_asyncio.AsyncSessionTransaction` object, or
         ``None``.

        .. versionadded:: 1.4.18

        N)r   get_nested_transactionr   r   r   rM   rM   rN   r   3  s   


z#AsyncSession.get_nested_transactionmapperOptional[_EntityBindKey[_O]]clauseOptional[ClauseElement]Optional[_SessionBind]Union[Engine, Connection]c                 K  s   | j jd|||d|S )a  Return a "bind" to which the synchronous proxied :class:`_orm.Session`
        is bound.

        Unlike the :meth:`_orm.Session.get_bind` method, this method is
        currently **not** used by this :class:`.AsyncSession` in any way
        in order to resolve engines for requests.

        .. note::

            This method proxies directly to the :meth:`_orm.Session.get_bind`
            method, however is currently **not** useful as an override target,
            in contrast to that of the :meth:`_orm.Session.get_bind` method.
            The example below illustrates how to implement custom
            :meth:`_orm.Session.get_bind` schemes that work with
            :class:`.AsyncSession` and :class:`.AsyncEngine`.

        The pattern introduced at :ref:`session_custom_partitioning`
        illustrates how to apply a custom bind-lookup scheme to a
        :class:`_orm.Session` given a set of :class:`_engine.Engine` objects.
        To apply a corresponding :meth:`_orm.Session.get_bind` implementation
        for use with a :class:`.AsyncSession` and :class:`.AsyncEngine`
        objects, continue to subclass :class:`_orm.Session` and apply it to
        :class:`.AsyncSession` using
        :paramref:`.AsyncSession.sync_session_class`. The inner method must
        continue to return :class:`_engine.Engine` instances, which can be
        acquired from a :class:`_asyncio.AsyncEngine` using the
        :attr:`_asyncio.AsyncEngine.sync_engine` attribute::

            # using example from "Custom Vertical Partitioning"


            import random

            from sqlalchemy.ext.asyncio import AsyncSession
            from sqlalchemy.ext.asyncio import create_async_engine
            from sqlalchemy.ext.asyncio import async_sessionmaker
            from sqlalchemy.orm import Session

            # construct async engines w/ async drivers
            engines = {
                "leader": create_async_engine("sqlite+aiosqlite:///leader.db"),
                "other": create_async_engine("sqlite+aiosqlite:///other.db"),
                "follower1": create_async_engine("sqlite+aiosqlite:///follower1.db"),
                "follower2": create_async_engine("sqlite+aiosqlite:///follower2.db"),
            }


            class RoutingSession(Session):
                def get_bind(self, mapper=None, clause=None, **kw):
                    # within get_bind(), return sync engines
                    if mapper and issubclass(mapper.class_, MyOtherClass):
                        return engines["other"].sync_engine
                    elif self._flushing or isinstance(clause, (Update, Delete)):
                        return engines["leader"].sync_engine
                    else:
                        return engines[
                            random.choice(["follower1", "follower2"])
                        ].sync_engine


            # apply to AsyncSession using sync_session_class
            AsyncSessionMaker = async_sessionmaker(sync_session_class=RoutingSession)

        The :meth:`_orm.Session.get_bind` method is called in a non-asyncio,
        implicitly non-blocking context in the same manner as ORM event hooks
        and functions that are invoked via :meth:`.AsyncSession.run_sync`, so
        routines that wish to run SQL commands inside of
        :meth:`_orm.Session.get_bind` can continue to do so using
        blocking-style code, which will be translated to implicitly async calls
        at the point of invoking IO on the database drivers.

        )r   r   r{   NrM   )r   get_bind)rL   r   r   r{   r   rM   rM   rN   r   C  s
   PzAsyncSession.get_bind%Optional[CoreExecuteOptionsParameter]r&   c                   s.   t | jjf||d|I dH }tj|S )a  Return a :class:`_asyncio.AsyncConnection` object corresponding to
        this :class:`.Session` object's transactional state.

        This method may also be used to establish execution options for the
        database connection used by the current transaction.

        .. versionadded:: 1.4.24  Added \**kw arguments which are passed
           through to the underlying :meth:`_orm.Session.connection` method.

        .. seealso::

            :meth:`_orm.Session.connection` - main documentation for
            "connection"

        )r   r   N)r#   r   
connectionr   r&   r   )rL   r   r   r   sync_connectionrM   rM   rN   r     s   zAsyncSession.connectionr   c                 C     t | S )a  Return an :class:`_asyncio.AsyncSessionTransaction` object.

        The underlying :class:`_orm.Session` will perform the
        "begin" action when the :class:`_asyncio.AsyncSessionTransaction`
        object is entered::

            async with async_session.begin():
                ...  # ORM transaction is begun

        Note that database IO will not normally occur when the session-level
        transaction is begun, as database transactions begin on an
        on-demand basis.  However, the begin block is async to accommodate
        for a :meth:`_orm.SessionEvents.after_transaction_create`
        event hook that may perform IO.

        For a general description of ORM begin, see
        :meth:`_orm.Session.begin`.

        r   r\   rM   rM   rN   begin  s   zAsyncSession.beginc                 C  s   t | ddS )a  Return an :class:`_asyncio.AsyncSessionTransaction` object
        which will begin a "nested" transaction, e.g. SAVEPOINT.

        Behavior is the same as that of :meth:`_asyncio.AsyncSession.begin`.

        For a general description of ORM begin nested, see
        :meth:`_orm.Session.begin_nested`.

        .. seealso::

            :ref:`aiosqlite_serializable` - special workarounds required
            with the SQLite asyncio driver in order for SAVEPOINT to work
            correctly.

        T)nestedr   r\   rM   rM   rN   begin_nested  s   zAsyncSession.begin_nestedc                      t | jjI dH  dS )zRollback the current transaction in progress.

        .. seealso::

            :meth:`_orm.Session.rollback` - main documentation for
            "rollback"
        N)r#   r   rollbackr\   rM   rM   rN   r        zAsyncSession.rollbackc                   r   )zCommit the current transaction in progress.

        .. seealso::

            :meth:`_orm.Session.commit` - main documentation for
            "commit"
        N)r#   r   commitr\   rM   rM   rN   r     r   zAsyncSession.commitc                   r   )a  Close out the transactional resources and ORM objects used by this
        :class:`_asyncio.AsyncSession`.

        .. seealso::

            :meth:`_orm.Session.close` - main documentation for
            "close"

            :ref:`session_closing` - detail on the semantics of
            :meth:`_asyncio.AsyncSession.close` and
            :meth:`_asyncio.AsyncSession.reset`.

        N)r#   r   closer\   rM   rM   rN   r     s   zAsyncSession.closec                   r   )a  Close out the transactional resources and ORM objects used by this
        :class:`_orm.Session`, resetting the session to its initial state.

        .. versionadded:: 2.0.22

        .. seealso::

            :meth:`_orm.Session.reset` - main documentation for
            "reset"

            :ref:`session_closing` - detail on the semantics of
            :meth:`_asyncio.AsyncSession.close` and
            :meth:`_asyncio.AsyncSession.reset`.

        N)r#   r   resetr\   rM   rM   rN   r     s   zAsyncSession.resetc                   s   |   I dH  dS )a  A synonym for :meth:`_asyncio.AsyncSession.close`.

        The :meth:`_asyncio.AsyncSession.aclose` name is specifically
        to support the Python standard library ``@contextlib.aclosing``
        context manager function.

        .. versionadded:: 2.0.20

        N)r   r\   rM   rM   rN   aclose     
zAsyncSession.aclosec                   r   )zClose this Session, using connection invalidation.

        For a complete description, see :meth:`_orm.Session.invalidate`.
        N)r#   r   
invalidater\   rM   rM   rN   r   #  s   zAsyncSession.invalidatez2.0zThe :meth:`.AsyncSession.close_all` method is deprecated and will be removed in a future release.  Please refer to :func:`_asyncio.close_all_sessions`.c                   s   t  I dH  dS )z2Close all :class:`_asyncio.AsyncSession` sessions.Nr   r   rM   rM   rN   	close_all*  s   	zAsyncSession.close_allrL   _ASc                   s   | S rK   rM   r\   rM   rM   rN   
__aenter__5  s   zAsyncSession.__aenter__type_value	tracebackc                   s$   t |  }t |I d H  d S rK   )asynciocreate_taskr   shield)rL   r   r   r   taskrM   rM   rN   	__aexit__8  s   zAsyncSession.__aexit__ _AsyncSessionContextManager[_AS]c                 C  r   rK   )_AsyncSessionContextManagerr\   rM   rM   rN   _maker_context_manager<  s   z#AsyncSession._maker_context_managerc                 C     | j |S )aK  Return True if the instance is associated with this session.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        The instance may be pending or persistent within the Session for a
        result of True.


        )r   ra   r   rM   rM   rN   ra   D     zAsyncSession.__contains__Iterator[object]c                 C  
   | j  S )zIterate over all pending or persistent instances within this
        Session.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.


        )r   rb   r\   rM   rM   rN   rb   T  s   
zAsyncSession.__iter___warnc                 C     | j j||dS )a:  Place an object into this :class:`_orm.Session`.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        Objects that are in the :term:`transient` state when passed to the
        :meth:`_orm.Session.add` method will move to the
        :term:`pending` state, until the next flush, at which point they
        will move to the :term:`persistent` state.

        Objects that are in the :term:`detached` state when passed to the
        :meth:`_orm.Session.add` method will move to the :term:`persistent`
        state directly.

        If the transaction used by the :class:`_orm.Session` is rolled back,
        objects which were transient when they were passed to
        :meth:`_orm.Session.add` will be moved back to the
        :term:`transient` state, and will no longer be present within this
        :class:`_orm.Session`.

        .. seealso::

            :meth:`_orm.Session.add_all`

            :ref:`session_adding` - at :ref:`session_basics`


        )r  )r   rc   )rL   r   r  rM   rM   rN   rc   b  s    zAsyncSession.add	instancesIterable[object]c                 C  r	  )a  Add the given collection of instances to this :class:`_orm.Session`.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        See the documentation for :meth:`_orm.Session.add` for a general
        behavioral description.

        .. seealso::

            :meth:`_orm.Session.add`

            :ref:`session_adding` - at :ref:`session_basics`


        )r   rd   )rL   r  rM   rM   rN   rd     s   zAsyncSession.add_allc                 C  r  )aa  Expire the attributes on an instance.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        Marks the attributes of an instance as out of date. When an expired
        attribute is next accessed, a query will be issued to the
        :class:`.Session` object's current transactional context in order to
        load all expired attributes for the given instance.   Note that
        a highly isolated transaction will return the same values as were
        previously read in that same transaction, regardless of changes
        in database state outside of that transaction.

        To expire all objects in the :class:`.Session` simultaneously,
        use :meth:`Session.expire_all`.

        The :class:`.Session` object's default behavior is to
        expire all state whenever the :meth:`Session.rollback`
        or :meth:`Session.commit` methods are called, so that new
        state can be loaded for the new transaction.   For this reason,
        calling :meth:`Session.expire` only makes sense for the specific
        case that a non-ORM SQL statement was emitted in the current
        transaction.

        :param instance: The instance to be refreshed.
        :param attribute_names: optional list of string attribute names
          indicating a subset of attributes to be expired.

        .. seealso::

            :ref:`session_expire` - introductory material

            :meth:`.Session.expire`

            :meth:`.Session.refresh`

            :meth:`_orm.Query.populate_existing`


        )r   )r   re   )rL   r   r   rM   rM   rN   re     s   .zAsyncSession.expirec                 C  r  )ak  Expires all persistent instances within this Session.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        When any attributes on a persistent instance is next accessed,
        a query will be issued using the
        :class:`.Session` object's current transactional context in order to
        load all expired attributes for the given instance.   Note that
        a highly isolated transaction will return the same values as were
        previously read in that same transaction, regardless of changes
        in database state outside of that transaction.

        To expire individual objects and individual attributes
        on those objects, use :meth:`Session.expire`.

        The :class:`.Session` object's default behavior is to
        expire all state whenever the :meth:`Session.rollback`
        or :meth:`Session.commit` methods are called, so that new
        state can be loaded for the new transaction.   For this reason,
        calling :meth:`Session.expire_all` is not usually needed,
        assuming the transaction is isolated.

        .. seealso::

            :ref:`session_expire` - introductory material

            :meth:`.Session.expire`

            :meth:`.Session.refresh`

            :meth:`_orm.Query.populate_existing`


        )r   rf   r\   rM   rM   rN   rf     s   
'zAsyncSession.expire_allc                 C  r	  )ad  Remove the `instance` from this ``Session``.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        This will free all internal references to the instance.  Cascading
        will be applied according to the *expunge* cascade rule.


        )r   rg   r   rM   rM   rN   rg     r
  zAsyncSession.expungec                 C  r  )aA  Remove all object instances from this ``Session``.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        This is equivalent to calling ``expunge(obj)`` on all objects in this
        ``Session``.


        )r   rh   r\   rM   rM   rN   rh        
zAsyncSession.expunge_allinclude_collectionsc                 C  r  )a
  Return ``True`` if the given instance has locally
        modified attributes.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        This method retrieves the history for each instrumented
        attribute on the instance and performs a comparison of the current
        value to its previously flushed or committed value, if any.

        It is in effect a more expensive and accurate
        version of checking for the given instance in the
        :attr:`.Session.dirty` collection; a full test for
        each attribute's net "dirty" status is performed.

        E.g.::

            return session.is_modified(someobject)

        A few caveats to this method apply:

        * Instances present in the :attr:`.Session.dirty` collection may
          report ``False`` when tested with this method.  This is because
          the object may have received change events via attribute mutation,
          thus placing it in :attr:`.Session.dirty`, but ultimately the state
          is the same as that loaded from the database, resulting in no net
          change here.
        * Scalar attributes may not have recorded the previously set
          value when a new value was applied, if the attribute was not loaded,
          or was expired, at the time the new value was received - in these
          cases, the attribute is assumed to have a change, even if there is
          ultimately no net change against its database value. SQLAlchemy in
          most cases does not need the "old" value when a set event occurs, so
          it skips the expense of a SQL call if the old value isn't present,
          based on the assumption that an UPDATE of the scalar value is
          usually needed, and in those few cases where it isn't, is less
          expensive on average than issuing a defensive SELECT.

          The "old" value is fetched unconditionally upon set only if the
          attribute container has the ``active_history`` flag set to ``True``.
          This flag is set typically for primary key attributes and scalar
          object references that are not a simple many-to-one.  To set this
          flag for any arbitrary mapped column, use the ``active_history``
          argument with :func:`.column_property`.

        :param instance: mapped instance to be tested for pending changes.
        :param include_collections: Indicates if multivalued collections
         should be included in the operation.  Setting this to ``False`` is a
         way to detect only local-column based properties (i.e. scalar columns
         or many-to-one foreign keys) that would result in an UPDATE for this
         instance upon flush.


        )r  )r   ri   )rL   r   r  rM   rM   rN   ri     s   <zAsyncSession.is_modifiedc                 C  r  )aO  Return True if this :class:`_orm.Session` has begun a transaction.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        .. versionadded:: 1.4

        .. seealso::

            :attr:`_orm.Session.is_active`



        )r   rj   r\   rM   rM   rN   rj   S  s   
zAsyncSession.in_transactionc                 C  r  )a+  Return True if this :class:`_orm.Session` has begun a nested
        transaction, e.g. SAVEPOINT.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        .. versionadded:: 1.4


        )r   rk   r\   rM   rM   rN   rk   g  r  z"AsyncSession.in_nested_transactionc                 C     | j jS )a  The set of all persistent instances considered dirty.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class
            on behalf of the :class:`_asyncio.AsyncSession` class.

        E.g.::

            some_mapped_object in session.dirty

        Instances are considered dirty when they were modified but not
        deleted.

        Note that this 'dirty' calculation is 'optimistic'; most
        attribute-setting or collection modification operations will
        mark an instance as 'dirty' and place it in this set, even if
        there is no net change to the attribute's value.  At flush
        time, the value of each attribute is compared to its
        previously saved value, and if there's no net change, no SQL
        operation will occur (this is a more expensive operation so
        it's only done at flush time).

        To check if an instance has actionable net changes to its
        attributes, use the :meth:`.Session.is_modified` method.


        )r   rl   r\   rM   rM   rN   rl   w  s   zAsyncSession.dirtyc                 C  r  )zThe set of all instances marked as 'deleted' within this ``Session``

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class
            on behalf of the :class:`_asyncio.AsyncSession` class.

        )r   rm   r\   rM   rM   rN   rm        zAsyncSession.deletedc                 C  r  )zThe set of all instances marked as 'new' within this ``Session``.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class
            on behalf of the :class:`_asyncio.AsyncSession` class.

        )r   rn   r\   rM   rM   rN   rn     r  zAsyncSession.newr5   c                 C  r  )zProxy for the :attr:`_orm.Session.identity_map` attribute
        on behalf of the :class:`_asyncio.AsyncSession` class.

        r   ro   r\   rM   rM   rN   ro        zAsyncSession.identity_mapattrc                 C     || j _d S rK   r  rL   r  rM   rM   rN   ro        c                 C  r  )a  True if this :class:`.Session` not in "partial rollback" state.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class
            on behalf of the :class:`_asyncio.AsyncSession` class.

        .. versionchanged:: 1.4 The :class:`_orm.Session` no longer begins
           a new transaction immediately, so this attribute will be False
           when the :class:`_orm.Session` is first instantiated.

        "partial rollback" state typically indicates that the flush process
        of the :class:`_orm.Session` has failed, and that the
        :meth:`_orm.Session.rollback` method must be emitted in order to
        fully roll back the transaction.

        If this :class:`_orm.Session` is not in a transaction at all, the
        :class:`_orm.Session` will autobegin when it is first used, so in this
        case :attr:`_orm.Session.is_active` will return True.

        Otherwise, if this :class:`_orm.Session` is within a transaction,
        and that transaction has not been rolled back internally, the
        :attr:`_orm.Session.is_active` will also return True.

        .. seealso::

            :ref:`faq_session_rollback`

            :meth:`_orm.Session.in_transaction`


        )r   rp   r\   rM   rM   rN   rp     s   #zAsyncSession.is_activec                 C  r  )zProxy for the :attr:`_orm.Session.autoflush` attribute
        on behalf of the :class:`_asyncio.AsyncSession` class.

        r   rq   r\   rM   rM   rN   rq     r  zAsyncSession.autoflushc                 C  r  rK   r  r  rM   rM   rN   rq     r  c                 C  r  )a  Return a context manager that disables autoflush.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class
            on behalf of the :class:`_asyncio.AsyncSession` class.

        e.g.::

            with session.no_autoflush:

                some_object = SomeClass()
                session.add(some_object)
                # won't autoflush
                some_object.related_thing = session.query(SomeRelated).first()

        Operations that proceed within the ``with:`` block
        will not be subject to flushes occurring upon query
        access.  This is useful when initializing a series
        of objects which involve existing database queries,
        where the uncompleted object should not yet be flushed.


        )r   rr   r\   rM   rM   rN   rr     s   zAsyncSession.no_autoflushc                 C  r  )a+  A user-modifiable dictionary.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class
            on behalf of the :class:`_asyncio.AsyncSession` class.

        The initial value of this dictionary can be populated using the
        ``info`` argument to the :class:`.Session` constructor or
        :class:`.sessionmaker` constructor or factory methods.  The dictionary
        here is always local to this :class:`.Session` and can be modified
        independently of all other :class:`.Session` objects.


        )r   rs   r\   rM   rM   rN   rs     s   zAsyncSession.infoOptional[Session]c                 C  s
   t |S )a  Return the :class:`.Session` to which an object belongs.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        This is an alias of :func:`.object_session`.


        )r    r   )r   r   rM   rM   rN   r   "  r  zAsyncSession.object_session)r   rowr   class_Optional[Type[Any]]Union[Any, Tuple[Any, ...]]r  %Optional[Union[Row[Any], RowMapping]]_IdentityKeyType[Any]c                C  s   t j|||||dS )zReturn an identity key.

        .. container:: class_bases

            Proxied for the :class:`_orm.Session` class on
            behalf of the :class:`_asyncio.AsyncSession` class.

        This is an alias of :func:`.util.identity_key`.


        )r  r   r   r  r   )r    r`   )r   r  r   r   r  r   rM   rM   rN   r`   2  s   zAsyncSession.identity_keyrK   )r{   r|   ry   r}   rz   r~   r   r   )rS   r   )NN)r   r   r   r   r   r@   rS   r   )r   r   r   r   r   r   rS   rC   )r   r   r   r   r   r4   r   r   r   r   r   r   rS   r   )r   r>   r   r   r   r4   r   r   r   r   r   r   rS   r   )r   r=   r   r   r   r4   r   r   r   r   r   r   rS   r   )r   r=   r   r   r   r4   r   r   r   r   rS   r   )r   r   r   r   r   r4   r   r   r   r   rS   r   )r   r=   r   r   r   r4   r   r   r   r   rS   r   )r   r   r   r   r   r4   r   r   r   r   rS   r   )r   r=   r   r   r   r4   r   r   r   r   rS   r   )r   r   r   r9   r   r   r   r   r   r@   r   r   r   r4   rS   r   )r   r   r   r9   r   r   r   r   r   r@   r   r   r   r4   rS   r3   )r   r   r   r   r   r4   r   r   r   r   rS   r   )r   r=   r   r   r   r4   r   r   r   r   rS   r   )r   r   r   r   r   r4   r   r   r   r   rS   r   )r   r=   r   r   r   r4   r   r   r   r   rS   r   )r   r   rS   r   )r   r3   r   r   r   r   rS   r3   )r   r   rS   r   )rS   r   )NNN)
r   r   r   r   r{   r   r   r   rS   r   )r   r   r   r   r   r   rS   r&   )rS   r   rS   r   )rL   r   rS   r   r   r   r   r   r   r   rS   r   )rL   r   rS   r  )r   r   rS   r   )rS   r  )T)r   r   r  r   rS   r   )r  r  rS   r   )r   r   r   r   rS   r   )r   r   r  r   rS   r   rS   r   )rS   r   )rS   r5   )r  r5   rS   r   )r  r   rS   r   )r   r   rS   r  )r  r  r   r   r   r   r  r!  r   r   rS   r"  )BrW   rX   rY   r^   _is_asyncio__annotations__rO   r    rz   classmethodr   r   r   r   r   
EMPTY_DICTr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   
deprecatedr   r   r  r  ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   r_   rl   rm   rn   ro   setterrp   rq   rr   rs   r   r`   rM   rM   rM   rN   rw      s  
 .	
@#
!
(%$


 


V
 











"
0
)
@ $rw   r   c                   @  s   e Zd ZU dZded< e	d'ddddd(ddZe	d'ddddd)ddZ	d*eddddd(ddZd+ddZd,ddZ	d-d"d#Z
d.d%d&ZdS )/async_sessionmakera"  A configurable :class:`.AsyncSession` factory.

    The :class:`.async_sessionmaker` factory works in the same way as the
    :class:`.sessionmaker` factory, to generate new :class:`.AsyncSession`
    objects when called, creating them given
    the configurational arguments established here.

    e.g.::

        from sqlalchemy.ext.asyncio import create_async_engine
        from sqlalchemy.ext.asyncio import AsyncSession
        from sqlalchemy.ext.asyncio import async_sessionmaker


        async def run_some_sql(
            async_session: async_sessionmaker[AsyncSession],
        ) -> None:
            async with async_session() as session:
                session.add(SomeObject(data="object"))
                session.add(SomeOtherObject(name="other object"))
                await session.commit()


        async def main() -> None:
            # an AsyncEngine, which the AsyncSession will use for connection
            # resources
            engine = create_async_engine(
                "postgresql+asyncpg://scott:tiger@localhost/"
            )

            # create a reusable factory for new AsyncSession instances
            async_session = async_sessionmaker(engine)

            await run_some_sql(async_session)

            await engine.dispose()

    The :class:`.async_sessionmaker` is useful so that different parts
    of a program can create new :class:`.AsyncSession` objects with a
    fixed configuration established up front.  Note that :class:`.AsyncSession`
    objects may also be instantiated directly when not using
    :class:`.async_sessionmaker`.

    .. versionadded:: 2.0  :class:`.async_sessionmaker` provides a
       :class:`.sessionmaker` class that's dedicated to the
       :class:`.AsyncSession` object, including pep-484 typing support.

    .. seealso::

        :ref:`asyncio_orm` - shows example use

        :class:`.sessionmaker`  - general overview of the
         :class:`.sessionmaker` architecture


        :ref:`session_getting` - introductory text on creating
        sessions using :class:`.sessionmaker`.

    	Type[_AS]r  .)rq   expire_on_commitrs   r{   r|   rq   r   r.  rs   Optional[_InfoType]r   r   c                K     d S rK   rM   rL   r{   r  rq   r.  rs   r   rM   rM   rN   rO     s   
zasync_sessionmaker.__init__rL   "'async_sessionmaker[AsyncSession]'c                K  r0  rK   rM   )rL   r{   rq   r.  rs   r   rM   rM   rN   rO     s   	NT)r  rq   r.  rs   c                K  s8   ||d< ||d< ||d< |dur||d< || _ || _dS )a  Construct a new :class:`.async_sessionmaker`.

        All arguments here except for ``class_`` correspond to arguments
        accepted by :class:`.Session` directly. See the
        :meth:`.AsyncSession.__init__` docstring for more details on
        parameters.


        r{   rq   r.  Nrs   )r   r  r1  rM   rM   rN   rO     s   
rS   r  c                 C  s   |  }|  S )a  Produce a context manager that both provides a new
        :class:`_orm.AsyncSession` as well as a transaction that commits.


        e.g.::

            async def main():
                Session = async_sessionmaker(some_engine)

                async with Session.begin() as session:
                    session.add(some_object)

                # commits transaction, closes session

        )r  )rL   sessionrM   rM   rN   r     s   zasync_sessionmaker.beginlocal_kwr   c                 K  s`   | j  D ]"\}}|dkr!d|v r!| }||d  ||d< q||| q| jdi |S )a  Produce a new :class:`.AsyncSession` object using the configuration
        established in this :class:`.async_sessionmaker`.

        In Python, the ``__call__`` method is invoked on an object when
        it is "called" in the same way as a function::

            AsyncSession = async_sessionmaker(async_engine, expire_on_commit=False)
            session = AsyncSession()  # invokes sessionmaker.__call__()

        rs   NrM   )r   r   copyupdate
setdefaultr  )rL   r4  kvdrM   rM   rN   __call__  s   
zasync_sessionmaker.__call__new_kwr   c                 K  s   | j | dS )z(Re)configure the arguments for this async_sessionmaker.

        e.g.::

            AsyncSession = async_sessionmaker(some_engine)

            AsyncSession.configure(bind=create_async_engine("sqlite+aiosqlite://"))
        N)r   r6  )rL   r<  rM   rM   rN   	configure  s   
zasync_sessionmaker.configurerR   c                 C  s,   d| j j| jjddd | j D f S )Nz%s(class_=%r, %s)z, c                 s  s     | ]\}}d ||f V  qdS )z%s=%rNrM   )r   r8  r9  rM   rM   rN   	<genexpr>  s    z.async_sessionmaker.__repr__.<locals>.<genexpr>)	__class__rW   r  joinr   r   r\   rM   rM   rN   __repr__  s
   zasync_sessionmaker.__repr__).)r{   r|   r  r-  rq   r   r.  r   rs   r/  r   r   )rL   r2  r{   r|   rq   r   r.  r   rs   r/  r   r   rK   )rS   r  )r4  r   rS   r   )r<  r   rS   r   )rS   rR   )rW   rX   rY   r^   r'  r   rO   rw   r   r;  r=  rA  rM   rM   rM   rN   r,  V  s8   
 <


r,  c                   @  s@   e Zd ZU dZded< ded< dddZdd	d
ZdddZdS )r  )async_sessionr   r   rB  r   r   c                 C  rJ   rK   )rB  )rL   rB  rM   rM   rN   rO   	  rP   z$_AsyncSessionContextManager.__init__rS   c                   s$   | j  | _| j I d H  | j S rK   )rB  r   r   r   r\   rM   rM   rN   r     s   z&_AsyncSessionContextManager.__aenter__r   r   r   r   r   c                   s6   d fdd}t | }t |I d H  d S )NrS   r   c                     s2    j I d H   jI d H  d S rK   )r   r  rB  rM   rL   r   r   r   rM   rN   go  s   z1_AsyncSessionContextManager.__aexit__.<locals>.gor#  )r  r  r  )rL   r   r   r   rD  r  rM   rC  rN   r    s   z%_AsyncSessionContextManager.__aexit__N)rB  r   )rS   r   r$  )rW   rX   rY   rZ   r'  rO   r   r  rM   rM   rM   rN   r    s   
 

r  c                   @  sv   e Zd ZU dZdZded< ded< d!d"d
dZed#ddZd$ddZ	d%ddZ
d%ddZ	d!d&ddZd'ddZd S )(r   a  A wrapper for the ORM :class:`_orm.SessionTransaction` object.

    This object is provided so that a transaction-holding object
    for the :meth:`_asyncio.AsyncSession.begin` may be returned.

    The object supports both explicit calls to
    :meth:`_asyncio.AsyncSessionTransaction.commit` and
    :meth:`_asyncio.AsyncSessionTransaction.rollback`, as well as use as an
    async context manager.


    .. versionadded:: 1.4

    )r3  sync_transactionr   rw   r3  zOptional[SessionTransaction]rE  Fr   r   c                 C  s   || _ || _d | _d S rK   )r3  r   rE  )rL   r3  r   rM   rM   rN   rO   2  s   
z AsyncSessionTransaction.__init__rS   c                 C  s   |   d uo
|   jS rK   )_sync_transactionrp   r\   rM   rM   rN   rp   7  s   z!AsyncSessionTransaction.is_activer!   c                 C  s   | j s|   | j S rK   )rE  _raise_for_not_startedr\   rM   rM   rN   rF  >  s   z)AsyncSessionTransaction._sync_transactionr   c                      t |  jI dH  dS )z2Roll back this :class:`_asyncio.AsyncTransaction`.N)r#   rF  r   r\   rM   rM   rN   r   C  s   z AsyncSessionTransaction.rollbackc                   rH  )z/Commit this :class:`_asyncio.AsyncTransaction`.N)r#   rF  r   r\   rM   rM   rN   r   G  s   zAsyncSessionTransaction.commitis_ctxmanagerc                   s@   |  t| jr| jjjn| jjjI d H | _|r| j  | S rK   )	r   r#   r   r3  r   r   r   rE  	__enter__)rL   rI  rM   rM   rN   startL  s   
zAsyncSessionTransaction.startr   r   r   r   c                   s    t |  j|||I d H  d S rK   )r#   rF  __exit__)rL   r   r   r   rM   rM   rN   r  Z  s   z!AsyncSessionTransaction.__aexit__N)F)r3  rw   r   r   r%  )rS   r!   r#  )rI  r   rS   r   r$  )rW   rX   rY   r^   rZ   r'  rO   r_   rp   rF  r   r   rK  r  rM   rM   rM   rN   r     s   
 


r   r   r   rS   Optional[AsyncSession]c                 C  s   t | }|durt|S dS )a  Return the :class:`_asyncio.AsyncSession` to which the given instance
    belongs.

    This function makes use of the sync-API function
    :class:`_orm.object_session` to retrieve the :class:`_orm.Session` which
    refers to the given instance, and from there links it to the original
    :class:`_asyncio.AsyncSession`.

    If the :class:`_asyncio.AsyncSession` has been garbage collected, the
    return value is ``None``.

    This functionality is also available from the
    :attr:`_orm.InstanceState.async_session` accessor.

    :param instance: an ORM mapped instance
    :return: an :class:`_asyncio.AsyncSession` object, or ``None``.

    .. versionadded:: 1.4.18

    N)r   rB  )r   r3  rM   rM   rN   async_object_session`  s   rN  r3  r    c                 C  s   t j| ddS )a  Return the :class:`_asyncio.AsyncSession` which is proxying the given
    :class:`_orm.Session` object, if any.

    :param session: a :class:`_orm.Session` instance.
    :return: a :class:`_asyncio.AsyncSession` instance, or ``None``.

    .. versionadded:: 1.4.18

    F)
regenerate)rw   r   )r3  rM   rM   rN   rB  }  s   
rB  r   c                     s   t tI dH  dS )zClose all :class:`_asyncio.AsyncSession` sessions.

    .. versionadded:: 2.0.23

    .. seealso::

        :func:`.session.close_all_sessions`

    N)r#   _sync_close_all_sessionsrM   rM   rM   rN   r     r   r   )r   r   rS   rM  )r3  r    rS   rM  r#  )c
__future__r   r  typingr   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r    r   baser   r   r   r   r   r   r   ormr   rP  r   r    r!   r"   _instance_stateutil.concurrencyr#   util.typingr$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   engine.interfacesr/   r0   eventr1   orm._typingr2   r3   r4   orm.identityr5   orm.interfacesr6   orm.sessionr7   r8   r9   r:   r;   sql._typingr<   sql.baser=   sql.dmlr>   sql.elementsr?   sql.selectabler@   rA   _AsyncSessionBindrB   rC   r   r   r   rG   create_proxy_methodsrw   r   r,  r  r   rN  rB  _async_providerrM   rM   rM   rN   <module>   s   ]            .

F


