
    ,hп                       % S SK Jr  S SKJr  S SKrS SKrS SKrS SKrS SK	r	S SK	J
r
  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S S	KJr  S S
KJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKrSSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSK J!r!  SSK J"r"  SSK J#r#  SSKJ$r$  SSK%J&r&  SSKJ'r'  SSKJ(r(  SSKJ)r)  SSK*J+r+  \(       a  SS KJ,r,  SS!KJ-r-  SS"KJ.r.  SS#KJ/r/  \\\S$4   \S%   4   r0\S$\4   r1\)Rd                  " S&5      r3S'\4S('   \/ \4   r5\S$\4   r6\/ \4   r7\" S)\"S*9r8\\8/\4   r9 " S+ S,\#5      r:      SA               SBS. jjr; " S/ S0\RZ                  5      r< " S1 S2\<5      r= " S3 S-\R|                  \<\"5      r? " S4 S5\R|                  \RZ                  5      r@ " S6 S7\?5      rA " S8 S95      rB " S: S;5      rC " S< S=5      rD " S> S?\&5      rE\(R                  " \<5      S@ 5       rGg)C    )annotationsN)CodeType)Any)Callable)cast)List)MutableMapping)Optional)Tuple)Type)TYPE_CHECKING)TypeVar)Union   )	cache_key)	coercions)elements)roles)schema)visitors)_clone)
Executable)Options)
CacheConst)ColumnOperators   )exc)
inspection)util)Literal)BindParameter)ClauseElement)SQLRole)_CloneCallableType.)NonAnalyzedFunctionAnalyzedFunctioni  _LambdaCacheType_closure_per_cache_key_E)boundc                  B    \ rS rSr% SrSrSrS\S'   SrSr	Sr
S\S'   Srg)	LambdaOptionsH   TNOptional[object]track_onOptional[_LambdaCacheType]lambda_cache )__name__
__module____qualname____firstlineno__enable_trackingtrack_closure_variablesr/   __annotations__global_track_bound_valuestrack_bound_valuesr1   __static_attributes__r2       N/var/www/auris/envauris/lib/python3.13/site-packages/sqlalchemy/sql/lambdas.pyr,   r,   H   s/    O"!%H% $/3L,3r=   r,   StatementLambdaElementc                P    [        U [        R                  [        UUUUUUS95      $ )a  Produce a SQL statement that is cached as a lambda.

The Python code object within the lambda is scanned for both Python
literals that will become bound parameters as well as closure variables
that refer to Core or ORM constructs that may vary.   The lambda itself
will be invoked only once per particular set of constructs detected.

E.g.::

    from sqlalchemy import lambda_stmt

    stmt = lambda_stmt(lambda: table.select())
    stmt += lambda s: s.where(table.c.id == 5)

    result = connection.execute(stmt)

The object returned is an instance of :class:`_sql.StatementLambdaElement`.

.. versionadded:: 1.4

:param lmb: a Python function, typically a lambda, which takes no arguments
 and returns a SQL expression construct
:param enable_tracking: when False, all scanning of the given lambda for
 changes in closure variables or bound parameters is disabled.  Use for
 a lambda that produces the identical results in all cases with no
 parameterization.
:param track_closure_variables: when False, changes in closure variables
 within the lambda will not be scanned.   Use for a lambda where the
 state of its closure variables will never change the SQL structure
 returned by the lambda.
:param track_bound_values: when False, bound parameter tracking will
 be disabled for the given lambda.  Use for a lambda that either does
 not produce any bound values, or where the initial bound values never
 change.
:param global_track_bound_values: when False, bound parameter tracking
 will be disabled for the entire statement including additional links
 added via the :meth:`_sql.StatementLambdaElement.add_criteria` method.
:param lambda_cache: a dictionary or other mapping-like object where
 information about the lambda's Python code as well as the tracked closure
 variables in the lambda itself will be stored.   Defaults
 to a global LRU cache.  This cache is independent of the "compiled_cache"
 used by the :class:`_engine.Connection` object.

.. seealso::

    :ref:`engine_lambda_caching`


)r7   r/   r8   r:   r;   r1   )r?   r   StatementRoler,   )lmbr7   r8   r/   r:   r;   r1   s          r>   lambda_stmtrC   Q   s8    v "+$;&?1%	
 r=   c                  n   \ rS rSr% SrSrSrS\R                  R                  4/r
SrS\S'   S	\S
'   SrS\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S r\S4       S&S jjrS rS r\S 5       r\S 5       r\S 5       rS rS  r\S4       S'S! jjr\R8                  S" 5       rS# rS(S$ jrS%r g))LambdaElement   a  A SQL construct where the state is stored as an un-invoked lambda.

The :class:`_sql.LambdaElement` is produced transparently whenever
passing lambda expressions into SQL constructs, such as::

    stmt = select(table).where(lambda: table.c.col == parameter)

The :class:`_sql.LambdaElement` is the base of the
:class:`_sql.StatementLambdaElement` which represents a full statement
within a lambda.

.. versionadded:: 1.4

.. seealso::

    :ref:`engine_lambda_caching`

lambda_elementT	_resolvedr2   zTuple[_CloneCallableType, ...]_transformszList[BindParameter[Any]]_resolved_bindparamsNz Optional[StatementLambdaElement]parent_lambdaz4Union[Tuple[Any, ...], Literal[CacheConst.NO_CACHE]]closure_cache_keyType[SQLRole]rolez,Union[AnalyzedFunction, NonAnalyzedFunction]_rec_AnyLambdaTypefnzTuple[CodeType, ...]tracker_keyc                f    U R                   R                  < SU R                  R                  < S3$ )N())	__class__r3   rQ   __code__selfs    r>   __repr__LambdaElement.__repr__   s&    NN##GG
 	
