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
sqlalchemy/sql/base.py ADDED
@@ -0,0 +1,2185 @@
1
+ # sql/base.py
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+ # mypy: allow-untyped-defs, allow-untyped-calls
8
+
9
+ """Foundational utilities common to many sql modules.
10
+
11
+ """
12
+
13
+
14
+ from __future__ import annotations
15
+
16
+ import collections
17
+ from enum import Enum
18
+ import itertools
19
+ from itertools import zip_longest
20
+ import operator
21
+ import re
22
+ from typing import Any
23
+ from typing import Callable
24
+ from typing import cast
25
+ from typing import Dict
26
+ from typing import FrozenSet
27
+ from typing import Generic
28
+ from typing import Iterable
29
+ from typing import Iterator
30
+ from typing import List
31
+ from typing import Mapping
32
+ from typing import MutableMapping
33
+ from typing import NamedTuple
34
+ from typing import NoReturn
35
+ from typing import Optional
36
+ from typing import overload
37
+ from typing import Sequence
38
+ from typing import Set
39
+ from typing import Tuple
40
+ from typing import Type
41
+ from typing import TYPE_CHECKING
42
+ from typing import TypeVar
43
+ from typing import Union
44
+
45
+ from . import roles
46
+ from . import visitors
47
+ from .cache_key import HasCacheKey # noqa
48
+ from .cache_key import MemoizedHasCacheKey # noqa
49
+ from .traversals import HasCopyInternals # noqa
50
+ from .visitors import ClauseVisitor
51
+ from .visitors import ExtendedInternalTraversal
52
+ from .visitors import ExternallyTraversible
53
+ from .visitors import InternalTraversal
54
+ from .. import event
55
+ from .. import exc
56
+ from .. import util
57
+ from ..util import HasMemoized as HasMemoized
58
+ from ..util import hybridmethod
59
+ from ..util import typing as compat_typing
60
+ from ..util.typing import Protocol
61
+ from ..util.typing import Self
62
+ from ..util.typing import TypeGuard
63
+
64
+ if TYPE_CHECKING:
65
+ from . import coercions
66
+ from . import elements
67
+ from . import type_api
68
+ from ._orm_types import DMLStrategyArgument
69
+ from ._orm_types import SynchronizeSessionArgument
70
+ from ._typing import _CLE
71
+ from .elements import BindParameter
72
+ from .elements import ClauseList
73
+ from .elements import ColumnClause # noqa
74
+ from .elements import ColumnElement
75
+ from .elements import NamedColumn
76
+ from .elements import SQLCoreOperations
77
+ from .elements import TextClause
78
+ from .schema import Column
79
+ from .schema import DefaultGenerator
80
+ from .selectable import _JoinTargetElement
81
+ from .selectable import _SelectIterable
82
+ from .selectable import FromClause
83
+ from ..engine import Connection
84
+ from ..engine import CursorResult
85
+ from ..engine.interfaces import _CoreMultiExecuteParams
86
+ from ..engine.interfaces import _ExecuteOptions
87
+ from ..engine.interfaces import _ImmutableExecuteOptions
88
+ from ..engine.interfaces import CacheStats
89
+ from ..engine.interfaces import Compiled
90
+ from ..engine.interfaces import CompiledCacheType
91
+ from ..engine.interfaces import CoreExecuteOptionsParameter
92
+ from ..engine.interfaces import Dialect
93
+ from ..engine.interfaces import IsolationLevel
94
+ from ..engine.interfaces import SchemaTranslateMapType
95
+ from ..event import dispatcher
96
+
97
+ if not TYPE_CHECKING:
98
+ coercions = None # noqa
99
+ elements = None # noqa
100
+ type_api = None # noqa
101
+
102
+
103
+ class _NoArg(Enum):
104
+ NO_ARG = 0
105
+
106
+ def __repr__(self):
107
+ return f"_NoArg.{self.name}"
108
+
109
+
110
+ NO_ARG = _NoArg.NO_ARG
111
+
112
+
113
+ class _NoneName(Enum):
114
+ NONE_NAME = 0
115
+ """indicate a 'deferred' name that was ultimately the value None."""
116
+
117
+
118
+ _NONE_NAME = _NoneName.NONE_NAME
119
+
120
+ _T = TypeVar("_T", bound=Any)
121
+
122
+ _Fn = TypeVar("_Fn", bound=Callable[..., Any])
123
+
124
+ _AmbiguousTableNameMap = MutableMapping[str, str]
125
+
126
+
127
+ class _DefaultDescriptionTuple(NamedTuple):
128
+ arg: Any
129
+ is_scalar: Optional[bool]
130
+ is_callable: Optional[bool]
131
+ is_sentinel: Optional[bool]
132
+
133
+ @classmethod
134
+ def _from_column_default(
135
+ cls, default: Optional[DefaultGenerator]
136
+ ) -> _DefaultDescriptionTuple:
137
+ return (
138
+ _DefaultDescriptionTuple(
139
+ default.arg, # type: ignore
140
+ default.is_scalar,
141
+ default.is_callable,
142
+ default.is_sentinel,
143
+ )
144
+ if default
145
+ and (
146
+ default.has_arg
147
+ or (not default.for_update and default.is_sentinel)
148
+ )
149
+ else _DefaultDescriptionTuple(None, None, None, None)
150
+ )
151
+
152
+
153
+ _never_select_column = operator.attrgetter("_omit_from_statements")
154
+
155
+
156
+ class _EntityNamespace(Protocol):
157
+ def __getattr__(self, key: str) -> SQLCoreOperations[Any]: ...
158
+
159
+
160
+ class _HasEntityNamespace(Protocol):
161
+ @util.ro_non_memoized_property
162
+ def entity_namespace(self) -> _EntityNamespace: ...
163
+
164
+
165
+ def _is_has_entity_namespace(element: Any) -> TypeGuard[_HasEntityNamespace]:
166
+ return hasattr(element, "entity_namespace")
167
+
168
+
169
+ # Remove when https://github.com/python/mypy/issues/14640 will be fixed
170
+ _Self = TypeVar("_Self", bound=Any)
171
+
172
+
173
+ class Immutable:
174
+ """mark a ClauseElement as 'immutable' when expressions are cloned.
175
+
176
+ "immutable" objects refers to the "mutability" of an object in the
177
+ context of SQL DQL and DML generation. Such as, in DQL, one can
178
+ compose a SELECT or subquery of varied forms, but one cannot modify
179
+ the structure of a specific table or column within DQL.
180
+ :class:`.Immutable` is mostly intended to follow this concept, and as
181
+ such the primary "immutable" objects are :class:`.ColumnClause`,
182
+ :class:`.Column`, :class:`.TableClause`, :class:`.Table`.
183
+
184
+ """
185
+
186
+ __slots__ = ()
187
+
188
+ _is_immutable = True
189
+
190
+ def unique_params(self, *optionaldict, **kwargs):
191
+ raise NotImplementedError("Immutable objects do not support copying")
192
+
193
+ def params(self, *optionaldict, **kwargs):
194
+ raise NotImplementedError("Immutable objects do not support copying")
195
+
196
+ def _clone(self: _Self, **kw: Any) -> _Self:
197
+ return self
198
+
199
+ def _copy_internals(
200
+ self, *, omit_attrs: Iterable[str] = (), **kw: Any
201
+ ) -> None:
202
+ pass
203
+
204
+
205
+ class SingletonConstant(Immutable):
206
+ """Represent SQL constants like NULL, TRUE, FALSE"""
207
+
208
+ _is_singleton_constant = True
209
+
210
+ _singleton: SingletonConstant
211
+
212
+ def __new__(cls: _T, *arg: Any, **kw: Any) -> _T:
213
+ return cast(_T, cls._singleton)
214
+
215
+ @util.non_memoized_property
216
+ def proxy_set(self) -> FrozenSet[ColumnElement[Any]]:
217
+ raise NotImplementedError()
218
+
219
+ @classmethod
220
+ def _create_singleton(cls):
221
+ obj = object.__new__(cls)
222
+ obj.__init__() # type: ignore
223
+
224
+ # for a long time this was an empty frozenset, meaning
225
+ # a SingletonConstant would never be a "corresponding column" in
226
+ # a statement. This referred to #6259. However, in #7154 we see
227
+ # that we do in fact need "correspondence" to work when matching cols
228
+ # in result sets, so the non-correspondence was moved to a more
229
+ # specific level when we are actually adapting expressions for SQL
230
+ # render only.
231
+ obj.proxy_set = frozenset([obj])
232
+ cls._singleton = obj
233
+
234
+
235
+ def _from_objects(
236
+ *elements: Union[
237
+ ColumnElement[Any], FromClause, TextClause, _JoinTargetElement
238
+ ]
239
+ ) -> Iterator[FromClause]:
240
+ return itertools.chain.from_iterable(
241
+ [element._from_objects for element in elements]
242
+ )
243
+
244
+
245
+ def _select_iterables(
246
+ elements: Iterable[roles.ColumnsClauseRole],
247
+ ) -> _SelectIterable:
248
+ """expand tables into individual columns in the
249
+ given list of column expressions.
250
+
251
+ """
252
+ return itertools.chain.from_iterable(
253
+ [c._select_iterable for c in elements]
254
+ )
255
+
256
+
257
+ _SelfGenerativeType = TypeVar("_SelfGenerativeType", bound="_GenerativeType")
258
+
259
+
260
+ class _GenerativeType(compat_typing.Protocol):
261
+ def _generate(self) -> Self: ...
262
+
263
+
264
+ def _generative(fn: _Fn) -> _Fn:
265
+ """non-caching _generative() decorator.
266
+
267
+ This is basically the legacy decorator that copies the object and
268
+ runs a method on the new copy.
269
+
270
+ """
271
+
272
+ @util.decorator
273
+ def _generative(
274
+ fn: _Fn, self: _SelfGenerativeType, *args: Any, **kw: Any
275
+ ) -> _SelfGenerativeType:
276
+ """Mark a method as generative."""
277
+
278
+ self = self._generate()
279
+ x = fn(self, *args, **kw)
280
+ assert x is self, "generative methods must return self"
281
+ return self
282
+
283
+ decorated = _generative(fn)
284
+ decorated.non_generative = fn # type: ignore
285
+ return decorated
286
+
287
+
288
+ def _exclusive_against(*names: str, **kw: Any) -> Callable[[_Fn], _Fn]:
289
+ msgs = kw.pop("msgs", {})
290
+
291
+ defaults = kw.pop("defaults", {})
292
+
293
+ getters = [
294
+ (name, operator.attrgetter(name), defaults.get(name, None))
295
+ for name in names
296
+ ]
297
+
298
+ @util.decorator
299
+ def check(fn, *args, **kw):
300
+ # make pylance happy by not including "self" in the argument
301
+ # list
302
+ self = args[0]
303
+ args = args[1:]
304
+ for name, getter, default_ in getters:
305
+ if getter(self) is not default_:
306
+ msg = msgs.get(
307
+ name,
308
+ "Method %s() has already been invoked on this %s construct"
309
+ % (fn.__name__, self.__class__),
310
+ )
311
+ raise exc.InvalidRequestError(msg)
312
+ return fn(self, *args, **kw)
313
+
314
+ return check
315
+
316
+
317
+ def _clone(element, **kw):
318
+ return element._clone(**kw)
319
+
320
+
321
+ def _expand_cloned(
322
+ elements: Iterable[_CLE],
323
+ ) -> Iterable[_CLE]:
324
+ """expand the given set of ClauseElements to be the set of all 'cloned'
325
+ predecessors.
326
+
327
+ """
328
+ # TODO: cython candidate
329
+ return itertools.chain(*[x._cloned_set for x in elements])
330
+
331
+
332
+ def _de_clone(
333
+ elements: Iterable[_CLE],
334
+ ) -> Iterable[_CLE]:
335
+ for x in elements:
336
+ while x._is_clone_of is not None:
337
+ x = x._is_clone_of
338
+ yield x
339
+
340
+
341
+ def _cloned_intersection(a: Iterable[_CLE], b: Iterable[_CLE]) -> Set[_CLE]:
342
+ """return the intersection of sets a and b, counting
343
+ any overlap between 'cloned' predecessors.
344
+
345
+ The returned set is in terms of the entities present within 'a'.
346
+
347
+ """
348
+ all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))
349
+ return {elem for elem in a if all_overlap.intersection(elem._cloned_set)}
350
+
351
+
352
+ def _cloned_difference(a: Iterable[_CLE], b: Iterable[_CLE]) -> Set[_CLE]:
353
+ all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))
354
+ return {
355
+ elem for elem in a if not all_overlap.intersection(elem._cloned_set)
356
+ }
357
+
358
+
359
+ class _DialectArgView(MutableMapping[str, Any]):
360
+ """A dictionary view of dialect-level arguments in the form
361
+ <dialectname>_<argument_name>.
362
+
363
+ """
364
+
365
+ def __init__(self, obj):
366
+ self.obj = obj
367
+
368
+ def _key(self, key):
369
+ try:
370
+ dialect, value_key = key.split("_", 1)
371
+ except ValueError as err:
372
+ raise KeyError(key) from err
373
+ else:
374
+ return dialect, value_key
375
+
376
+ def __getitem__(self, key):
377
+ dialect, value_key = self._key(key)
378
+
379
+ try:
380
+ opt = self.obj.dialect_options[dialect]
381
+ except exc.NoSuchModuleError as err:
382
+ raise KeyError(key) from err
383
+ else:
384
+ return opt[value_key]
385
+
386
+ def __setitem__(self, key, value):
387
+ try:
388
+ dialect, value_key = self._key(key)
389
+ except KeyError as err:
390
+ raise exc.ArgumentError(
391
+ "Keys must be of the form <dialectname>_<argname>"
392
+ ) from err
393
+ else:
394
+ self.obj.dialect_options[dialect][value_key] = value
395
+
396
+ def __delitem__(self, key):
397
+ dialect, value_key = self._key(key)
398
+ del self.obj.dialect_options[dialect][value_key]
399
+
400
+ def __len__(self):
401
+ return sum(
402
+ len(args._non_defaults)
403
+ for args in self.obj.dialect_options.values()
404
+ )
405
+
406
+ def __iter__(self):
407
+ return (
408
+ "%s_%s" % (dialect_name, value_name)
409
+ for dialect_name in self.obj.dialect_options
410
+ for value_name in self.obj.dialect_options[
411
+ dialect_name
412
+ ]._non_defaults
413
+ )
414
+
415
+
416
+ class _DialectArgDict(MutableMapping[str, Any]):
417
+ """A dictionary view of dialect-level arguments for a specific
418
+ dialect.
419
+
420
+ Maintains a separate collection of user-specified arguments
421
+ and dialect-specified default arguments.
422
+
423
+ """
424
+
425
+ def __init__(self):
426
+ self._non_defaults = {}
427
+ self._defaults = {}
428
+
429
+ def __len__(self):
430
+ return len(set(self._non_defaults).union(self._defaults))
431
+
432
+ def __iter__(self):
433
+ return iter(set(self._non_defaults).union(self._defaults))
434
+
435
+ def __getitem__(self, key):
436
+ if key in self._non_defaults:
437
+ return self._non_defaults[key]
438
+ else:
439
+ return self._defaults[key]
440
+
441
+ def __setitem__(self, key, value):
442
+ self._non_defaults[key] = value
443
+
444
+ def __delitem__(self, key):
445
+ del self._non_defaults[key]
446
+
447
+
448
+ @util.preload_module("sqlalchemy.dialects")
449
+ def _kw_reg_for_dialect(dialect_name):
450
+ dialect_cls = util.preloaded.dialects.registry.load(dialect_name)
451
+ if dialect_cls.construct_arguments is None:
452
+ return None
453
+ return dict(dialect_cls.construct_arguments)
454
+
455
+
456
+ class DialectKWArgs:
457
+ """Establish the ability for a class to have dialect-specific arguments
458
+ with defaults and constructor validation.
459
+
460
+ The :class:`.DialectKWArgs` interacts with the
461
+ :attr:`.DefaultDialect.construct_arguments` present on a dialect.
462
+
463
+ .. seealso::
464
+
465
+ :attr:`.DefaultDialect.construct_arguments`
466
+
467
+ """
468
+
469
+ __slots__ = ()
470
+
471
+ _dialect_kwargs_traverse_internals = [
472
+ ("dialect_options", InternalTraversal.dp_dialect_options)
473
+ ]
474
+
475
+ @classmethod
476
+ def argument_for(cls, dialect_name, argument_name, default):
477
+ """Add a new kind of dialect-specific keyword argument for this class.
478
+
479
+ E.g.::
480
+
481
+ Index.argument_for("mydialect", "length", None)
482
+
483
+ some_index = Index('a', 'b', mydialect_length=5)
484
+
485
+ The :meth:`.DialectKWArgs.argument_for` method is a per-argument
486
+ way adding extra arguments to the
487
+ :attr:`.DefaultDialect.construct_arguments` dictionary. This
488
+ dictionary provides a list of argument names accepted by various
489
+ schema-level constructs on behalf of a dialect.
490
+
491
+ New dialects should typically specify this dictionary all at once as a
492
+ data member of the dialect class. The use case for ad-hoc addition of
493
+ argument names is typically for end-user code that is also using
494
+ a custom compilation scheme which consumes the additional arguments.
495
+
496
+ :param dialect_name: name of a dialect. The dialect must be
497
+ locatable, else a :class:`.NoSuchModuleError` is raised. The
498
+ dialect must also include an existing
499
+ :attr:`.DefaultDialect.construct_arguments` collection, indicating
500
+ that it participates in the keyword-argument validation and default
501
+ system, else :class:`.ArgumentError` is raised. If the dialect does
502
+ not include this collection, then any keyword argument can be
503
+ specified on behalf of this dialect already. All dialects packaged
504
+ within SQLAlchemy include this collection, however for third party
505
+ dialects, support may vary.
506
+
507
+ :param argument_name: name of the parameter.
508
+
509
+ :param default: default value of the parameter.
510
+
511
+ """
512
+
513
+ construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
514
+ if construct_arg_dictionary is None:
515
+ raise exc.ArgumentError(
516
+ "Dialect '%s' does have keyword-argument "
517
+ "validation and defaults enabled configured" % dialect_name
518
+ )
519
+ if cls not in construct_arg_dictionary:
520
+ construct_arg_dictionary[cls] = {}
521
+ construct_arg_dictionary[cls][argument_name] = default
522
+
523
+ @util.memoized_property
524
+ def dialect_kwargs(self):
525
+ """A collection of keyword arguments specified as dialect-specific
526
+ options to this construct.
527
+
528
+ The arguments are present here in their original ``<dialect>_<kwarg>``
529
+ format. Only arguments that were actually passed are included;
530
+ unlike the :attr:`.DialectKWArgs.dialect_options` collection, which
531
+ contains all options known by this dialect including defaults.
532
+
533
+ The collection is also writable; keys are accepted of the
534
+ form ``<dialect>_<kwarg>`` where the value will be assembled
535
+ into the list of options.
536
+
537
+ .. seealso::
538
+
539
+ :attr:`.DialectKWArgs.dialect_options` - nested dictionary form
540
+
541
+ """
542
+ return _DialectArgView(self)
543
+
544
+ @property
545
+ def kwargs(self):
546
+ """A synonym for :attr:`.DialectKWArgs.dialect_kwargs`."""
547
+ return self.dialect_kwargs
548
+
549
+ _kw_registry = util.PopulateDict(_kw_reg_for_dialect)
550
+
551
+ def _kw_reg_for_dialect_cls(self, dialect_name):
552
+ construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
553
+ d = _DialectArgDict()
554
+
555
+ if construct_arg_dictionary is None:
556
+ d._defaults.update({"*": None})
557
+ else:
558
+ for cls in reversed(self.__class__.__mro__):
559
+ if cls in construct_arg_dictionary:
560
+ d._defaults.update(construct_arg_dictionary[cls])
561
+ return d
562
+
563
+ @util.memoized_property
564
+ def dialect_options(self):
565
+ """A collection of keyword arguments specified as dialect-specific
566
+ options to this construct.
567
+
568
+ This is a two-level nested registry, keyed to ``<dialect_name>``
569
+ and ``<argument_name>``. For example, the ``postgresql_where``
570
+ argument would be locatable as::
571
+
572
+ arg = my_object.dialect_options['postgresql']['where']
573
+
574
+ .. versionadded:: 0.9.2
575
+
576
+ .. seealso::
577
+
578
+ :attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form
579
+
580
+ """
581
+
582
+ return util.PopulateDict(
583
+ util.portable_instancemethod(self._kw_reg_for_dialect_cls)
584
+ )
585
+
586
+ def _validate_dialect_kwargs(self, kwargs: Dict[str, Any]) -> None:
587
+ # validate remaining kwargs that they all specify DB prefixes
588
+
589
+ if not kwargs:
590
+ return
591
+
592
+ for k in kwargs:
593
+ m = re.match("^(.+?)_(.+)$", k)
594
+ if not m:
595
+ raise TypeError(
596
+ "Additional arguments should be "
597
+ "named <dialectname>_<argument>, got '%s'" % k
598
+ )
599
+ dialect_name, arg_name = m.group(1, 2)
600
+
601
+ try:
602
+ construct_arg_dictionary = self.dialect_options[dialect_name]
603
+ except exc.NoSuchModuleError:
604
+ util.warn(
605
+ "Can't validate argument %r; can't "
606
+ "locate any SQLAlchemy dialect named %r"
607
+ % (k, dialect_name)
608
+ )
609
+ self.dialect_options[dialect_name] = d = _DialectArgDict()
610
+ d._defaults.update({"*": None})
611
+ d._non_defaults[arg_name] = kwargs[k]
612
+ else:
613
+ if (
614
+ "*" not in construct_arg_dictionary
615
+ and arg_name not in construct_arg_dictionary
616
+ ):
617
+ raise exc.ArgumentError(
618
+ "Argument %r is not accepted by "
619
+ "dialect %r on behalf of %r"
620
+ % (k, dialect_name, self.__class__)
621
+ )
622
+ else:
623
+ construct_arg_dictionary[arg_name] = kwargs[k]
624
+
625
+
626
+ class CompileState:
627
+ """Produces additional object state necessary for a statement to be
628
+ compiled.
629
+
630
+ the :class:`.CompileState` class is at the base of classes that assemble
631
+ state for a particular statement object that is then used by the
632
+ compiler. This process is essentially an extension of the process that
633
+ the SQLCompiler.visit_XYZ() method takes, however there is an emphasis
634
+ on converting raw user intent into more organized structures rather than
635
+ producing string output. The top-level :class:`.CompileState` for the
636
+ statement being executed is also accessible when the execution context
637
+ works with invoking the statement and collecting results.
638
+
639
+ The production of :class:`.CompileState` is specific to the compiler, such
640
+ as within the :meth:`.SQLCompiler.visit_insert`,
641
+ :meth:`.SQLCompiler.visit_select` etc. methods. These methods are also
642
+ responsible for associating the :class:`.CompileState` with the
643
+ :class:`.SQLCompiler` itself, if the statement is the "toplevel" statement,
644
+ i.e. the outermost SQL statement that's actually being executed.
645
+ There can be other :class:`.CompileState` objects that are not the
646
+ toplevel, such as when a SELECT subquery or CTE-nested
647
+ INSERT/UPDATE/DELETE is generated.
648
+
649
+ .. versionadded:: 1.4
650
+
651
+ """
652
+
653
+ __slots__ = ("statement", "_ambiguous_table_name_map")
654
+
655
+ plugins: Dict[Tuple[str, str], Type[CompileState]] = {}
656
+
657
+ _ambiguous_table_name_map: Optional[_AmbiguousTableNameMap]
658
+
659
+ @classmethod
660
+ def create_for_statement(cls, statement, compiler, **kw):
661
+ # factory construction.
662
+
663
+ if statement._propagate_attrs:
664
+ plugin_name = statement._propagate_attrs.get(
665
+ "compile_state_plugin", "default"
666
+ )
667
+ klass = cls.plugins.get(
668
+ (plugin_name, statement._effective_plugin_target), None
669
+ )
670
+ if klass is None:
671
+ klass = cls.plugins[
672
+ ("default", statement._effective_plugin_target)
673
+ ]
674
+
675
+ else:
676
+ klass = cls.plugins[
677
+ ("default", statement._effective_plugin_target)
678
+ ]
679
+
680
+ if klass is cls:
681
+ return cls(statement, compiler, **kw)
682
+ else:
683
+ return klass.create_for_statement(statement, compiler, **kw)
684
+
685
+ def __init__(self, statement, compiler, **kw):
686
+ self.statement = statement
687
+
688
+ @classmethod
689
+ def get_plugin_class(
690
+ cls, statement: Executable
691
+ ) -> Optional[Type[CompileState]]:
692
+ plugin_name = statement._propagate_attrs.get(
693
+ "compile_state_plugin", None
694
+ )
695
+
696
+ if plugin_name:
697
+ key = (plugin_name, statement._effective_plugin_target)
698
+ if key in cls.plugins:
699
+ return cls.plugins[key]
700
+
701
+ # there's no case where we call upon get_plugin_class() and want
702
+ # to get None back, there should always be a default. return that
703
+ # if there was no plugin-specific class (e.g. Insert with "orm"
704
+ # plugin)
705
+ try:
706
+ return cls.plugins[("default", statement._effective_plugin_target)]
707
+ except KeyError:
708
+ return None
709
+
710
+ @classmethod
711
+ def _get_plugin_class_for_plugin(
712
+ cls, statement: Executable, plugin_name: str
713
+ ) -> Optional[Type[CompileState]]:
714
+ try:
715
+ return cls.plugins[
716
+ (plugin_name, statement._effective_plugin_target)
717
+ ]
718
+ except KeyError:
719
+ return None
720
+
721
+ @classmethod
722
+ def plugin_for(
723
+ cls, plugin_name: str, visit_name: str
724
+ ) -> Callable[[_Fn], _Fn]:
725
+ def decorate(cls_to_decorate):
726
+ cls.plugins[(plugin_name, visit_name)] = cls_to_decorate
727
+ return cls_to_decorate
728
+
729
+ return decorate
730
+
731
+
732
+ class Generative(HasMemoized):
733
+ """Provide a method-chaining pattern in conjunction with the
734
+ @_generative decorator."""
735
+
736
+ def _generate(self) -> Self:
737
+ skip = self._memoized_keys
738
+ cls = self.__class__
739
+ s = cls.__new__(cls)
740
+ if skip:
741
+ # ensure this iteration remains atomic
742
+ s.__dict__ = {
743
+ k: v for k, v in self.__dict__.copy().items() if k not in skip
744
+ }
745
+ else:
746
+ s.__dict__ = self.__dict__.copy()
747
+ return s
748
+
749
+
750
+ class InPlaceGenerative(HasMemoized):
751
+ """Provide a method-chaining pattern in conjunction with the
752
+ @_generative decorator that mutates in place."""
753
+
754
+ __slots__ = ()
755
+
756
+ def _generate(self):
757
+ skip = self._memoized_keys
758
+ # note __dict__ needs to be in __slots__ if this is used
759
+ for k in skip:
760
+ self.__dict__.pop(k, None)
761
+ return self
762
+
763
+
764
+ class HasCompileState(Generative):
765
+ """A class that has a :class:`.CompileState` associated with it."""
766
+
767
+ _compile_state_plugin: Optional[Type[CompileState]] = None
768
+
769
+ _attributes: util.immutabledict[str, Any] = util.EMPTY_DICT
770
+
771
+ _compile_state_factory = CompileState.create_for_statement
772
+
773
+
774
+ class _MetaOptions(type):
775
+ """metaclass for the Options class.
776
+
777
+ This metaclass is actually necessary despite the availability of the
778
+ ``__init_subclass__()`` hook as this type also provides custom class-level
779
+ behavior for the ``__add__()`` method.
780
+
781
+ """
782
+
783
+ _cache_attrs: Tuple[str, ...]
784
+
785
+ def __add__(self, other):
786
+ o1 = self()
787
+
788
+ if set(other).difference(self._cache_attrs):
789
+ raise TypeError(
790
+ "dictionary contains attributes not covered by "
791
+ "Options class %s: %r"
792
+ % (self, set(other).difference(self._cache_attrs))
793
+ )
794
+
795
+ o1.__dict__.update(other)
796
+ return o1
797
+
798
+ if TYPE_CHECKING:
799
+
800
+ def __getattr__(self, key: str) -> Any: ...
801
+
802
+ def __setattr__(self, key: str, value: Any) -> None: ...
803
+
804
+ def __delattr__(self, key: str) -> None: ...
805
+
806
+
807
+ class Options(metaclass=_MetaOptions):
808
+ """A cacheable option dictionary with defaults."""
809
+
810
+ __slots__ = ()
811
+
812
+ _cache_attrs: Tuple[str, ...]
813
+
814
+ def __init_subclass__(cls) -> None:
815
+ dict_ = cls.__dict__
816
+ cls._cache_attrs = tuple(
817
+ sorted(
818
+ d
819
+ for d in dict_
820
+ if not d.startswith("__")
821
+ and d not in ("_cache_key_traversal",)
822
+ )
823
+ )
824
+ super().__init_subclass__()
825
+
826
+ def __init__(self, **kw):
827
+ self.__dict__.update(kw)
828
+
829
+ def __add__(self, other):
830
+ o1 = self.__class__.__new__(self.__class__)
831
+ o1.__dict__.update(self.__dict__)
832
+
833
+ if set(other).difference(self._cache_attrs):
834
+ raise TypeError(
835
+ "dictionary contains attributes not covered by "
836
+ "Options class %s: %r"
837
+ % (self, set(other).difference(self._cache_attrs))
838
+ )
839
+
840
+ o1.__dict__.update(other)
841
+ return o1
842
+
843
+ def __eq__(self, other):
844
+ # TODO: very inefficient. This is used only in test suites
845
+ # right now.
846
+ for a, b in zip_longest(self._cache_attrs, other._cache_attrs):
847
+ if getattr(self, a) != getattr(other, b):
848
+ return False
849
+ return True
850
+
851
+ def __repr__(self):
852
+ # TODO: fairly inefficient, used only in debugging right now.
853
+
854
+ return "%s(%s)" % (
855
+ self.__class__.__name__,
856
+ ", ".join(
857
+ "%s=%r" % (k, self.__dict__[k])
858
+ for k in self._cache_attrs
859
+ if k in self.__dict__
860
+ ),
861
+ )
862
+
863
+ @classmethod
864
+ def isinstance(cls, klass: Type[Any]) -> bool:
865
+ return issubclass(cls, klass)
866
+
867
+ @hybridmethod
868
+ def add_to_element(self, name, value):
869
+ return self + {name: getattr(self, name) + value}
870
+
871
+ @hybridmethod
872
+ def _state_dict_inst(self) -> Mapping[str, Any]:
873
+ return self.__dict__
874
+
875
+ _state_dict_const: util.immutabledict[str, Any] = util.EMPTY_DICT
876
+
877
+ @_state_dict_inst.classlevel
878
+ def _state_dict(cls) -> Mapping[str, Any]:
879
+ return cls._state_dict_const
880
+
881
+ @classmethod
882
+ def safe_merge(cls, other):
883
+ d = other._state_dict()
884
+
885
+ # only support a merge with another object of our class
886
+ # and which does not have attrs that we don't. otherwise
887
+ # we risk having state that might not be part of our cache
888
+ # key strategy
889
+
890
+ if (
891
+ cls is not other.__class__
892
+ and other._cache_attrs
893
+ and set(other._cache_attrs).difference(cls._cache_attrs)
894
+ ):
895
+ raise TypeError(
896
+ "other element %r is not empty, is not of type %s, "
897
+ "and contains attributes not covered here %r"
898
+ % (
899
+ other,
900
+ cls,
901
+ set(other._cache_attrs).difference(cls._cache_attrs),
902
+ )
903
+ )
904
+ return cls + d
905
+
906
+ @classmethod
907
+ def from_execution_options(
908
+ cls, key, attrs, exec_options, statement_exec_options
909
+ ):
910
+ """process Options argument in terms of execution options.
911
+
912
+
913
+ e.g.::
914
+
915
+ (
916
+ load_options,
917
+ execution_options,
918
+ ) = QueryContext.default_load_options.from_execution_options(
919
+ "_sa_orm_load_options",
920
+ {
921
+ "populate_existing",
922
+ "autoflush",
923
+ "yield_per"
924
+ },
925
+ execution_options,
926
+ statement._execution_options,
927
+ )
928
+
929
+ get back the Options and refresh "_sa_orm_load_options" in the
930
+ exec options dict w/ the Options as well
931
+
932
+ """
933
+
934
+ # common case is that no options we are looking for are
935
+ # in either dictionary, so cancel for that first
936
+ check_argnames = attrs.intersection(
937
+ set(exec_options).union(statement_exec_options)
938
+ )
939
+
940
+ existing_options = exec_options.get(key, cls)
941
+
942
+ if check_argnames:
943
+ result = {}
944
+ for argname in check_argnames:
945
+ local = "_" + argname
946
+ if argname in exec_options:
947
+ result[local] = exec_options[argname]
948
+ elif argname in statement_exec_options:
949
+ result[local] = statement_exec_options[argname]
950
+
951
+ new_options = existing_options + result
952
+ exec_options = util.immutabledict().merge_with(
953
+ exec_options, {key: new_options}
954
+ )
955
+ return new_options, exec_options
956
+
957
+ else:
958
+ return existing_options, exec_options
959
+
960
+ if TYPE_CHECKING:
961
+
962
+ def __getattr__(self, key: str) -> Any: ...
963
+
964
+ def __setattr__(self, key: str, value: Any) -> None: ...
965
+
966
+ def __delattr__(self, key: str) -> None: ...
967
+
968
+
969
+ class CacheableOptions(Options, HasCacheKey):
970
+ __slots__ = ()
971
+
972
+ @hybridmethod
973
+ def _gen_cache_key_inst(self, anon_map, bindparams):
974
+ return HasCacheKey._gen_cache_key(self, anon_map, bindparams)
975
+
976
+ @_gen_cache_key_inst.classlevel
977
+ def _gen_cache_key(cls, anon_map, bindparams):
978
+ return (cls, ())
979
+
980
+ @hybridmethod
981
+ def _generate_cache_key(self):
982
+ return HasCacheKey._generate_cache_key_for_object(self)
983
+
984
+
985
+ class ExecutableOption(HasCopyInternals):
986
+ __slots__ = ()
987
+
988
+ _annotations = util.EMPTY_DICT
989
+
990
+ __visit_name__ = "executable_option"
991
+
992
+ _is_has_cache_key = False
993
+
994
+ _is_core = True
995
+
996
+ def _clone(self, **kw):
997
+ """Create a shallow copy of this ExecutableOption."""
998
+ c = self.__class__.__new__(self.__class__)
999
+ c.__dict__ = dict(self.__dict__) # type: ignore
1000
+ return c
1001
+
1002
+
1003
+ class Executable(roles.StatementRole):
1004
+ """Mark a :class:`_expression.ClauseElement` as supporting execution.
1005
+
1006
+ :class:`.Executable` is a superclass for all "statement" types
1007
+ of objects, including :func:`select`, :func:`delete`, :func:`update`,
1008
+ :func:`insert`, :func:`text`.
1009
+
1010
+ """
1011
+
1012
+ supports_execution: bool = True
1013
+ _execution_options: _ImmutableExecuteOptions = util.EMPTY_DICT
1014
+ _is_default_generator = False
1015
+ _with_options: Tuple[ExecutableOption, ...] = ()
1016
+ _with_context_options: Tuple[
1017
+ Tuple[Callable[[CompileState], None], Any], ...
1018
+ ] = ()
1019
+ _compile_options: Optional[Union[Type[CacheableOptions], CacheableOptions]]
1020
+
1021
+ _executable_traverse_internals = [
1022
+ ("_with_options", InternalTraversal.dp_executable_options),
1023
+ (
1024
+ "_with_context_options",
1025
+ ExtendedInternalTraversal.dp_with_context_options,
1026
+ ),
1027
+ ("_propagate_attrs", ExtendedInternalTraversal.dp_propagate_attrs),
1028
+ ]
1029
+
1030
+ is_select = False
1031
+ is_from_statement = False
1032
+ is_update = False
1033
+ is_insert = False
1034
+ is_text = False
1035
+ is_delete = False
1036
+ is_dml = False
1037
+
1038
+ if TYPE_CHECKING:
1039
+ __visit_name__: str
1040
+
1041
+ def _compile_w_cache(
1042
+ self,
1043
+ dialect: Dialect,
1044
+ *,
1045
+ compiled_cache: Optional[CompiledCacheType],
1046
+ column_keys: List[str],
1047
+ for_executemany: bool = False,
1048
+ schema_translate_map: Optional[SchemaTranslateMapType] = None,
1049
+ **kw: Any,
1050
+ ) -> Tuple[
1051
+ Compiled, Optional[Sequence[BindParameter[Any]]], CacheStats
1052
+ ]: ...
1053
+
1054
+ def _execute_on_connection(
1055
+ self,
1056
+ connection: Connection,
1057
+ distilled_params: _CoreMultiExecuteParams,
1058
+ execution_options: CoreExecuteOptionsParameter,
1059
+ ) -> CursorResult[Any]: ...
1060
+
1061
+ def _execute_on_scalar(
1062
+ self,
1063
+ connection: Connection,
1064
+ distilled_params: _CoreMultiExecuteParams,
1065
+ execution_options: CoreExecuteOptionsParameter,
1066
+ ) -> Any: ...
1067
+
1068
+ @util.ro_non_memoized_property
1069
+ def _all_selected_columns(self):
1070
+ raise NotImplementedError()
1071
+
1072
+ @property
1073
+ def _effective_plugin_target(self) -> str:
1074
+ return self.__visit_name__
1075
+
1076
+ @_generative
1077
+ def options(self, *options: ExecutableOption) -> Self:
1078
+ """Apply options to this statement.
1079
+
1080
+ In the general sense, options are any kind of Python object
1081
+ that can be interpreted by the SQL compiler for the statement.
1082
+ These options can be consumed by specific dialects or specific kinds
1083
+ of compilers.
1084
+
1085
+ The most commonly known kind of option are the ORM level options
1086
+ that apply "eager load" and other loading behaviors to an ORM
1087
+ query. However, options can theoretically be used for many other
1088
+ purposes.
1089
+
1090
+ For background on specific kinds of options for specific kinds of
1091
+ statements, refer to the documentation for those option objects.
1092
+
1093
+ .. versionchanged:: 1.4 - added :meth:`.Executable.options` to
1094
+ Core statement objects towards the goal of allowing unified
1095
+ Core / ORM querying capabilities.
1096
+
1097
+ .. seealso::
1098
+
1099
+ :ref:`loading_columns` - refers to options specific to the usage
1100
+ of ORM queries
1101
+
1102
+ :ref:`relationship_loader_options` - refers to options specific
1103
+ to the usage of ORM queries
1104
+
1105
+ """
1106
+ self._with_options += tuple(
1107
+ coercions.expect(roles.ExecutableOptionRole, opt)
1108
+ for opt in options
1109
+ )
1110
+ return self
1111
+
1112
+ @_generative
1113
+ def _set_compile_options(self, compile_options: CacheableOptions) -> Self:
1114
+ """Assign the compile options to a new value.
1115
+
1116
+ :param compile_options: appropriate CacheableOptions structure
1117
+
1118
+ """
1119
+
1120
+ self._compile_options = compile_options
1121
+ return self
1122
+
1123
+ @_generative
1124
+ def _update_compile_options(self, options: CacheableOptions) -> Self:
1125
+ """update the _compile_options with new keys."""
1126
+
1127
+ assert self._compile_options is not None
1128
+ self._compile_options += options
1129
+ return self
1130
+
1131
+ @_generative
1132
+ def _add_context_option(
1133
+ self,
1134
+ callable_: Callable[[CompileState], None],
1135
+ cache_args: Any,
1136
+ ) -> Self:
1137
+ """Add a context option to this statement.
1138
+
1139
+ These are callable functions that will
1140
+ be given the CompileState object upon compilation.
1141
+
1142
+ A second argument cache_args is required, which will be combined with
1143
+ the ``__code__`` identity of the function itself in order to produce a
1144
+ cache key.
1145
+
1146
+ """
1147
+ self._with_context_options += ((callable_, cache_args),)
1148
+ return self
1149
+
1150
+ @overload
1151
+ def execution_options(
1152
+ self,
1153
+ *,
1154
+ compiled_cache: Optional[CompiledCacheType] = ...,
1155
+ logging_token: str = ...,
1156
+ isolation_level: IsolationLevel = ...,
1157
+ no_parameters: bool = False,
1158
+ stream_results: bool = False,
1159
+ max_row_buffer: int = ...,
1160
+ yield_per: int = ...,
1161
+ insertmanyvalues_page_size: int = ...,
1162
+ schema_translate_map: Optional[SchemaTranslateMapType] = ...,
1163
+ populate_existing: bool = False,
1164
+ autoflush: bool = False,
1165
+ synchronize_session: SynchronizeSessionArgument = ...,
1166
+ dml_strategy: DMLStrategyArgument = ...,
1167
+ render_nulls: bool = ...,
1168
+ is_delete_using: bool = ...,
1169
+ is_update_from: bool = ...,
1170
+ preserve_rowcount: bool = False,
1171
+ **opt: Any,
1172
+ ) -> Self: ...
1173
+
1174
+ @overload
1175
+ def execution_options(self, **opt: Any) -> Self: ...
1176
+
1177
+ @_generative
1178
+ def execution_options(self, **kw: Any) -> Self:
1179
+ """Set non-SQL options for the statement which take effect during
1180
+ execution.
1181
+
1182
+ Execution options can be set at many scopes, including per-statement,
1183
+ per-connection, or per execution, using methods such as
1184
+ :meth:`_engine.Connection.execution_options` and parameters which
1185
+ accept a dictionary of options such as
1186
+ :paramref:`_engine.Connection.execute.execution_options` and
1187
+ :paramref:`_orm.Session.execute.execution_options`.
1188
+
1189
+ The primary characteristic of an execution option, as opposed to
1190
+ other kinds of options such as ORM loader options, is that
1191
+ **execution options never affect the compiled SQL of a query, only
1192
+ things that affect how the SQL statement itself is invoked or how
1193
+ results are fetched**. That is, execution options are not part of
1194
+ what's accommodated by SQL compilation nor are they considered part of
1195
+ the cached state of a statement.
1196
+
1197
+ The :meth:`_sql.Executable.execution_options` method is
1198
+ :term:`generative`, as
1199
+ is the case for the method as applied to the :class:`_engine.Engine`
1200
+ and :class:`_orm.Query` objects, which means when the method is called,
1201
+ a copy of the object is returned, which applies the given parameters to
1202
+ that new copy, but leaves the original unchanged::
1203
+
1204
+ statement = select(table.c.x, table.c.y)
1205
+ new_statement = statement.execution_options(my_option=True)
1206
+
1207
+ An exception to this behavior is the :class:`_engine.Connection`
1208
+ object, where the :meth:`_engine.Connection.execution_options` method
1209
+ is explicitly **not** generative.
1210
+
1211
+ The kinds of options that may be passed to
1212
+ :meth:`_sql.Executable.execution_options` and other related methods and
1213
+ parameter dictionaries include parameters that are explicitly consumed
1214
+ by SQLAlchemy Core or ORM, as well as arbitrary keyword arguments not
1215
+ defined by SQLAlchemy, which means the methods and/or parameter
1216
+ dictionaries may be used for user-defined parameters that interact with
1217
+ custom code, which may access the parameters using methods such as
1218
+ :meth:`_sql.Executable.get_execution_options` and
1219
+ :meth:`_engine.Connection.get_execution_options`, or within selected
1220
+ event hooks using a dedicated ``execution_options`` event parameter
1221
+ such as
1222
+ :paramref:`_events.ConnectionEvents.before_execute.execution_options`
1223
+ or :attr:`_orm.ORMExecuteState.execution_options`, e.g.::
1224
+
1225
+ from sqlalchemy import event
1226
+
1227
+ @event.listens_for(some_engine, "before_execute")
1228
+ def _process_opt(conn, statement, multiparams, params, execution_options):
1229
+ "run a SQL function before invoking a statement"
1230
+
1231
+ if execution_options.get("do_special_thing", False):
1232
+ conn.exec_driver_sql("run_special_function()")
1233
+
1234
+ Within the scope of options that are explicitly recognized by
1235
+ SQLAlchemy, most apply to specific classes of objects and not others.
1236
+ The most common execution options include:
1237
+
1238
+ * :paramref:`_engine.Connection.execution_options.isolation_level` -
1239
+ sets the isolation level for a connection or a class of connections
1240
+ via an :class:`_engine.Engine`. This option is accepted only
1241
+ by :class:`_engine.Connection` or :class:`_engine.Engine`.
1242
+
1243
+ * :paramref:`_engine.Connection.execution_options.stream_results` -
1244
+ indicates results should be fetched using a server side cursor;
1245
+ this option is accepted by :class:`_engine.Connection`, by the
1246
+ :paramref:`_engine.Connection.execute.execution_options` parameter
1247
+ on :meth:`_engine.Connection.execute`, and additionally by
1248
+ :meth:`_sql.Executable.execution_options` on a SQL statement object,
1249
+ as well as by ORM constructs like :meth:`_orm.Session.execute`.
1250
+
1251
+ * :paramref:`_engine.Connection.execution_options.compiled_cache` -
1252
+ indicates a dictionary that will serve as the
1253
+ :ref:`SQL compilation cache <sql_caching>`
1254
+ for a :class:`_engine.Connection` or :class:`_engine.Engine`, as
1255
+ well as for ORM methods like :meth:`_orm.Session.execute`.
1256
+ Can be passed as ``None`` to disable caching for statements.
1257
+ This option is not accepted by
1258
+ :meth:`_sql.Executable.execution_options` as it is inadvisable to
1259
+ carry along a compilation cache within a statement object.
1260
+
1261
+ * :paramref:`_engine.Connection.execution_options.schema_translate_map`
1262
+ - a mapping of schema names used by the
1263
+ :ref:`Schema Translate Map <schema_translating>` feature, accepted
1264
+ by :class:`_engine.Connection`, :class:`_engine.Engine`,
1265
+ :class:`_sql.Executable`, as well as by ORM constructs
1266
+ like :meth:`_orm.Session.execute`.
1267
+
1268
+ .. seealso::
1269
+
1270
+ :meth:`_engine.Connection.execution_options`
1271
+
1272
+ :paramref:`_engine.Connection.execute.execution_options`
1273
+
1274
+ :paramref:`_orm.Session.execute.execution_options`
1275
+
1276
+ :ref:`orm_queryguide_execution_options` - documentation on all
1277
+ ORM-specific execution options
1278
+
1279
+ """ # noqa: E501
1280
+ if "isolation_level" in kw:
1281
+ raise exc.ArgumentError(
1282
+ "'isolation_level' execution option may only be specified "
1283
+ "on Connection.execution_options(), or "
1284
+ "per-engine using the isolation_level "
1285
+ "argument to create_engine()."
1286
+ )
1287
+ if "compiled_cache" in kw:
1288
+ raise exc.ArgumentError(
1289
+ "'compiled_cache' execution option may only be specified "
1290
+ "on Connection.execution_options(), not per statement."
1291
+ )
1292
+ self._execution_options = self._execution_options.union(kw)
1293
+ return self
1294
+
1295
+ def get_execution_options(self) -> _ExecuteOptions:
1296
+ """Get the non-SQL options which will take effect during execution.
1297
+
1298
+ .. versionadded:: 1.3
1299
+
1300
+ .. seealso::
1301
+
1302
+ :meth:`.Executable.execution_options`
1303
+ """
1304
+ return self._execution_options
1305
+
1306
+
1307
+ class SchemaEventTarget(event.EventTarget):
1308
+ """Base class for elements that are the targets of :class:`.DDLEvents`
1309
+ events.
1310
+
1311
+ This includes :class:`.SchemaItem` as well as :class:`.SchemaType`.
1312
+
1313
+ """
1314
+
1315
+ dispatch: dispatcher[SchemaEventTarget]
1316
+
1317
+ def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
1318
+ """Associate with this SchemaEvent's parent object."""
1319
+
1320
+ def _set_parent_with_dispatch(
1321
+ self, parent: SchemaEventTarget, **kw: Any
1322
+ ) -> None:
1323
+ self.dispatch.before_parent_attach(self, parent)
1324
+ self._set_parent(parent, **kw)
1325
+ self.dispatch.after_parent_attach(self, parent)
1326
+
1327
+
1328
+ class SchemaVisitor(ClauseVisitor):
1329
+ """Define the visiting for ``SchemaItem`` objects."""
1330
+
1331
+ __traverse_options__ = {"schema_visitor": True}
1332
+
1333
+
1334
+ class _SentinelDefaultCharacterization(Enum):
1335
+ NONE = "none"
1336
+ UNKNOWN = "unknown"
1337
+ CLIENTSIDE = "clientside"
1338
+ SENTINEL_DEFAULT = "sentinel_default"
1339
+ SERVERSIDE = "serverside"
1340
+ IDENTITY = "identity"
1341
+ SEQUENCE = "sequence"
1342
+
1343
+
1344
+ class _SentinelColumnCharacterization(NamedTuple):
1345
+ columns: Optional[Sequence[Column[Any]]] = None
1346
+ is_explicit: bool = False
1347
+ is_autoinc: bool = False
1348
+ default_characterization: _SentinelDefaultCharacterization = (
1349
+ _SentinelDefaultCharacterization.NONE
1350
+ )
1351
+
1352
+
1353
+ _COLKEY = TypeVar("_COLKEY", Union[None, str], str)
1354
+
1355
+ _COL_co = TypeVar("_COL_co", bound="ColumnElement[Any]", covariant=True)
1356
+ _COL = TypeVar("_COL", bound="ColumnElement[Any]")
1357
+
1358
+
1359
+ class _ColumnMetrics(Generic[_COL_co]):
1360
+ __slots__ = ("column",)
1361
+
1362
+ column: _COL_co
1363
+
1364
+ def __init__(
1365
+ self, collection: ColumnCollection[Any, _COL_co], col: _COL_co
1366
+ ):
1367
+ self.column = col
1368
+
1369
+ # proxy_index being non-empty means it was initialized.
1370
+ # so we need to update it
1371
+ pi = collection._proxy_index
1372
+ if pi:
1373
+ for eps_col in col._expanded_proxy_set:
1374
+ pi[eps_col].add(self)
1375
+
1376
+ def get_expanded_proxy_set(self):
1377
+ return self.column._expanded_proxy_set
1378
+
1379
+ def dispose(self, collection):
1380
+ pi = collection._proxy_index
1381
+ if not pi:
1382
+ return
1383
+ for col in self.column._expanded_proxy_set:
1384
+ colset = pi.get(col, None)
1385
+ if colset:
1386
+ colset.discard(self)
1387
+ if colset is not None and not colset:
1388
+ del pi[col]
1389
+
1390
+ def embedded(
1391
+ self,
1392
+ target_set: Union[
1393
+ Set[ColumnElement[Any]], FrozenSet[ColumnElement[Any]]
1394
+ ],
1395
+ ) -> bool:
1396
+ expanded_proxy_set = self.column._expanded_proxy_set
1397
+ for t in target_set.difference(expanded_proxy_set):
1398
+ if not expanded_proxy_set.intersection(_expand_cloned([t])):
1399
+ return False
1400
+ return True
1401
+
1402
+
1403
+ class ColumnCollection(Generic[_COLKEY, _COL_co]):
1404
+ """Collection of :class:`_expression.ColumnElement` instances,
1405
+ typically for
1406
+ :class:`_sql.FromClause` objects.
1407
+
1408
+ The :class:`_sql.ColumnCollection` object is most commonly available
1409
+ as the :attr:`_schema.Table.c` or :attr:`_schema.Table.columns` collection
1410
+ on the :class:`_schema.Table` object, introduced at
1411
+ :ref:`metadata_tables_and_columns`.
1412
+
1413
+ The :class:`_expression.ColumnCollection` has both mapping- and sequence-
1414
+ like behaviors. A :class:`_expression.ColumnCollection` usually stores
1415
+ :class:`_schema.Column` objects, which are then accessible both via mapping
1416
+ style access as well as attribute access style.
1417
+
1418
+ To access :class:`_schema.Column` objects using ordinary attribute-style
1419
+ access, specify the name like any other object attribute, such as below
1420
+ a column named ``employee_name`` is accessed::
1421
+
1422
+ >>> employee_table.c.employee_name
1423
+
1424
+ To access columns that have names with special characters or spaces,
1425
+ index-style access is used, such as below which illustrates a column named
1426
+ ``employee ' payment`` is accessed::
1427
+
1428
+ >>> employee_table.c["employee ' payment"]
1429
+
1430
+ As the :class:`_sql.ColumnCollection` object provides a Python dictionary
1431
+ interface, common dictionary method names like
1432
+ :meth:`_sql.ColumnCollection.keys`, :meth:`_sql.ColumnCollection.values`,
1433
+ and :meth:`_sql.ColumnCollection.items` are available, which means that
1434
+ database columns that are keyed under these names also need to use indexed
1435
+ access::
1436
+
1437
+ >>> employee_table.c["values"]
1438
+
1439
+
1440
+ The name for which a :class:`_schema.Column` would be present is normally
1441
+ that of the :paramref:`_schema.Column.key` parameter. In some contexts,
1442
+ such as a :class:`_sql.Select` object that uses a label style set
1443
+ using the :meth:`_sql.Select.set_label_style` method, a column of a certain
1444
+ key may instead be represented under a particular label name such
1445
+ as ``tablename_columnname``::
1446
+
1447
+ >>> from sqlalchemy import select, column, table
1448
+ >>> from sqlalchemy import LABEL_STYLE_TABLENAME_PLUS_COL
1449
+ >>> t = table("t", column("c"))
1450
+ >>> stmt = select(t).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
1451
+ >>> subq = stmt.subquery()
1452
+ >>> subq.c.t_c
1453
+ <sqlalchemy.sql.elements.ColumnClause at 0x7f59dcf04fa0; t_c>
1454
+
1455
+ :class:`.ColumnCollection` also indexes the columns in order and allows
1456
+ them to be accessible by their integer position::
1457
+
1458
+ >>> cc[0]
1459
+ Column('x', Integer(), table=None)
1460
+ >>> cc[1]
1461
+ Column('y', Integer(), table=None)
1462
+
1463
+ .. versionadded:: 1.4 :class:`_expression.ColumnCollection`
1464
+ allows integer-based
1465
+ index access to the collection.
1466
+
1467
+ Iterating the collection yields the column expressions in order::
1468
+
1469
+ >>> list(cc)
1470
+ [Column('x', Integer(), table=None),
1471
+ Column('y', Integer(), table=None)]
1472
+
1473
+ The base :class:`_expression.ColumnCollection` object can store
1474
+ duplicates, which can
1475
+ mean either two columns with the same key, in which case the column
1476
+ returned by key access is **arbitrary**::
1477
+
1478
+ >>> x1, x2 = Column('x', Integer), Column('x', Integer)
1479
+ >>> cc = ColumnCollection(columns=[(x1.name, x1), (x2.name, x2)])
1480
+ >>> list(cc)
1481
+ [Column('x', Integer(), table=None),
1482
+ Column('x', Integer(), table=None)]
1483
+ >>> cc['x'] is x1
1484
+ False
1485
+ >>> cc['x'] is x2
1486
+ True
1487
+
1488
+ Or it can also mean the same column multiple times. These cases are
1489
+ supported as :class:`_expression.ColumnCollection`
1490
+ is used to represent the columns in
1491
+ a SELECT statement which may include duplicates.
1492
+
1493
+ A special subclass :class:`.DedupeColumnCollection` exists which instead
1494
+ maintains SQLAlchemy's older behavior of not allowing duplicates; this
1495
+ collection is used for schema level objects like :class:`_schema.Table`
1496
+ and
1497
+ :class:`.PrimaryKeyConstraint` where this deduping is helpful. The
1498
+ :class:`.DedupeColumnCollection` class also has additional mutation methods
1499
+ as the schema constructs have more use cases that require removal and
1500
+ replacement of columns.
1501
+
1502
+ .. versionchanged:: 1.4 :class:`_expression.ColumnCollection`
1503
+ now stores duplicate
1504
+ column keys as well as the same column in multiple positions. The
1505
+ :class:`.DedupeColumnCollection` class is added to maintain the
1506
+ former behavior in those cases where deduplication as well as
1507
+ additional replace/remove operations are needed.
1508
+
1509
+
1510
+ """
1511
+
1512
+ __slots__ = "_collection", "_index", "_colset", "_proxy_index"
1513
+
1514
+ _collection: List[Tuple[_COLKEY, _COL_co, _ColumnMetrics[_COL_co]]]
1515
+ _index: Dict[Union[None, str, int], Tuple[_COLKEY, _COL_co]]
1516
+ _proxy_index: Dict[ColumnElement[Any], Set[_ColumnMetrics[_COL_co]]]
1517
+ _colset: Set[_COL_co]
1518
+
1519
+ def __init__(
1520
+ self, columns: Optional[Iterable[Tuple[_COLKEY, _COL_co]]] = None
1521
+ ):
1522
+ object.__setattr__(self, "_colset", set())
1523
+ object.__setattr__(self, "_index", {})
1524
+ object.__setattr__(
1525
+ self, "_proxy_index", collections.defaultdict(util.OrderedSet)
1526
+ )
1527
+ object.__setattr__(self, "_collection", [])
1528
+ if columns:
1529
+ self._initial_populate(columns)
1530
+
1531
+ @util.preload_module("sqlalchemy.sql.elements")
1532
+ def __clause_element__(self) -> ClauseList:
1533
+ elements = util.preloaded.sql_elements
1534
+
1535
+ return elements.ClauseList(
1536
+ _literal_as_text_role=roles.ColumnsClauseRole,
1537
+ group=False,
1538
+ *self._all_columns,
1539
+ )
1540
+
1541
+ def _initial_populate(
1542
+ self, iter_: Iterable[Tuple[_COLKEY, _COL_co]]
1543
+ ) -> None:
1544
+ self._populate_separate_keys(iter_)
1545
+
1546
+ @property
1547
+ def _all_columns(self) -> List[_COL_co]:
1548
+ return [col for (_, col, _) in self._collection]
1549
+
1550
+ def keys(self) -> List[_COLKEY]:
1551
+ """Return a sequence of string key names for all columns in this
1552
+ collection."""
1553
+ return [k for (k, _, _) in self._collection]
1554
+
1555
+ def values(self) -> List[_COL_co]:
1556
+ """Return a sequence of :class:`_sql.ColumnClause` or
1557
+ :class:`_schema.Column` objects for all columns in this
1558
+ collection."""
1559
+ return [col for (_, col, _) in self._collection]
1560
+
1561
+ def items(self) -> List[Tuple[_COLKEY, _COL_co]]:
1562
+ """Return a sequence of (key, column) tuples for all columns in this
1563
+ collection each consisting of a string key name and a
1564
+ :class:`_sql.ColumnClause` or
1565
+ :class:`_schema.Column` object.
1566
+ """
1567
+
1568
+ return [(k, col) for (k, col, _) in self._collection]
1569
+
1570
+ def __bool__(self) -> bool:
1571
+ return bool(self._collection)
1572
+
1573
+ def __len__(self) -> int:
1574
+ return len(self._collection)
1575
+
1576
+ def __iter__(self) -> Iterator[_COL_co]:
1577
+ # turn to a list first to maintain over a course of changes
1578
+ return iter([col for _, col, _ in self._collection])
1579
+
1580
+ @overload
1581
+ def __getitem__(self, key: Union[str, int]) -> _COL_co: ...
1582
+
1583
+ @overload
1584
+ def __getitem__(
1585
+ self, key: Tuple[Union[str, int], ...]
1586
+ ) -> ReadOnlyColumnCollection[_COLKEY, _COL_co]: ...
1587
+
1588
+ @overload
1589
+ def __getitem__(
1590
+ self, key: slice
1591
+ ) -> ReadOnlyColumnCollection[_COLKEY, _COL_co]: ...
1592
+
1593
+ def __getitem__(
1594
+ self, key: Union[str, int, slice, Tuple[Union[str, int], ...]]
1595
+ ) -> Union[ReadOnlyColumnCollection[_COLKEY, _COL_co], _COL_co]:
1596
+ try:
1597
+ if isinstance(key, (tuple, slice)):
1598
+ if isinstance(key, slice):
1599
+ cols = (
1600
+ (sub_key, col)
1601
+ for (sub_key, col, _) in self._collection[key]
1602
+ )
1603
+ else:
1604
+ cols = (self._index[sub_key] for sub_key in key)
1605
+
1606
+ return ColumnCollection(cols).as_readonly()
1607
+ else:
1608
+ return self._index[key][1]
1609
+ except KeyError as err:
1610
+ if isinstance(err.args[0], int):
1611
+ raise IndexError(err.args[0]) from err
1612
+ else:
1613
+ raise
1614
+
1615
+ def __getattr__(self, key: str) -> _COL_co:
1616
+ try:
1617
+ return self._index[key][1]
1618
+ except KeyError as err:
1619
+ raise AttributeError(key) from err
1620
+
1621
+ def __contains__(self, key: str) -> bool:
1622
+ if key not in self._index:
1623
+ if not isinstance(key, str):
1624
+ raise exc.ArgumentError(
1625
+ "__contains__ requires a string argument"
1626
+ )
1627
+ return False
1628
+ else:
1629
+ return True
1630
+
1631
+ def compare(self, other: ColumnCollection[Any, Any]) -> bool:
1632
+ """Compare this :class:`_expression.ColumnCollection` to another
1633
+ based on the names of the keys"""
1634
+
1635
+ for l, r in zip_longest(self, other):
1636
+ if l is not r:
1637
+ return False
1638
+ else:
1639
+ return True
1640
+
1641
+ def __eq__(self, other: Any) -> bool:
1642
+ return self.compare(other)
1643
+
1644
+ @overload
1645
+ def get(self, key: str, default: None = None) -> Optional[_COL_co]: ...
1646
+
1647
+ @overload
1648
+ def get(self, key: str, default: _COL) -> Union[_COL_co, _COL]: ...
1649
+
1650
+ def get(
1651
+ self, key: str, default: Optional[_COL] = None
1652
+ ) -> Optional[Union[_COL_co, _COL]]:
1653
+ """Get a :class:`_sql.ColumnClause` or :class:`_schema.Column` object
1654
+ based on a string key name from this
1655
+ :class:`_expression.ColumnCollection`."""
1656
+
1657
+ if key in self._index:
1658
+ return self._index[key][1]
1659
+ else:
1660
+ return default
1661
+
1662
+ def __str__(self) -> str:
1663
+ return "%s(%s)" % (
1664
+ self.__class__.__name__,
1665
+ ", ".join(str(c) for c in self),
1666
+ )
1667
+
1668
+ def __setitem__(self, key: str, value: Any) -> NoReturn:
1669
+ raise NotImplementedError()
1670
+
1671
+ def __delitem__(self, key: str) -> NoReturn:
1672
+ raise NotImplementedError()
1673
+
1674
+ def __setattr__(self, key: str, obj: Any) -> NoReturn:
1675
+ raise NotImplementedError()
1676
+
1677
+ def clear(self) -> NoReturn:
1678
+ """Dictionary clear() is not implemented for
1679
+ :class:`_sql.ColumnCollection`."""
1680
+ raise NotImplementedError()
1681
+
1682
+ def remove(self, column: Any) -> None:
1683
+ raise NotImplementedError()
1684
+
1685
+ def update(self, iter_: Any) -> NoReturn:
1686
+ """Dictionary update() is not implemented for
1687
+ :class:`_sql.ColumnCollection`."""
1688
+ raise NotImplementedError()
1689
+
1690
+ # https://github.com/python/mypy/issues/4266
1691
+ __hash__ = None # type: ignore
1692
+
1693
+ def _populate_separate_keys(
1694
+ self, iter_: Iterable[Tuple[_COLKEY, _COL_co]]
1695
+ ) -> None:
1696
+ """populate from an iterator of (key, column)"""
1697
+
1698
+ self._collection[:] = collection = [
1699
+ (k, c, _ColumnMetrics(self, c)) for k, c in iter_
1700
+ ]
1701
+ self._colset.update(c._deannotate() for _, c, _ in collection)
1702
+ self._index.update(
1703
+ {idx: (k, c) for idx, (k, c, _) in enumerate(collection)}
1704
+ )
1705
+ self._index.update({k: (k, col) for k, col, _ in reversed(collection)})
1706
+
1707
+ def add(
1708
+ self, column: ColumnElement[Any], key: Optional[_COLKEY] = None
1709
+ ) -> None:
1710
+ """Add a column to this :class:`_sql.ColumnCollection`.
1711
+
1712
+ .. note::
1713
+
1714
+ This method is **not normally used by user-facing code**, as the
1715
+ :class:`_sql.ColumnCollection` is usually part of an existing
1716
+ object such as a :class:`_schema.Table`. To add a
1717
+ :class:`_schema.Column` to an existing :class:`_schema.Table`
1718
+ object, use the :meth:`_schema.Table.append_column` method.
1719
+
1720
+ """
1721
+ colkey: _COLKEY
1722
+
1723
+ if key is None:
1724
+ colkey = column.key # type: ignore
1725
+ else:
1726
+ colkey = key
1727
+
1728
+ l = len(self._collection)
1729
+
1730
+ # don't really know how this part is supposed to work w/ the
1731
+ # covariant thing
1732
+
1733
+ _column = cast(_COL_co, column)
1734
+
1735
+ self._collection.append(
1736
+ (colkey, _column, _ColumnMetrics(self, _column))
1737
+ )
1738
+ self._colset.add(_column._deannotate())
1739
+ self._index[l] = (colkey, _column)
1740
+ if colkey not in self._index:
1741
+ self._index[colkey] = (colkey, _column)
1742
+
1743
+ def __getstate__(self) -> Dict[str, Any]:
1744
+ return {
1745
+ "_collection": [(k, c) for k, c, _ in self._collection],
1746
+ "_index": self._index,
1747
+ }
1748
+
1749
+ def __setstate__(self, state: Dict[str, Any]) -> None:
1750
+ object.__setattr__(self, "_index", state["_index"])
1751
+ object.__setattr__(
1752
+ self, "_proxy_index", collections.defaultdict(util.OrderedSet)
1753
+ )
1754
+ object.__setattr__(
1755
+ self,
1756
+ "_collection",
1757
+ [
1758
+ (k, c, _ColumnMetrics(self, c))
1759
+ for (k, c) in state["_collection"]
1760
+ ],
1761
+ )
1762
+ object.__setattr__(
1763
+ self, "_colset", {col for k, col, _ in self._collection}
1764
+ )
1765
+
1766
+ def contains_column(self, col: ColumnElement[Any]) -> bool:
1767
+ """Checks if a column object exists in this collection"""
1768
+ if col not in self._colset:
1769
+ if isinstance(col, str):
1770
+ raise exc.ArgumentError(
1771
+ "contains_column cannot be used with string arguments. "
1772
+ "Use ``col_name in table.c`` instead."
1773
+ )
1774
+ return False
1775
+ else:
1776
+ return True
1777
+
1778
+ def as_readonly(self) -> ReadOnlyColumnCollection[_COLKEY, _COL_co]:
1779
+ """Return a "read only" form of this
1780
+ :class:`_sql.ColumnCollection`."""
1781
+
1782
+ return ReadOnlyColumnCollection(self)
1783
+
1784
+ def _init_proxy_index(self):
1785
+ """populate the "proxy index", if empty.
1786
+
1787
+ proxy index is added in 2.0 to provide more efficient operation
1788
+ for the corresponding_column() method.
1789
+
1790
+ For reasons of both time to construct new .c collections as well as
1791
+ memory conservation for large numbers of large .c collections, the
1792
+ proxy_index is only filled if corresponding_column() is called. once
1793
+ filled it stays that way, and new _ColumnMetrics objects created after
1794
+ that point will populate it with new data. Note this case would be
1795
+ unusual, if not nonexistent, as it means a .c collection is being
1796
+ mutated after corresponding_column() were used, however it is tested in
1797
+ test/base/test_utils.py.
1798
+
1799
+ """
1800
+ pi = self._proxy_index
1801
+ if pi:
1802
+ return
1803
+
1804
+ for _, _, metrics in self._collection:
1805
+ eps = metrics.column._expanded_proxy_set
1806
+
1807
+ for eps_col in eps:
1808
+ pi[eps_col].add(metrics)
1809
+
1810
+ def corresponding_column(
1811
+ self, column: _COL, require_embedded: bool = False
1812
+ ) -> Optional[Union[_COL, _COL_co]]:
1813
+ """Given a :class:`_expression.ColumnElement`, return the exported
1814
+ :class:`_expression.ColumnElement` object from this
1815
+ :class:`_expression.ColumnCollection`
1816
+ which corresponds to that original :class:`_expression.ColumnElement`
1817
+ via a common
1818
+ ancestor column.
1819
+
1820
+ :param column: the target :class:`_expression.ColumnElement`
1821
+ to be matched.
1822
+
1823
+ :param require_embedded: only return corresponding columns for
1824
+ the given :class:`_expression.ColumnElement`, if the given
1825
+ :class:`_expression.ColumnElement`
1826
+ is actually present within a sub-element
1827
+ of this :class:`_expression.Selectable`.
1828
+ Normally the column will match if
1829
+ it merely shares a common ancestor with one of the exported
1830
+ columns of this :class:`_expression.Selectable`.
1831
+
1832
+ .. seealso::
1833
+
1834
+ :meth:`_expression.Selectable.corresponding_column`
1835
+ - invokes this method
1836
+ against the collection returned by
1837
+ :attr:`_expression.Selectable.exported_columns`.
1838
+
1839
+ .. versionchanged:: 1.4 the implementation for ``corresponding_column``
1840
+ was moved onto the :class:`_expression.ColumnCollection` itself.
1841
+
1842
+ """
1843
+ # TODO: cython candidate
1844
+
1845
+ # don't dig around if the column is locally present
1846
+ if column in self._colset:
1847
+ return column
1848
+
1849
+ selected_intersection, selected_metrics = None, None
1850
+ target_set = column.proxy_set
1851
+
1852
+ pi = self._proxy_index
1853
+ if not pi:
1854
+ self._init_proxy_index()
1855
+
1856
+ for current_metrics in (
1857
+ mm for ts in target_set if ts in pi for mm in pi[ts]
1858
+ ):
1859
+ if not require_embedded or current_metrics.embedded(target_set):
1860
+ if selected_metrics is None:
1861
+ # no corresponding column yet, pick this one.
1862
+ selected_metrics = current_metrics
1863
+ continue
1864
+
1865
+ current_intersection = target_set.intersection(
1866
+ current_metrics.column._expanded_proxy_set
1867
+ )
1868
+ if selected_intersection is None:
1869
+ selected_intersection = target_set.intersection(
1870
+ selected_metrics.column._expanded_proxy_set
1871
+ )
1872
+
1873
+ if len(current_intersection) > len(selected_intersection):
1874
+ # 'current' has a larger field of correspondence than
1875
+ # 'selected'. i.e. selectable.c.a1_x->a1.c.x->table.c.x
1876
+ # matches a1.c.x->table.c.x better than
1877
+ # selectable.c.x->table.c.x does.
1878
+
1879
+ selected_metrics = current_metrics
1880
+ selected_intersection = current_intersection
1881
+ elif current_intersection == selected_intersection:
1882
+ # they have the same field of correspondence. see
1883
+ # which proxy_set has fewer columns in it, which
1884
+ # indicates a closer relationship with the root
1885
+ # column. Also take into account the "weight"
1886
+ # attribute which CompoundSelect() uses to give
1887
+ # higher precedence to columns based on vertical
1888
+ # position in the compound statement, and discard
1889
+ # columns that have no reference to the target
1890
+ # column (also occurs with CompoundSelect)
1891
+
1892
+ selected_col_distance = sum(
1893
+ [
1894
+ sc._annotations.get("weight", 1)
1895
+ for sc in (
1896
+ selected_metrics.column._uncached_proxy_list()
1897
+ )
1898
+ if sc.shares_lineage(column)
1899
+ ],
1900
+ )
1901
+ current_col_distance = sum(
1902
+ [
1903
+ sc._annotations.get("weight", 1)
1904
+ for sc in (
1905
+ current_metrics.column._uncached_proxy_list()
1906
+ )
1907
+ if sc.shares_lineage(column)
1908
+ ],
1909
+ )
1910
+ if current_col_distance < selected_col_distance:
1911
+ selected_metrics = current_metrics
1912
+ selected_intersection = current_intersection
1913
+
1914
+ return selected_metrics.column if selected_metrics else None
1915
+
1916
+
1917
+ _NAMEDCOL = TypeVar("_NAMEDCOL", bound="NamedColumn[Any]")
1918
+
1919
+
1920
+ class DedupeColumnCollection(ColumnCollection[str, _NAMEDCOL]):
1921
+ """A :class:`_expression.ColumnCollection`
1922
+ that maintains deduplicating behavior.
1923
+
1924
+ This is useful by schema level objects such as :class:`_schema.Table` and
1925
+ :class:`.PrimaryKeyConstraint`. The collection includes more
1926
+ sophisticated mutator methods as well to suit schema objects which
1927
+ require mutable column collections.
1928
+
1929
+ .. versionadded:: 1.4
1930
+
1931
+ """
1932
+
1933
+ def add( # type: ignore[override]
1934
+ self, column: _NAMEDCOL, key: Optional[str] = None
1935
+ ) -> None:
1936
+ if key is not None and column.key != key:
1937
+ raise exc.ArgumentError(
1938
+ "DedupeColumnCollection requires columns be under "
1939
+ "the same key as their .key"
1940
+ )
1941
+ key = column.key
1942
+
1943
+ if key is None:
1944
+ raise exc.ArgumentError(
1945
+ "Can't add unnamed column to column collection"
1946
+ )
1947
+
1948
+ if key in self._index:
1949
+ existing = self._index[key][1]
1950
+
1951
+ if existing is column:
1952
+ return
1953
+
1954
+ self.replace(column)
1955
+
1956
+ # pop out memoized proxy_set as this
1957
+ # operation may very well be occurring
1958
+ # in a _make_proxy operation
1959
+ util.memoized_property.reset(column, "proxy_set")
1960
+ else:
1961
+ self._append_new_column(key, column)
1962
+
1963
+ def _append_new_column(self, key: str, named_column: _NAMEDCOL) -> None:
1964
+ l = len(self._collection)
1965
+ self._collection.append(
1966
+ (key, named_column, _ColumnMetrics(self, named_column))
1967
+ )
1968
+ self._colset.add(named_column._deannotate())
1969
+ self._index[l] = (key, named_column)
1970
+ self._index[key] = (key, named_column)
1971
+
1972
+ def _populate_separate_keys(
1973
+ self, iter_: Iterable[Tuple[str, _NAMEDCOL]]
1974
+ ) -> None:
1975
+ """populate from an iterator of (key, column)"""
1976
+ cols = list(iter_)
1977
+
1978
+ replace_col = []
1979
+ for k, col in cols:
1980
+ if col.key != k:
1981
+ raise exc.ArgumentError(
1982
+ "DedupeColumnCollection requires columns be under "
1983
+ "the same key as their .key"
1984
+ )
1985
+ if col.name in self._index and col.key != col.name:
1986
+ replace_col.append(col)
1987
+ elif col.key in self._index:
1988
+ replace_col.append(col)
1989
+ else:
1990
+ self._index[k] = (k, col)
1991
+ self._collection.append((k, col, _ColumnMetrics(self, col)))
1992
+ self._colset.update(c._deannotate() for (k, c, _) in self._collection)
1993
+
1994
+ self._index.update(
1995
+ (idx, (k, c)) for idx, (k, c, _) in enumerate(self._collection)
1996
+ )
1997
+ for col in replace_col:
1998
+ self.replace(col)
1999
+
2000
+ def extend(self, iter_: Iterable[_NAMEDCOL]) -> None:
2001
+ self._populate_separate_keys((col.key, col) for col in iter_)
2002
+
2003
+ def remove(self, column: _NAMEDCOL) -> None:
2004
+ if column not in self._colset:
2005
+ raise ValueError(
2006
+ "Can't remove column %r; column is not in this collection"
2007
+ % column
2008
+ )
2009
+ del self._index[column.key]
2010
+ self._colset.remove(column)
2011
+ self._collection[:] = [
2012
+ (k, c, metrics)
2013
+ for (k, c, metrics) in self._collection
2014
+ if c is not column
2015
+ ]
2016
+ for metrics in self._proxy_index.get(column, ()):
2017
+ metrics.dispose(self)
2018
+
2019
+ self._index.update(
2020
+ {idx: (k, col) for idx, (k, col, _) in enumerate(self._collection)}
2021
+ )
2022
+ # delete higher index
2023
+ del self._index[len(self._collection)]
2024
+
2025
+ def replace(
2026
+ self,
2027
+ column: _NAMEDCOL,
2028
+ extra_remove: Optional[Iterable[_NAMEDCOL]] = None,
2029
+ ) -> None:
2030
+ """add the given column to this collection, removing unaliased
2031
+ versions of this column as well as existing columns with the
2032
+ same key.
2033
+
2034
+ e.g.::
2035
+
2036
+ t = Table('sometable', metadata, Column('col1', Integer))
2037
+ t.columns.replace(Column('col1', Integer, key='columnone'))
2038
+
2039
+ will remove the original 'col1' from the collection, and add
2040
+ the new column under the name 'columnname'.
2041
+
2042
+ Used by schema.Column to override columns during table reflection.
2043
+
2044
+ """
2045
+
2046
+ if extra_remove:
2047
+ remove_col = set(extra_remove)
2048
+ else:
2049
+ remove_col = set()
2050
+ # remove up to two columns based on matches of name as well as key
2051
+ if column.name in self._index and column.key != column.name:
2052
+ other = self._index[column.name][1]
2053
+ if other.name == other.key:
2054
+ remove_col.add(other)
2055
+
2056
+ if column.key in self._index:
2057
+ remove_col.add(self._index[column.key][1])
2058
+
2059
+ if not remove_col:
2060
+ self._append_new_column(column.key, column)
2061
+ return
2062
+ new_cols: List[Tuple[str, _NAMEDCOL, _ColumnMetrics[_NAMEDCOL]]] = []
2063
+ replaced = False
2064
+ for k, col, metrics in self._collection:
2065
+ if col in remove_col:
2066
+ if not replaced:
2067
+ replaced = True
2068
+ new_cols.append(
2069
+ (column.key, column, _ColumnMetrics(self, column))
2070
+ )
2071
+ else:
2072
+ new_cols.append((k, col, metrics))
2073
+
2074
+ if remove_col:
2075
+ self._colset.difference_update(remove_col)
2076
+
2077
+ for rc in remove_col:
2078
+ for metrics in self._proxy_index.get(rc, ()):
2079
+ metrics.dispose(self)
2080
+
2081
+ if not replaced:
2082
+ new_cols.append((column.key, column, _ColumnMetrics(self, column)))
2083
+
2084
+ self._colset.add(column._deannotate())
2085
+ self._collection[:] = new_cols
2086
+
2087
+ self._index.clear()
2088
+
2089
+ self._index.update(
2090
+ {idx: (k, col) for idx, (k, col, _) in enumerate(self._collection)}
2091
+ )
2092
+ self._index.update({k: (k, col) for (k, col, _) in self._collection})
2093
+
2094
+
2095
+ class ReadOnlyColumnCollection(
2096
+ util.ReadOnlyContainer, ColumnCollection[_COLKEY, _COL_co]
2097
+ ):
2098
+ __slots__ = ("_parent",)
2099
+
2100
+ def __init__(self, collection):
2101
+ object.__setattr__(self, "_parent", collection)
2102
+ object.__setattr__(self, "_colset", collection._colset)
2103
+ object.__setattr__(self, "_index", collection._index)
2104
+ object.__setattr__(self, "_collection", collection._collection)
2105
+ object.__setattr__(self, "_proxy_index", collection._proxy_index)
2106
+
2107
+ def __getstate__(self):
2108
+ return {"_parent": self._parent}
2109
+
2110
+ def __setstate__(self, state):
2111
+ parent = state["_parent"]
2112
+ self.__init__(parent) # type: ignore
2113
+
2114
+ def add(self, column: Any, key: Any = ...) -> Any:
2115
+ self._readonly()
2116
+
2117
+ def extend(self, elements: Any) -> NoReturn:
2118
+ self._readonly()
2119
+
2120
+ def remove(self, item: Any) -> NoReturn:
2121
+ self._readonly()
2122
+
2123
+
2124
+ class ColumnSet(util.OrderedSet["ColumnClause[Any]"]):
2125
+ def contains_column(self, col):
2126
+ return col in self
2127
+
2128
+ def extend(self, cols):
2129
+ for col in cols:
2130
+ self.add(col)
2131
+
2132
+ def __eq__(self, other):
2133
+ l = []
2134
+ for c in other:
2135
+ for local in self:
2136
+ if c.shares_lineage(local):
2137
+ l.append(c == local)
2138
+ return elements.and_(*l)
2139
+
2140
+ def __hash__(self): # type: ignore[override]
2141
+ return hash(tuple(x for x in self))
2142
+
2143
+
2144
+ def _entity_namespace(
2145
+ entity: Union[_HasEntityNamespace, ExternallyTraversible]
2146
+ ) -> _EntityNamespace:
2147
+ """Return the nearest .entity_namespace for the given entity.
2148
+
2149
+ If not immediately available, does an iterate to find a sub-element
2150
+ that has one, if any.
2151
+
2152
+ """
2153
+ try:
2154
+ return cast(_HasEntityNamespace, entity).entity_namespace
2155
+ except AttributeError:
2156
+ for elem in visitors.iterate(cast(ExternallyTraversible, entity)):
2157
+ if _is_has_entity_namespace(elem):
2158
+ return elem.entity_namespace
2159
+ else:
2160
+ raise
2161
+
2162
+
2163
+ def _entity_namespace_key(
2164
+ entity: Union[_HasEntityNamespace, ExternallyTraversible],
2165
+ key: str,
2166
+ default: Union[SQLCoreOperations[Any], _NoArg] = NO_ARG,
2167
+ ) -> SQLCoreOperations[Any]:
2168
+ """Return an entry from an entity_namespace.
2169
+
2170
+
2171
+ Raises :class:`_exc.InvalidRequestError` rather than attribute error
2172
+ on not found.
2173
+
2174
+ """
2175
+
2176
+ try:
2177
+ ns = _entity_namespace(entity)
2178
+ if default is not NO_ARG:
2179
+ return getattr(ns, key, default)
2180
+ else:
2181
+ return getattr(ns, key) # type: ignore
2182
+ except AttributeError as err:
2183
+ raise exc.InvalidRequestError(
2184
+ 'Entity namespace for "%s" has no property "%s"' % (entity, key)
2185
+ ) from err