o
    gx                     @  s  d Z ddlmZ ddlZddlmZ ddlZddlmZ ddlZddl	Z	ddl
mZ ddl
mZ ddl
mZ dd	l
mZ dd
l
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
mZ ddl
m Z  ddl!m"Z" ddl!m#Z# ddl$m%Z% dd l$m&Z& dd!l'm(Z( dd"l#m)Z) dd#l#m*Z* dd$l#m+Z+ dd%l#m,Z, d&d'l!m-Z- d&d(l!m.Z. d&d)l!m/Z/ d&d*l/m0Z0 d&d+l/m1Z1 d&d,l/m
Z2 d&d-l3m4Z4 d&d.l3m5Z5 d&d/l3m6Z6 erdd0l!m7Z7 dd1l!m8Z8 dd2l!m9Z9 dd3l:m;Z; dd4l:m<Z< dd5l=m>Z> dd6l8m?Z? dd7l8m@Z@ dd8l8mAZA dd9l8mBZB dd:l8mCZC dd;l8mDZD dd<l8mEZE dd=lFmGZG dd>lFmHZH dd?lImJZJ dd@lImKZK ddAlImLZL d&dBlMmNZN d&dClMmOZO d&dDlPmQZQ d&dElPmRZR d&dFlPmSZS d&dGlPmTZT d&dHlPmUZU d&dIlPmVZV d&dJlPmWZW d&dKlPmXZX d&dLlPmYZY d&dMlPmZZZ d&dNl-m[Z[ esdZ7dZ8dZ9G dOdP dPeZ\e\j]Z]G dQdR dReZ^e^j_Z`edSedTZaedUedVef dTZbeececf ZdG dWdX dXeZeefdYZgG dZd[ d[e4ZhG d\d] d]e4ZiddbdcZjeddedTZkG dedf dfZlG dgdh dhelZmddldmZnddpdqZoedrdsdTZpG dtds dse2j4ZqddvdwZrdd|d}Zsd~d ZtdddZudddZvdddZwdddZxG dd deecef ZyG dd deecef Zze/{ddd Z|G dd dZ}G dd dZ~G dd de0ZG dd de0ZG dd deZG dd deZG dd dedZG dd dee%ZG dd de(ZG dd de"jZG dd de-jZG dd de)ZG dd deZG dd deZede decf ecZeddddZedddTZG dd dee ZG dd deeef ZedddTZG dd deecef ZG dd de/jeeef ZG dd de/jd ZdddƄZe]fddd̄ZdS )z4Foundational utilities common to many sql modules.

    )annotationsN)Enumzip_longest)Any)Callable)cast)Dict)	FrozenSet)Generic)Iterable)Iterator)List)Mapping)MutableMapping)
NamedTuple)NoReturn)Optional)overload)Sequence)Set)Tuple)Type)TYPE_CHECKING)TypeVar)Union   )roles)visitors)HasCacheKey)MemoizedHasCacheKey)HasCopyInternals)ClauseVisitor)ExtendedInternalTraversal)ExternallyTraversible)InternalTraversal   )event)exc)util)HasMemoized)hybridmethod)typing)Protocol)Self)	TypeGuard)	coercionselements)type_api)DMLStrategyArgument)SynchronizeSessionArgument)_CLE)BindParameter)
ClauseList)ColumnClause)ColumnElement)NamedColumn)SQLCoreOperations)
TextClause)Column)DefaultGenerator)_JoinTargetElement)_SelectIterable)
FromClause)
Connection)CursorResult)_CoreMultiExecuteParams)_ExecuteOptions)_ImmutableExecuteOptions)
CacheStats)Compiled)CompiledCacheType)CoreExecuteOptionsParameter)Dialect)IsolationLevel)SchemaTranslateMapType)
dispatcherc                   @  s   e Zd ZdZdd ZdS )_NoArgr   c                 C  s   d| j  S )Nz_NoArg.)nameself rT   U/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/sqlalchemy/sql/base.py__repr__j      z_NoArg.__repr__N)__name__
__module____qualname__NO_ARGrV   rT   rT   rT   rU   rP   g       rP   c                   @  s   e Zd ZdZdS )	_NoneNamer   N)rX   rY   rZ   	NONE_NAMErT   rT   rT   rU   r]   q   s    r]   _T)bound_Fn.c                   @  s<   e Zd ZU ded< ded< ded< ded< edd
dZdS )_DefaultDescriptionTupler   argzOptional[bool]	is_scalaris_callableis_sentineldefaultOptional[DefaultGenerator]returnc                 C  s:   |r|j s|js|jrt|j|j|j|jS td d d d S N)has_arg
for_updaterf   rb   rc   rd   re   )clsrg   rT   rT   rU   _from_column_default   s    		z-_DefaultDescriptionTuple._from_column_defaultN)rg   rh   ri   rb   )rX   rY   rZ   __annotations__classmethodrn   rT   rT   rT   rU   rb      s   
 rb   _omit_from_statementsc                   @  s   e Zd ZdddZdS )	_EntityNamespacekeystrri   SQLCoreOperations[Any]c                 C     d S rj   rT   rS   rs   rT   rT   rU   __getattr__       z_EntityNamespace.__getattr__N)rs   rt   ri   ru   )rX   rY   rZ   rx   rT   rT   rT   rU   rr          rr   c                   @  s   e Zd ZejdddZdS )_HasEntityNamespaceri   rr   c                 C  rv   rj   rT   rR   rT   rT   rU   entity_namespace      z$_HasEntityNamespace.entity_namespaceN)ri   rr   )rX   rY   rZ   r)   ro_non_memoized_propertyr|   rT   rT   rT   rU   r{      s    r{   elementr   ri   TypeGuard[_HasEntityNamespace]c                 C  s
   t | dS )Nr|   )hasattr)r   rT   rT   rU   _is_has_entity_namespace      
r   _Selfc                   @  sB   e Zd ZdZdZdZdd Zdd ZdddZdddddZ	dS )	Immutablea%  mark a ClauseElement as 'immutable' when expressions are cloned.

    "immutable" objects refers to the "mutability" of an object in the
    context of SQL DQL and DML generation.   Such as, in DQL, one can
    compose a SELECT or subquery of varied forms, but one cannot modify
    the structure of a specific table or column within DQL.
    :class:`.Immutable` is mostly intended to follow this concept, and as
    such the primary "immutable" objects are :class:`.ColumnClause`,
    :class:`.Column`, :class:`.TableClause`, :class:`.Table`.

    rT   Tc                 O     t dNz(Immutable objects do not support copyingNotImplementedErrorrS   optionaldictkwargsrT   rT   rU   unique_params      zImmutable.unique_paramsc                 O  r   r   r   r   rT   rT   rU   params   r   zImmutable.paramsrS   r   kwr   ri   c                 K  s   | S rj   rT   rS   r   rT   rT   rU   _clone   r}   zImmutable._clone)
omit_attrsr   Iterable[str]Nonec                K  rv   rj   rT   )rS   r   r   rT   rT   rU   _copy_internals      zImmutable._copy_internalsN)rS   r   r   r   ri   r   )r   r   r   r   ri   r   )
rX   rY   rZ   __doc__	__slots___is_immutabler   r   r   r   rT   rT   rT   rU   r      s    
r   c                   @  sD   e Zd ZU dZdZd ed< dd
dZejdddZ	e
dd ZdS )SingletonConstantz.Represent SQL constants like NULL, TRUE, FALSET
_singletonrm   r_   rc   r   r   ri   c                 O  s   t t| jS rj   )r   r_   r   )rm   rc   r   rT   rT   rU   __new__   rW   zSingletonConstant.__new__FrozenSet[ColumnElement[Any]]c                 C     t  rj   r   rR   rT   rT   rU   	proxy_set      zSingletonConstant.proxy_setc                 C  s(   t | }|  t|g|_|| _d S rj   )objectr   __init__	frozensetr   r   )rm   objrT   rT   rU   _create_singleton   s   
	
z#SingletonConstant._create_singletonN)rm   r_   rc   r   r   r   ri   r_   )ri   r   )rX   rY   rZ   r   _is_singleton_constantro   r   r)   non_memoized_propertyr   rp   r   rT   rT   rT   rU   r      s   
 
r   r2   EUnion[ColumnElement[Any], FromClause, TextClause, _JoinTargetElement]Iterator[FromClause]c                  G     t jdd | D S )Nc                 S     g | ]}|j qS rT   )_from_objects).0r   rT   rT   rU   
<listcomp>       z!_from_objects.<locals>.<listcomp>	itertoolschainfrom_iterabler1   rT   rT   rU   r      s   r   !Iterable[roles.ColumnsClauseRole]rA   c                 C  r   )zXexpand tables into individual columns in the
    given list of column expressions.

    c                 S  r   rT   )_select_iterabler   crT   rT   rU   r      r   z%_select_iterables.<locals>.<listcomp>r   r1   rT   rT   rU   _select_iterables   s   r   _SelfGenerativeType_GenerativeTypec                   @  s   e Zd ZdddZdS )r   ri   r.   c                 C  rv   rj   rT   rR   rT   rT   rU   	_generate  ry   z_GenerativeType._generateNri   r.   )rX   rY   rZ   r   rT   rT   rT   rU   r     rz   fnc                 C  s"   t jdd	d
}|| }| |_|S )znon-caching _generative() decorator.

    This is basically the legacy decorator that copies the object and
    runs a method on the new copy.

    r   ra   rS   r   argsr   r   ri   c                 _  s2   |  }| |g|R i |}||u sJ d|S )zMark a method as generative.z#generative methods must return self)r   )r   rS   r   r   xrT   rT   rU   _generative  s   z _generative.<locals>._generativeN)
r   ra   rS   r   r   r   r   r   ri   r   )r)   	decoratornon_generative)r   r   	decoratedrT   rT   rU   r     s
   
r   namesrt   r   Callable[[_Fn], _Fn]c                    sB   | di | di   fdd| D tjfdd}|S )Nmsgsdefaultsc                   s$   g | ]}|t | |d fqS rj   )operator
attrgetterget)r   rQ   )r   rT   rU   r   %  s    z&_exclusive_against.<locals>.<listcomp>c                   sh   |d }|dd  } D ]\}}}|||ur( |d| j|jf }t|q| |g|R i |S )Nr   r   z9Method %s() has already been invoked on this %s construct)r   rX   	__class__r(   InvalidRequestError)r   r   r   rS   rQ   getterdefault_msg)gettersr   rT   rU   check*  s   

z!_exclusive_against.<locals>.check)popr)   r   )r   r   r   rT   )r   r   r   rU   _exclusive_against   s   
r   c                 K  s   | j di |S NrT   )r   )r   r   rT   rT   rU   r   =     r   Iterable[_CLE]c                 C  s   t jdd | D  S )z\expand the given set of ClauseElements to be the set of all 'cloned'
    predecessors.

    c                 S  r   rT   )_cloned_setr   r   rT   rT   rU   r   I  r   z"_expand_cloned.<locals>.<listcomp>)r   r   r1   rT   rT   rU   _expand_clonedA  s   r   c                 c  s0    | D ]}|j d ur|j }|j d us
|V  qd S rj   )_is_clone_of)r2   r   rT   rT   rU   	_de_cloneL  s   

r   ab	Set[_CLE]c                   (   t t| t|  fdd| D S )zreturn the intersection of sets a and b, counting
    any overlap between 'cloned' predecessors.

    The returned set is in terms of the entities present within 'a'.

    c                   s   h | ]
}  |jr|qS rT   intersectionr   r   elemall_overlaprT   rU   	<setcomp>]      z'_cloned_intersection.<locals>.<setcomp>setr   r   r   r   rT   r   rU   _cloned_intersectionU  s   r   c                   r   )Nc                   s   h | ]
}  |js|qS rT   r   r   r   rT   rU   r   b  s
    z%_cloned_difference.<locals>.<setcomp>r   r   rT   r   rU   _cloned_difference`  s   
