o znh<@sdZddlmZddlZddlmZddlmZgdZGdd d eZ d d Z Gd d d e e e Z Gddde ZGdddeZGdddeZddZddZddZddZddZddZd d!ZdS)"a@Visitor/traversal interface and library functions. SQLAlchemy schema and expression constructs rely on a Python-centric version of the classic "visitor" pattern as the primary way in which they apply functionality. The most common use of this pattern is statement compilation, where individual expression classes match up to rendering methods that produce a string result. Beyond this, the visitor system is also used to inspect expressions for various information and patterns, as well as for the purposes of applying transformations to expressions. Examples of how the visit system is used can be seen in the source code of for example the ``sqlalchemy.sql.util`` and the ``sqlalchemy.sql.compiler`` modules. Some background on clause adaption is also at http://techspot.zzzeek.org/2008/01/23/expression-transformations/ . )dequeN)exc)util) VisitableType Visitable ClauseVisitorCloningVisitorReplacingCloningVisitoriterateiterate_depthfirsttraverse_usingtraversetraverse_depthfirstcloned_traversereplacement_traversecs eZdZdZfddZZS)rarMetaclass which assigns a ``_compiler_dispatch`` method to classes having a ``__visit_name__`` attribute. The ``_compiler_dispatch`` attribute becomes an instance method which looks approximately like the following:: def _compiler_dispatch (self, visitor, **kw): '''Look for an attribute named "visit_" + self.__visit_name__ on the visitor, and call it with the same kw params.''' visit_attr = 'visit_%s' % self.__visit_name__ return getattr(visitor, visit_attr)(self, **kw) Classes having no ``__visit_name__`` attribute will remain unaffected. cs2|dkr t|dr t|tt||||dS)Nr__visit_name__)hasattr_generate_dispatchsuperr__init__)clsclsnamebasesclsdict __class__B/usr/local/lib/python3.10/dist-packages/sqlalchemy/sql/visitors.pyrBszVisitableType.__init__)__name__ __module__ __qualname____doc__r __classcell__rrrrr1srcs\djvr,j}t|tjjrtd|fdd}nfdd}d|_|_ dSdS)zYReturn an optimized visit dispatch function for the cls for use by the compiler. rvisit_%scs8z|}Wn tyt|w||fi|SN)AttributeErrorrUnsupportedCompilationError)selfvisitorkwmethrgetterrr_compiler_dispatchVs    z._generate_dispatch.._compiler_dispatchcsDd|j}zt||}Wn tyt|w||fi|SNr$)rgetattrr&rr')r(r)r* visit_attrr+)rrrr.bs   zLook for an attribute named "visit_" + self.__visit_name__ on the visitor, and call it with the same kw params. N) __dict__r isinstancercompat string_typesoperator attrgetterr"r.)r visit_namer.rr,rrIs   rc@seZdZdZdS)rzBase class for visitable objects, applies the :class:`.visitors.VisitableType` metaclass. The :class:`.Visitable` class is essentially at the base of the :class:`.ClauseElement` hierarchy. N)rr r!r"rrrrrqsrc@sNeZdZdZiZddZddZddZej dd Z e d d Z d d Z dS)rzBase class for visitor objects which can traverse using the :func:`.visitors.traverse` function. Direct usage of the :func:`.visitors.traverse` function is usually preferred. cKs:|jD]}t|d|jd}|r||fi|SqdSr/)visitor_iteratorr0r)r(objr*vr+rrrtraverse_singles zClauseVisitor.traverse_singlecCs t||jS)zatraverse the given expression structure, returning an iterator of all elements. )r __traverse_options__r(r:rrrr s zClauseVisitor.iteratecCt||j|jS2traverse and visit the given expression structure.)rr= _visitor_dictr>rrrrszClauseVisitor.traversecCs6i}t|D]}|drt||||dd<q|S)Nvisit_)dir startswithr0)r(visitorsnamerrrrBs   zClauseVisitor._visitor_dictccs(|}|r|Vt|dd}|sdSdS)z8iterate through this visitor and each 'chained' visitor._nextN)r0)r(r;rrrr9s   zClauseVisitor.visitor_iteratorcCst|jd}||_|S)z'chain' an additional ClauseVisitor onto this ClauseVisitor. the chained visitor will receive all visit events after this one. )listr9rI)r(r)tailrrrchainszClauseVisitor.chainN)rr r!r"r=r<r rrmemoized_propertyrBpropertyr9rMrrrrr{s   rc@ eZdZdZddZddZdS)r zBase class for visitor objects which can traverse using the :func:`.visitors.cloned_traverse` function. Direct usage of the :func:`.visitors.cloned_traverse` function is usually preferred. csfdd|DS)z`Apply cloned traversal to the given list of elements, and return the new list. csg|]}|qSr)r.0xr(rr sz3CloningVisitor.copy_and_process..r)r(list_rrTrcopy_and_processszCloningVisitor.copy_and_processcCr?r@)rr=rBr>rrrrs zCloningVisitor.traverseN)rr r!r"rWrrrrrr s r c@rP)r zBase class for visitor objects which can traverse using the :func:`.visitors.replacement_traverse` function. Direct usage of the :func:`.visitors.replacement_traverse` function is usually preferred. cCsdS)areceive pre-copied elements during a cloning traversal. If the method returns a new element, the element is used instead of creating a simple copy of the element. Traversal will halt on the newly returned element if it is re-encountered. Nr)r(elemrrrreplaceszReplacingCloningVisitor.replacecsfdd}t|j|S)rAcs*jD]}||}|dur|SqdSr%)r9rY)rXr;erTrrrYs  z1ReplacingCloningVisitor.traverse..replace)rr=)r(r:rYrrTrrs z ReplacingCloningVisitor.traverseN)rr r!r"rYrrrrrr s r cCsl|jdi|}|s |gSt}t|g}|r2|}|||jdi|D]}||q(|st|S)a,traverse the given expression structure, returning an iterator. traversal is configured to be breadth-first. The central API feature used by the :func:`.visitors.iterate` and :func:`.visitors.iterate_depthfirst` functions is the :meth:`.ClauseElement.get_children` method of :class:`.ClauseElement` objects. This method should return all the :class:`.ClauseElement` objects which are associated with a particular :class:`.ClauseElement` object. For example, a :class:`.Case` structure will refer to a series of :class:`.ColumnElement` objects within its "whens" and "else\_" member variables. :param obj: :class:`.ClauseElement` structure to be traversed :param opts: dictionary of iteration options. This dictionary is usually empty in modern usage. Nr) get_childrenrpopleftappenditer)r:optschildren traversalstacktcrrrr s   r cCsl|jdi|}|s |gSt|g}t}|r2|}|||jdi|D]}||q(|st|S)atraverse the given expression structure, returning an iterator. traversal is configured to be depth-first. :param obj: :class:`.ClauseElement` structure to be traversed :param opts: dictionary of iteration options. This dictionary is usually empty in modern usage. .. seealso:: :func:`.visitors.iterate` - includes a general overview of iteration. Nr)r[rpop appendleftr]r^)r:r_r`rbrarcrdrrrr s   r cCs(|D]}||jd}|r||q|S)aEvisit the given expression structure using the given iterator of objects. :func:`.visitors.traverse_using` is usually called internally as the result of the :func:`.visitors.traverse` or :func:`.visitors.traverse_depthfirst` functions. :param iterator: an iterable or sequence which will yield :class:`.ClauseElement` structures; the iterator is assumed to be the product of the :func:`.visitors.iterate` or :func:`.visitors.iterate_depthfirst` functions. :param obj: the :class:`.ClauseElement` that was used as the target of the :func:`.iterate` or :func:`.iterate_depthfirst` function. :param visitors: dictionary of visit functions. See :func:`.traverse` for details on this dictionary. .. seealso:: :func:`.traverse` :func:`.traverse_depthfirst` N)getr)iteratorr:rGtargetr+rrrr -s r cCtt||||S)atraverse and visit the given expression structure using the default iterator. e.g.:: from sqlalchemy.sql import visitors stmt = select([some_table]).where(some_table.c.foo == 'bar') def visit_bindparam(bind_param): print("found bound value: %s" % bind_param.value) visitors.traverse(stmt, {}, {"bindparam": visit_bindparam}) The iteration of objects uses the :func:`.visitors.iterate` function, which does a breadth-first traversal using a stack. :param obj: :class:`.ClauseElement` structure to be traversed :param opts: dictionary of iteration options. This dictionary is usually empty in modern usage. :param visitors: dictionary of visit functions. The dictionary should have strings as keys, each of which would correspond to the ``__visit_name__`` of a particular kind of SQL expression object, and callable functions as values, each of which represents a visitor function for that kind of object. )r r r:r_rGrrrrNsrcCrj)a/traverse and visit the given expression structure using the depth-first iterator. The iteration of objects uses the :func:`.visitors.iterate_depthfirst` function, which does a depth-first traversal using a stack. Usage is the same as that of :func:`.visitors.traverse` function. )r r rkrrrros rcs>it|dgfdd|dur|}d|S)aclone the given expression structure, allowing modifications by visitors. Traversal usage is the same as that of :func:`.visitors.traverse`. The visitor functions present in the ``visitors`` dictionary may also modify the internals of the given structure as the traversal proceeds. The central API feature used by the :func:`.visitors.cloned_traverse` and :func:`.visitors.replacement_traverse` functions, in addition to the :meth:`.ClauseElement.get_children` function that is used to achieve the iteration, is the :meth:`.ClauseElement._copy_internals` method. For a :class:`.ClauseElement` structure to support cloning and replacement traversals correctly, it needs to be able to pass a cloning function into its internal members in order to make copies of them. .. seealso:: :func:`.visitors.traverse` :func:`.visitors.replacement_traverse` stop_oncsf|vr|St|vr-|t|<}|jddi||jd}|r-||t|S)Ncloner)id_clone_copy_internalsrgr)rXr*newelemr+rmclonedrlrGrrrms  zcloned_traverse..cloneN)setrgrkrrrrr}s rcsLidd|dgDfdd|dur"|fi|}d|S)a]clone the given expression structure, allowing element replacement by a given replacement function. This function is very similar to the :func:`.visitors.cloned_traverse` function, except instead of being passed a dictionary of visitors, all elements are unconditionally passed into the given replace function. The replace function then has the option to return an entirely new object which will replace the one given. if it returns ``None``, then the object is kept in place. The difference in usage between :func:`.visitors.cloned_traverse` and :func:`.visitors.replacement_traverse` is that in the former case, an already-cloned object is passed to the visitor function, and the visitor function can then manipulate the internal state of the object. In the case of the latter, the visitor function should only return an entirely different object, or do nothing. The use case for :func:`.visitors.replacement_traverse` is that of replacing a FROM clause inside of a SQL structure with a different one, as is a common use case within the ORM. cSsh|]}t|qSr)rnrQrrr sz'replacement_traverse..rlcspt|vs d|jvr |S|}|durt||S|vr4||<}|jddi||S)Nno_replacement_traversermr)rn _annotationsaddrorp)rXr*rqrmrsrYrlrrrms  z#replacement_traverse..cloneN)rg)r:r_rYrryrrsr)r" collectionsrr6rr__all__typerrwith_metaclassobjectrrr r r r r rrrrrrrrs&   ( :#!! /