relationships.py 141 KB

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