r   c                   @  sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dS )_DialectArgViewzaA dictionary view of dialect-level arguments in the form
    <dialectname>_<argument_name>.

    c                 C  
   || _ d S rj   )r   )rS   r   rT   rT   rU   r   m  r   z_DialectArgView.__init__c              
   C  s>   z| dd\}}W ||fS  ty } zt||d }~ww )N_r   )split
ValueErrorKeyError)rS   rs   dialect	value_keyerrrT   rT   rU   _keyp  s   
z_DialectArgView._keyc              
   C  sJ   |  |\}}z| jj| }W || S  tjy$ } zt||d }~ww rj   )r   r   dialect_optionsr(   NoSuchModuleErrorr   )rS   rs   r   r   optr   rT   rT   rU   __getitem__x  s   
z_DialectArgView.__getitem__c              
   C  sL   z	|  |\}}W n ty } ztd|d }~ww || jj| |< d S )Nz0Keys must be of the form <dialectname>_<argname>)r   r   r(   ArgumentErrorr   r   )rS   rs   valuer   r   r   rT   rT   rU   __setitem__  s   z_DialectArgView.__setitem__c                 C  s    |  |\}}| jj| |= d S rj   )r   r   r   )rS   rs   r   r   rT   rT   rU   __delitem__  s   z_DialectArgView.__delitem__c                 C  s   t dd | jj D S )Nc                 s  s    | ]}t |jV  qd S rj   )len_non_defaults)r   r   rT   rT   rU   	<genexpr>  s
    
z*_DialectArgView.__len__.<locals>.<genexpr>)sumr   r   valuesrR   rT   rT   rU   __len__  s   
z_DialectArgView.__len__c                   s    fdd j jD S )Nc                 3  s0    | ]} j j| jD ]	}d ||f V  qqdS )z%s_%sN)r   r   r  )r   dialect_name
value_namerR   rT   rU   r    s    
z+_DialectArgView.__iter__.<locals>.<genexpr>)r   r   rR   rT   rR   rU   __iter__  s   
z_DialectArgView.__iter__N)rX   rY   rZ   r   r   r   r   r   r   r  r  rT   rT   rT   rU   r   g  s    

r   c                   @  s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )_DialectArgDictzA dictionary view of dialect-level arguments for a specific
    dialect.

    Maintains a separate collection of user-specified arguments
    and dialect-specified default arguments.

    c                 C  s   i | _ i | _d S rj   r  	_defaultsrR   rT   rT   rU   r     s   
z_DialectArgDict.__init__c                 C     t t| j| jS rj   )r   r   r  unionr  rR   rT   rT   rU   r       z_DialectArgDict.__len__c                 C  r  rj   )iterr   r  r  r  rR   rT   rT   rU   r    r  z_DialectArgDict.__iter__c                 C  s   || j v r
| j | S | j| S rj   r
  rw   rT   rT   rU   r     s   


z_DialectArgDict.__getitem__c                 C  s   || j |< d S rj   r  rS   rs   r   rT   rT   rU   r     s   z_DialectArgDict.__setitem__c                 C  s   | j |= d S rj   r  rw   rT   rT   rU   r     rW   z_DialectArgDict.__delitem__N)
rX   rY   rZ   r   r   r  r  r   r   r   rT   rT   rT   rU   r	    s    r	  zsqlalchemy.dialectsc                 C  s(   t jjj| }|jd u rd S t|jS rj   )r)   	preloadeddialectsregistryloadconstruct_argumentsdict)r  dialect_clsrT   rT   rU   _kw_reg_for_dialect  s   

r  c                   @  sp   e Zd ZdZdZdejfgZedd Z	e
jdd Zedd	 Ze
eZd
d Ze
jdd ZdddZdS )DialectKWArgsa9  Establish the ability for a class to have dialect-specific arguments
    with defaults and constructor validation.

    The :class:`.DialectKWArgs` interacts with the
    :attr:`.DefaultDialect.construct_arguments` present on a dialect.

    .. seealso::

        :attr:`.DefaultDialect.construct_arguments`

    rT   r   c                 C  s@   t j| }|du rtd| | |vri || < |||  |< dS )a_  Add a new kind of dialect-specific keyword argument for this class.

        E.g.::

            Index.argument_for("mydialect", "length", None)

            some_index = Index("a", "b", mydialect_length=5)

        The :meth:`.DialectKWArgs.argument_for` method is a per-argument
        way adding extra arguments to the
        :attr:`.DefaultDialect.construct_arguments` dictionary. This
        dictionary provides a list of argument names accepted by various
        schema-level constructs on behalf of a dialect.

        New dialects should typically specify this dictionary all at once as a
        data member of the dialect class.  The use case for ad-hoc addition of
        argument names is typically for end-user code that is also using
        a custom compilation scheme which consumes the additional arguments.

        :param dialect_name: name of a dialect.  The dialect must be
         locatable, else a :class:`.NoSuchModuleError` is raised.   The
         dialect must also include an existing
         :attr:`.DefaultDialect.construct_arguments` collection, indicating
         that it participates in the keyword-argument validation and default
         system, else :class:`.ArgumentError` is raised.  If the dialect does
         not include this collection, then any keyword argument can be
         specified on behalf of this dialect already.  All dialects packaged
         within SQLAlchemy include this collection, however for third party
         dialects, support may vary.

        :param argument_name: name of the parameter.

        :param default: default value of the parameter.

        NzRDialect '%s' does have keyword-argument validation and defaults enabled configured)r  _kw_registryr(   r   )rm   r  argument_namerg   construct_arg_dictionaryrT   rT   rU   argument_for  s   
&zDialectKWArgs.argument_forc                 C     t | S )a  A collection of keyword arguments specified as dialect-specific
        options to this construct.

        The arguments are present here in their original ``<dialect>_<kwarg>``
        format.  Only arguments that were actually passed are included;
        unlike the :attr:`.DialectKWArgs.dialect_options` collection, which
        contains all options known by this dialect including defaults.

        The collection is also writable; keys are accepted of the
        form ``<dialect>_<kwarg>`` where the value will be assembled
        into the list of options.

        .. seealso::

            :attr:`.DialectKWArgs.dialect_options` - nested dictionary form

        )r   rR   rT   rT   rU   dialect_kwargs  s   zDialectKWArgs.dialect_kwargsc                 C     | j S )z4A synonym for :attr:`.DialectKWArgs.dialect_kwargs`.)r   rR   rT   rT   rU   r         zDialectKWArgs.kwargsc                 C  sZ   t j| }t }|d u r|jdd i |S t| jjD ]}||v r*|j||  q|S )N*)r  r  r	  r  updatereversedr   __mro__)rS   r  r  drm   rT   rT   rU   _kw_reg_for_dialect_cls'  s   
