U kf @sUddlmZddlmZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddl m Z ddl mZddl mZddl mZdd l mZdd l mZdd l mZdd l mZdd l mZddl mZddlZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!ddl m"Z"ddl m#Z#ddlm$Z$ddl%m&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddl*m+Z+erdd lm,Z,dd!lm-Z-dd"lm.Z.dd#lm/Z/eee d$fed%fZ0e d$e fZ1e)2d&Z3d'e4d(<e ge fZ5e d$e fZ6e ge fZ7ed)e"d*Z8e e8ge fZ9Gd+d,d,e#Z:dId.d/d/d0d/d/d1d2d3d4d5Z;Gd6d7d7ej-Zeej-Z@Gd=d>d>e?ZAGd?d@d@ZBGdAdBdBZCGdCdDdDZDGdEdFdFe&ZEe(Fe<dGdHZGdS)J) 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.)NonAnalyzedFunctionAnalyzedFunctioni_LambdaCacheType_closure_per_cache_key_E)boundc@s6eZdZUdZdZdZded<dZdZdZ ded<dS) LambdaOptionsTNOptional[object]track_onOptional[_LambdaCacheType] lambda_cache) __name__ __module__ __qualname__enable_trackingtrack_closure_variablesr,__annotations__global_track_bound_valuestrack_bound_valuesr.r7r7F/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/sql/lambdas.pyr*Hs  r*T_StmtLambdaTypeboolr+r-StatementLambdaElement)lmbr2r3r,r5r6r.returnc Cst|tjt||||||dS)ahProduce 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` )r2r,r3r5r6r.)r;r StatementRoler*)r<r2r3r,r5r6r.r7r7r8 lambda_stmtQs;r?c@seZdZUdZdZdZdejjfgZ dZ de d<de d <d Z d e d <d e d<de d<de d<de d<de d<ddZ ed fdddddddZdd Zd!d"Zed#d$Zed%d&Zed'd(Zd)d*Zd+d,Zed fd-d.d/d0d1d2d3Zejd4d5Zd6d7Zdd/d8d9d:d;Zd S)< LambdaElementaA 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 _resolvedr7zTuple[_CloneCallableType, ...] _transformszList[BindParameter[Any]]_resolved_bindparamsNz Optional[StatementLambdaElement] parent_lambdaz4Union[Tuple[Any, ...], Literal[CacheConst.NO_CACHE]]closure_cache_key Type[SQLRole]rolez,Union[AnalyzedFunction, NonAnalyzedFunction]_rec_AnyLambdaTypefnzTuple[CodeType, ...] tracker_keycCsd|jj|jjfS)Nz%s(%r)) __class__r/rK__code__selfr7r7r8__repr__szLambdaElement.__repr__ _LambdaType)Union[Type[LambdaOptions], LambdaOptions]Optional[ClauseElement]rKrHoptsapply_propagate_attrscCs\||_||_|jf|_||_|dkr2|tjkr2|}||||}|dk rX|j}|rX||_ dSN) rKrHrNrLrVrr>_retrieve_tracker_recpropagate_attrs_propagate_attrs)rPrKrHrVrWrecrZr7r7r8__init__s zLambdaElement.__init__c sj}|dkrt}|j}|j}|jt||}g|_|jdk rP|jj }nd}|t j k rt tfdd|jD}t j kr||}||_ z|||} Wqtk rd} YqXqt j }d} n t j }d} ||_ | dkrV|t j k rFtj>||} | |kr2t||||} | _| || <n|| } W5QRXnt||} nddt| jDdd<| |_|t j k r|jdk r|jjdd<|} | dk r| j} | jr| j} | jD]}|| j| q| j} q| S)Nr7csg|]}|qSr7r7).0getteranon_map bindparamsclosurerVr7r8 sz7LambdaElement._retrieve_tracker_rec..cSs g|]\}}|j|jddqS)TZ maintain_key) _with_valuevalue)r^Z orig_bindZnew_bindr7r7r8rd!sr)r.r'rLrK __closure__ AnalyzedCodegetrDrErF _cache_keyNO_CACHErratupleclosure_trackersKeyError_generation_mutexr%closure_bindparamsr$_invoke_user_fnziprIbindparam_trackerstracker_instrumented_fn) rPrKrWrVr.rLtrackerparent_closure_cache_keyrr\keyrArur7r`r8rYs               z#LambdaElement._retrieve_tracker_reccCst|jj|SrX)getattrrI expected_exprrPrxr7r7r8 __getattr__=szLambdaElement.__getattr__cCs|jjSrX)rI is_sequencerOr7r7r8 _is_sequence@szLambdaElement._is_sequencecCs*|jrtjdd|jDS|jjSdS)NcSsg|] }|jqSr7)_select_iterabler^elementr7r7r8rdHsz2LambdaElement._select_iterable..)r~ itertoolschain from_iterablerBrrOr7r7r8rDs zLambdaElement._select_iterablecCs*|jrtjdd|jDS|jjSdS)NcSsg|] }|jqSr7) _from_objectsrr7r7r8rdRsz/LambdaElement._from_objects..)r~rrrrBrrOr7r7r8rNs zLambdaElement._from_objectscCsdd|jDS)NcSsi|]}|j|jqSr7)rxrgr^br7r7r8 Ysz-LambdaElement._param_dict..)rDrOr7r7r8 _param_dictXszLambdaElement._param_dictcs`dd|jDddddfdd |jjrBfdd |D}nt|d d r\t|i}|S) NcSsi|] }|j|qSr7)rxrr7r7r8r\sz?LambdaElement._setup_binds_for_tracked_expr..z(Optional[visitors.ExternallyTraversible]r)rkwr=csDt|tjr@|jkr@|j}|jr.replacecsg|]}t|iqSr7)rreplacement_traverser^Zsub_expr)rr7r8rdmsz?LambdaElement._setup_binds_for_tracked_expr..is_clause_elementF)rDrIr}ryrrrPexprr7)rrr8_setup_binds_for_tracked_expr[s  z+LambdaElement._setup_binds_for_tracked_exprr#zOptional[_CloneCallableType]rNone)clonedeferred_copy_internalsrr=cKs||jfd|i||_dS)Nr)rBrPrrrr7r7r8_copy_internalsvszLambdaElement._copy_internalscCs|jj}|jr||}|SrX)rIrzrDrrr7r7r8rBs zLambdaElement._resolvedcCs|jtjkrd|tj<dS|jj|jf|j}|j}|dk rl|jtjk sLt|j}|jjf||}|j}q4|j r~| |j |Sr) rFrkrlrKrNrMrErAssertionErrorrDextend)rPrarbrparentrwr7r7r8_gen_cache_keys&   zLambdaElement._gen_cache_keyr!)rKargr=cGs|SrXr7rPrKrr7r7r8rrszLambdaElement._invoke_user_fn)r/r0r1__doc____visit_name___is_lambda_elementrInternalTraversaldp_clauseelement_traverse_internalsrCr4rErQr*r]rYr|propertyr~rrrrrrrZmemoized_propertyrBrrrr7r7r7r8r@sD     a     r@cs\eZdZdZedfdddddfdd Zd d Zd d dddZedffdd Z Z S)DeferredLambdaElementa>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. r7rJzType[roles.SQLRole]rSzTuple[Any, ...])rKrHrV lambda_argscs||_t|||dSrX)rsuperr])rPrKrHrVrrMr7r8r]szDeferredLambdaElement.__init__cGs ||jSrX)rrr7r7r8rrsz%DeferredLambdaElement._invoke_user_fnrr!)rr=cGsPt|jtst|jj}||}t|j|}||}|j D] }||}q>|SrX) rrIr%rrurexpectrHrrC)rPrZ tracker_fnrrr7r7r8_resolve_with_argss   z(DeferredLambdaElement._resolve_with_argsNc s*tj|||d|r&|j|f7_dS)N)rrrV)rrrCrrr7r8rsz%DeferredLambdaElement._copy_internals) r/r0r1rr*r]rrrrr __classcell__r7r7rr8rs  %rc@seZdZdZer*edfddddddd Zd dd d d Zd1d ddddddddZddZ e ddddZ e ddZ e ddZ e ddZe d d!Ze d"d#Ze d$d%Ze d&d'Ze d(d)Ze d*d+Ze d,d-Zd.dd/d0ZdS)2r;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` Nr9rGrSrTrUcCsdSrXr7)rPrKrHrVrWr7r7r8r]szStatementLambdaElement.__init___StmtLambdaElementType[Any])otherr=cCs ||SrX) add_criteria)rPrr7r7r8__add__szStatementLambdaElement.__add__Tr:z Optional[Any])rr2r,r3r6r=cCs*|jt|||jj||d}t|||dS)aAdd 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. )r2r3r5r,r6)rErV)rVdictr5LinkedLambdaElement)rPrr2r,r3r6rVr7r7r8r!s*z#StatementLambdaElement.add_criteriacCs<trt|jjtst|jjjr.||||St |dSrX) r rrIrzr!rsupports_execution_execute_clauseelementrObjectNotExecutableErrorrP connectionZdistilled_paramsZexecution_optionsr7r7r8_execute_on_connectionUs z-StatementLambdaElement._execute_on_connectionrr=cCs|jSrX)Z_rec_expected_exprrOr7r7r8_proxiedaszStatementLambdaElement._proxiedcCs|jjSrX)r _with_optionsrOr7r7r8resz$StatementLambdaElement._with_optionscCs|jjSrX)r_effective_plugin_targetrOr7r7r8risz/StatementLambdaElement._effective_plugin_targetcCs|jjSrX)r_execution_optionsrOr7r7r8rmsz)StatementLambdaElement._execution_optionscCs|jjSrX)r_all_selected_columnsrOr7r7r8rqsz,StatementLambdaElement._all_selected_columnscCs|jjSrX)r is_selectrOr7r7r8rusz StatementLambdaElement.is_selectcCs|jjSrX)r is_updaterOr7r7r8rysz StatementLambdaElement.is_updatecCs|jjSrX)r is_insertrOr7r7r8r}sz StatementLambdaElement.is_insertcCs|jjSrX)ris_textrOr7r7r8rszStatementLambdaElement.is_textcCs|jjSrX)r is_deleterOr7r7r8rsz StatementLambdaElement.is_deletecCs|jjSrX)ris_dmlrOr7r7r8rszStatementLambdaElement.is_dmlNullLambdaStatementcCs t|S)ztReturn a new :class:`.StatementLambdaElement` that will run all lambdas unconditionally each time. )rrKrOr7r7r8spoilszStatementLambdaElement.spoil)TNTT)r/r0r1rr r*r]rrrrrrrrrrrrrrrrr7r7r7r8r;sF4           c@sNeZdZdZdZdZdejjfgZ ddZ ddZ d d Z d d Z d dZdS)rzProvides 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. rATrBcCs||_|j|_dSrX)rBr[)rP statementr7r7r8r]szNullLambdaStatement.__init__cCs t|j|SrX)ryrBr{r7r7r8r|szNullLambdaStatement.__getattr__cCs||j}t|SrXrBr)rPrrr7r7r8rs zNullLambdaStatement.__add__cKs||j}t|SrXr)rPrrrr7r7r8rs z NullLambdaStatement.add_criteriacCs$|jjr||||St|dSrX)rBrrrrrr7r7r8rsz*NullLambdaStatement._execute_on_connectionN)r/r0r1rrrrrrrr]r|rrrr7r7r7r8rs  rc@s4eZdZUdZded<ddddddZd d Zd S) rzARepresent subsequent links of a :class:`.StatementLambdaElement`.r;rErrS)rKrErVcCs<||_||_||_|j|jf|_|||||j|_dSrX)rVrKrErLrNrYr[)rPrKrErVr7r7r8r]s zLinkedLambdaElement.__init__cGs ||jjSrX)rErBrr7r7r8rrsz#LinkedLambdaElement._invoke_user_fnN)r/r0r1rr4r]rrr7r7r7r8rs rc@seZdZUdZeZded<e Z e ddZ ddZ dd Zd d Zd d ZddZe ddZddZddZddZd ddZd!ddZddZdS)"ri)r3r6rtrnbuild_py_wrappersz1weakref.WeakKeyDictionary[CodeType, AnalyzedCode]_fnsc Ksz|j|jWStk r"YnX|jR|j|jkrP|j|jW5QRSt|||f||j|j<}|W5QRSQRXdSrX)rrNrorpri)clsrKrAZ lambda_kwrZanalyzedr7r7r8rjs zAnalyzedCode.getcCst|rtd||j}|jo(|j|_|j}|j}|j }|oF| |_ g|_ g|_ g|_ |r|rn| ||||r||||||dS)Nz/Method %s may not be passed as a SQL expression)inspectismethodr ArgumentErrorrhr6r5r2r,r3rtrnr_init_track_on _init_globals _init_closure"_setup_additional_closure_trackers)rPrKrArVrcr2r,r3r7r7r8r]s*      zAnalyzedCode.__init__cs"jfddt|DdS)Nc3s|]\}}||VqdSrX)_cache_key_getter_track_on)r^idxelemrOr7r8 $sz.AnalyzedCode._init_track_on..)rnr enumerate)rPr,r7rOr8r#szAnalyzedCode._init_track_oncCsl|j}|j}|j}|jjD]L}||jkr*q||j|}t|r| |df|r| | |qdSrX) rrtr6rNco_names __globals___roll_down_to_literalr_deep_is_literalappend$_bound_parameter_getter_func_globals)rPrKrrtr6name _bound_valuer7r7r8r)s   zAnalyzedCode._init_globalsc Cs|j}|j}|j}|j}|j}|j}tt|jj |D]d\}\} } | | j } t | r~|| |f|r||| |q6|r6|||| || j q6dSrX)rrhr6r3rtrnrrsrN co_freevarsr cell_contentsrrr$_bound_parameter_getter_func_closure"_cache_key_getter_closure_variable) rPrKrrcr6r3rtrn closure_indexfvcellrr7r7r8r;s8    zAnalyzedCode._init_closurecCs<t||d|}|j}|jD]}|js||||qdSrX)r%rnclosure_pywrappersZ_sa__has_paramr!_cache_key_getter_tracked_literal)rPrKrArVZanalyzed_functionrn pywrapperr7r7r8r^s  z/AnalyzedCode._setup_additional_closure_trackerscCst|d}|rJt|tjtjtfsJz |}Wqtk rFYqJYqXq|st j |dd}|dk rz |WStk r|YSX|S|SdS)N__clause_element__FZraiseerr) hasattrrrr!rZ SchemaItemrrAttributeErrorrr)rrrinspr7r7r8rts&      z"AnalyzedCode._roll_down_to_literalcsfdd}|S)zReturn a getter that will extend a list of bound parameters with new entries from the ``__globals__`` collection of a particular lambda. cs&|j}t|d|j|dSN_extract_bound_parameters)robject__getattribute__Z current_fnruresultwrapperrr7r8extract_parameter_values   zRAnalyzedCode._bound_parameter_getter_func_globals..extract_parameter_valuer7)rPrrr7rr8rs z1AnalyzedCode._bound_parameter_getter_func_globalscsfdd}|S)zReturn a getter that will extend a list of bound parameters with new entries from the ``__closure__`` collection of a particular lambda. cs*|jj}t|d|jj|dSr)rhrrrrrr7r8rs  zRAnalyzedCode._bound_parameter_getter_func_closure..extract_parameter_valuer7)rPrrrr7rr8rs z1AnalyzedCode._bound_parameter_getter_func_closurecsBt|trfdd}n&t|tjr2fdd}n fdd}|S)zReturn a getter that will extend a cache key with new entries from the "track_on" parameter passed to a :class:`.LambdaElement`. cstfdd|jDS)Nc3s|]}|VqdSrXr)r^Ztup_elemrarbr7r8rszGAnalyzedCode._cache_key_getter_track_on..get..)rmr,rcrVrarbrrr8rjsz4AnalyzedCode._cache_key_getter_track_on..getcs|j||SrX)r,rrrr7r8rjscs |jSrX)r,rrr7r8rjs)rrmrk HasCacheKey)rPrrrjr7rr8rs    z'AnalyzedCode._cache_key_getter_track_onFc st|tjrfdd}nt|tjr8fdd}nt|tjrXfdd}n|}d} t|drd} t|dds| }q`qq`| st j |dd } | d k r̈j | dd Snj |dd S |S) zReturn a getter that will extend a cache key with new entries from the ``__closure__`` collection of a particular lambda. csJ|j}rt|}n$r>t|dr>t|dds|}q|||S)NrrF)rrrrryrr)rcrVrarbobj)ruse_clause_element use_inspectr7r8rjs     z.getcs |jjSrX)rrNrrr7r8rjsc s\|j}ztfdd|DWStk rV}zj|dW5d}~XYnXdS)Nc3s|]}|VqdSrXr)r^rrr7r8rszOAnalyzedCode._cache_key_getter_closure_variable..get..)from_)rrmr'_raise_for_uncacheable_closure_variable)rcrVrarbcontentsZae)rKrrP variable_namerr8rjs  FrTrrN)r)r)rrkrtypes FunctionTypecollections_abcSequencerryrrrrr) rPrKrrrrrrjrrrr7)rKrrPrrrr8rs@       z/AnalyzedCode._cache_key_getter_closure_variableNcCstd||jf|dS)NaTClosure variable named '%s' inside of lambda callable %s 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=[] to explicitly select closure elements to track, or set track_closure_variables=False to exclude closure variables from being part of the cache key.)rInvalidRequestErrorrN)rPrrKrr7r7r8rs z4AnalyzedCode._raise_for_uncacheable_closure_variablecCs"|j}|j}|j}|||||S)aReturn 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. )Z_sa__to_evaluateZ_sa__closure_indexZ _sa__namer)rPrKZ pytrackerrrrr7r7r8r+s z.AnalyzedCode._cache_key_getter_tracked_literal)FF)N)r/r0r1 __slots__weakrefWeakKeyDictionaryrr4 threadingRLockrp classmethodrjr]rrrrrrrrrrrr7r7r7r8ris,   '#   M ric@sVeZdZUdZdZded<dZded<dZded <ddd d Ze dd d dZ dS)r$rN"Optional[List[BindParameter[Any]]]rq%Optional[List[_BoundParameterGetter]]rtFr!rcCs ||_dSrXrrr7r7r8r]IszNonAnalyzedFunction.__init__rcCs|jSrXrrOr7r7r8rzLsz!NonAnalyzedFunction.expected_expr) r/r0r1r rqr4rtr}r]rrzr7r7r7r8r$?s   r$c@sJeZdZUdZded<ded<ded<dd Zd d Zd d ZddZdS)r%) analyzed_coderKrrurrtrzr}rZrqrrqz)Union[ClauseElement, List[ClauseElement]]rzrrtcCs.||_||_|j|_|||||dSrX)rrKrt_instrument_and_run_function_coerce_expression)rPrrArWrKr7r7r8r]cs  zAnalyzedFunction.__init__cs|j}|j}g|_}|j}|s8||_}|||_n|j}|j}|rbddt |j j |Dni|j } |D]f\} } | dk r|| j} t|| | | |jjd| <} |r|| qt|j | } t|| | | | <} qt||fdd|j j D| |_}|||_dS)NcSsi|]\}}||jqSr7)r)r^rrr7r7r8rszAAnalyzedFunction._instrument_and_run_function..)rr6csg|] }|qSr7r7)r^rZ new_closurer7r8rdszAAnalyzedFunction._instrument_and_run_function..)rrKrrrurrrr3rhrsrNrrcopyr PyWrapperr6r_rewrite_code_obj)rPrArrKrrrur3rcZ new_globalsrrrgrr7rr8rssH         z-AnalyzedFunction._instrument_and_run_functioncsj}|j}|dkr`t|tjr>fdd|D|_d|_qltdtj j |d|_d|_n ||_d|_dk r~j |_ nt j|_ dS)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. Nc s$g|]}tdtjj|dqS)r!rW)rrrrHrrWrAr7r8rds z7AnalyzedFunction._coerce_expression..Tr!rF)rErrr r rzr}rrrrHr[rZr EMPTY_DICT)rPrArWrErr7rr8rs,     z#AnalyzedFunction._coerce_expressionc stt}d}rD|dddd|Dddd|Df7}|d7}|ddd d|D7}|d 7}fd d |D}t||||d }t||j||j|j|}|j|_|j |_ |j |_ |j |_ |S)zaReturn a copy of f, with a new closure and new globals yes it works in pypy :P zdef make_cells(): z (%s) = (%s) z, css|]}d|VqdSzi%dNr7r^ir7r7r8rsz5AnalyzedFunction._rewrite_code_obj..css|]}d|VqdS)o%dNr7r!r7r7r8rsz def closure(): z return %s css|]}d|VqdSr r7r!r7r7r8rsz return closure.__closure__csi|]}d||qS)r#r7r! cell_valuesr7r8rsz6AnalyzedFunction._rewrite_code_obj..Z make_cells) rangelenjoinexecrrNr/ __defaults__r4__kwdefaults__rr0) rPfr%globals_ZargrangecodeZvars_rcfuncr7r$r8rs2   z"AnalyzedFunction._rewrite_code_objN) r/r0r1r r4r]rrrr7r7r7r8r%Qs  D-r%c@sleZdZdZdddZddZdd Zd d Zd d ZdddZ ddZ ddZ ddZ ddZ ddZdS)raA 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. NTcCs:||_||_||_d|_d|_i|_||_||_||_dS)NF) rK_name _to_evaluate_param _has_param _bind_paths_getterZ_closure_indexr6)rPrKr to_evaluaterr_r6r7r7r8r]s zPyWrapper.__init__cOs^t|d}|||}|jrVt|rVt|tjsVt|d}t d||j j fn|SdS)Nr1r0a#Can't invoke Python callable %s() inside of lambda expression argument at %s; 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.) rrZ_sa_track_bound_valuesrrrrkrrr _sa_fnrN)rPrrrrgrr7r7r8__call__*s$    zPyWrapper.__call__cOst|d}||f||SN_py_wrapper_literalrrrPoprkwargsrr7r7r8operateIszPyWrapper.operatecKst|d}|||f|Sr9r;r<r7r7r8reverse_operateMszPyWrapper.reverse_operatecCsft|d}|dk r,|j|dd}||t|dD]$}t|d}||}|||q s                                       IJ  /f5#