SQLAlchemy 2.0.47__cp313-cp313t-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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-win_amd64.pyd +0 -0
  8. sqlalchemy/cyextension/collections.pyx +409 -0
  9. sqlalchemy/cyextension/immutabledict.cp313t-win_amd64.pyd +0 -0
  10. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  11. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  12. sqlalchemy/cyextension/processors.cp313t-win_amd64.pyd +0 -0
  13. sqlalchemy/cyextension/processors.pyx +68 -0
  14. sqlalchemy/cyextension/resultproxy.cp313t-win_amd64.pyd +0 -0
  15. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  16. sqlalchemy/cyextension/util.cp313t-win_amd64.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,1164 @@
1
+ # sql/visitors.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
+ """Visitor/traversal interface and library functions."""
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections import deque
13
+ from enum import Enum
14
+ import itertools
15
+ import operator
16
+ import typing
17
+ from typing import Any
18
+ from typing import Callable
19
+ from typing import cast
20
+ from typing import ClassVar
21
+ from typing import Dict
22
+ from typing import Iterable
23
+ from typing import Iterator
24
+ from typing import List
25
+ from typing import Mapping
26
+ from typing import Optional
27
+ from typing import overload
28
+ from typing import Tuple
29
+ from typing import Type
30
+ from typing import TYPE_CHECKING
31
+ from typing import TypeVar
32
+ from typing import Union
33
+
34
+ from .. import exc
35
+ from .. import util
36
+ from ..util import langhelpers
37
+ from ..util._has_cy import HAS_CYEXTENSION
38
+ from ..util.typing import Literal
39
+ from ..util.typing import Protocol
40
+ from ..util.typing import Self
41
+
42
+ if TYPE_CHECKING:
43
+ from .annotation import _AnnotationDict
44
+ from .elements import ColumnElement
45
+
46
+ if typing.TYPE_CHECKING or not HAS_CYEXTENSION:
47
+ from ._py_util import prefix_anon_map as prefix_anon_map
48
+ from ._py_util import cache_anon_map as anon_map
49
+ else:
50
+ from sqlalchemy.cyextension.util import ( # noqa: F401,E501
51
+ prefix_anon_map as prefix_anon_map,
52
+ )
53
+ from sqlalchemy.cyextension.util import ( # noqa: F401,E501
54
+ cache_anon_map as anon_map,
55
+ )
56
+
57
+
58
+ __all__ = [
59
+ "iterate",
60
+ "traverse_using",
61
+ "traverse",
62
+ "cloned_traverse",
63
+ "replacement_traverse",
64
+ "Visitable",
65
+ "ExternalTraversal",
66
+ "InternalTraversal",
67
+ "anon_map",
68
+ ]
69
+
70
+
71
+ class _CompilerDispatchType(Protocol):
72
+ def __call__(_self, self: Visitable, visitor: Any, **kw: Any) -> Any: ...
73
+
74
+
75
+ class Visitable:
76
+ """Base class for visitable objects.
77
+
78
+ :class:`.Visitable` is used to implement the SQL compiler dispatch
79
+ functions. Other forms of traversal such as for cache key generation
80
+ are implemented separately using the :class:`.HasTraverseInternals`
81
+ interface.
82
+
83
+ .. versionchanged:: 2.0 The :class:`.Visitable` class was named
84
+ :class:`.Traversible` in the 1.4 series; the name is changed back
85
+ to :class:`.Visitable` in 2.0 which is what it was prior to 1.4.
86
+
87
+ Both names remain importable in both 1.4 and 2.0 versions.
88
+
89
+ """
90
+
91
+ __slots__ = ()
92
+
93
+ __visit_name__: str
94
+
95
+ _original_compiler_dispatch: _CompilerDispatchType
96
+
97
+ if typing.TYPE_CHECKING:
98
+
99
+ def _compiler_dispatch(self, visitor: Any, **kw: Any) -> str: ...
100
+
101
+ def __init_subclass__(cls) -> None:
102
+ if "__visit_name__" in cls.__dict__:
103
+ cls._generate_compiler_dispatch()
104
+ super().__init_subclass__()
105
+
106
+ @classmethod
107
+ def _generate_compiler_dispatch(cls) -> None:
108
+ visit_name = cls.__visit_name__
109
+
110
+ if "_compiler_dispatch" in cls.__dict__:
111
+ # class has a fixed _compiler_dispatch() method.
112
+ # copy it to "original" so that we can get it back if
113
+ # sqlalchemy.ext.compiles overrides it.
114
+ cls._original_compiler_dispatch = cls._compiler_dispatch
115
+ return
116
+
117
+ if not isinstance(visit_name, str):
118
+ raise exc.InvalidRequestError(
119
+ f"__visit_name__ on class {cls.__name__} must be a string "
120
+ "at the class level"
121
+ )
122
+
123
+ name = "visit_%s" % visit_name
124
+ getter = operator.attrgetter(name)
125
+
126
+ def _compiler_dispatch(
127
+ self: Visitable, visitor: Any, **kw: Any
128
+ ) -> str:
129
+ """Look for an attribute named "visit_<visit_name>" on the
130
+ visitor, and call it with the same kw params.
131
+
132
+ """
133
+ try:
134
+ meth = getter(visitor)
135
+ except AttributeError as err:
136
+ return visitor.visit_unsupported_compilation(self, err, **kw) # type: ignore # noqa: E501
137
+ else:
138
+ return meth(self, **kw) # type: ignore # noqa: E501
139
+
140
+ cls._compiler_dispatch = ( # type: ignore
141
+ cls._original_compiler_dispatch
142
+ ) = _compiler_dispatch
143
+
144
+ def __class_getitem__(cls, key: Any) -> Any:
145
+ # allow generic classes in py3.9+
146
+ return cls
147
+
148
+
149
+ class InternalTraversal(Enum):
150
+ r"""Defines visitor symbols used for internal traversal.
151
+
152
+ The :class:`.InternalTraversal` class is used in two ways. One is that
153
+ it can serve as the superclass for an object that implements the
154
+ various visit methods of the class. The other is that the symbols
155
+ themselves of :class:`.InternalTraversal` are used within
156
+ the ``_traverse_internals`` collection. Such as, the :class:`.Case`
157
+ object defines ``_traverse_internals`` as ::
158
+
159
+ class Case(ColumnElement[_T]):
160
+ _traverse_internals = [
161
+ ("value", InternalTraversal.dp_clauseelement),
162
+ ("whens", InternalTraversal.dp_clauseelement_tuples),
163
+ ("else_", InternalTraversal.dp_clauseelement),
164
+ ]
165
+
166
+ Above, the :class:`.Case` class indicates its internal state as the
167
+ attributes named ``value``, ``whens``, and ``else_``. They each
168
+ link to an :class:`.InternalTraversal` method which indicates the type
169
+ of datastructure to which each attribute refers.
170
+
171
+ Using the ``_traverse_internals`` structure, objects of type
172
+ :class:`.InternalTraversible` will have the following methods automatically
173
+ implemented:
174
+
175
+ * :meth:`.HasTraverseInternals.get_children`
176
+
177
+ * :meth:`.HasTraverseInternals._copy_internals`
178
+
179
+ * :meth:`.HasCacheKey._gen_cache_key`
180
+
181
+ Subclasses can also implement these methods directly, particularly for the
182
+ :meth:`.HasTraverseInternals._copy_internals` method, when special steps
183
+ are needed.
184
+
185
+ .. versionadded:: 1.4
186
+
187
+ """
188
+
189
+ dp_has_cache_key = "HC"
190
+ """Visit a :class:`.HasCacheKey` object."""
191
+
192
+ dp_has_cache_key_list = "HL"
193
+ """Visit a list of :class:`.HasCacheKey` objects."""
194
+
195
+ dp_clauseelement = "CE"
196
+ """Visit a :class:`_expression.ClauseElement` object."""
197
+
198
+ dp_fromclause_canonical_column_collection = "FC"
199
+ """Visit a :class:`_expression.FromClause` object in the context of the
200
+ ``columns`` attribute.
201
+
202
+ The column collection is "canonical", meaning it is the originally
203
+ defined location of the :class:`.ColumnClause` objects. Right now
204
+ this means that the object being visited is a
205
+ :class:`_expression.TableClause`
206
+ or :class:`_schema.Table` object only.
207
+
208
+ """
209
+
210
+ dp_clauseelement_tuples = "CTS"
211
+ """Visit a list of tuples which contain :class:`_expression.ClauseElement`
212
+ objects.
213
+
214
+ """
215
+
216
+ dp_clauseelement_list = "CL"
217
+ """Visit a list of :class:`_expression.ClauseElement` objects.
218
+
219
+ """
220
+
221
+ dp_clauseelement_tuple = "CT"
222
+ """Visit a tuple of :class:`_expression.ClauseElement` objects.
223
+
224
+ """
225
+
226
+ dp_executable_options = "EO"
227
+
228
+ dp_with_context_options = "WC"
229
+
230
+ dp_fromclause_ordered_set = "CO"
231
+ """Visit an ordered set of :class:`_expression.FromClause` objects. """
232
+
233
+ dp_string = "S"
234
+ """Visit a plain string value.
235
+
236
+ Examples include table and column names, bound parameter keys, special
237
+ keywords such as "UNION", "UNION ALL".
238
+
239
+ The string value is considered to be significant for cache key
240
+ generation.
241
+
242
+ """
243
+
244
+ dp_string_list = "SL"
245
+ """Visit a list of strings."""
246
+
247
+ dp_anon_name = "AN"
248
+ """Visit a potentially "anonymized" string value.
249
+
250
+ The string value is considered to be significant for cache key
251
+ generation.
252
+
253
+ """
254
+
255
+ dp_boolean = "B"
256
+ """Visit a boolean value.
257
+
258
+ The boolean value is considered to be significant for cache key
259
+ generation.
260
+
261
+ """
262
+
263
+ dp_operator = "O"
264
+ """Visit an operator.
265
+
266
+ The operator is a function from the :mod:`sqlalchemy.sql.operators`
267
+ module.
268
+
269
+ The operator value is considered to be significant for cache key
270
+ generation.
271
+
272
+ """
273
+
274
+ dp_type = "T"
275
+ """Visit a :class:`.TypeEngine` object
276
+
277
+ The type object is considered to be significant for cache key
278
+ generation.
279
+
280
+ """
281
+
282
+ dp_plain_dict = "PD"
283
+ """Visit a dictionary with string keys.
284
+
285
+ The keys of the dictionary should be strings, the values should
286
+ be immutable and hashable. The dictionary is considered to be
287
+ significant for cache key generation.
288
+
289
+ """
290
+
291
+ dp_dialect_options = "DO"
292
+ """Visit a dialect options structure."""
293
+
294
+ dp_string_clauseelement_dict = "CD"
295
+ """Visit a dictionary of string keys to :class:`_expression.ClauseElement`
296
+ objects.
297
+
298
+ """
299
+
300
+ dp_string_multi_dict = "MD"
301
+ """Visit a dictionary of string keys to values which may either be
302
+ plain immutable/hashable or :class:`.HasCacheKey` objects.
303
+
304
+ """
305
+
306
+ dp_annotations_key = "AK"
307
+ """Visit the _annotations_cache_key element.
308
+
309
+ This is a dictionary of additional information about a ClauseElement
310
+ that modifies its role. It should be included when comparing or caching
311
+ objects, however generating this key is relatively expensive. Visitors
312
+ should check the "_annotations" dict for non-None first before creating
313
+ this key.
314
+
315
+ """
316
+
317
+ dp_plain_obj = "PO"
318
+ """Visit a plain python object.
319
+
320
+ The value should be immutable and hashable, such as an integer.
321
+ The value is considered to be significant for cache key generation.
322
+
323
+ """
324
+
325
+ dp_named_ddl_element = "DD"
326
+ """Visit a simple named DDL element.
327
+
328
+ The current object used by this method is the :class:`.Sequence`.
329
+
330
+ The object is only considered to be important for cache key generation
331
+ as far as its name, but not any other aspects of it.
332
+
333
+ """
334
+
335
+ dp_prefix_sequence = "PS"
336
+ """Visit the sequence represented by :class:`_expression.HasPrefixes`
337
+ or :class:`_expression.HasSuffixes`.
338
+
339
+ """
340
+
341
+ dp_table_hint_list = "TH"
342
+ """Visit the ``_hints`` collection of a :class:`_expression.Select`
343
+ object.
344
+
345
+ """
346
+
347
+ dp_setup_join_tuple = "SJ"
348
+
349
+ dp_memoized_select_entities = "ME"
350
+
351
+ dp_statement_hint_list = "SH"
352
+ """Visit the ``_statement_hints`` collection of a
353
+ :class:`_expression.Select`
354
+ object.
355
+
356
+ """
357
+
358
+ dp_unknown_structure = "UK"
359
+ """Visit an unknown structure.
360
+
361
+ """
362
+
363
+ dp_dml_ordered_values = "DML_OV"
364
+ """Visit the values() ordered tuple list of an
365
+ :class:`_expression.Update` object."""
366
+
367
+ dp_dml_values = "DML_V"
368
+ """Visit the values() dictionary of a :class:`.ValuesBase`
369
+ (e.g. Insert or Update) object.
370
+
371
+ """
372
+
373
+ dp_dml_multi_values = "DML_MV"
374
+ """Visit the values() multi-valued list of dictionaries of an
375
+ :class:`_expression.Insert` object.
376
+
377
+ """
378
+
379
+ dp_propagate_attrs = "PA"
380
+ """Visit the propagate attrs dict. This hardcodes to the particular
381
+ elements we care about right now."""
382
+
383
+ """Symbols that follow are additional symbols that are useful in
384
+ caching applications.
385
+
386
+ Traversals for :class:`_expression.ClauseElement` objects only need to use
387
+ those symbols present in :class:`.InternalTraversal`. However, for
388
+ additional caching use cases within the ORM, symbols dealing with the
389
+ :class:`.HasCacheKey` class are added here.
390
+
391
+ """
392
+
393
+ dp_ignore = "IG"
394
+ """Specify an object that should be ignored entirely.
395
+
396
+ This currently applies function call argument caching where some
397
+ arguments should not be considered to be part of a cache key.
398
+
399
+ """
400
+
401
+ dp_inspectable = "IS"
402
+ """Visit an inspectable object where the return value is a
403
+ :class:`.HasCacheKey` object."""
404
+
405
+ dp_multi = "M"
406
+ """Visit an object that may be a :class:`.HasCacheKey` or may be a
407
+ plain hashable object."""
408
+
409
+ dp_multi_list = "MT"
410
+ """Visit a tuple containing elements that may be :class:`.HasCacheKey` or
411
+ may be a plain hashable object."""
412
+
413
+ dp_has_cache_key_tuples = "HT"
414
+ """Visit a list of tuples which contain :class:`.HasCacheKey`
415
+ objects.
416
+
417
+ """
418
+
419
+ dp_inspectable_list = "IL"
420
+ """Visit a list of inspectable objects which upon inspection are
421
+ HasCacheKey objects."""
422
+
423
+
424
+ _TraverseInternalsType = List[Tuple[str, InternalTraversal]]
425
+ """a structure that defines how a HasTraverseInternals should be
426
+ traversed.
427
+
428
+ This structure consists of a list of (attributename, internaltraversal)
429
+ tuples, where the "attributename" refers to the name of an attribute on an
430
+ instance of the HasTraverseInternals object, and "internaltraversal" refers
431
+ to an :class:`.InternalTraversal` enumeration symbol defining what kind
432
+ of data this attribute stores, which indicates to the traverser how it should
433
+ be handled.
434
+
435
+ """
436
+
437
+
438
+ class HasTraverseInternals:
439
+ """base for classes that have a "traverse internals" element,
440
+ which defines all kinds of ways of traversing the elements of an object.
441
+
442
+ Compared to :class:`.Visitable`, which relies upon an external visitor to
443
+ define how the object is traversed (i.e. the :class:`.SQLCompiler`), the
444
+ :class:`.HasTraverseInternals` interface allows classes to define their own
445
+ traversal, that is, what attributes are accessed and in what order.
446
+
447
+ """
448
+
449
+ __slots__ = ()
450
+
451
+ _traverse_internals: _TraverseInternalsType
452
+
453
+ _is_immutable: bool = False
454
+
455
+ @util.preload_module("sqlalchemy.sql.traversals")
456
+ def get_children(
457
+ self, *, omit_attrs: Tuple[str, ...] = (), **kw: Any
458
+ ) -> Iterable[HasTraverseInternals]:
459
+ r"""Return immediate child :class:`.visitors.HasTraverseInternals`
460
+ elements of this :class:`.visitors.HasTraverseInternals`.
461
+
462
+ This is used for visit traversal.
463
+
464
+ \**kw may contain flags that change the collection that is
465
+ returned, for example to return a subset of items in order to
466
+ cut down on larger traversals, or to return child items from a
467
+ different context (such as schema-level collections instead of
468
+ clause-level).
469
+
470
+ """
471
+
472
+ traversals = util.preloaded.sql_traversals
473
+
474
+ try:
475
+ traverse_internals = self._traverse_internals
476
+ except AttributeError:
477
+ # user-defined classes may not have a _traverse_internals
478
+ return []
479
+
480
+ dispatch = traversals._get_children.run_generated_dispatch
481
+ return itertools.chain.from_iterable(
482
+ meth(obj, **kw)
483
+ for attrname, obj, meth in dispatch(
484
+ self, traverse_internals, "_generated_get_children_traversal"
485
+ )
486
+ if attrname not in omit_attrs and obj is not None
487
+ )
488
+
489
+
490
+ class _InternalTraversalDispatchType(Protocol):
491
+ def __call__(s, self: object, visitor: HasTraversalDispatch) -> Any: ...
492
+
493
+
494
+ class HasTraversalDispatch:
495
+ r"""Define infrastructure for classes that perform internal traversals
496
+
497
+ .. versionadded:: 2.0
498
+
499
+ """
500
+
501
+ __slots__ = ()
502
+
503
+ _dispatch_lookup: ClassVar[Dict[Union[InternalTraversal, str], str]] = {}
504
+
505
+ def dispatch(self, visit_symbol: InternalTraversal) -> Callable[..., Any]:
506
+ """Given a method from :class:`.HasTraversalDispatch`, return the
507
+ corresponding method on a subclass.
508
+
509
+ """
510
+ name = _dispatch_lookup[visit_symbol]
511
+ return getattr(self, name, None) # type: ignore
512
+
513
+ def run_generated_dispatch(
514
+ self,
515
+ target: object,
516
+ internal_dispatch: _TraverseInternalsType,
517
+ generate_dispatcher_name: str,
518
+ ) -> Any:
519
+ dispatcher: _InternalTraversalDispatchType
520
+ try:
521
+ dispatcher = target.__class__.__dict__[generate_dispatcher_name]
522
+ except KeyError:
523
+ # traversals.py -> _preconfigure_traversals()
524
+ # may be used to run these ahead of time, but
525
+ # is not enabled right now.
526
+ # this block will generate any remaining dispatchers.
527
+ dispatcher = self.generate_dispatch(
528
+ target.__class__, internal_dispatch, generate_dispatcher_name
529
+ )
530
+ return dispatcher(target, self)
531
+
532
+ def generate_dispatch(
533
+ self,
534
+ target_cls: Type[object],
535
+ internal_dispatch: _TraverseInternalsType,
536
+ generate_dispatcher_name: str,
537
+ ) -> _InternalTraversalDispatchType:
538
+ dispatcher = self._generate_dispatcher(
539
+ internal_dispatch, generate_dispatcher_name
540
+ )
541
+ # assert isinstance(target_cls, type)
542
+ setattr(target_cls, generate_dispatcher_name, dispatcher)
543
+ return dispatcher
544
+
545
+ def _generate_dispatcher(
546
+ self, internal_dispatch: _TraverseInternalsType, method_name: str
547
+ ) -> _InternalTraversalDispatchType:
548
+ names = []
549
+ for attrname, visit_sym in internal_dispatch:
550
+ meth = self.dispatch(visit_sym)
551
+ if meth is not None:
552
+ visit_name = _dispatch_lookup[visit_sym]
553
+ names.append((attrname, visit_name))
554
+
555
+ code = (
556
+ (" return [\n")
557
+ + (
558
+ ", \n".join(
559
+ " (%r, self.%s, visitor.%s)"
560
+ % (attrname, attrname, visit_name)
561
+ for attrname, visit_name in names
562
+ )
563
+ )
564
+ + ("\n ]\n")
565
+ )
566
+ meth_text = ("def %s(self, visitor):\n" % method_name) + code + "\n"
567
+ return cast(
568
+ _InternalTraversalDispatchType,
569
+ langhelpers._exec_code_in_env(meth_text, {}, method_name),
570
+ )
571
+
572
+
573
+ ExtendedInternalTraversal = InternalTraversal
574
+
575
+
576
+ def _generate_traversal_dispatch() -> None:
577
+ lookup = _dispatch_lookup
578
+
579
+ for sym in InternalTraversal:
580
+ key = sym.name
581
+ if key.startswith("dp_"):
582
+ visit_key = key.replace("dp_", "visit_")
583
+ sym_name = sym.value
584
+ assert sym_name not in lookup, sym_name
585
+ lookup[sym] = lookup[sym_name] = visit_key
586
+
587
+
588
+ _dispatch_lookup = HasTraversalDispatch._dispatch_lookup
589
+ _generate_traversal_dispatch()
590
+
591
+
592
+ class ExternallyTraversible(HasTraverseInternals, Visitable):
593
+ __slots__ = ()
594
+
595
+ _annotations: Mapping[Any, Any] = util.EMPTY_DICT
596
+
597
+ if typing.TYPE_CHECKING:
598
+
599
+ def _annotate(self, values: _AnnotationDict) -> Self: ...
600
+
601
+ def get_children(
602
+ self, *, omit_attrs: Tuple[str, ...] = (), **kw: Any
603
+ ) -> Iterable[ExternallyTraversible]: ...
604
+
605
+ def _clone(self, **kw: Any) -> Self:
606
+ """clone this element"""
607
+ raise NotImplementedError()
608
+
609
+ def _copy_internals(
610
+ self, *, omit_attrs: Tuple[str, ...] = (), **kw: Any
611
+ ) -> None:
612
+ """Reassign internal elements to be clones of themselves.
613
+
614
+ Called during a copy-and-traverse operation on newly
615
+ shallow-copied elements to create a deep copy.
616
+
617
+ The given clone function should be used, which may be applying
618
+ additional transformations to the element (i.e. replacement
619
+ traversal, cloned traversal, annotations).
620
+
621
+ """
622
+ raise NotImplementedError()
623
+
624
+
625
+ _ET = TypeVar("_ET", bound=ExternallyTraversible)
626
+
627
+ _CE = TypeVar("_CE", bound="ColumnElement[Any]")
628
+
629
+ _TraverseCallableType = Callable[[_ET], None]
630
+
631
+
632
+ class _CloneCallableType(Protocol):
633
+ def __call__(self, element: _ET, **kw: Any) -> _ET: ...
634
+
635
+
636
+ class _TraverseTransformCallableType(Protocol[_ET]):
637
+ def __call__(self, element: _ET, **kw: Any) -> Optional[_ET]: ...
638
+
639
+
640
+ _ExtT = TypeVar("_ExtT", bound="ExternalTraversal")
641
+
642
+
643
+ class ExternalTraversal(util.MemoizedSlots):
644
+ """Base class for visitor objects which can traverse externally using
645
+ the :func:`.visitors.traverse` function.
646
+
647
+ Direct usage of the :func:`.visitors.traverse` function is usually
648
+ preferred.
649
+
650
+ """
651
+
652
+ __slots__ = ("_visitor_dict", "_next")
653
+
654
+ __traverse_options__: Dict[str, Any] = {}
655
+ _next: Optional[ExternalTraversal]
656
+
657
+ def traverse_single(self, obj: Visitable, **kw: Any) -> Any:
658
+ for v in self.visitor_iterator:
659
+ meth = getattr(v, "visit_%s" % obj.__visit_name__, None)
660
+ if meth:
661
+ return meth(obj, **kw)
662
+
663
+ def iterate(
664
+ self, obj: Optional[ExternallyTraversible]
665
+ ) -> Iterator[ExternallyTraversible]:
666
+ """Traverse the given expression structure, returning an iterator
667
+ of all elements.
668
+
669
+ """
670
+ return iterate(obj, self.__traverse_options__)
671
+
672
+ @overload
673
+ def traverse(self, obj: Literal[None]) -> None: ...
674
+
675
+ @overload
676
+ def traverse(
677
+ self, obj: ExternallyTraversible
678
+ ) -> ExternallyTraversible: ...
679
+
680
+ def traverse(
681
+ self, obj: Optional[ExternallyTraversible]
682
+ ) -> Optional[ExternallyTraversible]:
683
+ """Traverse and visit the given expression structure."""
684
+
685
+ return traverse(obj, self.__traverse_options__, self._visitor_dict)
686
+
687
+ def _memoized_attr__visitor_dict(
688
+ self,
689
+ ) -> Dict[str, _TraverseCallableType[Any]]:
690
+ visitors = {}
691
+
692
+ for name in dir(self):
693
+ if name.startswith("visit_"):
694
+ visitors[name[6:]] = getattr(self, name)
695
+ return visitors
696
+
697
+ @property
698
+ def visitor_iterator(self) -> Iterator[ExternalTraversal]:
699
+ """Iterate through this visitor and each 'chained' visitor."""
700
+
701
+ v: Optional[ExternalTraversal] = self
702
+ while v:
703
+ yield v
704
+ v = getattr(v, "_next", None)
705
+
706
+ def chain(self: _ExtT, visitor: ExternalTraversal) -> _ExtT:
707
+ """'Chain' an additional ExternalTraversal onto this ExternalTraversal
708
+
709
+ The chained visitor will receive all visit events after this one.
710
+
711
+ """
712
+ tail = list(self.visitor_iterator)[-1]
713
+ tail._next = visitor
714
+ return self
715
+
716
+
717
+ class CloningExternalTraversal(ExternalTraversal):
718
+ """Base class for visitor objects which can traverse using
719
+ the :func:`.visitors.cloned_traverse` function.
720
+
721
+ Direct usage of the :func:`.visitors.cloned_traverse` function is usually
722
+ preferred.
723
+
724
+
725
+ """
726
+
727
+ __slots__ = ()
728
+
729
+ def copy_and_process(
730
+ self, list_: List[ExternallyTraversible]
731
+ ) -> List[ExternallyTraversible]:
732
+ """Apply cloned traversal to the given list of elements, and return
733
+ the new list.
734
+
735
+ """
736
+ return [self.traverse(x) for x in list_]
737
+
738
+ @overload
739
+ def traverse(self, obj: Literal[None]) -> None: ...
740
+
741
+ @overload
742
+ def traverse(
743
+ self, obj: ExternallyTraversible
744
+ ) -> ExternallyTraversible: ...
745
+
746
+ def traverse(
747
+ self, obj: Optional[ExternallyTraversible]
748
+ ) -> Optional[ExternallyTraversible]:
749
+ """Traverse and visit the given expression structure."""
750
+
751
+ return cloned_traverse(
752
+ obj, self.__traverse_options__, self._visitor_dict
753
+ )
754
+
755
+
756
+ class ReplacingExternalTraversal(CloningExternalTraversal):
757
+ """Base class for visitor objects which can traverse using
758
+ the :func:`.visitors.replacement_traverse` function.
759
+
760
+ Direct usage of the :func:`.visitors.replacement_traverse` function is
761
+ usually preferred.
762
+
763
+ """
764
+
765
+ __slots__ = ()
766
+
767
+ def replace(
768
+ self, elem: ExternallyTraversible
769
+ ) -> Optional[ExternallyTraversible]:
770
+ """Receive pre-copied elements during a cloning traversal.
771
+
772
+ If the method returns a new element, the element is used
773
+ instead of creating a simple copy of the element. Traversal
774
+ will halt on the newly returned element if it is re-encountered.
775
+ """
776
+ return None
777
+
778
+ @overload
779
+ def traverse(self, obj: Literal[None]) -> None: ...
780
+
781
+ @overload
782
+ def traverse(
783
+ self, obj: ExternallyTraversible
784
+ ) -> ExternallyTraversible: ...
785
+
786
+ def traverse(
787
+ self, obj: Optional[ExternallyTraversible]
788
+ ) -> Optional[ExternallyTraversible]:
789
+ """Traverse and visit the given expression structure."""
790
+
791
+ def replace(
792
+ element: ExternallyTraversible,
793
+ **kw: Any,
794
+ ) -> Optional[ExternallyTraversible]:
795
+ for v in self.visitor_iterator:
796
+ e = cast(ReplacingExternalTraversal, v).replace(element)
797
+ if e is not None:
798
+ return e
799
+
800
+ return None
801
+
802
+ return replacement_traverse(obj, self.__traverse_options__, replace)
803
+
804
+
805
+ # backwards compatibility
806
+ Traversible = Visitable
807
+
808
+ ClauseVisitor = ExternalTraversal
809
+ CloningVisitor = CloningExternalTraversal
810
+ ReplacingCloningVisitor = ReplacingExternalTraversal
811
+
812
+
813
+ def iterate(
814
+ obj: Optional[ExternallyTraversible],
815
+ opts: Mapping[str, Any] = util.EMPTY_DICT,
816
+ ) -> Iterator[ExternallyTraversible]:
817
+ r"""Traverse the given expression structure, returning an iterator.
818
+
819
+ Traversal is configured to be breadth-first.
820
+
821
+ The central API feature used by the :func:`.visitors.iterate`
822
+ function is the
823
+ :meth:`_expression.ClauseElement.get_children` method of
824
+ :class:`_expression.ClauseElement` objects. This method should return all
825
+ the :class:`_expression.ClauseElement` objects which are associated with a
826
+ particular :class:`_expression.ClauseElement` object. For example, a
827
+ :class:`.Case` structure will refer to a series of
828
+ :class:`_expression.ColumnElement` objects within its "whens" and "else\_"
829
+ member variables.
830
+
831
+ :param obj: :class:`_expression.ClauseElement` structure to be traversed
832
+
833
+ :param opts: dictionary of iteration options. This dictionary is usually
834
+ empty in modern usage.
835
+
836
+ """
837
+ if obj is None:
838
+ return
839
+
840
+ yield obj
841
+ children = obj.get_children(**opts)
842
+
843
+ if not children:
844
+ return
845
+
846
+ stack = deque([children])
847
+ while stack:
848
+ t_iterator = stack.popleft()
849
+ for t in t_iterator:
850
+ yield t
851
+ stack.append(t.get_children(**opts))
852
+
853
+
854
+ @overload
855
+ def traverse_using(
856
+ iterator: Iterable[ExternallyTraversible],
857
+ obj: Literal[None],
858
+ visitors: Mapping[str, _TraverseCallableType[Any]],
859
+ ) -> None: ...
860
+
861
+
862
+ @overload
863
+ def traverse_using(
864
+ iterator: Iterable[ExternallyTraversible],
865
+ obj: ExternallyTraversible,
866
+ visitors: Mapping[str, _TraverseCallableType[Any]],
867
+ ) -> ExternallyTraversible: ...
868
+
869
+
870
+ def traverse_using(
871
+ iterator: Iterable[ExternallyTraversible],
872
+ obj: Optional[ExternallyTraversible],
873
+ visitors: Mapping[str, _TraverseCallableType[Any]],
874
+ ) -> Optional[ExternallyTraversible]:
875
+ """Visit the given expression structure using the given iterator of
876
+ objects.
877
+
878
+ :func:`.visitors.traverse_using` is usually called internally as the result
879
+ of the :func:`.visitors.traverse` function.
880
+
881
+ :param iterator: an iterable or sequence which will yield
882
+ :class:`_expression.ClauseElement`
883
+ structures; the iterator is assumed to be the
884
+ product of the :func:`.visitors.iterate` function.
885
+
886
+ :param obj: the :class:`_expression.ClauseElement`
887
+ that was used as the target of the
888
+ :func:`.iterate` function.
889
+
890
+ :param visitors: dictionary of visit functions. See :func:`.traverse`
891
+ for details on this dictionary.
892
+
893
+ .. seealso::
894
+
895
+ :func:`.traverse`
896
+
897
+
898
+ """
899
+ for target in iterator:
900
+ meth = visitors.get(target.__visit_name__, None)
901
+ if meth:
902
+ meth(target)
903
+ return obj
904
+
905
+
906
+ @overload
907
+ def traverse(
908
+ obj: Literal[None],
909
+ opts: Mapping[str, Any],
910
+ visitors: Mapping[str, _TraverseCallableType[Any]],
911
+ ) -> None: ...
912
+
913
+
914
+ @overload
915
+ def traverse(
916
+ obj: ExternallyTraversible,
917
+ opts: Mapping[str, Any],
918
+ visitors: Mapping[str, _TraverseCallableType[Any]],
919
+ ) -> ExternallyTraversible: ...
920
+
921
+
922
+ def traverse(
923
+ obj: Optional[ExternallyTraversible],
924
+ opts: Mapping[str, Any],
925
+ visitors: Mapping[str, _TraverseCallableType[Any]],
926
+ ) -> Optional[ExternallyTraversible]:
927
+ """Traverse and visit the given expression structure using the default
928
+ iterator.
929
+
930
+ e.g.::
931
+
932
+ from sqlalchemy.sql import visitors
933
+
934
+ stmt = select(some_table).where(some_table.c.foo == "bar")
935
+
936
+
937
+ def visit_bindparam(bind_param):
938
+ print("found bound value: %s" % bind_param.value)
939
+
940
+
941
+ visitors.traverse(stmt, {}, {"bindparam": visit_bindparam})
942
+
943
+ The iteration of objects uses the :func:`.visitors.iterate` function,
944
+ which does a breadth-first traversal using a stack.
945
+
946
+ :param obj: :class:`_expression.ClauseElement` structure to be traversed
947
+
948
+ :param opts: dictionary of iteration options. This dictionary is usually
949
+ empty in modern usage.
950
+
951
+ :param visitors: dictionary of visit functions. The dictionary should
952
+ have strings as keys, each of which would correspond to the
953
+ ``__visit_name__`` of a particular kind of SQL expression object, and
954
+ callable functions as values, each of which represents a visitor function
955
+ for that kind of object.
956
+
957
+ """
958
+ return traverse_using(iterate(obj, opts), obj, visitors)
959
+
960
+
961
+ @overload
962
+ def cloned_traverse(
963
+ obj: Literal[None],
964
+ opts: Mapping[str, Any],
965
+ visitors: Mapping[str, _TraverseCallableType[Any]],
966
+ ) -> None: ...
967
+
968
+
969
+ # a bit of controversy here, as the clone of the lead element
970
+ # *could* in theory replace with an entirely different kind of element.
971
+ # however this is really not how cloned_traverse is ever used internally
972
+ # at least.
973
+ @overload
974
+ def cloned_traverse(
975
+ obj: _ET,
976
+ opts: Mapping[str, Any],
977
+ visitors: Mapping[str, _TraverseCallableType[Any]],
978
+ ) -> _ET: ...
979
+
980
+
981
+ def cloned_traverse(
982
+ obj: Optional[ExternallyTraversible],
983
+ opts: Mapping[str, Any],
984
+ visitors: Mapping[str, _TraverseCallableType[Any]],
985
+ ) -> Optional[ExternallyTraversible]:
986
+ """Clone the given expression structure, allowing modifications by
987
+ visitors for mutable objects.
988
+
989
+ Traversal usage is the same as that of :func:`.visitors.traverse`.
990
+ The visitor functions present in the ``visitors`` dictionary may also
991
+ modify the internals of the given structure as the traversal proceeds.
992
+
993
+ The :func:`.cloned_traverse` function does **not** provide objects that are
994
+ part of the :class:`.Immutable` interface to the visit methods (this
995
+ primarily includes :class:`.ColumnClause`, :class:`.Column`,
996
+ :class:`.TableClause` and :class:`.Table` objects). As this traversal is
997
+ only intended to allow in-place mutation of objects, :class:`.Immutable`
998
+ objects are skipped. The :meth:`.Immutable._clone` method is still called
999
+ on each object to allow for objects to replace themselves with a different
1000
+ object based on a clone of their sub-internals (e.g. a
1001
+ :class:`.ColumnClause` that clones its subquery to return a new
1002
+ :class:`.ColumnClause`).
1003
+
1004
+ .. versionchanged:: 2.0 The :func:`.cloned_traverse` function omits
1005
+ objects that are part of the :class:`.Immutable` interface.
1006
+
1007
+ The central API feature used by the :func:`.visitors.cloned_traverse`
1008
+ and :func:`.visitors.replacement_traverse` functions, in addition to the
1009
+ :meth:`_expression.ClauseElement.get_children`
1010
+ function that is used to achieve
1011
+ the iteration, is the :meth:`_expression.ClauseElement._copy_internals`
1012
+ method.
1013
+ For a :class:`_expression.ClauseElement`
1014
+ structure to support cloning and replacement
1015
+ traversals correctly, it needs to be able to pass a cloning function into
1016
+ its internal members in order to make copies of them.
1017
+
1018
+ .. seealso::
1019
+
1020
+ :func:`.visitors.traverse`
1021
+
1022
+ :func:`.visitors.replacement_traverse`
1023
+
1024
+ """
1025
+
1026
+ cloned: Dict[int, ExternallyTraversible] = {}
1027
+ stop_on = set(opts.get("stop_on", []))
1028
+
1029
+ def deferred_copy_internals(
1030
+ obj: ExternallyTraversible,
1031
+ ) -> ExternallyTraversible:
1032
+ return cloned_traverse(obj, opts, visitors)
1033
+
1034
+ def clone(elem: ExternallyTraversible, **kw: Any) -> ExternallyTraversible:
1035
+ if elem in stop_on:
1036
+ return elem
1037
+ else:
1038
+ if id(elem) not in cloned:
1039
+ if "replace" in kw:
1040
+ newelem = cast(
1041
+ Optional[ExternallyTraversible], kw["replace"](elem)
1042
+ )
1043
+ if newelem is not None:
1044
+ cloned[id(elem)] = newelem
1045
+ return newelem
1046
+
1047
+ # the _clone method for immutable normally returns "self".
1048
+ # however, the method is still allowed to return a
1049
+ # different object altogether; ColumnClause._clone() will
1050
+ # based on options clone the subquery to which it is associated
1051
+ # and return the new corresponding column.
1052
+ cloned[id(elem)] = newelem = elem._clone(clone=clone, **kw)
1053
+ newelem._copy_internals(clone=clone, **kw)
1054
+
1055
+ # however, visit methods which are tasked with in-place
1056
+ # mutation of the object should not get access to the immutable
1057
+ # object.
1058
+ if not elem._is_immutable:
1059
+ meth = visitors.get(newelem.__visit_name__, None)
1060
+ if meth:
1061
+ meth(newelem)
1062
+ return cloned[id(elem)]
1063
+
1064
+ if obj is not None:
1065
+ obj = clone(
1066
+ obj, deferred_copy_internals=deferred_copy_internals, **opts
1067
+ )
1068
+ clone = None # type: ignore[assignment] # remove gc cycles
1069
+ return obj
1070
+
1071
+
1072
+ @overload
1073
+ def replacement_traverse(
1074
+ obj: Literal[None],
1075
+ opts: Mapping[str, Any],
1076
+ replace: _TraverseTransformCallableType[Any],
1077
+ ) -> None: ...
1078
+
1079
+
1080
+ @overload
1081
+ def replacement_traverse(
1082
+ obj: _CE,
1083
+ opts: Mapping[str, Any],
1084
+ replace: _TraverseTransformCallableType[Any],
1085
+ ) -> _CE: ...
1086
+
1087
+
1088
+ @overload
1089
+ def replacement_traverse(
1090
+ obj: ExternallyTraversible,
1091
+ opts: Mapping[str, Any],
1092
+ replace: _TraverseTransformCallableType[Any],
1093
+ ) -> ExternallyTraversible: ...
1094
+
1095
+
1096
+ def replacement_traverse(
1097
+ obj: Optional[ExternallyTraversible],
1098
+ opts: Mapping[str, Any],
1099
+ replace: _TraverseTransformCallableType[Any],
1100
+ ) -> Optional[ExternallyTraversible]:
1101
+ """Clone the given expression structure, allowing element
1102
+ replacement by a given replacement function.
1103
+
1104
+ This function is very similar to the :func:`.visitors.cloned_traverse`
1105
+ function, except instead of being passed a dictionary of visitors, all
1106
+ elements are unconditionally passed into the given replace function.
1107
+ The replace function then has the option to return an entirely new object
1108
+ which will replace the one given. If it returns ``None``, then the object
1109
+ is kept in place.
1110
+
1111
+ The difference in usage between :func:`.visitors.cloned_traverse` and
1112
+ :func:`.visitors.replacement_traverse` is that in the former case, an
1113
+ already-cloned object is passed to the visitor function, and the visitor
1114
+ function can then manipulate the internal state of the object.
1115
+ In the case of the latter, the visitor function should only return an
1116
+ entirely different object, or do nothing.
1117
+
1118
+ The use case for :func:`.visitors.replacement_traverse` is that of
1119
+ replacing a FROM clause inside of a SQL structure with a different one,
1120
+ as is a common use case within the ORM.
1121
+
1122
+ """
1123
+
1124
+ cloned = {}
1125
+ stop_on = {id(x) for x in opts.get("stop_on", [])}
1126
+
1127
+ def deferred_copy_internals(
1128
+ obj: ExternallyTraversible,
1129
+ ) -> ExternallyTraversible:
1130
+ return replacement_traverse(obj, opts, replace)
1131
+
1132
+ def clone(elem: ExternallyTraversible, **kw: Any) -> ExternallyTraversible:
1133
+ if (
1134
+ id(elem) in stop_on
1135
+ or "no_replacement_traverse" in elem._annotations
1136
+ ):
1137
+ return elem
1138
+ else:
1139
+ newelem = replace(elem)
1140
+ if newelem is not None:
1141
+ stop_on.add(id(newelem))
1142
+ return newelem # type: ignore
1143
+ else:
1144
+ # base "already seen" on id(), not hash, so that we don't
1145
+ # replace an Annotated element with its non-annotated one, and
1146
+ # vice versa
1147
+ id_elem = id(elem)
1148
+ if id_elem not in cloned:
1149
+ if "replace" in kw:
1150
+ newelem = kw["replace"](elem)
1151
+ if newelem is not None:
1152
+ cloned[id_elem] = newelem
1153
+ return newelem # type: ignore
1154
+
1155
+ cloned[id_elem] = newelem = elem._clone(**kw)
1156
+ newelem._copy_internals(clone=clone, **kw)
1157
+ return cloned[id_elem] # type: ignore
1158
+
1159
+ if obj is not None:
1160
+ obj = clone(
1161
+ obj, deferred_copy_internals=deferred_copy_internals, **opts
1162
+ )
1163
+ clone = None # type: ignore[assignment] # remove gc cycles
1164
+ return obj