z%DialectKWArgs._kw_reg_for_dialect_clsc                 C  s   t t | jS )a  A collection of keyword arguments specified as dialect-specific
        options to this construct.

        This is a two-level nested registry, keyed to ``<dialect_name>``
        and ``<argument_name>``.  For example, the ``postgresql_where``
        argument would be locatable as::

            arg = my_object.dialect_options["postgresql"]["where"]

        .. versionadded:: 0.9.2

        .. seealso::

            :attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form

        )r)   PopulateDictportable_instancemethodr(  rR   rT   rT   rU   r   3  s   
zDialectKWArgs.dialect_optionsr   Dict[str, Any]ri   r   c              	   C  s   |sd S |D ]c}t d|}|std| |dd\}}z| j| }W n* tjyO   td||f  t	  | j|< }|j
dd i || |j|< Y qw d|vrc||vrctd||| jf || ||< qd S )Nz^(.+?)_(.+)$zGAdditional arguments should be named <dialectname>_<argument>, got '%s'r   r&   zHCan't validate argument %r; can't locate any SQLAlchemy dialect named %rr#  z9Argument %r is not accepted by dialect %r on behalf of %r)rematch	TypeErrorgroupr   r(   r   r)   warnr	  r  r$  r  r   r   )rS   r   kmr  arg_namer  r'  rT   rT   rU   _validate_dialect_kwargsJ  s@   
z&DialectKWArgs._validate_dialect_kwargsN)r   r+  ri   r   )rX   rY   rZ   r   r   r%   dp_dialect_options"_dialect_kwargs_traverse_internalsrp   r  r)   memoized_propertyr   propertyr   r)  r  r  r(  r   r4  rT   rT   rT   rU   r    s     
/



r  c                   @  sh   e Zd ZU dZdZi Zded< ded< edd Zd	d
 Z	edddZ
edddZedddZdS )CompileStatea  Produces additional object state necessary for a statement to be
    compiled.

    the :class:`.CompileState` class is at the base of classes that assemble
    state for a particular statement object that is then used by the
    compiler.   This process is essentially an extension of the process that
    the SQLCompiler.visit_XYZ() method takes, however there is an emphasis
    on converting raw user intent into more organized structures rather than
    producing string output.   The top-level :class:`.CompileState` for the
    statement being executed is also accessible when the execution context
    works with invoking the statement and collecting results.

    The production of :class:`.CompileState` is specific to the compiler,  such
    as within the :meth:`.SQLCompiler.visit_insert`,
    :meth:`.SQLCompiler.visit_select` etc. methods.  These methods are also
    responsible for associating the :class:`.CompileState` with the
    :class:`.SQLCompiler` itself, if the statement is the "toplevel" statement,
    i.e. the outermost SQL statement that's actually being executed.
    There can be other :class:`.CompileState` objects that are not the
    toplevel, such as when a SELECT subquery or CTE-nested
    INSERT/UPDATE/DELETE is generated.

    .. versionadded:: 1.4

    )	statement_ambiguous_table_name_mapz)Dict[Tuple[str, str], Type[CompileState]]pluginsz Optional[_AmbiguousTableNameMap]r;  c                 K  s   |j r!|j dd}| j||jfd }|d u r | jd|jf }n| jd|jf }|| u r6| ||fi |S |j||fi |S Ncompile_state_pluginrg   )_propagate_attrsr   r<  _effective_plugin_targetcreate_for_statement)rm   r:  compilerr   plugin_nameklassrT   rT   rU   rA    s$   
z!CompileState.create_for_statementc                 K  r   rj   )r:  )rS   r:  rB  r   rT   rT   rU   r     r   zCompileState.__init__r:  
Executableri   Optional[Type[CompileState]]c                 C  sX   |j dd }|r||jf}|| jv r| j| S z	| jd|jf W S  ty+   Y d S w r=  )r?  r   r@  r<  r   )rm   r:  rC  rs   rT   rT   rU   get_plugin_class  s   


zCompileState.get_plugin_classrC  rt   c                 C  s(   z	| j ||jf W S  ty   Y d S w rj   )r<  r@  r   )rm   r:  rC  rT   rT   rU   _get_plugin_class_for_plugin  s   z)CompileState._get_plugin_class_for_plugin
visit_namer   c                   s    fdd}|S )Nc                   s   |  j f< | S rj   )r<  )cls_to_decoraterm   rC  rI  rT   rU   decorate  s   z)CompileState.plugin_for.<locals>.decoraterT   )rm   rC  rI  rL  rT   rK  rU   
plugin_for  s   zCompileState.plugin_forN)r:  rE  ri   rF  )r:  rE  rC  rt   ri   rF  )rC  rt   rI  rt   ri   r   )rX   rY   rZ   r   r   r<  ro   rp   rA  r   rG  rH  rM  rT   rT   rT   rU   r9  r  s   
 

r9  c                   @  s   e Zd ZdZdddZdS )
GenerativezUProvide a method-chaining pattern in conjunction with the
    @_generative decorator.ri   r.   c                   sL   | j  | j}||} r fdd| j  D |_|S | j |_|S )Nc                   s   i | ]\}}| vr||qS rT   rT   )r   r1  vskiprT   rU   
<dictcomp>  s    z(Generative._generate.<locals>.<dictcomp>)_memoized_keysr   r   __dict__copyitems)rS   rm   srT   rP  rU   r     s   

zGenerative._generateNr   )rX   rY   rZ   r   r   rT   rT   rT   rU   rN    s    rN  c                   @  s   e Zd ZdZdZdd ZdS )InPlaceGenerativezkProvide a method-chaining pattern in conjunction with the
    @_generative decorator that mutates in place.rT   c                 C  s"   | j }|D ]	}| j|d  q| S rj   )rS  rT  r   )rS   rQ  r1  rT   rT   rU   r     s   zInPlaceGenerative._generateN)rX   rY   rZ   r   r   r   rT   rT   rT   rU   rX    s    rX  c                   @  s2   e Zd ZU dZdZded< ejZded< e	j
ZdS )HasCompileStatez=A class that has a :class:`.CompileState` associated with it.NrF  _compile_state_pluginutil.immutabledict[str, Any]_attributes)rX   rY   rZ   r   rZ  ro   r)   
EMPTY_DICTr\  r9  rA  _compile_state_factoryrT   rT   rT   rU   rY    s
   
 
rY  c                   @  sH   e Zd ZU dZded< dd Zer"dd
dZdddZdddZ	dS dS )_MetaOptionszmetaclass for the Options class.

    This metaclass is actually necessary despite the availability of the
    ``__init_subclass__()`` hook as this type also provides custom class-level
    behavior for the ``__add__()`` method.

    Tuple[str, ...]_cache_attrsc                 C  sB   |  }t || jrtd| t || jf |j| |S NzBdictionary contains attributes not covered by Options class %s: %r)r   
differencera  r.  rT  r$  rS   othero1rT   rT   rU   __add__  s   z_MetaOptions.__add__rs   rt   ri   r   c                 C  rv   rj   rT   rw   rT   rT   rU   rx      ry   z_MetaOptions.__getattr__r   r   c                 C  rv   rj   rT   r  rT   rT   rU   __setattr__"  ry   z_MetaOptions.__setattr__c                 C  rv   rj   rT   rw   rT   rT   rU   __delattr__$  ry   z_MetaOptions.__delattr__Nrs   rt   ri   r   rs   rt   r   r   ri   r   rs   rt   ri   r   )
rX   rY   rZ   r   ro   rg  r   rx   rh  ri  rT   rT   rT   rU   r_    s   
 

r_  c                      s   e Zd ZU dZdZded< d- fddZd	d
 Zdd Zdd Z	dd Z
ed.ddZedd Zed/ddZejZded< ejd/ddZedd  Zed!d" Zerhd0d&d'Zd1d)d*Zd2d+d,Z  ZS   ZS )3Optionsz,A cacheable option dictionary with defaults.rT   r`  ra  ri   r   c                   s,   | j }ttdd |D | _t   d S )Nc                 s  s&    | ]}| d s|dvr|V  qdS )__)_cache_key_traversalN)
startswith)r   r'  rT   rT   rU   r  1  s    z,Options.__init_subclass__.<locals>.<genexpr>)rT  tuplesortedra  super__init_subclass__)rm   dict_r   rT   rU   rt  .  s   zOptions.__init_subclass__c                 K  s   | j | d S rj   )rT  r$  r   rT   rT   rU   r   :  r   zOptions.__init__c                 C  sX   | j | j }|j| j t|| jr$td| t|| jf |j| |S rb  )r   r   rT  r$  r   rc  ra  r.  rd  rT   rT   rU   rg  =  s   zOptions.__add__c                 C  s6   t | j|jD ]\}}t| |t||kr dS qdS NFT)r   ra  getattr)rS   re  r   r   rT   rT   rU   __eq__K  s
   zOptions.__eq__c                   s&   d j jd fdd jD f S )N%s(%s), c                 3  s,    | ]}| j v rd | j | f V  qdS )z%s=%rNrT  )r   r1  rR   rT   rU   r  X  s    
