SQLAlchemy 2.0.47__cp313-cp313t-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 (274) hide show
  1. sqlalchemy/__init__.py +283 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +184 -0
  4. sqlalchemy/connectors/asyncio.py +429 -0
  5. sqlalchemy/connectors/pyodbc.py +250 -0
  6. sqlalchemy/cyextension/__init__.py +6 -0
  7. sqlalchemy/cyextension/collections.cp313t-win32.pyd +0 -0
  8. sqlalchemy/cyextension/collections.pyx +409 -0
  9. sqlalchemy/cyextension/immutabledict.cp313t-win32.pyd +0 -0
  10. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  11. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  12. sqlalchemy/cyextension/processors.cp313t-win32.pyd +0 -0
  13. sqlalchemy/cyextension/processors.pyx +68 -0
  14. sqlalchemy/cyextension/resultproxy.cp313t-win32.pyd +0 -0
  15. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  16. sqlalchemy/cyextension/util.cp313t-win32.pyd +0 -0
  17. sqlalchemy/cyextension/util.pyx +90 -0
  18. sqlalchemy/dialects/__init__.py +62 -0
  19. sqlalchemy/dialects/_typing.py +30 -0
  20. sqlalchemy/dialects/mssql/__init__.py +88 -0
  21. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  22. sqlalchemy/dialects/mssql/base.py +4093 -0
  23. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  24. sqlalchemy/dialects/mssql/json.py +129 -0
  25. sqlalchemy/dialects/mssql/provision.py +185 -0
  26. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  27. sqlalchemy/dialects/mssql/pyodbc.py +760 -0
  28. sqlalchemy/dialects/mysql/__init__.py +104 -0
  29. sqlalchemy/dialects/mysql/aiomysql.py +250 -0
  30. sqlalchemy/dialects/mysql/asyncmy.py +231 -0
  31. sqlalchemy/dialects/mysql/base.py +3949 -0
  32. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  33. sqlalchemy/dialects/mysql/dml.py +225 -0
  34. sqlalchemy/dialects/mysql/enumerated.py +282 -0
  35. sqlalchemy/dialects/mysql/expression.py +146 -0
  36. sqlalchemy/dialects/mysql/json.py +91 -0
  37. sqlalchemy/dialects/mysql/mariadb.py +72 -0
  38. sqlalchemy/dialects/mysql/mariadbconnector.py +322 -0
  39. sqlalchemy/dialects/mysql/mysqlconnector.py +302 -0
  40. sqlalchemy/dialects/mysql/mysqldb.py +314 -0
  41. sqlalchemy/dialects/mysql/provision.py +153 -0
  42. sqlalchemy/dialects/mysql/pymysql.py +158 -0
  43. sqlalchemy/dialects/mysql/pyodbc.py +157 -0
  44. sqlalchemy/dialects/mysql/reflection.py +727 -0
  45. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  46. sqlalchemy/dialects/mysql/types.py +835 -0
  47. sqlalchemy/dialects/oracle/__init__.py +81 -0
  48. sqlalchemy/dialects/oracle/base.py +3802 -0
  49. sqlalchemy/dialects/oracle/cx_oracle.py +1555 -0
  50. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  51. sqlalchemy/dialects/oracle/oracledb.py +941 -0
  52. sqlalchemy/dialects/oracle/provision.py +297 -0
  53. sqlalchemy/dialects/oracle/types.py +316 -0
  54. sqlalchemy/dialects/oracle/vector.py +365 -0
  55. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  56. sqlalchemy/dialects/postgresql/_psycopg_common.py +189 -0
  57. sqlalchemy/dialects/postgresql/array.py +519 -0
  58. sqlalchemy/dialects/postgresql/asyncpg.py +1284 -0
  59. sqlalchemy/dialects/postgresql/base.py +5378 -0
  60. sqlalchemy/dialects/postgresql/dml.py +339 -0
  61. sqlalchemy/dialects/postgresql/ext.py +540 -0
  62. sqlalchemy/dialects/postgresql/hstore.py +406 -0
  63. sqlalchemy/dialects/postgresql/json.py +404 -0
  64. sqlalchemy/dialects/postgresql/named_types.py +524 -0
  65. sqlalchemy/dialects/postgresql/operators.py +129 -0
  66. sqlalchemy/dialects/postgresql/pg8000.py +669 -0
  67. sqlalchemy/dialects/postgresql/pg_catalog.py +326 -0
  68. sqlalchemy/dialects/postgresql/provision.py +183 -0
  69. sqlalchemy/dialects/postgresql/psycopg.py +862 -0
  70. sqlalchemy/dialects/postgresql/psycopg2.py +892 -0
  71. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  72. sqlalchemy/dialects/postgresql/ranges.py +1031 -0
  73. sqlalchemy/dialects/postgresql/types.py +313 -0
  74. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  75. sqlalchemy/dialects/sqlite/aiosqlite.py +482 -0
  76. sqlalchemy/dialects/sqlite/base.py +3056 -0
  77. sqlalchemy/dialects/sqlite/dml.py +263 -0
  78. sqlalchemy/dialects/sqlite/json.py +92 -0
  79. sqlalchemy/dialects/sqlite/provision.py +229 -0
  80. sqlalchemy/dialects/sqlite/pysqlcipher.py +157 -0
  81. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  82. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  83. sqlalchemy/engine/__init__.py +62 -0
  84. sqlalchemy/engine/_py_processors.py +136 -0
  85. sqlalchemy/engine/_py_row.py +128 -0
  86. sqlalchemy/engine/_py_util.py +74 -0
  87. sqlalchemy/engine/base.py +3390 -0
  88. sqlalchemy/engine/characteristics.py +155 -0
  89. sqlalchemy/engine/create.py +893 -0
  90. sqlalchemy/engine/cursor.py +2298 -0
  91. sqlalchemy/engine/default.py +2394 -0
  92. sqlalchemy/engine/events.py +965 -0
  93. sqlalchemy/engine/interfaces.py +3471 -0
  94. sqlalchemy/engine/mock.py +134 -0
  95. sqlalchemy/engine/processors.py +61 -0
  96. sqlalchemy/engine/reflection.py +2102 -0
  97. sqlalchemy/engine/result.py +2399 -0
  98. sqlalchemy/engine/row.py +400 -0
  99. sqlalchemy/engine/strategies.py +16 -0
  100. sqlalchemy/engine/url.py +924 -0
  101. sqlalchemy/engine/util.py +167 -0
  102. sqlalchemy/event/__init__.py +26 -0
  103. sqlalchemy/event/api.py +220 -0
  104. sqlalchemy/event/attr.py +676 -0
  105. sqlalchemy/event/base.py +472 -0
  106. sqlalchemy/event/legacy.py +258 -0
  107. sqlalchemy/event/registry.py +390 -0
  108. sqlalchemy/events.py +17 -0
  109. sqlalchemy/exc.py +832 -0
  110. sqlalchemy/ext/__init__.py +11 -0
  111. sqlalchemy/ext/associationproxy.py +2027 -0
  112. sqlalchemy/ext/asyncio/__init__.py +25 -0
  113. sqlalchemy/ext/asyncio/base.py +281 -0
  114. sqlalchemy/ext/asyncio/engine.py +1471 -0
  115. sqlalchemy/ext/asyncio/exc.py +21 -0
  116. sqlalchemy/ext/asyncio/result.py +965 -0
  117. sqlalchemy/ext/asyncio/scoping.py +1599 -0
  118. sqlalchemy/ext/asyncio/session.py +1947 -0
  119. sqlalchemy/ext/automap.py +1701 -0
  120. sqlalchemy/ext/baked.py +570 -0
  121. sqlalchemy/ext/compiler.py +600 -0
  122. sqlalchemy/ext/declarative/__init__.py +65 -0
  123. sqlalchemy/ext/declarative/extensions.py +564 -0
  124. sqlalchemy/ext/horizontal_shard.py +478 -0
  125. sqlalchemy/ext/hybrid.py +1535 -0
  126. sqlalchemy/ext/indexable.py +364 -0
  127. sqlalchemy/ext/instrumentation.py +450 -0
  128. sqlalchemy/ext/mutable.py +1085 -0
  129. sqlalchemy/ext/mypy/__init__.py +6 -0
  130. sqlalchemy/ext/mypy/apply.py +324 -0
  131. sqlalchemy/ext/mypy/decl_class.py +515 -0
  132. sqlalchemy/ext/mypy/infer.py +590 -0
  133. sqlalchemy/ext/mypy/names.py +335 -0
  134. sqlalchemy/ext/mypy/plugin.py +303 -0
  135. sqlalchemy/ext/mypy/util.py +357 -0
  136. sqlalchemy/ext/orderinglist.py +439 -0
  137. sqlalchemy/ext/serializer.py +185 -0
  138. sqlalchemy/future/__init__.py +16 -0
  139. sqlalchemy/future/engine.py +15 -0
  140. sqlalchemy/inspection.py +174 -0
  141. sqlalchemy/log.py +288 -0
  142. sqlalchemy/orm/__init__.py +171 -0
  143. sqlalchemy/orm/_orm_constructors.py +2661 -0
  144. sqlalchemy/orm/_typing.py +179 -0
  145. sqlalchemy/orm/attributes.py +2845 -0
  146. sqlalchemy/orm/base.py +971 -0
  147. sqlalchemy/orm/bulk_persistence.py +2135 -0
  148. sqlalchemy/orm/clsregistry.py +571 -0
  149. sqlalchemy/orm/collections.py +1627 -0
  150. sqlalchemy/orm/context.py +3334 -0
  151. sqlalchemy/orm/decl_api.py +2004 -0
  152. sqlalchemy/orm/decl_base.py +2192 -0
  153. sqlalchemy/orm/dependency.py +1302 -0
  154. sqlalchemy/orm/descriptor_props.py +1092 -0
  155. sqlalchemy/orm/dynamic.py +300 -0
  156. sqlalchemy/orm/evaluator.py +379 -0
  157. sqlalchemy/orm/events.py +3252 -0
  158. sqlalchemy/orm/exc.py +237 -0
  159. sqlalchemy/orm/identity.py +302 -0
  160. sqlalchemy/orm/instrumentation.py +754 -0
  161. sqlalchemy/orm/interfaces.py +1496 -0
  162. sqlalchemy/orm/loading.py +1686 -0
  163. sqlalchemy/orm/mapped_collection.py +557 -0
  164. sqlalchemy/orm/mapper.py +4444 -0
  165. sqlalchemy/orm/path_registry.py +809 -0
  166. sqlalchemy/orm/persistence.py +1788 -0
  167. sqlalchemy/orm/properties.py +935 -0
  168. sqlalchemy/orm/query.py +3459 -0
  169. sqlalchemy/orm/relationships.py +3508 -0
  170. sqlalchemy/orm/scoping.py +2148 -0
  171. sqlalchemy/orm/session.py +5280 -0
  172. sqlalchemy/orm/state.py +1168 -0
  173. sqlalchemy/orm/state_changes.py +196 -0
  174. sqlalchemy/orm/strategies.py +3470 -0
  175. sqlalchemy/orm/strategy_options.py +2568 -0
  176. sqlalchemy/orm/sync.py +164 -0
  177. sqlalchemy/orm/unitofwork.py +796 -0
  178. sqlalchemy/orm/util.py +2403 -0
  179. sqlalchemy/orm/writeonly.py +674 -0
  180. sqlalchemy/pool/__init__.py +44 -0
  181. sqlalchemy/pool/base.py +1524 -0
  182. sqlalchemy/pool/events.py +375 -0
  183. sqlalchemy/pool/impl.py +588 -0
  184. sqlalchemy/py.typed +0 -0
  185. sqlalchemy/schema.py +69 -0
  186. sqlalchemy/sql/__init__.py +145 -0
  187. sqlalchemy/sql/_dml_constructors.py +132 -0
  188. sqlalchemy/sql/_elements_constructors.py +1872 -0
  189. sqlalchemy/sql/_orm_types.py +20 -0
  190. sqlalchemy/sql/_py_util.py +75 -0
  191. sqlalchemy/sql/_selectable_constructors.py +763 -0
  192. sqlalchemy/sql/_typing.py +482 -0
  193. sqlalchemy/sql/annotation.py +587 -0
  194. sqlalchemy/sql/base.py +2293 -0
  195. sqlalchemy/sql/cache_key.py +1057 -0
  196. sqlalchemy/sql/coercions.py +1404 -0
  197. sqlalchemy/sql/compiler.py +8081 -0
  198. sqlalchemy/sql/crud.py +1752 -0
  199. sqlalchemy/sql/ddl.py +1444 -0
  200. sqlalchemy/sql/default_comparator.py +551 -0
  201. sqlalchemy/sql/dml.py +1850 -0
  202. sqlalchemy/sql/elements.py +5589 -0
  203. sqlalchemy/sql/events.py +458 -0
  204. sqlalchemy/sql/expression.py +159 -0
  205. sqlalchemy/sql/functions.py +2158 -0
  206. sqlalchemy/sql/lambdas.py +1442 -0
  207. sqlalchemy/sql/naming.py +209 -0
  208. sqlalchemy/sql/operators.py +2623 -0
  209. sqlalchemy/sql/roles.py +323 -0
  210. sqlalchemy/sql/schema.py +6222 -0
  211. sqlalchemy/sql/selectable.py +7265 -0
  212. sqlalchemy/sql/sqltypes.py +3930 -0
  213. sqlalchemy/sql/traversals.py +1024 -0
  214. sqlalchemy/sql/type_api.py +2368 -0
  215. sqlalchemy/sql/util.py +1485 -0
  216. sqlalchemy/sql/visitors.py +1164 -0
  217. sqlalchemy/testing/__init__.py +96 -0
  218. sqlalchemy/testing/assertions.py +994 -0
  219. sqlalchemy/testing/assertsql.py +520 -0
  220. sqlalchemy/testing/asyncio.py +135 -0
  221. sqlalchemy/testing/config.py +434 -0
  222. sqlalchemy/testing/engines.py +483 -0
  223. sqlalchemy/testing/entities.py +117 -0
  224. sqlalchemy/testing/exclusions.py +476 -0
  225. sqlalchemy/testing/fixtures/__init__.py +28 -0
  226. sqlalchemy/testing/fixtures/base.py +384 -0
  227. sqlalchemy/testing/fixtures/mypy.py +332 -0
  228. sqlalchemy/testing/fixtures/orm.py +227 -0
  229. sqlalchemy/testing/fixtures/sql.py +482 -0
  230. sqlalchemy/testing/pickleable.py +155 -0
  231. sqlalchemy/testing/plugin/__init__.py +6 -0
  232. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  233. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  234. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  235. sqlalchemy/testing/profiling.py +329 -0
  236. sqlalchemy/testing/provision.py +603 -0
  237. sqlalchemy/testing/requirements.py +1945 -0
  238. sqlalchemy/testing/schema.py +198 -0
  239. sqlalchemy/testing/suite/__init__.py +19 -0
  240. sqlalchemy/testing/suite/test_cte.py +237 -0
  241. sqlalchemy/testing/suite/test_ddl.py +389 -0
  242. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  243. sqlalchemy/testing/suite/test_dialect.py +776 -0
  244. sqlalchemy/testing/suite/test_insert.py +630 -0
  245. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  246. sqlalchemy/testing/suite/test_results.py +504 -0
  247. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  248. sqlalchemy/testing/suite/test_select.py +2010 -0
  249. sqlalchemy/testing/suite/test_sequence.py +317 -0
  250. sqlalchemy/testing/suite/test_types.py +2147 -0
  251. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  252. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  253. sqlalchemy/testing/util.py +535 -0
  254. sqlalchemy/testing/warnings.py +52 -0
  255. sqlalchemy/types.py +74 -0
  256. sqlalchemy/util/__init__.py +162 -0
  257. sqlalchemy/util/_collections.py +712 -0
  258. sqlalchemy/util/_concurrency_py3k.py +288 -0
  259. sqlalchemy/util/_has_cy.py +40 -0
  260. sqlalchemy/util/_py_collections.py +541 -0
  261. sqlalchemy/util/compat.py +421 -0
  262. sqlalchemy/util/concurrency.py +110 -0
  263. sqlalchemy/util/deprecations.py +401 -0
  264. sqlalchemy/util/langhelpers.py +2203 -0
  265. sqlalchemy/util/preloaded.py +150 -0
  266. sqlalchemy/util/queue.py +322 -0
  267. sqlalchemy/util/tool_support.py +201 -0
  268. sqlalchemy/util/topological.py +120 -0
  269. sqlalchemy/util/typing.py +734 -0
  270. sqlalchemy-2.0.47.dist-info/METADATA +243 -0
  271. sqlalchemy-2.0.47.dist-info/RECORD +274 -0
  272. sqlalchemy-2.0.47.dist-info/WHEEL +5 -0
  273. sqlalchemy-2.0.47.dist-info/licenses/LICENSE +19 -0
  274. sqlalchemy-2.0.47.dist-info/top_level.txt +1 -0
