mapper.py 141 KB

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