z#Options.__repr__.<locals>.<genexpr>)r   rX   joinra  rR   rT   rR   rU   rV   S  s   zOptions.__repr__rD  	Type[Any]boolc                 C  s
   t | |S rj   )
issubclass)rm   rD  rT   rT   rU   
isinstance_     
zOptions.isinstancec                 C  s   | |t | || i S rj   )rx  )rS   rQ   r   rT   rT   rU   add_to_elementc  s   zOptions.add_to_elementMapping[str, Any]c                 C  r!  rj   r|  rR   rT   rT   rU   _state_dict_instg  r   zOptions._state_dict_instr[  _state_dict_constc                 C  r!  rj   )r  )rm   rT   rT   rU   _state_dictm  r   zOptions._state_dictc                 C  sR   |  }| |jur%|jr%t|j| jr%td|| t|j| jf | | S )Nz]other element %r is not empty, is not of type %s, and contains attributes not covered here %r)r  r   ra  r   rc  r.  )rm   re  r'  rT   rT   rU   
safe_mergeq  s   
	zOptions.safe_mergec                 C  s   | t||}||| }|rDi }|D ]}d| }	||v r'|| ||	< q||v r1|| ||	< q|| }
t |||
i}|
|fS ||fS )a-  process Options argument in terms of execution options.


        e.g.::

            (
                load_options,
                execution_options,
            ) = QueryContext.default_load_options.from_execution_options(
                "_sa_orm_load_options",
                {"populate_existing", "autoflush", "yield_per"},
                execution_options,
                statement._execution_options,
            )

        get back the Options and refresh "_sa_orm_load_options" in the
        exec options dict w/ the Options as well

        r   )r   r   r  r   r)   immutabledict
merge_with)rm   rs   attrsexec_optionsstatement_exec_optionscheck_argnamesexisting_optionsresultargnamelocalnew_optionsrT   rT   rU   from_execution_options  s&   zOptions.from_execution_optionsrs   rt   r   c                 C  rv   rj   rT   rw   rT   rT   rU   rx     ry   zOptions.__getattr__r   c                 C  rv   rj   rT   r  rT   rT   rU   rh    ry   zOptions.__setattr__c                 C  rv   rj   rT   rw   rT   rT   rU   ri    ry   zOptions.__delattr__)ri   r   )rD  r~  ri   r  )ri   r  rj  rk  rl  )rX   rY   rZ   r   r   ro   rt  r   rg  ry  rV   rp   r  r+   r  r  r)   r]  r  
classlevelr  r  r  r   rx   rh  ri  __classcell__rT   rT   rv  rU   rm  '  s6   
 


1

rm  )	metaclassc                   @  s6   e Zd ZdZedd Zejdd Zedd ZdS )	CacheableOptionsrT   c                 C  s   t | ||S rj   )r   _gen_cache_key)rS   anon_map
bindparamsrT   rT   rU   _gen_cache_key_inst  s   z$CacheableOptions._gen_cache_key_instc                 C  s   | dfS r   rT   )rm   r  r  rT   rT   rU   r    s   zCacheableOptions._gen_cache_keyc                 C  s
   t | S rj   )r   _generate_cache_key_for_objectrR   rT   rT   rU   _generate_cache_key  r  z$CacheableOptions._generate_cache_keyN)	rX   rY   rZ   r   r+   r  r  r  r  rT   rT   rT   rU   r    s    

r  c                   @  s*   e Zd ZdZejZdZdZdZ	dd Z
dS )ExecutableOptionrT   executable_optionFTc                 K  s   | j | j }t| j|_|S )z/Create a shallow copy of this ExecutableOption.)r   r   r  rT  )rS   r   r   rT   rT   rU   r     s   zExecutableOption._cloneN)rX   rY   rZ   r   r)   r]  _annotations__visit_name___is_has_cache_key_is_corer   rT   rT   rT   rU   r    s    r  c                   @  sh  e Zd ZU dZdZded< ejZded< dZ	dZ
d	ed
< dZded< ded< d
ejfdejfdejfgZdZdZdZdZdZdZdZer[ded< dddd_d!d"Zd`d*d+Zdad,d-Zejd.d/ Zedbd0d1Z e!dcd5d6Z"e!ddd9d:Z#e!ded;d<Z$e!dfd@dAZ%e&dBdBdBdddBdBdBdBdddBdBdBdBdBddCdgdXdYZ'e&dhdZdYZ'e!did[dYZ'djd]d^Z(dS )krE  zMark a :class:`_expression.ClauseElement` as supporting execution.

    :class:`.Executable` is a superclass for all "statement" types
    of objects, including :func:`select`, :func:`delete`, :func:`update`,
    :func:`insert`, :func:`text`.

    Tr  supports_executionrG   _execution_optionsFrT   zTuple[ExecutableOption, ...]_with_optionsz6Tuple[Tuple[Callable[[CompileState], None], Any], ...]_with_context_optionsz9Optional[Union[Type[CacheableOptions], CacheableOptions]]_compile_optionsr?  rt   r  N)for_executemanyschema_translate_mapr   rL   compiled_cacheOptional[CompiledCacheType]column_keys	List[str]r  r   Optional[SchemaTranslateMapType]r   r   ri   CTuple[Compiled, Optional[Sequence[BindParameter[Any]]], CacheStats]c                K  rv   rj   rT   )rS   r   r  r  r  r  r   rT   rT   rU   _compile_w_cache  s   zExecutable._compile_w_cache
connectionrC   distilled_paramsrE   execution_optionsrK   CursorResult[Any]c                 C  rv   rj   rT   rS   r  r  r  rT   rT   rU   _execute_on_connection     z!Executable._execute_on_connectionc                 C  rv   rj   rT   r  rT   rT   rU   _execute_on_scalar!  r  zExecutable._execute_on_scalarc                 C  r   rj   r   rR   rT   rT   rU   _all_selected_columns(  r   z Executable._all_selected_columnsc                 C  r!  rj   )r  rR   rT   rT   rU   r@  ,  r   z#Executable._effective_plugin_targetoptionsr  r.   c                 G  s    |  j tdd |D 7  _ | S )aJ  Apply options to this statement.

        In the general sense, options are any kind of Python object
        that can be interpreted by the SQL compiler for the statement.
        These options can be consumed by specific dialects or specific kinds
        of compilers.

        The most commonly known kind of option are the ORM level options
        that apply "eager load" and other loading behaviors to an ORM
        query.   However, options can theoretically be used for many other
        purposes.

        For background on specific kinds of options for specific kinds of
        statements, refer to the documentation for those option objects.

        .. versionchanged:: 1.4 - added :meth:`.Executable.options` to
           Core statement objects towards the goal of allowing unified
           Core / ORM querying capabilities.

        .. seealso::

            :ref:`loading_columns` - refers to options specific to the usage
            of ORM queries

            :ref:`relationship_loader_options` - refers to options specific
            to the usage of ORM queries

        c                 s  s    | ]
}t tj|V  qd S rj   )r0   expectr   ExecutableOptionRole)r   r   rT   rT   rU   r  N  s
    
z%Executable.options.<locals>.<genexpr>)r  rq  rS   r  rT   rT   rU   r  0  s   zExecutable.optionscompile_optionsr  c                 C  s
   || _ | S )z|Assign the compile options to a new value.

        :param compile_options: appropriate CacheableOptions structure

        r  )rS   r  rT   rT   rU   _set_compile_optionsT  s   zExecutable._set_compile_optionsc                 C  s    | j dusJ |  j |7  _ | S )z*update the _compile_options with new keys.Nr  r  rT   rT   rU   _update_compile_options_  s   z"Executable._update_compile_options	callable_Callable[[CompileState], None]
