scoping.py 76 KB

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