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.

3677 line
139KB

  1. # orm/relationships.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. """Heuristics related to join conditions as used in
  8. :func:`_orm.relationship`.
  9. Provides the :class:`.JoinCondition` object, which encapsulates
  10. SQL annotation and aliasing behavior focused on the `primaryjoin`
  11. and `secondaryjoin` aspects of :func:`_orm.relationship`.
  12. """
  13. from __future__ import absolute_import
  14. import collections
  15. import re
  16. import weakref
  17. from . import attributes
  18. from .base import _is_mapped_class
  19. from .base import state_str
  20. from .interfaces import MANYTOMANY
  21. from .interfaces import MANYTOONE
  22. from .interfaces import ONETOMANY
  23. from .interfaces import PropComparator
  24. from .interfaces import StrategizedProperty
  25. from .util import _orm_annotate
  26. from .util import _orm_deannotate
  27. from .util import CascadeOptions
  28. from .. import exc as sa_exc
  29. from .. import log
  30. from .. import schema
  31. from .. import sql
  32. from .. import util
  33. from ..inspection import inspect
  34. from ..sql import coercions
  35. from ..sql import expression
  36. from ..sql import operators
  37. from ..sql import roles
  38. from ..sql import visitors
  39. from ..sql.util import _deep_deannotate
  40. from ..sql.util import _shallow_annotate
  41. from ..sql.util import adapt_criterion_to_null
  42. from ..sql.util import ClauseAdapter
  43. from ..sql.util import join_condition
  44. from ..sql.util import selectables_overlap
  45. from ..sql.util import visit_binary_product
  46. def remote(expr):
  47. """Annotate a portion of a primaryjoin expression
  48. with a 'remote' annotation.
  49. See the section :ref:`relationship_custom_foreign` for a
  50. description of use.
  51. .. seealso::
  52. :ref:`relationship_custom_foreign`
  53. :func:`.foreign`
  54. """
  55. return _annotate_columns(
  56. coercions.expect(roles.ColumnArgumentRole, expr), {"remote": True}
  57. )
  58. def foreign(expr):
  59. """Annotate a portion of a primaryjoin expression
  60. with a 'foreign' annotation.
  61. See the section :ref:`relationship_custom_foreign` for a
  62. description of use.
  63. .. seealso::
  64. :ref:`relationship_custom_foreign`
  65. :func:`.remote`
  66. """
  67. return _annotate_columns(
  68. coercions.expect(roles.ColumnArgumentRole, expr), {"foreign": True}
  69. )
  70. @log.class_logger
  71. class RelationshipProperty(StrategizedProperty):
  72. """Describes an object property that holds a single item or list
  73. of items that correspond to a related database table.
  74. Public constructor is the :func:`_orm.relationship` function.
  75. .. seealso::
  76. :ref:`relationship_config_toplevel`
  77. """
  78. strategy_wildcard_key = "relationship"
  79. inherit_cache = True
  80. _persistence_only = dict(
  81. passive_deletes=False,
  82. passive_updates=True,
  83. enable_typechecks=True,
  84. active_history=False,
  85. cascade_backrefs=True,
  86. )
  87. _dependency_processor = None
  88. def __init__(
  89. self,
  90. argument,
  91. secondary=None,
  92. primaryjoin=None,
  93. secondaryjoin=None,
  94. foreign_keys=None,
  95. uselist=None,
  96. order_by=False,
  97. backref=None,
  98. back_populates=None,
  99. overlaps=None,
  100. post_update=False,
  101. cascade=False,
  102. viewonly=False,
  103. lazy="select",
  104. collection_class=None,
  105. passive_deletes=_persistence_only["passive_deletes"],
  106. passive_updates=_persistence_only["passive_updates"],
  107. remote_side=None,
  108. enable_typechecks=_persistence_only["enable_typechecks"],
  109. join_depth=None,
  110. comparator_factory=None,
  111. single_parent=False,
  112. innerjoin=False,
  113. distinct_target_key=None,
  114. doc=None,
  115. active_history=_persistence_only["active_history"],
  116. cascade_backrefs=_persistence_only["cascade_backrefs"],
  117. load_on_pending=False,
  118. bake_queries=True,
  119. _local_remote_pairs=None,
  120. query_class=None,
  121. info=None,
  122. omit_join=None,
  123. sync_backref=None,
  124. ):
  125. """Provide a relationship between two mapped classes.
  126. This corresponds to a parent-child or associative table relationship.
  127. The constructed class is an instance of
  128. :class:`.RelationshipProperty`.
  129. A typical :func:`_orm.relationship`, used in a classical mapping::
  130. mapper(Parent, properties={
  131. 'children': relationship(Child)
  132. })
  133. Some arguments accepted by :func:`_orm.relationship`
  134. optionally accept a
  135. callable function, which when called produces the desired value.
  136. The callable is invoked by the parent :class:`_orm.Mapper` at "mapper
  137. initialization" time, which happens only when mappers are first used,
  138. and is assumed to be after all mappings have been constructed. This
  139. can be used to resolve order-of-declaration and other dependency
  140. issues, such as if ``Child`` is declared below ``Parent`` in the same
  141. file::
  142. mapper(Parent, properties={
  143. "children":relationship(lambda: Child,
  144. order_by=lambda: Child.id)
  145. })
  146. When using the :ref:`declarative_toplevel` extension, the Declarative
  147. initializer allows string arguments to be passed to
  148. :func:`_orm.relationship`. These string arguments are converted into
  149. callables that evaluate the string as Python code, using the
  150. Declarative class-registry as a namespace. This allows the lookup of
  151. related classes to be automatic via their string name, and removes the
  152. need for related classes to be imported into the local module space
  153. before the dependent classes have been declared. It is still required
  154. that the modules in which these related classes appear are imported
  155. anywhere in the application at some point before the related mappings
  156. are actually used, else a lookup error will be raised when the
  157. :func:`_orm.relationship`
  158. attempts to resolve the string reference to the
  159. related class. An example of a string- resolved class is as
  160. follows::
  161. from sqlalchemy.ext.declarative import declarative_base
  162. Base = declarative_base()
  163. class Parent(Base):
  164. __tablename__ = 'parent'
  165. id = Column(Integer, primary_key=True)
  166. children = relationship("Child", order_by="Child.id")
  167. .. seealso::
  168. :ref:`relationship_config_toplevel` - Full introductory and
  169. reference documentation for :func:`_orm.relationship`.
  170. :ref:`orm_tutorial_relationship` - ORM tutorial introduction.
  171. :param argument:
  172. A mapped class, or actual :class:`_orm.Mapper` instance,
  173. representing
  174. the target of the relationship.
  175. :paramref:`_orm.relationship.argument`
  176. may also be passed as a callable
  177. function which is evaluated at mapper initialization time, and may
  178. be passed as a string name when using Declarative.
  179. .. warning:: Prior to SQLAlchemy 1.3.16, this value is interpreted
  180. using Python's ``eval()`` function.
  181. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
  182. See :ref:`declarative_relationship_eval` for details on
  183. declarative evaluation of :func:`_orm.relationship` arguments.
  184. .. versionchanged 1.3.16::
  185. The string evaluation of the main "argument" no longer accepts an
  186. open ended Python expression, instead only accepting a string
  187. class name or dotted package-qualified name.
  188. .. seealso::
  189. :ref:`declarative_configuring_relationships` - further detail
  190. on relationship configuration when using Declarative.
  191. :param secondary:
  192. For a many-to-many relationship, specifies the intermediary
  193. table, and is typically an instance of :class:`_schema.Table`.
  194. In less common circumstances, the argument may also be specified
  195. as an :class:`_expression.Alias` construct, or even a
  196. :class:`_expression.Join` construct.
  197. :paramref:`_orm.relationship.secondary` may
  198. also be passed as a callable function which is evaluated at
  199. mapper initialization time. When using Declarative, it may also
  200. be a string argument noting the name of a :class:`_schema.Table`
  201. that is
  202. present in the :class:`_schema.MetaData`
  203. collection associated with the
  204. parent-mapped :class:`_schema.Table`.
  205. .. warning:: When passed as a Python-evaluable string, the
  206. argument is interpreted using Python's ``eval()`` function.
  207. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
  208. See :ref:`declarative_relationship_eval` for details on
  209. declarative evaluation of :func:`_orm.relationship` arguments.
  210. The :paramref:`_orm.relationship.secondary` keyword argument is
  211. typically applied in the case where the intermediary
  212. :class:`_schema.Table`
  213. is not otherwise expressed in any direct class mapping. If the
  214. "secondary" table is also explicitly mapped elsewhere (e.g. as in
  215. :ref:`association_pattern`), one should consider applying the
  216. :paramref:`_orm.relationship.viewonly` flag so that this
  217. :func:`_orm.relationship`
  218. is not used for persistence operations which
  219. may conflict with those of the association object pattern.
  220. .. seealso::
  221. :ref:`relationships_many_to_many` - Reference example of "many
  222. to many".
  223. :ref:`orm_tutorial_many_to_many` - ORM tutorial introduction to
  224. many-to-many relationships.
  225. :ref:`self_referential_many_to_many` - Specifics on using
  226. many-to-many in a self-referential case.
  227. :ref:`declarative_many_to_many` - Additional options when using
  228. Declarative.
  229. :ref:`association_pattern` - an alternative to
  230. :paramref:`_orm.relationship.secondary`
  231. when composing association
  232. table relationships, allowing additional attributes to be
  233. specified on the association table.
  234. :ref:`composite_secondary_join` - a lesser-used pattern which
  235. in some cases can enable complex :func:`_orm.relationship` SQL
  236. conditions to be used.
  237. .. versionadded:: 0.9.2 :paramref:`_orm.relationship.secondary`
  238. works
  239. more effectively when referring to a :class:`_expression.Join`
  240. instance.
  241. :param active_history=False:
  242. When ``True``, indicates that the "previous" value for a
  243. many-to-one reference should be loaded when replaced, if
  244. not already loaded. Normally, history tracking logic for
  245. simple many-to-ones only needs to be aware of the "new"
  246. value in order to perform a flush. This flag is available
  247. for applications that make use of
  248. :func:`.attributes.get_history` which also need to know
  249. the "previous" value of the attribute.
  250. :param backref:
  251. Indicates the string name of a property to be placed on the related
  252. mapper's class that will handle this relationship in the other
  253. direction. The other property will be created automatically
  254. when the mappers are configured. Can also be passed as a
  255. :func:`.backref` object to control the configuration of the
  256. new relationship.
  257. .. seealso::
  258. :ref:`relationships_backref` - Introductory documentation and
  259. examples.
  260. :paramref:`_orm.relationship.back_populates` - alternative form
  261. of backref specification.
  262. :func:`.backref` - allows control over :func:`_orm.relationship`
  263. configuration when using :paramref:`_orm.relationship.backref`.
  264. :param back_populates:
  265. Takes a string name and has the same meaning as
  266. :paramref:`_orm.relationship.backref`, except the complementing
  267. property is **not** created automatically, and instead must be
  268. configured explicitly on the other mapper. The complementing
  269. property should also indicate
  270. :paramref:`_orm.relationship.back_populates` to this relationship to
  271. ensure proper functioning.
  272. .. seealso::
  273. :ref:`relationships_backref` - Introductory documentation and
  274. examples.
  275. :paramref:`_orm.relationship.backref` - alternative form
  276. of backref specification.
  277. :param overlaps:
  278. A string name or comma-delimited set of names of other relationships
  279. on either this mapper, a descendant mapper, or a target mapper with
  280. which this relationship may write to the same foreign keys upon
  281. persistence. The only effect this has is to eliminate the
  282. warning that this relationship will conflict with another upon
  283. persistence. This is used for such relationships that are truly
  284. capable of conflicting with each other on write, but the application
  285. will ensure that no such conflicts occur.
  286. .. versionadded:: 1.4
  287. .. seealso::
  288. :ref:`error_qzyx` - usage example
  289. :param bake_queries=True:
  290. Enable :ref:`lambda caching <engine_lambda_caching>` for loader
  291. strategies, if applicable, which adds a performance gain to the
  292. construction of SQL constructs used by loader strategies, in addition
  293. to the usual SQL statement caching used throughout SQLAlchemy. This
  294. parameter currently applies only to the "lazy" and "selectin" loader
  295. strategies. There is generally no reason to set this parameter to
  296. False.
  297. .. versionchanged:: 1.4 Relationship loaders no longer use the
  298. previous "baked query" system of query caching. The "lazy"
  299. and "selectin" loaders make use of the "lambda cache" system
  300. for the construction of SQL constructs,
  301. as well as the usual SQL caching system that is throughout
  302. SQLAlchemy as of the 1.4 series.
  303. :param cascade:
  304. A comma-separated list of cascade rules which determines how
  305. Session operations should be "cascaded" from parent to child.
  306. This defaults to ``False``, which means the default cascade
  307. should be used - this default cascade is ``"save-update, merge"``.
  308. The available cascades are ``save-update``, ``merge``,
  309. ``expunge``, ``delete``, ``delete-orphan``, and ``refresh-expire``.
  310. An additional option, ``all`` indicates shorthand for
  311. ``"save-update, merge, refresh-expire,
  312. expunge, delete"``, and is often used as in ``"all, delete-orphan"``
  313. to indicate that related objects should follow along with the
  314. parent object in all cases, and be deleted when de-associated.
  315. .. seealso::
  316. :ref:`unitofwork_cascades` - Full detail on each of the available
  317. cascade options.
  318. :ref:`tutorial_delete_cascade` - Tutorial example describing
  319. a delete cascade.
  320. :param cascade_backrefs=True:
  321. A boolean value indicating if the ``save-update`` cascade should
  322. operate along an assignment event intercepted by a backref.
  323. When set to ``False``, the attribute managed by this relationship
  324. will not cascade an incoming transient object into the session of a
  325. persistent parent, if the event is received via backref.
  326. .. deprecated:: 1.4 The
  327. :paramref:`_orm.relationship.cascade_backrefs`
  328. flag will default to False in all cases in SQLAlchemy 2.0.
  329. .. seealso::
  330. :ref:`backref_cascade` - Full discussion and examples on how
  331. the :paramref:`_orm.relationship.cascade_backrefs` option is used.
  332. :param collection_class:
  333. A class or callable that returns a new list-holding object. will
  334. be used in place of a plain list for storing elements.
  335. .. seealso::
  336. :ref:`custom_collections` - Introductory documentation and
  337. examples.
  338. :param comparator_factory:
  339. A class which extends :class:`.RelationshipProperty.Comparator`
  340. which provides custom SQL clause generation for comparison
  341. operations.
  342. .. seealso::
  343. :class:`.PropComparator` - some detail on redefining comparators
  344. at this level.
  345. :ref:`custom_comparators` - Brief intro to this feature.
  346. :param distinct_target_key=None:
  347. Indicate if a "subquery" eager load should apply the DISTINCT
  348. keyword to the innermost SELECT statement. When left as ``None``,
  349. the DISTINCT keyword will be applied in those cases when the target
  350. columns do not comprise the full primary key of the target table.
  351. When set to ``True``, the DISTINCT keyword is applied to the
  352. innermost SELECT unconditionally.
  353. It may be desirable to set this flag to False when the DISTINCT is
  354. reducing performance of the innermost subquery beyond that of what
  355. duplicate innermost rows may be causing.
  356. .. versionchanged:: 0.9.0 -
  357. :paramref:`_orm.relationship.distinct_target_key` now defaults to
  358. ``None``, so that the feature enables itself automatically for
  359. those cases where the innermost query targets a non-unique
  360. key.
  361. .. seealso::
  362. :ref:`loading_toplevel` - includes an introduction to subquery
  363. eager loading.
  364. :param doc:
  365. Docstring which will be applied to the resulting descriptor.
  366. :param foreign_keys:
  367. A list of columns which are to be used as "foreign key"
  368. columns, or columns which refer to the value in a remote
  369. column, within the context of this :func:`_orm.relationship`
  370. object's :paramref:`_orm.relationship.primaryjoin` condition.
  371. That is, if the :paramref:`_orm.relationship.primaryjoin`
  372. condition of this :func:`_orm.relationship` is ``a.id ==
  373. b.a_id``, and the values in ``b.a_id`` are required to be
  374. present in ``a.id``, then the "foreign key" column of this
  375. :func:`_orm.relationship` is ``b.a_id``.
  376. In normal cases, the :paramref:`_orm.relationship.foreign_keys`
  377. parameter is **not required.** :func:`_orm.relationship` will
  378. automatically determine which columns in the
  379. :paramref:`_orm.relationship.primaryjoin` condition are to be
  380. considered "foreign key" columns based on those
  381. :class:`_schema.Column` objects that specify
  382. :class:`_schema.ForeignKey`,
  383. or are otherwise listed as referencing columns in a
  384. :class:`_schema.ForeignKeyConstraint` construct.
  385. :paramref:`_orm.relationship.foreign_keys` is only needed when:
  386. 1. There is more than one way to construct a join from the local
  387. table to the remote table, as there are multiple foreign key
  388. references present. Setting ``foreign_keys`` will limit the
  389. :func:`_orm.relationship`
  390. to consider just those columns specified
  391. here as "foreign".
  392. 2. The :class:`_schema.Table` being mapped does not actually have
  393. :class:`_schema.ForeignKey` or
  394. :class:`_schema.ForeignKeyConstraint`
  395. constructs present, often because the table
  396. was reflected from a database that does not support foreign key
  397. reflection (MySQL MyISAM).
  398. 3. The :paramref:`_orm.relationship.primaryjoin`
  399. argument is used to
  400. construct a non-standard join condition, which makes use of
  401. columns or expressions that do not normally refer to their
  402. "parent" column, such as a join condition expressed by a
  403. complex comparison using a SQL function.
  404. The :func:`_orm.relationship` construct will raise informative
  405. error messages that suggest the use of the
  406. :paramref:`_orm.relationship.foreign_keys` parameter when
  407. presented with an ambiguous condition. In typical cases,
  408. if :func:`_orm.relationship` doesn't raise any exceptions, the
  409. :paramref:`_orm.relationship.foreign_keys` parameter is usually
  410. not needed.
  411. :paramref:`_orm.relationship.foreign_keys` may also be passed as a
  412. callable function which is evaluated at mapper initialization time,
  413. and may be passed as a Python-evaluable string when using
  414. Declarative.
  415. .. warning:: When passed as a Python-evaluable string, the
  416. argument is interpreted using Python's ``eval()`` function.
  417. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
  418. See :ref:`declarative_relationship_eval` for details on
  419. declarative evaluation of :func:`_orm.relationship` arguments.
  420. .. seealso::
  421. :ref:`relationship_foreign_keys`
  422. :ref:`relationship_custom_foreign`
  423. :func:`.foreign` - allows direct annotation of the "foreign"
  424. columns within a :paramref:`_orm.relationship.primaryjoin`
  425. condition.
  426. :param info: Optional data dictionary which will be populated into the
  427. :attr:`.MapperProperty.info` attribute of this object.
  428. :param innerjoin=False:
  429. When ``True``, joined eager loads will use an inner join to join
  430. against related tables instead of an outer join. The purpose
  431. of this option is generally one of performance, as inner joins
  432. generally perform better than outer joins.
  433. This flag can be set to ``True`` when the relationship references an
  434. object via many-to-one using local foreign keys that are not
  435. nullable, or when the reference is one-to-one or a collection that
  436. is guaranteed to have one or at least one entry.
  437. The option supports the same "nested" and "unnested" options as
  438. that of :paramref:`_orm.joinedload.innerjoin`. See that flag
  439. for details on nested / unnested behaviors.
  440. .. seealso::
  441. :paramref:`_orm.joinedload.innerjoin` - the option as specified by
  442. loader option, including detail on nesting behavior.
  443. :ref:`what_kind_of_loading` - Discussion of some details of
  444. various loader options.
  445. :param join_depth:
  446. When non-``None``, an integer value indicating how many levels
  447. deep "eager" loaders should join on a self-referring or cyclical
  448. relationship. The number counts how many times the same Mapper
  449. shall be present in the loading condition along a particular join
  450. branch. When left at its default of ``None``, eager loaders
  451. will stop chaining when they encounter a the same target mapper
  452. which is already higher up in the chain. This option applies
  453. both to joined- and subquery- eager loaders.
  454. .. seealso::
  455. :ref:`self_referential_eager_loading` - Introductory documentation
  456. and examples.
  457. :param lazy='select': specifies
  458. How the related items should be loaded. Default value is
  459. ``select``. Values include:
  460. * ``select`` - items should be loaded lazily when the property is
  461. first accessed, using a separate SELECT statement, or identity map
  462. fetch for simple many-to-one references.
  463. * ``immediate`` - items should be loaded as the parents are loaded,
  464. using a separate SELECT statement, or identity map fetch for
  465. simple many-to-one references.
  466. * ``joined`` - items should be loaded "eagerly" in the same query as
  467. that of the parent, using a JOIN or LEFT OUTER JOIN. Whether
  468. the join is "outer" or not is determined by the
  469. :paramref:`_orm.relationship.innerjoin` parameter.
  470. * ``subquery`` - items should be loaded "eagerly" as the parents are
  471. loaded, using one additional SQL statement, which issues a JOIN to
  472. a subquery of the original statement, for each collection
  473. requested.
  474. * ``selectin`` - items should be loaded "eagerly" as the parents
  475. are loaded, using one or more additional SQL statements, which
  476. issues a JOIN to the immediate parent object, specifying primary
  477. key identifiers using an IN clause.
  478. .. versionadded:: 1.2
  479. * ``noload`` - no loading should occur at any time. This is to
  480. support "write-only" attributes, or attributes which are
  481. populated in some manner specific to the application.
  482. * ``raise`` - lazy loading is disallowed; accessing
  483. the attribute, if its value were not already loaded via eager
  484. loading, will raise an :exc:`~sqlalchemy.exc.InvalidRequestError`.
  485. This strategy can be used when objects are to be detached from
  486. their attached :class:`.Session` after they are loaded.
  487. .. versionadded:: 1.1
  488. * ``raise_on_sql`` - lazy loading that emits SQL is disallowed;
  489. accessing the attribute, if its value were not already loaded via
  490. eager loading, will raise an
  491. :exc:`~sqlalchemy.exc.InvalidRequestError`, **if the lazy load
  492. needs to emit SQL**. If the lazy load can pull the related value
  493. from the identity map or determine that it should be None, the
  494. value is loaded. This strategy can be used when objects will
  495. remain associated with the attached :class:`.Session`, however
  496. additional SELECT statements should be blocked.
  497. .. versionadded:: 1.1
  498. * ``dynamic`` - the attribute will return a pre-configured
  499. :class:`_query.Query` object for all read
  500. operations, onto which further filtering operations can be
  501. applied before iterating the results. See
  502. the section :ref:`dynamic_relationship` for more details.
  503. * True - a synonym for 'select'
  504. * False - a synonym for 'joined'
  505. * None - a synonym for 'noload'
  506. .. seealso::
  507. :doc:`/orm/loading_relationships` - Full documentation on
  508. relationship loader configuration.
  509. :ref:`dynamic_relationship` - detail on the ``dynamic`` option.
  510. :ref:`collections_noload_raiseload` - notes on "noload" and "raise"
  511. :param load_on_pending=False:
  512. Indicates loading behavior for transient or pending parent objects.
  513. When set to ``True``, causes the lazy-loader to
  514. issue a query for a parent object that is not persistent, meaning it
  515. has never been flushed. This may take effect for a pending object
  516. when autoflush is disabled, or for a transient object that has been
  517. "attached" to a :class:`.Session` but is not part of its pending
  518. collection.
  519. The :paramref:`_orm.relationship.load_on_pending`
  520. flag does not improve
  521. behavior when the ORM is used normally - object references should be
  522. constructed at the object level, not at the foreign key level, so
  523. that they are present in an ordinary way before a flush proceeds.
  524. This flag is not not intended for general use.
  525. .. seealso::
  526. :meth:`.Session.enable_relationship_loading` - this method
  527. establishes "load on pending" behavior for the whole object, and
  528. also allows loading on objects that remain transient or
  529. detached.
  530. :param order_by:
  531. Indicates the ordering that should be applied when loading these
  532. items. :paramref:`_orm.relationship.order_by`
  533. is expected to refer to
  534. one of the :class:`_schema.Column`
  535. objects to which the target class is
  536. mapped, or the attribute itself bound to the target class which
  537. refers to the column.
  538. :paramref:`_orm.relationship.order_by`
  539. may also be passed as a callable
  540. function which is evaluated at mapper initialization time, and may
  541. be passed as a Python-evaluable string when using Declarative.
  542. .. warning:: When passed as a Python-evaluable string, the
  543. argument is interpreted using Python's ``eval()`` function.
  544. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
  545. See :ref:`declarative_relationship_eval` for details on
  546. declarative evaluation of :func:`_orm.relationship` arguments.
  547. :param passive_deletes=False:
  548. Indicates loading behavior during delete operations.
  549. A value of True indicates that unloaded child items should not
  550. be loaded during a delete operation on the parent. Normally,
  551. when a parent item is deleted, all child items are loaded so
  552. that they can either be marked as deleted, or have their
  553. foreign key to the parent set to NULL. Marking this flag as
  554. True usually implies an ON DELETE <CASCADE|SET NULL> rule is in
  555. place which will handle updating/deleting child rows on the
  556. database side.
  557. Additionally, setting the flag to the string value 'all' will
  558. disable the "nulling out" of the child foreign keys, when the parent
  559. object is deleted and there is no delete or delete-orphan cascade
  560. enabled. This is typically used when a triggering or error raise
  561. scenario is in place on the database side. Note that the foreign
  562. key attributes on in-session child objects will not be changed after
  563. a flush occurs so this is a very special use-case setting.
  564. Additionally, the "nulling out" will still occur if the child
  565. object is de-associated with the parent.
  566. .. seealso::
  567. :ref:`passive_deletes` - Introductory documentation
  568. and examples.
  569. :param passive_updates=True:
  570. Indicates the persistence behavior to take when a referenced
  571. primary key value changes in place, indicating that the referencing
  572. foreign key columns will also need their value changed.
  573. When True, it is assumed that ``ON UPDATE CASCADE`` is configured on
  574. the foreign key in the database, and that the database will
  575. handle propagation of an UPDATE from a source column to
  576. dependent rows. When False, the SQLAlchemy
  577. :func:`_orm.relationship`
  578. construct will attempt to emit its own UPDATE statements to
  579. modify related targets. However note that SQLAlchemy **cannot**
  580. emit an UPDATE for more than one level of cascade. Also,
  581. setting this flag to False is not compatible in the case where
  582. the database is in fact enforcing referential integrity, unless
  583. those constraints are explicitly "deferred", if the target backend
  584. supports it.
  585. It is highly advised that an application which is employing
  586. mutable primary keys keeps ``passive_updates`` set to True,
  587. and instead uses the referential integrity features of the database
  588. itself in order to handle the change efficiently and fully.
  589. .. seealso::
  590. :ref:`passive_updates` - Introductory documentation and
  591. examples.
  592. :paramref:`.mapper.passive_updates` - a similar flag which
  593. takes effect for joined-table inheritance mappings.
  594. :param post_update:
  595. This indicates that the relationship should be handled by a
  596. second UPDATE statement after an INSERT or before a
  597. DELETE. Currently, it also will issue an UPDATE after the
  598. instance was UPDATEd as well, although this technically should
  599. be improved. This flag is used to handle saving bi-directional
  600. dependencies between two individual rows (i.e. each row
  601. references the other), where it would otherwise be impossible to
  602. INSERT or DELETE both rows fully since one row exists before the
  603. other. Use this flag when a particular mapping arrangement will
  604. incur two rows that are dependent on each other, such as a table
  605. that has a one-to-many relationship to a set of child rows, and
  606. also has a column that references a single child row within that
  607. list (i.e. both tables contain a foreign key to each other). If
  608. a flush operation returns an error that a "cyclical
  609. dependency" was detected, this is a cue that you might want to
  610. use :paramref:`_orm.relationship.post_update` to "break" the cycle.
  611. .. seealso::
  612. :ref:`post_update` - Introductory documentation and examples.
  613. :param primaryjoin:
  614. A SQL expression that will be used as the primary
  615. join of the child object against the parent object, or in a
  616. many-to-many relationship the join of the parent object to the
  617. association table. By default, this value is computed based on the
  618. foreign key relationships of the parent and child tables (or
  619. association table).
  620. :paramref:`_orm.relationship.primaryjoin` may also be passed as a
  621. callable function which is evaluated at mapper initialization time,
  622. and may be passed as a Python-evaluable string when using
  623. Declarative.
  624. .. warning:: When passed as a Python-evaluable string, the
  625. argument is interpreted using Python's ``eval()`` function.
  626. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
  627. See :ref:`declarative_relationship_eval` for details on
  628. declarative evaluation of :func:`_orm.relationship` arguments.
  629. .. seealso::
  630. :ref:`relationship_primaryjoin`
  631. :param remote_side:
  632. Used for self-referential relationships, indicates the column or
  633. list of columns that form the "remote side" of the relationship.
  634. :paramref:`_orm.relationship.remote_side` may also be passed as a
  635. callable function which is evaluated at mapper initialization time,
  636. and may be passed as a Python-evaluable string when using
  637. Declarative.
  638. .. warning:: When passed as a Python-evaluable string, the
  639. argument is interpreted using Python's ``eval()`` function.
  640. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
  641. See :ref:`declarative_relationship_eval` for details on
  642. declarative evaluation of :func:`_orm.relationship` arguments.
  643. .. seealso::
  644. :ref:`self_referential` - in-depth explanation of how
  645. :paramref:`_orm.relationship.remote_side`
  646. is used to configure self-referential relationships.
  647. :func:`.remote` - an annotation function that accomplishes the
  648. same purpose as :paramref:`_orm.relationship.remote_side`,
  649. typically
  650. when a custom :paramref:`_orm.relationship.primaryjoin` condition
  651. is used.
  652. :param query_class:
  653. A :class:`_query.Query`
  654. subclass that will be used internally by the
  655. ``AppenderQuery`` returned by a "dynamic" relationship, that
  656. is, a relationship that specifies ``lazy="dynamic"`` or was
  657. otherwise constructed using the :func:`_orm.dynamic_loader`
  658. function.
  659. .. seealso::
  660. :ref:`dynamic_relationship` - Introduction to "dynamic"
  661. relationship loaders.
  662. :param secondaryjoin:
  663. A SQL expression that will be used as the join of
  664. an association table to the child object. By default, this value is
  665. computed based on the foreign key relationships of the association
  666. and child tables.
  667. :paramref:`_orm.relationship.secondaryjoin` may also be passed as a
  668. callable function which is evaluated at mapper initialization time,
  669. and may be passed as a Python-evaluable string when using
  670. Declarative.
  671. .. warning:: When passed as a Python-evaluable string, the
  672. argument is interpreted using Python's ``eval()`` function.
  673. **DO NOT PASS UNTRUSTED INPUT TO THIS STRING**.
  674. See :ref:`declarative_relationship_eval` for details on
  675. declarative evaluation of :func:`_orm.relationship` arguments.
  676. .. seealso::
  677. :ref:`relationship_primaryjoin`
  678. :param single_parent:
  679. When True, installs a validator which will prevent objects
  680. from being associated with more than one parent at a time.
  681. This is used for many-to-one or many-to-many relationships that
  682. should be treated either as one-to-one or one-to-many. Its usage
  683. is optional, except for :func:`_orm.relationship` constructs which
  684. are many-to-one or many-to-many and also
  685. specify the ``delete-orphan`` cascade option. The
  686. :func:`_orm.relationship` construct itself will raise an error
  687. instructing when this option is required.
  688. .. seealso::
  689. :ref:`unitofwork_cascades` - includes detail on when the
  690. :paramref:`_orm.relationship.single_parent`
  691. flag may be appropriate.
  692. :param uselist:
  693. A boolean that indicates if this property should be loaded as a
  694. list or a scalar. In most cases, this value is determined
  695. automatically by :func:`_orm.relationship` at mapper configuration
  696. time, based on the type and direction
  697. of the relationship - one to many forms a list, many to one
  698. forms a scalar, many to many is a list. If a scalar is desired
  699. where normally a list would be present, such as a bi-directional
  700. one-to-one relationship, set :paramref:`_orm.relationship.uselist`
  701. to
  702. False.
  703. The :paramref:`_orm.relationship.uselist`
  704. flag is also available on an
  705. existing :func:`_orm.relationship`
  706. construct as a read-only attribute,
  707. which can be used to determine if this :func:`_orm.relationship`
  708. deals
  709. with collections or scalar attributes::
  710. >>> User.addresses.property.uselist
  711. True
  712. .. seealso::
  713. :ref:`relationships_one_to_one` - Introduction to the "one to
  714. one" relationship pattern, which is typically when the
  715. :paramref:`_orm.relationship.uselist` flag is needed.
  716. :param viewonly=False:
  717. When set to ``True``, the relationship is used only for loading
  718. objects, and not for any persistence operation. A
  719. :func:`_orm.relationship` which specifies
  720. :paramref:`_orm.relationship.viewonly` can work
  721. with a wider range of SQL operations within the
  722. :paramref:`_orm.relationship.primaryjoin` condition, including
  723. operations that feature the use of a variety of comparison operators
  724. as well as SQL functions such as :func:`_expression.cast`. The
  725. :paramref:`_orm.relationship.viewonly`
  726. flag is also of general use when defining any kind of
  727. :func:`_orm.relationship` that doesn't represent
  728. the full set of related objects, to prevent modifications of the
  729. collection from resulting in persistence operations.
  730. When using the :paramref:`_orm.relationship.viewonly` flag in
  731. conjunction with backrefs, the originating relationship for a
  732. particular state change will not produce state changes within the
  733. viewonly relationship. This is the behavior implied by
  734. :paramref:`_orm.relationship.sync_backref` being set to False.
  735. .. versionchanged:: 1.3.17 - the
  736. :paramref:`_orm.relationship.sync_backref` flag is set to False
  737. when using viewonly in conjunction with backrefs.
  738. .. seealso::
  739. :paramref:`_orm.relationship.sync_backref`
  740. :param sync_backref:
  741. A boolean that enables the events used to synchronize the in-Python
  742. attributes when this relationship is target of either
  743. :paramref:`_orm.relationship.backref` or
  744. :paramref:`_orm.relationship.back_populates`.
  745. Defaults to ``None``, which indicates that an automatic value should
  746. be selected based on the value of the
  747. :paramref:`_orm.relationship.viewonly` flag. When left at its
  748. default, changes in state will be back-populated only if neither
  749. sides of a relationship is viewonly.
  750. .. versionadded:: 1.3.17
  751. .. versionchanged:: 1.4 - A relationship that specifies
  752. :paramref:`_orm.relationship.viewonly` automatically implies
  753. that :paramref:`_orm.relationship.sync_backref` is ``False``.
  754. .. seealso::
  755. :paramref:`_orm.relationship.viewonly`
  756. :param omit_join:
  757. Allows manual control over the "selectin" automatic join
  758. optimization. Set to ``False`` to disable the "omit join" feature
  759. added in SQLAlchemy 1.3; or leave as ``None`` to leave automatic
  760. optimization in place.
  761. .. note:: This flag may only be set to ``False``. It is not
  762. necessary to set it to ``True`` as the "omit_join" optimization is
  763. automatically detected; if it is not detected, then the
  764. optimization is not supported.
  765. .. versionchanged:: 1.3.11 setting ``omit_join`` to True will now
  766. emit a warning as this was not the intended use of this flag.
  767. .. versionadded:: 1.3
  768. """
  769. super(RelationshipProperty, self).__init__()
  770. self.uselist = uselist
  771. self.argument = argument
  772. self.secondary = secondary
  773. self.primaryjoin = primaryjoin
  774. self.secondaryjoin = secondaryjoin
  775. self.post_update = post_update
  776. self.direction = None
  777. self.viewonly = viewonly
  778. if viewonly:
  779. self._warn_for_persistence_only_flags(
  780. passive_deletes=passive_deletes,
  781. passive_updates=passive_updates,
  782. enable_typechecks=enable_typechecks,
  783. active_history=active_history,
  784. cascade_backrefs=cascade_backrefs,
  785. )
  786. if viewonly and sync_backref:
  787. raise sa_exc.ArgumentError(
  788. "sync_backref and viewonly cannot both be True"
  789. )
  790. self.sync_backref = sync_backref
  791. self.lazy = lazy
  792. self.single_parent = single_parent
  793. self._user_defined_foreign_keys = foreign_keys
  794. self.collection_class = collection_class
  795. self.passive_deletes = passive_deletes
  796. self.cascade_backrefs = cascade_backrefs
  797. self.passive_updates = passive_updates
  798. self.remote_side = remote_side
  799. self.enable_typechecks = enable_typechecks
  800. self.query_class = query_class
  801. self.innerjoin = innerjoin
  802. self.distinct_target_key = distinct_target_key
  803. self.doc = doc
  804. self.active_history = active_history
  805. self.join_depth = join_depth
  806. if omit_join:
  807. util.warn(
  808. "setting omit_join to True is not supported; selectin "
  809. "loading of this relationship may not work correctly if this "
  810. "flag is set explicitly. omit_join optimization is "
  811. "automatically detected for conditions under which it is "
  812. "supported."
  813. )
  814. self.omit_join = omit_join
  815. self.local_remote_pairs = _local_remote_pairs
  816. self.bake_queries = bake_queries
  817. self.load_on_pending = load_on_pending
  818. self.comparator_factory = (
  819. comparator_factory or RelationshipProperty.Comparator
  820. )
  821. self.comparator = self.comparator_factory(self, None)
  822. util.set_creation_order(self)
  823. if info is not None:
  824. self.info = info
  825. self.strategy_key = (("lazy", self.lazy),)
  826. self._reverse_property = set()
  827. if overlaps:
  828. self._overlaps = set(re.split(r"\s*,\s*", overlaps))
  829. else:
  830. self._overlaps = ()
  831. if cascade is not False:
  832. self.cascade = cascade
  833. elif self.viewonly:
  834. self.cascade = "none"
  835. else:
  836. self.cascade = "save-update, merge"
  837. self.order_by = order_by
  838. self.back_populates = back_populates
  839. if self.back_populates:
  840. if backref:
  841. raise sa_exc.ArgumentError(
  842. "backref and back_populates keyword arguments "
  843. "are mutually exclusive"
  844. )
  845. self.backref = None
  846. else:
  847. self.backref = backref
  848. def _warn_for_persistence_only_flags(self, **kw):
  849. for k, v in kw.items():
  850. if v != self._persistence_only[k]:
  851. # we are warning here rather than warn deprecated as this is a
  852. # configuration mistake, and Python shows regular warnings more
  853. # aggressively than deprecation warnings by default. Unlike the
  854. # case of setting viewonly with cascade, the settings being
  855. # warned about here are not actively doing the wrong thing
  856. # against viewonly=True, so it is not as urgent to have these
  857. # raise an error.
  858. util.warn(
  859. "Setting %s on relationship() while also "
  860. "setting viewonly=True does not make sense, as a "
  861. "viewonly=True relationship does not perform persistence "
  862. "operations. This configuration may raise an error "
  863. "in a future release." % (k,)
  864. )
  865. def instrument_class(self, mapper):
  866. attributes.register_descriptor(
  867. mapper.class_,
  868. self.key,
  869. comparator=self.comparator_factory(self, mapper),
  870. parententity=mapper,
  871. doc=self.doc,
  872. )
  873. class Comparator(PropComparator):
  874. """Produce boolean, comparison, and other operators for
  875. :class:`.RelationshipProperty` attributes.
  876. See the documentation for :class:`.PropComparator` for a brief
  877. overview of ORM level operator definition.
  878. .. seealso::
  879. :class:`.PropComparator`
  880. :class:`.ColumnProperty.Comparator`
  881. :class:`.ColumnOperators`
  882. :ref:`types_operators`
  883. :attr:`.TypeEngine.comparator_factory`
  884. """
  885. _of_type = None
  886. _extra_criteria = ()
  887. def __init__(
  888. self,
  889. prop,
  890. parentmapper,
  891. adapt_to_entity=None,
  892. of_type=None,
  893. extra_criteria=(),
  894. ):
  895. """Construction of :class:`.RelationshipProperty.Comparator`
  896. is internal to the ORM's attribute mechanics.
  897. """
  898. self.prop = prop
  899. self._parententity = parentmapper
  900. self._adapt_to_entity = adapt_to_entity
  901. if of_type:
  902. self._of_type = of_type
  903. self._extra_criteria = extra_criteria
  904. def adapt_to_entity(self, adapt_to_entity):
  905. return self.__class__(
  906. self.property,
  907. self._parententity,
  908. adapt_to_entity=adapt_to_entity,
  909. of_type=self._of_type,
  910. )
  911. @util.memoized_property
  912. def entity(self):
  913. """The target entity referred to by this
  914. :class:`.RelationshipProperty.Comparator`.
  915. This is either a :class:`_orm.Mapper` or :class:`.AliasedInsp`
  916. object.
  917. This is the "target" or "remote" side of the
  918. :func:`_orm.relationship`.
  919. """
  920. return self.property.entity
  921. @util.memoized_property
  922. def mapper(self):
  923. """The target :class:`_orm.Mapper` referred to by this
  924. :class:`.RelationshipProperty.Comparator`.
  925. This is the "target" or "remote" side of the
  926. :func:`_orm.relationship`.
  927. """
  928. return self.property.mapper
  929. @util.memoized_property
  930. def _parententity(self):
  931. return self.property.parent
  932. def _source_selectable(self):
  933. if self._adapt_to_entity:
  934. return self._adapt_to_entity.selectable
  935. else:
  936. return self.property.parent._with_polymorphic_selectable
  937. def __clause_element__(self):
  938. adapt_from = self._source_selectable()
  939. if self._of_type:
  940. of_type_entity = inspect(self._of_type)
  941. else:
  942. of_type_entity = None
  943. (
  944. pj,
  945. sj,
  946. source,
  947. dest,
  948. secondary,
  949. target_adapter,
  950. ) = self.property._create_joins(
  951. source_selectable=adapt_from,
  952. source_polymorphic=True,
  953. of_type_entity=of_type_entity,
  954. alias_secondary=True,
  955. extra_criteria=self._extra_criteria,
  956. )
  957. if sj is not None:
  958. return pj & sj
  959. else:
  960. return pj
  961. def of_type(self, cls):
  962. r"""Redefine this object in terms of a polymorphic subclass.
  963. See :meth:`.PropComparator.of_type` for an example.
  964. """
  965. return RelationshipProperty.Comparator(
  966. self.property,
  967. self._parententity,
  968. adapt_to_entity=self._adapt_to_entity,
  969. of_type=cls,
  970. extra_criteria=self._extra_criteria,
  971. )
  972. def and_(self, *other):
  973. """Add AND criteria.
  974. See :meth:`.PropComparator.and_` for an example.
  975. .. versionadded:: 1.4
  976. """
  977. return RelationshipProperty.Comparator(
  978. self.property,
  979. self._parententity,
  980. adapt_to_entity=self._adapt_to_entity,
  981. of_type=self._of_type,
  982. extra_criteria=self._extra_criteria + other,
  983. )
  984. def in_(self, other):
  985. """Produce an IN clause - this is not implemented
  986. for :func:`_orm.relationship`-based attributes at this time.
  987. """
  988. raise NotImplementedError(
  989. "in_() not yet supported for "
  990. "relationships. For a simple "
  991. "many-to-one, use in_() against "
  992. "the set of foreign key values."
  993. )
  994. __hash__ = None
  995. def __eq__(self, other):
  996. """Implement the ``==`` operator.
  997. In a many-to-one context, such as::
  998. MyClass.some_prop == <some object>
  999. this will typically produce a
  1000. clause such as::
  1001. mytable.related_id == <some id>
  1002. Where ``<some id>`` is the primary key of the given
  1003. object.
  1004. The ``==`` operator provides partial functionality for non-
  1005. many-to-one comparisons:
  1006. * Comparisons against collections are not supported.
  1007. Use :meth:`~.RelationshipProperty.Comparator.contains`.
  1008. * Compared to a scalar one-to-many, will produce a
  1009. clause that compares the target columns in the parent to
  1010. the given target.
  1011. * Compared to a scalar many-to-many, an alias
  1012. of the association table will be rendered as
  1013. well, forming a natural join that is part of the
  1014. main body of the query. This will not work for
  1015. queries that go beyond simple AND conjunctions of
  1016. comparisons, such as those which use OR. Use
  1017. explicit joins, outerjoins, or
  1018. :meth:`~.RelationshipProperty.Comparator.has` for
  1019. more comprehensive non-many-to-one scalar
  1020. membership tests.
  1021. * Comparisons against ``None`` given in a one-to-many
  1022. or many-to-many context produce a NOT EXISTS clause.
  1023. """
  1024. if isinstance(other, (util.NoneType, expression.Null)):
  1025. if self.property.direction in [ONETOMANY, MANYTOMANY]:
  1026. return ~self._criterion_exists()
  1027. else:
  1028. return _orm_annotate(
  1029. self.property._optimized_compare(
  1030. None, adapt_source=self.adapter
  1031. )
  1032. )
  1033. elif self.property.uselist:
  1034. raise sa_exc.InvalidRequestError(
  1035. "Can't compare a collection to an object or collection; "
  1036. "use contains() to test for membership."
  1037. )
  1038. else:
  1039. return _orm_annotate(
  1040. self.property._optimized_compare(
  1041. other, adapt_source=self.adapter
  1042. )
  1043. )
  1044. def _criterion_exists(self, criterion=None, **kwargs):
  1045. if getattr(self, "_of_type", None):
  1046. info = inspect(self._of_type)
  1047. target_mapper, to_selectable, is_aliased_class = (
  1048. info.mapper,
  1049. info.selectable,
  1050. info.is_aliased_class,
  1051. )
  1052. if self.property._is_self_referential and not is_aliased_class:
  1053. to_selectable = to_selectable._anonymous_fromclause()
  1054. single_crit = target_mapper._single_table_criterion
  1055. if single_crit is not None:
  1056. if criterion is not None:
  1057. criterion = single_crit & criterion
  1058. else:
  1059. criterion = single_crit
  1060. else:
  1061. is_aliased_class = False
  1062. to_selectable = None
  1063. if self.adapter:
  1064. source_selectable = self._source_selectable()
  1065. else:
  1066. source_selectable = None
  1067. (
  1068. pj,
  1069. sj,
  1070. source,
  1071. dest,
  1072. secondary,
  1073. target_adapter,
  1074. ) = self.property._create_joins(
  1075. dest_selectable=to_selectable,
  1076. source_selectable=source_selectable,
  1077. )
  1078. for k in kwargs:
  1079. crit = getattr(self.property.mapper.class_, k) == kwargs[k]
  1080. if criterion is None:
  1081. criterion = crit
  1082. else:
  1083. criterion = criterion & crit
  1084. # annotate the *local* side of the join condition, in the case
  1085. # of pj + sj this is the full primaryjoin, in the case of just
  1086. # pj its the local side of the primaryjoin.
  1087. if sj is not None:
  1088. j = _orm_annotate(pj) & sj
  1089. else:
  1090. j = _orm_annotate(pj, exclude=self.property.remote_side)
  1091. if (
  1092. criterion is not None
  1093. and target_adapter
  1094. and not is_aliased_class
  1095. ):
  1096. # limit this adapter to annotated only?
  1097. criterion = target_adapter.traverse(criterion)
  1098. # only have the "joined left side" of what we
  1099. # return be subject to Query adaption. The right
  1100. # side of it is used for an exists() subquery and
  1101. # should not correlate or otherwise reach out
  1102. # to anything in the enclosing query.
  1103. if criterion is not None:
  1104. criterion = criterion._annotate(
  1105. {"no_replacement_traverse": True}
  1106. )
  1107. crit = j & sql.True_._ifnone(criterion)
  1108. if secondary is not None:
  1109. ex = (
  1110. sql.exists(1)
  1111. .where(crit)
  1112. .select_from(dest, secondary)
  1113. .correlate_except(dest, secondary)
  1114. )
  1115. else:
  1116. ex = (
  1117. sql.exists(1)
  1118. .where(crit)
  1119. .select_from(dest)
  1120. .correlate_except(dest)
  1121. )
  1122. return ex
  1123. def any(self, criterion=None, **kwargs):
  1124. """Produce an expression that tests a collection against
  1125. particular criterion, using EXISTS.
  1126. An expression like::
  1127. session.query(MyClass).filter(
  1128. MyClass.somereference.any(SomeRelated.x==2)
  1129. )
  1130. Will produce a query like::
  1131. SELECT * FROM my_table WHERE
  1132. EXISTS (SELECT 1 FROM related WHERE related.my_id=my_table.id
  1133. AND related.x=2)
  1134. Because :meth:`~.RelationshipProperty.Comparator.any` uses
  1135. a correlated subquery, its performance is not nearly as
  1136. good when compared against large target tables as that of
  1137. using a join.
  1138. :meth:`~.RelationshipProperty.Comparator.any` is particularly
  1139. useful for testing for empty collections::
  1140. session.query(MyClass).filter(
  1141. ~MyClass.somereference.any()
  1142. )
  1143. will produce::
  1144. SELECT * FROM my_table WHERE
  1145. NOT (EXISTS (SELECT 1 FROM related WHERE
  1146. related.my_id=my_table.id))
  1147. :meth:`~.RelationshipProperty.Comparator.any` is only
  1148. valid for collections, i.e. a :func:`_orm.relationship`
  1149. that has ``uselist=True``. For scalar references,
  1150. use :meth:`~.RelationshipProperty.Comparator.has`.
  1151. """
  1152. if not self.property.uselist:
  1153. raise sa_exc.InvalidRequestError(
  1154. "'any()' not implemented for scalar "
  1155. "attributes. Use has()."
  1156. )
  1157. return self._criterion_exists(criterion, **kwargs)
  1158. def has(self, criterion=None, **kwargs):
  1159. """Produce an expression that tests a scalar reference against
  1160. particular criterion, using EXISTS.
  1161. An expression like::
  1162. session.query(MyClass).filter(
  1163. MyClass.somereference.has(SomeRelated.x==2)
  1164. )
  1165. Will produce a query like::
  1166. SELECT * FROM my_table WHERE
  1167. EXISTS (SELECT 1 FROM related WHERE
  1168. related.id==my_table.related_id AND related.x=2)
  1169. Because :meth:`~.RelationshipProperty.Comparator.has` uses
  1170. a correlated subquery, its performance is not nearly as
  1171. good when compared against large target tables as that of
  1172. using a join.
  1173. :meth:`~.RelationshipProperty.Comparator.has` is only
  1174. valid for scalar references, i.e. a :func:`_orm.relationship`
  1175. that has ``uselist=False``. For collection references,
  1176. use :meth:`~.RelationshipProperty.Comparator.any`.
  1177. """
  1178. if self.property.uselist:
  1179. raise sa_exc.InvalidRequestError(
  1180. "'has()' not implemented for collections. " "Use any()."
  1181. )
  1182. return self._criterion_exists(criterion, **kwargs)
  1183. def contains(self, other, **kwargs):
  1184. """Return a simple expression that tests a collection for
  1185. containment of a particular item.
  1186. :meth:`~.RelationshipProperty.Comparator.contains` is
  1187. only valid for a collection, i.e. a
  1188. :func:`_orm.relationship` that implements
  1189. one-to-many or many-to-many with ``uselist=True``.
  1190. When used in a simple one-to-many context, an
  1191. expression like::
  1192. MyClass.contains(other)
  1193. Produces a clause like::
  1194. mytable.id == <some id>
  1195. Where ``<some id>`` is the value of the foreign key
  1196. attribute on ``other`` which refers to the primary
  1197. key of its parent object. From this it follows that
  1198. :meth:`~.RelationshipProperty.Comparator.contains` is
  1199. very useful when used with simple one-to-many
  1200. operations.
  1201. For many-to-many operations, the behavior of
  1202. :meth:`~.RelationshipProperty.Comparator.contains`
  1203. has more caveats. The association table will be
  1204. rendered in the statement, producing an "implicit"
  1205. join, that is, includes multiple tables in the FROM
  1206. clause which are equated in the WHERE clause::
  1207. query(MyClass).filter(MyClass.contains(other))
  1208. Produces a query like::
  1209. SELECT * FROM my_table, my_association_table AS
  1210. my_association_table_1 WHERE
  1211. my_table.id = my_association_table_1.parent_id
  1212. AND my_association_table_1.child_id = <some id>
  1213. Where ``<some id>`` would be the primary key of
  1214. ``other``. From the above, it is clear that
  1215. :meth:`~.RelationshipProperty.Comparator.contains`
  1216. will **not** work with many-to-many collections when
  1217. used in queries that move beyond simple AND
  1218. conjunctions, such as multiple
  1219. :meth:`~.RelationshipProperty.Comparator.contains`
  1220. expressions joined by OR. In such cases subqueries or
  1221. explicit "outer joins" will need to be used instead.
  1222. See :meth:`~.RelationshipProperty.Comparator.any` for
  1223. a less-performant alternative using EXISTS, or refer
  1224. to :meth:`_query.Query.outerjoin`
  1225. as well as :ref:`ormtutorial_joins`
  1226. for more details on constructing outer joins.
  1227. """
  1228. if not self.property.uselist:
  1229. raise sa_exc.InvalidRequestError(
  1230. "'contains' not implemented for scalar "
  1231. "attributes. Use =="
  1232. )
  1233. clause = self.property._optimized_compare(
  1234. other, adapt_source=self.adapter
  1235. )
  1236. if self.property.secondaryjoin is not None:
  1237. clause.negation_clause = self.__negated_contains_or_equals(
  1238. other
  1239. )
  1240. return clause
  1241. def __negated_contains_or_equals(self, other):
  1242. if self.property.direction == MANYTOONE:
  1243. state = attributes.instance_state(other)
  1244. def state_bindparam(local_col, state, remote_col):
  1245. dict_ = state.dict
  1246. return sql.bindparam(
  1247. local_col.key,
  1248. type_=local_col.type,
  1249. unique=True,
  1250. callable_=self.property._get_attr_w_warn_on_none(
  1251. self.property.mapper, state, dict_, remote_col
  1252. ),
  1253. )
  1254. def adapt(col):
  1255. if self.adapter:
  1256. return self.adapter(col)
  1257. else:
  1258. return col
  1259. if self.property._use_get:
  1260. return sql.and_(
  1261. *[
  1262. sql.or_(
  1263. adapt(x)
  1264. != state_bindparam(adapt(x), state, y),
  1265. adapt(x) == None,
  1266. )
  1267. for (x, y) in self.property.local_remote_pairs
  1268. ]
  1269. )
  1270. criterion = sql.and_(
  1271. *[
  1272. x == y
  1273. for (x, y) in zip(
  1274. self.property.mapper.primary_key,
  1275. self.property.mapper.primary_key_from_instance(other),
  1276. )
  1277. ]
  1278. )
  1279. return ~self._criterion_exists(criterion)
  1280. def __ne__(self, other):
  1281. """Implement the ``!=`` operator.
  1282. In a many-to-one context, such as::
  1283. MyClass.some_prop != <some object>
  1284. This will typically produce a clause such as::
  1285. mytable.related_id != <some id>
  1286. Where ``<some id>`` is the primary key of the
  1287. given object.
  1288. The ``!=`` operator provides partial functionality for non-
  1289. many-to-one comparisons:
  1290. * Comparisons against collections are not supported.
  1291. Use
  1292. :meth:`~.RelationshipProperty.Comparator.contains`
  1293. in conjunction with :func:`_expression.not_`.
  1294. * Compared to a scalar one-to-many, will produce a
  1295. clause that compares the target columns in the parent to
  1296. the given target.
  1297. * Compared to a scalar many-to-many, an alias
  1298. of the association table will be rendered as
  1299. well, forming a natural join that is part of the
  1300. main body of the query. This will not work for
  1301. queries that go beyond simple AND conjunctions of
  1302. comparisons, such as those which use OR. Use
  1303. explicit joins, outerjoins, or
  1304. :meth:`~.RelationshipProperty.Comparator.has` in
  1305. conjunction with :func:`_expression.not_` for
  1306. more comprehensive non-many-to-one scalar
  1307. membership tests.
  1308. * Comparisons against ``None`` given in a one-to-many
  1309. or many-to-many context produce an EXISTS clause.
  1310. """
  1311. if isinstance(other, (util.NoneType, expression.Null)):
  1312. if self.property.direction == MANYTOONE:
  1313. return _orm_annotate(
  1314. ~self.property._optimized_compare(
  1315. None, adapt_source=self.adapter
  1316. )
  1317. )
  1318. else:
  1319. return self._criterion_exists()
  1320. elif self.property.uselist:
  1321. raise sa_exc.InvalidRequestError(
  1322. "Can't compare a collection"
  1323. " to an object or collection; use "
  1324. "contains() to test for membership."
  1325. )
  1326. else:
  1327. return _orm_annotate(self.__negated_contains_or_equals(other))
  1328. @util.memoized_property
  1329. def property(self):
  1330. self.prop.parent._check_configure()
  1331. return self.prop
  1332. def _with_parent(self, instance, alias_secondary=True, from_entity=None):
  1333. assert instance is not None
  1334. adapt_source = None
  1335. if from_entity is not None:
  1336. insp = inspect(from_entity)
  1337. if insp.is_aliased_class:
  1338. adapt_source = insp._adapter.adapt_clause
  1339. return self._optimized_compare(
  1340. instance,
  1341. value_is_parent=True,
  1342. adapt_source=adapt_source,
  1343. alias_secondary=alias_secondary,
  1344. )
  1345. def _optimized_compare(
  1346. self,
  1347. state,
  1348. value_is_parent=False,
  1349. adapt_source=None,
  1350. alias_secondary=True,
  1351. ):
  1352. if state is not None:
  1353. try:
  1354. state = inspect(state)
  1355. except sa_exc.NoInspectionAvailable:
  1356. state = None
  1357. if state is None or not getattr(state, "is_instance", False):
  1358. raise sa_exc.ArgumentError(
  1359. "Mapped instance expected for relationship "
  1360. "comparison to object. Classes, queries and other "
  1361. "SQL elements are not accepted in this context; for "
  1362. "comparison with a subquery, "
  1363. "use %s.has(**criteria)." % self
  1364. )
  1365. reverse_direction = not value_is_parent
  1366. if state is None:
  1367. return self._lazy_none_clause(
  1368. reverse_direction, adapt_source=adapt_source
  1369. )
  1370. if not reverse_direction:
  1371. criterion, bind_to_col = (
  1372. self._lazy_strategy._lazywhere,
  1373. self._lazy_strategy._bind_to_col,
  1374. )
  1375. else:
  1376. criterion, bind_to_col = (
  1377. self._lazy_strategy._rev_lazywhere,
  1378. self._lazy_strategy._rev_bind_to_col,
  1379. )
  1380. if reverse_direction:
  1381. mapper = self.mapper
  1382. else:
  1383. mapper = self.parent
  1384. dict_ = attributes.instance_dict(state.obj())
  1385. def visit_bindparam(bindparam):
  1386. if bindparam._identifying_key in bind_to_col:
  1387. bindparam.callable = self._get_attr_w_warn_on_none(
  1388. mapper,
  1389. state,
  1390. dict_,
  1391. bind_to_col[bindparam._identifying_key],
  1392. )
  1393. if self.secondary is not None and alias_secondary:
  1394. criterion = ClauseAdapter(
  1395. self.secondary._anonymous_fromclause()
  1396. ).traverse(criterion)
  1397. criterion = visitors.cloned_traverse(
  1398. criterion, {}, {"bindparam": visit_bindparam}
  1399. )
  1400. if adapt_source:
  1401. criterion = adapt_source(criterion)
  1402. return criterion
  1403. def _get_attr_w_warn_on_none(self, mapper, state, dict_, column):
  1404. """Create the callable that is used in a many-to-one expression.
  1405. E.g.::
  1406. u1 = s.query(User).get(5)
  1407. expr = Address.user == u1
  1408. Above, the SQL should be "address.user_id = 5". The callable
  1409. returned by this method produces the value "5" based on the identity
  1410. of ``u1``.
  1411. """
  1412. # in this callable, we're trying to thread the needle through
  1413. # a wide variety of scenarios, including:
  1414. #
  1415. # * the object hasn't been flushed yet and there's no value for
  1416. # the attribute as of yet
  1417. #
  1418. # * the object hasn't been flushed yet but it has a user-defined
  1419. # value
  1420. #
  1421. # * the object has a value but it's expired and not locally present
  1422. #
  1423. # * the object has a value but it's expired and not locally present,
  1424. # and the object is also detached
  1425. #
  1426. # * The object hadn't been flushed yet, there was no value, but
  1427. # later, the object has been expired and detached, and *now*
  1428. # they're trying to evaluate it
  1429. #
  1430. # * the object had a value, but it was changed to a new value, and
  1431. # then expired
  1432. #
  1433. # * the object had a value, but it was changed to a new value, and
  1434. # then expired, then the object was detached
  1435. #
  1436. # * the object has a user-set value, but it's None and we don't do
  1437. # the comparison correctly for that so warn
  1438. #
  1439. prop = mapper.get_property_by_column(column)
  1440. # by invoking this method, InstanceState will track the last known
  1441. # value for this key each time the attribute is to be expired.
  1442. # this feature was added explicitly for use in this method.
  1443. state._track_last_known_value(prop.key)
  1444. def _go():
  1445. last_known = to_return = state._last_known_values[prop.key]
  1446. existing_is_available = last_known is not attributes.NO_VALUE
  1447. # we support that the value may have changed. so here we
  1448. # try to get the most recent value including re-fetching.
  1449. # only if we can't get a value now due to detachment do we return
  1450. # the last known value
  1451. current_value = mapper._get_state_attr_by_column(
  1452. state,
  1453. dict_,
  1454. column,
  1455. passive=attributes.PASSIVE_OFF
  1456. if state.persistent
  1457. else attributes.PASSIVE_NO_FETCH ^ attributes.INIT_OK,
  1458. )
  1459. if current_value is attributes.NEVER_SET:
  1460. if not existing_is_available:
  1461. raise sa_exc.InvalidRequestError(
  1462. "Can't resolve value for column %s on object "
  1463. "%s; no value has been set for this column"
  1464. % (column, state_str(state))
  1465. )
  1466. elif current_value is attributes.PASSIVE_NO_RESULT:
  1467. if not existing_is_available:
  1468. raise sa_exc.InvalidRequestError(
  1469. "Can't resolve value for column %s on object "
  1470. "%s; the object is detached and the value was "
  1471. "expired" % (column, state_str(state))
  1472. )
  1473. else:
  1474. to_return = current_value
  1475. if to_return is None:
  1476. util.warn(
  1477. "Got None for value of column %s; this is unsupported "
  1478. "for a relationship comparison and will not "
  1479. "currently produce an IS comparison "
  1480. "(but may in a future release)" % column
  1481. )
  1482. return to_return
  1483. return _go
  1484. def _lazy_none_clause(self, reverse_direction=False, adapt_source=None):
  1485. if not reverse_direction:
  1486. criterion, bind_to_col = (
  1487. self._lazy_strategy._lazywhere,
  1488. self._lazy_strategy._bind_to_col,
  1489. )
  1490. else:
  1491. criterion, bind_to_col = (
  1492. self._lazy_strategy._rev_lazywhere,
  1493. self._lazy_strategy._rev_bind_to_col,
  1494. )
  1495. criterion = adapt_criterion_to_null(criterion, bind_to_col)
  1496. if adapt_source:
  1497. criterion = adapt_source(criterion)
  1498. return criterion
  1499. def __str__(self):
  1500. return str(self.parent.class_.__name__) + "." + self.key
  1501. def merge(
  1502. self,
  1503. session,
  1504. source_state,
  1505. source_dict,
  1506. dest_state,
  1507. dest_dict,
  1508. load,
  1509. _recursive,
  1510. _resolve_conflict_map,
  1511. ):
  1512. if load:
  1513. for r in self._reverse_property:
  1514. if (source_state, r) in _recursive:
  1515. return
  1516. if "merge" not in self._cascade:
  1517. return
  1518. if self.key not in source_dict:
  1519. return
  1520. if self.uselist:
  1521. impl = source_state.get_impl(self.key)
  1522. instances_iterable = impl.get_collection(source_state, source_dict)
  1523. # if this is a CollectionAttributeImpl, then empty should
  1524. # be False, otherwise "self.key in source_dict" should not be
  1525. # True
  1526. assert not instances_iterable.empty if impl.collection else True
  1527. if load:
  1528. # for a full merge, pre-load the destination collection,
  1529. # so that individual _merge of each item pulls from identity
  1530. # map for those already present.
  1531. # also assumes CollectionAttributeImpl behavior of loading
  1532. # "old" list in any case
  1533. dest_state.get_impl(self.key).get(dest_state, dest_dict)
  1534. dest_list = []
  1535. for current in instances_iterable:
  1536. current_state = attributes.instance_state(current)
  1537. current_dict = attributes.instance_dict(current)
  1538. _recursive[(current_state, self)] = True
  1539. obj = session._merge(
  1540. current_state,
  1541. current_dict,
  1542. load=load,
  1543. _recursive=_recursive,
  1544. _resolve_conflict_map=_resolve_conflict_map,
  1545. )
  1546. if obj is not None:
  1547. dest_list.append(obj)
  1548. if not load:
  1549. coll = attributes.init_state_collection(
  1550. dest_state, dest_dict, self.key
  1551. )
  1552. for c in dest_list:
  1553. coll.append_without_event(c)
  1554. else:
  1555. dest_state.get_impl(self.key).set(
  1556. dest_state, dest_dict, dest_list, _adapt=False
  1557. )
  1558. else:
  1559. current = source_dict[self.key]
  1560. if current is not None:
  1561. current_state = attributes.instance_state(current)
  1562. current_dict = attributes.instance_dict(current)
  1563. _recursive[(current_state, self)] = True
  1564. obj = session._merge(
  1565. current_state,
  1566. current_dict,
  1567. load=load,
  1568. _recursive=_recursive,
  1569. _resolve_conflict_map=_resolve_conflict_map,
  1570. )
  1571. else:
  1572. obj = None
  1573. if not load:
  1574. dest_dict[self.key] = obj
  1575. else:
  1576. dest_state.get_impl(self.key).set(
  1577. dest_state, dest_dict, obj, None
  1578. )
  1579. def _value_as_iterable(
  1580. self, state, dict_, key, passive=attributes.PASSIVE_OFF
  1581. ):
  1582. """Return a list of tuples (state, obj) for the given
  1583. key.
  1584. returns an empty list if the value is None/empty/PASSIVE_NO_RESULT
  1585. """
  1586. impl = state.manager[key].impl
  1587. x = impl.get(state, dict_, passive=passive)
  1588. if x is attributes.PASSIVE_NO_RESULT or x is None:
  1589. return []
  1590. elif hasattr(impl, "get_collection"):
  1591. return [
  1592. (attributes.instance_state(o), o)
  1593. for o in impl.get_collection(state, dict_, x, passive=passive)
  1594. ]
  1595. else:
  1596. return [(attributes.instance_state(x), x)]
  1597. def cascade_iterator(
  1598. self, type_, state, dict_, visited_states, halt_on=None
  1599. ):
  1600. # assert type_ in self._cascade
  1601. # only actively lazy load on the 'delete' cascade
  1602. if type_ != "delete" or self.passive_deletes:
  1603. passive = attributes.PASSIVE_NO_INITIALIZE
  1604. else:
  1605. passive = attributes.PASSIVE_OFF
  1606. if type_ == "save-update":
  1607. tuples = state.manager[self.key].impl.get_all_pending(state, dict_)
  1608. else:
  1609. tuples = self._value_as_iterable(
  1610. state, dict_, self.key, passive=passive
  1611. )
  1612. skip_pending = (
  1613. type_ == "refresh-expire" and "delete-orphan" not in self._cascade
  1614. )
  1615. for instance_state, c in tuples:
  1616. if instance_state in visited_states:
  1617. continue
  1618. if c is None:
  1619. # would like to emit a warning here, but
  1620. # would not be consistent with collection.append(None)
  1621. # current behavior of silently skipping.
  1622. # see [ticket:2229]
  1623. continue
  1624. instance_dict = attributes.instance_dict(c)
  1625. if halt_on and halt_on(instance_state):
  1626. continue
  1627. if skip_pending and not instance_state.key:
  1628. continue
  1629. instance_mapper = instance_state.manager.mapper
  1630. if not instance_mapper.isa(self.mapper.class_manager.mapper):
  1631. raise AssertionError(
  1632. "Attribute '%s' on class '%s' "
  1633. "doesn't handle objects "
  1634. "of type '%s'"
  1635. % (self.key, self.parent.class_, c.__class__)
  1636. )
  1637. visited_states.add(instance_state)
  1638. yield c, instance_mapper, instance_state, instance_dict
  1639. @property
  1640. def _effective_sync_backref(self):
  1641. if self.viewonly:
  1642. return False
  1643. else:
  1644. return self.sync_backref is not False
  1645. @staticmethod
  1646. def _check_sync_backref(rel_a, rel_b):
  1647. if rel_a.viewonly and rel_b.sync_backref:
  1648. raise sa_exc.InvalidRequestError(
  1649. "Relationship %s cannot specify sync_backref=True since %s "
  1650. "includes viewonly=True." % (rel_b, rel_a)
  1651. )
  1652. if (
  1653. rel_a.viewonly
  1654. and not rel_b.viewonly
  1655. and rel_b.sync_backref is not False
  1656. ):
  1657. rel_b.sync_backref = False
  1658. def _add_reverse_property(self, key):
  1659. other = self.mapper.get_property(key, _configure_mappers=False)
  1660. if not isinstance(other, RelationshipProperty):
  1661. raise sa_exc.InvalidRequestError(
  1662. "back_populates on relationship '%s' refers to attribute '%s' "
  1663. "that is not a relationship. The back_populates parameter "
  1664. "should refer to the name of a relationship on the target "
  1665. "class." % (self, other)
  1666. )
  1667. # viewonly and sync_backref cases
  1668. # 1. self.viewonly==True and other.sync_backref==True -> error
  1669. # 2. self.viewonly==True and other.viewonly==False and
  1670. # other.sync_backref==None -> warn sync_backref=False, set to False
  1671. self._check_sync_backref(self, other)
  1672. # 3. other.viewonly==True and self.sync_backref==True -> error
  1673. # 4. other.viewonly==True and self.viewonly==False and
  1674. # self.sync_backref==None -> warn sync_backref=False, set to False
  1675. self._check_sync_backref(other, self)
  1676. self._reverse_property.add(other)
  1677. other._reverse_property.add(self)
  1678. if not other.mapper.common_parent(self.parent):
  1679. raise sa_exc.ArgumentError(
  1680. "reverse_property %r on "
  1681. "relationship %s references relationship %s, which "
  1682. "does not reference mapper %s"
  1683. % (key, self, other, self.parent)
  1684. )
  1685. if (
  1686. self.direction in (ONETOMANY, MANYTOONE)
  1687. and self.direction == other.direction
  1688. ):
  1689. raise sa_exc.ArgumentError(
  1690. "%s and back-reference %s are "
  1691. "both of the same direction %r. Did you mean to "
  1692. "set remote_side on the many-to-one side ?"
  1693. % (other, self, self.direction)
  1694. )
  1695. @util.memoized_property
  1696. @util.preload_module("sqlalchemy.orm.mapper")
  1697. def entity(self):
  1698. """Return the target mapped entity, which is an inspect() of the
  1699. class or aliased class that is referred towards.
  1700. """
  1701. mapperlib = util.preloaded.orm_mapper
  1702. if isinstance(self.argument, util.string_types):
  1703. argument = self._clsregistry_resolve_name(self.argument)()
  1704. elif callable(self.argument) and not isinstance(
  1705. self.argument, (type, mapperlib.Mapper)
  1706. ):
  1707. argument = self.argument()
  1708. else:
  1709. argument = self.argument
  1710. if isinstance(argument, type):
  1711. return mapperlib.class_mapper(argument, configure=False)
  1712. try:
  1713. entity = inspect(argument)
  1714. except sa_exc.NoInspectionAvailable:
  1715. pass
  1716. else:
  1717. if hasattr(entity, "mapper"):
  1718. return entity
  1719. raise sa_exc.ArgumentError(
  1720. "relationship '%s' expects "
  1721. "a class or a mapper argument (received: %s)"
  1722. % (self.key, type(argument))
  1723. )
  1724. @util.memoized_property
  1725. def mapper(self):
  1726. """Return the targeted :class:`_orm.Mapper` for this
  1727. :class:`.RelationshipProperty`.
  1728. This is a lazy-initializing static attribute.
  1729. """
  1730. return self.entity.mapper
  1731. def do_init(self):
  1732. self._check_conflicts()
  1733. self._process_dependent_arguments()
  1734. self._setup_registry_dependencies()
  1735. self._setup_join_conditions()
  1736. self._check_cascade_settings(self._cascade)
  1737. self._post_init()
  1738. self._generate_backref()
  1739. self._join_condition._warn_for_conflicting_sync_targets()
  1740. super(RelationshipProperty, self).do_init()
  1741. self._lazy_strategy = self._get_strategy((("lazy", "select"),))
  1742. def _setup_registry_dependencies(self):
  1743. self.parent.mapper.registry._set_depends_on(
  1744. self.entity.mapper.registry
  1745. )
  1746. def _process_dependent_arguments(self):
  1747. """Convert incoming configuration arguments to their
  1748. proper form.
  1749. Callables are resolved, ORM annotations removed.
  1750. """
  1751. # accept callables for other attributes which may require
  1752. # deferred initialization. This technique is used
  1753. # by declarative "string configs" and some recipes.
  1754. for attr in (
  1755. "order_by",
  1756. "primaryjoin",
  1757. "secondaryjoin",
  1758. "secondary",
  1759. "_user_defined_foreign_keys",
  1760. "remote_side",
  1761. ):
  1762. attr_value = getattr(self, attr)
  1763. if isinstance(attr_value, util.string_types):
  1764. setattr(
  1765. self,
  1766. attr,
  1767. self._clsregistry_resolve_arg(
  1768. attr_value, favor_tables=attr == "secondary"
  1769. )(),
  1770. )
  1771. elif callable(attr_value) and not _is_mapped_class(attr_value):
  1772. setattr(self, attr, attr_value())
  1773. # remove "annotations" which are present if mapped class
  1774. # descriptors are used to create the join expression.
  1775. for attr in "primaryjoin", "secondaryjoin":
  1776. val = getattr(self, attr)
  1777. if val is not None:
  1778. setattr(
  1779. self,
  1780. attr,
  1781. _orm_deannotate(
  1782. coercions.expect(
  1783. roles.ColumnArgumentRole, val, argname=attr
  1784. )
  1785. ),
  1786. )
  1787. if self.secondary is not None and _is_mapped_class(self.secondary):
  1788. raise sa_exc.ArgumentError(
  1789. "secondary argument %s passed to to relationship() %s must "
  1790. "be a Table object or other FROM clause; can't send a mapped "
  1791. "class directly as rows in 'secondary' are persisted "
  1792. "independently of a class that is mapped "
  1793. "to that same table." % (self.secondary, self)
  1794. )
  1795. # ensure expressions in self.order_by, foreign_keys,
  1796. # remote_side are all columns, not strings.
  1797. if self.order_by is not False and self.order_by is not None:
  1798. self.order_by = tuple(
  1799. coercions.expect(
  1800. roles.ColumnArgumentRole, x, argname="order_by"
  1801. )
  1802. for x in util.to_list(self.order_by)
  1803. )
  1804. self._user_defined_foreign_keys = util.column_set(
  1805. coercions.expect(
  1806. roles.ColumnArgumentRole, x, argname="foreign_keys"
  1807. )
  1808. for x in util.to_column_set(self._user_defined_foreign_keys)
  1809. )
  1810. self.remote_side = util.column_set(
  1811. coercions.expect(
  1812. roles.ColumnArgumentRole, x, argname="remote_side"
  1813. )
  1814. for x in util.to_column_set(self.remote_side)
  1815. )
  1816. self.target = self.entity.persist_selectable
  1817. def _setup_join_conditions(self):
  1818. self._join_condition = jc = JoinCondition(
  1819. parent_persist_selectable=self.parent.persist_selectable,
  1820. child_persist_selectable=self.entity.persist_selectable,
  1821. parent_local_selectable=self.parent.local_table,
  1822. child_local_selectable=self.entity.local_table,
  1823. primaryjoin=self.primaryjoin,
  1824. secondary=self.secondary,
  1825. secondaryjoin=self.secondaryjoin,
  1826. parent_equivalents=self.parent._equivalent_columns,
  1827. child_equivalents=self.mapper._equivalent_columns,
  1828. consider_as_foreign_keys=self._user_defined_foreign_keys,
  1829. local_remote_pairs=self.local_remote_pairs,
  1830. remote_side=self.remote_side,
  1831. self_referential=self._is_self_referential,
  1832. prop=self,
  1833. support_sync=not self.viewonly,
  1834. can_be_synced_fn=self._columns_are_mapped,
  1835. )
  1836. self.primaryjoin = jc.primaryjoin
  1837. self.secondaryjoin = jc.secondaryjoin
  1838. self.direction = jc.direction
  1839. self.local_remote_pairs = jc.local_remote_pairs
  1840. self.remote_side = jc.remote_columns
  1841. self.local_columns = jc.local_columns
  1842. self.synchronize_pairs = jc.synchronize_pairs
  1843. self._calculated_foreign_keys = jc.foreign_key_columns
  1844. self.secondary_synchronize_pairs = jc.secondary_synchronize_pairs
  1845. @property
  1846. def _clsregistry_resolve_arg(self):
  1847. return self._clsregistry_resolvers[1]
  1848. @property
  1849. def _clsregistry_resolve_name(self):
  1850. return self._clsregistry_resolvers[0]
  1851. @util.memoized_property
  1852. @util.preload_module("sqlalchemy.orm.clsregistry")
  1853. def _clsregistry_resolvers(self):
  1854. _resolver = util.preloaded.orm_clsregistry._resolver
  1855. return _resolver(self.parent.class_, self)
  1856. @util.preload_module("sqlalchemy.orm.mapper")
  1857. def _check_conflicts(self):
  1858. """Test that this relationship is legal, warn about
  1859. inheritance conflicts."""
  1860. mapperlib = util.preloaded.orm_mapper
  1861. if self.parent.non_primary and not mapperlib.class_mapper(
  1862. self.parent.class_, configure=False
  1863. ).has_property(self.key):
  1864. raise sa_exc.ArgumentError(
  1865. "Attempting to assign a new "
  1866. "relationship '%s' to a non-primary mapper on "
  1867. "class '%s'. New relationships can only be added "
  1868. "to the primary mapper, i.e. the very first mapper "
  1869. "created for class '%s' "
  1870. % (
  1871. self.key,
  1872. self.parent.class_.__name__,
  1873. self.parent.class_.__name__,
  1874. )
  1875. )
  1876. @property
  1877. def cascade(self):
  1878. """Return the current cascade setting for this
  1879. :class:`.RelationshipProperty`.
  1880. """
  1881. return self._cascade
  1882. @cascade.setter
  1883. def cascade(self, cascade):
  1884. self._set_cascade(cascade)
  1885. def _set_cascade(self, cascade):
  1886. cascade = CascadeOptions(cascade)
  1887. if self.viewonly:
  1888. non_viewonly = set(cascade).difference(
  1889. CascadeOptions._viewonly_cascades
  1890. )
  1891. if non_viewonly:
  1892. raise sa_exc.ArgumentError(
  1893. 'Cascade settings "%s" apply to persistence operations '
  1894. "and should not be combined with a viewonly=True "
  1895. "relationship." % (", ".join(sorted(non_viewonly)))
  1896. )
  1897. if "mapper" in self.__dict__:
  1898. self._check_cascade_settings(cascade)
  1899. self._cascade = cascade
  1900. if self._dependency_processor:
  1901. self._dependency_processor.cascade = cascade
  1902. def _check_cascade_settings(self, cascade):
  1903. if (
  1904. cascade.delete_orphan
  1905. and not self.single_parent
  1906. and (self.direction is MANYTOMANY or self.direction is MANYTOONE)
  1907. ):
  1908. raise sa_exc.ArgumentError(
  1909. "For %(direction)s relationship %(rel)s, delete-orphan "
  1910. "cascade is normally "
  1911. 'configured only on the "one" side of a one-to-many '
  1912. "relationship, "
  1913. 'and not on the "many" side of a many-to-one or many-to-many '
  1914. "relationship. "
  1915. "To force this relationship to allow a particular "
  1916. '"%(relatedcls)s" object to be referred towards by only '
  1917. 'a single "%(clsname)s" object at a time via the '
  1918. "%(rel)s relationship, which "
  1919. "would allow "
  1920. "delete-orphan cascade to take place in this direction, set "
  1921. "the single_parent=True flag."
  1922. % {
  1923. "rel": self,
  1924. "direction": "many-to-one"
  1925. if self.direction is MANYTOONE
  1926. else "many-to-many",
  1927. "clsname": self.parent.class_.__name__,
  1928. "relatedcls": self.mapper.class_.__name__,
  1929. },
  1930. code="bbf0",
  1931. )
  1932. if self.passive_deletes == "all" and (
  1933. "delete" in cascade or "delete-orphan" in cascade
  1934. ):
  1935. raise sa_exc.ArgumentError(
  1936. "On %s, can't set passive_deletes='all' in conjunction "
  1937. "with 'delete' or 'delete-orphan' cascade" % self
  1938. )
  1939. if cascade.delete_orphan:
  1940. self.mapper.primary_mapper()._delete_orphans.append(
  1941. (self.key, self.parent.class_)
  1942. )
  1943. def _persists_for(self, mapper):
  1944. """Return True if this property will persist values on behalf
  1945. of the given mapper.
  1946. """
  1947. return (
  1948. self.key in mapper.relationships
  1949. and mapper.relationships[self.key] is self
  1950. )
  1951. def _columns_are_mapped(self, *cols):
  1952. """Return True if all columns in the given collection are
  1953. mapped by the tables referenced by this :class:`.Relationship`.
  1954. """
  1955. for c in cols:
  1956. if (
  1957. self.secondary is not None
  1958. and self.secondary.c.contains_column(c)
  1959. ):
  1960. continue
  1961. if not self.parent.persist_selectable.c.contains_column(
  1962. c
  1963. ) and not self.target.c.contains_column(c):
  1964. return False
  1965. return True
  1966. def _generate_backref(self):
  1967. """Interpret the 'backref' instruction to create a
  1968. :func:`_orm.relationship` complementary to this one."""
  1969. if self.parent.non_primary:
  1970. return
  1971. if self.backref is not None and not self.back_populates:
  1972. if isinstance(self.backref, util.string_types):
  1973. backref_key, kwargs = self.backref, {}
  1974. else:
  1975. backref_key, kwargs = self.backref
  1976. mapper = self.mapper.primary_mapper()
  1977. if not mapper.concrete:
  1978. check = set(mapper.iterate_to_root()).union(
  1979. mapper.self_and_descendants
  1980. )
  1981. for m in check:
  1982. if m.has_property(backref_key) and not m.concrete:
  1983. raise sa_exc.ArgumentError(
  1984. "Error creating backref "
  1985. "'%s' on relationship '%s': property of that "
  1986. "name exists on mapper '%s'"
  1987. % (backref_key, self, m)
  1988. )
  1989. # determine primaryjoin/secondaryjoin for the
  1990. # backref. Use the one we had, so that
  1991. # a custom join doesn't have to be specified in
  1992. # both directions.
  1993. if self.secondary is not None:
  1994. # for many to many, just switch primaryjoin/
  1995. # secondaryjoin. use the annotated
  1996. # pj/sj on the _join_condition.
  1997. pj = kwargs.pop(
  1998. "primaryjoin",
  1999. self._join_condition.secondaryjoin_minus_local,
  2000. )
  2001. sj = kwargs.pop(
  2002. "secondaryjoin",
  2003. self._join_condition.primaryjoin_minus_local,
  2004. )
  2005. else:
  2006. pj = kwargs.pop(
  2007. "primaryjoin",
  2008. self._join_condition.primaryjoin_reverse_remote,
  2009. )
  2010. sj = kwargs.pop("secondaryjoin", None)
  2011. if sj:
  2012. raise sa_exc.InvalidRequestError(
  2013. "Can't assign 'secondaryjoin' on a backref "
  2014. "against a non-secondary relationship."
  2015. )
  2016. foreign_keys = kwargs.pop(
  2017. "foreign_keys", self._user_defined_foreign_keys
  2018. )
  2019. parent = self.parent.primary_mapper()
  2020. kwargs.setdefault("viewonly", self.viewonly)
  2021. kwargs.setdefault("post_update", self.post_update)
  2022. kwargs.setdefault("passive_updates", self.passive_updates)
  2023. kwargs.setdefault("sync_backref", self.sync_backref)
  2024. self.back_populates = backref_key
  2025. relationship = RelationshipProperty(
  2026. parent,
  2027. self.secondary,
  2028. pj,
  2029. sj,
  2030. foreign_keys=foreign_keys,
  2031. back_populates=self.key,
  2032. **kwargs
  2033. )
  2034. mapper._configure_property(backref_key, relationship)
  2035. if self.back_populates:
  2036. self._add_reverse_property(self.back_populates)
  2037. @util.preload_module("sqlalchemy.orm.dependency")
  2038. def _post_init(self):
  2039. dependency = util.preloaded.orm_dependency
  2040. if self.uselist is None:
  2041. self.uselist = self.direction is not MANYTOONE
  2042. if not self.viewonly:
  2043. self._dependency_processor = (
  2044. dependency.DependencyProcessor.from_relationship
  2045. )(self)
  2046. @util.memoized_property
  2047. def _use_get(self):
  2048. """memoize the 'use_get' attribute of this RelationshipLoader's
  2049. lazyloader."""
  2050. strategy = self._lazy_strategy
  2051. return strategy.use_get
  2052. @util.memoized_property
  2053. def _is_self_referential(self):
  2054. return self.mapper.common_parent(self.parent)
  2055. def _create_joins(
  2056. self,
  2057. source_polymorphic=False,
  2058. source_selectable=None,
  2059. dest_selectable=None,
  2060. of_type_entity=None,
  2061. alias_secondary=False,
  2062. extra_criteria=(),
  2063. ):
  2064. aliased = False
  2065. if alias_secondary and self.secondary is not None:
  2066. aliased = True
  2067. if source_selectable is None:
  2068. if source_polymorphic and self.parent.with_polymorphic:
  2069. source_selectable = self.parent._with_polymorphic_selectable
  2070. if of_type_entity:
  2071. dest_mapper = of_type_entity.mapper
  2072. if dest_selectable is None:
  2073. dest_selectable = of_type_entity.selectable
  2074. aliased = True
  2075. else:
  2076. dest_mapper = self.mapper
  2077. if dest_selectable is None:
  2078. dest_selectable = self.entity.selectable
  2079. if self.mapper.with_polymorphic:
  2080. aliased = True
  2081. if self._is_self_referential and source_selectable is None:
  2082. dest_selectable = dest_selectable._anonymous_fromclause()
  2083. aliased = True
  2084. elif (
  2085. dest_selectable is not self.mapper._with_polymorphic_selectable
  2086. or self.mapper.with_polymorphic
  2087. ):
  2088. aliased = True
  2089. single_crit = dest_mapper._single_table_criterion
  2090. aliased = aliased or (
  2091. source_selectable is not None
  2092. and (
  2093. source_selectable
  2094. is not self.parent._with_polymorphic_selectable
  2095. or source_selectable._is_subquery
  2096. )
  2097. )
  2098. (
  2099. primaryjoin,
  2100. secondaryjoin,
  2101. secondary,
  2102. target_adapter,
  2103. dest_selectable,
  2104. ) = self._join_condition.join_targets(
  2105. source_selectable,
  2106. dest_selectable,
  2107. aliased,
  2108. single_crit,
  2109. extra_criteria,
  2110. )
  2111. if source_selectable is None:
  2112. source_selectable = self.parent.local_table
  2113. if dest_selectable is None:
  2114. dest_selectable = self.entity.local_table
  2115. return (
  2116. primaryjoin,
  2117. secondaryjoin,
  2118. source_selectable,
  2119. dest_selectable,
  2120. secondary,
  2121. target_adapter,
  2122. )
  2123. def _annotate_columns(element, annotations):
  2124. def clone(elem):
  2125. if isinstance(elem, expression.ColumnClause):
  2126. elem = elem._annotate(annotations.copy())
  2127. elem._copy_internals(clone=clone)
  2128. return elem
  2129. if element is not None:
  2130. element = clone(element)
  2131. clone = None # remove gc cycles
  2132. return element
  2133. class JoinCondition(object):
  2134. def __init__(
  2135. self,
  2136. parent_persist_selectable,
  2137. child_persist_selectable,
  2138. parent_local_selectable,
  2139. child_local_selectable,
  2140. primaryjoin=None,
  2141. secondary=None,
  2142. secondaryjoin=None,
  2143. parent_equivalents=None,
  2144. child_equivalents=None,
  2145. consider_as_foreign_keys=None,
  2146. local_remote_pairs=None,
  2147. remote_side=None,
  2148. self_referential=False,
  2149. prop=None,
  2150. support_sync=True,
  2151. can_be_synced_fn=lambda *c: True,
  2152. ):
  2153. self.parent_persist_selectable = parent_persist_selectable
  2154. self.parent_local_selectable = parent_local_selectable
  2155. self.child_persist_selectable = child_persist_selectable
  2156. self.child_local_selectable = child_local_selectable
  2157. self.parent_equivalents = parent_equivalents
  2158. self.child_equivalents = child_equivalents
  2159. self.primaryjoin = primaryjoin
  2160. self.secondaryjoin = secondaryjoin
  2161. self.secondary = secondary
  2162. self.consider_as_foreign_keys = consider_as_foreign_keys
  2163. self._local_remote_pairs = local_remote_pairs
  2164. self._remote_side = remote_side
  2165. self.prop = prop
  2166. self.self_referential = self_referential
  2167. self.support_sync = support_sync
  2168. self.can_be_synced_fn = can_be_synced_fn
  2169. self._determine_joins()
  2170. self._sanitize_joins()
  2171. self._annotate_fks()
  2172. self._annotate_remote()
  2173. self._annotate_local()
  2174. self._annotate_parentmapper()
  2175. self._setup_pairs()
  2176. self._check_foreign_cols(self.primaryjoin, True)
  2177. if self.secondaryjoin is not None:
  2178. self._check_foreign_cols(self.secondaryjoin, False)
  2179. self._determine_direction()
  2180. self._check_remote_side()
  2181. self._log_joins()
  2182. def _log_joins(self):
  2183. if self.prop is None:
  2184. return
  2185. log = self.prop.logger
  2186. log.info("%s setup primary join %s", self.prop, self.primaryjoin)
  2187. log.info("%s setup secondary join %s", self.prop, self.secondaryjoin)
  2188. log.info(
  2189. "%s synchronize pairs [%s]",
  2190. self.prop,
  2191. ",".join(
  2192. "(%s => %s)" % (l, r) for (l, r) in self.synchronize_pairs
  2193. ),
  2194. )
  2195. log.info(
  2196. "%s secondary synchronize pairs [%s]",
  2197. self.prop,
  2198. ",".join(
  2199. "(%s => %s)" % (l, r)
  2200. for (l, r) in self.secondary_synchronize_pairs or []
  2201. ),
  2202. )
  2203. log.info(
  2204. "%s local/remote pairs [%s]",
  2205. self.prop,
  2206. ",".join(
  2207. "(%s / %s)" % (l, r) for (l, r) in self.local_remote_pairs
  2208. ),
  2209. )
  2210. log.info(
  2211. "%s remote columns [%s]",
  2212. self.prop,
  2213. ",".join("%s" % col for col in self.remote_columns),
  2214. )
  2215. log.info(
  2216. "%s local columns [%s]",
  2217. self.prop,
  2218. ",".join("%s" % col for col in self.local_columns),
  2219. )
  2220. log.info("%s relationship direction %s", self.prop, self.direction)
  2221. def _sanitize_joins(self):
  2222. """remove the parententity annotation from our join conditions which
  2223. can leak in here based on some declarative patterns and maybe others.
  2224. We'd want to remove "parentmapper" also, but apparently there's
  2225. an exotic use case in _join_fixture_inh_selfref_w_entity
  2226. that relies upon it being present, see :ticket:`3364`.
  2227. """
  2228. self.primaryjoin = _deep_deannotate(
  2229. self.primaryjoin, values=("parententity", "proxy_key")
  2230. )
  2231. if self.secondaryjoin is not None:
  2232. self.secondaryjoin = _deep_deannotate(
  2233. self.secondaryjoin, values=("parententity", "proxy_key")
  2234. )
  2235. def _determine_joins(self):
  2236. """Determine the 'primaryjoin' and 'secondaryjoin' attributes,
  2237. if not passed to the constructor already.
  2238. This is based on analysis of the foreign key relationships
  2239. between the parent and target mapped selectables.
  2240. """
  2241. if self.secondaryjoin is not None and self.secondary is None:
  2242. raise sa_exc.ArgumentError(
  2243. "Property %s specified with secondary "
  2244. "join condition but "
  2245. "no secondary argument" % self.prop
  2246. )
  2247. # find a join between the given mapper's mapped table and
  2248. # the given table. will try the mapper's local table first
  2249. # for more specificity, then if not found will try the more
  2250. # general mapped table, which in the case of inheritance is
  2251. # a join.
  2252. try:
  2253. consider_as_foreign_keys = self.consider_as_foreign_keys or None
  2254. if self.secondary is not None:
  2255. if self.secondaryjoin is None:
  2256. self.secondaryjoin = join_condition(
  2257. self.child_persist_selectable,
  2258. self.secondary,
  2259. a_subset=self.child_local_selectable,
  2260. consider_as_foreign_keys=consider_as_foreign_keys,
  2261. )
  2262. if self.primaryjoin is None:
  2263. self.primaryjoin = join_condition(
  2264. self.parent_persist_selectable,
  2265. self.secondary,
  2266. a_subset=self.parent_local_selectable,
  2267. consider_as_foreign_keys=consider_as_foreign_keys,
  2268. )
  2269. else:
  2270. if self.primaryjoin is None:
  2271. self.primaryjoin = join_condition(
  2272. self.parent_persist_selectable,
  2273. self.child_persist_selectable,
  2274. a_subset=self.parent_local_selectable,
  2275. consider_as_foreign_keys=consider_as_foreign_keys,
  2276. )
  2277. except sa_exc.NoForeignKeysError as nfe:
  2278. if self.secondary is not None:
  2279. util.raise_(
  2280. sa_exc.NoForeignKeysError(
  2281. "Could not determine join "
  2282. "condition between parent/child tables on "
  2283. "relationship %s - there are no foreign keys "
  2284. "linking these tables via secondary table '%s'. "
  2285. "Ensure that referencing columns are associated "
  2286. "with a ForeignKey or ForeignKeyConstraint, or "
  2287. "specify 'primaryjoin' and 'secondaryjoin' "
  2288. "expressions." % (self.prop, self.secondary)
  2289. ),
  2290. from_=nfe,
  2291. )
  2292. else:
  2293. util.raise_(
  2294. sa_exc.NoForeignKeysError(
  2295. "Could not determine join "
  2296. "condition between parent/child tables on "
  2297. "relationship %s - there are no foreign keys "
  2298. "linking these tables. "
  2299. "Ensure that referencing columns are associated "
  2300. "with a ForeignKey or ForeignKeyConstraint, or "
  2301. "specify a 'primaryjoin' expression." % self.prop
  2302. ),
  2303. from_=nfe,
  2304. )
  2305. except sa_exc.AmbiguousForeignKeysError as afe:
  2306. if self.secondary is not None:
  2307. util.raise_(
  2308. sa_exc.AmbiguousForeignKeysError(
  2309. "Could not determine join "
  2310. "condition between parent/child tables on "
  2311. "relationship %s - there are multiple foreign key "
  2312. "paths linking the tables via secondary table '%s'. "
  2313. "Specify the 'foreign_keys' "
  2314. "argument, providing a list of those columns which "
  2315. "should be counted as containing a foreign key "
  2316. "reference from the secondary table to each of the "
  2317. "parent and child tables."
  2318. % (self.prop, self.secondary)
  2319. ),
  2320. from_=afe,
  2321. )
  2322. else:
  2323. util.raise_(
  2324. sa_exc.AmbiguousForeignKeysError(
  2325. "Could not determine join "
  2326. "condition between parent/child tables on "
  2327. "relationship %s - there are multiple foreign key "
  2328. "paths linking the tables. Specify the "
  2329. "'foreign_keys' argument, providing a list of those "
  2330. "columns which should be counted as containing a "
  2331. "foreign key reference to the parent table."
  2332. % self.prop
  2333. ),
  2334. from_=afe,
  2335. )
  2336. @property
  2337. def primaryjoin_minus_local(self):
  2338. return _deep_deannotate(self.primaryjoin, values=("local", "remote"))
  2339. @property
  2340. def secondaryjoin_minus_local(self):
  2341. return _deep_deannotate(self.secondaryjoin, values=("local", "remote"))
  2342. @util.memoized_property
  2343. def primaryjoin_reverse_remote(self):
  2344. """Return the primaryjoin condition suitable for the
  2345. "reverse" direction.
  2346. If the primaryjoin was delivered here with pre-existing
  2347. "remote" annotations, the local/remote annotations
  2348. are reversed. Otherwise, the local/remote annotations
  2349. are removed.
  2350. """
  2351. if self._has_remote_annotations:
  2352. def replace(element):
  2353. if "remote" in element._annotations:
  2354. v = dict(element._annotations)
  2355. del v["remote"]
  2356. v["local"] = True
  2357. return element._with_annotations(v)
  2358. elif "local" in element._annotations:
  2359. v = dict(element._annotations)
  2360. del v["local"]
  2361. v["remote"] = True
  2362. return element._with_annotations(v)
  2363. return visitors.replacement_traverse(self.primaryjoin, {}, replace)
  2364. else:
  2365. if self._has_foreign_annotations:
  2366. # TODO: coverage
  2367. return _deep_deannotate(
  2368. self.primaryjoin, values=("local", "remote")
  2369. )
  2370. else:
  2371. return _deep_deannotate(self.primaryjoin)
  2372. def _has_annotation(self, clause, annotation):
  2373. for col in visitors.iterate(clause, {}):
  2374. if annotation in col._annotations:
  2375. return True
  2376. else:
  2377. return False
  2378. @util.memoized_property
  2379. def _has_foreign_annotations(self):
  2380. return self._has_annotation(self.primaryjoin, "foreign")
  2381. @util.memoized_property
  2382. def _has_remote_annotations(self):
  2383. return self._has_annotation(self.primaryjoin, "remote")
  2384. def _annotate_fks(self):
  2385. """Annotate the primaryjoin and secondaryjoin
  2386. structures with 'foreign' annotations marking columns
  2387. considered as foreign.
  2388. """
  2389. if self._has_foreign_annotations:
  2390. return
  2391. if self.consider_as_foreign_keys:
  2392. self._annotate_from_fk_list()
  2393. else:
  2394. self._annotate_present_fks()
  2395. def _annotate_from_fk_list(self):
  2396. def check_fk(col):
  2397. if col in self.consider_as_foreign_keys:
  2398. return col._annotate({"foreign": True})
  2399. self.primaryjoin = visitors.replacement_traverse(
  2400. self.primaryjoin, {}, check_fk
  2401. )
  2402. if self.secondaryjoin is not None:
  2403. self.secondaryjoin = visitors.replacement_traverse(
  2404. self.secondaryjoin, {}, check_fk
  2405. )
  2406. def _annotate_present_fks(self):
  2407. if self.secondary is not None:
  2408. secondarycols = util.column_set(self.secondary.c)
  2409. else:
  2410. secondarycols = set()
  2411. def is_foreign(a, b):
  2412. if isinstance(a, schema.Column) and isinstance(b, schema.Column):
  2413. if a.references(b):
  2414. return a
  2415. elif b.references(a):
  2416. return b
  2417. if secondarycols:
  2418. if a in secondarycols and b not in secondarycols:
  2419. return a
  2420. elif b in secondarycols and a not in secondarycols:
  2421. return b
  2422. def visit_binary(binary):
  2423. if not isinstance(
  2424. binary.left, sql.ColumnElement
  2425. ) or not isinstance(binary.right, sql.ColumnElement):
  2426. return
  2427. if (
  2428. "foreign" not in binary.left._annotations
  2429. and "foreign" not in binary.right._annotations
  2430. ):
  2431. col = is_foreign(binary.left, binary.right)
  2432. if col is not None:
  2433. if col.compare(binary.left):
  2434. binary.left = binary.left._annotate({"foreign": True})
  2435. elif col.compare(binary.right):
  2436. binary.right = binary.right._annotate(
  2437. {"foreign": True}
  2438. )
  2439. self.primaryjoin = visitors.cloned_traverse(
  2440. self.primaryjoin, {}, {"binary": visit_binary}
  2441. )
  2442. if self.secondaryjoin is not None:
  2443. self.secondaryjoin = visitors.cloned_traverse(
  2444. self.secondaryjoin, {}, {"binary": visit_binary}
  2445. )
  2446. def _refers_to_parent_table(self):
  2447. """Return True if the join condition contains column
  2448. comparisons where both columns are in both tables.
  2449. """
  2450. pt = self.parent_persist_selectable
  2451. mt = self.child_persist_selectable
  2452. result = [False]
  2453. def visit_binary(binary):
  2454. c, f = binary.left, binary.right
  2455. if (
  2456. isinstance(c, expression.ColumnClause)
  2457. and isinstance(f, expression.ColumnClause)
  2458. and pt.is_derived_from(c.table)
  2459. and pt.is_derived_from(f.table)
  2460. and mt.is_derived_from(c.table)
  2461. and mt.is_derived_from(f.table)
  2462. ):
  2463. result[0] = True
  2464. visitors.traverse(self.primaryjoin, {}, {"binary": visit_binary})
  2465. return result[0]
  2466. def _tables_overlap(self):
  2467. """Return True if parent/child tables have some overlap."""
  2468. return selectables_overlap(
  2469. self.parent_persist_selectable, self.child_persist_selectable
  2470. )
  2471. def _annotate_remote(self):
  2472. """Annotate the primaryjoin and secondaryjoin
  2473. structures with 'remote' annotations marking columns
  2474. considered as part of the 'remote' side.
  2475. """
  2476. if self._has_remote_annotations:
  2477. return
  2478. if self.secondary is not None:
  2479. self._annotate_remote_secondary()
  2480. elif self._local_remote_pairs or self._remote_side:
  2481. self._annotate_remote_from_args()
  2482. elif self._refers_to_parent_table():
  2483. self._annotate_selfref(
  2484. lambda col: "foreign" in col._annotations, False
  2485. )
  2486. elif self._tables_overlap():
  2487. self._annotate_remote_with_overlap()
  2488. else:
  2489. self._annotate_remote_distinct_selectables()
  2490. def _annotate_remote_secondary(self):
  2491. """annotate 'remote' in primaryjoin, secondaryjoin
  2492. when 'secondary' is present.
  2493. """
  2494. def repl(element):
  2495. if self.secondary.c.contains_column(element):
  2496. return element._annotate({"remote": True})
  2497. self.primaryjoin = visitors.replacement_traverse(
  2498. self.primaryjoin, {}, repl
  2499. )
  2500. self.secondaryjoin = visitors.replacement_traverse(
  2501. self.secondaryjoin, {}, repl
  2502. )
  2503. def _annotate_selfref(self, fn, remote_side_given):
  2504. """annotate 'remote' in primaryjoin, secondaryjoin
  2505. when the relationship is detected as self-referential.
  2506. """
  2507. def visit_binary(binary):
  2508. equated = binary.left.compare(binary.right)
  2509. if isinstance(binary.left, expression.ColumnClause) and isinstance(
  2510. binary.right, expression.ColumnClause
  2511. ):
  2512. # assume one to many - FKs are "remote"
  2513. if fn(binary.left):
  2514. binary.left = binary.left._annotate({"remote": True})
  2515. if fn(binary.right) and not equated:
  2516. binary.right = binary.right._annotate({"remote": True})
  2517. elif not remote_side_given:
  2518. self._warn_non_column_elements()
  2519. self.primaryjoin = visitors.cloned_traverse(
  2520. self.primaryjoin, {}, {"binary": visit_binary}
  2521. )
  2522. def _annotate_remote_from_args(self):
  2523. """annotate 'remote' in primaryjoin, secondaryjoin
  2524. when the 'remote_side' or '_local_remote_pairs'
  2525. arguments are used.
  2526. """
  2527. if self._local_remote_pairs:
  2528. if self._remote_side:
  2529. raise sa_exc.ArgumentError(
  2530. "remote_side argument is redundant "
  2531. "against more detailed _local_remote_side "
  2532. "argument."
  2533. )
  2534. remote_side = [r for (l, r) in self._local_remote_pairs]
  2535. else:
  2536. remote_side = self._remote_side
  2537. if self._refers_to_parent_table():
  2538. self._annotate_selfref(lambda col: col in remote_side, True)
  2539. else:
  2540. def repl(element):
  2541. # use set() to avoid generating ``__eq__()`` expressions
  2542. # against each element
  2543. if element in set(remote_side):
  2544. return element._annotate({"remote": True})
  2545. self.primaryjoin = visitors.replacement_traverse(
  2546. self.primaryjoin, {}, repl
  2547. )
  2548. def _annotate_remote_with_overlap(self):
  2549. """annotate 'remote' in primaryjoin, secondaryjoin
  2550. when the parent/child tables have some set of
  2551. tables in common, though is not a fully self-referential
  2552. relationship.
  2553. """
  2554. def visit_binary(binary):
  2555. binary.left, binary.right = proc_left_right(
  2556. binary.left, binary.right
  2557. )
  2558. binary.right, binary.left = proc_left_right(
  2559. binary.right, binary.left
  2560. )
  2561. check_entities = (
  2562. self.prop is not None and self.prop.mapper is not self.prop.parent
  2563. )
  2564. def proc_left_right(left, right):
  2565. if isinstance(left, expression.ColumnClause) and isinstance(
  2566. right, expression.ColumnClause
  2567. ):
  2568. if self.child_persist_selectable.c.contains_column(
  2569. right
  2570. ) and self.parent_persist_selectable.c.contains_column(left):
  2571. right = right._annotate({"remote": True})
  2572. elif (
  2573. check_entities
  2574. and right._annotations.get("parentmapper") is self.prop.mapper
  2575. ):
  2576. right = right._annotate({"remote": True})
  2577. elif (
  2578. check_entities
  2579. and left._annotations.get("parentmapper") is self.prop.mapper
  2580. ):
  2581. left = left._annotate({"remote": True})
  2582. else:
  2583. self._warn_non_column_elements()
  2584. return left, right
  2585. self.primaryjoin = visitors.cloned_traverse(
  2586. self.primaryjoin, {}, {"binary": visit_binary}
  2587. )
  2588. def _annotate_remote_distinct_selectables(self):
  2589. """annotate 'remote' in primaryjoin, secondaryjoin
  2590. when the parent/child tables are entirely
  2591. separate.
  2592. """
  2593. def repl(element):
  2594. if self.child_persist_selectable.c.contains_column(element) and (
  2595. not self.parent_local_selectable.c.contains_column(element)
  2596. or self.child_local_selectable.c.contains_column(element)
  2597. ):
  2598. return element._annotate({"remote": True})
  2599. self.primaryjoin = visitors.replacement_traverse(
  2600. self.primaryjoin, {}, repl
  2601. )
  2602. def _warn_non_column_elements(self):
  2603. util.warn(
  2604. "Non-simple column elements in primary "
  2605. "join condition for property %s - consider using "
  2606. "remote() annotations to mark the remote side." % self.prop
  2607. )
  2608. def _annotate_local(self):
  2609. """Annotate the primaryjoin and secondaryjoin
  2610. structures with 'local' annotations.
  2611. This annotates all column elements found
  2612. simultaneously in the parent table
  2613. and the join condition that don't have a
  2614. 'remote' annotation set up from
  2615. _annotate_remote() or user-defined.
  2616. """
  2617. if self._has_annotation(self.primaryjoin, "local"):
  2618. return
  2619. if self._local_remote_pairs:
  2620. local_side = util.column_set(
  2621. [l for (l, r) in self._local_remote_pairs]
  2622. )
  2623. else:
  2624. local_side = util.column_set(self.parent_persist_selectable.c)
  2625. def locals_(elem):
  2626. if "remote" not in elem._annotations and elem in local_side:
  2627. return elem._annotate({"local": True})
  2628. self.primaryjoin = visitors.replacement_traverse(
  2629. self.primaryjoin, {}, locals_
  2630. )
  2631. def _annotate_parentmapper(self):
  2632. if self.prop is None:
  2633. return
  2634. def parentmappers_(elem):
  2635. if "remote" in elem._annotations:
  2636. return elem._annotate({"parentmapper": self.prop.mapper})
  2637. elif "local" in elem._annotations:
  2638. return elem._annotate({"parentmapper": self.prop.parent})
  2639. self.primaryjoin = visitors.replacement_traverse(
  2640. self.primaryjoin, {}, parentmappers_
  2641. )
  2642. def _check_remote_side(self):
  2643. if not self.local_remote_pairs:
  2644. raise sa_exc.ArgumentError(
  2645. "Relationship %s could "
  2646. "not determine any unambiguous local/remote column "
  2647. "pairs based on join condition and remote_side "
  2648. "arguments. "
  2649. "Consider using the remote() annotation to "
  2650. "accurately mark those elements of the join "
  2651. "condition that are on the remote side of "
  2652. "the relationship." % (self.prop,)
  2653. )
  2654. def _check_foreign_cols(self, join_condition, primary):
  2655. """Check the foreign key columns collected and emit error
  2656. messages."""
  2657. can_sync = False
  2658. foreign_cols = self._gather_columns_with_annotation(
  2659. join_condition, "foreign"
  2660. )
  2661. has_foreign = bool(foreign_cols)
  2662. if primary:
  2663. can_sync = bool(self.synchronize_pairs)
  2664. else:
  2665. can_sync = bool(self.secondary_synchronize_pairs)
  2666. if (
  2667. self.support_sync
  2668. and can_sync
  2669. or (not self.support_sync and has_foreign)
  2670. ):
  2671. return
  2672. # from here below is just determining the best error message
  2673. # to report. Check for a join condition using any operator
  2674. # (not just ==), perhaps they need to turn on "viewonly=True".
  2675. if self.support_sync and has_foreign and not can_sync:
  2676. err = (
  2677. "Could not locate any simple equality expressions "
  2678. "involving locally mapped foreign key columns for "
  2679. "%s join condition "
  2680. "'%s' on relationship %s."
  2681. % (
  2682. primary and "primary" or "secondary",
  2683. join_condition,
  2684. self.prop,
  2685. )
  2686. )
  2687. err += (
  2688. " Ensure that referencing columns are associated "
  2689. "with a ForeignKey or ForeignKeyConstraint, or are "
  2690. "annotated in the join condition with the foreign() "
  2691. "annotation. To allow comparison operators other than "
  2692. "'==', the relationship can be marked as viewonly=True."
  2693. )
  2694. raise sa_exc.ArgumentError(err)
  2695. else:
  2696. err = (
  2697. "Could not locate any relevant foreign key columns "
  2698. "for %s join condition '%s' on relationship %s."
  2699. % (
  2700. primary and "primary" or "secondary",
  2701. join_condition,
  2702. self.prop,
  2703. )
  2704. )
  2705. err += (
  2706. " Ensure that referencing columns are associated "
  2707. "with a ForeignKey or ForeignKeyConstraint, or are "
  2708. "annotated in the join condition with the foreign() "
  2709. "annotation."
  2710. )
  2711. raise sa_exc.ArgumentError(err)
  2712. def _determine_direction(self):
  2713. """Determine if this relationship is one to many, many to one,
  2714. many to many.
  2715. """
  2716. if self.secondaryjoin is not None:
  2717. self.direction = MANYTOMANY
  2718. else:
  2719. parentcols = util.column_set(self.parent_persist_selectable.c)
  2720. targetcols = util.column_set(self.child_persist_selectable.c)
  2721. # fk collection which suggests ONETOMANY.
  2722. onetomany_fk = targetcols.intersection(self.foreign_key_columns)
  2723. # fk collection which suggests MANYTOONE.
  2724. manytoone_fk = parentcols.intersection(self.foreign_key_columns)
  2725. if onetomany_fk and manytoone_fk:
  2726. # fks on both sides. test for overlap of local/remote
  2727. # with foreign key.
  2728. # we will gather columns directly from their annotations
  2729. # without deannotating, so that we can distinguish on a column
  2730. # that refers to itself.
  2731. # 1. columns that are both remote and FK suggest
  2732. # onetomany.
  2733. onetomany_local = self._gather_columns_with_annotation(
  2734. self.primaryjoin, "remote", "foreign"
  2735. )
  2736. # 2. columns that are FK but are not remote (e.g. local)
  2737. # suggest manytoone.
  2738. manytoone_local = set(
  2739. [
  2740. c
  2741. for c in self._gather_columns_with_annotation(
  2742. self.primaryjoin, "foreign"
  2743. )
  2744. if "remote" not in c._annotations
  2745. ]
  2746. )
  2747. # 3. if both collections are present, remove columns that
  2748. # refer to themselves. This is for the case of
  2749. # and_(Me.id == Me.remote_id, Me.version == Me.version)
  2750. if onetomany_local and manytoone_local:
  2751. self_equated = self.remote_columns.intersection(
  2752. self.local_columns
  2753. )
  2754. onetomany_local = onetomany_local.difference(self_equated)
  2755. manytoone_local = manytoone_local.difference(self_equated)
  2756. # at this point, if only one or the other collection is
  2757. # present, we know the direction, otherwise it's still
  2758. # ambiguous.
  2759. if onetomany_local and not manytoone_local:
  2760. self.direction = ONETOMANY
  2761. elif manytoone_local and not onetomany_local:
  2762. self.direction = MANYTOONE
  2763. else:
  2764. raise sa_exc.ArgumentError(
  2765. "Can't determine relationship"
  2766. " direction for relationship '%s' - foreign "
  2767. "key columns within the join condition are present "
  2768. "in both the parent and the child's mapped tables. "
  2769. "Ensure that only those columns referring "
  2770. "to a parent column are marked as foreign, "
  2771. "either via the foreign() annotation or "
  2772. "via the foreign_keys argument." % self.prop
  2773. )
  2774. elif onetomany_fk:
  2775. self.direction = ONETOMANY
  2776. elif manytoone_fk:
  2777. self.direction = MANYTOONE
  2778. else:
  2779. raise sa_exc.ArgumentError(
  2780. "Can't determine relationship "
  2781. "direction for relationship '%s' - foreign "
  2782. "key columns are present in neither the parent "
  2783. "nor the child's mapped tables" % self.prop
  2784. )
  2785. def _deannotate_pairs(self, collection):
  2786. """provide deannotation for the various lists of
  2787. pairs, so that using them in hashes doesn't incur
  2788. high-overhead __eq__() comparisons against
  2789. original columns mapped.
  2790. """
  2791. return [(x._deannotate(), y._deannotate()) for x, y in collection]
  2792. def _setup_pairs(self):
  2793. sync_pairs = []
  2794. lrp = util.OrderedSet([])
  2795. secondary_sync_pairs = []
  2796. def go(joincond, collection):
  2797. def visit_binary(binary, left, right):
  2798. if (
  2799. "remote" in right._annotations
  2800. and "remote" not in left._annotations
  2801. and self.can_be_synced_fn(left)
  2802. ):
  2803. lrp.add((left, right))
  2804. elif (
  2805. "remote" in left._annotations
  2806. and "remote" not in right._annotations
  2807. and self.can_be_synced_fn(right)
  2808. ):
  2809. lrp.add((right, left))
  2810. if binary.operator is operators.eq and self.can_be_synced_fn(
  2811. left, right
  2812. ):
  2813. if "foreign" in right._annotations:
  2814. collection.append((left, right))
  2815. elif "foreign" in left._annotations:
  2816. collection.append((right, left))
  2817. visit_binary_product(visit_binary, joincond)
  2818. for joincond, collection in [
  2819. (self.primaryjoin, sync_pairs),
  2820. (self.secondaryjoin, secondary_sync_pairs),
  2821. ]:
  2822. if joincond is None:
  2823. continue
  2824. go(joincond, collection)
  2825. self.local_remote_pairs = self._deannotate_pairs(lrp)
  2826. self.synchronize_pairs = self._deannotate_pairs(sync_pairs)
  2827. self.secondary_synchronize_pairs = self._deannotate_pairs(
  2828. secondary_sync_pairs
  2829. )
  2830. _track_overlapping_sync_targets = weakref.WeakKeyDictionary()
  2831. def _warn_for_conflicting_sync_targets(self):
  2832. if not self.support_sync:
  2833. return
  2834. # we would like to detect if we are synchronizing any column
  2835. # pairs in conflict with another relationship that wishes to sync
  2836. # an entirely different column to the same target. This is a
  2837. # very rare edge case so we will try to minimize the memory/overhead
  2838. # impact of this check
  2839. for from_, to_ in [
  2840. (from_, to_) for (from_, to_) in self.synchronize_pairs
  2841. ] + [
  2842. (from_, to_) for (from_, to_) in self.secondary_synchronize_pairs
  2843. ]:
  2844. # save ourselves a ton of memory and overhead by only
  2845. # considering columns that are subject to a overlapping
  2846. # FK constraints at the core level. This condition can arise
  2847. # if multiple relationships overlap foreign() directly, but
  2848. # we're going to assume it's typically a ForeignKeyConstraint-
  2849. # level configuration that benefits from this warning.
  2850. if to_ not in self._track_overlapping_sync_targets:
  2851. self._track_overlapping_sync_targets[
  2852. to_
  2853. ] = weakref.WeakKeyDictionary({self.prop: from_})
  2854. else:
  2855. other_props = []
  2856. prop_to_from = self._track_overlapping_sync_targets[to_]
  2857. for pr, fr_ in prop_to_from.items():
  2858. if (
  2859. not pr.mapper._dispose_called
  2860. and pr not in self.prop._reverse_property
  2861. and pr.key not in self.prop._overlaps
  2862. and self.prop.key not in pr._overlaps
  2863. # note: the "__*" symbol is used internally by
  2864. # SQLAlchemy as a general means of supressing the
  2865. # overlaps warning for some extension cases, however
  2866. # this is not currently
  2867. # a publicly supported symbol and may change at
  2868. # any time.
  2869. and "__*" not in self.prop._overlaps
  2870. and "__*" not in pr._overlaps
  2871. and not self.prop.parent.is_sibling(pr.parent)
  2872. and not self.prop.mapper.is_sibling(pr.mapper)
  2873. and not self.prop.parent.is_sibling(pr.mapper)
  2874. and not self.prop.mapper.is_sibling(pr.parent)
  2875. and (
  2876. self.prop.key != pr.key
  2877. or not self.prop.parent.common_parent(pr.parent)
  2878. )
  2879. ):
  2880. other_props.append((pr, fr_))
  2881. if other_props:
  2882. util.warn(
  2883. "relationship '%s' will copy column %s to column %s, "
  2884. "which conflicts with relationship(s): %s. "
  2885. "If this is not the intention, consider if these "
  2886. "relationships should be linked with "
  2887. "back_populates, or if viewonly=True should be "
  2888. "applied to one or more if they are read-only. "
  2889. "For the less common case that foreign key "
  2890. "constraints are partially overlapping, the "
  2891. "orm.foreign() "
  2892. "annotation can be used to isolate the columns that "
  2893. "should be written towards. To silence this "
  2894. "warning, add the parameter 'overlaps=\"%s\"' to the "
  2895. "'%s' relationship."
  2896. % (
  2897. self.prop,
  2898. from_,
  2899. to_,
  2900. ", ".join(
  2901. sorted(
  2902. "'%s' (copies %s to %s)" % (pr, fr_, to_)
  2903. for (pr, fr_) in other_props
  2904. )
  2905. ),
  2906. ",".join(sorted(pr.key for pr, fr in other_props)),
  2907. self.prop,
  2908. ),
  2909. code="qzyx",
  2910. )
  2911. self._track_overlapping_sync_targets[to_][self.prop] = from_
  2912. @util.memoized_property
  2913. def remote_columns(self):
  2914. return self._gather_join_annotations("remote")
  2915. @util.memoized_property
  2916. def local_columns(self):
  2917. return self._gather_join_annotations("local")
  2918. @util.memoized_property
  2919. def foreign_key_columns(self):
  2920. return self._gather_join_annotations("foreign")
  2921. def _gather_join_annotations(self, annotation):
  2922. s = set(
  2923. self._gather_columns_with_annotation(self.primaryjoin, annotation)
  2924. )
  2925. if self.secondaryjoin is not None:
  2926. s.update(
  2927. self._gather_columns_with_annotation(
  2928. self.secondaryjoin, annotation
  2929. )
  2930. )
  2931. return {x._deannotate() for x in s}
  2932. def _gather_columns_with_annotation(self, clause, *annotation):
  2933. annotation = set(annotation)
  2934. return set(
  2935. [
  2936. col
  2937. for col in visitors.iterate(clause, {})
  2938. if annotation.issubset(col._annotations)
  2939. ]
  2940. )
  2941. def join_targets(
  2942. self,
  2943. source_selectable,
  2944. dest_selectable,
  2945. aliased,
  2946. single_crit=None,
  2947. extra_criteria=(),
  2948. ):
  2949. """Given a source and destination selectable, create a
  2950. join between them.
  2951. This takes into account aliasing the join clause
  2952. to reference the appropriate corresponding columns
  2953. in the target objects, as well as the extra child
  2954. criterion, equivalent column sets, etc.
  2955. """
  2956. # place a barrier on the destination such that
  2957. # replacement traversals won't ever dig into it.
  2958. # its internal structure remains fixed
  2959. # regardless of context.
  2960. dest_selectable = _shallow_annotate(
  2961. dest_selectable, {"no_replacement_traverse": True}
  2962. )
  2963. primaryjoin, secondaryjoin, secondary = (
  2964. self.primaryjoin,
  2965. self.secondaryjoin,
  2966. self.secondary,
  2967. )
  2968. # adjust the join condition for single table inheritance,
  2969. # in the case that the join is to a subclass
  2970. # this is analogous to the
  2971. # "_adjust_for_single_table_inheritance()" method in Query.
  2972. if single_crit is not None:
  2973. if secondaryjoin is not None:
  2974. secondaryjoin = secondaryjoin & single_crit
  2975. else:
  2976. primaryjoin = primaryjoin & single_crit
  2977. if extra_criteria:
  2978. if secondaryjoin is not None:
  2979. secondaryjoin = secondaryjoin & sql.and_(*extra_criteria)
  2980. else:
  2981. primaryjoin = primaryjoin & sql.and_(*extra_criteria)
  2982. if aliased:
  2983. if secondary is not None:
  2984. secondary = secondary._anonymous_fromclause(flat=True)
  2985. primary_aliasizer = ClauseAdapter(
  2986. secondary, exclude_fn=_ColInAnnotations("local")
  2987. )
  2988. secondary_aliasizer = ClauseAdapter(
  2989. dest_selectable, equivalents=self.child_equivalents
  2990. ).chain(primary_aliasizer)
  2991. if source_selectable is not None:
  2992. primary_aliasizer = ClauseAdapter(
  2993. secondary, exclude_fn=_ColInAnnotations("local")
  2994. ).chain(
  2995. ClauseAdapter(
  2996. source_selectable,
  2997. equivalents=self.parent_equivalents,
  2998. )
  2999. )
  3000. secondaryjoin = secondary_aliasizer.traverse(secondaryjoin)
  3001. else:
  3002. primary_aliasizer = ClauseAdapter(
  3003. dest_selectable,
  3004. exclude_fn=_ColInAnnotations("local"),
  3005. equivalents=self.child_equivalents,
  3006. )
  3007. if source_selectable is not None:
  3008. primary_aliasizer.chain(
  3009. ClauseAdapter(
  3010. source_selectable,
  3011. exclude_fn=_ColInAnnotations("remote"),
  3012. equivalents=self.parent_equivalents,
  3013. )
  3014. )
  3015. secondary_aliasizer = None
  3016. primaryjoin = primary_aliasizer.traverse(primaryjoin)
  3017. target_adapter = secondary_aliasizer or primary_aliasizer
  3018. target_adapter.exclude_fn = None
  3019. else:
  3020. target_adapter = None
  3021. return (
  3022. primaryjoin,
  3023. secondaryjoin,
  3024. secondary,
  3025. target_adapter,
  3026. dest_selectable,
  3027. )
  3028. def create_lazy_clause(self, reverse_direction=False):
  3029. binds = util.column_dict()
  3030. equated_columns = util.column_dict()
  3031. has_secondary = self.secondaryjoin is not None
  3032. if has_secondary:
  3033. lookup = collections.defaultdict(list)
  3034. for l, r in self.local_remote_pairs:
  3035. lookup[l].append((l, r))
  3036. equated_columns[r] = l
  3037. elif not reverse_direction:
  3038. for l, r in self.local_remote_pairs:
  3039. equated_columns[r] = l
  3040. else:
  3041. for l, r in self.local_remote_pairs:
  3042. equated_columns[l] = r
  3043. def col_to_bind(col):
  3044. if (
  3045. (not reverse_direction and "local" in col._annotations)
  3046. or reverse_direction
  3047. and (
  3048. (has_secondary and col in lookup)
  3049. or (not has_secondary and "remote" in col._annotations)
  3050. )
  3051. ):
  3052. if col not in binds:
  3053. binds[col] = sql.bindparam(
  3054. None, None, type_=col.type, unique=True
  3055. )
  3056. return binds[col]
  3057. return None
  3058. lazywhere = self.primaryjoin
  3059. if self.secondaryjoin is None or not reverse_direction:
  3060. lazywhere = visitors.replacement_traverse(
  3061. lazywhere, {}, col_to_bind
  3062. )
  3063. if self.secondaryjoin is not None:
  3064. secondaryjoin = self.secondaryjoin
  3065. if reverse_direction:
  3066. secondaryjoin = visitors.replacement_traverse(
  3067. secondaryjoin, {}, col_to_bind
  3068. )
  3069. lazywhere = sql.and_(lazywhere, secondaryjoin)
  3070. bind_to_col = {binds[col].key: col for col in binds}
  3071. return lazywhere, bind_to_col, equated_columns
  3072. class _ColInAnnotations(object):
  3073. """Serializable object that tests for a name in c._annotations."""
  3074. __slots__ = ("name",)
  3075. def __init__(self, name):
  3076. self.name = name
  3077. def __call__(self, c):
  3078. return self.name in c._annotations