cache_argsc                 C  s   |  j ||ff7  _ | S )aM  Add a context option to this statement.

        These are callable functions that will
        be given the CompileState object upon compilation.

        A second argument cache_args is required, which will be combined with
        the ``__code__`` identity of the function itself in order to produce a
        cache key.

        )r  )rS   r  r  rT   rT   rU   _add_context_optiong  s   zExecutable._add_context_option.)r  logging_tokenisolation_levelno_parametersstream_resultsmax_row_buffer	yield_perinsertmanyvalues_page_sizer  populate_existing	autoflushsynchronize_sessiondml_strategyrender_nullsis_delete_usingis_update_frompreserve_rowcountr  r  rM   r  r  r  intr  r  r  r  r  r5   r  r4   r  r  r  r  r   c                K  rv   rj   rT   )rS   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   rT   rT   rU   r  z  s   zExecutable.execution_optionsc                 K  rv   rj   rT   )rS   r   rT   rT   rU   r    r}   c                 K  s6   d|v r	t dd|v rt d| j|| _| S )a  Set non-SQL options for the statement which take effect during
        execution.

        Execution options can be set at many scopes, including per-statement,
        per-connection, or per execution, using methods such as
        :meth:`_engine.Connection.execution_options` and parameters which
        accept a dictionary of options such as
        :paramref:`_engine.Connection.execute.execution_options` and
        :paramref:`_orm.Session.execute.execution_options`.

        The primary characteristic of an execution option, as opposed to
        other kinds of options such as ORM loader options, is that
        **execution options never affect the compiled SQL of a query, only
        things that affect how the SQL statement itself is invoked or how
        results are fetched**.  That is, execution options are not part of
        what's accommodated by SQL compilation nor are they considered part of
        the cached state of a statement.

        The :meth:`_sql.Executable.execution_options` method is
        :term:`generative`, as
        is the case for the method as applied to the :class:`_engine.Engine`
        and :class:`_orm.Query` objects, which means when the method is called,
        a copy of the object is returned, which applies the given parameters to
        that new copy, but leaves the original unchanged::

            statement = select(table.c.x, table.c.y)
            new_statement = statement.execution_options(my_option=True)

        An exception to this behavior is the :class:`_engine.Connection`
        object, where the :meth:`_engine.Connection.execution_options` method
        is explicitly **not** generative.

        The kinds of options that may be passed to
        :meth:`_sql.Executable.execution_options` and other related methods and
        parameter dictionaries include parameters that are explicitly consumed
        by SQLAlchemy Core or ORM, as well as arbitrary keyword arguments not
        defined by SQLAlchemy, which means the methods and/or parameter
        dictionaries may be used for user-defined parameters that interact with
        custom code, which may access the parameters using methods such as
        :meth:`_sql.Executable.get_execution_options` and
        :meth:`_engine.Connection.get_execution_options`, or within selected
        event hooks using a dedicated ``execution_options`` event parameter
        such as
        :paramref:`_events.ConnectionEvents.before_execute.execution_options`
        or :attr:`_orm.ORMExecuteState.execution_options`, e.g.::

             from sqlalchemy import event


             @event.listens_for(some_engine, "before_execute")
             def _process_opt(conn, statement, multiparams, params, execution_options):
                 "run a SQL function before invoking a statement"

                 if execution_options.get("do_special_thing", False):
                     conn.exec_driver_sql("run_special_function()")

        Within the scope of options that are explicitly recognized by
        SQLAlchemy, most apply to specific classes of objects and not others.
        The most common execution options include:

        * :paramref:`_engine.Connection.execution_options.isolation_level` -
          sets the isolation level for a connection or a class of connections
          via an :class:`_engine.Engine`.  This option is accepted only
          by :class:`_engine.Connection` or :class:`_engine.Engine`.

        * :paramref:`_engine.Connection.execution_options.stream_results` -
          indicates results should be fetched using a server side cursor;
          this option is accepted by :class:`_engine.Connection`, by the
          :paramref:`_engine.Connection.execute.execution_options` parameter
          on :meth:`_engine.Connection.execute`, and additionally by
          :meth:`_sql.Executable.execution_options` on a SQL statement object,
          as well as by ORM constructs like :meth:`_orm.Session.execute`.

        * :paramref:`_engine.Connection.execution_options.compiled_cache` -
          indicates a dictionary that will serve as the
          :ref:`SQL compilation cache <sql_caching>`
          for a :class:`_engine.Connection` or :class:`_engine.Engine`, as
          well as for ORM methods like :meth:`_orm.Session.execute`.
          Can be passed as ``None`` to disable caching for statements.
          This option is not accepted by
          :meth:`_sql.Executable.execution_options` as it is inadvisable to
          carry along a compilation cache within a statement object.

        * :paramref:`_engine.Connection.execution_options.schema_translate_map`
          - a mapping of schema names used by the
          :ref:`Schema Translate Map <schema_translating>` feature, accepted
          by :class:`_engine.Connection`, :class:`_engine.Engine`,
          :class:`_sql.Executable`, as well as by ORM constructs
          like :meth:`_orm.Session.execute`.

        .. seealso::

            :meth:`_engine.Connection.execution_options`

            :paramref:`_engine.Connection.execute.execution_options`

            :paramref:`_orm.Session.execute.execution_options`

            :ref:`orm_queryguide_execution_options` - documentation on all
            ORM-specific execution options

        r  z'isolation_level' execution option may only be specified on Connection.execution_options(), or per-engine using the isolation_level argument to create_engine().r  zm'compiled_cache' execution option may only be specified on Connection.execution_options(), not per statement.)r(   r   r  r  r   rT   rT   rU   r    s   hrF   c                 C  r!  )zGet the non-SQL options which will take effect during execution.

        .. versionadded:: 1.3

        .. seealso::

            :meth:`.Executable.execution_options`
        )r  rR   rT   rT   rU   get_execution_options  s   	z Executable.get_execution_options)r   rL   r  r  r  r  r  r  r  r  r   r   ri   r  )r  rC   r  rE   r  rK   ri   r  )r  rC   r  rE   r  rK   ri   r   ri   rt   )r  r  ri   r.   )r  r  ri   r.   )r  r  ri   r.   )r  r  r  r   ri   r.   )&r  r  r  rt   r  rM   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r5   r  r4   r  r  r  r  r  r  r  r  r   r   ri   r.   )r   r   ri   r.   )r   r   ri   r.   )ri   rF   ))rX   rY   rZ   r   r  ro   r)   r]  r  _is_default_generatorr  r  r%   dp_executable_optionsr#   dp_with_context_optionsdp_propagate_attrs_executable_traverse_internals	is_selectis_from_statement	is_update	is_insertis_text	is_deleteis_dmlr   r  r  r  r~   r  r8  r@  r   r  r  r  r  r   r  r  rT   rT   rT   rU   rE    s   
 
	


#
vrE  c                   @  s.   e Zd ZU dZded< dd	d
ZdddZdS )SchemaEventTargetzBase class for elements that are the targets of :class:`.DDLEvents`
    events.

    This includes :class:`.SchemaItem` as well as :class:`.SchemaType`.

    zdispatcher[SchemaEventTarget]dispatchparentr   r   ri   r   c                 K  s   dS )z0Associate with this SchemaEvent's parent object.NrT   rS   r  r   rT   rT   rU   _set_parent"  ry   zSchemaEventTarget._set_parentc                 K  s2   | j | | | j|fi | | j | | d S rj   )r  before_parent_attachr  after_parent_attachr  rT   rT   rU   _set_parent_with_dispatch%  s   z+SchemaEventTarget._set_parent_with_dispatchN)r  r  r   r   ri   r   )rX   rY   rZ   r   ro   r  r  rT   rT   rT   rU   r    s
   
 
r  c                   @  s   e Zd ZdZddiZdS )SchemaVisitorz/Define the visiting for ``SchemaItem`` objects.schema_visitorTN)rX   rY   rZ   r   __traverse_options__rT   rT   rT   rU   r  -  r\   r  c                   @  s(   e Zd ZdZdZdZdZdZdZdZ	dS )	 _SentinelDefaultCharacterizationnoneunknown
clientsidesentinel_default
serversideidentitysequenceN)
rX   rY   rZ   NONEUNKNOWN
CLIENTSIDESENTINEL_DEFAULT
SERVERSIDEIDENTITYSEQUENCErT   rT   rT   rU   r  3  s    r  c                   @  s@   e Zd ZU dZded< dZded< dZded< ejZ	ded	< dS )
_SentinelColumnCharacterizationNzOptional[Sequence[Column[Any]]]columnsFr  is_explicit
is_autoincr  default_characterization)
rX   rY   rZ   r  ro   r  r  r  r  r  rT   rT   rT   rU   r   =  s   
 r   _COLKEY_COL_coColumnElement[Any]T)r`   	covariant_COLc                   @  s>   e Zd ZU dZded< dddZd	d
 Zdd ZdddZdS )_ColumnMetricscolumnr  r  
collectionColumnCollection[Any, _COL_co]colc                 C  s2   || _ |j}|r|jD ]}|| |  qd S d S rj   )r  _proxy_index_expanded_proxy_setadd)rS   r  r  pieps_colrT   rT   rU   r   Q  s   
z_ColumnMetrics.__init__c                 C  s   | j jS rj   )r  r  rR   rT   rT   rU   get_expanded_proxy_set]  r   z%_ColumnMetrics.get_expanded_proxy_setc                 C  sL   |j }|sd S | jjD ]}||d }|r||  |d ur#|s#||= qd S rj   )r  r  r  r   discard)rS   r  r  r  colsetrT   rT   rU   dispose`  s   
z_ColumnMetrics.dispose
target_set=Union[Set[ColumnElement[Any]], FrozenSet[ColumnElement[Any]]]ri   r  c                 C  s2   | j j}||D ]}|t|gs dS q	dS rw  )r  r  rc  r   r   )rS   r  expanded_proxy_settrT   rT   rU   embeddedk  s   z_ColumnMetrics.embeddedN)r  r  r  r  )r  r  ri   r  )	rX   rY   rZ   r   ro   r   r  r  r  rT   rT   rT   rU   r
  L  s   
 
r
  c                   @  s  e Zd ZU dZdZded< ded< ded< d	ed
