session.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947
  1. # ext/asyncio/session.py
  2. # Copyright (C) 2020-2026 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. from __future__ import annotations
  8. import asyncio
  9. from typing import Any
  10. from typing import Awaitable
  11. from typing import Callable
  12. from typing import cast
  13. from typing import Dict
  14. from typing import Generic
  15. from typing import Iterable
  16. from typing import Iterator
  17. from typing import NoReturn
  18. from typing import Optional
  19. from typing import overload
  20. from typing import Sequence
  21. from typing import Tuple
  22. from typing import Type
  23. from typing import TYPE_CHECKING
  24. from typing import TypeVar
  25. from typing import Union
  26. from . import engine
  27. from .base import ReversibleProxy
  28. from .base import StartableContext
  29. from .result import _ensure_sync_result
  30. from .result import AsyncResult
  31. from .result import AsyncScalarResult
  32. from ... import util
  33. from ...orm import close_all_sessions as _sync_close_all_sessions
  34. from ...orm import object_session
  35. from ...orm import Session
  36. from ...orm import SessionTransaction
  37. from ...orm import state as _instance_state
  38. from ...util.concurrency import greenlet_spawn
  39. from ...util.typing import Concatenate
  40. from ...util.typing import ParamSpec
  41. if TYPE_CHECKING:
  42. from .engine import AsyncConnection
  43. from .engine import AsyncEngine
  44. from ...engine import Connection
  45. from ...engine import Engine
  46. from ...engine import Result
  47. from ...engine import Row
  48. from ...engine import RowMapping
  49. from ...engine import ScalarResult
  50. from ...engine.interfaces import _CoreAnyExecuteParams
  51. from ...engine.interfaces import CoreExecuteOptionsParameter
  52. from ...event import dispatcher
  53. from ...orm._typing import _IdentityKeyType
  54. from ...orm._typing import _O
  55. from ...orm._typing import OrmExecuteOptionsParameter
  56. from ...orm.identity import IdentityMap
  57. from ...orm.interfaces import ORMOption
  58. from ...orm.session import _BindArguments
  59. from ...orm.session import _EntityBindKey
  60. from ...orm.session import _PKIdentityArgument
  61. from ...orm.session import _SessionBind
  62. from ...orm.session import _SessionBindKey
  63. from ...sql._typing import _InfoType
  64. from ...sql.base import Executable
  65. from ...sql.elements import ClauseElement
  66. from ...sql.selectable import ForUpdateParameter
  67. from ...sql.selectable import TypedReturnsRows
  68. _AsyncSessionBind = Union["AsyncEngine", "AsyncConnection"]
  69. _P = ParamSpec("_P")
  70. _T = TypeVar("_T", bound=Any)
  71. _EXECUTE_OPTIONS = util.immutabledict({"prebuffer_rows": True})
  72. _STREAM_OPTIONS = util.immutabledict({"stream_results": True})
  73. class AsyncAttrs:
  74. """Mixin class which provides an awaitable accessor for all attributes.
  75. E.g.::
  76. from __future__ import annotations
  77. from typing import List
  78. from sqlalchemy import ForeignKey
  79. from sqlalchemy import func
  80. from sqlalchemy.ext.asyncio import AsyncAttrs
  81. from sqlalchemy.orm import DeclarativeBase
  82. from sqlalchemy.orm import Mapped
  83. from sqlalchemy.orm import mapped_column
  84. from sqlalchemy.orm import relationship
  85. class Base(AsyncAttrs, DeclarativeBase):
  86. pass
  87. class A(Base):
  88. __tablename__ = "a"
  89. id: Mapped[int] = mapped_column(primary_key=True)
  90. data: Mapped[str]
  91. bs: Mapped[List[B]] = relationship()
  92. class B(Base):
  93. __tablename__ = "b"
  94. id: Mapped[int] = mapped_column(primary_key=True)
  95. a_id: Mapped[int] = mapped_column(ForeignKey("a.id"))
  96. data: Mapped[str]
  97. In the above example, the :class:`_asyncio.AsyncAttrs` mixin is applied to
  98. the declarative ``Base`` class where it takes effect for all subclasses.
  99. This mixin adds a single new attribute
  100. :attr:`_asyncio.AsyncAttrs.awaitable_attrs` to all classes, which will
  101. yield the value of any attribute as an awaitable. This allows attributes
  102. which may be subject to lazy loading or deferred / unexpiry loading to be
  103. accessed such that IO can still be emitted::
  104. a1 = (await async_session.scalars(select(A).where(A.id == 5))).one()
  105. # use the lazy loader on ``a1.bs`` via the ``.awaitable_attrs``
  106. # interface, so that it may be awaited
  107. for b1 in await a1.awaitable_attrs.bs:
  108. print(b1)
  109. The :attr:`_asyncio.AsyncAttrs.awaitable_attrs` performs a call against the
  110. attribute that is approximately equivalent to using the
  111. :meth:`_asyncio.AsyncSession.run_sync` method, e.g.::
  112. for b1 in await async_session.run_sync(lambda sess: a1.bs):
  113. print(b1)
  114. .. versionadded:: 2.0.13
  115. .. seealso::
  116. :ref:`asyncio_orm_avoid_lazyloads`
  117. """
  118. class _AsyncAttrGetitem:
  119. __slots__ = "_instance"
  120. def __init__(self, _instance: Any):
  121. self._instance = _instance
  122. def __getattr__(self, name: str) -> Awaitable[Any]:
  123. return greenlet_spawn(getattr, self._instance, name)
  124. @property
  125. def awaitable_attrs(self) -> AsyncAttrs._AsyncAttrGetitem:
  126. """provide a namespace of all attributes on this object wrapped
  127. as awaitables.
  128. e.g.::
  129. a1 = (await async_session.scalars(select(A).where(A.id == 5))).one()
  130. some_attribute = await a1.awaitable_attrs.some_deferred_attribute
  131. some_collection = await a1.awaitable_attrs.some_collection
  132. """ # noqa: E501
  133. return AsyncAttrs._AsyncAttrGetitem(self)
  134. @util.create_proxy_methods(
  135. Session,
  136. ":class:`_orm.Session`",
  137. ":class:`_asyncio.AsyncSession`",
  138. classmethods=["object_session", "identity_key"],
  139. methods=[
  140. "__contains__",
  141. "__iter__",
  142. "add",
  143. "add_all",
  144. "expire",
  145. "expire_all",
  146. "expunge",
  147. "expunge_all",
  148. "is_modified",
  149. "in_transaction",
  150. "in_nested_transaction",
  151. ],
  152. attributes=[
  153. "dirty",
  154. "deleted",
  155. "new",
  156. "identity_map",
  157. "is_active",
  158. "autoflush",
  159. "no_autoflush",
  160. "info",
  161. ],
  162. )
  163. class AsyncSession(ReversibleProxy[Session]):
  164. """Asyncio version of :class:`_orm.Session`.
  165. The :class:`_asyncio.AsyncSession` is a proxy for a traditional
  166. :class:`_orm.Session` instance.
  167. The :class:`_asyncio.AsyncSession` is **not safe for use in concurrent
  168. tasks.**. See :ref:`session_faq_threadsafe` for background.
  169. .. versionadded:: 1.4
  170. To use an :class:`_asyncio.AsyncSession` with custom :class:`_orm.Session`
  171. implementations, see the
  172. :paramref:`_asyncio.AsyncSession.sync_session_class` parameter.
  173. """
  174. _is_asyncio = True
  175. dispatch: dispatcher[Session]
  176. def __init__(
  177. self,
  178. bind: Optional[_AsyncSessionBind] = None,
  179. *,
  180. binds: Optional[Dict[_SessionBindKey, _AsyncSessionBind]] = None,
  181. sync_session_class: Optional[Type[Session]] = None,
  182. **kw: Any,
  183. ):
  184. r"""Construct a new :class:`_asyncio.AsyncSession`.
  185. All parameters other than ``sync_session_class`` are passed to the
  186. ``sync_session_class`` callable directly to instantiate a new
  187. :class:`_orm.Session`. Refer to :meth:`_orm.Session.__init__` for
  188. parameter documentation.
  189. :param sync_session_class:
  190. A :class:`_orm.Session` subclass or other callable which will be used
  191. to construct the :class:`_orm.Session` which will be proxied. This
  192. parameter may be used to provide custom :class:`_orm.Session`
  193. subclasses. Defaults to the
  194. :attr:`_asyncio.AsyncSession.sync_session_class` class-level
  195. attribute.
  196. .. versionadded:: 1.4.24
  197. """
  198. sync_bind = sync_binds = None
  199. if bind:
  200. self.bind = bind
  201. sync_bind = engine._get_sync_engine_or_connection(bind)
  202. if binds:
  203. self.binds = binds
  204. sync_binds = {
  205. key: engine._get_sync_engine_or_connection(b)
  206. for key, b in binds.items()
  207. }
  208. if sync_session_class:
  209. self.sync_session_class = sync_session_class
  210. self.sync_session = self._proxied = self._assign_proxied(
  211. self.sync_session_class(bind=sync_bind, binds=sync_binds, **kw)
  212. )
  213. sync_session_class: Type[Session] = Session
  214. """The class or callable that provides the
  215. underlying :class:`_orm.Session` instance for a particular
  216. :class:`_asyncio.AsyncSession`.
  217. At the class level, this attribute is the default value for the
  218. :paramref:`_asyncio.AsyncSession.sync_session_class` parameter. Custom
  219. subclasses of :class:`_asyncio.AsyncSession` can override this.
  220. At the instance level, this attribute indicates the current class or
  221. callable that was used to provide the :class:`_orm.Session` instance for
  222. this :class:`_asyncio.AsyncSession` instance.
  223. .. versionadded:: 1.4.24
  224. """
  225. sync_session: Session
  226. """Reference to the underlying :class:`_orm.Session` this
  227. :class:`_asyncio.AsyncSession` proxies requests towards.
  228. This instance can be used as an event target.
  229. .. seealso::
  230. :ref:`asyncio_events`
  231. """
  232. @classmethod
  233. def _no_async_engine_events(cls) -> NoReturn:
  234. raise NotImplementedError(
  235. "asynchronous events are not implemented at this time. Apply "
  236. "synchronous listeners to the AsyncSession.sync_session."
  237. )
  238. async def refresh(
  239. self,
  240. instance: object,
  241. attribute_names: Optional[Iterable[str]] = None,
  242. with_for_update: ForUpdateParameter = None,
  243. ) -> None:
  244. """Expire and refresh the attributes on the given instance.
  245. A query will be issued to the database and all attributes will be
  246. refreshed with their current database value.
  247. This is the async version of the :meth:`_orm.Session.refresh` method.
  248. See that method for a complete description of all options.
  249. .. seealso::
  250. :meth:`_orm.Session.refresh` - main documentation for refresh
  251. """
  252. await greenlet_spawn(
  253. self.sync_session.refresh,
  254. instance,
  255. attribute_names=attribute_names,
  256. with_for_update=with_for_update,
  257. )
  258. async def run_sync(
  259. self,
  260. fn: Callable[Concatenate[Session, _P], _T],
  261. *arg: _P.args,
  262. **kw: _P.kwargs,
  263. ) -> _T:
  264. '''Invoke the given synchronous (i.e. not async) callable,
  265. passing a synchronous-style :class:`_orm.Session` as the first
  266. argument.
  267. This method allows traditional synchronous SQLAlchemy functions to
  268. run within the context of an asyncio application.
  269. E.g.::
  270. def some_business_method(session: Session, param: str) -> str:
  271. """A synchronous function that does not require awaiting
  272. :param session: a SQLAlchemy Session, used synchronously
  273. :return: an optional return value is supported
  274. """
  275. session.add(MyObject(param=param))
  276. session.flush()
  277. return "success"
  278. async def do_something_async(async_engine: AsyncEngine) -> None:
  279. """an async function that uses awaiting"""
  280. with AsyncSession(async_engine) as async_session:
  281. # run some_business_method() with a sync-style
  282. # Session, proxied into an awaitable
  283. return_code = await async_session.run_sync(
  284. some_business_method, param="param1"
  285. )
  286. print(return_code)
  287. This method maintains the asyncio event loop all the way through
  288. to the database connection by running the given callable in a
  289. specially instrumented greenlet.
  290. .. tip::
  291. The provided callable is invoked inline within the asyncio event
  292. loop, and will block on traditional IO calls. IO within this
  293. callable should only call into SQLAlchemy's asyncio database
  294. APIs which will be properly adapted to the greenlet context.
  295. .. seealso::
  296. :class:`.AsyncAttrs` - a mixin for ORM mapped classes that provides
  297. a similar feature more succinctly on a per-attribute basis
  298. :meth:`.AsyncConnection.run_sync`
  299. :ref:`session_run_sync`
  300. ''' # noqa: E501
  301. return await greenlet_spawn(
  302. fn, self.sync_session, *arg, _require_await=False, **kw
  303. )
  304. @overload
  305. async def execute(
  306. self,
  307. statement: TypedReturnsRows[_T],
  308. params: Optional[_CoreAnyExecuteParams] = None,
  309. *,
  310. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  311. bind_arguments: Optional[_BindArguments] = None,
  312. _parent_execute_state: Optional[Any] = None,
  313. _add_event: Optional[Any] = None,
  314. ) -> Result[_T]: ...
  315. @overload
  316. async def execute(
  317. self,
  318. statement: Executable,
  319. params: Optional[_CoreAnyExecuteParams] = None,
  320. *,
  321. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  322. bind_arguments: Optional[_BindArguments] = None,
  323. _parent_execute_state: Optional[Any] = None,
  324. _add_event: Optional[Any] = None,
  325. ) -> Result[Any]: ...
  326. async def execute(
  327. self,
  328. statement: Executable,
  329. params: Optional[_CoreAnyExecuteParams] = None,
  330. *,
  331. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  332. bind_arguments: Optional[_BindArguments] = None,
  333. **kw: Any,
  334. ) -> Result[Any]:
  335. """Execute a statement and return a buffered
  336. :class:`_engine.Result` object.
  337. .. seealso::
  338. :meth:`_orm.Session.execute` - main documentation for execute
  339. """
  340. if execution_options:
  341. execution_options = util.immutabledict(execution_options).union(
  342. _EXECUTE_OPTIONS
  343. )
  344. else:
  345. execution_options = _EXECUTE_OPTIONS
  346. result = await greenlet_spawn(
  347. self.sync_session.execute,
  348. statement,
  349. params=params,
  350. execution_options=execution_options,
  351. bind_arguments=bind_arguments,
  352. **kw,
  353. )
  354. return await _ensure_sync_result(result, self.execute)
  355. @overload
  356. async def scalar(
  357. self,
  358. statement: TypedReturnsRows[Tuple[_T]],
  359. params: Optional[_CoreAnyExecuteParams] = None,
  360. *,
  361. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  362. bind_arguments: Optional[_BindArguments] = None,
  363. **kw: Any,
  364. ) -> Optional[_T]: ...
  365. @overload
  366. async def scalar(
  367. self,
  368. statement: Executable,
  369. params: Optional[_CoreAnyExecuteParams] = None,
  370. *,
  371. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  372. bind_arguments: Optional[_BindArguments] = None,
  373. **kw: Any,
  374. ) -> Any: ...
  375. async def scalar(
  376. self,
  377. statement: Executable,
  378. params: Optional[_CoreAnyExecuteParams] = None,
  379. *,
  380. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  381. bind_arguments: Optional[_BindArguments] = None,
  382. **kw: Any,
  383. ) -> Any:
  384. """Execute a statement and return a scalar result.
  385. .. seealso::
  386. :meth:`_orm.Session.scalar` - main documentation for scalar
  387. """
  388. if execution_options:
  389. execution_options = util.immutabledict(execution_options).union(
  390. _EXECUTE_OPTIONS
  391. )
  392. else:
  393. execution_options = _EXECUTE_OPTIONS
  394. return await greenlet_spawn(
  395. self.sync_session.scalar,
  396. statement,
  397. params=params,
  398. execution_options=execution_options,
  399. bind_arguments=bind_arguments,
  400. **kw,
  401. )
  402. @overload
  403. async def scalars(
  404. self,
  405. statement: TypedReturnsRows[Tuple[_T]],
  406. params: Optional[_CoreAnyExecuteParams] = None,
  407. *,
  408. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  409. bind_arguments: Optional[_BindArguments] = None,
  410. **kw: Any,
  411. ) -> ScalarResult[_T]: ...
  412. @overload
  413. async def scalars(
  414. self,
  415. statement: Executable,
  416. params: Optional[_CoreAnyExecuteParams] = None,
  417. *,
  418. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  419. bind_arguments: Optional[_BindArguments] = None,
  420. **kw: Any,
  421. ) -> ScalarResult[Any]: ...
  422. async def scalars(
  423. self,
  424. statement: Executable,
  425. params: Optional[_CoreAnyExecuteParams] = None,
  426. *,
  427. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  428. bind_arguments: Optional[_BindArguments] = None,
  429. **kw: Any,
  430. ) -> ScalarResult[Any]:
  431. """Execute a statement and return scalar results.
  432. :return: a :class:`_result.ScalarResult` object
  433. .. versionadded:: 1.4.24 Added :meth:`_asyncio.AsyncSession.scalars`
  434. .. versionadded:: 1.4.26 Added
  435. :meth:`_asyncio.async_scoped_session.scalars`
  436. .. seealso::
  437. :meth:`_orm.Session.scalars` - main documentation for scalars
  438. :meth:`_asyncio.AsyncSession.stream_scalars` - streaming version
  439. """
  440. result = await self.execute(
  441. statement,
  442. params=params,
  443. execution_options=execution_options,
  444. bind_arguments=bind_arguments,
  445. **kw,
  446. )
  447. return result.scalars()
  448. async def get(
  449. self,
  450. entity: _EntityBindKey[_O],
  451. ident: _PKIdentityArgument,
  452. *,
  453. options: Optional[Sequence[ORMOption]] = None,
  454. populate_existing: bool = False,
  455. with_for_update: ForUpdateParameter = None,
  456. identity_token: Optional[Any] = None,
  457. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  458. ) -> Union[_O, None]:
  459. """Return an instance based on the given primary key identifier,
  460. or ``None`` if not found.
  461. .. seealso::
  462. :meth:`_orm.Session.get` - main documentation for get
  463. """
  464. return await greenlet_spawn(
  465. cast("Callable[..., _O]", self.sync_session.get),
  466. entity,
  467. ident,
  468. options=options,
  469. populate_existing=populate_existing,
  470. with_for_update=with_for_update,
  471. identity_token=identity_token,
  472. execution_options=execution_options,
  473. )
  474. async def get_one(
  475. self,
  476. entity: _EntityBindKey[_O],
  477. ident: _PKIdentityArgument,
  478. *,
  479. options: Optional[Sequence[ORMOption]] = None,
  480. populate_existing: bool = False,
  481. with_for_update: ForUpdateParameter = None,
  482. identity_token: Optional[Any] = None,
  483. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  484. ) -> _O:
  485. """Return an instance based on the given primary key identifier,
  486. or raise an exception if not found.
  487. Raises :class:`_exc.NoResultFound` if the query selects no rows.
  488. ..versionadded: 2.0.22
  489. .. seealso::
  490. :meth:`_orm.Session.get_one` - main documentation for get_one
  491. """
  492. return await greenlet_spawn(
  493. cast("Callable[..., _O]", self.sync_session.get_one),
  494. entity,
  495. ident,
  496. options=options,
  497. populate_existing=populate_existing,
  498. with_for_update=with_for_update,
  499. identity_token=identity_token,
  500. execution_options=execution_options,
  501. )
  502. @overload
  503. async def stream(
  504. self,
  505. statement: TypedReturnsRows[_T],
  506. params: Optional[_CoreAnyExecuteParams] = None,
  507. *,
  508. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  509. bind_arguments: Optional[_BindArguments] = None,
  510. **kw: Any,
  511. ) -> AsyncResult[_T]: ...
  512. @overload
  513. async def stream(
  514. self,
  515. statement: Executable,
  516. params: Optional[_CoreAnyExecuteParams] = None,
  517. *,
  518. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  519. bind_arguments: Optional[_BindArguments] = None,
  520. **kw: Any,
  521. ) -> AsyncResult[Any]: ...
  522. async def stream(
  523. self,
  524. statement: Executable,
  525. params: Optional[_CoreAnyExecuteParams] = None,
  526. *,
  527. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  528. bind_arguments: Optional[_BindArguments] = None,
  529. **kw: Any,
  530. ) -> AsyncResult[Any]:
  531. """Execute a statement and return a streaming
  532. :class:`_asyncio.AsyncResult` object.
  533. """
  534. if execution_options:
  535. execution_options = util.immutabledict(execution_options).union(
  536. _STREAM_OPTIONS
  537. )
  538. else:
  539. execution_options = _STREAM_OPTIONS
  540. result = await greenlet_spawn(
  541. self.sync_session.execute,
  542. statement,
  543. params=params,
  544. execution_options=execution_options,
  545. bind_arguments=bind_arguments,
  546. **kw,
  547. )
  548. return AsyncResult(result)
  549. @overload
  550. async def stream_scalars(
  551. self,
  552. statement: TypedReturnsRows[Tuple[_T]],
  553. params: Optional[_CoreAnyExecuteParams] = None,
  554. *,
  555. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  556. bind_arguments: Optional[_BindArguments] = None,
  557. **kw: Any,
  558. ) -> AsyncScalarResult[_T]: ...
  559. @overload
  560. async def stream_scalars(
  561. self,
  562. statement: Executable,
  563. params: Optional[_CoreAnyExecuteParams] = None,
  564. *,
  565. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  566. bind_arguments: Optional[_BindArguments] = None,
  567. **kw: Any,
  568. ) -> AsyncScalarResult[Any]: ...
  569. async def stream_scalars(
  570. self,
  571. statement: Executable,
  572. params: Optional[_CoreAnyExecuteParams] = None,
  573. *,
  574. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  575. bind_arguments: Optional[_BindArguments] = None,
  576. **kw: Any,
  577. ) -> AsyncScalarResult[Any]:
  578. """Execute a statement and return a stream of scalar results.
  579. :return: an :class:`_asyncio.AsyncScalarResult` object
  580. .. versionadded:: 1.4.24
  581. .. seealso::
  582. :meth:`_orm.Session.scalars` - main documentation for scalars
  583. :meth:`_asyncio.AsyncSession.scalars` - non streaming version
  584. """
  585. result = await self.stream(
  586. statement,
  587. params=params,
  588. execution_options=execution_options,
  589. bind_arguments=bind_arguments,
  590. **kw,
  591. )
  592. return result.scalars()
  593. async def delete(self, instance: object) -> None:
  594. """Mark an instance as deleted.
  595. The database delete operation occurs upon ``flush()``.
  596. As this operation may need to cascade along unloaded relationships,
  597. it is awaitable to allow for those queries to take place.
  598. .. seealso::
  599. :meth:`_orm.Session.delete` - main documentation for delete
  600. """
  601. await greenlet_spawn(self.sync_session.delete, instance)
  602. async def merge(
  603. self,
  604. instance: _O,
  605. *,
  606. load: bool = True,
  607. options: Optional[Sequence[ORMOption]] = None,
  608. ) -> _O:
  609. """Copy the state of a given instance into a corresponding instance
  610. within this :class:`_asyncio.AsyncSession`.
  611. .. seealso::
  612. :meth:`_orm.Session.merge` - main documentation for merge
  613. """
  614. return await greenlet_spawn(
  615. self.sync_session.merge, instance, load=load, options=options
  616. )
  617. async def flush(self, objects: Optional[Sequence[Any]] = None) -> None:
  618. """Flush all the object changes to the database.
  619. .. seealso::
  620. :meth:`_orm.Session.flush` - main documentation for flush
  621. """
  622. await greenlet_spawn(self.sync_session.flush, objects=objects)
  623. def get_transaction(self) -> Optional[AsyncSessionTransaction]:
  624. """Return the current root transaction in progress, if any.
  625. :return: an :class:`_asyncio.AsyncSessionTransaction` object, or
  626. ``None``.
  627. .. versionadded:: 1.4.18
  628. """
  629. trans = self.sync_session.get_transaction()
  630. if trans is not None:
  631. return AsyncSessionTransaction._retrieve_proxy_for_target(
  632. trans, async_session=self
  633. )
  634. else:
  635. return None
  636. def get_nested_transaction(self) -> Optional[AsyncSessionTransaction]:
  637. """Return the current nested transaction in progress, if any.
  638. :return: an :class:`_asyncio.AsyncSessionTransaction` object, or
  639. ``None``.
  640. .. versionadded:: 1.4.18
  641. """
  642. trans = self.sync_session.get_nested_transaction()
  643. if trans is not None:
  644. return AsyncSessionTransaction._retrieve_proxy_for_target(
  645. trans, async_session=self
  646. )
  647. else:
  648. return None
  649. def get_bind(
  650. self,
  651. mapper: Optional[_EntityBindKey[_O]] = None,
  652. clause: Optional[ClauseElement] = None,
  653. bind: Optional[_SessionBind] = None,
  654. **kw: Any,
  655. ) -> Union[Engine, Connection]:
  656. """Return a "bind" to which the synchronous proxied :class:`_orm.Session`
  657. is bound.
  658. Unlike the :meth:`_orm.Session.get_bind` method, this method is
  659. currently **not** used by this :class:`.AsyncSession` in any way
  660. in order to resolve engines for requests.
  661. .. note::
  662. This method proxies directly to the :meth:`_orm.Session.get_bind`
  663. method, however is currently **not** useful as an override target,
  664. in contrast to that of the :meth:`_orm.Session.get_bind` method.
  665. The example below illustrates how to implement custom
  666. :meth:`_orm.Session.get_bind` schemes that work with
  667. :class:`.AsyncSession` and :class:`.AsyncEngine`.
  668. The pattern introduced at :ref:`session_custom_partitioning`
  669. illustrates how to apply a custom bind-lookup scheme to a
  670. :class:`_orm.Session` given a set of :class:`_engine.Engine` objects.
  671. To apply a corresponding :meth:`_orm.Session.get_bind` implementation
  672. for use with a :class:`.AsyncSession` and :class:`.AsyncEngine`
  673. objects, continue to subclass :class:`_orm.Session` and apply it to
  674. :class:`.AsyncSession` using
  675. :paramref:`.AsyncSession.sync_session_class`. The inner method must
  676. continue to return :class:`_engine.Engine` instances, which can be
  677. acquired from a :class:`_asyncio.AsyncEngine` using the
  678. :attr:`_asyncio.AsyncEngine.sync_engine` attribute::
  679. # using example from "Custom Vertical Partitioning"
  680. import random
  681. from sqlalchemy.ext.asyncio import AsyncSession
  682. from sqlalchemy.ext.asyncio import create_async_engine
  683. from sqlalchemy.ext.asyncio import async_sessionmaker
  684. from sqlalchemy.orm import Session
  685. # construct async engines w/ async drivers
  686. engines = {
  687. "leader": create_async_engine("sqlite+aiosqlite:///leader.db"),
  688. "other": create_async_engine("sqlite+aiosqlite:///other.db"),
  689. "follower1": create_async_engine("sqlite+aiosqlite:///follower1.db"),
  690. "follower2": create_async_engine("sqlite+aiosqlite:///follower2.db"),
  691. }
  692. class RoutingSession(Session):
  693. def get_bind(self, mapper=None, clause=None, **kw):
  694. # within get_bind(), return sync engines
  695. if mapper and issubclass(mapper.class_, MyOtherClass):
  696. return engines["other"].sync_engine
  697. elif self._flushing or isinstance(clause, (Update, Delete)):
  698. return engines["leader"].sync_engine
  699. else:
  700. return engines[
  701. random.choice(["follower1", "follower2"])
  702. ].sync_engine
  703. # apply to AsyncSession using sync_session_class
  704. AsyncSessionMaker = async_sessionmaker(sync_session_class=RoutingSession)
  705. The :meth:`_orm.Session.get_bind` method is called in a non-asyncio,
  706. implicitly non-blocking context in the same manner as ORM event hooks
  707. and functions that are invoked via :meth:`.AsyncSession.run_sync`, so
  708. routines that wish to run SQL commands inside of
  709. :meth:`_orm.Session.get_bind` can continue to do so using
  710. blocking-style code, which will be translated to implicitly async calls
  711. at the point of invoking IO on the database drivers.
  712. """ # noqa: E501
  713. return self.sync_session.get_bind(
  714. mapper=mapper, clause=clause, bind=bind, **kw
  715. )
  716. async def connection(
  717. self,
  718. bind_arguments: Optional[_BindArguments] = None,
  719. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  720. **kw: Any,
  721. ) -> AsyncConnection:
  722. r"""Return a :class:`_asyncio.AsyncConnection` object corresponding to
  723. this :class:`.Session` object's transactional state.
  724. This method may also be used to establish execution options for the
  725. database connection used by the current transaction.
  726. .. versionadded:: 1.4.24 Added \**kw arguments which are passed
  727. through to the underlying :meth:`_orm.Session.connection` method.
  728. .. seealso::
  729. :meth:`_orm.Session.connection` - main documentation for
  730. "connection"
  731. """
  732. sync_connection = await greenlet_spawn(
  733. self.sync_session.connection,
  734. bind_arguments=bind_arguments,
  735. execution_options=execution_options,
  736. **kw,
  737. )
  738. return engine.AsyncConnection._retrieve_proxy_for_target(
  739. sync_connection
  740. )
  741. def begin(self) -> AsyncSessionTransaction:
  742. """Return an :class:`_asyncio.AsyncSessionTransaction` object.
  743. The underlying :class:`_orm.Session` will perform the
  744. "begin" action when the :class:`_asyncio.AsyncSessionTransaction`
  745. object is entered::
  746. async with async_session.begin():
  747. ... # ORM transaction is begun
  748. Note that database IO will not normally occur when the session-level
  749. transaction is begun, as database transactions begin on an
  750. on-demand basis. However, the begin block is async to accommodate
  751. for a :meth:`_orm.SessionEvents.after_transaction_create`
  752. event hook that may perform IO.
  753. For a general description of ORM begin, see
  754. :meth:`_orm.Session.begin`.
  755. """
  756. return AsyncSessionTransaction(self)
  757. def begin_nested(self) -> AsyncSessionTransaction:
  758. """Return an :class:`_asyncio.AsyncSessionTransaction` object
  759. which will begin a "nested" transaction, e.g. SAVEPOINT.
  760. Behavior is the same as that of :meth:`_asyncio.AsyncSession.begin`.
  761. For a general description of ORM begin nested, see
  762. :meth:`_orm.Session.begin_nested`.
  763. .. seealso::
  764. :ref:`aiosqlite_serializable` - special workarounds required
  765. with the SQLite asyncio driver in order for SAVEPOINT to work
  766. correctly.
  767. """
  768. return AsyncSessionTransaction(self, nested=True)
  769. async def rollback(self) -> None:
  770. """Rollback the current transaction in progress.
  771. .. seealso::
  772. :meth:`_orm.Session.rollback` - main documentation for
  773. "rollback"
  774. """
  775. await greenlet_spawn(self.sync_session.rollback)
  776. async def commit(self) -> None:
  777. """Commit the current transaction in progress.
  778. .. seealso::
  779. :meth:`_orm.Session.commit` - main documentation for
  780. "commit"
  781. """
  782. await greenlet_spawn(self.sync_session.commit)
  783. async def close(self) -> None:
  784. """Close out the transactional resources and ORM objects used by this
  785. :class:`_asyncio.AsyncSession`.
  786. .. seealso::
  787. :meth:`_orm.Session.close` - main documentation for
  788. "close"
  789. :ref:`session_closing` - detail on the semantics of
  790. :meth:`_asyncio.AsyncSession.close` and
  791. :meth:`_asyncio.AsyncSession.reset`.
  792. """
  793. await greenlet_spawn(self.sync_session.close)
  794. async def reset(self) -> None:
  795. """Close out the transactional resources and ORM objects used by this
  796. :class:`_orm.Session`, resetting the session to its initial state.
  797. .. versionadded:: 2.0.22
  798. .. seealso::
  799. :meth:`_orm.Session.reset` - main documentation for
  800. "reset"
  801. :ref:`session_closing` - detail on the semantics of
  802. :meth:`_asyncio.AsyncSession.close` and
  803. :meth:`_asyncio.AsyncSession.reset`.
  804. """
  805. await greenlet_spawn(self.sync_session.reset)
  806. async def aclose(self) -> None:
  807. """A synonym for :meth:`_asyncio.AsyncSession.close`.
  808. The :meth:`_asyncio.AsyncSession.aclose` name is specifically
  809. to support the Python standard library ``@contextlib.aclosing``
  810. context manager function.
  811. .. versionadded:: 2.0.20
  812. """
  813. await self.close()
  814. async def invalidate(self) -> None:
  815. """Close this Session, using connection invalidation.
  816. For a complete description, see :meth:`_orm.Session.invalidate`.
  817. """
  818. await greenlet_spawn(self.sync_session.invalidate)
  819. @classmethod
  820. @util.deprecated(
  821. "2.0",
  822. "The :meth:`.AsyncSession.close_all` method is deprecated and will be "
  823. "removed in a future release. Please refer to "
  824. ":func:`_asyncio.close_all_sessions`.",
  825. )
  826. async def close_all(cls) -> None:
  827. """Close all :class:`_asyncio.AsyncSession` sessions."""
  828. await close_all_sessions()
  829. async def __aenter__(self: _AS) -> _AS:
  830. return self
  831. async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:
  832. task = asyncio.create_task(self.close())
  833. await asyncio.shield(task)
  834. def _maker_context_manager(self: _AS) -> _AsyncSessionContextManager[_AS]:
  835. return _AsyncSessionContextManager(self)
  836. # START PROXY METHODS AsyncSession
  837. # code within this block is **programmatically,
  838. # statically generated** by tools/generate_proxy_methods.py
  839. def __contains__(self, instance: object) -> bool:
  840. r"""Return True if the instance is associated with this session.
  841. .. container:: class_bases
  842. Proxied for the :class:`_orm.Session` class on
  843. behalf of the :class:`_asyncio.AsyncSession` class.
  844. The instance may be pending or persistent within the Session for a
  845. result of True.
  846. """ # noqa: E501
  847. return self._proxied.__contains__(instance)
  848. def __iter__(self) -> Iterator[object]:
  849. r"""Iterate over all pending or persistent instances within this
  850. Session.
  851. .. container:: class_bases
  852. Proxied for the :class:`_orm.Session` class on
  853. behalf of the :class:`_asyncio.AsyncSession` class.
  854. """ # noqa: E501
  855. return self._proxied.__iter__()
  856. def add(self, instance: object, _warn: bool = True) -> None:
  857. r"""Place an object into this :class:`_orm.Session`.
  858. .. container:: class_bases
  859. Proxied for the :class:`_orm.Session` class on
  860. behalf of the :class:`_asyncio.AsyncSession` class.
  861. Objects that are in the :term:`transient` state when passed to the
  862. :meth:`_orm.Session.add` method will move to the
  863. :term:`pending` state, until the next flush, at which point they
  864. will move to the :term:`persistent` state.
  865. Objects that are in the :term:`detached` state when passed to the
  866. :meth:`_orm.Session.add` method will move to the :term:`persistent`
  867. state directly.
  868. If the transaction used by the :class:`_orm.Session` is rolled back,
  869. objects which were transient when they were passed to
  870. :meth:`_orm.Session.add` will be moved back to the
  871. :term:`transient` state, and will no longer be present within this
  872. :class:`_orm.Session`.
  873. .. seealso::
  874. :meth:`_orm.Session.add_all`
  875. :ref:`session_adding` - at :ref:`session_basics`
  876. """ # noqa: E501
  877. return self._proxied.add(instance, _warn=_warn)
  878. def add_all(self, instances: Iterable[object]) -> None:
  879. r"""Add the given collection of instances to this :class:`_orm.Session`.
  880. .. container:: class_bases
  881. Proxied for the :class:`_orm.Session` class on
  882. behalf of the :class:`_asyncio.AsyncSession` class.
  883. See the documentation for :meth:`_orm.Session.add` for a general
  884. behavioral description.
  885. .. seealso::
  886. :meth:`_orm.Session.add`
  887. :ref:`session_adding` - at :ref:`session_basics`
  888. """ # noqa: E501
  889. return self._proxied.add_all(instances)
  890. def expire(
  891. self, instance: object, attribute_names: Optional[Iterable[str]] = None
  892. ) -> None:
  893. r"""Expire the attributes on an instance.
  894. .. container:: class_bases
  895. Proxied for the :class:`_orm.Session` class on
  896. behalf of the :class:`_asyncio.AsyncSession` class.
  897. Marks the attributes of an instance as out of date. When an expired
  898. attribute is next accessed, a query will be issued to the
  899. :class:`.Session` object's current transactional context in order to
  900. load all expired attributes for the given instance. Note that
  901. a highly isolated transaction will return the same values as were
  902. previously read in that same transaction, regardless of changes
  903. in database state outside of that transaction.
  904. To expire all objects in the :class:`.Session` simultaneously,
  905. use :meth:`Session.expire_all`.
  906. The :class:`.Session` object's default behavior is to
  907. expire all state whenever the :meth:`Session.rollback`
  908. or :meth:`Session.commit` methods are called, so that new
  909. state can be loaded for the new transaction. For this reason,
  910. calling :meth:`Session.expire` only makes sense for the specific
  911. case that a non-ORM SQL statement was emitted in the current
  912. transaction.
  913. :param instance: The instance to be refreshed.
  914. :param attribute_names: optional list of string attribute names
  915. indicating a subset of attributes to be expired.
  916. .. seealso::
  917. :ref:`session_expire` - introductory material
  918. :meth:`.Session.expire`
  919. :meth:`.Session.refresh`
  920. :meth:`_orm.Query.populate_existing`
  921. """ # noqa: E501
  922. return self._proxied.expire(instance, attribute_names=attribute_names)
  923. def expire_all(self) -> None:
  924. r"""Expires all persistent instances within this Session.
  925. .. container:: class_bases
  926. Proxied for the :class:`_orm.Session` class on
  927. behalf of the :class:`_asyncio.AsyncSession` class.
  928. When any attributes on a persistent instance is next accessed,
  929. a query will be issued using the
  930. :class:`.Session` object's current transactional context in order to
  931. load all expired attributes for the given instance. Note that
  932. a highly isolated transaction will return the same values as were
  933. previously read in that same transaction, regardless of changes
  934. in database state outside of that transaction.
  935. To expire individual objects and individual attributes
  936. on those objects, use :meth:`Session.expire`.
  937. The :class:`.Session` object's default behavior is to
  938. expire all state whenever the :meth:`Session.rollback`
  939. or :meth:`Session.commit` methods are called, so that new
  940. state can be loaded for the new transaction. For this reason,
  941. calling :meth:`Session.expire_all` is not usually needed,
  942. assuming the transaction is isolated.
  943. .. seealso::
  944. :ref:`session_expire` - introductory material
  945. :meth:`.Session.expire`
  946. :meth:`.Session.refresh`
  947. :meth:`_orm.Query.populate_existing`
  948. """ # noqa: E501
  949. return self._proxied.expire_all()
  950. def expunge(self, instance: object) -> None:
  951. r"""Remove the `instance` from this ``Session``.
  952. .. container:: class_bases
  953. Proxied for the :class:`_orm.Session` class on
  954. behalf of the :class:`_asyncio.AsyncSession` class.
  955. This will free all internal references to the instance. Cascading
  956. will be applied according to the *expunge* cascade rule.
  957. """ # noqa: E501
  958. return self._proxied.expunge(instance)
  959. def expunge_all(self) -> None:
  960. r"""Remove all object instances from this ``Session``.
  961. .. container:: class_bases
  962. Proxied for the :class:`_orm.Session` class on
  963. behalf of the :class:`_asyncio.AsyncSession` class.
  964. This is equivalent to calling ``expunge(obj)`` on all objects in this
  965. ``Session``.
  966. """ # noqa: E501
  967. return self._proxied.expunge_all()
  968. def is_modified(
  969. self, instance: object, include_collections: bool = True
  970. ) -> bool:
  971. r"""Return ``True`` if the given instance has locally
  972. modified attributes.
  973. .. container:: class_bases
  974. Proxied for the :class:`_orm.Session` class on
  975. behalf of the :class:`_asyncio.AsyncSession` class.
  976. This method retrieves the history for each instrumented
  977. attribute on the instance and performs a comparison of the current
  978. value to its previously flushed or committed value, if any.
  979. It is in effect a more expensive and accurate
  980. version of checking for the given instance in the
  981. :attr:`.Session.dirty` collection; a full test for
  982. each attribute's net "dirty" status is performed.
  983. E.g.::
  984. return session.is_modified(someobject)
  985. A few caveats to this method apply:
  986. * Instances present in the :attr:`.Session.dirty` collection may
  987. report ``False`` when tested with this method. This is because
  988. the object may have received change events via attribute mutation,
  989. thus placing it in :attr:`.Session.dirty`, but ultimately the state
  990. is the same as that loaded from the database, resulting in no net
  991. change here.
  992. * Scalar attributes may not have recorded the previously set
  993. value when a new value was applied, if the attribute was not loaded,
  994. or was expired, at the time the new value was received - in these
  995. cases, the attribute is assumed to have a change, even if there is
  996. ultimately no net change against its database value. SQLAlchemy in
  997. most cases does not need the "old" value when a set event occurs, so
  998. it skips the expense of a SQL call if the old value isn't present,
  999. based on the assumption that an UPDATE of the scalar value is
  1000. usually needed, and in those few cases where it isn't, is less
  1001. expensive on average than issuing a defensive SELECT.
  1002. The "old" value is fetched unconditionally upon set only if the
  1003. attribute container has the ``active_history`` flag set to ``True``.
  1004. This flag is set typically for primary key attributes and scalar
  1005. object references that are not a simple many-to-one. To set this
  1006. flag for any arbitrary mapped column, use the ``active_history``
  1007. argument with :func:`.column_property`.
  1008. :param instance: mapped instance to be tested for pending changes.
  1009. :param include_collections: Indicates if multivalued collections
  1010. should be included in the operation. Setting this to ``False`` is a
  1011. way to detect only local-column based properties (i.e. scalar columns
  1012. or many-to-one foreign keys) that would result in an UPDATE for this
  1013. instance upon flush.
  1014. """ # noqa: E501
  1015. return self._proxied.is_modified(
  1016. instance, include_collections=include_collections
  1017. )
  1018. def in_transaction(self) -> bool:
  1019. r"""Return True if this :class:`_orm.Session` has begun a transaction.
  1020. .. container:: class_bases
  1021. Proxied for the :class:`_orm.Session` class on
  1022. behalf of the :class:`_asyncio.AsyncSession` class.
  1023. .. versionadded:: 1.4
  1024. .. seealso::
  1025. :attr:`_orm.Session.is_active`
  1026. """ # noqa: E501
  1027. return self._proxied.in_transaction()
  1028. def in_nested_transaction(self) -> bool:
  1029. r"""Return True if this :class:`_orm.Session` has begun a nested
  1030. transaction, e.g. SAVEPOINT.
  1031. .. container:: class_bases
  1032. Proxied for the :class:`_orm.Session` class on
  1033. behalf of the :class:`_asyncio.AsyncSession` class.
  1034. .. versionadded:: 1.4
  1035. """ # noqa: E501
  1036. return self._proxied.in_nested_transaction()
  1037. @property
  1038. def dirty(self) -> Any:
  1039. r"""The set of all persistent instances considered dirty.
  1040. .. container:: class_bases
  1041. Proxied for the :class:`_orm.Session` class
  1042. on behalf of the :class:`_asyncio.AsyncSession` class.
  1043. E.g.::
  1044. some_mapped_object in session.dirty
  1045. Instances are considered dirty when they were modified but not
  1046. deleted.
  1047. Note that this 'dirty' calculation is 'optimistic'; most
  1048. attribute-setting or collection modification operations will
  1049. mark an instance as 'dirty' and place it in this set, even if
  1050. there is no net change to the attribute's value. At flush
  1051. time, the value of each attribute is compared to its
  1052. previously saved value, and if there's no net change, no SQL
  1053. operation will occur (this is a more expensive operation so
  1054. it's only done at flush time).
  1055. To check if an instance has actionable net changes to its
  1056. attributes, use the :meth:`.Session.is_modified` method.
  1057. """ # noqa: E501
  1058. return self._proxied.dirty
  1059. @property
  1060. def deleted(self) -> Any:
  1061. r"""The set of all instances marked as 'deleted' within this ``Session``
  1062. .. container:: class_bases
  1063. Proxied for the :class:`_orm.Session` class
  1064. on behalf of the :class:`_asyncio.AsyncSession` class.
  1065. """ # noqa: E501
  1066. return self._proxied.deleted
  1067. @property
  1068. def new(self) -> Any:
  1069. r"""The set of all instances marked as 'new' within this ``Session``.
  1070. .. container:: class_bases
  1071. Proxied for the :class:`_orm.Session` class
  1072. on behalf of the :class:`_asyncio.AsyncSession` class.
  1073. """ # noqa: E501
  1074. return self._proxied.new
  1075. @property
  1076. def identity_map(self) -> IdentityMap:
  1077. r"""Proxy for the :attr:`_orm.Session.identity_map` attribute
  1078. on behalf of the :class:`_asyncio.AsyncSession` class.
  1079. """ # noqa: E501
  1080. return self._proxied.identity_map
  1081. @identity_map.setter
  1082. def identity_map(self, attr: IdentityMap) -> None:
  1083. self._proxied.identity_map = attr
  1084. @property
  1085. def is_active(self) -> Any:
  1086. r"""True if this :class:`.Session` not in "partial rollback" state.
  1087. .. container:: class_bases
  1088. Proxied for the :class:`_orm.Session` class
  1089. on behalf of the :class:`_asyncio.AsyncSession` class.
  1090. .. versionchanged:: 1.4 The :class:`_orm.Session` no longer begins
  1091. a new transaction immediately, so this attribute will be False
  1092. when the :class:`_orm.Session` is first instantiated.
  1093. "partial rollback" state typically indicates that the flush process
  1094. of the :class:`_orm.Session` has failed, and that the
  1095. :meth:`_orm.Session.rollback` method must be emitted in order to
  1096. fully roll back the transaction.
  1097. If this :class:`_orm.Session` is not in a transaction at all, the
  1098. :class:`_orm.Session` will autobegin when it is first used, so in this
  1099. case :attr:`_orm.Session.is_active` will return True.
  1100. Otherwise, if this :class:`_orm.Session` is within a transaction,
  1101. and that transaction has not been rolled back internally, the
  1102. :attr:`_orm.Session.is_active` will also return True.
  1103. .. seealso::
  1104. :ref:`faq_session_rollback`
  1105. :meth:`_orm.Session.in_transaction`
  1106. """ # noqa: E501
  1107. return self._proxied.is_active
  1108. @property
  1109. def autoflush(self) -> bool:
  1110. r"""Proxy for the :attr:`_orm.Session.autoflush` attribute
  1111. on behalf of the :class:`_asyncio.AsyncSession` class.
  1112. """ # noqa: E501
  1113. return self._proxied.autoflush
  1114. @autoflush.setter
  1115. def autoflush(self, attr: bool) -> None:
  1116. self._proxied.autoflush = attr
  1117. @property
  1118. def no_autoflush(self) -> Any:
  1119. r"""Return a context manager that disables autoflush.
  1120. .. container:: class_bases
  1121. Proxied for the :class:`_orm.Session` class
  1122. on behalf of the :class:`_asyncio.AsyncSession` class.
  1123. e.g.::
  1124. with session.no_autoflush:
  1125. some_object = SomeClass()
  1126. session.add(some_object)
  1127. # won't autoflush
  1128. some_object.related_thing = session.query(SomeRelated).first()
  1129. Operations that proceed within the ``with:`` block
  1130. will not be subject to flushes occurring upon query
  1131. access. This is useful when initializing a series
  1132. of objects which involve existing database queries,
  1133. where the uncompleted object should not yet be flushed.
  1134. """ # noqa: E501
  1135. return self._proxied.no_autoflush
  1136. @property
  1137. def info(self) -> Any:
  1138. r"""A user-modifiable dictionary.
  1139. .. container:: class_bases
  1140. Proxied for the :class:`_orm.Session` class
  1141. on behalf of the :class:`_asyncio.AsyncSession` class.
  1142. The initial value of this dictionary can be populated using the
  1143. ``info`` argument to the :class:`.Session` constructor or
  1144. :class:`.sessionmaker` constructor or factory methods. The dictionary
  1145. here is always local to this :class:`.Session` and can be modified
  1146. independently of all other :class:`.Session` objects.
  1147. """ # noqa: E501
  1148. return self._proxied.info
  1149. @classmethod
  1150. def object_session(cls, instance: object) -> Optional[Session]:
  1151. r"""Return the :class:`.Session` to which an object belongs.
  1152. .. container:: class_bases
  1153. Proxied for the :class:`_orm.Session` class on
  1154. behalf of the :class:`_asyncio.AsyncSession` class.
  1155. This is an alias of :func:`.object_session`.
  1156. """ # noqa: E501
  1157. return Session.object_session(instance)
  1158. @classmethod
  1159. def identity_key(
  1160. cls,
  1161. class_: Optional[Type[Any]] = None,
  1162. ident: Union[Any, Tuple[Any, ...]] = None,
  1163. *,
  1164. instance: Optional[Any] = None,
  1165. row: Optional[Union[Row[Any], RowMapping]] = None,
  1166. identity_token: Optional[Any] = None,
  1167. ) -> _IdentityKeyType[Any]:
  1168. r"""Return an identity key.
  1169. .. container:: class_bases
  1170. Proxied for the :class:`_orm.Session` class on
  1171. behalf of the :class:`_asyncio.AsyncSession` class.
  1172. This is an alias of :func:`.util.identity_key`.
  1173. """ # noqa: E501
  1174. return Session.identity_key(
  1175. class_=class_,
  1176. ident=ident,
  1177. instance=instance,
  1178. row=row,
  1179. identity_token=identity_token,
  1180. )
  1181. # END PROXY METHODS AsyncSession
  1182. _AS = TypeVar("_AS", bound="AsyncSession")
  1183. class async_sessionmaker(Generic[_AS]):
  1184. """A configurable :class:`.AsyncSession` factory.
  1185. The :class:`.async_sessionmaker` factory works in the same way as the
  1186. :class:`.sessionmaker` factory, to generate new :class:`.AsyncSession`
  1187. objects when called, creating them given
  1188. the configurational arguments established here.
  1189. e.g.::
  1190. from sqlalchemy.ext.asyncio import create_async_engine
  1191. from sqlalchemy.ext.asyncio import AsyncSession
  1192. from sqlalchemy.ext.asyncio import async_sessionmaker
  1193. async def run_some_sql(
  1194. async_session: async_sessionmaker[AsyncSession],
  1195. ) -> None:
  1196. async with async_session() as session:
  1197. session.add(SomeObject(data="object"))
  1198. session.add(SomeOtherObject(name="other object"))
  1199. await session.commit()
  1200. async def main() -> None:
  1201. # an AsyncEngine, which the AsyncSession will use for connection
  1202. # resources
  1203. engine = create_async_engine(
  1204. "postgresql+asyncpg://scott:tiger@localhost/"
  1205. )
  1206. # create a reusable factory for new AsyncSession instances
  1207. async_session = async_sessionmaker(engine)
  1208. await run_some_sql(async_session)
  1209. await engine.dispose()
  1210. The :class:`.async_sessionmaker` is useful so that different parts
  1211. of a program can create new :class:`.AsyncSession` objects with a
  1212. fixed configuration established up front. Note that :class:`.AsyncSession`
  1213. objects may also be instantiated directly when not using
  1214. :class:`.async_sessionmaker`.
  1215. .. versionadded:: 2.0 :class:`.async_sessionmaker` provides a
  1216. :class:`.sessionmaker` class that's dedicated to the
  1217. :class:`.AsyncSession` object, including pep-484 typing support.
  1218. .. seealso::
  1219. :ref:`asyncio_orm` - shows example use
  1220. :class:`.sessionmaker` - general overview of the
  1221. :class:`.sessionmaker` architecture
  1222. :ref:`session_getting` - introductory text on creating
  1223. sessions using :class:`.sessionmaker`.
  1224. """ # noqa E501
  1225. class_: Type[_AS]
  1226. @overload
  1227. def __init__(
  1228. self,
  1229. bind: Optional[_AsyncSessionBind] = ...,
  1230. *,
  1231. class_: Type[_AS],
  1232. autoflush: bool = ...,
  1233. expire_on_commit: bool = ...,
  1234. info: Optional[_InfoType] = ...,
  1235. **kw: Any,
  1236. ): ...
  1237. @overload
  1238. def __init__(
  1239. self: "async_sessionmaker[AsyncSession]",
  1240. bind: Optional[_AsyncSessionBind] = ...,
  1241. *,
  1242. autoflush: bool = ...,
  1243. expire_on_commit: bool = ...,
  1244. info: Optional[_InfoType] = ...,
  1245. **kw: Any,
  1246. ): ...
  1247. def __init__(
  1248. self,
  1249. bind: Optional[_AsyncSessionBind] = None,
  1250. *,
  1251. class_: Type[_AS] = AsyncSession, # type: ignore
  1252. autoflush: bool = True,
  1253. expire_on_commit: bool = True,
  1254. info: Optional[_InfoType] = None,
  1255. **kw: Any,
  1256. ):
  1257. r"""Construct a new :class:`.async_sessionmaker`.
  1258. All arguments here except for ``class_`` correspond to arguments
  1259. accepted by :class:`.Session` directly. See the
  1260. :meth:`.AsyncSession.__init__` docstring for more details on
  1261. parameters.
  1262. """
  1263. kw["bind"] = bind
  1264. kw["autoflush"] = autoflush
  1265. kw["expire_on_commit"] = expire_on_commit
  1266. if info is not None:
  1267. kw["info"] = info
  1268. self.kw = kw
  1269. self.class_ = class_
  1270. def begin(self) -> _AsyncSessionContextManager[_AS]:
  1271. """Produce a context manager that both provides a new
  1272. :class:`_orm.AsyncSession` as well as a transaction that commits.
  1273. e.g.::
  1274. async def main():
  1275. Session = async_sessionmaker(some_engine)
  1276. async with Session.begin() as session:
  1277. session.add(some_object)
  1278. # commits transaction, closes session
  1279. """
  1280. session = self()
  1281. return session._maker_context_manager()
  1282. def __call__(self, **local_kw: Any) -> _AS:
  1283. """Produce a new :class:`.AsyncSession` object using the configuration
  1284. established in this :class:`.async_sessionmaker`.
  1285. In Python, the ``__call__`` method is invoked on an object when
  1286. it is "called" in the same way as a function::
  1287. AsyncSession = async_sessionmaker(async_engine, expire_on_commit=False)
  1288. session = AsyncSession() # invokes sessionmaker.__call__()
  1289. """ # noqa E501
  1290. for k, v in self.kw.items():
  1291. if k == "info" and "info" in local_kw:
  1292. d = v.copy()
  1293. d.update(local_kw["info"])
  1294. local_kw["info"] = d
  1295. else:
  1296. local_kw.setdefault(k, v)
  1297. return self.class_(**local_kw)
  1298. def configure(self, **new_kw: Any) -> None:
  1299. """(Re)configure the arguments for this async_sessionmaker.
  1300. e.g.::
  1301. AsyncSession = async_sessionmaker(some_engine)
  1302. AsyncSession.configure(bind=create_async_engine("sqlite+aiosqlite://"))
  1303. """ # noqa E501
  1304. self.kw.update(new_kw)
  1305. def __repr__(self) -> str:
  1306. return "%s(class_=%r, %s)" % (
  1307. self.__class__.__name__,
  1308. self.class_.__name__,
  1309. ", ".join("%s=%r" % (k, v) for k, v in self.kw.items()),
  1310. )
  1311. class _AsyncSessionContextManager(Generic[_AS]):
  1312. __slots__ = ("async_session", "trans")
  1313. async_session: _AS
  1314. trans: AsyncSessionTransaction
  1315. def __init__(self, async_session: _AS):
  1316. self.async_session = async_session
  1317. async def __aenter__(self) -> _AS:
  1318. self.trans = self.async_session.begin()
  1319. await self.trans.__aenter__()
  1320. return self.async_session
  1321. async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:
  1322. async def go() -> None:
  1323. await self.trans.__aexit__(type_, value, traceback)
  1324. await self.async_session.__aexit__(type_, value, traceback)
  1325. task = asyncio.create_task(go())
  1326. await asyncio.shield(task)
  1327. class AsyncSessionTransaction(
  1328. ReversibleProxy[SessionTransaction],
  1329. StartableContext["AsyncSessionTransaction"],
  1330. ):
  1331. """A wrapper for the ORM :class:`_orm.SessionTransaction` object.
  1332. This object is provided so that a transaction-holding object
  1333. for the :meth:`_asyncio.AsyncSession.begin` may be returned.
  1334. The object supports both explicit calls to
  1335. :meth:`_asyncio.AsyncSessionTransaction.commit` and
  1336. :meth:`_asyncio.AsyncSessionTransaction.rollback`, as well as use as an
  1337. async context manager.
  1338. .. versionadded:: 1.4
  1339. """
  1340. __slots__ = ("session", "sync_transaction", "nested")
  1341. session: AsyncSession
  1342. sync_transaction: Optional[SessionTransaction]
  1343. def __init__(self, session: AsyncSession, nested: bool = False):
  1344. self.session = session
  1345. self.nested = nested
  1346. self.sync_transaction = None
  1347. @property
  1348. def is_active(self) -> bool:
  1349. return (
  1350. self._sync_transaction() is not None
  1351. and self._sync_transaction().is_active
  1352. )
  1353. def _sync_transaction(self) -> SessionTransaction:
  1354. if not self.sync_transaction:
  1355. self._raise_for_not_started()
  1356. return self.sync_transaction
  1357. async def rollback(self) -> None:
  1358. """Roll back this :class:`_asyncio.AsyncTransaction`."""
  1359. await greenlet_spawn(self._sync_transaction().rollback)
  1360. async def commit(self) -> None:
  1361. """Commit this :class:`_asyncio.AsyncTransaction`."""
  1362. await greenlet_spawn(self._sync_transaction().commit)
  1363. @classmethod
  1364. def _regenerate_proxy_for_target( # type: ignore[override]
  1365. cls,
  1366. target: SessionTransaction,
  1367. async_session: AsyncSession,
  1368. **additional_kw: Any, # noqa: U100
  1369. ) -> AsyncSessionTransaction:
  1370. sync_transaction = target
  1371. nested = target.nested
  1372. obj = cls.__new__(cls)
  1373. obj.session = async_session
  1374. obj.sync_transaction = obj._assign_proxied(sync_transaction)
  1375. obj.nested = nested
  1376. return obj
  1377. async def start(
  1378. self, is_ctxmanager: bool = False
  1379. ) -> AsyncSessionTransaction:
  1380. self.sync_transaction = self._assign_proxied(
  1381. await greenlet_spawn(
  1382. self.session.sync_session.begin_nested
  1383. if self.nested
  1384. else self.session.sync_session.begin
  1385. )
  1386. )
  1387. if is_ctxmanager:
  1388. self.sync_transaction.__enter__()
  1389. return self
  1390. async def __aexit__(self, type_: Any, value: Any, traceback: Any) -> None:
  1391. await greenlet_spawn(
  1392. self._sync_transaction().__exit__, type_, value, traceback
  1393. )
  1394. def async_object_session(instance: object) -> Optional[AsyncSession]:
  1395. """Return the :class:`_asyncio.AsyncSession` to which the given instance
  1396. belongs.
  1397. This function makes use of the sync-API function
  1398. :class:`_orm.object_session` to retrieve the :class:`_orm.Session` which
  1399. refers to the given instance, and from there links it to the original
  1400. :class:`_asyncio.AsyncSession`.
  1401. If the :class:`_asyncio.AsyncSession` has been garbage collected, the
  1402. return value is ``None``.
  1403. This functionality is also available from the
  1404. :attr:`_orm.InstanceState.async_session` accessor.
  1405. :param instance: an ORM mapped instance
  1406. :return: an :class:`_asyncio.AsyncSession` object, or ``None``.
  1407. .. versionadded:: 1.4.18
  1408. """
  1409. session = object_session(instance)
  1410. if session is not None:
  1411. return async_session(session)
  1412. else:
  1413. return None
  1414. def async_session(session: Session) -> Optional[AsyncSession]:
  1415. """Return the :class:`_asyncio.AsyncSession` which is proxying the given
  1416. :class:`_orm.Session` object, if any.
  1417. :param session: a :class:`_orm.Session` instance.
  1418. :return: a :class:`_asyncio.AsyncSession` instance, or ``None``.
  1419. .. versionadded:: 1.4.18
  1420. """
  1421. return AsyncSession._retrieve_proxy_for_target(session, regenerate=False)
  1422. async def close_all_sessions() -> None:
  1423. """Close all :class:`_asyncio.AsyncSession` sessions.
  1424. .. versionadded:: 2.0.23
  1425. .. seealso::
  1426. :func:`.session.close_all_sessions`
  1427. """
  1428. await greenlet_spawn(_sync_close_all_sessions)
  1429. _instance_state._async_provider = async_session # type: ignore