r=   c                    Xl         X l        UR                  4U l        X0l        Uc  U[
        R                  L a  U nU R                  XU5      nUb  UR                  nU(       a  Xdl	        g g g N)
rQ   rN   rW   rR   optsr   rA   _retrieve_tracker_recpropagate_attrs_propagate_attrs)rY   rQ   rN   r^   apply_propagate_attrsrecr`   s          r>   __init__LambdaElement.__init__   sp     	KK>	 (de6I6I.I$(!((DI ,!11O9H6  -r=   c                j   UR                   nUc  [        nU R                  nU R                  nUR                  n[
        R                  UU U5      n/ =U l        nU R                  b  U R                  R                  n	OSn	U	[        R                  La  [        R                  " 5       n
[        UR                   Vs/ s H  nU" XcX5      PM     sn5      n[        R                  U
;  a  X-   nXl	        UR                  X\-   5      nO%[        R                  nS nO[        R                  nS nXl	        Ucv  U[        R                  LaH  [
        R                      X\-   nX;  a!  [#        XpX!5      n[%        U5      Ul        XU'   OXN   nS S S 5        Ob[)        U R+                  U5      5      nOG[-        UR&                  U5       VVs/ s H   u  nnUR/                  UR0                  SS9PM"     snnUS S & Xl        U[        R                  La  U R                  b  U R                  R                  US S& U nUba  UR2                  nUR4                  (       a3  UR6                  nUR4                   H  nU" UR                  UU5        M     UR                  nUb  Ma  U$ s  snf ! , (       d  f       N= fs  snnf )Nr2   Tmaintain_keyr   )r1   r(   rR   rQ   __closure__AnalyzedCodegetrJ   rK   rL   
_cache_keyNO_CACHEr   anon_maptupleclosure_trackers_generation_mutexr&   listclosure_bindparamsr%   _invoke_user_fnzip_with_valuevaluerO   bindparam_trackerstracker_instrumented_fn)rY   rQ   rb   r^   r1   rR   closuretracker
bindparamsparent_closure_cache_keyrn   getterr   rc   key	orig_bindnew_bindrG   ry   s                      r>   r_   #LambdaElement._retrieve_tracker_rec   s   ((1L&&WW..""
 243!J)'+'9'9'K'K$')$ $:+>+>>((*H #*":":": 7(?":I ""(24@	)2&"&&{'>?&//	 #++IC!*;
 3 33!33%1C..#+@ 26j1A.,/S)*/ 43 *$*>*>r*BC
 ,/**J,,'Ix %%hnn4%H,JqM 	J///!!-!%!3!3!H!H
2A6:N ,$)))).1.I.I+#&#9#9*--3& $: "0!=!= !, 
A0 43s   ;J/J'J/
J,c                B    [        U R                  R                  U5      $ r]   )getattrrO   expected_exprrY   r   s     r>   __getattr__LambdaElement.__getattr__:  s    tyy..44r=   c                .    U R                   R                  $ r]   )rO   is_sequencerX   s    r>   _is_sequenceLambdaElement._is_sequence=  s    yy$$$r=   c                    U R                   (       aC  [        R                  R                  U R                   Vs/ s H  oR
                  PM     sn5      $ U R                  R
                  $ s  snf r]   )r   	itertoolschainfrom_iterablerH   _select_iterablerY   elements     r>   r   LambdaElement._select_iterableA  sT    ??009=Hg))H 
 >>222	 I   A+c                    U R                   (       aC  [        R                  R                  U R                   Vs/ s H  oR
                  PM     sn5      $ U R                  R
                  $ s  snf r]   )r   r   r   r   rH   _from_objectsr   s     r>   r   LambdaElement._from_objectsK  sT    ??006:nnEn7&&nE 
 >>///	 Fr   c                n    U R                    Vs0 s H  oR                  UR                  _M     sn$ s  snf r]   )rJ   r   rw   )rY   bs     r>   _param_dictLambdaElement._param_dictU  s,    (,(A(AB(A1qww(ABBBs    2c                d  ^ U R                    Vs0 s H  o"R                  U_M     snm      SU4S jjnU R                  R                  (       a*  U Vs/ s H  n[        R
                  " U0 U5      PM     nnU$ [        USS5      (       a  [        R
                  " U0 U5      nU$ s  snf s  snf )Nc                   > [        U [        R                  5      (       a[  U R                  T;   aK  TU R                     nU R                  (       a)  SUl        U R
                  Ul        U R                  Ul        U$ g NT)
isinstancer   r!   r   	expanding	expand_optype)r   kwbindbindparam_lookups      r>   replace<LambdaElement._setup_binds_for_tracked_expr.<locals>.replace[  sc     '8#9#9::;;"22+GKK8D(()-)0):):$+LL	Kr=   is_clause_elementF)r   (Optional[visitors.ExternallyTraversible]r   r   returnr   )rJ   r   rO   r   r   replacement_traverser   )rY   exprr   r   sub_exprr   s        @r>   _setup_binds_for_tracked_expr+LambdaElement._setup_binds_for_tracked_exprX  s    .2.G.GH.GEE1H.GH	=	EH	5	 99   !% $H --hGD $    T.6600r7CD1 I"s   B("B-c                8    U" U R                   4SU0UD6U l         g )Ndeferred_copy_internals)rH   )rY   cloner   r   s       r>   _copy_internalsLambdaElement._copy_internalss  s)     NN
$;
 
r=   c                v    U R                   R                  nU R                  (       a  U R                  U5      nU$ r]   )rO   r   rJ   r   rY   r   s     r>   rH   LambdaElement._resolved  s/    yy&&$$55d;Dr=   c                   U R                   [        R                  L a  SU[        R                  '   g U R                  R                  U R
                  4U R                   -   nU R                  nUbY  UR                   [        R                  Ld   eUR                   nUR                  R                  4U-   U-   nUR                  nUb  MY  U R                  (       a  UR                  U R                  5        U$ r   )
rL   rl   rm   rQ   rW   rV   rK   r   rJ   extend)rY   rn   r|   r   parentr}   s         r>   _gen_cache_keyLambdaElement._gen_cache_key  s    !!Z%8%88,0HZ(() GGNN
 ""#	
 ## ++:3F3FFFF(( %
 ##%(@@9L  ))F   $$d778r=   c                    U" 5       $ r]   r2   rY   rQ   args      r>   rt   LambdaElement._invoke_user_fn  s	    tr=   )rO   rH   rJ   rL   rQ   r^   rN   rR   )rQ   _LambdaTyperN   rM   r^   )Union[Type[LambdaOptions], LambdaOptions]rb   Optional[ClauseElement])r   r$   r   zOptional[_CloneCallableType]r   r   r   None)rQ   rP   r   r   r   r"   )!r3   r4   r5   r6   __doc____visit_name___is_lambda_elementr   InternalTraversaldp_clauseelement_traverse_internalsrI   r9   rK   rZ   r,   rd   r_   r   propertyr   r   r   r   r   r   r   r   memoized_propertyrH   r   rt   r<   r2   r=   r>   rE   rE      sV   & &N 
h00AAB 35K/4226:M3:KK

66%%
 ;H9=II I 8	I
  7I,\|5 % % 3 3 0 0C: %+@D
!
 ">
 	

 

 
 8r=   rE   c                  j   ^  \ rS rSrSr\S4       S
U 4S jjjrS rSS jr\	S4U 4S jjr
S	rU =r$ )DeferredLambdaElementi  a*  A LambdaElement where the lambda accepts arguments and is
invoked within the compile phase with special context.

This lambda doesn't normally produce its real SQL expression outside of the
compile phase.  It is passed a fixed set of initial arguments
so that it can generate a sample expression.

r2   c                2   > X@l         [        TU ]	  XU5        g r]   )lambda_argssuperrd   )rY   rQ   rN   r^   r   rV   s        r>   rd   DeferredLambdaElement.__init__  s     '4(r=   c                     U" U R                   6 $ r]   r   r   s      r>   rt   %DeferredLambdaElement._invoke_user_fn  s    4##$$r=   c                   [        U R                  [        5      (       d   eU R                  R                  nU" U6 n[        R
                  " U R                  U5      nU R                  U5      nU R                   H  nU" U5      nM     U$ r]   )	r   rO   r&   ry   r   expectrN   r   rI   )rY   r   
tracker_fnr   r   s        r>   _resolve_with_args(DeferredLambdaElement._resolve_with_args  s}    $))%56666YY66
;'		4011$70 (,'7'7#*40D (8 r=   Nc                `   > [         TU ]  UUUS9  U(       a  U =R                  U4-  sl        g g )N)r   r   r^   )r   r   rI   )rY   r   r   r   rV   s       r>   r   %DeferredLambdaElement._copy_internals  s?     	$; 	  	
 #!8 :: #r=   r   )rQ   rP   rN   zType[roles.SQLRole]r^   r   r   zTuple[Any, ...])r   r   r   r"   )r3   r4   r5   r6   r   r,   rd   rt   r   r   r   r<   __classcell__)rV   s   @r>   r   r     s]     ;H'))) ") 8	)
 %) )%"J D; ;r=   r   c                  H   \ rS rSrSr\(       a  \S4       SS jjr    SS jr    S           SS jjr	S r
