g rddlmZddlZddlmZddlmZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd lm Z dd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z!ddlm"Z"ddlm#Z#dd lm$Z$dd!lm%Z&dd"l'm(Z(dd#l)m*Z*dd$l)m+Z+erdd%lm,Z,dd&lm-Z-dd'lm.Z.dd(lm/Z/dd)lm0Z0dd*lm1Z1dd+lm2Z2dd,lm3Z3dd-lm4Z4dd.l5m6Z6dd/l5m7Z7dd0l8m9Z9dd1l:m;Z;dd2l:mm?Z?dd5l@mAZAdd6lBmCZCdd7lBmDZDdd8lBmEZEdd9lBmFZFdd:lBmGZGdd;lHmIZIddlNmOZOdd?lPmQZQdd@lPmRZRedAZSe+dBZTedCeDZUejdEdFiZWejdGdFiZXGdHdIZYeje#dJdKdLdMggdNgdOPGdQdRee#Z[edSdRDZ\GdTdUe e\Z]GdVdWe e\Z^GdXdYee$edYZ_d]dZZ`d^d[Zad_d\Z eae&_by)`) 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)utilclose_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)boundprebuffer_rowsTstream_resultsc6eZdZdZGddZeddZy) AsyncAttrsa0Mixin 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 eZdZdZddZddZy)AsyncAttrs._AsyncAttrGetitem _instancec||_yN)rL)selfrLs O/opt/hc_python/lib64/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py__init__z%AsyncAttrs._AsyncAttrGetitem.__init__s &DNc8tt|j|SrN)r$getattrrL)rOnames rP __getattr__z(AsyncAttrs._AsyncAttrGetitem.__getattr__s!'4>>4@ @rRN)rLr)rUstrreturnzAwaitable[Any])__name__ __module__ __qualname__ __slots__rQrVrRrP_AsyncAttrGetitemrKs  ' ArRr^c,tj|S)aVprovide 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 )rIr^rOs rPawaitable_attrszAsyncAttrs.awaitable_attrss++D11rRN)rXrK)rYrZr[__doc__r^propertyrar]rRrPrIrIUs(?BAA22rRrIz:class:`_orm.Session`z:class:`_asyncio.AsyncSession`r identity_key) __contains____iter__addadd_allexpire expire_allexpunge expunge_all is_modifiedin_transactionin_nested_transaction)dirtydeletednew identity_map is_active autoflush no_autoflushinfo) classmethodsmethods attributescJeZdZUdZdZded< dSddd dTdZeZd ed< d ed < e dUd Z dV dWd Z dXdZ e dSejdddd dYdZe dSejdddd dZdZe dSejdddd d[dZ dSejdd d\dZe dSejdd d]dZe dSejdd d^dZ dSejdd d^dZe dSejdd d_dZe dSejdd d`dZ dSejdd d`dZddddejd dadZddddejd dbdZe dSejdd dcdZe dSejdd ddd Z dSejdd ddd!Ze dSejdd ded"Ze dSejdd dfd#Z dSejdd dfd$Zdgd%Zddd& dhd'ZdSdid(Zdjd)Zdjd*Z dk dld+Z dV dmd,Zdnd-Zdnd.Zdod/Z dod0Z!dod1Z"dod2Z#dod3Z$dod4Z%e ejLd5d6dod7Z'dpd8Z(dqd9Z)drd:Z*dsd;Z+dtd<Z,dudvd=Z-dwd>Z. dS dxd?Z/dod@Z0dgdAZ1dodBZ2 du dydCZ3dzdDZ4dzdEZ5e6d{dFZ7e6d{dGZ8e6d{dHZ9e6d|dIZ:e:jvd}dJZ:e6d{dKZe6d{dOZ?e ddPZ@e dVddddQ ddRZAy) AsyncSessionaAsyncio 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. Tzdispatcher[Session]dispatchN)bindssync_session_classrc Ddx}}|r||_tj|}|r=||_|j Dcic]\}}|tj|}}}|r||_|j |j d||d|x|_|_ycc}}w)aConstruct 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 N)bindr~r]) rr_get_sync_engine_or_connectionr~itemsr_assign_proxied sync_session_proxied) rOrr~rkw sync_bind sync_bindskeybs rPrQzAsyncSession.__init__s4"&% J DI==dCI DJ$kkm+FCV::1==+  &8D #,0,@,@ #D # # K* K K-  DMs Bz Type[Session]r!rctd)Nztasynchronous events are not implemented at this time. Apply synchronous listeners to the AsyncSession.sync_session.)NotImplementedErrorclss rP_no_async_engine_eventsz$AsyncSession._no_async_engine_events0s! F  rRcfKt|jj|||d{y7w)aExpire 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 )attribute_nameswith_for_updateN)r$rrefresh)rOinstancerrs rPrzAsyncSession.refresh7s2(    % % ++    '1/1cVKt||jg|ddi|d{S7w)aInvoke 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)rOfnargrs rPrun_synczAsyncSession.run_syncRsCx$ !! $' 8= AC    s )'))execution_optionsbind_arguments_parent_execute_state _add_eventc KywrNr]rO statementparamsrrrrs rPexecutezAsyncSession.executes c KywrNr]rs rPrzAsyncSession.executes  rc KywrNr]rs rPrzAsyncSession.executes r)rrc K|r)tj|jt}nt}t |j j |f|||d|d{}t||j d{S7"7w)zExecute a statement and return a buffered :class:`_engine.Result` object. .. seealso:: :meth:`_orm.Session.execute` - main documentation for execute rrrN)r immutabledictunion_EXECUTE_OPTIONSr$rrrrOrrrrrresults rPrzAsyncSession.executes$  $ 2 23D E K K ! !1 %    % %  /)     )>>> ?s$ABA?B:B;BBc KywrNr]rOrrrrrs rPscalarzAsyncSession.scalars rc KywrNr]rs rPrzAsyncSession.scalars rcK|r)tj|jt}nt}t |j j |f|||d|d{S7w)zExecute a statement and return a scalar result. .. seealso:: :meth:`_orm.Session.scalar` - main documentation for scalar rN)rrrrr$rrrs rPrzAsyncSession.scalarsv"  $ 2 23D E K K ! !1 #    $ $  /)       sAA#A!A#c KywrNr]rs rPscalarszAsyncSession.scalars rc KywrNr]rs rPrzAsyncSession.scalarss  rclK|j|f|||d|d{}|jS7w)aExecute 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 rN)rrrs rPrzAsyncSession.scalars&sL4$t||  /)     ~~ 424Foptionspopulate_existingridentity_tokenrc Kttd|jj|||||||d{S7w)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]rN)r$rrgetrOentityidentrrrrrs rPrzAsyncSession.getIsK*$ $d&7&7&;&; <  /+)/    5><>c Kttd|jj|||||||d{S7w)aOReturn 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 rrN)r$rrget_oners rPrzAsyncSession.get_oneisK2$ $d&7&7&?&? @  /+)/    rc KywrNr]rs rPstreamzAsyncSession.streams rc KywrNr]rs rPrzAsyncSession.streamrrcK|r)tj|jt}nt}t |j j |f|||d|d{}t|S7w)zbExecute a statement and return a streaming :class:`_asyncio.AsyncResult` object. rN)rrr_STREAM_OPTIONSr$rrrrs rPrzAsyncSession.streams  $ 2 23D E K K! !0 %    % %  /)     6"" sAA.A,A.c KywrNr]rs rPstream_scalarszAsyncSession.stream_scalarss !$rc KywrNr]rs rPrzAsyncSession.stream_scalarss "%rclK|j|f|||d|d{}|jS7w)aRExecute 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 rN)rrrs rPrzAsyncSession.stream_scalarssL.#t{{  /)     ~~ rc`Kt|jj|d{y7w)aTMark 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$rdeleterOrs rPrzAsyncSession.deletes$T..55x@@@s $.,.loadrcdKt|jj|||d{S7w)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 rN)r$rmerge)rOrrrs rPrzAsyncSession.merges4$    # #XD'    s '0.0cbKt|jj|d{y7w)zFlush all the object changes to the database. .. seealso:: :meth:`_orm.Session.flush` - main documentation for flush )objectsN)r$rflush)rOrs rPrzAsyncSession.flushs$T..44gFFFs %/-/cf|jj}|tj|Sy)zReturn the current root transaction in progress, if any. :return: an :class:`_asyncio.AsyncSessionTransaction` object, or ``None``. .. versionadded:: 1.4.18 N)rget_transactionAsyncSessionTransaction_retrieve_proxy_for_targetrOtranss rPrzAsyncSession.get_transaction$s2!!113  *EEeL LrRcf|jj}|tj|Sy)zReturn the current nested transaction in progress, if any. :return: an :class:`_asyncio.AsyncSessionTransaction` object, or ``None``. .. versionadded:: 1.4.18 N)rget_nested_transactionrrrs rPrz#AsyncSession.get_nested_transaction3s2!!88:  *EEeL LrRc B|jjd|||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. )mapperclauserr])rget_bind)rOrrrrs rPrzAsyncSession.get_bindCs4`*t  )) &t 79  rRcKt|jjf||d|d{}tjj |S7#w)aReturn 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" )rrN)r$r connectionrr'r)rOrrrsync_connections rPrzAsyncSession.connections^,!/    ( (! )/!  !   %%@@    s'AA $Act|S)aReturn 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`. rr`s rPbeginzAsyncSession.begins*'t,,rRct|dS)aReturn 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)nestedrr`s rP begin_nestedzAsyncSession.begin_nesteds"'tD99rRc^Kt|jjd{y7w)zRollback the current transaction in progress. .. seealso:: :meth:`_orm.Session.rollback` - main documentation for "rollback" N)r$rrollbackr`s rPrzAsyncSession.rollbacks"T..77888 #-+-c^Kt|jjd{y7w)zCommit the current transaction in progress. .. seealso:: :meth:`_orm.Session.commit` - main documentation for "commit" N)r$rcommitr`s rPrzAsyncSession.commits"T..55666rc^Kt|jjd{y7w)aClose 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$rcloser`s rPrzAsyncSession.closes"T..44555rc^Kt|jjd{y7w)aClose 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$rresetr`s rPrzAsyncSession.resets" T..44555rc@K|jd{y7w)aA 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)rr`s rPaclosezAsyncSession.aclosesjjls c^Kt|jjd{y7w)zClose this Session, using connection invalidation. For a complete description, see :meth:`_orm.Session.invalidate`. N)r$r invalidater`s rPrzAsyncSession.invalidate#s" T..99:::rz2.0zThe :meth:`.AsyncSession.close_all` method is deprecated and will be removed in a future release. Please refer to :func:`_asyncio.close_all_sessions`.c4Ktd{y7w)z2Close all :class:`_asyncio.AsyncSession` sessions.Nrrs rP close_allzAsyncSession.close_all*s!"""s cK|SwrNr]r`s rP __aenter__zAsyncSession.__aenter__5s  scKtj|j}tj|d{y7wrN)asyncio create_taskrshield)rOtype_value tracebacktasks rP __aexit__zAsyncSession.__aexit__8s.""4::<0nnT"""s}}"""rRc.|jjS)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. )rrqr`s rPrqzAsyncSession.deleteds}}$$$rRc.|jjS)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. )rrrr`s rPrrzAsyncSession.news}}   rRc.|jjS)zProxy for the :attr:`_orm.Session.identity_map` attribute on behalf of the :class:`_asyncio.AsyncSession` class. rrsr`s rPrszAsyncSession.identity_maps}})))rRc&||j_yrNrrOattrs rPrszAsyncSession.identity_maps%) "rRc.|jjS)aTrue 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` )rrtr`s rPrtzAsyncSession.is_activesF}}&&&rRc.|jjS)zProxy for the :attr:`_orm.Session.autoflush` attribute on behalf of the :class:`_asyncio.AsyncSession` class. rrur`s rPruzAsyncSession.autoflushs}}&&&rRc&||j_yrNr$r s rPruzAsyncSession.autoflushs"& rRc.|jjS)aReturn 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. )rrvr`s rPrvzAsyncSession.no_autoflushs6}})))rRc.|jjS)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. )rrwr`s rPrwzAsyncSession.infos$}}!!!rRc,tj|S)aReturn 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 )rrs rPr zAsyncSession.object_session"s%%h//rR)rrowrc6tj|||||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`. )class_rrr)r)r!rd)rr+rrr)rs rPrdzAsyncSession.identity_key2s&,##)   rRrN)rOptional[_AsyncSessionBind]r~z2Optional[Dict[_SessionBindKey, _AsyncSessionBind]]rzOptional[Type[Session]]rr)rXr )NN)robjectrOptional[Iterable[str]]rrArXNone)rz&Callable[Concatenate[Session, _P], _T]rz_P.argsrz _P.kwargsrXrD)rTypedReturnsRows[_T]rOptional[_CoreAnyExecuteParams]rr5rOptional[_BindArguments]r Optional[Any]rr3rXz Result[_T])rr?rr1rr5rr2rr3rr3rXzCursorResult[Any])rr>rr1rr5rr2rr3rr3rX Result[Any]) rr>rr1rr5rr2rrrXr4) rTypedReturnsRows[Tuple[_T]]rr1rr5rr2rrrXz Optional[_T]) rr>rr1rr5rr2rrrXr) rr5rr1rr5rr2rrrXzScalarResult[_T]) rr>rr1rr5rr2rrrXzScalarResult[Any])r_EntityBindKey[_O]rr:rOptional[Sequence[ORMOption]]rboolrrArr3rr5rXzUnion[_O, None])rr6rr:rr7rr8rrArr3rr5rXr4) rr0rr1rr5rr2rrrXzAsyncResult[_T]) rr>rr1rr5rr2rrrXzAsyncResult[Any]) rr5rr1rr5rr2rrrXzAsyncScalarResult[_T]) rr>rr1rr5rr2rrrXzAsyncScalarResult[Any])rr-rXr/)rr4rr8rr7rXr4)rzOptional[Sequence[Any]]rXr/)rXz!Optional[AsyncSessionTransaction])NNN) rzOptional[_EntityBindKey[_O]]rzOptional[ClauseElement]rzOptional[_SessionBind]rrrXzUnion[Engine, Connection])rr2rz%Optional[CoreExecuteOptionsParameter]rrrXr')rXrrXr/)rO_ASrXr:rrrrrrrXr/)rOr:rX _AsyncSessionContextManager[_AS])rr-rXr8)rXzIterator[object])T)rr-rr8rXr/)rzIterable[object]rXr/)rr-rr.rXr/)rr-rr8rXr8rXr8)rXr)rXr6)r!r6rXr/)r!r8rXr/)rr-rXzOptional[Session]) r+zOptional[Type[Any]]rzUnion[Any, Tuple[Any, ...]]rr3r)z%Optional[Union[Row[Any], RowMapping]]rr3rXz_IdentityKeyType[Any])BrYrZr[rb _is_asyncio__annotations__rQr!r classmethodrrrrr EMPTY_DICTrrrrrrrrrrrrrrrrrrrrrr deprecatedrrrr rerfrgrhrirjrkrlrmrnrorcrprqrrrssetterrtrurvrwr rdr]rRrPr|r|s <"K!!-1, EI6: , ), B , 4 ,  , \)0 /    48.2   1 ,    6> 2> >  > > @37  9=37/3$( ' 0  6  1  - "    37  9=37/3$(    0  6  1   -  "       37  9=37/3$(  0  6  1  - "    37!? 9=37 !?!?0!? 6 !? 1 !?!? !?F37 9=37 .0 6  1  37 9=37 0 6  1  37 9=37   0 6  1     B37 9=37 .0 6  1  37 9=37   0 6  1      37! 9=37 ! ! 0! 6 ! 1 ! !  ! P26"'.2(,8< " # /    , & 6   J26"'.2(,8<" "" #" / "  " ," &" 6"  " H37 9=37 '0 6  1  37 9=37 0 6  1  37# 9=37 ##0# 6 # 1 ## #>37$ 9=37 $.$0$ 6 $ 1 $$ $$37% 9=37 %%0% 6 % 1 %% %%37 9=37   0 6  1     @ A&15     /   &G $04*.'+ R ,R (R % R  R # R l48CG 0 A     @-.:&976 6$ ;T__  / # ##14 ( 8D0.LP.O.O1H.O .O`'*R/ +"=A> > 59> > @.(5 ##@ % % ! !****"'"'H''''**8""& 0 0'+-1 #'59(, # +   3  &    rRr|r:ceZdZUdZded<e ddddd ddZe ddddd ddZ ded d dd  dd Zdd Zdd Z ddZ ddZ y)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+.)ruexpire_on_commitrwc yrNr]rOrr+rurGrwrs rPrQzasync_sessionmaker.__init__s rRc yrNr])rOrrurGrwrs rPrQzasync_sessionmaker.__init__s rRNT)r+rurGrwc L||d<||d<||d<|||d<||_||_y)aConstruct 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. rrurGNrw)rr+rIs rPrQzasync_sessionmaker.__init__s>&6 #;!1   BvJ rRc0|}|jS)aProduce 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 )rOsessions rPrzasync_sessionmaker.begins"&--//rRc |jjD]J\}}|dk(r.d|vr*|j}|j|d||d<9|j ||L|j di|S)aProduce 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__() rwr])rrcopyupdate setdefaultr+)rOlocal_kwkvds rP__call__zasync_sessionmaker.__call__svGGMMODAqF{v1FFH&)*#$ ##Aq) $t{{&X&&rRc :|jj|y)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)rrP)rOnew_kws rP configurezasync_sessionmaker.configures vrRc |jjd|jjddjd|jj DdS)Nz(class_=z, c30K|]\}}|d|yw)=Nr]).0rSrTs rP z.async_sessionmaker.__repr__..sC?41aA&?s)) __class__rYr+joinrrr`s rP__repr__zasync_sessionmaker.__repr__sB NN # # KK IIC477==?C C  rR).) rr,r+rFrur8rGr8rwOptional[_InfoType]rr) rOz"'async_sessionmaker[AsyncSession]'rr,rur8rGr8rwrcrrrN)rXr<)rRrrXr:)rXrrXr/)rXrW) rYrZr[rbr?rrQr|rrVrYrbr]rRrPrErEVs=:x  -0  !$$'  )        "      -0 !$$'  0 )     "    -1)!%$()     "60('(  rRrEc>eZdZUdZded<ded<d dZd dZd dZy ) r ) async_sessionrr:rerrc||_yrN)re)rOres rPrQz$_AsyncSessionContextManager.__init__ s *rRcK|jj|_|jjd{|jS7wrN)rerrrr`s rPrz&_AsyncSessionContextManager.__aenter__ sC''--/ jj##%%%!!! &s=AAAcKdfd }tj|}tj|d{y7w)NcKjjd{jjd{y7*7wrN)rrre)rOrrrsrPgoz1_AsyncSessionContextManager.__aexit__..gosK**&&ueY? ? ?$$..ueYG G G @ Gs!!AA$A A AAr9)rrr)rOrrrrjrs```` rPrz%_AsyncSessionContextManager.__aexit__s9 H H""24(nnT"""ss#$$  ' ' )$$$rRcfKt|jjd{y7w)z2Roll back this :class:`_asyncio.AsyncTransaction`.N)r$rorr`s rPrz AsyncSessionTransaction.rollbackCs#T335>>???rcfKt|jjd{y7w)z/Commit this :class:`_asyncio.AsyncTransaction`.N)r$rorr`s rPrzAsyncSessionTransaction.commitGs%T335<<===rc,K|jt|jr |jjj n|jjj d{|_|r|jj|S7+wrN) rr$rrMrrrrl __enter__)rO is_ctxmanagers rPstartzAsyncSessionTransaction.startLsx!% 4 4 ;; ))66\\..44 !    ! ! + + -  sA$B&B',BclKt|jj|||d{y7wrN)r$ro__exit__)rOrrrs rPrz!AsyncSessionTransaction.__aexit__Zs0  " " $ - -ueY   s *424N)F)rMr|rr8r=)rXr"r9)rvr8rXrr;)rYrZr[rbr\r?rQrcrtrorrrwrr]rRrPrrsb :I 22%   % @> %* !    rRrc4t|}| t|Sy)aReturn 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 re)rrMs rPasync_object_sessionr{`s",X&GW%%rRc0tj|dS)aReturn 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)r|r)rMs rPrere}s  2 27u 2 MMrRc>Kttd{y7w)zClose all :class:`_asyncio.AsyncSession` sessions. .. versionadded:: 2.0.23 .. seealso:: :func:`.session.close_all_sessions` N)r$_sync_close_all_sessionsr]rRrPrrs 1 222s )rr-rXOptional[AsyncSession])rMr!rXrr9)c __future__rrtypingrrrrrr r r r r rrrrrrrrbaserrrrrrrormrrr r!r"r#_instance_stateutil.concurrencyr$ util.typingr%r&r'r(r)r*r+r,r-r.r/engine.interfacesr0r1eventr2 orm._typingr3r4r5 orm.identityr6orm.interfacesr7 orm.sessionr8r9r:r;r< sql._typingr=sql.baser>sql.dmlr? sql.elementsr@sql.selectablerArB_AsyncSessionBindrCrDrrrrIcreate_proxy_methodsr|r:rEr rr{re_async_providerr]rRrPrs# !"'%A!%+.&$'#$&  $&:@#/!9++--2+.(&%-42:;t_ T&4%%'7&>?$$$$&6%=>Z2Z2z $"N3  %: ?7+ ;: H,e>*j j Z#'#,#.C &'./C L: N 3#0rR