mapper.py 119 KB

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