U kf]M@s<UdZddlmZddlZddlmZddlmZddlmZddlmZddlmZdd lm Z dd lm Z dd lm Z dd lm Z dd lm Z ddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%dd lm&Z&dd!lm'Z'd"d#lm(Z)d"d$lm*Z*d"dlmZd"d%l+m,Z,d"d&l+m-Z-d"d'l+m.Z.d"d(l+m/Z/d"d)l+m0Z0d"d*l+m1Z1d"d+l2m3Z3d"d,l4m5Z5d"d-l4m6Z6d"d.l4m7Z7d/Z8d0e9d1<d2Z:d3e9d4<ed5d6d7Z;ej<rdd8lm=Z=dd9lm>Z>dd:l?m@Z@dd;l?mAZAddlmDZDdd?lmEZEdd@lFmGZGddAlmHZHd"dBlImJZJd"dClImKZKd"dDlLmMZMd"dElLmNZNee6dFdGfZOe6dHZPeeQefZReeQefZSe eOdIfZTGdJdKdKe0jUeZVGdLdMdMeVZWGdNdOdOeVZXGdPdQdQe-jYe0jZe1j[Z\GdRdSdSe\Z]GdTdUdUe\Z^GdVdWdWe\Z_dXdYdZd[dKd\d]d^Z`d_d`dadbdcZad5d5dddedfZbebd_d[dKdgdhdiZcebdjdkd_dZdKdldmdnZdebd_d[dKdgdodpZeebd_dKdqdrdsZfebddtd_dudKdvdwdxZgebd_dKdqdydzZhebddtd_dudKdvd{d|Ziebd_dKdqd}d~Zjebd_d[dKdgddZkebd_dKdqddZlebdjdkd_d_dZdKdddZmebd_d_dKdddZnebddKdddZoebd_ddKdddZpebdddKdddZqddZrdS)z ) annotationsN)Any)Callable)cast)Dict)Iterable)Optional)overload)Sequence)Tuple)Type)TypeVar)Union)util)insp_is_aliased_class)insp_is_attribute)insp_is_mapper)insp_is_mapper_property)QueryableAttribute)InspectionAttr) LoaderOption)_DEFAULT_TOKEN) _StrPathToken)_WILDCARD_TOKEN)AbstractEntityRegistry)path_is_property) PathRegistry) TokenRegistry)_orm_full_deannotate) AliasedInsp)excinspect)and_) cache_key) coercions)roles) traversals)visitors) _generative)Final)Literal)Self relationshipzFinal[Literal['relationship']]_RELATIONSHIP_TOKENcolumnzFinal[Literal['column']] _COLUMN_TOKEN_FNzCallable[..., Any])bound) _EntityType)_InternalEntityType) _MapperEntity)ORMCompileState) QueryContext) _StrategyKey)MapperProperty) ORMOption)Mapper)_PathRepresentation)_ColumnExpressionArgument)_FromClauseArgument)_CacheKeyTraversalType)CacheKey*zQueryableAttribute[Any])r/r1.c @sfeZdZUdZdZded<drddddd d d d Zdd ddd dddZdsddd dddZdd dddZ dtddd dddZ dd dddZ duddd dddZ dd dd d!Z dvddd d"d#d$Zdd dd%d&Zdwddd d'd(d)Zdd d*d+d,Zd-d d.d/d0Zdd1d d2d3d4Zd5d d6d7d8Zed9d:d;dd?d;d@d=ZdAdBd;dCd=ZedxddAddDdd dEdFdGZedydHdAdDdId dJdKdLZedzdHd9dd dMdNdOZed9dPd dQdRdSZdTd?dUdVdWZdd dXdYdZZd{d[dBd\dDd]dddId d^ d_d`Zdadbd?dcdddeZdad?dfdgdhZ dadbdd?didjdkZ!e"d|dldmddndodpdqZ#dS)} _AbstractLoad)propagate_to_loadersTboolrENF _AttrTypezOptional[_FromClauseArgument]r.)attralias _is_chain_propagate_to_loadersreturncCs|dk r6t|ts"ttj|}qrtjddd|}n Address``, specify subquery loading for the ``User.addresses`` collection, but on each ``Address`` object load only the ``email_address`` attribute:: session.query(User).options( subqueryload(User.addresses).load_only(Address.email_address) ) For a statement that has multiple entities, the lead entity can be specifically referred to using the :class:`_orm.Load` constructor:: stmt = ( select(User, Address) .join(User.addresses) .options( Load(User).load_only(User.name, User.fullname), Load(Address).load_only(Address.email_address), ) ) When used together with the :ref:`populate_existing ` execution option only the attributes listed will be refreshed. :param \*attrs: Attributes to be loaded, all others will be deferred. :param raiseload: raise :class:`.InvalidRequestError` rather than lazy loading a value when a deferred attribute is accessed. Used to prevent unwanted SQL from being emitted. .. versionadded:: 2.0 .. seealso:: :ref:`orm_queryguide_column_deferral` - in the :ref:`queryguide_toplevel` :param \*attrs: Attributes to be loaded, all others will be deferred. :param raiseload: raise :class:`.InvalidRequestError` rather than lazy loading a value when a deferred attribute is accessed. Used to prevent unwanted SQL from being emitted. .. versionadded:: 2.0 FTdeferredZ instrumentrb)rC_set_column_strategy)r\rbrdr]Zwildcard_strategyr^r^r_ load_onlys< z_AbstractLoad.load_onlyOptional[bool])rH innerjoinrLcCs*|j|ddi|dk rd|intjd}|S)a; Indicate that the given attribute should be loaded using joined eager loading. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. examples:: # joined-load the "orders" collection on "User" select(User).options(joinedload(User.orders)) # joined-load Order.items and then Item.keywords select(Order).options( joinedload(Order.items).joinedload(Item.keywords) ) # lazily load Order.items, but when Items are loaded, # joined-load the keywords collection select(Order).options( lazyload(Order.items).joinedload(Item.keywords) ) :param innerjoin: if ``True``, indicates that the joined eager load should use an inner join instead of the default of left outer join:: select(Order).options(joinedload(Order.user, innerjoin=True)) In order to chain multiple eager joins together where some may be OUTER and others INNER, right-nested joins are used to link them:: select(A).options( joinedload(A.bs, innerjoin=False).joinedload( B.cs, innerjoin=True ) ) The above query, linking A.bs via "outer" join and B.cs via "inner" join would render the joins as "a LEFT OUTER JOIN (b JOIN c)". When using older versions of SQLite (< 3.7.16), this form of JOIN is translated to use full subqueries as this syntax is otherwise not directly supported. The ``innerjoin`` flag can also be stated with the term ``"unnested"``. This indicates that an INNER JOIN should be used, *unless* the join is linked to a LEFT OUTER JOIN to the left, in which case it will render as LEFT OUTER JOIN. For example, supposing ``A.bs`` is an outerjoin:: select(A).options( joinedload(A.bs).joinedload(B.cs, innerjoin="unnested") ) The above join will render as "a LEFT OUTER JOIN b LEFT OUTER JOIN c", rather than as "a LEFT OUTER JOIN (b JOIN c)". .. note:: The "unnested" flag does **not** affect the JOIN rendered from a many-to-many association table, e.g. a table configured as :paramref:`_orm.relationship.secondary`, to the target table; for correctness of results, these joins are always INNER and are therefore right-nested if linked to an OUTER join. .. note:: The joins produced by :func:`_orm.joinedload` are **anonymously aliased**. The criteria by which the join proceeds cannot be modified, nor can the ORM-enabled :class:`_sql.Select` or legacy :class:`_query.Query` refer to these joins in any way, including ordering. See :ref:`zen_of_eager_loading` for further detail. To produce a specific SQL JOIN which is explicitly available, use :meth:`_sql.Select.join` and :meth:`_query.Query.join`. To combine explicit JOINs with eager loading of collections, use :func:`_orm.contains_eager`; see :ref:`contains_eager`. .. seealso:: :ref:`loading_toplevel` :ref:`joined_eager_loading` rQrRNrkrS)r[r EMPTY_DICT)r\rHrkloaderr^r^r_ joinedloadsW  z_AbstractLoad.joinedloadrHrLcCs||ddiS)aIndicate that the given attribute should be loaded using subquery eager loading. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. examples:: # subquery-load the "orders" collection on "User" select(User).options(subqueryload(User.orders)) # subquery-load Order.items and then Item.keywords select(Order).options( subqueryload(Order.items).subqueryload(Item.keywords) ) # lazily load Order.items, but when Items are loaded, # subquery-load the keywords collection select(Order).options( lazyload(Order.items).subqueryload(Item.keywords) ) .. seealso:: :ref:`loading_toplevel` :ref:`subquery_eager_loading` rQZsubqueryr[r\rHr^r^r_ subqueryloadUsz_AbstractLoad.subqueryload Optional[int])rHrecursion_depthrLcCs|j|ddid|idS)aIndicate that the given attribute should be loaded using SELECT IN eager loading. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. examples:: # selectin-load the "orders" collection on "User" select(User).options(selectinload(User.orders)) # selectin-load Order.items and then Item.keywords select(Order).options( selectinload(Order.items).selectinload(Item.keywords) ) # lazily load Order.items, but when Items are loaded, # selectin-load the keywords collection select(Order).options( lazyload(Order.items).selectinload(Item.keywords) ) :param recursion_depth: optional int; when set to a positive integer in conjunction with a self-referential relationship, indicates "selectin" loading will continue that many levels deep automatically until no items are found. .. note:: The :paramref:`_orm.selectinload.recursion_depth` option currently supports only self-referential relationships. There is not yet an option to automatically traverse recursive structures with more than one relationship involved. Additionally, the :paramref:`_orm.selectinload.recursion_depth` parameter is new and experimental and should be treated as "alpha" status for the 2.0 series. .. versionadded:: 2.0 added :paramref:`_orm.selectinload.recursion_depth` .. seealso:: :ref:`loading_toplevel` :ref:`selectin_eager_loading` rQZselectinrurlrq)r\rHrur^r^r_ selectinloadvs 4z_AbstractLoad.selectinloadcCs||ddiS)a<Indicate that the given attribute should be loaded using "lazy" loading. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. .. seealso:: :ref:`loading_toplevel` :ref:`lazy_loading` rQselectrqrrr^r^r_lazyloadsz_AbstractLoad.lazyloadcCs|j|ddid|id}|S)aIndicate that the given attribute should be loaded using an immediate load with a per-attribute SELECT statement. The load is achieved using the "lazyloader" strategy and does not fire off any additional eager loaders. The :func:`.immediateload` option is superseded in general by the :func:`.selectinload` option, which performs the same task more efficiently by emitting a SELECT for all loaded objects. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. :param recursion_depth: optional int; when set to a positive integer in conjunction with a self-referential relationship, indicates "selectin" loading will continue that many levels deep automatically until no items are found. .. note:: The :paramref:`_orm.immediateload.recursion_depth` option currently supports only self-referential relationships. There is not yet an option to automatically traverse recursive structures with more than one relationship involved. .. warning:: This parameter is new and experimental and should be treated as "alpha" status .. versionadded:: 2.0 added :paramref:`_orm.immediateload.recursion_depth` .. seealso:: :ref:`loading_toplevel` :ref:`selectin_eager_loading` rQZ immediaterurlrq)r\rHrurnr^r^r_ immediateloads *z_AbstractLoad.immediateloadcCs||ddiS)aIndicate that the given relationship attribute should remain unloaded. The relationship attribute will return ``None`` when accessed without producing any loading effect. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. :func:`_orm.noload` applies to :func:`_orm.relationship` attributes only. .. legacy:: The :func:`_orm.noload` option is **legacy**. As it forces collections to be empty, which invariably leads to non-intuitive and difficult to predict results. There are no legitimate uses for this option in modern SQLAlchemy. .. seealso:: :ref:`loading_toplevel` rQnoloadrqrrr^r^r_rzsz_AbstractLoad.noload)rHsql_onlyrLcCs||d|rdndiS)aIndicate that the given attribute should raise an error if accessed. A relationship attribute configured with :func:`_orm.raiseload` will raise an :exc:`~sqlalchemy.exc.InvalidRequestError` upon access. The typical way this is useful is when an application is attempting to ensure that all relationship attributes that are accessed in a particular context would have been already loaded via eager loading. Instead of having to read through SQL logs to ensure lazy loads aren't occurring, this strategy will cause them to raise immediately. :func:`_orm.raiseload` applies to :func:`_orm.relationship` attributes only. In order to apply raise-on-SQL behavior to a column-based attribute, use the :paramref:`.orm.defer.raiseload` parameter on the :func:`.defer` loader option. :param sql_only: if True, raise only if the lazy load would emit SQL, but not if it is only checking the identity map, or determining that the related value should just be None due to missing keys. When False, the strategy will raise for all varieties of relationship loading. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. .. seealso:: :ref:`loading_toplevel` :ref:`prevent_lazy_with_raiseload` :ref:`orm_queryguide_deferred_raiseload` rQZ raise_on_sqlraiserq)r\rHr{r^r^r_rb s"z_AbstractLoad.raiseloadcCs ||dS)aIndicate an attribute should load using its predefined loader style. The behavior of this loading option is to not change the current loading style of the attribute, meaning that the previously configured one is used or, if no previous style was selected, the default loading will be used. This method is used to link to other loader options further into a chain of attributes without altering the loader style of the links along the chain. For example, to set joined eager loading for an element of an element:: session.query(MyClass).options( defaultload(MyClass.someattribute).joinedload( MyOtherClass.someotherattribute ) ) :func:`.defaultload` is also useful for setting column-level options on a related class, namely that of :func:`.defer` and :func:`.undefer`:: session.scalars( select(MyClass).options( defaultload(MyClass.someattribute) .defer("some_column") .undefer("some_other_column") ) ) .. seealso:: :ref:`orm_queryguide_relationship_sub_options` :meth:`_orm.Load.options` Nrqrrr^r^r_ defaultload1s%z_AbstractLoad.defaultload)keyrbrLcCs$ddd}|rd|d<||f|S)aIndicate that the given column-oriented attribute should be deferred, e.g. not loaded until accessed. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. e.g.:: from sqlalchemy.orm import defer session.query(MyClass).options( defer(MyClass.attribute_one), defer(MyClass.attribute_two) ) To specify a deferred load of an attribute on a related class, the path can be specified one token at a time, specifying the loading style for each link along the chain. To leave the loading style for a link unchanged, use :func:`_orm.defaultload`:: session.query(MyClass).options( defaultload(MyClass.someattr).defer(RelatedClass.some_column) ) Multiple deferral options related to a relationship can be bundled at once using :meth:`_orm.Load.options`:: select(MyClass).options( defaultload(MyClass.someattr).options( defer(RelatedClass.some_column), defer(RelatedClass.some_other_column), defer(RelatedClass.another_column) ) ) :param key: Attribute to be deferred. :param raiseload: raise :class:`.InvalidRequestError` rather than lazy loading a value when the deferred attribute is accessed. Used to prevent unwanted SQL from being emitted. .. versionadded:: 1.4 .. seealso:: :ref:`orm_queryguide_column_deferral` - in the :ref:`queryguide_toplevel` :func:`_orm.load_only` :func:`_orm.undefer` Trerbrg)r\r~rbstrategyr^r^r_deferXs7 z_AbstractLoad.defer)r~rLcCs||fdddS)aIndicate that the given column-oriented attribute should be undeferred, e.g. specified within the SELECT statement of the entity as a whole. The column being undeferred is typically set up on the mapping as a :func:`.deferred` attribute. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. Examples:: # undefer two columns session.query(MyClass).options( undefer(MyClass.col1), undefer(MyClass.col2) ) # undefer all columns specific to a single class using Load + * session.query(MyClass, MyOtherClass).options( Load(MyClass).undefer("*") ) # undefer a column on a related object select(MyClass).options( defaultload(MyClass.items).undefer(MyClass.text) ) :param key: Attribute to be undeferred. .. seealso:: :ref:`orm_queryguide_column_deferral` - in the :ref:`queryguide_toplevel` :func:`_orm.defer` :func:`_orm.undefer_group` FTrerg)r\r~r^r^r_undefers(z_AbstractLoad.undeferrVnamerLcCs|tfdd|diS)a$Indicate that columns within the given deferred group name should be undeferred. The columns being undeferred are set up on the mapping as :func:`.deferred` attributes and include a "group" name. E.g:: session.query(MyClass).options(undefer_group("large_attrs")) To undefer a group of attributes on a related entity, the path can be spelled out using relationship loader options, such as :func:`_orm.defaultload`:: select(MyClass).options( defaultload("someattr").undefer_group("large_attrs") ) .. seealso:: :ref:`orm_queryguide_column_deferral` - in the :ref:`queryguide_toplevel` :func:`_orm.defer` :func:`_orm.undefer` NZundefer_group_T)rhr)r\rr^r^r_ undefer_groups  z_AbstractLoad.undefer_group_ColumnExpressionArgument[Any]r~ expressionrLcCs*tttj|}|j|fddi|fdS)aApply an ad-hoc SQL expression to a "deferred expression" attribute. This option is used in conjunction with the :func:`_orm.query_expression` mapper-level construct that indicates an attribute which should be the target of an ad-hoc SQL expression. E.g.:: stmt = select(SomeClass).options( with_expression(SomeClass.x_y_expr, SomeClass.x + SomeClass.y) ) .. versionadded:: 1.2 :param key: Attribute to be populated :param expr: SQL expression to be applied to the attribute. .. seealso:: :ref:`orm_queryguide_with_expression` - background and usage examples Zquery_expressionT)extra_criteria)rr'rWr(ZLabeledColumnExprRolerh)r\r~rr^r^r_with_expressions z_AbstractLoad.with_expressionIterable[Type[Any]])classesrLcCs0|jddidttdd|Dtdid}|S)aIndicate an eager load should take place for all attributes specific to a subclass. This uses an additional SELECT with IN against all matched primary key values, and is the per-query analogue to the ``"selectin"`` setting on the :paramref:`.mapper.polymorphic_load` parameter. .. versionadded:: 1.2 .. seealso:: :ref:`polymorphic_selectin` Zselectinload_polymorphicTentitiescss|]}t|VqdSNr#).0clsr^r^r_ sz5_AbstractLoad.selectin_polymorphic..)r~rl)_set_class_strategytuplesortedid)r\rr^r^r_selectin_polymorphicsz"_AbstractLoad.selectin_polymorphic _StrategySpecr:)rrLcCsdSrr^r\rr^r^r_ _coerce_strat!sz_AbstractLoad._coerce_stratz Literal[None]NonecCsdSrr^rr^r^r_r$szOptional[_StrategySpec]Optional[_StrategyKey]cCs"|dk rtt|}nd}|Sr)rritems)r\r strategy_keyr^r^r_r'sOptional[_OptsType])rHrrErSrTrLcCs&||}|j|f|t|||d|S)N)rSrEreconcile_to_other)r_clone_for_bind_strategyr0)r\rHrrErSrTrr^r^r_r[0s z(_AbstractLoad._set_relationship_strategyTuple[_AttrType, ...]Optional[Tuple[Any, ...]])rdrrSrrLcCs$||}|j||t|||d|S)N)rS attr_groupr)rrr2)r\rdrrSrrr^r^r_rhEs z"_AbstractLoad._set_column_strategy)rdrrTrLcCs"||}|j||dd|d|S)NT)rErrr)r\rdrrTrr^r^r__set_generic_strategyYs z#_AbstractLoad._set_generic_strategy _OptsType)rrSrLcCs ||}|jd|d|d|S)Nrlr)r\rrSrr^r^r_rjs z!_AbstractLoad._set_class_strategyLoadparentrLcCs tdS)zapply this :class:`_orm._AbstractLoad` object as a sub-option o a :class:`_orm.Load` object. Implementation is provided by subclasses. NNotImplementedErrorr\rr^r^r__apply_to_parentssz_AbstractLoad._apply_to_parentrSrLcGs tdS)zApply a series of options as sub-options to this :class:`_orm._AbstractLoad` object. Implementation is provided by subclasses. Nrr\rSr^r^r_options|sz_AbstractLoad.optionsOptional[Tuple[_AttrType, ...]]Optional[_WildcardKeyType]Optional[_AttrGroupType] rdr wildcard_keyrSrrErrrLc Cs tdSrr) r\rdrrrSrrErrr^r^r_rs z&_AbstractLoad._clone_for_bind_strategyr8Sequence[_MapperEntity]) compile_statemapper_entitiesrLcCs&|jjs dS|||t|j dSr)compile_options_enable_eagerloads_processrF current_path)r\rrr^r^r_'process_compile_state_replaced_entitiess z5_AbstractLoad.process_compile_state_replaced_entities)rrLcCs2|jjs dS|||jt|j o*|jj dSr)rrrZ_lead_mapper_entitiesrFr_for_refresh_state)r\rr^r^r_process_compile_states z#_AbstractLoad.process_compile_staterrraiseerrrLcCs tdS)zimplemented by subclassesNr)r\rrrr^r^r_rsz_AbstractLoad._processr>rzOptional[_PathRepresentation])to_choppathdebugrLcCsd}tt||jD]\}\}}t|tr||dkrZ|dtsR|dtrZ|S|tdtkr|||j kr|dS||krqqt|t rt |rt |r| |rqqdSq||ddS)Nr:r) enumeratezip natural_pathrUrVendswithrrr0r~rrZisa)rrrriZc_tokenZp_tokenr^r^r_ _chop_paths:  z_AbstractLoad._chop_path)NFF)N)N)N)F)F)TNN)NN)N)NNTNN)F)$__name__ __module__ __qualname__ __slots__Z_is_strategy_option__annotations__r`rirorsrvrxryrzrbr}rrrrrr rr+r[rhrrrrrrrr classmethodrr^r^r^r_rDZsr HNb$:1&'<,!'     rDc @s0eZdZUdZdZdejjfdejj fdejj fdejj fgZ dZ de d<d e d<d e d<d d d dZddddZedddddZddddddZdddddZddddd Zd!d"Zd#d$d%d&d'd(d)Zdd&d*d+d,Zed-d.d/d0d1ZdAd3d4d5d6d7d%d8d9d.d: d;d<Zd=d>Zd?d@ZdS)BraRepresents loader options which modify the state of a ORM-enabled :class:`_sql.Select` or a legacy :class:`_query.Query` in order to affect how various mapped attributes are loaded. The :class:`_orm.Load` object is in most cases used implicitly behind the scenes when one makes use of a query option like :func:`_orm.joinedload`, :func:`_orm.defer`, or similar. It typically is not instantiated directly except for in some very specific cases. .. seealso:: :ref:`orm_queryguide_relationship_per_entity_wildcard` - illustrates an example where direct use of :class:`_orm.Load` may be useful )rcontextadditional_source_entitiesrrrErNrzTuple[_LoadElement, ...]z$Tuple[_InternalEntityType[Any], ...]_EntityType[Any])entitycCs2tdt|}|j|j|_d|_d|_d|_dS)Nz$Union[Mapper[Any], AliasedInsp[Any]]r^F)rr$Z _post_inspect_path_registryrrrEr)r\rinspr^r^r___init__s z Load.__init__rVrLcCsd|jddS)NLoad(r)rr\r^r^r___str__sz Load.__str__rrrLcCs&||}||_d|_d|_d|_|S)Nr^F)__new__rrrEr)rrloadr^r^r__construct_for_existing_paths  z!Load._construct_for_existing_pathr9r<)r uncached_optrLcCs||kr |S||Sr)_adjust_for_extra_criteria)r\rrr^r^r_'_adapt_cached_option_to_uncached_optionsz,Load._adapt_cached_option_to_uncached_optioncs&|}tfdd|jD|_|S)Nc3s|]}|VqdSr) _prepend_path)relementrr^r_r'sz%Load._prepend_path..)_clonerrr\rr]r^rr_r%s   zLoad._prepend_path)rrLcs|jD]}|jrqq|S|jdkr0|S|jj}|dk sLtddddddd|}tfdd|jD|_|S) zApply the current bound parameters in a QueryContext to all occurrences "extra_criteria" stored within this ``Load`` object, returning a new instance of this ``Load`` object. N _LoadElementrB)optreplacement_cache_keyorig_cache_keyrLcs(|}tfdd|jD|_|S)Nc3s|]}|VqdSr)_apply_params_to_element)rcritrrr^r_rLs zCLoad._adjust_for_extra_criteria..process..)rr_extra_criteria)rrrZ cloned_optr^rr_processEs  z0Load._adjust_for_extra_criteria..processc3s$|]}|jr|n|VqdSr)rrvaluerrrr^r_rVsz2Load._adjust_for_extra_criteria..) rrquery_generate_cache_keyrselect_statementrZrr)r\rr orig_queryr]r^rr_r,s    zLoad._adjust_for_extra_criteriacCs@|j}d}|D],}|j}|rt|td|dr|SqdS)zocalled at process time to allow adjustment of the root entity inside of _LoadElement objects. Nz_InternalEntityType[Any]r)r entity_zeroorm_util_entity_corresponds_tor)r\rrrezeroentr^r^r_!_reconcile_query_entities_with_us`s  z&Load._reconcile_query_entities_with_usr8rrFrrcCsF|||}t|jj}|jD]"}|r.|js.q||||||qdSr)rrFrZ _current_pathrrEr)r\rrrreconciled_lead_entityZhas_current_pathrnr^r^r_rts  z Load._processrcs|j|jksttfddjdfjDstjdkrbjd}jd}njd}jd}tj||t jddjdd_|j rt fdd|j D_ j rj j 7_ jj7_dS)zapply this :class:`_orm.Load` object as a sub-option of another :class:`_orm.Load` object. This method is used by the :meth:`_orm.Load.options` method. c3s"|]}t|jdVqdSrNr$_entity_corresponds_to_use_path_implr odd_elementrelem)r]r^r_rs  z(Load._apply_to_parent..rrrNc3s|]}|VqdSr)_prepend_path_fromr)rr^r_rs) Z _generaterErZanyrrrlen_raise_for_does_not_linkrcoercerr)r\rattrname parent_entityr^)r]rr_rs.      $  zLoad._apply_to_parentrDr.rc Gsb|D]X}z||Wqtk rZ}z&t|tsHtd|d|nW5d}~XYqXq|S)acApply a series of options as sub-options to this :class:`_orm.Load` object. E.g.:: query = session.query(Author) query = query.options( joinedload(Author.book).options( load_only(Book.summary, Book.excerpt), joinedload(Book.citations).options( joinedload(Citation.author) ) ) ) :param \*opts: A series of loader option objects (ultimately :class:`_orm.Load` objects) which should be applied to the path specified by this :class:`_orm.Load` object. .. versionadded:: 1.3.6 .. seealso:: :func:`.defaultload` :ref:`orm_queryguide_relationship_sub_options` zLoader option z2 is not compatible with the Load.options() method.N)rAttributeErrorrUrDsa_exc ArgumentError)r\rSrZaer^r^r_rs  z Load.optionsTrrrrrrjrrc Cs^|r d|_|jjrtdn>t|jr\|rF|jj|jj|dntd|jjd|dkrtj |jd|||||||d } | r|j | f7_ |dk st |j t d|d7_ n|D]} t| trtj |j| |||||||d } ntj |j| |||||||d } | r|tkr"| j|_|j | f7_ | jd d r| } |j | f7_ q|S) NT3Wildcard token cannot be followed by another entityrzMapped attribute 'z#' does not refer to a mapped entity)rrrzTuple[_InternalEntityType[Any]]rruF)rEris_tokenrrrpropZ_strategy_lookup_ClassStrategyLoadcreaterrZrrrUrV_TokenStrategyLoad_AttributeStrategyLoadr0 local_optsget_recurse) r\rdrrrSrrErr load_elementrHr1r^r^r_rs~        zLoad._clone_for_bind_strategycCs|}|j|d<|SNr_shallow_to_dictr serializer\dr^r^r_ __getstate__GszLoad.__getstate__cCs t|d|d<||dSrr deserialize_shallow_from_dictr\stater^r^r_ __setstate__LszLoad.__setstate__)NNTNN)rrr__doc__rr*ExtendedInternalTraversaldp_has_cache_keyInternalTraversalZdp_has_cache_key_listZ dp_boolean_traverse_internals_cache_key_traversalrrrrrrrrrrrr+rrr#r)r^r^r^r_rsF      4 '0 `rc@seZdZUdZdZdejjfdejjfdejjfgZ dZ de d<d e d<d e d<d e d<d Z d dddZ d,ddZdddddZdd dddZddZdd d!d"d#d$d%Zd&dd'd(Zd&d d)d*d+ZdS)- _WildcardLoadz)represent a standalone '*' load operation)rrrrrrNrAcache_key_traversalrrzUnion[Tuple[()], Tuple[str]]FrrcCsd|_d|_tj|_dS)Nr^)rrrrmrrr^r^r_resz_WildcardLoad.__init__Tc Csn|dk s t|d} |r.t| tr.| ttfks2t|d| } ||_| f|_|r^t||_ |dksjtdS)Nrr) rZrUrVrrrrr immutabledictr) r\rdrrrSrrErrrHr^r^r_rjs   z&_WildcardLoad._clone_for_bind_strategyrDr.rcGs tddS)Nz(Star option does not support sub-optionsrrr^r^r_rsz_WildcardLoad.optionsrrcCs|js t|jd}|tr6|dddt}tt|j|}|j sRtt |d|j d|j |j}|j|f7_dS)aPapply this :class:`_orm._WildcardLoad` object as a sub-option of a :class:`_orm.Load` object. This method is used by the :meth:`_orm.Load.options` method. Note that :class:`_orm.WildcardLoad` itself can't have sub-options, but it may be used as the sub-option of a :class:`_orm.Load` object. rrN)rrZrrsplitrrrtokenrrrrrrEr)r\rrHeffective_pathrnr^r^r_rs     z_WildcardLoad._apply_to_parentc Cs|jj}|r|jsdSdd|D}|j}|j}|rX|||}|dkrLdS||ksXt|rht|dkslt|d} t| t st| || |} | sdS| } t| t stt j | j | |jd|j|j|d} | sdS| jjst| |||d|| S)NcSsg|] }|jqSr^)rrrr^r^r_ sz*_WildcardLoad._process..rr)r)rrrErrrrZr rUrV_find_entity_basestringrrrrrrr) r\rrr is_refreshrr start_pathnew_pathr4rZ path_elementrnr^r^r_rsN     z_WildcardLoad._processz"Iterable[_InternalEntityType[Any]]rVrFz"Optional[_InternalEntityType[Any]])rr4rrLc Cs|dtr^tt|dkrl|rltdddd|Ddddd|Dd n|trld }|D] }|S|rtd |d ndSdS) NrrzMCan't apply wildcard ('*') or load_only() loader option to multiple entities , css|]}t|VqdSr)rVr6r^r^r_rsz8_WildcardLoad._find_entity_basestring..z?. Specify loader options for each entity individually, such as css|]}d|dVqdS)rz).some_option('*')Nr^r6r^r^r_rs.FzFQuery has only expression-based entities - can't find property named "".)rrr listrrjoinr)r\rr4rrr^r^r_r8s&   z%_WildcardLoad._find_entity_basestringDict[str, Any]cCs |}|Sr)rr!r^r^r_r# sz_WildcardLoad.__getstate__r(rLcCs||dSr)r&r'r^r^r_r) sz_WildcardLoad.__setstate__)NNTNN)rrrr*rr*r+ dp_plain_objdp_string_multi_dictr.r1rrErrrrrr8r#r)r^r^r^r_r0Qs4      =&r0c@seZdZUdZdZdZdejjfdejj fdejj fdej j fdej j fd ej j fgZ d Zd ed<d ed <d ed<ded<ded<ded<ded<ded<ddddZddZeddddZdddddZddddd Zd!dd"d#Zd!d$d%d&d'Zd(d)Zddd*d+d,d-Zd.d/Zd0d1Zd2d3ZedKdd5d d6d7ddd8d d9dd: d;d<Zd$dd=d>Zddd?d@Z dAddBdCdDZ!dddEdFdGZ"e#ddddHdIdJZ$d S)LraArepresents strategy information to select for a LoaderStrategy and pass options to it. :class:`._LoadElement` objects provide the inner datastructure stored by a :class:`_orm.Load` object and are also the object passed to methods like :meth:`.LoaderStrategy.setup_query`. .. versionadded:: 2.0 )rrrErrrTrrrrrrErTNzTuple[Any, ...]rjrrrFzutil.immutabledict[str, Any]is_token_strategyis_class_strategyintrcCst|Sr)rrr^r^r___hash__Bsz_LoadElement.__hash__cCs t||Sr)r)compare)r\otherr^r^r___eq__Esz_LoadElement.__eq__cCst|jo|jdkSr)rFrrrr^r^r_ is_opts_onlyHsz_LoadElement.is_opts_onlyr)kwrLcKs|j}||}|||Sr) __class__rZ_shallow_copy_to)r\rMrsr^r^r_rLs  z_LoadElement._clonecKs|}|j||_|Sr)rrunion)r\rMnewr^r^r_ _update_optsSsz_LoadElement._update_optsrAcCs|}|j|d<|Srrr!r^r^r_r#Xsz_LoadElement.__getstate__rrBcCs t|d|d<||dSrr$r'r^r^r_r)]sz_LoadElement.__setstate__c Csr|j}d}|D]}|j}|rd}q&q|sBtd|ddn,td|dddd d |Dd dS) NFTzGQuery has only expression-based entities; attribute loader options for rz can't be applied here.z Mapped class z@ does not apply to any of the root entities in this query, e.g. r<css|]}|jrt|jVqdSr)rrV)rxr^r^r_rtsz3_LoadElement._raise_for_no_match..zV. Please specify the full path from one of the root entities to the target attribute. )rrrrr@)r\ parent_loaderrrZfound_entitiesrrr^r^r__raise_for_no_matchas$  z _LoadElement._raise_for_no_matchOptional[PathRegistry])r5rrLcCsLt|j|}|sdSt|t|}|j|}t|f|dd}|S)areceives the 'current_path' entry from an :class:`.ORMCompileState` instance, which is set during lazy loads and secondary loader strategy loads, and adjusts the given path to be relative to the current_path. E.g. given a loader path and current path:: lp: User -> orders -> Order -> items -> Item -> keywords -> Keyword cp: User -> orders -> Order -> items The adjusted path would be:: Item -> keywords -> Keyword Nr)rrrr rrr )r\r5rZchopped_start_pathZtokens_removed_from_start_pathZloader_lead_path_elementr^r^r_'_adjust_effective_path_for_current_paths z4_LoadElement._adjust_effective_path_for_current_pathcCs tdS)zApply ORM attributes and/or wildcard to an existing path, producing a new path. This method is used within the :meth:`.create` method to initialize a :class:`._LoadElement` object. Nrr\rrHrrrrr^r^r_ _init_paths z_LoadElement._init_pathcCs tdS)zimplemented by subclasses.Nr)r\rTrrrrr^r^r__prepare_for_compile_states z'_LoadElement._prepare_for_compile_statecCsN||||||}|D]2}||jkr>t||j||j|<q||j|<qdS)z^populate ORMCompileState.attributes with loader state for this _LoadElement. N)rZ attributesr _reconcile)r\rTrrrrkeysr~r^r^r_rs   z"_LoadElement.process_compile_stateTz%Union[_AttrType, _StrPathToken, None]rrrr) rrHrrrrErrrrrLc Cs||} || _|| _|| _|r*t|ntj| _d| _| dk rH| | _ n|dkr\|s\d| _ nd| _ | |||||| }|s~dS| j |j kst || _| S)z+Create a new :class:`._LoadElement` object.r^NT)rrrrErr2rmrrrTrYrErrZ) rrrHrrrrErrrrrr^r^r_rs2  z_LoadElement.createcCs tdSrrrr^r^r_rsz_LoadElement.__init__cCs0|}t|jdd|jdd|_|S)N)rrr r)r\r]r^r^r_rs$z_LoadElement._recurserrcsVtfdd|jdf|jDsJtdjdd|jdd|jS)a%adjust the path of this :class:`._LoadElement` to be a subpath of that of the given parent :class:`_orm.Load` object's path. This is used by the :meth:`_orm.Load._apply_to_parent` method, which is in turn part of the :meth:`_orm.Load.options` method. c3s"|]}t|jdVqdSrrrrr^r_rs  z2_LoadElement._prepend_path_from..rz Attribute "rz" does not link from element "r>)rrrrrrrrr^rr_r s  z_LoadElement._prepend_path_fromrcCs^|}|j|jkst|j|jks(t|j|jks8tt|dd|jdd|_|S)Nrr)rrrZrrFrr rrr^r^r_r%s "z_LoadElement._prepend_path) replacementexistingrLcCs|jr |S|jdkr|S|jr"|S|jdkr0|S||kr<|S|j|jkrX|j|jkrX|S|jr|}|j|j|_|j|j7_|S|jr|}|j|j|_|j|j7_|S|jjr|St d|jddS)adefine behavior for when two Load objects are to be put into the context.attributes under the same key. :param replacement: ``_LoadElement`` that seeks to replace the existing one :param existing: ``_LoadElement`` that is already present. FzLoader strategies for z conflictN) rTrrrLrrPrrrrZInvalidRequestError)r_r`r^r^r_r\0sD     z_LoadElement._reconcile)TNNN)%rrrr*r__visit_name__r*r+r,rCrDr-Zdp_clauseelement_listr.r/rrHrKpropertyrLrrRr#r)rUrWrYrZrrrrrrr staticmethodr\r^r^r^r_rs\        &   &+ rcseZdZUdZdZdZejdej j fdej j fgZde d<de d<dZ dZd d Zd d Zd dZddZfddZfddZZS)rzLoader strategies against specific relationship or column paths. e.g.:: joinedload(User.addresses) defer(Order.name) selectinload(User.orders).lazyload(Order.items) )rP_path_with_polymorphic_pathZattribute_strategy_load_elementrPrdz*Union[Mapper[Any], AliasedInsp[Any], None]rVFc Cs|dk s td|_d|_t|\}}} |jrH|} || }|jrD|j}|S|jsVdsVtt |d|j s|r|r||dk rt dqt |t||j ndS|r|jrt||_n|j|_t|ddr|j} t| } | |_|j| |_|| | }n|| }|jr|j}|S)NFrrzCan't apply wildcard ('*') or load_only() loader option to multiple entities in the same option. Use separate options per entity.rP)rZrPrd_parse_attr_argumentZ is_property has_entityZ entity_pathZ is_attributerrrrrr rVrrYr$) r\rrHrrrrr_racZext_infor^r^r_rYsJ     z!_AttributeStrategyLoad._init_pathcCs>|jstd|jj}|j}|}|}||t|jS)aApply the current bound parameters in a QueryContext to the immediate "extra_criteria" stored with this Load object. Load objects are typically pulled from the cached version of the statement from a QueryContext. The statement currently being executed will have new values (and keys) for bound parameters in the extra criteria which need to be applied by loader strategies when they handle this criteria for a result set. z8this should only be called if _extra_criteria is present)rrZrrrrrr%)r\rrZ current_queryZk1Zk2r^r^r__generate_extra_criterias z/_AttributeStrategyLoad._generate_extra_criteriac Cs|js t|j}|st|js>ttjj|jj |jfddd}|j}|rd| ||}|dkr`dS|}d|j f}||kr||}|}| |} | ||<n|||<dS)NT)aliasedZ_use_mapper_pathZpath_with_polymorphic) rdrZrPis_aliased_classr$rr Z_with_polymorphic_factorymapperZ base_mapperrWrZ _merge_with) r\rrZpwpir:r;r~Zexisting_aliased_inspZthis_aliased_inspZnew_aliased_inspr^r^r__set_of_type_infos<   z(_AttributeStrategyLoad._set_of_type_infoc Cs|j}|jj}|jjrt|r(|js(gS|jr<||j ||j sL|j sLgS|r`|s`| |||jj rr|jj}n|j}|r|dk st|||}|dkrgSdtt|jfgSNrn)rrrrrrZrErPrmr[rrrUrfrrWrrr) r\rTrrrrrr9r5r^r^r_rZs.       z1_AttributeStrategyLoad._prepare_for_compile_statecsdt}d|d<|jr&|j|d<|jr`|jjr>d|d<n"|jjrT|jj|d<n ds`td|S)Nr^rrdrPFzunexpected object for _of_type) superr#rdr rPrkZ is_mapperclass_rZr!rNr^r_r#As   z#_AttributeStrategyLoad.__getstate__csVt||ddr*t|d|_nd|_|ddrLt|d|_nd|_dS)NrdrP)ror)rrr%rdr$rPr'rqr^r_r)Ys   z#_AttributeStrategyLoad.__setstate__)rrrr*rrarr.r*r+Zdp_multir,rrFrErYrirmrZr#r) __classcell__r^r^rqr_rjs&   G%", rc@s0eZdZdZdZdZdZdZddZddZ d S) raLoader strategies against wildcard attributes e.g.:: raiseload('*') Load(User).lazyload('*') defer('*') load_only(User.name, User.email) # will create a defer('*') joinedload(User.addresses).raiseload('*') Ztoken_strategy_load_elementTFcCsN|dk rJ|t}|ts |r@|r2|d|}||}|Std|S)NrkStrings are not accepted for attribute names in loader options; please use class-bound attributes directly.)rrrr4rr)r\rrHrrrrZ default_tokenr^r^r_rY|s  z_TokenStrategyLoad._init_pathc Cs|j}|jj}|jjst|r(|js(gS|js8|js8gS|j}|r\t |f|jdd}|r|| ||} | dkrxgS| }ddt t |DS)NrcSsg|] }d|fqS)rnr^)rrr^r^r_r7szA_TokenStrategyLoad._prepare_for_compile_state..)rrrrrrZrErrrr rWrrZ"_generate_natural_for_superclasses r\rTrrrrrr9r5Znew_effective_pathr^r^r_rZs4    z-_TokenStrategyLoad._prepare_for_compile_stateN) rrrr*ra inherit_cacherFrErYrZr^r^r^r_ris rc@s0eZdZdZdZdZdZdZddZddZ d S) rzLoader strategies that deals with a class as a target, not an attribute path e.g.:: q = s.query(Person).options( selectin_polymorphic(Person, [Engineer, Manager]) ) TFZclass_strategy_load_elementcCs|Srr^rXr^r^r_rYsz_ClassStrategyLoad._init_pathc Cs^|j}|jj}|r|jsgS|js,|js,gS|j}|rR|||} | dkrNgS| }d|jfgSrn) rrrrErrrrWrrtr^r^r_rZs   z-_ClassStrategyLoad._prepare_for_compile_stateN) rrrr*rurFrErarYrZr^r^r^r_rs rzCallable[..., _AbstractLoad]rrFr)methr]chainedrMrLc Csd}d|ddfd|ddffD]\}}|D]}t|tr|dtrftjddd|d d}|tkr|r|td |dkrt}||t f|}qtd q0|dkrt |\}} }t | }|r|s| |}q|||fd di|}q0|||f|}q0q$|s t |S) NTrrFr=zThe undocumented `.{WILDCARD}` format is deprecated and will be removed in a future version as it is believed to be unused. If you have been using this functionality, please comment on Issue #4390 on the SQLAlchemy project tracker.rMrNrrrsrJ)rUrV startswithrrrXrrr0rrerr}rZ) rvr]rwrM lead_element is_defaultZ_keysrHrg lead_entityr^r^r__generate_from_keyssL(     r|rGzDTuple[InspectionAttr, _InternalEntityType[Any], MapperProperty[Any]]rpc Cs|z t|}Wn0tjk r<}ztd|W5d}~XYnXt|rR|j}|}n t|rh|j}|j}n td|||fS)aparse an attribute or wildcard argument to produce an :class:`._AbstractLoad` instance. This is used by the standalone loader strategy functions like ``joinedload()``, ``defer()``, etc. to produce :class:`_orm.Load` or :class:`._WildcardLoad` objects. z:expected ORM mapped attribute for loader strategy argumentN)r$rZNoInspectionAvailablerrrrr)rHrerrr{rr^r^r_re: s$  re)fnrLcCs4tt|j}|j}d|jd|jd|_||_|S)zdecorator that applies docstrings between standalone loader functions and the loader methods on :class:`._AbstractLoad`. z=Produce a new :class:`_orm.Load` object with the :func:`_orm.z#` option applied. See :func:`_orm.z` for usage examples. )rYrDrr*)r~Zbound_fnZfn_docr^r^r_loader_unbound_fn_ s  r)r]rMrLcOsttj|d|S)NT)r|rr`r]rMr^r^r_r`u sr`FrarccGs&t|d\}}}t|j|d|iS)Nrrb)rerri)rbrdrgryr^r^r_riz sricOsttj|d|SNF)r|rrorr^r^r_ro sro)r]rLcGsttj|diSr)r|rrsr]r^r^r_rs srs)rurt)r]rurLcGsttj|dd|iSNFru)r|rrvrur]r^r^r_rv s rvcGsttj|diSr)r|rrxrr^r^r_rx srxcGsttj|dd|iSr)r|rryrr^r^r_ry s rycGsttj|diSr)r|rrzrr^r^r_rz srzcOsttj|d|Sr)r|rrbrr^r^r_rb srbcGsttj|diSr)r|rr}rr^r^r_r} sr})r~ addl_attrsrbrLcGs:|rtjddd|r d|i}ni}ttj|f|d|S)Nz}The *addl_attrs on orm.defer is deprecated. Please use method chaining in conjunction with defaultload() to indicate a path.1.3rNrbF)rrXr|rr)r~rbrrMr^r^r_r s r)r~rrLcGs(|rtjdddttj|f|diS)NzThe *addl_attrs on orm.undefer is deprecated. Please use method chaining in conjunction with defaultload() to indicate a path.rrNF)rrXr|rr)r~rr^r^r_r s rrVrcCst}||Sr)r0r)rrr^r^r_r srrrcCsttj|fdd|iS)NFr)r|rr)r~rr^r^r_r s rrr)base_clsrrLcCst|}||Sr)rr)rrZulr^r^r_r src Cst|dkr|dj|djjk }t|r4t|}n|jj}td|d|dd|rhd|ddnd |s|dj st |jt |jrd |dd|d |djjjd |d nd fntd|d|dddS)Nrrr^z ORM mapped entity or attribute "z#" does not link from relationship "z%s".%sz .of_type(rz Did you mean to use "z,)" or "loadopt.options(selectin_polymorphic(z, [z ]), ...)" ?zORM mapped attribute "z" does not link mapped class "") r rrlrprrVrrrrkrrr$)rr r Zpath_is_of_typeZparent_entity_strr^r^r_r  s0  . r )sr* __future__rtypingrrrrrrr r r r r rrrrZ_typingrrrrr[rbaserZ interfacesrZ path_registryrrrrrrrrr r"rr$sqlr%r&r'r(r)r*Zsql.baser+Z util.typingr,r-r.r0rr2r3 TYPE_CHECKINGr5r6rr7r8r9r:r;r<rlr=r>Z sql._typingr?r@Z sql.cache_keyrArBrGZ_WildcardKeyTyperVrrZ_AttrGroupTypeZGenerativeOnTraversalrDrr0Z HasCacheKeyZHasShallowCopyZ Traversiblerrrrr|rerr`rirorsrvrxryrzrbr}rrrrrr r^r^r^r_ s                                                                uA [Y8@%