state.py 37 KB

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