visitors.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. # sql/visitors.py
  2. # Copyright (C) 2005-2022 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. SQLAlchemy schema and expression constructs rely on a Python-centric
  9. version of the classic "visitor" pattern as the primary way in which
  10. they apply functionality. The most common use of this pattern
  11. is statement compilation, where individual expression classes match
  12. up to rendering methods that produce a string result. Beyond this,
  13. the visitor system is also used to inspect expressions for various
  14. information and patterns, as well as for the purposes of applying
  15. transformations to expressions.
  16. Examples of how the visit system is used can be seen in the source code
  17. of for example the ``sqlalchemy.sql.util`` and the ``sqlalchemy.sql.compiler``
  18. modules. Some background on clause adaption is also at
  19. https://techspot.zzzeek.org/2008/01/23/expression-transformations/ .
  20. """
  21. from collections import deque
  22. import itertools
  23. import operator
  24. from .. import exc
  25. from .. import util
  26. from ..util import langhelpers
  27. from ..util import symbol
  28. __all__ = [
  29. "iterate",
  30. "traverse_using",
  31. "traverse",
  32. "cloned_traverse",
  33. "replacement_traverse",
  34. "Traversible",
  35. "TraversibleType",
  36. "ExternalTraversal",
  37. "InternalTraversal",
  38. ]
  39. def _generate_compiler_dispatch(cls):
  40. """Generate a _compiler_dispatch() external traversal on classes with a
  41. __visit_name__ attribute.
  42. """
  43. visit_name = cls.__visit_name__
  44. if "_compiler_dispatch" in cls.__dict__:
  45. # class has a fixed _compiler_dispatch() method.
  46. # copy it to "original" so that we can get it back if
  47. # sqlalchemy.ext.compiles overrides it.
  48. cls._original_compiler_dispatch = cls._compiler_dispatch
  49. return
  50. if not isinstance(visit_name, util.compat.string_types):
  51. raise exc.InvalidRequestError(
  52. "__visit_name__ on class %s must be a string at the class level"
  53. % cls.__name__
  54. )
  55. name = "visit_%s" % visit_name
  56. getter = operator.attrgetter(name)
  57. def _compiler_dispatch(self, visitor, **kw):
  58. """Look for an attribute named "visit_<visit_name>" on the
  59. visitor, and call it with the same kw params.
  60. """
  61. try:
  62. meth = getter(visitor)
  63. except AttributeError as err:
  64. return visitor.visit_unsupported_compilation(self, err, **kw)
  65. else:
  66. return meth(self, **kw)
  67. cls._compiler_dispatch = (
  68. cls._original_compiler_dispatch
  69. ) = _compiler_dispatch
  70. class TraversibleType(type):
  71. """Metaclass which assigns dispatch attributes to various kinds of
  72. "visitable" classes.
  73. Attributes include:
  74. * The ``_compiler_dispatch`` method, corresponding to ``__visit_name__``.
  75. This is called "external traversal" because the caller of each visit()
  76. method is responsible for sub-traversing the inner elements of each
  77. object. This is appropriate for string compilers and other traversals
  78. that need to call upon the inner elements in a specific pattern.
  79. * internal traversal collections ``_children_traversal``,
  80. ``_cache_key_traversal``, ``_copy_internals_traversal``, generated from
  81. an optional ``_traverse_internals`` collection of symbols which comes
  82. from the :class:`.InternalTraversal` list of symbols. This is called
  83. "internal traversal" MARKMARK
  84. """
  85. def __init__(cls, clsname, bases, clsdict):
  86. if clsname != "Traversible":
  87. if "__visit_name__" in clsdict:
  88. _generate_compiler_dispatch(cls)
  89. super(TraversibleType, cls).__init__(clsname, bases, clsdict)
  90. class Traversible(util.with_metaclass(TraversibleType)):
  91. """Base class for visitable objects, applies the
  92. :class:`.visitors.TraversibleType` metaclass.
  93. """
  94. def __class_getitem__(cls, key):
  95. # allow generic classes in py3.9+
  96. return cls
  97. @util.preload_module("sqlalchemy.sql.traversals")
  98. def get_children(self, omit_attrs=(), **kw):
  99. r"""Return immediate child :class:`.visitors.Traversible`
  100. elements of this :class:`.visitors.Traversible`.
  101. This is used for visit traversal.
  102. \**kw may contain flags that change the collection that is
  103. returned, for example to return a subset of items in order to
  104. cut down on larger traversals, or to return child items from a
  105. different context (such as schema-level collections instead of
  106. clause-level).
  107. """
  108. traversals = util.preloaded.sql_traversals
  109. try:
  110. traverse_internals = self._traverse_internals
  111. except AttributeError:
  112. # user-defined classes may not have a _traverse_internals
  113. return []
  114. dispatch = traversals._get_children.run_generated_dispatch
  115. return itertools.chain.from_iterable(
  116. meth(obj, **kw)
  117. for attrname, obj, meth in dispatch(
  118. self, traverse_internals, "_generated_get_children_traversal"
  119. )
  120. if attrname not in omit_attrs and obj is not None
  121. )
  122. class _InternalTraversalType(type):
  123. def __init__(cls, clsname, bases, clsdict):
  124. if cls.__name__ in ("InternalTraversal", "ExtendedInternalTraversal"):
  125. lookup = {}
  126. for key, sym in clsdict.items():
  127. if key.startswith("dp_"):
  128. visit_key = key.replace("dp_", "visit_")
  129. sym_name = sym.name
  130. assert sym_name not in lookup, sym_name
  131. lookup[sym] = lookup[sym_name] = visit_key
  132. if hasattr(cls, "_dispatch_lookup"):
  133. lookup.update(cls._dispatch_lookup)
  134. cls._dispatch_lookup = lookup
  135. super(_InternalTraversalType, cls).__init__(clsname, bases, clsdict)
  136. def _generate_dispatcher(visitor, internal_dispatch, method_name):
  137. names = []
  138. for attrname, visit_sym in internal_dispatch:
  139. meth = visitor.dispatch(visit_sym)
  140. if meth:
  141. visit_name = ExtendedInternalTraversal._dispatch_lookup[visit_sym]
  142. names.append((attrname, visit_name))
  143. code = (
  144. (" return [\n")
  145. + (
  146. ", \n".join(
  147. " (%r, self.%s, visitor.%s)"
  148. % (attrname, attrname, visit_name)
  149. for attrname, visit_name in names
  150. )
  151. )
  152. + ("\n ]\n")
  153. )
  154. meth_text = ("def %s(self, visitor):\n" % method_name) + code + "\n"
  155. # print(meth_text)
  156. return langhelpers._exec_code_in_env(meth_text, {}, method_name)
  157. class InternalTraversal(util.with_metaclass(_InternalTraversalType, object)):
  158. r"""Defines visitor symbols used for internal traversal.
  159. The :class:`.InternalTraversal` class is used in two ways. One is that
  160. it can serve as the superclass for an object that implements the
  161. various visit methods of the class. The other is that the symbols
  162. themselves of :class:`.InternalTraversal` are used within
  163. the ``_traverse_internals`` collection. Such as, the :class:`.Case`
  164. object defines ``_traverse_internals`` as ::
  165. _traverse_internals = [
  166. ("value", InternalTraversal.dp_clauseelement),
  167. ("whens", InternalTraversal.dp_clauseelement_tuples),
  168. ("else_", InternalTraversal.dp_clauseelement),
  169. ]
  170. Above, the :class:`.Case` class indicates its internal state as the
  171. attributes named ``value``, ``whens``, and ``else_``. They each
  172. link to an :class:`.InternalTraversal` method which indicates the type
  173. of datastructure referred towards.
  174. Using the ``_traverse_internals`` structure, objects of type
  175. :class:`.InternalTraversible` will have the following methods automatically
  176. implemented:
  177. * :meth:`.Traversible.get_children`
  178. * :meth:`.Traversible._copy_internals`
  179. * :meth:`.Traversible._gen_cache_key`
  180. Subclasses can also implement these methods directly, particularly for the
  181. :meth:`.Traversible._copy_internals` method, when special steps
  182. are needed.
  183. .. versionadded:: 1.4
  184. """
  185. def dispatch(self, visit_symbol):
  186. """Given a method from :class:`.InternalTraversal`, return the
  187. corresponding method on a subclass.
  188. """
  189. name = self._dispatch_lookup[visit_symbol]
  190. return getattr(self, name, None)
  191. def run_generated_dispatch(
  192. self, target, internal_dispatch, generate_dispatcher_name
  193. ):
  194. try:
  195. dispatcher = target.__class__.__dict__[generate_dispatcher_name]
  196. except KeyError:
  197. # most of the dispatchers are generated up front
  198. # in sqlalchemy/sql/__init__.py ->
  199. # traversals.py-> _preconfigure_traversals().
  200. # this block will generate any remaining dispatchers.
  201. dispatcher = self.generate_dispatch(
  202. target.__class__, internal_dispatch, generate_dispatcher_name
  203. )
  204. return dispatcher(target, self)
  205. def generate_dispatch(
  206. self, target_cls, internal_dispatch, generate_dispatcher_name
  207. ):
  208. dispatcher = _generate_dispatcher(
  209. self, internal_dispatch, generate_dispatcher_name
  210. )
  211. # assert isinstance(target_cls, type)
  212. setattr(target_cls, generate_dispatcher_name, dispatcher)
  213. return dispatcher
  214. dp_has_cache_key = symbol("HC")
  215. """Visit a :class:`.HasCacheKey` object."""
  216. dp_has_cache_key_list = symbol("HL")
  217. """Visit a list of :class:`.HasCacheKey` objects."""
  218. dp_clauseelement = symbol("CE")
  219. """Visit a :class:`_expression.ClauseElement` object."""
  220. dp_fromclause_canonical_column_collection = symbol("FC")
  221. """Visit a :class:`_expression.FromClause` object in the context of the
  222. ``columns`` attribute.
  223. The column collection is "canonical", meaning it is the originally
  224. defined location of the :class:`.ColumnClause` objects. Right now
  225. this means that the object being visited is a
  226. :class:`_expression.TableClause`
  227. or :class:`_schema.Table` object only.
  228. """
  229. dp_clauseelement_tuples = symbol("CTS")
  230. """Visit a list of tuples which contain :class:`_expression.ClauseElement`
  231. objects.
  232. """
  233. dp_clauseelement_list = symbol("CL")
  234. """Visit a list of :class:`_expression.ClauseElement` objects.
  235. """
  236. dp_clauseelement_tuple = symbol("CT")
  237. """Visit a tuple of :class:`_expression.ClauseElement` objects.
  238. """
  239. dp_executable_options = symbol("EO")
  240. dp_with_context_options = symbol("WC")
  241. dp_fromclause_ordered_set = symbol("CO")
  242. """Visit an ordered set of :class:`_expression.FromClause` objects. """
  243. dp_string = symbol("S")
  244. """Visit a plain string value.
  245. Examples include table and column names, bound parameter keys, special
  246. keywords such as "UNION", "UNION ALL".
  247. The string value is considered to be significant for cache key
  248. generation.
  249. """
  250. dp_string_list = symbol("SL")
  251. """Visit a list of strings."""
  252. dp_anon_name = symbol("AN")
  253. """Visit a potentially "anonymized" string value.
  254. The string value is considered to be significant for cache key
  255. generation.
  256. """
  257. dp_boolean = symbol("B")
  258. """Visit a boolean value.
  259. The boolean value is considered to be significant for cache key
  260. generation.
  261. """
  262. dp_operator = symbol("O")
  263. """Visit an operator.
  264. The operator is a function from the :mod:`sqlalchemy.sql.operators`
  265. module.
  266. The operator value is considered to be significant for cache key
  267. generation.
  268. """
  269. dp_type = symbol("T")
  270. """Visit a :class:`.TypeEngine` object
  271. The type object is considered to be significant for cache key
  272. generation.
  273. """
  274. dp_plain_dict = symbol("PD")
  275. """Visit a dictionary with string keys.
  276. The keys of the dictionary should be strings, the values should
  277. be immutable and hashable. The dictionary is considered to be
  278. significant for cache key generation.
  279. """
  280. dp_dialect_options = symbol("DO")
  281. """Visit a dialect options structure."""
  282. dp_string_clauseelement_dict = symbol("CD")
  283. """Visit a dictionary of string keys to :class:`_expression.ClauseElement`
  284. objects.
  285. """
  286. dp_string_multi_dict = symbol("MD")
  287. """Visit a dictionary of string keys to values which may either be
  288. plain immutable/hashable or :class:`.HasCacheKey` objects.
  289. """
  290. dp_annotations_key = symbol("AK")
  291. """Visit the _annotations_cache_key element.
  292. This is a dictionary of additional information about a ClauseElement
  293. that modifies its role. It should be included when comparing or caching
  294. objects, however generating this key is relatively expensive. Visitors
  295. should check the "_annotations" dict for non-None first before creating
  296. this key.
  297. """
  298. dp_plain_obj = symbol("PO")
  299. """Visit a plain python object.
  300. The value should be immutable and hashable, such as an integer.
  301. The value is considered to be significant for cache key generation.
  302. """
  303. dp_named_ddl_element = symbol("DD")
  304. """Visit a simple named DDL element.
  305. The current object used by this method is the :class:`.Sequence`.
  306. The object is only considered to be important for cache key generation
  307. as far as its name, but not any other aspects of it.
  308. """
  309. dp_prefix_sequence = symbol("PS")
  310. """Visit the sequence represented by :class:`_expression.HasPrefixes`
  311. or :class:`_expression.HasSuffixes`.
  312. """
  313. dp_table_hint_list = symbol("TH")
  314. """Visit the ``_hints`` collection of a :class:`_expression.Select`
  315. object.
  316. """
  317. dp_setup_join_tuple = symbol("SJ")
  318. dp_memoized_select_entities = symbol("ME")
  319. dp_statement_hint_list = symbol("SH")
  320. """Visit the ``_statement_hints`` collection of a
  321. :class:`_expression.Select`
  322. object.
  323. """
  324. dp_unknown_structure = symbol("UK")
  325. """Visit an unknown structure.
  326. """
  327. dp_dml_ordered_values = symbol("DML_OV")
  328. """Visit the values() ordered tuple list of an
  329. :class:`_expression.Update` object."""
  330. dp_dml_values = symbol("DML_V")
  331. """Visit the values() dictionary of a :class:`.ValuesBase`
  332. (e.g. Insert or Update) object.
  333. """
  334. dp_dml_multi_values = symbol("DML_MV")
  335. """Visit the values() multi-valued list of dictionaries of an
  336. :class:`_expression.Insert` object.
  337. """
  338. dp_propagate_attrs = symbol("PA")
  339. """Visit the propagate attrs dict. This hardcodes to the particular
  340. elements we care about right now."""
  341. class ExtendedInternalTraversal(InternalTraversal):
  342. """Defines additional symbols that are useful in caching applications.
  343. Traversals for :class:`_expression.ClauseElement` objects only need to use
  344. those symbols present in :class:`.InternalTraversal`. However, for
  345. additional caching use cases within the ORM, symbols dealing with the
  346. :class:`.HasCacheKey` class are added here.
  347. """
  348. dp_ignore = symbol("IG")
  349. """Specify an object that should be ignored entirely.
  350. This currently applies function call argument caching where some
  351. arguments should not be considered to be part of a cache key.
  352. """
  353. dp_inspectable = symbol("IS")
  354. """Visit an inspectable object where the return value is a
  355. :class:`.HasCacheKey` object."""
  356. dp_multi = symbol("M")
  357. """Visit an object that may be a :class:`.HasCacheKey` or may be a
  358. plain hashable object."""
  359. dp_multi_list = symbol("MT")
  360. """Visit a tuple containing elements that may be :class:`.HasCacheKey` or
  361. may be a plain hashable object."""
  362. dp_has_cache_key_tuples = symbol("HT")
  363. """Visit a list of tuples which contain :class:`.HasCacheKey`
  364. objects.
  365. """
  366. dp_inspectable_list = symbol("IL")
  367. """Visit a list of inspectable objects which upon inspection are
  368. HasCacheKey objects."""
  369. class ExternalTraversal(object):
  370. """Base class for visitor objects which can traverse externally using
  371. the :func:`.visitors.traverse` function.
  372. Direct usage of the :func:`.visitors.traverse` function is usually
  373. preferred.
  374. """
  375. __traverse_options__ = {}
  376. def traverse_single(self, obj, **kw):
  377. for v in self.visitor_iterator:
  378. meth = getattr(v, "visit_%s" % obj.__visit_name__, None)
  379. if meth:
  380. return meth(obj, **kw)
  381. def iterate(self, obj):
  382. """Traverse the given expression structure, returning an iterator
  383. of all elements.
  384. """
  385. return iterate(obj, self.__traverse_options__)
  386. def traverse(self, obj):
  387. """Traverse and visit the given expression structure."""
  388. return traverse(obj, self.__traverse_options__, self._visitor_dict)
  389. @util.memoized_property
  390. def _visitor_dict(self):
  391. visitors = {}
  392. for name in dir(self):
  393. if name.startswith("visit_"):
  394. visitors[name[6:]] = getattr(self, name)
  395. return visitors
  396. @property
  397. def visitor_iterator(self):
  398. """Iterate through this visitor and each 'chained' visitor."""
  399. v = self
  400. while v:
  401. yield v
  402. v = getattr(v, "_next", None)
  403. def chain(self, visitor):
  404. """'Chain' an additional ClauseVisitor onto this ClauseVisitor.
  405. The chained visitor will receive all visit events after this one.
  406. """
  407. tail = list(self.visitor_iterator)[-1]
  408. tail._next = visitor
  409. return self
  410. class CloningExternalTraversal(ExternalTraversal):
  411. """Base class for visitor objects which can traverse using
  412. the :func:`.visitors.cloned_traverse` function.
  413. Direct usage of the :func:`.visitors.cloned_traverse` function is usually
  414. preferred.
  415. """
  416. def copy_and_process(self, list_):
  417. """Apply cloned traversal to the given list of elements, and return
  418. the new list.
  419. """
  420. return [self.traverse(x) for x in list_]
  421. def traverse(self, obj):
  422. """Traverse and visit the given expression structure."""
  423. return cloned_traverse(
  424. obj, self.__traverse_options__, self._visitor_dict
  425. )
  426. class ReplacingExternalTraversal(CloningExternalTraversal):
  427. """Base class for visitor objects which can traverse using
  428. the :func:`.visitors.replacement_traverse` function.
  429. Direct usage of the :func:`.visitors.replacement_traverse` function is
  430. usually preferred.
  431. """
  432. def replace(self, elem):
  433. """Receive pre-copied elements during a cloning traversal.
  434. If the method returns a new element, the element is used
  435. instead of creating a simple copy of the element. Traversal
  436. will halt on the newly returned element if it is re-encountered.
  437. """
  438. return None
  439. def traverse(self, obj):
  440. """Traverse and visit the given expression structure."""
  441. def replace(elem):
  442. for v in self.visitor_iterator:
  443. e = v.replace(elem)
  444. if e is not None:
  445. return e
  446. return replacement_traverse(obj, self.__traverse_options__, replace)
  447. # backwards compatibility
  448. Visitable = Traversible
  449. VisitableType = TraversibleType
  450. ClauseVisitor = ExternalTraversal
  451. CloningVisitor = CloningExternalTraversal
  452. ReplacingCloningVisitor = ReplacingExternalTraversal
  453. def iterate(obj, opts=util.immutabledict()):
  454. r"""Traverse the given expression structure, returning an iterator.
  455. Traversal is configured to be breadth-first.
  456. The central API feature used by the :func:`.visitors.iterate`
  457. function is the
  458. :meth:`_expression.ClauseElement.get_children` method of
  459. :class:`_expression.ClauseElement` objects. This method should return all
  460. the :class:`_expression.ClauseElement` objects which are associated with a
  461. particular :class:`_expression.ClauseElement` object. For example, a
  462. :class:`.Case` structure will refer to a series of
  463. :class:`_expression.ColumnElement` objects within its "whens" and "else\_"
  464. member variables.
  465. :param obj: :class:`_expression.ClauseElement` structure to be traversed
  466. :param opts: dictionary of iteration options. This dictionary is usually
  467. empty in modern usage.
  468. """
  469. yield obj
  470. children = obj.get_children(**opts)
  471. if not children:
  472. return
  473. stack = deque([children])
  474. while stack:
  475. t_iterator = stack.popleft()
  476. for t in t_iterator:
  477. yield t
  478. stack.append(t.get_children(**opts))
  479. def traverse_using(iterator, obj, visitors):
  480. """Visit the given expression structure using the given iterator of
  481. objects.
  482. :func:`.visitors.traverse_using` is usually called internally as the result
  483. of the :func:`.visitors.traverse` function.
  484. :param iterator: an iterable or sequence which will yield
  485. :class:`_expression.ClauseElement`
  486. structures; the iterator is assumed to be the
  487. product of the :func:`.visitors.iterate` function.
  488. :param obj: the :class:`_expression.ClauseElement`
  489. that was used as the target of the
  490. :func:`.iterate` function.
  491. :param visitors: dictionary of visit functions. See :func:`.traverse`
  492. for details on this dictionary.
  493. .. seealso::
  494. :func:`.traverse`
  495. """
  496. for target in iterator:
  497. meth = visitors.get(target.__visit_name__, None)
  498. if meth:
  499. meth(target)
  500. return obj
  501. def traverse(obj, opts, visitors):
  502. """Traverse and visit the given expression structure using the default
  503. iterator.
  504. e.g.::
  505. from sqlalchemy.sql import visitors
  506. stmt = select(some_table).where(some_table.c.foo == 'bar')
  507. def visit_bindparam(bind_param):
  508. print("found bound value: %s" % bind_param.value)
  509. visitors.traverse(stmt, {}, {"bindparam": visit_bindparam})
  510. The iteration of objects uses the :func:`.visitors.iterate` function,
  511. which does a breadth-first traversal using a stack.
  512. :param obj: :class:`_expression.ClauseElement` structure to be traversed
  513. :param opts: dictionary of iteration options. This dictionary is usually
  514. empty in modern usage.
  515. :param visitors: dictionary of visit functions. The dictionary should
  516. have strings as keys, each of which would correspond to the
  517. ``__visit_name__`` of a particular kind of SQL expression object, and
  518. callable functions as values, each of which represents a visitor function
  519. for that kind of object.
  520. """
  521. return traverse_using(iterate(obj, opts), obj, visitors)
  522. def cloned_traverse(obj, opts, visitors):
  523. """Clone the given expression structure, allowing modifications by
  524. visitors.
  525. Traversal usage is the same as that of :func:`.visitors.traverse`.
  526. The visitor functions present in the ``visitors`` dictionary may also
  527. modify the internals of the given structure as the traversal proceeds.
  528. The central API feature used by the :func:`.visitors.cloned_traverse`
  529. and :func:`.visitors.replacement_traverse` functions, in addition to the
  530. :meth:`_expression.ClauseElement.get_children`
  531. function that is used to achieve
  532. the iteration, is the :meth:`_expression.ClauseElement._copy_internals`
  533. method.
  534. For a :class:`_expression.ClauseElement`
  535. structure to support cloning and replacement
  536. traversals correctly, it needs to be able to pass a cloning function into
  537. its internal members in order to make copies of them.
  538. .. seealso::
  539. :func:`.visitors.traverse`
  540. :func:`.visitors.replacement_traverse`
  541. """
  542. cloned = {}
  543. stop_on = set(opts.get("stop_on", []))
  544. def deferred_copy_internals(obj):
  545. return cloned_traverse(obj, opts, visitors)
  546. def clone(elem, **kw):
  547. if elem in stop_on:
  548. return elem
  549. else:
  550. if id(elem) not in cloned:
  551. if "replace" in kw:
  552. newelem = kw["replace"](elem)
  553. if newelem is not None:
  554. cloned[id(elem)] = newelem
  555. return newelem
  556. cloned[id(elem)] = newelem = elem._clone(clone=clone, **kw)
  557. newelem._copy_internals(clone=clone, **kw)
  558. meth = visitors.get(newelem.__visit_name__, None)
  559. if meth:
  560. meth(newelem)
  561. return cloned[id(elem)]
  562. if obj is not None:
  563. obj = clone(
  564. obj, deferred_copy_internals=deferred_copy_internals, **opts
  565. )
  566. clone = None # remove gc cycles
  567. return obj
  568. def replacement_traverse(obj, opts, replace):
  569. """Clone the given expression structure, allowing element
  570. replacement by a given replacement function.
  571. This function is very similar to the :func:`.visitors.cloned_traverse`
  572. function, except instead of being passed a dictionary of visitors, all
  573. elements are unconditionally passed into the given replace function.
  574. The replace function then has the option to return an entirely new object
  575. which will replace the one given. If it returns ``None``, then the object
  576. is kept in place.
  577. The difference in usage between :func:`.visitors.cloned_traverse` and
  578. :func:`.visitors.replacement_traverse` is that in the former case, an
  579. already-cloned object is passed to the visitor function, and the visitor
  580. function can then manipulate the internal state of the object.
  581. In the case of the latter, the visitor function should only return an
  582. entirely different object, or do nothing.
  583. The use case for :func:`.visitors.replacement_traverse` is that of
  584. replacing a FROM clause inside of a SQL structure with a different one,
  585. as is a common use case within the ORM.
  586. """
  587. cloned = {}
  588. stop_on = {id(x) for x in opts.get("stop_on", [])}
  589. def deferred_copy_internals(obj):
  590. return replacement_traverse(obj, opts, replace)
  591. def clone(elem, **kw):
  592. if (
  593. id(elem) in stop_on
  594. or "no_replacement_traverse" in elem._annotations
  595. ):
  596. return elem
  597. else:
  598. newelem = replace(elem)
  599. if newelem is not None:
  600. stop_on.add(id(newelem))
  601. return newelem
  602. else:
  603. # base "already seen" on id(), not hash, so that we don't
  604. # replace an Annotated element with its non-annotated one, and
  605. # vice versa
  606. id_elem = id(elem)
  607. if id_elem not in cloned:
  608. if "replace" in kw:
  609. newelem = kw["replace"](elem)
  610. if newelem is not None:
  611. cloned[id_elem] = newelem
  612. return newelem
  613. cloned[id_elem] = newelem = elem._clone(**kw)
  614. newelem._copy_internals(clone=clone, **kw)
  615. return cloned[id_elem]
  616. if obj is not None:
  617. obj = clone(
  618. obj, deferred_copy_internals=deferred_copy_internals, **opts
  619. )
  620. clone = None # remove gc cycles
  621. return obj