session.py 62 KB

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