o
    [hD>                     @   s   d Z ddlmZ ddlZddlmZ ddlmZ g dZG dd	 d	eZ	d
d Z
G dd dee	eZG dd deZG dd deZG dd deZdd Zdd Zdd Zdd Zdd Zdd Zd d! ZdS )"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ClauseVisitorCloningVisitorReplacingCloningVisitoriterateiterate_depthfirsttraverse_usingtraversetraverse_depthfirstcloned_traversereplacement_traversec                       s    e Zd ZdZ fddZ  ZS )r   ar  Metaclass 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.

    c                    s2   |dkrt | drt|  tt| ||| d S )Nr   __visit_name__)hasattr_generate_dispatchsuperr   __init__)clsZclsnamebasesZclsdict	__class__ ~/home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/site-packages/sqlalchemy/sql/visitors.pyr   B   s   zVisitableType.__init__)__name__
__module____qualname____doc__r   __classcell__r   r   r   r   r   1   s    r   c                    s\   d j v r, j}t|tjjrtd|  fdd}n fdd}d|_| _	dS dS )zZReturn an optimized visit dispatch function for the cls
    for use by the compiler.

    r   visit_%sc              
      sZ   z|}W n t y$ } ztjt| |d W Y d }~d S d }~ww || fi |S )NZreplace_context)AttributeErrorr   raise_r   UnsupportedCompilationError)selfvisitorkwmetherrr   getterr   r   _compiler_dispatchW   s   
z._generate_dispatch.<locals>._compiler_dispatchc              
      sf   d| j  }zt||}W n ty* } ztjt| |d W Y d }~d S d }~ww || fi |S )Nr"   r#   )r   getattrr$   r   r%   r   r&   )r'   r(   r)   Z
visit_attrr*   r+   )r   r   r   r.   f   s   

zLook for an attribute named "visit_" + self.__visit_name__
            on the visitor, and call it with the same kw params.
            N)
__dict__r   
isinstancer   compatstring_typesoperator
attrgetterr    r.   )r   Z
visit_namer.   r   r,   r   r   I   s   

r   c                   @   s   e Zd ZdZdS )r   zBase class for visitable objects, applies the
    :class:`.visitors.VisitableType` metaclass.

    The :class:`.Visitable` class is essentially at the base of the
    :class:`_expression.ClauseElement` hierarchy.

    N)r   r   r   r    r   r   r   r   r   x   s    r   c                   @   sN   e Zd ZdZi Zdd Zdd Zdd Zej	dd	 Z
ed
d Zdd ZdS )r   zBase class for visitor objects which can traverse using
    the :func:`.visitors.traverse` function.

    Direct usage of the :func:`.visitors.traverse` function is usually
    preferred.

    c                 K   s:   | j D ]}t|d|j d }|r||fi |  S qd S )Nr"   )visitor_iteratorr/   r   )r'   objr)   vr*   r   r   r   traverse_single   s   
zClauseVisitor.traverse_singlec                 C   s   t || jS )zaTraverse the given expression structure, returning an iterator
        of all elements.

        )r   __traverse_options__r'   r7   r   r   r   r      s   zClauseVisitor.iteratec                 C      t || j| jS 2Traverse and visit the given expression structure.)r   r:   _visitor_dictr;   r   r   r   r      s   zClauseVisitor.traversec                 C   s6   i }t | D ]}|drt| |||dd  < q|S )Nvisit_   )dir
startswithr/   )r'   visitorsnamer   r   r   r?      s   
zClauseVisitor._visitor_dictc                 c   s(    | }|r|V  t |dd}|sdS dS )z8Iterate through this visitor and each 'chained' visitor._nextN)r/   )r'   r8   r   r   r   r6      s   zClauseVisitor.visitor_iteratorc                 C   s   t | jd }||_| S )z'Chain' an additional ClauseVisitor onto this ClauseVisitor.

        The chained visitor will receive all visit events after this one.

        )listr6   rF   )r'   r(   tailr   r   r   chain   s   zClauseVisitor.chainN)r   r   r   r    r:   r9   r   r   r   Zmemoized_propertyr?   propertyr6   rJ   r   r   r   r   r      s    

r   c                   @       e Zd ZdZdd Zdd ZdS )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.


    c                    s    fdd|D S )z`Apply cloned traversal to the given list of elements, and return
        the new list.

        c                    s   g | ]}  |qS r   )r   .0xr'   r   r   
<listcomp>   s    z3CloningVisitor.copy_and_process.<locals>.<listcomp>r   )r'   list_r   rP   r   copy_and_process   s   zCloningVisitor.copy_and_processc                 C   r<   r=   )r   r:   r?   r;   r   r   r   r      s   
zCloningVisitor.traverseN)r   r   r   r    rS   r   r   r   r   r   r	      s    	r	   c                   @   rL   )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.

    c                 C   s   dS )a  Receive 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'   elemr   r   r   replace   s   zReplacingCloningVisitor.replacec                    s    fdd}t | j|S )r>   c                    s*    j D ]}|| }|d ur|  S qd S )N)r6   rU   )rT   r8   erP   r   r   rU      s   

z1ReplacingCloningVisitor.traverse.<locals>.replace)r   r:   )r'   r7   rU   r   rP   r   r      s   z ReplacingCloningVisitor.traverseN)r   r   r   r    rU   r   r   r   r   r   r
      s    	r
   c                 C   sl   | j di |}|s| gS t }t| g}|r2| }|| |j di |D ]}|| q(|st|S )ar  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:`_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.

    Nr   )get_childrenr   popleftappenditer)r7   optschildren	traversalstacktcr   r   r   r      s   

r   c                 C   sl   | j di |}|s| gS t| g}t }|r2| }|| |j di |D ]}|| q(|st|S )a  Traverse the given expression structure, returning an iterator.

    Traversal is configured to be depth-first.

    :param obj: :class:`_expression.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   )rW   r   pop
appendleftrY   rZ   )r7   r[   r\   r^   r]   r_   r`   r   r   r   r     s   

r   c                 C   s(   | D ]}| |jd}|r|| q|S )ae  Visit 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:`_expression.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:`_expression.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   )iteratorr7   rD   targetr*   r   r   r   r   5  s   r   c                 C      t t| || |S )a  Traverse 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   r7   r[   rD   r   r   r   r   X  s   r   c                 C   rf   )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   rg   r   r   r   r   y  s   r   c                    s>   i t |dg  fdd | dur | } d | S )a  Clone 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_onc                    sf   | v r| S t | vr-|   t | < }|jdd i| |jd }|r-|| t |  S )Ncloner   )id_clone_copy_internalsrc   r   )rT   r)   newelemr*   ri   clonedrh   rD   r   r   ri     s   zcloned_traverse.<locals>.cloneN)setrc   rg   r   rn   r   r     s   r   c                    sL   i dd | dg D  fdd | dur" | f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.

    c                 S   s   h | ]}t |qS r   )rj   rM   r   r   r   	<setcomp>  s    z'replacement_traverse.<locals>.<setcomp>rh   c                    sp   t | v sd| jv r| S | }|d urt | |S | vr4|   | < }|jdd i| |  S )NZno_replacement_traverseri   r   )rj   Z_annotationsaddrk   rl   )rT   r)   rm   ri   ro   rU   rh   r   r   ri     s   
z#replacement_traverse.<locals>.cloneN)rc   )r7   r[   rU   r   rs   r   r     s   r   )r    collectionsr   r4    r   r   __all__typer   r   with_metaclassobjectr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   <module>   s&   /
:$#!0