U aN@sdZddlmZddlmZddlmZddlmZddlm Z ddlm Z ddl m Z dd l m Z dd l mZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZGdddee Z Gddde Z!Gddde"Z#e#dNd d!Z$e$j%d"d!Z$e#d#d$Z&e&j%d%d$Z&e#dOd&d'Z'e'j%d(d'Z'e#d)d*Z(e(j%d+d*Z(e#d,d-Z)e)j%d.d-Z)e#d/d0Z*e*j%d1d0Z*e#d2d3Z+e+j%d4d3Z+e#d5d6Z,e,j%d7d6Z,e#dPd9d:Z-e-j%d;d:Z-e#dd=Z.e#dQd?d@Z/e/j%dAd@Z/e#dBdCZ0e0j%dDdCZ0e#dEdFZ1e1j%dGdFZ1e#dHdIZ2e2j%dJdIZ2e#dKdLZ3e3j%dMdLZ3dS)Rz )util)QueryableAttribute)_class_to_mapper)_is_aliased_class)_is_mapped_class)InspectionAttr) LoaderOption)MapperProperty)PropComparator)_DEFAULT_TOKEN)_WILDCARD_TOKEN) PathRegistry) TokenRegistry)_orm_full_deannotate)excinspect)and_) coercions)roles)visitors) _generative) GenerativecsNeZdZdZdejjfdejjfdejjfdej j fdejj fdejj fgZ dd Zed d Zd d ZeddZfddZdZdZdZdZdZdZddZddZddZd:ddZddZd d!Z d"d#Z!e"d$d%Z#e"d;d&d'Z$e"dd0d1Z)d2d3Z*d4d5Z+d6d7Z,d8d9Z-Z.S)?LoadaRepresents loader options which modify the state of a :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:`.defer`, or similar. However, the :class:`_orm.Load` object can also be used directly, and in some cases can be useful. To use :class:`_orm.Load` directly, instantiate it with the target mapped class as the argument. This style of usage is useful when dealing with a :class:`_query.Query` that has multiple entities:: myopt = Load(MyClass).joinedload("widgets") The above ``myopt`` can now be used with :meth:`_query.Query.options`, where it will only take effect for the ``MyClass`` entity:: session.query(MyClass, MyOtherClass).options(myopt) One case where :class:`_orm.Load` is useful as public API is when specifying "wildcard" options that only take effect for a certain class:: session.query(Order).options(Load(Order).lazyload('*')) Above, all relationships on ``Order`` will be lazy-loaded, but other attributes on those descendant objects will load using their normal loader strategy. .. seealso:: :ref:`deferred_options` :ref:`deferred_loading_w_multiple` :ref:`relationship_loader_options` pathstrategy_of_type_extra_criteria_context_cache_key local_optscCs0t|}|j|j|_t|_i|_d|_dSNF) rZ _post_inspectZ_path_registryrr OrderedDictcontextr is_class_strategy)selfentityinspr(`C:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\orm\strategy_options.py__init__^s  z Load.__init__cCs,||}||_i|_i|_d|_d|_|SNr()__new__rr#r rr)clsrloadr(r(r)for_existing_pathis zLoad.for_existing_pathcCs>|jstd|jj}|j}|}|}||t|jS)aApply the current bound parameters in a QueryContext to the "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)rAssertionError compile_stateZselect_statementqueryZ_generate_cache_keyZ_apply_params_to_elementr)r%r#Z orig_queryZ current_queryZk1Zk2r(r(r)_generate_extra_criteriass zLoad._generate_extra_criteriacCsHg}|jdkrgS|jD]&\\}}}|dkr2q|||fq|SNloader)r#itemsappend)r%Z serializedkeyZ loader_pathobjr(r(r)rs zLoad._context_cache_keycstt|}i|_|SN)superr _generater )r%cloned __class__r(r)r<szLoad._generateFNr(cCs&|jjs dS|||t|j dSr:)compile_options_enable_eagerloads_processbool current_path)r%r1mapper_entitiesr(r(r)'process_compile_state_replaced_entitiess z,Load.process_compile_state_replaced_entitiescCs(|jjs dS|||jt|j dSr:)r@rArBZ_lead_mapper_entitiesrCrD)r%r1r(r(r)process_compile_states zLoad.process_compile_statec Csl|jj}|j}|rZ|jD]:\\}}}|r4|js4q|||} | dk r||j|| f<qn|j|jdSr:) r@_for_refresh_staterDr#r6propagate_to_loaders _chop_path attributesupdate) r%r1rEraiseerr is_refreshrDtoken start_pathr5Zchopped_start_pathr(r(r)rBs  z Load._processTc Csr|j}d|_|r>|js>t|tr,tdntd|jft|tjr| t }|} | t sh|r|rrd|_ |rd||f}|r|j s|j|}||}||_|S|rt|} n|j} tdzt| j|}WnRtk r*} z2|rtjtd|| f| dn WYdSW5d} ~ XYnhXz|j}} WnVtk r} z6t|ts~tjtd| | t|f| dnW5d} ~ XYnX||}nt|}|js|j rt|j|d sF|rtd ||jfndSnX|jr |}} ||}n<|jrF|j}} t|j|d s|rtd ||jt |d krx|jjrx|jj rxd |d|jj!fndfndS|j"r|j"|_"t|ddr>|j}t|}}|dkr|j#}|j$|%|d}|j stj&|j'j(|j'dd|dk rt|ndd}t|}|j$|)|d||||}||_n||}|dk rZ| *||jrh|j$}||_|S)Nz3Wildcard token cannot be followed by another entityz7Mapped attribute '%s' does not refer to a mapped entityF%s:%szUsing strings to indicate column or relationship paths in loader options is deprecated and will be removed in SQLAlchemy 2.0. Please use the class-bound attribute directly.z3Can't find property named "%s" on %s in this Query.)Zreplace_contextzNExpected attribute "%s" on %s to be a mapped attribute; instead got %s object.z.Attribute '%s' does not link from element '%s'z1Attribute "%s" does not link from element "%s".%srz% Did you mean to use %s.of_type(%s)?rZpath_with_polymorphicT)aliasedZ_use_mapper_pathZ_existing_alias)+r has_entity isinstancersa_exc ArgumentErrorpropr string_typesendswithr r rIis_aliased_classparentrOrrr&Zwarn_deprecated_20getattrclass_AttributeErrorZraise_propertyr type is_mapperorm_utilZ$_entity_corresponds_to_use_path_implZ is_propertyZ is_attributelen__name__rr#Z entity_pathgetZwith_polymorphicmapperZ base_mappersetZ _get_strategy)r%rattr for_strategy wildcard_keyrMpolymorphic_entity_contextZexisting_of_typeZ default_tokenZ attr_str_nameenterrZfound_propertyZaer'rZacZext_infoZ of_type_infoexistingr(r(r)_generate_paths                          zLoad._generate_pathcCs d|jfS)NzLoad(strategy=%r))rr%r(r(r)__str__sz Load.__str__cCs|dk rtt|}|Sr:)tuplesortedr6)r%rr(r(r) _coerce_stratszLoad._coerce_stratcCs tddS)NzHOnly 'unbound' loader options may be used with the Load.options() method)NotImplementedError)r%r^appliedboundr(r(r)_apply_to_parentszLoad._apply_to_parentcGs8i}t|t }|rtd|D]}||||q dS)aApply 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:`relationship_loader_options` :ref:`deferred_loading_w_multiple` zMThe options() method is currently only supported for 'unbound' loader optionsN)rW _UnboundLoadryr|)r%optsZ apply_cacher{optr(r(r)optionss! z Load.optionscCsN||}||_|||d}|j|_|j|_|j|_d|_|_|j|_dS)NZ relationshipF)rxrI_clone_for_bind_strategyrrrr$)r%rkrrIr=r(r(r)set_relationship_strategys  zLoad.set_relationship_strategycCs8||}d|_|D]}|j||d||d}d|_qdS)NFcolumn) opts_onlyr~T)rxr$rrI)r%attrsrr~rrkr=r(r(r)set_column_strategys zLoad.set_column_strategycCs,||}|D]}|||d}d|_qdSNT)rxrrI)r%rrrkr=r(r(r)set_generic_strategys zLoad.set_generic_strategycCs4||}|d|d}d|_d|_|j|dSr)rxrr$rIr rL)r%rr~r=r(r(r)set_class_strategys  zLoad.set_class_strategycCsX|}||j|||||_|j|_|r8|j||rBd|_|sL|jrT||S)aCreate an anonymous clone of the Load/_UnboundLoad that is suitable to be placed in the context / _to_bind collection of this Load object. The clone will then lose references to context/_to_bind in order to not create reference cycles. T)r<rsrrr rL is_opts_only_set_path_strategy)r%rkrrmrr~r=r(r(r)rs   zLoad._clone_for_bind_strategycCs|s|sL||d}|r<|rJ|j|j|j|j7_q||d|nB||d}||d||r|jr|j|j|j|j7_dSr4)rhr rLrrjr)r%r#rreplace merge_optsrrr(r(r) _set_for_paths   zLoad._set_for_pathcCsj|js|jjr|jj}n|j}|jrJ|D]}|j|j|d|jdq,n|j|j|d|jdd|_dS)NTrr) r$rrVr^is_tokengenerate_for_superclassesrr#r)r%effective_pathrr(r(r)rs$    zLoad._set_path_strategycCsD|j}d|d<|ddk r2t|dd|d<|j|d<|S)Nr(rr#)r5r)__dict__copyr Zserialize_context_dictr serializer%dr(r(r) __getstate__(s  zLoad.__getstate__cCs6|j|t|j|_|jdk r2t|j|_dSr:)rrLr Z deserializerr#Zdeserialize_context_dict)r%stater(r(r) __setstate__5s  zLoad.__setstate__cCsd}tt||jD]\}\}}t|tjrh|dkrJ|dtrJ|S|dtfkrh||j krhdS||krtqqt|t r|j r|j r| |rqqdSq||ddSNrR:zrelationship:%sr) enumerateziprrWrr[r\r r r8rrdisa)r%to_chopric_tokenZp_tokenr(r(r)rJ;s.  zLoad._chop_path)TN)T)NF)FN)TF)/rg __module__ __qualname____doc__rExtendedInternalTraversalZdp_has_cache_key dp_plain_objZdp_multiInternalTraversaldp_clauseelement_listZdp_has_cache_key_tuplesdp_string_multi_dict_cache_key_traversalr* classmethodr/r3rbrr<rr$rrIrrrFrGrBrsrurxr|rrrrrrrrrrrrJ __classcell__r(r(r>r)r$sl+      %   2 *       rc@seZdZdZddZdejjfdejjfdejj fdej j fdejj fgZ d Zd d Zd#d dZddZddZddZddZeddZddZd$ddZddZdd Zd!d"Zd S)%r}a<Represent a loader option that isn't tied to a root entity. The loader option will produce an entity-linked :class:`_orm.Load` object when it is passed :meth:`_query.Query.options`. This provides compatibility with the traditional system of freestanding options, e.g. ``joinedload('x.y.z')``. cCsd|_g|_i|_d|_dSr+)r_to_bindr rrtr(r(r)r*dsz_UnboundLoad.__init__rrrrr FcCs|j|d|_dSr:)rr7rtr(r(r)rws z_UnboundLoad._set_path_strategyNcs|kr|Sdkr|j|}||<|j|_|jr|jd}t|tjrr|trr| dddt }| j|jdd||jd|j |j kst |j|jkst |j|jkst fddD}j|_|j||j|j|S)NrRrrcsh|]}|qSr()r|).0elemrzr{r^to_bindr(r) sz0_UnboundLoad._apply_to_parent..)rr<rrrWrr[r\r splitr rsrIr0r$rextendr rL)r%r^rzr{rr=rkZ new_to_bindr(rr)r|~s:  z_UnboundLoad._apply_to_parentcCs~|r6t|tjr6|ttfkr6|tkr*d|_d||f}|rXt|drX|jsX|dd}|rf||f}||_t |dd|_ |S)NFrQrRrrr() rWrr[r r rIrr$rr_r)r%rrkrlrmr(r(r)rss      z_UnboundLoad._generate_pathcCs*|j}d|d<|j|jdd|d<|S)Nr(rT)filter_aliased_classr)rr_serialize_pathrrr(r(r)rs z_UnboundLoad.__getstate__cCsg}|dD]`}t|trbt|dkr4|\}}d}n |\}}}t||}|rV||}||q ||q t||d<||_dS)Nrr)rWrvrfr_of_typer7r)r%rretr8r-ZpropkeyrrZr(r(r)rs         z_UnboundLoad.__setstate__cCs^|jd}|jj}|jD]@}||kr|||r:|js:q|dd|D|j|j|qdS)NZ_unbound_load_dedupescSsg|] }|jqSr()Z entity_zerorror(r(r) sz)_UnboundLoad._process..)rKr@rHraddrI _bind_loaderrD)r%r1rErMZdedupesrNvalr(r(r)rBs     z_UnboundLoad._processcsrt}ddfdd|D}|ddD](}d|_|rJ|||f|}q,||}q,|||df|}d|_|S) NcSsHt|tjr>|tkrtfS|dtr4|dd}|dS|fSdS)N.r)rWrr[r r startswithrr8r(r(r) _split_keys   z+_UnboundLoad._from_keys.._split_keycsg|]}|D]}|qqSr(r()rr8rOrr(r)rs z+_UnboundLoad._from_keys..rrRTF)r}_is_chain_link defaultload)r-methkeysZchainedkwrZ all_tokensrOr(rr) _from_keyss  z_UnboundLoad._from_keyscCsd}tt||D]\}\}\}}t|tjrp|dkrP|dtrP|S|dtfkr||j krdSqt|t r|j |k s|j |k r|j j r|j |sdSq|d7}||dSr)rrpairsrWrr[r\r r r8r rb _parententityrdr)r%rrrrZp_entityZp_propr(r(r)rJs.      z_UnboundLoad._chop_pathcCsg}|D]}t|trj|rD|jrDt|jjrD||jj|jdfq||jj|j|jr`|jj ndfqt|t r||jj|jdfq||q|Sr:) rWrrrr]r7Z _parentmapperr`r8r&r )r%rrrrOr(r(r)rs(    z_UnboundLoad._serialize_pathc Cs|j}|jr|r||df7}|r.|||}|s6dS|d}t|tjrZ||||}nRt|tr~|j}| |||j |}n.|jrt |rt |}||krd}n t d|sdS|} t| } |dkr| j}|j| _|j| _|j| _| j} | js\} }| j| j|| t|dkr&|jndd||dsdSq| j|j| jsf| jjrf| jj} n| j} | jr| D]} | j|| |j |jdq|n| j|| |j |jd| S)a]Convert from an _UnboundLoad() object into a Load() object. The _UnboundLoad() uses an informal "path" and does not necessarily refer to a lead entity as it may use string tokens. The Load() OTOH refers to a complete path. This method reconciles from a given Query into a Load. Example:: query = session.query(User).options( joinedload("orders").joinedload("items")) The above options will be an _UnboundLoad object along the lines of (note this is not the exact API of _UnboundLoad):: _UnboundLoad( _to_bind=[ _UnboundLoad(["orders"], {"lazy": "joined"}), _UnboundLoad(["orders", "items"], {"lazy": "joined"}), ] ) After this method, we get something more like this (again this is not exact API):: Load( User, (User, User.orders.property)) Load( User, (User, User.orders.property, Order, Order.items.property)) rNz6mapper option expects string key or list of attributesr)rnr)rr$rJrWrr[_find_entity_basestringr rb_find_entity_prop_comparatorrrrrXrYrr#rrrrsrfr rLrVr^rrrr)r%entitiesrDr#rMrPrOr&rZZ path_elementr5ridxrr(r(r)r3s$       z_UnboundLoad._bind_loadercCst|r|}nt|}|D]}t||r|Sq|rt|s^tdtt ||fqtd|d dd|DfndSdS)NzGQuery has only expression-based entities, which do not apply to %s "%s"zMapped attribute "%s" does not apply to any of the root entities in this query, e.g. %s. Please specify the full path from one of the root entities to the target attribute. , css|]}t|VqdSr:str)rxr(r(r) sz<_UnboundLoad._find_entity_prop_comparator..) rrreZ_entity_corresponds_tolistrXrYrZclsname_as_plain_namercjoin)r%rrZrirMZ searchforror(r(r)rs&   z)_UnboundLoad._find_entity_prop_comparatorcCs|dtrVtt|dkrd|rdtdddd|Dddd|Dfn|trdd}|D] }|S|rtd |fndSdS) NrrzCan't apply wildcard ('*') or load_only() loader option to multiple entities %s. Specify loader options for each entity individually, such as %s.rcss|]}t|VqdSr:rrr(r(r)rsz7_UnboundLoad._find_entity_basestring..css|]}d|VqdS)zLoad(%s).some_option('*')Nr(rr(r(r)rsFzJQuery has only expression-based entities - can't find property named "%s".)r\r rfrrXrYrr )r%rrOrMror(r(r)rs.  z$_UnboundLoad._find_entity_basestring)N)F)rgrrrr*rrZ dp_multi_listrZdp_has_cache_key_listrrrrrrr|rsrrrBrrrJrrrrr(r(r(r)r}Ys2       &   r}c@s,eZdZddZddZddZddZd S) loader_optioncCsdSr:r(rtr(r(r)r*szloader_option.__init__cCs8|j|_}||_tt|r(td|tt|||S)Nz#Load class already has a %s method.)rgnamefnhasattrr TypeErrorsetattr)r%rrr(r(r)__call__s     zloader_option.__call__cCs*||_|jj}dd|ji|j_||_|S)NzProduce a new :class:`_orm.Load` object with the :func:`_orm.%(name)s` option applied. See :func:`_orm.%(name)s` for usage examples. r)Z _unbound_fnrrr)r%rZfn_docr(r(r)_add_unbound_fns zloader_option._add_unbound_fncCs8dd|ji|_tjddd|jidd|}||_|S)Na}Produce a standalone "all" option for :func:`_orm.%(name)s`. .. deprecated:: 0.9 The :func:`_orm.%(name)s_all` function is deprecated, and will be removed in a future release. Please use method chaining with :func:`_orm.%(name)s` instead, as in:: session.query(MyClass).options( %(name)s("someattribute").%(name)s("anotherattribute") ) rz0.9zThe :func:`.%(name)s_all` function is deprecated, and will be removed in a future release. Please use method chaining with :func:`.%(name)s` insteadF)Zadd_deprecation_to_docstring)rrr deprecatedZ_unbound_all_fn)r%rr(r(r)_add_unbound_all_fns  z!loader_option._add_unbound_all_fnN)rgrrr*rrrr(r(r(r)rs rNcCsp|dk r2t|ts"t|}|j}qNtjdddnt|ddrNt|j}|j}|j|ddidd }||j d <|S) aIndicate that the given attribute should be eagerly loaded from columns stated manually in the query. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. The option is used in conjunction with an explicit join that loads the desired rows, i.e.:: sess.query(Order).\ join(Order.user).\ options(contains_eager(Order.user)) The above query would join from the ``Order`` entity to its related ``User`` entity, and the returned ``Order`` objects would have the ``Order.user`` attribute pre-populated. It may also be used for customizing the entries in an eagerly loaded collection; queries will normally want to use the :meth:`_query.Query.populate_existing` method assuming the primary collection of parent objects may already have been loaded:: sess.query(User).\ join(User.addresses).\ filter(Address.email_address.like('%@aol.com')).\ options(contains_eager(User.addresses)).\ populate_existing() See the section :ref:`contains_eager` for complete usage details. .. seealso:: :ref:`loading_toplevel` :ref:`contains_eager` NzPassing a string name for the 'alias' argument to 'contains_eager()` is deprecated, and will not work in a future release. Please use a sqlalchemy.alias() or sqlalchemy.orm.aliased() construct.z1.4versionrlazyjoinedF)rIZeager_from_alias) rWrrZ selectablerwarn_deprecatedr_rrr )loadoptrkaliasinfoZotr=r(r(r)contains_eager0s$'    rcOsttj|d|Sr)r}rrrrr(r(r)rps cGs.||ddd}|ddddddi|S)alIndicate that for a particular entity, only the given list of column-based attribute names should be loaded; all others will be deferred. This function is part of the :class:`_orm.Load` interface and supports both method-chained and standalone operation. Example - given a class ``User``, load only the ``name`` and ``fullname`` attributes:: session.query(User).options(load_only(User.name, User.fullname)) Example - given a relationship ``User.addresses -> 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 :class:`_query.Query` that has multiple entities, the lead entity can be specifically referred to using the :class:`_orm.Load` constructor:: session.query(User, Address).join(User.addresses).options( Load(User).load_only(User.name, User.fullname), Load(Address).load_only(Address.email_address) ) .. note:: This method will still load a :class:`_schema.Column` even if the column property is defined with ``deferred=True`` for the :func:`.column_property` function. .. versionadded:: 0.9.0 FTdeferredZ instrument*Z undefer_pksr)rrr=r(r(r) load_onlyws&rcGs tj|Sr:)r}r)rr(r(r)rscCs&||ddi}|dk r"||jd<|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" query(User).options(joinedload(User.orders)) # joined-load Order.items and then Item.keywords query(Order).options( joinedload(Order.items).joinedload(Item.keywords)) # lazily load Order.items, but when Items are loaded, # joined-load the keywords collection query(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:: query(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:: query(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:: query(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. .. versionchanged:: 1.0.0 ``innerjoin=True`` now implies ``innerjoin="nested"``, whereas in 0.9 it implied ``innerjoin="unnested"``. In order to achieve the pre-1.0 "unnested" inner join behavior, use the value ``innerjoin="unnested"``. See :ref:`migration_3008`. .. note:: The joins produced by :func:`_orm.joinedload` are **anonymously aliased**. The criteria by which the join proceeds cannot be modified, nor can the :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:`_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` rrN innerjoin)rr )rrkrr5r(r(r) joinedloadsX rcOsttj|d|Sr!)r}rrrr(r(r)r scCs||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" query(User).options(subqueryload(User.orders)) # subquery-load Order.items and then Item.keywords query(Order).options( subqueryload(Order.items).subqueryload(Item.keywords)) # lazily load Order.items, but when Items are loaded, # subquery-load the keywords collection query(Order).options( lazyload(Order.items).subqueryload(Item.keywords)) .. seealso:: :ref:`loading_toplevel` :ref:`subquery_eager_loading` rZsubqueryrrrkr(r(r) subqueryloadsrcGsttj|diSr!)r}rrrr(r(r)r/scCs||ddiS)a9Indicate 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" query(User).options(selectinload(User.orders)) # selectin-load Order.items and then Item.keywords query(Order).options( selectinload(Order.items).selectinload(Item.keywords)) # lazily load Order.items, but when Items are loaded, # selectin-load the keywords collection query(Order).options( lazyload(Order.items).selectinload(Item.keywords)) .. versionadded:: 1.2 .. seealso:: :ref:`loading_toplevel` :ref:`selectin_eager_loading` rZselectinrrr(r(r) selectinload4srcGsttj|diSr!)r}rrrr(r(r)rVscCs||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` rselectrrr(r(r)lazyload[srcGsttj|diSr!)r}rrrr(r(r)rmscCs||ddi}|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. .. seealso:: :ref:`loading_toplevel` :ref:`selectin_eager_loading` rZ immediater)rrkr5r(r(r) immediateloadrsrcGsttj|diSr!)r}rrrr(r(r)rscCs||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; for column-based attributes, see :func:`_orm.defer`. .. note:: Setting this loading strategy as the default strategy for a relationship using the :paramref:`.orm.relationship.lazy` parameter may cause issues with flushes, such if a delete operation needs to load related objects and instead ``None`` was returned. .. seealso:: :ref:`loading_toplevel` rnoloadrrr(r(r)rsrcGsttj|diSr!)r}rrrr(r(r)rsFcCs||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. .. versionadded:: 1.1 .. seealso:: :ref:`loading_toplevel` :ref:`prevent_lazy_with_raiseload` :ref:`deferred_raiseload` rZ raise_on_sqlraiser)rrkZsql_onlyr(r(r) raiseloads'rcOsttj|d|Sr!)r}rrrr(r(r)rscCs ||dS)a:Indicate an attribute should load using its default loader style. 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.query(MyClass).options( defaultload(MyClass.someattribute). defer("some_column"). undefer("some_other_column") ) .. seealso:: :meth:`_orm.Load.options` - allows for complex hierarchical loader option structures with less verbosity than with individual :func:`.defaultload` directives. :ref:`relationship_loader_options` :ref:`deferred_loading_w_multiple` Nrrr(r(r)rs"rcGsttj|diSr!)r}rrrr(r(r)rscCs$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("attribute_one"), defer("attribute_two")) 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("someattr").defer("some_column")) A :class:`_orm.Load` object that is present on a certain path can have :meth:`_orm.Load.defer` called multiple times, each will operate on the same parent entity:: session.query(MyClass).options( defaultload("someattr"). defer("some_column"). defer("some_other_column"). defer("another_column") ) :param key: Attribute to be deferred. :param raiseload: raise :class:`.InvalidRequestError` if the column value is to be loaded from emitting SQL. Used to prevent unwanted SQL from being emitted. .. versionadded:: 1.4 .. seealso:: :ref:`deferred_raiseload` :param \*addl_attrs: This option supports the old 0.8 style of specifying a path as a series of attributes, which is now superseded by the method-chained style. .. deprecated:: 0.9 The \*addl_attrs on :func:`_orm.defer` is deprecated and will be removed in a future release. Please use method chaining in conjunction with defaultload() to indicate a path. .. seealso:: :ref:`deferred` :func:`_orm.undefer` Trrr)rr8rrr(r(r)defer sE rcOs*|rtjdddttj|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.3rF)rrr}rr)r8 addl_attrsrr(r(r)rWscCs||fdddS)agIndicate 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("col1"), undefer("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 session.query(MyClass).options( defaultload(MyClass.items).undefer('text')) :param key: Attribute to be undeferred. :param \*addl_attrs: This option supports the old 0.8 style of specifying a path as a series of attributes, which is now superseded by the method-chained style. .. deprecated:: 0.9 The \*addl_attrs on :func:`_orm.undefer` is deprecated and will be removed in a future release. Please use method chaining in conjunction with defaultload() to indicate a path. .. seealso:: :ref:`deferred` :func:`_orm.defer` :func:`_orm.undefer_group` FTrr)rr8r(r(r)undeferes,rcGs*|rtjdddttj|f|diS)NzThe *addl_attrs on orm.undefer is deprecated. Please use method chaining in conjunction with defaultload() to indicate a path.rrF)rrr}rr)r8rr(r(r)rscCs|jddd|diddS)aIndicate 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`:: session.query(MyClass).options( defaultload("someattr").undefer_group("large_attrs")) .. versionchanged:: 0.9.0 :func:`_orm.undefer_group` is now specific to a particular entity load path. .. seealso:: :ref:`deferred` :func:`_orm.defer` :func:`_orm.undefer` rNzundefer_group_%sT)rr)rrr(r(r) undefer_groups  rcCs t|Sr:)r}r)rr(r(r)rscCs,ttjt|}|j|fddid|idS)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.:: sess.query(SomeClass).options( with_expression(SomeClass.x_y_expr, SomeClass.x + SomeClass.y) ) .. versionadded:: 1.2 :param key: Attribute to be undeferred. :param expr: SQL expression to be applied to the attribute. .. note:: the target attribute is populated only if the target object is **not currently loaded** in the current :class:`_orm.Session` unless the :meth:`_query.Query.populate_existing` method is used. Please refer to :ref:`mapper_querytime_expression` for complete usage details. .. seealso:: :ref:`mapper_querytime_expression` Zquery_expressionT expressionr~)rexpectrZLabeledColumnExprRolerr)rr8rr(r(r)with_expressions!rcCsttj|fdd|iS)NFr)r}rr)r8rr(r(r)rs cCs0|jddidttdd|Dtdid|S)a~Indicate 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_polymorphicTrcss|]}t|VqdSr:r)rr-r(r(r)rsz'selectin_polymorphic..rr)rrvrwid)rclassesr(r(r)selectin_polymorphicsr cCs&t}d|_t|f|_|||Sr)r}r$rrr )Zbase_clsrulr(r(r)r s   )N)N)F)F)4rrTrrerKrbaserrrrZ interfacesrr r Z path_registryr r r rrrrXrZsqlrrrrZsql.baserrrr}objectrrrrrrrrrrrrrrrrr r(r(r(r)s                       9; ?  .  ]    !        +  $  J  0  #  )