U kfݍ @s>dZddlmZddlmZddlmZddlZddlZddl Z ddl m Z ddl m Z ddl m Z dd l m Z dd l mZdd l mZdd l mZdd l mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddlmZddlmZddlmZddlmZddl m!Z!ddl m"Z"ddl m#Z#errddl$m%Z%dd l&m'Z'e jsesdd!l(m)Z)dd"l(m*Z+ndd!l,m)Z)dd"l,m*Z+d#d$d%d&d'd(d)d*d+g Z-Gd,d-d-e"Z.Gd.d(d(Z/Gd/d*d*eZ0eee1e0fZ2Gd0d1d1Z3Gd2d3d3e"Z4Gd4d5d5Z5e0Z6d6d7d8d9Z7e5j8Z8e7Gd:d;d;e3e/Z9edd?d=Z;e e:gdfZedDd)d=Z?GdEd)d)ej@ZAGdFdGdGeAZBGdHdIdIeBZCe/ZDeAZEeBZFeCZGejHfdJdKdLdMdNd#ZIedOdPdQd6dRdSd$ZJedOd;dQd;dRdTd$ZJdOdJdQdJdRdUd$ZJedPdKdQd6dVdWd%ZKed;dKdQd;dVdXd%ZKdJdKdQdJdVdYd%ZKedPdKdQd6dVdZd&ZLeddKd]d>d^d`d'ZMed;dKd]d;d^dad'ZMdJdKd]dJd^dbd'ZMdS)cz5Visitor/traversal interface and library functions. ) annotations)deque)EnumN)Any)Callable)cast)ClassVar)Dict)Iterable)Iterator)List)Mapping)Optional)overload)Tuple)Type) TYPE_CHECKING)TypeVar)Union)exc)util) langhelpers)HAS_CYEXTENSION)Literal)Protocol)Self)_AnnotationDict) ColumnElement)prefix_anon_map)cache_anon_mapiteratetraverse_usingtraversecloned_traversereplacement_traverse VisitableExternalTraversalInternalTraversalanon_mapc@s eZdZdddddddZdS)_CompilerDispatchTyper'rselfvisitorkwreturncKsdSN)_selfr-r.r/r2r2G/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/sql/visitors.py__call__Kz_CompilerDispatchType.__call__N__name__ __module__ __qualname__r5r2r2r2r4r+Jsr+csveZdZUdZdZded<ded<ejr:ddddd d Zd d fd d Z e d d ddZ dddddZ Z S)r'a,Base class for visitable objects. :class:`.Visitable` is used to implement the SQL compiler dispatch functions. Other forms of traversal such as for cache key generation are implemented separately using the :class:`.HasTraverseInternals` interface. .. versionchanged:: 2.0 The :class:`.Visitable` class was named :class:`.Traversible` in the 1.4 series; the name is changed back to :class:`.Visitable` in 2.0 which is what it was prior to 1.4. Both names remain importable in both 1.4 and 2.0 versions. r2str__visit_name__r+_original_compiler_dispatchr)r.r/r0cKsdSr1r2)r-r.r/r2r2r4_compiler_dispatchfr6zVisitable._compiler_dispatchNoner0cs d|jkr|tdS)Nr<)__dict___generate_compiler_dispatchsuper__init_subclass__)cls __class__r2r4rDhs zVisitable.__init_subclass__cst|j}d|jkr|j|_dSt|ts:td|jdd|}t |dddddfd d }||_|_dS) Nr>z__visit_name__ on class z$ must be a string at the class levelvisit_%sr'rr;r,c sTz |}Wn6tk rB}z|j||f|WYSd}~XYnX||f|SdS)zLook for an attribute named "visit_" on the visitor, and call it with the same kw params. N)AttributeErrorZvisit_unsupported_compilation)r-r.r/metherrgetterr2r4r>s  &zAVisitable._generate_compiler_dispatch.._compiler_dispatch) r<rAr>r= isinstancer;rZInvalidRequestErrorr8operator attrgetter)rE visit_namenamer>r2rLr4rBms    z%Visitable._generate_compiler_dispatch)keyr0cCs|Sr1r2)rErSr2r2r4__class_getitem__szVisitable.__class_getitem__)r8r9r:__doc__ __slots____annotations__typingrr>rD classmethodrBrT __classcell__r2r2rFr4r'Ns %c@seZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(d'Z)d(Z*d)S)*r)aDefines 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 :: class Case(ColumnElement[_T]): _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 to which each attribute refers. Using the ``_traverse_internals`` structure, objects of type :class:`.InternalTraversible` will have the following methods automatically implemented: * :meth:`.HasTraverseInternals.get_children` * :meth:`.HasTraverseInternals._copy_internals` * :meth:`.HasCacheKey._gen_cache_key` Subclasses can also implement these methods directly, particularly for the :meth:`.HasTraverseInternals._copy_internals` method, when special steps are needed. .. versionadded:: 1.4 ZHCZHLZCEZFCZCTSZCLZCTZEOZWCZCOSZSLANBOTZPDZDOZCDZMDZAKZPOZDDZPSZTHZSJZMEZSHZUKZDML_OVZDML_VZDML_MVZPAZIGZISMZMTZHTZILN)+r8r9r:rUZdp_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_attrsZ dp_ignoreZdp_inspectableZdp_multiZ dp_multi_listZdp_has_cache_key_tuplesZdp_inspectable_listr2r2r2r4r)sR'      c@sLeZdZUdZdZded<dZded<eddd d d d d ddZ dS)HasTraverseInternalsabase for classes that have a "traverse internals" element, which defines all kinds of ways of traversing the elements of an object. Compared to :class:`.Visitable`, which relies upon an external visitor to define how the object is travered (i.e. the :class:`.SQLCompiler`), the :class:`.HasTraverseInternals` interface allows classes to define their own traversal, that is, what attributes are accessed and in what order. r2_TraverseInternalsType_traverse_internalsFbool _is_immutablezsqlalchemy.sql.traversals omit_attrsTuple[str, ...]rzIterable[HasTraverseInternals]rgr/r0c sXtjj}z |j}Wntk r*gYSX|jj}tj fdd|||dDS)aReturn immediate child :class:`.visitors.HasTraverseInternals` elements of this :class:`.visitors.HasTraverseInternals`. 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||fVqdSr1r2).0attrnameobjrJr/rgr2r4 sz4HasTraverseInternals.get_children..Z!_generated_get_children_traversal) rZ preloadedZsql_traversalsrcrIZ _get_childrenrun_generated_dispatch itertoolschain from_iterable)r-rgr/Z traversalsZtraverse_internalsdispatchr2rmr4 get_childrens  z!HasTraverseInternals.get_childrenN) r8r9r:rUrVrWrerZpreload_modulertr2r2r2r4ras   rac@seZdZddddddZdS)_InternalTraversalDispatchTypeobjectHasTraversalDispatchrr-r.r0cCsdSr1r2)sr-r.r2r2r4r5r6z'_InternalTraversalDispatchType.__call__Nr7r2r2r2r4rusruc@sleZdZUdZdZiZded<ddddd Zd d d d dddZdd d ddddZ d d ddddZ dS)rwzcDefine infrastructure for classes that perform internal traversals .. versionadded:: 2.0 r2z2ClassVar[Dict[Union[InternalTraversal, str], str]]_dispatch_lookupr)zCallable[..., Any]) visit_symbolr0cCst|}t||dS)ztGiven a method from :class:`.HasTraversalDispatch`, return the corresponding method on a subclass. N)rzgetattr)r-r{rRr2r2r4rsszHasTraversalDispatch.dispatchrvrbr;r)targetinternal_dispatchgenerate_dispatcher_namer0cCs@z|jj|}Wn$tk r4||j||}YnX|||Sr1)rGrAKeyErrorgenerate_dispatch)r-r}r~r dispatcherr2r2r4ros z+HasTraversalDispatch.run_generated_dispatchz Type[object]ru) target_clsr~rr0cCs|||}t||||Sr1)_generate_dispatchersetattr)r-rr~rrr2r2r4rs  z&HasTraversalDispatch.generate_dispatch)r~ method_namer0c Cszg}|D]0\}}||}|dk rt|}|||fqdddd|Dd}d||d} ttt| i|S)Nz return [ z, css |]\}}d|||fVqdS)z! (%r, self.%s, visitor.%s)Nr2)rjrkrQr2r2r4rn1sz.z ] zdef %s(self, visitor):  )rsrzappendjoinrrurZ_exec_code_in_env) r-r~rnamesrkZ visit_symrJrQcodeZ meth_textr2r2r4r$s&     z)HasTraversalDispatch._generate_dispatcherN) r8r9r:rUrVrzrWrsrorrr2r2r2r4rws   rwr?r@cCsTt}tD]F}|j}|dr|dd}|j}||ks>t||||<||<qdS)NZdp_visit_)rzr)rR startswithreplacevalueAssertionError)lookupsymrSZ visit_keyZsym_namer2r2r4_generate_traversal_dispatchCs  rc@sveZdZUdZejZded<ej rJdddddZ dd d d d d ddZ d ddddZ dd d d dd ddZ dS)ExternallyTraversibler2zMapping[Any, Any] _annotationsrr)valuesr0cCsdSr1r2)r-rr2r2r4 _annotateZr6zExternallyTraversible._annotaterfrhrIterable[ExternallyTraversible]ricKsdSr1r2r-rgr/r2r2r4rt\sz"ExternallyTraversible.get_children)r/r0cKs tdS)zclone this elementNNotImplementedError)r-r/r2r2r4_clone`szExternallyTraversible._cloner?cKs tdS)atReassign internal elements to be clones of themselves. Called during a copy-and-traverse operation on newly shallow-copied elements to create a deep copy. The given clone function should be used, which may be applying additional transformations to the element (i.e. replacement traversal, cloned traversal, annotations). Nrrr2r2r4_copy_internalsds z%ExternallyTraversible._copy_internalsN)r8r9r:rVr EMPTY_DICTrrWrXrrrtrrr2r2r2r4rSs r_ET)bound_CEzColumnElement[Any]c@seZdZddddddZdS)_CloneCallableTyperrelementr/r0cKsdSr1r2r-rr/r2r2r4r5|r6z_CloneCallableType.__call__Nr7r2r2r2r4r{src@seZdZddddddZdS)_TraverseTransformCallableTyperrz Optional[_ET]rcKsdSr1r2rr2r2r4r5r6z'_TraverseTransformCallableType.__call__Nr7r2r2r2r4rsr_ExtTc@seZdZUdZdZiZded<ded<dddd d d Zd d dddZe dddddZ e dddddZ d d dddZ ddddZ e ddddZ dddd d!d"Zd#S)$r(zBase 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. ) _visitor_dict_nextzDict[str, Any]__traverse_options__zOptional[ExternalTraversal]rr'r)rlr/r0cKs6|jD]*}t|d|jd}|r||f|SqdS)NrH)visitor_iteratorr|r<)r-rlr/vrJr2r2r4traverse_singles z!ExternalTraversal.traverse_singleOptional[ExternallyTraversible]Iterator[ExternallyTraversible]rlr0cCs t||jS)zaTraverse the given expression structure, returning an iterator of all elements. )r"rr-rlr2r2r4r"szExternalTraversal.iterate Literal[None]r?cCsdSr1r2rr2r2r4r$szExternalTraversal.traversercCsdSr1r2rr2r2r4r$scCst||j|jS2Traverse and visit the given expression structure.)r$rrrr2r2r4r$sz%Dict[str, _TraverseCallableType[Any]]r@cCs6i}t|D]$}|dr t||||dd<q |S)Nr)dirrr|)r-visitorsrRr2r2r4_memoized_attr__visitor_dicts   z.ExternalTraversal._memoized_attr__visitor_dictzIterator[ExternalTraversal]ccs |}|r|Vt|dd}qdS)z8Iterate through this visitor and each 'chained' visitor.rN)r|)r-rr2r2r4rsz"ExternalTraversal.visitor_iteratorrrxcCst|jd}||_|S)z'Chain' an additional ExternalTraversal onto this ExternalTraversal The chained visitor will receive all visit events after this one. )listrr)r-r.tailr2r2r4rqszExternalTraversal.chainN)r8r9r:rUrVrrWrr"rr$rpropertyrrqr2r2r2r4r(s    c@s\eZdZdZdZdddddZeddd d d Zed d d d d Zddd dd ZdS)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. r2zList[ExternallyTraversible])list_r0csfdd|DS)z`Apply cloned traversal to the given list of elements, and return the new list. csg|]}|qSr2)r$rjxr-r2r4 sz=CloningExternalTraversal.copy_and_process..r2)r-rr2rr4copy_and_processsz)CloningExternalTraversal.copy_and_processrr?rcCsdSr1r2rr2r2r4r$sz!CloningExternalTraversal.traversercCsdSr1r2rr2r2r4r$srcCst||j|jSr)r%rrrr2r2r4r$s N)r8r9r:rUrVrrr$r2r2r2r4rs  rc@s\eZdZdZdZdddddZedd d d d Zeddd d d Zddd dd ZdS)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. r2rr)elemr0cCsdS)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. Nr2)r-rr2r2r4rs z"ReplacingExternalTraversal.replacerr?rcCsdSr1r2rr2r2r4r$ sz#ReplacingExternalTraversal.traversecCsdSr1r2rr2r2r4r$scs$ddddfdd }t|j|S)rrrrrcs0jD]$}tt||}|dk r|SqdSr1)rrrr)rr/rerr2r4rs   z4ReplacingExternalTraversal.traverse..replace)r&r)r-rlrr2rr4r$s N)r8r9r:rUrVrrr$r2r2r2r4rs rrzMapping[str, Any]r)rloptsr0ccsd|dkr dS|V|jf|}|s&dSt|g}|r`|}|D]}|V||jf|q@q0dS)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)rtrpopleftr)rlrchildrenstackZ t_iteratortr2r2r4r"0s  rrz(Mapping[str, _TraverseCallableType[Any]])iteratorrlrr0cCsdSr1r2rrlrr2r2r4r#YscCsdSr1r2rr2r2r4r#ascCs(|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<)rrlrr}rJr2r2r4r#is  )rlrrr0cCsdSr1r2rlrrr2r2r4r$scCsdSr1r2rr2r2r4r$scCstt||||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"rr2r2r4r$s"cCsdSr1r2rr2r2r4r%scCsdSr1r2rr2r2r4r%scsjitdgdddfdd }ddddfdd |d k rb|fd |i}d |S) aClone the given expression structure, allowing modifications by visitors for mutable objects. 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 :func:`.cloned_traverse` function does **not** provide objects that are part of the :class:`.Immutable` interface to the visit methods (this primarily includes :class:`.ColumnClause`, :class:`.Column`, :class:`.TableClause` and :class:`.Table` objects). As this traversal is only intended to allow in-place mutation of objects, :class:`.Immutable` objects are skipped. The :meth:`.Immutable._clone` method is still called on each object to allow for objects to replace themselves with a different object based on a clone of their sub-internals (e.g. a :class:`.ColumnClause` that clones its subquery to return a new :class:`.ColumnClause`). .. versionchanged:: 2.0 The :func:`.cloned_traverse` function omits objects that are part of the :class:`.Immutable` interface. 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_onrrcs t|Sr1)r%rl)rrr2r4deferred_copy_internalssz0cloned_traverse..deferred_copy_internalsrrr/r0cs|kr |St|krd|krNttt|d|}|dk rN|t|<|S|jfdi|t|<}|jfdi||js|jd}|r||t|SdS)Nrclone) idrrrrrrerr<)rr/newelemrJ)rclonedrrr2r4r s$    zcloned_traverse..cloneNr)setr)rlrrrr2)rrrrrr4r%s-z#_TraverseTransformCallableType[Any])rlrrr0cCsdSr1r2rlrrr2r2r4r&1scCsdSr1r2rr2r2r4r&9scCsdSr1r2rr2r2r4r&AscspidddgDdddfdd }dddd fd d |d k rh|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|qSr2)rrr2r2r4 fsz'replacement_traverse..rrrcs t|Sr1)r&r)rrr2r4rhsz5replacement_traverse..deferred_copy_internalsrrcst|ksd|jkr|S|}|dk r<t||St|}|krd|krt|d|}|dk rt||<|S|jf||<}|jfdi||SdS)NZno_replacement_traverserr)rraddrr)rr/rZid_elem)rrrrr2r4rms&  z#replacement_traverse..cloneNr)r)rlrrrr2)rrrrrr4r&Is)NrU __future__r collectionsrenumrrprOrXrrrrr r r r r rrrrrrrrrrZ util._has_cyrZ util.typingrrr annotationrelementsrZ_py_utilr r!r*Zsqlalchemy.cyextension.util__all__r+r'r)r;rbrarurwZExtendedInternalTraversalrrzrrrZ_TraverseCallableTyperrrZ MemoizedSlotsr(rrZ TraversibleZ ClauseVisitorZCloningVisitorZReplacingCloningVisitorrr"r#r$r%r&r2r2r2r4s                                J4O !   J'2)$% [