< 	d{d|ddZedd}ddZ	d~ddZ
edddZdddZdd d!Zdd#d$Zdd&d'Zdd)d*Zdd,d-Zedd1d2Zedd5d2Zedd7d2Zdd:d2Zdd<d=Zdd>d?ZddBdCZddEdFZed{ddIdJZeddMdJZ	d{ddPdJZddQdRZddUdVZddWdXZddZd[Zdd\d]Zdd_d`ZddadbZ dZ!d~dcddZ"	d{ddgdhZ#ddjdkZ$ddmdnZ%ddpdqZ&ddrdsZ'dtdu Z(	vdddydzZ)dS )ColumnCollectiona  Collection of :class:`_expression.ColumnElement` instances,
    typically for
    :class:`_sql.FromClause` objects.

    The :class:`_sql.ColumnCollection` object is most commonly available
    as the :attr:`_schema.Table.c` or :attr:`_schema.Table.columns` collection
    on the :class:`_schema.Table` object, introduced at
    :ref:`metadata_tables_and_columns`.

    The :class:`_expression.ColumnCollection` has both mapping- and sequence-
    like behaviors. A :class:`_expression.ColumnCollection` usually stores
    :class:`_schema.Column` objects, which are then accessible both via mapping
    style access as well as attribute access style.

    To access :class:`_schema.Column` objects using ordinary attribute-style
    access, specify the name like any other object attribute, such as below
    a column named ``employee_name`` is accessed::

        >>> employee_table.c.employee_name

    To access columns that have names with special characters or spaces,
    index-style access is used, such as below which illustrates a column named
    ``employee ' payment`` is accessed::

        >>> employee_table.c["employee ' payment"]

    As the :class:`_sql.ColumnCollection` object provides a Python dictionary
    interface, common dictionary method names like
    :meth:`_sql.ColumnCollection.keys`, :meth:`_sql.ColumnCollection.values`,
    and :meth:`_sql.ColumnCollection.items` are available, which means that
    database columns that are keyed under these names also need to use indexed
    access::

        >>> employee_table.c["values"]


    The name for which a :class:`_schema.Column` would be present is normally
    that of the :paramref:`_schema.Column.key` parameter.  In some contexts,
    such as a :class:`_sql.Select` object that uses a label style set
    using the :meth:`_sql.Select.set_label_style` method, a column of a certain
    key may instead be represented under a particular label name such
    as ``tablename_columnname``::

        >>> from sqlalchemy import select, column, table
        >>> from sqlalchemy import LABEL_STYLE_TABLENAME_PLUS_COL
        >>> t = table("t", column("c"))
        >>> stmt = select(t).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
        >>> subq = stmt.subquery()
        >>> subq.c.t_c
        <sqlalchemy.sql.elements.ColumnClause at 0x7f59dcf04fa0; t_c>

    :class:`.ColumnCollection` also indexes the columns in order and allows
    them to be accessible by their integer position::

        >>> cc[0]
        Column('x', Integer(), table=None)
        >>> cc[1]
        Column('y', Integer(), table=None)

    .. versionadded:: 1.4 :class:`_expression.ColumnCollection`
       allows integer-based
       index access to the collection.

    Iterating the collection yields the column expressions in order::

        >>> list(cc)
        [Column('x', Integer(), table=None),
         Column('y', Integer(), table=None)]

    The base :class:`_expression.ColumnCollection` object can store
    duplicates, which can
    mean either two columns with the same key, in which case the column
    returned by key  access is **arbitrary**::

        >>> x1, x2 = Column("x", Integer), Column("x", Integer)
        >>> cc = ColumnCollection(columns=[(x1.name, x1), (x2.name, x2)])
        >>> list(cc)
        [Column('x', Integer(), table=None),
         Column('x', Integer(), table=None)]
        >>> cc["x"] is x1
        False
        >>> cc["x"] is x2
        True

    Or it can also mean the same column multiple times.   These cases are
    supported as :class:`_expression.ColumnCollection`
    is used to represent the columns in
    a SELECT statement which may include duplicates.

    A special subclass :class:`.DedupeColumnCollection` exists which instead
    maintains SQLAlchemy's older behavior of not allowing duplicates; this
    collection is used for schema level objects like :class:`_schema.Table`
    and
    :class:`.PrimaryKeyConstraint` where this deduping is helpful.  The
    :class:`.DedupeColumnCollection` class also has additional mutation methods
    as the schema constructs have more use cases that require removal and
    replacement of columns.

    .. versionchanged:: 1.4 :class:`_expression.ColumnCollection`
       now stores duplicate
       column keys as well as the same column in multiple positions.  The
       :class:`.DedupeColumnCollection` class is added to maintain the
       former behavior in those cases where deduplication as well as
       additional replace/remove operations are needed.


    )_collection_index_colsetr  z6List[Tuple[_COLKEY, _COL_co, _ColumnMetrics[_COL_co]]]r  z4Dict[Union[None, str, int], Tuple[_COLKEY, _COL_co]]r   z6Dict[ColumnElement[Any], Set[_ColumnMetrics[_COL_co]]]r  zSet[_COL_co]r!  Nr  +Optional[Iterable[Tuple[_COLKEY, _COL_co]]]c                 C  sX   t | dt  t | di  t | dttj t | dg  |r*| | d S d S )Nr!  r   r  r  )r   rh  r   collectionsdefaultdictr)   
OrderedSet_initial_populate)rS   r  rT   rT   rU   r     s   zColumnCollection.__init__zsqlalchemy.sql.elementsri   r8   c                 C  s   t jj}|j| jtjddS )NF)_literal_as_text_roler/  )r)   r  sql_elementsr8   _all_columnsr   ColumnsClauseRolerS   r2   rT   rT   rU   __clause_element__  s   z#ColumnCollection.__clause_element__iter_!Iterable[Tuple[_COLKEY, _COL_co]]r   c                 C  s   |  | d S rj   _populate_separate_keysrS   r-  rT   rT   rU   r&    s   z"ColumnCollection._initial_populateList[_COL_co]c                 C     dd | j D S )Nc                 S     g | ]\}}}|qS rT   rT   r   r   r  rT   rT   rU   r   	      z1ColumnCollection._all_columns.<locals>.<listcomp>r  rR   rT   rT   rU   r)    s   zColumnCollection._all_columnsList[_COLKEY]c                 C  r3  )zQReturn a sequence of string key names for all columns in this
        collection.c                 S  s   g | ]\}}}|qS rT   rT   )r   r1  r   rT   rT   rU   r     r6  z)ColumnCollection.keys.<locals>.<listcomp>r7  rR   rT   rT   rU   keys  s   zColumnCollection.keysc                 C  r3  )zReturn a sequence of :class:`_sql.ColumnClause` or
        :class:`_schema.Column` objects for all columns in this
        collection.c                 S  r4  rT   rT   r5  rT   rT   rU   r     r6  z+ColumnCollection.values.<locals>.<listcomp>r7  rR   rT   rT   rU   r    s   zColumnCollection.valuesList[Tuple[_COLKEY, _COL_co]]c                 C  r3  )zReturn a sequence of (key, column) tuples for all columns in this
        collection each consisting of a string key name and a
        :class:`_sql.ColumnClause` or
        :class:`_schema.Column` object.
        c                 S     g | ]	\}}}||fqS rT   rT   r   r1  r  r   rT   rT   rU   r         z*ColumnCollection.items.<locals>.<listcomp>r7  rR   rT   rT   rU   rV    s   zColumnCollection.itemsr  c                 C  
   t | jS rj   )r  r  rR   rT   rT   rU   __bool__  r   zColumnCollection.__bool__r  c                 C  r>  rj   )r   r  rR   rT   rT   rU   r  "  r   zColumnCollection.__len__Iterator[_COL_co]c                 C  s   t dd | jD S )Nc                 S  r4  rT   rT   r5  rT   rT   rU   r   '  r6  z-ColumnCollection.__iter__.<locals>.<listcomp>)r  r  rR   rT   rT   rU   r  %  s   zColumnCollection.__iter__rs   Union[str, int]r  c                 C  rv   rj   rT   rw   rT   rT   rU   r   )  r}   zColumnCollection.__getitem__Tuple[Union[str, int], ...]*ReadOnlyColumnCollection[_COLKEY, _COL_co]c                 C  rv   rj   rT   rw   rT   rT   rU   r   ,  r   slicec                 C  rv   rj   rT   rw   rT   rT   rU   r   1  r   3Union[str, int, slice, Tuple[Union[str, int], ...]]:Union[ReadOnlyColumnCollection[_COLKEY, _COL_co], _COL_co]c              
     s   z/t |ttfr(t |trdd  j| D }n	 fdd|D }t| W S  j| d W S  tyL } zt |jd t	rGt
|jd | d }~ww )Nc                 s  s    | ]
\}}}||fV  qd S rj   rT   )r   sub_keyr  r   rT   rT   rU   r  <  s
    
z/ColumnCollection.__getitem__.<locals>.<genexpr>c                 3  s    | ]} j | V  qd S rj   r   )r   rG  rR   rT   rU   r  A      r   r   )r  rq  rD  r  r  as_readonlyr   r   r   r  
IndexError)rS   rs   colsr   rT   rR   rU   r   6  s   
rt   c              
   C  s4   z| j | d W S  ty } zt||d }~ww )Nr   )r   r   AttributeError)rS   rs   r   rT   rT   rU   rx   L  s   
zColumnCollection.__getattr__c                 C  s&   || j vrt|tstddS dS )Nz'__contains__ requires a string argumentFT)r   r  rt   r(   r   rw   rT   rT   rU   __contains__R  s   