@@ -0,0 +1,587 @@
1
+ # sql/annotation.py
2
+ # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ """The :class:`.Annotated` class and related routines; creates hash-equivalent
9
+ copies of SQL constructs which contain context-specific markers and
10
+ associations.
11
+
12
+ Note that the :class:`.Annotated` concept as implemented in this module is not
13
+ related in any way to the pep-593 concept of "Annotated".
14
+
15
+
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import typing
21
+ from typing import Any
22
+ from typing import Callable
23
+ from typing import cast
24
+ from typing import Dict
25
+ from typing import FrozenSet
26
+ from typing import Mapping
27
+ from typing import Optional
28
+ from typing import overload
29
+ from typing import Sequence
30
+ from typing import Tuple
31
+ from typing import Type
32
+ from typing import TYPE_CHECKING
33
+ from typing import TypeVar
34
+
35
+ from . import operators
36
+ from .cache_key import HasCacheKey
37
+ from .visitors import anon_map
38
+ from .visitors import ExternallyTraversible
39
+ from .visitors import InternalTraversal
40
+ from .. import util
41
+ from ..util.typing import Literal
42
+ from ..util.typing import Self
43
+
44
+ if TYPE_CHECKING:
45
+ from .base import _EntityNamespace
46
+ from .visitors import _TraverseInternalsType
47
+
48
+ _AnnotationDict = Mapping[str, Any]
49
+
50
+ EMPTY_ANNOTATIONS: util.immutabledict[str, Any] = util.EMPTY_DICT
51
+
52
+
53
+ class SupportsAnnotations(ExternallyTraversible):
54
+ __slots__ = ()
55
+
56
+ _annotations: util.immutabledict[str, Any] = EMPTY_ANNOTATIONS
57
+
58
+ proxy_set: util.generic_fn_descriptor[FrozenSet[Any]]
59
+
60
+ _is_immutable: bool
61
+
62
+ def _annotate(self, values: _AnnotationDict) -> Self:
63
+ raise NotImplementedError()
64
+
65
+ @overload
66
+ def _deannotate(
67
+ self,
68
+ values: Literal[None] = ...,
69
+ clone: bool = ...,
70
+ ) -> Self: ...
71
+
72
+ @overload
73
+ def _deannotate(
74
+ self,
75
+ values: Sequence[str] = ...,
76
+ clone: bool = ...,
77
+ ) -> SupportsAnnotations: ...
78
+
79
+ def _deannotate(
80
+ self,
81
+ values: Optional[Sequence[str]] = None,
82
+ clone: bool = False,
83
+ ) -> SupportsAnnotations:
84
+ raise NotImplementedError()
85
+
86
+ @util.memoized_property
87
+ def _annotations_cache_key(self) -> Tuple[Any, ...]:
88
+ anon_map_ = anon_map()
89
+
90
+ return self._gen_annotations_cache_key(anon_map_)
91
+
92
+ def _gen_annotations_cache_key(
93
+ self, anon_map: anon_map
94
+ ) -> Tuple[Any, ...]:
95
+ return (
96
+ "_annotations",
97
+ tuple(
98
+ (
99
+ key,
100
+ (
101
+ value._gen_cache_key(anon_map, [])
102
+ if isinstance(value, HasCacheKey)
103
+ else value
104
+ ),
105
+ )
106
+ for key, value in [
107
+ (key, self._annotations[key])
108
+ for key in sorted(self._annotations)
109
+ ]
110
+ ),
111
+ )
112
+
113
+
114
+ class SupportsWrappingAnnotations(SupportsAnnotations):
115
+ __slots__ = ()
116
+
117
+ _constructor: Callable[..., SupportsWrappingAnnotations]
118
+
119
+ if TYPE_CHECKING:
120
+
121
+ @util.ro_non_memoized_property
122
+ def entity_namespace(self) -> _EntityNamespace: ...
123
+
124
+ def _annotate(self, values: _AnnotationDict) -> Self:
125
+ """return a copy of this ClauseElement with annotations
126
+ updated by the given dictionary.
127
+
128
+ """
129
+ return Annotated._as_annotated_instance(self, values) # type: ignore
130
+
131
+ def _with_annotations(self, values: _AnnotationDict) -> Self:
132
+ """return a copy of this ClauseElement with annotations
133
+ replaced by the given dictionary.
134
+
135
+ """
136
+ return Annotated._as_annotated_instance(self, values) # type: ignore
137
+
138
+ @overload
139
+ def _deannotate(
140
+ self,
141
+ values: Literal[None] = ...,
142
+ clone: bool = ...,
143
+ ) -> Self: ...
144
+
145
+ @overload
146
+ def _deannotate(
147
+ self,
148
+ values: Sequence[str] = ...,
149
+ clone: bool = ...,
150
+ ) -> SupportsAnnotations: ...
151
+
152
+ def _deannotate(
153
+ self,
154
+ values: Optional[Sequence[str]] = None,
155
+ clone: bool = False,
156
+ ) -> SupportsAnnotations:
157
+ """return a copy of this :class:`_expression.ClauseElement`
158
+ with annotations
159
+ removed.
160
+
161
+ :param values: optional tuple of individual values
162
+ to remove.
163
+
164
+ """
165
+ if clone:
166
+ s = self._clone()
167
+ return s
168
+ else:
169
+ return self
170
+
171
+
172
+ class SupportsCloneAnnotations(SupportsWrappingAnnotations):
173
+ # SupportsCloneAnnotations extends from SupportsWrappingAnnotations
174
+ # to support the structure of having the base ClauseElement
175
+ # be a subclass of SupportsWrappingAnnotations. Any ClauseElement
176
+ # subclass that wants to extend from SupportsCloneAnnotations
177
+ # will inherently also be subclassing SupportsWrappingAnnotations, so
178
+ # make that specific here.
179
+
180
+ if not typing.TYPE_CHECKING:
181
+ __slots__ = ()
182
+
183
+ _clone_annotations_traverse_internals: _TraverseInternalsType = [
184
+ ("_annotations", InternalTraversal.dp_annotations_key)
185
+ ]
186
+
187
+ def _annotate(self, values: _AnnotationDict) -> Self:
188
+ """return a copy of this ClauseElement with annotations
189
+ updated by the given dictionary.
190
+
191
+ """
192
+ new = self._clone()
193
+ new._annotations = new._annotations.union(values)
194
+ new.__dict__.pop("_annotations_cache_key", None)
195
+ new.__dict__.pop("_generate_cache_key", None)
196
+ return new
197
+
198
+ def _with_annotations(self, values: _AnnotationDict) -> Self:
199
+ """return a copy of this ClauseElement with annotations
200
+ replaced by the given dictionary.
201
+
202
+ """
203
+ new = self._clone()
204
+ new._annotations = util.immutabledict(values)
205
+ new.__dict__.pop("_annotations_cache_key", None)
206
+ new.__dict__.pop("_generate_cache_key", None)
207
+ return new
208
+
209
+ @overload
210
+ def _deannotate(
211
+ self,
212
+ values: Literal[None] = ...,
213
+ clone: bool = ...,
214
+ ) -> Self: ...
215
+
216
+ @overload
217
+ def _deannotate(
218
+ self,
219
+ values: Sequence[str] = ...,
220
+ clone: bool = ...,
221
+ ) -> SupportsAnnotations: ...
222
+
223
+ def _deannotate(
224
+ self,
225
+ values: Optional[Sequence[str]] = None,
226
+ clone: bool = False,
227
+ ) -> SupportsAnnotations:
228
+ """return a copy of this :class:`_expression.ClauseElement`
229
+ with annotations
230
+ removed.
231
+
232
+ :param values: optional tuple of individual values
233
+ to remove.
234
+
235
+ """
236
+ if clone or self._annotations:
237
+ # clone is used when we are also copying
238
+ # the expression for a deep deannotation
239
+ new = self._clone()
240
+ new._annotations = util.immutabledict()
241
+ new.__dict__.pop("_annotations_cache_key", None)
242
+ return new
243
+ else:
244
+ return self
245
+
246
+
247
+ class Annotated(SupportsAnnotations):
248
+ """clones a SupportsAnnotations and applies an 'annotations' dictionary.
249
+
250
+ Unlike regular clones, this clone also mimics __hash__() and
251
+ __eq__() of the original element so that it takes its place
252
+ in hashed collections.
253
+
254
+ A reference to the original element is maintained, for the important
255
+ reason of keeping its hash value current. When GC'ed, the
256
+ hash value may be reused, causing conflicts.
257
+
258
+ .. note:: The rationale for Annotated producing a brand new class,
259
+ rather than placing the functionality directly within ClauseElement,
260
+ is **performance**. The __hash__() method is absent on plain
261
+ ClauseElement which leads to significantly reduced function call
262
+ overhead, as the use of sets and dictionaries against ClauseElement
263
+ objects is prevalent, but most are not "annotated".
264
+
265
+ """
266
+
267
+ _is_column_operators = False
268
+
269
+ @classmethod
270
+ def _as_annotated_instance(
271
+ cls, element: SupportsWrappingAnnotations, values: _AnnotationDict
272
+ ) -> Annotated:
273
+ try:
274
+ cls = annotated_classes[element.__class__]
275
+ except KeyError:
276
+ cls = _new_annotation_type(element.__class__, cls)
277
+ return cls(element, values)
278
+
279
+ _annotations: util.immutabledict[str, Any]
280
+ __element: SupportsWrappingAnnotations
281
+ _hash: int
282
+
283
+ def __new__(cls: Type[Self], *args: Any) -> Self:
284
+ return object.__new__(cls)
285
+
286
+ def __init__(
287
+ self, element: SupportsWrappingAnnotations, values: _AnnotationDict
288
+ ):
289
+ self.__dict__ = element.__dict__.copy()
290
+ self.__dict__.pop("_annotations_cache_key", None)
291
+ self.__dict__.pop("_generate_cache_key", None)
292
+ self.__element = element
293
+ self._annotations = util.immutabledict(values)
294
+ self._hash = hash(element)
295
+
296
+ def _annotate(self, values: _AnnotationDict) -> Self:
297
+ _values = self._annotations.union(values)
298
+ new = self._with_annotations(_values)
299
+ return new
300
+
301
+ def _with_annotations(self, values: _AnnotationDict) -> Self:
302
+ clone = self.__class__.__new__(self.__class__)
303
+ clone.__dict__ = self.__dict__.copy()
304
+ clone.__dict__.pop("_annotations_cache_key", None)
305
+ clone.__dict__.pop("_generate_cache_key", None)
306
+ clone._annotations = util.immutabledict(values)
307
+ return clone
308
+
309
+ @overload
310
+ def _deannotate(
311
+ self,
312
+ values: Literal[None] = ...,
313
+ clone: bool = ...,
314
+ ) -> Self: ...
315
+
316
+ @overload
317
+ def _deannotate(
318
+ self,
319
+ values: Sequence[str] = ...,
320
+ clone: bool = ...,
321
+ ) -> Annotated: ...
322
+
323
+ def _deannotate(
324
+ self,
325
+ values: Optional[Sequence[str]] = None,
326
+ clone: bool = True,
327
+ ) -> SupportsAnnotations:
328
+ if values is None:
329
+ return self.__element
330
+ else:
331
+ return self._with_annotations(
332
+ util.immutabledict(
333
+ {
334
+ key: value
335
+ for key, value in self._annotations.items()
336
+ if key not in values
337
+ }
338
+ )
339
+ )
340
+
341
+ if not typing.TYPE_CHECKING:
342
+ # manually proxy some methods that need extra attention
343
+ def _compiler_dispatch(self, visitor: Any, **kw: Any) -> Any:
344
+ return self.__element.__class__._compiler_dispatch(
345
+ self, visitor, **kw
346
+ )
347
+
348
+ @property
349
+ def _constructor(self):
350
+ return self.__element._constructor
351
+
352
+ def _clone(self, **kw: Any) -> Self:
353
+ clone = self.__element._clone(**kw)
354
+ if clone is self.__element:
355
+ # detect immutable, don't change anything
356
+ return self
357
+ else:
358
+ # update the clone with any changes that have occurred
359
+ # to this object's __dict__.
360
+ clone.__dict__.update(self.__dict__)
361
+ return self.__class__(clone, self._annotations)
362
+
363
+ def __reduce__(self) -> Tuple[Type[Annotated], Tuple[Any, ...]]:
364
+ return self.__class__, (self.__element, self._annotations)
365
+
366
+ def __hash__(self) -> int:
367
+ return self._hash
368
+
369
+ def __eq__(self, other: Any) -> bool:
370
+ if self._is_column_operators:
371
+ return self.__element.__class__.__eq__(self, other)
372
+ else:
373
+ return hash(other) == hash(self)
374
+
375
+ @util.ro_non_memoized_property
376
+ def entity_namespace(self) -> _EntityNamespace:
377
+ if "entity_namespace" in self._annotations:
378
+ return cast(
379
+ SupportsWrappingAnnotations,
380
+ self._annotations["entity_namespace"],
381
+ ).entity_namespace
382
+ else:
383
+ return self.__element.entity_namespace
384
+
385
+
386
+ # hard-generate Annotated subclasses. this technique
387
+ # is used instead of on-the-fly types (i.e. type.__new__())
388
+ # so that the resulting objects are pickleable; additionally, other
389
+ # decisions can be made up front about the type of object being annotated
390
+ # just once per class rather than per-instance.
391
+ annotated_classes: Dict[Type[SupportsWrappingAnnotations], Type[Annotated]] = (
392
+ {}
393
+ )
394
+
395
+ _SA = TypeVar("_SA", bound="SupportsAnnotations")
396
+
397
+
398
+ def _safe_annotate(to_annotate: _SA, annotations: _AnnotationDict) -> _SA:
399
+ try:
400
+ _annotate = to_annotate._annotate
401
+ except AttributeError:
402
+ # skip objects that don't actually have an `_annotate`
403
+ # attribute, namely QueryableAttribute inside of a join
404
+ # condition
405
+ return to_annotate
406
+ else:
407
+ return _annotate(annotations)
408
+
409
+
410
+ def _deep_annotate(
411
+ element: _SA,
412
+ annotations: _AnnotationDict,
413
+ exclude: Optional[Sequence[SupportsAnnotations]] = None,
414
+ *,
415
+ detect_subquery_cols: bool = False,
416
+ ind_cols_on_fromclause: bool = False,
417
+ annotate_callable: Optional[
418
+ Callable[[SupportsAnnotations, _AnnotationDict], SupportsAnnotations]
419
+ ] = None,
420
+ ) -> _SA:
421
+ """Deep copy the given ClauseElement, annotating each element
422
+ with the given annotations dictionary.
423
+
424
+ Elements within the exclude collection will be cloned but not annotated.
425
+
426
+ """
427
+
428
+ # annotated objects hack the __hash__() method so if we want to
429
+ # uniquely process them we have to use id()
430
+
431
+ cloned_ids: Dict[int, SupportsAnnotations] = {}
432
+
433
+ def clone(elem: SupportsAnnotations, **kw: Any) -> SupportsAnnotations:
434
+ # ind_cols_on_fromclause means make sure an AnnotatedFromClause
435
+ # has its own .c collection independent of that which its proxying.
436
+ # this is used specifically by orm.LoaderCriteriaOption to break
437
+ # a reference cycle that it's otherwise prone to building,
438
+ # see test_relationship_criteria->
439
+ # test_loader_criteria_subquery_w_same_entity. logic here was
440
+ # changed for #8796 and made explicit; previously it occurred
441
+ # by accident
442
+
443
+ kw["detect_subquery_cols"] = detect_subquery_cols
444
+ id_ = id(elem)
445
+
446
+ if id_ in cloned_ids:
447
+ return cloned_ids[id_]
448
+
449
+ if (
450
+ exclude
451
+ and hasattr(elem, "proxy_set")
452
+ and elem.proxy_set.intersection(exclude)
453
+ ):
454
+ newelem = elem._clone(clone=clone, **kw)
455
+ elif annotations != elem._annotations:
456
+ if detect_subquery_cols and elem._is_immutable:
457
+ to_annotate = elem._clone(clone=clone, **kw)
458
+ else:
459
+ to_annotate = elem
460
+ if annotate_callable:
461
+ newelem = annotate_callable(to_annotate, annotations)
462
+ else:
463
+ newelem = _safe_annotate(to_annotate, annotations)
464
+ else:
465
+ newelem = elem
466
+
467
+ newelem._copy_internals(
468
+ clone=clone,
469
+ ind_cols_on_fromclause=ind_cols_on_fromclause,
470
+ _annotations_traversal=True,
471
+ )
472
+
473
+ cloned_ids[id_] = newelem
474
+ return newelem
475
+
476
+ if element is not None:
477
+ element = cast(_SA, clone(element))
478
+ clone = None # type: ignore # remove gc cycles
479
+ return element
480
+
481
+
482
+ @overload
483
+ def _deep_deannotate(
484
+ element: Literal[None], values: Optional[Sequence[str]] = None
485
+ ) -> Literal[None]: ...
486
+
487
+
488
+ @overload
489
+ def _deep_deannotate(
490
+ element: _SA, values: Optional[Sequence[str]] = None
491
+ ) -> _SA: ...
492
+
493
+
494
+ def _deep_deannotate(
495
+ element: Optional[_SA], values: Optional[Sequence[str]] = None
496
+ ) -> Optional[_SA]:
497
+ """Deep copy the given element, removing annotations."""
498
+
499
+ cloned: Dict[Any, SupportsAnnotations] = {}
500
+
501
+ def clone(elem: SupportsAnnotations, **kw: Any) -> SupportsAnnotations:
502
+ key: Any
503
+ if values:
504
+ key = id(elem)
505
+ else:
506
+ key = elem
507
+
508
+ if key not in cloned:
509
+ newelem = elem._deannotate(values=values, clone=True)
510
+ newelem._copy_internals(clone=clone, _annotations_traversal=True)
511
+ cloned[key] = newelem
512
+ return newelem
513
+ else:
514
+ return cloned[key]
515
+
516
+ if element is not None:
517
+ element = cast(_SA, clone(element))
518
+ clone = None # type: ignore # remove gc cycles
519
+ return element
520
+
521
+
522
+ def _shallow_annotate(element: _SA, annotations: _AnnotationDict) -> _SA:
523
+ """Annotate the given ClauseElement and copy its internals so that
524
+ internal objects refer to the new annotated object.
525
+
526
+ Basically used to apply a "don't traverse" annotation to a
527
+ selectable, without digging throughout the whole
528
+ structure wasting time.
529
+ """
530
+ element = element._annotate(annotations)
531
+ element._copy_internals(_annotations_traversal=True)
532
+ return element
533
+
534
+
535
+ def _new_annotation_type(
536
+ cls: Type[SupportsWrappingAnnotations], base_cls: Type[Annotated]
537
+ ) -> Type[Annotated]:
538
+ """Generates a new class that subclasses Annotated and proxies a given
539
+ element type.
540
+
541
+ """
542
+ if issubclass(cls, Annotated):
543
+ return cls
544
+ elif cls in annotated_classes:
545
+ return annotated_classes[cls]
546
+
547
+ for super_ in cls.__mro__:
548
+ # check if an Annotated subclass more specific than
549
+ # the given base_cls is already registered, such
550
+ # as AnnotatedColumnElement.
551
+ if super_ in annotated_classes:
552
+ base_cls = annotated_classes[super_]
553
+ break
554
+
555
+ annotated_classes[cls] = anno_cls = cast(
556
+ Type[Annotated],
557
+ type("Annotated%s" % cls.__name__, (base_cls, cls), {}),
558
+ )
559
+ globals()["Annotated%s" % cls.__name__] = anno_cls
560
+
561
+ if "_traverse_internals" in cls.__dict__:
562
+ anno_cls._traverse_internals = list(cls._traverse_internals) + [
563
+ ("_annotations", InternalTraversal.dp_annotations_key)
564
+ ]
565
+ elif cls.__dict__.get("inherit_cache", False):
566
+ anno_cls._traverse_internals = list(cls._traverse_internals) + [
567
+ ("_annotations", InternalTraversal.dp_annotations_key)
568
+ ]
569
+
570
+ # some classes include this even if they have traverse_internals
571
+ # e.g. BindParameter, add it if present.
572
+ if cls.__dict__.get("inherit_cache", False):
573
+ anno_cls.inherit_cache = True # type: ignore
574
+ elif "inherit_cache" in cls.__dict__:
575
+ anno_cls.inherit_cache = cls.__dict__["inherit_cache"] # type: ignore
576
+
577
+ anno_cls._is_column_operators = issubclass(cls, operators.ColumnOperators)
578
+
579
+ return anno_cls
580
+
581
+
582
+ def _prepare_annotations(
583
+ target_hierarchy: Type[SupportsWrappingAnnotations],
584
+ base_cls: Type[Annotated],
585
+ ) -> None:
586
+ for cls in util.walk_subclasses(target_hierarchy):
587
+ _new_annotation_type(cls, base_cls)