U am @sLdZddlmZddlZddlZddlmZddlmZddlmZddlm Z d d d d d ddddg Z ddZ Gddde Z Gdddee ZGddde ZddZGdddeeeZGdddeZGdddeZGdddeZGd d!d!eZeZe ZeZeZeZefd"d Zd#d Zd$d Z d%d Z!d&d Z"dS)'aAVisitor/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 https://techspot.zzzeek.org/2008/01/23/expression-transformations/ . )dequeN)exc)util) langhelpers)symboliteratetraverse_usingtraversecloned_traversereplacement_traverse TraversibleTraversibleTypeExternalTraversalInternalTraversalcsh|j}d|jkr|j|_dSt|tjjs:t d|j d|}t |fdd}||_|_dS)zhGenerate a _compiler_dispatch() external traversal on classes with a __visit_name__ attribute. _compiler_dispatchNz>__visit_name__ on class %s must be a string at the class levelvisit_%sc sTz |}Wn6tk rB}z|j||f|WYSd}~XYnX||f|SdS)zwLook for an attribute named "visit_" on the visitor, and call it with the same kw params. N)AttributeErrorZvisit_unsupported_compilation)selfvisitorkwmetherrgetterXC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\sql\visitors.pyrGs  &z7_generate_compiler_dispatch.._compiler_dispatch) __visit_name____dict__rZ_original_compiler_dispatch isinstancercompat string_typesrZInvalidRequestError__name__operator attrgetter)cls visit_namenamerrrr_generate_compiler_dispatch0s"   r(cs eZdZdZfddZZS)ra9Metaclass which assigns dispatch attributes to various kinds of "visitable" classes. Attributes include: * The ``_compiler_dispatch`` method, corresponding to ``__visit_name__``. This is called "external traversal" because the caller of each visit() method is responsible for sub-traversing the inner elements of each object. This is appropriate for string compilers and other traversals that need to call upon the inner elements in a specific pattern. * internal traversal collections ``_children_traversal``, ``_cache_key_traversal``, ``_copy_internals_traversal``, generated from an optional ``_traverse_internals`` collection of symbols which comes from the :class:`.InternalTraversal` list of symbols. This is called "internal traversal" MARKMARK cs0|dkrd|krt|tt||||dS)Nr r)r(superr__init__)r%clsnamebasesclsdict __class__rrr*mszTraversibleType.__init__)r" __module__ __qualname____doc__r* __classcell__rrr.rrYsc@s$eZdZdZeddddZdS)r zeBase class for visitable objects, applies the :class:`.visitors.TraversibleType` metaclass. zsqlalchemy.sql.traversalsrc sXtjj}z |j}Wntk r*gYSX|jj}tj fdd|||dDS)aReturn immediate child :class:`.visitors.Traversible` elements of this :class:`.visitors.Traversible`. This is used for visit traversal. \**kw may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level). c3s0|](\}}}|kr|dk r||fVqdSNr).0attrnameobjrr omit_attrsrr sz+Traversible.get_children..Z!_generated_get_children_traversal) rZ preloadedZsql_traversalsZ_traverse_internalsrZ _get_childrenrun_generated_dispatch itertoolschain from_iterable)rr9rZ traversalsZtraverse_internalsdispatchrr8r get_children{s  zTraversible.get_childrenN)r)r"r0r1r2rZpreload_moduler@rrrrr uscseZdZfddZZS)_InternalTraversalTypec s|jdkrxi}|D]D\}}|dr|dd}|j}||ksJt||||<||<qt|drr||j||_t t | |||dS)N)rExtendedInternalTraversalZdp_visit__dispatch_lookup) r"items startswithreplacer'AssertionErrorhasattrupdaterDr)rAr*) r%r+r,r-lookupkeysymZ visit_keyZsym_namer.rrr*s     z_InternalTraversalType.__init__)r"r0r1r*r3rrr.rrAsrAc Csrg}|D].\}}||}|rtj|}|||fqdddd|Dd}d||d} t| i|S)Nz return [ z, css |]\}}d|||fVqdS)z! (%r, self.%s, visitor.%s)Nr)r5r6r&rrrr:sz'_generate_dispatcher..z ] zdef %s(self, visitor):  )r?rBrDappendjoinrZ_exec_code_in_env) rinternal_dispatch method_namenamesr6Z visit_symrr&codeZ meth_textrrr_generate_dispatchers      rUc@s0eZdZdZddZddZddZedZed Z ed Z ed Z ed Z ed Z edZedZedZedZedZedZedZedZedZedZedZedZedZedZedZedZedZedZed Z ed!Z!ed"Z"ed#Z#ed$Z$ed%Z%ed&Z&ed'Z'ed(Z(d)S)*raDefines visitor symbols used for internal traversal. The :class:`.InternalTraversal` class is used in two ways. One is that it can serve as the superclass for an object that implements the various visit methods of the class. The other is that the symbols themselves of :class:`.InternalTraversal` are used within the ``_traverse_internals`` collection. Such as, the :class:`.Case` object defines ``_traverse_internals`` as :: _traverse_internals = [ ("value", InternalTraversal.dp_clauseelement), ("whens", InternalTraversal.dp_clauseelement_tuples), ("else_", InternalTraversal.dp_clauseelement), ] Above, the :class:`.Case` class indicates its internal state as the attributes named ``value``, ``whens``, and ``else_``. They each link to an :class:`.InternalTraversal` method which indicates the type of datastructure referred towards. Using the ``_traverse_internals`` structure, objects of type :class:`.InternalTraversible` will have the following methods automatically implemented: * :meth:`.Traversible.get_children` * :meth:`.Traversible._copy_internals` * :meth:`.Traversible._gen_cache_key` Subclasses can also implement these methods directly, particularly for the :meth:`.Traversible._copy_internals` method, when special steps are needed. .. versionadded:: 1.4 cCs|j|}t||dS)zqGiven a method from :class:`.InternalTraversal`, return the corresponding method on a subclass. N)rDgetattr)rZ visit_symbolr'rrrr?s zInternalTraversal.dispatchcCs@z|jj|}Wn$tk r4||j||}YnX|||Sr4)r/rKeyErrorgenerate_dispatch)rtargetrQgenerate_dispatcher_name dispatcherrrrr;s z(InternalTraversal.run_generated_dispatchcCst|||}t||||Sr4)rUsetattr)rZ target_clsrQrZr[rrrrXs z#InternalTraversal.generate_dispatchZHCZHLZCEZFCZCTSZCLZCTZEOZWCZCOSZSLANBOTZPDZDOZCDZMDZAKZPOZDDZPSZTHZSJZMEZSHZUKZDML_OVZDML_VZDML_MVZPAN))r"r0r1r2r?r;rXrZdp_has_cache_keyZdp_has_cache_key_listZdp_clauseelementZ)dp_fromclause_canonical_column_collectionZdp_clauseelement_tuplesZdp_clauseelement_listZdp_clauseelement_tupleZdp_executable_optionsZdp_with_context_optionsZdp_fromclause_ordered_setZ dp_stringZdp_string_listZ dp_anon_nameZ dp_booleanZ dp_operatorZdp_typeZ dp_plain_dictZdp_dialect_optionsZdp_string_clauseelement_dictZdp_string_multi_dictZdp_annotations_keyZ dp_plain_objZdp_named_ddl_elementZdp_prefix_sequenceZdp_table_hint_listZdp_setup_join_tupleZdp_memoized_select_entitiesZdp_statement_hint_listZdp_unknown_structureZdp_dml_ordered_valuesZ dp_dml_valuesZdp_dml_multi_valuesZdp_propagate_attrsrrrrrsL&       c@s@eZdZdZedZedZedZedZedZ edZ dS) rBa[Defines additional symbols that are useful in caching applications. Traversals for :class:`_expression.ClauseElement` objects only need to use those symbols present in :class:`.InternalTraversal`. However, for additional caching use cases within the ORM, symbols dealing with the :class:`.HasCacheKey` class are added here. ZIGZISMZMTZHTZILN) r"r0r1r2rZ dp_ignoreZdp_inspectableZdp_multiZ dp_multi_listZdp_has_cache_key_tuplesZdp_inspectable_listrrrrrBs rBc@sNeZdZdZiZddZddZddZej dd Z e d d Z d d Z dS)rzBase class for visitor objects which can traverse externally using the :func:`.visitors.traverse` function. Direct usage of the :func:`.visitors.traverse` function is usually preferred. cKs6|jD]*}t|d|jd}|r||f|SqdS)Nr)visitor_iteratorrVr)rr7rvrrrrtraverse_singles z!ExternalTraversal.traverse_singlecCs t||jS)zaTraverse the given expression structure, returning an iterator of all elements. )r__traverse_options__rr7rrrr szExternalTraversal.iteratecCst||j|jS2Traverse and visit the given expression structure.)r rf _visitor_dictrgrrrr szExternalTraversal.traversecCs6i}t|D]$}|dr t||||dd<q |S)NrC)dirrFrV)rvisitorsr'rrrrjs   zExternalTraversal._visitor_dictccs |}|r|Vt|dd}qdS)z8Iterate through this visitor and each 'chained' visitor._nextN)rV)rrdrrrrcsz"ExternalTraversal.visitor_iteratorcCst|jd}||_|S)z'Chain' an additional ClauseVisitor onto this ClauseVisitor. The chained visitor will receive all visit events after this one. )listrcrn)rrtailrrrr=(szExternalTraversal.chainN)r"r0r1r2rfrerr rZmemoized_propertyrjpropertyrcr=rrrrrs  c@s eZdZdZddZddZdS)CloningExternalTraversalzBase 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 r5xrrr Bsz=CloningExternalTraversal.copy_and_process..r)rlist_rrvrcopy_and_process=sz)CloningExternalTraversal.copy_and_processcCst||j|jSrh)r rfrjrgrrrr Ds z!CloningExternalTraversal.traverseN)r"r0r1r2ryr rrrrrs3s rsc@s eZdZdZddZddZdS)ReplacingExternalTraversalzBase 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)relemrrrrGUsz"ReplacingExternalTraversal.replacecsfdd}t|j|S)rics*jD]}||}|dk r|SqdSr4)rcrG)r{rdervrrrGas  z4ReplacingExternalTraversal.traverse..replace)r rf)rr7rGrrvrr ^s z#ReplacingExternalTraversal.traverseN)r"r0r1r2rGr rrrrrzLs rzccsX|V|jf|}|sdSt|g}|rT|}|D]}|V||jf|q4q$dS)aHTraverse the given expression structure, returning an iterator. Traversal is configured to be breadth-first. The central API feature used by the :func:`.visitors.iterate` function is the :meth:`_expression.ClauseElement.get_children` method of :class:`_expression.ClauseElement` objects. This method should return all the :class:`_expression.ClauseElement` objects which are associated with a particular :class:`_expression.ClauseElement` object. For example, a :class:`.Case` structure will refer to a series of :class:`_expression.ColumnElement` objects within its "whens" and "else\_" member variables. :param obj: :class:`_expression.ClauseElement` structure to be traversed :param opts: dictionary of iteration options. This dictionary is usually empty in modern usage. N)r@rpopleftrO)r7optschildrenstackZ t_iteratortrrrrrs  cCs(|D]}||jd}|r||q|S)aVisit 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` function. :param iterator: an iterable or sequence which will yield :class:`_expression.ClauseElement` structures; the iterator is assumed to be the product of the :func:`.visitors.iterate` function. :param obj: the :class:`_expression.ClauseElement` that was used as the target of the :func:`.iterate` function. :param visitors: dictionary of visit functions. See :func:`.traverse` for details on this dictionary. .. seealso:: :func:`.traverse` N)getr)iteratorr7rmrYrrrrr s  cCstt||||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:`_expression.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)r7r~rmrrrr scsXitdgfdd}fdd|dk rP|fd|i}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:`_expression.ClauseElement.get_children` function that is used to achieve the iteration, is the :meth:`_expression.ClauseElement._copy_internals` method. For a :class:`_expression.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_oncs t|Sr4)r r7)r~rmrrdeferred_copy_internalssz0cloned_traverse..deferred_copy_internalscs|kr |St|krd|krD|d|}|dk rD|t|<|S|jf|t|<}|jfdi||jd}|r||t|SdS)NrGclone)id_clone_copy_internalsrr)r{rnewelemr)rclonedrrmrrrs   zcloned_traverse..cloneNr)setr)r7r~rmrr)rrr~rrmrr scs^idddgDfdd}fdd|dk rV|fd |i}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)rrtrrr +sz'replacement_traverse..rcs t|Sr4)r r)r~rGrrr-sz5replacement_traverse..deferred_copy_internalscst|ksd|jkr|S|}|dk r<t||St|}|krd|krt|d|}|dk rt||<|S|jf||<}|jfdi||SdS)NZno_replacement_traverserGr)rZ _annotationsaddrr)r{rrZid_elem)rrrGrrrr0s&  z#replacement_traverse..cloneNr)r)r7r~rGrr)rrr~rGrrr s)#r2 collectionsrr<r#rrrr__all__r(typerwith_metaclassr rArUobjectrrBrrsrzZ VisitableZ VisitableTypeZ ClauseVisitorZCloningVisitorZReplacingCloningVisitorZ immutabledictrr r r r rrrrsN      )' ):# !<