state.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. # orm/state.py
  2. # Copyright (C) 2005-2017 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: http://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. import weakref
  12. from .. import util
  13. from .. import inspection
  14. from . import exc as orm_exc, interfaces
  15. from .path_registry import PathRegistry
  16. from .base import PASSIVE_NO_RESULT, SQL_OK, NEVER_SET, ATTR_WAS_SET, \
  17. NO_VALUE, PASSIVE_NO_INITIALIZE, INIT_OK, PASSIVE_OFF
  18. from . import base
  19. @inspection._self_inspects
  20. class InstanceState(interfaces.InspectionAttr):
  21. """tracks state information at the instance level.
  22. The :class:`.InstanceState` is a key object used by the
  23. SQLAlchemy ORM in order to track the state of an object;
  24. it is created the moment an object is instantiated, typically
  25. as a result of :term:`instrumentation` which SQLAlchemy applies
  26. to the ``__init__()`` method of the class.
  27. :class:`.InstanceState` is also a semi-public object,
  28. available for runtime inspection as to the state of a
  29. mapped instance, including information such as its current
  30. status within a particular :class:`.Session` and details
  31. about data on individual attributes. The public API
  32. in order to acquire a :class:`.InstanceState` object
  33. is to use the :func:`.inspect` system::
  34. >>> from sqlalchemy import inspect
  35. >>> insp = inspect(some_mapped_object)
  36. .. seealso::
  37. :ref:`core_inspection_toplevel`
  38. """
  39. session_id = None
  40. key = None
  41. runid = None
  42. load_options = util.EMPTY_SET
  43. load_path = ()
  44. insert_order = None
  45. _strong_obj = None
  46. modified = False
  47. expired = False
  48. _deleted = False
  49. _load_pending = False
  50. is_instance = True
  51. callables = ()
  52. """A namespace where a per-state loader callable can be associated.
  53. In SQLAlchemy 1.0, this is only used for lazy loaders / deferred
  54. loaders that were set up via query option.
  55. Previously, callables was used also to indicate expired attributes
  56. by storing a link to the InstanceState itself in this dictionary.
  57. This role is now handled by the expired_attributes set.
  58. """
  59. def __init__(self, obj, manager):
  60. self.class_ = obj.__class__
  61. self.manager = manager
  62. self.obj = weakref.ref(obj, self._cleanup)
  63. self.committed_state = {}
  64. self.expired_attributes = set()
  65. expired_attributes = None
  66. """The set of keys which are 'expired' to be loaded by
  67. the manager's deferred scalar loader, assuming no pending
  68. changes.
  69. see also the ``unmodified`` collection which is intersected
  70. against this set when a refresh operation occurs."""
  71. @util.memoized_property
  72. def attrs(self):
  73. """Return a namespace representing each attribute on
  74. the mapped object, including its current value
  75. and history.
  76. The returned object is an instance of :class:`.AttributeState`.
  77. This object allows inspection of the current data
  78. within an attribute as well as attribute history
  79. since the last flush.
  80. """
  81. return util.ImmutableProperties(
  82. dict(
  83. (key, AttributeState(self, key))
  84. for key in self.manager
  85. )
  86. )
  87. @property
  88. def transient(self):
  89. """Return true if the object is :term:`transient`.
  90. .. seealso::
  91. :ref:`session_object_states`
  92. """
  93. return self.key is None and \
  94. not self._attached
  95. @property
  96. def pending(self):
  97. """Return true if the object is :term:`pending`.
  98. .. seealso::
  99. :ref:`session_object_states`
  100. """
  101. return self.key is None and \
  102. self._attached
  103. @property
  104. def deleted(self):
  105. """Return true if the object is :term:`deleted`.
  106. An object that is in the deleted state is guaranteed to
  107. not be within the :attr:`.Session.identity_map` of its parent
  108. :class:`.Session`; however if the session's transaction is rolled
  109. back, the object will be restored to the persistent state and
  110. the identity map.
  111. .. note::
  112. The :attr:`.InstanceState.deleted` attribute refers to a specific
  113. state of the object that occurs between the "persistent" and
  114. "detached" states; once the object is :term:`detached`, the
  115. :attr:`.InstanceState.deleted` attribute **no longer returns
  116. True**; in order to detect that a state was deleted, regardless
  117. of whether or not the object is associated with a :class:`.Session`,
  118. use the :attr:`.InstanceState.was_deleted` accessor.
  119. .. versionadded: 1.1
  120. .. seealso::
  121. :ref:`session_object_states`
  122. """
  123. return self.key is not None and \
  124. self._attached and self._deleted
  125. @property
  126. def was_deleted(self):
  127. """Return True if this object is or was previously in the
  128. "deleted" state and has not been reverted to persistent.
  129. This flag returns True once the object was deleted in flush.
  130. When the object is expunged from the session either explicitly
  131. or via transaction commit and enters the "detached" state,
  132. this flag will continue to report True.
  133. .. versionadded:: 1.1 - added a local method form of
  134. :func:`.orm.util.was_deleted`.
  135. .. seealso::
  136. :attr:`.InstanceState.deleted` - refers to the "deleted" state
  137. :func:`.orm.util.was_deleted` - standalone function
  138. :ref:`session_object_states`
  139. """
  140. return self._deleted
  141. @property
  142. def persistent(self):
  143. """Return true if the object is :term:`persistent`.
  144. An object that is in the persistent state is guaranteed to
  145. be within the :attr:`.Session.identity_map` of its parent
  146. :class:`.Session`.
  147. .. versionchanged:: 1.1 The :attr:`.InstanceState.persistent`
  148. accessor no longer returns True for an object that was
  149. "deleted" within a flush; use the :attr:`.InstanceState.deleted`
  150. accessor to detect this state. This allows the "persistent"
  151. state to guarantee membership in the identity map.
  152. .. seealso::
  153. :ref:`session_object_states`
  154. """
  155. return self.key is not None and \
  156. self._attached and not self._deleted
  157. @property
  158. def detached(self):
  159. """Return true if the object is :term:`detached`.
  160. .. seealso::
  161. :ref:`session_object_states`
  162. """
  163. return self.key is not None and not self._attached
  164. @property
  165. @util.dependencies("sqlalchemy.orm.session")
  166. def _attached(self, sessionlib):
  167. return self.session_id is not None and \
  168. self.session_id in sessionlib._sessions
  169. @property
  170. @util.dependencies("sqlalchemy.orm.session")
  171. def session(self, sessionlib):
  172. """Return the owning :class:`.Session` for this instance,
  173. or ``None`` if none available.
  174. Note that the result here can in some cases be *different*
  175. from that of ``obj in session``; an object that's been deleted
  176. will report as not ``in session``, however if the transaction is
  177. still in progress, this attribute will still refer to that session.
  178. Only when the transaction is completed does the object become
  179. fully detached under normal circumstances.
  180. """
  181. return sessionlib._state_session(self)
  182. @property
  183. def object(self):
  184. """Return the mapped object represented by this
  185. :class:`.InstanceState`."""
  186. return self.obj()
  187. @property
  188. def identity(self):
  189. """Return the mapped identity of the mapped object.
  190. This is the primary key identity as persisted by the ORM
  191. which can always be passed directly to
  192. :meth:`.Query.get`.
  193. Returns ``None`` if the object has no primary key identity.
  194. .. note::
  195. An object which is :term:`transient` or :term:`pending`
  196. does **not** have a mapped identity until it is flushed,
  197. even if its attributes include primary key values.
  198. """
  199. if self.key is None:
  200. return None
  201. else:
  202. return self.key[1]
  203. @property
  204. def identity_key(self):
  205. """Return the identity key for the mapped object.
  206. This is the key used to locate the object within
  207. the :attr:`.Session.identity_map` mapping. It contains
  208. the identity as returned by :attr:`.identity` within it.
  209. """
  210. # TODO: just change .key to .identity_key across
  211. # the board ? probably
  212. return self.key
  213. @util.memoized_property
  214. def parents(self):
  215. return {}
  216. @util.memoized_property
  217. def _pending_mutations(self):
  218. return {}
  219. @util.memoized_property
  220. def mapper(self):
  221. """Return the :class:`.Mapper` used for this mapepd object."""
  222. return self.manager.mapper
  223. @property
  224. def has_identity(self):
  225. """Return ``True`` if this object has an identity key.
  226. This should always have the same value as the
  227. expression ``state.persistent or state.detached``.
  228. """
  229. return bool(self.key)
  230. @classmethod
  231. def _detach_states(self, states, session, to_transient=False):
  232. persistent_to_detached = \
  233. session.dispatch.persistent_to_detached or None
  234. deleted_to_detached = \
  235. session.dispatch.deleted_to_detached or None
  236. pending_to_transient = \
  237. session.dispatch.pending_to_transient or None
  238. persistent_to_transient = \
  239. session.dispatch.persistent_to_transient or None
  240. for state in states:
  241. deleted = state._deleted
  242. pending = state.key is None
  243. persistent = not pending and not deleted
  244. state.session_id = None
  245. if to_transient and state.key:
  246. del state.key
  247. if persistent:
  248. if to_transient:
  249. if persistent_to_transient is not None:
  250. obj = state.obj()
  251. if obj is not None:
  252. persistent_to_transient(session, obj)
  253. elif persistent_to_detached is not None:
  254. obj = state.obj()
  255. if obj is not None:
  256. persistent_to_detached(session, obj)
  257. elif deleted and deleted_to_detached is not None:
  258. obj = state.obj()
  259. if obj is not None:
  260. deleted_to_detached(session, obj)
  261. elif pending and pending_to_transient is not None:
  262. obj = state.obj()
  263. if obj is not None:
  264. pending_to_transient(session, obj)
  265. state._strong_obj = None
  266. def _detach(self, session=None):
  267. if session:
  268. InstanceState._detach_states([self], session)
  269. else:
  270. self.session_id = self._strong_obj = None
  271. def _dispose(self):
  272. self._detach()
  273. del self.obj
  274. def _cleanup(self, ref):
  275. """Weakref callback cleanup.
  276. This callable cleans out the state when it is being garbage
  277. collected.
  278. this _cleanup **assumes** that there are no strong refs to us!
  279. Will not work otherwise!
  280. """
  281. instance_dict = self._instance_dict()
  282. if instance_dict is not None:
  283. instance_dict._fast_discard(self)
  284. del self._instance_dict
  285. # we can't possibly be in instance_dict._modified
  286. # b.c. this is weakref cleanup only, that set
  287. # is strong referencing!
  288. # assert self not in instance_dict._modified
  289. self.session_id = self._strong_obj = None
  290. del self.obj
  291. def obj(self):
  292. return None
  293. @property
  294. def dict(self):
  295. """Return the instance dict used by the object.
  296. Under normal circumstances, this is always synonymous
  297. with the ``__dict__`` attribute of the mapped object,
  298. unless an alternative instrumentation system has been
  299. configured.
  300. In the case that the actual object has been garbage
  301. collected, this accessor returns a blank dictionary.
  302. """
  303. o = self.obj()
  304. if o is not None:
  305. return base.instance_dict(o)
  306. else:
  307. return {}
  308. def _initialize_instance(*mixed, **kwargs):
  309. self, instance, args = mixed[0], mixed[1], mixed[2:] # noqa
  310. manager = self.manager
  311. manager.dispatch.init(self, args, kwargs)
  312. try:
  313. return manager.original_init(*mixed[1:], **kwargs)
  314. except:
  315. with util.safe_reraise():
  316. manager.dispatch.init_failure(self, args, kwargs)
  317. def get_history(self, key, passive):
  318. return self.manager[key].impl.get_history(self, self.dict, passive)
  319. def get_impl(self, key):
  320. return self.manager[key].impl
  321. def _get_pending_mutation(self, key):
  322. if key not in self._pending_mutations:
  323. self._pending_mutations[key] = PendingCollection()
  324. return self._pending_mutations[key]
  325. def __getstate__(self):
  326. state_dict = {'instance': self.obj()}
  327. state_dict.update(
  328. (k, self.__dict__[k]) for k in (
  329. 'committed_state', '_pending_mutations', 'modified',
  330. 'expired', 'callables', 'key', 'parents', 'load_options',
  331. 'class_', 'expired_attributes'
  332. ) if k in self.__dict__
  333. )
  334. if self.load_path:
  335. state_dict['load_path'] = self.load_path.serialize()
  336. state_dict['manager'] = self.manager._serialize(self, state_dict)
  337. return state_dict
  338. def __setstate__(self, state_dict):
  339. inst = state_dict['instance']
  340. if inst is not None:
  341. self.obj = weakref.ref(inst, self._cleanup)
  342. self.class_ = inst.__class__
  343. else:
  344. # None being possible here generally new as of 0.7.4
  345. # due to storage of state in "parents". "class_"
  346. # also new.
  347. self.obj = None
  348. self.class_ = state_dict['class_']
  349. self.committed_state = state_dict.get('committed_state', {})
  350. self._pending_mutations = state_dict.get('_pending_mutations', {})
  351. self.parents = state_dict.get('parents', {})
  352. self.modified = state_dict.get('modified', False)
  353. self.expired = state_dict.get('expired', False)
  354. if 'callables' in state_dict:
  355. self.callables = state_dict['callables']
  356. try:
  357. self.expired_attributes = state_dict['expired_attributes']
  358. except KeyError:
  359. self.expired_attributes = set()
  360. # 0.9 and earlier compat
  361. for k in list(self.callables):
  362. if self.callables[k] is self:
  363. self.expired_attributes.add(k)
  364. del self.callables[k]
  365. self.__dict__.update([
  366. (k, state_dict[k]) for k in (
  367. 'key', 'load_options',
  368. ) if k in state_dict
  369. ])
  370. if 'load_path' in state_dict:
  371. self.load_path = PathRegistry.\
  372. deserialize(state_dict['load_path'])
  373. state_dict['manager'](self, inst, state_dict)
  374. def _reset(self, dict_, key):
  375. """Remove the given attribute and any
  376. callables associated with it."""
  377. old = dict_.pop(key, None)
  378. if old is not None and self.manager[key].impl.collection:
  379. self.manager[key].impl._invalidate_collection(old)
  380. self.expired_attributes.discard(key)
  381. if self.callables:
  382. self.callables.pop(key, None)
  383. def _copy_callables(self, from_):
  384. if 'callables' in from_.__dict__:
  385. self.callables = dict(from_.callables)
  386. @classmethod
  387. def _instance_level_callable_processor(cls, manager, fn, key):
  388. impl = manager[key].impl
  389. if impl.collection:
  390. def _set_callable(state, dict_, row):
  391. if 'callables' not in state.__dict__:
  392. state.callables = {}
  393. old = dict_.pop(key, None)
  394. if old is not None:
  395. impl._invalidate_collection(old)
  396. state.callables[key] = fn
  397. else:
  398. def _set_callable(state, dict_, row):
  399. if 'callables' not in state.__dict__:
  400. state.callables = {}
  401. state.callables[key] = fn
  402. return _set_callable
  403. def _expire(self, dict_, modified_set):
  404. self.expired = True
  405. if self.modified:
  406. modified_set.discard(self)
  407. self.committed_state.clear()
  408. self.modified = False
  409. self._strong_obj = None
  410. if '_pending_mutations' in self.__dict__:
  411. del self.__dict__['_pending_mutations']
  412. if 'parents' in self.__dict__:
  413. del self.__dict__['parents']
  414. self.expired_attributes.update(
  415. [impl.key for impl in self.manager._scalar_loader_impls
  416. if impl.expire_missing or impl.key in dict_]
  417. )
  418. if self.callables:
  419. for k in self.expired_attributes.intersection(self.callables):
  420. del self.callables[k]
  421. for k in self.manager._collection_impl_keys.intersection(dict_):
  422. collection = dict_.pop(k)
  423. collection._sa_adapter.invalidated = True
  424. for key in self.manager._all_key_set.intersection(dict_):
  425. del dict_[key]
  426. self.manager.dispatch.expire(self, None)
  427. def _expire_attributes(self, dict_, attribute_names, no_loader=False):
  428. pending = self.__dict__.get('_pending_mutations', None)
  429. callables = self.callables
  430. for key in attribute_names:
  431. impl = self.manager[key].impl
  432. if impl.accepts_scalar_loader:
  433. if no_loader and (
  434. impl.callable_ or
  435. key in callables
  436. ):
  437. continue
  438. self.expired_attributes.add(key)
  439. if callables and key in callables:
  440. del callables[key]
  441. old = dict_.pop(key, None)
  442. if impl.collection and old is not None:
  443. impl._invalidate_collection(old)
  444. self.committed_state.pop(key, None)
  445. if pending:
  446. pending.pop(key, None)
  447. self.manager.dispatch.expire(self, attribute_names)
  448. def _load_expired(self, state, passive):
  449. """__call__ allows the InstanceState to act as a deferred
  450. callable for loading expired attributes, which is also
  451. serializable (picklable).
  452. """
  453. if not passive & SQL_OK:
  454. return PASSIVE_NO_RESULT
  455. toload = self.expired_attributes.\
  456. intersection(self.unmodified)
  457. self.manager.deferred_scalar_loader(self, toload)
  458. # if the loader failed, or this
  459. # instance state didn't have an identity,
  460. # the attributes still might be in the callables
  461. # dict. ensure they are removed.
  462. self.expired_attributes.clear()
  463. return ATTR_WAS_SET
  464. @property
  465. def unmodified(self):
  466. """Return the set of keys which have no uncommitted changes"""
  467. return set(self.manager).difference(self.committed_state)
  468. def unmodified_intersection(self, keys):
  469. """Return self.unmodified.intersection(keys)."""
  470. return set(keys).intersection(self.manager).\
  471. difference(self.committed_state)
  472. @property
  473. def unloaded(self):
  474. """Return the set of keys which do not have a loaded value.
  475. This includes expired attributes and any other attribute that
  476. was never populated or modified.
  477. """
  478. return set(self.manager).\
  479. difference(self.committed_state).\
  480. difference(self.dict)
  481. @property
  482. def _unloaded_non_object(self):
  483. return self.unloaded.intersection(
  484. attr for attr in self.manager
  485. if self.manager[attr].impl.accepts_scalar_loader
  486. )
  487. def _instance_dict(self):
  488. return None
  489. def _modified_event(
  490. self, dict_, attr, previous, collection=False, force=False):
  491. if not attr.send_modified_events:
  492. return
  493. if attr.key not in self.committed_state or force:
  494. if collection:
  495. if previous is NEVER_SET:
  496. if attr.key in dict_:
  497. previous = dict_[attr.key]
  498. if previous not in (None, NO_VALUE, NEVER_SET):
  499. previous = attr.copy(previous)
  500. self.committed_state[attr.key] = previous
  501. # assert self._strong_obj is None or self.modified
  502. if (self.session_id and self._strong_obj is None) \
  503. or not self.modified:
  504. self.modified = True
  505. instance_dict = self._instance_dict()
  506. if instance_dict:
  507. instance_dict._modified.add(self)
  508. # only create _strong_obj link if attached
  509. # to a session
  510. inst = self.obj()
  511. if self.session_id:
  512. self._strong_obj = inst
  513. if inst is None:
  514. raise orm_exc.ObjectDereferencedError(
  515. "Can't emit change event for attribute '%s' - "
  516. "parent object of type %s has been garbage "
  517. "collected."
  518. % (
  519. self.manager[attr.key],
  520. base.state_class_str(self)
  521. ))
  522. def _commit(self, dict_, keys):
  523. """Commit attributes.
  524. This is used by a partial-attribute load operation to mark committed
  525. those attributes which were refreshed from the database.
  526. Attributes marked as "expired" can potentially remain "expired" after
  527. this step if a value was not populated in state.dict.
  528. """
  529. for key in keys:
  530. self.committed_state.pop(key, None)
  531. self.expired = False
  532. self.expired_attributes.difference_update(
  533. set(keys).intersection(dict_))
  534. # the per-keys commit removes object-level callables,
  535. # while that of commit_all does not. it's not clear
  536. # if this behavior has a clear rationale, however tests do
  537. # ensure this is what it does.
  538. if self.callables:
  539. for key in set(self.callables).\
  540. intersection(keys).\
  541. intersection(dict_):
  542. del self.callables[key]
  543. def _commit_all(self, dict_, instance_dict=None):
  544. """commit all attributes unconditionally.
  545. This is used after a flush() or a full load/refresh
  546. to remove all pending state from the instance.
  547. - all attributes are marked as "committed"
  548. - the "strong dirty reference" is removed
  549. - the "modified" flag is set to False
  550. - any "expired" markers for scalar attributes loaded are removed.
  551. - lazy load callables for objects / collections *stay*
  552. Attributes marked as "expired" can potentially remain
  553. "expired" after this step if a value was not populated in state.dict.
  554. """
  555. self._commit_all_states([(self, dict_)], instance_dict)
  556. @classmethod
  557. def _commit_all_states(self, iter, instance_dict=None):
  558. """Mass / highly inlined version of commit_all()."""
  559. for state, dict_ in iter:
  560. state_dict = state.__dict__
  561. state.committed_state.clear()
  562. if '_pending_mutations' in state_dict:
  563. del state_dict['_pending_mutations']
  564. state.expired_attributes.difference_update(dict_)
  565. if instance_dict and state.modified:
  566. instance_dict._modified.discard(state)
  567. state.modified = state.expired = False
  568. state._strong_obj = None
  569. class AttributeState(object):
  570. """Provide an inspection interface corresponding
  571. to a particular attribute on a particular mapped object.
  572. The :class:`.AttributeState` object is accessed
  573. via the :attr:`.InstanceState.attrs` collection
  574. of a particular :class:`.InstanceState`::
  575. from sqlalchemy import inspect
  576. insp = inspect(some_mapped_object)
  577. attr_state = insp.attrs.some_attribute
  578. """
  579. def __init__(self, state, key):
  580. self.state = state
  581. self.key = key
  582. @property
  583. def loaded_value(self):
  584. """The current value of this attribute as loaded from the database.
  585. If the value has not been loaded, or is otherwise not present
  586. in the object's dictionary, returns NO_VALUE.
  587. """
  588. return self.state.dict.get(self.key, NO_VALUE)
  589. @property
  590. def value(self):
  591. """Return the value of this attribute.
  592. This operation is equivalent to accessing the object's
  593. attribute directly or via ``getattr()``, and will fire
  594. off any pending loader callables if needed.
  595. """
  596. return self.state.manager[self.key].__get__(
  597. self.state.obj(), self.state.class_)
  598. @property
  599. def history(self):
  600. """Return the current pre-flush change history for
  601. this attribute, via the :class:`.History` interface.
  602. This method will **not** emit loader callables if the value of the
  603. attribute is unloaded.
  604. .. seealso::
  605. :meth:`.AttributeState.load_history` - retrieve history
  606. using loader callables if the value is not locally present.
  607. :func:`.attributes.get_history` - underlying function
  608. """
  609. return self.state.get_history(self.key,
  610. PASSIVE_NO_INITIALIZE)
  611. def load_history(self):
  612. """Return the current pre-flush change history for
  613. this attribute, via the :class:`.History` interface.
  614. This method **will** emit loader callables if the value of the
  615. attribute is unloaded.
  616. .. seealso::
  617. :attr:`.AttributeState.history`
  618. :func:`.attributes.get_history` - underlying function
  619. .. versionadded:: 0.9.0
  620. """
  621. return self.state.get_history(self.key,
  622. PASSIVE_OFF ^ INIT_OK)
  623. class PendingCollection(object):
  624. """A writable placeholder for an unloaded collection.
  625. Stores items appended to and removed from a collection that has not yet
  626. been loaded. When the collection is loaded, the changes stored in
  627. PendingCollection are applied to it to produce the final result.
  628. """
  629. def __init__(self):
  630. self.deleted_items = util.IdentitySet()
  631. self.added_items = util.OrderedIdentitySet()
  632. def append(self, value):
  633. if value in self.deleted_items:
  634. self.deleted_items.remove(value)
  635. else:
  636. self.added_items.add(value)
  637. def remove(self, value):
  638. if value in self.added_items:
  639. self.added_items.remove(value)
  640. else:
  641. self.deleted_items.add(value)