visitors.py 36 KB

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