zColumnCollection.__contains__re  ColumnCollection[Any, Any]c                 C  s&   t | |D ]\}}||ur dS qdS )zdCompare this :class:`_expression.ColumnCollection` to another
        based on the names of the keysFTr   )rS   re  lrrT   rT   rU   compare\  s
   zColumnCollection.comparer   c                 C  s
   |  |S rj   )rR  )rS   re  rT   rT   rU   ry  f  r   zColumnCollection.__eq__rg   Optional[_COL_co]c                 C  rv   rj   rT   rS   rs   rg   rT   rT   rU   r   i  r}   zColumnCollection.getr	  Union[_COL_co, _COL]c                 C  rv   rj   rT   rT  rT   rT   rU   r   l  r}   Optional[_COL]Optional[Union[_COL_co, _COL]]c                 C  s   || j v r| j | d S |S )zGet a :class:`_sql.ColumnClause` or :class:`_schema.Column` object
        based on a string key name from this
        :class:`_expression.ColumnCollection`.r   rH  rT  rT   rT   rU   r   o  s   
c                 C  s    d| j jddd | D f S )Nrz  r{  c                 s  s    | ]}t |V  qd S rj   )rt   r   rT   rT   rU   r  ~  s    z+ColumnCollection.__str__.<locals>.<genexpr>)r   rX   r}  rR   rT   rT   rU   __str__{  s   zColumnCollection.__str__r   r   c                 C  r   rj   r   r  rT   rT   rU   r        zColumnCollection.__setitem__c                 C  r   rj   r   rw   rT   rT   rU   r     rY  zColumnCollection.__delitem__r   c                 C  r   rj   r   )rS   rs   r   rT   rT   rU   rh    rY  zColumnCollection.__setattr__c                 C  r   )zQDictionary clear() is not implemented for
        :class:`_sql.ColumnCollection`.r   rR   rT   rT   rU   clear  r"  zColumnCollection.clearr  c                 C  r   rj   r   )rS   r  rT   rT   rU   remove  rY  zColumnCollection.removec                 C  r   )zRDictionary update() is not implemented for
        :class:`_sql.ColumnCollection`.r   r1  rT   rT   rU   r$    r"  zColumnCollection.updatec                   sn    fdd|D   j dd< } jdd |D   jdd t|D   jdd t|D  dS )	*populate from an iterator of (key, column)c                       g | ]\}}||t  |fqS rT   r
  r   r1  r   rR   rT   rU   r     s    z<ColumnCollection._populate_separate_keys.<locals>.<listcomp>Nc                 s  s    | ]
\}}}|  V  qd S rj   _deannotate)r   r   r   rT   rT   rU   r        z;ColumnCollection._populate_separate_keys.<locals>.<genexpr>c                 S      i | ]\}\}}}|||fqS rT   rT   r   idxr1  r   r   rT   rT   rU   rR         z<ColumnCollection._populate_separate_keys.<locals>.<dictcomp>c                 S     i | ]
\}}}|||fqS rT   rT   r<  rT   rT   rU   rR    r   )r  r!  r$  r   	enumerater%  )rS   r-  r  rT   rR   rU   r0    s   
z(ColumnCollection._populate_separate_keysr  Optional[_COLKEY]c                 C  s~   |du r|j }n|}t| j}tt|}| j||t| |f | j|	  ||f| j
|< || j
vr=||f| j
|< dS dS )a  Add a column to this :class:`_sql.ColumnCollection`.

        .. note::

            This method is **not normally used by user-facing code**, as the
            :class:`_sql.ColumnCollection` is usually part of an existing
            object such as a :class:`_schema.Table`. To add a
            :class:`_schema.Column` to an existing :class:`_schema.Table`
            object, use the :meth:`_schema.Table.append_column` method.

        N)rs   r   r  r   r  appendr
  r!  r  ra  r   )rS   r  rs   colkeyrP  _columnrT   rT   rU   r    s   


zColumnCollection.addr+  c                 C  s   dd | j D | jdS )Nc                 S  r;  rT   rT   r   r1  r   r   rT   rT   rU   r     r=  z1ColumnCollection.__getstate__.<locals>.<listcomp>r  r   rn  rR   rT   rT   rU   __getstate__  s   zColumnCollection.__getstate__statec                   sf   t  d|d  t  dttj t  d fdd|d D  t  ddd  jD  d S )	Nr   r  r  c                   r]  rT   r^  r_  rR   rT   rU   r     s    z1ColumnCollection.__setstate__.<locals>.<listcomp>r!  c                 S  s   h | ]\}}}|qS rT   rT   r<  rT   rT   rU   r     r6  z0ColumnCollection.__setstate__.<locals>.<setcomp>)r   rh  r#  r$  r)   r%  r  )rS   rp  rT   rR   rU   __setstate__  s   
zColumnCollection.__setstate__r  c                 C  s&   || j vrt|trtddS dS )z3Checks if a column object exists in this collectionzZcontains_column cannot be used with string arguments. Use ``col_name in table.c`` instead.FT)r!  r  rt   r(   r   rS   r  rT   rT   rU   contains_column  s   

z ColumnCollection.contains_columnc                 C  r  )zIReturn a "read only" form of this
        :class:`_sql.ColumnCollection`.)ReadOnlyColumnCollectionrR   rT   rT   rU   rJ    s   zColumnCollection.as_readonlyc                 C  sD   | j }|rdS | jD ]\}}}|jj}|D ]	}|| | qq
dS )a  populate the "proxy index", if empty.

        proxy index is added in 2.0 to provide more efficient operation
        for the corresponding_column() method.

        For reasons of both time to construct new .c collections as well as
        memory conservation for large numbers of large .c collections, the
        proxy_index is only filled if corresponding_column() is called. once
        filled it stays that way, and new _ColumnMetrics objects created after
        that point will populate it with new data. Note this case would be
        unusual, if not nonexistent, as it means a .c collection is being
        mutated after corresponding_column() were used, however it is tested in
        test/base/test_utils.py.

        N)r  r  r  r  r  )rS   r  r   metricsepsr  rT   rT   rU   _init_proxy_index  s   z"ColumnCollection._init_proxy_indexFrequire_embeddedOptional[Union[_COL, _COL_co]]c           
        s    | j v r S d\}} j}| js|   fdd|D D ]W}|r)||rw|du r0|}q ||jj}|du rB||jj}t|t|krO|}|}q ||krwt	 fdd|j
 D }t	 fdd|j
 D }	|	|k rw|}|}q |r}|jS dS )a  Given a :class:`_expression.ColumnElement`, return the exported
        :class:`_expression.ColumnElement` object from this
        :class:`_expression.ColumnCollection`
        which corresponds to that original :class:`_expression.ColumnElement`
        via a common
        ancestor column.

        :param column: the target :class:`_expression.ColumnElement`
                      to be matched.

        :param require_embedded: only return corresponding columns for
         the given :class:`_expression.ColumnElement`, if the given
         :class:`_expression.ColumnElement`
         is actually present within a sub-element
         of this :class:`_expression.Selectable`.
         Normally the column will match if
         it merely shares a common ancestor with one of the exported
         columns of this :class:`_expression.Selectable`.

        .. seealso::

            :meth:`_expression.Selectable.corresponding_column`
            - invokes this method
            against the collection returned by
            :attr:`_expression.Selectable.exported_columns`.

        .. versionchanged:: 1.4 the implementation for ``corresponding_column``
           was moved onto the :class:`_expression.ColumnCollection` itself.

        )NNc                 3  s*    | ]}| v r | D ]}|V  qqd S rj   rT   )r   tsmm)r  rT   rU   r  =  s     z8ColumnCollection.corresponding_column.<locals>.<genexpr>Nc                   $   g | ]}|  r|jd dqS weightr   shares_lineager  r   r   scr  rT   rU   r   b      z9ColumnCollection.corresponding_column.<locals>.<listcomp>c                   r|  r}  r  r  r  rT   rU   r   k  r  )r!  r   r  rw  r  r   r  r  r   r  _uncached_proxy_list)
rS   r  rx  selected_intersectionselected_metricsr  current_metricscurrent_intersectionselected_col_distancecurrent_col_distancerT   )r  r  rU   corresponding_column  sP   
$


	
	z%ColumnCollection.corresponding_columnrj   )r  r"  )ri   r8   )r-  r.  ri   r   )ri   r2  )ri   r8  )ri   r:  )ri   r  )ri   r  )ri   r@  )rs   rA  ri   r  )rs   rB  ri   rC  )rs   rD  ri   rC  )rs   rE  ri   rF  )rs   rt   ri   r  )rs   rt   ri   r  )re  rO  ri   r  )re  r   ri   r  )rs   rt   rg   r   ri   rS  )rs   rt   rg   r	  ri   rU  )rs   rt   rg   rV  ri   rW  r  )rs   rt   r   r   ri   r   )rs   rt   ri   r   )rs   rt   r   r   ri   r   )ri   r   )r  r   ri   r   )r-  r   ri   r   )r  r  rs   ri  ri   r   )ri   r+  )rp  r+  ri   r   )r  r  ri   r  )ri   rC  )F)r  r	  rx  r  ri   ry  )*rX   rY   rZ   r   r   ro   r   r)   preload_moduler,  r&  r8  r)  r9  r  rV  r?  r  r  r   r   rx   rN  rR  ry  r   rX  r   r   rh  rZ  r[  r$  __hash__r0  r  ro  rq  rs  rJ  rw  r  rT   rT   rT   rU   r  x  sn   
 l
	



	

















$