\SS j5       r\S	 5       r\S
 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       rSS jrSrg)r?   i  a/  Represent a composable SQL statement as a :class:`_sql.LambdaElement`.

The :class:`_sql.StatementLambdaElement` is constructed using the
:func:`_sql.lambda_stmt` function::


    from sqlalchemy import lambda_stmt

    stmt = lambda_stmt(lambda: select(table))

Once constructed, additional criteria can be built onto the statement
by adding subsequent lambdas, which accept the existing statement
object as a single parameter::

    stmt += lambda s: s.where(table.c.col == parameter)

.. versionadded:: 1.4

.. seealso::

    :ref:`engine_lambda_caching`

Nc                    g r]   r2   )rY   rQ   rN   r^   rb   s        r>   rd   StatementLambdaElement.__init__  s     r=   c                $    U R                  U5      $ r]   )add_criteria)rY   others     r>   __add__StatementLambdaElement.__add__  s       ''r=   c           	     r    U R                   [        UUU R                   R                  UUS9-   n[        XUS9$ )a  Add new criteria to this :class:`_sql.StatementLambdaElement`.

E.g.::

    >>> def my_stmt(parameter):
    ...     stmt = lambda_stmt(
    ...         lambda: select(table.c.x, table.c.y),
    ...     )
    ...     stmt = stmt.add_criteria(lambda: table.c.x > parameter)
    ...     return stmt

The :meth:`_sql.StatementLambdaElement.add_criteria` method is
equivalent to using the Python addition operator to add a new
lambda, except that additional arguments may be added including
``track_closure_values`` and ``track_on``::

    >>> def my_stmt(self, foo):
    ...     stmt = lambda_stmt(
    ...         lambda: select(func.max(foo.x, foo.y)),
    ...         track_closure_variables=False,
    ...     )
    ...     stmt = stmt.add_criteria(lambda: self.where_criteria, track_on=[self])
    ...     return stmt

See :func:`_sql.lambda_stmt` for a description of the parameters
accepted.

)r7   r8   r:   r/   r;   )rK   r^   )r^   dictr:   LinkedLambdaElement)rY   r   r7   r/   r8   r;   r^   s          r>   r   #StatementLambdaElement.add_criteria  sB    J yy4+$;&*ii&I&I1
 
 #54HHr=   c                   [         (       a+  [        U R                  R                  [        5      (       d   eU R                  R                  R
                  (       a  UR                  XU5      $ [        R                  " U 5      er]   )	r   r   rO   r   r"   supports_execution_execute_clauseelementr   ObjectNotExecutableErrorrY   
connectiondistilled_paramsexecution_optionss       r>   _execute_on_connection-StatementLambdaElement._execute_on_connectionL  se     =dii55}EEEE99""5544(9  ..t44r=   c                    U R                   $ r]   )_rec_expected_exprrX   s    r>   _proxiedStatementLambdaElement._proxiedX  s    &&&r=   c                .    U R                   R                  $ r]   )r   _with_optionsrX   s    r>   r   $StatementLambdaElement._with_options\  s    }}***r=   c                .    U R                   R                  $ r]   )r   _effective_plugin_targetrX   s    r>   r   /StatementLambdaElement._effective_plugin_target`  s    }}555r=   c                .    U R                   R                  $ r]   )r   _execution_optionsrX   s    r>   r   )StatementLambdaElement._execution_optionsd  s    }}///r=   c                .    U R                   R                  $ r]   )r   _all_selected_columnsrX   s    r>   r  ,StatementLambdaElement._all_selected_columnsh  s    }}222r=   c                .    U R                   R                  $ r]   )r   	is_selectrX   s    r>   r   StatementLambdaElement.is_selectl      }}&&&r=   c                .    U R                   R                  $ r]   )r   	is_updaterX   s    r>   r
   StatementLambdaElement.is_updatep  r  r=   c                .    U R                   R                  $ r]   )r   	is_insertrX   s    r>   r   StatementLambdaElement.is_insertt  r  r=   c                .    U R                   R                  $ r]   )r   is_textrX   s    r>   r  StatementLambdaElement.is_textx  s    }}$$$r=   c                .    U R                   R                  $ r]   )r   	is_deleterX   s    r>   r   StatementLambdaElement.is_delete|  r  r=   c                .    U R                   R                  $ r]   )r   is_dmlrX   s    r>   r  StatementLambdaElement.is_dml  s    }}###r=   c                4    [        U R                  5       5      $ )zdReturn a new :class:`.StatementLambdaElement` that will run
all lambdas unconditionally each time.

)NullLambdaStatementrQ   rX   s    r>   spoilStatementLambdaElement.spoil  s    
 #4779--r=   r2   )rQ   _StmtLambdaTyperN   rM   r^   r   rb   r   )r   _StmtLambdaElementType[Any]r   r?   )TNTT)r   r  r7   boolr/   zOptional[Any]r8   r  r;   r  r   r?   )r   r   )r   r  )r3   r4   r5   r6   r   r   r,   rd   r   r   r   r   r   r   r   r   r  r  r
  r  r  r  r  r  r<   r2   r=   r>   r?   r?     s   0  ?L=A		  	 <		
 $;	(0(	( !%"&(,#'-I*-I -I  	-I
 "&-I !-I 
 -I^
5 ' ' + + 6 6 0 0 3 3 ' ' ' ' ' ' % % ' ' $ $.r=   c                  p    \ rS rSrSrSrSrS\R                  R                  4/r
S rS rS rS	 rS
 rSrg)r  i  zProvides the :class:`.StatementLambdaElement` API but does not
cache or analyze lambdas.

the lambdas are instead invoked immediately.

The intended use is to isolate issues that may arise when using
lambda statements.

rG   TrH   c                2    Xl         UR                  U l        g r]   )rH   ra   )rY   	statements     r>   rd   NullLambdaStatement.__init__  s    " ) : :r=   c                .    [        U R                  U5      $ r]   )r   rH   r   s     r>   r   NullLambdaStatement.__getattr__  s    t~~s++r=   c                <    U" U R                   5      n[        U5      $ r]   rH   r  )rY   r   r!  s      r>   r   NullLambdaStatement.__add__      $..)	"9--r=   c                <    U" U R                   5      n[        U5      $ r]   r&  )rY   r   r   r!  s       r>   r    NullLambdaStatement.add_criteria  r(  r=   c                    U R                   R                  (       a  UR                  XU5      $ [        R                  " U 5      er]   )rH   r   r   r   r   r   s       r>   r   *NullLambdaStatement._execute_on_connection  s=     >>,,44(9  ..t44r=   )ra   rH   N)r3   r4   r5   r6   r   r   r   r   r   r   r   rd   r   r   r   r   r<   r2   r=   r>   r  r    sK     &N 
h00AAB;,.
.
5r=   r  c                  @    \ rS rSr% SrS\S'         S	S jrS rSrg)
r   i  zARepresent subsequent links of a :class:`.StatementLambdaElement`.r?   rK   c                    X0l         Xl        X l        UR                  UR                  4-   U l        U R                  XU5        UR                  U l        g r]   )r^   rQ   rK   rR   rW   r_   ra   )rY   rQ   rK   r^   s       r>   rd   LinkedLambdaElement.__init__  sK     	*(44~E""2T2 - > >r=   c                :    U" U R                   R                  5      $ r]   )rK   rH   r   s      r>   rt   #LinkedLambdaElement._invoke_user_fn  s    $$$..//r=   )ra   rQ   r^   rK   rR   N)rQ   r  rK   r?   r^   r   )	r3   r4   r5   r6   r   r9   rd   rt   r<   r2   r=   r>   r   r     s1    K))?'? .? 8	?0r=   r   c                      \ rS rSr% Sr\R                  " 5       rS\S'   \	R                  " 5       r\S 5       rS rS rS rS	 rS
 r\S 5       rS rS rS r  SS jr SS jrS rSrg)rj   i  )r8   r;   rx   rp   build_py_wrappersz1weakref.WeakKeyDictionary[CodeType, AnalyzedCode]_fnsc                l    U R                   UR                     $ ! [         a     Of = fU R                     UR                  U R                   ;   a"  U R                   UR                     sS S S 5        $ [	        XU40 UD6=U R                   UR                  '   nUsS S S 5        $ ! , (       d  f       g = fr]   )r4  rW   KeyErrorrq   rj   )clsrQ   rG   	lambda_kwr   analyzeds         r>   rk   AnalyzedCode.get  s    	88BKK(( 		 ""{{chh&xx, #" 0<I0130 CHHR[[!H  #""s    
((3B%4'B%%
B3c                   [         R                  " U5      (       a  [        R                  " SU-  5      eUR                  nUR
                  =(       a    UR                  U l        UR                  nUR                  nUR                  nU=(       a    U(       + U l	        / U l
        / U l        / U l        U(       aA  U(       a  U R                  U5        U R                  U5        U(       a  U R                  U5        U R!                  XU5        g )Nz/Method %s may not be passed as a SQL expression)inspectismethodr   ArgumentErrorri   r;   r:   r7   r/   r8   rx   rp   r3  _init_track_on_init_globals_init_closure"_setup_additional_closure_trackers)rY   rQ   rG   r^   rz   r7   r/   r8   s           r>   rd   AnalyzedCode.__init__  s    B##ABF  .. ##F(F(F 	 ..=="&">">'>'Ox<$
 #%
 !#!###H-r"""2&//DIr=   c                b   ^  T R                   R                  U 4S j[        U5       5       5        g )Nc              3  J   >#    U  H  u  pTR                  X5      v   M     g 7fr]   )_cache_key_getter_track_on).0idxelemrY   s      r>   	<genexpr>.AnalyzedCode._init_track_on.<locals>.<genexpr>  s(      %
0	 ++C660s    #)rp   r   	enumerate)rY   r/   s   ` r>   r?  AnalyzedCode._init_track_on  s)    $$ %
&x0%
 	
