PageRenderTime 57ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/SQLAlchemy-0.7.8/lib/sqlalchemy/orm/attributes.py

#
Python | 1395 lines | 1365 code | 5 blank | 25 comment | 4 complexity | a14f326c0760e09e8b4843c6b73ad0aa MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. # orm/attributes.py
  2. # Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file>
  3. #
  4. # This module is part of SQLAlchemy and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. """Defines instrumentation for class attributes and their interaction
  7. with 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 operator
  12. from operator import itemgetter
  13. from sqlalchemy import util, event, exc as sa_exc
  14. from sqlalchemy.orm import interfaces, collections, events, exc as orm_exc
  15. mapperutil = util.importlater("sqlalchemy.orm", "util")
  16. PASSIVE_NO_RESULT = util.symbol('PASSIVE_NO_RESULT')
  17. ATTR_WAS_SET = util.symbol('ATTR_WAS_SET')
  18. ATTR_EMPTY = util.symbol('ATTR_EMPTY')
  19. NO_VALUE = util.symbol('NO_VALUE')
  20. NEVER_SET = util.symbol('NEVER_SET')
  21. PASSIVE_RETURN_NEVER_SET = util.symbol('PASSIVE_RETURN_NEVER_SET',
  22. """Symbol indicating that loader callables can be
  23. fired off, but if no callable is applicable and no value is
  24. present, the attribute should remain non-initialized.
  25. NEVER_SET is returned in this case.
  26. """)
  27. PASSIVE_NO_INITIALIZE = util.symbol('PASSIVE_NO_INITIALIZE',
  28. """Symbol indicating that loader callables should
  29. not be fired off, and a non-initialized attribute
  30. should remain that way.
  31. """)
  32. PASSIVE_NO_FETCH = util.symbol('PASSIVE_NO_FETCH',
  33. """Symbol indicating that loader callables should not emit SQL,
  34. but a value can be fetched from the current session.
  35. Non-initialized attributes should be initialized to an empty value.
  36. """)
  37. PASSIVE_NO_FETCH_RELATED = util.symbol('PASSIVE_NO_FETCH_RELATED',
  38. """Symbol indicating that loader callables should not emit SQL for
  39. loading a related object, but can refresh the attributes of the local
  40. instance in order to locate a related object in the current session.
  41. Non-initialized attributes should be initialized to an empty value.
  42. The unit of work uses this mode to check if history is present
  43. on many-to-one attributes with minimal SQL emitted.
  44. """)
  45. PASSIVE_ONLY_PERSISTENT = util.symbol('PASSIVE_ONLY_PERSISTENT',
  46. """Symbol indicating that loader callables should only fire off for
  47. parent objects which are persistent (i.e., have a database
  48. identity).
  49. Load operations for the "previous" value of an attribute make
  50. use of this flag during change events.
  51. """)
  52. PASSIVE_OFF = util.symbol('PASSIVE_OFF',
  53. """Symbol indicating that loader callables should be executed
  54. normally.
  55. """)
  56. class QueryableAttribute(interfaces.PropComparator):
  57. """Base class for class-bound attributes. """
  58. def __init__(self, class_, key, impl=None,
  59. comparator=None, parententity=None):
  60. self.class_ = class_
  61. self.key = key
  62. self.impl = impl
  63. self.comparator = comparator
  64. self.parententity = parententity
  65. manager = manager_of_class(class_)
  66. # manager is None in the case of AliasedClass
  67. if manager:
  68. # propagate existing event listeners from
  69. # immediate superclass
  70. for base in manager._bases:
  71. if key in base:
  72. self.dispatch._update(base[key].dispatch)
  73. dispatch = event.dispatcher(events.AttributeEvents)
  74. dispatch.dispatch_cls._active_history = False
  75. @util.memoized_property
  76. def _supports_population(self):
  77. return self.impl.supports_population
  78. def get_history(self, instance, passive=PASSIVE_OFF):
  79. return self.impl.get_history(instance_state(instance),
  80. instance_dict(instance), passive)
  81. def __selectable__(self):
  82. # TODO: conditionally attach this method based on clause_element ?
  83. return self
  84. def __clause_element__(self):
  85. return self.comparator.__clause_element__()
  86. def label(self, name):
  87. return self.__clause_element__().label(name)
  88. def operate(self, op, *other, **kwargs):
  89. return op(self.comparator, *other, **kwargs)
  90. def reverse_operate(self, op, other, **kwargs):
  91. return op(other, self.comparator, **kwargs)
  92. def hasparent(self, state, optimistic=False):
  93. return self.impl.hasparent(state, optimistic=optimistic) is not False
  94. def __getattr__(self, key):
  95. try:
  96. return getattr(self.comparator, key)
  97. except AttributeError:
  98. raise AttributeError(
  99. 'Neither %r object nor %r object has an attribute %r' % (
  100. type(self).__name__,
  101. type(self.comparator).__name__,
  102. key)
  103. )
  104. def __str__(self):
  105. return "%s.%s" % (self.class_.__name__, self.key)
  106. @util.memoized_property
  107. def property(self):
  108. return self.comparator.property
  109. class InstrumentedAttribute(QueryableAttribute):
  110. """Class bound instrumented attribute which adds descriptor methods."""
  111. def __set__(self, instance, value):
  112. self.impl.set(instance_state(instance),
  113. instance_dict(instance), value, None)
  114. def __delete__(self, instance):
  115. self.impl.delete(instance_state(instance), instance_dict(instance))
  116. def __get__(self, instance, owner):
  117. if instance is None:
  118. return self
  119. dict_ = instance_dict(instance)
  120. if self._supports_population and self.key in dict_:
  121. return dict_[self.key]
  122. else:
  123. return self.impl.get(instance_state(instance),dict_)
  124. def create_proxied_attribute(descriptor):
  125. """Create an QueryableAttribute / user descriptor hybrid.
  126. Returns a new QueryableAttribute type that delegates descriptor
  127. behavior and getattr() to the given descriptor.
  128. """
  129. # TODO: can move this to descriptor_props if the need for this
  130. # function is removed from ext/hybrid.py
  131. class Proxy(QueryableAttribute):
  132. """Presents the :class:`.QueryableAttribute` interface as a
  133. proxy on top of a Python descriptor / :class:`.PropComparator`
  134. combination.
  135. """
  136. def __init__(self, class_, key, descriptor, comparator,
  137. adapter=None, doc=None):
  138. self.class_ = class_
  139. self.key = key
  140. self.descriptor = descriptor
  141. self._comparator = comparator
  142. self.adapter = adapter
  143. self.__doc__ = doc
  144. @property
  145. def property(self):
  146. return self.comparator.property
  147. @util.memoized_property
  148. def comparator(self):
  149. if util.callable(self._comparator):
  150. self._comparator = self._comparator()
  151. if self.adapter:
  152. self._comparator = self._comparator.adapted(self.adapter)
  153. return self._comparator
  154. def adapted(self, adapter):
  155. """Proxy adapted() for the use case of AliasedClass calling adapted."""
  156. return self.__class__(self.class_, self.key, self.descriptor,
  157. self._comparator,
  158. adapter)
  159. def __get__(self, instance, owner):
  160. if instance is None:
  161. return self
  162. else:
  163. return self.descriptor.__get__(instance, owner)
  164. def __str__(self):
  165. return self.key
  166. def __getattr__(self, attribute):
  167. """Delegate __getattr__ to the original descriptor and/or
  168. comparator."""
  169. try:
  170. return getattr(descriptor, attribute)
  171. except AttributeError:
  172. try:
  173. return getattr(self.comparator, attribute)
  174. except AttributeError:
  175. raise AttributeError(
  176. 'Neither %r object nor %r object has an attribute %r' % (
  177. type(descriptor).__name__,
  178. type(self.comparator).__name__,
  179. attribute)
  180. )
  181. Proxy.__name__ = type(descriptor).__name__ + 'Proxy'
  182. util.monkeypatch_proxied_specials(Proxy, type(descriptor),
  183. name='descriptor',
  184. from_instance=descriptor)
  185. return Proxy
  186. class AttributeImpl(object):
  187. """internal implementation for instrumented attributes."""
  188. def __init__(self, class_, key,
  189. callable_, dispatch, trackparent=False, extension=None,
  190. compare_function=None, active_history=False,
  191. parent_token=None, expire_missing=True,
  192. **kwargs):
  193. """Construct an AttributeImpl.
  194. \class_
  195. associated class
  196. key
  197. string name of the attribute
  198. \callable_
  199. optional function which generates a callable based on a parent
  200. instance, which produces the "default" values for a scalar or
  201. collection attribute when it's first accessed, if not present
  202. already.
  203. trackparent
  204. if True, attempt to track if an instance has a parent attached
  205. to it via this attribute.
  206. extension
  207. a single or list of AttributeExtension object(s) which will
  208. receive set/delete/append/remove/etc. events. Deprecated.
  209. The event package is now used.
  210. compare_function
  211. a function that compares two values which are normally
  212. assignable to this attribute.
  213. active_history
  214. indicates that get_history() should always return the "old" value,
  215. even if it means executing a lazy callable upon attribute change.
  216. parent_token
  217. Usually references the MapperProperty, used as a key for
  218. the hasparent() function to identify an "owning" attribute.
  219. Allows multiple AttributeImpls to all match a single
  220. owner attribute.
  221. expire_missing
  222. if False, don't add an "expiry" callable to this attribute
  223. during state.expire_attributes(None), if no value is present
  224. for this key.
  225. """
  226. self.class_ = class_
  227. self.key = key
  228. self.callable_ = callable_
  229. self.dispatch = dispatch
  230. self.trackparent = trackparent
  231. self.parent_token = parent_token or self
  232. if compare_function is None:
  233. self.is_equal = operator.eq
  234. else:
  235. self.is_equal = compare_function
  236. # TODO: pass in the manager here
  237. # instead of doing a lookup
  238. attr = manager_of_class(class_)[key]
  239. for ext in util.to_list(extension or []):
  240. ext._adapt_listener(attr, ext)
  241. if active_history:
  242. self.dispatch._active_history = True
  243. self.expire_missing = expire_missing
  244. def _get_active_history(self):
  245. """Backwards compat for impl.active_history"""
  246. return self.dispatch._active_history
  247. def _set_active_history(self, value):
  248. self.dispatch._active_history = value
  249. active_history = property(_get_active_history, _set_active_history)
  250. def hasparent(self, state, optimistic=False):
  251. """Return the boolean value of a `hasparent` flag attached to
  252. the given state.
  253. The `optimistic` flag determines what the default return value
  254. should be if no `hasparent` flag can be located.
  255. As this function is used to determine if an instance is an
  256. *orphan*, instances that were loaded from storage should be
  257. assumed to not be orphans, until a True/False value for this
  258. flag is set.
  259. An instance attribute that is loaded by a callable function
  260. will also not have a `hasparent` flag.
  261. """
  262. assert self.trackparent, "This AttributeImpl is not configured to track parents."
  263. return state.parents.get(id(self.parent_token), optimistic) \
  264. is not False
  265. def sethasparent(self, state, parent_state, value):
  266. """Set a boolean flag on the given item corresponding to
  267. whether or not it is attached to a parent object via the
  268. attribute represented by this ``InstrumentedAttribute``.
  269. """
  270. assert self.trackparent, "This AttributeImpl is not configured to track parents."
  271. id_ = id(self.parent_token)
  272. if value:
  273. state.parents[id_] = parent_state
  274. else:
  275. if id_ in state.parents:
  276. last_parent = state.parents[id_]
  277. if last_parent is not False and \
  278. last_parent.key != parent_state.key:
  279. if last_parent.obj() is None:
  280. raise orm_exc.StaleDataError(
  281. "Removing state %s from parent "
  282. "state %s along attribute '%s', "
  283. "but the parent record "
  284. "has gone stale, can't be sure this "
  285. "is the most recent parent." %
  286. (mapperutil.state_str(state),
  287. mapperutil.state_str(parent_state),
  288. self.key))
  289. return
  290. state.parents[id_] = False
  291. def set_callable(self, state, callable_):
  292. """Set a callable function for this attribute on the given object.
  293. This callable will be executed when the attribute is next
  294. accessed, and is assumed to construct part of the instances
  295. previously stored state. When its value or values are loaded,
  296. they will be established as part of the instance's *committed
  297. state*. While *trackparent* information will be assembled for
  298. these instances, attribute-level event handlers will not be
  299. fired.
  300. The callable overrides the class level callable set in the
  301. ``InstrumentedAttribute`` constructor.
  302. """
  303. state.callables[self.key] = callable_
  304. def get_history(self, state, dict_, passive=PASSIVE_OFF):
  305. raise NotImplementedError()
  306. def get_all_pending(self, state, dict_):
  307. """Return a list of tuples of (state, obj)
  308. for all objects in this attribute's current state
  309. + history.
  310. Only applies to object-based attributes.
  311. This is an inlining of existing functionality
  312. which roughly corresponds to:
  313. get_state_history(
  314. state,
  315. key,
  316. passive=PASSIVE_NO_INITIALIZE).sum()
  317. """
  318. raise NotImplementedError()
  319. def initialize(self, state, dict_):
  320. """Initialize the given state's attribute with an empty value."""
  321. dict_[self.key] = None
  322. return None
  323. def get(self, state, dict_, passive=PASSIVE_OFF):
  324. """Retrieve a value from the given object.
  325. If a callable is assembled on this object's attribute, and
  326. passive is False, the callable will be executed and the
  327. resulting value will be set as the new value for this attribute.
  328. """
  329. if self.key in dict_:
  330. return dict_[self.key]
  331. else:
  332. # if history present, don't load
  333. key = self.key
  334. if key not in state.committed_state or \
  335. state.committed_state[key] is NEVER_SET:
  336. if passive is PASSIVE_NO_INITIALIZE:
  337. return PASSIVE_NO_RESULT
  338. if key in state.callables:
  339. callable_ = state.callables[key]
  340. value = callable_(passive)
  341. elif self.callable_:
  342. value = self.callable_(state, passive)
  343. else:
  344. value = ATTR_EMPTY
  345. if value is PASSIVE_NO_RESULT or value is NEVER_SET:
  346. return value
  347. elif value is ATTR_WAS_SET:
  348. try:
  349. return dict_[key]
  350. except KeyError:
  351. # TODO: no test coverage here.
  352. raise KeyError(
  353. "Deferred loader for attribute "
  354. "%r failed to populate "
  355. "correctly" % key)
  356. elif value is not ATTR_EMPTY:
  357. return self.set_committed_value(state, dict_, value)
  358. if passive is PASSIVE_RETURN_NEVER_SET:
  359. return NEVER_SET
  360. else:
  361. # Return a new, empty value
  362. return self.initialize(state, dict_)
  363. def append(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
  364. self.set(state, dict_, value, initiator, passive=passive)
  365. def remove(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
  366. self.set(state, dict_, None, initiator,
  367. passive=passive, check_old=value)
  368. def pop(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
  369. self.set(state, dict_, None, initiator,
  370. passive=passive, check_old=value, pop=True)
  371. def set(self, state, dict_, value, initiator,
  372. passive=PASSIVE_OFF, check_old=None, pop=False):
  373. raise NotImplementedError()
  374. def get_committed_value(self, state, dict_, passive=PASSIVE_OFF):
  375. """return the unchanged value of this attribute"""
  376. if self.key in state.committed_state:
  377. value = state.committed_state[self.key]
  378. if value is NO_VALUE:
  379. return None
  380. else:
  381. return value
  382. else:
  383. return self.get(state, dict_, passive=passive)
  384. def set_committed_value(self, state, dict_, value):
  385. """set an attribute value on the given instance and 'commit' it."""
  386. dict_[self.key] = value
  387. state.commit(dict_, [self.key])
  388. return value
  389. class ScalarAttributeImpl(AttributeImpl):
  390. """represents a scalar value-holding InstrumentedAttribute."""
  391. accepts_scalar_loader = True
  392. uses_objects = False
  393. supports_population = True
  394. def delete(self, state, dict_):
  395. # TODO: catch key errors, convert to attributeerror?
  396. if self.dispatch._active_history:
  397. old = self.get(state, dict_, PASSIVE_RETURN_NEVER_SET)
  398. else:
  399. old = dict_.get(self.key, NO_VALUE)
  400. if self.dispatch.remove:
  401. self.fire_remove_event(state, dict_, old, None)
  402. state.modified_event(dict_, self, old)
  403. del dict_[self.key]
  404. def get_history(self, state, dict_, passive=PASSIVE_OFF):
  405. return History.from_scalar_attribute(
  406. self, state, dict_.get(self.key, NO_VALUE))
  407. def set(self, state, dict_, value, initiator,
  408. passive=PASSIVE_OFF, check_old=None, pop=False):
  409. if initiator and initiator.parent_token is self.parent_token:
  410. return
  411. if self.dispatch._active_history:
  412. old = self.get(state, dict_, PASSIVE_RETURN_NEVER_SET)
  413. else:
  414. old = dict_.get(self.key, NO_VALUE)
  415. if self.dispatch.set:
  416. value = self.fire_replace_event(state, dict_,
  417. value, old, initiator)
  418. state.modified_event(dict_, self, old)
  419. dict_[self.key] = value
  420. def fire_replace_event(self, state, dict_, value, previous, initiator):
  421. for fn in self.dispatch.set:
  422. value = fn(state, value, previous, initiator or self)
  423. return value
  424. def fire_remove_event(self, state, dict_, value, initiator):
  425. for fn in self.dispatch.remove:
  426. fn(state, value, initiator or self)
  427. @property
  428. def type(self):
  429. self.property.columns[0].type
  430. class MutableScalarAttributeImpl(ScalarAttributeImpl):
  431. """represents a scalar value-holding InstrumentedAttribute, which can
  432. detect changes within the value itself.
  433. """
  434. uses_objects = False
  435. supports_population = True
  436. def __init__(self, class_, key, callable_, dispatch,
  437. class_manager, copy_function=None,
  438. compare_function=None, **kwargs):
  439. super(ScalarAttributeImpl, self).__init__(
  440. class_,
  441. key,
  442. callable_, dispatch,
  443. compare_function=compare_function,
  444. **kwargs)
  445. class_manager.mutable_attributes.add(key)
  446. if copy_function is None:
  447. raise sa_exc.ArgumentError(
  448. "MutableScalarAttributeImpl requires a copy function")
  449. self.copy = copy_function
  450. def get_history(self, state, dict_, passive=PASSIVE_OFF):
  451. if not dict_:
  452. v = state.committed_state.get(self.key, NO_VALUE)
  453. else:
  454. v = dict_.get(self.key, NO_VALUE)
  455. return History.from_scalar_attribute(self, state, v)
  456. def check_mutable_modified(self, state, dict_):
  457. a, u, d = self.get_history(state, dict_)
  458. return bool(a or d)
  459. def get(self, state, dict_, passive=PASSIVE_OFF):
  460. if self.key not in state.mutable_dict:
  461. ret = ScalarAttributeImpl.get(self, state, dict_, passive=passive)
  462. if ret is not PASSIVE_NO_RESULT:
  463. state.mutable_dict[self.key] = ret
  464. return ret
  465. else:
  466. return state.mutable_dict[self.key]
  467. def delete(self, state, dict_):
  468. ScalarAttributeImpl.delete(self, state, dict_)
  469. state.mutable_dict.pop(self.key)
  470. def set(self, state, dict_, value, initiator,
  471. passive=PASSIVE_OFF, check_old=None, pop=False):
  472. ScalarAttributeImpl.set(self, state, dict_, value,
  473. initiator, passive, check_old=check_old, pop=pop)
  474. state.mutable_dict[self.key] = value
  475. class ScalarObjectAttributeImpl(ScalarAttributeImpl):
  476. """represents a scalar-holding InstrumentedAttribute,
  477. where the target object is also instrumented.
  478. Adds events to delete/set operations.
  479. """
  480. accepts_scalar_loader = False
  481. uses_objects = True
  482. supports_population = True
  483. def delete(self, state, dict_):
  484. old = self.get(state, dict_)
  485. self.fire_remove_event(state, dict_, old, self)
  486. del dict_[self.key]
  487. def get_history(self, state, dict_, passive=PASSIVE_OFF):
  488. if self.key in dict_:
  489. return History.from_object_attribute(self, state, dict_[self.key])
  490. else:
  491. if passive is PASSIVE_OFF:
  492. passive = PASSIVE_RETURN_NEVER_SET
  493. current = self.get(state, dict_, passive=passive)
  494. if current is PASSIVE_NO_RESULT:
  495. return HISTORY_BLANK
  496. else:
  497. return History.from_object_attribute(self, state, current)
  498. def get_all_pending(self, state, dict_):
  499. if self.key in dict_:
  500. current = dict_[self.key]
  501. if current is not None:
  502. ret = [(instance_state(current), current)]
  503. else:
  504. ret = [(None, None)]
  505. if self.key in state.committed_state:
  506. original = state.committed_state[self.key]
  507. if original not in (NEVER_SET, PASSIVE_NO_RESULT, None) and \
  508. original is not current:
  509. ret.append((instance_state(original), original))
  510. return ret
  511. else:
  512. return []
  513. def set(self, state, dict_, value, initiator,
  514. passive=PASSIVE_OFF, check_old=None, pop=False):
  515. """Set a value on the given InstanceState.
  516. `initiator` is the ``InstrumentedAttribute`` that initiated the
  517. ``set()`` operation and is used to control the depth of a circular
  518. setter operation.
  519. """
  520. if initiator and initiator.parent_token is self.parent_token:
  521. return
  522. if self.dispatch._active_history:
  523. old = self.get(state, dict_, passive=PASSIVE_ONLY_PERSISTENT)
  524. else:
  525. old = self.get(state, dict_, passive=PASSIVE_NO_FETCH)
  526. if check_old is not None and \
  527. old is not PASSIVE_NO_RESULT and \
  528. check_old is not old:
  529. if pop:
  530. return
  531. else:
  532. raise ValueError(
  533. "Object %s not associated with %s on attribute '%s'" % (
  534. mapperutil.instance_str(check_old),
  535. mapperutil.state_str(state),
  536. self.key
  537. ))
  538. value = self.fire_replace_event(state, dict_, value, old, initiator)
  539. dict_[self.key] = value
  540. def fire_remove_event(self, state, dict_, value, initiator):
  541. if self.trackparent and value is not None:
  542. self.sethasparent(instance_state(value), state, False)
  543. for fn in self.dispatch.remove:
  544. fn(state, value, initiator or self)
  545. state.modified_event(dict_, self, value)
  546. def fire_replace_event(self, state, dict_, value, previous, initiator):
  547. if self.trackparent:
  548. if (previous is not value and
  549. previous is not None and
  550. previous is not PASSIVE_NO_RESULT):
  551. self.sethasparent(instance_state(previous), state, False)
  552. for fn in self.dispatch.set:
  553. value = fn(state, value, previous, initiator or self)
  554. state.modified_event(dict_, self, previous)
  555. if self.trackparent:
  556. if value is not None:
  557. self.sethasparent(instance_state(value), state, True)
  558. return value
  559. class CollectionAttributeImpl(AttributeImpl):
  560. """A collection-holding attribute that instruments changes in membership.
  561. Only handles collections of instrumented objects.
  562. InstrumentedCollectionAttribute holds an arbitrary, user-specified
  563. container object (defaulting to a list) and brokers access to the
  564. CollectionAdapter, a "view" onto that object that presents consistent bag
  565. semantics to the orm layer independent of the user data implementation.
  566. """
  567. accepts_scalar_loader = False
  568. uses_objects = True
  569. supports_population = True
  570. def __init__(self, class_, key, callable_, dispatch,
  571. typecallable=None, trackparent=False, extension=None,
  572. copy_function=None, compare_function=None, **kwargs):
  573. super(CollectionAttributeImpl, self).__init__(
  574. class_,
  575. key,
  576. callable_, dispatch,
  577. trackparent=trackparent,
  578. extension=extension,
  579. compare_function=compare_function,
  580. **kwargs)
  581. if copy_function is None:
  582. copy_function = self.__copy
  583. self.copy = copy_function
  584. self.collection_factory = typecallable
  585. def __copy(self, item):
  586. return [y for y in list(collections.collection_adapter(item))]
  587. def get_history(self, state, dict_, passive=PASSIVE_OFF):
  588. current = self.get(state, dict_, passive=passive)
  589. if current is PASSIVE_NO_RESULT:
  590. return HISTORY_BLANK
  591. else:
  592. return History.from_collection(self, state, current)
  593. def get_all_pending(self, state, dict_):
  594. if self.key not in dict_:
  595. return []
  596. current = dict_[self.key]
  597. current = getattr(current, '_sa_adapter')
  598. if self.key in state.committed_state:
  599. original = state.committed_state[self.key]
  600. if original is not NO_VALUE:
  601. current_states = [((c is not None) and
  602. instance_state(c) or None, c)
  603. for c in current]
  604. original_states = [((c is not None) and
  605. instance_state(c) or None, c)
  606. for c in original]
  607. current_set = dict(current_states)
  608. original_set = dict(original_states)
  609. return \
  610. [(s, o) for s, o in current_states if s not in original_set] + \
  611. [(s, o) for s, o in current_states if s in original_set] + \
  612. [(s, o) for s, o in original_states if s not in current_set]
  613. return [(instance_state(o), o) for o in current]
  614. def fire_append_event(self, state, dict_, value, initiator):
  615. for fn in self.dispatch.append:
  616. value = fn(state, value, initiator or self)
  617. state.modified_event(dict_, self, NEVER_SET, True)
  618. if self.trackparent and value is not None:
  619. self.sethasparent(instance_state(value), state, True)
  620. return value
  621. def fire_pre_remove_event(self, state, dict_, initiator):
  622. state.modified_event(dict_, self, NEVER_SET, True)
  623. def fire_remove_event(self, state, dict_, value, initiator):
  624. if self.trackparent and value is not None:
  625. self.sethasparent(instance_state(value), state, False)
  626. for fn in self.dispatch.remove:
  627. fn(state, value, initiator or self)
  628. state.modified_event(dict_, self, NEVER_SET, True)
  629. def delete(self, state, dict_):
  630. if self.key not in dict_:
  631. return
  632. state.modified_event(dict_, self, NEVER_SET, True)
  633. collection = self.get_collection(state, state.dict)
  634. collection.clear_with_event()
  635. # TODO: catch key errors, convert to attributeerror?
  636. del dict_[self.key]
  637. def initialize(self, state, dict_):
  638. """Initialize this attribute with an empty collection."""
  639. _, user_data = self._initialize_collection(state)
  640. dict_[self.key] = user_data
  641. return user_data
  642. def _initialize_collection(self, state):
  643. return state.manager.initialize_collection(
  644. self.key, state, self.collection_factory)
  645. def append(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
  646. if initiator and initiator.parent_token is self.parent_token:
  647. return
  648. collection = self.get_collection(state, dict_, passive=passive)
  649. if collection is PASSIVE_NO_RESULT:
  650. value = self.fire_append_event(state, dict_, value, initiator)
  651. assert self.key not in dict_, \
  652. "Collection was loaded during event handling."
  653. state.get_pending(self.key).append(value)
  654. else:
  655. collection.append_with_event(value, initiator)
  656. def remove(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
  657. if initiator and initiator.parent_token is self.parent_token:
  658. return
  659. collection = self.get_collection(state, state.dict, passive=passive)
  660. if collection is PASSIVE_NO_RESULT:
  661. self.fire_remove_event(state, dict_, value, initiator)
  662. assert self.key not in dict_, \
  663. "Collection was loaded during event handling."
  664. state.get_pending(self.key).remove(value)
  665. else:
  666. collection.remove_with_event(value, initiator)
  667. def pop(self, state, dict_, value, initiator, passive=PASSIVE_OFF):
  668. try:
  669. # TODO: better solution here would be to add
  670. # a "popper" role to collections.py to complement
  671. # "remover".
  672. self.remove(state, dict_, value, initiator, passive=passive)
  673. except (ValueError, KeyError, IndexError):
  674. pass
  675. def set(self, state, dict_, value, initiator,
  676. passive=PASSIVE_OFF, pop=False):
  677. """Set a value on the given object.
  678. `initiator` is the ``InstrumentedAttribute`` that initiated the
  679. ``set()`` operation and is used to control the depth of a circular
  680. setter operation.
  681. """
  682. if initiator and initiator.parent_token is self.parent_token:
  683. return
  684. self._set_iterable(
  685. state, dict_, value,
  686. lambda adapter, i: adapter.adapt_like_to_iterable(i))
  687. def _set_iterable(self, state, dict_, iterable, adapter=None):
  688. """Set a collection value from an iterable of state-bearers.
  689. ``adapter`` is an optional callable invoked with a CollectionAdapter
  690. and the iterable. Should return an iterable of state-bearing
  691. instances suitable for appending via a CollectionAdapter. Can be used
  692. for, e.g., adapting an incoming dictionary into an iterator of values
  693. rather than keys.
  694. """
  695. # pulling a new collection first so that an adaptation exception does
  696. # not trigger a lazy load of the old collection.
  697. new_collection, user_data = self._initialize_collection(state)
  698. if adapter:
  699. new_values = list(adapter(new_collection, iterable))
  700. else:
  701. new_values = list(iterable)
  702. old = self.get(state, dict_, passive=PASSIVE_ONLY_PERSISTENT)
  703. if old is PASSIVE_NO_RESULT:
  704. old = self.initialize(state, dict_)
  705. elif old is iterable:
  706. # ignore re-assignment of the current collection, as happens
  707. # implicitly with in-place operators (foo.collection |= other)
  708. return
  709. # place a copy of "old" in state.committed_state
  710. state.modified_event(dict_, self, old, True)
  711. old_collection = getattr(old, '_sa_adapter')
  712. dict_[self.key] = user_data
  713. collections.bulk_replace(new_values, old_collection, new_collection)
  714. old_collection.unlink(old)
  715. def set_committed_value(self, state, dict_, value):
  716. """Set an attribute value on the given instance and 'commit' it."""
  717. collection, user_data = self._initialize_collection(state)
  718. if value:
  719. collection.append_multiple_without_event(value)
  720. state.dict[self.key] = user_data
  721. state.commit(dict_, [self.key])
  722. if self.key in state.pending:
  723. # pending items exist. issue a modified event,
  724. # add/remove new items.
  725. state.modified_event(dict_, self, user_data, True)
  726. pending = state.pending.pop(self.key)
  727. added = pending.added_items
  728. removed = pending.deleted_items
  729. for item in added:
  730. collection.append_without_event(item)
  731. for item in removed:
  732. collection.remove_without_event(item)
  733. return user_data
  734. def get_collection(self, state, dict_,
  735. user_data=None, passive=PASSIVE_OFF):
  736. """Retrieve the CollectionAdapter associated with the given state.
  737. Creates a new CollectionAdapter if one does not exist.
  738. """
  739. if user_data is None:
  740. user_data = self.get(state, dict_, passive=passive)
  741. if user_data is PASSIVE_NO_RESULT:
  742. return user_data
  743. return getattr(user_data, '_sa_adapter')
  744. def backref_listeners(attribute, key, uselist):
  745. """Apply listeners to synchronize a two-way relationship."""
  746. # use easily recognizable names for stack traces
  747. def emit_backref_from_scalar_set_event(state, child, oldchild, initiator):
  748. if oldchild is child:
  749. return child
  750. if oldchild is not None and oldchild is not PASSIVE_NO_RESULT:
  751. # With lazy=None, there's no guarantee that the full collection is
  752. # present when updating via a backref.
  753. old_state, old_dict = instance_state(oldchild),\
  754. instance_dict(oldchild)
  755. impl = old_state.manager[key].impl
  756. impl.pop(old_state,
  757. old_dict,
  758. state.obj(),
  759. initiator, passive=PASSIVE_NO_FETCH)
  760. if child is not None:
  761. child_state, child_dict = instance_state(child),\
  762. instance_dict(child)
  763. child_state.manager[key].impl.append(
  764. child_state,
  765. child_dict,
  766. state.obj(),
  767. initiator,
  768. passive=PASSIVE_NO_FETCH)
  769. return child
  770. def emit_backref_from_collection_append_event(state, child, initiator):
  771. child_state, child_dict = instance_state(child), \
  772. instance_dict(child)
  773. child_state.manager[key].impl.append(
  774. child_state,
  775. child_dict,
  776. state.obj(),
  777. initiator,
  778. passive=PASSIVE_NO_FETCH)
  779. return child
  780. def emit_backref_from_collection_remove_event(state, child, initiator):
  781. if child is not None:
  782. child_state, child_dict = instance_state(child),\
  783. instance_dict(child)
  784. child_state.manager[key].impl.pop(
  785. child_state,
  786. child_dict,
  787. state.obj(),
  788. initiator,
  789. passive=PASSIVE_NO_FETCH)
  790. if uselist:
  791. event.listen(attribute, "append",
  792. emit_backref_from_collection_append_event,
  793. retval=True, raw=True)
  794. else:
  795. event.listen(attribute, "set",
  796. emit_backref_from_scalar_set_event,
  797. retval=True, raw=True)
  798. # TODO: need coverage in test/orm/ of remove event
  799. event.listen(attribute, "remove",
  800. emit_backref_from_collection_remove_event,
  801. retval=True, raw=True)
  802. _NO_HISTORY = util.symbol('NO_HISTORY')
  803. _NO_STATE_SYMBOLS = frozenset([
  804. id(PASSIVE_NO_RESULT),
  805. id(NO_VALUE),
  806. id(NEVER_SET)])
  807. class History(tuple):
  808. """A 3-tuple of added, unchanged and deleted values,
  809. representing the changes which have occurred on an instrumented
  810. attribute.
  811. Each tuple member is an iterable sequence.
  812. """
  813. __slots__ = ()
  814. added = property(itemgetter(0))
  815. """Return the collection of items added to the attribute (the first tuple
  816. element)."""
  817. unchanged = property(itemgetter(1))
  818. """Return the collection of items that have not changed on the attribute
  819. (the second tuple element)."""
  820. deleted = property(itemgetter(2))
  821. """Return the collection of items that have been removed from the
  822. attribute (the third tuple element)."""
  823. def __new__(cls, added, unchanged, deleted):
  824. return tuple.__new__(cls, (added, unchanged, deleted))
  825. def __nonzero__(self):
  826. return self != HISTORY_BLANK
  827. def empty(self):
  828. """Return True if this :class:`.History` has no changes
  829. and no existing, unchanged state.
  830. """
  831. return not bool(
  832. (self.added or self.deleted)
  833. or self.unchanged and self.unchanged != [None]
  834. )
  835. def sum(self):
  836. """Return a collection of added + unchanged + deleted."""
  837. return (self.added or []) +\
  838. (self.unchanged or []) +\
  839. (self.deleted or [])
  840. def non_deleted(self):
  841. """Return a collection of added + unchanged."""
  842. return (self.added or []) +\
  843. (self.unchanged or [])
  844. def non_added(self):
  845. """Return a collection of unchanged + deleted."""
  846. return (self.unchanged or []) +\
  847. (self.deleted or [])
  848. def has_changes(self):
  849. """Return True if this :class:`.History` has changes."""
  850. return bool(self.added or self.deleted)
  851. def as_state(self):
  852. return History(
  853. [(c is not None)
  854. and instance_state(c) or None
  855. for c in self.added],
  856. [(c is not None)
  857. and instance_state(c) or None
  858. for c in self.unchanged],
  859. [(c is not None)
  860. and instance_state(c) or None
  861. for c in self.deleted],
  862. )
  863. @classmethod
  864. def from_scalar_attribute(cls, attribute, state, current):
  865. original = state.committed_state.get(attribute.key, _NO_HISTORY)
  866. if original is _NO_HISTORY:
  867. if current is NO_VALUE:
  868. return cls((), (), ())
  869. else:
  870. return cls((), [current], ())
  871. # don't let ClauseElement expressions here trip things up
  872. elif attribute.is_equal(current, original) is True:
  873. return cls((), [current], ())
  874. else:
  875. # current convention on native scalars is to not
  876. # include information
  877. # about missing previous value in "deleted", but
  878. # we do include None, which helps in some primary
  879. # key situations
  880. if id(original) in _NO_STATE_SYMBOLS:
  881. deleted = ()
  882. else:
  883. deleted = [original]
  884. if current is NO_VALUE:
  885. return cls((), (), deleted)
  886. else:
  887. return cls([current], (), deleted)
  888. @classmethod
  889. def from_object_attribute(cls, attribute, state, current):
  890. original = state.committed_state.get(attribute.key, _NO_HISTORY)
  891. if original is _NO_HISTORY:
  892. if current is NO_VALUE or current is NEVER_SET:
  893. return cls((), (), ())
  894. else:
  895. return cls((), [current], ())
  896. elif current is original:
  897. return cls((), [current], ())
  898. else:
  899. # current convention on related objects is to not
  900. # include information
  901. # about missing previous value in "deleted", and
  902. # to also not include None - the dependency.py rules
  903. # ignore the None in any case.
  904. if id(original) in _NO_STATE_SYMBOLS or original is None:
  905. deleted = ()
  906. else:
  907. deleted = [original]
  908. if current is NO_VALUE or current is NEVER_SET:
  909. return cls((), (), deleted)
  910. else:
  911. return cls([current], (), deleted)
  912. @classmethod
  913. def from_collection(cls, attribute, state, current):
  914. original = state.committed_state.get(attribute.key, _NO_HISTORY)
  915. current = getattr(current, '_sa_adapter')
  916. if original is NO_VALUE:
  917. return cls(list(current), (), ())
  918. elif original is _NO_HISTORY:
  919. return cls((), list(current), ())
  920. else:
  921. current_states = [((c is not None) and instance_state(c) or None, c)
  922. for c in current
  923. ]
  924. original_states = [((c is not None) and instance_state(c) or None, c)
  925. for c in original
  926. ]
  927. current_set = dict(current_states)
  928. original_set = dict(original_states)
  929. return cls(
  930. [o for s, o in current_states if s not in original_set],
  931. [o for s, o in current_states if s in original_set],
  932. [o for s, o in original_states if s not in current_set]
  933. )
  934. HISTORY_BLANK = History(None, None, None)
  935. def get_history(obj, key, passive=PASSIVE_OFF):
  936. """Return a :class:`.History` record for the given object
  937. and attribute key.
  938. :param obj: an object whose class is instrumented by the
  939. attributes package.
  940. :param key: string attribute name.
  941. :param passive: indicates if the attribute should be
  942. loaded from the database if not already present (:attr:`.PASSIVE_NO_FETCH`), and
  943. if the attribute should be not initialized to a blank value otherwise
  944. (:attr:`.PASSIVE_NO_INITIALIZE`). Default is :attr:`PASSIVE_OFF`.
  945. """
  946. if passive is True:
  947. util.warn_deprecated("Passing True for 'passive' is deprecated. "
  948. "Use attributes.PASSIVE_NO_INITIALIZE")
  949. passive = PASSIVE_NO_INITIALIZE
  950. elif passive is False:
  951. util.warn_deprecated("Passing False for 'passive' is "
  952. "deprecated. Use attributes.PASSIVE_OFF")
  953. passive = PASSIVE_OFF
  954. return get_state_history(instance_state(obj), key, passive)
  955. def get_state_history(state, key, passive=PASSIVE_OFF):
  956. return state.get_history(key, passive)
  957. def has_parent(cls, obj, key, optimistic=False):
  958. """TODO"""
  959. manager = manager_of_class(cls)
  960. state = instance_state(obj)
  961. return manager.has_parent(state, key, optimistic)
  962. def register_attribute(class_, key, **kw):
  963. comparator = kw.pop('comparator', None)
  964. parententity = kw.pop('parententity', None)
  965. doc = kw.pop('doc', None)
  966. desc = register_descriptor(class_, key,
  967. comparator, parententity, doc=doc)
  968. register_attribute_impl(class_, key, **kw)
  969. return desc
  970. def register_attribute_impl(class_, key,
  971. uselist=False, callable_=None,
  972. useobject=False, mutable_scalars=False,
  973. impl_class=None, backref=None, **kw):
  974. manager = manager_of_class(class_)
  975. if uselist:
  976. factory = kw.pop('typecallable', None)
  977. typecallable = manager.instrument_collection_class(
  978. key, factory or list)
  979. else:
  980. typecallable = kw.pop('typecallable', None)
  981. dispatch = manager[key].dispatch
  982. if impl_class:
  983. impl = impl_class(class_, key, typecallable, dispatch, **kw)
  984. elif uselist:
  985. impl = CollectionAttributeImpl(class_, key, callable_, dispatch,
  986. typecallable=typecallable, **kw)
  987. elif useobject:
  988. impl = ScalarObjectAttributeImpl(class_, key, callable_,
  989. dispatch,**kw)
  990. elif mutable_scalars:
  991. impl = MutableScalarAttributeImpl(class_, key, callable_, dispatch,
  992. class_manager=manager, **kw)
  993. else:
  994. impl = ScalarAttributeImpl(class_, key, callable_, dispatch, **kw)
  995. manager[key].impl = impl
  996. if backref:
  997. backref_listeners(manager[key], backref, uselist)
  998. manager.post_configure_attribute(key)
  999. return manager[key]
  1000. def register_descriptor(class_, key, comparator=None,
  1001. parententity=None, doc=None):
  1002. manager = manager_of_class(class_)
  1003. descriptor = InstrumentedAttribute(class_, key, comparator=comparator,
  1004. parententity=parententity)
  1005. descriptor.__doc__ = doc
  1006. manager.instrument_attribute(key, descriptor)
  1007. return descriptor
  1008. def unregister_attribute(class_, key):
  1009. manager_of_class(class_).uninstrument_attribute(key)
  1010. def init_collection(obj, key):
  1011. """Initialize a collection attribute and return the collection adapter.
  1012. This function is used to provide direct access to collection internals
  1013. for a previously unloaded attribute. e.g.::
  1014. collection_adapter = init_collection(someobject, 'elements')
  1015. for elem in values:
  1016. collection_adapter.append_without_event(elem)
  1017. For an easier way to do the above, see
  1018. :func:`~sqlalchemy.orm.attributes.set_committed_value`.
  1019. obj is an instrumented object instance. An InstanceState
  1020. is accepted directly for backwards compatibility but
  1021. this usage is deprecated.
  1022. """
  1023. state = instance_state(obj)
  1024. dict_ = state.dict
  1025. return init_state_collection(state, dict_, key)
  1026. def init_state_collection(state, dict_, key):
  1027. """Initialize a collection attribute and return the collection adapter."""
  1028. attr = state.manager[key].impl
  1029. user_data = attr.initialize(state, dict_)
  1030. return attr.get_collection(state, dict_, user_data)
  1031. def set_committed_value(instance, key, value):
  1032. """Set the value of an attribute with no history events.
  1033. Cancels any previous history present. The value should be
  1034. a scalar value for scalar-holding attributes, or
  1035. an iterable for any collection-holding attribute.
  1036. This is the same underlying method used when a lazy loader
  1037. fires off and loads additional data from the database.
  1038. In particular, this method can be used by application code
  1039. which has loaded additional attributes or collections through
  1040. separate queries, which can then be attached to an instance
  1041. as though it were part of its original loaded state.
  1042. """
  1043. state, dict_ = instance_state(instance), instance_dict(instance)
  1044. state.manager[key].impl.set_committed_value(state, dict_, value)
  1045. def set_attribute(instance, key, value):
  1046. """Set the value of an attribute, firing history events.
  1047. This function may be used regardless of instrumentation
  1048. applied directly to the class, i.e. no descriptors are required.
  1049. Custom attribute management schemes will need to make usage
  1050. of this method to establish attribute state as understood
  1051. by SQLAlchemy.
  1052. """
  1053. state, dict_ = instance_state(instance), instance_dict(instance)
  1054. state.manager[key].impl.set(state, dict_, value, None)
  1055. def get_attribute(instance, key):
  1056. """Get the value of an attribute, firing any callables required.
  1057. This function may be used regardless of instrumentation
  1058. applied directly to the class, i.e. no descriptors are required.
  1059. Custom attribute management schemes will need to make usage
  1060. of this method to make usage of attribute state as understood
  1061. by SQLAlchemy.
  1062. """
  1063. state, dict_ = instance_state(instance), instance_dict(instance)
  1064. return

Large files files are truncated, but you can click here to view the full file