r  	_NAMEDCOLzNamedColumn[Any]c                   @  sT   e Zd ZdZ	ddd	d
ZdddZdddZd ddZd!ddZ	dd"ddZ	dS )#DedupeColumnCollectionau  A :class:`_expression.ColumnCollection`
    that maintains deduplicating behavior.

    This is useful by schema level objects such as :class:`_schema.Table` and
    :class:`.PrimaryKeyConstraint`.    The collection includes more
    sophisticated mutator methods as well to suit schema objects which
    require mutable column collections.

    .. versionadded:: 1.4

    Nr  r  rs   Optional[str]ri   r   c                 C  s   |d ur|j |krtd|j }|d u rtd|| jv r:| j| d }||u r,d S | | tj|d d S | || d S )NKDedupeColumnCollection requires columns be under the same key as their .keyz-Can't add unnamed column to column collectionr   r   )	rs   r(   r   r   replacer)   r7  reset_append_new_column)rS   r  rs   existingrT   rT   rU   r    s    

zDedupeColumnCollection.addrt   named_columnc                 C  sR   t | j}| j||t| |f | j|  ||f| j|< ||f| j|< d S rj   )r   r  rj  r
  r!  r  ra  r   )rS   rs   r  rP  rT   rT   rU   r    s   
z)DedupeColumnCollection._append_new_columnr-  Iterable[Tuple[str, _NAMEDCOL]]c                 C  s   t |}g }|D ]?\}}|j|krtd|j| jv r(|j|jkr(|| q|j| jv r4|| q||f| j|< | j||t| |f q| j	
dd | jD  | j
dd t| jD  |D ]}| | qddS )r\  r  c                 s  s    | ]
\}}}|  V  qd S rj   r`  rm  rT   rT   rU   r    rb  zADedupeColumnCollection._populate_separate_keys.<locals>.<genexpr>c                 s  s&    | ]\}\}}}|||ffV  qd S rj   rT   rd  rT   rT   rU   r    s    
N)listrs   r(   r   rQ   r   rj  r  r
  r!  r$  rh  r  )rS   r-  rL  replace_colr1  r  rT   rT   rU   r0    s(   
z.DedupeColumnCollection._populate_separate_keysIterable[_NAMEDCOL]c                 C  s   |  dd |D  d S )Nc                 s  s    | ]}|j |fV  qd S rj   )rs   )r   r  rT   rT   rU   r    rI  z0DedupeColumnCollection.extend.<locals>.<genexpr>r/  r1  rT   rT   rU   extend  s   zDedupeColumnCollection.extendc                   s    | j vrtd  | j j= | j    fdd| jD | jd d < | j dD ]}||  q,| j	dd t
| jD  | jt| j= d S )Nz8Can't remove column %r; column is not in this collectionc                   s$   g | ]\}}}| ur|||fqS rT   rT   )r   r1  r   ru  r  rT   rU   r     s
    z1DedupeColumnCollection.remove.<locals>.<listcomp>rT   c                 S  rc  rT   rT   r   re  r1  r  r   rT   rT   rU   rR    rf  z1DedupeColumnCollection.remove.<locals>.<dictcomp>)r!  r   r   rs   r[  r  r  r   r  r$  rh  r   )rS   r  ru  rT   r  rU   r[    s"   


zDedupeColumnCollection.removeextra_removeOptional[Iterable[_NAMEDCOL]]c                 C  s  |rt |}nt  }|j| jv r)|j|jkr)| j|j d }|j|jkr)|| |j| jv r:|| j|j d  |sE| |j| dS g }d}| jD ]"\}}}	||v rf|sed}||j|t| |f qL||||	f qL|r| j	
| |D ]}
| j|
dD ]}	|	|  qqy|s||j|t| |f | j	|  || jdd< | j  | jdd t| jD  | jdd | jD  dS )	a  add the given column to this collection, removing unaliased
        versions of this column  as well as existing columns with the
        same key.

        e.g.::

            t = Table("sometable", metadata, Column("col1", Integer))
            t.columns.replace(Column("col1", Integer, key="columnone"))

        will remove the original 'col1' from the collection, and add
        the new column under the name 'columnname'.

        Used by schema.Column to override columns during table reflection.

        r   NFTrT   c                 S  rc  rT   rT   r  rT   rT   rU   rR  '  rf  z2DedupeColumnCollection.replace.<locals>.<dictcomp>c                 S  rg  rT   rT   r<  rT   rT   rU   rR  )  r   )r   rQ   r   rs   r  r  r  rj  r
  r!  difference_updater  r   r  ra  rZ  r$  rh  )rS   r  r  
remove_colre  new_colsreplacedr1  r  ru  rcrT   rT   rU   r    sL   


zDedupeColumnCollection.replacerj   )r  r  rs   r  ri   r   )rs   rt   r  r  ri   r   )r-  r  ri   r   )r-  r  ri   r   )r  r  ri   r   )r  r  r  r  ri   r   )
rX   rY   rZ   r   r  r  r0  r  r[  r  rT   rT   rT   rU   r  }  s    

	

r  c                   @  sH   e Zd ZdZdd Zdd Zdd ZddddZdddZdddZ	dS )rt  _parentc                 C  sR   t | d| t | d|j t | d|j t | d|j t | d|j d S )Nr  r!  r   r  r  )r   rh  r!  r   r  r  )rS   r  rT   rT   rU   r   1  s
   z!ReadOnlyColumnCollection.__init__c                 C  s
   d| j iS Nr  r  rR   rT   rT   rU   ro  8  r   z%ReadOnlyColumnCollection.__getstate__c                 C  s   |d }|  | d S r  )r   )rS   rp  r  rT   rT   rU   rq  ;  s   z%ReadOnlyColumnCollection.__setstate__.r  r   rs   ri   c                 C     |    d S rj   	_readonly)rS   r  rs   rT   rT   rU   r  ?  rW   zReadOnlyColumnCollection.addr2   r   c                 C  r  rj   r  r+  rT   rT   rU   r  B  rW   zReadOnlyColumnCollection.extenditemc                 C  r  rj   r  )rS   r  rT   rT   rU   r[  E  rW   zReadOnlyColumnCollection.removeN).)r  r   rs   r   ri   r   )r2   r   ri   r   )r  r   ri   r   )
rX   rY   rZ   r   r   ro  rq  r  r  r[  rT   rT   rT   rU   rt  ,  s    
rt  c                   @  s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
	ColumnSetc                 C  s   || v S rj   rT   rr  rT   rT   rU   rs  J  r   zColumnSet.contains_columnc                 C  s   |D ]}|  | qd S rj   )r  )rS   rL  r  rT   rT   rU   r  M  s   zColumnSet.extendc                 C  s:   g }|D ]}| D ]}| |r|||k qqtj| S rj   )r  rj  r2   and_)rS   re  rP  r   r  rT   rT   rU   ry  Q  s   

zColumnSet.__eq__c                 C  s   t tdd | D S )Nc                 s  s    | ]}|V  qd S rj   rT   r   rT   rT   rU   r  Z  s    z%ColumnSet.__hash__.<locals>.<genexpr>)hashrq  rR   rT   rT   rU   r  Y  r  zColumnSet.__hash__N)rX   rY   rZ   rs  r  ry  r  rT   rT   rT   rU   r  I  s
    r  zColumnClause[Any]entity1Union[_HasEntityNamespace, ExternallyTraversible]c                 C  sL   zt t| jW S  ty%   tt t| D ]}t|r#|j   Y S q w )zReturn the nearest .entity_namespace for the given entity.

    If not immediately available, does an iterate to find a sub-element
    that has one, if any.

    )r   r{   r|   rM  r   iterater$   r   )r  r   rT   rT   rU   _entity_namespace]  s   	r  rs   rg   %Union[SQLCoreOperations[Any], _NoArg]ru   c              
   C  sX   zt | }|turt|||W S t||W S  ty+ } z
td| |f |d}~ww )zReturn an entry from an entity_namespace.


    Raises :class:`_exc.InvalidRequestError` rather than attribute error
    on not found.

    z.Entity namespace for "%s" has no property "%s"N)r  r[   rx  rM  r(   r   )r  rs   rg   nsr   rT   rT   rU   _entity_namespace_keyp  s   
r  )r   r   ri   r   )r2   r   ri   r   )r2   r   ri   rA   )r   ra   ri   ra   )r   rt   r   r   ri   r   )r2   r   ri   r   )r   r   r   r   ri   r   )r  r  ri   rr   )r  r  rs   rt   rg   r  ri   ru   )r   
__future__r   r#  enumr   r   r   r   r,  r,   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r   r   	cache_keyr   r    
traversalsr!   r"   r#   r$   r%   r'   r(   r)   r*   r+   compat_typingutil.typingr-   r.   r/   r0   r2   r3   
_orm_typesr4   r5   _typingr6   r7   r8   r9   r:   r;   r<   r=   schemar>   r?   
selectabler@   rA   rB   enginerC   rD   engine.interfacesrE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   r[   r]   r^   
_NONE_NAMEr_   ra   rt   _AmbiguousTableNameMaprb   r   _never_select_columnrr   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r  r  r  r9  rN  rX  rY  typer_  rm  r  r  StatementRolerE  EventTargetr  r  r  r   r  r  r	  r
  r  r  r  ReadOnlyContainerrt  r%  r  r  r  rT   rT   rT   rU   <module>   s.  

 







	
9 
 +j
!   3
	,     
0
