mapper.py 139 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627
  1. # orm/mapper.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. """Logic to map Python classes to and from selectables.
  8. Defines the :class:`~sqlalchemy.orm.mapper.Mapper` class, the central
  9. configurational unit which associates a class with a database table.
  10. This is a semi-private module; the main configurational API of the ORM is
  11. available in :class:`~sqlalchemy.orm.`.
  12. """
  13. from __future__ import absolute_import
  14. from collections import deque
  15. from itertools import chain
  16. import sys
  17. import weakref
  18. from . import attributes
  19. from . import exc as orm_exc
  20. from . import instrumentation
  21. from . import loading
  22. from . import properties
  23. from . import util as orm_util
  24. from .base import _class_to_mapper
  25. from .base import _state_mapper
  26. from .base import class_mapper
  27. from .base import state_str
  28. from .interfaces import _MappedAttribute
  29. from .interfaces import EXT_SKIP
  30. from .interfaces import InspectionAttr
  31. from .interfaces import MapperProperty
  32. from .interfaces import ORMEntityColumnsClauseRole
  33. from .interfaces import ORMFromClauseRole
  34. from .path_registry import PathRegistry
  35. from .. import event
  36. from .. import exc as sa_exc
  37. from .. import inspection
  38. from .. import log
  39. from .. import schema
  40. from .. import sql
  41. from .. import util
  42. from ..sql import base as sql_base
  43. from ..sql import coercions
  44. from ..sql import expression
  45. from ..sql import operators
  46. from ..sql import roles
  47. from ..sql import util as sql_util
  48. from ..sql import visitors
  49. from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
  50. from ..util import HasMemoized
  51. _mapper_registries = weakref.WeakKeyDictionary()
  52. _legacy_registry = None
  53. def _all_registries():
  54. with _CONFIGURE_MUTEX:
  55. return set(_mapper_registries)
  56. def _unconfigured_mappers():
  57. for reg in _all_registries():
  58. for mapper in reg._mappers_to_configure():
  59. yield mapper
  60. _already_compiling = False
  61. # a constant returned by _get_attr_by_column to indicate
  62. # this mapper is not handling an attribute for a particular
  63. # column
  64. NO_ATTRIBUTE = util.symbol("NO_ATTRIBUTE")
  65. # lock used to synchronize the "mapper configure" step
  66. _CONFIGURE_MUTEX = util.threading.RLock()
  67. @inspection._self_inspects
  68. @log.class_logger
  69. class Mapper(
  70. ORMFromClauseRole,
  71. ORMEntityColumnsClauseRole,
  72. sql_base.MemoizedHasCacheKey,
  73. InspectionAttr,
  74. ):
  75. """Defines an association between a Python class and a database table or
  76. other relational structure, so that ORM operations against the class may
  77. proceed.
  78. The :class:`_orm.Mapper` object is instantiated using mapping methods
  79. present on the :class:`_orm.registry` object. For information
  80. about instantiating new :class:`_orm.Mapper` objects, see
  81. :ref:`orm_mapping_classes_toplevel`.
  82. """
  83. _dispose_called = False
  84. _ready_for_configure = False
  85. @util.deprecated_params(
  86. non_primary=(
  87. "1.3",
  88. "The :paramref:`.mapper.non_primary` parameter is deprecated, "
  89. "and will be removed in a future release. The functionality "
  90. "of non primary mappers is now better suited using the "
  91. ":class:`.AliasedClass` construct, which can also be used "
  92. "as the target of a :func:`_orm.relationship` in 1.3.",
  93. ),
  94. )
  95. def __init__(
  96. self,
  97. class_,
  98. local_table=None,
  99. properties=None,
  100. primary_key=None,
  101. non_primary=False,
  102. inherits=None,
  103. inherit_condition=None,
  104. inherit_foreign_keys=None,
  105. always_refresh=False,
  106. version_id_col=None,
  107. version_id_generator=None,
  108. polymorphic_on=None,
  109. _polymorphic_map=None,
  110. polymorphic_identity=None,
  111. concrete=False,
  112. with_polymorphic=None,
  113. polymorphic_load=None,
  114. allow_partial_pks=True,
  115. batch=True,
  116. column_prefix=None,
  117. include_properties=None,
  118. exclude_properties=None,
  119. passive_updates=True,
  120. passive_deletes=False,
  121. confirm_deleted_rows=True,
  122. eager_defaults=False,
  123. legacy_is_orphan=False,
  124. _compiled_cache_size=100,
  125. ):
  126. r"""Direct constructor for a new :class:`_orm.Mapper` object.
  127. The :func:`_orm.mapper` function is normally invoked through the
  128. use of the :class:`_orm.registry` object through either the
  129. :ref:`Declarative <orm_declarative_mapping>` or
  130. :ref:`Imperative <orm_imperative_mapping>` mapping styles.
  131. .. versionchanged:: 1.4 The :func:`_orm.mapper` function should not
  132. be called directly for classical mapping; for a classical mapping
  133. configuration, use the :meth:`_orm.registry.map_imperatively`
  134. method. The :func:`_orm.mapper` function may become private in a
  135. future release.
  136. Parameters documented below may be passed to either the
  137. :meth:`_orm.registry.map_imperatively` method, or may be passed in the
  138. ``__mapper_args__`` declarative class attribute described at
  139. :ref:`orm_declarative_mapper_options`.
  140. :param class\_: The class to be mapped. When using Declarative,
  141. this argument is automatically passed as the declared class
  142. itself.
  143. :param local_table: The :class:`_schema.Table` or other selectable
  144. to which the class is mapped. May be ``None`` if
  145. this mapper inherits from another mapper using single-table
  146. inheritance. When using Declarative, this argument is
  147. automatically passed by the extension, based on what
  148. is configured via the ``__table__`` argument or via the
  149. :class:`_schema.Table`
  150. produced as a result of the ``__tablename__``
  151. and :class:`_schema.Column` arguments present.
  152. :param always_refresh: If True, all query operations for this mapped
  153. class will overwrite all data within object instances that already
  154. exist within the session, erasing any in-memory changes with
  155. whatever information was loaded from the database. Usage of this
  156. flag is highly discouraged; as an alternative, see the method
  157. :meth:`_query.Query.populate_existing`.
  158. :param allow_partial_pks: Defaults to True. Indicates that a
  159. composite primary key with some NULL values should be considered as
  160. possibly existing within the database. This affects whether a
  161. mapper will assign an incoming row to an existing identity, as well
  162. as if :meth:`.Session.merge` will check the database first for a
  163. particular primary key value. A "partial primary key" can occur if
  164. one has mapped to an OUTER JOIN, for example.
  165. :param batch: Defaults to ``True``, indicating that save operations
  166. of multiple entities can be batched together for efficiency.
  167. Setting to False indicates
  168. that an instance will be fully saved before saving the next
  169. instance. This is used in the extremely rare case that a
  170. :class:`.MapperEvents` listener requires being called
  171. in between individual row persistence operations.
  172. :param column_prefix: A string which will be prepended
  173. to the mapped attribute name when :class:`_schema.Column`
  174. objects are automatically assigned as attributes to the
  175. mapped class. Does not affect explicitly specified
  176. column-based properties.
  177. See the section :ref:`column_prefix` for an example.
  178. :param concrete: If True, indicates this mapper should use concrete
  179. table inheritance with its parent mapper.
  180. See the section :ref:`concrete_inheritance` for an example.
  181. :param confirm_deleted_rows: defaults to True; when a DELETE occurs
  182. of one more rows based on specific primary keys, a warning is
  183. emitted when the number of rows matched does not equal the number
  184. of rows expected. This parameter may be set to False to handle the
  185. case where database ON DELETE CASCADE rules may be deleting some of
  186. those rows automatically. The warning may be changed to an
  187. exception in a future release.
  188. .. versionadded:: 0.9.4 - added
  189. :paramref:`.mapper.confirm_deleted_rows` as well as conditional
  190. matched row checking on delete.
  191. :param eager_defaults: if True, the ORM will immediately fetch the
  192. value of server-generated default values after an INSERT or UPDATE,
  193. rather than leaving them as expired to be fetched on next access.
  194. This can be used for event schemes where the server-generated values
  195. are needed immediately before the flush completes. By default,
  196. this scheme will emit an individual ``SELECT`` statement per row
  197. inserted or updated, which note can add significant performance
  198. overhead. However, if the
  199. target database supports :term:`RETURNING`, the default values will
  200. be returned inline with the INSERT or UPDATE statement, which can
  201. greatly enhance performance for an application that needs frequent
  202. access to just-generated server defaults.
  203. .. seealso::
  204. :ref:`orm_server_defaults`
  205. .. versionchanged:: 0.9.0 The ``eager_defaults`` option can now
  206. make use of :term:`RETURNING` for backends which support it.
  207. :param exclude_properties: A list or set of string column names to
  208. be excluded from mapping.
  209. See :ref:`include_exclude_cols` for an example.
  210. :param include_properties: An inclusive list or set of string column
  211. names to map.
  212. See :ref:`include_exclude_cols` for an example.
  213. :param inherits: A mapped class or the corresponding
  214. :class:`_orm.Mapper`
  215. of one indicating a superclass to which this :class:`_orm.Mapper`
  216. should *inherit* from. The mapped class here must be a subclass
  217. of the other mapper's class. When using Declarative, this argument
  218. is passed automatically as a result of the natural class
  219. hierarchy of the declared classes.
  220. .. seealso::
  221. :ref:`inheritance_toplevel`
  222. :param inherit_condition: For joined table inheritance, a SQL
  223. expression which will
  224. define how the two tables are joined; defaults to a natural join
  225. between the two tables.
  226. :param inherit_foreign_keys: When ``inherit_condition`` is used and
  227. the columns present are missing a :class:`_schema.ForeignKey`
  228. configuration, this parameter can be used to specify which columns
  229. are "foreign". In most cases can be left as ``None``.
  230. :param legacy_is_orphan: Boolean, defaults to ``False``.
  231. When ``True``, specifies that "legacy" orphan consideration
  232. is to be applied to objects mapped by this mapper, which means
  233. that a pending (that is, not persistent) object is auto-expunged
  234. from an owning :class:`.Session` only when it is de-associated
  235. from *all* parents that specify a ``delete-orphan`` cascade towards
  236. this mapper. The new default behavior is that the object is
  237. auto-expunged when it is de-associated with *any* of its parents
  238. that specify ``delete-orphan`` cascade. This behavior is more
  239. consistent with that of a persistent object, and allows behavior to
  240. be consistent in more scenarios independently of whether or not an
  241. orphan object has been flushed yet or not.
  242. See the change note and example at :ref:`legacy_is_orphan_addition`
  243. for more detail on this change.
  244. :param non_primary: Specify that this :class:`_orm.Mapper`
  245. is in addition
  246. to the "primary" mapper, that is, the one used for persistence.
  247. The :class:`_orm.Mapper` created here may be used for ad-hoc
  248. mapping of the class to an alternate selectable, for loading
  249. only.
  250. .. seealso::
  251. :ref:`relationship_aliased_class` - the new pattern that removes
  252. the need for the :paramref:`_orm.Mapper.non_primary` flag.
  253. :param passive_deletes: Indicates DELETE behavior of foreign key
  254. columns when a joined-table inheritance entity is being deleted.
  255. Defaults to ``False`` for a base mapper; for an inheriting mapper,
  256. defaults to ``False`` unless the value is set to ``True``
  257. on the superclass mapper.
  258. When ``True``, it is assumed that ON DELETE CASCADE is configured
  259. on the foreign key relationships that link this mapper's table
  260. to its superclass table, so that when the unit of work attempts
  261. to delete the entity, it need only emit a DELETE statement for the
  262. superclass table, and not this table.
  263. When ``False``, a DELETE statement is emitted for this mapper's
  264. table individually. If the primary key attributes local to this
  265. table are unloaded, then a SELECT must be emitted in order to
  266. validate these attributes; note that the primary key columns
  267. of a joined-table subclass are not part of the "primary key" of
  268. the object as a whole.
  269. Note that a value of ``True`` is **always** forced onto the
  270. subclass mappers; that is, it's not possible for a superclass
  271. to specify passive_deletes without this taking effect for
  272. all subclass mappers.
  273. .. versionadded:: 1.1
  274. .. seealso::
  275. :ref:`passive_deletes` - description of similar feature as
  276. used with :func:`_orm.relationship`
  277. :paramref:`.mapper.passive_updates` - supporting ON UPDATE
  278. CASCADE for joined-table inheritance mappers
  279. :param passive_updates: Indicates UPDATE behavior of foreign key
  280. columns when a primary key column changes on a joined-table
  281. inheritance mapping. Defaults to ``True``.
  282. When True, it is assumed that ON UPDATE CASCADE is configured on
  283. the foreign key in the database, and that the database will handle
  284. propagation of an UPDATE from a source column to dependent columns
  285. on joined-table rows.
  286. When False, it is assumed that the database does not enforce
  287. referential integrity and will not be issuing its own CASCADE
  288. operation for an update. The unit of work process will
  289. emit an UPDATE statement for the dependent columns during a
  290. primary key change.
  291. .. seealso::
  292. :ref:`passive_updates` - description of a similar feature as
  293. used with :func:`_orm.relationship`
  294. :paramref:`.mapper.passive_deletes` - supporting ON DELETE
  295. CASCADE for joined-table inheritance mappers
  296. :param polymorphic_load: Specifies "polymorphic loading" behavior
  297. for a subclass in an inheritance hierarchy (joined and single
  298. table inheritance only). Valid values are:
  299. * "'inline'" - specifies this class should be part of the
  300. "with_polymorphic" mappers, e.g. its columns will be included
  301. in a SELECT query against the base.
  302. * "'selectin'" - specifies that when instances of this class
  303. are loaded, an additional SELECT will be emitted to retrieve
  304. the columns specific to this subclass. The SELECT uses
  305. IN to fetch multiple subclasses at once.
  306. .. versionadded:: 1.2
  307. .. seealso::
  308. :ref:`with_polymorphic_mapper_config`
  309. :ref:`polymorphic_selectin`
  310. :param polymorphic_on: Specifies the column, attribute, or
  311. SQL expression used to determine the target class for an
  312. incoming row, when inheriting classes are present.
  313. This value is commonly a :class:`_schema.Column` object that's
  314. present in the mapped :class:`_schema.Table`::
  315. class Employee(Base):
  316. __tablename__ = 'employee'
  317. id = Column(Integer, primary_key=True)
  318. discriminator = Column(String(50))
  319. __mapper_args__ = {
  320. "polymorphic_on":discriminator,
  321. "polymorphic_identity":"employee"
  322. }
  323. It may also be specified
  324. as a SQL expression, as in this example where we
  325. use the :func:`.case` construct to provide a conditional
  326. approach::
  327. class Employee(Base):
  328. __tablename__ = 'employee'
  329. id = Column(Integer, primary_key=True)
  330. discriminator = Column(String(50))
  331. __mapper_args__ = {
  332. "polymorphic_on":case([
  333. (discriminator == "EN", "engineer"),
  334. (discriminator == "MA", "manager"),
  335. ], else_="employee"),
  336. "polymorphic_identity":"employee"
  337. }
  338. It may also refer to any attribute
  339. configured with :func:`.column_property`, or to the
  340. string name of one::
  341. class Employee(Base):
  342. __tablename__ = 'employee'
  343. id = Column(Integer, primary_key=True)
  344. discriminator = Column(String(50))
  345. employee_type = column_property(
  346. case([
  347. (discriminator == "EN", "engineer"),
  348. (discriminator == "MA", "manager"),
  349. ], else_="employee")
  350. )
  351. __mapper_args__ = {
  352. "polymorphic_on":employee_type,
  353. "polymorphic_identity":"employee"
  354. }
  355. When setting ``polymorphic_on`` to reference an
  356. attribute or expression that's not present in the
  357. locally mapped :class:`_schema.Table`, yet the value
  358. of the discriminator should be persisted to the database,
  359. the value of the
  360. discriminator is not automatically set on new
  361. instances; this must be handled by the user,
  362. either through manual means or via event listeners.
  363. A typical approach to establishing such a listener
  364. looks like::
  365. from sqlalchemy import event
  366. from sqlalchemy.orm import object_mapper
  367. @event.listens_for(Employee, "init", propagate=True)
  368. def set_identity(instance, *arg, **kw):
  369. mapper = object_mapper(instance)
  370. instance.discriminator = mapper.polymorphic_identity
  371. Where above, we assign the value of ``polymorphic_identity``
  372. for the mapped class to the ``discriminator`` attribute,
  373. thus persisting the value to the ``discriminator`` column
  374. in the database.
  375. .. warning::
  376. Currently, **only one discriminator column may be set**, typically
  377. on the base-most class in the hierarchy. "Cascading" polymorphic
  378. columns are not yet supported.
  379. .. seealso::
  380. :ref:`inheritance_toplevel`
  381. :param polymorphic_identity: Specifies the value which
  382. identifies this particular class as returned by the
  383. column expression referred to by the ``polymorphic_on``
  384. setting. As rows are received, the value corresponding
  385. to the ``polymorphic_on`` column expression is compared
  386. to this value, indicating which subclass should
  387. be used for the newly reconstructed object.
  388. :param properties: A dictionary mapping the string names of object
  389. attributes to :class:`.MapperProperty` instances, which define the
  390. persistence behavior of that attribute. Note that
  391. :class:`_schema.Column`
  392. objects present in
  393. the mapped :class:`_schema.Table` are automatically placed into
  394. ``ColumnProperty`` instances upon mapping, unless overridden.
  395. When using Declarative, this argument is passed automatically,
  396. based on all those :class:`.MapperProperty` instances declared
  397. in the declared class body.
  398. :param primary_key: A list of :class:`_schema.Column`
  399. objects which define
  400. the primary key to be used against this mapper's selectable unit.
  401. This is normally simply the primary key of the ``local_table``, but
  402. can be overridden here.
  403. :param version_id_col: A :class:`_schema.Column`
  404. that will be used to keep a running version id of rows
  405. in the table. This is used to detect concurrent updates or
  406. the presence of stale data in a flush. The methodology is to
  407. detect if an UPDATE statement does not match the last known
  408. version id, a
  409. :class:`~sqlalchemy.orm.exc.StaleDataError` exception is
  410. thrown.
  411. By default, the column must be of :class:`.Integer` type,
  412. unless ``version_id_generator`` specifies an alternative version
  413. generator.
  414. .. seealso::
  415. :ref:`mapper_version_counter` - discussion of version counting
  416. and rationale.
  417. :param version_id_generator: Define how new version ids should
  418. be generated. Defaults to ``None``, which indicates that
  419. a simple integer counting scheme be employed. To provide a custom
  420. versioning scheme, provide a callable function of the form::
  421. def generate_version(version):
  422. return next_version
  423. Alternatively, server-side versioning functions such as triggers,
  424. or programmatic versioning schemes outside of the version id
  425. generator may be used, by specifying the value ``False``.
  426. Please see :ref:`server_side_version_counter` for a discussion
  427. of important points when using this option.
  428. .. versionadded:: 0.9.0 ``version_id_generator`` supports
  429. server-side version number generation.
  430. .. seealso::
  431. :ref:`custom_version_counter`
  432. :ref:`server_side_version_counter`
  433. :param with_polymorphic: A tuple in the form ``(<classes>,
  434. <selectable>)`` indicating the default style of "polymorphic"
  435. loading, that is, which tables are queried at once. <classes> is
  436. any single or list of mappers and/or classes indicating the
  437. inherited classes that should be loaded at once. The special value
  438. ``'*'`` may be used to indicate all descending classes should be
  439. loaded immediately. The second tuple argument <selectable>
  440. indicates a selectable that will be used to query for multiple
  441. classes.
  442. .. seealso::
  443. :ref:`with_polymorphic` - discussion of polymorphic querying
  444. techniques.
  445. """
  446. self.class_ = util.assert_arg_type(class_, type, "class_")
  447. self._sort_key = "%s.%s" % (
  448. self.class_.__module__,
  449. self.class_.__name__,
  450. )
  451. self.class_manager = None
  452. self._primary_key_argument = util.to_list(primary_key)
  453. self.non_primary = non_primary
  454. self.always_refresh = always_refresh
  455. if isinstance(version_id_col, MapperProperty):
  456. self.version_id_prop = version_id_col
  457. self.version_id_col = None
  458. else:
  459. self.version_id_col = version_id_col
  460. if version_id_generator is False:
  461. self.version_id_generator = False
  462. elif version_id_generator is None:
  463. self.version_id_generator = lambda x: (x or 0) + 1
  464. else:
  465. self.version_id_generator = version_id_generator
  466. self.concrete = concrete
  467. self.single = False
  468. self.inherits = inherits
  469. if local_table is not None:
  470. self.local_table = coercions.expect(
  471. roles.StrictFromClauseRole, local_table
  472. )
  473. else:
  474. self.local_table = None
  475. self.inherit_condition = inherit_condition
  476. self.inherit_foreign_keys = inherit_foreign_keys
  477. self._init_properties = properties or {}
  478. self._delete_orphans = []
  479. self.batch = batch
  480. self.eager_defaults = eager_defaults
  481. self.column_prefix = column_prefix
  482. self.polymorphic_on = (
  483. coercions.expect(
  484. roles.ColumnArgumentOrKeyRole,
  485. polymorphic_on,
  486. argname="polymorphic_on",
  487. )
  488. if polymorphic_on is not None
  489. else None
  490. )
  491. self._dependency_processors = []
  492. self.validators = util.EMPTY_DICT
  493. self.passive_updates = passive_updates
  494. self.passive_deletes = passive_deletes
  495. self.legacy_is_orphan = legacy_is_orphan
  496. self._clause_adapter = None
  497. self._requires_row_aliasing = False
  498. self._inherits_equated_pairs = None
  499. self._memoized_values = {}
  500. self._compiled_cache_size = _compiled_cache_size
  501. self._reconstructor = None
  502. self.allow_partial_pks = allow_partial_pks
  503. if self.inherits and not self.concrete:
  504. self.confirm_deleted_rows = False
  505. else:
  506. self.confirm_deleted_rows = confirm_deleted_rows
  507. self._set_with_polymorphic(with_polymorphic)
  508. self.polymorphic_load = polymorphic_load
  509. # our 'polymorphic identity', a string name that when located in a
  510. # result set row indicates this Mapper should be used to construct
  511. # the object instance for that row.
  512. self.polymorphic_identity = polymorphic_identity
  513. # a dictionary of 'polymorphic identity' names, associating those
  514. # names with Mappers that will be used to construct object instances
  515. # upon a select operation.
  516. if _polymorphic_map is None:
  517. self.polymorphic_map = {}
  518. else:
  519. self.polymorphic_map = _polymorphic_map
  520. if include_properties is not None:
  521. self.include_properties = util.to_set(include_properties)
  522. else:
  523. self.include_properties = None
  524. if exclude_properties:
  525. self.exclude_properties = util.to_set(exclude_properties)
  526. else:
  527. self.exclude_properties = None
  528. # prevent this mapper from being constructed
  529. # while a configure_mappers() is occurring (and defer a
  530. # configure_mappers() until construction succeeds)
  531. with _CONFIGURE_MUTEX:
  532. self.dispatch._events._new_mapper_instance(class_, self)
  533. self._configure_inheritance()
  534. self._configure_class_instrumentation()
  535. self._configure_properties()
  536. self._configure_polymorphic_setter()
  537. self._configure_pks()
  538. self.registry._flag_new_mapper(self)
  539. self._log("constructed")
  540. self._expire_memoizations()
  541. # major attributes initialized at the classlevel so that
  542. # they can be Sphinx-documented.
  543. is_mapper = True
  544. """Part of the inspection API."""
  545. represents_outer_join = False
  546. @property
  547. def mapper(self):
  548. """Part of the inspection API.
  549. Returns self.
  550. """
  551. return self
  552. def _gen_cache_key(self, anon_map, bindparams):
  553. return (self,)
  554. @property
  555. def entity(self):
  556. r"""Part of the inspection API.
  557. Returns self.class\_.
  558. """
  559. return self.class_
  560. local_table = None
  561. """The :class:`_expression.Selectable` which this :class:`_orm.Mapper`
  562. manages.
  563. Typically is an instance of :class:`_schema.Table` or
  564. :class:`_expression.Alias`.
  565. May also be ``None``.
  566. The "local" table is the
  567. selectable that the :class:`_orm.Mapper` is directly responsible for
  568. managing from an attribute access and flush perspective. For
  569. non-inheriting mappers, the local table is the same as the
  570. "mapped" table. For joined-table inheritance mappers, local_table
  571. will be the particular sub-table of the overall "join" which
  572. this :class:`_orm.Mapper` represents. If this mapper is a
  573. single-table inheriting mapper, local_table will be ``None``.
  574. .. seealso::
  575. :attr:`_orm.Mapper.persist_selectable`.
  576. """
  577. persist_selectable = None
  578. """The :class:`_expression.Selectable` to which this :class:`_orm.Mapper`
  579. is mapped.
  580. Typically an instance of :class:`_schema.Table`,
  581. :class:`_expression.Join`, or :class:`_expression.Alias`.
  582. The :attr:`_orm.Mapper.persist_selectable` is separate from
  583. :attr:`_orm.Mapper.selectable` in that the former represents columns
  584. that are mapped on this class or its superclasses, whereas the
  585. latter may be a "polymorphic" selectable that contains additional columns
  586. which are in fact mapped on subclasses only.
  587. "persist selectable" is the "thing the mapper writes to" and
  588. "selectable" is the "thing the mapper selects from".
  589. :attr:`_orm.Mapper.persist_selectable` is also separate from
  590. :attr:`_orm.Mapper.local_table`, which represents the set of columns that
  591. are locally mapped on this class directly.
  592. .. seealso::
  593. :attr:`_orm.Mapper.selectable`.
  594. :attr:`_orm.Mapper.local_table`.
  595. """
  596. inherits = None
  597. """References the :class:`_orm.Mapper` which this :class:`_orm.Mapper`
  598. inherits from, if any.
  599. This is a *read only* attribute determined during mapper construction.
  600. Behavior is undefined if directly modified.
  601. """
  602. configured = False
  603. """Represent ``True`` if this :class:`_orm.Mapper` has been configured.
  604. This is a *read only* attribute determined during mapper construction.
  605. Behavior is undefined if directly modified.
  606. .. seealso::
  607. :func:`.configure_mappers`.
  608. """
  609. concrete = None
  610. """Represent ``True`` if this :class:`_orm.Mapper` is a concrete
  611. inheritance mapper.
  612. This is a *read only* attribute determined during mapper construction.
  613. Behavior is undefined if directly modified.
  614. """
  615. tables = None
  616. """An iterable containing the collection of :class:`_schema.Table` objects
  617. which this :class:`_orm.Mapper` is aware of.
  618. If the mapper is mapped to a :class:`_expression.Join`, or an
  619. :class:`_expression.Alias`
  620. representing a :class:`_expression.Select`, the individual
  621. :class:`_schema.Table`
  622. objects that comprise the full construct will be represented here.
  623. This is a *read only* attribute determined during mapper construction.
  624. Behavior is undefined if directly modified.
  625. """
  626. primary_key = None
  627. """An iterable containing the collection of :class:`_schema.Column`
  628. objects
  629. which comprise the 'primary key' of the mapped table, from the
  630. perspective of this :class:`_orm.Mapper`.
  631. This list is against the selectable in
  632. :attr:`_orm.Mapper.persist_selectable`.
  633. In the case of inheriting mappers, some columns may be managed by a
  634. superclass mapper. For example, in the case of a
  635. :class:`_expression.Join`, the
  636. primary key is determined by all of the primary key columns across all
  637. tables referenced by the :class:`_expression.Join`.
  638. The list is also not necessarily the same as the primary key column
  639. collection associated with the underlying tables; the :class:`_orm.Mapper`
  640. features a ``primary_key`` argument that can override what the
  641. :class:`_orm.Mapper` considers as primary key columns.
  642. This is a *read only* attribute determined during mapper construction.
  643. Behavior is undefined if directly modified.
  644. """
  645. class_ = None
  646. """The Python class which this :class:`_orm.Mapper` maps.
  647. This is a *read only* attribute determined during mapper construction.
  648. Behavior is undefined if directly modified.
  649. """
  650. class_manager = None
  651. """The :class:`.ClassManager` which maintains event listeners
  652. and class-bound descriptors for this :class:`_orm.Mapper`.
  653. This is a *read only* attribute determined during mapper construction.
  654. Behavior is undefined if directly modified.
  655. """
  656. single = None
  657. """Represent ``True`` if this :class:`_orm.Mapper` is a single table
  658. inheritance mapper.
  659. :attr:`_orm.Mapper.local_table` will be ``None`` if this flag is set.
  660. This is a *read only* attribute determined during mapper construction.
  661. Behavior is undefined if directly modified.
  662. """
  663. non_primary = None
  664. """Represent ``True`` if this :class:`_orm.Mapper` is a "non-primary"
  665. mapper, e.g. a mapper that is used only to select rows but not for
  666. persistence management.
  667. This is a *read only* attribute determined during mapper construction.
  668. Behavior is undefined if directly modified.
  669. """
  670. polymorphic_on = None
  671. """The :class:`_schema.Column` or SQL expression specified as the
  672. ``polymorphic_on`` argument
  673. for this :class:`_orm.Mapper`, within an inheritance scenario.
  674. This attribute is normally a :class:`_schema.Column` instance but
  675. may also be an expression, such as one derived from
  676. :func:`.cast`.
  677. This is a *read only* attribute determined during mapper construction.
  678. Behavior is undefined if directly modified.
  679. """
  680. polymorphic_map = None
  681. """A mapping of "polymorphic identity" identifiers mapped to
  682. :class:`_orm.Mapper` instances, within an inheritance scenario.
  683. The identifiers can be of any type which is comparable to the
  684. type of column represented by :attr:`_orm.Mapper.polymorphic_on`.
  685. An inheritance chain of mappers will all reference the same
  686. polymorphic map object. The object is used to correlate incoming
  687. result rows to target mappers.
  688. This is a *read only* attribute determined during mapper construction.
  689. Behavior is undefined if directly modified.
  690. """
  691. polymorphic_identity = None
  692. """Represent an identifier which is matched against the
  693. :attr:`_orm.Mapper.polymorphic_on` column during result row loading.
  694. Used only with inheritance, this object can be of any type which is
  695. comparable to the type of column represented by
  696. :attr:`_orm.Mapper.polymorphic_on`.
  697. This is a *read only* attribute determined during mapper construction.
  698. Behavior is undefined if directly modified.
  699. """
  700. base_mapper = None
  701. """The base-most :class:`_orm.Mapper` in an inheritance chain.
  702. In a non-inheriting scenario, this attribute will always be this
  703. :class:`_orm.Mapper`. In an inheritance scenario, it references
  704. the :class:`_orm.Mapper` which is parent to all other :class:`_orm.Mapper`
  705. objects in the inheritance chain.
  706. This is a *read only* attribute determined during mapper construction.
  707. Behavior is undefined if directly modified.
  708. """
  709. columns = None
  710. """A collection of :class:`_schema.Column` or other scalar expression
  711. objects maintained by this :class:`_orm.Mapper`.
  712. The collection behaves the same as that of the ``c`` attribute on
  713. any :class:`_schema.Table` object,
  714. except that only those columns included in
  715. this mapping are present, and are keyed based on the attribute name
  716. defined in the mapping, not necessarily the ``key`` attribute of the
  717. :class:`_schema.Column` itself. Additionally, scalar expressions mapped
  718. by :func:`.column_property` are also present here.
  719. This is a *read only* attribute determined during mapper construction.
  720. Behavior is undefined if directly modified.
  721. """
  722. validators = None
  723. """An immutable dictionary of attributes which have been decorated
  724. using the :func:`_orm.validates` decorator.
  725. The dictionary contains string attribute names as keys
  726. mapped to the actual validation method.
  727. """
  728. c = None
  729. """A synonym for :attr:`_orm.Mapper.columns`."""
  730. @property
  731. @util.deprecated("1.3", "Use .persist_selectable")
  732. def mapped_table(self):
  733. return self.persist_selectable
  734. @util.memoized_property
  735. def _path_registry(self):
  736. return PathRegistry.per_mapper(self)
  737. def _configure_inheritance(self):
  738. """Configure settings related to inheriting and/or inherited mappers
  739. being present."""
  740. # a set of all mappers which inherit from this one.
  741. self._inheriting_mappers = util.WeakSequence()
  742. if self.inherits:
  743. if isinstance(self.inherits, type):
  744. self.inherits = class_mapper(self.inherits, configure=False)
  745. if not issubclass(self.class_, self.inherits.class_):
  746. raise sa_exc.ArgumentError(
  747. "Class '%s' does not inherit from '%s'"
  748. % (self.class_.__name__, self.inherits.class_.__name__)
  749. )
  750. self.dispatch._update(self.inherits.dispatch)
  751. if self.non_primary != self.inherits.non_primary:
  752. np = not self.non_primary and "primary" or "non-primary"
  753. raise sa_exc.ArgumentError(
  754. "Inheritance of %s mapper for class '%s' is "
  755. "only allowed from a %s mapper"
  756. % (np, self.class_.__name__, np)
  757. )
  758. # inherit_condition is optional.
  759. if self.local_table is None:
  760. self.local_table = self.inherits.local_table
  761. self.persist_selectable = self.inherits.persist_selectable
  762. self.single = True
  763. elif self.local_table is not self.inherits.local_table:
  764. if self.concrete:
  765. self.persist_selectable = self.local_table
  766. for mapper in self.iterate_to_root():
  767. if mapper.polymorphic_on is not None:
  768. mapper._requires_row_aliasing = True
  769. else:
  770. if self.inherit_condition is None:
  771. # figure out inherit condition from our table to the
  772. # immediate table of the inherited mapper, not its
  773. # full table which could pull in other stuff we don't
  774. # want (allows test/inheritance.InheritTest4 to pass)
  775. try:
  776. self.inherit_condition = sql_util.join_condition(
  777. self.inherits.local_table, self.local_table
  778. )
  779. except sa_exc.NoForeignKeysError as nfe:
  780. assert self.inherits.local_table is not None
  781. assert self.local_table is not None
  782. util.raise_(
  783. sa_exc.NoForeignKeysError(
  784. "Can't determine the inherit condition "
  785. "between inherited table '%s' and "
  786. "inheriting "
  787. "table '%s'; tables have no "
  788. "foreign key relationships established. "
  789. "Please ensure the inheriting table has "
  790. "a foreign key relationship to the "
  791. "inherited "
  792. "table, or provide an "
  793. "'on clause' using "
  794. "the 'inherit_condition' mapper argument."
  795. % (
  796. self.inherits.local_table.description,
  797. self.local_table.description,
  798. )
  799. ),
  800. replace_context=nfe,
  801. )
  802. except sa_exc.AmbiguousForeignKeysError as afe:
  803. assert self.inherits.local_table is not None
  804. assert self.local_table is not None
  805. util.raise_(
  806. sa_exc.AmbiguousForeignKeysError(
  807. "Can't determine the inherit condition "
  808. "between inherited table '%s' and "
  809. "inheriting "
  810. "table '%s'; tables have more than one "
  811. "foreign key relationship established. "
  812. "Please specify the 'on clause' using "
  813. "the 'inherit_condition' mapper argument."
  814. % (
  815. self.inherits.local_table.description,
  816. self.local_table.description,
  817. )
  818. ),
  819. replace_context=afe,
  820. )
  821. self.persist_selectable = sql.join(
  822. self.inherits.persist_selectable,
  823. self.local_table,
  824. self.inherit_condition,
  825. )
  826. fks = util.to_set(self.inherit_foreign_keys)
  827. self._inherits_equated_pairs = sql_util.criterion_as_pairs(
  828. self.persist_selectable.onclause,
  829. consider_as_foreign_keys=fks,
  830. )
  831. else:
  832. self.persist_selectable = self.local_table
  833. if self.polymorphic_identity is not None and not self.concrete:
  834. self._identity_class = self.inherits._identity_class
  835. else:
  836. self._identity_class = self.class_
  837. if self.version_id_col is None:
  838. self.version_id_col = self.inherits.version_id_col
  839. self.version_id_generator = self.inherits.version_id_generator
  840. elif (
  841. self.inherits.version_id_col is not None
  842. and self.version_id_col is not self.inherits.version_id_col
  843. ):
  844. util.warn(
  845. "Inheriting version_id_col '%s' does not match inherited "
  846. "version_id_col '%s' and will not automatically populate "
  847. "the inherited versioning column. "
  848. "version_id_col should only be specified on "
  849. "the base-most mapper that includes versioning."
  850. % (
  851. self.version_id_col.description,
  852. self.inherits.version_id_col.description,
  853. )
  854. )
  855. self.polymorphic_map = self.inherits.polymorphic_map
  856. self.batch = self.inherits.batch
  857. self.inherits._inheriting_mappers.append(self)
  858. self.base_mapper = self.inherits.base_mapper
  859. self.passive_updates = self.inherits.passive_updates
  860. self.passive_deletes = (
  861. self.inherits.passive_deletes or self.passive_deletes
  862. )
  863. self._all_tables = self.inherits._all_tables
  864. if self.polymorphic_identity is not None:
  865. if self.polymorphic_identity in self.polymorphic_map:
  866. util.warn(
  867. "Reassigning polymorphic association for identity %r "
  868. "from %r to %r: Check for duplicate use of %r as "
  869. "value for polymorphic_identity."
  870. % (
  871. self.polymorphic_identity,
  872. self.polymorphic_map[self.polymorphic_identity],
  873. self,
  874. self.polymorphic_identity,
  875. )
  876. )
  877. self.polymorphic_map[self.polymorphic_identity] = self
  878. if self.polymorphic_load and self.concrete:
  879. raise sa_exc.ArgumentError(
  880. "polymorphic_load is not currently supported "
  881. "with concrete table inheritance"
  882. )
  883. if self.polymorphic_load == "inline":
  884. self.inherits._add_with_polymorphic_subclass(self)
  885. elif self.polymorphic_load == "selectin":
  886. pass
  887. elif self.polymorphic_load is not None:
  888. raise sa_exc.ArgumentError(
  889. "unknown argument for polymorphic_load: %r"
  890. % self.polymorphic_load
  891. )
  892. else:
  893. self._all_tables = set()
  894. self.base_mapper = self
  895. self.persist_selectable = self.local_table
  896. if self.polymorphic_identity is not None:
  897. self.polymorphic_map[self.polymorphic_identity] = self
  898. self._identity_class = self.class_
  899. if self.persist_selectable is None:
  900. raise sa_exc.ArgumentError(
  901. "Mapper '%s' does not have a persist_selectable specified."
  902. % self
  903. )
  904. def _set_with_polymorphic(self, with_polymorphic):
  905. if with_polymorphic == "*":
  906. self.with_polymorphic = ("*", None)
  907. elif isinstance(with_polymorphic, (tuple, list)):
  908. if isinstance(
  909. with_polymorphic[0], util.string_types + (tuple, list)
  910. ):
  911. self.with_polymorphic = with_polymorphic
  912. else:
  913. self.with_polymorphic = (with_polymorphic, None)
  914. elif with_polymorphic is not None:
  915. raise sa_exc.ArgumentError("Invalid setting for with_polymorphic")
  916. else:
  917. self.with_polymorphic = None
  918. if self.with_polymorphic and self.with_polymorphic[1] is not None:
  919. self.with_polymorphic = (
  920. self.with_polymorphic[0],
  921. coercions.expect(
  922. roles.StrictFromClauseRole,
  923. self.with_polymorphic[1],
  924. allow_select=True,
  925. ),
  926. )
  927. if self.configured:
  928. self._expire_memoizations()
  929. def _add_with_polymorphic_subclass(self, mapper):
  930. subcl = mapper.class_
  931. if self.with_polymorphic is None:
  932. self._set_with_polymorphic((subcl,))
  933. elif self.with_polymorphic[0] != "*":
  934. self._set_with_polymorphic(
  935. (self.with_polymorphic[0] + (subcl,), self.with_polymorphic[1])
  936. )
  937. def _set_concrete_base(self, mapper):
  938. """Set the given :class:`_orm.Mapper` as the 'inherits' for this
  939. :class:`_orm.Mapper`, assuming this :class:`_orm.Mapper` is concrete
  940. and does not already have an inherits."""
  941. assert self.concrete
  942. assert not self.inherits
  943. assert isinstance(mapper, Mapper)
  944. self.inherits = mapper
  945. self.inherits.polymorphic_map.update(self.polymorphic_map)
  946. self.polymorphic_map = self.inherits.polymorphic_map
  947. for mapper in self.iterate_to_root():
  948. if mapper.polymorphic_on is not None:
  949. mapper._requires_row_aliasing = True
  950. self.batch = self.inherits.batch
  951. for mp in self.self_and_descendants:
  952. mp.base_mapper = self.inherits.base_mapper
  953. self.inherits._inheriting_mappers.append(self)
  954. self.passive_updates = self.inherits.passive_updates
  955. self._all_tables = self.inherits._all_tables
  956. for key, prop in mapper._props.items():
  957. if key not in self._props and not self._should_exclude(
  958. key, key, local=False, column=None
  959. ):
  960. self._adapt_inherited_property(key, prop, False)
  961. def _set_polymorphic_on(self, polymorphic_on):
  962. self.polymorphic_on = polymorphic_on
  963. self._configure_polymorphic_setter(True)
  964. def _configure_class_instrumentation(self):
  965. """If this mapper is to be a primary mapper (i.e. the
  966. non_primary flag is not set), associate this Mapper with the
  967. given class and entity name.
  968. Subsequent calls to ``class_mapper()`` for the ``class_`` / ``entity``
  969. name combination will return this mapper. Also decorate the
  970. `__init__` method on the mapped class to include optional
  971. auto-session attachment logic.
  972. """
  973. # we expect that declarative has applied the class manager
  974. # already and set up a registry. if this is None,
  975. # we will emit a deprecation warning below when we also see that
  976. # it has no registry.
  977. manager = attributes.manager_of_class(self.class_)
  978. if self.non_primary:
  979. if not manager or not manager.is_mapped:
  980. raise sa_exc.InvalidRequestError(
  981. "Class %s has no primary mapper configured. Configure "
  982. "a primary mapper first before setting up a non primary "
  983. "Mapper." % self.class_
  984. )
  985. self.class_manager = manager
  986. self.registry = manager.registry
  987. self._identity_class = manager.mapper._identity_class
  988. manager.registry._add_non_primary_mapper(self)
  989. return
  990. if manager is not None:
  991. assert manager.class_ is self.class_
  992. if manager.is_mapped:
  993. # changed in #7579:
  994. # this message is defined in two places as of this change,
  995. # also in decl_api -> _add_manager(). in 2.0, this codepath
  996. # is removed as any calls to mapper() / Mapper without
  997. # the registry setting up first will be rejected.
  998. raise sa_exc.ArgumentError(
  999. "Class '%s' already has a primary mapper defined. "
  1000. % self.class_
  1001. )
  1002. # else:
  1003. # a ClassManager may already exist as
  1004. # ClassManager.instrument_attribute() creates
  1005. # new managers for each subclass if they don't yet exist.
  1006. self.dispatch.instrument_class(self, self.class_)
  1007. # this invokes the class_instrument event and sets up
  1008. # the __init__ method. documented behavior is that this must
  1009. # occur after the instrument_class event above.
  1010. # yes two events with the same two words reversed and different APIs.
  1011. # :(
  1012. manager = instrumentation.register_class(
  1013. self.class_,
  1014. mapper=self,
  1015. expired_attribute_loader=util.partial(
  1016. loading.load_scalar_attributes, self
  1017. ),
  1018. # finalize flag means instrument the __init__ method
  1019. # and call the class_instrument event
  1020. finalize=True,
  1021. )
  1022. if not manager.registry:
  1023. util.warn_deprecated_20(
  1024. "Calling the mapper() function directly outside of a "
  1025. "declarative registry is deprecated."
  1026. " Please use the sqlalchemy.orm.registry.map_imperatively() "
  1027. "function for a classical mapping."
  1028. )
  1029. assert _legacy_registry is not None
  1030. _legacy_registry._add_manager(manager)
  1031. self.class_manager = manager
  1032. self.registry = manager.registry
  1033. # The remaining members can be added by any mapper,
  1034. # e_name None or not.
  1035. if manager.mapper is None:
  1036. return
  1037. event.listen(manager, "init", _event_on_init, raw=True)
  1038. for key, method in util.iterate_attributes(self.class_):
  1039. if key == "__init__" and hasattr(method, "_sa_original_init"):
  1040. method = method._sa_original_init
  1041. if hasattr(method, "__func__"):
  1042. method = method.__func__
  1043. if callable(method):
  1044. if hasattr(method, "__sa_reconstructor__"):
  1045. self._reconstructor = method
  1046. event.listen(manager, "load", _event_on_load, raw=True)
  1047. elif hasattr(method, "__sa_validators__"):
  1048. validation_opts = method.__sa_validation_opts__
  1049. for name in method.__sa_validators__:
  1050. if name in self.validators:
  1051. raise sa_exc.InvalidRequestError(
  1052. "A validation function for mapped "
  1053. "attribute %r on mapper %s already exists."
  1054. % (name, self)
  1055. )
  1056. self.validators = self.validators.union(
  1057. {name: (method, validation_opts)}
  1058. )
  1059. def _set_dispose_flags(self):
  1060. self.configured = True
  1061. self._ready_for_configure = True
  1062. self._dispose_called = True
  1063. self.__dict__.pop("_configure_failed", None)
  1064. def _configure_pks(self):
  1065. self.tables = sql_util.find_tables(self.persist_selectable)
  1066. self._pks_by_table = {}
  1067. self._cols_by_table = {}
  1068. all_cols = util.column_set(
  1069. chain(*[col.proxy_set for col in self._columntoproperty])
  1070. )
  1071. pk_cols = util.column_set(c for c in all_cols if c.primary_key)
  1072. # identify primary key columns which are also mapped by this mapper.
  1073. tables = set(self.tables + [self.persist_selectable])
  1074. self._all_tables.update(tables)
  1075. for t in tables:
  1076. if t.primary_key and pk_cols.issuperset(t.primary_key):
  1077. # ordering is important since it determines the ordering of
  1078. # mapper.primary_key (and therefore query.get())
  1079. self._pks_by_table[t] = util.ordered_column_set(
  1080. t.primary_key
  1081. ).intersection(pk_cols)
  1082. self._cols_by_table[t] = util.ordered_column_set(t.c).intersection(
  1083. all_cols
  1084. )
  1085. # if explicit PK argument sent, add those columns to the
  1086. # primary key mappings
  1087. if self._primary_key_argument:
  1088. for k in self._primary_key_argument:
  1089. if k.table not in self._pks_by_table:
  1090. self._pks_by_table[k.table] = util.OrderedSet()
  1091. self._pks_by_table[k.table].add(k)
  1092. # otherwise, see that we got a full PK for the mapped table
  1093. elif (
  1094. self.persist_selectable not in self._pks_by_table
  1095. or len(self._pks_by_table[self.persist_selectable]) == 0
  1096. ):
  1097. raise sa_exc.ArgumentError(
  1098. "Mapper %s could not assemble any primary "
  1099. "key columns for mapped table '%s'"
  1100. % (self, self.persist_selectable.description)
  1101. )
  1102. elif self.local_table not in self._pks_by_table and isinstance(
  1103. self.local_table, schema.Table
  1104. ):
  1105. util.warn(
  1106. "Could not assemble any primary "
  1107. "keys for locally mapped table '%s' - "
  1108. "no rows will be persisted in this Table."
  1109. % self.local_table.description
  1110. )
  1111. if (
  1112. self.inherits
  1113. and not self.concrete
  1114. and not self._primary_key_argument
  1115. ):
  1116. # if inheriting, the "primary key" for this mapper is
  1117. # that of the inheriting (unless concrete or explicit)
  1118. self.primary_key = self.inherits.primary_key
  1119. else:
  1120. # determine primary key from argument or persist_selectable pks -
  1121. # reduce to the minimal set of columns
  1122. if self._primary_key_argument:
  1123. primary_key = sql_util.reduce_columns(
  1124. [
  1125. self.persist_selectable.corresponding_column(c)
  1126. for c in self._primary_key_argument
  1127. ],
  1128. ignore_nonexistent_tables=True,
  1129. )
  1130. else:
  1131. primary_key = sql_util.reduce_columns(
  1132. self._pks_by_table[self.persist_selectable],
  1133. ignore_nonexistent_tables=True,
  1134. )
  1135. if len(primary_key) == 0:
  1136. raise sa_exc.ArgumentError(
  1137. "Mapper %s could not assemble any primary "
  1138. "key columns for mapped table '%s'"
  1139. % (self, self.persist_selectable.description)
  1140. )
  1141. self.primary_key = tuple(primary_key)
  1142. self._log("Identified primary key columns: %s", primary_key)
  1143. # determine cols that aren't expressed within our tables; mark these
  1144. # as "read only" properties which are refreshed upon INSERT/UPDATE
  1145. self._readonly_props = set(
  1146. self._columntoproperty[col]
  1147. for col in self._columntoproperty
  1148. if self._columntoproperty[col] not in self._identity_key_props
  1149. and (
  1150. not hasattr(col, "table")
  1151. or col.table not in self._cols_by_table
  1152. )
  1153. )
  1154. def _configure_properties(self):
  1155. # Column and other ClauseElement objects which are mapped
  1156. # TODO: technically this should be a DedupeColumnCollection
  1157. # however DCC needs changes and more tests to fully cover
  1158. # storing columns under a separate key name
  1159. self.columns = self.c = sql_base.ColumnCollection()
  1160. # object attribute names mapped to MapperProperty objects
  1161. self._props = util.OrderedDict()
  1162. # table columns mapped to lists of MapperProperty objects
  1163. # using a list allows a single column to be defined as
  1164. # populating multiple object attributes
  1165. self._columntoproperty = _ColumnMapping(self)
  1166. # load custom properties
  1167. if self._init_properties:
  1168. for key, prop in self._init_properties.items():
  1169. self._configure_property(key, prop, False)
  1170. # pull properties from the inherited mapper if any.
  1171. if self.inherits:
  1172. for key, prop in self.inherits._props.items():
  1173. if key not in self._props and not self._should_exclude(
  1174. key, key, local=False, column=None
  1175. ):
  1176. self._adapt_inherited_property(key, prop, False)
  1177. # create properties for each column in the mapped table,
  1178. # for those columns which don't already map to a property
  1179. for column in self.persist_selectable.columns:
  1180. if column in self._columntoproperty:
  1181. continue
  1182. column_key = (self.column_prefix or "") + column.key
  1183. if self._should_exclude(
  1184. column.key,
  1185. column_key,
  1186. local=self.local_table.c.contains_column(column),
  1187. column=column,
  1188. ):
  1189. continue
  1190. # adjust the "key" used for this column to that
  1191. # of the inheriting mapper
  1192. for mapper in self.iterate_to_root():
  1193. if column in mapper._columntoproperty:
  1194. column_key = mapper._columntoproperty[column].key
  1195. self._configure_property(
  1196. column_key, column, init=False, setparent=True
  1197. )
  1198. def _configure_polymorphic_setter(self, init=False):
  1199. """Configure an attribute on the mapper representing the
  1200. 'polymorphic_on' column, if applicable, and not
  1201. already generated by _configure_properties (which is typical).
  1202. Also create a setter function which will assign this
  1203. attribute to the value of the 'polymorphic_identity'
  1204. upon instance construction, also if applicable. This
  1205. routine will run when an instance is created.
  1206. """
  1207. setter = False
  1208. if self.polymorphic_on is not None:
  1209. setter = True
  1210. if isinstance(self.polymorphic_on, util.string_types):
  1211. # polymorphic_on specified as a string - link
  1212. # it to mapped ColumnProperty
  1213. try:
  1214. self.polymorphic_on = self._props[self.polymorphic_on]
  1215. except KeyError as err:
  1216. util.raise_(
  1217. sa_exc.ArgumentError(
  1218. "Can't determine polymorphic_on "
  1219. "value '%s' - no attribute is "
  1220. "mapped to this name." % self.polymorphic_on
  1221. ),
  1222. replace_context=err,
  1223. )
  1224. if self.polymorphic_on in self._columntoproperty:
  1225. # polymorphic_on is a column that is already mapped
  1226. # to a ColumnProperty
  1227. prop = self._columntoproperty[self.polymorphic_on]
  1228. elif isinstance(self.polymorphic_on, MapperProperty):
  1229. # polymorphic_on is directly a MapperProperty,
  1230. # ensure it's a ColumnProperty
  1231. if not isinstance(
  1232. self.polymorphic_on, properties.ColumnProperty
  1233. ):
  1234. raise sa_exc.ArgumentError(
  1235. "Only direct column-mapped "
  1236. "property or SQL expression "
  1237. "can be passed for polymorphic_on"
  1238. )
  1239. prop = self.polymorphic_on
  1240. else:
  1241. # polymorphic_on is a Column or SQL expression and
  1242. # doesn't appear to be mapped. this means it can be 1.
  1243. # only present in the with_polymorphic selectable or
  1244. # 2. a totally standalone SQL expression which we'd
  1245. # hope is compatible with this mapper's persist_selectable
  1246. col = self.persist_selectable.corresponding_column(
  1247. self.polymorphic_on
  1248. )
  1249. if col is None:
  1250. # polymorphic_on doesn't derive from any
  1251. # column/expression isn't present in the mapped
  1252. # table. we will make a "hidden" ColumnProperty
  1253. # for it. Just check that if it's directly a
  1254. # schema.Column and we have with_polymorphic, it's
  1255. # likely a user error if the schema.Column isn't
  1256. # represented somehow in either persist_selectable or
  1257. # with_polymorphic. Otherwise as of 0.7.4 we
  1258. # just go with it and assume the user wants it
  1259. # that way (i.e. a CASE statement)
  1260. setter = False
  1261. instrument = False
  1262. col = self.polymorphic_on
  1263. if isinstance(col, schema.Column) and (
  1264. self.with_polymorphic is None
  1265. or self.with_polymorphic[1].corresponding_column(col)
  1266. is None
  1267. ):
  1268. raise sa_exc.InvalidRequestError(
  1269. "Could not map polymorphic_on column "
  1270. "'%s' to the mapped table - polymorphic "
  1271. "loads will not function properly"
  1272. % col.description
  1273. )
  1274. else:
  1275. # column/expression that polymorphic_on derives from
  1276. # is present in our mapped table
  1277. # and is probably mapped, but polymorphic_on itself
  1278. # is not. This happens when
  1279. # the polymorphic_on is only directly present in the
  1280. # with_polymorphic selectable, as when use
  1281. # polymorphic_union.
  1282. # we'll make a separate ColumnProperty for it.
  1283. instrument = True
  1284. key = getattr(col, "key", None)
  1285. if key:
  1286. if self._should_exclude(col.key, col.key, False, col):
  1287. raise sa_exc.InvalidRequestError(
  1288. "Cannot exclude or override the "
  1289. "discriminator column %r" % col.key
  1290. )
  1291. else:
  1292. self.polymorphic_on = col = col.label("_sa_polymorphic_on")
  1293. key = col.key
  1294. prop = properties.ColumnProperty(col, _instrument=instrument)
  1295. self._configure_property(key, prop, init=init, setparent=True)
  1296. # the actual polymorphic_on should be the first public-facing
  1297. # column in the property
  1298. self.polymorphic_on = prop.columns[0]
  1299. polymorphic_key = prop.key
  1300. else:
  1301. # no polymorphic_on was set.
  1302. # check inheriting mappers for one.
  1303. for mapper in self.iterate_to_root():
  1304. # determine if polymorphic_on of the parent
  1305. # should be propagated here. If the col
  1306. # is present in our mapped table, or if our mapped
  1307. # table is the same as the parent (i.e. single table
  1308. # inheritance), we can use it
  1309. if mapper.polymorphic_on is not None:
  1310. if self.persist_selectable is mapper.persist_selectable:
  1311. self.polymorphic_on = mapper.polymorphic_on
  1312. else:
  1313. self.polymorphic_on = (
  1314. self.persist_selectable
  1315. ).corresponding_column(mapper.polymorphic_on)
  1316. # we can use the parent mapper's _set_polymorphic_identity
  1317. # directly; it ensures the polymorphic_identity of the
  1318. # instance's mapper is used so is portable to subclasses.
  1319. if self.polymorphic_on is not None:
  1320. self._set_polymorphic_identity = (
  1321. mapper._set_polymorphic_identity
  1322. )
  1323. self._validate_polymorphic_identity = (
  1324. mapper._validate_polymorphic_identity
  1325. )
  1326. else:
  1327. self._set_polymorphic_identity = None
  1328. return
  1329. if setter:
  1330. def _set_polymorphic_identity(state):
  1331. dict_ = state.dict
  1332. state.get_impl(polymorphic_key).set(
  1333. state,
  1334. dict_,
  1335. state.manager.mapper.polymorphic_identity,
  1336. None,
  1337. )
  1338. def _validate_polymorphic_identity(mapper, state, dict_):
  1339. if (
  1340. polymorphic_key in dict_
  1341. and dict_[polymorphic_key]
  1342. not in mapper._acceptable_polymorphic_identities
  1343. ):
  1344. util.warn_limited(
  1345. "Flushing object %s with "
  1346. "incompatible polymorphic identity %r; the "
  1347. "object may not refresh and/or load correctly",
  1348. (state_str(state), dict_[polymorphic_key]),
  1349. )
  1350. self._set_polymorphic_identity = _set_polymorphic_identity
  1351. self._validate_polymorphic_identity = (
  1352. _validate_polymorphic_identity
  1353. )
  1354. else:
  1355. self._set_polymorphic_identity = None
  1356. _validate_polymorphic_identity = None
  1357. @HasMemoized.memoized_attribute
  1358. def _version_id_prop(self):
  1359. if self.version_id_col is not None:
  1360. return self._columntoproperty[self.version_id_col]
  1361. else:
  1362. return None
  1363. @HasMemoized.memoized_attribute
  1364. def _acceptable_polymorphic_identities(self):
  1365. identities = set()
  1366. stack = deque([self])
  1367. while stack:
  1368. item = stack.popleft()
  1369. if item.persist_selectable is self.persist_selectable:
  1370. identities.add(item.polymorphic_identity)
  1371. stack.extend(item._inheriting_mappers)
  1372. return identities
  1373. @HasMemoized.memoized_attribute
  1374. def _prop_set(self):
  1375. return frozenset(self._props.values())
  1376. @util.preload_module("sqlalchemy.orm.descriptor_props")
  1377. def _adapt_inherited_property(self, key, prop, init):
  1378. descriptor_props = util.preloaded.orm_descriptor_props
  1379. if not self.concrete:
  1380. self._configure_property(key, prop, init=False, setparent=False)
  1381. elif key not in self._props:
  1382. # determine if the class implements this attribute; if not,
  1383. # or if it is implemented by the attribute that is handling the
  1384. # given superclass-mapped property, then we need to report that we
  1385. # can't use this at the instance level since we are a concrete
  1386. # mapper and we don't map this. don't trip user-defined
  1387. # descriptors that might have side effects when invoked.
  1388. implementing_attribute = self.class_manager._get_class_attr_mro(
  1389. key, prop
  1390. )
  1391. if implementing_attribute is prop or (
  1392. isinstance(
  1393. implementing_attribute, attributes.InstrumentedAttribute
  1394. )
  1395. and implementing_attribute._parententity is prop.parent
  1396. ):
  1397. self._configure_property(
  1398. key,
  1399. descriptor_props.ConcreteInheritedProperty(),
  1400. init=init,
  1401. setparent=True,
  1402. )
  1403. @util.preload_module("sqlalchemy.orm.descriptor_props")
  1404. def _configure_property(self, key, prop, init=True, setparent=True):
  1405. descriptor_props = util.preloaded.orm_descriptor_props
  1406. self._log("_configure_property(%s, %s)", key, prop.__class__.__name__)
  1407. if not isinstance(prop, MapperProperty):
  1408. prop = self._property_from_column(key, prop)
  1409. if isinstance(prop, properties.ColumnProperty):
  1410. col = self.persist_selectable.corresponding_column(prop.columns[0])
  1411. # if the column is not present in the mapped table,
  1412. # test if a column has been added after the fact to the
  1413. # parent table (or their parent, etc.) [ticket:1570]
  1414. if col is None and self.inherits:
  1415. path = [self]
  1416. for m in self.inherits.iterate_to_root():
  1417. col = m.local_table.corresponding_column(prop.columns[0])
  1418. if col is not None:
  1419. for m2 in path:
  1420. m2.persist_selectable._refresh_for_new_column(col)
  1421. col = self.persist_selectable.corresponding_column(
  1422. prop.columns[0]
  1423. )
  1424. break
  1425. path.append(m)
  1426. # subquery expression, column not present in the mapped
  1427. # selectable.
  1428. if col is None:
  1429. col = prop.columns[0]
  1430. # column is coming in after _readonly_props was
  1431. # initialized; check for 'readonly'
  1432. if hasattr(self, "_readonly_props") and (
  1433. not hasattr(col, "table")
  1434. or col.table not in self._cols_by_table
  1435. ):
  1436. self._readonly_props.add(prop)
  1437. else:
  1438. # if column is coming in after _cols_by_table was
  1439. # initialized, ensure the col is in the right set
  1440. if (
  1441. hasattr(self, "_cols_by_table")
  1442. and col.table in self._cols_by_table
  1443. and col not in self._cols_by_table[col.table]
  1444. ):
  1445. self._cols_by_table[col.table].add(col)
  1446. # if this properties.ColumnProperty represents the "polymorphic
  1447. # discriminator" column, mark it. We'll need this when rendering
  1448. # columns in SELECT statements.
  1449. if not hasattr(prop, "_is_polymorphic_discriminator"):
  1450. prop._is_polymorphic_discriminator = (
  1451. col is self.polymorphic_on
  1452. or prop.columns[0] is self.polymorphic_on
  1453. )
  1454. if isinstance(col, expression.Label):
  1455. # new in 1.4, get column property against expressions
  1456. # to be addressable in subqueries
  1457. col.key = col._tq_key_label = key
  1458. self.columns.add(col, key)
  1459. for col in prop.columns + prop._orig_columns:
  1460. for col in col.proxy_set:
  1461. self._columntoproperty[col] = prop
  1462. prop.key = key
  1463. if setparent:
  1464. prop.set_parent(self, init)
  1465. if key in self._props and getattr(
  1466. self._props[key], "_mapped_by_synonym", False
  1467. ):
  1468. syn = self._props[key]._mapped_by_synonym
  1469. raise sa_exc.ArgumentError(
  1470. "Can't call map_column=True for synonym %r=%r, "
  1471. "a ColumnProperty already exists keyed to the name "
  1472. "%r for column %r" % (syn, key, key, syn)
  1473. )
  1474. if (
  1475. key in self._props
  1476. and not isinstance(prop, properties.ColumnProperty)
  1477. and not isinstance(
  1478. self._props[key],
  1479. (
  1480. properties.ColumnProperty,
  1481. descriptor_props.ConcreteInheritedProperty,
  1482. ),
  1483. )
  1484. ):
  1485. util.warn(
  1486. "Property %s on %s being replaced with new "
  1487. "property %s; the old property will be discarded"
  1488. % (self._props[key], self, prop)
  1489. )
  1490. oldprop = self._props[key]
  1491. self._path_registry.pop(oldprop, None)
  1492. self._props[key] = prop
  1493. if not self.non_primary:
  1494. prop.instrument_class(self)
  1495. for mapper in self._inheriting_mappers:
  1496. mapper._adapt_inherited_property(key, prop, init)
  1497. if init:
  1498. prop.init()
  1499. prop.post_instrument_class(self)
  1500. if self.configured:
  1501. self._expire_memoizations()
  1502. @util.preload_module("sqlalchemy.orm.descriptor_props")
  1503. def _property_from_column(self, key, prop):
  1504. """generate/update a :class:`.ColumnProperty` given a
  1505. :class:`_schema.Column` object."""
  1506. descriptor_props = util.preloaded.orm_descriptor_props
  1507. # we were passed a Column or a list of Columns;
  1508. # generate a properties.ColumnProperty
  1509. columns = util.to_list(prop)
  1510. column = columns[0]
  1511. assert isinstance(column, expression.ColumnElement)
  1512. prop = self._props.get(key, None)
  1513. if isinstance(prop, properties.ColumnProperty):
  1514. if (
  1515. (
  1516. not self._inherits_equated_pairs
  1517. or (prop.columns[0], column)
  1518. not in self._inherits_equated_pairs
  1519. )
  1520. and not prop.columns[0].shares_lineage(column)
  1521. and prop.columns[0] is not self.version_id_col
  1522. and column is not self.version_id_col
  1523. ):
  1524. warn_only = prop.parent is not self
  1525. msg = (
  1526. "Implicitly combining column %s with column "
  1527. "%s under attribute '%s'. Please configure one "
  1528. "or more attributes for these same-named columns "
  1529. "explicitly." % (prop.columns[-1], column, key)
  1530. )
  1531. if warn_only:
  1532. util.warn(msg)
  1533. else:
  1534. raise sa_exc.InvalidRequestError(msg)
  1535. # existing properties.ColumnProperty from an inheriting
  1536. # mapper. make a copy and append our column to it
  1537. prop = prop.copy()
  1538. prop.columns.insert(0, column)
  1539. self._log(
  1540. "inserting column to existing list "
  1541. "in properties.ColumnProperty %s" % (key)
  1542. )
  1543. return prop
  1544. elif prop is None or isinstance(
  1545. prop, descriptor_props.ConcreteInheritedProperty
  1546. ):
  1547. mapped_column = []
  1548. for c in columns:
  1549. mc = self.persist_selectable.corresponding_column(c)
  1550. if mc is None:
  1551. mc = self.local_table.corresponding_column(c)
  1552. if mc is not None:
  1553. # if the column is in the local table but not the
  1554. # mapped table, this corresponds to adding a
  1555. # column after the fact to the local table.
  1556. # [ticket:1523]
  1557. self.persist_selectable._refresh_for_new_column(mc)
  1558. mc = self.persist_selectable.corresponding_column(c)
  1559. if mc is None:
  1560. raise sa_exc.ArgumentError(
  1561. "When configuring property '%s' on %s, "
  1562. "column '%s' is not represented in the mapper's "
  1563. "table. Use the `column_property()` function to "
  1564. "force this column to be mapped as a read-only "
  1565. "attribute." % (key, self, c)
  1566. )
  1567. mapped_column.append(mc)
  1568. return properties.ColumnProperty(*mapped_column)
  1569. else:
  1570. raise sa_exc.ArgumentError(
  1571. "WARNING: when configuring property '%s' on %s, "
  1572. "column '%s' conflicts with property '%r'. "
  1573. "To resolve this, map the column to the class under a "
  1574. "different name in the 'properties' dictionary. Or, "
  1575. "to remove all awareness of the column entirely "
  1576. "(including its availability as a foreign key), "
  1577. "use the 'include_properties' or 'exclude_properties' "
  1578. "mapper arguments to control specifically which table "
  1579. "columns get mapped." % (key, self, column.key, prop)
  1580. )
  1581. def _check_configure(self):
  1582. if self.registry._new_mappers:
  1583. _configure_registries({self.registry}, cascade=True)
  1584. def _post_configure_properties(self):
  1585. """Call the ``init()`` method on all ``MapperProperties``
  1586. attached to this mapper.
  1587. This is a deferred configuration step which is intended
  1588. to execute once all mappers have been constructed.
  1589. """
  1590. self._log("_post_configure_properties() started")
  1591. l = [(key, prop) for key, prop in self._props.items()]
  1592. for key, prop in l:
  1593. self._log("initialize prop %s", key)
  1594. if prop.parent is self and not prop._configure_started:
  1595. prop.init()
  1596. if prop._configure_finished:
  1597. prop.post_instrument_class(self)
  1598. self._log("_post_configure_properties() complete")
  1599. self.configured = True
  1600. def add_properties(self, dict_of_properties):
  1601. """Add the given dictionary of properties to this mapper,
  1602. using `add_property`.
  1603. """
  1604. for key, value in dict_of_properties.items():
  1605. self.add_property(key, value)
  1606. def add_property(self, key, prop):
  1607. """Add an individual MapperProperty to this mapper.
  1608. If the mapper has not been configured yet, just adds the
  1609. property to the initial properties dictionary sent to the
  1610. constructor. If this Mapper has already been configured, then
  1611. the given MapperProperty is configured immediately.
  1612. """
  1613. self._init_properties[key] = prop
  1614. self._configure_property(key, prop, init=self.configured)
  1615. def _expire_memoizations(self):
  1616. for mapper in self.iterate_to_root():
  1617. mapper._reset_memoizations()
  1618. @property
  1619. def _log_desc(self):
  1620. return (
  1621. "("
  1622. + self.class_.__name__
  1623. + "|"
  1624. + (
  1625. self.local_table is not None
  1626. and self.local_table.description
  1627. or str(self.local_table)
  1628. )
  1629. + (self.non_primary and "|non-primary" or "")
  1630. + ")"
  1631. )
  1632. def _log(self, msg, *args):
  1633. self.logger.info("%s " + msg, *((self._log_desc,) + args))
  1634. def _log_debug(self, msg, *args):
  1635. self.logger.debug("%s " + msg, *((self._log_desc,) + args))
  1636. def __repr__(self):
  1637. return "<Mapper at 0x%x; %s>" % (id(self), self.class_.__name__)
  1638. def __str__(self):
  1639. return "mapped class %s%s->%s" % (
  1640. self.class_.__name__,
  1641. self.non_primary and " (non-primary)" or "",
  1642. self.local_table.description
  1643. if self.local_table is not None
  1644. else self.persist_selectable.description,
  1645. )
  1646. def _is_orphan(self, state):
  1647. orphan_possible = False
  1648. for mapper in self.iterate_to_root():
  1649. for (key, cls) in mapper._delete_orphans:
  1650. orphan_possible = True
  1651. has_parent = attributes.manager_of_class(cls).has_parent(
  1652. state, key, optimistic=state.has_identity
  1653. )
  1654. if self.legacy_is_orphan and has_parent:
  1655. return False
  1656. elif not self.legacy_is_orphan and not has_parent:
  1657. return True
  1658. if self.legacy_is_orphan:
  1659. return orphan_possible
  1660. else:
  1661. return False
  1662. def has_property(self, key):
  1663. return key in self._props
  1664. def get_property(self, key, _configure_mappers=True):
  1665. """return a MapperProperty associated with the given key."""
  1666. if _configure_mappers:
  1667. self._check_configure()
  1668. try:
  1669. return self._props[key]
  1670. except KeyError as err:
  1671. util.raise_(
  1672. sa_exc.InvalidRequestError(
  1673. "Mapper '%s' has no property '%s'" % (self, key)
  1674. ),
  1675. replace_context=err,
  1676. )
  1677. def get_property_by_column(self, column):
  1678. """Given a :class:`_schema.Column` object, return the
  1679. :class:`.MapperProperty` which maps this column."""
  1680. return self._columntoproperty[column]
  1681. @property
  1682. def iterate_properties(self):
  1683. """return an iterator of all MapperProperty objects."""
  1684. self._check_configure()
  1685. return iter(self._props.values())
  1686. def _mappers_from_spec(self, spec, selectable):
  1687. """given a with_polymorphic() argument, return the set of mappers it
  1688. represents.
  1689. Trims the list of mappers to just those represented within the given
  1690. selectable, if present. This helps some more legacy-ish mappings.
  1691. """
  1692. if spec == "*":
  1693. mappers = list(self.self_and_descendants)
  1694. elif spec:
  1695. mappers = set()
  1696. for m in util.to_list(spec):
  1697. m = _class_to_mapper(m)
  1698. if not m.isa(self):
  1699. raise sa_exc.InvalidRequestError(
  1700. "%r does not inherit from %r" % (m, self)
  1701. )
  1702. if selectable is None:
  1703. mappers.update(m.iterate_to_root())
  1704. else:
  1705. mappers.add(m)
  1706. mappers = [m for m in self.self_and_descendants if m in mappers]
  1707. else:
  1708. mappers = []
  1709. if selectable is not None:
  1710. tables = set(
  1711. sql_util.find_tables(selectable, include_aliases=True)
  1712. )
  1713. mappers = [m for m in mappers if m.local_table in tables]
  1714. return mappers
  1715. def _selectable_from_mappers(self, mappers, innerjoin):
  1716. """given a list of mappers (assumed to be within this mapper's
  1717. inheritance hierarchy), construct an outerjoin amongst those mapper's
  1718. mapped tables.
  1719. """
  1720. from_obj = self.persist_selectable
  1721. for m in mappers:
  1722. if m is self:
  1723. continue
  1724. if m.concrete:
  1725. raise sa_exc.InvalidRequestError(
  1726. "'with_polymorphic()' requires 'selectable' argument "
  1727. "when concrete-inheriting mappers are used."
  1728. )
  1729. elif not m.single:
  1730. if innerjoin:
  1731. from_obj = from_obj.join(
  1732. m.local_table, m.inherit_condition
  1733. )
  1734. else:
  1735. from_obj = from_obj.outerjoin(
  1736. m.local_table, m.inherit_condition
  1737. )
  1738. return from_obj
  1739. @HasMemoized.memoized_attribute
  1740. def _single_table_criterion(self):
  1741. if self.single and self.inherits and self.polymorphic_on is not None:
  1742. return self.polymorphic_on._annotate({"parentmapper": self}).in_(
  1743. m.polymorphic_identity for m in self.self_and_descendants
  1744. )
  1745. else:
  1746. return None
  1747. @HasMemoized.memoized_attribute
  1748. def _with_polymorphic_mappers(self):
  1749. self._check_configure()
  1750. if not self.with_polymorphic:
  1751. return []
  1752. return self._mappers_from_spec(*self.with_polymorphic)
  1753. @HasMemoized.memoized_attribute
  1754. def _post_inspect(self):
  1755. """This hook is invoked by attribute inspection.
  1756. E.g. when Query calls:
  1757. coercions.expect(roles.ColumnsClauseRole, ent, keep_inspect=True)
  1758. This allows the inspection process run a configure mappers hook.
  1759. """
  1760. self._check_configure()
  1761. @HasMemoized.memoized_attribute
  1762. def _with_polymorphic_selectable(self):
  1763. if not self.with_polymorphic:
  1764. return self.persist_selectable
  1765. spec, selectable = self.with_polymorphic
  1766. if selectable is not None:
  1767. return selectable
  1768. else:
  1769. return self._selectable_from_mappers(
  1770. self._mappers_from_spec(spec, selectable), False
  1771. )
  1772. with_polymorphic_mappers = _with_polymorphic_mappers
  1773. """The list of :class:`_orm.Mapper` objects included in the
  1774. default "polymorphic" query.
  1775. """
  1776. @HasMemoized.memoized_attribute
  1777. def _insert_cols_evaluating_none(self):
  1778. return dict(
  1779. (
  1780. table,
  1781. frozenset(
  1782. col for col in columns if col.type.should_evaluate_none
  1783. ),
  1784. )
  1785. for table, columns in self._cols_by_table.items()
  1786. )
  1787. @HasMemoized.memoized_attribute
  1788. def _insert_cols_as_none(self):
  1789. return dict(
  1790. (
  1791. table,
  1792. frozenset(
  1793. col.key
  1794. for col in columns
  1795. if not col.primary_key
  1796. and not col.server_default
  1797. and not col.default
  1798. and not col.type.should_evaluate_none
  1799. ),
  1800. )
  1801. for table, columns in self._cols_by_table.items()
  1802. )
  1803. @HasMemoized.memoized_attribute
  1804. def _propkey_to_col(self):
  1805. return dict(
  1806. (
  1807. table,
  1808. dict(
  1809. (self._columntoproperty[col].key, col) for col in columns
  1810. ),
  1811. )
  1812. for table, columns in self._cols_by_table.items()
  1813. )
  1814. @HasMemoized.memoized_attribute
  1815. def _pk_keys_by_table(self):
  1816. return dict(
  1817. (table, frozenset([col.key for col in pks]))
  1818. for table, pks in self._pks_by_table.items()
  1819. )
  1820. @HasMemoized.memoized_attribute
  1821. def _pk_attr_keys_by_table(self):
  1822. return dict(
  1823. (
  1824. table,
  1825. frozenset([self._columntoproperty[col].key for col in pks]),
  1826. )
  1827. for table, pks in self._pks_by_table.items()
  1828. )
  1829. @HasMemoized.memoized_attribute
  1830. def _server_default_cols(self):
  1831. return dict(
  1832. (
  1833. table,
  1834. frozenset(
  1835. [
  1836. col.key
  1837. for col in columns
  1838. if col.server_default is not None
  1839. ]
  1840. ),
  1841. )
  1842. for table, columns in self._cols_by_table.items()
  1843. )
  1844. @HasMemoized.memoized_attribute
  1845. def _server_default_plus_onupdate_propkeys(self):
  1846. result = set()
  1847. for table, columns in self._cols_by_table.items():
  1848. for col in columns:
  1849. if (
  1850. col.server_default is not None
  1851. or col.server_onupdate is not None
  1852. ) and col in self._columntoproperty:
  1853. result.add(self._columntoproperty[col].key)
  1854. return result
  1855. @HasMemoized.memoized_attribute
  1856. def _server_onupdate_default_cols(self):
  1857. return dict(
  1858. (
  1859. table,
  1860. frozenset(
  1861. [
  1862. col.key
  1863. for col in columns
  1864. if col.server_onupdate is not None
  1865. ]
  1866. ),
  1867. )
  1868. for table, columns in self._cols_by_table.items()
  1869. )
  1870. @HasMemoized.memoized_instancemethod
  1871. def __clause_element__(self):
  1872. annotations = {
  1873. "entity_namespace": self,
  1874. "parententity": self,
  1875. "parentmapper": self,
  1876. }
  1877. if self.persist_selectable is not self.local_table:
  1878. # joined table inheritance, with polymorphic selectable,
  1879. # etc.
  1880. annotations["dml_table"] = self.local_table._annotate(
  1881. {
  1882. "entity_namespace": self,
  1883. "parententity": self,
  1884. "parentmapper": self,
  1885. }
  1886. )._set_propagate_attrs(
  1887. {"compile_state_plugin": "orm", "plugin_subject": self}
  1888. )
  1889. return self.selectable._annotate(annotations)._set_propagate_attrs(
  1890. {"compile_state_plugin": "orm", "plugin_subject": self}
  1891. )
  1892. @util.memoized_property
  1893. def select_identity_token(self):
  1894. return (
  1895. expression.null()
  1896. ._annotate(
  1897. {
  1898. "entity_namespace": self,
  1899. "parententity": self,
  1900. "parentmapper": self,
  1901. "identity_token": True,
  1902. }
  1903. )
  1904. ._set_propagate_attrs(
  1905. {"compile_state_plugin": "orm", "plugin_subject": self}
  1906. )
  1907. )
  1908. @property
  1909. def selectable(self):
  1910. """The :class:`_schema.FromClause` construct this
  1911. :class:`_orm.Mapper` selects from by default.
  1912. Normally, this is equivalent to :attr:`.persist_selectable`, unless
  1913. the ``with_polymorphic`` feature is in use, in which case the
  1914. full "polymorphic" selectable is returned.
  1915. """
  1916. return self._with_polymorphic_selectable
  1917. def _with_polymorphic_args(
  1918. self, spec=None, selectable=False, innerjoin=False
  1919. ):
  1920. if selectable not in (None, False):
  1921. selectable = coercions.expect(
  1922. roles.StrictFromClauseRole, selectable, allow_select=True
  1923. )
  1924. if self.with_polymorphic:
  1925. if not spec:
  1926. spec = self.with_polymorphic[0]
  1927. if selectable is False:
  1928. selectable = self.with_polymorphic[1]
  1929. elif selectable is False:
  1930. selectable = None
  1931. mappers = self._mappers_from_spec(spec, selectable)
  1932. if selectable is not None:
  1933. return mappers, selectable
  1934. else:
  1935. return mappers, self._selectable_from_mappers(mappers, innerjoin)
  1936. @HasMemoized.memoized_attribute
  1937. def _polymorphic_properties(self):
  1938. return list(
  1939. self._iterate_polymorphic_properties(
  1940. self._with_polymorphic_mappers
  1941. )
  1942. )
  1943. @property
  1944. def _all_column_expressions(self):
  1945. poly_properties = self._polymorphic_properties
  1946. adapter = self._polymorphic_adapter
  1947. return [
  1948. adapter.columns[prop.columns[0]] if adapter else prop.columns[0]
  1949. for prop in poly_properties
  1950. if isinstance(prop, properties.ColumnProperty)
  1951. and prop._renders_in_subqueries
  1952. ]
  1953. def _columns_plus_keys(self, polymorphic_mappers=()):
  1954. if polymorphic_mappers:
  1955. poly_properties = self._iterate_polymorphic_properties(
  1956. polymorphic_mappers
  1957. )
  1958. else:
  1959. poly_properties = self._polymorphic_properties
  1960. return [
  1961. (prop.key, prop.columns[0])
  1962. for prop in poly_properties
  1963. if isinstance(prop, properties.ColumnProperty)
  1964. ]
  1965. @HasMemoized.memoized_attribute
  1966. def _polymorphic_adapter(self):
  1967. if self.with_polymorphic:
  1968. return sql_util.ColumnAdapter(
  1969. self.selectable, equivalents=self._equivalent_columns
  1970. )
  1971. else:
  1972. return None
  1973. def _iterate_polymorphic_properties(self, mappers=None):
  1974. """Return an iterator of MapperProperty objects which will render into
  1975. a SELECT."""
  1976. if mappers is None:
  1977. mappers = self._with_polymorphic_mappers
  1978. if not mappers:
  1979. for c in self.iterate_properties:
  1980. yield c
  1981. else:
  1982. # in the polymorphic case, filter out discriminator columns
  1983. # from other mappers, as these are sometimes dependent on that
  1984. # mapper's polymorphic selectable (which we don't want rendered)
  1985. for c in util.unique_list(
  1986. chain(
  1987. *[
  1988. list(mapper.iterate_properties)
  1989. for mapper in [self] + mappers
  1990. ]
  1991. )
  1992. ):
  1993. if getattr(c, "_is_polymorphic_discriminator", False) and (
  1994. self.polymorphic_on is None
  1995. or c.columns[0] is not self.polymorphic_on
  1996. ):
  1997. continue
  1998. yield c
  1999. @HasMemoized.memoized_attribute
  2000. def attrs(self):
  2001. """A namespace of all :class:`.MapperProperty` objects
  2002. associated this mapper.
  2003. This is an object that provides each property based on
  2004. its key name. For instance, the mapper for a
  2005. ``User`` class which has ``User.name`` attribute would
  2006. provide ``mapper.attrs.name``, which would be the
  2007. :class:`.ColumnProperty` representing the ``name``
  2008. column. The namespace object can also be iterated,
  2009. which would yield each :class:`.MapperProperty`.
  2010. :class:`_orm.Mapper` has several pre-filtered views
  2011. of this attribute which limit the types of properties
  2012. returned, including :attr:`.synonyms`, :attr:`.column_attrs`,
  2013. :attr:`.relationships`, and :attr:`.composites`.
  2014. .. warning::
  2015. The :attr:`_orm.Mapper.attrs` accessor namespace is an
  2016. instance of :class:`.OrderedProperties`. This is
  2017. a dictionary-like object which includes a small number of
  2018. named methods such as :meth:`.OrderedProperties.items`
  2019. and :meth:`.OrderedProperties.values`. When
  2020. accessing attributes dynamically, favor using the dict-access
  2021. scheme, e.g. ``mapper.attrs[somename]`` over
  2022. ``getattr(mapper.attrs, somename)`` to avoid name collisions.
  2023. .. seealso::
  2024. :attr:`_orm.Mapper.all_orm_descriptors`
  2025. """
  2026. self._check_configure()
  2027. return util.ImmutableProperties(self._props)
  2028. @HasMemoized.memoized_attribute
  2029. def all_orm_descriptors(self):
  2030. """A namespace of all :class:`.InspectionAttr` attributes associated
  2031. with the mapped class.
  2032. These attributes are in all cases Python :term:`descriptors`
  2033. associated with the mapped class or its superclasses.
  2034. This namespace includes attributes that are mapped to the class
  2035. as well as attributes declared by extension modules.
  2036. It includes any Python descriptor type that inherits from
  2037. :class:`.InspectionAttr`. This includes
  2038. :class:`.QueryableAttribute`, as well as extension types such as
  2039. :class:`.hybrid_property`, :class:`.hybrid_method` and
  2040. :class:`.AssociationProxy`.
  2041. To distinguish between mapped attributes and extension attributes,
  2042. the attribute :attr:`.InspectionAttr.extension_type` will refer
  2043. to a constant that distinguishes between different extension types.
  2044. The sorting of the attributes is based on the following rules:
  2045. 1. Iterate through the class and its superclasses in order from
  2046. subclass to superclass (i.e. iterate through ``cls.__mro__``)
  2047. 2. For each class, yield the attributes in the order in which they
  2048. appear in ``__dict__``, with the exception of those in step
  2049. 3 below. In Python 3.6 and above this ordering will be the
  2050. same as that of the class' construction, with the exception
  2051. of attributes that were added after the fact by the application
  2052. or the mapper.
  2053. 3. If a certain attribute key is also in the superclass ``__dict__``,
  2054. then it's included in the iteration for that class, and not the
  2055. class in which it first appeared.
  2056. The above process produces an ordering that is deterministic in terms
  2057. of the order in which attributes were assigned to the class.
  2058. .. versionchanged:: 1.3.19 ensured deterministic ordering for
  2059. :meth:`_orm.Mapper.all_orm_descriptors`.
  2060. When dealing with a :class:`.QueryableAttribute`, the
  2061. :attr:`.QueryableAttribute.property` attribute refers to the
  2062. :class:`.MapperProperty` property, which is what you get when
  2063. referring to the collection of mapped properties via
  2064. :attr:`_orm.Mapper.attrs`.
  2065. .. warning::
  2066. The :attr:`_orm.Mapper.all_orm_descriptors`
  2067. accessor namespace is an
  2068. instance of :class:`.OrderedProperties`. This is
  2069. a dictionary-like object which includes a small number of
  2070. named methods such as :meth:`.OrderedProperties.items`
  2071. and :meth:`.OrderedProperties.values`. When
  2072. accessing attributes dynamically, favor using the dict-access
  2073. scheme, e.g. ``mapper.all_orm_descriptors[somename]`` over
  2074. ``getattr(mapper.all_orm_descriptors, somename)`` to avoid name
  2075. collisions.
  2076. .. seealso::
  2077. :attr:`_orm.Mapper.attrs`
  2078. """
  2079. return util.ImmutableProperties(
  2080. dict(self.class_manager._all_sqla_attributes())
  2081. )
  2082. @HasMemoized.memoized_attribute
  2083. @util.preload_module("sqlalchemy.orm.descriptor_props")
  2084. def synonyms(self):
  2085. """Return a namespace of all :class:`.SynonymProperty`
  2086. properties maintained by this :class:`_orm.Mapper`.
  2087. .. seealso::
  2088. :attr:`_orm.Mapper.attrs` - namespace of all
  2089. :class:`.MapperProperty`
  2090. objects.
  2091. """
  2092. descriptor_props = util.preloaded.orm_descriptor_props
  2093. return self._filter_properties(descriptor_props.SynonymProperty)
  2094. @property
  2095. def entity_namespace(self):
  2096. return self.class_
  2097. @HasMemoized.memoized_attribute
  2098. def column_attrs(self):
  2099. """Return a namespace of all :class:`.ColumnProperty`
  2100. properties maintained by this :class:`_orm.Mapper`.
  2101. .. seealso::
  2102. :attr:`_orm.Mapper.attrs` - namespace of all
  2103. :class:`.MapperProperty`
  2104. objects.
  2105. """
  2106. return self._filter_properties(properties.ColumnProperty)
  2107. @util.preload_module("sqlalchemy.orm.relationships")
  2108. @HasMemoized.memoized_attribute
  2109. def relationships(self):
  2110. """A namespace of all :class:`.RelationshipProperty` properties
  2111. maintained by this :class:`_orm.Mapper`.
  2112. .. warning::
  2113. the :attr:`_orm.Mapper.relationships` accessor namespace is an
  2114. instance of :class:`.OrderedProperties`. This is
  2115. a dictionary-like object which includes a small number of
  2116. named methods such as :meth:`.OrderedProperties.items`
  2117. and :meth:`.OrderedProperties.values`. When
  2118. accessing attributes dynamically, favor using the dict-access
  2119. scheme, e.g. ``mapper.relationships[somename]`` over
  2120. ``getattr(mapper.relationships, somename)`` to avoid name
  2121. collisions.
  2122. .. seealso::
  2123. :attr:`_orm.Mapper.attrs` - namespace of all
  2124. :class:`.MapperProperty`
  2125. objects.
  2126. """
  2127. return self._filter_properties(
  2128. util.preloaded.orm_relationships.RelationshipProperty
  2129. )
  2130. @HasMemoized.memoized_attribute
  2131. @util.preload_module("sqlalchemy.orm.descriptor_props")
  2132. def composites(self):
  2133. """Return a namespace of all :class:`.CompositeProperty`
  2134. properties maintained by this :class:`_orm.Mapper`.
  2135. .. seealso::
  2136. :attr:`_orm.Mapper.attrs` - namespace of all
  2137. :class:`.MapperProperty`
  2138. objects.
  2139. """
  2140. return self._filter_properties(
  2141. util.preloaded.orm_descriptor_props.CompositeProperty
  2142. )
  2143. def _filter_properties(self, type_):
  2144. self._check_configure()
  2145. return util.ImmutableProperties(
  2146. util.OrderedDict(
  2147. (k, v) for k, v in self._props.items() if isinstance(v, type_)
  2148. )
  2149. )
  2150. @HasMemoized.memoized_attribute
  2151. def _get_clause(self):
  2152. """create a "get clause" based on the primary key. this is used
  2153. by query.get() and many-to-one lazyloads to load this item
  2154. by primary key.
  2155. """
  2156. params = [
  2157. (
  2158. primary_key,
  2159. sql.bindparam("pk_%d" % idx, type_=primary_key.type),
  2160. )
  2161. for idx, primary_key in enumerate(self.primary_key, 1)
  2162. ]
  2163. return (
  2164. sql.and_(*[k == v for (k, v) in params]),
  2165. util.column_dict(params),
  2166. )
  2167. @HasMemoized.memoized_attribute
  2168. def _equivalent_columns(self):
  2169. """Create a map of all equivalent columns, based on
  2170. the determination of column pairs that are equated to
  2171. one another based on inherit condition. This is designed
  2172. to work with the queries that util.polymorphic_union
  2173. comes up with, which often don't include the columns from
  2174. the base table directly (including the subclass table columns
  2175. only).
  2176. The resulting structure is a dictionary of columns mapped
  2177. to lists of equivalent columns, e.g.::
  2178. {
  2179. tablea.col1:
  2180. {tableb.col1, tablec.col1},
  2181. tablea.col2:
  2182. {tabled.col2}
  2183. }
  2184. """
  2185. result = util.column_dict()
  2186. def visit_binary(binary):
  2187. if binary.operator == operators.eq:
  2188. if binary.left in result:
  2189. result[binary.left].add(binary.right)
  2190. else:
  2191. result[binary.left] = util.column_set((binary.right,))
  2192. if binary.right in result:
  2193. result[binary.right].add(binary.left)
  2194. else:
  2195. result[binary.right] = util.column_set((binary.left,))
  2196. for mapper in self.base_mapper.self_and_descendants:
  2197. if mapper.inherit_condition is not None:
  2198. visitors.traverse(
  2199. mapper.inherit_condition, {}, {"binary": visit_binary}
  2200. )
  2201. return result
  2202. def _is_userland_descriptor(self, assigned_name, obj):
  2203. if isinstance(
  2204. obj,
  2205. (
  2206. _MappedAttribute,
  2207. instrumentation.ClassManager,
  2208. expression.ColumnElement,
  2209. ),
  2210. ):
  2211. return False
  2212. else:
  2213. return assigned_name not in self._dataclass_fields
  2214. @HasMemoized.memoized_attribute
  2215. def _dataclass_fields(self):
  2216. return [f.name for f in util.dataclass_fields(self.class_)]
  2217. def _should_exclude(self, name, assigned_name, local, column):
  2218. """determine whether a particular property should be implicitly
  2219. present on the class.
  2220. This occurs when properties are propagated from an inherited class, or
  2221. are applied from the columns present in the mapped table.
  2222. """
  2223. # check for class-bound attributes and/or descriptors,
  2224. # either local or from an inherited class
  2225. # ignore dataclass field default values
  2226. if local:
  2227. if self.class_.__dict__.get(
  2228. assigned_name, None
  2229. ) is not None and self._is_userland_descriptor(
  2230. assigned_name, self.class_.__dict__[assigned_name]
  2231. ):
  2232. return True
  2233. else:
  2234. attr = self.class_manager._get_class_attr_mro(assigned_name, None)
  2235. if attr is not None and self._is_userland_descriptor(
  2236. assigned_name, attr
  2237. ):
  2238. return True
  2239. if (
  2240. self.include_properties is not None
  2241. and name not in self.include_properties
  2242. and (column is None or column not in self.include_properties)
  2243. ):
  2244. self._log("not including property %s" % (name))
  2245. return True
  2246. if self.exclude_properties is not None and (
  2247. name in self.exclude_properties
  2248. or (column is not None and column in self.exclude_properties)
  2249. ):
  2250. self._log("excluding property %s" % (name))
  2251. return True
  2252. return False
  2253. def common_parent(self, other):
  2254. """Return true if the given mapper shares a
  2255. common inherited parent as this mapper."""
  2256. return self.base_mapper is other.base_mapper
  2257. def is_sibling(self, other):
  2258. """return true if the other mapper is an inheriting sibling to this
  2259. one. common parent but different branch
  2260. """
  2261. return (
  2262. self.base_mapper is other.base_mapper
  2263. and not self.isa(other)
  2264. and not other.isa(self)
  2265. )
  2266. def _canload(self, state, allow_subtypes):
  2267. s = self.primary_mapper()
  2268. if self.polymorphic_on is not None or allow_subtypes:
  2269. return _state_mapper(state).isa(s)
  2270. else:
  2271. return _state_mapper(state) is s
  2272. def isa(self, other):
  2273. """Return True if the this mapper inherits from the given mapper."""
  2274. m = self
  2275. while m and m is not other:
  2276. m = m.inherits
  2277. return bool(m)
  2278. def iterate_to_root(self):
  2279. m = self
  2280. while m:
  2281. yield m
  2282. m = m.inherits
  2283. @HasMemoized.memoized_attribute
  2284. def self_and_descendants(self):
  2285. """The collection including this mapper and all descendant mappers.
  2286. This includes not just the immediately inheriting mappers but
  2287. all their inheriting mappers as well.
  2288. """
  2289. descendants = []
  2290. stack = deque([self])
  2291. while stack:
  2292. item = stack.popleft()
  2293. descendants.append(item)
  2294. stack.extend(item._inheriting_mappers)
  2295. return util.WeakSequence(descendants)
  2296. def polymorphic_iterator(self):
  2297. """Iterate through the collection including this mapper and
  2298. all descendant mappers.
  2299. This includes not just the immediately inheriting mappers but
  2300. all their inheriting mappers as well.
  2301. To iterate through an entire hierarchy, use
  2302. ``mapper.base_mapper.polymorphic_iterator()``.
  2303. """
  2304. return iter(self.self_and_descendants)
  2305. def primary_mapper(self):
  2306. """Return the primary mapper corresponding to this mapper's class key
  2307. (class)."""
  2308. return self.class_manager.mapper
  2309. @property
  2310. def primary_base_mapper(self):
  2311. return self.class_manager.mapper.base_mapper
  2312. def _result_has_identity_key(self, result, adapter=None):
  2313. pk_cols = self.primary_key
  2314. if adapter:
  2315. pk_cols = [adapter.columns[c] for c in pk_cols]
  2316. rk = result.keys()
  2317. for col in pk_cols:
  2318. if col not in rk:
  2319. return False
  2320. else:
  2321. return True
  2322. def identity_key_from_row(self, row, identity_token=None, adapter=None):
  2323. """Return an identity-map key for use in storing/retrieving an
  2324. item from the identity map.
  2325. :param row: A :class:`.Row` instance. The columns which are
  2326. mapped by this :class:`_orm.Mapper` should be locatable in the row,
  2327. preferably via the :class:`_schema.Column`
  2328. object directly (as is the case
  2329. when a :func:`_expression.select` construct is executed), or
  2330. via string names of the form ``<tablename>_<colname>``.
  2331. """
  2332. pk_cols = self.primary_key
  2333. if adapter:
  2334. pk_cols = [adapter.columns[c] for c in pk_cols]
  2335. return (
  2336. self._identity_class,
  2337. tuple(row[column] for column in pk_cols),
  2338. identity_token,
  2339. )
  2340. def identity_key_from_primary_key(self, primary_key, identity_token=None):
  2341. """Return an identity-map key for use in storing/retrieving an
  2342. item from an identity map.
  2343. :param primary_key: A list of values indicating the identifier.
  2344. """
  2345. return self._identity_class, tuple(primary_key), identity_token
  2346. def identity_key_from_instance(self, instance):
  2347. """Return the identity key for the given instance, based on
  2348. its primary key attributes.
  2349. If the instance's state is expired, calling this method
  2350. will result in a database check to see if the object has been deleted.
  2351. If the row no longer exists,
  2352. :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
  2353. This value is typically also found on the instance state under the
  2354. attribute name `key`.
  2355. """
  2356. state = attributes.instance_state(instance)
  2357. return self._identity_key_from_state(state, attributes.PASSIVE_OFF)
  2358. def _identity_key_from_state(
  2359. self, state, passive=attributes.PASSIVE_RETURN_NO_VALUE
  2360. ):
  2361. dict_ = state.dict
  2362. manager = state.manager
  2363. return (
  2364. self._identity_class,
  2365. tuple(
  2366. [
  2367. manager[prop.key].impl.get(state, dict_, passive)
  2368. for prop in self._identity_key_props
  2369. ]
  2370. ),
  2371. state.identity_token,
  2372. )
  2373. def primary_key_from_instance(self, instance):
  2374. """Return the list of primary key values for the given
  2375. instance.
  2376. If the instance's state is expired, calling this method
  2377. will result in a database check to see if the object has been deleted.
  2378. If the row no longer exists,
  2379. :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
  2380. """
  2381. state = attributes.instance_state(instance)
  2382. identity_key = self._identity_key_from_state(
  2383. state, attributes.PASSIVE_OFF
  2384. )
  2385. return identity_key[1]
  2386. @HasMemoized.memoized_attribute
  2387. def _persistent_sortkey_fn(self):
  2388. key_fns = [col.type.sort_key_function for col in self.primary_key]
  2389. if set(key_fns).difference([None]):
  2390. def key(state):
  2391. return tuple(
  2392. key_fn(val) if key_fn is not None else val
  2393. for key_fn, val in zip(key_fns, state.key[1])
  2394. )
  2395. else:
  2396. def key(state):
  2397. return state.key[1]
  2398. return key
  2399. @HasMemoized.memoized_attribute
  2400. def _identity_key_props(self):
  2401. return [self._columntoproperty[col] for col in self.primary_key]
  2402. @HasMemoized.memoized_attribute
  2403. def _all_pk_cols(self):
  2404. collection = set()
  2405. for table in self.tables:
  2406. collection.update(self._pks_by_table[table])
  2407. return collection
  2408. @HasMemoized.memoized_attribute
  2409. def _should_undefer_in_wildcard(self):
  2410. cols = set(self.primary_key)
  2411. if self.polymorphic_on is not None:
  2412. cols.add(self.polymorphic_on)
  2413. return cols
  2414. @HasMemoized.memoized_attribute
  2415. def _primary_key_propkeys(self):
  2416. return {self._columntoproperty[col].key for col in self._all_pk_cols}
  2417. def _get_state_attr_by_column(
  2418. self, state, dict_, column, passive=attributes.PASSIVE_RETURN_NO_VALUE
  2419. ):
  2420. prop = self._columntoproperty[column]
  2421. return state.manager[prop.key].impl.get(state, dict_, passive=passive)
  2422. def _set_committed_state_attr_by_column(self, state, dict_, column, value):
  2423. prop = self._columntoproperty[column]
  2424. state.manager[prop.key].impl.set_committed_value(state, dict_, value)
  2425. def _set_state_attr_by_column(self, state, dict_, column, value):
  2426. prop = self._columntoproperty[column]
  2427. state.manager[prop.key].impl.set(state, dict_, value, None)
  2428. def _get_committed_attr_by_column(self, obj, column):
  2429. state = attributes.instance_state(obj)
  2430. dict_ = attributes.instance_dict(obj)
  2431. return self._get_committed_state_attr_by_column(
  2432. state, dict_, column, passive=attributes.PASSIVE_OFF
  2433. )
  2434. def _get_committed_state_attr_by_column(
  2435. self, state, dict_, column, passive=attributes.PASSIVE_RETURN_NO_VALUE
  2436. ):
  2437. prop = self._columntoproperty[column]
  2438. return state.manager[prop.key].impl.get_committed_value(
  2439. state, dict_, passive=passive
  2440. )
  2441. def _optimized_get_statement(self, state, attribute_names):
  2442. """assemble a WHERE clause which retrieves a given state by primary
  2443. key, using a minimized set of tables.
  2444. Applies to a joined-table inheritance mapper where the
  2445. requested attribute names are only present on joined tables,
  2446. not the base table. The WHERE clause attempts to include
  2447. only those tables to minimize joins.
  2448. """
  2449. props = self._props
  2450. col_attribute_names = set(attribute_names).intersection(
  2451. state.mapper.column_attrs.keys()
  2452. )
  2453. tables = set(
  2454. chain(
  2455. *[
  2456. sql_util.find_tables(c, check_columns=True)
  2457. for key in col_attribute_names
  2458. for c in props[key].columns
  2459. ]
  2460. )
  2461. )
  2462. if self.base_mapper.local_table in tables:
  2463. return None
  2464. def visit_binary(binary):
  2465. leftcol = binary.left
  2466. rightcol = binary.right
  2467. if leftcol is None or rightcol is None:
  2468. return
  2469. if leftcol.table not in tables:
  2470. leftval = self._get_committed_state_attr_by_column(
  2471. state,
  2472. state.dict,
  2473. leftcol,
  2474. passive=attributes.PASSIVE_NO_INITIALIZE,
  2475. )
  2476. if leftval in orm_util._none_set:
  2477. raise _OptGetColumnsNotAvailable()
  2478. binary.left = sql.bindparam(
  2479. None, leftval, type_=binary.right.type
  2480. )
  2481. elif rightcol.table not in tables:
  2482. rightval = self._get_committed_state_attr_by_column(
  2483. state,
  2484. state.dict,
  2485. rightcol,
  2486. passive=attributes.PASSIVE_NO_INITIALIZE,
  2487. )
  2488. if rightval in orm_util._none_set:
  2489. raise _OptGetColumnsNotAvailable()
  2490. binary.right = sql.bindparam(
  2491. None, rightval, type_=binary.right.type
  2492. )
  2493. allconds = []
  2494. start = False
  2495. # as of #7507, from the lowest base table on upwards,
  2496. # we include all intermediary tables.
  2497. for mapper in reversed(list(self.iterate_to_root())):
  2498. if mapper.local_table in tables:
  2499. start = True
  2500. elif not isinstance(mapper.local_table, expression.TableClause):
  2501. return None
  2502. if start and not mapper.single:
  2503. allconds.append(mapper.inherit_condition)
  2504. tables.add(mapper.local_table)
  2505. # only the bottom table needs its criteria to be altered to fit
  2506. # the primary key ident - the rest of the tables upwards to the
  2507. # descendant-most class should all be present and joined to each
  2508. # other.
  2509. try:
  2510. allconds[0] = visitors.cloned_traverse(
  2511. allconds[0], {}, {"binary": visit_binary}
  2512. )
  2513. except _OptGetColumnsNotAvailable:
  2514. return None
  2515. cond = sql.and_(*allconds)
  2516. cols = []
  2517. for key in col_attribute_names:
  2518. cols.extend(props[key].columns)
  2519. return (
  2520. sql.select(*cols)
  2521. .where(cond)
  2522. .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  2523. )
  2524. def _iterate_to_target_viawpoly(self, mapper):
  2525. if self.isa(mapper):
  2526. prev = self
  2527. for m in self.iterate_to_root():
  2528. yield m
  2529. if m is not prev and prev not in m._with_polymorphic_mappers:
  2530. break
  2531. prev = m
  2532. if m is mapper:
  2533. break
  2534. def _should_selectin_load(self, enabled_via_opt, polymorphic_from):
  2535. if not enabled_via_opt:
  2536. # common case, takes place for all polymorphic loads
  2537. mapper = polymorphic_from
  2538. for m in self._iterate_to_target_viawpoly(mapper):
  2539. if m.polymorphic_load == "selectin":
  2540. return m
  2541. else:
  2542. # uncommon case, selectin load options were used
  2543. enabled_via_opt = set(enabled_via_opt)
  2544. enabled_via_opt_mappers = {e.mapper: e for e in enabled_via_opt}
  2545. for entity in enabled_via_opt.union([polymorphic_from]):
  2546. mapper = entity.mapper
  2547. for m in self._iterate_to_target_viawpoly(mapper):
  2548. if (
  2549. m.polymorphic_load == "selectin"
  2550. or m in enabled_via_opt_mappers
  2551. ):
  2552. return enabled_via_opt_mappers.get(m, m)
  2553. return None
  2554. @util.preload_module("sqlalchemy.orm.strategy_options")
  2555. def _subclass_load_via_in(self, entity):
  2556. """Assemble a that can load the columns local to
  2557. this subclass as a SELECT with IN.
  2558. """
  2559. strategy_options = util.preloaded.orm_strategy_options
  2560. assert self.inherits
  2561. polymorphic_prop = self._columntoproperty[self.polymorphic_on]
  2562. keep_props = set([polymorphic_prop] + self._identity_key_props)
  2563. disable_opt = strategy_options.Load(entity)
  2564. enable_opt = strategy_options.Load(entity)
  2565. for prop in self.attrs:
  2566. if prop.parent is self or prop in keep_props:
  2567. # "enable" options, to turn on the properties that we want to
  2568. # load by default (subject to options from the query)
  2569. enable_opt.set_generic_strategy(
  2570. # convert string name to an attribute before passing
  2571. # to loader strategy
  2572. (getattr(entity.entity_namespace, prop.key),),
  2573. dict(prop.strategy_key),
  2574. )
  2575. else:
  2576. # "disable" options, to turn off the properties from the
  2577. # superclass that we *don't* want to load, applied after
  2578. # the options from the query to override them
  2579. disable_opt.set_generic_strategy(
  2580. # convert string name to an attribute before passing
  2581. # to loader strategy
  2582. (getattr(entity.entity_namespace, prop.key),),
  2583. {"do_nothing": True},
  2584. )
  2585. primary_key = [
  2586. sql_util._deep_annotate(pk, {"_orm_adapt": True})
  2587. for pk in self.primary_key
  2588. ]
  2589. if len(primary_key) > 1:
  2590. in_expr = sql.tuple_(*primary_key)
  2591. else:
  2592. in_expr = primary_key[0]
  2593. if entity.is_aliased_class:
  2594. assert entity.mapper is self
  2595. q = sql.select(entity).set_label_style(
  2596. LABEL_STYLE_TABLENAME_PLUS_COL
  2597. )
  2598. in_expr = entity._adapter.traverse(in_expr)
  2599. primary_key = [entity._adapter.traverse(k) for k in primary_key]
  2600. q = q.where(
  2601. in_expr.in_(sql.bindparam("primary_keys", expanding=True))
  2602. ).order_by(*primary_key)
  2603. else:
  2604. q = sql.select(self).set_label_style(
  2605. LABEL_STYLE_TABLENAME_PLUS_COL
  2606. )
  2607. q = q.where(
  2608. in_expr.in_(sql.bindparam("primary_keys", expanding=True))
  2609. ).order_by(*primary_key)
  2610. return q, enable_opt, disable_opt
  2611. @HasMemoized.memoized_attribute
  2612. def _subclass_load_via_in_mapper(self):
  2613. return self._subclass_load_via_in(self)
  2614. def cascade_iterator(self, type_, state, halt_on=None):
  2615. r"""Iterate each element and its mapper in an object graph,
  2616. for all relationships that meet the given cascade rule.
  2617. :param type\_:
  2618. The name of the cascade rule (i.e. ``"save-update"``, ``"delete"``,
  2619. etc.).
  2620. .. note:: the ``"all"`` cascade is not accepted here. For a generic
  2621. object traversal function, see :ref:`faq_walk_objects`.
  2622. :param state:
  2623. The lead InstanceState. child items will be processed per
  2624. the relationships defined for this object's mapper.
  2625. :return: the method yields individual object instances.
  2626. .. seealso::
  2627. :ref:`unitofwork_cascades`
  2628. :ref:`faq_walk_objects` - illustrates a generic function to
  2629. traverse all objects without relying on cascades.
  2630. """
  2631. visited_states = set()
  2632. prp, mpp = object(), object()
  2633. assert state.mapper.isa(self)
  2634. visitables = deque(
  2635. [(deque(state.mapper._props.values()), prp, state, state.dict)]
  2636. )
  2637. while visitables:
  2638. iterator, item_type, parent_state, parent_dict = visitables[-1]
  2639. if not iterator:
  2640. visitables.pop()
  2641. continue
  2642. if item_type is prp:
  2643. prop = iterator.popleft()
  2644. if type_ not in prop.cascade:
  2645. continue
  2646. queue = deque(
  2647. prop.cascade_iterator(
  2648. type_,
  2649. parent_state,
  2650. parent_dict,
  2651. visited_states,
  2652. halt_on,
  2653. )
  2654. )
  2655. if queue:
  2656. visitables.append((queue, mpp, None, None))
  2657. elif item_type is mpp:
  2658. (
  2659. instance,
  2660. instance_mapper,
  2661. corresponding_state,
  2662. corresponding_dict,
  2663. ) = iterator.popleft()
  2664. yield (
  2665. instance,
  2666. instance_mapper,
  2667. corresponding_state,
  2668. corresponding_dict,
  2669. )
  2670. visitables.append(
  2671. (
  2672. deque(instance_mapper._props.values()),
  2673. prp,
  2674. corresponding_state,
  2675. corresponding_dict,
  2676. )
  2677. )
  2678. @HasMemoized.memoized_attribute
  2679. def _compiled_cache(self):
  2680. return util.LRUCache(self._compiled_cache_size)
  2681. @HasMemoized.memoized_attribute
  2682. def _sorted_tables(self):
  2683. table_to_mapper = {}
  2684. for mapper in self.base_mapper.self_and_descendants:
  2685. for t in mapper.tables:
  2686. table_to_mapper.setdefault(t, mapper)
  2687. extra_dependencies = []
  2688. for table, mapper in table_to_mapper.items():
  2689. super_ = mapper.inherits
  2690. if super_:
  2691. extra_dependencies.extend(
  2692. [(super_table, table) for super_table in super_.tables]
  2693. )
  2694. def skip(fk):
  2695. # attempt to skip dependencies that are not
  2696. # significant to the inheritance chain
  2697. # for two tables that are related by inheritance.
  2698. # while that dependency may be important, it's technically
  2699. # not what we mean to sort on here.
  2700. parent = table_to_mapper.get(fk.parent.table)
  2701. dep = table_to_mapper.get(fk.column.table)
  2702. if (
  2703. parent is not None
  2704. and dep is not None
  2705. and dep is not parent
  2706. and dep.inherit_condition is not None
  2707. ):
  2708. cols = set(sql_util._find_columns(dep.inherit_condition))
  2709. if parent.inherit_condition is not None:
  2710. cols = cols.union(
  2711. sql_util._find_columns(parent.inherit_condition)
  2712. )
  2713. return fk.parent not in cols and fk.column not in cols
  2714. else:
  2715. return fk.parent not in cols
  2716. return False
  2717. sorted_ = sql_util.sort_tables(
  2718. table_to_mapper,
  2719. skip_fn=skip,
  2720. extra_dependencies=extra_dependencies,
  2721. )
  2722. ret = util.OrderedDict()
  2723. for t in sorted_:
  2724. ret[t] = table_to_mapper[t]
  2725. return ret
  2726. def _memo(self, key, callable_):
  2727. if key in self._memoized_values:
  2728. return self._memoized_values[key]
  2729. else:
  2730. self._memoized_values[key] = value = callable_()
  2731. return value
  2732. @util.memoized_property
  2733. def _table_to_equated(self):
  2734. """memoized map of tables to collections of columns to be
  2735. synchronized upwards to the base mapper."""
  2736. result = util.defaultdict(list)
  2737. for table in self._sorted_tables:
  2738. cols = set(table.c)
  2739. for m in self.iterate_to_root():
  2740. if m._inherits_equated_pairs and cols.intersection(
  2741. util.reduce(
  2742. set.union,
  2743. [l.proxy_set for l, r in m._inherits_equated_pairs],
  2744. )
  2745. ):
  2746. result[table].append((m, m._inherits_equated_pairs))
  2747. return result
  2748. class _OptGetColumnsNotAvailable(Exception):
  2749. pass
  2750. def configure_mappers():
  2751. """Initialize the inter-mapper relationships of all mappers that
  2752. have been constructed thus far across all :class:`_orm.registry`
  2753. collections.
  2754. The configure step is used to reconcile and initialize the
  2755. :func:`_orm.relationship` linkages between mapped classes, as well as to
  2756. invoke configuration events such as the
  2757. :meth:`_orm.MapperEvents.before_configured` and
  2758. :meth:`_orm.MapperEvents.after_configured`, which may be used by ORM
  2759. extensions or user-defined extension hooks.
  2760. Mapper configuration is normally invoked automatically, the first time
  2761. mappings from a particular :class:`_orm.registry` are used, as well as
  2762. whenever mappings are used and additional not-yet-configured mappers have
  2763. been constructed. The automatic configuration process however is local only
  2764. to the :class:`_orm.registry` involving the target mapper and any related
  2765. :class:`_orm.registry` objects which it may depend on; this is
  2766. equivalent to invoking the :meth:`_orm.registry.configure` method
  2767. on a particular :class:`_orm.registry`.
  2768. By contrast, the :func:`_orm.configure_mappers` function will invoke the
  2769. configuration process on all :class:`_orm.registry` objects that
  2770. exist in memory, and may be useful for scenarios where many individual
  2771. :class:`_orm.registry` objects that are nonetheless interrelated are
  2772. in use.
  2773. .. versionchanged:: 1.4
  2774. As of SQLAlchemy 1.4.0b2, this function works on a
  2775. per-:class:`_orm.registry` basis, locating all :class:`_orm.registry`
  2776. objects present and invoking the :meth:`_orm.registry.configure` method
  2777. on each. The :meth:`_orm.registry.configure` method may be preferred to
  2778. limit the configuration of mappers to those local to a particular
  2779. :class:`_orm.registry` and/or declarative base class.
  2780. Points at which automatic configuration is invoked include when a mapped
  2781. class is instantiated into an instance, as well as when ORM queries
  2782. are emitted using :meth:`.Session.query` or :meth:`_orm.Session.execute`
  2783. with an ORM-enabled statement.
  2784. The mapper configure process, whether invoked by
  2785. :func:`_orm.configure_mappers` or from :meth:`_orm.registry.configure`,
  2786. provides several event hooks that can be used to augment the mapper
  2787. configuration step. These hooks include:
  2788. * :meth:`.MapperEvents.before_configured` - called once before
  2789. :func:`.configure_mappers` or :meth:`_orm.registry.configure` does any
  2790. work; this can be used to establish additional options, properties, or
  2791. related mappings before the operation proceeds.
  2792. * :meth:`.MapperEvents.mapper_configured` - called as each individual
  2793. :class:`_orm.Mapper` is configured within the process; will include all
  2794. mapper state except for backrefs set up by other mappers that are still
  2795. to be configured.
  2796. * :meth:`.MapperEvents.after_configured` - called once after
  2797. :func:`.configure_mappers` or :meth:`_orm.registry.configure` is
  2798. complete; at this stage, all :class:`_orm.Mapper` objects that fall
  2799. within the scope of the configuration operation will be fully configured.
  2800. Note that the calling application may still have other mappings that
  2801. haven't been produced yet, such as if they are in modules as yet
  2802. unimported, and may also have mappings that are still to be configured,
  2803. if they are in other :class:`_orm.registry` collections not part of the
  2804. current scope of configuration.
  2805. """
  2806. _configure_registries(_all_registries(), cascade=True)
  2807. def _configure_registries(registries, cascade):
  2808. for reg in registries:
  2809. if reg._new_mappers:
  2810. break
  2811. else:
  2812. return
  2813. with _CONFIGURE_MUTEX:
  2814. global _already_compiling
  2815. if _already_compiling:
  2816. return
  2817. _already_compiling = True
  2818. try:
  2819. # double-check inside mutex
  2820. for reg in registries:
  2821. if reg._new_mappers:
  2822. break
  2823. else:
  2824. return
  2825. Mapper.dispatch._for_class(Mapper).before_configured()
  2826. # initialize properties on all mappers
  2827. # note that _mapper_registry is unordered, which
  2828. # may randomly conceal/reveal issues related to
  2829. # the order of mapper compilation
  2830. _do_configure_registries(registries, cascade)
  2831. finally:
  2832. _already_compiling = False
  2833. Mapper.dispatch._for_class(Mapper).after_configured()
  2834. @util.preload_module("sqlalchemy.orm.decl_api")
  2835. def _do_configure_registries(registries, cascade):
  2836. registry = util.preloaded.orm_decl_api.registry
  2837. orig = set(registries)
  2838. for reg in registry._recurse_with_dependencies(registries):
  2839. has_skip = False
  2840. for mapper in reg._mappers_to_configure():
  2841. run_configure = None
  2842. for fn in mapper.dispatch.before_mapper_configured:
  2843. run_configure = fn(mapper, mapper.class_)
  2844. if run_configure is EXT_SKIP:
  2845. has_skip = True
  2846. break
  2847. if run_configure is EXT_SKIP:
  2848. continue
  2849. if getattr(mapper, "_configure_failed", False):
  2850. e = sa_exc.InvalidRequestError(
  2851. "One or more mappers failed to initialize - "
  2852. "can't proceed with initialization of other "
  2853. "mappers. Triggering mapper: '%s'. "
  2854. "Original exception was: %s"
  2855. % (mapper, mapper._configure_failed)
  2856. )
  2857. e._configure_failed = mapper._configure_failed
  2858. raise e
  2859. if not mapper.configured:
  2860. try:
  2861. mapper._post_configure_properties()
  2862. mapper._expire_memoizations()
  2863. mapper.dispatch.mapper_configured(mapper, mapper.class_)
  2864. except Exception:
  2865. exc = sys.exc_info()[1]
  2866. if not hasattr(exc, "_configure_failed"):
  2867. mapper._configure_failed = exc
  2868. raise
  2869. if not has_skip:
  2870. reg._new_mappers = False
  2871. if not cascade and reg._dependencies.difference(orig):
  2872. raise sa_exc.InvalidRequestError(
  2873. "configure was called with cascade=False but "
  2874. "additional registries remain"
  2875. )
  2876. @util.preload_module("sqlalchemy.orm.decl_api")
  2877. def _dispose_registries(registries, cascade):
  2878. registry = util.preloaded.orm_decl_api.registry
  2879. orig = set(registries)
  2880. for reg in registry._recurse_with_dependents(registries):
  2881. if not cascade and reg._dependents.difference(orig):
  2882. raise sa_exc.InvalidRequestError(
  2883. "Registry has dependent registries that are not disposed; "
  2884. "pass cascade=True to clear these also"
  2885. )
  2886. while reg._managers:
  2887. try:
  2888. manager, _ = reg._managers.popitem()
  2889. except KeyError:
  2890. # guard against race between while and popitem
  2891. pass
  2892. else:
  2893. reg._dispose_manager_and_mapper(manager)
  2894. reg._non_primary_mappers.clear()
  2895. reg._dependents.clear()
  2896. for dep in reg._dependencies:
  2897. dep._dependents.discard(reg)
  2898. reg._dependencies.clear()
  2899. # this wasn't done in the 1.3 clear_mappers() and in fact it
  2900. # was a bug, as it could cause configure_mappers() to invoke
  2901. # the "before_configured" event even though mappers had all been
  2902. # disposed.
  2903. reg._new_mappers = False
  2904. def reconstructor(fn):
  2905. """Decorate a method as the 'reconstructor' hook.
  2906. Designates a single method as the "reconstructor", an ``__init__``-like
  2907. method that will be called by the ORM after the instance has been
  2908. loaded from the database or otherwise reconstituted.
  2909. The reconstructor will be invoked with no arguments. Scalar
  2910. (non-collection) database-mapped attributes of the instance will
  2911. be available for use within the function. Eagerly-loaded
  2912. collections are generally not yet available and will usually only
  2913. contain the first element. ORM state changes made to objects at
  2914. this stage will not be recorded for the next flush() operation, so
  2915. the activity within a reconstructor should be conservative.
  2916. .. seealso::
  2917. :ref:`mapping_constructors`
  2918. :meth:`.InstanceEvents.load`
  2919. """
  2920. fn.__sa_reconstructor__ = True
  2921. return fn
  2922. def validates(*names, **kw):
  2923. r"""Decorate a method as a 'validator' for one or more named properties.
  2924. Designates a method as a validator, a method which receives the
  2925. name of the attribute as well as a value to be assigned, or in the
  2926. case of a collection, the value to be added to the collection.
  2927. The function can then raise validation exceptions to halt the
  2928. process from continuing (where Python's built-in ``ValueError``
  2929. and ``AssertionError`` exceptions are reasonable choices), or can
  2930. modify or replace the value before proceeding. The function should
  2931. otherwise return the given value.
  2932. Note that a validator for a collection **cannot** issue a load of that
  2933. collection within the validation routine - this usage raises
  2934. an assertion to avoid recursion overflows. This is a reentrant
  2935. condition which is not supported.
  2936. :param \*names: list of attribute names to be validated.
  2937. :param include_removes: if True, "remove" events will be
  2938. sent as well - the validation function must accept an additional
  2939. argument "is_remove" which will be a boolean.
  2940. :param include_backrefs: defaults to ``True``; if ``False``, the
  2941. validation function will not emit if the originator is an attribute
  2942. event related via a backref. This can be used for bi-directional
  2943. :func:`.validates` usage where only one validator should emit per
  2944. attribute operation.
  2945. .. versionadded:: 0.9.0
  2946. .. seealso::
  2947. :ref:`simple_validators` - usage examples for :func:`.validates`
  2948. """
  2949. include_removes = kw.pop("include_removes", False)
  2950. include_backrefs = kw.pop("include_backrefs", True)
  2951. def wrap(fn):
  2952. fn.__sa_validators__ = names
  2953. fn.__sa_validation_opts__ = {
  2954. "include_removes": include_removes,
  2955. "include_backrefs": include_backrefs,
  2956. }
  2957. return fn
  2958. return wrap
  2959. def _event_on_load(state, ctx):
  2960. instrumenting_mapper = state.manager.mapper
  2961. if instrumenting_mapper._reconstructor:
  2962. instrumenting_mapper._reconstructor(state.obj())
  2963. def _event_on_init(state, args, kwargs):
  2964. """Run init_instance hooks.
  2965. This also includes mapper compilation, normally not needed
  2966. here but helps with some piecemeal configuration
  2967. scenarios (such as in the ORM tutorial).
  2968. """
  2969. instrumenting_mapper = state.manager.mapper
  2970. if instrumenting_mapper:
  2971. instrumenting_mapper._check_configure()
  2972. if instrumenting_mapper._set_polymorphic_identity:
  2973. instrumenting_mapper._set_polymorphic_identity(state)
  2974. class _ColumnMapping(dict):
  2975. """Error reporting helper for mapper._columntoproperty."""
  2976. __slots__ = ("mapper",)
  2977. def __init__(self, mapper):
  2978. self.mapper = mapper
  2979. def __missing__(self, column):
  2980. prop = self.mapper._props.get(column)
  2981. if prop:
  2982. raise orm_exc.UnmappedColumnError(
  2983. "Column '%s.%s' is not available, due to "
  2984. "conflicting property '%s':%r"
  2985. % (column.table.name, column.name, column.key, prop)
  2986. )
  2987. raise orm_exc.UnmappedColumnError(
  2988. "No column %s is configured on mapper %s..."
  2989. % (column, self.mapper)
  2990. )