state.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. # orm/state.py
  2. # Copyright (C) 2005-2025 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. """Defines instrumentation of instances.
  8. This module is usually not directly visible to user applications, but
  9. defines a large part of the ORM's interactivity.
  10. """
  11. from __future__ import annotations
  12. from typing import Any
  13. from typing import Callable
  14. from typing import Dict
  15. from typing import Generic
  16. from typing import Iterable
  17. from typing import Optional
  18. from typing import Set
  19. from typing import Tuple
  20. from typing import TYPE_CHECKING
  21. from typing import Union
  22. import weakref
  23. from . import base
  24. from . import exc as orm_exc
  25. from . import interfaces
  26. from ._typing import _O
  27. from ._typing import is_collection_impl
  28. from .base import ATTR_WAS_SET
  29. from .base import INIT_OK
  30. from .base import LoaderCallableStatus
  31. from .base import NEVER_SET
  32. from .base import NO_VALUE
  33. from .base import PASSIVE_NO_INITIALIZE
  34. from .base import PASSIVE_NO_RESULT
  35. from .base import PASSIVE_OFF
  36. from .base import SQL_OK
  37. from .path_registry import PathRegistry
  38. from .. import exc as sa_exc
  39. from .. import inspection
  40. from .. import util
  41. from ..util.typing import Literal
  42. from ..util.typing import Protocol
  43. if TYPE_CHECKING:
  44. from ._typing import _IdentityKeyType
  45. from ._typing import _InstanceDict
  46. from ._typing import _LoaderCallable
  47. from .attributes import AttributeImpl
  48. from .attributes import History
  49. from .base import PassiveFlag
  50. from .collections import _AdaptedCollectionProtocol
  51. from .identity import IdentityMap
  52. from .instrumentation import ClassManager
  53. from .interfaces import ORMOption
  54. from .mapper import Mapper
  55. from .session import Session
  56. from ..engine import Row
  57. from ..ext.asyncio.session import async_session as _async_provider
  58. from ..ext.asyncio.session import AsyncSession
  59. if TYPE_CHECKING:
  60. _sessions: weakref.WeakValueDictionary[int, Session]
  61. else:
  62. # late-populated by session.py
  63. _sessions = None
  64. if not TYPE_CHECKING:
  65. # optionally late-provided by sqlalchemy.ext.asyncio.session
  66. _async_provider = None # noqa
  67. class _InstanceDictProto(Protocol):
  68. def __call__(self) -> Optional[IdentityMap]: ...
  69. class _InstallLoaderCallableProto(Protocol[_O]):
  70. """used at result loading time to install a _LoaderCallable callable
  71. upon a specific InstanceState, which will be used to populate an
  72. attribute when that attribute is accessed.
  73. Concrete examples are per-instance deferred column loaders and
  74. relationship lazy loaders.
  75. """
  76. def __call__(
  77. self, state: InstanceState[_O], dict_: _InstanceDict, row: Row[Any]
  78. ) -> None: ...
  79. @inspection._self_inspects
  80. class InstanceState(interfaces.InspectionAttrInfo, Generic[_O]):
  81. """Tracks state information at the instance level.
  82. The :class:`.InstanceState` is a key object used by the
  83. SQLAlchemy ORM in order to track the state of an object;
  84. it is created the moment an object is instantiated, typically
  85. as a result of :term:`instrumentation` which SQLAlchemy applies
  86. to the ``__init__()`` method of the class.
  87. :class:`.InstanceState` is also a semi-public object,
  88. available for runtime inspection as to the state of a
  89. mapped instance, including information such as its current
  90. status within a particular :class:`.Session` and details
  91. about data on individual attributes. The public API
  92. in order to acquire a :class:`.InstanceState` object
  93. is to use the :func:`_sa.inspect` system::
  94. >>> from sqlalchemy import inspect
  95. >>> insp = inspect(some_mapped_object)
  96. >>> insp.attrs.nickname.history
  97. History(added=['new nickname'], unchanged=(), deleted=['nickname'])
  98. .. seealso::
  99. :ref:`orm_mapper_inspection_instancestate`
  100. """
  101. __slots__ = (
  102. "__dict__",
  103. "__weakref__",
  104. "class_",
  105. "manager",
  106. "obj",
  107. "committed_state",
  108. "expired_attributes",
  109. )
  110. manager: ClassManager[_O]
  111. session_id: Optional[int] = None
  112. key: Optional[_IdentityKeyType[_O]] = None
  113. runid: Optional[int] = None
  114. load_options: Tuple[ORMOption, ...] = ()
  115. load_path: PathRegistry = PathRegistry.root
  116. insert_order: Optional[int] = None
  117. _strong_obj: Optional[object] = None
  118. obj: weakref.ref[_O]
  119. committed_state: Dict[str, Any]
  120. modified: bool = False
  121. """When ``True`` the object was modified."""
  122. expired: bool = False
  123. """When ``True`` the object is :term:`expired`.
  124. .. seealso::
  125. :ref:`session_expire`
  126. """
  127. _deleted: bool = False
  128. _load_pending: bool = False
  129. _orphaned_outside_of_session: bool = False
  130. is_instance: bool = True
  131. identity_token: object = None
  132. _last_known_values: Optional[Dict[str, Any]] = None
  133. _instance_dict: _InstanceDictProto
  134. """A weak reference, or in the default case a plain callable, that
  135. returns a reference to the current :class:`.IdentityMap`, if any.
  136. """
  137. if not TYPE_CHECKING:
  138. def _instance_dict(self):
  139. """default 'weak reference' for _instance_dict"""
  140. return None
  141. expired_attributes: Set[str]
  142. """The set of keys which are 'expired' to be loaded by
  143. the manager's deferred scalar loader, assuming no pending
  144. changes.
  145. See also the ``unmodified`` collection which is intersected
  146. against this set when a refresh operation occurs.
  147. """
  148. callables: Dict[str, Callable[[InstanceState[_O], PassiveFlag], Any]]
  149. """A namespace where a per-state loader callable can be associated.
  150. In SQLAlchemy 1.0, this is only used for lazy loaders / deferred
  151. loaders that were set up via query option.
  152. Previously, callables was used also to indicate expired attributes
  153. by storing a link to the InstanceState itself in this dictionary.
  154. This role is now handled by the expired_attributes set.
  155. """
  156. if not TYPE_CHECKING:
  157. callables = util.EMPTY_DICT
  158. def __init__(self, obj: _O, manager: ClassManager[_O]):
  159. self.class_ = obj.__class__
  160. self.manager = manager
  161. self.obj = weakref.ref(obj, self._cleanup)
  162. self.committed_state = {}
  163. self.expired_attributes = set()
  164. @util.memoized_property
  165. def attrs(self) -> util.ReadOnlyProperties[AttributeState]:
  166. """Return a namespace representing each attribute on
  167. the mapped object, including its current value
  168. and history.
  169. The returned object is an instance of :class:`.AttributeState`.
  170. This object allows inspection of the current data
  171. within an attribute as well as attribute history
  172. since the last flush.
  173. """
  174. return util.ReadOnlyProperties(
  175. {key: AttributeState(self, key) for key in self.manager}
  176. )
  177. @property
  178. def transient(self) -> bool:
  179. """Return ``True`` if the object is :term:`transient`.
  180. .. seealso::
  181. :ref:`session_object_states`
  182. """
  183. return self.key is None and not self._attached
  184. @property
  185. def pending(self) -> bool:
  186. """Return ``True`` if the object is :term:`pending`.
  187. .. seealso::
  188. :ref:`session_object_states`
  189. """
  190. return self.key is None and self._attached
  191. @property
  192. def deleted(self) -> bool:
  193. """Return ``True`` if the object is :term:`deleted`.
  194. An object that is in the deleted state is guaranteed to
  195. not be within the :attr:`.Session.identity_map` of its parent
  196. :class:`.Session`; however if the session's transaction is rolled
  197. back, the object will be restored to the persistent state and
  198. the identity map.
  199. .. note::
  200. The :attr:`.InstanceState.deleted` attribute refers to a specific
  201. state of the object that occurs between the "persistent" and
  202. "detached" states; once the object is :term:`detached`, the
  203. :attr:`.InstanceState.deleted` attribute **no longer returns
  204. True**; in order to detect that a state was deleted, regardless
  205. of whether or not the object is associated with a
  206. :class:`.Session`, use the :attr:`.InstanceState.was_deleted`
  207. accessor.
  208. .. versionadded: 1.1
  209. .. seealso::
  210. :ref:`session_object_states`
  211. """
  212. return self.key is not None and self._attached and self._deleted
  213. @property
  214. def was_deleted(self) -> bool:
  215. """Return True if this object is or was previously in the
  216. "deleted" state and has not been reverted to persistent.
  217. This flag returns True once the object was deleted in flush.
  218. When the object is expunged from the session either explicitly
  219. or via transaction commit and enters the "detached" state,
  220. this flag will continue to report True.
  221. .. seealso::
  222. :attr:`.InstanceState.deleted` - refers to the "deleted" state
  223. :func:`.orm.util.was_deleted` - standalone function
  224. :ref:`session_object_states`
  225. """
  226. return self._deleted
  227. @property
  228. def persistent(self) -> bool:
  229. """Return ``True`` if the object is :term:`persistent`.
  230. An object that is in the persistent state is guaranteed to
  231. be within the :attr:`.Session.identity_map` of its parent
  232. :class:`.Session`.
  233. .. seealso::
  234. :ref:`session_object_states`
  235. """
  236. return self.key is not None and self._attached and not self._deleted
  237. @property
  238. def detached(self) -> bool:
  239. """Return ``True`` if the object is :term:`detached`.
  240. .. seealso::
  241. :ref:`session_object_states`
  242. """
  243. return self.key is not None and not self._attached
  244. @util.non_memoized_property
  245. @util.preload_module("sqlalchemy.orm.session")
  246. def _attached(self) -> bool:
  247. return (
  248. self.session_id is not None
  249. and self.session_id in util.preloaded.orm_session._sessions
  250. )
  251. def _track_last_known_value(self, key: str) -> None:
  252. """Track the last known value of a particular key after expiration
  253. operations.
  254. .. versionadded:: 1.3
  255. """
  256. lkv = self._last_known_values
  257. if lkv is None:
  258. self._last_known_values = lkv = {}
  259. if key not in lkv:
  260. lkv[key] = NO_VALUE
  261. @property
  262. def session(self) -> Optional[Session]:
  263. """Return the owning :class:`.Session` for this instance,
  264. or ``None`` if none available.
  265. Note that the result here can in some cases be *different*
  266. from that of ``obj in session``; an object that's been deleted
  267. will report as not ``in session``, however if the transaction is
  268. still in progress, this attribute will still refer to that session.
  269. Only when the transaction is completed does the object become
  270. fully detached under normal circumstances.
  271. .. seealso::
  272. :attr:`_orm.InstanceState.async_session`
  273. """
  274. if self.session_id:
  275. try:
  276. return _sessions[self.session_id]
  277. except KeyError:
  278. pass
  279. return None
  280. @property
  281. def async_session(self) -> Optional[AsyncSession]:
  282. """Return the owning :class:`_asyncio.AsyncSession` for this instance,
  283. or ``None`` if none available.
  284. This attribute is only non-None when the :mod:`sqlalchemy.ext.asyncio`
  285. API is in use for this ORM object. The returned
  286. :class:`_asyncio.AsyncSession` object will be a proxy for the
  287. :class:`_orm.Session` object that would be returned from the
  288. :attr:`_orm.InstanceState.session` attribute for this
  289. :class:`_orm.InstanceState`.
  290. .. versionadded:: 1.4.18
  291. .. seealso::
  292. :ref:`asyncio_toplevel`
  293. """
  294. if _async_provider is None:
  295. return None
  296. sess = self.session
  297. if sess is not None:
  298. return _async_provider(sess)
  299. else:
  300. return None
  301. @property
  302. def object(self) -> Optional[_O]:
  303. """Return the mapped object represented by this
  304. :class:`.InstanceState`.
  305. Returns None if the object has been garbage collected
  306. """
  307. return self.obj()
  308. @property
  309. def identity(self) -> Optional[Tuple[Any, ...]]:
  310. """Return the mapped identity of the mapped object.
  311. This is the primary key identity as persisted by the ORM
  312. which can always be passed directly to
  313. :meth:`_query.Query.get`.
  314. Returns ``None`` if the object has no primary key identity.
  315. .. note::
  316. An object which is :term:`transient` or :term:`pending`
  317. does **not** have a mapped identity until it is flushed,
  318. even if its attributes include primary key values.
  319. """
  320. if self.key is None:
  321. return None
  322. else:
  323. return self.key[1]
  324. @property
  325. def identity_key(self) -> Optional[_IdentityKeyType[_O]]:
  326. """Return the identity key for the mapped object.
  327. This is the key used to locate the object within
  328. the :attr:`.Session.identity_map` mapping. It contains
  329. the identity as returned by :attr:`.identity` within it.
  330. """
  331. return self.key
  332. @util.memoized_property
  333. def parents(self) -> Dict[int, Union[Literal[False], InstanceState[Any]]]:
  334. return {}
  335. @util.memoized_property
  336. def _pending_mutations(self) -> Dict[str, PendingCollection]:
  337. return {}
  338. @util.memoized_property
  339. def _empty_collections(self) -> Dict[str, _AdaptedCollectionProtocol]:
  340. return {}
  341. @util.memoized_property
  342. def mapper(self) -> Mapper[_O]:
  343. """Return the :class:`_orm.Mapper` used for this mapped object."""
  344. return self.manager.mapper
  345. @property
  346. def has_identity(self) -> bool:
  347. """Return ``True`` if this object has an identity key.
  348. This should always have the same value as the
  349. expression ``state.persistent`` or ``state.detached``.
  350. """
  351. return bool(self.key)
  352. @classmethod
  353. def _detach_states(
  354. self,
  355. states: Iterable[InstanceState[_O]],
  356. session: Session,
  357. to_transient: bool = False,
  358. ) -> None:
  359. persistent_to_detached = (
  360. session.dispatch.persistent_to_detached or None
  361. )
  362. deleted_to_detached = session.dispatch.deleted_to_detached or None
  363. pending_to_transient = session.dispatch.pending_to_transient or None
  364. persistent_to_transient = (
  365. session.dispatch.persistent_to_transient or None
  366. )
  367. for state in states:
  368. deleted = state._deleted
  369. pending = state.key is None
  370. persistent = not pending and not deleted
  371. state.session_id = None
  372. if to_transient and state.key:
  373. del state.key
  374. if persistent:
  375. if to_transient:
  376. if persistent_to_transient is not None:
  377. persistent_to_transient(session, state)
  378. elif persistent_to_detached is not None:
  379. persistent_to_detached(session, state)
  380. elif deleted and deleted_to_detached is not None:
  381. deleted_to_detached(session, state)
  382. elif pending and pending_to_transient is not None:
  383. pending_to_transient(session, state)
  384. state._strong_obj = None
  385. def _detach(self, session: Optional[Session] = None) -> None:
  386. if session:
  387. InstanceState._detach_states([self], session)
  388. else:
  389. self.session_id = self._strong_obj = None
  390. def _dispose(self) -> None:
  391. # used by the test suite, apparently
  392. self._detach()
  393. def _cleanup(self, ref: weakref.ref[_O]) -> None:
  394. """Weakref callback cleanup.
  395. This callable cleans out the state when it is being garbage
  396. collected.
  397. this _cleanup **assumes** that there are no strong refs to us!
  398. Will not work otherwise!
  399. """
  400. # Python builtins become undefined during interpreter shutdown.
  401. # Guard against exceptions during this phase, as the method cannot
  402. # proceed in any case if builtins have been undefined.
  403. if dict is None:
  404. return
  405. instance_dict = self._instance_dict()
  406. if instance_dict is not None:
  407. instance_dict._fast_discard(self)
  408. del self._instance_dict
  409. # we can't possibly be in instance_dict._modified
  410. # b.c. this is weakref cleanup only, that set
  411. # is strong referencing!
  412. # assert self not in instance_dict._modified
  413. self.session_id = self._strong_obj = None
  414. @property
  415. def dict(self) -> _InstanceDict:
  416. """Return the instance dict used by the object.
  417. Under normal circumstances, this is always synonymous
  418. with the ``__dict__`` attribute of the mapped object,
  419. unless an alternative instrumentation system has been
  420. configured.
  421. In the case that the actual object has been garbage
  422. collected, this accessor returns a blank dictionary.
  423. """
  424. o = self.obj()
  425. if o is not None:
  426. return base.instance_dict(o)
  427. else:
  428. return {}
  429. def _initialize_instance(*mixed: Any, **kwargs: Any) -> None:
  430. self, instance, args = mixed[0], mixed[1], mixed[2:] # noqa
  431. manager = self.manager
  432. manager.dispatch.init(self, args, kwargs)
  433. try:
  434. manager.original_init(*mixed[1:], **kwargs)
  435. except:
  436. with util.safe_reraise():
  437. manager.dispatch.init_failure(self, args, kwargs)
  438. def get_history(self, key: str, passive: PassiveFlag) -> History:
  439. return self.manager[key].impl.get_history(self, self.dict, passive)
  440. def get_impl(self, key: str) -> AttributeImpl:
  441. return self.manager[key].impl
  442. def _get_pending_mutation(self, key: str) -> PendingCollection:
  443. if key not in self._pending_mutations:
  444. self._pending_mutations[key] = PendingCollection()
  445. return self._pending_mutations[key]
  446. def __getstate__(self) -> Dict[str, Any]:
  447. state_dict: Dict[str, Any] = {
  448. "instance": self.obj(),
  449. "class_": self.class_,
  450. "committed_state": self.committed_state,
  451. "expired_attributes": self.expired_attributes,
  452. }
  453. state_dict.update(
  454. (k, self.__dict__[k])
  455. for k in (
  456. "_pending_mutations",
  457. "modified",
  458. "expired",
  459. "callables",
  460. "key",
  461. "parents",
  462. "load_options",
  463. "class_",
  464. "expired_attributes",
  465. "info",
  466. )
  467. if k in self.__dict__
  468. )
  469. if self.load_path:
  470. state_dict["load_path"] = self.load_path.serialize()
  471. state_dict["manager"] = self.manager._serialize(self, state_dict)
  472. return state_dict
  473. def __setstate__(self, state_dict: Dict[str, Any]) -> None:
  474. inst = state_dict["instance"]
  475. if inst is not None:
  476. self.obj = weakref.ref(inst, self._cleanup)
  477. self.class_ = inst.__class__
  478. else:
  479. self.obj = lambda: None # type: ignore
  480. self.class_ = state_dict["class_"]
  481. self.committed_state = state_dict.get("committed_state", {})
  482. self._pending_mutations = state_dict.get("_pending_mutations", {})
  483. self.parents = state_dict.get("parents", {})
  484. self.modified = state_dict.get("modified", False)
  485. self.expired = state_dict.get("expired", False)
  486. if "info" in state_dict:
  487. self.info.update(state_dict["info"])
  488. if "callables" in state_dict:
  489. self.callables = state_dict["callables"]
  490. self.expired_attributes = state_dict["expired_attributes"]
  491. else:
  492. if "expired_attributes" in state_dict:
  493. self.expired_attributes = state_dict["expired_attributes"]
  494. else:
  495. self.expired_attributes = set()
  496. self.__dict__.update(
  497. [
  498. (k, state_dict[k])
  499. for k in ("key", "load_options")
  500. if k in state_dict
  501. ]
  502. )
  503. if self.key:
  504. self.identity_token = self.key[2]
  505. if "load_path" in state_dict:
  506. self.load_path = PathRegistry.deserialize(state_dict["load_path"])
  507. state_dict["manager"](self, inst, state_dict)
  508. def _reset(self, dict_: _InstanceDict, key: str) -> None:
  509. """Remove the given attribute and any
  510. callables associated with it."""
  511. old = dict_.pop(key, None)
  512. manager_impl = self.manager[key].impl
  513. if old is not None and is_collection_impl(manager_impl):
  514. manager_impl._invalidate_collection(old)
  515. self.expired_attributes.discard(key)
  516. if self.callables:
  517. self.callables.pop(key, None)
  518. def _copy_callables(self, from_: InstanceState[Any]) -> None:
  519. if "callables" in from_.__dict__:
  520. self.callables = dict(from_.callables)
  521. @classmethod
  522. def _instance_level_callable_processor(
  523. cls, manager: ClassManager[_O], fn: _LoaderCallable, key: Any
  524. ) -> _InstallLoaderCallableProto[_O]:
  525. impl = manager[key].impl
  526. if is_collection_impl(impl):
  527. fixed_impl = impl
  528. def _set_callable(
  529. state: InstanceState[_O], dict_: _InstanceDict, row: Row[Any]
  530. ) -> None:
  531. if "callables" not in state.__dict__:
  532. state.callables = {}
  533. old = dict_.pop(key, None)
  534. if old is not None:
  535. fixed_impl._invalidate_collection(old)
  536. state.callables[key] = fn
  537. else:
  538. def _set_callable(
  539. state: InstanceState[_O], dict_: _InstanceDict, row: Row[Any]
  540. ) -> None:
  541. if "callables" not in state.__dict__:
  542. state.callables = {}
  543. state.callables[key] = fn
  544. return _set_callable
  545. def _expire(
  546. self, dict_: _InstanceDict, modified_set: Set[InstanceState[Any]]
  547. ) -> None:
  548. self.expired = True
  549. if self.modified:
  550. modified_set.discard(self)
  551. self.committed_state.clear()
  552. self.modified = False
  553. self._strong_obj = None
  554. if "_pending_mutations" in self.__dict__:
  555. del self.__dict__["_pending_mutations"]
  556. if "parents" in self.__dict__:
  557. del self.__dict__["parents"]
  558. self.expired_attributes.update(
  559. [impl.key for impl in self.manager._loader_impls]
  560. )
  561. if self.callables:
  562. # the per state loader callables we can remove here are
  563. # LoadDeferredColumns, which undefers a column at the instance
  564. # level that is mapped with deferred, and LoadLazyAttribute,
  565. # which lazy loads a relationship at the instance level that
  566. # is mapped with "noload" or perhaps "immediateload".
  567. # Before 1.4, only column-based
  568. # attributes could be considered to be "expired", so here they
  569. # were the only ones "unexpired", which means to make them deferred
  570. # again. For the moment, as of 1.4 we also apply the same
  571. # treatment relationships now, that is, an instance level lazy
  572. # loader is reset in the same way as a column loader.
  573. for k in self.expired_attributes.intersection(self.callables):
  574. del self.callables[k]
  575. for k in self.manager._collection_impl_keys.intersection(dict_):
  576. collection = dict_.pop(k)
  577. collection._sa_adapter.invalidated = True
  578. if self._last_known_values:
  579. self._last_known_values.update(
  580. {k: dict_[k] for k in self._last_known_values if k in dict_}
  581. )
  582. for key in self.manager._all_key_set.intersection(dict_):
  583. del dict_[key]
  584. self.manager.dispatch.expire(self, None)
  585. def _expire_attributes(
  586. self,
  587. dict_: _InstanceDict,
  588. attribute_names: Iterable[str],
  589. no_loader: bool = False,
  590. ) -> None:
  591. pending = self.__dict__.get("_pending_mutations", None)
  592. callables = self.callables
  593. for key in attribute_names:
  594. impl = self.manager[key].impl
  595. if impl.accepts_scalar_loader:
  596. if no_loader and (impl.callable_ or key in callables):
  597. continue
  598. self.expired_attributes.add(key)
  599. if callables and key in callables:
  600. del callables[key]
  601. old = dict_.pop(key, NO_VALUE)
  602. if is_collection_impl(impl) and old is not NO_VALUE:
  603. impl._invalidate_collection(old)
  604. lkv = self._last_known_values
  605. if lkv is not None and key in lkv and old is not NO_VALUE:
  606. lkv[key] = old
  607. self.committed_state.pop(key, None)
  608. if pending:
  609. pending.pop(key, None)
  610. self.manager.dispatch.expire(self, attribute_names)
  611. def _load_expired(
  612. self, state: InstanceState[_O], passive: PassiveFlag
  613. ) -> LoaderCallableStatus:
  614. """__call__ allows the InstanceState to act as a deferred
  615. callable for loading expired attributes, which is also
  616. serializable (picklable).
  617. """
  618. if not passive & SQL_OK:
  619. return PASSIVE_NO_RESULT
  620. toload = self.expired_attributes.intersection(self.unmodified)
  621. toload = toload.difference(
  622. attr
  623. for attr in toload
  624. if not self.manager[attr].impl.load_on_unexpire
  625. )
  626. self.manager.expired_attribute_loader(self, toload, passive)
  627. # if the loader failed, or this
  628. # instance state didn't have an identity,
  629. # the attributes still might be in the callables
  630. # dict. ensure they are removed.
  631. self.expired_attributes.clear()
  632. return ATTR_WAS_SET
  633. @property
  634. def unmodified(self) -> Set[str]:
  635. """Return the set of keys which have no uncommitted changes"""
  636. return set(self.manager).difference(self.committed_state)
  637. def unmodified_intersection(self, keys: Iterable[str]) -> Set[str]:
  638. """Return self.unmodified.intersection(keys)."""
  639. return (
  640. set(keys)
  641. .intersection(self.manager)
  642. .difference(self.committed_state)
  643. )
  644. @property
  645. def unloaded(self) -> Set[str]:
  646. """Return the set of keys which do not have a loaded value.
  647. This includes expired attributes and any other attribute that was never
  648. populated or modified.
  649. """
  650. return (
  651. set(self.manager)
  652. .difference(self.committed_state)
  653. .difference(self.dict)
  654. )
  655. @property
  656. @util.deprecated(
  657. "2.0",
  658. "The :attr:`.InstanceState.unloaded_expirable` attribute is "
  659. "deprecated. Please use :attr:`.InstanceState.unloaded`.",
  660. )
  661. def unloaded_expirable(self) -> Set[str]:
  662. """Synonymous with :attr:`.InstanceState.unloaded`.
  663. This attribute was added as an implementation-specific detail at some
  664. point and should be considered to be private.
  665. """
  666. return self.unloaded
  667. @property
  668. def _unloaded_non_object(self) -> Set[str]:
  669. return self.unloaded.intersection(
  670. attr
  671. for attr in self.manager
  672. if self.manager[attr].impl.accepts_scalar_loader
  673. )
  674. def _modified_event(
  675. self,
  676. dict_: _InstanceDict,
  677. attr: Optional[AttributeImpl],
  678. previous: Any,
  679. collection: bool = False,
  680. is_userland: bool = False,
  681. ) -> None:
  682. if attr:
  683. if not attr.send_modified_events:
  684. return
  685. if is_userland and attr.key not in dict_:
  686. raise sa_exc.InvalidRequestError(
  687. "Can't flag attribute '%s' modified; it's not present in "
  688. "the object state" % attr.key
  689. )
  690. if attr.key not in self.committed_state or is_userland:
  691. if collection:
  692. if TYPE_CHECKING:
  693. assert is_collection_impl(attr)
  694. if previous is NEVER_SET:
  695. if attr.key in dict_:
  696. previous = dict_[attr.key]
  697. if previous not in (None, NO_VALUE, NEVER_SET):
  698. previous = attr.copy(previous)
  699. self.committed_state[attr.key] = previous
  700. lkv = self._last_known_values
  701. if lkv is not None and attr.key in lkv:
  702. lkv[attr.key] = NO_VALUE
  703. # assert self._strong_obj is None or self.modified
  704. if (self.session_id and self._strong_obj is None) or not self.modified:
  705. self.modified = True
  706. instance_dict = self._instance_dict()
  707. if instance_dict:
  708. has_modified = bool(instance_dict._modified)
  709. instance_dict._modified.add(self)
  710. else:
  711. has_modified = False
  712. # only create _strong_obj link if attached
  713. # to a session
  714. inst = self.obj()
  715. if self.session_id:
  716. self._strong_obj = inst
  717. # if identity map already had modified objects,
  718. # assume autobegin already occurred, else check
  719. # for autobegin
  720. if not has_modified:
  721. # inline of autobegin, to ensure session transaction
  722. # snapshot is established
  723. try:
  724. session = _sessions[self.session_id]
  725. except KeyError:
  726. pass
  727. else:
  728. if session._transaction is None:
  729. session._autobegin_t()
  730. if inst is None and attr:
  731. raise orm_exc.ObjectDereferencedError(
  732. "Can't emit change event for attribute '%s' - "
  733. "parent object of type %s has been garbage "
  734. "collected."
  735. % (self.manager[attr.key], base.state_class_str(self))
  736. )
  737. def _commit(self, dict_: _InstanceDict, keys: Iterable[str]) -> None:
  738. """Commit attributes.
  739. This is used by a partial-attribute load operation to mark committed
  740. those attributes which were refreshed from the database.
  741. Attributes marked as "expired" can potentially remain "expired" after
  742. this step if a value was not populated in state.dict.
  743. """
  744. for key in keys:
  745. self.committed_state.pop(key, None)
  746. self.expired = False
  747. self.expired_attributes.difference_update(
  748. set(keys).intersection(dict_)
  749. )
  750. # the per-keys commit removes object-level callables,
  751. # while that of commit_all does not. it's not clear
  752. # if this behavior has a clear rationale, however tests do
  753. # ensure this is what it does.
  754. if self.callables:
  755. for key in (
  756. set(self.callables).intersection(keys).intersection(dict_)
  757. ):
  758. del self.callables[key]
  759. def _commit_all(
  760. self, dict_: _InstanceDict, instance_dict: Optional[IdentityMap] = None
  761. ) -> None:
  762. """commit all attributes unconditionally.
  763. This is used after a flush() or a full load/refresh
  764. to remove all pending state from the instance.
  765. - all attributes are marked as "committed"
  766. - the "strong dirty reference" is removed
  767. - the "modified" flag is set to False
  768. - any "expired" markers for scalar attributes loaded are removed.
  769. - lazy load callables for objects / collections *stay*
  770. Attributes marked as "expired" can potentially remain
  771. "expired" after this step if a value was not populated in state.dict.
  772. """
  773. self._commit_all_states([(self, dict_)], instance_dict)
  774. @classmethod
  775. def _commit_all_states(
  776. self,
  777. iter_: Iterable[Tuple[InstanceState[Any], _InstanceDict]],
  778. instance_dict: Optional[IdentityMap] = None,
  779. ) -> None:
  780. """Mass / highly inlined version of commit_all()."""
  781. for state, dict_ in iter_:
  782. state_dict = state.__dict__
  783. state.committed_state.clear()
  784. if "_pending_mutations" in state_dict:
  785. del state_dict["_pending_mutations"]
  786. state.expired_attributes.difference_update(dict_)
  787. if instance_dict and state.modified:
  788. instance_dict._modified.discard(state)
  789. state.modified = state.expired = False
  790. state._strong_obj = None
  791. class AttributeState:
  792. """Provide an inspection interface corresponding
  793. to a particular attribute on a particular mapped object.
  794. The :class:`.AttributeState` object is accessed
  795. via the :attr:`.InstanceState.attrs` collection
  796. of a particular :class:`.InstanceState`::
  797. from sqlalchemy import inspect
  798. insp = inspect(some_mapped_object)
  799. attr_state = insp.attrs.some_attribute
  800. """
  801. __slots__ = ("state", "key")
  802. state: InstanceState[Any]
  803. key: str
  804. def __init__(self, state: InstanceState[Any], key: str):
  805. self.state = state
  806. self.key = key
  807. @property
  808. def loaded_value(self) -> Any:
  809. """The current value of this attribute as loaded from the database.
  810. If the value has not been loaded, or is otherwise not present
  811. in the object's dictionary, returns NO_VALUE.
  812. """
  813. return self.state.dict.get(self.key, NO_VALUE)
  814. @property
  815. def value(self) -> Any:
  816. """Return the value of this attribute.
  817. This operation is equivalent to accessing the object's
  818. attribute directly or via ``getattr()``, and will fire
  819. off any pending loader callables if needed.
  820. """
  821. return self.state.manager[self.key].__get__(
  822. self.state.obj(), self.state.class_
  823. )
  824. @property
  825. def history(self) -> History:
  826. """Return the current **pre-flush** change history for
  827. this attribute, via the :class:`.History` interface.
  828. This method will **not** emit loader callables if the value of the
  829. attribute is unloaded.
  830. .. note::
  831. The attribute history system tracks changes on a **per flush
  832. basis**. Each time the :class:`.Session` is flushed, the history
  833. of each attribute is reset to empty. The :class:`.Session` by
  834. default autoflushes each time a :class:`_query.Query` is invoked.
  835. For
  836. options on how to control this, see :ref:`session_flushing`.
  837. .. seealso::
  838. :meth:`.AttributeState.load_history` - retrieve history
  839. using loader callables if the value is not locally present.
  840. :func:`.attributes.get_history` - underlying function
  841. """
  842. return self.state.get_history(self.key, PASSIVE_NO_INITIALIZE)
  843. def load_history(self) -> History:
  844. """Return the current **pre-flush** change history for
  845. this attribute, via the :class:`.History` interface.
  846. This method **will** emit loader callables if the value of the
  847. attribute is unloaded.
  848. .. note::
  849. The attribute history system tracks changes on a **per flush
  850. basis**. Each time the :class:`.Session` is flushed, the history
  851. of each attribute is reset to empty. The :class:`.Session` by
  852. default autoflushes each time a :class:`_query.Query` is invoked.
  853. For
  854. options on how to control this, see :ref:`session_flushing`.
  855. .. seealso::
  856. :attr:`.AttributeState.history`
  857. :func:`.attributes.get_history` - underlying function
  858. """
  859. return self.state.get_history(self.key, PASSIVE_OFF ^ INIT_OK)
  860. class PendingCollection:
  861. """A writable placeholder for an unloaded collection.
  862. Stores items appended to and removed from a collection that has not yet
  863. been loaded. When the collection is loaded, the changes stored in
  864. PendingCollection are applied to it to produce the final result.
  865. """
  866. __slots__ = ("deleted_items", "added_items")
  867. deleted_items: util.IdentitySet
  868. added_items: util.OrderedIdentitySet
  869. def __init__(self) -> None:
  870. self.deleted_items = util.IdentitySet()
  871. self.added_items = util.OrderedIdentitySet()
  872. def merge_with_history(self, history: History) -> History:
  873. return history._merge(self.added_items, self.deleted_items)
  874. def append(self, value: Any) -> None:
  875. if value in self.deleted_items:
  876. self.deleted_items.remove(value)
  877. else:
  878. self.added_items.add(value)
  879. def remove(self, value: Any) -> None:
  880. if value in self.added_items:
  881. self.added_items.remove(value)
  882. else:
  883. self.deleted_items.add(value)