relationships.py 144 KB

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