U kf @s.dZddlmZddlZddlmZddlZddlmZddlZddl Z ddl m Z ddl m Z ddl m Z dd l mZdd l mZdd l mZdd l mZdd l mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl mZddl m Z ddl!m"Z"ddl!m#Z#ddl$m%Z%dd l$m&Z&dd!l'm(Z(dd"l#m)Z)dd#l#m*Z*dd$l#m+Z+dd%l#m,Z,d&d'l!m-Z-d&d(l!m.Z.d&d)l!m/Z/d&d*l/m0Z0d&d+l/m1Z1d&d,l/m Z2d&d-l3m4Z4d&d.l3m5Z5d&d/l3m6Z6erdd0l!m7Z7dd1l!m8Z8dd2l!m9Z9dd3l:m;Z;dd4l:mZ>dd6l8m?Z?dd7l8m@Z@dd8l8mAZAdd9l8mBZBdd:l8mCZCdd;l8mDZDddlFmHZHdd?lImJZJdd@lImKZKddAlImLZLd&dBlMmNZNd&dClMmOZOd&dDlPmQZQd&dElPmRZRd&dFlPmSZSd&dGlPmTZTd&dHlPmUZUd&dIlPmVZVd&dJlPmWZWd&dKlPmXZXd&dLlPmYZYd&dMlPmZZZd&dNl-m[Z[esdZ7dZ8dZ9GdOdPdPeZ\e\j]Z]GdQdRdReZ^e^j_Z`edSe dTZaedUe dVe fdTZbeececfZdGdWdXdXeZeefdYZgGdZd[d[e4ZhGd\d]d]e4Zid^d_d`dadbZjedce dTZkGdddedeZlGdfdgdgelZmdhdidjdkdlZndmdndjdodpZoedqdrdTZpGdsdrdre2j4ZqdUdUdtdudvZrdwd^dxdydzd{Zsd|d}Ztd~d~djddZud~d~djddZvd~d~ddddZwd~d~ddddZxGdddeece fZyGdddeece fZze/{dddZ|GdddZ}GdddZ~Gddde0ZGddde0ZGdddeZGdddeZGdddedZGdddee%ZGddde(ZGddde"jZGddde-jZGddde)ZGdddeZGdddeZede decfecZeddddZedddTZGdddeeZGdddeeefZedddTZGdddeecefZGddde/jeeefZGddde/jdZdd[dddÄZe]fddwdddƜddȄZdS)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) coercionselements)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@seZdZdZddZdS)_NoArgrcCs d|jS)Nz_NoArg.)nameselfrTC/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/sql/base.py__repr__jsz_NoArg.__repr__N)__name__ __module__ __qualname__NO_ARGrVrTrTrTrUrPgsrPc@seZdZdZdS) _NoneNamerN)rWrXrY NONE_NAMErTrTrTrUr[qsr[_T)bound_Fn.c@sBeZdZUded<ded<ded<ded<edddd d Zd S) _DefaultDescriptionTuplerargzOptional[bool] is_scalar is_callable is_sentinelzOptional[DefaultGenerator])defaultreturncCs:|r,|js|js,|jr,t|j|j|j|jStddddSN)has_argZ for_updaterdr`rarbrc)clsrerTrTrU_from_column_defaults    z-_DefaultDescriptionTuple._from_column_defaultN)rWrXrY__annotations__ classmethodrjrTrTrTrUr`s r`Z_omit_from_statementsc@seZdZdddddZdS)_EntityNamespacestrSQLCoreOperations[Any]keyrfcCsdSrgrTrSrqrTrTrU __getattr__z_EntityNamespace.__getattr__N)rWrXrYrsrTrTrTrUrmsrmc@s eZdZejddddZdS)_HasEntityNamespacermrfcCsdSrgrTrRrTrTrUentity_namespacesz$_HasEntityNamespace.entity_namespaceN)rWrXrYr)ro_non_memoized_propertyrwrTrTrTrUrusrurzTypeGuard[_HasEntityNamespace])elementrfcCs t|dS)Nrw)hasattr)ryrTrTrU_is_has_entity_namespacesr{_Selfc@sReZdZdZdZdZddZddZdd dd d d Zdd dd ddddZ dS) 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`. rTTcOs tddSNz(Immutable objects do not support copyingNotImplementedErrorrSZ optionaldictkwargsrTrTrU unique_paramsszImmutable.unique_paramscOs tddSr~rrrTrTrUparamsszImmutable.paramsr|r)rSkwrfcKs|SrgrTrSrrTrTrU_cloneszImmutable._clone) omit_attrsz Iterable[str]None)rrrfcKsdSrgrT)rSrrrTrTrU_copy_internalsszImmutable._copy_internalsN) rWrXrY__doc__ __slots__ _is_immutablerrrrrTrTrTrUr}s r}c@sReZdZUdZdZded<dddddddZejd d d d Z e d dZ dS)SingletonConstantz.Represent SQL constants like NULL, TRUE, FALSET _singletonr]r)rirarrfcOs tt|jSrg)rr]r)rirarrTrTrU__new__szSingletonConstant.__new__zFrozenSet[ColumnElement[Any]]rvcCs tdSrgrrRrTrTrU proxy_setszSingletonConstant.proxy_setcCs(t|}|t|g|_||_dSrg)objectr__init__ frozensetrr)riobjrTrTrU_create_singletons  z#SingletonConstant._create_singletonN) rWrXrYrZ_is_singleton_constantrkrr)Znon_memoized_propertyrrlrrTrTrTrUrs rzEUnion[ColumnElement[Any], FromClause, TextClause, _JoinTargetElement]zIterator[FromClause]r2rfcGstjdd|DS)NcSsg|] }|jqSrT) _from_objects).0ryrTrTrU sz!_from_objects.. itertoolschain from_iterabler1rTrTrUrs rz!Iterable[roles.ColumnsClauseRole]rAcCstjdd|DS)zXexpand tables into individual columns in the given list of column expressions. cSsg|] }|jqSrT)Z_select_iterablercrTrTrUrsz%_select_iterables..rr1rTrTrU_select_iterabless r_SelfGenerativeType_GenerativeTypec@seZdZddddZdS)rr.rvcCsdSrgrTrRrTrTrU _generatertz_GenerativeType._generateN)rWrXrYrrTrTrTrUrs)fnrfcCs.tjdddddddd}||}||_|S)znon-caching _generative() decorator. This is basically the legacy decorator that copies the object and runs a method on the new copy. r_rr)rrSargsrrfc_s,|}||f||}||ks(td|S)zMark a method as generative.z#generative methods must return self)rAssertionError)rrSrrxrTrTrU _generativesz _generative.._generative)r) decoratorZnon_generative)rrZ decoratedrTrTrUrs  rrnCallable[[_Fn], _Fn])namesrrfcsB|di|difdd|Dtjfdd}|S)Nmsgsdefaultscs$g|]}|t||dfqSrg)operator attrgetterget)rrQ)rrTrUr%sz&_exclusive_against..csb|d}|dd}D]8\}}}|||k r|d|j|jf}t|q||f||S)Nrrz9Method %s() has already been invoked on this %s construct)rrW __class__r(InvalidRequestError)rrrrSrQgetterZdefault_msg)gettersrrTrUcheck*s    z!_exclusive_against..check)popr)r)rrrrT)rrrrU_exclusive_against s   rcKs |jf|Srg)r)ryrrTrTrUr=srzIterable[_CLE]cCstjdd|DS)z\expand the given set of ClauseElements to be the set of all 'cloned' predecessors. cSsg|] }|jqSrT) _cloned_setrrrTrTrUrIsz"_expand_cloned..)rrr1rTrTrU_expand_clonedAsrccs&|D]}|jdk r|j}q|VqdSrg)Z _is_clone_of)r2rrTrTrU _de_cloneLs rz Set[_CLE])abrfcs(tt|t|fdd|DS)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'. csh|]}|jr|qSrT intersectionrrelemZ all_overlaprTrU ]s z'_cloned_intersection..setrrrrrTrrU_cloned_intersectionUsrcs(tt|t|fdd|DS)Ncsh|]}|js|qSrTrrrrTrUrbs z%_cloned_difference..rrrTrrU_cloned_difference`s rc@sHeZdZdZddZddZddZdd Zd d Zd d Z ddZ dS)_DialectArgViewzaA dictionary view of dialect-level arguments in the form _. cCs ||_dSrg)r)rSrrTrTrUrmsz_DialectArgView.__init__c CsNz|dd\}}Wn,tk r@}zt||W5d}~XYn X||fSdS)N_r)split ValueErrorKeyError)rSrqdialect value_keyerrrTrTrU_keyps z_DialectArgView._keyc CsZ||\}}z|jj|}Wn.tjk rL}zt||W5d}~XYn X||SdSrg)rrdialect_optionsr(NoSuchModuleErrorr)rSrqrroptrrTrTrU __getitem__xs z_DialectArgView.__getitem__c CsVz||\}}Wn.tk r@}ztd|W5d}~XYnX||jj||<dS)Nz0Keys must be of the form _)rrr( ArgumentErrorrr)rSrqvaluerrrrTrTrU __setitem__sz_DialectArgView.__setitem__cCs ||\}}|jj||=dSrg)rrr)rSrqrrrTrTrU __delitem__sz_DialectArgView.__delitem__cCstdd|jjDS)Ncss|]}t|jVqdSrg)len _non_defaults)rrrTrTrU sz*_DialectArgView.__len__..)sumrrvaluesrRrTrTrU__len__s z_DialectArgView.__len__csfddjjDS)Nc3s.|]&}jj|jD]}d||fVqqdS)z%s_%sN)rrr)r dialect_nameZ value_namerRrTrUrs z+_DialectArgView.__iter__..)rrrRrTrRrU__iter__s z_DialectArgView.__iter__N) rWrXrYrrrrrrrrrTrTrTrUrgs  rc@s@eZdZdZddZddZddZdd Zd d Zd d Z dS)_DialectArgDictzA dictionary view of dialect-level arguments for a specific dialect. Maintains a separate collection of user-specified arguments and dialect-specified default arguments. cCsi|_i|_dSrgr _defaultsrRrTrTrUrsz_DialectArgDict.__init__cCstt|j|jSrg)rrrunionrrRrTrTrUrsz_DialectArgDict.__len__cCstt|j|jSrg)iterrrrrrRrTrTrUrsz_DialectArgDict.__iter__cCs"||jkr|j|S|j|SdSrgrrrrTrTrUrs  z_DialectArgDict.__getitem__cCs||j|<dSrgrrSrqrrTrTrUrsz_DialectArgDict.__setitem__cCs |j|=dSrgrrrrTrTrUrsz_DialectArgDict.__delitem__N) rWrXrYrrrrrrrrTrTrTrUrsrzsqlalchemy.dialectscCs(tjjj|}|jdkrdSt|jSrg)r) preloadedZdialectsregistryloadZconstruct_argumentsdict)rZ dialect_clsrTrTrU_kw_reg_for_dialects rc@sveZdZdZdZdejfgZeddZ e j ddZ e dd Ze eZd d Ze j d d ZdddddZdS) DialectKWArgsa9Establish 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` rTrcCs@tj|}|dkr td|||kr0i||<||||<dS)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)rir argument_namereconstruct_arg_dictionaryrTrTrU argument_fors& zDialectKWArgs.argument_forcCst|S)aA collection of keyword arguments specified as dialect-specific options to this construct. The arguments are present here in their original ``_`` 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 ``_`` where the value will be assembled into the list of options. .. seealso:: :attr:`.DialectKWArgs.dialect_options` - nested dictionary form )rrRrTrTrUdialect_kwargs szDialectKWArgs.dialect_kwargscCs|jS)z4A synonym for :attr:`.DialectKWArgs.dialect_kwargs`.)rrRrTrTrUr szDialectKWArgs.kwargscCsXtj|}t}|dkr*|jddin*t|jjD]}||kr6|j||q6|S)N*)rrrrupdatereversedr__mro__)rSrrdrirTrTrU_kw_reg_for_dialect_cls's z%DialectKWArgs._kw_reg_for_dialect_clscCstt|jS)aA collection of keyword arguments specified as dialect-specific options to this construct. This is a two-level nested registry, keyed to ```` and ````. 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) PopulateDictZportable_instancemethodrrRrTrTrUr3s zDialectKWArgs.dialect_optionsDict[str, Any]r)rrfc Cs|sdS|D]}td|}|s,td||dd\}}z|j|}WnVtjk rtd||ft |j|<}|j ddi|||j |<Yq Xd|kr||krt d|||jfq ||||<q dS)Nz ^(.+?)_(.+)$zGAdditional arguments should be named _, got '%s'rr&zHCan't validate argument %r; can't locate any SQLAlchemy dialect named %rrz9Argument %r is not accepted by dialect %r on behalf of %r)rematch TypeErrorgrouprr(rr)warnrrrrrr)rSrkmrZarg_namerrrTrTrU_validate_dialect_kwargsJs@  z&DialectKWArgs._validate_dialect_kwargsN)rWrXrYrrr%Zdp_dialect_optionsZ"_dialect_kwargs_traverse_internalsrlrr)memoized_propertyrpropertyrrrrrrrrTrTrTrUrs  /     rc@s~eZdZUdZdZiZded<ded<eddZd d Z ed d d ddZ ed dd dddZ eddddddZ dS) CompileStateaProduces 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 cKs||jrB|jdd}|j||jfd}|dkrR|jd|jf}n|jd|jf}||krh|||f|S|j||f|SdSNZcompile_state_pluginre)_propagate_attrsrr _effective_plugin_targetcreate_for_statement)rir compilerr plugin_nameklassrTrTrUrs&z!CompileState.create_for_statementcKs ||_dSrg)r )rSr rrrTrTrUrszCompileState.__init__ ExecutableOptional[Type[CompileState]])r rfcCs^|jdd}|r0||jf}||jkr0|j|Sz|jd|jfWStk rXYdSXdSr )r rrr r)rir rrqrTrTrUget_plugin_classs   zCompileState.get_plugin_classrn)r rrfcCs.z|j||jfWStk r(YdSXdSrg)r rr)rir rrTrTrU_get_plugin_class_for_plugins z)CompileState._get_plugin_class_for_pluginr)r visit_namerfcsfdd}|S)Ncs|jf<|Srg)r )Zcls_to_decoraterirrrTrUdecoratesz)CompileState.plugin_for..decoraterT)rirrrrTrrU plugin_forszCompileState.plugin_forN) rWrXrYrrr rkrlrrrrrrTrTrTrUrrs    rc@seZdZdZddddZdS) GenerativezUProvide a method-chaining pattern in conjunction with the @_generative decorator.r.rvcsJ|j|j}||}r:fdd|jD|_n |j|_|S)Ncsi|]\}}|kr||qSrTrT)rrvskiprTrU sz(Generative._generate..)_memoized_keysrr__dict__copyitems)rSrisrTrrUrs    zGenerative._generateN)rWrXrYrrrTrTrTrUrsrc@seZdZdZdZddZdS)InPlaceGenerativezkProvide a method-chaining pattern in conjunction with the @_generative decorator that mutates in place.rTcCs"|j}|D]}|j|dq |Srg)r r!r)rSrrrTrTrUrszInPlaceGenerative._generateN)rWrXrYrrrrTrTrTrUr%sr%c@s2eZdZUdZdZded<ejZded<e j Z dS)HasCompileStatez=A class that has a :class:`.CompileState` associated with it.Nr_compile_state_pluginutil.immutabledict[str, Any] _attributes) rWrXrYrr'rkr) EMPTY_DICTr)rrZ_compile_state_factoryrTrTrTrUr&s  r&c@sXeZdZUdZded<ddZerTdddd d Zddd d d dZdd dddZ dS) _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_attrscCsB|}t||jr2td|t||jf|j||SNzBdictionary contains attributes not covered by Options class %s: %r)r differencer-rr!rrSotherZo1rTrTrU__add__s z_MetaOptions.__add__rnrrpcCsdSrgrTrrrTrTrUrs rtz_MetaOptions.__getattr__rrqrrfcCsdSrgrTrrTrTrU __setattr__"rtz_MetaOptions.__setattr__cCsdSrgrTrrrTrTrU __delattr__$rtz_MetaOptions.__delattr__N) rWrXrYrrkr2rrsr4r5rTrTrTrUr+s  r+cseZdZUdZdZded<ddfdd Zd d Zd d Zd dZ ddZ e dddddZ e ddZe ddddZejZded<ejddddZe dd Ze d!d"Zerd#d$d%d&d'Zd#d$dd(d)d*Zd#dd%d+d,ZZS)-Optionsz,A cacheable option dictionary with defaults.rTr,r-rrvcs,|j}ttdd|D|_tdS)Ncss$|]}|ds|dkr|VqdS)__)Z_cache_key_traversalN) startswith)rrrTrTrUr1s z,Options.__init_subclass__..)r!tuplesortedr-super__init_subclass__)riZdict_rrTrUr<.szOptions.__init_subclass__cKs|j|dSrg)r!rrrTrTrUr:szOptions.__init__cCsX|j|j}|j|jt||jrHtd|t||jf|j||Sr.)rrr!rrr/r-rr0rTrTrUr2=s zOptions.__add__cCs6t|j|jD]"\}}t||t||krdSqdSNFT)rr-getattr)rSr1rrrTrTrU__eq__KszOptions.__eq__cs&djjdfddjDfS)N%s(%s), c3s*|]"}|jkrd|j|fVqdS)z%s=%rNr!)rrrRrTrUrXs z#Options.__repr__..)rrWjoinr-rRrTrRrUrVSs zOptions.__repr__z Type[Any]bool)rrfcCs t||Srg) issubclass)rirrTrTrU isinstance_szOptions.isinstancecCs||t|||iSrg)r?)rSrQrrTrTrUadd_to_elementcszOptions.add_to_elementzMapping[str, Any]cCs|jSrgrCrRrTrTrU_state_dict_instgszOptions._state_dict_instr(_state_dict_constcCs|jSrg)rJ)rirTrTrU _state_dictmszOptions._state_dictcCsR|}||jk rJ|jrJt|j|jrJtd||t|j|jf||S)Nz]other element %r is not empty, is not of type %s, and contains attributes not covered here %r)rKrr-rr/r)rir1rrTrTrU safe_mergeqs  zOptions.safe_mergec Cs|t||}|||}|ri}|D]6}d|} ||krN|||| <q,||kr,|||| <q,||} t||| i}| |fS||fSdS)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 rN)rrrrr)Z immutabledictZ merge_with) rirqattrsZ exec_optionsZstatement_exec_optionsZcheck_argnamesZexisting_optionsresultargnamelocal new_optionsrTrTrUfrom_execution_optionss&  zOptions.from_execution_optionsrnrrpcCsdSrgrTrrrTrTrUrsrtzOptions.__getattr__r3cCsdSrgrTrrTrTrUr4rtzOptions.__setattr__cCsdSrgrTrrrTrTrUr5rtzOptions.__delattr__)rWrXrYrrrkr<rr2r@rVrlrGr+rHrIr)r*rJ classlevelrKrLrRrrsr4r5 __classcell__rTrTr=rUr6's2      5r6) metaclassc@s6eZdZdZeddZejddZeddZdS) CacheableOptionsrTcCst|||Srg)r_gen_cache_key)rSanon_map bindparamsrTrTrU_gen_cache_key_instsz$CacheableOptions._gen_cache_key_instcCs|dfS)NrTrT)rirXrYrTrTrUrWszCacheableOptions._gen_cache_keycCs t|Srg)rZ_generate_cache_key_for_objectrRrTrTrU_generate_cache_keysz$CacheableOptions._generate_cache_keyN) rWrXrYrr+rZrSrWr[rTrTrTrUrVs  rVc@s*eZdZdZejZdZdZdZ ddZ dS)ExecutableOptionrTZexecutable_optionFTcKs|j|j}t|j|_|S)z/Create a shallow copy of this ExecutableOption.)rrrr!)rSrrrTrTrUrs zExecutableOption._cloneN) rWrXrYrr)r* _annotations__visit_name__Z_is_has_cache_keyZ_is_corerrTrTrTrUr\s r\c@seZdZUdZdZded<ejZded<dZ dZ d ed <dZ d ed <d ed<d e j fd ejfdejfgZdZdZdZdZdZdZdZerded<dddddddddddddZdddd d!d"d#Zddddd!d$d%Zejd&d'Zedd(d)d*Z e!d+d,d-d.d/Z"e!d0d,d1d2d3Z#e!d0d,d-d4d5Z$e!d6dd,d7d8d9Z%e&d:d:d:ddd:d:d:d:ddd:d:d:d:d:dd;dddd?dddddd,d@dAdBZ'e&dd,dCdDdBZ'e!dd,dEdFdBZ'dGd(dHdIZ(dS)JrzMark 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`. TrEsupports_executionrG_execution_optionsFrTzTuple[ExecutableOption, ...] _with_optionsz6Tuple[Tuple[Callable[[CompileState], None], Any], ...]_with_context_optionsz9Optional[Union[Type[CacheableOptions], CacheableOptions]]_compile_optionsr rnr^N)for_executemanyschema_translate_maprLzOptional[CompiledCacheType]z List[str]z Optional[SchemaTranslateMapType]rzCTuple[Compiled, Optional[Sequence[BindParameter[Any]]], CacheStats])rcompiled_cache column_keysrdrerrfcKsdSrgrT)rSrrfrgrdrerrTrTrU_compile_w_caches zExecutable._compile_w_cacherCrErKzCursorResult[Any]) connectiondistilled_paramsexecution_optionsrfcCsdSrgrTrSrirjrkrTrTrU_execute_on_connectionsz!Executable._execute_on_connectioncCsdSrgrTrlrTrTrU_execute_on_scalar%szExecutable._execute_on_scalarcCs tdSrgrrRrTrTrU_all_selected_columns,sz Executable._all_selected_columnsrvcCs|jSrg)r^rRrTrTrUr0sz#Executable._effective_plugin_targetr\r.)optionsrfcGs |jtdd|D7_|S)aJApply 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 css|]}ttj|VqdSrg)r0expectrZExecutableOptionRole)rrrTrTrUrRsz%Executable.options..)rar9rSrprTrTrUrp4s zExecutable.optionsrV)compile_optionsrfcCs ||_|S)z|Assign the compile options to a new value. :param compile_options: appropriate CacheableOptions structure )rc)rSrsrTrTrU_set_compile_optionsXszExecutable._set_compile_optionscCs |jdk st|j|7_|S)z*update the _compile_options with new keys.N)rcrrrrTrTrU_update_compile_optionscsz"Executable._update_compile_optionszCallable[[CompileState], None]) callable_ cache_argsrfcCs|j||ff7_|S)aMAdd 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. )rb)rSrvrwrTrTrU_add_context_optionkszExecutable._add_context_option.)rf logging_tokenisolation_level no_parametersstream_resultsmax_row_buffer yield_perinsertmanyvalues_page_sizerepopulate_existing autoflushsynchronize_session dml_strategy render_nullsis_delete_usingis_update_frompreserve_rowcountrMintr5r4)rfryrzr{r|r}r~rrerrrrrrrrrrfcKsdSrgrT)rSrfryrzr{r|r}r~rrerrrrrrrrrrTrTrUrk~szExecutable.execution_options)rrfcKsdSrgrT)rSrrTrTrUrks)rrfcKs6d|krtdd|kr$td|j||_|S)aSet 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 ` 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 ` 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 rzz'isolation_level' execution option may only be specified on Connection.execution_options(), or per-engine using the isolation_level argument to create_engine().rfzm'compiled_cache' execution option may only be specified on Connection.execution_options(), not per statement.)r(rr`rrrTrTrUrksgrFcCs|jS)zGet the non-SQL options which will take effect during execution. .. versionadded:: 1.3 .. seealso:: :meth:`.Executable.execution_options` )r`rRrTrTrUget_execution_optionss z Executable.get_execution_options))rWrXrYrr_rkr)r*r`Z_is_default_generatorrarbr%Zdp_executable_optionsr#Zdp_with_context_optionsZdp_propagate_attrsZ_executable_traverse_internalsZ is_selectZis_from_statementZ is_updateZ is_insertZis_textZ is_deleteZis_dmlrrhrmrnrxrorrrrprtrurxrrkrrTrTrTrUrs       # 8urc@s>eZdZUdZded<ddddddZddddd d Zd S) SchemaEventTargetzBase class for elements that are the targets of :class:`.DDLEvents` events. This includes :class:`.SchemaItem` as well as :class:`.SchemaType`. zdispatcher[SchemaEventTarget]dispatchrr)parentrrfcKsdS)z0Associate with this SchemaEvent's parent object.NrTrSrrrTrTrU _set_parent%szSchemaEventTarget._set_parentcKs.|j|||j|f||j||dSrg)rZbefore_parent_attachrZafter_parent_attachrrTrTrU_set_parent_with_dispatch(sz+SchemaEventTarget._set_parent_with_dispatchN)rWrXrYrrkrrrTrTrTrUrs rc@seZdZdZddiZdS) SchemaVisitorz/Define the visiting for ``SchemaItem`` objects.Zschema_visitorTN)rWrXrYrZ__traverse_options__rTrTrTrUr0src@s(eZdZdZdZdZdZdZdZdZ dS) _SentinelDefaultCharacterizationnoneunknownZ clientsideZsentinel_defaultZ serversideidentitysequenceN) rWrXrYNONEUNKNOWNZ CLIENTSIDEZSENTINEL_DEFAULTZ SERVERSIDEZIDENTITYZSEQUENCErTrTrTrUr6src@s@eZdZUdZded<dZded<dZded<ejZ ded <dS) _SentinelColumnCharacterizationNzOptional[Sequence[Column[Any]]]columnsFrE is_explicit is_autoincrdefault_characterization) rWrXrYrrkrrrrrrTrTrTrUr@s    r_COLKEY_COL_coColumnElement[Any]T)r^ covariant_COLc@sJeZdZUdZded<dddddZdd Zd d Zd d dddZdS)_ColumnMetricscolumnrrzColumnCollection[Any, _COL_co]) collectioncolcCs.||_|j}|r*|jD]}|||qdSrg)r _proxy_index_expanded_proxy_setadd)rSrrpieps_colrTrTrUrTs  z_ColumnMetrics.__init__cCs|jjSrg)rrrRrTrTrUget_expanded_proxy_set`sz%_ColumnMetrics.get_expanded_proxy_setcCsL|j}|sdS|jjD]0}||d}|r4|||dk r|s||=qdSrg)rrrrdiscard)rSrrrZcolsetrTrTrUdisposecs    z_ColumnMetrics.disposez=Union[Set[ColumnElement[Any]], FrozenSet[ColumnElement[Any]]]rE) target_setrfcCs2|jj}||D]}|t|gsdSqdSr>)rrr/rr)rSrZexpanded_proxy_settrTrTrUembeddedns z_ColumnMetrics.embeddedN) rWrXrYrrkrrrrrTrTrTrUrOs   rc@seZdZUdZdZded<ded<ded<d ed <d|d d ddZedddddZ dddddZ e ddddZ ddddZ ddd d!Zd"dd#d$Zd%dd&d'Zd(dd)d*Zd+dd,d-Zed.d/d0d1d2Zed3d4d0d5d2Zed6d4d0d7d2Zd8d9d0d:d2Zd;d/d0dd?Zd@d%dAdBdCZdDd%dAdEdFZed}d;ddGdHdIdJZed;dKdLdHdMdJZd~d;dNdOdHdPdJZd;ddQdRZd;dDdSdTdUdVZd;dSd0dWdXZd;dDdSdYdZd[ZdSdd\d]ZdDdd^d_d`ZdDdSddadbZ d Z!ddddcddZ"ddedfddgdhdiZ#djddkdlZ$djddmdndoZ%ded%dpdqdrZ&d4ddsdtZ'dudvZ(ddKd%dxdydzd{Z)d S)ColumnCollectionaCollection 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 :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_colsetrz6List[Tuple[_COLKEY, _COL_co, _ColumnMetrics[_COL_co]]]rz4Dict[Union[None, str, int], Tuple[_COLKEY, _COL_co]]rz6Dict[ColumnElement[Any], Set[_ColumnMetrics[_COL_co]]]rz Set[_COL_co]rNz+Optional[Iterable[Tuple[_COLKEY, _COL_co]]])rcCsTt|dtt|dit|dttjt|dg|rP||dS)Nrrrr)rr4r collections defaultdictr) OrderedSet_initial_populate)rSrrTrTrUrs zColumnCollection.__init__zsqlalchemy.sql.elementsr8rvcCstjj}|j|jtjddS)NF)Z_literal_as_text_roler)r)rZ sql_elementsr8 _all_columnsrZColumnsClauseRolerSr2rTrTrU__clause_element__s z#ColumnCollection.__clause_element__z!Iterable[Tuple[_COLKEY, _COL_co]]riter_rfcCs||dSrg_populate_separate_keysrSrrTrTrUrsz"ColumnCollection._initial_populatez List[_COL_co]cCsdd|jDS)NcSsg|]\}}}|qSrTrTrrrrTrTrUr sz1ColumnCollection._all_columns..rrRrTrTrUr szColumnCollection._all_columnsz List[_COLKEY]cCsdd|jDS)zQReturn a sequence of string key names for all columns in this collection.cSsg|]\}}}|qSrTrT)rrrrTrTrUrsz)ColumnCollection.keys..rrRrTrTrUkeysszColumnCollection.keyscCsdd|jDS)zReturn a sequence of :class:`_sql.ColumnClause` or :class:`_schema.Column` objects for all columns in this collection.cSsg|]\}}}|qSrTrTrrTrTrUrsz+ColumnCollection.values..rrRrTrTrUrszColumnCollection.valueszList[Tuple[_COLKEY, _COL_co]]cCsdd|jDS)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. cSsg|]\}}}||fqSrTrTrrrrrTrTrUr sz*ColumnCollection.items..rrRrTrTrUr#szColumnCollection.itemsrEcCs t|jSrg)rErrRrTrTrU__bool__"szColumnCollection.__bool__rcCs t|jSrg)rrrRrTrTrUr%szColumnCollection.__len__zIterator[_COL_co]cCstdd|jDS)NcSsg|]\}}}|qSrTrTrrTrTrUr*sz-ColumnCollection.__iter__..)rrrRrTrTrUr(szColumnCollection.__iter__zUnion[str, int]rrpcCsdSrgrTrrrTrTrUr,szColumnCollection.__getitem__zTuple[Union[str, int], ...]z*ReadOnlyColumnCollection[_COLKEY, _COL_co]cCsdSrgrTrrrTrTrUr/sslicecCsdSrgrTrrrTrTrUr4sz3Union[str, int, slice, Tuple[Union[str, int], ...]]z:Union[ReadOnlyColumnCollection[_COLKEY, _COL_co], _COL_co]c szbt|ttfrPt|tr0ddj|D}nfdd|D}t|WSj|dWSWnFtk r}z(t|jdt rt |jd|nW5d}~XYnXdS)Ncss|]\}}}||fVqdSrgrT)rsub_keyrrrTrTrUr?sz/ColumnCollection.__getitem__..c3s|]}j|VqdSrgr)rrrRrTrUrDsrr) rGr9rrr as_readonlyrrrr IndexError)rSrqcolsrrTrRrUr9s rnc CsBz|j|dWStk r<}zt||W5d}~XYnXdS)Nr)rrAttributeError)rSrqrrTrTrUrsOszColumnCollection.__getattr__cCs*||jkr"t|tstddSdSdS)Nz'__contains__ requires a string argumentFT)rrGrnr(rrrrTrTrU __contains__Us  zColumnCollection.__contains__zColumnCollection[Any, Any])r1rfcCs&t||D]\}}||k r dSq dS)zdCompare this :class:`_expression.ColumnCollection` to another based on the names of the keysFTNr)rSr1lrrTrTrUcompare_szColumnCollection.comparercCs ||Srg)r)rSr1rTrTrUr@iszColumnCollection.__eq__zOptional[_COL_co])rqrerfcCsdSrgrTrSrqrerTrTrUrlszColumnCollection.getrzUnion[_COL_co, _COL]cCsdSrgrTrrTrTrUroszOptional[_COL]zOptional[Union[_COL_co, _COL]]cCs ||jkr|j|dS|SdS)zGet a :class:`_sql.ColumnClause` or :class:`_schema.Column` object based on a string key name from this :class:`_expression.ColumnCollection`.rNrrrTrTrUrrs cCs d|jjddd|DfS)NrArBcss|]}t|VqdSrg)rnrrTrTrUrsz+ColumnCollection.__str__..)rrWrDrRrTrTrU__str__~szColumnCollection.__str__rr3cCs tdSrgrrrTrTrUrszColumnCollection.__setitem__cCs tdSrgrrrrTrTrUrszColumnCollection.__delitem__)rqrrfcCs tdSrgr)rSrqrrTrTrUr4szColumnCollection.__setattr__cCs tdS)zQDictionary clear() is not implemented for :class:`_sql.ColumnCollection`.NrrRrTrTrUclearszColumnCollection.clearrrfcCs tdSrgr)rSrrTrTrUremoveszColumnCollection.removecCs tdS)zRDictionary update() is not implemented for :class:`_sql.ColumnCollection`.NrrrTrTrUrszColumnCollection.updatecsnfdd|Djdd<}jdd|Djddt|Djddt|DdS) *populate from an iterator of (key, column)cs g|]\}}||t|fqSrTrrrrrRrTrUrsz.Ncss|]\}}}|VqdSrg _deannotate)rrrrTrTrUrsz;ColumnCollection._populate_separate_keys..cSs i|]\}\}}}|||fqSrTrTridxrrrrTrTrUrs z.cSsi|]\}}}|||fqSrTrTrrTrTrUrs)rrrr enumerater)rSrrrTrRrUrs z(ColumnCollection._populate_separate_keysrzOptional[_COLKEY]rrqrfcCsz|dkr|j}n|}t|j}tt|}|j||t||f|j| ||f|j |<||j krv||f|j |<dS)aAdd 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) rqrrrrappendrrrrr)rSrrqZcolkeyr_columnrTrTrUrs   zColumnCollection.addrcCsdd|jD|jdS)NcSsg|]\}}}||fqSrTrTrrrrrTrTrUrsz1ColumnCollection.__getstate__..rrrrRrTrTrU __getstate__szColumnCollection.__getstate__)staterfcsftd|dtdttjtdfdd|dDtdddjDdS) Nrrrcs g|]\}}||t|fqSrTrrrRrTrUrsz1ColumnCollection.__setstate__..rcSsh|]\}}}|qSrTrTrrTrTrUrsz0ColumnCollection.__setstate__..)rr4rrr)rr)rSrrTrRrU __setstate__s$  zColumnCollection.__setstate__)rrfcCs*||jkr"t|trtddSdSdS)z3Checks if a column object exists in this collectionzZcontains_column cannot be used with string arguments. Use ``col_name in table.c`` instead.FTN)rrGrnr(rrSrrTrTrUcontains_columns  z ColumnCollection.contains_columncCst|S)zIReturn a "read only" form of this :class:`_sql.ColumnCollection`.)ReadOnlyColumnCollectionrRrTrTrUrszColumnCollection.as_readonlycCsD|j}|rdS|jD]*\}}}|jj}|D]}|||q*qdS)apopulate 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)rrrrr)rSrrmetricsepsrrTrTrU_init_proxy_indexsz"ColumnCollection._init_proxy_indexFzOptional[Union[_COL, _COL_co]])rrequire_embeddedrfc s|jkrSd\}}j}|js.|fdd|DD]}|rR||r@|dkr`|}q@||jj}|dkr||jj}t|t|kr|}|}q@||kr@t fdd|j D}t fdd|j D} | |kr@|}|}q@|r|jSdS)aGiven 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. )NNc3s(|] }|kr|D] }|VqqdSrgrT)rtsmm)rrTrUr@s  z8ColumnCollection.corresponding_column..Ncs$g|]}|r|jddqSweightrshares_lineager]rrscrrTrUres z9ColumnCollection.corresponding_column..cs$g|]}|r|jddqSrrrrrTrUrns ) rrrrrrrrrrZ_uncached_proxy_list) rSrrZselected_intersectionZselected_metricsrZcurrent_metricsZcurrent_intersectionZselected_col_distanceZcurrent_col_distancerT)rrrUcorresponding_columnsN$        z%ColumnCollection.corresponding_column)N)N)N)N)F)*rWrXrYrrrkrr)preload_modulerrrrrrr#rrrrrrsrrr@rrrrr4rrr__hash__rrrrrrrrrTrTrTrUr{sl l      $ r _NAMEDCOLzNamedColumn[Any]c@szeZdZdZdddddddZd ddd d d Zd ddddZdddddZdddddZdddddddZ dS)DedupeColumnCollectionauA :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 Nrz Optional[str]rrcCs|dk r|j|krtd|j}|dkr4td||jkrr|j|d}||krXdS||tj|dn |||dS)NKDedupeColumnCollection requires columns be under the same key as their .keyz-Can't add unnamed column to column collectionrr) rqr(rrreplacer)rreset_append_new_column)rSrrqexistingrTrTrUrs   zDedupeColumnCollection.addrn)rq named_columnrfcCsRt|j}|j||t||f|j|||f|j|<||f|j|<dSrg)rrrrrrrr)rSrqrrrTrTrUrs z)DedupeColumnCollection._append_new_columnzIterable[Tuple[str, _NAMEDCOL]]rcCst|}g}|D]~\}}|j|kr,td|j|jkrP|j|jkrP||q|j|jkrh||q||f|j|<|j||t||fq|j dd|jD|j ddt |jD|D]}| |qdS)rrcss|]\}}}|VqdSrgrrrTrTrUrszADedupeColumnCollection._populate_separate_keys..css$|]\}\}}}|||ffVqdSrgrTrrTrTrUrs N) listrqr(rrQrrrrrrrr)rSrrZ replace_colrrrTrTrUrs&      z.DedupeColumnCollection._populate_separate_keyszIterable[_NAMEDCOL]cCs|dd|DdS)Ncss|]}|j|fVqdSrg)rq)rrrTrTrUrsz0DedupeColumnCollection.extend..rrrTrTrUextendszDedupeColumnCollection.extendrcs|jkrtd|jj=|jfdd|jD|jdd<|jdD]}||qX|j ddt |jD|jt |j=dS)Nz8Can't remove column %r; column is not in this collectioncs$g|]\}}}|k r|||fqSrTrT)rrrrrrTrUrsz1DedupeColumnCollection.remove..rTcSs i|]\}\}}}|||fqSrTrTrrrrrrTrTrUrs z1DedupeColumnCollection.remove..) rrrrqrrrrrrrr)rSrrrTrrUrs"     zDedupeColumnCollection.removezOptional[Iterable[_NAMEDCOL]])r extra_removerfc Cs|rt|}nt}|j|jkrR|j|jkrR|j|jd}|j|jkrR|||j|jkrt||j|jd|s||j|dSg}d}|jD]D\}}} ||kr|sd}||j|t||fq|||| fq|r|j ||D]$} |j | dD]} | |qq|s8||j|t||f|j |||jdd<|j|jddt|jD|jdd|jDdS) aadd 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. rNFTrTcSs i|]\}\}}}|||fqSrTrTrrTrTrUr*s z2DedupeColumnCollection.replace..cSsi|]\}}}|||fqSrTrTrrTrTrUr,s)rrQrrqrrrrrrdifference_updaterrrrrrr) rSrrZ remove_colr1Znew_colsZreplacedrrrrcrTrTrUrsH      zDedupeColumnCollection.replace)N)N) rWrXrYrrrrrrrrTrTrTrUrs  rc@s\eZdZdZddZddZddZdd d d d d d Zd d dddZd d dddZ dS)r_parentcCsRt|d|t|d|jt|d|jt|d|jt|d|jdS)Nrrrrr)rr4rrrr)rSrrTrTrUr4s z!ReadOnlyColumnCollection.__init__cCs d|jiSNrrrRrTrTrUr;sz%ReadOnlyColumnCollection.__getstate__cCs|d}||dSr )r)rSrrrTrTrUr>sz%ReadOnlyColumnCollection.__setstate__.rrcCs |dSrgZ _readonly)rSrrqrTrTrUrBszReadOnlyColumnCollection.addrrcCs |dSrgr rrTrTrUrEszReadOnlyColumnCollection.extend)itemrfcCs |dSrgr )rSr rTrTrUrHszReadOnlyColumnCollection.removeN).) rWrXrYrrrrrrrrTrTrTrUr/src@s,eZdZddZddZddZddZd S) ColumnSetcCs||kSrgrTrrTrTrUrMszColumnSet.contains_columncCs|D]}||qdSrg)r)rSrrrTrTrUrPszColumnSet.extendcCs:g}|D]&}|D]}||r|||kqqtj|Srg)rrr2and_)rSr1rrrPrTrTrUr@Ts  zColumnSet.__eq__cCsttdd|DS)Ncss|] }|VqdSrgrTrrTrTrUr]sz%ColumnSet.__hash__..)hashr9rRrTrTrUr\szColumnSet.__hash__N)rWrXrYrrr@rrTrTrTrUr Lsr zColumnClause[Any]z1Union[_HasEntityNamespace, ExternallyTraversible])entityrfcCsVztt|jWStk rPttt|D]}t|r.|jYSq.YnXdS)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. N)rrurwrrZiterater$r{)rrrTrTrU_entity_namespace`s rz%Union[SQLCoreOperations[Any], _NoArg]ro)rrqrerfc Csjz.t|}|tk r t|||WSt||WSWn6tk rd}ztd||f|W5d}~XYnXdS)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)rrZr?rr(r)rrqrensrrTrTrU_entity_namespace_keyss  r)r __future__rrenumrrrrrr,rrrr r r r r rrrrrrrrrrrrrrrr cache_keyrr Z traversalsr!r"r#r$r%r'r(r)r*r+Z compat_typingZ util.typingr-r.r/r0r2r3Z _orm_typesr4r5Z_typingr6r7r8r9r:r;r<r=Zschemar>r?Z selectabler@rArBZenginerCrDZengine.interfacesrErFrGrHrIrJrKrLrMrNrOrPrZr[r\Z _NONE_NAMEr]r_rnZ_AmbiguousTableNameMapr`rZ_never_select_columnrmrur{r|r}rrrrrrrrrrrrrrrrrrrr%r&typer+r6rVr\Z StatementRolerZ EventTargetrrrrrrrrrrrZReadOnlyContainerrrr rrrTrTrTrU s.                                                                                    9  +j !#2   , 0