scoping.py 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  1. # orm/scoping.py
  2. # Copyright (C) 2005-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. from typing import Any
  9. from typing import Callable
  10. from typing import Dict
  11. from typing import Generic
  12. from typing import Iterable
  13. from typing import Iterator
  14. from typing import Optional
  15. from typing import overload
  16. from typing import Sequence
  17. from typing import Tuple
  18. from typing import Type
  19. from typing import TYPE_CHECKING
  20. from typing import TypeVar
  21. from typing import Union
  22. from .session import _S
  23. from .session import Session
  24. from .. import exc as sa_exc
  25. from .. import util
  26. from ..util import create_proxy_methods
  27. from ..util import ScopedRegistry
  28. from ..util import ThreadLocalRegistry
  29. from ..util import warn
  30. from ..util import warn_deprecated
  31. from ..util.typing import Protocol
  32. if TYPE_CHECKING:
  33. from ._typing import _EntityType
  34. from ._typing import _IdentityKeyType
  35. from ._typing import OrmExecuteOptionsParameter
  36. from .identity import IdentityMap
  37. from .interfaces import ORMOption
  38. from .mapper import Mapper
  39. from .query import Query
  40. from .query import RowReturningQuery
  41. from .session import _BindArguments
  42. from .session import _EntityBindKey
  43. from .session import _PKIdentityArgument
  44. from .session import _SessionBind
  45. from .session import sessionmaker
  46. from .session import SessionTransaction
  47. from ..engine import Connection
  48. from ..engine import CursorResult
  49. from ..engine import Engine
  50. from ..engine import Result
  51. from ..engine import Row
  52. from ..engine import RowMapping
  53. from ..engine.interfaces import _CoreAnyExecuteParams
  54. from ..engine.interfaces import _CoreSingleExecuteParams
  55. from ..engine.interfaces import CoreExecuteOptionsParameter
  56. from ..engine.result import ScalarResult
  57. from ..sql._typing import _ColumnsClauseArgument
  58. from ..sql._typing import _T0
  59. from ..sql._typing import _T1
  60. from ..sql._typing import _T2
  61. from ..sql._typing import _T3
  62. from ..sql._typing import _T4
  63. from ..sql._typing import _T5
  64. from ..sql._typing import _T6
  65. from ..sql._typing import _T7
  66. from ..sql._typing import _TypedColumnClauseArgument as _TCCA
  67. from ..sql.base import Executable
  68. from ..sql.dml import UpdateBase
  69. from ..sql.elements import ClauseElement
  70. from ..sql.roles import TypedColumnsClauseRole
  71. from ..sql.selectable import ForUpdateParameter
  72. from ..sql.selectable import TypedReturnsRows
  73. _T = TypeVar("_T", bound=Any)
  74. class QueryPropertyDescriptor(Protocol):
  75. """Describes the type applied to a class-level
  76. :meth:`_orm.scoped_session.query_property` attribute.
  77. .. versionadded:: 2.0.5
  78. """
  79. def __get__(self, instance: Any, owner: Type[_T]) -> Query[_T]:
  80. ...
  81. _O = TypeVar("_O", bound=object)
  82. __all__ = ["scoped_session"]
  83. @create_proxy_methods(
  84. Session,
  85. ":class:`_orm.Session`",
  86. ":class:`_orm.scoping.scoped_session`",
  87. classmethods=["close_all", "object_session", "identity_key"],
  88. methods=[
  89. "__contains__",
  90. "__iter__",
  91. "add",
  92. "add_all",
  93. "begin",
  94. "begin_nested",
  95. "close",
  96. "reset",
  97. "commit",
  98. "connection",
  99. "delete",
  100. "execute",
  101. "expire",
  102. "expire_all",
  103. "expunge",
  104. "expunge_all",
  105. "flush",
  106. "get",
  107. "get_one",
  108. "get_bind",
  109. "is_modified",
  110. "bulk_save_objects",
  111. "bulk_insert_mappings",
  112. "bulk_update_mappings",
  113. "merge",
  114. "query",
  115. "refresh",
  116. "rollback",
  117. "scalar",
  118. "scalars",
  119. ],
  120. attributes=[
  121. "bind",
  122. "dirty",
  123. "deleted",
  124. "new",
  125. "identity_map",
  126. "is_active",
  127. "autoflush",
  128. "no_autoflush",
  129. "info",
  130. ],
  131. )
  132. class scoped_session(Generic[_S]):
  133. """Provides scoped management of :class:`.Session` objects.
  134. See :ref:`unitofwork_contextual` for a tutorial.
  135. .. note::
  136. When using :ref:`asyncio_toplevel`, the async-compatible
  137. :class:`_asyncio.async_scoped_session` class should be
  138. used in place of :class:`.scoped_session`.
  139. """
  140. _support_async: bool = False
  141. session_factory: sessionmaker[_S]
  142. """The `session_factory` provided to `__init__` is stored in this
  143. attribute and may be accessed at a later time. This can be useful when
  144. a new non-scoped :class:`.Session` is needed."""
  145. registry: ScopedRegistry[_S]
  146. def __init__(
  147. self,
  148. session_factory: sessionmaker[_S],
  149. scopefunc: Optional[Callable[[], Any]] = None,
  150. ):
  151. """Construct a new :class:`.scoped_session`.
  152. :param session_factory: a factory to create new :class:`.Session`
  153. instances. This is usually, but not necessarily, an instance
  154. of :class:`.sessionmaker`.
  155. :param scopefunc: optional function which defines
  156. the current scope. If not passed, the :class:`.scoped_session`
  157. object assumes "thread-local" scope, and will use
  158. a Python ``threading.local()`` in order to maintain the current
  159. :class:`.Session`. If passed, the function should return
  160. a hashable token; this token will be used as the key in a
  161. dictionary in order to store and retrieve the current
  162. :class:`.Session`.
  163. """
  164. self.session_factory = session_factory
  165. if scopefunc:
  166. self.registry = ScopedRegistry(session_factory, scopefunc)
  167. else:
  168. self.registry = ThreadLocalRegistry(session_factory)
  169. @property
  170. def _proxied(self) -> _S:
  171. return self.registry()
  172. def __call__(self, **kw: Any) -> _S:
  173. r"""Return the current :class:`.Session`, creating it
  174. using the :attr:`.scoped_session.session_factory` if not present.
  175. :param \**kw: Keyword arguments will be passed to the
  176. :attr:`.scoped_session.session_factory` callable, if an existing
  177. :class:`.Session` is not present. If the :class:`.Session` is present
  178. and keyword arguments have been passed,
  179. :exc:`~sqlalchemy.exc.InvalidRequestError` is raised.
  180. """
  181. if kw:
  182. if self.registry.has():
  183. raise sa_exc.InvalidRequestError(
  184. "Scoped session is already present; "
  185. "no new arguments may be specified."
  186. )
  187. else:
  188. sess = self.session_factory(**kw)
  189. self.registry.set(sess)
  190. else:
  191. sess = self.registry()
  192. if not self._support_async and sess._is_asyncio:
  193. warn_deprecated(
  194. "Using `scoped_session` with asyncio is deprecated and "
  195. "will raise an error in a future version. "
  196. "Please use `async_scoped_session` instead.",
  197. "1.4.23",
  198. )
  199. return sess
  200. def configure(self, **kwargs: Any) -> None:
  201. """reconfigure the :class:`.sessionmaker` used by this
  202. :class:`.scoped_session`.
  203. See :meth:`.sessionmaker.configure`.
  204. """
  205. if self.registry.has():
  206. warn(
  207. "At least one scoped session is already present. "
  208. " configure() can not affect sessions that have "
  209. "already been created."
  210. )
  211. self.session_factory.configure(**kwargs)
  212. def remove(self) -> None:
  213. """Dispose of the current :class:`.Session`, if present.
  214. This will first call :meth:`.Session.close` method
  215. on the current :class:`.Session`, which releases any existing
  216. transactional/connection resources still being held; transactions
  217. specifically are rolled back. The :class:`.Session` is then
  218. discarded. Upon next usage within the same scope,
  219. the :class:`.scoped_session` will produce a new
  220. :class:`.Session` object.
  221. """
  222. if self.registry.has():
  223. self.registry().close()
  224. self.registry.clear()
  225. def query_property(
  226. self, query_cls: Optional[Type[Query[_T]]] = None
  227. ) -> QueryPropertyDescriptor:
  228. """return a class property which produces a legacy
  229. :class:`_query.Query` object against the class and the current
  230. :class:`.Session` when called.
  231. .. legacy:: The :meth:`_orm.scoped_session.query_property` accessor
  232. is specific to the legacy :class:`.Query` object and is not
  233. considered to be part of :term:`2.0-style` ORM use.
  234. e.g.::
  235. from sqlalchemy.orm import QueryPropertyDescriptor
  236. from sqlalchemy.orm import scoped_session
  237. from sqlalchemy.orm import sessionmaker
  238. Session = scoped_session(sessionmaker())
  239. class MyClass:
  240. query: QueryPropertyDescriptor = Session.query_property()
  241. # after mappers are defined
  242. result = MyClass.query.filter(MyClass.name=='foo').all()
  243. Produces instances of the session's configured query class by
  244. default. To override and use a custom implementation, provide
  245. a ``query_cls`` callable. The callable will be invoked with
  246. the class's mapper as a positional argument and a session
  247. keyword argument.
  248. There is no limit to the number of query properties placed on
  249. a class.
  250. """
  251. class query:
  252. def __get__(s, instance: Any, owner: Type[_O]) -> Query[_O]:
  253. if query_cls:
  254. # custom query class
  255. return query_cls(owner, session=self.registry()) # type: ignore # noqa: E501
  256. else:
  257. # session's configured query class
  258. return self.registry().query(owner)
  259. return query()
  260. # START PROXY METHODS scoped_session
  261. # code within this block is **programmatically,
  262. # statically generated** by tools/generate_proxy_methods.py
  263. def __contains__(self, instance: object) -> bool:
  264. r"""Return True if the instance is associated with this session.
  265. .. container:: class_bases
  266. Proxied for the :class:`_orm.Session` class on
  267. behalf of the :class:`_orm.scoping.scoped_session` class.
  268. The instance may be pending or persistent within the Session for a
  269. result of True.
  270. """ # noqa: E501
  271. return self._proxied.__contains__(instance)
  272. def __iter__(self) -> Iterator[object]:
  273. r"""Iterate over all pending or persistent instances within this
  274. Session.
  275. .. container:: class_bases
  276. Proxied for the :class:`_orm.Session` class on
  277. behalf of the :class:`_orm.scoping.scoped_session` class.
  278. """ # noqa: E501
  279. return self._proxied.__iter__()
  280. def add(self, instance: object, _warn: bool = True) -> None:
  281. r"""Place an object into this :class:`_orm.Session`.
  282. .. container:: class_bases
  283. Proxied for the :class:`_orm.Session` class on
  284. behalf of the :class:`_orm.scoping.scoped_session` class.
  285. Objects that are in the :term:`transient` state when passed to the
  286. :meth:`_orm.Session.add` method will move to the
  287. :term:`pending` state, until the next flush, at which point they
  288. will move to the :term:`persistent` state.
  289. Objects that are in the :term:`detached` state when passed to the
  290. :meth:`_orm.Session.add` method will move to the :term:`persistent`
  291. state directly.
  292. If the transaction used by the :class:`_orm.Session` is rolled back,
  293. objects which were transient when they were passed to
  294. :meth:`_orm.Session.add` will be moved back to the
  295. :term:`transient` state, and will no longer be present within this
  296. :class:`_orm.Session`.
  297. .. seealso::
  298. :meth:`_orm.Session.add_all`
  299. :ref:`session_adding` - at :ref:`session_basics`
  300. """ # noqa: E501
  301. return self._proxied.add(instance, _warn=_warn)
  302. def add_all(self, instances: Iterable[object]) -> None:
  303. r"""Add the given collection of instances to this :class:`_orm.Session`.
  304. .. container:: class_bases
  305. Proxied for the :class:`_orm.Session` class on
  306. behalf of the :class:`_orm.scoping.scoped_session` class.
  307. See the documentation for :meth:`_orm.Session.add` for a general
  308. behavioral description.
  309. .. seealso::
  310. :meth:`_orm.Session.add`
  311. :ref:`session_adding` - at :ref:`session_basics`
  312. """ # noqa: E501
  313. return self._proxied.add_all(instances)
  314. def begin(self, nested: bool = False) -> SessionTransaction:
  315. r"""Begin a transaction, or nested transaction,
  316. on this :class:`.Session`, if one is not already begun.
  317. .. container:: class_bases
  318. Proxied for the :class:`_orm.Session` class on
  319. behalf of the :class:`_orm.scoping.scoped_session` class.
  320. The :class:`_orm.Session` object features **autobegin** behavior,
  321. so that normally it is not necessary to call the
  322. :meth:`_orm.Session.begin`
  323. method explicitly. However, it may be used in order to control
  324. the scope of when the transactional state is begun.
  325. When used to begin the outermost transaction, an error is raised
  326. if this :class:`.Session` is already inside of a transaction.
  327. :param nested: if True, begins a SAVEPOINT transaction and is
  328. equivalent to calling :meth:`~.Session.begin_nested`. For
  329. documentation on SAVEPOINT transactions, please see
  330. :ref:`session_begin_nested`.
  331. :return: the :class:`.SessionTransaction` object. Note that
  332. :class:`.SessionTransaction`
  333. acts as a Python context manager, allowing :meth:`.Session.begin`
  334. to be used in a "with" block. See :ref:`session_explicit_begin` for
  335. an example.
  336. .. seealso::
  337. :ref:`session_autobegin`
  338. :ref:`unitofwork_transaction`
  339. :meth:`.Session.begin_nested`
  340. """ # noqa: E501
  341. return self._proxied.begin(nested=nested)
  342. def begin_nested(self) -> SessionTransaction:
  343. r"""Begin a "nested" transaction on this Session, e.g. SAVEPOINT.
  344. .. container:: class_bases
  345. Proxied for the :class:`_orm.Session` class on
  346. behalf of the :class:`_orm.scoping.scoped_session` class.
  347. The target database(s) and associated drivers must support SQL
  348. SAVEPOINT for this method to function correctly.
  349. For documentation on SAVEPOINT
  350. transactions, please see :ref:`session_begin_nested`.
  351. :return: the :class:`.SessionTransaction` object. Note that
  352. :class:`.SessionTransaction` acts as a context manager, allowing
  353. :meth:`.Session.begin_nested` to be used in a "with" block.
  354. See :ref:`session_begin_nested` for a usage example.
  355. .. seealso::
  356. :ref:`session_begin_nested`
  357. :ref:`pysqlite_serializable` - special workarounds required
  358. with the SQLite driver in order for SAVEPOINT to work
  359. correctly. For asyncio use cases, see the section
  360. :ref:`aiosqlite_serializable`.
  361. """ # noqa: E501
  362. return self._proxied.begin_nested()
  363. def close(self) -> None:
  364. r"""Close out the transactional resources and ORM objects used by this
  365. :class:`_orm.Session`.
  366. .. container:: class_bases
  367. Proxied for the :class:`_orm.Session` class on
  368. behalf of the :class:`_orm.scoping.scoped_session` class.
  369. This expunges all ORM objects associated with this
  370. :class:`_orm.Session`, ends any transaction in progress and
  371. :term:`releases` any :class:`_engine.Connection` objects which this
  372. :class:`_orm.Session` itself has checked out from associated
  373. :class:`_engine.Engine` objects. The operation then leaves the
  374. :class:`_orm.Session` in a state which it may be used again.
  375. .. tip::
  376. In the default running mode the :meth:`_orm.Session.close`
  377. method **does not prevent the Session from being used again**.
  378. The :class:`_orm.Session` itself does not actually have a
  379. distinct "closed" state; it merely means
  380. the :class:`_orm.Session` will release all database connections
  381. and ORM objects.
  382. Setting the parameter :paramref:`_orm.Session.close_resets_only`
  383. to ``False`` will instead make the ``close`` final, meaning that
  384. any further action on the session will be forbidden.
  385. .. versionchanged:: 1.4 The :meth:`.Session.close` method does not
  386. immediately create a new :class:`.SessionTransaction` object;
  387. instead, the new :class:`.SessionTransaction` is created only if
  388. the :class:`.Session` is used again for a database operation.
  389. .. seealso::
  390. :ref:`session_closing` - detail on the semantics of
  391. :meth:`_orm.Session.close` and :meth:`_orm.Session.reset`.
  392. :meth:`_orm.Session.reset` - a similar method that behaves like
  393. ``close()`` with the parameter
  394. :paramref:`_orm.Session.close_resets_only` set to ``True``.
  395. """ # noqa: E501
  396. return self._proxied.close()
  397. def reset(self) -> None:
  398. r"""Close out the transactional resources and ORM objects used by this
  399. :class:`_orm.Session`, resetting the session to its initial state.
  400. .. container:: class_bases
  401. Proxied for the :class:`_orm.Session` class on
  402. behalf of the :class:`_orm.scoping.scoped_session` class.
  403. This method provides for same "reset-only" behavior that the
  404. :meth:`_orm.Session.close` method has provided historically, where the
  405. state of the :class:`_orm.Session` is reset as though the object were
  406. brand new, and ready to be used again.
  407. This method may then be useful for :class:`_orm.Session` objects
  408. which set :paramref:`_orm.Session.close_resets_only` to ``False``,
  409. so that "reset only" behavior is still available.
  410. .. versionadded:: 2.0.22
  411. .. seealso::
  412. :ref:`session_closing` - detail on the semantics of
  413. :meth:`_orm.Session.close` and :meth:`_orm.Session.reset`.
  414. :meth:`_orm.Session.close` - a similar method will additionally
  415. prevent re-use of the Session when the parameter
  416. :paramref:`_orm.Session.close_resets_only` is set to ``False``.
  417. """ # noqa: E501
  418. return self._proxied.reset()
  419. def commit(self) -> None:
  420. r"""Flush pending changes and commit the current transaction.
  421. .. container:: class_bases
  422. Proxied for the :class:`_orm.Session` class on
  423. behalf of the :class:`_orm.scoping.scoped_session` class.
  424. When the COMMIT operation is complete, all objects are fully
  425. :term:`expired`, erasing their internal contents, which will be
  426. automatically re-loaded when the objects are next accessed. In the
  427. interim, these objects are in an expired state and will not function if
  428. they are :term:`detached` from the :class:`.Session`. Additionally,
  429. this re-load operation is not supported when using asyncio-oriented
  430. APIs. The :paramref:`.Session.expire_on_commit` parameter may be used
  431. to disable this behavior.
  432. When there is no transaction in place for the :class:`.Session`,
  433. indicating that no operations were invoked on this :class:`.Session`
  434. since the previous call to :meth:`.Session.commit`, the method will
  435. begin and commit an internal-only "logical" transaction, that does not
  436. normally affect the database unless pending flush changes were
  437. detected, but will still invoke event handlers and object expiration
  438. rules.
  439. The outermost database transaction is committed unconditionally,
  440. automatically releasing any SAVEPOINTs in effect.
  441. .. seealso::
  442. :ref:`session_committing`
  443. :ref:`unitofwork_transaction`
  444. :ref:`asyncio_orm_avoid_lazyloads`
  445. """ # noqa: E501
  446. return self._proxied.commit()
  447. def connection(
  448. self,
  449. bind_arguments: Optional[_BindArguments] = None,
  450. execution_options: Optional[CoreExecuteOptionsParameter] = None,
  451. ) -> Connection:
  452. r"""Return a :class:`_engine.Connection` object corresponding to this
  453. :class:`.Session` object's transactional state.
  454. .. container:: class_bases
  455. Proxied for the :class:`_orm.Session` class on
  456. behalf of the :class:`_orm.scoping.scoped_session` class.
  457. Either the :class:`_engine.Connection` corresponding to the current
  458. transaction is returned, or if no transaction is in progress, a new
  459. one is begun and the :class:`_engine.Connection`
  460. returned (note that no
  461. transactional state is established with the DBAPI until the first
  462. SQL statement is emitted).
  463. Ambiguity in multi-bind or unbound :class:`.Session` objects can be
  464. resolved through any of the optional keyword arguments. This
  465. ultimately makes usage of the :meth:`.get_bind` method for resolution.
  466. :param bind_arguments: dictionary of bind arguments. May include
  467. "mapper", "bind", "clause", other custom arguments that are passed
  468. to :meth:`.Session.get_bind`.
  469. :param execution_options: a dictionary of execution options that will
  470. be passed to :meth:`_engine.Connection.execution_options`, **when the
  471. connection is first procured only**. If the connection is already
  472. present within the :class:`.Session`, a warning is emitted and
  473. the arguments are ignored.
  474. .. seealso::
  475. :ref:`session_transaction_isolation`
  476. """ # noqa: E501
  477. return self._proxied.connection(
  478. bind_arguments=bind_arguments, execution_options=execution_options
  479. )
  480. def delete(self, instance: object) -> None:
  481. r"""Mark an instance as deleted.
  482. .. container:: class_bases
  483. Proxied for the :class:`_orm.Session` class on
  484. behalf of the :class:`_orm.scoping.scoped_session` class.
  485. The object is assumed to be either :term:`persistent` or
  486. :term:`detached` when passed; after the method is called, the
  487. object will remain in the :term:`persistent` state until the next
  488. flush proceeds. During this time, the object will also be a member
  489. of the :attr:`_orm.Session.deleted` collection.
  490. When the next flush proceeds, the object will move to the
  491. :term:`deleted` state, indicating a ``DELETE`` statement was emitted
  492. for its row within the current transaction. When the transaction
  493. is successfully committed,
  494. the deleted object is moved to the :term:`detached` state and is
  495. no longer present within this :class:`_orm.Session`.
  496. .. seealso::
  497. :ref:`session_deleting` - at :ref:`session_basics`
  498. """ # noqa: E501
  499. return self._proxied.delete(instance)
  500. @overload
  501. def execute(
  502. self,
  503. statement: TypedReturnsRows[_T],
  504. params: Optional[_CoreAnyExecuteParams] = None,
  505. *,
  506. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  507. bind_arguments: Optional[_BindArguments] = None,
  508. _parent_execute_state: Optional[Any] = None,
  509. _add_event: Optional[Any] = None,
  510. ) -> Result[_T]:
  511. ...
  512. @overload
  513. def execute(
  514. self,
  515. statement: UpdateBase,
  516. params: Optional[_CoreAnyExecuteParams] = None,
  517. *,
  518. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  519. bind_arguments: Optional[_BindArguments] = None,
  520. _parent_execute_state: Optional[Any] = None,
  521. _add_event: Optional[Any] = None,
  522. ) -> CursorResult[Any]:
  523. ...
  524. @overload
  525. def execute(
  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. _parent_execute_state: Optional[Any] = None,
  533. _add_event: Optional[Any] = None,
  534. ) -> Result[Any]:
  535. ...
  536. def execute(
  537. self,
  538. statement: Executable,
  539. params: Optional[_CoreAnyExecuteParams] = None,
  540. *,
  541. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  542. bind_arguments: Optional[_BindArguments] = None,
  543. _parent_execute_state: Optional[Any] = None,
  544. _add_event: Optional[Any] = None,
  545. ) -> Result[Any]:
  546. r"""Execute a SQL expression construct.
  547. .. container:: class_bases
  548. Proxied for the :class:`_orm.Session` class on
  549. behalf of the :class:`_orm.scoping.scoped_session` class.
  550. Returns a :class:`_engine.Result` object representing
  551. results of the statement execution.
  552. E.g.::
  553. from sqlalchemy import select
  554. result = session.execute(
  555. select(User).where(User.id == 5)
  556. )
  557. The API contract of :meth:`_orm.Session.execute` is similar to that
  558. of :meth:`_engine.Connection.execute`, the :term:`2.0 style` version
  559. of :class:`_engine.Connection`.
  560. .. versionchanged:: 1.4 the :meth:`_orm.Session.execute` method is
  561. now the primary point of ORM statement execution when using
  562. :term:`2.0 style` ORM usage.
  563. :param statement:
  564. An executable statement (i.e. an :class:`.Executable` expression
  565. such as :func:`_expression.select`).
  566. :param params:
  567. Optional dictionary, or list of dictionaries, containing
  568. bound parameter values. If a single dictionary, single-row
  569. execution occurs; if a list of dictionaries, an
  570. "executemany" will be invoked. The keys in each dictionary
  571. must correspond to parameter names present in the statement.
  572. :param execution_options: optional dictionary of execution options,
  573. which will be associated with the statement execution. This
  574. dictionary can provide a subset of the options that are accepted
  575. by :meth:`_engine.Connection.execution_options`, and may also
  576. provide additional options understood only in an ORM context.
  577. .. seealso::
  578. :ref:`orm_queryguide_execution_options` - ORM-specific execution
  579. options
  580. :param bind_arguments: dictionary of additional arguments to determine
  581. the bind. May include "mapper", "bind", or other custom arguments.
  582. Contents of this dictionary are passed to the
  583. :meth:`.Session.get_bind` method.
  584. :return: a :class:`_engine.Result` object.
  585. """ # noqa: E501
  586. return self._proxied.execute(
  587. statement,
  588. params=params,
  589. execution_options=execution_options,
  590. bind_arguments=bind_arguments,
  591. _parent_execute_state=_parent_execute_state,
  592. _add_event=_add_event,
  593. )
  594. def expire(
  595. self, instance: object, attribute_names: Optional[Iterable[str]] = None
  596. ) -> None:
  597. r"""Expire the attributes on an instance.
  598. .. container:: class_bases
  599. Proxied for the :class:`_orm.Session` class on
  600. behalf of the :class:`_orm.scoping.scoped_session` class.
  601. Marks the attributes of an instance as out of date. When an expired
  602. attribute is next accessed, a query will be issued to the
  603. :class:`.Session` object's current transactional context in order to
  604. load all expired attributes for the given instance. Note that
  605. a highly isolated transaction will return the same values as were
  606. previously read in that same transaction, regardless of changes
  607. in database state outside of that transaction.
  608. To expire all objects in the :class:`.Session` simultaneously,
  609. use :meth:`Session.expire_all`.
  610. The :class:`.Session` object's default behavior is to
  611. expire all state whenever the :meth:`Session.rollback`
  612. or :meth:`Session.commit` methods are called, so that new
  613. state can be loaded for the new transaction. For this reason,
  614. calling :meth:`Session.expire` only makes sense for the specific
  615. case that a non-ORM SQL statement was emitted in the current
  616. transaction.
  617. :param instance: The instance to be refreshed.
  618. :param attribute_names: optional list of string attribute names
  619. indicating a subset of attributes to be expired.
  620. .. seealso::
  621. :ref:`session_expire` - introductory material
  622. :meth:`.Session.expire`
  623. :meth:`.Session.refresh`
  624. :meth:`_orm.Query.populate_existing`
  625. """ # noqa: E501
  626. return self._proxied.expire(instance, attribute_names=attribute_names)
  627. def expire_all(self) -> None:
  628. r"""Expires all persistent instances within this Session.
  629. .. container:: class_bases
  630. Proxied for the :class:`_orm.Session` class on
  631. behalf of the :class:`_orm.scoping.scoped_session` class.
  632. When any attributes on a persistent instance is next accessed,
  633. a query will be issued using the
  634. :class:`.Session` object's current transactional context in order to
  635. load all expired attributes for the given instance. Note that
  636. a highly isolated transaction will return the same values as were
  637. previously read in that same transaction, regardless of changes
  638. in database state outside of that transaction.
  639. To expire individual objects and individual attributes
  640. on those objects, use :meth:`Session.expire`.
  641. The :class:`.Session` object's default behavior is to
  642. expire all state whenever the :meth:`Session.rollback`
  643. or :meth:`Session.commit` methods are called, so that new
  644. state can be loaded for the new transaction. For this reason,
  645. calling :meth:`Session.expire_all` is not usually needed,
  646. assuming the transaction is isolated.
  647. .. seealso::
  648. :ref:`session_expire` - introductory material
  649. :meth:`.Session.expire`
  650. :meth:`.Session.refresh`
  651. :meth:`_orm.Query.populate_existing`
  652. """ # noqa: E501
  653. return self._proxied.expire_all()
  654. def expunge(self, instance: object) -> None:
  655. r"""Remove the `instance` from this ``Session``.
  656. .. container:: class_bases
  657. Proxied for the :class:`_orm.Session` class on
  658. behalf of the :class:`_orm.scoping.scoped_session` class.
  659. This will free all internal references to the instance. Cascading
  660. will be applied according to the *expunge* cascade rule.
  661. """ # noqa: E501
  662. return self._proxied.expunge(instance)
  663. def expunge_all(self) -> None:
  664. r"""Remove all object instances from this ``Session``.
  665. .. container:: class_bases
  666. Proxied for the :class:`_orm.Session` class on
  667. behalf of the :class:`_orm.scoping.scoped_session` class.
  668. This is equivalent to calling ``expunge(obj)`` on all objects in this
  669. ``Session``.
  670. """ # noqa: E501
  671. return self._proxied.expunge_all()
  672. def flush(self, objects: Optional[Sequence[Any]] = None) -> None:
  673. r"""Flush all the object changes to the database.
  674. .. container:: class_bases
  675. Proxied for the :class:`_orm.Session` class on
  676. behalf of the :class:`_orm.scoping.scoped_session` class.
  677. Writes out all pending object creations, deletions and modifications
  678. to the database as INSERTs, DELETEs, UPDATEs, etc. Operations are
  679. automatically ordered by the Session's unit of work dependency
  680. solver.
  681. Database operations will be issued in the current transactional
  682. context and do not affect the state of the transaction, unless an
  683. error occurs, in which case the entire transaction is rolled back.
  684. You may flush() as often as you like within a transaction to move
  685. changes from Python to the database's transaction buffer.
  686. :param objects: Optional; restricts the flush operation to operate
  687. only on elements that are in the given collection.
  688. This feature is for an extremely narrow set of use cases where
  689. particular objects may need to be operated upon before the
  690. full flush() occurs. It is not intended for general use.
  691. """ # noqa: E501
  692. return self._proxied.flush(objects=objects)
  693. def get(
  694. self,
  695. entity: _EntityBindKey[_O],
  696. ident: _PKIdentityArgument,
  697. *,
  698. options: Optional[Sequence[ORMOption]] = None,
  699. populate_existing: bool = False,
  700. with_for_update: ForUpdateParameter = None,
  701. identity_token: Optional[Any] = None,
  702. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  703. bind_arguments: Optional[_BindArguments] = None,
  704. ) -> Optional[_O]:
  705. r"""Return an instance based on the given primary key identifier,
  706. or ``None`` if not found.
  707. .. container:: class_bases
  708. Proxied for the :class:`_orm.Session` class on
  709. behalf of the :class:`_orm.scoping.scoped_session` class.
  710. E.g.::
  711. my_user = session.get(User, 5)
  712. some_object = session.get(VersionedFoo, (5, 10))
  713. some_object = session.get(
  714. VersionedFoo,
  715. {"id": 5, "version_id": 10}
  716. )
  717. .. versionadded:: 1.4 Added :meth:`_orm.Session.get`, which is moved
  718. from the now legacy :meth:`_orm.Query.get` method.
  719. :meth:`_orm.Session.get` is special in that it provides direct
  720. access to the identity map of the :class:`.Session`.
  721. If the given primary key identifier is present
  722. in the local identity map, the object is returned
  723. directly from this collection and no SQL is emitted,
  724. unless the object has been marked fully expired.
  725. If not present,
  726. a SELECT is performed in order to locate the object.
  727. :meth:`_orm.Session.get` also will perform a check if
  728. the object is present in the identity map and
  729. marked as expired - a SELECT
  730. is emitted to refresh the object as well as to
  731. ensure that the row is still present.
  732. If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
  733. :param entity: a mapped class or :class:`.Mapper` indicating the
  734. type of entity to be loaded.
  735. :param ident: A scalar, tuple, or dictionary representing the
  736. primary key. For a composite (e.g. multiple column) primary key,
  737. a tuple or dictionary should be passed.
  738. For a single-column primary key, the scalar calling form is typically
  739. the most expedient. If the primary key of a row is the value "5",
  740. the call looks like::
  741. my_object = session.get(SomeClass, 5)
  742. The tuple form contains primary key values typically in
  743. the order in which they correspond to the mapped
  744. :class:`_schema.Table`
  745. object's primary key columns, or if the
  746. :paramref:`_orm.Mapper.primary_key` configuration parameter were
  747. used, in
  748. the order used for that parameter. For example, if the primary key
  749. of a row is represented by the integer
  750. digits "5, 10" the call would look like::
  751. my_object = session.get(SomeClass, (5, 10))
  752. The dictionary form should include as keys the mapped attribute names
  753. corresponding to each element of the primary key. If the mapped class
  754. has the attributes ``id``, ``version_id`` as the attributes which
  755. store the object's primary key value, the call would look like::
  756. my_object = session.get(SomeClass, {"id": 5, "version_id": 10})
  757. :param options: optional sequence of loader options which will be
  758. applied to the query, if one is emitted.
  759. :param populate_existing: causes the method to unconditionally emit
  760. a SQL query and refresh the object with the newly loaded data,
  761. regardless of whether or not the object is already present.
  762. :param with_for_update: optional boolean ``True`` indicating FOR UPDATE
  763. should be used, or may be a dictionary containing flags to
  764. indicate a more specific set of FOR UPDATE flags for the SELECT;
  765. flags should match the parameters of
  766. :meth:`_query.Query.with_for_update`.
  767. Supersedes the :paramref:`.Session.refresh.lockmode` parameter.
  768. :param execution_options: optional dictionary of execution options,
  769. which will be associated with the query execution if one is emitted.
  770. This dictionary can provide a subset of the options that are
  771. accepted by :meth:`_engine.Connection.execution_options`, and may
  772. also provide additional options understood only in an ORM context.
  773. .. versionadded:: 1.4.29
  774. .. seealso::
  775. :ref:`orm_queryguide_execution_options` - ORM-specific execution
  776. options
  777. :param bind_arguments: dictionary of additional arguments to determine
  778. the bind. May include "mapper", "bind", or other custom arguments.
  779. Contents of this dictionary are passed to the
  780. :meth:`.Session.get_bind` method.
  781. .. versionadded: 2.0.0rc1
  782. :return: The object instance, or ``None``.
  783. """ # noqa: E501
  784. return self._proxied.get(
  785. entity,
  786. ident,
  787. options=options,
  788. populate_existing=populate_existing,
  789. with_for_update=with_for_update,
  790. identity_token=identity_token,
  791. execution_options=execution_options,
  792. bind_arguments=bind_arguments,
  793. )
  794. def get_one(
  795. self,
  796. entity: _EntityBindKey[_O],
  797. ident: _PKIdentityArgument,
  798. *,
  799. options: Optional[Sequence[ORMOption]] = None,
  800. populate_existing: bool = False,
  801. with_for_update: ForUpdateParameter = None,
  802. identity_token: Optional[Any] = None,
  803. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  804. bind_arguments: Optional[_BindArguments] = None,
  805. ) -> _O:
  806. r"""Return exactly one instance based on the given primary key
  807. identifier, or raise an exception if not found.
  808. .. container:: class_bases
  809. Proxied for the :class:`_orm.Session` class on
  810. behalf of the :class:`_orm.scoping.scoped_session` class.
  811. Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query
  812. selects no rows.
  813. For a detailed documentation of the arguments see the
  814. method :meth:`.Session.get`.
  815. .. versionadded:: 2.0.22
  816. :return: The object instance.
  817. .. seealso::
  818. :meth:`.Session.get` - equivalent method that instead
  819. returns ``None`` if no row was found with the provided primary
  820. key
  821. """ # noqa: E501
  822. return self._proxied.get_one(
  823. entity,
  824. ident,
  825. options=options,
  826. populate_existing=populate_existing,
  827. with_for_update=with_for_update,
  828. identity_token=identity_token,
  829. execution_options=execution_options,
  830. bind_arguments=bind_arguments,
  831. )
  832. def get_bind(
  833. self,
  834. mapper: Optional[_EntityBindKey[_O]] = None,
  835. *,
  836. clause: Optional[ClauseElement] = None,
  837. bind: Optional[_SessionBind] = None,
  838. _sa_skip_events: Optional[bool] = None,
  839. _sa_skip_for_implicit_returning: bool = False,
  840. **kw: Any,
  841. ) -> Union[Engine, Connection]:
  842. r"""Return a "bind" to which this :class:`.Session` is bound.
  843. .. container:: class_bases
  844. Proxied for the :class:`_orm.Session` class on
  845. behalf of the :class:`_orm.scoping.scoped_session` class.
  846. The "bind" is usually an instance of :class:`_engine.Engine`,
  847. except in the case where the :class:`.Session` has been
  848. explicitly bound directly to a :class:`_engine.Connection`.
  849. For a multiply-bound or unbound :class:`.Session`, the
  850. ``mapper`` or ``clause`` arguments are used to determine the
  851. appropriate bind to return.
  852. Note that the "mapper" argument is usually present
  853. when :meth:`.Session.get_bind` is called via an ORM
  854. operation such as a :meth:`.Session.query`, each
  855. individual INSERT/UPDATE/DELETE operation within a
  856. :meth:`.Session.flush`, call, etc.
  857. The order of resolution is:
  858. 1. if mapper given and :paramref:`.Session.binds` is present,
  859. locate a bind based first on the mapper in use, then
  860. on the mapped class in use, then on any base classes that are
  861. present in the ``__mro__`` of the mapped class, from more specific
  862. superclasses to more general.
  863. 2. if clause given and ``Session.binds`` is present,
  864. locate a bind based on :class:`_schema.Table` objects
  865. found in the given clause present in ``Session.binds``.
  866. 3. if ``Session.binds`` is present, return that.
  867. 4. if clause given, attempt to return a bind
  868. linked to the :class:`_schema.MetaData` ultimately
  869. associated with the clause.
  870. 5. if mapper given, attempt to return a bind
  871. linked to the :class:`_schema.MetaData` ultimately
  872. associated with the :class:`_schema.Table` or other
  873. selectable to which the mapper is mapped.
  874. 6. No bind can be found, :exc:`~sqlalchemy.exc.UnboundExecutionError`
  875. is raised.
  876. Note that the :meth:`.Session.get_bind` method can be overridden on
  877. a user-defined subclass of :class:`.Session` to provide any kind
  878. of bind resolution scheme. See the example at
  879. :ref:`session_custom_partitioning`.
  880. :param mapper:
  881. Optional mapped class or corresponding :class:`_orm.Mapper` instance.
  882. The bind can be derived from a :class:`_orm.Mapper` first by
  883. consulting the "binds" map associated with this :class:`.Session`,
  884. and secondly by consulting the :class:`_schema.MetaData` associated
  885. with the :class:`_schema.Table` to which the :class:`_orm.Mapper` is
  886. mapped for a bind.
  887. :param clause:
  888. A :class:`_expression.ClauseElement` (i.e.
  889. :func:`_expression.select`,
  890. :func:`_expression.text`,
  891. etc.). If the ``mapper`` argument is not present or could not
  892. produce a bind, the given expression construct will be searched
  893. for a bound element, typically a :class:`_schema.Table`
  894. associated with
  895. bound :class:`_schema.MetaData`.
  896. .. seealso::
  897. :ref:`session_partitioning`
  898. :paramref:`.Session.binds`
  899. :meth:`.Session.bind_mapper`
  900. :meth:`.Session.bind_table`
  901. """ # noqa: E501
  902. return self._proxied.get_bind(
  903. mapper=mapper,
  904. clause=clause,
  905. bind=bind,
  906. _sa_skip_events=_sa_skip_events,
  907. _sa_skip_for_implicit_returning=_sa_skip_for_implicit_returning,
  908. **kw,
  909. )
  910. def is_modified(
  911. self, instance: object, include_collections: bool = True
  912. ) -> bool:
  913. r"""Return ``True`` if the given instance has locally
  914. modified attributes.
  915. .. container:: class_bases
  916. Proxied for the :class:`_orm.Session` class on
  917. behalf of the :class:`_orm.scoping.scoped_session` class.
  918. This method retrieves the history for each instrumented
  919. attribute on the instance and performs a comparison of the current
  920. value to its previously committed value, if any.
  921. It is in effect a more expensive and accurate
  922. version of checking for the given instance in the
  923. :attr:`.Session.dirty` collection; a full test for
  924. each attribute's net "dirty" status is performed.
  925. E.g.::
  926. return session.is_modified(someobject)
  927. A few caveats to this method apply:
  928. * Instances present in the :attr:`.Session.dirty` collection may
  929. report ``False`` when tested with this method. This is because
  930. the object may have received change events via attribute mutation,
  931. thus placing it in :attr:`.Session.dirty`, but ultimately the state
  932. is the same as that loaded from the database, resulting in no net
  933. change here.
  934. * Scalar attributes may not have recorded the previously set
  935. value when a new value was applied, if the attribute was not loaded,
  936. or was expired, at the time the new value was received - in these
  937. cases, the attribute is assumed to have a change, even if there is
  938. ultimately no net change against its database value. SQLAlchemy in
  939. most cases does not need the "old" value when a set event occurs, so
  940. it skips the expense of a SQL call if the old value isn't present,
  941. based on the assumption that an UPDATE of the scalar value is
  942. usually needed, and in those few cases where it isn't, is less
  943. expensive on average than issuing a defensive SELECT.
  944. The "old" value is fetched unconditionally upon set only if the
  945. attribute container has the ``active_history`` flag set to ``True``.
  946. This flag is set typically for primary key attributes and scalar
  947. object references that are not a simple many-to-one. To set this
  948. flag for any arbitrary mapped column, use the ``active_history``
  949. argument with :func:`.column_property`.
  950. :param instance: mapped instance to be tested for pending changes.
  951. :param include_collections: Indicates if multivalued collections
  952. should be included in the operation. Setting this to ``False`` is a
  953. way to detect only local-column based properties (i.e. scalar columns
  954. or many-to-one foreign keys) that would result in an UPDATE for this
  955. instance upon flush.
  956. """ # noqa: E501
  957. return self._proxied.is_modified(
  958. instance, include_collections=include_collections
  959. )
  960. def bulk_save_objects(
  961. self,
  962. objects: Iterable[object],
  963. return_defaults: bool = False,
  964. update_changed_only: bool = True,
  965. preserve_order: bool = True,
  966. ) -> None:
  967. r"""Perform a bulk save of the given list of objects.
  968. .. container:: class_bases
  969. Proxied for the :class:`_orm.Session` class on
  970. behalf of the :class:`_orm.scoping.scoped_session` class.
  971. .. legacy::
  972. This method is a legacy feature as of the 2.0 series of
  973. SQLAlchemy. For modern bulk INSERT and UPDATE, see
  974. the sections :ref:`orm_queryguide_bulk_insert` and
  975. :ref:`orm_queryguide_bulk_update`.
  976. For general INSERT and UPDATE of existing ORM mapped objects,
  977. prefer standard :term:`unit of work` data management patterns,
  978. introduced in the :ref:`unified_tutorial` at
  979. :ref:`tutorial_orm_data_manipulation`. SQLAlchemy 2.0
  980. now uses :ref:`engine_insertmanyvalues` with modern dialects
  981. which solves previous issues of bulk INSERT slowness.
  982. :param objects: a sequence of mapped object instances. The mapped
  983. objects are persisted as is, and are **not** associated with the
  984. :class:`.Session` afterwards.
  985. For each object, whether the object is sent as an INSERT or an
  986. UPDATE is dependent on the same rules used by the :class:`.Session`
  987. in traditional operation; if the object has the
  988. :attr:`.InstanceState.key`
  989. attribute set, then the object is assumed to be "detached" and
  990. will result in an UPDATE. Otherwise, an INSERT is used.
  991. In the case of an UPDATE, statements are grouped based on which
  992. attributes have changed, and are thus to be the subject of each
  993. SET clause. If ``update_changed_only`` is False, then all
  994. attributes present within each object are applied to the UPDATE
  995. statement, which may help in allowing the statements to be grouped
  996. together into a larger executemany(), and will also reduce the
  997. overhead of checking history on attributes.
  998. :param return_defaults: when True, rows that are missing values which
  999. generate defaults, namely integer primary key defaults and sequences,
  1000. will be inserted **one at a time**, so that the primary key value
  1001. is available. In particular this will allow joined-inheritance
  1002. and other multi-table mappings to insert correctly without the need
  1003. to provide primary key values ahead of time; however,
  1004. :paramref:`.Session.bulk_save_objects.return_defaults` **greatly
  1005. reduces the performance gains** of the method overall. It is strongly
  1006. advised to please use the standard :meth:`_orm.Session.add_all`
  1007. approach.
  1008. :param update_changed_only: when True, UPDATE statements are rendered
  1009. based on those attributes in each state that have logged changes.
  1010. When False, all attributes present are rendered into the SET clause
  1011. with the exception of primary key attributes.
  1012. :param preserve_order: when True, the order of inserts and updates
  1013. matches exactly the order in which the objects are given. When
  1014. False, common types of objects are grouped into inserts
  1015. and updates, to allow for more batching opportunities.
  1016. .. seealso::
  1017. :doc:`queryguide/dml`
  1018. :meth:`.Session.bulk_insert_mappings`
  1019. :meth:`.Session.bulk_update_mappings`
  1020. """ # noqa: E501
  1021. return self._proxied.bulk_save_objects(
  1022. objects,
  1023. return_defaults=return_defaults,
  1024. update_changed_only=update_changed_only,
  1025. preserve_order=preserve_order,
  1026. )
  1027. def bulk_insert_mappings(
  1028. self,
  1029. mapper: Mapper[Any],
  1030. mappings: Iterable[Dict[str, Any]],
  1031. return_defaults: bool = False,
  1032. render_nulls: bool = False,
  1033. ) -> None:
  1034. r"""Perform a bulk insert of the given list of mapping dictionaries.
  1035. .. container:: class_bases
  1036. Proxied for the :class:`_orm.Session` class on
  1037. behalf of the :class:`_orm.scoping.scoped_session` class.
  1038. .. legacy::
  1039. This method is a legacy feature as of the 2.0 series of
  1040. SQLAlchemy. For modern bulk INSERT and UPDATE, see
  1041. the sections :ref:`orm_queryguide_bulk_insert` and
  1042. :ref:`orm_queryguide_bulk_update`. The 2.0 API shares
  1043. implementation details with this method and adds new features
  1044. as well.
  1045. :param mapper: a mapped class, or the actual :class:`_orm.Mapper`
  1046. object,
  1047. representing the single kind of object represented within the mapping
  1048. list.
  1049. :param mappings: a sequence of dictionaries, each one containing the
  1050. state of the mapped row to be inserted, in terms of the attribute
  1051. names on the mapped class. If the mapping refers to multiple tables,
  1052. such as a joined-inheritance mapping, each dictionary must contain all
  1053. keys to be populated into all tables.
  1054. :param return_defaults: when True, the INSERT process will be altered
  1055. to ensure that newly generated primary key values will be fetched.
  1056. The rationale for this parameter is typically to enable
  1057. :ref:`Joined Table Inheritance <joined_inheritance>` mappings to
  1058. be bulk inserted.
  1059. .. note:: for backends that don't support RETURNING, the
  1060. :paramref:`_orm.Session.bulk_insert_mappings.return_defaults`
  1061. parameter can significantly decrease performance as INSERT
  1062. statements can no longer be batched. See
  1063. :ref:`engine_insertmanyvalues`
  1064. for background on which backends are affected.
  1065. :param render_nulls: When True, a value of ``None`` will result
  1066. in a NULL value being included in the INSERT statement, rather
  1067. than the column being omitted from the INSERT. This allows all
  1068. the rows being INSERTed to have the identical set of columns which
  1069. allows the full set of rows to be batched to the DBAPI. Normally,
  1070. each column-set that contains a different combination of NULL values
  1071. than the previous row must omit a different series of columns from
  1072. the rendered INSERT statement, which means it must be emitted as a
  1073. separate statement. By passing this flag, the full set of rows
  1074. are guaranteed to be batchable into one batch; the cost however is
  1075. that server-side defaults which are invoked by an omitted column will
  1076. be skipped, so care must be taken to ensure that these are not
  1077. necessary.
  1078. .. warning::
  1079. When this flag is set, **server side default SQL values will
  1080. not be invoked** for those columns that are inserted as NULL;
  1081. the NULL value will be sent explicitly. Care must be taken
  1082. to ensure that no server-side default functions need to be
  1083. invoked for the operation as a whole.
  1084. .. seealso::
  1085. :doc:`queryguide/dml`
  1086. :meth:`.Session.bulk_save_objects`
  1087. :meth:`.Session.bulk_update_mappings`
  1088. """ # noqa: E501
  1089. return self._proxied.bulk_insert_mappings(
  1090. mapper,
  1091. mappings,
  1092. return_defaults=return_defaults,
  1093. render_nulls=render_nulls,
  1094. )
  1095. def bulk_update_mappings(
  1096. self, mapper: Mapper[Any], mappings: Iterable[Dict[str, Any]]
  1097. ) -> None:
  1098. r"""Perform a bulk update of the given list of mapping dictionaries.
  1099. .. container:: class_bases
  1100. Proxied for the :class:`_orm.Session` class on
  1101. behalf of the :class:`_orm.scoping.scoped_session` class.
  1102. .. legacy::
  1103. This method is a legacy feature as of the 2.0 series of
  1104. SQLAlchemy. For modern bulk INSERT and UPDATE, see
  1105. the sections :ref:`orm_queryguide_bulk_insert` and
  1106. :ref:`orm_queryguide_bulk_update`. The 2.0 API shares
  1107. implementation details with this method and adds new features
  1108. as well.
  1109. :param mapper: a mapped class, or the actual :class:`_orm.Mapper`
  1110. object,
  1111. representing the single kind of object represented within the mapping
  1112. list.
  1113. :param mappings: a sequence of dictionaries, each one containing the
  1114. state of the mapped row to be updated, in terms of the attribute names
  1115. on the mapped class. If the mapping refers to multiple tables, such
  1116. as a joined-inheritance mapping, each dictionary may contain keys
  1117. corresponding to all tables. All those keys which are present and
  1118. are not part of the primary key are applied to the SET clause of the
  1119. UPDATE statement; the primary key values, which are required, are
  1120. applied to the WHERE clause.
  1121. .. seealso::
  1122. :doc:`queryguide/dml`
  1123. :meth:`.Session.bulk_insert_mappings`
  1124. :meth:`.Session.bulk_save_objects`
  1125. """ # noqa: E501
  1126. return self._proxied.bulk_update_mappings(mapper, mappings)
  1127. def merge(
  1128. self,
  1129. instance: _O,
  1130. *,
  1131. load: bool = True,
  1132. options: Optional[Sequence[ORMOption]] = None,
  1133. ) -> _O:
  1134. r"""Copy the state of a given instance into a corresponding instance
  1135. within this :class:`.Session`.
  1136. .. container:: class_bases
  1137. Proxied for the :class:`_orm.Session` class on
  1138. behalf of the :class:`_orm.scoping.scoped_session` class.
  1139. :meth:`.Session.merge` examines the primary key attributes of the
  1140. source instance, and attempts to reconcile it with an instance of the
  1141. same primary key in the session. If not found locally, it attempts
  1142. to load the object from the database based on primary key, and if
  1143. none can be located, creates a new instance. The state of each
  1144. attribute on the source instance is then copied to the target
  1145. instance. The resulting target instance is then returned by the
  1146. method; the original source instance is left unmodified, and
  1147. un-associated with the :class:`.Session` if not already.
  1148. This operation cascades to associated instances if the association is
  1149. mapped with ``cascade="merge"``.
  1150. See :ref:`unitofwork_merging` for a detailed discussion of merging.
  1151. :param instance: Instance to be merged.
  1152. :param load: Boolean, when False, :meth:`.merge` switches into
  1153. a "high performance" mode which causes it to forego emitting history
  1154. events as well as all database access. This flag is used for
  1155. cases such as transferring graphs of objects into a :class:`.Session`
  1156. from a second level cache, or to transfer just-loaded objects
  1157. into the :class:`.Session` owned by a worker thread or process
  1158. without re-querying the database.
  1159. The ``load=False`` use case adds the caveat that the given
  1160. object has to be in a "clean" state, that is, has no pending changes
  1161. to be flushed - even if the incoming object is detached from any
  1162. :class:`.Session`. This is so that when
  1163. the merge operation populates local attributes and
  1164. cascades to related objects and
  1165. collections, the values can be "stamped" onto the
  1166. target object as is, without generating any history or attribute
  1167. events, and without the need to reconcile the incoming data with
  1168. any existing related objects or collections that might not
  1169. be loaded. The resulting objects from ``load=False`` are always
  1170. produced as "clean", so it is only appropriate that the given objects
  1171. should be "clean" as well, else this suggests a mis-use of the
  1172. method.
  1173. :param options: optional sequence of loader options which will be
  1174. applied to the :meth:`_orm.Session.get` method when the merge
  1175. operation loads the existing version of the object from the database.
  1176. .. versionadded:: 1.4.24
  1177. .. seealso::
  1178. :func:`.make_transient_to_detached` - provides for an alternative
  1179. means of "merging" a single object into the :class:`.Session`
  1180. """ # noqa: E501
  1181. return self._proxied.merge(instance, load=load, options=options)
  1182. @overload
  1183. def query(self, _entity: _EntityType[_O]) -> Query[_O]:
  1184. ...
  1185. @overload
  1186. def query(
  1187. self, _colexpr: TypedColumnsClauseRole[_T]
  1188. ) -> RowReturningQuery[Tuple[_T]]:
  1189. ...
  1190. # START OVERLOADED FUNCTIONS self.query RowReturningQuery 2-8
  1191. # code within this block is **programmatically,
  1192. # statically generated** by tools/generate_tuple_map_overloads.py
  1193. @overload
  1194. def query(
  1195. self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1]
  1196. ) -> RowReturningQuery[Tuple[_T0, _T1]]:
  1197. ...
  1198. @overload
  1199. def query(
  1200. self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2]
  1201. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2]]:
  1202. ...
  1203. @overload
  1204. def query(
  1205. self,
  1206. __ent0: _TCCA[_T0],
  1207. __ent1: _TCCA[_T1],
  1208. __ent2: _TCCA[_T2],
  1209. __ent3: _TCCA[_T3],
  1210. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3]]:
  1211. ...
  1212. @overload
  1213. def query(
  1214. self,
  1215. __ent0: _TCCA[_T0],
  1216. __ent1: _TCCA[_T1],
  1217. __ent2: _TCCA[_T2],
  1218. __ent3: _TCCA[_T3],
  1219. __ent4: _TCCA[_T4],
  1220. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4]]:
  1221. ...
  1222. @overload
  1223. def query(
  1224. self,
  1225. __ent0: _TCCA[_T0],
  1226. __ent1: _TCCA[_T1],
  1227. __ent2: _TCCA[_T2],
  1228. __ent3: _TCCA[_T3],
  1229. __ent4: _TCCA[_T4],
  1230. __ent5: _TCCA[_T5],
  1231. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]:
  1232. ...
  1233. @overload
  1234. def query(
  1235. self,
  1236. __ent0: _TCCA[_T0],
  1237. __ent1: _TCCA[_T1],
  1238. __ent2: _TCCA[_T2],
  1239. __ent3: _TCCA[_T3],
  1240. __ent4: _TCCA[_T4],
  1241. __ent5: _TCCA[_T5],
  1242. __ent6: _TCCA[_T6],
  1243. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]:
  1244. ...
  1245. @overload
  1246. def query(
  1247. self,
  1248. __ent0: _TCCA[_T0],
  1249. __ent1: _TCCA[_T1],
  1250. __ent2: _TCCA[_T2],
  1251. __ent3: _TCCA[_T3],
  1252. __ent4: _TCCA[_T4],
  1253. __ent5: _TCCA[_T5],
  1254. __ent6: _TCCA[_T6],
  1255. __ent7: _TCCA[_T7],
  1256. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]:
  1257. ...
  1258. # END OVERLOADED FUNCTIONS self.query
  1259. @overload
  1260. def query(
  1261. self, *entities: _ColumnsClauseArgument[Any], **kwargs: Any
  1262. ) -> Query[Any]:
  1263. ...
  1264. def query(
  1265. self, *entities: _ColumnsClauseArgument[Any], **kwargs: Any
  1266. ) -> Query[Any]:
  1267. r"""Return a new :class:`_query.Query` object corresponding to this
  1268. :class:`_orm.Session`.
  1269. .. container:: class_bases
  1270. Proxied for the :class:`_orm.Session` class on
  1271. behalf of the :class:`_orm.scoping.scoped_session` class.
  1272. Note that the :class:`_query.Query` object is legacy as of
  1273. SQLAlchemy 2.0; the :func:`_sql.select` construct is now used
  1274. to construct ORM queries.
  1275. .. seealso::
  1276. :ref:`unified_tutorial`
  1277. :ref:`queryguide_toplevel`
  1278. :ref:`query_api_toplevel` - legacy API doc
  1279. """ # noqa: E501
  1280. return self._proxied.query(*entities, **kwargs)
  1281. def refresh(
  1282. self,
  1283. instance: object,
  1284. attribute_names: Optional[Iterable[str]] = None,
  1285. with_for_update: ForUpdateParameter = None,
  1286. ) -> None:
  1287. r"""Expire and refresh attributes on the given instance.
  1288. .. container:: class_bases
  1289. Proxied for the :class:`_orm.Session` class on
  1290. behalf of the :class:`_orm.scoping.scoped_session` class.
  1291. The selected attributes will first be expired as they would when using
  1292. :meth:`_orm.Session.expire`; then a SELECT statement will be issued to
  1293. the database to refresh column-oriented attributes with the current
  1294. value available in the current transaction.
  1295. :func:`_orm.relationship` oriented attributes will also be immediately
  1296. loaded if they were already eagerly loaded on the object, using the
  1297. same eager loading strategy that they were loaded with originally.
  1298. .. versionadded:: 1.4 - the :meth:`_orm.Session.refresh` method
  1299. can also refresh eagerly loaded attributes.
  1300. :func:`_orm.relationship` oriented attributes that would normally
  1301. load using the ``select`` (or "lazy") loader strategy will also
  1302. load **if they are named explicitly in the attribute_names
  1303. collection**, emitting a SELECT statement for the attribute using the
  1304. ``immediate`` loader strategy. If lazy-loaded relationships are not
  1305. named in :paramref:`_orm.Session.refresh.attribute_names`, then
  1306. they remain as "lazy loaded" attributes and are not implicitly
  1307. refreshed.
  1308. .. versionchanged:: 2.0.4 The :meth:`_orm.Session.refresh` method
  1309. will now refresh lazy-loaded :func:`_orm.relationship` oriented
  1310. attributes for those which are named explicitly in the
  1311. :paramref:`_orm.Session.refresh.attribute_names` collection.
  1312. .. tip::
  1313. While the :meth:`_orm.Session.refresh` method is capable of
  1314. refreshing both column and relationship oriented attributes, its
  1315. primary focus is on refreshing of local column-oriented attributes
  1316. on a single instance. For more open ended "refresh" functionality,
  1317. including the ability to refresh the attributes on many objects at
  1318. once while having explicit control over relationship loader
  1319. strategies, use the
  1320. :ref:`populate existing <orm_queryguide_populate_existing>` feature
  1321. instead.
  1322. Note that a highly isolated transaction will return the same values as
  1323. were previously read in that same transaction, regardless of changes
  1324. in database state outside of that transaction. Refreshing
  1325. attributes usually only makes sense at the start of a transaction
  1326. where database rows have not yet been accessed.
  1327. :param attribute_names: optional. An iterable collection of
  1328. string attribute names indicating a subset of attributes to
  1329. be refreshed.
  1330. :param with_for_update: optional boolean ``True`` indicating FOR UPDATE
  1331. should be used, or may be a dictionary containing flags to
  1332. indicate a more specific set of FOR UPDATE flags for the SELECT;
  1333. flags should match the parameters of
  1334. :meth:`_query.Query.with_for_update`.
  1335. Supersedes the :paramref:`.Session.refresh.lockmode` parameter.
  1336. .. seealso::
  1337. :ref:`session_expire` - introductory material
  1338. :meth:`.Session.expire`
  1339. :meth:`.Session.expire_all`
  1340. :ref:`orm_queryguide_populate_existing` - allows any ORM query
  1341. to refresh objects as they would be loaded normally.
  1342. """ # noqa: E501
  1343. return self._proxied.refresh(
  1344. instance,
  1345. attribute_names=attribute_names,
  1346. with_for_update=with_for_update,
  1347. )
  1348. def rollback(self) -> None:
  1349. r"""Rollback the current transaction in progress.
  1350. .. container:: class_bases
  1351. Proxied for the :class:`_orm.Session` class on
  1352. behalf of the :class:`_orm.scoping.scoped_session` class.
  1353. If no transaction is in progress, this method is a pass-through.
  1354. The method always rolls back
  1355. the topmost database transaction, discarding any nested
  1356. transactions that may be in progress.
  1357. .. seealso::
  1358. :ref:`session_rollback`
  1359. :ref:`unitofwork_transaction`
  1360. """ # noqa: E501
  1361. return self._proxied.rollback()
  1362. @overload
  1363. def scalar(
  1364. self,
  1365. statement: TypedReturnsRows[Tuple[_T]],
  1366. params: Optional[_CoreSingleExecuteParams] = None,
  1367. *,
  1368. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  1369. bind_arguments: Optional[_BindArguments] = None,
  1370. **kw: Any,
  1371. ) -> Optional[_T]:
  1372. ...
  1373. @overload
  1374. def scalar(
  1375. self,
  1376. statement: Executable,
  1377. params: Optional[_CoreSingleExecuteParams] = None,
  1378. *,
  1379. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  1380. bind_arguments: Optional[_BindArguments] = None,
  1381. **kw: Any,
  1382. ) -> Any:
  1383. ...
  1384. def scalar(
  1385. self,
  1386. statement: Executable,
  1387. params: Optional[_CoreSingleExecuteParams] = None,
  1388. *,
  1389. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  1390. bind_arguments: Optional[_BindArguments] = None,
  1391. **kw: Any,
  1392. ) -> Any:
  1393. r"""Execute a statement and return a scalar result.
  1394. .. container:: class_bases
  1395. Proxied for the :class:`_orm.Session` class on
  1396. behalf of the :class:`_orm.scoping.scoped_session` class.
  1397. Usage and parameters are the same as that of
  1398. :meth:`_orm.Session.execute`; the return result is a scalar Python
  1399. value.
  1400. """ # noqa: E501
  1401. return self._proxied.scalar(
  1402. statement,
  1403. params=params,
  1404. execution_options=execution_options,
  1405. bind_arguments=bind_arguments,
  1406. **kw,
  1407. )
  1408. @overload
  1409. def scalars(
  1410. self,
  1411. statement: TypedReturnsRows[Tuple[_T]],
  1412. params: Optional[_CoreAnyExecuteParams] = None,
  1413. *,
  1414. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  1415. bind_arguments: Optional[_BindArguments] = None,
  1416. **kw: Any,
  1417. ) -> ScalarResult[_T]:
  1418. ...
  1419. @overload
  1420. def scalars(
  1421. self,
  1422. statement: Executable,
  1423. params: Optional[_CoreAnyExecuteParams] = None,
  1424. *,
  1425. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  1426. bind_arguments: Optional[_BindArguments] = None,
  1427. **kw: Any,
  1428. ) -> ScalarResult[Any]:
  1429. ...
  1430. def scalars(
  1431. self,
  1432. statement: Executable,
  1433. params: Optional[_CoreAnyExecuteParams] = None,
  1434. *,
  1435. execution_options: OrmExecuteOptionsParameter = util.EMPTY_DICT,
  1436. bind_arguments: Optional[_BindArguments] = None,
  1437. **kw: Any,
  1438. ) -> ScalarResult[Any]:
  1439. r"""Execute a statement and return the results as scalars.
  1440. .. container:: class_bases
  1441. Proxied for the :class:`_orm.Session` class on
  1442. behalf of the :class:`_orm.scoping.scoped_session` class.
  1443. Usage and parameters are the same as that of
  1444. :meth:`_orm.Session.execute`; the return result is a
  1445. :class:`_result.ScalarResult` filtering object which
  1446. will return single elements rather than :class:`_row.Row` objects.
  1447. :return: a :class:`_result.ScalarResult` object
  1448. .. versionadded:: 1.4.24 Added :meth:`_orm.Session.scalars`
  1449. .. versionadded:: 1.4.26 Added :meth:`_orm.scoped_session.scalars`
  1450. .. seealso::
  1451. :ref:`orm_queryguide_select_orm_entities` - contrasts the behavior
  1452. of :meth:`_orm.Session.execute` to :meth:`_orm.Session.scalars`
  1453. """ # noqa: E501
  1454. return self._proxied.scalars(
  1455. statement,
  1456. params=params,
  1457. execution_options=execution_options,
  1458. bind_arguments=bind_arguments,
  1459. **kw,
  1460. )
  1461. @property
  1462. def bind(self) -> Optional[Union[Engine, Connection]]:
  1463. r"""Proxy for the :attr:`_orm.Session.bind` attribute
  1464. on behalf of the :class:`_orm.scoping.scoped_session` class.
  1465. """ # noqa: E501
  1466. return self._proxied.bind
  1467. @bind.setter
  1468. def bind(self, attr: Optional[Union[Engine, Connection]]) -> None:
  1469. self._proxied.bind = attr
  1470. @property
  1471. def dirty(self) -> Any:
  1472. r"""The set of all persistent instances considered dirty.
  1473. .. container:: class_bases
  1474. Proxied for the :class:`_orm.Session` class
  1475. on behalf of the :class:`_orm.scoping.scoped_session` class.
  1476. E.g.::
  1477. some_mapped_object in session.dirty
  1478. Instances are considered dirty when they were modified but not
  1479. deleted.
  1480. Note that this 'dirty' calculation is 'optimistic'; most
  1481. attribute-setting or collection modification operations will
  1482. mark an instance as 'dirty' and place it in this set, even if
  1483. there is no net change to the attribute's value. At flush
  1484. time, the value of each attribute is compared to its
  1485. previously saved value, and if there's no net change, no SQL
  1486. operation will occur (this is a more expensive operation so
  1487. it's only done at flush time).
  1488. To check if an instance has actionable net changes to its
  1489. attributes, use the :meth:`.Session.is_modified` method.
  1490. """ # noqa: E501
  1491. return self._proxied.dirty
  1492. @property
  1493. def deleted(self) -> Any:
  1494. r"""The set of all instances marked as 'deleted' within this ``Session``
  1495. .. container:: class_bases
  1496. Proxied for the :class:`_orm.Session` class
  1497. on behalf of the :class:`_orm.scoping.scoped_session` class.
  1498. """ # noqa: E501
  1499. return self._proxied.deleted
  1500. @property
  1501. def new(self) -> Any:
  1502. r"""The set of all instances marked as 'new' within this ``Session``.
  1503. .. container:: class_bases
  1504. Proxied for the :class:`_orm.Session` class
  1505. on behalf of the :class:`_orm.scoping.scoped_session` class.
  1506. """ # noqa: E501
  1507. return self._proxied.new
  1508. @property
  1509. def identity_map(self) -> IdentityMap:
  1510. r"""Proxy for the :attr:`_orm.Session.identity_map` attribute
  1511. on behalf of the :class:`_orm.scoping.scoped_session` class.
  1512. """ # noqa: E501
  1513. return self._proxied.identity_map
  1514. @identity_map.setter
  1515. def identity_map(self, attr: IdentityMap) -> None:
  1516. self._proxied.identity_map = attr
  1517. @property
  1518. def is_active(self) -> Any:
  1519. r"""True if this :class:`.Session` not in "partial rollback" state.
  1520. .. container:: class_bases
  1521. Proxied for the :class:`_orm.Session` class
  1522. on behalf of the :class:`_orm.scoping.scoped_session` class.
  1523. .. versionchanged:: 1.4 The :class:`_orm.Session` no longer begins
  1524. a new transaction immediately, so this attribute will be False
  1525. when the :class:`_orm.Session` is first instantiated.
  1526. "partial rollback" state typically indicates that the flush process
  1527. of the :class:`_orm.Session` has failed, and that the
  1528. :meth:`_orm.Session.rollback` method must be emitted in order to
  1529. fully roll back the transaction.
  1530. If this :class:`_orm.Session` is not in a transaction at all, the
  1531. :class:`_orm.Session` will autobegin when it is first used, so in this
  1532. case :attr:`_orm.Session.is_active` will return True.
  1533. Otherwise, if this :class:`_orm.Session` is within a transaction,
  1534. and that transaction has not been rolled back internally, the
  1535. :attr:`_orm.Session.is_active` will also return True.
  1536. .. seealso::
  1537. :ref:`faq_session_rollback`
  1538. :meth:`_orm.Session.in_transaction`
  1539. """ # noqa: E501
  1540. return self._proxied.is_active
  1541. @property
  1542. def autoflush(self) -> bool:
  1543. r"""Proxy for the :attr:`_orm.Session.autoflush` attribute
  1544. on behalf of the :class:`_orm.scoping.scoped_session` class.
  1545. """ # noqa: E501
  1546. return self._proxied.autoflush
  1547. @autoflush.setter
  1548. def autoflush(self, attr: bool) -> None:
  1549. self._proxied.autoflush = attr
  1550. @property
  1551. def no_autoflush(self) -> Any:
  1552. r"""Return a context manager that disables autoflush.
  1553. .. container:: class_bases
  1554. Proxied for the :class:`_orm.Session` class
  1555. on behalf of the :class:`_orm.scoping.scoped_session` class.
  1556. e.g.::
  1557. with session.no_autoflush:
  1558. some_object = SomeClass()
  1559. session.add(some_object)
  1560. # won't autoflush
  1561. some_object.related_thing = session.query(SomeRelated).first()
  1562. Operations that proceed within the ``with:`` block
  1563. will not be subject to flushes occurring upon query
  1564. access. This is useful when initializing a series
  1565. of objects which involve existing database queries,
  1566. where the uncompleted object should not yet be flushed.
  1567. """ # noqa: E501
  1568. return self._proxied.no_autoflush
  1569. @property
  1570. def info(self) -> Any:
  1571. r"""A user-modifiable dictionary.
  1572. .. container:: class_bases
  1573. Proxied for the :class:`_orm.Session` class
  1574. on behalf of the :class:`_orm.scoping.scoped_session` class.
  1575. The initial value of this dictionary can be populated using the
  1576. ``info`` argument to the :class:`.Session` constructor or
  1577. :class:`.sessionmaker` constructor or factory methods. The dictionary
  1578. here is always local to this :class:`.Session` and can be modified
  1579. independently of all other :class:`.Session` objects.
  1580. """ # noqa: E501
  1581. return self._proxied.info
  1582. @classmethod
  1583. def close_all(cls) -> None:
  1584. r"""Close *all* sessions in memory.
  1585. .. container:: class_bases
  1586. Proxied for the :class:`_orm.Session` class on
  1587. behalf of the :class:`_orm.scoping.scoped_session` class.
  1588. .. deprecated:: 1.3 The :meth:`.Session.close_all` method is deprecated and will be removed in a future release. Please refer to :func:`.session.close_all_sessions`.
  1589. """ # noqa: E501
  1590. return Session.close_all()
  1591. @classmethod
  1592. def object_session(cls, instance: object) -> Optional[Session]:
  1593. r"""Return the :class:`.Session` to which an object belongs.
  1594. .. container:: class_bases
  1595. Proxied for the :class:`_orm.Session` class on
  1596. behalf of the :class:`_orm.scoping.scoped_session` class.
  1597. This is an alias of :func:`.object_session`.
  1598. """ # noqa: E501
  1599. return Session.object_session(instance)
  1600. @classmethod
  1601. def identity_key(
  1602. cls,
  1603. class_: Optional[Type[Any]] = None,
  1604. ident: Union[Any, Tuple[Any, ...]] = None,
  1605. *,
  1606. instance: Optional[Any] = None,
  1607. row: Optional[Union[Row[Any], RowMapping]] = None,
  1608. identity_token: Optional[Any] = None,
  1609. ) -> _IdentityKeyType[Any]:
  1610. r"""Return an identity key.
  1611. .. container:: class_bases
  1612. Proxied for the :class:`_orm.Session` class on
  1613. behalf of the :class:`_orm.scoping.scoped_session` class.
  1614. This is an alias of :func:`.util.identity_key`.
  1615. """ # noqa: E501
  1616. return Session.identity_key(
  1617. class_=class_,
  1618. ident=ident,
  1619. instance=instance,
  1620. row=row,
  1621. identity_token=identity_token,
  1622. )
  1623. # END PROXY METHODS scoped_session
  1624. ScopedSession = scoped_session
  1625. """Old name for backwards compatibility."""