You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1599 lines
49KB

  1. # ext/associationproxy.py
  2. # Copyright (C) 2005-2021 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. """Contain the ``AssociationProxy`` class.
  8. The ``AssociationProxy`` is a Python property object which provides
  9. transparent proxied access to the endpoint of an association object.
  10. See the example ``examples/association/proxied_association.py``.
  11. """
  12. import operator
  13. from .. import exc
  14. from .. import inspect
  15. from .. import orm
  16. from .. import util
  17. from ..orm import collections
  18. from ..orm import interfaces
  19. from ..sql import or_
  20. from ..sql.operators import ColumnOperators
  21. def association_proxy(target_collection, attr, **kw):
  22. r"""Return a Python property implementing a view of a target
  23. attribute which references an attribute on members of the
  24. target.
  25. The returned value is an instance of :class:`.AssociationProxy`.
  26. Implements a Python property representing a relationship as a collection
  27. of simpler values, or a scalar value. The proxied property will mimic
  28. the collection type of the target (list, dict or set), or, in the case of
  29. a one to one relationship, a simple scalar value.
  30. :param target_collection: Name of the attribute we'll proxy to.
  31. This attribute is typically mapped by
  32. :func:`~sqlalchemy.orm.relationship` to link to a target collection, but
  33. can also be a many-to-one or non-scalar relationship.
  34. :param attr: Attribute on the associated instance or instances we'll
  35. proxy for.
  36. For example, given a target collection of [obj1, obj2], a list created
  37. by this proxy property would look like [getattr(obj1, *attr*),
  38. getattr(obj2, *attr*)]
  39. If the relationship is one-to-one or otherwise uselist=False, then
  40. simply: getattr(obj, *attr*)
  41. :param creator: optional.
  42. When new items are added to this proxied collection, new instances of
  43. the class collected by the target collection will be created. For list
  44. and set collections, the target class constructor will be called with
  45. the 'value' for the new instance. For dict types, two arguments are
  46. passed: key and value.
  47. If you want to construct instances differently, supply a *creator*
  48. function that takes arguments as above and returns instances.
  49. For scalar relationships, creator() will be called if the target is None.
  50. If the target is present, set operations are proxied to setattr() on the
  51. associated object.
  52. If you have an associated object with multiple attributes, you may set
  53. up multiple association proxies mapping to different attributes. See
  54. the unit tests for examples, and for examples of how creator() functions
  55. can be used to construct the scalar relationship on-demand in this
  56. situation.
  57. :param \*\*kw: Passes along any other keyword arguments to
  58. :class:`.AssociationProxy`.
  59. """
  60. return AssociationProxy(target_collection, attr, **kw)
  61. ASSOCIATION_PROXY = util.symbol("ASSOCIATION_PROXY")
  62. """Symbol indicating an :class:`.InspectionAttr` that's
  63. of type :class:`.AssociationProxy`.
  64. Is assigned to the :attr:`.InspectionAttr.extension_type`
  65. attribute.
  66. """
  67. class AssociationProxy(interfaces.InspectionAttrInfo):
  68. """A descriptor that presents a read/write view of an object attribute."""
  69. is_attribute = True
  70. extension_type = ASSOCIATION_PROXY
  71. def __init__(
  72. self,
  73. target_collection,
  74. attr,
  75. creator=None,
  76. getset_factory=None,
  77. proxy_factory=None,
  78. proxy_bulk_set=None,
  79. info=None,
  80. cascade_scalar_deletes=False,
  81. ):
  82. """Construct a new :class:`.AssociationProxy`.
  83. The :func:`.association_proxy` function is provided as the usual
  84. entrypoint here, though :class:`.AssociationProxy` can be instantiated
  85. and/or subclassed directly.
  86. :param target_collection: Name of the collection we'll proxy to,
  87. usually created with :func:`_orm.relationship`.
  88. :param attr: Attribute on the collected instances we'll proxy
  89. for. For example, given a target collection of [obj1, obj2], a
  90. list created by this proxy property would look like
  91. [getattr(obj1, attr), getattr(obj2, attr)]
  92. :param creator: Optional. When new items are added to this proxied
  93. collection, new instances of the class collected by the target
  94. collection will be created. For list and set collections, the
  95. target class constructor will be called with the 'value' for the
  96. new instance. For dict types, two arguments are passed:
  97. key and value.
  98. If you want to construct instances differently, supply a 'creator'
  99. function that takes arguments as above and returns instances.
  100. :param cascade_scalar_deletes: when True, indicates that setting
  101. the proxied value to ``None``, or deleting it via ``del``, should
  102. also remove the source object. Only applies to scalar attributes.
  103. Normally, removing the proxied target will not remove the proxy
  104. source, as this object may have other state that is still to be
  105. kept.
  106. .. versionadded:: 1.3
  107. .. seealso::
  108. :ref:`cascade_scalar_deletes` - complete usage example
  109. :param getset_factory: Optional. Proxied attribute access is
  110. automatically handled by routines that get and set values based on
  111. the `attr` argument for this proxy.
  112. If you would like to customize this behavior, you may supply a
  113. `getset_factory` callable that produces a tuple of `getter` and
  114. `setter` functions. The factory is called with two arguments, the
  115. abstract type of the underlying collection and this proxy instance.
  116. :param proxy_factory: Optional. The type of collection to emulate is
  117. determined by sniffing the target collection. If your collection
  118. type can't be determined by duck typing or you'd like to use a
  119. different collection implementation, you may supply a factory
  120. function to produce those collections. Only applicable to
  121. non-scalar relationships.
  122. :param proxy_bulk_set: Optional, use with proxy_factory. See
  123. the _set() method for details.
  124. :param info: optional, will be assigned to
  125. :attr:`.AssociationProxy.info` if present.
  126. .. versionadded:: 1.0.9
  127. """
  128. self.target_collection = target_collection
  129. self.value_attr = attr
  130. self.creator = creator
  131. self.getset_factory = getset_factory
  132. self.proxy_factory = proxy_factory
  133. self.proxy_bulk_set = proxy_bulk_set
  134. self.cascade_scalar_deletes = cascade_scalar_deletes
  135. self.key = "_%s_%s_%s" % (
  136. type(self).__name__,
  137. target_collection,
  138. id(self),
  139. )
  140. if info:
  141. self.info = info
  142. def __get__(self, obj, class_):
  143. if class_ is None:
  144. return self
  145. inst = self._as_instance(class_, obj)
  146. if inst:
  147. return inst.get(obj)
  148. # obj has to be None here
  149. # assert obj is None
  150. return self
  151. def __set__(self, obj, values):
  152. class_ = type(obj)
  153. return self._as_instance(class_, obj).set(obj, values)
  154. def __delete__(self, obj):
  155. class_ = type(obj)
  156. return self._as_instance(class_, obj).delete(obj)
  157. def for_class(self, class_, obj=None):
  158. r"""Return the internal state local to a specific mapped class.
  159. E.g., given a class ``User``::
  160. class User(Base):
  161. # ...
  162. keywords = association_proxy('kws', 'keyword')
  163. If we access this :class:`.AssociationProxy` from
  164. :attr:`_orm.Mapper.all_orm_descriptors`, and we want to view the
  165. target class for this proxy as mapped by ``User``::
  166. inspect(User).all_orm_descriptors["keywords"].for_class(User).target_class
  167. This returns an instance of :class:`.AssociationProxyInstance` that
  168. is specific to the ``User`` class. The :class:`.AssociationProxy`
  169. object remains agnostic of its parent class.
  170. :param class\_: the class that we are returning state for.
  171. :param obj: optional, an instance of the class that is required
  172. if the attribute refers to a polymorphic target, e.g. where we have
  173. to look at the type of the actual destination object to get the
  174. complete path.
  175. .. versionadded:: 1.3 - :class:`.AssociationProxy` no longer stores
  176. any state specific to a particular parent class; the state is now
  177. stored in per-class :class:`.AssociationProxyInstance` objects.
  178. """
  179. return self._as_instance(class_, obj)
  180. def _as_instance(self, class_, obj):
  181. try:
  182. inst = class_.__dict__[self.key + "_inst"]
  183. except KeyError:
  184. inst = None
  185. # avoid exception context
  186. if inst is None:
  187. owner = self._calc_owner(class_)
  188. if owner is not None:
  189. inst = AssociationProxyInstance.for_proxy(self, owner, obj)
  190. setattr(class_, self.key + "_inst", inst)
  191. else:
  192. inst = None
  193. if inst is not None and not inst._is_canonical:
  194. # the AssociationProxyInstance can't be generalized
  195. # since the proxied attribute is not on the targeted
  196. # class, only on subclasses of it, which might be
  197. # different. only return for the specific
  198. # object's current value
  199. return inst._non_canonical_get_for_object(obj)
  200. else:
  201. return inst
  202. def _calc_owner(self, target_cls):
  203. # we might be getting invoked for a subclass
  204. # that is not mapped yet, in some declarative situations.
  205. # save until we are mapped
  206. try:
  207. insp = inspect(target_cls)
  208. except exc.NoInspectionAvailable:
  209. # can't find a mapper, don't set owner. if we are a not-yet-mapped
  210. # subclass, we can also scan through __mro__ to find a mapped
  211. # class, but instead just wait for us to be called again against a
  212. # mapped class normally.
  213. return None
  214. else:
  215. return insp.mapper.class_manager.class_
  216. def _default_getset(self, collection_class):
  217. attr = self.value_attr
  218. _getter = operator.attrgetter(attr)
  219. def getter(target):
  220. return _getter(target) if target is not None else None
  221. if collection_class is dict:
  222. def setter(o, k, v):
  223. setattr(o, attr, v)
  224. else:
  225. def setter(o, v):
  226. setattr(o, attr, v)
  227. return getter, setter
  228. def __repr__(self):
  229. return "AssociationProxy(%r, %r)" % (
  230. self.target_collection,
  231. self.value_attr,
  232. )
  233. class AssociationProxyInstance(object):
  234. """A per-class object that serves class- and object-specific results.
  235. This is used by :class:`.AssociationProxy` when it is invoked
  236. in terms of a specific class or instance of a class, i.e. when it is
  237. used as a regular Python descriptor.
  238. When referring to the :class:`.AssociationProxy` as a normal Python
  239. descriptor, the :class:`.AssociationProxyInstance` is the object that
  240. actually serves the information. Under normal circumstances, its presence
  241. is transparent::
  242. >>> User.keywords.scalar
  243. False
  244. In the special case that the :class:`.AssociationProxy` object is being
  245. accessed directly, in order to get an explicit handle to the
  246. :class:`.AssociationProxyInstance`, use the
  247. :meth:`.AssociationProxy.for_class` method::
  248. proxy_state = inspect(User).all_orm_descriptors["keywords"].for_class(User)
  249. # view if proxy object is scalar or not
  250. >>> proxy_state.scalar
  251. False
  252. .. versionadded:: 1.3
  253. """ # noqa
  254. def __init__(self, parent, owning_class, target_class, value_attr):
  255. self.parent = parent
  256. self.key = parent.key
  257. self.owning_class = owning_class
  258. self.target_collection = parent.target_collection
  259. self.collection_class = None
  260. self.target_class = target_class
  261. self.value_attr = value_attr
  262. target_class = None
  263. """The intermediary class handled by this
  264. :class:`.AssociationProxyInstance`.
  265. Intercepted append/set/assignment events will result
  266. in the generation of new instances of this class.
  267. """
  268. @classmethod
  269. def for_proxy(cls, parent, owning_class, parent_instance):
  270. target_collection = parent.target_collection
  271. value_attr = parent.value_attr
  272. prop = orm.class_mapper(owning_class).get_property(target_collection)
  273. # this was never asserted before but this should be made clear.
  274. if not isinstance(prop, orm.RelationshipProperty):
  275. util.raise_(
  276. NotImplementedError(
  277. "association proxy to a non-relationship "
  278. "intermediary is not supported"
  279. ),
  280. replace_context=None,
  281. )
  282. target_class = prop.mapper.class_
  283. try:
  284. target_assoc = cls._cls_unwrap_target_assoc_proxy(
  285. target_class, value_attr
  286. )
  287. except AttributeError:
  288. # the proxied attribute doesn't exist on the target class;
  289. # return an "ambiguous" instance that will work on a per-object
  290. # basis
  291. return AmbiguousAssociationProxyInstance(
  292. parent, owning_class, target_class, value_attr
  293. )
  294. else:
  295. return cls._construct_for_assoc(
  296. target_assoc, parent, owning_class, target_class, value_attr
  297. )
  298. @classmethod
  299. def _construct_for_assoc(
  300. cls, target_assoc, parent, owning_class, target_class, value_attr
  301. ):
  302. if target_assoc is not None:
  303. return ObjectAssociationProxyInstance(
  304. parent, owning_class, target_class, value_attr
  305. )
  306. attr = getattr(target_class, value_attr)
  307. if not hasattr(attr, "_is_internal_proxy"):
  308. return AmbiguousAssociationProxyInstance(
  309. parent, owning_class, target_class, value_attr
  310. )
  311. is_object = attr._impl_uses_objects
  312. if is_object:
  313. return ObjectAssociationProxyInstance(
  314. parent, owning_class, target_class, value_attr
  315. )
  316. else:
  317. return ColumnAssociationProxyInstance(
  318. parent, owning_class, target_class, value_attr
  319. )
  320. def _get_property(self):
  321. return orm.class_mapper(self.owning_class).get_property(
  322. self.target_collection
  323. )
  324. @property
  325. def _comparator(self):
  326. return self._get_property().comparator
  327. def __clause_element__(self):
  328. raise NotImplementedError(
  329. "The association proxy can't be used as a plain column "
  330. "expression; it only works inside of a comparison expression"
  331. )
  332. @classmethod
  333. def _cls_unwrap_target_assoc_proxy(cls, target_class, value_attr):
  334. attr = getattr(target_class, value_attr)
  335. if isinstance(attr, (AssociationProxy, AssociationProxyInstance)):
  336. return attr
  337. return None
  338. @util.memoized_property
  339. def _unwrap_target_assoc_proxy(self):
  340. return self._cls_unwrap_target_assoc_proxy(
  341. self.target_class, self.value_attr
  342. )
  343. @property
  344. def remote_attr(self):
  345. """The 'remote' class attribute referenced by this
  346. :class:`.AssociationProxyInstance`.
  347. .. seealso::
  348. :attr:`.AssociationProxyInstance.attr`
  349. :attr:`.AssociationProxyInstance.local_attr`
  350. """
  351. return getattr(self.target_class, self.value_attr)
  352. @property
  353. def local_attr(self):
  354. """The 'local' class attribute referenced by this
  355. :class:`.AssociationProxyInstance`.
  356. .. seealso::
  357. :attr:`.AssociationProxyInstance.attr`
  358. :attr:`.AssociationProxyInstance.remote_attr`
  359. """
  360. return getattr(self.owning_class, self.target_collection)
  361. @property
  362. def attr(self):
  363. """Return a tuple of ``(local_attr, remote_attr)``.
  364. This attribute is convenient when specifying a join
  365. using :meth:`_query.Query.join` across two relationships::
  366. sess.query(Parent).join(*Parent.proxied.attr)
  367. .. seealso::
  368. :attr:`.AssociationProxyInstance.local_attr`
  369. :attr:`.AssociationProxyInstance.remote_attr`
  370. """
  371. return (self.local_attr, self.remote_attr)
  372. @util.memoized_property
  373. def scalar(self):
  374. """Return ``True`` if this :class:`.AssociationProxyInstance`
  375. proxies a scalar relationship on the local side."""
  376. scalar = not self._get_property().uselist
  377. if scalar:
  378. self._initialize_scalar_accessors()
  379. return scalar
  380. @util.memoized_property
  381. def _value_is_scalar(self):
  382. return (
  383. not self._get_property()
  384. .mapper.get_property(self.value_attr)
  385. .uselist
  386. )
  387. @property
  388. def _target_is_object(self):
  389. raise NotImplementedError()
  390. def _initialize_scalar_accessors(self):
  391. if self.parent.getset_factory:
  392. get, set_ = self.parent.getset_factory(None, self)
  393. else:
  394. get, set_ = self.parent._default_getset(None)
  395. self._scalar_get, self._scalar_set = get, set_
  396. def _default_getset(self, collection_class):
  397. attr = self.value_attr
  398. _getter = operator.attrgetter(attr)
  399. def getter(target):
  400. return _getter(target) if target is not None else None
  401. if collection_class is dict:
  402. def setter(o, k, v):
  403. return setattr(o, attr, v)
  404. else:
  405. def setter(o, v):
  406. return setattr(o, attr, v)
  407. return getter, setter
  408. @property
  409. def info(self):
  410. return self.parent.info
  411. def get(self, obj):
  412. if obj is None:
  413. return self
  414. if self.scalar:
  415. target = getattr(obj, self.target_collection)
  416. return self._scalar_get(target)
  417. else:
  418. try:
  419. # If the owning instance is reborn (orm session resurrect,
  420. # etc.), refresh the proxy cache.
  421. creator_id, self_id, proxy = getattr(obj, self.key)
  422. except AttributeError:
  423. pass
  424. else:
  425. if id(obj) == creator_id and id(self) == self_id:
  426. assert self.collection_class is not None
  427. return proxy
  428. self.collection_class, proxy = self._new(
  429. _lazy_collection(obj, self.target_collection)
  430. )
  431. setattr(obj, self.key, (id(obj), id(self), proxy))
  432. return proxy
  433. def set(self, obj, values):
  434. if self.scalar:
  435. creator = (
  436. self.parent.creator
  437. if self.parent.creator
  438. else self.target_class
  439. )
  440. target = getattr(obj, self.target_collection)
  441. if target is None:
  442. if values is None:
  443. return
  444. setattr(obj, self.target_collection, creator(values))
  445. else:
  446. self._scalar_set(target, values)
  447. if values is None and self.parent.cascade_scalar_deletes:
  448. setattr(obj, self.target_collection, None)
  449. else:
  450. proxy = self.get(obj)
  451. assert self.collection_class is not None
  452. if proxy is not values:
  453. proxy._bulk_replace(self, values)
  454. def delete(self, obj):
  455. if self.owning_class is None:
  456. self._calc_owner(obj, None)
  457. if self.scalar:
  458. target = getattr(obj, self.target_collection)
  459. if target is not None:
  460. delattr(target, self.value_attr)
  461. delattr(obj, self.target_collection)
  462. def _new(self, lazy_collection):
  463. creator = (
  464. self.parent.creator if self.parent.creator else self.target_class
  465. )
  466. collection_class = util.duck_type_collection(lazy_collection())
  467. if self.parent.proxy_factory:
  468. return (
  469. collection_class,
  470. self.parent.proxy_factory(
  471. lazy_collection, creator, self.value_attr, self
  472. ),
  473. )
  474. if self.parent.getset_factory:
  475. getter, setter = self.parent.getset_factory(collection_class, self)
  476. else:
  477. getter, setter = self.parent._default_getset(collection_class)
  478. if collection_class is list:
  479. return (
  480. collection_class,
  481. _AssociationList(
  482. lazy_collection, creator, getter, setter, self
  483. ),
  484. )
  485. elif collection_class is dict:
  486. return (
  487. collection_class,
  488. _AssociationDict(
  489. lazy_collection, creator, getter, setter, self
  490. ),
  491. )
  492. elif collection_class is set:
  493. return (
  494. collection_class,
  495. _AssociationSet(
  496. lazy_collection, creator, getter, setter, self
  497. ),
  498. )
  499. else:
  500. raise exc.ArgumentError(
  501. "could not guess which interface to use for "
  502. 'collection_class "%s" backing "%s"; specify a '
  503. "proxy_factory and proxy_bulk_set manually"
  504. % (self.collection_class.__name__, self.target_collection)
  505. )
  506. def _set(self, proxy, values):
  507. if self.parent.proxy_bulk_set:
  508. self.parent.proxy_bulk_set(proxy, values)
  509. elif self.collection_class is list:
  510. proxy.extend(values)
  511. elif self.collection_class is dict:
  512. proxy.update(values)
  513. elif self.collection_class is set:
  514. proxy.update(values)
  515. else:
  516. raise exc.ArgumentError(
  517. "no proxy_bulk_set supplied for custom "
  518. "collection_class implementation"
  519. )
  520. def _inflate(self, proxy):
  521. creator = (
  522. self.parent.creator and self.parent.creator or self.target_class
  523. )
  524. if self.parent.getset_factory:
  525. getter, setter = self.parent.getset_factory(
  526. self.collection_class, self
  527. )
  528. else:
  529. getter, setter = self.parent._default_getset(self.collection_class)
  530. proxy.creator = creator
  531. proxy.getter = getter
  532. proxy.setter = setter
  533. def _criterion_exists(self, criterion=None, **kwargs):
  534. is_has = kwargs.pop("is_has", None)
  535. target_assoc = self._unwrap_target_assoc_proxy
  536. if target_assoc is not None:
  537. inner = target_assoc._criterion_exists(
  538. criterion=criterion, **kwargs
  539. )
  540. return self._comparator._criterion_exists(inner)
  541. if self._target_is_object:
  542. prop = getattr(self.target_class, self.value_attr)
  543. value_expr = prop._criterion_exists(criterion, **kwargs)
  544. else:
  545. if kwargs:
  546. raise exc.ArgumentError(
  547. "Can't apply keyword arguments to column-targeted "
  548. "association proxy; use =="
  549. )
  550. elif is_has and criterion is not None:
  551. raise exc.ArgumentError(
  552. "Non-empty has() not allowed for "
  553. "column-targeted association proxy; use =="
  554. )
  555. value_expr = criterion
  556. return self._comparator._criterion_exists(value_expr)
  557. def any(self, criterion=None, **kwargs):
  558. """Produce a proxied 'any' expression using EXISTS.
  559. This expression will be a composed product
  560. using the :meth:`.RelationshipProperty.Comparator.any`
  561. and/or :meth:`.RelationshipProperty.Comparator.has`
  562. operators of the underlying proxied attributes.
  563. """
  564. if self._unwrap_target_assoc_proxy is None and (
  565. self.scalar
  566. and (not self._target_is_object or self._value_is_scalar)
  567. ):
  568. raise exc.InvalidRequestError(
  569. "'any()' not implemented for scalar " "attributes. Use has()."
  570. )
  571. return self._criterion_exists(
  572. criterion=criterion, is_has=False, **kwargs
  573. )
  574. def has(self, criterion=None, **kwargs):
  575. """Produce a proxied 'has' expression using EXISTS.
  576. This expression will be a composed product
  577. using the :meth:`.RelationshipProperty.Comparator.any`
  578. and/or :meth:`.RelationshipProperty.Comparator.has`
  579. operators of the underlying proxied attributes.
  580. """
  581. if self._unwrap_target_assoc_proxy is None and (
  582. not self.scalar
  583. or (self._target_is_object and not self._value_is_scalar)
  584. ):
  585. raise exc.InvalidRequestError(
  586. "'has()' not implemented for collections. " "Use any()."
  587. )
  588. return self._criterion_exists(
  589. criterion=criterion, is_has=True, **kwargs
  590. )
  591. def __repr__(self):
  592. return "%s(%r)" % (self.__class__.__name__, self.parent)
  593. class AmbiguousAssociationProxyInstance(AssociationProxyInstance):
  594. """an :class:`.AssociationProxyInstance` where we cannot determine
  595. the type of target object.
  596. """
  597. _is_canonical = False
  598. def _ambiguous(self):
  599. raise AttributeError(
  600. "Association proxy %s.%s refers to an attribute '%s' that is not "
  601. "directly mapped on class %s; therefore this operation cannot "
  602. "proceed since we don't know what type of object is referred "
  603. "towards"
  604. % (
  605. self.owning_class.__name__,
  606. self.target_collection,
  607. self.value_attr,
  608. self.target_class,
  609. )
  610. )
  611. def get(self, obj):
  612. if obj is None:
  613. return self
  614. else:
  615. return super(AmbiguousAssociationProxyInstance, self).get(obj)
  616. def __eq__(self, obj):
  617. self._ambiguous()
  618. def __ne__(self, obj):
  619. self._ambiguous()
  620. def any(self, criterion=None, **kwargs):
  621. self._ambiguous()
  622. def has(self, criterion=None, **kwargs):
  623. self._ambiguous()
  624. @util.memoized_property
  625. def _lookup_cache(self):
  626. # mapping of <subclass>->AssociationProxyInstance.
  627. # e.g. proxy is A-> A.b -> B -> B.b_attr, but B.b_attr doesn't exist;
  628. # only B1(B) and B2(B) have "b_attr", keys in here would be B1, B2
  629. return {}
  630. def _non_canonical_get_for_object(self, parent_instance):
  631. if parent_instance is not None:
  632. actual_obj = getattr(parent_instance, self.target_collection)
  633. if actual_obj is not None:
  634. try:
  635. insp = inspect(actual_obj)
  636. except exc.NoInspectionAvailable:
  637. pass
  638. else:
  639. mapper = insp.mapper
  640. instance_class = mapper.class_
  641. if instance_class not in self._lookup_cache:
  642. self._populate_cache(instance_class, mapper)
  643. try:
  644. return self._lookup_cache[instance_class]
  645. except KeyError:
  646. pass
  647. # no object or ambiguous object given, so return "self", which
  648. # is a proxy with generally only instance-level functionality
  649. return self
  650. def _populate_cache(self, instance_class, mapper):
  651. prop = orm.class_mapper(self.owning_class).get_property(
  652. self.target_collection
  653. )
  654. if mapper.isa(prop.mapper):
  655. target_class = instance_class
  656. try:
  657. target_assoc = self._cls_unwrap_target_assoc_proxy(
  658. target_class, self.value_attr
  659. )
  660. except AttributeError:
  661. pass
  662. else:
  663. self._lookup_cache[instance_class] = self._construct_for_assoc(
  664. target_assoc,
  665. self.parent,
  666. self.owning_class,
  667. target_class,
  668. self.value_attr,
  669. )
  670. class ObjectAssociationProxyInstance(AssociationProxyInstance):
  671. """an :class:`.AssociationProxyInstance` that has an object as a target."""
  672. _target_is_object = True
  673. _is_canonical = True
  674. def contains(self, obj):
  675. """Produce a proxied 'contains' expression using EXISTS.
  676. This expression will be a composed product
  677. using the :meth:`.RelationshipProperty.Comparator.any`,
  678. :meth:`.RelationshipProperty.Comparator.has`,
  679. and/or :meth:`.RelationshipProperty.Comparator.contains`
  680. operators of the underlying proxied attributes.
  681. """
  682. target_assoc = self._unwrap_target_assoc_proxy
  683. if target_assoc is not None:
  684. return self._comparator._criterion_exists(
  685. target_assoc.contains(obj)
  686. if not target_assoc.scalar
  687. else target_assoc == obj
  688. )
  689. elif (
  690. self._target_is_object
  691. and self.scalar
  692. and not self._value_is_scalar
  693. ):
  694. return self._comparator.has(
  695. getattr(self.target_class, self.value_attr).contains(obj)
  696. )
  697. elif self._target_is_object and self.scalar and self._value_is_scalar:
  698. raise exc.InvalidRequestError(
  699. "contains() doesn't apply to a scalar object endpoint; use =="
  700. )
  701. else:
  702. return self._comparator._criterion_exists(**{self.value_attr: obj})
  703. def __eq__(self, obj):
  704. # note the has() here will fail for collections; eq_()
  705. # is only allowed with a scalar.
  706. if obj is None:
  707. return or_(
  708. self._comparator.has(**{self.value_attr: obj}),
  709. self._comparator == None,
  710. )
  711. else:
  712. return self._comparator.has(**{self.value_attr: obj})
  713. def __ne__(self, obj):
  714. # note the has() here will fail for collections; eq_()
  715. # is only allowed with a scalar.
  716. return self._comparator.has(
  717. getattr(self.target_class, self.value_attr) != obj
  718. )
  719. class ColumnAssociationProxyInstance(
  720. ColumnOperators, AssociationProxyInstance
  721. ):
  722. """an :class:`.AssociationProxyInstance` that has a database column as a
  723. target.
  724. """
  725. _target_is_object = False
  726. _is_canonical = True
  727. def __eq__(self, other):
  728. # special case "is None" to check for no related row as well
  729. expr = self._criterion_exists(
  730. self.remote_attr.operate(operator.eq, other)
  731. )
  732. if other is None:
  733. return or_(expr, self._comparator == None)
  734. else:
  735. return expr
  736. def operate(self, op, *other, **kwargs):
  737. return self._criterion_exists(
  738. self.remote_attr.operate(op, *other, **kwargs)
  739. )
  740. class _lazy_collection(object):
  741. def __init__(self, obj, target):
  742. self.parent = obj
  743. self.target = target
  744. def __call__(self):
  745. return getattr(self.parent, self.target)
  746. def __getstate__(self):
  747. return {"obj": self.parent, "target": self.target}
  748. def __setstate__(self, state):
  749. self.parent = state["obj"]
  750. self.target = state["target"]
  751. class _AssociationCollection(object):
  752. def __init__(self, lazy_collection, creator, getter, setter, parent):
  753. """Constructs an _AssociationCollection.
  754. This will always be a subclass of either _AssociationList,
  755. _AssociationSet, or _AssociationDict.
  756. lazy_collection
  757. A callable returning a list-based collection of entities (usually an
  758. object attribute managed by a SQLAlchemy relationship())
  759. creator
  760. A function that creates new target entities. Given one parameter:
  761. value. This assertion is assumed::
  762. obj = creator(somevalue)
  763. assert getter(obj) == somevalue
  764. getter
  765. A function. Given an associated object, return the 'value'.
  766. setter
  767. A function. Given an associated object and a value, store that
  768. value on the object.
  769. """
  770. self.lazy_collection = lazy_collection
  771. self.creator = creator
  772. self.getter = getter
  773. self.setter = setter
  774. self.parent = parent
  775. col = property(lambda self: self.lazy_collection())
  776. def __len__(self):
  777. return len(self.col)
  778. def __bool__(self):
  779. return bool(self.col)
  780. __nonzero__ = __bool__
  781. def __getstate__(self):
  782. return {"parent": self.parent, "lazy_collection": self.lazy_collection}
  783. def __setstate__(self, state):
  784. self.parent = state["parent"]
  785. self.lazy_collection = state["lazy_collection"]
  786. self.parent._inflate(self)
  787. def _bulk_replace(self, assoc_proxy, values):
  788. self.clear()
  789. assoc_proxy._set(self, values)
  790. class _AssociationList(_AssociationCollection):
  791. """Generic, converting, list-to-list proxy."""
  792. def _create(self, value):
  793. return self.creator(value)
  794. def _get(self, object_):
  795. return self.getter(object_)
  796. def _set(self, object_, value):
  797. return self.setter(object_, value)
  798. def __getitem__(self, index):
  799. if not isinstance(index, slice):
  800. return self._get(self.col[index])
  801. else:
  802. return [self._get(member) for member in self.col[index]]
  803. def __setitem__(self, index, value):
  804. if not isinstance(index, slice):
  805. self._set(self.col[index], value)
  806. else:
  807. if index.stop is None:
  808. stop = len(self)
  809. elif index.stop < 0:
  810. stop = len(self) + index.stop
  811. else:
  812. stop = index.stop
  813. step = index.step or 1
  814. start = index.start or 0
  815. rng = list(range(index.start or 0, stop, step))
  816. if step == 1:
  817. for i in rng:
  818. del self[start]
  819. i = start
  820. for item in value:
  821. self.insert(i, item)
  822. i += 1
  823. else:
  824. if len(value) != len(rng):
  825. raise ValueError(
  826. "attempt to assign sequence of size %s to "
  827. "extended slice of size %s" % (len(value), len(rng))
  828. )
  829. for i, item in zip(rng, value):
  830. self._set(self.col[i], item)
  831. def __delitem__(self, index):
  832. del self.col[index]
  833. def __contains__(self, value):
  834. for member in self.col:
  835. # testlib.pragma exempt:__eq__
  836. if self._get(member) == value:
  837. return True
  838. return False
  839. def __getslice__(self, start, end):
  840. return [self._get(member) for member in self.col[start:end]]
  841. def __setslice__(self, start, end, values):
  842. members = [self._create(v) for v in values]
  843. self.col[start:end] = members
  844. def __delslice__(self, start, end):
  845. del self.col[start:end]
  846. def __iter__(self):
  847. """Iterate over proxied values.
  848. For the actual domain objects, iterate over .col instead or
  849. just use the underlying collection directly from its property
  850. on the parent.
  851. """
  852. for member in self.col:
  853. yield self._get(member)
  854. return
  855. def append(self, value):
  856. col = self.col
  857. item = self._create(value)
  858. col.append(item)
  859. def count(self, value):
  860. return sum(
  861. [
  862. 1
  863. for _ in util.itertools_filter(
  864. lambda v: v == value, iter(self)
  865. )
  866. ]
  867. )
  868. def extend(self, values):
  869. for v in values:
  870. self.append(v)
  871. def insert(self, index, value):
  872. self.col[index:index] = [self._create(value)]
  873. def pop(self, index=-1):
  874. return self.getter(self.col.pop(index))
  875. def remove(self, value):
  876. for i, val in enumerate(self):
  877. if val == value:
  878. del self.col[i]
  879. return
  880. raise ValueError("value not in list")
  881. def reverse(self):
  882. """Not supported, use reversed(mylist)"""
  883. raise NotImplementedError
  884. def sort(self):
  885. """Not supported, use sorted(mylist)"""
  886. raise NotImplementedError
  887. def clear(self):
  888. del self.col[0 : len(self.col)]
  889. def __eq__(self, other):
  890. return list(self) == other
  891. def __ne__(self, other):
  892. return list(self) != other
  893. def __lt__(self, other):
  894. return list(self) < other
  895. def __le__(self, other):
  896. return list(self) <= other
  897. def __gt__(self, other):
  898. return list(self) > other
  899. def __ge__(self, other):
  900. return list(self) >= other
  901. def __cmp__(self, other):
  902. return util.cmp(list(self), other)
  903. def __add__(self, iterable):
  904. try:
  905. other = list(iterable)
  906. except TypeError:
  907. return NotImplemented
  908. return list(self) + other
  909. def __radd__(self, iterable):
  910. try:
  911. other = list(iterable)
  912. except TypeError:
  913. return NotImplemented
  914. return other + list(self)
  915. def __mul__(self, n):
  916. if not isinstance(n, int):
  917. return NotImplemented
  918. return list(self) * n
  919. __rmul__ = __mul__
  920. def __iadd__(self, iterable):
  921. self.extend(iterable)
  922. return self
  923. def __imul__(self, n):
  924. # unlike a regular list *=, proxied __imul__ will generate unique
  925. # backing objects for each copy. *= on proxied lists is a bit of
  926. # a stretch anyhow, and this interpretation of the __imul__ contract
  927. # is more plausibly useful than copying the backing objects.
  928. if not isinstance(n, int):
  929. return NotImplemented
  930. if n == 0:
  931. self.clear()
  932. elif n > 1:
  933. self.extend(list(self) * (n - 1))
  934. return self
  935. def index(self, item, *args):
  936. return list(self).index(item, *args)
  937. def copy(self):
  938. return list(self)
  939. def __repr__(self):
  940. return repr(list(self))
  941. def __hash__(self):
  942. raise TypeError("%s objects are unhashable" % type(self).__name__)
  943. for func_name, func in list(locals().items()):
  944. if (
  945. callable(func)
  946. and func.__name__ == func_name
  947. and not func.__doc__
  948. and hasattr(list, func_name)
  949. ):
  950. func.__doc__ = getattr(list, func_name).__doc__
  951. del func_name, func
  952. _NotProvided = util.symbol("_NotProvided")
  953. class _AssociationDict(_AssociationCollection):
  954. """Generic, converting, dict-to-dict proxy."""
  955. def _create(self, key, value):
  956. return self.creator(key, value)
  957. def _get(self, object_):
  958. return self.getter(object_)
  959. def _set(self, object_, key, value):
  960. return self.setter(object_, key, value)
  961. def __getitem__(self, key):
  962. return self._get(self.col[key])
  963. def __setitem__(self, key, value):
  964. if key in self.col:
  965. self._set(self.col[key], key, value)
  966. else:
  967. self.col[key] = self._create(key, value)
  968. def __delitem__(self, key):
  969. del self.col[key]
  970. def __contains__(self, key):
  971. # testlib.pragma exempt:__hash__
  972. return key in self.col
  973. def has_key(self, key):
  974. # testlib.pragma exempt:__hash__
  975. return key in self.col
  976. def __iter__(self):
  977. return iter(self.col.keys())
  978. def clear(self):
  979. self.col.clear()
  980. def __eq__(self, other):
  981. return dict(self) == other
  982. def __ne__(self, other):
  983. return dict(self) != other
  984. def __lt__(self, other):
  985. return dict(self) < other
  986. def __le__(self, other):
  987. return dict(self) <= other
  988. def __gt__(self, other):
  989. return dict(self) > other
  990. def __ge__(self, other):
  991. return dict(self) >= other
  992. def __cmp__(self, other):
  993. return util.cmp(dict(self), other)
  994. def __repr__(self):
  995. return repr(dict(self.items()))
  996. def get(self, key, default=None):
  997. try:
  998. return self[key]
  999. except KeyError:
  1000. return default
  1001. def setdefault(self, key, default=None):
  1002. if key not in self.col:
  1003. self.col[key] = self._create(key, default)
  1004. return default
  1005. else:
  1006. return self[key]
  1007. def keys(self):
  1008. return self.col.keys()
  1009. if util.py2k:
  1010. def iteritems(self):
  1011. return ((key, self._get(self.col[key])) for key in self.col)
  1012. def itervalues(self):
  1013. return (self._get(self.col[key]) for key in self.col)
  1014. def iterkeys(self):
  1015. return self.col.iterkeys()
  1016. def values(self):
  1017. return [self._get(member) for member in self.col.values()]
  1018. def items(self):
  1019. return [(k, self._get(self.col[k])) for k in self]
  1020. else:
  1021. def items(self):
  1022. return ((key, self._get(self.col[key])) for key in self.col)
  1023. def values(self):
  1024. return (self._get(self.col[key]) for key in self.col)
  1025. def pop(self, key, default=_NotProvided):
  1026. if default is _NotProvided:
  1027. member = self.col.pop(key)
  1028. else:
  1029. member = self.col.pop(key, default)
  1030. return self._get(member)
  1031. def popitem(self):
  1032. item = self.col.popitem()
  1033. return (item[0], self._get(item[1]))
  1034. def update(self, *a, **kw):
  1035. if len(a) > 1:
  1036. raise TypeError(
  1037. "update expected at most 1 arguments, got %i" % len(a)
  1038. )
  1039. elif len(a) == 1:
  1040. seq_or_map = a[0]
  1041. # discern dict from sequence - took the advice from
  1042. # http://www.voidspace.org.uk/python/articles/duck_typing.shtml
  1043. # still not perfect :(
  1044. if hasattr(seq_or_map, "keys"):
  1045. for item in seq_or_map:
  1046. self[item] = seq_or_map[item]
  1047. else:
  1048. try:
  1049. for k, v in seq_or_map:
  1050. self[k] = v
  1051. except ValueError as err:
  1052. util.raise_(
  1053. ValueError(
  1054. "dictionary update sequence "
  1055. "requires 2-element tuples"
  1056. ),
  1057. replace_context=err,
  1058. )
  1059. for key, value in kw:
  1060. self[key] = value
  1061. def _bulk_replace(self, assoc_proxy, values):
  1062. existing = set(self)
  1063. constants = existing.intersection(values or ())
  1064. additions = set(values or ()).difference(constants)
  1065. removals = existing.difference(constants)
  1066. for key, member in values.items() or ():
  1067. if key in additions:
  1068. self[key] = member
  1069. elif key in constants:
  1070. self[key] = member
  1071. for key in removals:
  1072. del self[key]
  1073. def copy(self):
  1074. return dict(self.items())
  1075. def __hash__(self):
  1076. raise TypeError("%s objects are unhashable" % type(self).__name__)
  1077. for func_name, func in list(locals().items()):
  1078. if (
  1079. callable(func)
  1080. and func.__name__ == func_name
  1081. and not func.__doc__
  1082. and hasattr(dict, func_name)
  1083. ):
  1084. func.__doc__ = getattr(dict, func_name).__doc__
  1085. del func_name, func
  1086. class _AssociationSet(_AssociationCollection):
  1087. """Generic, converting, set-to-set proxy."""
  1088. def _create(self, value):
  1089. return self.creator(value)
  1090. def _get(self, object_):
  1091. return self.getter(object_)
  1092. def __len__(self):
  1093. return len(self.col)
  1094. def __bool__(self):
  1095. if self.col:
  1096. return True
  1097. else:
  1098. return False
  1099. __nonzero__ = __bool__
  1100. def __contains__(self, value):
  1101. for member in self.col:
  1102. # testlib.pragma exempt:__eq__
  1103. if self._get(member) == value:
  1104. return True
  1105. return False
  1106. def __iter__(self):
  1107. """Iterate over proxied values.
  1108. For the actual domain objects, iterate over .col instead or just use
  1109. the underlying collection directly from its property on the parent.
  1110. """
  1111. for member in self.col:
  1112. yield self._get(member)
  1113. return
  1114. def add(self, value):
  1115. if value not in self:
  1116. self.col.add(self._create(value))
  1117. # for discard and remove, choosing a more expensive check strategy rather
  1118. # than call self.creator()
  1119. def discard(self, value):
  1120. for member in self.col:
  1121. if self._get(member) == value:
  1122. self.col.discard(member)
  1123. break
  1124. def remove(self, value):
  1125. for member in self.col:
  1126. if self._get(member) == value:
  1127. self.col.discard(member)
  1128. return
  1129. raise KeyError(value)
  1130. def pop(self):
  1131. if not self.col:
  1132. raise KeyError("pop from an empty set")
  1133. member = self.col.pop()
  1134. return self._get(member)
  1135. def update(self, other):
  1136. for value in other:
  1137. self.add(value)
  1138. def _bulk_replace(self, assoc_proxy, values):
  1139. existing = set(self)
  1140. constants = existing.intersection(values or ())
  1141. additions = set(values or ()).difference(constants)
  1142. removals = existing.difference(constants)
  1143. appender = self.add
  1144. remover = self.remove
  1145. for member in values or ():
  1146. if member in additions:
  1147. appender(member)
  1148. elif member in constants:
  1149. appender(member)
  1150. for member in removals:
  1151. remover(member)
  1152. def __ior__(self, other):
  1153. if not collections._set_binops_check_strict(self, other):
  1154. return NotImplemented
  1155. for value in other:
  1156. self.add(value)
  1157. return self
  1158. def _set(self):
  1159. return set(iter(self))
  1160. def union(self, other):
  1161. return set(self).union(other)
  1162. __or__ = union
  1163. def difference(self, other):
  1164. return set(self).difference(other)
  1165. __sub__ = difference
  1166. def difference_update(self, other):
  1167. for value in other:
  1168. self.discard(value)
  1169. def __isub__(self, other):
  1170. if not collections._set_binops_check_strict(self, other):
  1171. return NotImplemented
  1172. for value in other:
  1173. self.discard(value)
  1174. return self
  1175. def intersection(self, other):
  1176. return set(self).intersection(other)
  1177. __and__ = intersection
  1178. def intersection_update(self, other):
  1179. want, have = self.intersection(other), set(self)
  1180. remove, add = have - want, want - have
  1181. for value in remove:
  1182. self.remove(value)
  1183. for value in add:
  1184. self.add(value)
  1185. def __iand__(self, other):
  1186. if not collections._set_binops_check_strict(self, other):
  1187. return NotImplemented
  1188. want, have = self.intersection(other), set(self)
  1189. remove, add = have - want, want - have
  1190. for value in remove:
  1191. self.remove(value)
  1192. for value in add:
  1193. self.add(value)
  1194. return self
  1195. def symmetric_difference(self, other):
  1196. return set(self).symmetric_difference(other)
  1197. __xor__ = symmetric_difference
  1198. def symmetric_difference_update(self, other):
  1199. want, have = self.symmetric_difference(other), set(self)
  1200. remove, add = have - want, want - have
  1201. for value in remove:
  1202. self.remove(value)
  1203. for value in add:
  1204. self.add(value)
  1205. def __ixor__(self, other):
  1206. if not collections._set_binops_check_strict(self, other):
  1207. return NotImplemented
  1208. want, have = self.symmetric_difference(other), set(self)
  1209. remove, add = have - want, want - have
  1210. for value in remove:
  1211. self.remove(value)
  1212. for value in add:
  1213. self.add(value)
  1214. return self
  1215. def issubset(self, other):
  1216. return set(self).issubset(other)
  1217. def issuperset(self, other):
  1218. return set(self).issuperset(other)
  1219. def clear(self):
  1220. self.col.clear()
  1221. def copy(self):
  1222. return set(self)
  1223. def __eq__(self, other):
  1224. return set(self) == other
  1225. def __ne__(self, other):
  1226. return set(self) != other
  1227. def __lt__(self, other):
  1228. return set(self) < other
  1229. def __le__(self, other):
  1230. return set(self) <= other
  1231. def __gt__(self, other):
  1232. return set(self) > other
  1233. def __ge__(self, other):
  1234. return set(self) >= other
  1235. def __repr__(self):
  1236. return repr(set(self))
  1237. def __hash__(self):
  1238. raise TypeError("%s objects are unhashable" % type(self).__name__)
  1239. for func_name, func in list(locals().items()):
  1240. if (
  1241. callable(func)
  1242. and func.__name__ == func_name
  1243. and not func.__doc__
  1244. and hasattr(set, func_name)
  1245. ):
  1246. func.__doc__ = getattr(set, func_name).__doc__
  1247. del func_name, func