You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

849 lines
27KB

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