SQLAlchemy 2.0.36__cp313-cp313-win_amd64.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-win_amd64.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win_amd64.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win_amd64.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,1076 @@
1
+ # orm/descriptor_props.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
+ """Descriptor properties are more "auxiliary" properties
9
+ that exist as configurational elements, but don't participate
10
+ as actively in the load/persist ORM loop.
11
+
12
+ """
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import is_dataclass
16
+ import inspect
17
+ import itertools
18
+ import operator
19
+ import typing
20
+ from typing import Any
21
+ from typing import Callable
22
+ from typing import Dict
23
+ from typing import List
24
+ from typing import NoReturn
25
+ from typing import Optional
26
+ from typing import Sequence
27
+ from typing import Tuple
28
+ from typing import Type
29
+ from typing import TYPE_CHECKING
30
+ from typing import TypeVar
31
+ from typing import Union
32
+ import weakref
33
+
34
+ from . import attributes
35
+ from . import util as orm_util
36
+ from .base import _DeclarativeMapped
37
+ from .base import LoaderCallableStatus
38
+ from .base import Mapped
39
+ from .base import PassiveFlag
40
+ from .base import SQLORMOperations
41
+ from .interfaces import _AttributeOptions
42
+ from .interfaces import _IntrospectsAnnotations
43
+ from .interfaces import _MapsColumns
44
+ from .interfaces import MapperProperty
45
+ from .interfaces import PropComparator
46
+ from .util import _none_set
47
+ from .util import de_stringify_annotation
48
+ from .. import event
49
+ from .. import exc as sa_exc
50
+ from .. import schema
51
+ from .. import sql
52
+ from .. import util
53
+ from ..sql import expression
54
+ from ..sql import operators
55
+ from ..sql.elements import BindParameter
56
+ from ..util.typing import is_fwd_ref
57
+ from ..util.typing import is_pep593
58
+ from ..util.typing import typing_get_args
59
+
60
+ if typing.TYPE_CHECKING:
61
+ from ._typing import _InstanceDict
62
+ from ._typing import _RegistryType
63
+ from .attributes import History
64
+ from .attributes import InstrumentedAttribute
65
+ from .attributes import QueryableAttribute
66
+ from .context import ORMCompileState
67
+ from .decl_base import _ClassScanMapperConfig
68
+ from .mapper import Mapper
69
+ from .properties import ColumnProperty
70
+ from .properties import MappedColumn
71
+ from .state import InstanceState
72
+ from ..engine.base import Connection
73
+ from ..engine.row import Row
74
+ from ..sql._typing import _DMLColumnArgument
75
+ from ..sql._typing import _InfoType
76
+ from ..sql.elements import ClauseList
77
+ from ..sql.elements import ColumnElement
78
+ from ..sql.operators import OperatorType
79
+ from ..sql.schema import Column
80
+ from ..sql.selectable import Select
81
+ from ..util.typing import _AnnotationScanType
82
+ from ..util.typing import CallableReference
83
+ from ..util.typing import DescriptorReference
84
+ from ..util.typing import RODescriptorReference
85
+
86
+ _T = TypeVar("_T", bound=Any)
87
+ _PT = TypeVar("_PT", bound=Any)
88
+
89
+
90
+ class DescriptorProperty(MapperProperty[_T]):
91
+ """:class:`.MapperProperty` which proxies access to a
92
+ user-defined descriptor."""
93
+
94
+ doc: Optional[str] = None
95
+
96
+ uses_objects = False
97
+ _links_to_entity = False
98
+
99
+ descriptor: DescriptorReference[Any]
100
+
101
+ def get_history(
102
+ self,
103
+ state: InstanceState[Any],
104
+ dict_: _InstanceDict,
105
+ passive: PassiveFlag = PassiveFlag.PASSIVE_OFF,
106
+ ) -> History:
107
+ raise NotImplementedError()
108
+
109
+ def instrument_class(self, mapper: Mapper[Any]) -> None:
110
+ prop = self
111
+
112
+ class _ProxyImpl(attributes.AttributeImpl):
113
+ accepts_scalar_loader = False
114
+ load_on_unexpire = True
115
+ collection = False
116
+
117
+ @property
118
+ def uses_objects(self) -> bool: # type: ignore
119
+ return prop.uses_objects
120
+
121
+ def __init__(self, key: str):
122
+ self.key = key
123
+
124
+ def get_history(
125
+ self,
126
+ state: InstanceState[Any],
127
+ dict_: _InstanceDict,
128
+ passive: PassiveFlag = PassiveFlag.PASSIVE_OFF,
129
+ ) -> History:
130
+ return prop.get_history(state, dict_, passive)
131
+
132
+ if self.descriptor is None:
133
+ desc = getattr(mapper.class_, self.key, None)
134
+ if mapper._is_userland_descriptor(self.key, desc):
135
+ self.descriptor = desc
136
+
137
+ if self.descriptor is None:
138
+
139
+ def fset(obj: Any, value: Any) -> None:
140
+ setattr(obj, self.name, value)
141
+
142
+ def fdel(obj: Any) -> None:
143
+ delattr(obj, self.name)
144
+
145
+ def fget(obj: Any) -> Any:
146
+ return getattr(obj, self.name)
147
+
148
+ self.descriptor = property(fget=fget, fset=fset, fdel=fdel)
149
+
150
+ proxy_attr = attributes.create_proxied_attribute(self.descriptor)(
151
+ self.parent.class_,
152
+ self.key,
153
+ self.descriptor,
154
+ lambda: self._comparator_factory(mapper),
155
+ doc=self.doc,
156
+ original_property=self,
157
+ )
158
+ proxy_attr.impl = _ProxyImpl(self.key)
159
+ mapper.class_manager.instrument_attribute(self.key, proxy_attr)
160
+
161
+
162
+ _CompositeAttrType = Union[
163
+ str,
164
+ "Column[_T]",
165
+ "MappedColumn[_T]",
166
+ "InstrumentedAttribute[_T]",
167
+ "Mapped[_T]",
168
+ ]
169
+
170
+
171
+ _CC = TypeVar("_CC", bound=Any)
172
+
173
+
174
+ _composite_getters: weakref.WeakKeyDictionary[
175
+ Type[Any], Callable[[Any], Tuple[Any, ...]]
176
+ ] = weakref.WeakKeyDictionary()
177
+
178
+
179
+ class CompositeProperty(
180
+ _MapsColumns[_CC], _IntrospectsAnnotations, DescriptorProperty[_CC]
181
+ ):
182
+ """Defines a "composite" mapped attribute, representing a collection
183
+ of columns as one attribute.
184
+
185
+ :class:`.CompositeProperty` is constructed using the :func:`.composite`
186
+ function.
187
+
188
+ .. seealso::
189
+
190
+ :ref:`mapper_composite`
191
+
192
+ """
193
+
194
+ composite_class: Union[Type[_CC], Callable[..., _CC]]
195
+ attrs: Tuple[_CompositeAttrType[Any], ...]
196
+
197
+ _generated_composite_accessor: CallableReference[
198
+ Optional[Callable[[_CC], Tuple[Any, ...]]]
199
+ ]
200
+
201
+ comparator_factory: Type[Comparator[_CC]]
202
+
203
+ def __init__(
204
+ self,
205
+ _class_or_attr: Union[
206
+ None, Type[_CC], Callable[..., _CC], _CompositeAttrType[Any]
207
+ ] = None,
208
+ *attrs: _CompositeAttrType[Any],
209
+ attribute_options: Optional[_AttributeOptions] = None,
210
+ active_history: bool = False,
211
+ deferred: bool = False,
212
+ group: Optional[str] = None,
213
+ comparator_factory: Optional[Type[Comparator[_CC]]] = None,
214
+ info: Optional[_InfoType] = None,
215
+ **kwargs: Any,
216
+ ):
217
+ super().__init__(attribute_options=attribute_options)
218
+
219
+ if isinstance(_class_or_attr, (Mapped, str, sql.ColumnElement)):
220
+ self.attrs = (_class_or_attr,) + attrs
221
+ # will initialize within declarative_scan
222
+ self.composite_class = None # type: ignore
223
+ else:
224
+ self.composite_class = _class_or_attr # type: ignore
225
+ self.attrs = attrs
226
+
227
+ self.active_history = active_history
228
+ self.deferred = deferred
229
+ self.group = group
230
+ self.comparator_factory = (
231
+ comparator_factory
232
+ if comparator_factory is not None
233
+ else self.__class__.Comparator
234
+ )
235
+ self._generated_composite_accessor = None
236
+ if info is not None:
237
+ self.info.update(info)
238
+
239
+ util.set_creation_order(self)
240
+ self._create_descriptor()
241
+ self._init_accessor()
242
+
243
+ def instrument_class(self, mapper: Mapper[Any]) -> None:
244
+ super().instrument_class(mapper)
245
+ self._setup_event_handlers()
246
+
247
+ def _composite_values_from_instance(self, value: _CC) -> Tuple[Any, ...]:
248
+ if self._generated_composite_accessor:
249
+ return self._generated_composite_accessor(value)
250
+ else:
251
+ try:
252
+ accessor = value.__composite_values__
253
+ except AttributeError as ae:
254
+ raise sa_exc.InvalidRequestError(
255
+ f"Composite class {self.composite_class.__name__} is not "
256
+ f"a dataclass and does not define a __composite_values__()"
257
+ " method; can't get state"
258
+ ) from ae
259
+ else:
260
+ return accessor() # type: ignore
261
+
262
+ def do_init(self) -> None:
263
+ """Initialization which occurs after the :class:`.Composite`
264
+ has been associated with its parent mapper.
265
+
266
+ """
267
+ self._setup_arguments_on_columns()
268
+
269
+ _COMPOSITE_FGET = object()
270
+
271
+ def _create_descriptor(self) -> None:
272
+ """Create the Python descriptor that will serve as
273
+ the access point on instances of the mapped class.
274
+
275
+ """
276
+
277
+ def fget(instance: Any) -> Any:
278
+ dict_ = attributes.instance_dict(instance)
279
+ state = attributes.instance_state(instance)
280
+
281
+ if self.key not in dict_:
282
+ # key not present. Iterate through related
283
+ # attributes, retrieve their values. This
284
+ # ensures they all load.
285
+ values = [
286
+ getattr(instance, key) for key in self._attribute_keys
287
+ ]
288
+
289
+ # current expected behavior here is that the composite is
290
+ # created on access if the object is persistent or if
291
+ # col attributes have non-None. This would be better
292
+ # if the composite were created unconditionally,
293
+ # but that would be a behavioral change.
294
+ if self.key not in dict_ and (
295
+ state.key is not None or not _none_set.issuperset(values)
296
+ ):
297
+ dict_[self.key] = self.composite_class(*values)
298
+ state.manager.dispatch.refresh(
299
+ state, self._COMPOSITE_FGET, [self.key]
300
+ )
301
+
302
+ return dict_.get(self.key, None)
303
+
304
+ def fset(instance: Any, value: Any) -> None:
305
+ dict_ = attributes.instance_dict(instance)
306
+ state = attributes.instance_state(instance)
307
+ attr = state.manager[self.key]
308
+
309
+ if attr.dispatch._active_history:
310
+ previous = fget(instance)
311
+ else:
312
+ previous = dict_.get(self.key, LoaderCallableStatus.NO_VALUE)
313
+
314
+ for fn in attr.dispatch.set:
315
+ value = fn(state, value, previous, attr.impl)
316
+ dict_[self.key] = value
317
+ if value is None:
318
+ for key in self._attribute_keys:
319
+ setattr(instance, key, None)
320
+ else:
321
+ for key, value in zip(
322
+ self._attribute_keys,
323
+ self._composite_values_from_instance(value),
324
+ ):
325
+ setattr(instance, key, value)
326
+
327
+ def fdel(instance: Any) -> None:
328
+ state = attributes.instance_state(instance)
329
+ dict_ = attributes.instance_dict(instance)
330
+ attr = state.manager[self.key]
331
+
332
+ if attr.dispatch._active_history:
333
+ previous = fget(instance)
334
+ dict_.pop(self.key, None)
335
+ else:
336
+ previous = dict_.pop(self.key, LoaderCallableStatus.NO_VALUE)
337
+
338
+ attr = state.manager[self.key]
339
+ attr.dispatch.remove(state, previous, attr.impl)
340
+ for key in self._attribute_keys:
341
+ setattr(instance, key, None)
342
+
343
+ self.descriptor = property(fget, fset, fdel)
344
+
345
+ @util.preload_module("sqlalchemy.orm.properties")
346
+ def declarative_scan(
347
+ self,
348
+ decl_scan: _ClassScanMapperConfig,
349
+ registry: _RegistryType,
350
+ cls: Type[Any],
351
+ originating_module: Optional[str],
352
+ key: str,
353
+ mapped_container: Optional[Type[Mapped[Any]]],
354
+ annotation: Optional[_AnnotationScanType],
355
+ extracted_mapped_annotation: Optional[_AnnotationScanType],
356
+ is_dataclass_field: bool,
357
+ ) -> None:
358
+ MappedColumn = util.preloaded.orm_properties.MappedColumn
359
+ if (
360
+ self.composite_class is None
361
+ and extracted_mapped_annotation is None
362
+ ):
363
+ self._raise_for_required(key, cls)
364
+ argument = extracted_mapped_annotation
365
+
366
+ if is_pep593(argument):
367
+ argument = typing_get_args(argument)[0]
368
+
369
+ if argument and self.composite_class is None:
370
+ if isinstance(argument, str) or is_fwd_ref(
371
+ argument, check_generic=True
372
+ ):
373
+ if originating_module is None:
374
+ str_arg = (
375
+ argument.__forward_arg__
376
+ if hasattr(argument, "__forward_arg__")
377
+ else str(argument)
378
+ )
379
+ raise sa_exc.ArgumentError(
380
+ f"Can't use forward ref {argument} for composite "
381
+ f"class argument; set up the type as Mapped[{str_arg}]"
382
+ )
383
+ argument = de_stringify_annotation(
384
+ cls, argument, originating_module, include_generic=True
385
+ )
386
+
387
+ self.composite_class = argument
388
+
389
+ if is_dataclass(self.composite_class):
390
+ self._setup_for_dataclass(registry, cls, originating_module, key)
391
+ else:
392
+ for attr in self.attrs:
393
+ if (
394
+ isinstance(attr, (MappedColumn, schema.Column))
395
+ and attr.name is None
396
+ ):
397
+ raise sa_exc.ArgumentError(
398
+ "Composite class column arguments must be named "
399
+ "unless a dataclass is used"
400
+ )
401
+ self._init_accessor()
402
+
403
+ def _init_accessor(self) -> None:
404
+ if is_dataclass(self.composite_class) and not hasattr(
405
+ self.composite_class, "__composite_values__"
406
+ ):
407
+ insp = inspect.signature(self.composite_class)
408
+ getter = operator.attrgetter(
409
+ *[p.name for p in insp.parameters.values()]
410
+ )
411
+ if len(insp.parameters) == 1:
412
+ self._generated_composite_accessor = lambda obj: (getter(obj),)
413
+ else:
414
+ self._generated_composite_accessor = getter
415
+
416
+ if (
417
+ self.composite_class is not None
418
+ and isinstance(self.composite_class, type)
419
+ and self.composite_class not in _composite_getters
420
+ ):
421
+ if self._generated_composite_accessor is not None:
422
+ _composite_getters[self.composite_class] = (
423
+ self._generated_composite_accessor
424
+ )
425
+ elif hasattr(self.composite_class, "__composite_values__"):
426
+ _composite_getters[self.composite_class] = (
427
+ lambda obj: obj.__composite_values__()
428
+ )
429
+
430
+ @util.preload_module("sqlalchemy.orm.properties")
431
+ @util.preload_module("sqlalchemy.orm.decl_base")
432
+ def _setup_for_dataclass(
433
+ self,
434
+ registry: _RegistryType,
435
+ cls: Type[Any],
436
+ originating_module: Optional[str],
437
+ key: str,
438
+ ) -> None:
439
+ MappedColumn = util.preloaded.orm_properties.MappedColumn
440
+
441
+ decl_base = util.preloaded.orm_decl_base
442
+
443
+ insp = inspect.signature(self.composite_class)
444
+ for param, attr in itertools.zip_longest(
445
+ insp.parameters.values(), self.attrs
446
+ ):
447
+ if param is None:
448
+ raise sa_exc.ArgumentError(
449
+ f"number of composite attributes "
450
+ f"{len(self.attrs)} exceeds "
451
+ f"that of the number of attributes in class "
452
+ f"{self.composite_class.__name__} {len(insp.parameters)}"
453
+ )
454
+ if attr is None:
455
+ # fill in missing attr spots with empty MappedColumn
456
+ attr = MappedColumn()
457
+ self.attrs += (attr,)
458
+
459
+ if isinstance(attr, MappedColumn):
460
+ attr.declarative_scan_for_composite(
461
+ registry,
462
+ cls,
463
+ originating_module,
464
+ key,
465
+ param.name,
466
+ param.annotation,
467
+ )
468
+ elif isinstance(attr, schema.Column):
469
+ decl_base._undefer_column_name(param.name, attr)
470
+
471
+ @util.memoized_property
472
+ def _comparable_elements(self) -> Sequence[QueryableAttribute[Any]]:
473
+ return [getattr(self.parent.class_, prop.key) for prop in self.props]
474
+
475
+ @util.memoized_property
476
+ @util.preload_module("orm.properties")
477
+ def props(self) -> Sequence[MapperProperty[Any]]:
478
+ props = []
479
+ MappedColumn = util.preloaded.orm_properties.MappedColumn
480
+
481
+ for attr in self.attrs:
482
+ if isinstance(attr, str):
483
+ prop = self.parent.get_property(attr, _configure_mappers=False)
484
+ elif isinstance(attr, schema.Column):
485
+ prop = self.parent._columntoproperty[attr]
486
+ elif isinstance(attr, MappedColumn):
487
+ prop = self.parent._columntoproperty[attr.column]
488
+ elif isinstance(attr, attributes.InstrumentedAttribute):
489
+ prop = attr.property
490
+ else:
491
+ prop = None
492
+
493
+ if not isinstance(prop, MapperProperty):
494
+ raise sa_exc.ArgumentError(
495
+ "Composite expects Column objects or mapped "
496
+ f"attributes/attribute names as arguments, got: {attr!r}"
497
+ )
498
+
499
+ props.append(prop)
500
+ return props
501
+
502
+ @util.non_memoized_property
503
+ @util.preload_module("orm.properties")
504
+ def columns(self) -> Sequence[Column[Any]]:
505
+ MappedColumn = util.preloaded.orm_properties.MappedColumn
506
+ return [
507
+ a.column if isinstance(a, MappedColumn) else a
508
+ for a in self.attrs
509
+ if isinstance(a, (schema.Column, MappedColumn))
510
+ ]
511
+
512
+ @property
513
+ def mapper_property_to_assign(self) -> Optional[MapperProperty[_CC]]:
514
+ return self
515
+
516
+ @property
517
+ def columns_to_assign(self) -> List[Tuple[schema.Column[Any], int]]:
518
+ return [(c, 0) for c in self.columns if c.table is None]
519
+
520
+ @util.preload_module("orm.properties")
521
+ def _setup_arguments_on_columns(self) -> None:
522
+ """Propagate configuration arguments made on this composite
523
+ to the target columns, for those that apply.
524
+
525
+ """
526
+ ColumnProperty = util.preloaded.orm_properties.ColumnProperty
527
+
528
+ for prop in self.props:
529
+ if not isinstance(prop, ColumnProperty):
530
+ continue
531
+ else:
532
+ cprop = prop
533
+
534
+ cprop.active_history = self.active_history
535
+ if self.deferred:
536
+ cprop.deferred = self.deferred
537
+ cprop.strategy_key = (("deferred", True), ("instrument", True))
538
+ cprop.group = self.group
539
+
540
+ def _setup_event_handlers(self) -> None:
541
+ """Establish events that populate/expire the composite attribute."""
542
+
543
+ def load_handler(
544
+ state: InstanceState[Any], context: ORMCompileState
545
+ ) -> None:
546
+ _load_refresh_handler(state, context, None, is_refresh=False)
547
+
548
+ def refresh_handler(
549
+ state: InstanceState[Any],
550
+ context: ORMCompileState,
551
+ to_load: Optional[Sequence[str]],
552
+ ) -> None:
553
+ # note this corresponds to sqlalchemy.ext.mutable load_attrs()
554
+
555
+ if not to_load or (
556
+ {self.key}.union(self._attribute_keys)
557
+ ).intersection(to_load):
558
+ _load_refresh_handler(state, context, to_load, is_refresh=True)
559
+
560
+ def _load_refresh_handler(
561
+ state: InstanceState[Any],
562
+ context: ORMCompileState,
563
+ to_load: Optional[Sequence[str]],
564
+ is_refresh: bool,
565
+ ) -> None:
566
+ dict_ = state.dict
567
+
568
+ # if context indicates we are coming from the
569
+ # fget() handler, this already set the value; skip the
570
+ # handler here. (other handlers like mutablecomposite will still
571
+ # want to catch it)
572
+ # there's an insufficiency here in that the fget() handler
573
+ # really should not be using the refresh event and there should
574
+ # be some other event that mutablecomposite can subscribe
575
+ # towards for this.
576
+
577
+ if (
578
+ not is_refresh or context is self._COMPOSITE_FGET
579
+ ) and self.key in dict_:
580
+ return
581
+
582
+ # if column elements aren't loaded, skip.
583
+ # __get__() will initiate a load for those
584
+ # columns
585
+ for k in self._attribute_keys:
586
+ if k not in dict_:
587
+ return
588
+
589
+ dict_[self.key] = self.composite_class(
590
+ *[state.dict[key] for key in self._attribute_keys]
591
+ )
592
+
593
+ def expire_handler(
594
+ state: InstanceState[Any], keys: Optional[Sequence[str]]
595
+ ) -> None:
596
+ if keys is None or set(self._attribute_keys).intersection(keys):
597
+ state.dict.pop(self.key, None)
598
+
599
+ def insert_update_handler(
600
+ mapper: Mapper[Any],
601
+ connection: Connection,
602
+ state: InstanceState[Any],
603
+ ) -> None:
604
+ """After an insert or update, some columns may be expired due
605
+ to server side defaults, or re-populated due to client side
606
+ defaults. Pop out the composite value here so that it
607
+ recreates.
608
+
609
+ """
610
+
611
+ state.dict.pop(self.key, None)
612
+
613
+ event.listen(
614
+ self.parent, "after_insert", insert_update_handler, raw=True
615
+ )
616
+ event.listen(
617
+ self.parent, "after_update", insert_update_handler, raw=True
618
+ )
619
+ event.listen(
620
+ self.parent, "load", load_handler, raw=True, propagate=True
621
+ )
622
+ event.listen(
623
+ self.parent, "refresh", refresh_handler, raw=True, propagate=True
624
+ )
625
+ event.listen(
626
+ self.parent, "expire", expire_handler, raw=True, propagate=True
627
+ )
628
+
629
+ proxy_attr = self.parent.class_manager[self.key]
630
+ proxy_attr.impl.dispatch = proxy_attr.dispatch # type: ignore
631
+ proxy_attr.impl.dispatch._active_history = self.active_history
632
+
633
+ # TODO: need a deserialize hook here
634
+
635
+ @util.memoized_property
636
+ def _attribute_keys(self) -> Sequence[str]:
637
+ return [prop.key for prop in self.props]
638
+
639
+ def _populate_composite_bulk_save_mappings_fn(
640
+ self,
641
+ ) -> Callable[[Dict[str, Any]], None]:
642
+ if self._generated_composite_accessor:
643
+ get_values = self._generated_composite_accessor
644
+ else:
645
+
646
+ def get_values(val: Any) -> Tuple[Any]:
647
+ return val.__composite_values__() # type: ignore
648
+
649
+ attrs = [prop.key for prop in self.props]
650
+
651
+ def populate(dest_dict: Dict[str, Any]) -> None:
652
+ dest_dict.update(
653
+ {
654
+ key: val
655
+ for key, val in zip(
656
+ attrs, get_values(dest_dict.pop(self.key))
657
+ )
658
+ }
659
+ )
660
+
661
+ return populate
662
+
663
+ def get_history(
664
+ self,
665
+ state: InstanceState[Any],
666
+ dict_: _InstanceDict,
667
+ passive: PassiveFlag = PassiveFlag.PASSIVE_OFF,
668
+ ) -> History:
669
+ """Provided for userland code that uses attributes.get_history()."""
670
+
671
+ added: List[Any] = []
672
+ deleted: List[Any] = []
673
+
674
+ has_history = False
675
+ for prop in self.props:
676
+ key = prop.key
677
+ hist = state.manager[key].impl.get_history(state, dict_)
678
+ if hist.has_changes():
679
+ has_history = True
680
+
681
+ non_deleted = hist.non_deleted()
682
+ if non_deleted:
683
+ added.extend(non_deleted)
684
+ else:
685
+ added.append(None)
686
+ if hist.deleted:
687
+ deleted.extend(hist.deleted)
688
+ else:
689
+ deleted.append(None)
690
+
691
+ if has_history:
692
+ return attributes.History(
693
+ [self.composite_class(*added)],
694
+ (),
695
+ [self.composite_class(*deleted)],
696
+ )
697
+ else:
698
+ return attributes.History((), [self.composite_class(*added)], ())
699
+
700
+ def _comparator_factory(
701
+ self, mapper: Mapper[Any]
702
+ ) -> Composite.Comparator[_CC]:
703
+ return self.comparator_factory(self, mapper)
704
+
705
+ class CompositeBundle(orm_util.Bundle[_T]):
706
+ def __init__(
707
+ self,
708
+ property_: Composite[_T],
709
+ expr: ClauseList,
710
+ ):
711
+ self.property = property_
712
+ super().__init__(property_.key, *expr)
713
+
714
+ def create_row_processor(
715
+ self,
716
+ query: Select[Any],
717
+ procs: Sequence[Callable[[Row[Any]], Any]],
718
+ labels: Sequence[str],
719
+ ) -> Callable[[Row[Any]], Any]:
720
+ def proc(row: Row[Any]) -> Any:
721
+ return self.property.composite_class(
722
+ *[proc(row) for proc in procs]
723
+ )
724
+
725
+ return proc
726
+
727
+ class Comparator(PropComparator[_PT]):
728
+ """Produce boolean, comparison, and other operators for
729
+ :class:`.Composite` attributes.
730
+
731
+ See the example in :ref:`composite_operations` for an overview
732
+ of usage , as well as the documentation for :class:`.PropComparator`.
733
+
734
+ .. seealso::
735
+
736
+ :class:`.PropComparator`
737
+
738
+ :class:`.ColumnOperators`
739
+
740
+ :ref:`types_operators`
741
+
742
+ :attr:`.TypeEngine.comparator_factory`
743
+
744
+ """
745
+
746
+ # https://github.com/python/mypy/issues/4266
747
+ __hash__ = None # type: ignore
748
+
749
+ prop: RODescriptorReference[Composite[_PT]]
750
+
751
+ @util.memoized_property
752
+ def clauses(self) -> ClauseList:
753
+ return expression.ClauseList(
754
+ group=False, *self._comparable_elements
755
+ )
756
+
757
+ def __clause_element__(self) -> CompositeProperty.CompositeBundle[_PT]:
758
+ return self.expression
759
+
760
+ @util.memoized_property
761
+ def expression(self) -> CompositeProperty.CompositeBundle[_PT]:
762
+ clauses = self.clauses._annotate(
763
+ {
764
+ "parententity": self._parententity,
765
+ "parentmapper": self._parententity,
766
+ "proxy_key": self.prop.key,
767
+ }
768
+ )
769
+ return CompositeProperty.CompositeBundle(self.prop, clauses)
770
+
771
+ def _bulk_update_tuples(
772
+ self, value: Any
773
+ ) -> Sequence[Tuple[_DMLColumnArgument, Any]]:
774
+ if isinstance(value, BindParameter):
775
+ value = value.value
776
+
777
+ values: Sequence[Any]
778
+
779
+ if value is None:
780
+ values = [None for key in self.prop._attribute_keys]
781
+ elif isinstance(self.prop.composite_class, type) and isinstance(
782
+ value, self.prop.composite_class
783
+ ):
784
+ values = self.prop._composite_values_from_instance(
785
+ value # type: ignore[arg-type]
786
+ )
787
+ else:
788
+ raise sa_exc.ArgumentError(
789
+ "Can't UPDATE composite attribute %s to %r"
790
+ % (self.prop, value)
791
+ )
792
+
793
+ return list(zip(self._comparable_elements, values))
794
+
795
+ @util.memoized_property
796
+ def _comparable_elements(self) -> Sequence[QueryableAttribute[Any]]:
797
+ if self._adapt_to_entity:
798
+ return [
799
+ getattr(self._adapt_to_entity.entity, prop.key)
800
+ for prop in self.prop._comparable_elements
801
+ ]
802
+ else:
803
+ return self.prop._comparable_elements
804
+
805
+ def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
806
+ return self._compare(operators.eq, other)
807
+
808
+ def __ne__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
809
+ return self._compare(operators.ne, other)
810
+
811
+ def __lt__(self, other: Any) -> ColumnElement[bool]:
812
+ return self._compare(operators.lt, other)
813
+
814
+ def __gt__(self, other: Any) -> ColumnElement[bool]:
815
+ return self._compare(operators.gt, other)
816
+
817
+ def __le__(self, other: Any) -> ColumnElement[bool]:
818
+ return self._compare(operators.le, other)
819
+
820
+ def __ge__(self, other: Any) -> ColumnElement[bool]:
821
+ return self._compare(operators.ge, other)
822
+
823
+ # what might be interesting would be if we create
824
+ # an instance of the composite class itself with
825
+ # the columns as data members, then use "hybrid style" comparison
826
+ # to create these comparisons. then your Point.__eq__() method could
827
+ # be where comparison behavior is defined for SQL also. Likely
828
+ # not a good choice for default behavior though, not clear how it would
829
+ # work w/ dataclasses, etc. also no demand for any of this anyway.
830
+ def _compare(
831
+ self, operator: OperatorType, other: Any
832
+ ) -> ColumnElement[bool]:
833
+ values: Sequence[Any]
834
+ if other is None:
835
+ values = [None] * len(self.prop._comparable_elements)
836
+ else:
837
+ values = self.prop._composite_values_from_instance(other)
838
+ comparisons = [
839
+ operator(a, b)
840
+ for a, b in zip(self.prop._comparable_elements, values)
841
+ ]
842
+ if self._adapt_to_entity:
843
+ assert self.adapter is not None
844
+ comparisons = [self.adapter(x) for x in comparisons]
845
+ return sql.and_(*comparisons)
846
+
847
+ def __str__(self) -> str:
848
+ return str(self.parent.class_.__name__) + "." + self.key
849
+
850
+
851
+ class Composite(CompositeProperty[_T], _DeclarativeMapped[_T]):
852
+ """Declarative-compatible front-end for the :class:`.CompositeProperty`
853
+ class.
854
+
855
+ Public constructor is the :func:`_orm.composite` function.
856
+
857
+ .. versionchanged:: 2.0 Added :class:`_orm.Composite` as a Declarative
858
+ compatible subclass of :class:`_orm.CompositeProperty`.
859
+
860
+ .. seealso::
861
+
862
+ :ref:`mapper_composite`
863
+
864
+ """
865
+
866
+ inherit_cache = True
867
+ """:meta private:"""
868
+
869
+
870
+ class ConcreteInheritedProperty(DescriptorProperty[_T]):
871
+ """A 'do nothing' :class:`.MapperProperty` that disables
872
+ an attribute on a concrete subclass that is only present
873
+ on the inherited mapper, not the concrete classes' mapper.
874
+
875
+ Cases where this occurs include:
876
+
877
+ * When the superclass mapper is mapped against a
878
+ "polymorphic union", which includes all attributes from
879
+ all subclasses.
880
+ * When a relationship() is configured on an inherited mapper,
881
+ but not on the subclass mapper. Concrete mappers require
882
+ that relationship() is configured explicitly on each
883
+ subclass.
884
+
885
+ """
886
+
887
+ def _comparator_factory(
888
+ self, mapper: Mapper[Any]
889
+ ) -> Type[PropComparator[_T]]:
890
+ comparator_callable = None
891
+
892
+ for m in self.parent.iterate_to_root():
893
+ p = m._props[self.key]
894
+ if getattr(p, "comparator_factory", None) is not None:
895
+ comparator_callable = p.comparator_factory
896
+ break
897
+ assert comparator_callable is not None
898
+ return comparator_callable(p, mapper) # type: ignore
899
+
900
+ def __init__(self) -> None:
901
+ super().__init__()
902
+
903
+ def warn() -> NoReturn:
904
+ raise AttributeError(
905
+ "Concrete %s does not implement "
906
+ "attribute %r at the instance level. Add "
907
+ "this property explicitly to %s."
908
+ % (self.parent, self.key, self.parent)
909
+ )
910
+
911
+ class NoninheritedConcreteProp:
912
+ def __set__(s: Any, obj: Any, value: Any) -> NoReturn:
913
+ warn()
914
+
915
+ def __delete__(s: Any, obj: Any) -> NoReturn:
916
+ warn()
917
+
918
+ def __get__(s: Any, obj: Any, owner: Any) -> Any:
919
+ if obj is None:
920
+ return self.descriptor
921
+ warn()
922
+
923
+ self.descriptor = NoninheritedConcreteProp()
924
+
925
+
926
+ class SynonymProperty(DescriptorProperty[_T]):
927
+ """Denote an attribute name as a synonym to a mapped property,
928
+ in that the attribute will mirror the value and expression behavior
929
+ of another attribute.
930
+
931
+ :class:`.Synonym` is constructed using the :func:`_orm.synonym`
932
+ function.
933
+
934
+ .. seealso::
935
+
936
+ :ref:`synonyms` - Overview of synonyms
937
+
938
+ """
939
+
940
+ comparator_factory: Optional[Type[PropComparator[_T]]]
941
+
942
+ def __init__(
943
+ self,
944
+ name: str,
945
+ map_column: Optional[bool] = None,
946
+ descriptor: Optional[Any] = None,
947
+ comparator_factory: Optional[Type[PropComparator[_T]]] = None,
948
+ attribute_options: Optional[_AttributeOptions] = None,
949
+ info: Optional[_InfoType] = None,
950
+ doc: Optional[str] = None,
951
+ ):
952
+ super().__init__(attribute_options=attribute_options)
953
+
954
+ self.name = name
955
+ self.map_column = map_column
956
+ self.descriptor = descriptor
957
+ self.comparator_factory = comparator_factory
958
+ if doc:
959
+ self.doc = doc
960
+ elif descriptor and descriptor.__doc__:
961
+ self.doc = descriptor.__doc__
962
+ else:
963
+ self.doc = None
964
+ if info:
965
+ self.info.update(info)
966
+
967
+ util.set_creation_order(self)
968
+
969
+ if not TYPE_CHECKING:
970
+
971
+ @property
972
+ def uses_objects(self) -> bool:
973
+ return getattr(self.parent.class_, self.name).impl.uses_objects
974
+
975
+ # TODO: when initialized, check _proxied_object,
976
+ # emit a warning if its not a column-based property
977
+
978
+ @util.memoized_property
979
+ def _proxied_object(
980
+ self,
981
+ ) -> Union[MapperProperty[_T], SQLORMOperations[_T]]:
982
+ attr = getattr(self.parent.class_, self.name)
983
+ if not hasattr(attr, "property") or not isinstance(
984
+ attr.property, MapperProperty
985
+ ):
986
+ # attribute is a non-MapperProprerty proxy such as
987
+ # hybrid or association proxy
988
+ if isinstance(attr, attributes.QueryableAttribute):
989
+ return attr.comparator
990
+ elif isinstance(attr, SQLORMOperations):
991
+ # assocaition proxy comes here
992
+ return attr
993
+
994
+ raise sa_exc.InvalidRequestError(
995
+ """synonym() attribute "%s.%s" only supports """
996
+ """ORM mapped attributes, got %r"""
997
+ % (self.parent.class_.__name__, self.name, attr)
998
+ )
999
+ return attr.property
1000
+
1001
+ def _comparator_factory(self, mapper: Mapper[Any]) -> SQLORMOperations[_T]:
1002
+ prop = self._proxied_object
1003
+
1004
+ if isinstance(prop, MapperProperty):
1005
+ if self.comparator_factory:
1006
+ comp = self.comparator_factory(prop, mapper)
1007
+ else:
1008
+ comp = prop.comparator_factory(prop, mapper)
1009
+ return comp
1010
+ else:
1011
+ return prop
1012
+
1013
+ def get_history(
1014
+ self,
1015
+ state: InstanceState[Any],
1016
+ dict_: _InstanceDict,
1017
+ passive: PassiveFlag = PassiveFlag.PASSIVE_OFF,
1018
+ ) -> History:
1019
+ attr: QueryableAttribute[Any] = getattr(self.parent.class_, self.name)
1020
+ return attr.impl.get_history(state, dict_, passive=passive)
1021
+
1022
+ @util.preload_module("sqlalchemy.orm.properties")
1023
+ def set_parent(self, parent: Mapper[Any], init: bool) -> None:
1024
+ properties = util.preloaded.orm_properties
1025
+
1026
+ if self.map_column:
1027
+ # implement the 'map_column' option.
1028
+ if self.key not in parent.persist_selectable.c:
1029
+ raise sa_exc.ArgumentError(
1030
+ "Can't compile synonym '%s': no column on table "
1031
+ "'%s' named '%s'"
1032
+ % (
1033
+ self.name,
1034
+ parent.persist_selectable.description,
1035
+ self.key,
1036
+ )
1037
+ )
1038
+ elif (
1039
+ parent.persist_selectable.c[self.key]
1040
+ in parent._columntoproperty
1041
+ and parent._columntoproperty[
1042
+ parent.persist_selectable.c[self.key]
1043
+ ].key
1044
+ == self.name
1045
+ ):
1046
+ raise sa_exc.ArgumentError(
1047
+ "Can't call map_column=True for synonym %r=%r, "
1048
+ "a ColumnProperty already exists keyed to the name "
1049
+ "%r for column %r"
1050
+ % (self.key, self.name, self.name, self.key)
1051
+ )
1052
+ p: ColumnProperty[Any] = properties.ColumnProperty(
1053
+ parent.persist_selectable.c[self.key]
1054
+ )
1055
+ parent._configure_property(self.name, p, init=init, setparent=True)
1056
+ p._mapped_by_synonym = self.key
1057
+
1058
+ self.parent = parent
1059
+
1060
+
1061
+ class Synonym(SynonymProperty[_T], _DeclarativeMapped[_T]):
1062
+ """Declarative front-end for the :class:`.SynonymProperty` class.
1063
+
1064
+ Public constructor is the :func:`_orm.synonym` function.
1065
+
1066
+ .. versionchanged:: 2.0 Added :class:`_orm.Synonym` as a Declarative
1067
+ compatible subclass for :class:`_orm.SynonymProperty`
1068
+
1069
+ .. seealso::
1070
+
1071
+ :ref:`synonyms` - Overview of synonyms
1072
+
1073
+ """
1074
+
1075
+ inherit_cache = True
1076
+ """:meta private:"""