r=   c                   U R                   nU R                  nU R                  nUR                  R                   H  nXQR
                  ;  a  M  U R                  UR
                  U   5      n[        R                  " U5      (       d  MO  UR                  US 45        U(       d  Mk  UR                  U R                  U5      5        M     g r]   )r3  rx   r;   rW   co_names__globals___roll_down_to_literalr   _deep_is_literalappend$_bound_parameter_getter_func_globals)rY   rQ   r3  rx   r;   name_bound_values          r>   r@  AnalyzedCode._init_globals   s     22!44!44KK((D>>)55bnnT6JKL)),77!(($6%%&--AA$G )r=   c           	     L   U R                   nUR                  nU R                  nU R                  nU R                  nU R
                  n[        [        UR                  R                  U5      5       H  u  nu  pU R                  U
R                  5      n[        R                  " U5      (       a=  UR                  X45        U(       a"  UR                  U R                  X5      5        My  M{  U(       d  M  UR                  U R!                  XXR                  5      5        M     g r]   )r3  ri   r;   r8   rx   rp   rL  ru   rW   co_freevarsrQ  cell_contentsr   rR  rS  $_bound_parameter_getter_func_closure"_cache_key_getter_closure_variable)rY   rQ   r3  rz   r;   r8   rx   rp   closure_indexfvcellrV  s               r>   rA  AnalyzedCode._init_closure2  s    22..!44"&">">!4400)2''1*
%M:B  55d6H6HIL)),77!((")<=%&--AA & +*$++??M3E3E)*
r=   c                    [        U US U5      nU R                  nUR                   H6  nUR                  (       a  M  UR	                  U R                  X5      5        M8     g r]   )r&   rp   closure_pywrappers_sa__has_paramrS  !_cache_key_getter_tracked_literal)rY   rQ   rG   r^   analyzed_functionrp   	pywrappers          r>   rB  /AnalyzedCode._setup_additional_closure_trackersU  sa     -	
  00*==I+++ ''::2I >r=   c                   [        US5      nU(       a{  [        U[        R                  [        R
                  [        45      (       dG   UR                  5       n[        U[        R                  [        R
                  [        45      (       d  MG  U(       d+  [        R                  " USS9nUb   UR                  5       $ U$ U$ ! [         a     MA  f = f! [         a    Us $ f = f)N__clause_element__Fraiseerr)hasattrr   r   r"   r   
SchemaItemr   ri  AttributeErrorr   r<  )r7  r   r   insps       r>   rQ  "AnalyzedCode._roll_down_to_literalk  s    #G-AB (00&2C2CTJ %88:G	 !(00&2C2CTJ  !%%g>D 2244
 NN &  &  K s$   	C /C 
CCC#"C#c                   ^ U4S jnU$ )zReturn a getter that will extend a list of bound parameters
with new entries from the ``__globals__`` collection of a particular
lambda.

c                x   > UR                   T   n[        R                  US5      " U R                   T   U5        g N_extract_bound_parameters)rP  object__getattribute__)
current_fnry   resultwrapperrU  s       r>   extract_parameter_valueRAnalyzedCode._bound_parameter_getter_func_globals.<locals>.extract_parameter_value  s;     .99$?G##G-HI&&t,fr=   r2   )rY   rU  rz  s    ` r>   rT  1AnalyzedCode._bound_parameter_getter_func_globals  s    	 '&r=   c                   ^ U4S jnU$ )zReturn a getter that will extend a list of bound parameters
with new entries from the ``__closure__`` collection of a particular
lambda.

c                   > UR                   T   R                  n[        R                  US5      " U R                   T   R                  U5        g rs  )ri   rZ  ru  rv  )rw  ry   rx  ry  r]  s       r>   rz  RAnalyzedCode._bound_parameter_getter_func_closure.<locals>.extract_parameter_value  sN     .99m  ##G-HI&&}5CCVr=   r2   )rY   rU  r]  rz  s     ` r>   r[  1AnalyzedCode._bound_parameter_getter_func_closure  s    	 '&r=   c                   ^ [        U[        5      (       a  U4S jnU$ [        U[        R                  5      (       a  U4S jnU$ U4S jnU$ )zReturn a getter that will extend a cache key with new entries
from the "track_on" parameter passed to a :class:`.LambdaElement`.

c                N   >^^ [        UU4S jUR                  T    5       5      $ )Nc              3  H   >#    U  H  nUR                  TT5      v   M     g 7fr]   r   )rG  tup_elemrn   r|   s     r>   rJ  GAnalyzedCode._cache_key_getter_track_on.<locals>.get.<locals>.<genexpr>  s(      $6 ++HjAA$6   ")ro   r/   rz   r^   rn   r|   rH  s     ``r>   rk   4AnalyzedCode._cache_key_getter_track_on.<locals>.get  s&     $(MM#$6  r=   c                @   > UR                   T   R                  X#5      $ r]   )r/   r   r  s       r>   rk   r    s    }}S)88NNr=   c                "   > UR                   T   $ r]   )r/   r  s       r>   rk   r    s    }}S))r=   )r   ro   rl   HasCacheKey)rY   rH  rI  rk   s    `  r>   rF  'AnalyzedCode._cache_key_getter_track_on  sL     dE""  
 j4455O 
* 
r=   c                R  ^ ^^^^^ [        U[        R                  5      (       a
  UUU4S jnU$ [        U[        R                  5      (       a  U4S jnU$ [        U[
        R                  5      (       a  UUU U4S jnU$ UnSn	[        US5      (       a9  Sn	[        USS5      (       d  UR                  5       nOO[        US5      (       a  M9  U	(       d,  [        R                  " USS9n
U
b  T R                  TTTU
SS	9$ OT R                  TTTUSS
9$ T R                  TT5        W$ )z{Return a getter that will extend a cache key with new entries
from the ``__closure__`` collection of a particular lambda.

c                  > U T   R                   nT(       a  [        R                  " U5      nOMT(       aF  [        US5      (       a5  [	        USS5      (       d  UR                  5       n[        US5      (       a  M5  UR                  X#5      $ )Nri  r   F)rZ  r   r<  rl  r   ri  r   )rz   r^   rn   r|   objrH  use_clause_elementuse_inspects        r>   rk   <AnalyzedCode._cache_key_getter_closure_variable.<locals>.get  sw    cl00$,,S1C'!#';<<&s,?GG"%"8"8":C "#';<< ))(??r=   c                6   > U T   R                   R                  $ r]   )rZ  rW   r  s       r>   rk   r    s    s|11:::r=   c                   >^^ U T   R                   n [        UU4S jU 5       5      $ ! [         a  nTR                  T	TUS9   S nAg S nAff = f)Nc              3  H   >#    U  H  nUR                  TT5      v   M     g 7fr]   r  )rG  rI  rn   r|   s     r>   rJ  OAnalyzedCode._cache_key_getter_closure_variable.<locals>.get.<locals>.<genexpr>  s(      !$,D ++HjAA$,r  )from_)rZ  ro   rn  '_raise_for_uncacheable_closure_variable)
rz   r^   rn   r|   contentsaerQ   rH  rY   variable_names
     ``  r>   rk   r    s^    "3<55  !$,!   & @@%r A s   * 
AA

AFri  Tr   rj  )r  )r  )r   rl   r  typesFunctionTypecollections_abcSequencerl  r   ri  r   r<  r\  r  )rY   rQ   r  rH  rZ  r  r  rk   r   r   ro  s   ```` ``    r>   r\  /AnalyzedCode._cache_key_getter_closure_variable  sE    mZ%;%;<<	@t 
_ u'9'9::;Z 
U '?'?@@ P 
- $G %'#788$(!w(;UCC%88:G '#788 %!))'EB#BBM3$ C   $
 >>sG ?   88K
r=   Nc                V    [         R                  " SU< SUR                  < S35      Ue)NzClosure variable named 'z' inside of lambda callable a   does not refer to a cacheable SQL element, and also does not appear to be serving as a SQL literal bound value based on the default SQL expression returned by the function.   This variable needs to remain outside the scope of a SQL-generating lambda so that a proper cache key may be generated from the lambda's state.  Evaluate this variable outside of the lambda, set track_on=[<elements>] to explicitly select closure elements to track, or set track_closure_variables=False to exclude closure variables from being part of the cache key.)r   InvalidRequestErrorrW   )rY   r  rQ   r  s       r>   r  4AnalyzedCode._raise_for_uncacheable_closure_variable  s,     %% bkk+
 	r=   c                n    UR                   nUR                  nUR                  nU R                  XXC5      $ )ai  Return a getter that will extend a cache key with new entries
from the ``__closure__`` collection of a particular lambda.

this getter differs from _cache_key_getter_closure_variable
in that these are detected after the function is run, and PyWrapper
objects have recorded that a particular literal value is in fact
not being interpreted as a bound parameter.

)_sa__to_evaluate_sa__closure_index	_sa__namer\  )rY   rQ   	pytrackerrI  r]  r  s         r>   rd  .AnalyzedCode._cache_key_getter_tracked_literal"  s=     ))!44!++66}
 	
r=   )rx   r3  rp   r;   r8   )FFr]   )r3   r4   r5   r6   	__slots__weakrefWeakKeyDictionaryr4  r9   	threadingRLockrq   classmethodrk   rd   r?  r@  rA  rB  rQ  rT  r[  rF  r\  r  rd  r<   r2   r=   r>   rj   rj     s    I 	!!# 	
;  ") $%JN
$!F,  2'"'&@ !JZ (,&
r=   rj   c                  b    \ rS rSr% SrSrS\S'   SrS\S'   SrS	\S
'   SS jr	\
SS j5       rSrg)r%   i6  r   N"Optional[List[BindParameter[Any]]]rs   %Optional[List[_BoundParameterGetter]]rx   Fr"   r   c                    Xl         g r]   r  r   s     r>   rd   NonAnalyzedFunction.__init__@  s    	r=   c                    U R                   $ r]   r  rX   s    r>   r   !NonAnalyzedFunction.expected_exprC  s    yyr=   )r   r"   )r   r"   )r3   r4   r5   r6   r  rs   r9   rx   r   rd   r   r   r<   r2   r=   r>   r%   r%   6  sC    I=A:A@D=DK
  r=   r%   c                  P    \ rS rSr% SrS\S'   S\S'   S\S'   S	 rS
 rS rS r	Sr
g)r&   iH  )
analyzed_coderQ   rb  ry   r   rx   r   r   r`   rs   r  rs   z)Union[ClauseElement, List[ClauseElement]]r   r  rx   c                    Xl         X@l        UR                  U l        U R                  U5        U R	                  X#5        g r]   )r  rQ   rx   _instrument_and_run_function_coerce_expression)rY   r  rG   rb   rQ   s        r>   rd   AnalyzedFunction.__init__Z  s9     +"/"B"B)).9Fr=   c           	     X   U R                   nU R                  n/ =U l        nUR                  nU(       d   U=U l        nUR                  U5      U l        g UR                  nUR                  nU(       a?  [        UR                  R                  U5       V	V
s0 s H  u  pXR                  _M     nn	n
O0 nUR                  R                  5       nU Ht  u  pUbO  X   R                  n[        UUUUU R                   R                   S9=X'   nU(       a  UR#                  U5        MU  MW  UR                  U   n[        X=U5      X'   Mv     U R%                  UUR                  R                   Vs/ s H  oU   PM	     snU5      =U l        nUR                  U5      U l        g s  sn
n	f s  snf )N)r]  r;   )r  rQ   rb  r3  ry   rt   r   r8   ri   ru   rW   rY  rZ  rP  copy	PyWrapperr;   rS  _rewrite_code_obj)rY   rG   r  rQ   rb  r3  ry   r8   rz   r^  r_  new_closurenew_globalsrU  r]  rw   r   s                    r>   r  -AnalyzedFunction._instrument_and_run_functionj  s   **WW799"4);; EGGD(+B&667NODI&3&K&K#nnG  %((?(?$I$I ***$I  
 ! ..--/K'8# ,#2@@E/8&3 ..AA0 K% /*11$7 / NN40E(1"E(BK%! (9* &&35;;3J3JK3J4&3JKD(+B& '667NODIcB Ls   F!-F'
c                   UR                   nU R                  nUc  [        U[        R                  5      (       aH  U Vs/ s H-  n[        S[        R                  " UR                  UUS95      PM/     snU l	        SU l
        OD[        S[        R                  " UR                  UUS95      U l	        SU l
        OX@l	        SU l
        Ub  UR                  U l        g[        R                  U l        gs  snf )a  Run the tracker-generated expression through coercion rules.

After the user-defined lambda has been invoked to produce a statement
for re-use, run it through coercion rules to both check that it's the
correct type of object and also to coerce it to its useful form.

Nr"   )rb   TF)rK   r   r   r  r  r   r   r   rN   r   r   ra   r`   r   
EMPTY_DICT)rY   rG   rb   rK   r   r   s         r>   r  #AnalyzedFunction._coerce_expression  s     '44yy $ 8 899 %)
& %) '!((*//$2G %)
&" $( %)#$$&++.C&" $) !%$D ,#8#I#ID #'??D ;
&s   4C2c                V   [        [        U5      5      nSnU(       a:  USSR                  S U 5       5      < SSR                  S U 5       5      < S3-  nUS-  nUS	SR                  S
 U 5       5      -  -  nUS-  nU Vs0 s H  nSU-  X&   _M     nn[        XWU5        US   " 5       n[	        U5      " UR
                  X1R                  UR                  U5      n	UR                  U	l        UR                  U	l	        UR                  U	l
        UR                  U	l        U	$ s  snf )zQReturn a copy of f, with a new closure and new globals

yes it works in pypy :P

zdef make_cells():
z    (z, c              3  ,   #    U  H
  nS U-  v   M     g7fzi%dNr2   rG  is     r>   rJ  5AnalyzedFunction._rewrite_code_obj.<locals>.<genexpr>       6X%!)X   z) = (c              3  ,   #    U  H
  nS U-  v   M     g7f)o%dNr2   r  s     r>   rJ  r    r  r  z)
z    def closure():
z        return %s
c              3  ,   #    U  H
  nS U-  v   M     g7fr  r2   r  s     r>   rJ  r    s     1NX%!)Xr  z    return closure.__closure__r  
make_cells)rangelenjoinexecr   rW   r3   __defaults__r9   __kwdefaults__r   r4   )
rY   fcell_valuesglobals_argrangecoder  vars_rz   funcs
             r>   r  "AnalyzedFunction._rewrite_code_obj  s    [)*$		6X66		6X66 D 	&&%		1NX1N(NNN004<=HqKN*H=T% %'AwJJ**anng
  !00..yy,, >s   D&)	r  rx   rb  r   r   rQ   r   r`   ry   N)r3   r4   r5   r6   r  r9   rd   r  r  r  r<   r2   r=   r>   r&   r&   H  s6    I ;:<<==G BPH+3Zr=   r&   c                  h    \ rS rSrSr   SS jrS rS rS rS r	SS	 jr
S
 rS rS rS rS rSrg)r  i  ah  A wrapper object that is injected into the ``__globals__`` and
``__closure__`` of a Python function.

When the function is instrumented with :class:`.PyWrapper` objects, it is
then invoked just once in order to set up the wrappers.  We look through
all the :class:`.PyWrapper` objects we made to find the ones that generated
a :class:`.BindParameter` object, e.g. the expression system interpreted
something as a literal.   Those positions in the globals/closure are then
ones that we will look at, each time a new lambda comes in that refers to
the same ``__code__`` object.   In this way, we keep a single version of
the SQL expression that this lambda produced, without calling upon the
Python function that created it more than once, unless its other closure
variables have changed.   The expression is then transformed to have the
new bound values embedded into it.

Nc                v    Xl         X l        X0l        S U l        SU l        0 U l        XPl        X@l        X`l        g )NF)	rQ   _name_to_evaluate_param
_has_param_bind_paths_getter_closure_indexr;   )rY   rQ   rU  to_evaluater]  r~   r;   s          r>   rd   PyWrapper.__init__  s;     
'+"4r=   c                j   [         R                  U S5      nU" U0 UD6nU R                  (       a  [        R                  " U5      (       ah  [        U[        R                  5      (       dI  [         R                  U S5      n[        R                  " SU< SU R                  R                  < S35      eU$ )Nr  r  zCan't invoke Python callable z+() inside of lambda expression argument at a  ; lambda SQL constructs should not invoke functions from closure variables to produce literal values since the lambda SQL system normally extracts bound values without actually invoking the lambda or any functions within it.  Call the function outside of the lambda and assign to a local variable that is used in the lambda as a closure variable, or set track_bound_values=False if the return value of this function is used in some other way other than a SQL bound value.)ru  rv  _sa_track_bound_valuesr   rR  r   rl   r  r   r  _sa_fnrW   )rY   r   r   rI  rw   rU  s         r>   __call__PyWrapper.__call__!  s    &&t^<c R ''**511&&  **49D)) !$++"6"68   Lr=   c                P    [         R                  U S5      " 5       nU" U/UQ70 UD6$ N_py_wrapper_literalru  rv  rY   opr   kwargsrI  s        r>   operatePyWrapper.operate@  s-    &&t-BCE$))&))r=   c                J    [         R                  U S5      " 5       nU" X$40 UD6$ r  r  r  s        r>   reverse_operatePyWrapper.reverse_operateD  s(    &&t-BCE%(((r=   c                ,   [         R                  U S5      nUb!  UR                  USS9nUR                  U5        [         R                  U S5      R	                  5        H2  n[         R                  US5      nU" U5      nUR                  Xb5        M4     g )Nr  Trg   r  r  )ru  rv  rv   rS  values_sa__extract_bound_parameters)rY   starting_pointresult_listparamrf  r~   r   s          r>   rt  #PyWrapper._extract_bound_parametersH  s    ''h7%%n4%HEu%00}ELLNI,,Y	BF^,G33GI Or=   c                   [         R                  U S5      n[         R                  U S5      nUcK  [         R                  U S5      n[        R                  " USSUUb  UR                  OS S9=U l        nSU l        UR                  USS9$ )Nr  r  r  FT)requiredunique_compared_to_operator_compared_to_typerg   )ru  rv  r   r!   r   r  r  rv   )rY   r   operatorr   r  r  rU  s          r>   r  PyWrapper._py_wrapper_literalR  s    ''h7--dNC=**49D"*"8"8&./3/?$))T# DK% #DO  4 @@r=   c                D    [         R                  U S5      n[        U5      $ Nr  )ru  rv  r  )rY   r  s     r>   __bool__PyWrapper.__bool__a  s    --dNCK  r=   c                B   UR                  S5      (       a  [        R                  XSS  5      $ US;   a  [        R                  X5      $ UR                  S5      (       a!  [        R                  U S5      n[        X!5      $ U R	                  U[
        R                  5      $ )N_sa_   )ri  r  r  r  rV   __dict____r  )
startswithru  rv  r   _sa__add_getterr  
attrgetterrY   r   rI  s      r>   rv  PyWrapper.__getattribute__e  s    >>&!!**4QR99 
 
 **455>>$**4@D4%%''X-@-@AAr=   c                D    [         R                  U S5      n[        U5      $ r  )ru  rv  iter)rY   rI  s     r>   __iter__PyWrapper.__iter__x  s    &&t^<Dzr=   c                    [         R                  U S5      n[        US5      (       d  [        S5      e[	        U[
        5      (       a  [        R                  " S5      eU R                  U[        R                  5      $ )Nr  __getitem__zUDictionary keys / list indexes inside of a cached lambda must be Python literals only)ru  rv  rl  rn  r   r  r   r  r  r  
itemgetterr  s      r>   r   PyWrapper.__getitem__|  sl    &&t^<t]++ //c9%%))6  ##C)<)<==r=   c                ,   [         R                  U S5      nX4nXC;   a  X4   $ U" U5      n[         R                  U S5      nU" U5      n[        R                  U5      n[        R
                  " U5      (       a  [        U R                  XUS9n	XU'   U	$ U$ )Nr  r  )r~   )ru  rv  rj   rQ  r   rR  r  r  )
rY   r   	getter_fn
bind_pathsbind_path_keyr~   rI  rw   rolled_down_valuery  s
             r>   _add_getterPyWrapper._add_getter  s    ,,T=A
(&,,3&&t^<t(>>uE%%&788SGG(/}%NLr=   )	r  r  r  r  r  r  r  rQ   r;   )NNT)NN)r3   r4   r5   r6   r   rd   r  r  r  rt  r  r  rv  r  r   r(  r<   r2   r=   r>   r  r    sL    , 5&>*)JA!B&>r=   r  c                B    [         R                  " U R                  5      $ r]   )r   r<  rH   )rB   s    r>   ro  ro    s    cmm,,r=   )TTNTTN)rB   r  r7   r  r8   r  r/   r.   r:   r  r;   r  r1   r0   r   r?   )H
__future__r   collections.abcabcr  r<  r   r  r  r  r   typingr   r   r   r   r	   r
   r   r   r   r   r   r   r   rl   r   r   r   r   r   baser   r   r   r   	operatorsr   r   r   r   util.typingr    r!   r"   r#   r$   r'   _BoundParameterGetterLRUCacher(   r9   r   rP   r  r)   _StmtLambdaElementTyper,   rC   rE   r   AllowsLambdaRoler?   r  r   rj   r%   r&   r  	_inspectsro  r2   r=   r>   <module>r8     sD   # )           !         %         ! &    ! '',!	#s(OUDEE  !c* +/==+> ( > r3w#s(#2s7#T$!2$), 4G 4 !$(!%&*#/3F	FF "F 	F
  $F F -F FRLH** L^G;M G;TV.	M:V.r,5%00(2H2H ,5^00 0.a
 a
H $q qh_ _D m$- %-r=   