SQLAlchemy 2.0.36__cp313-cp313-win32.whl

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