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,1474 @@
1
+ # orm/interfaces.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
+
8
+ """
9
+
10
+ Contains various base classes used throughout the ORM.
11
+
12
+ Defines some key base classes prominent within the internals.
13
+
14
+ This module and the classes within are mostly private, though some attributes
15
+ are exposed when inspecting mappings.
16
+
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import collections
22
+ import dataclasses
23
+ import typing
24
+ from typing import Any
25
+ from typing import Callable
26
+ from typing import cast
27
+ from typing import ClassVar
28
+ from typing import Dict
29
+ from typing import Generic
30
+ from typing import Iterator
31
+ from typing import List
32
+ from typing import NamedTuple
33
+ from typing import NoReturn
34
+ from typing import Optional
35
+ from typing import Sequence
36
+ from typing import Set
37
+ from typing import Tuple
38
+ from typing import Type
39
+ from typing import TYPE_CHECKING
40
+ from typing import TypeVar
41
+ from typing import Union
42
+
43
+ from . import exc as orm_exc
44
+ from . import path_registry
45
+ from .base import _MappedAttribute as _MappedAttribute
46
+ from .base import EXT_CONTINUE as EXT_CONTINUE # noqa: F401
47
+ from .base import EXT_SKIP as EXT_SKIP # noqa: F401
48
+ from .base import EXT_STOP as EXT_STOP # noqa: F401
49
+ from .base import InspectionAttr as InspectionAttr # noqa: F401
50
+ from .base import InspectionAttrInfo as InspectionAttrInfo
51
+ from .base import MANYTOMANY as MANYTOMANY # noqa: F401
52
+ from .base import MANYTOONE as MANYTOONE # noqa: F401
53
+ from .base import NO_KEY as NO_KEY # noqa: F401
54
+ from .base import NO_VALUE as NO_VALUE # noqa: F401
55
+ from .base import NotExtension as NotExtension # noqa: F401
56
+ from .base import ONETOMANY as ONETOMANY # noqa: F401
57
+ from .base import RelationshipDirection as RelationshipDirection # noqa: F401
58
+ from .base import SQLORMOperations
59
+ from .. import ColumnElement
60
+ from .. import exc as sa_exc
61
+ from .. import inspection
62
+ from .. import util
63
+ from ..sql import operators
64
+ from ..sql import roles
65
+ from ..sql import visitors
66
+ from ..sql.base import _NoArg
67
+ from ..sql.base import ExecutableOption
68
+ from ..sql.cache_key import HasCacheKey
69
+ from ..sql.operators import ColumnOperators
70
+ from ..sql.schema import Column
71
+ from ..sql.type_api import TypeEngine
72
+ from ..util import warn_deprecated
73
+ from ..util.typing import RODescriptorReference
74
+ from ..util.typing import TypedDict
75
+
76
+ if typing.TYPE_CHECKING:
77
+ from ._typing import _EntityType
78
+ from ._typing import _IdentityKeyType
79
+ from ._typing import _InstanceDict
80
+ from ._typing import _InternalEntityType
81
+ from ._typing import _ORMAdapterProto
82
+ from .attributes import InstrumentedAttribute
83
+ from .base import Mapped
84
+ from .context import _MapperEntity
85
+ from .context import ORMCompileState
86
+ from .context import QueryContext
87
+ from .decl_api import RegistryType
88
+ from .decl_base import _ClassScanMapperConfig
89
+ from .loading import _PopulatorDict
90
+ from .mapper import Mapper
91
+ from .path_registry import AbstractEntityRegistry
92
+ from .query import Query
93
+ from .session import Session
94
+ from .state import InstanceState
95
+ from .strategy_options import _LoadElement
96
+ from .util import AliasedInsp
97
+ from .util import ORMAdapter
98
+ from ..engine.result import Result
99
+ from ..sql._typing import _ColumnExpressionArgument
100
+ from ..sql._typing import _ColumnsClauseArgument
101
+ from ..sql._typing import _DMLColumnArgument
102
+ from ..sql._typing import _InfoType
103
+ from ..sql.operators import OperatorType
104
+ from ..sql.visitors import _TraverseInternalsType
105
+ from ..util.typing import _AnnotationScanType
106
+
107
+ _StrategyKey = Tuple[Any, ...]
108
+
109
+ _T = TypeVar("_T", bound=Any)
110
+ _T_co = TypeVar("_T_co", bound=Any, covariant=True)
111
+
112
+ _TLS = TypeVar("_TLS", bound="Type[LoaderStrategy]")
113
+
114
+
115
+ class ORMStatementRole(roles.StatementRole):
116
+ __slots__ = ()
117
+ _role_name = (
118
+ "Executable SQL or text() construct, including ORM aware objects"
119
+ )
120
+
121
+
122
+ class ORMColumnsClauseRole(
123
+ roles.ColumnsClauseRole, roles.TypedColumnsClauseRole[_T]
124
+ ):
125
+ __slots__ = ()
126
+ _role_name = "ORM mapped entity, aliased entity, or Column expression"
127
+
128
+
129
+ class ORMEntityColumnsClauseRole(ORMColumnsClauseRole[_T]):
130
+ __slots__ = ()
131
+ _role_name = "ORM mapped or aliased entity"
132
+
133
+
134
+ class ORMFromClauseRole(roles.StrictFromClauseRole):
135
+ __slots__ = ()
136
+ _role_name = "ORM mapped entity, aliased entity, or FROM expression"
137
+
138
+
139
+ class ORMColumnDescription(TypedDict):
140
+ name: str
141
+ # TODO: add python_type and sql_type here; combining them
142
+ # into "type" is a bad idea
143
+ type: Union[Type[Any], TypeEngine[Any]]
144
+ aliased: bool
145
+ expr: _ColumnsClauseArgument[Any]
146
+ entity: Optional[_ColumnsClauseArgument[Any]]
147
+
148
+
149
+ class _IntrospectsAnnotations:
150
+ __slots__ = ()
151
+
152
+ @classmethod
153
+ def _mapper_property_name(cls) -> str:
154
+ return cls.__name__
155
+
156
+ def found_in_pep593_annotated(self) -> Any:
157
+ """return a copy of this object to use in declarative when the
158
+ object is found inside of an Annotated object."""
159
+
160
+ raise NotImplementedError(
161
+ f"Use of the {self._mapper_property_name()!r} "
162
+ "construct inside of an Annotated object is not yet supported."
163
+ )
164
+
165
+ def declarative_scan(
166
+ self,
167
+ decl_scan: _ClassScanMapperConfig,
168
+ registry: RegistryType,
169
+ cls: Type[Any],
170
+ originating_module: Optional[str],
171
+ key: str,
172
+ mapped_container: Optional[Type[Mapped[Any]]],
173
+ annotation: Optional[_AnnotationScanType],
174
+ extracted_mapped_annotation: Optional[_AnnotationScanType],
175
+ is_dataclass_field: bool,
176
+ ) -> None:
177
+ """Perform class-specific initializaton at early declarative scanning
178
+ time.
179
+
180
+ .. versionadded:: 2.0
181
+
182
+ """
183
+
184
+ def _raise_for_required(self, key: str, cls: Type[Any]) -> NoReturn:
185
+ raise sa_exc.ArgumentError(
186
+ f"Python typing annotation is required for attribute "
187
+ f'"{cls.__name__}.{key}" when primary argument(s) for '
188
+ f'"{self._mapper_property_name()}" '
189
+ "construct are None or not present"
190
+ )
191
+
192
+
193
+ class _AttributeOptions(NamedTuple):
194
+ """define Python-local attribute behavior options common to all
195
+ :class:`.MapperProperty` objects.
196
+
197
+ Currently this includes dataclass-generation arguments.
198
+
199
+ .. versionadded:: 2.0
200
+
201
+ """
202
+
203
+ dataclasses_init: Union[_NoArg, bool]
204
+ dataclasses_repr: Union[_NoArg, bool]
205
+ dataclasses_default: Union[_NoArg, Any]
206
+ dataclasses_default_factory: Union[_NoArg, Callable[[], Any]]
207
+ dataclasses_compare: Union[_NoArg, bool]
208
+ dataclasses_kw_only: Union[_NoArg, bool]
209
+ dataclasses_hash: Union[_NoArg, bool, None]
210
+
211
+ def _as_dataclass_field(self, key: str) -> Any:
212
+ """Return a ``dataclasses.Field`` object given these arguments."""
213
+
214
+ kw: Dict[str, Any] = {}
215
+ if self.dataclasses_default_factory is not _NoArg.NO_ARG:
216
+ kw["default_factory"] = self.dataclasses_default_factory
217
+ if self.dataclasses_default is not _NoArg.NO_ARG:
218
+ kw["default"] = self.dataclasses_default
219
+ if self.dataclasses_init is not _NoArg.NO_ARG:
220
+ kw["init"] = self.dataclasses_init
221
+ if self.dataclasses_repr is not _NoArg.NO_ARG:
222
+ kw["repr"] = self.dataclasses_repr
223
+ if self.dataclasses_compare is not _NoArg.NO_ARG:
224
+ kw["compare"] = self.dataclasses_compare
225
+ if self.dataclasses_kw_only is not _NoArg.NO_ARG:
226
+ kw["kw_only"] = self.dataclasses_kw_only
227
+ if self.dataclasses_hash is not _NoArg.NO_ARG:
228
+ kw["hash"] = self.dataclasses_hash
229
+
230
+ if "default" in kw and callable(kw["default"]):
231
+ # callable defaults are ambiguous. deprecate them in favour of
232
+ # insert_default or default_factory. #9936
233
+ warn_deprecated(
234
+ f"Callable object passed to the ``default`` parameter for "
235
+ f"attribute {key!r} in a ORM-mapped Dataclasses context is "
236
+ "ambiguous, "
237
+ "and this use will raise an error in a future release. "
238
+ "If this callable is intended to produce Core level INSERT "
239
+ "default values for an underlying ``Column``, use "
240
+ "the ``mapped_column.insert_default`` parameter instead. "
241
+ "To establish this callable as providing a default value "
242
+ "for instances of the dataclass itself, use the "
243
+ "``default_factory`` dataclasses parameter.",
244
+ "2.0",
245
+ )
246
+
247
+ if (
248
+ "init" in kw
249
+ and not kw["init"]
250
+ and "default" in kw
251
+ and not callable(kw["default"]) # ignore callable defaults. #9936
252
+ and "default_factory" not in kw # illegal but let dc.field raise
253
+ ):
254
+ # fix for #9879
255
+ default = kw.pop("default")
256
+ kw["default_factory"] = lambda: default
257
+
258
+ return dataclasses.field(**kw)
259
+
260
+ @classmethod
261
+ def _get_arguments_for_make_dataclass(
262
+ cls,
263
+ key: str,
264
+ annotation: _AnnotationScanType,
265
+ mapped_container: Optional[Any],
266
+ elem: _T,
267
+ ) -> Union[
268
+ Tuple[str, _AnnotationScanType],
269
+ Tuple[str, _AnnotationScanType, dataclasses.Field[Any]],
270
+ ]:
271
+ """given attribute key, annotation, and value from a class, return
272
+ the argument tuple we would pass to dataclasses.make_dataclass()
273
+ for this attribute.
274
+
275
+ """
276
+ if isinstance(elem, _DCAttributeOptions):
277
+ dc_field = elem._attribute_options._as_dataclass_field(key)
278
+
279
+ return (key, annotation, dc_field)
280
+ elif elem is not _NoArg.NO_ARG:
281
+ # why is typing not erroring on this?
282
+ return (key, annotation, elem)
283
+ elif mapped_container is not None:
284
+ # it's Mapped[], but there's no "element", which means declarative
285
+ # did not actually do anything for this field. this shouldn't
286
+ # happen.
287
+ # previously, this would occur because _scan_attributes would
288
+ # skip a field that's on an already mapped superclass, but it
289
+ # would still include it in the annotations, leading
290
+ # to issue #8718
291
+
292
+ assert False, "Mapped[] received without a mapping declaration"
293
+
294
+ else:
295
+ # plain dataclass field, not mapped. Is only possible
296
+ # if __allow_unmapped__ is set up. I can see this mode causing
297
+ # problems...
298
+ return (key, annotation)
299
+
300
+
301
+ _DEFAULT_ATTRIBUTE_OPTIONS = _AttributeOptions(
302
+ _NoArg.NO_ARG,
303
+ _NoArg.NO_ARG,
304
+ _NoArg.NO_ARG,
305
+ _NoArg.NO_ARG,
306
+ _NoArg.NO_ARG,
307
+ _NoArg.NO_ARG,
308
+ _NoArg.NO_ARG,
309
+ )
310
+
311
+ _DEFAULT_READONLY_ATTRIBUTE_OPTIONS = _AttributeOptions(
312
+ False,
313
+ _NoArg.NO_ARG,
314
+ _NoArg.NO_ARG,
315
+ _NoArg.NO_ARG,
316
+ _NoArg.NO_ARG,
317
+ _NoArg.NO_ARG,
318
+ _NoArg.NO_ARG,
319
+ )
320
+
321
+
322
+ class _DCAttributeOptions:
323
+ """mixin for descriptors or configurational objects that include dataclass
324
+ field options.
325
+
326
+ This includes :class:`.MapperProperty`, :class:`._MapsColumn` within
327
+ the ORM, but also includes :class:`.AssociationProxy` within ext.
328
+ Can in theory be used for other descriptors that serve a similar role
329
+ as association proxy. (*maybe* hybrids, not sure yet.)
330
+
331
+ """
332
+
333
+ __slots__ = ()
334
+
335
+ _attribute_options: _AttributeOptions
336
+ """behavioral options for ORM-enabled Python attributes
337
+
338
+ .. versionadded:: 2.0
339
+
340
+ """
341
+
342
+ _has_dataclass_arguments: bool
343
+
344
+
345
+ class _MapsColumns(_DCAttributeOptions, _MappedAttribute[_T]):
346
+ """interface for declarative-capable construct that delivers one or more
347
+ Column objects to the declarative process to be part of a Table.
348
+ """
349
+
350
+ __slots__ = ()
351
+
352
+ @property
353
+ def mapper_property_to_assign(self) -> Optional[MapperProperty[_T]]:
354
+ """return a MapperProperty to be assigned to the declarative mapping"""
355
+ raise NotImplementedError()
356
+
357
+ @property
358
+ def columns_to_assign(self) -> List[Tuple[Column[_T], int]]:
359
+ """A list of Column objects that should be declaratively added to the
360
+ new Table object.
361
+
362
+ """
363
+ raise NotImplementedError()
364
+
365
+
366
+ # NOTE: MapperProperty needs to extend _MappedAttribute so that declarative
367
+ # typing works, i.e. "Mapped[A] = relationship()". This introduces an
368
+ # inconvenience which is that all the MapperProperty objects are treated
369
+ # as descriptors by typing tools, which are misled by this as assignment /
370
+ # access to a descriptor attribute wants to move through __get__.
371
+ # Therefore, references to MapperProperty as an instance variable, such
372
+ # as in PropComparator, may have some special typing workarounds such as the
373
+ # use of sqlalchemy.util.typing.DescriptorReference to avoid mis-interpretation
374
+ # by typing tools
375
+ @inspection._self_inspects
376
+ class MapperProperty(
377
+ HasCacheKey,
378
+ _DCAttributeOptions,
379
+ _MappedAttribute[_T],
380
+ InspectionAttrInfo,
381
+ util.MemoizedSlots,
382
+ ):
383
+ """Represent a particular class attribute mapped by :class:`_orm.Mapper`.
384
+
385
+ The most common occurrences of :class:`.MapperProperty` are the
386
+ mapped :class:`_schema.Column`, which is represented in a mapping as
387
+ an instance of :class:`.ColumnProperty`,
388
+ and a reference to another class produced by :func:`_orm.relationship`,
389
+ represented in the mapping as an instance of
390
+ :class:`.Relationship`.
391
+
392
+ """
393
+
394
+ __slots__ = (
395
+ "_configure_started",
396
+ "_configure_finished",
397
+ "_attribute_options",
398
+ "_has_dataclass_arguments",
399
+ "parent",
400
+ "key",
401
+ "info",
402
+ "doc",
403
+ )
404
+
405
+ _cache_key_traversal: _TraverseInternalsType = [
406
+ ("parent", visitors.ExtendedInternalTraversal.dp_has_cache_key),
407
+ ("key", visitors.ExtendedInternalTraversal.dp_string),
408
+ ]
409
+
410
+ if not TYPE_CHECKING:
411
+ cascade = None
412
+
413
+ is_property = True
414
+ """Part of the InspectionAttr interface; states this object is a
415
+ mapper property.
416
+
417
+ """
418
+
419
+ comparator: PropComparator[_T]
420
+ """The :class:`_orm.PropComparator` instance that implements SQL
421
+ expression construction on behalf of this mapped attribute."""
422
+
423
+ key: str
424
+ """name of class attribute"""
425
+
426
+ parent: Mapper[Any]
427
+ """the :class:`.Mapper` managing this property."""
428
+
429
+ _is_relationship = False
430
+
431
+ _links_to_entity: bool
432
+ """True if this MapperProperty refers to a mapped entity.
433
+
434
+ Should only be True for Relationship, False for all others.
435
+
436
+ """
437
+
438
+ doc: Optional[str]
439
+ """optional documentation string"""
440
+
441
+ info: _InfoType
442
+ """Info dictionary associated with the object, allowing user-defined
443
+ data to be associated with this :class:`.InspectionAttr`.
444
+
445
+ The dictionary is generated when first accessed. Alternatively,
446
+ it can be specified as a constructor argument to the
447
+ :func:`.column_property`, :func:`_orm.relationship`, or :func:`.composite`
448
+ functions.
449
+
450
+ .. seealso::
451
+
452
+ :attr:`.QueryableAttribute.info`
453
+
454
+ :attr:`.SchemaItem.info`
455
+
456
+ """
457
+
458
+ def _memoized_attr_info(self) -> _InfoType:
459
+ """Info dictionary associated with the object, allowing user-defined
460
+ data to be associated with this :class:`.InspectionAttr`.
461
+
462
+ The dictionary is generated when first accessed. Alternatively,
463
+ it can be specified as a constructor argument to the
464
+ :func:`.column_property`, :func:`_orm.relationship`, or
465
+ :func:`.composite`
466
+ functions.
467
+
468
+ .. seealso::
469
+
470
+ :attr:`.QueryableAttribute.info`
471
+
472
+ :attr:`.SchemaItem.info`
473
+
474
+ """
475
+ return {}
476
+
477
+ def setup(
478
+ self,
479
+ context: ORMCompileState,
480
+ query_entity: _MapperEntity,
481
+ path: AbstractEntityRegistry,
482
+ adapter: Optional[ORMAdapter],
483
+ **kwargs: Any,
484
+ ) -> None:
485
+ """Called by Query for the purposes of constructing a SQL statement.
486
+
487
+ Each MapperProperty associated with the target mapper processes the
488
+ statement referenced by the query context, adding columns and/or
489
+ criterion as appropriate.
490
+
491
+ """
492
+
493
+ def create_row_processor(
494
+ self,
495
+ context: ORMCompileState,
496
+ query_entity: _MapperEntity,
497
+ path: AbstractEntityRegistry,
498
+ mapper: Mapper[Any],
499
+ result: Result[Any],
500
+ adapter: Optional[ORMAdapter],
501
+ populators: _PopulatorDict,
502
+ ) -> None:
503
+ """Produce row processing functions and append to the given
504
+ set of populators lists.
505
+
506
+ """
507
+
508
+ def cascade_iterator(
509
+ self,
510
+ type_: str,
511
+ state: InstanceState[Any],
512
+ dict_: _InstanceDict,
513
+ visited_states: Set[InstanceState[Any]],
514
+ halt_on: Optional[Callable[[InstanceState[Any]], bool]] = None,
515
+ ) -> Iterator[
516
+ Tuple[object, Mapper[Any], InstanceState[Any], _InstanceDict]
517
+ ]:
518
+ """Iterate through instances related to the given instance for
519
+ a particular 'cascade', starting with this MapperProperty.
520
+
521
+ Return an iterator3-tuples (instance, mapper, state).
522
+
523
+ Note that the 'cascade' collection on this MapperProperty is
524
+ checked first for the given type before cascade_iterator is called.
525
+
526
+ This method typically only applies to Relationship.
527
+
528
+ """
529
+
530
+ return iter(())
531
+
532
+ def set_parent(self, parent: Mapper[Any], init: bool) -> None:
533
+ """Set the parent mapper that references this MapperProperty.
534
+
535
+ This method is overridden by some subclasses to perform extra
536
+ setup when the mapper is first known.
537
+
538
+ """
539
+ self.parent = parent
540
+
541
+ def instrument_class(self, mapper: Mapper[Any]) -> None:
542
+ """Hook called by the Mapper to the property to initiate
543
+ instrumentation of the class attribute managed by this
544
+ MapperProperty.
545
+
546
+ The MapperProperty here will typically call out to the
547
+ attributes module to set up an InstrumentedAttribute.
548
+
549
+ This step is the first of two steps to set up an InstrumentedAttribute,
550
+ and is called early in the mapper setup process.
551
+
552
+ The second step is typically the init_class_attribute step,
553
+ called from StrategizedProperty via the post_instrument_class()
554
+ hook. This step assigns additional state to the InstrumentedAttribute
555
+ (specifically the "impl") which has been determined after the
556
+ MapperProperty has determined what kind of persistence
557
+ management it needs to do (e.g. scalar, object, collection, etc).
558
+
559
+ """
560
+
561
+ def __init__(
562
+ self,
563
+ attribute_options: Optional[_AttributeOptions] = None,
564
+ _assume_readonly_dc_attributes: bool = False,
565
+ ) -> None:
566
+ self._configure_started = False
567
+ self._configure_finished = False
568
+
569
+ if _assume_readonly_dc_attributes:
570
+ default_attrs = _DEFAULT_READONLY_ATTRIBUTE_OPTIONS
571
+ else:
572
+ default_attrs = _DEFAULT_ATTRIBUTE_OPTIONS
573
+
574
+ if attribute_options and attribute_options != default_attrs:
575
+ self._has_dataclass_arguments = True
576
+ self._attribute_options = attribute_options
577
+ else:
578
+ self._has_dataclass_arguments = False
579
+ self._attribute_options = default_attrs
580
+
581
+ def init(self) -> None:
582
+ """Called after all mappers are created to assemble
583
+ relationships between mappers and perform other post-mapper-creation
584
+ initialization steps.
585
+
586
+
587
+ """
588
+ self._configure_started = True
589
+ self.do_init()
590
+ self._configure_finished = True
591
+
592
+ @property
593
+ def class_attribute(self) -> InstrumentedAttribute[_T]:
594
+ """Return the class-bound descriptor corresponding to this
595
+ :class:`.MapperProperty`.
596
+
597
+ This is basically a ``getattr()`` call::
598
+
599
+ return getattr(self.parent.class_, self.key)
600
+
601
+ I.e. if this :class:`.MapperProperty` were named ``addresses``,
602
+ and the class to which it is mapped is ``User``, this sequence
603
+ is possible::
604
+
605
+ >>> from sqlalchemy import inspect
606
+ >>> mapper = inspect(User)
607
+ >>> addresses_property = mapper.attrs.addresses
608
+ >>> addresses_property.class_attribute is User.addresses
609
+ True
610
+ >>> User.addresses.property is addresses_property
611
+ True
612
+
613
+
614
+ """
615
+
616
+ return getattr(self.parent.class_, self.key) # type: ignore
617
+
618
+ def do_init(self) -> None:
619
+ """Perform subclass-specific initialization post-mapper-creation
620
+ steps.
621
+
622
+ This is a template method called by the ``MapperProperty``
623
+ object's init() method.
624
+
625
+ """
626
+
627
+ def post_instrument_class(self, mapper: Mapper[Any]) -> None:
628
+ """Perform instrumentation adjustments that need to occur
629
+ after init() has completed.
630
+
631
+ The given Mapper is the Mapper invoking the operation, which
632
+ may not be the same Mapper as self.parent in an inheritance
633
+ scenario; however, Mapper will always at least be a sub-mapper of
634
+ self.parent.
635
+
636
+ This method is typically used by StrategizedProperty, which delegates
637
+ it to LoaderStrategy.init_class_attribute() to perform final setup
638
+ on the class-bound InstrumentedAttribute.
639
+
640
+ """
641
+
642
+ def merge(
643
+ self,
644
+ session: Session,
645
+ source_state: InstanceState[Any],
646
+ source_dict: _InstanceDict,
647
+ dest_state: InstanceState[Any],
648
+ dest_dict: _InstanceDict,
649
+ load: bool,
650
+ _recursive: Dict[Any, object],
651
+ _resolve_conflict_map: Dict[_IdentityKeyType[Any], object],
652
+ ) -> None:
653
+ """Merge the attribute represented by this ``MapperProperty``
654
+ from source to destination object.
655
+
656
+ """
657
+
658
+ def __repr__(self) -> str:
659
+ return "<%s at 0x%x; %s>" % (
660
+ self.__class__.__name__,
661
+ id(self),
662
+ getattr(self, "key", "no key"),
663
+ )
664
+
665
+
666
+ @inspection._self_inspects
667
+ class PropComparator(SQLORMOperations[_T_co], Generic[_T_co], ColumnOperators):
668
+ r"""Defines SQL operations for ORM mapped attributes.
669
+
670
+ SQLAlchemy allows for operators to
671
+ be redefined at both the Core and ORM level. :class:`.PropComparator`
672
+ is the base class of operator redefinition for ORM-level operations,
673
+ including those of :class:`.ColumnProperty`,
674
+ :class:`.Relationship`, and :class:`.Composite`.
675
+
676
+ User-defined subclasses of :class:`.PropComparator` may be created. The
677
+ built-in Python comparison and math operator methods, such as
678
+ :meth:`.operators.ColumnOperators.__eq__`,
679
+ :meth:`.operators.ColumnOperators.__lt__`, and
680
+ :meth:`.operators.ColumnOperators.__add__`, can be overridden to provide
681
+ new operator behavior. The custom :class:`.PropComparator` is passed to
682
+ the :class:`.MapperProperty` instance via the ``comparator_factory``
683
+ argument. In each case,
684
+ the appropriate subclass of :class:`.PropComparator` should be used::
685
+
686
+ # definition of custom PropComparator subclasses
687
+
688
+ from sqlalchemy.orm.properties import \
689
+ ColumnProperty,\
690
+ Composite,\
691
+ Relationship
692
+
693
+ class MyColumnComparator(ColumnProperty.Comparator):
694
+ def __eq__(self, other):
695
+ return self.__clause_element__() == other
696
+
697
+ class MyRelationshipComparator(Relationship.Comparator):
698
+ def any(self, expression):
699
+ "define the 'any' operation"
700
+ # ...
701
+
702
+ class MyCompositeComparator(Composite.Comparator):
703
+ def __gt__(self, other):
704
+ "redefine the 'greater than' operation"
705
+
706
+ return sql.and_(*[a>b for a, b in
707
+ zip(self.__clause_element__().clauses,
708
+ other.__composite_values__())])
709
+
710
+
711
+ # application of custom PropComparator subclasses
712
+
713
+ from sqlalchemy.orm import column_property, relationship, composite
714
+ from sqlalchemy import Column, String
715
+
716
+ class SomeMappedClass(Base):
717
+ some_column = column_property(Column("some_column", String),
718
+ comparator_factory=MyColumnComparator)
719
+
720
+ some_relationship = relationship(SomeOtherClass,
721
+ comparator_factory=MyRelationshipComparator)
722
+
723
+ some_composite = composite(
724
+ Column("a", String), Column("b", String),
725
+ comparator_factory=MyCompositeComparator
726
+ )
727
+
728
+ Note that for column-level operator redefinition, it's usually
729
+ simpler to define the operators at the Core level, using the
730
+ :attr:`.TypeEngine.comparator_factory` attribute. See
731
+ :ref:`types_operators` for more detail.
732
+
733
+ .. seealso::
734
+
735
+ :class:`.ColumnProperty.Comparator`
736
+
737
+ :class:`.Relationship.Comparator`
738
+
739
+ :class:`.Composite.Comparator`
740
+
741
+ :class:`.ColumnOperators`
742
+
743
+ :ref:`types_operators`
744
+
745
+ :attr:`.TypeEngine.comparator_factory`
746
+
747
+ """
748
+
749
+ __slots__ = "prop", "_parententity", "_adapt_to_entity"
750
+
751
+ __visit_name__ = "orm_prop_comparator"
752
+
753
+ _parententity: _InternalEntityType[Any]
754
+ _adapt_to_entity: Optional[AliasedInsp[Any]]
755
+ prop: RODescriptorReference[MapperProperty[_T_co]]
756
+
757
+ def __init__(
758
+ self,
759
+ prop: MapperProperty[_T],
760
+ parentmapper: _InternalEntityType[Any],
761
+ adapt_to_entity: Optional[AliasedInsp[Any]] = None,
762
+ ):
763
+ self.prop = prop
764
+ self._parententity = adapt_to_entity or parentmapper
765
+ self._adapt_to_entity = adapt_to_entity
766
+
767
+ @util.non_memoized_property
768
+ def property(self) -> MapperProperty[_T_co]:
769
+ """Return the :class:`.MapperProperty` associated with this
770
+ :class:`.PropComparator`.
771
+
772
+
773
+ Return values here will commonly be instances of
774
+ :class:`.ColumnProperty` or :class:`.Relationship`.
775
+
776
+
777
+ """
778
+ return self.prop
779
+
780
+ def __clause_element__(self) -> roles.ColumnsClauseRole:
781
+ raise NotImplementedError("%r" % self)
782
+
783
+ def _bulk_update_tuples(
784
+ self, value: Any
785
+ ) -> Sequence[Tuple[_DMLColumnArgument, Any]]:
786
+ """Receive a SQL expression that represents a value in the SET
787
+ clause of an UPDATE statement.
788
+
789
+ Return a tuple that can be passed to a :class:`_expression.Update`
790
+ construct.
791
+
792
+ """
793
+
794
+ return [(cast("_DMLColumnArgument", self.__clause_element__()), value)]
795
+
796
+ def adapt_to_entity(
797
+ self, adapt_to_entity: AliasedInsp[Any]
798
+ ) -> PropComparator[_T_co]:
799
+ """Return a copy of this PropComparator which will use the given
800
+ :class:`.AliasedInsp` to produce corresponding expressions.
801
+ """
802
+ return self.__class__(self.prop, self._parententity, adapt_to_entity)
803
+
804
+ @util.ro_non_memoized_property
805
+ def _parentmapper(self) -> Mapper[Any]:
806
+ """legacy; this is renamed to _parententity to be
807
+ compatible with QueryableAttribute."""
808
+ return self._parententity.mapper
809
+
810
+ def _criterion_exists(
811
+ self,
812
+ criterion: Optional[_ColumnExpressionArgument[bool]] = None,
813
+ **kwargs: Any,
814
+ ) -> ColumnElement[Any]:
815
+ return self.prop.comparator._criterion_exists(criterion, **kwargs)
816
+
817
+ @util.ro_non_memoized_property
818
+ def adapter(self) -> Optional[_ORMAdapterProto]:
819
+ """Produce a callable that adapts column expressions
820
+ to suit an aliased version of this comparator.
821
+
822
+ """
823
+ if self._adapt_to_entity is None:
824
+ return None
825
+ else:
826
+ return self._adapt_to_entity._orm_adapt_element
827
+
828
+ @util.ro_non_memoized_property
829
+ def info(self) -> _InfoType:
830
+ return self.prop.info
831
+
832
+ @staticmethod
833
+ def _any_op(a: Any, b: Any, **kwargs: Any) -> Any:
834
+ return a.any(b, **kwargs)
835
+
836
+ @staticmethod
837
+ def _has_op(left: Any, other: Any, **kwargs: Any) -> Any:
838
+ return left.has(other, **kwargs)
839
+
840
+ @staticmethod
841
+ def _of_type_op(a: Any, class_: Any) -> Any:
842
+ return a.of_type(class_)
843
+
844
+ any_op = cast(operators.OperatorType, _any_op)
845
+ has_op = cast(operators.OperatorType, _has_op)
846
+ of_type_op = cast(operators.OperatorType, _of_type_op)
847
+
848
+ if typing.TYPE_CHECKING:
849
+
850
+ def operate(
851
+ self, op: OperatorType, *other: Any, **kwargs: Any
852
+ ) -> ColumnElement[Any]: ...
853
+
854
+ def reverse_operate(
855
+ self, op: OperatorType, other: Any, **kwargs: Any
856
+ ) -> ColumnElement[Any]: ...
857
+
858
+ def of_type(self, class_: _EntityType[Any]) -> PropComparator[_T_co]:
859
+ r"""Redefine this object in terms of a polymorphic subclass,
860
+ :func:`_orm.with_polymorphic` construct, or :func:`_orm.aliased`
861
+ construct.
862
+
863
+ Returns a new PropComparator from which further criterion can be
864
+ evaluated.
865
+
866
+ e.g.::
867
+
868
+ query.join(Company.employees.of_type(Engineer)).\
869
+ filter(Engineer.name=='foo')
870
+
871
+ :param \class_: a class or mapper indicating that criterion will be
872
+ against this specific subclass.
873
+
874
+ .. seealso::
875
+
876
+ :ref:`orm_queryguide_joining_relationships_aliased` - in the
877
+ :ref:`queryguide_toplevel`
878
+
879
+ :ref:`inheritance_of_type`
880
+
881
+ """
882
+
883
+ return self.operate(PropComparator.of_type_op, class_) # type: ignore
884
+
885
+ def and_(
886
+ self, *criteria: _ColumnExpressionArgument[bool]
887
+ ) -> PropComparator[bool]:
888
+ """Add additional criteria to the ON clause that's represented by this
889
+ relationship attribute.
890
+
891
+ E.g.::
892
+
893
+
894
+ stmt = select(User).join(
895
+ User.addresses.and_(Address.email_address != 'foo')
896
+ )
897
+
898
+ stmt = select(User).options(
899
+ joinedload(User.addresses.and_(Address.email_address != 'foo'))
900
+ )
901
+
902
+ .. versionadded:: 1.4
903
+
904
+ .. seealso::
905
+
906
+ :ref:`orm_queryguide_join_on_augmented`
907
+
908
+ :ref:`loader_option_criteria`
909
+
910
+ :func:`.with_loader_criteria`
911
+
912
+ """
913
+ return self.operate(operators.and_, *criteria) # type: ignore
914
+
915
+ def any(
916
+ self,
917
+ criterion: Optional[_ColumnExpressionArgument[bool]] = None,
918
+ **kwargs: Any,
919
+ ) -> ColumnElement[bool]:
920
+ r"""Return a SQL expression representing true if this element
921
+ references a member which meets the given criterion.
922
+
923
+ The usual implementation of ``any()`` is
924
+ :meth:`.Relationship.Comparator.any`.
925
+
926
+ :param criterion: an optional ClauseElement formulated against the
927
+ member class' table or attributes.
928
+
929
+ :param \**kwargs: key/value pairs corresponding to member class
930
+ attribute names which will be compared via equality to the
931
+ corresponding values.
932
+
933
+ """
934
+
935
+ return self.operate(PropComparator.any_op, criterion, **kwargs)
936
+
937
+ def has(
938
+ self,
939
+ criterion: Optional[_ColumnExpressionArgument[bool]] = None,
940
+ **kwargs: Any,
941
+ ) -> ColumnElement[bool]:
942
+ r"""Return a SQL expression representing true if this element
943
+ references a member which meets the given criterion.
944
+
945
+ The usual implementation of ``has()`` is
946
+ :meth:`.Relationship.Comparator.has`.
947
+
948
+ :param criterion: an optional ClauseElement formulated against the
949
+ member class' table or attributes.
950
+
951
+ :param \**kwargs: key/value pairs corresponding to member class
952
+ attribute names which will be compared via equality to the
953
+ corresponding values.
954
+
955
+ """
956
+
957
+ return self.operate(PropComparator.has_op, criterion, **kwargs)
958
+
959
+
960
+ class StrategizedProperty(MapperProperty[_T]):
961
+ """A MapperProperty which uses selectable strategies to affect
962
+ loading behavior.
963
+
964
+ There is a single strategy selected by default. Alternate
965
+ strategies can be selected at Query time through the usage of
966
+ ``StrategizedOption`` objects via the Query.options() method.
967
+
968
+ The mechanics of StrategizedProperty are used for every Query
969
+ invocation for every mapped attribute participating in that Query,
970
+ to determine first how the attribute will be rendered in SQL
971
+ and secondly how the attribute will retrieve a value from a result
972
+ row and apply it to a mapped object. The routines here are very
973
+ performance-critical.
974
+
975
+ """
976
+
977
+ __slots__ = (
978
+ "_strategies",
979
+ "strategy",
980
+ "_wildcard_token",
981
+ "_default_path_loader_key",
982
+ "strategy_key",
983
+ )
984
+ inherit_cache = True
985
+ strategy_wildcard_key: ClassVar[str]
986
+
987
+ strategy_key: _StrategyKey
988
+
989
+ _strategies: Dict[_StrategyKey, LoaderStrategy]
990
+
991
+ def _memoized_attr__wildcard_token(self) -> Tuple[str]:
992
+ return (
993
+ f"{self.strategy_wildcard_key}:{path_registry._WILDCARD_TOKEN}",
994
+ )
995
+
996
+ def _memoized_attr__default_path_loader_key(
997
+ self,
998
+ ) -> Tuple[str, Tuple[str]]:
999
+ return (
1000
+ "loader",
1001
+ (f"{self.strategy_wildcard_key}:{path_registry._DEFAULT_TOKEN}",),
1002
+ )
1003
+
1004
+ def _get_context_loader(
1005
+ self, context: ORMCompileState, path: AbstractEntityRegistry
1006
+ ) -> Optional[_LoadElement]:
1007
+ load: Optional[_LoadElement] = None
1008
+
1009
+ search_path = path[self]
1010
+
1011
+ # search among: exact match, "attr.*", "default" strategy
1012
+ # if any.
1013
+ for path_key in (
1014
+ search_path._loader_key,
1015
+ search_path._wildcard_path_loader_key,
1016
+ search_path._default_path_loader_key,
1017
+ ):
1018
+ if path_key in context.attributes:
1019
+ load = context.attributes[path_key]
1020
+ break
1021
+
1022
+ # note that if strategy_options.Load is placing non-actionable
1023
+ # objects in the context like defaultload(), we would
1024
+ # need to continue the loop here if we got such an
1025
+ # option as below.
1026
+ # if load.strategy or load.local_opts:
1027
+ # break
1028
+
1029
+ return load
1030
+
1031
+ def _get_strategy(self, key: _StrategyKey) -> LoaderStrategy:
1032
+ try:
1033
+ return self._strategies[key]
1034
+ except KeyError:
1035
+ pass
1036
+
1037
+ # run outside to prevent transfer of exception context
1038
+ cls = self._strategy_lookup(self, *key)
1039
+ # this previously was setting self._strategies[cls], that's
1040
+ # a bad idea; should use strategy key at all times because every
1041
+ # strategy has multiple keys at this point
1042
+ self._strategies[key] = strategy = cls(self, key)
1043
+ return strategy
1044
+
1045
+ def setup(
1046
+ self,
1047
+ context: ORMCompileState,
1048
+ query_entity: _MapperEntity,
1049
+ path: AbstractEntityRegistry,
1050
+ adapter: Optional[ORMAdapter],
1051
+ **kwargs: Any,
1052
+ ) -> None:
1053
+ loader = self._get_context_loader(context, path)
1054
+ if loader and loader.strategy:
1055
+ strat = self._get_strategy(loader.strategy)
1056
+ else:
1057
+ strat = self.strategy
1058
+ strat.setup_query(
1059
+ context, query_entity, path, loader, adapter, **kwargs
1060
+ )
1061
+
1062
+ def create_row_processor(
1063
+ self,
1064
+ context: ORMCompileState,
1065
+ query_entity: _MapperEntity,
1066
+ path: AbstractEntityRegistry,
1067
+ mapper: Mapper[Any],
1068
+ result: Result[Any],
1069
+ adapter: Optional[ORMAdapter],
1070
+ populators: _PopulatorDict,
1071
+ ) -> None:
1072
+ loader = self._get_context_loader(context, path)
1073
+ if loader and loader.strategy:
1074
+ strat = self._get_strategy(loader.strategy)
1075
+ else:
1076
+ strat = self.strategy
1077
+ strat.create_row_processor(
1078
+ context,
1079
+ query_entity,
1080
+ path,
1081
+ loader,
1082
+ mapper,
1083
+ result,
1084
+ adapter,
1085
+ populators,
1086
+ )
1087
+
1088
+ def do_init(self) -> None:
1089
+ self._strategies = {}
1090
+ self.strategy = self._get_strategy(self.strategy_key)
1091
+
1092
+ def post_instrument_class(self, mapper: Mapper[Any]) -> None:
1093
+ if (
1094
+ not self.parent.non_primary
1095
+ and not mapper.class_manager._attr_has_impl(self.key)
1096
+ ):
1097
+ self.strategy.init_class_attribute(mapper)
1098
+
1099
+ _all_strategies: collections.defaultdict[
1100
+ Type[MapperProperty[Any]], Dict[_StrategyKey, Type[LoaderStrategy]]
1101
+ ] = collections.defaultdict(dict)
1102
+
1103
+ @classmethod
1104
+ def strategy_for(cls, **kw: Any) -> Callable[[_TLS], _TLS]:
1105
+ def decorate(dec_cls: _TLS) -> _TLS:
1106
+ # ensure each subclass of the strategy has its
1107
+ # own _strategy_keys collection
1108
+ if "_strategy_keys" not in dec_cls.__dict__:
1109
+ dec_cls._strategy_keys = []
1110
+ key = tuple(sorted(kw.items()))
1111
+ cls._all_strategies[cls][key] = dec_cls
1112
+ dec_cls._strategy_keys.append(key)
1113
+ return dec_cls
1114
+
1115
+ return decorate
1116
+
1117
+ @classmethod
1118
+ def _strategy_lookup(
1119
+ cls, requesting_property: MapperProperty[Any], *key: Any
1120
+ ) -> Type[LoaderStrategy]:
1121
+ requesting_property.parent._with_polymorphic_mappers
1122
+
1123
+ for prop_cls in cls.__mro__:
1124
+ if prop_cls in cls._all_strategies:
1125
+ if TYPE_CHECKING:
1126
+ assert issubclass(prop_cls, MapperProperty)
1127
+ strategies = cls._all_strategies[prop_cls]
1128
+ try:
1129
+ return strategies[key]
1130
+ except KeyError:
1131
+ pass
1132
+
1133
+ for property_type, strats in cls._all_strategies.items():
1134
+ if key in strats:
1135
+ intended_property_type = property_type
1136
+ actual_strategy = strats[key]
1137
+ break
1138
+ else:
1139
+ intended_property_type = None
1140
+ actual_strategy = None
1141
+
1142
+ raise orm_exc.LoaderStrategyException(
1143
+ cls,
1144
+ requesting_property,
1145
+ intended_property_type,
1146
+ actual_strategy,
1147
+ key,
1148
+ )
1149
+
1150
+
1151
+ class ORMOption(ExecutableOption):
1152
+ """Base class for option objects that are passed to ORM queries.
1153
+
1154
+ These options may be consumed by :meth:`.Query.options`,
1155
+ :meth:`.Select.options`, or in a more general sense by any
1156
+ :meth:`.Executable.options` method. They are interpreted at
1157
+ statement compile time or execution time in modern use. The
1158
+ deprecated :class:`.MapperOption` is consumed at ORM query construction
1159
+ time.
1160
+
1161
+ .. versionadded:: 1.4
1162
+
1163
+ """
1164
+
1165
+ __slots__ = ()
1166
+
1167
+ _is_legacy_option = False
1168
+
1169
+ propagate_to_loaders = False
1170
+ """if True, indicate this option should be carried along
1171
+ to "secondary" SELECT statements that occur for relationship
1172
+ lazy loaders as well as attribute load / refresh operations.
1173
+
1174
+ """
1175
+
1176
+ _is_core = False
1177
+
1178
+ _is_user_defined = False
1179
+
1180
+ _is_compile_state = False
1181
+
1182
+ _is_criteria_option = False
1183
+
1184
+ _is_strategy_option = False
1185
+
1186
+ def _adapt_cached_option_to_uncached_option(
1187
+ self, context: QueryContext, uncached_opt: ORMOption
1188
+ ) -> ORMOption:
1189
+ """adapt this option to the "uncached" version of itself in a
1190
+ loader strategy context.
1191
+
1192
+ given "self" which is an option from a cached query, as well as the
1193
+ corresponding option from the uncached version of the same query,
1194
+ return the option we should use in a new query, in the context of a
1195
+ loader strategy being asked to load related rows on behalf of that
1196
+ cached query, which is assumed to be building a new query based on
1197
+ entities passed to us from the cached query.
1198
+
1199
+ Currently this routine chooses between "self" and "uncached" without
1200
+ manufacturing anything new. If the option is itself a loader strategy
1201
+ option which has a path, that path needs to match to the entities being
1202
+ passed to us by the cached query, so the :class:`_orm.Load` subclass
1203
+ overrides this to return "self". For all other options, we return the
1204
+ uncached form which may have changing state, such as a
1205
+ with_loader_criteria() option which will very often have new state.
1206
+
1207
+ This routine could in the future involve
1208
+ generating a new option based on both inputs if use cases arise,
1209
+ such as if with_loader_criteria() needed to match up to
1210
+ ``AliasedClass`` instances given in the parent query.
1211
+
1212
+ However, longer term it might be better to restructure things such that
1213
+ ``AliasedClass`` entities are always matched up on their cache key,
1214
+ instead of identity, in things like paths and such, so that this whole
1215
+ issue of "the uncached option does not match the entities" goes away.
1216
+ However this would make ``PathRegistry`` more complicated and difficult
1217
+ to debug as well as potentially less performant in that it would be
1218
+ hashing enormous cache keys rather than a simple AliasedInsp. UNLESS,
1219
+ we could get cache keys overall to be reliably hashed into something
1220
+ like an md5 key.
1221
+
1222
+ .. versionadded:: 1.4.41
1223
+
1224
+ """
1225
+ if uncached_opt is not None:
1226
+ return uncached_opt
1227
+ else:
1228
+ return self
1229
+
1230
+
1231
+ class CompileStateOption(HasCacheKey, ORMOption):
1232
+ """base for :class:`.ORMOption` classes that affect the compilation of
1233
+ a SQL query and therefore need to be part of the cache key.
1234
+
1235
+ .. note:: :class:`.CompileStateOption` is generally non-public and
1236
+ should not be used as a base class for user-defined options; instead,
1237
+ use :class:`.UserDefinedOption`, which is easier to use as it does not
1238
+ interact with ORM compilation internals or caching.
1239
+
1240
+ :class:`.CompileStateOption` defines an internal attribute
1241
+ ``_is_compile_state=True`` which has the effect of the ORM compilation
1242
+ routines for SELECT and other statements will call upon these options when
1243
+ a SQL string is being compiled. As such, these classes implement
1244
+ :class:`.HasCacheKey` and need to provide robust ``_cache_key_traversal``
1245
+ structures.
1246
+
1247
+ The :class:`.CompileStateOption` class is used to implement the ORM
1248
+ :class:`.LoaderOption` and :class:`.CriteriaOption` classes.
1249
+
1250
+ .. versionadded:: 1.4.28
1251
+
1252
+
1253
+ """
1254
+
1255
+ __slots__ = ()
1256
+
1257
+ _is_compile_state = True
1258
+
1259
+ def process_compile_state(self, compile_state: ORMCompileState) -> None:
1260
+ """Apply a modification to a given :class:`.ORMCompileState`.
1261
+
1262
+ This method is part of the implementation of a particular
1263
+ :class:`.CompileStateOption` and is only invoked internally
1264
+ when an ORM query is compiled.
1265
+
1266
+ """
1267
+
1268
+ def process_compile_state_replaced_entities(
1269
+ self,
1270
+ compile_state: ORMCompileState,
1271
+ mapper_entities: Sequence[_MapperEntity],
1272
+ ) -> None:
1273
+ """Apply a modification to a given :class:`.ORMCompileState`,
1274
+ given entities that were replaced by with_only_columns() or
1275
+ with_entities().
1276
+
1277
+ This method is part of the implementation of a particular
1278
+ :class:`.CompileStateOption` and is only invoked internally
1279
+ when an ORM query is compiled.
1280
+
1281
+ .. versionadded:: 1.4.19
1282
+
1283
+ """
1284
+
1285
+
1286
+ class LoaderOption(CompileStateOption):
1287
+ """Describe a loader modification to an ORM statement at compilation time.
1288
+
1289
+ .. versionadded:: 1.4
1290
+
1291
+ """
1292
+
1293
+ __slots__ = ()
1294
+
1295
+ def process_compile_state_replaced_entities(
1296
+ self,
1297
+ compile_state: ORMCompileState,
1298
+ mapper_entities: Sequence[_MapperEntity],
1299
+ ) -> None:
1300
+ self.process_compile_state(compile_state)
1301
+
1302
+
1303
+ class CriteriaOption(CompileStateOption):
1304
+ """Describe a WHERE criteria modification to an ORM statement at
1305
+ compilation time.
1306
+
1307
+ .. versionadded:: 1.4
1308
+
1309
+ """
1310
+
1311
+ __slots__ = ()
1312
+
1313
+ _is_criteria_option = True
1314
+
1315
+ def get_global_criteria(self, attributes: Dict[str, Any]) -> None:
1316
+ """update additional entity criteria options in the given
1317
+ attributes dictionary.
1318
+
1319
+ """
1320
+
1321
+
1322
+ class UserDefinedOption(ORMOption):
1323
+ """Base class for a user-defined option that can be consumed from the
1324
+ :meth:`.SessionEvents.do_orm_execute` event hook.
1325
+
1326
+ """
1327
+
1328
+ __slots__ = ("payload",)
1329
+
1330
+ _is_legacy_option = False
1331
+
1332
+ _is_user_defined = True
1333
+
1334
+ propagate_to_loaders = False
1335
+ """if True, indicate this option should be carried along
1336
+ to "secondary" Query objects produced during lazy loads
1337
+ or refresh operations.
1338
+
1339
+ """
1340
+
1341
+ def __init__(self, payload: Optional[Any] = None):
1342
+ self.payload = payload
1343
+
1344
+
1345
+ @util.deprecated_cls(
1346
+ "1.4",
1347
+ "The :class:`.MapperOption class is deprecated and will be removed "
1348
+ "in a future release. For "
1349
+ "modifications to queries on a per-execution basis, use the "
1350
+ ":class:`.UserDefinedOption` class to establish state within a "
1351
+ ":class:`.Query` or other Core statement, then use the "
1352
+ ":meth:`.SessionEvents.before_orm_execute` hook to consume them.",
1353
+ constructor=None,
1354
+ )
1355
+ class MapperOption(ORMOption):
1356
+ """Describe a modification to a Query"""
1357
+
1358
+ __slots__ = ()
1359
+
1360
+ _is_legacy_option = True
1361
+
1362
+ propagate_to_loaders = False
1363
+ """if True, indicate this option should be carried along
1364
+ to "secondary" Query objects produced during lazy loads
1365
+ or refresh operations.
1366
+
1367
+ """
1368
+
1369
+ def process_query(self, query: Query[Any]) -> None:
1370
+ """Apply a modification to the given :class:`_query.Query`."""
1371
+
1372
+ def process_query_conditionally(self, query: Query[Any]) -> None:
1373
+ """same as process_query(), except that this option may not
1374
+ apply to the given query.
1375
+
1376
+ This is typically applied during a lazy load or scalar refresh
1377
+ operation to propagate options stated in the original Query to the
1378
+ new Query being used for the load. It occurs for those options that
1379
+ specify propagate_to_loaders=True.
1380
+
1381
+ """
1382
+
1383
+ self.process_query(query)
1384
+
1385
+
1386
+ class LoaderStrategy:
1387
+ """Describe the loading behavior of a StrategizedProperty object.
1388
+
1389
+ The ``LoaderStrategy`` interacts with the querying process in three
1390
+ ways:
1391
+
1392
+ * it controls the configuration of the ``InstrumentedAttribute``
1393
+ placed on a class to handle the behavior of the attribute. this
1394
+ may involve setting up class-level callable functions to fire
1395
+ off a select operation when the attribute is first accessed
1396
+ (i.e. a lazy load)
1397
+
1398
+ * it processes the ``QueryContext`` at statement construction time,
1399
+ where it can modify the SQL statement that is being produced.
1400
+ For example, simple column attributes will add their represented
1401
+ column to the list of selected columns, a joined eager loader
1402
+ may establish join clauses to add to the statement.
1403
+
1404
+ * It produces "row processor" functions at result fetching time.
1405
+ These "row processor" functions populate a particular attribute
1406
+ on a particular mapped instance.
1407
+
1408
+ """
1409
+
1410
+ __slots__ = (
1411
+ "parent_property",
1412
+ "is_class_level",
1413
+ "parent",
1414
+ "key",
1415
+ "strategy_key",
1416
+ "strategy_opts",
1417
+ )
1418
+
1419
+ _strategy_keys: ClassVar[List[_StrategyKey]]
1420
+
1421
+ def __init__(
1422
+ self, parent: MapperProperty[Any], strategy_key: _StrategyKey
1423
+ ):
1424
+ self.parent_property = parent
1425
+ self.is_class_level = False
1426
+ self.parent = self.parent_property.parent
1427
+ self.key = self.parent_property.key
1428
+ self.strategy_key = strategy_key
1429
+ self.strategy_opts = dict(strategy_key)
1430
+
1431
+ def init_class_attribute(self, mapper: Mapper[Any]) -> None:
1432
+ pass
1433
+
1434
+ def setup_query(
1435
+ self,
1436
+ compile_state: ORMCompileState,
1437
+ query_entity: _MapperEntity,
1438
+ path: AbstractEntityRegistry,
1439
+ loadopt: Optional[_LoadElement],
1440
+ adapter: Optional[ORMAdapter],
1441
+ **kwargs: Any,
1442
+ ) -> None:
1443
+ """Establish column and other state for a given QueryContext.
1444
+
1445
+ This method fulfills the contract specified by MapperProperty.setup().
1446
+
1447
+ StrategizedProperty delegates its setup() method
1448
+ directly to this method.
1449
+
1450
+ """
1451
+
1452
+ def create_row_processor(
1453
+ self,
1454
+ context: ORMCompileState,
1455
+ query_entity: _MapperEntity,
1456
+ path: AbstractEntityRegistry,
1457
+ loadopt: Optional[_LoadElement],
1458
+ mapper: Mapper[Any],
1459
+ result: Result[Any],
1460
+ adapter: Optional[ORMAdapter],
1461
+ populators: _PopulatorDict,
1462
+ ) -> None:
1463
+ """Establish row processing functions for a given QueryContext.
1464
+
1465
+ This method fulfills the contract specified by
1466
+ MapperProperty.create_row_processor().
1467
+
1468
+ StrategizedProperty delegates its create_row_processor() method
1469
+ directly to this method.
1470
+
1471
+ """
1472
+
1473
+ def __str__(self) -> str:
1474
+ return str(self.parent_property)