mapper.py 168 KB

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