L i; " ddlmZddlZddlZddlZddlZddlZddlmZddlmZddlm Z ddlm Z ddlm Z ddlm Z dd lm Z dd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlZddlmZddlmZddlmZddlmZddlm Z ddlm!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#m0Z0dd)l#m1Z1dd*l#m2Z2dd+l#m3Z3dd,l#m4Z4dd-l#m5Z5dd.l#m6Z6dd/l7m8Z8dd0l7m9Z9dd1l7m:Z:dd2l7m;Z;dd3l7mZ>d5d6lm?Z?d5dlmZ@d5d7lmAZAd5d8lmBZBd5d9lmCZCd5d:lDmEZEd5d;lBmFZFd5dlBmIZId5d9lBmCZJd5d?lBmKZKd5d@lLmMZMd5dAlNmOZOd5dBlPmQZQd5dClRmSZSd5dDlRmTZTd5dElUmVZVd5dFlUmWZWd5dGlXmYZYd5dHlZm[Z[d5dIl\m]Z^d5dJl\m_Z`d5dKl\maZad5dLl\mbZbd5dMl\mcZcd5dNl\mdZdd5dOl\meZeej,rddPlmfZfddQlmgZgddRlmhZhddSlmiZiddTljmkZkddUljmlZlddVlmmnZnddWl=moZoddXlpmqZqddYlrmsZsd5dZltmuZud5d[ltmvZvd5d\lLmwZwd5d]lLmxZxd5d^lLmyZyd5d_lLmzZzd5d`lLm{Z{d5dalLm|Z|d5dblNm}Z}d5dclPm~Z~d5ddlUmZd5delXmZd5dflXmZd5dglXmZd5dhlmZd5dil\mZedjekZedlZejejeCje.e6e+dmnZGdodpeeZe eee^Z]GdqdreeZe eee`Z_Gdsdte eZduZ ddvZ dddddw ddxZGdydzej&ZGd{d|eJj*ZGd}d~eJj*ZGddeAj0de:eZeAj4Gdde;ee.detect_is_backrefs&==%**D>>- -rc|jtjur$s ||s|j|dS|SNFoprOP_BULK_REPLACEobjrvaluerrinclude_backrefsr validators rappendz!_validator_events..append s>||:#=#== (9%(K c5%@@ rc s ||s-|j}|Dcgc] }||dc}|ddyycc}wrr rrrrrrrrrs rbulk_setz#_validator_events..bulk_setsJ'8 'JiikCI:?Ic3u5q (Ks;cPs ||s|j|dS|Srrrroldvaluerrrrrs rset_z_validator_events..set_s,'8 'J c5%@@ rcPs ||s|j|dyy)NTrrs rremovez!_validator_events..removes*'8 'J%))+sE48(Krc|jtjur#s ||s|j|S|Sr|rrs rrz!_validator_events..append$s<||:#=#== (9%(K c599 rc~s ||s,|j}|Dcgc] }||c}|ddyycc}wr|rrs rrz#_validator_events..bulk_set,sA'8 'JiikEKLEYsC7Lq (KLs:cNs ||s|j|S|Sr|rrs rrz_validator_events..set_1s*'8 'J c599 rrT)rawretval bulk_replace)rrrN)r7listen) descrrinclude_removesrrrrrrs `` ` @r_validator_eventsrs  .     9 9   M    LLxT$? LL~xT: LLudT: T8VdCrc  tj}i i|D]}||}tjtj |d}|||<i}|j D]p}|j|k(rtjd|d|d|j|j|||j<|j|j<r| |< fd} g} |jD]\} }|| jtj|D cgc] } | | | c} tj t#j$| j'|gzj)|| jtj|D cgc] } | | | c} j)|tj*| j-|Scc} wcc} w)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) allow_selectzPolymorphic union can't use 'z3' as the discriminator column due to mapped column zn; please apply the 'typecolname' argument; this is available on ConcreteBase as '_concrete_discriminator_name'c$ ||S#t$r{r.colosy Lu%d+ + Lxx E$K8>>tDDsxxz5;?EEdKK  Ls AB:BB)r: OrderedSetr=expectr@StrictFromClauseRolerrrInvalidRequestErroraddtypeitemsrr9selectliteral_columnsql_util_quote_ddl_exprr select_from union_allalias) table_map typecolname aliasnamercolnamesrrmrrresulttype_rrrs ` @@rpolymorphic_unionr>s,&*__%6HK E#   & &D  #  "Auu #00 #A ' LL AaeeH66E!%%L " E-0LF!) u  " MM 6>?dT5)?.. ( 8 8 ?#eK0 +e$  MM 3;<4c$&<+e$ ( ==& ! ' ' 22@=s G!G&)instancerowidentity_tokenc8|ft|}|F|tjd|jt t j ||S|j||S|t|}|j|Stjd)a5Generate "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 zident or row is required)r zclass or instance is required) r#rridentity_key_from_primary_keytupler:to_listidentity_key_from_rowr(identity_key_from_instance)class_identrr r mappers r identity_keyrsJf% ;}**+EFF77dll5)*>8 //N0   x(00::""#BCCrceZdZdZej Zej Zej Zej Z ej Z ej Z ej Z ej Z ej Zej Zej Zy)_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_INSPJOINEDLOAD_USER_DEFINED_ALIAS JOINEDLOAD_PATH_WITH_POLYMORPHICJOINEDLOAD_MEMOIZED_ADAPTERMAPPER_POLYMORPHIC_ADAPTERWITH_POLYMORPHIC_ADAPTER#WITH_POLYMORPHIC_ADAPTER_RIGHT_JOIN DEPRECATED_JOIN_ADAPT_RIGHT_SIDEADAPT_FROM_STATEMENTCOMPOUND_EAGER_STATEMENTLEGACY_SELECT_FROM_ALIASr}rrrrs0499;L%.DIIK!'0tyy{$"+$))+"+(tyy{*3$))+''0tyy{$ %499; )tyy{ )tyy{rrcVeZdZdZdZddddddd dfdZxZS) ORMStatementAdapterz.ColumnAdapter which includes a role attribute.)roleNFT equivalentsadapt_requiredallow_label_resolveanonymize_labelsadapt_on_namesadapt_from_selectablesc @||_t | |||||||y)Nr')r&r__init__) r~r& selectabler(r)r*r+r,r-rs rr/zORMStatementAdapter.__init__)s3   #) 3-)#9  r)r&rr0rir(Optional[_EquivalentColumnMap]r)rr*rr+rr,rr-!Optional[AbstractSet[FromClause]])rrrrrr/rrs@rr%r%$sx8I7;$$(!&$DH   4    "   !B  rr%c ~eZdZUdZdZded<ded<ddd ddd ddd  d fd Zd ZxZS) ORMAdapterzaColumnAdapter subclass which excludes adaptation of entities from non-matching mappers. )r&ris_aliased_class aliased_insprr5Optional[AliasedInsp[Any]]r6NFT)r(r)r*r+r0limit_on_entityr,r-c ||_|j|_| |j}t|rd|_||_nd|_d|_t |||||||r |jnd| | y)NTF)r)r*r+ include_fnr,r-) r&rr0rr5r6rr/ _include_fn) r~r&entityr(r)r*r+r0r8r,r-rs rr/zORMAdapter.__init__Ls mm  **J  ($(D ! &D $)D ! $D    ) 3-+:t'')#9  rc|jjdd}| xs8|j|jxs|jj|S)N parentmapper) _annotationsgetisar)r~elemr<s rr;zORMAdapter._include_fnpsF""&&~t<zOVZZ 4O 8OOr)r&rr<_InternalEntityType[Any]r(r1r)rr*rr+rr0zOptional[Selectable]r8rr,rr-r2) rrrrrrr/r;rrs@rr4r4As GI,,7;$$(!&+/ $$DH" " )" 4 "  " "" " )" " " !B" HPrr4ceZdZUdZded< d d dZe d dZddZ ddZ dd Z dd Z y) 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` rrNc tdtj|} | j} d} |[| jr1| j j r| j j}n,| jj||}n| jrd} |Jt|| |||r|n | j||n | j|| || | |_ d| jjd|_y)N_InternalEntityType[_O]FrflatTaliased())rr8inspectrr5r0 _is_subqueryr_with_polymorphic_selectable_anonymous_fromclause AliasedInspwith_polymorphic_mapperspolymorphic_on _aliased_insprr)r~mapped_class_or_acrrrIr,rQwith_polymorphic_discriminator base_aliasuse_mapper_pathrepresents_outer_joininspr nest_adapterss rr/zAliasedClass.__init__s  %z'9'9:L'M  =$$)E)E--/77MM!!N  " " M   (    ,)442=/**    ! ' ,#6==#9#9":!< rc8|j|}d|jjjd|_||_|j rL|j D]=}||ustj|}t||jj|?|S)NrJrK) rrrrrS_is_with_polymorphic_with_polymorphic_entitiesrE_reconstitute_from_aliased_inspsetattr)rr6rsub_aliased_inspents rr^z,AliasedClass._reconstitute_from_aliased_inspskk#!,"5"5"<"<"E"E!FaH (  , ,$0$K$K H #<7&FF(CC!1!8!8!A!A3G  H rc |jd}|j}t||}t |dr,t |dr t j|j|St |dr|jd|}t |dr|j|}t||||S#t$r t wxYw)NrSr__self____get__adapt_to_entity) __dict___targetgetattrrAttributeErrorhasattrr MethodType__func__rdrer_)r~rrStargetattrs r __getattr__zAliasedClass.__getattr__s ( MM/:M#**F63'D 4 $z)B##DMM48 8 4 #<<d+D 4* +'' 6D D#t $ 1 # " " #s B++B?cRt||}t|dr,t|dr tj|j|St|dr|j d|}t|dr8t j||_|j|}t||||S)Nrrcrdre) rhrjrrkrlrdweakrefref _weak_entityrer_)r~r mapped_classr6rns r_get_from_serializedz!AliasedClass._get_from_serializeds |S) 4 $z)B##DMM48 8 4 #<<d+D 4* +(/ D(9L %'' 5D D#t $ rc^dt||jjjfzS)Nz)idrSrgrr~s rrzAliasedClass.__repr__6s0+ tH    & & / //   rc,t|jSr|)rrSrxs r__str__zAliasedClass.__str__<s4%%&&r) NNFFNNNFF)rTz_EntityType[_O]rOptional[FromClause]r Optional[str]rIrr,rrQOptional[Sequence[Mapper[Any]]]rUOptional[ColumnElement[Any]]rVr7rWrrXr)r6AliasedInsp[_O]rAliasedClass[_O])rrrr)rrrtrr6rrr)rr) rrrrrr/rr^rorurrzr}rrrErEvs9vM '+"$DHGK15 %&+8=+8=$8= 8=  8=  8=#B8=)E8=/8=8= $8=t* ":&(8G . 'rrErc(eZdZUdZdZdej jfdej jfdej jfdej jfdej jfdejjfd ejjfgZ d ed <d ed<d ed<ded<ded<ded< ded< d+dZe d, d-dZe d. d/dZed0dZdZ d1dZed0dZed2dZed3dZd4dZd5d Zd6d!Z d7 d8d"Zer d7 d9d#ZneZd$Z d%Z!d&Z"d'Z#d(Z$d)Z%d*Z&y):rPaProvide 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__rsrr0r_adapt_on_namesrQrR_use_mapper_path _base_aliasrXpersist_selectable local_tabler\r]_adapterrg__clause_element___memoized_values_all_column_expressions_nest_adaptersrrrrgr0rQrRz Mapper[_O]rrIr4rzSequence[Mapper[Any]]zSequence[AliasedInsp[Any]]r]zweakref.ref[AliasedClass[_O]]rsz!Union[Type[_O], AliasedClass[_O]]c |j} |j} tj||_| |_|x|_x|_|_||_||_ tj|xs||_ ||_ | |_ | |_ |rd|_||_g|_|jD]q}|| ust#|j$||| |}t'|j|j$j(||j j+|j,snd|_| g|_t/t0j2| || j4| d|jDchc]}| s |j c}d|_| r>tDC ' C 0D  rTcx|jj|j||djd|dS)N)r> parententityentity_namespaceormcompile_state_pluginplugin_subject)r0 _annotater_set_propagate_attrsrxs r#_memoized_method___clause_element__z/AliasedInsp._memoized_method___clause_element__Hs@(( $ $$(   %*d C  rc|jSr|)r<rxs rrzAliasedInsp.entity_namespaceSs {{rc.|jjS)zUReturn the mapped class ultimately represented by this :class:`.AliasedInsp`.)rrrxs rrzAliasedInsp.class_Ws{{!!!rcp|jr|jjStj|Sr|)rr_path_registryr5 per_mapperrxs rrzAliasedInsp._path_registry]s,  ;;-- -**40 0rc |j|j|j|j|j|j |j |j|j|j|jd S)N) r<rrrr,rQrUrVrWrXrZ) r<rr0rrrQrRrrrXrrxs r __getstate__zAliasedInsp.__getstate__dsjkkkk__II"22(,(E(E.2.A.A**,#44%)%?%?!00  rc||j|d|d|d|d|d|d|d|d|d |d |d  y) Nr<rrrrQrUrVrWr,rXrZ)r/)r~rs r __setstate__zAliasedInsp.__setstate__ssg (O (O 'N &M , - 2 3 ,  # $ " # ) * / " rc|j}|j|usJtjd|jD}|jDchc]}|j}}||k(r|S|j |}|j |d|j \}}|jd}t||||j|j|jjScc}w)Nc34K|]}|jywr|)r.0mps r z*AliasedInsp._merge_with..s" BII" srTr)rQrUrWrX) rr:to_setrQrunionrrXrOrErRrrS) r~otherr our_classesr new_classesrrr0s r _merge_withzAliasedInsp._merge_withs{{n,,,kk" $ = ="  ,1+I+IJRryyJ J + %L!'' 4G,CC T)D)D%DD  5545@   %,+0+?+?!22"'"="=   - KsC+ct|tsJ||jd}|r||d<|jj |j |j d|dS)N)rr> proxy_keyrr)rrGrrtraverserr)r~exprrds r_adapt_elementzAliasedInsp._adapt_elementsh$ ...  KK   AkN MM " "4 ( Yq\ ! !).$G rcyr|r})r~rrs r_orm_adapt_elementzAliasedInsp._orm_adapt_elementsrc|j}||vrD||jur|St|j|jj j S|j|jr|SJd|d|)Nzmapper z doesn't correspond to )rQrrhr<rrrSrA)r~r self_polys r_entity_for_mapperzAliasedInsp._entity_for_mappersq11 Y $ KK!7!7- ZZ $K O&$O O5rc|jj\}}|jj||j Dcic]!\}}|jj||#c}}fScc}}wr|)r _get_clauserrr)r~onclause replacemaprparams r_memoized_attr__get_clausez&AliasedInsp._memoized_attr__get_clausesp#{{66* MM " "8 ,#-"2"2"4 C &&s+U2    s&A2ciSr|r}rxs r_memoized_attr__memoized_valuesz+AliasedInsp._memoized_attr__memoized_valuess rc@|jr>|jj|jDcgc]}|jc}}n|jj}|Dcgc]\}}||j |f}}}t |Scc}wcc}}wr|)r\r_columns_plus_keysr]rrD)r~racols_plus_keysrrs r&_memoized_attr__all_column_expressionsz2AliasedInsp._memoized_attr__all_column_expressionss  $ $![[;;'+'F'FGGN"[[;;=N=K 08SS$%%c* +   //H  s B*Bcn||jvr|j|S||i|x|j|<}|Sr|)r)r~r callable_argskwrs r_memozAliasedInsp._memosE $'' '((- -1:D1GB1G GD ! !# &Lrc|jr&ddjd|jDz}nd}dt||jj|fzS)Nz(%s)rc3HK|]}|jjywr|)rrrs rrz'AliasedInsp.__repr__..s+') ""+s "rz)rQrrwrr)r~ with_polys rrzAliasedInsp.__repr__sc  ( (+-1-J-J+"II, tH KK 0   rcjr?djjddjfdjDdSdjjdS)Nzwith_polymorphic(z, [rc3fK|](}|jur|jj*ywr|)rrr)rrr~s rrz&AliasedInsp.__str__..s/,II&&s.1z])rJrK)r\rgrrrQrxs`rrzzAliasedInsp.__str__s\  $ $ %% ";;  %%)LL$9$9; ;r)r<rrrGr0rIrr|rQr}rRr~rr7rrr,rrXrrZr)NNFF) rz"Union[_EntityType[_O], FromClause]rr{rr|rIrr,rrz#Union[AliasedClass[_O], FromClause])FFNFFFNF)rzUnion[Type[_O], Mapper[_O]]rz/Union[Literal['*'], Iterable[_EntityType[Any]]]r0z'Union[Literal[False, None], FromClause]rIrrRr~rrrrr,rrr|rrrr)rr)rrI)rType[_O])rrY)rDict[str, Any])rrrNone)rrrrr|)rrUrr|rrU)rr^rr|rr^)'rrrrrrAExtendedInternalTraversal dp_string dp_booleandp_inspectabledp_clauseelementInternalTraversaldp_has_cache_key_list_cache_key_traversalrr/rrrpropertyr<r5rrrrrrrrrrrrrrrrrzr}rrrPrP@s>$LI2 33==> H>>IIJ X??JJK H66EEF x99JJK &  & & < <  855FFG  33 :://: ..J* J*+J* J*  J* #B J*5J*0J*J*J* $J*J*X'+"$ 3$      -8 ?D7;$"!&% )% A% < %  % 5 % % % % % %  % % N    "" 11    >7;  &3  *"&     , P  0   >%%..))$ : 7## #   T "H$:$:) ##D)..w7 77D) )rN) rrrrrr/r:preload_modulerr}rrrr s5IT23 *4 *rrceZdZUdZdZdej jfdej jfdejjfdejjfdejjfgZ de d<d e d<d e d<d e d <d e d<d e d<d e d< d ddZedZdZddZddZ ddZ ddZddZd dZy)!LoaderCriteriaOptiona 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_entityr<deferred_where_criteriawhere_criteria_where_crit_originclude_aliasespropagate_to_loadersrr<rrrzOptional[Type[Any]]"Optional[_InternalEntityType[Any]]z9Union[ColumnElement[bool], lambdas.DeferredLambdaElement]rrrrc,tdtj|d}|td||_d|_nd|_||_||_t |r{|j |j}n|J|j}d|_tj|tjt|ftj||_n0d|_tj tj||_||_||_y)NrCFrT)track_closure_variables) lambda_argsopts)rr8rLrr<rcallablerr?DeferredLambdaElementr@WhereHavingRoler LambdaOptionsrr=rrr) r~entity_or_baser loader_onlyrrrr< wrap_entitys rr/zLoaderCriteriaOption.__init__Ps &   ~u 5  >#K@D DK#D  DK . N #+".. )))$mm +/D (")"?"?%%,[9;**,C #D ,1D ("+"2"2%%~#D  /$8!rc t||||S)N)rr)r)rr<rrrs r _unreducezLoaderCriteriaOption._unreduces$  +!5   rctj|jr|jjn |j|j |j |jffSr|)rrr<rrrrrrxs r __reduce__zLoaderCriteriaOption.__reduce__sP * *&*kk ""t7G7G%%$$))    rc#K|jr)|jjjEd{y|jsJt |jj }|rv|j d}tdtj|d}|r|jjEd{n|j|j |ruyy77+w)NrrCF)raiseerr) r<rself_and_descendantsrlist__subclasses__poprr8rLextend)r~stacksubclassras r _all_mappersz!LoaderCriteriaOption._all_mapperss ;;{{))>> > >## ##))88:;E 99Q<.&&x%@"zz>>>>LL!8!8!:; ??s(0C&C"BC&8C$9&C& C&$C&cV|jjjdd|uryy)Nfor_loader_criteriaFT)select_statementr?r@r~ compile_states r_should_includez$LoaderCriteriaOption._should_includes3  * * 7 7 ; ;%t   rc|jr0td|jj|j}n |j}t |t sJtj|d|iddS)NColumnElement[bool]rT)detect_subquery_colsind_cols_on_fromclause) rrr_resolve_with_argsr<rrGr_deep_annotate)r~ext_infocrits r_resolve_where_criteriaz,LoaderCriteriaOption._resolve_where_criteriass  ' '%##66xGD &&D$ ...&&  "D )!%#'   rc&|j|yr|)process_compile_state)r~r!mapper_entitiess r'process_compile_state_replaced_entitieszr;s &2F2Frc t|}| |jsy|j}|S#tj$rYywxYwr|)r* is_mappedrrNO_STATE)r class_managerrs r _inspect_mcr@sL,V4  (?(?%%  <<s* *AAcBtdt|}t|S)Nr)rrNr@)rorigins r_inspect_generic_aliasrCs *j0 1F v rc*eZdZUdZdZ dZdZdZdZe jZ de d<e jZde d< ddZ dd Zedd Zedd Ze dd Zd e d< d e d< dZdZedZdZ ddZy)Bundlea+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` FTrc_propagate_attrszList[_ColumnsClauseElement]exprsc |x|_|_|Dcgc](}tjtj ||*}}||_td|Dcgc]}|jjd| c}Djx|_ |_ |jd|j|_ycc}wcc}w)a<Construct 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. )apply_propagate_attrsc3NK|]}t|d|j|fyw)rN)rh_label)rrs rrz"Bundle.__init__..As*1 S% ,c 21 s#%bundle single_entityN)rrKr=rr@ColumnsClauseRolerGrDr?r@ as_readonlyrcolumnsrrM)r~rrGrr coerced_exprses rr/zBundle.__init__%s&#'& DK      ''T   # 01 ANOA**8Q7O1 !  +-  VVOT5G5GH Ps -B?#C c |j|j|jft|jDcgc]}|j ||c}zScc}wr|)rrrMr rG_gen_cache_key)r~rj bindparamsrs rrTzBundle._gen_cache_keyGsP 4+=+=>CG:: N4T : 6 NB   NsA cX|jdjjdd}|S)Nrr>rGr?r@)r~rs rrz Bundle.mapperNs,$(JJqM$>$>$B$B D%  rcX|jdjjdd}|S)NrrrW)r~ies rr<z Bundle.entityUs-15 2 ,ss>40  r6ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]c|jSr|)rrxs rrzBundle.entity_namespace\s vv rrPrc |jj|j}|jj|j|Sr|)rrrfr)r~rcloneds r_clonez Bundle._clones5''7t}}- rc ||d}|j|j|jdjj d|j }t j|jDcgc]}|jj d| c}tjddj|jd|dScc}w) N)rLrrrrLF)_literal_as_text_rolegrouprr) rr?rGrFr@r<r> ClauseListr@rNrr)r~rrrRs rrzBundle.__clause_element__s!%4@  4,,-A77;; dkk   ! !<@::Fa!..$$Xq1F',&=&=  Y{ # ! !-2&4 Gs2#C c6|jjSr|)rclausesrxs rrdzBundle.clausess&&(000rc4|j}||_|S)z.procs e ,@s & N)rrrGz_ColumnExpressionArgument[Any]rr)rjrjrUzList[BindParameter[Any]]rzTuple[Any, ...])rzOptional[Mapper[Any]])rr)rrZ)rkz Select[Any]rjz#Sequence[Callable[[Row[Any]], Any]]rlz Sequence[str]rzCallable[[Row[Any]], Any])rrrrrMis_clause_element is_mapperr5 is_bundler: immutabledictrFr EMPTY_SET proxy_setr/rTrrr<rr^rrdrrnr}rrrErEs;$M<II,>D,>,>,@)@I && I I!? IGJ ID   .F     ? DC0>=/  211++3+ + # +rrEz Bundle[_T]c4tj|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()rexcludes r _orm_annotaterxs  " "7\4,@' JJrc0tj|dS)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. )rvr)rr_deep_deannotaters r_orm_deannotater}s  $ $6 rc,tj|Sr|rzr|s r_orm_full_deannotaters  $ $W --rceZdZdZej j ZdZ d d dZdZ d d dZ d d dZ y)_ORMJoinz/Extend Join to support ORM constructs as input.TNc tdtj|} tdtj|} | j} ||_||_t |tjrbtr&t |jtjsJ|jj} |j} ||jz }n-t |t r|} | j"j} nd} d} | j}| rt%j&| |r| }nt |t(sJ|}| j+|| d| d|\}}}}}}|7|rt-j.|||}|}nt-j.||||}|}n|}||_t3| r|j4j7dd}nt9| s t;| r| }nd}|"|j4j=d|i|_t?|xr| }t@jBjE|||||||jFJ|r%|xjFt-jH|zc_#| stK| ddrw| jLjNr`td| } | jLjP}|;t;| r| jRjU|}|jF|z|_#yyyyy)Nz+Union[FromClause, _InternalEntityType[Any]]T)source_selectabledest_selectablesource_polymorphicof_type_entityalias_secondaryextra_criteriarrrC)+rr8rLr0 _left_memo _right_memorrQueryableAttributer comparatorr[ Comparator_source_selectabler_extra_criteriar1parentrclause_is_presentrI _create_joinsr9r_target_adapterrBr?r@rrrrr>Joinr/rand_rhrsingle_single_table_criterionrr)r~leftrightrisouterfullrrr left_info right_infoadapt_to on_selectablepropleft_selectable adapt_frompjsjsourcedest secondarytarget_adapterraugment_onclause single_crits rr/z_ORMJoin.__init__s 9   t $  9   u % ((%& h = = >!'')=)H)H%//BBDM$$D x77 7O . 1D KK22MD M#.. ))-I* !/:>>>, """, (#') $. # ~HHYr:E!H88D)RAD!H#1D  #*77;;LI &*? *J$LL  # $ 1 1 7 7.!D  0=X  tUHgtL}}(((  MMSXX7 7M Hd3!!((8*EJ%++CCK&(4","5"5">">{"KK $ ; ')4rc|}t|tjr'|j}t|tjr'|j|usJt |j|j|j |j|j|jj}t ||j|j |j|jS)zlSplice a join into the center. Given join(a, b) and join(b, c), return join(a, b).join(c) )rrr)rr) rr9rrrrrrrrr)r~rleftmostrs r_splice_into_centerz_ORMJoin._splice_into_centerrs 388,}}H388,zzX%%% II JJ MMLL((77    KK NNMM))   rc"t|||||S)N)rrr)r~rrrrs rrz _ORMJoin.joinseXD'JJrc"t|||d|S)NT)rrr)r~rrrs r outerjoinz_ORMJoin.outerjoins eXt$GGr)NFFNNr})rrarrarOptional[_OnClauseArgument]rrrrr Optional[Any]rrrzTuple[ColumnElement[bool], ...])NFF) rrarrrrrrrrr)rrarrrrrr) rrrrr>r__visit_name__ inherit_cacher/rrrr}rrrrs9__33NM 15$(%);=w<!w<#w<. w<  w<  w<"w<#w<9w + &&&') !   x[  AArcDtj|}|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_identityobject_rs rrrs   % %g .E   rcDtj|}|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_deletedrs rrrs   % %g .E   rct|r-t|r!|j|juryyt|r|jr||jvS||uSt |sJ|j |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)rrrrQr common_parentgivenr<s r_entity_corresponds_torsV$  '!!#u'8'8':: u %  ! !U;;; ;U? " %     &&rct|r0t|xr#|j xr||uxs||jvSt|s|j|jS|jxr||j vS)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 )rrr]rArrQrs r$_entity_corresponds_to_use_path_implr%s*U# !& ) P+++ P&NFe.N.N$N #6 *yy''  # # 9888 rc|jr+||jvxs|jj|S|jr!||jvxs|j|S|j|S)zedetermine if 'given' "is a" mapper, in terms of the given would load rows of type 'mapper'. )r5rQrrA)rrs r _entity_isarIsr  777 5<<;K;K <    ' '777L599V;LLyy  rcd}t|trtj|\}}}t|trt|tr ||z dkrgSt|tr|dkst|tr |dkr||j||}|t |dd|j St |S|dk(r|yt |||dzdS)zdcalculate __getitem__ in terms of an iterable query object that also has a slice() method. ctd)Nz@negative indexes are not accepted by SQL index / slice operators) IndexErrorr}rr_no_negative_indexesz&_getitem.._no_negative_indexes^s &  rrNr)rslicer: decode_sliceintrstep)iterable_queryitemrstartstoprress r_getitemrXs  $ --d3tT tS !5#&u !I$ tS !dQh """5$/  9TD49945 59  2: "tdQh78; ;rcp t|||j}t|tS#t$rYywxYwr)rKrrOr NameError)raw_annotationroriginating_cls annotateds r_is_mapped_annotationrsE B+ !;!;  +@AA s ) 55c eZdZy) _CleanupErrorN)rrrr}rrrrsrrc B tjd|}|s|S t|jd|}|t jurd}n! t|tr |j}n|S g}|} |j||ur|n|jd|jd}tjd|}||j|nbtjd|d smtjd |d sTd d j fd |d jdD|d <dj|dt!|dz zz}|S#t$r'}t d|d|jdd|d}~wwxYw#t$r|cYSwxYw)Nz^([^ \|]+?)\[(.+)\]$rzFor annotation "z%", could not resolve container type "z[". Please ensure this type is imported at the module level outside of TYPE_CHECKING blocksClassVarr6z ^["'].*["']$rz[\[\]]z"' rc3HK|]}d|jdyw)"N)strip)rrB stripcharss rrz1_cleanup_mapped_str_annotation..s) .2a :&'q ) s"r[])rmatchrLrarrtypingr issubclassrr TypeErrorrsearchrrlen) rrmmrne real_symbolrinnerg2rs @r_cleanup_mapped_str_annotationrs ): 6B RXXa[*<= foo  #45!ll !! E E  B%K[U[[^D [[^0"5 = LL   . HH(%) 4  )U2Y/ II 6;Biooc6J  b XXe_s5zA~(>? C zl+!xx{m,. .       s)EF F &"FF  FFc "|6|r3tjd|jd|d|jdy t|||t} |r| dfSt| d rt| tsr|rl|syt| d d} | tjuryt| trt| t rytjd |jd|d d | dfSt#| j$dk7rtjdt'| j$d| j(fS#t $r} tjd|d| d} ~ wt $r-} |rd |vrtjd|d| |} Yd} ~ 3%(%%&&IK  # ,   9  ,$y,/7G ,8  L$?V__, -*M3 33+CLL>3% @- - $!$& y!! "a '//;  %Y%7%7%: ;    } ++-n-=>D D    #  ^3//1.1ABHH   # #s#D22 F;E F!"F  Fclt|dr|j}nd}tj||S)N_mapper_property_name)rjrr:clsname_as_plain_name)rrs r_mapper_property_as_plain_namer ^ s3t,-))+  % %dD 11r)p_unionT)NN) rzOptional[Type[_T]]rzUnion[Any, Tuple[Any, ...]]rz Optional[_T]r z%Optional[Union[Row[Any], RowMapping]]r rrz_IdentityKeyType[_T])rrrzOptional[Mapper[_O]]r|)rrdrwrrrd)rrdrrd)rrrz"attributes.QueryableAttribute[Any]rzOptional[_EntityType[Any]]rr$)rrrr)rrCr<rCrr)rrCrz Mapper[Any]rr)rz Query[Any]rrrr)rrkrrrrrr)rrrrrr)TT)rzOptional[_AnnotationScanType]rrrrrrrrrrrrrrrrrz@Optional[Tuple[Union[_AnnotationScanType, str], Optional[type]]])rrrr) __future__rr functoolsrrrrrrrrr r r r r rrrrrrrrrqrrrr_typingrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/ interfacesr0r1r2r3r4 path_registryr5r7rr8r9r: engine.resultr<r=r>r?r@rrA sql._typingrBsql.annotationrCsql.baserD sql.cache_keyrErF sql.elementsrGrHsql.selectablerIutil.langhelpersrJ util.typingrK_de_stringify_annotationrL_eval_name_onlyrMrNrOrPrQrRrSrTrUcontextrVrWrrXrYrkrZ relationshipsr[enginer\r]r^r_r`rarbrcrdrerfrgrhri sql.visitorsrjrkrl frozensetrpartialrr_de_stringify_partialrxrrrrrrEnumr ColumnAdapterr%r4 InspectablerE_self_inspectsrPrr _inspectsrr@ GenericAliasrCrErxr}rrrrrrrrrrr Exceptionrrrr r}rrr)s#   *#)6'*2(0.2.0.&<4(!&8,2)7("'5''/(-',M;2$*!" $),$&(53#!721/1$3,6'+'1 T   * ))  D  .*    X 12JK @H@m%:?%KLFYs^FR?DF=AO3f"&)-UD"15$( UD UD &UD UD / UD " UDUDp9+dii9+x (00 :2P''2PjG',-/CB/GG'T I<r",- BKI<Ip'f# \"#FGd     DI l# $ Y<( YYxK .lHzlHd/3IBIB ,IB,IB IBX  "' #'-E' '.! #! -E!  ! H !$