U a@s ddlZddlZddlZddlmZddlmZddlmZddlmZddlm Z ddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddl!m"Z"ddlmZ#ddlm$Z$dd lm%Z%dd!lm&Z&dd"lm'Z'ddlm Z(dd#lm)Z)dd$l*m+Z+dd%l,m-Z-e.d&Z/Gd'd(d(e.Z0d)d*Z1dad-d.Z2d/d0Z3Gd1d2d2e(j4Z5Gd3d4d4e6Z7Gd5d6d6eee#j8e Z9Gd7d8d8e6Z:Gd9d:d:eZ;eej?GdCdDdDee+e Z@dddEdFZAdGdHZBdIdJZCGdKdLdLe%jDZEdedMdNZFdfdOdPZGdgdQdRZHdSdTZIdUdVZJdWdXZKdYdZZLd[d\ZMd]d^ZNd_d`ZOdS)hN) attributes)_class_to_mapper) _never_set) _none_set) attribute_str) class_mapper)InspectionAttr) instance_str) object_mapper) object_state)state_attribute_str)state_class_str) state_str)CriteriaOption)MapperProperty)ORMColumnsClauseRole)ORMEntityColumnsClauseRole)ORMFromClauseRole)PropComparator) PathRegistry)event)exc) inspection)sql)util result_tuple)base) coercions) expression)lambdas)roles)visitors)SupportsCloneAnnotations)ColumnCollection)delete delete-orphanallmergeexpunge save-updaterefresh-expirenonec@sPeZdZdZedddgZeZddddgZdZ dd Z d d Z e d d Z dS)CascadeOptionszHKeeps track of the options sent to :paramref:`.relationship.cascade`r)r.r(r+r-) save_updater'refresh_expirer*r+ delete_orphanc Cst|tjs|dkr||St|}||jr\tdd ddt ||jDd|krp| |j d|kr| |dtt|}d|k|_d|k|_d |k|_d |k|_d |k|_d |k|_|jr|jstd |S)NzInvalid cascade option(s): %s, cSsg|] }t|qS)repr.0xr4r4TC:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\orm\util.py \sz*CascadeOptions.__new__..r)r.r,r'r-r*r+r(z5The 'delete-orphan' cascade option requires 'delete'.) isinstancer string_types from_stringset difference_allowed_cascadessa_exc ArgumentErrorjoinsortedupdate_add_w_all_cascadescleardiscard frozenset__new__r/r0r'r1r*r+r2warn)clsZ value_listvaluesselfr4r4r9rJTs@              zCascadeOptions.__new__cCsddddt|DS)NzCascadeOptions(%r),cSsg|]}|qSr4r4r6r4r4r9r:zsz+CascadeOptions.__repr__..)rCrDrNr4r4r9__repr__yszCascadeOptions.__repr__cCs"ddtd|pdD}||S)NcSsg|] }|r|qSr4r4)r7cr4r4r9r:~sz.CascadeOptions.from_string..z\s*,\s*)resplit)rLargrMr4r4r9r=|szCascadeOptions.from_stringN)__name__ __module__ __qualname____doc__ all_cascadesr?rFr@Z_viewonly_cascades __slots__rJrQ classmethodr=r4r4r4r9r/@s  %r/c 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 SN)managerimpl)state initiatorr`)keyr4r9detect_is_backrefs z,_validator_events..detect_is_backrefcs4|jtjk r,s||s,||dS|SdSNFoprZOP_BULK_REPLACEobjravaluerbrdinclude_backrefsrc validatorr4r9appends z!_validator_events..appendcs8s||s4|fdd|D|dd<dS)Ncsg|]}|dqS)Fr4r7rjrcrhrmr4r9r:s7_validator_events..bulk_set..rhrarMrbrkrrr9bulk_sets z#_validator_events..bulk_setcs(s||s ||dS|SdSrerrrarjZoldvaluerbrkr4r9set_sz_validator_events..set_cs$s||s ||ddS)NTrrrirkr4r9removesz!_validator_events..removecs2|jtjk r*s||s*||S|SdSr^rfrirkr4r9rns cs8s||s4|fdd|D|dd<dS)Ncsg|]}|qSr4r4rorpr4r9r:srqrrrsrkrrr9rtscs&s||s||S|SdSr^rrrurkr4r9rvsrnT)rawretvalZ bulk_replace)rxr>rwN)rlisten) descrcrmZinclude_removesrlrnrtrvrwr4rkr9_validator_eventss r|p_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^)KeyErrorrcastnulllabelZ type_coerce)nametable) cast_nulls colnamemapstypesr4r9cols zpolymorphic_union..colNcsg|]}|qSr4r4r7rrrr4r9r:sz%polymorphic_union..csg|]}|qSr4r4rrr4r9r:s)rZ OrderedSetr expectr#ZStrictFromClauseRolerRrcrAZInvalidRequestErroraddtypeitemsrnrselectZliteral_columnsql_utilZ_quote_ddl_exprr select_fromZ union_allalias) Z table_mapZ typecolnameZ aliasnamerZcolnamesrcmrRresulttype_r4)rrrrrr9polymorphic_unionsb        rc Os|rd}t|}|dkrP|d}z|d}Wqptk rL|d}YqpXn |dkrb|\}}ntd||dd}|rtd d |t|}|dkr|jt ||d S|j ||d Sn6|d }|rtd d |j t |}| |SdS) a9Generate "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` 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 Nrrrowident)rz1expected up to three positional arguments, got %sidentity_tokenzunknown keyword arguments: %sr3)rinstance)lenpopr~rArBrCrZidentity_key_from_primary_keyrZto_listZidentity_key_from_rowkeysr Zidentity_key_from_instance) argskwargsrlargsclass_rrmapperrr4r4r9 identity_keysH@    rc@s"eZdZdZd ddZddZdS) ORMAdapterzaColumnAdapter subclass which excludes adaptation of entities from non-matching mappers. NFTc CsPt|}|j|_|j}|j}|r*||_nd|_tjj|||||||j ddS)N)adapt_requiredallow_label_resolveanonymize_labelsZ include_fn) rinspectr selectableis_aliased_classZ aliased_classr ColumnAdapter__init__ _include_fn) rNentity equivalentsrrrinforrr4r4r9rs  zORMAdapter.__init__cCs |jdd}| p||jS)N parentmapper) _annotationsgetisar)rNelemrr4r4r9rszORMAdapter._include_fn)NFTF)rWrXrYrZrrr4r4r4r9r~s rc @sFeZdZdZdddZeddZd d Zd d Zd dZ ddZ 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` NFr4c Csnt|} | j} |dkr(| jj||d}t|| |||r:|n| j|dk rJ|n| j|| || |_d| j j |_ dS)NrflatAliasedClass_%s) rrrZ_with_polymorphic_selectable_anonymous_fromclause AliasedInspwith_polymorphic_mapperspolymorphic_on _aliased_insprrW) rNmapped_class_or_acrrradapt_on_namesrwith_polymorphic_discriminator base_aliasuse_mapper_pathrepresents_outer_joinZinsprr4r4r9rs0 zAliasedClass.__init__cCsX||}d|jjj|_||_|jrT|jD]&}||k r,t|}t ||jj|q,|S)Nr) rJrrrWr_is_with_polymorphic_with_polymorphic_entitiesr_reconstitute_from_aliased_inspsetattr)rL aliased_insprhZsub_aliased_inspentr4r4r9r s  z,AliasedClass._reconstitute_from_aliased_inspcCsz|jd}Wntk r(tYnX|j}t||}t|dr\t|dr\t|j|St|drr| d|}t|dr| |}t ||||S)Nr__call____self____get__adapt_to_entity) __dict__r~AttributeError_targetgetattrhasattrr MethodType__func__rrr)rNrcrtargetattrr4r4r9 __getattr__s       zAliasedClass.__getattr__cCsrt||}t|dr,t|dr,t|j|St|drB|d|}t|drnt||_| |}t ||||S)Nrrrr) rrrrrrweakrefref _weak_entityrr)rNrcZ mapped_classrrr4r4r9_get_from_serialized7s       z!AliasedClass._get_from_serializedcCsdt||jjjfS)Nz)idrrrWrPr4r4r9rQLszAliasedClass.__repr__cCs t|jSr^)strrrPr4r4r9__str__RszAliasedClass.__str__) NNFFr4NNFF) rWrXrYrZrr]rrrrQrr4r4r4r9rs"= * rc@seZdZdZddZeddZdZej ddZ ed d Z d e j jfd e j jfd e j jfgZeddZeddZddZddZd'ddZddZejddZejddZejdd Zd!d"Zd#d$Zd%d&ZdS)(raProvide 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` c Cs|j} |j} t||_| |_||_|_|_||_||_ t|pF||_ ||_ | |_ |rd|_ ||_g|_|jD]@} | | k rtt| j||| |d}t|j| jj||j|jqtnd|_ | g|_tj|| j| ddd|jDd|_|jr|j|j|_| |_| |_dS)NT)rrrFcSsg|] }|jqSr4)r)r7rr4r4r9r:sz(AliasedInsp.__init__..)rrrZadapt_from_selectables)rrrrrrZpersist_selectableZ local_tablerr _base_alias_use_mapper_pathrrrrrrrrWrnrrrZ_equivalent_columns_adapterrwrap_adapt_on_namesr)rNrZ inspectedrrrrrrrrrrZpolyrr4r4r9rsV   zAliasedInsp.__init__cCs*|}|dkr&t|}t||_|Sr^)rrrrr)rNrr4r4r9rs   zAliasedInsp.entityTcCs"|j|j||dd|dS)N)r parententityentity_namespaceormZcompile_state_pluginplugin_subject)r _annotater_set_propagate_attrsrPr4r4r9__clause_element__szAliasedInsp.__clause_element__cCs|jSr^)rrPr4r4r9rszAliasedInsp.entity_namespacerrrcCs|jjS)zUReturn the mapped class ultimately represented by this :class:`.AliasedInsp`.)rrrPr4r4r9rszAliasedInsp.class_cCs|jr|jjSt|SdSr^)rr_path_registryrZ per_mapperrPr4r4r9rszAliasedInsp._path_registryc Cs0|j|j|j|j|j|j|j||j|j d S)N) rrrrrrrrrr) rrrrrrrrrrrPr4r4r9 __getstate__szAliasedInsp.__getstate__c CsH||d|d|d|d|d|d|d|d|d |d  dS) Nrrrrrrrrrr)r)rNrar4r4r9 __setstate__ szAliasedInsp.__setstate__NcCs6||jd}|r||d<|j||d|dS)N)rr proxy_keyrr)rrtraverserr)rNrrcdr4r4r9_adapt_elements zAliasedInsp._adapt_elementcCsX|j}||kr0||jkr|St|j|jjjSn$||jr@|SdsTtd||fdS)NFz"mapper %s doesn't correspond to %s) rrrrrrWrrAssertionError)rNrZ self_polyr4r4r9_entity_for_mapper&s  zAliasedInsp._entity_for_mappercs.jj\}}j|fdd|DfS)Ncsi|]\}}j||qSr4)rr)r7rparamrPr4r9 9s z+AliasedInsp._get_clause..)r _get_clauserrr)rNonclauseZ replacemapr4rPr9r4s    zAliasedInsp._get_clausecCsiSr^r4rPr4r4r9_memoized_values?szAliasedInsp._memoized_valuescsDjr jddjD}n j}fdd|D}t|S)NcSsg|] }|jqSr4)r)r7rr4r4r9r:Gsz7AliasedInsp._all_column_expressions..csg|]\}}||fqSr4)r)r7rcrrPr4r9r:Ls)rrZ_columns_plus_keysrr&)rNZcols_plus_keysr4rPr9_all_column_expressionsCs  z#AliasedInsp._all_column_expressionscOs0||jkr|j|S||||j|<}|SdSr^)r)rNrcZ callable_rkwrjr4r4r9_memoRs  zAliasedInsp._memocCs<|jr"dddd|jD}nd}dt||jj|fS)Nz(%s)r3css|]}|jjVqdSr^)rrWr7mpr4r4r9 [sz'AliasedInsp.__repr__..rSz)rrCrrrW)rNZ with_polyr4r4r9rQYs  zAliasedInsp.__repr__cs>jr,djjdfddjDfSdjjfSdS)Nzwith_polymorphic(%s, [%s])r3c3s |]}|jk r|jjVqdSr^)rrrWrrPr4r9rjs z&AliasedInsp.__str__..z aliased(%s))rrrWrCrrPr4rPr9rfs zAliasedInsp.__str__)N)rWrXrYrZrpropertyrrrZmemoized_instancemethodrrr$ExtendedInternalTraversalZ dp_string dp_booleandp_clauseelementZ_cache_key_traversalrrrrrrZmemoized_propertyrrrrrQrr4r4r4r9rVs<&E             rc@s*eZdZdZddZedddZdS)_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. cCs ||_dSr^)subject)rNrr4r4r9r~sz_WrapUserEntity.__init__zsqlalchemy.orm.decl_apicCsPtjjj}t|d}||jkrBt|j||jrB|j| |St ||SdS)Nr) rZ preloadedrdecl_apiobject__getattribute__rr;Z declared_attrfgetr)rNrrrr4r4r9r s   z _WrapUserEntity.__getattribute__N)rWrXrYrZrrZpreload_moduler r4r4r4r9rts rc@speZdZdZdejjfdejjfdejj fdejj fdejj fgZ dd d Z d d Z d dZddZddZdS)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_entityrwhere_criteriainclude_aliasespropagate_to_loadersFTcCst|d}|dkr"||_d|_n d|_||_t|rvd|_tj|tj t |jdk rX|jn|jjftj |dd|_ nd|_t tj ||_ ||_||_dS)aAdd additional WHERE criteria to the load for all occurrences of a particular entity. .. versionadded:: 1.4 The :func:`_orm.with_loader_criteria` option is intended to add limiting criteria to a particular kind of entity in a query, **globally**, meaning it will apply to the entity as it appears in the SELECT query as well as within any subqueries, join conditions, and relationship loads, including both eager and lazy loaders, without the need for it to be specified in any particular part of the query. The rendering logic uses the same system used by single table inheritance to ensure a certain discriminator is applied to a table. E.g., using :term:`2.0-style` queries, we can limit the way the ``User.addresses`` collection is loaded, regardless of the kind of loading used:: from sqlalchemy.orm import with_loader_criteria stmt = select(User).options( selectinload(User.addresses), with_loader_criteria(Address, Address.email_address != 'foo')) ) Above, the "selectinload" for ``User.addresses`` will apply the given filtering criteria to the WHERE clause. Another example, where the filtering will be applied to the ON clause of the join, in this example using :term:`1.x style` queries:: q = session.query(User).outerjoin(User.addresses).options( with_loader_criteria(Address, Address.email_address != 'foo')) ) The primary purpose of :func:`_orm.with_loader_criteria` is to use it in the :meth:`_orm.SessionEvents.do_orm_execute` event handler to ensure that all occurrences of a particular entity are filtered in a certain way, such as filtering for access control roles. It also can be used to apply criteria to relationship loads. In the example below, we can apply a certain set of rules to all queries emitted by a particular :class:`_orm.Session`:: session = Session(bind=engine) @event.listens_for("do_orm_execute", session) def _add_filtering_criteria(execute_state): if ( execute_state.is_select and not execute_state.is_column_load and not execute_state.is_relationship_load ): execute_state.statement = execute_state.statement.options( with_loader_criteria( SecurityRole, lambda cls: cls.role.in_(['some_role']), include_aliases=True ) ) In the above example, the :meth:`_orm.SessionEvents.do_orm_execute` event will intercept all queries emitted using the :class:`_orm.Session`. For those queries which are SELECT statements and are not attribute or relationship loads a custom :func:`_orm.with_loader_criteria` option is added to the query. The :func:`_orm.with_loader_criteria` option will be used in the given statement and will also be automatically propagated to all relationship loads that descend from this query. The criteria argument given is a ``lambda`` that accepts a ``cls`` argument. The given class will expand to include all mapped subclass and need not itself be a mapped class. .. warning:: The use of a lambda inside of the call to :func:`_orm.with_loader_criteria` is only invoked **once per unique class**. Custom functions should not be invoked within this lambda. See :ref:`engine_lambda_caching` for an overview of the "lambda SQL" feature, which is for advanced use only. :param entity_or_base: a mapped class, or a class that is a super class of a particular set of mapped classes, to which the rule will apply. :param where_criteria: a Core SQL expression that applies limiting criteria. This may also be a "lambda:" or Python function that accepts a target class as an argument, when the given class is a base with many different mapped subclasses. :param include_aliases: if True, apply the rule to :func:`_orm.aliased` constructs as well. :param propagate_to_loaders: defaults to True, apply to relationship loaders such as lazy loaders. .. seealso:: :ref:`examples_session_orm_events` - includes examples of using :func:`_orm.with_loader_criteria`. :ref:`do_orm_execute_global_criteria` - basic example on how to combine :func:`_orm.with_loader_criteria` with the :meth:`_orm.SessionEvents.do_orm_execute` event. :param track_closure_variables: when False, closure variables inside of a lambda expression will not be used as part of any cache key. This allows more complex expressions to be used inside of a lambda expression but requires that the lambda ensures it returns the identical SQL every time given a particular class. .. versionadded:: 1.4.0b2 FNT)track_closure_variables)Z lambda_argsopts)rrr rcallabledeferred_where_criteriar"ZDeferredLambdaElementr#ZWhereHavingRolerZ LambdaOptionsr r rrr)rNZentity_or_baser Z loader_onlyrrrrr4r4r9rs8}  zLoaderCriteriaOption.__init__ccsv|jr|jjjD] }|VqnTt|j}|rr|d}tj|dd}|rb|jjD] }|VqTq,| |q,dS)NrF)Zraiseerr) rrZself_and_descendantslistr __subclasses__rrrextend)rNrstacksubclassrr4r4r9 _all_mappers@s    z!LoaderCriteriaOption._all_mapperscCs|jr|j|jS|jSdSr^)rr Z_resolve_with_argsr)rNZext_infor4r4r9_resolve_where_criteriaOsz,LoaderCriteriaOption._resolve_where_criteriacCs*|jjrtd|jjs&||jdS)z7Apply a modification to a given :class:`.CompileState`.zThe with_loader_criteria() function may not work correctly with the legacy Query.with_polymorphic() feature. Please migrate code to use the with_polymorphic() standalone function before using with_loader_criteria().N)Zcompile_optionsZ_with_polymorphic_adapt_maprrKZ_for_refresh_stateget_global_criteriaZglobal_attributes)rNZ compile_stater4r4r9process_compile_stateUs z*LoaderCriteriaOption.process_compile_statecCs,|D]}|d|fg}||qdS)NZadditional_entity_criteria)r setdefaultrn)rNrrZ load_criteriar4r4r9res  z(LoaderCriteriaOption.get_global_criteriaN)FFTT)rWrXrYrZr$rZ dp_plain_objZdp_has_cache_keyZInternalTraversalrrZ_traverse_internalsrrrrrr4r4r4r9r s"       r cCs|jSr^)rrr4r4r9nrcCs|Sr^r4rr4r4r9ror FcCsVt|tjr@|rtd|r,|j||dStjtj ||dSnt |||||dSdS)a%Produce an alias of the given element, usually an :class:`.AliasedClass` instance. E.g.:: my_alias = aliased(MyClass) session.query(MyClass, my_alias).filter(MyClass.id > my_alias.id) The :func:`.aliased` function is used to create an ad-hoc mapping of a mapped class to a new selectable. By default, a selectable is generated from the normally mapped selectable (typically a :class:`_schema.Table` ) using the :meth:`_expression.FromClause.alias` method. However, :func:`.aliased` can also be used to link the class to a new :func:`_expression.select` statement. Also, the :func:`.with_polymorphic` function is a variant of :func:`.aliased` that is intended to specify a so-called "polymorphic selectable", that corresponds to the union of several joined-inheritance subclasses at once. For convenience, the :func:`.aliased` function also accepts plain :class:`_expression.FromClause` constructs, such as a :class:`_schema.Table` or :func:`_expression.select` construct. In those cases, the :meth:`_expression.FromClause.alias` method is called on the object and the new :class:`_expression.Alias` object returned. The returned :class:`_expression.Alias` is not ORM-mapped in this case. :param element: element to be aliased. Is normally a mapped class, but for convenience can also be a :class:`_expression.FromClause` element. :param alias: Optional selectable unit to map the element to. This is usually used to link the object to a subquery, and should be an aliased select construct as one would produce from the :meth:`_query.Query.subquery` method or the :meth:`_expression.Select.subquery` or :meth:`_expression.Select.alias` methods of the :func:`_expression.select` construct. :param name: optional string name to use for the alias, if not specified by the ``alias`` parameter. The name, among other things, forms the attribute name that will be accessible via tuples returned by a :class:`_query.Query` object. Not supported when creating aliases of :class:`_sql.Join` objects. :param flat: Boolean, will be passed through to the :meth:`_expression.FromClause.alias` call so that aliases of :class:`_expression.Join` objects will alias the individual tables inside the join, rather than creating a subquery. This is generally supported by all modern databases with regards to right-nested joins and generally produces more efficient queries. :param adapt_on_names: if True, more liberal "matching" will be used when mapping the mapped columns of the ORM entity to those of the given selectable - a name-based match will be performed if the given selectable doesn't otherwise have a column that corresponds to one on the entity. The use case for this is when associating an entity with some derived selectable such as one that uses aggregate functions:: class UnitPrice(Base): __tablename__ = 'unit_price' ... unit_id = Column(Integer) price = Column(Numeric) aggregated_unit_price = Session.query( func.sum(UnitPrice.price).label('price') ).group_by(UnitPrice.unit_id).subquery() aggregated_unit_price = aliased(UnitPrice, alias=aggregated_unit_price, adapt_on_names=True) Above, functions on ``aggregated_unit_price`` which refer to ``.price`` will return the ``func.sum(UnitPrice.price).label('price')`` column, as it is matched on the name "price". Ordinarily, the "price" function wouldn't have any "column correspondence" to the actual ``UnitPrice.price`` column as it is not a proxy of the original. z+adapt_on_names only applies to ORM elementsrr)rrrrN) r;r!Z FromClauserArBrr rr#ZAnonymizedFromClauseRoler)elementrrrrr4r4r9aliasedrs&V r#c Cst|} |dkr|rtd|rd|j| ks0tt|}tdd|jD} || krZ|S| | }| j |||d\} }|s|r|j |d}t ||| ||| dS)ak Produce an :class:`.AliasedClass` construct which specifies columns for descendant mappers of the given base. Using this method will ensure that each descendant mapper's tables are included in the FROM clause, and will allow filter() criterion to be used against those tables. The resulting instances will also have those columns already loaded so that no "post fetch" of those columns will be required. .. seealso:: :ref:`with_polymorphic` - full discussion of :func:`_orm.with_polymorphic`. :param base: Base class to be aliased. :param classes: a single class or mapper, or list of class/mappers, which inherit from the base class. Alternatively, it may also be the string ``'*'``, in which case all descending mapped classes will be added to the FROM clause. :param aliased: when True, the selectable will be aliased. For a JOIN, this means the JOIN will be SELECTed from inside of a subquery unless the :paramref:`_orm.with_polymorphic.flat` flag is set to True, which is recommended for simpler use cases. :param flat: Boolean, will be passed through to the :meth:`_expression.FromClause.alias` call so that aliases of :class:`_expression.Join` objects will alias the individual tables inside the join, rather than creating a subquery. This is generally supported by all modern databases with regards to right-nested joins and generally produces more efficient queries. Setting this flag is recommended as long as the resulting SQL is functional. :param selectable: a table or subquery that will be used in place of the generated FROM clause. This argument is required if any of the desired classes use concrete table inheritance, since SQLAlchemy currently cannot generate UNIONs among tables automatically. If used, the ``selectable`` argument must represent the full set of tables and columns mapped by every mapped class. Otherwise, the unaccounted mapped columns will result in their table being appended directly to the FROM clause which will usually lead to incorrect results. :param polymorphic_on: a column to be used as the "discriminator" column for the given selectable. If not given, the polymorphic_on attribute of the base classes' mapper will be used, if any. This is useful for mappings that don't have polymorphic loading behavior by default. :param innerjoin: if True, an INNER JOIN will be used. This should only be specified if querying for one specific subtype only rez[the 'flat' and 'selectable' arguments cannot be passed simultaneously to with_polymorphic()cSsg|] }|jqSr4)rrr4r4r9r:)sz$with_polymorphic..) innerjoinr!)rrrr) rrArBrrrZto_setr>runionZ_with_polymorphic_argsrr) rclassesrrrr#r$rZ_existing_aliasZprimary_mapperZ new_classesZmappersr4r4r9with_polymorphics:@     r'c@seZdZdZdZdZdZdZdZe Z ddZ e ddZe dd Ze d d Zd Zd Zd dZddZe ddZddZddZd S)BundleaHA 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. .. versionadded:: 0.9.0 .. seealso:: :ref:`bundles` FTcs\|__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#ColumnsClauseRole)r7exprrPr4r9r:us z#Bundle.__init__..css |]}t|d|j|fVqdS)rcN)r_label)r7rr4r4r9r|sz"Bundle.__init__..cSsg|]}|jd|qSbundlerrr7er4r4r9r:~s single_entityN)rr+exprsr&rRcolumnsrr1)rNrr2rr4rPr9rbs    zBundle.__init__cCs|jdjddS)Nrrr2rrrPr4r4r9rsz Bundle.mappercCs|jdjddS)Nrrr4rPr4r4r9rsz Bundle.entitycCs|jSr^)rRrPr4r4r9rszBundle.entity_namespaceNcCs |j|j}|j|j|Sr^) __class__rJrrE)rNclonedr4r4r9_clonesz Bundle._clonecCs^||d}||j|jdjd|j}tjdd|jDtj dd | d|d S) N)r-rrrcSsg|]}|jd|qSr,r.r/r4r4r9r:sz-Bundle.__clause_element__..F)Z_literal_as_text_rolegrouprr) rErr2_propagate_attrsrrr!Z ClauseListr#r)rr)rN annotationsrr4r4r9rs$    zBundle.__clause_element__cCs |jSr^)rclausesrPr4r4r9r;szBundle.clausescCs|}||_|S)z.csfddDS)Ncsg|] }|qSr4r4)r7procrr4r9r:sz=Bundle.create_row_processor..proc..r4r>Z keyed_tupleprocsr>r9r=sz)Bundle.create_row_processor..procr)rNqueryr@labelsr=r4r?r9create_row_processors zBundle.create_row_processor)rWrXrYrZr1Zis_clause_elementZ is_mapperrZ is_bundlerZ immutabledictr9rrrrrr3rRr7rr;rrCr4r4r4r9r(>s,     r(cCst|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)rZ_deep_annotate)r"excluder4r4r9 _orm_annotatesrFcCstj|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. )rDr)rMrZ_deep_deannotater"r4r4r9_orm_deannotates rIcCs t|Sr^rGrHr4r4r9_orm_full_deannotatesrJc@sBeZdZdZejjZdZdddZdd Z dd d Z dd d Z dS)_ORMJoinz/Extend Join to support ORM constructs as input.TNFr4c Cst|} t|} | j} ||_||_t|d| } | |_t|tj rPt| j |}t|t j rx|j } |j}||j7}nt|tr|}|jj} nd}|r| j}t| |r| }n|}|j|| d| d|d\}}}}}}|dk r|rt|||}|}nt||||}|}n|}||_tj|||||||st| ddr| jjr| jj}|dk r| jrt| j !|}|j"|@|_"dS)N_joined_from_infoT)Zsource_selectableZdest_selectableZsource_polymorphicZof_type_entityZalias_secondaryZextra_criteriar)#rrr _left_memo _right_memorrLr;rr<rrQueryableAttributeZ comparatorZ_source_selectabler_extra_criteriarparentrZclause_is_presentZ _create_joinsrrCZ_target_adapterr!JoinrrZsingleZ_single_table_criterionrrrr)rNleftrightrisouterfullrMrNrPZ left_infoZ right_infoZadapt_toZ left_orm_infoZ on_selectablepropZleft_selectableZ adapt_fromZpjZsjsourcedestZ secondaryZtarget_adapterZ single_critr4r4r9rsr                z_ORMJoin.__init__cCs`|}t|tjr|j}q|j|ks&tt|j|j|j|j|j |j d}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) )rUrMrN)rUrN) r;rrRrSrTrrKrrUrMrN)rNotherZleftmostrSr4r4r9_splice_into_centerds&  z_ORMJoin._splice_into_centercCst|||||dS)N)rVrUrK)rNrTrrUrV join_to_leftr4r4r9rCsz _ORMJoin.joincCst|||d|dS)NT)rUrVr\)rNrTrrVr]r4r4r9 outerjoinsz_ORMJoin.outerjoin)NFFNNr4)NFFN)NFN) rWrXrYrZr!rRZ__visit_name__Z inherit_cacherr[rCr^r4r4r4r9rKs" \  rKcCst|||||S)aProduce an inner join between left and right clauses. :func:`_orm.join` is an extension to the core join interface provided by :func:`_expression.join()`, where the left and right selectables may be not only core selectable objects such as :class:`_schema.Table`, but also mapped classes or :class:`.AliasedClass` instances. The "on" clause can be a SQL expression, or an attribute or string name referencing a configured :func:`_orm.relationship`. :func:`_orm.join` is not commonly needed in modern usage, as its functionality is encapsulated within that of the :meth:`_query.Query.join` method, which features a significant amount of automation beyond :func:`_orm.join` by itself. Explicit usage of :func:`_orm.join` with :class:`_query.Query` involves usage of the :meth:`_query.Query.select_from` method, as in:: from sqlalchemy.orm import join session.query(User).\ select_from(join(User, Address, User.addresses)).\ filter(Address.email_address=='foo@bar.com') In modern SQLAlchemy the above join can be written more succinctly as:: session.query(User).\ join(User.addresses).\ filter(Address.email_address=='foo@bar.com') See :meth:`_query.Query.join` for information on modern usage of ORM level joins. .. deprecated:: 0.8 the ``join_to_left`` parameter is deprecated, and will be removed in a future release. The parameter has no effect. r\)rSrTrrUrVr]r4r4r9rCs*rCcCst|||d|S)aProduce a left outer join between left and right clauses. This is the "outer join" version of the :func:`_orm.join` function, featuring the same behavior except that an OUTER JOIN is generated. See that function's documentation for other usage details. Tr\)rSrTrrVr]r4r4r9r^sr^cCsZt|tjr.tdt|}t|j|j}nt|tj rL|j rF|j }|j}|j ||dS)aCreate 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, Address.user)) 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: String property name, or class-bound attribute, which indicates what relationship from the instance should be used to reconcile the parent/child relationship. .. deprecated:: 1.4 Using strings is deprecated and will be removed in SQLAlchemy 2.0. Please use the class-bound attribute directly. :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 zUsing strings to indicate relationship names in the ORM with_parent() function is deprecated and will be removed SQLAlchemy 2.0. Please use the class-bound attribute directly.) from_entity) r;rr<warn_deprecated_20r rrrrrOZ_of_typeZ _with_parent)rrWr_rr4r4r9 with_parents6  racCst|}|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_identityZobject_rar4r4r9rc s rccCst|}|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` )rrb was_deletedrdr4r4r9res recCsL|jr$|jr ||kr dSdS|jrB|jr:||jkS||kS||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)rrrr common_parentgivenrr4r4r9_entity_corresponds_to.s ricCsL|jr&|jo$|j o$||kp$||jkS|js8||jS|joF||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)rrrrfrrrgr4r4r9$_entity_corresponds_to_use_path_implBs rjcCs:|jr||jkp|j|S|jr,||jkS||SdS)zedetermine if 'given' "is a" mapper, in terms of the given would load rows of type 'mapper'. N)rrrr)rhrr4r4r9 _entity_isaes rkcCsRddlm}m}m}m}ddlm}ddlm}||_ |_ |_ |_ |_ dS)aZUse random-ordering sets within the unit of work in order to detect unit of work sorting issues. This is a utility function that can be used to help reproduce inconsistent unit of work sorting issues. For example, if two kinds of objects A and B are being inserted, and B has a foreign key reference to A - the A must be inserted first. However, if there is no relationship between A and B, the unit of work won't know to perform this sorting, and an operation may or may not fail, depending on how the ordering works out. Since Python sets and dictionaries have non-deterministic ordering, such an issue may occur on some runs and not on others, and in practice it tends to have a great dependence on the state of the interpreter. This leads to so-called "heisenbugs" where changing entirely irrelevant aspects of the test program still cause the failure behavior to change. By calling ``randomize_unitofwork()`` when a script first runs, the ordering of a key series of sets within the unit of work implementation are randomized, so that the script can be minimized down to the fundamental mapping and operation that's failing, while still reproducing the issue on at least some runs. This utility is also available when running the test suite via the ``--reversetop`` flag. r) unitofworksessionr dependency) topological) RandomSetN) Zsqlalchemy.ormrlrmrrnZsqlalchemy.utilroZsqlalchemy.testing.utilrpr>)rlrmrrnrorpr4r4r9randomize_unitofworkts  rqcsfdd}t|trt|\}}}t|trJt|trJ||dkrJgSt|tr\|dksnt|tr|dkr|t||S|||}|dk rt|dd|jSt|Sn2|dkr|t|dSt|||ddSdS)zdcalculate __getitem__ in terms of an iterable query object that also has a slice() method. csstdn tddS)Nz@negative indexes are not accepted by SQL index / slice operatorszSupport for negative indexes for SQL index / slice operators will be removed in 2.0; these operators fetch the complete result and do not work efficiently.) IndexErrorrr`r4allow_negativer4r9_no_negative_indexessz&_getitem.._no_negative_indexesrNr)r;slicerZ decode_sliceintrstep)Ziterable_queryitemrtrustartstopryresr4rsr9_getitems2       r~)r}T)NNFF)FFNFFFN)N)NFFN)NFN)N)PrTrrrSrrrrrrrr r r r r rrZ interfacesrrrrrrZ path_registryrrrrArrrZ engine.resultrZsql_baser r!r"r#rr$Zsql.annotationr%Zsql.baser&rIr[r/r|rrrrrrZMemoizedHasCacheKeyrrr Z _inspectsr#r'Z_self_inspectsr(rFrIrJrRrKrCr^rarcrerirjrkrqr~r4r4r4r9 s                                   BC Rh'2  a n a'  - F#$