U kf^; @s8ddlmZddlZddlZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z ddlm Z dd lm Z dd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddl"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,dd&l"m-Z-dd'l"m.Z.dd(l"m/Z/dd)l"m0Z0dd*l"m1Z1dd+l"m2Z2dd,l"m3Z3dd-l"m4Z4dd.l5m6Z6dd/l5m7Z7dd0l5m8Z8dd1l5m9Z9dd2l5m:Z:dd3l;md4d6lm?Z?d4d7lm@Z@d4d8lmAZAd4d9lBmCZCd4d:l@mDZDd4d;l@mEZEd4dl@mIZId4d?lJmKZKd4d@lLmMZMd4dAlNmOZOd4dBlPmQZQd4dClPmRZRd4dDlSmTZTd4dElSmUZUd4dFlVmWZWd4dGlXmYZYd4dHlZm[Z\d4dIlZm]Z^d4dJlZm_Z`d4dKlZmaZad4dLlZmbZbd4dMlZmcZcd4dNlZmdZdejrddOlmeZeddPlmfZfddQlmgZgddRlmhZhddSlimjZjddTlimkZkddUllmmZmddVl;mnZnddWlompZpddXlqmrZrd4dYlsmtZtd4dZlsmuZud4d[lJmvZvd4d\lJmwZwd4d]lJmxZxd4d^lJmyZyd4d_lJmzZzd4d`lJm{Z{d4dalLm|Z|d4dblNm}Z}d4dclSm~Z~d4ddlVmZd4delVmZd4dflVmZd4dglmZd4dhlZmZd4dilZmZedjedkZedlZejejeAe,e4e)dmdnZGdodpdpecZe eee\Z[GdqdrdrecZe eee^Z]GdsdtdtecZe eee`Z_Gdudvdve eZdwdxZdd{d|Zddddd}d~ddddddddZGdddejZGdddeHjZGdddeHjZGddde?jde8eZe?jGddde9ee:eQe*eYe?jde e ZGdddZGddde6Ze?edde?edddddZeeeZe?edddddZe?jGddde8eeMeRe?jde*ZdddddddZdddddZdddddZGdddeEjZddddddddZdddddZdddddZddddddZddddddZddddddÄZddddƜddȄZddddd˜dd̈́ZGddτdeZddddќddӄZddddddddddddל ddلZdddڜdd܄ZdS)) annotationsN) AbstractSet)Any)Callable)cast)Dict) FrozenSet)Generic)Iterable)Iterator)List)Match)Optional)Sequence)Tuple)Type) TYPE_CHECKING)TypeVar)Union) attributes)exc)_O)insp_is_aliased_class)insp_is_mapper)prop_is_relationship)_class_to_mapper)_MappedAnnotationBase) _never_set) _none_set) attribute_str) class_mapper) DynamicMapped)InspectionAttr) instance_str)Mapped) object_mapper) object_state)opt_manager_of_class) ORMDescriptor)state_attribute_str)state_class_str) state_str)WriteOnlyMapped)CriteriaOption)MapperProperty)ORMColumnsClauseRole)ORMEntityColumnsClauseRole)ORMFromClauseRole) PathRegistry)event) inspection)sql)util result_tuple) coercions) expression)lambdas)roles)visitors) is_selectable)SupportsCloneAnnotations)ColumnCollection) HasCacheKey)MemoizedHasCacheKey) ColumnElement)KeyedColumnElement) FromClause) MemoizedSlots)de_stringify_annotation)de_stringify_union_elements)eval_name_only)is_origin_of_cls)Literal)Protocol)typing_get_origin) _EntityType)_IdentityKeyType)_InternalEntityType) _ORMCOLEXPR) _MapperEntity)ORMCompileState)Mapper)AbstractEntityRegistry)Query)RelationshipProperty)Row) RowMapping)_CE)_ColumnExpressionArgument)_EquivalentColumnMap)_FromClauseArgument)_OnClauseArgument)_PropagateAttrsType)_SA)ReadOnlyColumnCollection) BindParameter)_ColumnsClauseElement)Select) Selectable)anon_map)_AnnotationScanType)ArgsTypeProcotol_T)bound)delete delete-orphanallmergeexpunge save-updaterefresh-expirenone)r%r-r")Zlocals_c@s,eZdZdddddddddd d d ZdS) _DeStringifyAnnotationNF)str_cleanup_fninclude_generic Type[Any]ristr#Optional[Callable[[str, str], str]]bool)cls annotationoriginating_modulervrwreturncCsdSN)selfr|r}r~rvrwrrC/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/orm/util.py__call__sz_DeStringifyAnnotation.__call____name__ __module__ __qualname__rrrrrrusruc@s(eZdZdddddddddd ZdS) _DeStringifyUnionElementsNrvrxrjryrz)r|r}r~rvrcCsdSrr)rr|r}r~rvrrrrsz"_DeStringifyUnionElements.__call__rrrrrrsrc@seZdZddddddZdS) _EvalNameOnlyryr)name module_namercCsdSrr)rrrrrrrz_EvalNameOnly.__call__NrrrrrrsrcseZdZUdZedddgZeZdddddgZdZ d e d <d e d <d e d <d e d<d e d<d e d <dddfdd Z ddZ e ddZZS)CascadeOptionszHKeeps track of the options sent to :paramref:`.relationship.cascade`rortrnrqrsrp) save_updatermrefresh_expirerprq delete_orphanr{rrmrrz#Optional[Union[Iterable[str], str]]) value_listrc st|ts|dkr||St|}||jrZtddddt ||jDd|krn| |j d|kr~| | dt||}d|k|_d|k|_d |k|_d |k|_d |k|_d |k|_|jr|jstd |S)NzInvalid cascade option(s): %s, cSsg|] }t|qSr)repr.0xrrr sz*CascadeOptions.__new__..rortrrrmrsrprqrnz5The 'delete-orphan' cascade option requires 'delete'.) isinstancery from_stringset difference_allowed_cascadessa_exc ArgumentErrorjoinsortedupdate_add_w_all_cascadescleardiscardsuper__new__rrmrrprqrr8warn)r|rvaluesr __class__rrrs<              zCascadeOptions.__new__cCsddddt|DS)NzCascadeOptions(%r),cSsg|]}|qSrrrrrrrsz+CascadeOptions.__repr__..)rrrrrr__repr__szCascadeOptions.__repr__cCs"ddtd|pdD}||S)NcSsg|] }|r|qSrr)rcrrrr sz.CascadeOptions.from_string..z\s*,\s*)resplit)r|argrrrrr szCascadeOptions.from_string)rrr__doc__ all_cascadesrrrZ_viewonly_cascades __slots____annotations__rr classmethodr __classcell__rrrrrs"  %rc ssfdd|r^fdd}fdd}fdd}fd d }n6fd d}fd d}fd d}tj|d|dddtj|d|ddtj|d|ddd|rtj|d|ddddS)zNRuns a validation method on an attribute value to be set or appended. cs|jj}|j|k Sr)managerimpl)state initiatorr)keyrrdetect_is_backrefs z,_validator_events..detect_is_backrefcs4|jtjk r,s||s,||dS|SdSNFoprZOP_BULK_REPLACEobjrvaluerrinclude_backrefsr validatorrrappends z!_validator_events..appendcs8s||s4|fdd|D|dd<dS)Ncsg|]}|dqS)Frrrrrrrrr's7_validator_events..bulk_set..rrrrrrrbulk_set$s z#_validator_events..bulk_setcs(s||s ||dS|SdSrrrrZoldvaluerrrrset_+sz_validator_events..set_cs$s||s ||ddS)NTrrrrrremove1sz!_validator_events..removecs2|jtjk r*s||s*||S|SdSrrrrrrr7s cs8s||s4|fdd|D|dd<dS)Ncsg|]}|qSrrrrrrrBsrrrrrrr?scs&s||s||S|SdSrrrrrrrDsrT)rawretvalZ bulk_replace)rrrN)r5listen) descrrZinclude_removesrrrrrrrr_validator_eventss rp_unionTc s6t}ii|D]|}||tjtjdd||<i}jD]B}|j|krdt d||f| |j|||j<|j |j<qD|<qfddg}| D]v\} |dk r| tjfdd|Dtt| |gq| tjfd d|Dqtj||S) a0Create a ``UNION`` statement used by a polymorphic mapper. See :ref:`concrete_inheritance` for an example of how this is used. :param table_map: mapping of polymorphic identities to :class:`_schema.Table` objects. :param typecolname: string name of a "discriminator" column, which will be derived from the query, producing the polymorphic identity for each row. If ``None``, no polymorphic discriminator is generated. :param aliasname: name of the :func:`~sqlalchemy.sql.expression.alias()` construct generated. :param cast_nulls: if True, non-existent columns, which are represented as labeled NULLs, will be passed into CAST. This is a legacy behavior that is problematic on some backends such as Oracle - in which case it can be set to False. T)Z allow_selectzPolymorphic union can't use '%s' as the discriminator column due to mapped column %r; please apply the 'typecolname' argument; this is available on ConcreteBase as '_concrete_discriminator_name'cshz||WStk rbr@tt||YStt||YSYnXdSr)KeyErrorr7rnulllabelZ type_coerce)rtable) cast_nulls colnamemapstypesrrcols zpolymorphic_union..colNcsg|]}|qSrrrrrrrrrsz%polymorphic_union..csg|]}|qSrrrrrrrs)r8Z OrderedSetr;expectr>ZStrictFromClauseRolerrrZInvalidRequestErroraddtypeitemsrr7selectZliteral_columnsql_utilZ_quote_ddl_exprr select_fromZ union_allalias) Z table_mapZ typecolnameZ aliasnamerZcolnamesrmrresulttype_r)rrrrrrpolymorphic_unionQsb        r)instancerowidentity_tokenzOptional[Type[_T]]zUnion[Any, Tuple[Any, ...]]z Optional[_T]z%Optional[Union[Row[Any], RowMapping]] Optional[Any]z_IdentityKeyType[_T])class_identrrrrcCsz|dk rRt|}|dkrB|dkr*td|jtt||dS|j||dSn$|dk rlt|}| |StddS)aQGenerate "identity key" tuples, as are used as keys in the :attr:`.Session.identity_map` dictionary. This function has several call styles: * ``identity_key(class, ident, identity_token=token)`` This form receives a mapped class and a primary key scalar or tuple as an argument. E.g.:: >>> identity_key(MyClass, (1, 2)) (, (1, 2), None) :param class: mapped class (must be a positional argument) :param ident: primary key, may be a scalar or tuple argument. :param identity_token: optional identity token .. versionadded:: 1.2 added identity_token * ``identity_key(instance=instance)`` This form will produce the identity key for a given instance. The instance need not be persistent, only that its primary key attributes are populated (else the key will contain ``None`` for those missing values). E.g.:: >>> instance = MyClass(1, 2) >>> identity_key(instance=instance) (, (1, 2), None) In this form, the given instance is ultimately run though :meth:`_orm.Mapper.identity_key_from_instance`, which will have the effect of performing a database check for the corresponding row if the object is expired. :param instance: object instance (must be given as a keyword arg) * ``identity_key(class, row=row, identity_token=token)`` This form is similar to the class/tuple form, except is passed a database result row as a :class:`.Row` or :class:`.RowMapping` object. E.g.:: >>> row = engine.execute(\ text("select * from table where a=1 and b=2")\ ).first() >>> identity_key(MyClass, row=row) (, (1, 2), None) :param class: mapped class (must be a positional argument) :param row: :class:`.Row` row returned by a :class:`_engine.CursorResult` (must be given as a keyword arg) :param identity_token: optional identity token .. versionadded:: 1.2 added identity_token Nzident or row is required)rzclass or instance is required) r!rrZidentity_key_from_primary_keytupler8Zto_listZidentity_key_from_rowr&Zidentity_key_from_instance)rrrrrmapperrrr identity_keys"G   rc@sheZdZdZeZeZeZeZ eZ eZ eZ eZ eZeZeZdS)_TraceAdaptRoleaEnumeration of all the use cases for ORMAdapter. ORMAdapter remains one of the most complicated aspects of the ORM, as it is used for in-place adaption of column expressions to be applied to a SELECT, replacing :class:`.Table` and other objects that are mapped to classes with aliases of those tables in the case of joined eager loading, or in the case of polymorphic loading as used with concrete mappings or other custom "with polymorphic" parameters, with whole user-defined subqueries. The enumerations provide an overview of all the use cases used by ORMAdapter, a layer of formality as to the introduction of new ORMAdapter use cases (of which none are anticipated), as well as a means to trace the origins of a particular ORMAdapter within runtime debugging. SQLAlchemy 2.0 has greatly scaled back ORM features which relied heavily on open-ended statement adaption, including the ``Query.with_polymorphic()`` method and the ``Query.select_from_entity()`` methods, favoring user-explicit aliasing schemes using the ``aliased()`` and ``with_polymorphic()`` standalone constructs; these still use adaption, however the adaption is applied in a narrower scope. N)rrrrenumauto ALIASED_INSPZJOINEDLOAD_USER_DEFINED_ALIASZ JOINEDLOAD_PATH_WITH_POLYMORPHICZJOINEDLOAD_MEMOIZED_ADAPTERZMAPPER_POLYMORPHIC_ADAPTERZWITH_POLYMORPHIC_ADAPTERZ#WITH_POLYMORPHIC_ADAPTER_RIGHT_JOINZ DEPRECATED_JOIN_ADAPT_RIGHT_SIDEZADAPT_FROM_STATEMENTZCOMPOUND_EAGER_STATEMENTZLEGACY_SELECT_FROM_ALIASrrrrrsrc sHeZdZdZdZdddddddddd d d d d d d fd dZZS)ORMStatementAdapterz.ColumnAdapter which includes a role attribute.)roleNFT equivalentsadapt_requiredallow_label_resolveanonymize_labelsadapt_on_namesadapt_from_selectablesrrgOptional[_EquivalentColumnMap]r{!Optional[AbstractSet[FromClause]])r selectablerrrrrrc s$||_tj|||||||ddS)Nr)rr__init__) rrrrrrrrrrrrr >s zORMStatementAdapter.__init__)rrrrrr rrrrrr9src sjeZdZUdZdZded<ded<ddd ddd ddd d d d dddddddd fddZddZZS) ORMAdapterzaColumnAdapter subclass which excludes adaptation of entities from non-matching mappers. )rris_aliased_class aliased_inspr{r Optional[AliasedInsp[Any]]r NFT)rrrrrlimit_on_entityrrr_InternalEntityType[Any]rzOptional[Selectable]r) rentityrrrrrrrrc sh||_|j|_|dkr|j}t|r2d|_||_n d|_d|_tj||||||rX|jnd| | ddS)NTF)rrrZ include_fnrr) rrrrr r rr  _include_fn) rrrrrrrrrrrrrrr as& zORMAdapter.__init__cCs,|jdd}| p*||jp*|j|S)N parentmapper) _annotationsgetisar)relemrrrrrszORMAdapter._include_fn) rrrrrrr rrrrrrr Vs ($r c @seZdZUdZded<d"dddd d d d d d d d ddZedddddZdddddZdddddddZ ddddZ ddd d!Z dS)# AliasedClassaRepresents an "aliased" form of a mapped class for usage with Query. The ORM equivalent of a :func:`~sqlalchemy.sql.expression.alias` construct, this object mimics the mapped class using a ``__getattr__`` scheme and maintains a reference to a real :class:`~sqlalchemy.sql.expression.Alias` object. A primary purpose of :class:`.AliasedClass` is to serve as an alternate within a SQL statement generated by the ORM, such that an existing mapped entity can be used in multiple contexts. A simple example:: # find all pairs of users with the same name user_alias = aliased(User) session.query(User, user_alias).\ join((user_alias, User.id > user_alias.id)).\ filter(User.name == user_alias.name) :class:`.AliasedClass` is also capable of mapping an existing mapped class to an entirely new selectable, provided this selectable is column- compatible with the existing mapped selectable, and it can also be configured in a mapping as the target of a :func:`_orm.relationship`. See the links below for examples. The :class:`.AliasedClass` object is constructed typically using the :func:`_orm.aliased` function. It also is produced with additional configuration when using the :func:`_orm.with_polymorphic` function. The resulting object is an instance of :class:`.AliasedClass`. This object implements an attribute scheme which produces the same attribute and method interface as the original mapped class, allowing :class:`.AliasedClass` to be compatible with any attribute technique which works on the original class, including hybrid attributes (see :ref:`hybrids_toplevel`). The :class:`.AliasedClass` can be inspected for its underlying :class:`_orm.Mapper`, aliased selectable, and other information using :func:`_sa.inspect`:: from sqlalchemy import inspect my_alias = aliased(MyClass) insp = inspect(my_alias) The resulting inspection object is an instance of :class:`.AliasedInsp`. .. seealso:: :func:`.aliased` :func:`.with_polymorphic` :ref:`relationship_aliased_class` :ref:`relationship_to_window_function` ryrNFz_EntityType[_O]Optional[FromClause] Optional[str]r{Optional[Sequence[Mapper[Any]]]Optional[ColumnElement[Any]]r ) mapped_class_or_acrrflatrwith_polymorphic_mapperswith_polymorphic_discriminator base_aliasuse_mapper_pathrepresents_outer_joinc  Cstdt|} | j} d} |dkrN| jr<| jjr<| j}qX| jj ||d}n | jrXd} |dk sdt t || |||rv|n| j |dk r|n| j || || | |_d| jjd|_dS)N_InternalEntityType[_O]FrrTaliased())rr6inspectrr rZ _is_subqueryrZ_with_polymorphic_selectable_anonymous_fromclauseAssertionError AliasedInsprpolymorphic_on _aliased_insprr)rrrrrrrrr r!r"Zinspr nest_adaptersrrrr sF   zAliasedClass.__init__AliasedInsp[_O]AliasedClass[_O])r rcCs\||}d|jjjd|_||_|jrX|jD]&}||k r0t|}t ||jj|q0|S)Nr%r&) rrrrr,_is_with_polymorphic_with_polymorphic_entitiesr_reconstitute_from_aliased_inspsetattr)r|r rZsub_aliased_inspentrrrr2s  z,AliasedClass._reconstitute_from_aliased_inspr)rrcCsz|jd}Wntk r(tYnX|j}t||}t|dr\t|dr\t|j|St|drr| d|}t|dr| |}t ||||S)Nr,r__self____get__adapt_to_entity) __dict__rAttributeError_targetgetattrhasattrr MethodType__func__r6r7r3)rrr,targetattrrrr __getattr__s       zAliasedClass.__getattr__r)r mapped_classr rcCsrt||}t|dr,t|dr,t|j|St|drB|d|}t|drnt||_| |}t ||||S)Nrr5r6r7) r;r<rr=r>r6weakrefref _weak_entityr7r3)rrrBr r@rrr_get_from_serialized3s       z!AliasedClass._get_from_serializedrcCsdt||jjjfS)Nz)idr,r:rrrrrrJszAliasedClass.__repr__cCs t|jSr)ryr,rrrr__str__PszAliasedClass.__str__) NNFFNNNFF) rrrrrr rr2rArFrrIrrrrrs$ :":rr.c@seZdZUdZdZdejjfdejjfdejjfdejj fdejj fdej j fd ej j fgZ d ed <d ed<d ed<ded<ded<ded<ded<ddd ddddddddd ddZed\d!d"dddd#d$d%d&Zed]d'd(d)ddddddddd* d+d,Zedd-d.d/Zd0Zd d-d1d2Zedd-d3d4Zed5d-d6d7Zed8d-d9d:Zd;d-dd?d@dAZdBdBdCdDdEZd^dFddFdGdHdIZerd_dJddJdKdLdMZneZdNdOZ dPdQZ!dRdSZ"dTdUZ#dVdWZ$dXdYZ%dZd[Z&dS)`r*aProvide an inspection interface for an :class:`.AliasedClass` object. The :class:`.AliasedInsp` object is returned given an :class:`.AliasedClass` using the :func:`_sa.inspect` function:: from sqlalchemy import inspect from sqlalchemy.orm import aliased my_alias = aliased(MyMappedClass) insp = inspect(my_alias) Attributes on :class:`.AliasedInsp` include: * ``entity`` - the :class:`.AliasedClass` represented. * ``mapper`` - the :class:`_orm.Mapper` mapping the underlying class. * ``selectable`` - the :class:`_expression.Alias` construct which ultimately represents an aliased :class:`_schema.Table` or :class:`_expression.Select` construct. * ``name`` - the name of the alias. Also is used as the attribute name when returned in a result tuple from :class:`_query.Query`. * ``with_polymorphic_mappers`` - collection of :class:`_orm.Mapper` objects indicating all those mappers expressed in the select construct for the :class:`.AliasedClass`. * ``polymorphic_on`` - an alternate column or SQL expression which will be used as the "discriminator" for a polymorphic load. .. seealso:: :ref:`inspection_toplevel` ) __weakref__rErrr_adapt_on_namesrr+_use_mapper_path _base_aliasr"persist_selectable local_tabler0r1_adapterr:__clause_element___memoized_valuesZ_all_column_expressions_nest_adaptersrrKrLr:rrr+z Mapper[_O]rrGr rPzSequence[Mapper[Any]]zSequence[AliasedInsp[Any]]r1zweakref.ref[AliasedClass[_O]]rEz!Union[Type[_O], AliasedClass[_O]]r/r#rrrr r{) r inspectedrrrr+rMrLrr"r-c  s0|j} |j} t||_| |_||_|_|_||_||_ t|pF||_ ||_ | |_ | |_ |rd|_||_g|_|jD]@}|| k rzt|j|||d}t|j|jj||j|jqznd|_| g|_ttj| || jdfdd|jDdd|_| r t|tst|j|j|_|_ | |_!dS)NT)r rr!Fcsh|]}s|jqSr)r)rrrrr sz'AliasedInsp.__init__..)rrrrrr)"rrrCrDrErrNrOrr+rMrLr"rSr0rr1rrr3rrr,r rrZ_equivalent_columnsrPrr*r)wraprKr:)rrrTrrrr+rMrLrr"r-rrZpolyr4rrUrr s\   zAliasedInsp.__init__NFz"Union[_EntityType[_O], FromClause]rz#Union[AliasedClass[_O], FromClause])elementrrrrrcCsTt|tr>|rtd|r*|j||dStjtj||dSnt |||||dSdS)Nz+adapt_on_names only applies to ORM elementsr$r)rrrr) rrGrrrr;rr>ZAnonymizedFromClauseRoler)r|rXrrrrrrr_alias_factorys& zAliasedInsp._alias_factoryzUnion[Type[_O], Mapper[_O]]z/Union[Literal['*'], Iterable[_EntityType[Any]]]z)Union[Literal[(False, None)], FromClause]) baseclassesrrr+aliased innerjoinrrrLrc Cslt|} |dkr|rtd| j|||d\} }|s:|rR|dk sFt|j|d}t||| | ||| | dS)Nrz[the 'flat' and 'selectable' arguments cannot be passed simultaneously to with_polymorphic()r^rY)rrrrr!r")rrr_with_polymorphic_argsr)r(r) r|r[r\rrr+r]r^rrrLprimary_mappermappersrrr_with_polymorphic_factory#s.    z%AliasedInsp._with_polymorphic_factoryrGcCs*|}|dkr&t|}t||_|Sr)rErr2rCrD)rr4rrrrKs   zAliasedInsp.entityTcCs"|j|j||dd|dS)N)r parententityentity_namespaceormZcompile_state_pluginplugin_subject)r _annotater_set_propagate_attrsrrrr#_memoized_method___clause_element__\sz/AliasedInsp._memoized_method___clause_element__cCs|jSr)rrrrrregszAliasedInsp.entity_namespaceType[_O]cCs|jjS)zUReturn the mapped class ultimately represented by this :class:`.AliasedInsp`.)rrrrrrrkszAliasedInsp.class_rWcCs|jr|jjSt|SdSr)rLr_path_registryr3Z per_mapperrrrrrmqszAliasedInsp._path_registryzDict[str, Any]c Cs4|j|j|j|j|j|j|j||j|j |j d S)N) rrrrrrrr r!r"r-) rrrrrKrr+rMrLr"rSrrrr __getstate__xszAliasedInsp.__getstate__None)rrcCsN||d|d|d|d|d|d|d|d|d |d |d  dS) Nrrrrrrr r!rr"r-)r )rrrrr __setstate__szAliasedInsp.__setstate__r.)otherrcCs|j}|j|ksttdd|jD}dd|jD}||krF|S||}|j|d|j d\}}|jdd}t ||||j |j |jdj S) Ncss|] }|jVqdSrrrmprrr sz*AliasedInsp._merge_with..cSsh|] }|jqSrrrrsrrrrVsz*AliasedInsp._merge_with..r_TrY)rrr!r") rr)r8Zto_setrunionr`r"r(rr+rLr,)rrqraZ our_classesZ new_classesr\rbrrrr _merge_withs.    zAliasedInsp._merge_withrS)exprrrcCsDt|tst||jd}|r&||d<|j||d|dS)N)rdr proxy_keyrfrg)rrEr)rrPtraverserirj)rrxrdrrr_adapt_elements zAliasedInsp._adapt_elementr\)rrrcCsdSrr)rrrrrr_orm_adapt_elementszAliasedInsp._orm_adapt_elementcCsX|j}||kr0||jkr|St|j|jjjSn$||jr@|SdsTtd||fdS)NFz"mapper %s doesn't correspond to %s) rrr;rrrr,rr))rrZ self_polyrrr_entity_for_mappers  zAliasedInsp._entity_for_mappercs.jj\}}j|fdd|DfS)Ncsi|]\}}j||qSr)rPrz)rrparamrrr s z:AliasedInsp._memoized_attr__get_clause..)rZ _get_clauserPrzr)ronclauseZ replacemaprrr_memoized_attr__get_clauses    z&AliasedInsp._memoized_attr__get_clausecCsiSrrrrrr_memoized_attr__memoized_valuessz+AliasedInsp._memoized_attr__memoized_valuescsDjr jddjD}n j}fdd|D}t|S)NcSsg|] }|jqSr)r)rr4rrrrszFAliasedInsp._memoized_attr__all_column_expressions..csg|]\}}||fqSr)r|)rrrrrrrs)r0rZ_columns_plus_keysr1rB)rZcols_plus_keysrrr&_memoized_attr__all_column_expressionss  z2AliasedInsp._memoized_attr__all_column_expressionscOs0||jkr|j|S||||j|<}|SdSr)rR)rrZ callable_argskwrrrr_memos  zAliasedInsp._memocCs<|jr"dddd|jD}nd}dt||jj|fS)Nz(%s)rcss|]}|jjVqdSr)rrrsrrrrusz'AliasedInsp.__repr__..rz)rrrHrr)rZ with_polyrrrrs  zAliasedInsp.__repr__cs>jr,djjdfddjDfSdjjfSdS)Nzwith_polymorphic(%s, [%s])rc3s |]}|jk r|jjVqdSr)rrrrsrrrrus z&AliasedInsp.__str__..z aliased(%s))r0r:rrrrrrrrIs zAliasedInsp.__str__)NNFF)FFNFFFNF)N)N)'rrrrrr?ExtendedInternalTraversalZ dp_string dp_booleanZdp_inspectabledp_clauseelementInternalTraversalZdp_has_cache_key_listZ_cache_key_traversalrr rrZrcpropertyrr rkrerrmrnrprwr|rr}r~rrrrrrIrrrrr*Ts| &       "L&'    r*c@s.eZdZdZdZddZedddZdS) _WrapUserEntityaA wrapper used within the loader_criteria lambda caller so that we can bypass declared_attr descriptors on unmapped mixins, which normally emit a warning for such use. might also be useful for other per-lambda instrumentations should the need arise. subjectcCs ||_dSrr)rrrrrr -sz_WrapUserEntity.__init__zsqlalchemy.orm.decl_apicCsPtjjj}t|d}||jkrBt|j||jrB|j| |St ||SdS)Nr) r8Z preloadedrfdecl_apiobject__getattribute__r8rZ declared_attrfgetr;)rrrrrrrr0s   z _WrapUserEntity.__getattribute__N) rrrrrr r8Zpreload_modulerrrrrr!s  rc@seZdZUdZdZdejjfdejjfdej j fdej j fdej j fgZ de d<d e d<d e d<d e d <d e d<d e d<d e d<d3ddd d d d dddZeddZddZddddZdd dd d!Zd"d#d$d%d&Zdd'd(d)d*d+Zdd(dd,d-Zd.d(d/d0d1Zd2S)4LoaderCriteriaOptiona Add additional WHERE criteria to the load for all occurrences of a particular entity. :class:`_orm.LoaderCriteriaOption` is invoked using the :func:`_orm.with_loader_criteria` function; see that function for details. .. versionadded:: 1.4 ) root_entityrdeferred_where_criteriawhere_criteria_where_crit_originclude_aliasespropagate_to_loadersrrrrrzOptional[Type[Any]]"Optional[_InternalEntityType[Any]]z9Union[ColumnElement[bool], lambdas.DeferredLambdaElement]r{rrrFTz_EntityType[Any]zXUnion[_ColumnExpressionArgument[bool], Callable[[Any], _ColumnExpressionArgument[bool]]])entity_or_baser loader_onlyrrtrack_closure_variablesc Cstdt|d}|dkr.td||_d|_n d|_||_||_t|r|jdk rZ|j}n|dk sft|j}d|_t j |t j t |ft j|dd|_nd|_tt j ||_||_||_dS)NrFrxT)r)Z lambda_argsopts)rr6r'rrrcallabler)rr=ZDeferredLambdaElementr>ZWhereHavingRolerZ LambdaOptionsrr;rrr) rrrrrrrrZ wrap_entityrrrr ds>      zLoaderCriteriaOption.__init__cCst||||dS)N)rr)r)r|rrrrrrr _unreduces zLoaderCriteriaOption._unreducecCs(tj|jr|jjn|j|j|j|jffSr)rrrrrrrrrrrr __reduce__szLoaderCriteriaOption.__reduce__zIterator[Mapper[Any]]rGccsz|jr|jjjEdHn^|js"tt|j}|rv|d}tdt j |dd}|rf|jjEdHq0| |q0dS)NrrF)raiseerr) rrZself_and_descendantsrr)list__subclasses__poprr6r'extend)rstacksubclassr4rrr _all_mapperss   z!LoaderCriteriaOption._all_mappersrU) compile_statercCs|jjdd|krdSdS)Nfor_loader_criteriaFT)Zselect_statementrrrrrrr_should_includesz$LoaderCriteriaOption._should_includerColumnElement[bool])ext_inforcCsF|jrtd|j|j}n|j}t|ts0ttj |d|idddS)NrrT)Zdetect_subquery_colsZind_cols_on_fromclause) rrrZ_resolve_with_argsrrrEr)r_deep_annotate)rrcritrrr_resolve_where_criterias z,LoaderCriteriaOption._resolve_where_criteriazIterable[_MapperEntity]ro)rmapper_entitiesrcCs||dSr)process_compile_state)rrrrrr'process_compile_state_replaced_entitiesszrrrlzOptional[Mapper[_O]])rrcCsHz&t|}|dks|jsWdS|j}Wntjk r>YdSX|SdSr)r(Z is_mappedrrZNO_STATE)rZ class_managerrrrr _inspect_mcs rcCstdt|}t|S)Nrl)rrOr)roriginrrr_inspect_generic_aliassrc@seZdZUdZdZdZdZdZdZe Z de d<e j Zde d<dd d d d d ZddddddZeddddZeddddZeddddZde d<de d<d d!Zd"d#Zed$d%Zd&d'Zd(d)d*d+d,d-d.Zd/S)0Bundlea+A grouping of SQL expressions that are returned by a :class:`.Query` under one namespace. The :class:`.Bundle` essentially allows nesting of the tuple-based results returned by a column-oriented :class:`_query.Query` object. It also is extensible via simple subclassing, where the primary capability to override is that of how the set of expressions should be returned, allowing post-processing as well as custom return types, without involving ORM identity-mapped classes. .. seealso:: :ref:`bundles` FTra_propagate_attrszList[_ColumnsClauseElement]exprsryz_ColumnExpressionArgument[Any]r)rrrcs`|__fdd|D}|_tdddd|DD__|dj_dS)aQConstruct a new :class:`.Bundle`. e.g.:: bn = Bundle("mybundle", MyClass.x, MyClass.y) for row in session.query(bn).filter( bn.c.x == 5).filter(bn.c.y == 4): print(row.mybundle.x, row.mybundle.y) :param name: name of the bundle. :param \*exprs: columns or SQL expressions comprising the bundle. :param single_entity=False: if True, rows for this :class:`.Bundle` can be returned as a "single entity" outside of any enclosing tuple in the same manner as a mapped entity. csg|]}tjtj|dqS))Zapply_propagate_attrs)r;rr>ColumnsClauseRolerrxrrrrNs z#Bundle.__init__..css |]}t|d|j|fVqdS)rN)r;_label)rrrrrruVsz"Bundle.__init__..cSsg|]}|jd|qSbundlerrrerrrrXs single_entityN) rrrrBZ as_readonlyrcolumnsrr)rrrrZ coerced_exprsrrrr 9s   zBundle.__init__rhzList[BindParameter[Any]]zTuple[Any, ...])rh bindparamsrcs*|j|j|jftfdd|jDS)Ncsg|]}|qSr)_gen_cache_keyrrhrrrr`sz)Bundle._gen_cache_key..)rrrrr)rrhrrrrr\szBundle._gen_cache_keyzOptional[Mapper[Any]]rGcCs|jdjdd}|S)Nrrrrr)rrtrrrrcs  z Bundle.mapperrcCs|jdjdd}|S)Nrrdr)rZierrrrjsz Bundle.entityz6ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]cCs|jSr)rrrrrreqszBundle.entity_namespacerrcKs |j|j}|j|j|Sr)rrr8r)rrclonedrrr_clonesz Bundle._clonecCs^||d}||j|jdjd|j}tjdd|jDtj dd | d|d S) N)rrerrhcSsg|]}|jd|qSrrrrrrrsz-Bundle.__clause_element__..F)Z_literal_as_text_rolegrouprfrg) rrrrrrr<Z ClauseListr>rrirj)rrrhrrrrQs$    zBundle.__clause_element__cCs |jSr)rQclausesrrrrrszBundle.clausescCs|}||_|S)z.zRow[Any]r)rrcsfddDS)Ncsg|] }|qSrr)rprocrrrrsz=Bundle.create_row_processor..proc..rrZ keyed_tuplerrrrsz)Bundle.create_row_processor..procr9)rrrrrrrrcreate_row_processors'zBundle.create_row_processorN)rrrrrZis_clause_elementZ is_mapperr Z is_bundler8 immutabledictrr EMPTY_SETZ proxy_setr rrrrrerrQrrrrrrrr s2 # rz Bundle[_T]rb)rXexcludercCst|ddi|S)zDeep copy the given ClauseElement, annotating each element with the "_orm_adapt" flag. Elements within the exclude collection will be cloned but not annotated. _orm_adaptT)rr)rXrrrr _orm_annotatesr)rXrcCstj|ddS)zRemove annotations that link a column to a particular mapping. Note this doesn't affect "remote" and "foreign" annotations passed by the :func:`_orm.foreign` and :func:`_orm.remote` annotators. )rrd)rrZ_deep_deannotaterXrrr_orm_deannotates rcCs t|Srrrrrr_orm_full_deannotatesrc @speZdZdZejjZdZddddddd d d d d d ZddZ dddddddddZ ddddddddZ dS)_ORMJoinz/Extend Join to support ORM constructs as input.TNFrr_zOptional[_OnClauseArgument]r{rzTuple[ColumnElement[bool], ...])leftrightrisouterfull _left_memo _right_memo_extra_criteriac Cs*tdt|} tdt|} | j} ||_||_t|tjrpt rTt|j t j sTt |j } |j} ||j7}n t|tr|} | jj} nd} d} | j}| r&t| |r| }nt|tst |}| j|| d| d|d\}}}}}}|dk r|rt|||}|}nt||||}|}n|}||_t| r@|jdd}nt| sTt| rZ| }nd}|dk rz|jd|i|_t |o| }t!j"#|||||||j$dk st |r|j$tj%|M_$| s&t&| ddr&| j'j(r&td| } | j'j)}|dk r&t| r| j*+|}|j$|@|_$dS)Nz+Union[FromClause, _InternalEntityType[Any]]T)Zsource_selectableZdest_selectableZsource_polymorphicZof_type_entityZalias_secondaryZextra_criteriardrr),rr6r'rrrrrQueryableAttributerZ comparatorrYZ Comparatorr)Z_source_selectablerrr/parentrZclause_is_presentrGZ _create_joinsr7rZ_target_adapterr@rrrrrvr{r<Joinr rand_r;rZsingleZ_single_table_criterionrPrz)rrrrrrrrrZ left_infoZ right_infoZadapt_toZ on_selectablepropZleft_selectableZ adapt_fromZpjZsjsourcedestZ secondaryZtarget_adapterrdZaugment_onclauseZ single_critrrrr s                z_ORMJoin.__init__cCs^|}t|tjr|j}q|j|ks&tt|j|j|j|j|j dd}t||j|j|j|j dS)zlSplice a join into the center. Given join(a, b) and join(b, c), return join(a, b).join(c) N)rrr)rr) rr7rrrr)rrrrr)rrqleftmostrrrr_splice_into_centers&  z_ORMJoin._splice_into_center)rrrrrcCst|||||dS)N)rrr)rrrrrrrrrsz _ORMJoin.join)rrrrcCst|||d|dS)NT)rrr)rrrrrrr outerjoinsz_ORMJoin.outerjoin)NFFNNr)NFF)NF) rrrrr<rZ__visit_name__Z inherit_cacher rrrrrrrrs$y  rrz"attributes.QueryableAttribute[Any]zOptional[_EntityType[Any]]r)rr from_entityrcCslt|trtdnHt|tjrZ|jr.|j}|j}|dksDt|sTtd||}n|}|j ||dS)a Create filtering criterion that relates this query's primary entity to the given related instance, using established :func:`_orm.relationship()` configuration. E.g.:: stmt = select(Address).where(with_parent(some_user, User.addresses)) The SQL rendered is the same as that rendered when a lazy loader would fire off from the given parent on that attribute, meaning that the appropriate state is taken from the parent object in Python without the need to render joins to the parent table in the rendered statement. The given property may also make use of :meth:`_orm.PropComparator.of_type` to indicate the left side of the criteria:: a1 = aliased(Address) a2 = aliased(Address) stmt = select(a1, a2).where( with_parent(u1, User.addresses.of_type(a2)) ) The above use is equivalent to using the :func:`_orm.with_parent.from_entity` argument:: a1 = aliased(Address) a2 = aliased(Address) stmt = select(a1, a2).where( with_parent(u1, User.addresses, from_entity=a2) ) :param instance: An instance which has some :func:`_orm.relationship`. :param property: Class-bound attribute, which indicates what relationship from the instance should be used to reconcile the parent/child relationship. :param from_entity: Entity in which to consider as the left side. This defaults to the "zero" entity of the :class:`_query.Query` itself. .. versionadded:: 1.2 z@with_parent() accepts class-bound mapped attributes, not stringsNz6Expected relationship property for with_parent(), got )r) rryrrrrZ_of_typerrZ _with_parent)rrrZmapper_propertyZprop_trrr with_parents"9   rr{)object_rcCst|}|jS)zReturn True if the given object has a database identity. This typically corresponds to the object being in either the persistent or detached state. .. seealso:: :func:`.was_deleted` )rinstance_state has_identityrrrrrrs rcCst|}|jS)zReturn True if the given object was deleted within a session flush. This is regardless of whether or not the object is persistent or detached. .. seealso:: :attr:`.InstanceState.was_deleted` )rr was_deletedrrrrrs rr)givenrrcCs^t|r(t|r$||kr$dSdSt|rH|jr@||jkS||kSt|sTt||S)zdetermine if 'given' corresponds to 'entity', in terms of an entity passed to Query that would match the same entity being referred to elsewhere in the query. TF)rrMrLrrr)Z common_parentrrrrr_entity_corresponds_to's  rcCsRt|r*t|o(|j o(||kp(||jkSt|s>||jS|joL||jkSdS)adetermine if 'given' corresponds to 'entity', in terms of a path of loader options where a mapped attribute is taken to be a member of a parent entity. e.g.:: someoption(A).someoption(A.b) # -> fn(A, A) -> True someoption(A).someoption(C.d) # -> fn(A, C) -> False a1 = aliased(A) someoption(a1).someoption(A.b) # -> fn(a1, A) -> False someoption(a1).someoption(a1.b) # -> fn(a1, a1) -> True wp = with_polymorphic(A, [A1, A2]) someoption(wp).someoption(A1.foo) # -> fn(wp, A1) -> False someoption(wp).someoption(wp.A1.foo) # -> fn(wp, wp.A1) -> True N)rrLr1rrrrrrr$_entity_corresponds_to_use_path_impl>s rz Mapper[Any])rrrcCsD|jr||jkp|j|S|jr6||jkp4||S||SdS)zedetermine if 'given' "is a" mapper, in terms of the given would load rows of type 'mapper'. N)r rrr)rrrrr _entity_isacsrz Query[Any]r)iterable_queryitemrcCsdd}t|trt|\}}}t|trFt|trF||dkrFgSt|trX|dksjt|trp|dkrp||||}|dk rt|dd|jSt|Sn(|dkr|nt|||ddSdS)zdcalculate __getitem__ in terms of an iterable query object that also has a slice() method. cSs tddS)Nz@negative indexes are not accepted by SQL index / slice operators) IndexErrorrrrr_no_negative_indexesxsz&_getitem.._no_negative_indexesrNr)rslicer8Z decode_sliceintrstep)rrrstartstopr resrrr_getitemrs.    r rirx)raw_annotationr|originating_clsrcCs8zt|||j}Wntk r(YdSXt|tSdSr)rIr NameErrorrLr)rr|r annotatedrrr_is_mapped_annotationsrc@s eZdZdS) _CleanupErrorN)rrrrrrrrsrry)r}r~rc sntd|}|s|Szt|d|}Wn@tk rh}z"td|d|dd|W5d}~XYnX|tjkrzd}n6zt|t r|j }n|WSWnt k r|YSXg}|}| ||kr|n|d|d}td|}|dkr| |qqtd|d sjtd |d sjd d fd d|d dD|d <d |dt|d}|S)Nz^(.+?)\[(.+)\]$rzFor annotation "z%", could not resolve container type "z[". Please ensure this type is imported at the module level outside of TYPE_CHECKING blocksClassVarr4z ^["'].*["']$rz.*\[.*\]z"' rc3s |]}d|dVqdS)"N)strip)rrZ stripcharsrrru sz1_cleanup_mapped_str_annotation..r[])rmatchrKrrrtypingr issubclassrr TypeErrorrrrlen) r}r~mmrneZ real_symbolrinnerg2rrr_cleanup_mapped_str_annotationsJ         r#zOptional[_AnnotationScanType]rz1Optional[Tuple[Union[type, str], Optional[type]]]) rr|r~rattr_clsrequiredis_dataclass_field expect_mappedrrc Cs|dkr2|r.td|jd|d|jddSzt|||td} Wnztk r|} ztd|d| W5d} ~ XYnFtk r} z(|rd |krtd|d| |} W5d} ~ XYnX|r| dfSt| d rt| t sR|rJ|sdSt | d d} | t j krdSt | tr*t| tr*dStjd |jd|d d dn| dfSt| jdkrltd| jd| jfSdS)zgiven an annotation, figure out if it's ``Mapped[something]`` and if so, return the ``something`` part. Includes error raise scenarios and other options. Nz4Python typing annotation is required for attribute ".z " when primary argument(s) for "z#" construct are None or not presentrzCould not interpret annotation zt. Check that it uses names that are correctly imported at the module level. See chained stack trace for more hints.zMapped[ __origin__zType annotation for "a" can't be correctly interpreted for Annotated Declarative Table form. ORM annotations should normally make use of the ``Mapped[]`` generic type, or other ORM-compatible generic type, as a container for the actual type, which indicates the intent that the attribute is mapped. Class variables that are not intended to be mapped by the ORM should use ClassVar[]. To allow Annotated Declarative to disregard legacy annotations which don't use Mapped[] to pass, set "__allow_unmapped__ = True" on the class or a superclass this class.Zzlpr)coderz)Expected sub-type for Mapped[] annotationr)rrrrIr#rrr<rLrr;rrrrrr)r__args__r)) rr|r~rr$r%r&r'rrZcer rrrr_extract_mapped_subtype sl        r,)rrcCs$t|dr|}nd}t||S)N_mapper_property_name)r<r-r8Zclsname_as_plain_name)rrrrr_mapper_property_as_plain_namem s  r.)rT)NN)N)N)TT) __future__rr functoolsrrrrrrrrrr r r r r rrrrrrrrCrrrZ_typingrrrrr[rrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-Z interfacesr.r/r0r1r2Z path_registryr3r5rr6r7r8Z engine.resultr:r;r<r=r>rr?Z sql._typingr@Zsql.annotationrAZsql.baserBZ sql.cache_keyrCrDZ sql.elementsrErFZsql.selectablerGZutil.langhelpersrHZ util.typingrIZ_de_stringify_annotationrJZ_de_stringify_union_elementsrKZ_eval_name_onlyrLrMrNrOrPrQrRrScontextrTrUrrVrWrrXZ relationshipsrYZenginerZr[r\r]r^r_r`rarbrcrdrerfrgZ sql.visitorsrhrirjrk frozensetrpartialrZ_de_stringify_partialrurrryrrrrEnumrZ ColumnAdapterrr Z InspectablerZ_self_inspectsr*rrZ _inspectsrr GenericAliasrrrrrrrrrrrrrr r Exceptionrr#r,r.rrrr s                                                                                                           IC SZ<5 J O4  _ 3O%'`"c