scoping.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  1. # ext/asyncio/scoping.py
  2. # Copyright (C) 2005-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. from typing import Any
  9. from typing import Callable
  10. from typing import Generic
  11. from typing import Iterable
  12. from typing import Iterator
  13. from typing import Optional
  14. from typing import overload
  15. from typing import Sequence
  16. from typing import Tuple
  17. from typing import Type
  18. from typing import TYPE_CHECKING
  19. from typing import TypeVar
  20. from typing import Union
  21. from .session import _AS
  22. from .session import async_sessionmaker
  23. from .session import AsyncSession
  24. from ... import exc as sa_exc
  25. from ... import util
  26. from ...orm.session import Session
  27. from ...util import create_proxy_methods
  28. from ...util import ScopedRegistry
  29. from ...util import warn
  30. from ...util import warn_deprecated
  31. if TYPE_CHECKING:
  32. from .engine import AsyncConnection
  33. from .result import AsyncResult
  34. from .result import AsyncScalarResult
  35. from .session import AsyncSessionTransaction
  36. from ...engine import Connection
  37. from ...engine import Engine
  38. from ...engine import Result
  39. from ...engine import Row
  40. from ...engine import RowMapping
  41. from ...engine.interfaces import _CoreAnyExecuteParams
  42. from ...engine.interfaces import CoreExecuteOptionsParameter
  43. from ...engine.result import ScalarResult
  44. from ...orm._typing import _IdentityKeyType
  45. from ...orm._typing import _O
  46. from ...orm._typing import OrmExecuteOptionsParameter
  47. from ...orm.interfaces import ORMOption
  48. from ...orm.session import _BindArguments
  49. from ...orm.session import _EntityBindKey
  50. from ...orm.session import _PKIdentityArgument
  51. from ...orm.session import _SessionBind
  52. from ...sql.base import Executable
  53. from ...sql.elements import ClauseElement
  54. from ...sql.selectable import ForUpdateParameter
  55. from ...sql.selectable import TypedReturnsRows
  56. _T = TypeVar("_T", bound=Any)
  57. @create_proxy_methods(
  58. AsyncSession,
  59. ":class:`_asyncio.AsyncSession`",
  60. ":class:`_asyncio.scoping.async_scoped_session`",
  61. classmethods=["close_all", "object_session", "identity_key"],
  62. methods=[
  63. "__contains__",
  64. "__iter__",
  65. "aclose",
  66. "add",
  67. "add_all",
  68. "begin",
  69. "begin_nested",
  70. "close",
  71. "reset",
  72. "commit",
  73. "connection",
  74. "delete",
  75. "execute",
  76. "expire",
  77. "expire_all",
  78. "expunge",
  79. "expunge_all",
  80. "flush",
  81. "get_bind",
  82. "is_modified",
  83. "invalidate",
  84. "merge",
  85. "refresh",
  86. "rollback",
  87. "scalar",
  88. "scalars",
  89. "get",
  90. "get_one",
  91. "stream",
  92. "stream_scalars",
  93. ],
  94. attributes=[
  95. "bind",
  96. "dirty",
  97. "deleted",
  98. "new",
  99. "identity_map",
  100. "is_active",
  101. "autoflush",
  102. "no_autoflush",
  103. "info",
  104. ],
  105. use_intermediate_variable=["get"],
  106. )
  107. class async_scoped_session(Generic[_AS]):
  108. """Provides scoped management of :class:`.AsyncSession` objects.
  109. See the section :ref:`asyncio_scoped_session` for usage details.
  110. .. versionadded:: 1.4.19
  111. """
  112. _support_async = True
  113. session_factory: async_sessionmaker[_AS]
  114. """The `session_factory` provided to `__init__` is stored in this
  115. attribute and may be accessed at a later time. This can be useful when
  116. a new non-scoped :class:`.AsyncSession` is needed."""
  117. registry: ScopedRegistry[_AS]
  118. def __init__(
  119. self,
  120. session_factory: async_sessionmaker[_AS],
  121. scopefunc: Callable[[], Any],
  122. ):
  123. """Construct a new :class:`_asyncio.async_scoped_session`.
  124. :param session_factory: a factory to create new :class:`_asyncio.AsyncSession`
  125. instances. This is usually, but not necessarily, an instance
  126. of :class:`_asyncio.async_sessionmaker`.
  127. :param scopefunc: function which defines
  128. the current scope. A function such as ``asyncio.current_task``
  129. may be useful here.
  130. """ # noqa: E501
  131. self.session_factory = session_factory
  132. self.registry = ScopedRegistry(session_factory, scopefunc)
  133. @property
  134. def _proxied(self) -> _AS:
  135. return self.registry()
  136. def __call__(self, **kw: Any) -> _AS:
  137. r"""Return the current :class:`.AsyncSession`, creating it
  138. using the :attr:`.scoped_session.session_factory` if not present.
  139. :param \**kw: Keyword arguments will be passed to the
  140. :attr:`.scoped_session.session_factory` callable, if an existing
  141. :class:`.AsyncSession` is not present. If the
  142. :class:`.AsyncSession` is present
  143. and keyword arguments have been passed,
  144. :exc:`~sqlalchemy.exc.InvalidRequestError` is raised.
  145. """
  146. if kw:
  147. if self.registry.has():
  148. raise sa_exc.InvalidRequestError(
  149. "Scoped session is already present; "
  150. "no new arguments may be specified."
  151. )
  152. else:
  153. sess = self.session_factory(**kw)
  154. self.registry.set(sess)
  155. else:
  156. sess = self.registry()
  157. if not self._support_async and sess._is_asyncio:
  158. warn_deprecated(
  159. "Using `scoped_session` with asyncio is deprecated and "
  160. "will raise an error in a future version. "
  161. "Please use `async_scoped_session` instead.",
  162. "1.4.23",
  163. )
  164. return sess
  165. def configure(self, **kwargs: Any) -> None:
  166. """reconfigure the :class:`.sessionmaker` used by this
  167. :class:`.scoped_session`.
  168. See :meth:`.sessionmaker.configure`.
  169. """
  170. if self.registry.has():
  171. warn(
  172. "At least one scoped session is already present. "
  173. " configure() can not affect sessions that have "
  174. "already been created."
  175. )
  176. self.session_factory.configure(**kwargs)
  177. async def remove(self) -> None:
  178. """Dispose of the current :class:`.AsyncSession`, if present.
  179. Different from scoped_session's remove method, this method would use
  180. await to wait for the close method of AsyncSession.
  181. """
  182. if self.registry.has():
  183. await self.registry().close()
  184. self.registry.clear()
  185. # START PROXY METHODS async_scoped_session
  186. # code within this block is **programmatically,
  187. # statically generated** by tools/generate_proxy_methods.py
  188. def __contains__(self, instance: object) -> bool:
  189. r"""Return True if the instance is associated with this session.
  190. .. container:: class_bases
  191. Proxied for the :class:`_asyncio.AsyncSession` class on
  192. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  193. .. container:: class_bases
  194. Proxied for the :class:`_orm.Session` class on
  195. behalf of the :class:`_asyncio.AsyncSession` class.
  196. The instance may be pending or persistent within the Session for a
  197. result of True.
  198. """ # noqa: E501
  199. return self._proxied.__contains__(instance)
  200. def __iter__(self) -> Iterator[object]:
  201. r"""Iterate over all pending or persistent instances within this
  202. Session.
  203. .. container:: class_bases
  204. Proxied for the :class:`_asyncio.AsyncSession` class on
  205. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  206. .. container:: class_bases
  207. Proxied for the :class:`_orm.Session` class on
  208. behalf of the :class:`_asyncio.AsyncSession` class.
  209. """ # noqa: E501
  210. return self._proxied.__iter__()
  211. async def aclose(self) -> None:
  212. r"""A synonym for :meth:`_asyncio.AsyncSession.close`.
  213. .. container:: class_bases
  214. Proxied for the :class:`_asyncio.AsyncSession` class on
  215. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  216. The :meth:`_asyncio.AsyncSession.aclose` name is specifically
  217. to support the Python standard library ``@contextlib.aclosing``
  218. context manager function.
  219. .. versionadded:: 2.0.20
  220. """ # noqa: E501
  221. return await self._proxied.aclose()
  222. def add(self, instance: object, _warn: bool = True) -> None:
  223. r"""Place an object into this :class:`_orm.Session`.
  224. .. container:: class_bases
  225. Proxied for the :class:`_asyncio.AsyncSession` class on
  226. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  227. .. container:: class_bases
  228. Proxied for the :class:`_orm.Session` class on
  229. behalf of the :class:`_asyncio.AsyncSession` class.
  230. Objects that are in the :term:`transient` state when passed to the
  231. :meth:`_orm.Session.add` method will move to the
  232. :term:`pending` state, until the next flush, at which point they
  233. will move to the :term:`persistent` state.
  234. Objects that are in the :term:`detached` state when passed to the
  235. :meth:`_orm.Session.add` method will move to the :term:`persistent`
  236. state directly.
  237. If the transaction used by the :class:`_orm.Session` is rolled back,
  238. objects which were transient when they were passed to
  239. :meth:`_orm.Session.add` will be moved back to the
  240. :term:`transient` state, and will no longer be present within this
  241. :class:`_orm.Session`.
  242. .. seealso::
  243. :meth:`_orm.Session.add_all`
  244. :ref:`session_adding` - at :ref:`session_basics`
  245. """ # noqa: E501
  246. return self._proxied.add(instance, _warn=_warn)
  247. def add_all(self, instances: Iterable[object]) -> None:
  248. r"""Add the given collection of instances to this :class:`_orm.Session`.
  249. .. container:: class_bases
  250. Proxied for the :class:`_asyncio.AsyncSession` class on
  251. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  252. .. container:: class_bases
  253. Proxied for the :class:`_orm.Session` class on
  254. behalf of the :class:`_asyncio.AsyncSession` class.
  255. See the documentation for :meth:`_orm.Session.add` for a general
  256. behavioral description.
  257. .. seealso::
  258. :meth:`_orm.Session.add`
  259. :ref:`session_adding` - at :ref:`session_basics`
  260. """ # noqa: E501
  261. return self._proxied.add_all(instances)
  262. def begin(self) -> AsyncSessionTransaction:
  263. r"""Return an :class:`_asyncio.AsyncSessionTransaction` object.
  264. .. container:: class_bases
  265. Proxied for the :class:`_asyncio.AsyncSession` class on
  266. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  267. The underlying :class:`_orm.Session` will perform the
  268. "begin" action when the :class:`_asyncio.AsyncSessionTransaction`
  269. object is entered::
  270. async with async_session.begin():
  271. ... # ORM transaction is begun
  272. Note that database IO will not normally occur when the session-level
  273. transaction is begun, as database transactions begin on an
  274. on-demand basis. However, the begin block is async to accommodate
  275. for a :meth:`_orm.SessionEvents.after_transaction_create`
  276. event hook that may perform IO.
  277. For a general description of ORM begin, see
  278. :meth:`_orm.Session.begin`.
  279. """ # noqa: E501
  280. return self._proxied.begin()
  281. def begin_nested(self) -> AsyncSessionTransaction:
  282. r"""Return an :class:`_asyncio.AsyncSessionTransaction` object
  283. which will begin a "nested" transaction, e.g. SAVEPOINT.
  284. .. container:: class_bases
  285. Proxied for the :class:`_asyncio.AsyncSession` class on
  286. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  287. Behavior is the same as that of :meth:`_asyncio.AsyncSession.begin`.
  288. For a general description of ORM begin nested, see
  289. :meth:`_orm.Session.begin_nested`.
  290. .. seealso::
  291. :ref:`aiosqlite_serializable` - special workarounds required
  292. with the SQLite asyncio driver in order for SAVEPOINT to work
  293. correctly.
  294. """ # noqa: E501
  295. return self._proxied.begin_nested()
  296. async def close(self) -> None:
  297. r"""Close out the transactional resources and ORM objects used by this
  298. :class:`_asyncio.AsyncSession`.
  299. .. container:: class_bases
  300. Proxied for the :class:`_asyncio.AsyncSession` class on
  301. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  302. .. seealso::
  303. :meth:`_orm.Session.close` - main documentation for
  304. "close"
  305. :ref:`session_closing` - detail on the semantics of
  306. :meth:`_asyncio.AsyncSession.close` and
  307. :meth:`_asyncio.AsyncSession.reset`.
  308. """ # noqa: E501
  309. return await self._proxied.close()
  310. async def reset(self) -> None:
  311. r"""Close out the transactional resources and ORM objects used by this
  312. :class:`_orm.Session`, resetting the session to its initial state.
  313. .. container:: class_bases
  314. Proxied for the :class:`_asyncio.AsyncSession` class on
  315. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  316. .. versionadded:: 2.0.22
  317. .. seealso::
  318. :meth:`_orm.Session.reset` - main documentation for
  319. "reset"
  320. :ref:`session_closing` - detail on the semantics of
  321. :meth:`_asyncio.AsyncSession.close` and
  322. :meth:`_asyncio.AsyncSession.reset`.
  323. """ # noqa: E501
  324. return await self._proxied.reset()
  325. async def commit(self) -> None:
  326. r"""Commit the current transaction in progress.
  327. .. container:: class_bases
  328. Proxied for the :class:`_asyncio.AsyncSession` class on
  329. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  330. .. seealso::
  331. :meth:`_orm.Session.commit` - main documentation for
  332. "commit"
  333. """ # noqa: E501
  334. return await self._proxied.commit()
  335. async def connection(
  336. self,
  337. bind_arguments: Optional[_BindArguments] = None,
  338. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  339. **kw: Any,
  340. ) -> AsyncConnection:
  341. r"""Return a :class:`_asyncio.AsyncConnection` object corresponding to
  342. this :class:`.Session` object's transactional state.
  343. .. container:: class_bases
  344. Proxied for the :class:`_asyncio.AsyncSession` class on
  345. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  346. This method may also be used to establish execution options for the
  347. database connection used by the current transaction.
  348. .. versionadded:: 1.4.24 Added \**kw arguments which are passed
  349. through to the underlying :meth:`_orm.Session.connection` method.
  350. .. seealso::
  351. :meth:`_orm.Session.connection` - main documentation for
  352. "connection"
  353. """ # noqa: E501
  354. return await self._proxied.connection(
  355. bind_arguments=bind_arguments,
  356. execution_options=execution_options,
  357. **kw,
  358. )
  359. async def delete(self, instance: object) -> None:
  360. r"""Mark an instance as deleted.
  361. .. container:: class_bases
  362. Proxied for the :class:`_asyncio.AsyncSession` class on
  363. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  364. The database delete operation occurs upon ``flush()``.
  365. As this operation may need to cascade along unloaded relationships,
  366. it is awaitable to allow for those queries to take place.
  367. .. seealso::
  368. :meth:`_orm.Session.delete` - main documentation for delete
  369. """ # noqa: E501
  370. return await self._proxied.delete(instance)
  371. @overload
  372. async def execute(
  373. self,
  374. statement: TypedReturnsRows[_T],
  375. params: Optional[_CoreAnyExecuteParams] = None,
  376. *,
  377. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  378. bind_arguments: Optional[_BindArguments] = None,
  379. _parent_execute_state: Optional[Any] = None,
  380. _add_event: Optional[Any] = None,
  381. ) -> Result[_T]: ...
  382. @overload
  383. async def execute(
  384. self,
  385. statement: Executable,
  386. params: Optional[_CoreAnyExecuteParams] = None,
  387. *,
  388. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  389. bind_arguments: Optional[_BindArguments] = None,
  390. _parent_execute_state: Optional[Any] = None,
  391. _add_event: Optional[Any] = None,
  392. ) -> Result[Any]: ...
  393. async def execute(
  394. self,
  395. statement: Executable,
  396. params: Optional[_CoreAnyExecuteParams] = None,
  397. *,
  398. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  399. bind_arguments: Optional[_BindArguments] = None,
  400. **kw: Any,
  401. ) -> Result[Any]:
  402. r"""Execute a statement and return a buffered
  403. :class:`_engine.Result` object.
  404. .. container:: class_bases
  405. Proxied for the :class:`_asyncio.AsyncSession` class on
  406. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  407. .. seealso::
  408. :meth:`_orm.Session.execute` - main documentation for execute
  409. """ # noqa: E501
  410. return await self._proxied.execute(
  411. statement,
  412. params=params,
  413. execution_options=execution_options,
  414. bind_arguments=bind_arguments,
  415. **kw,
  416. )
  417. def expire(
  418. self, instance: object, attribute_names: Optional[Iterable[str]] = None
  419. ) -> None:
  420. r"""Expire the attributes on an instance.
  421. .. container:: class_bases
  422. Proxied for the :class:`_asyncio.AsyncSession` class on
  423. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  424. .. container:: class_bases
  425. Proxied for the :class:`_orm.Session` class on
  426. behalf of the :class:`_asyncio.AsyncSession` class.
  427. Marks the attributes of an instance as out of date. When an expired
  428. attribute is next accessed, a query will be issued to the
  429. :class:`.Session` object's current transactional context in order to
  430. load all expired attributes for the given instance. Note that
  431. a highly isolated transaction will return the same values as were
  432. previously read in that same transaction, regardless of changes
  433. in database state outside of that transaction.
  434. To expire all objects in the :class:`.Session` simultaneously,
  435. use :meth:`Session.expire_all`.
  436. The :class:`.Session` object's default behavior is to
  437. expire all state whenever the :meth:`Session.rollback`
  438. or :meth:`Session.commit` methods are called, so that new
  439. state can be loaded for the new transaction. For this reason,
  440. calling :meth:`Session.expire` only makes sense for the specific
  441. case that a non-ORM SQL statement was emitted in the current
  442. transaction.
  443. :param instance: The instance to be refreshed.
  444. :param attribute_names: optional list of string attribute names
  445. indicating a subset of attributes to be expired.
  446. .. seealso::
  447. :ref:`session_expire` - introductory material
  448. :meth:`.Session.expire`
  449. :meth:`.Session.refresh`
  450. :meth:`_orm.Query.populate_existing`
  451. """ # noqa: E501
  452. return self._proxied.expire(instance, attribute_names=attribute_names)
  453. def expire_all(self) -> None:
  454. r"""Expires all persistent instances within this Session.
  455. .. container:: class_bases
  456. Proxied for the :class:`_asyncio.AsyncSession` class on
  457. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  458. .. container:: class_bases
  459. Proxied for the :class:`_orm.Session` class on
  460. behalf of the :class:`_asyncio.AsyncSession` class.
  461. When any attributes on a persistent instance is next accessed,
  462. a query will be issued using the
  463. :class:`.Session` object's current transactional context in order to
  464. load all expired attributes for the given instance. Note that
  465. a highly isolated transaction will return the same values as were
  466. previously read in that same transaction, regardless of changes
  467. in database state outside of that transaction.
  468. To expire individual objects and individual attributes
  469. on those objects, use :meth:`Session.expire`.
  470. The :class:`.Session` object's default behavior is to
  471. expire all state whenever the :meth:`Session.rollback`
  472. or :meth:`Session.commit` methods are called, so that new
  473. state can be loaded for the new transaction. For this reason,
  474. calling :meth:`Session.expire_all` is not usually needed,
  475. assuming the transaction is isolated.
  476. .. seealso::
  477. :ref:`session_expire` - introductory material
  478. :meth:`.Session.expire`
  479. :meth:`.Session.refresh`
  480. :meth:`_orm.Query.populate_existing`
  481. """ # noqa: E501
  482. return self._proxied.expire_all()
  483. def expunge(self, instance: object) -> None:
  484. r"""Remove the `instance` from this ``Session``.
  485. .. container:: class_bases
  486. Proxied for the :class:`_asyncio.AsyncSession` class on
  487. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  488. .. container:: class_bases
  489. Proxied for the :class:`_orm.Session` class on
  490. behalf of the :class:`_asyncio.AsyncSession` class.
  491. This will free all internal references to the instance. Cascading
  492. will be applied according to the *expunge* cascade rule.
  493. """ # noqa: E501
  494. return self._proxied.expunge(instance)
  495. def expunge_all(self) -> None:
  496. r"""Remove all object instances from this ``Session``.
  497. .. container:: class_bases
  498. Proxied for the :class:`_asyncio.AsyncSession` class on
  499. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  500. .. container:: class_bases
  501. Proxied for the :class:`_orm.Session` class on
  502. behalf of the :class:`_asyncio.AsyncSession` class.
  503. This is equivalent to calling ``expunge(obj)`` on all objects in this
  504. ``Session``.
  505. """ # noqa: E501
  506. return self._proxied.expunge_all()
  507. async def flush(self, objects: Optional[Sequence[Any]] = None) -> None:
  508. r"""Flush all the object changes to the database.
  509. .. container:: class_bases
  510. Proxied for the :class:`_asyncio.AsyncSession` class on
  511. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  512. .. seealso::
  513. :meth:`_orm.Session.flush` - main documentation for flush
  514. """ # noqa: E501
  515. return await self._proxied.flush(objects=objects)
  516. def get_bind(
  517. self,
  518. mapper: Optional[_EntityBindKey[_O]] = None,
  519. clause: Optional[ClauseElement] = None,
  520. bind: Optional[_SessionBind] = None,
  521. **kw: Any,
  522. ) -> Union[Engine, Connection]:
  523. r"""Return a "bind" to which the synchronous proxied :class:`_orm.Session`
  524. is bound.
  525. .. container:: class_bases
  526. Proxied for the :class:`_asyncio.AsyncSession` class on
  527. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  528. Unlike the :meth:`_orm.Session.get_bind` method, this method is
  529. currently **not** used by this :class:`.AsyncSession` in any way
  530. in order to resolve engines for requests.
  531. .. note::
  532. This method proxies directly to the :meth:`_orm.Session.get_bind`
  533. method, however is currently **not** useful as an override target,
  534. in contrast to that of the :meth:`_orm.Session.get_bind` method.
  535. The example below illustrates how to implement custom
  536. :meth:`_orm.Session.get_bind` schemes that work with
  537. :class:`.AsyncSession` and :class:`.AsyncEngine`.
  538. The pattern introduced at :ref:`session_custom_partitioning`
  539. illustrates how to apply a custom bind-lookup scheme to a
  540. :class:`_orm.Session` given a set of :class:`_engine.Engine` objects.
  541. To apply a corresponding :meth:`_orm.Session.get_bind` implementation
  542. for use with a :class:`.AsyncSession` and :class:`.AsyncEngine`
  543. objects, continue to subclass :class:`_orm.Session` and apply it to
  544. :class:`.AsyncSession` using
  545. :paramref:`.AsyncSession.sync_session_class`. The inner method must
  546. continue to return :class:`_engine.Engine` instances, which can be
  547. acquired from a :class:`_asyncio.AsyncEngine` using the
  548. :attr:`_asyncio.AsyncEngine.sync_engine` attribute::
  549. # using example from "Custom Vertical Partitioning"
  550. import random
  551. from sqlalchemy.ext.asyncio import AsyncSession
  552. from sqlalchemy.ext.asyncio import create_async_engine
  553. from sqlalchemy.ext.asyncio import async_sessionmaker
  554. from sqlalchemy.orm import Session
  555. # construct async engines w/ async drivers
  556. engines = {
  557. "leader": create_async_engine("sqlite+aiosqlite:///leader.db"),
  558. "other": create_async_engine("sqlite+aiosqlite:///other.db"),
  559. "follower1": create_async_engine("sqlite+aiosqlite:///follower1.db"),
  560. "follower2": create_async_engine("sqlite+aiosqlite:///follower2.db"),
  561. }
  562. class RoutingSession(Session):
  563. def get_bind(self, mapper=None, clause=None, **kw):
  564. # within get_bind(), return sync engines
  565. if mapper and issubclass(mapper.class_, MyOtherClass):
  566. return engines["other"].sync_engine
  567. elif self._flushing or isinstance(clause, (Update, Delete)):
  568. return engines["leader"].sync_engine
  569. else:
  570. return engines[
  571. random.choice(["follower1", "follower2"])
  572. ].sync_engine
  573. # apply to AsyncSession using sync_session_class
  574. AsyncSessionMaker = async_sessionmaker(sync_session_class=RoutingSession)
  575. The :meth:`_orm.Session.get_bind` method is called in a non-asyncio,
  576. implicitly non-blocking context in the same manner as ORM event hooks
  577. and functions that are invoked via :meth:`.AsyncSession.run_sync`, so
  578. routines that wish to run SQL commands inside of
  579. :meth:`_orm.Session.get_bind` can continue to do so using
  580. blocking-style code, which will be translated to implicitly async calls
  581. at the point of invoking IO on the database drivers.
  582. """ # noqa: E501
  583. return self._proxied.get_bind(
  584. mapper=mapper, clause=clause, bind=bind, **kw
  585. )
  586. def is_modified(
  587. self, instance: object, include_collections: bool = True
  588. ) -> bool:
  589. r"""Return ``True`` if the given instance has locally
  590. modified attributes.
  591. .. container:: class_bases
  592. Proxied for the :class:`_asyncio.AsyncSession` class on
  593. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  594. .. container:: class_bases
  595. Proxied for the :class:`_orm.Session` class on
  596. behalf of the :class:`_asyncio.AsyncSession` class.
  597. This method retrieves the history for each instrumented
  598. attribute on the instance and performs a comparison of the current
  599. value to its previously flushed or committed value, if any.
  600. It is in effect a more expensive and accurate
  601. version of checking for the given instance in the
  602. :attr:`.Session.dirty` collection; a full test for
  603. each attribute's net "dirty" status is performed.
  604. E.g.::
  605. return session.is_modified(someobject)
  606. A few caveats to this method apply:
  607. * Instances present in the :attr:`.Session.dirty` collection may
  608. report ``False`` when tested with this method. This is because
  609. the object may have received change events via attribute mutation,
  610. thus placing it in :attr:`.Session.dirty`, but ultimately the state
  611. is the same as that loaded from the database, resulting in no net
  612. change here.
  613. * Scalar attributes may not have recorded the previously set
  614. value when a new value was applied, if the attribute was not loaded,
  615. or was expired, at the time the new value was received - in these
  616. cases, the attribute is assumed to have a change, even if there is
  617. ultimately no net change against its database value. SQLAlchemy in
  618. most cases does not need the "old" value when a set event occurs, so
  619. it skips the expense of a SQL call if the old value isn't present,
  620. based on the assumption that an UPDATE of the scalar value is
  621. usually needed, and in those few cases where it isn't, is less
  622. expensive on average than issuing a defensive SELECT.
  623. The "old" value is fetched unconditionally upon set only if the
  624. attribute container has the ``active_history`` flag set to ``True``.
  625. This flag is set typically for primary key attributes and scalar
  626. object references that are not a simple many-to-one. To set this
  627. flag for any arbitrary mapped column, use the ``active_history``
  628. argument with :func:`.column_property`.
  629. :param instance: mapped instance to be tested for pending changes.
  630. :param include_collections: Indicates if multivalued collections
  631. should be included in the operation. Setting this to ``False`` is a
  632. way to detect only local-column based properties (i.e. scalar columns
  633. or many-to-one foreign keys) that would result in an UPDATE for this
  634. instance upon flush.
  635. """ # noqa: E501
  636. return self._proxied.is_modified(
  637. instance, include_collections=include_collections
  638. )
  639. async def invalidate(self) -> None:
  640. r"""Close this Session, using connection invalidation.
  641. .. container:: class_bases
  642. Proxied for the :class:`_asyncio.AsyncSession` class on
  643. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  644. For a complete description, see :meth:`_orm.Session.invalidate`.
  645. """ # noqa: E501
  646. return await self._proxied.invalidate()
  647. async def merge(
  648. self,
  649. instance: _O,
  650. *,
  651. load: bool = True,
  652. options: Optional[Sequence[ORMOption]] = None,
  653. ) -> _O:
  654. r"""Copy the state of a given instance into a corresponding instance
  655. within this :class:`_asyncio.AsyncSession`.
  656. .. container:: class_bases
  657. Proxied for the :class:`_asyncio.AsyncSession` class on
  658. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  659. .. seealso::
  660. :meth:`_orm.Session.merge` - main documentation for merge
  661. """ # noqa: E501
  662. return await self._proxied.merge(instance, load=load, options=options)
  663. async def refresh(
  664. self,
  665. instance: object,
  666. attribute_names: Optional[Iterable[str]] = None,
  667. with_for_update: ForUpdateParameter = None,
  668. ) -> None:
  669. r"""Expire and refresh the attributes on the given instance.
  670. .. container:: class_bases
  671. Proxied for the :class:`_asyncio.AsyncSession` class on
  672. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  673. A query will be issued to the database and all attributes will be
  674. refreshed with their current database value.
  675. This is the async version of the :meth:`_orm.Session.refresh` method.
  676. See that method for a complete description of all options.
  677. .. seealso::
  678. :meth:`_orm.Session.refresh` - main documentation for refresh
  679. """ # noqa: E501
  680. return await self._proxied.refresh(
  681. instance,
  682. attribute_names=attribute_names,
  683. with_for_update=with_for_update,
  684. )
  685. async def rollback(self) -> None:
  686. r"""Rollback the current transaction in progress.
  687. .. container:: class_bases
  688. Proxied for the :class:`_asyncio.AsyncSession` class on
  689. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  690. .. seealso::
  691. :meth:`_orm.Session.rollback` - main documentation for
  692. "rollback"
  693. """ # noqa: E501
  694. return await self._proxied.rollback()
  695. @overload
  696. async def scalar(
  697. self,
  698. statement: TypedReturnsRows[Tuple[_T]],
  699. params: Optional[_CoreAnyExecuteParams] = None,
  700. *,
  701. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  702. bind_arguments: Optional[_BindArguments] = None,
  703. **kw: Any,
  704. ) -> Optional[_T]: ...
  705. @overload
  706. async def scalar(
  707. self,
  708. statement: Executable,
  709. params: Optional[_CoreAnyExecuteParams] = None,
  710. *,
  711. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  712. bind_arguments: Optional[_BindArguments] = None,
  713. **kw: Any,
  714. ) -> Any: ...
  715. async def scalar(
  716. self,
  717. statement: Executable,
  718. params: Optional[_CoreAnyExecuteParams] = None,
  719. *,
  720. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  721. bind_arguments: Optional[_BindArguments] = None,
  722. **kw: Any,
  723. ) -> Any:
  724. r"""Execute a statement and return a scalar result.
  725. .. container:: class_bases
  726. Proxied for the :class:`_asyncio.AsyncSession` class on
  727. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  728. .. seealso::
  729. :meth:`_orm.Session.scalar` - main documentation for scalar
  730. """ # noqa: E501
  731. return await self._proxied.scalar(
  732. statement,
  733. params=params,
  734. execution_options=execution_options,
  735. bind_arguments=bind_arguments,
  736. **kw,
  737. )
  738. @overload
  739. async def scalars(
  740. self,
  741. statement: TypedReturnsRows[Tuple[_T]],
  742. params: Optional[_CoreAnyExecuteParams] = None,
  743. *,
  744. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  745. bind_arguments: Optional[_BindArguments] = None,
  746. **kw: Any,
  747. ) -> ScalarResult[_T]: ...
  748. @overload
  749. async def scalars(
  750. self,
  751. statement: Executable,
  752. params: Optional[_CoreAnyExecuteParams] = None,
  753. *,
  754. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  755. bind_arguments: Optional[_BindArguments] = None,
  756. **kw: Any,
  757. ) -> ScalarResult[Any]: ...
  758. async def scalars(
  759. self,
  760. statement: Executable,
  761. params: Optional[_CoreAnyExecuteParams] = None,
  762. *,
  763. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  764. bind_arguments: Optional[_BindArguments] = None,
  765. **kw: Any,
  766. ) -> ScalarResult[Any]:
  767. r"""Execute a statement and return scalar results.
  768. .. container:: class_bases
  769. Proxied for the :class:`_asyncio.AsyncSession` class on
  770. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  771. :return: a :class:`_result.ScalarResult` object
  772. .. versionadded:: 1.4.24 Added :meth:`_asyncio.AsyncSession.scalars`
  773. .. versionadded:: 1.4.26 Added
  774. :meth:`_asyncio.async_scoped_session.scalars`
  775. .. seealso::
  776. :meth:`_orm.Session.scalars` - main documentation for scalars
  777. :meth:`_asyncio.AsyncSession.stream_scalars` - streaming version
  778. """ # noqa: E501
  779. return await self._proxied.scalars(
  780. statement,
  781. params=params,
  782. execution_options=execution_options,
  783. bind_arguments=bind_arguments,
  784. **kw,
  785. )
  786. async def get(
  787. self,
  788. entity: _EntityBindKey[_O],
  789. ident: _PKIdentityArgument,
  790. *,
  791. options: Optional[Sequence[ORMOption]] = None,
  792. populate_existing: bool = False,
  793. with_for_update: ForUpdateParameter = None,
  794. identity_token: Optional[Any] = None,
  795. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  796. ) -> Union[_O, None]:
  797. r"""Return an instance based on the given primary key identifier,
  798. or ``None`` if not found.
  799. .. container:: class_bases
  800. Proxied for the :class:`_asyncio.AsyncSession` class on
  801. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  802. .. seealso::
  803. :meth:`_orm.Session.get` - main documentation for get
  804. """ # noqa: E501
  805. result = await self._proxied.get(
  806. entity,
  807. ident,
  808. options=options,
  809. populate_existing=populate_existing,
  810. with_for_update=with_for_update,
  811. identity_token=identity_token,
  812. execution_options=execution_options,
  813. )
  814. return result
  815. async def get_one(
  816. self,
  817. entity: _EntityBindKey[_O],
  818. ident: _PKIdentityArgument,
  819. *,
  820. options: Optional[Sequence[ORMOption]] = None,
  821. populate_existing: bool = False,
  822. with_for_update: ForUpdateParameter = None,
  823. identity_token: Optional[Any] = None,
  824. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  825. ) -> _O:
  826. r"""Return an instance based on the given primary key identifier,
  827. or raise an exception if not found.
  828. .. container:: class_bases
  829. Proxied for the :class:`_asyncio.AsyncSession` class on
  830. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  831. Raises :class:`_exc.NoResultFound` if the query selects no rows.
  832. ..versionadded: 2.0.22
  833. .. seealso::
  834. :meth:`_orm.Session.get_one` - main documentation for get_one
  835. """ # noqa: E501
  836. return await self._proxied.get_one(
  837. entity,
  838. ident,
  839. options=options,
  840. populate_existing=populate_existing,
  841. with_for_update=with_for_update,
  842. identity_token=identity_token,
  843. execution_options=execution_options,
  844. )
  845. @overload
  846. async def stream(
  847. self,
  848. statement: TypedReturnsRows[_T],
  849. params: Optional[_CoreAnyExecuteParams] = None,
  850. *,
  851. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  852. bind_arguments: Optional[_BindArguments] = None,
  853. **kw: Any,
  854. ) -> AsyncResult[_T]: ...
  855. @overload
  856. async def stream(
  857. self,
  858. statement: Executable,
  859. params: Optional[_CoreAnyExecuteParams] = None,
  860. *,
  861. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  862. bind_arguments: Optional[_BindArguments] = None,
  863. **kw: Any,
  864. ) -> AsyncResult[Any]: ...
  865. async def stream(
  866. self,
  867. statement: Executable,
  868. params: Optional[_CoreAnyExecuteParams] = None,
  869. *,
  870. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  871. bind_arguments: Optional[_BindArguments] = None,
  872. **kw: Any,
  873. ) -> AsyncResult[Any]:
  874. r"""Execute a statement and return a streaming
  875. :class:`_asyncio.AsyncResult` object.
  876. .. container:: class_bases
  877. Proxied for the :class:`_asyncio.AsyncSession` class on
  878. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  879. """ # noqa: E501
  880. return await self._proxied.stream(
  881. statement,
  882. params=params,
  883. execution_options=execution_options,
  884. bind_arguments=bind_arguments,
  885. **kw,
  886. )
  887. @overload
  888. async def stream_scalars(
  889. self,
  890. statement: TypedReturnsRows[Tuple[_T]],
  891. params: Optional[_CoreAnyExecuteParams] = None,
  892. *,
  893. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  894. bind_arguments: Optional[_BindArguments] = None,
  895. **kw: Any,
  896. ) -> AsyncScalarResult[_T]: ...
  897. @overload
  898. async def stream_scalars(
  899. self,
  900. statement: Executable,
  901. params: Optional[_CoreAnyExecuteParams] = None,
  902. *,
  903. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  904. bind_arguments: Optional[_BindArguments] = None,
  905. **kw: Any,
  906. ) -> AsyncScalarResult[Any]: ...
  907. async def stream_scalars(
  908. self,
  909. statement: Executable,
  910. params: Optional[_CoreAnyExecuteParams] = None,
  911. *,
  912. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  913. bind_arguments: Optional[_BindArguments] = None,
  914. **kw: Any,
  915. ) -> AsyncScalarResult[Any]:
  916. r"""Execute a statement and return a stream of scalar results.
  917. .. container:: class_bases
  918. Proxied for the :class:`_asyncio.AsyncSession` class on
  919. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  920. :return: an :class:`_asyncio.AsyncScalarResult` object
  921. .. versionadded:: 1.4.24
  922. .. seealso::
  923. :meth:`_orm.Session.scalars` - main documentation for scalars
  924. :meth:`_asyncio.AsyncSession.scalars` - non streaming version
  925. """ # noqa: E501
  926. return await self._proxied.stream_scalars(
  927. statement,
  928. params=params,
  929. execution_options=execution_options,
  930. bind_arguments=bind_arguments,
  931. **kw,
  932. )
  933. @property
  934. def bind(self) -> Any:
  935. r"""Proxy for the :attr:`_asyncio.AsyncSession.bind` attribute
  936. on behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  937. """ # noqa: E501
  938. return self._proxied.bind
  939. @bind.setter
  940. def bind(self, attr: Any) -> None:
  941. self._proxied.bind = attr
  942. @property
  943. def dirty(self) -> Any:
  944. r"""The set of all persistent instances considered dirty.
  945. .. container:: class_bases
  946. Proxied for the :class:`_asyncio.AsyncSession` class
  947. on behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  948. .. container:: class_bases
  949. Proxied for the :class:`_orm.Session` class
  950. on behalf of the :class:`_asyncio.AsyncSession` class.
  951. E.g.::
  952. some_mapped_object in session.dirty
  953. Instances are considered dirty when they were modified but not
  954. deleted.
  955. Note that this 'dirty' calculation is 'optimistic'; most
  956. attribute-setting or collection modification operations will
  957. mark an instance as 'dirty' and place it in this set, even if
  958. there is no net change to the attribute's value. At flush
  959. time, the value of each attribute is compared to its
  960. previously saved value, and if there's no net change, no SQL
  961. operation will occur (this is a more expensive operation so
  962. it's only done at flush time).
  963. To check if an instance has actionable net changes to its
  964. attributes, use the :meth:`.Session.is_modified` method.
  965. """ # noqa: E501
  966. return self._proxied.dirty
  967. @property
  968. def deleted(self) -> Any:
  969. r"""The set of all instances marked as 'deleted' within this ``Session``
  970. .. container:: class_bases
  971. Proxied for the :class:`_asyncio.AsyncSession` class
  972. on behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  973. .. container:: class_bases
  974. Proxied for the :class:`_orm.Session` class
  975. on behalf of the :class:`_asyncio.AsyncSession` class.
  976. """ # noqa: E501
  977. return self._proxied.deleted
  978. @property
  979. def new(self) -> Any:
  980. r"""The set of all instances marked as 'new' within this ``Session``.
  981. .. container:: class_bases
  982. Proxied for the :class:`_asyncio.AsyncSession` class
  983. on behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  984. .. container:: class_bases
  985. Proxied for the :class:`_orm.Session` class
  986. on behalf of the :class:`_asyncio.AsyncSession` class.
  987. """ # noqa: E501
  988. return self._proxied.new
  989. @property
  990. def identity_map(self) -> Any:
  991. r"""Proxy for the :attr:`_orm.Session.identity_map` attribute
  992. on behalf of the :class:`_asyncio.AsyncSession` class.
  993. .. container:: class_bases
  994. Proxied for the :class:`_asyncio.AsyncSession` class
  995. on behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  996. """ # noqa: E501
  997. return self._proxied.identity_map
  998. @identity_map.setter
  999. def identity_map(self, attr: Any) -> None:
  1000. self._proxied.identity_map = attr
  1001. @property
  1002. def is_active(self) -> Any:
  1003. r"""True if this :class:`.Session` not in "partial rollback" state.
  1004. .. container:: class_bases
  1005. Proxied for the :class:`_asyncio.AsyncSession` class
  1006. on behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  1007. .. container:: class_bases
  1008. Proxied for the :class:`_orm.Session` class
  1009. on behalf of the :class:`_asyncio.AsyncSession` class.
  1010. .. versionchanged:: 1.4 The :class:`_orm.Session` no longer begins
  1011. a new transaction immediately, so this attribute will be False
  1012. when the :class:`_orm.Session` is first instantiated.
  1013. "partial rollback" state typically indicates that the flush process
  1014. of the :class:`_orm.Session` has failed, and that the
  1015. :meth:`_orm.Session.rollback` method must be emitted in order to
  1016. fully roll back the transaction.
  1017. If this :class:`_orm.Session` is not in a transaction at all, the
  1018. :class:`_orm.Session` will autobegin when it is first used, so in this
  1019. case :attr:`_orm.Session.is_active` will return True.
  1020. Otherwise, if this :class:`_orm.Session` is within a transaction,
  1021. and that transaction has not been rolled back internally, the
  1022. :attr:`_orm.Session.is_active` will also return True.
  1023. .. seealso::
  1024. :ref:`faq_session_rollback`
  1025. :meth:`_orm.Session.in_transaction`
  1026. """ # noqa: E501
  1027. return self._proxied.is_active
  1028. @property
  1029. def autoflush(self) -> Any:
  1030. r"""Proxy for the :attr:`_orm.Session.autoflush` attribute
  1031. on behalf of the :class:`_asyncio.AsyncSession` class.
  1032. .. container:: class_bases
  1033. Proxied for the :class:`_asyncio.AsyncSession` class
  1034. on behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  1035. """ # noqa: E501
  1036. return self._proxied.autoflush
  1037. @autoflush.setter
  1038. def autoflush(self, attr: Any) -> None:
  1039. self._proxied.autoflush = attr
  1040. @property
  1041. def no_autoflush(self) -> Any:
  1042. r"""Return a context manager that disables autoflush.
  1043. .. container:: class_bases
  1044. Proxied for the :class:`_asyncio.AsyncSession` class
  1045. on behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  1046. .. container:: class_bases
  1047. Proxied for the :class:`_orm.Session` class
  1048. on behalf of the :class:`_asyncio.AsyncSession` class.
  1049. e.g.::
  1050. with session.no_autoflush:
  1051. some_object = SomeClass()
  1052. session.add(some_object)
  1053. # won't autoflush
  1054. some_object.related_thing = session.query(SomeRelated).first()
  1055. Operations that proceed within the ``with:`` block
  1056. will not be subject to flushes occurring upon query
  1057. access. This is useful when initializing a series
  1058. of objects which involve existing database queries,
  1059. where the uncompleted object should not yet be flushed.
  1060. """ # noqa: E501
  1061. return self._proxied.no_autoflush
  1062. @property
  1063. def info(self) -> Any:
  1064. r"""A user-modifiable dictionary.
  1065. .. container:: class_bases
  1066. Proxied for the :class:`_asyncio.AsyncSession` class
  1067. on behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  1068. .. container:: class_bases
  1069. Proxied for the :class:`_orm.Session` class
  1070. on behalf of the :class:`_asyncio.AsyncSession` class.
  1071. The initial value of this dictionary can be populated using the
  1072. ``info`` argument to the :class:`.Session` constructor or
  1073. :class:`.sessionmaker` constructor or factory methods. The dictionary
  1074. here is always local to this :class:`.Session` and can be modified
  1075. independently of all other :class:`.Session` objects.
  1076. """ # noqa: E501
  1077. return self._proxied.info
  1078. @classmethod
  1079. async def close_all(cls) -> None:
  1080. r"""Close all :class:`_asyncio.AsyncSession` sessions.
  1081. .. container:: class_bases
  1082. Proxied for the :class:`_asyncio.AsyncSession` class on
  1083. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  1084. .. deprecated:: 2.0 The :meth:`.AsyncSession.close_all` method is deprecated and will be removed in a future release. Please refer to :func:`_asyncio.close_all_sessions`.
  1085. """ # noqa: E501
  1086. return await AsyncSession.close_all()
  1087. @classmethod
  1088. def object_session(cls, instance: object) -> Optional[Session]:
  1089. r"""Return the :class:`.Session` to which an object belongs.
  1090. .. container:: class_bases
  1091. Proxied for the :class:`_asyncio.AsyncSession` class on
  1092. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  1093. .. container:: class_bases
  1094. Proxied for the :class:`_orm.Session` class on
  1095. behalf of the :class:`_asyncio.AsyncSession` class.
  1096. This is an alias of :func:`.object_session`.
  1097. """ # noqa: E501
  1098. return AsyncSession.object_session(instance)
  1099. @classmethod
  1100. def identity_key(
  1101. cls,
  1102. class_: Optional[Type[Any]] = None,
  1103. ident: Union[Any, Tuple[Any, ...]] = None,
  1104. *,
  1105. instance: Optional[Any] = None,
  1106. row: Optional[Union[Row[Any], RowMapping]] = None,
  1107. identity_token: Optional[Any] = None,
  1108. ) -> _IdentityKeyType[Any]:
  1109. r"""Return an identity key.
  1110. .. container:: class_bases
  1111. Proxied for the :class:`_asyncio.AsyncSession` class on
  1112. behalf of the :class:`_asyncio.scoping.async_scoped_session` class.
  1113. .. container:: class_bases
  1114. Proxied for the :class:`_orm.Session` class on
  1115. behalf of the :class:`_asyncio.AsyncSession` class.
  1116. This is an alias of :func:`.util.identity_key`.
  1117. """ # noqa: E501
  1118. return AsyncSession.identity_key(
  1119. class_=class_,
  1120. ident=ident,
  1121. instance=instance,
  1122. row=row,
  1123. identity_token=identity_token,
  1124. )
  1125. # END PROXY METHODS async_scoped_session