o znh@sdZddlmZddlmZddlmZddlmZddlm Z ddlm Z ddl m Z dd l m Z dd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZGdddee ZGdddeZGdddeZ e dRddZ!e!j"ddZ!e dd Z#e#j"d!d Z#e dRd"d#Z$e$j"d$d#Z$e$j%d%d&Z&e d'd(Z'e'j"d)d(Z'e'j%d*d+Z(e d,d-Z)e)j"d.d-Z)e)j%d/d0Z*e d1d2Z+e+j"d3d2Z+e+j%d4d5Z,e d6d7Z-e-j"d8d7Z-e d9d:Z.e.j"d;d:Z.e dSd=d>Z/e/j"d?d>Z/e d@dAZ0e0j"dBdAZ0e dCdDZ1e1j"dEdDZ1e dFdGZ2e2j"dHdGZ2e dIdJZ3e3j"dKdJZ3e dLdMZ4e4j"dNdMZ4e dOdPZ5e5j"dQdPZ5dS)Tz )util)QueryableAttribute)_class_to_mapper)_is_aliased_class)_is_mapped_class)InspectionAttr) MapperOption)PropComparator)_DEFAULT_TOKEN)_WILDCARD_TOKEN) PathRegistry) TokenRegistry)_orm_full_deannotate)excinspect) expression) _generative) GenerativecseZdZdZddZeddZddZfdd Zd Z d Z d Z d Z d Z d d ZddZddZ d1ddZddZddZddZeddZe d1ddZed2dd Zed!d"Zed#d$Z d3d%d&Zd4d'd(Zd)d*Zd+d,Zd-d.Zd/d0Z Z!S)5LoadaqRepresents loader options which modify the state of a :class:`.Query` in order to affect how various mapped attributes are loaded. The :class:`.Load` object is in most cases used implicitly behind the scenes when one makes use of a query option like :func:`.joinedload`, :func:`.defer`, or similar. However, the :class:`.Load` object can also be used directly, and in some cases can be useful. To use :class:`.Load` directly, instantiate it with the target mapped class as the argument. This style of usage is useful when dealing with a :class:`.Query` that has multiple entities:: myopt = Load(MyClass).joinedload("widgets") The above ``myopt`` can now be used with :meth:`.Query.options`, where it will only take effect for the ``MyClass`` entity:: session.query(MyClass, MyOtherClass).options(myopt) One case where :class:`.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` cCs*t|}|j|_t|_i|_d|_dSNF)r_path_registrypathr OrderedDictcontext local_optsis_class_strategy)selfentityinspr!J/usr/local/lib/python3.10/dist-packages/sqlalchemy/orm/strategy_options.py__init__Hs   z Load.__init__cCs&||}||_i|_i|_d|_|SN)__new__rrr_of_type)clsrloadr!r!r"for_existing_pathQs zLoad.for_existing_pathc sh|jdjrdSg}|jD]\\}}|dkrqt|jj|D] \}}||ur+nq!jp4jjd}|||}|dusD|sEjsEqg} |D]*} t| tj rW| | qI| jr^dS| j rh| | j qI| j smJ| | jqI| r||| dkr|j r| |jn|jrdS| t| jpdjrtfddtjDndq|sdSt|S)NFloaderr!csg|] }|j|fqSr!)r).0keyobjr!r" s z,Load._generate_cache_key..)ris_aliased_classritemszipr& _chop_path isinstancer string_typesappend is_propertyr. is_mapperclass_tuplestrategyrsorted) rr serializedr. loader_path local_elemobj_elemendpointchoppedserialized_pathtokenr!r/r"_generate_cache_keyZsh        zLoad._generate_cache_keycstt|}i|_|Sr$)superr _generater)rcloned __class__r!r"rIszLoad._generateFNcC||ddSNT_processrqueryr!r!r" process_queryzLoad.process_querycCrMrrOrQr!r!r"process_query_conditionallyrTz Load.process_query_conditionallycCsZ|j}|r$|jD]\\}}}|||}|dur!||j||f<q dS|j|jdSr$) _current_pathrr3r5 _attributesupdate)rrRraiseerr current_pathrF start_pathr+chopped_start_pathr!r!r"rPs z Load._processTcCs||j}d|_|r|jst|trtdtd|jft|tjr| t }| t s0|rQ|r5d|_ |r=d||f}|rG|j sG|j|}||}||_|S|rXt|}n|j}zt|j|}Wntyx|rutd||fYdSw|j}} ||}nt|rt|j|ds|rtd||jfdSn|j} } t|j|ds|rtd||jt|d kr|jjr|jj rd |d |jjffd fdSt|d dr$|j} t| } } |j| |jd}| j stj | j!j"| j!dd|durt|ndd} t| } |j| #|jd| || | }| |_n|| }|dur2| $||jr9|j}||_|S)Nz3Wildcard token cannot be followed by another entityz7Mapped attribute '%s' does not refer to a mapped entityF%s:%sz3Can't find property named "%s" on %s in this Query.r,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)?r&path_with_polymorphicT)aliased_use_mapper_path_existing_alias)%r& has_entityr6r sa_exc ArgumentErrorproprr7endswithr r propagate_to_loadersr2parentrFrrrgetattrr;AttributeErrorpropertyrorm_util$_entity_corresponds_to_use_path_impllenr:__name__ entity_pathgetrwith_polymorphicmapper base_mapperset _get_strategy)rrattr for_strategy wildcard_keyrYexisting_of_type default_tokenentfound_propertyrgacext_info of_type_infoexistingr!r!r"_generate_paths                       zLoad._generate_pathcCs d|jfS)NzLoad(strategy=%r))r=rr!r!r"__str__Bs z Load.__str__cCs|dur tt|}|Sr$)r<r>r3)rr=r!r!r" _coerce_stratEszLoad._coerce_stratcCstd)NzHOnly 'unbound' loader options may be used with the Load.options() method)NotImplementedError)rrjappliedboundr!r!r"_apply_to_parentJszLoad._apply_to_parentcGs8i}t|t }|rtd|D] }||||qdS)amApply a series of options as sub-options to this :class:`.Load` object. E.g.:: query = session.query(Author) query = query.options( joinedload(Author.book).options( load_only("summary", "excerpt"), joinedload(Book.citations).options( joinedload(Citation.author) ) ) ) :param \*opts: A series of loader option objects (ultimately :class:`.Load` objects) which should be applied to the path specified by this :class:`.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)r6 _UnboundLoadrr)ropts apply_cacheroptr!r!r"optionsPs z Load.optionscCsF||}||_|||d}|j|_|j|_d|_|_|j|_dS)N relationshipF)rri_clone_for_bind_strategyrr&r)rryr=rirJr!r!r"set_relationship_strategyzs   zLoad.set_relationship_strategycCs8||}d|_|D]}|j||d||d}d|_q dS)NFcolumn) opts_onlyrT)rrrri)rattrsr=rrryrJr!r!r"set_column_strategys  zLoad.set_column_strategycCs,||}|D] }|||d}d|_qdSrN)rrri)rrr=ryrJr!r!r"set_generic_strategys zLoad.set_generic_strategycCs4||}|d|d}d|_d|_|j|dSrN)rrrrirrX)rr=rrJr!r!r"set_class_strategys zLoad.set_class_strategycCsX|}||j|||||_|j|_|r|j||r!d|_|s&|jr*||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)rIrrr=rrX is_opts_only_set_path_strategy)rryr=r{rrrJr!r!r"rs   zLoad._clone_for_bind_strategycCs|s|s#||jd}|r|r|j|jdSdS||d|dS||jd}||d||r?|jrA|j|jdSdSdS)Nr+)rsrrrXrwr)rrrreplace merge_optsrr!r!r" _set_for_paths zLoad._set_for_pathcCsj|js |jjr |jj}n|j}|jr%|D] }|j|j|d|jdqn |j|j|d|jdd|_dS)NTrr) rrrdrjis_tokengenerate_for_superclassesrrr)reffective_pathrr!r!r"rs&   zLoad._set_path_strategycCs<|j}|ddurt|dd|d<|j|d<|S)Nr)r+r)__dict__copyr serialize_context_dictr serializerdr!r!r" __getstate__s  zLoad.__getstate__cCs:|j|t|j|_|jdurt|j|_dSdSr$)rrXr deserializerrdeserialize_context_dict)rstater!r!r" __setstate__s  zLoad.__setstate__cCsd}tt||jD]B\}\}}t|tjr4|dkr%|dtr%|S|dtfkr4||j kr4dS||ur9q t|t rJ|j rJ|j rJ| |rJq dS||ddSNr,r*:zrelationship:%sr) enumerater4rr6rr7rhr r r.rr:isa)rto_chopric_tokenp_tokenr!r!r"r5s*  zLoad._chop_path)Tr)FN)TF)"rq __module__ __qualname____doc__r# classmethodr)rGrIrrr=rir&rSrUrPrrrrrrrrrrrrrrrr5 __classcell__r!r!rKr"r sN'  F  )      rc@seZdZdZddZdZddZddZd d d Zd d Z ddZ ddZ ddZ e ddZddZd!ddZddZddZddZd S)"ra2Represent a loader option that isn't tied to a root entity. The loader option will produce an entity-linked :class:`.Load` object when it is passed :meth:`.Query.options`. This provides compatibility with the traditional system of freestanding options, e.g. ``joinedload('x.y.z')``. cCsd|_g|_i|_dS)Nr!)r_to_bindrrr!r!r"r#s z_UnboundLoad.__init__FcCsd}|jD]4}t|j|jD] \}}||urn!q||jdgddd}|r9||}|dur3dS|r9||7}q|s>dS|S)Nr!r*F)rr4r _bind_loaderrG)rrr?valrAval_elemrc_keyr!r!r"rG!s"  z _UnboundLoad._generate_cache_keycCs|j|d|_dSr$)rr8rr!r!r"r4s  z_UnboundLoad._set_path_strategyNcs|vr|Sdur|j|}||<|j|_|jrJ|jd}t|tjr9|tr9| dddt }| j|jdd||jd|j |j ksRJ|j |j ksZJ|j|jksbJfddD}j|_|j||j|j|S)Nr,rr*csh|] }|qSr!)r)r-elemrrrjto_bindr!r" Wsz0_UnboundLoad._apply_to_parent..)rrIr=rr6rr7rhr splitr rrirrextendrrX)rrjrrrrJry new_to_bindr!rr"r;s4  z_UnboundLoad._apply_to_parentcCsp|rt|tjr|ttfvr|tkrd|_d||f}|r,t|dr,|js,|dd}|r3||f}||_|S)NFr]r,r*) r6rr7r r rirrr)rrryrzr{r!r!r"ras     z_UnboundLoad._generate_pathcCs"|j}|j|jdd|d<|S)NT)filter_aliased_classr)rr_serialize_pathrrr!r!r"rqs z_UnboundLoad.__getstate__cCsg}|dD]0}t|tr1t|dkr|\}}d}n|\}}}t||}|r+||}||q||qt||d<||_dS)Nrr)r6r<rprkof_typer8r)rrretr.r'propkeyrrgr!r!r"rvs          z_UnboundLoad.__setstate__cCsL|jd}|jD]}||vr#|||dd|jD|j|j|qdS)N_unbound_load_dedupescSsg|]}|jqSr!) entity_zeror-r~r!r!r"r1sz)_UnboundLoad._process..)rWraddr_mapper_entitiesrV)rrRrYdedupesrr!r!r"rPs   z_UnboundLoad._processcszt}ddfdd|D}|ddD]}d|_|r'|||fi|}q||}q|||dfi|}d|_|S) NcSsDt|tjr|tkr tfS|dtr|dd}|dS|fS)N.r)r6rr7r r startswithrr.r!r!r" _split_keys   z+_UnboundLoad._from_keys.._split_keycsg|] }|D]}|qqSr!r!)r-r.rFrr!r"r1sz+_UnboundLoad._from_keys..r*r,TF)r_is_chain_link defaultload)r'methkeyschainedkwr all_tokensrFr!rr" _from_keyss  z_UnboundLoad._from_keyscCsd}tt||D]I\}\}\}}t|tjr8|dkr(|dtr(|S|dtfkr7||j kr7dSq t|t rT|j |usQ|j |urT|j j rQ|j |sTdSq |d7}||dSr)rr4pairsr6rr7rhr r r.r rm _parententityr:r)rrrrrp_entityp_propr!r!r"r5s,        z_UnboundLoad._chop_pathcCsg}|D]A}t|tr/|r"|jr"t|jjr"||jj|jdfq||jj|j|jfqt|t r@||jj|jdfq||q|Sr$) r6rr&rr2r8 _parentmapperr;r.r )rrrrrFr!r!r"rs"    z_UnboundLoad._serialize_pathcCs|j}|jr|r||df7}|r|||}|sdS|d}t|tjr-||||}n)t|tr?|j}| |||j |}n|jrQt |rQt |}||vrPd}nt d|sZdS|} t| } |durh|| _n| j}|j| _|j| _|j| _| j} | jst|D]\} }| | j|| t|dkr|jndd|sdSq| j|j| js| jjr| jj} n| j} | jr| D]} | j|| |j |jdq| S| 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)) r*Nz6mapper option expects string key or list of attributesrr)rrr5r6rr7_find_entity_basestringr rm_find_entity_prop_comparatorrrrrerfrrr=rrrrprrXrdrjrrrr)rentitiesrZrrYr[rFrrg path_elementr+ridxrr!r!r"rs$        z_UnboundLoad._bind_loadercCst|r|}nt|}|D] }t||r|Sq |r?t|s.tdtt ||ftd|d dd|DfdS)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. , cs|]}t|VqdSr$str)r-xr!r!r" ~z<_UnboundLoad._find_entity_prop_comparator..) rrrn_entity_corresponds_tolistrerfrclsname_as_plain_nametypejoin)rrrgrurY searchforr~r!r!r"rgs(  z)_UnboundLoad._find_entity_prop_comparatorcCs|dtr+tt|dkr*|r*tdddd|Dddd|Dfn|tr2d}|D]}|S|rDtd |fdS) NrrzCan't apply wildcard ('*') or load_only() loader option to multiple entities %s. Specify loader options for each entity individually, such as %s.rcsrr$rrr!r!r"rrz7_UnboundLoad._find_entity_basestring..css|]}d|VqdS)zLoad(%s).some_option('*')Nr!rr!r!r"rs  FzJQuery has only expression-based entities - can't find property named "%s".)rhr rprrerfrr )rrrFrYr~r!r!r"rs0  z$_UnboundLoad._find_entity_basestringr$F)rqrrrr#rrGrrrrrrPrrr5rrrrr!r!r!r"rs&  &   rc@s,eZdZddZddZddZddZd S) loader_optioncCsdSr$r!rr!r!r"r#szloader_option.__init__cCs8|j|_}||_tt|rtd|tt|||S)Nz#Load class already has a %s method.)rqnamefnhasattrr TypeErrorsetattr)rrrr!r!r"__call__s    zloader_option.__call__cCs*||_|jj}dd|ji|j_||_|S)NzProduce a new :class:`.Load` object with the :func:`.orm.%(name)s` option applied. See :func:`.orm.%(name)s` for usage examples. r) _unbound_fnrrr)rrfn_docr!r!r"_add_unbound_fns zloader_option._add_unbound_fncCs8dd|ji|_tjddd|jidd|}||_|S)NauProduce a standalone "all" option for :func:`.orm.%(name)s`. .. deprecated:: 0.9 The :func:`.%(name)s_all` function is deprecated, and will be removed in a future release. Please use method chaining with :func:`.%(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)add_deprecation_to_docstring)rrr deprecated_unbound_all_fn)rrr!r!r"_add_unbound_all_fns z!loader_option._add_unbound_all_fnN)rqrrr#rrrr!r!r!r"rs  rNcCs`|durt|tst|}|j}nt|ddrt|j}|j}|j|ddidd}||jd<|S)aIndicate that the given attribute should be eagerly loaded from columns stated manually in the query. This function is part of the :class:`.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. When making use of aliases with :func:`.contains_eager`, the path should be specified using :meth:`.PropComparator.of_type`:: user_alias = aliased(User) sess.query(Order).\ join((user_alias, Order.user)).\ options(contains_eager(Order.user.of_type(user_alias))) :meth:`.PropComparator.of_type` is also used to indicate a join against specific subclasses of an inherting mapper, or of a :func:`.with_polymorphic` construct:: # employees of a particular subtype sess.query(Company).\ outerjoin(Company.employees.of_type(Manager)).\ options( contains_eager( Company.employees.of_type(Manager), ) ) # employees of a multiple subtypes wp = with_polymorphic(Employee, [Manager, Engineer]) sess.query(Company).\ outerjoin(Company.employees.of_type(wp)).\ options( contains_eager( Company.employees.of_type(wp), ) ) The :paramref:`.contains_eager.alias` parameter is used for a similar purpose, however the :meth:`.PropComparator.of_type` approach should work in all cases and is more effective and explicit. .. seealso:: :ref:`loading_toplevel` :ref:`contains_eager` Nr&lazyjoinedF)rieager_from_alias)r6rr selectablerkr&rr)loadoptryaliasinfootrJr!r!r"contains_eagers=     r cOsttj|d|SrN)rrr rrr!r!r"r +s cGs.||ddd}|ddddddi|S)aIndicate 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:`.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("name", "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("addresses").load_only("email_address") ) For a :class:`.Query` that has multiple entities, the lead entity can be specifically referred to using the :class:`.Load` constructor:: session.query(User, Address).join(User.addresses).options( Load(User).load_only("name", "fullname"), Load(Address).load_only("email_addres") ) .. versionadded:: 0.9.0 FTdeferred instrument* undefer_pksr)r rrJr!r!r" load_only2s" rcGs tj|Sr$)rr)rr!r!r"r] cCs&||ddi}|dur||jd<|S)a Indicate that the given attribute should be loaded using joined eager loading. This function is part of the :class:`.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:`.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` 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.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)r ryrr+r!r!r" joinedloadbsV rcOttj|d|Srrrrrr!r!r"rcOrrNrrr!r!r"joinedload_allrrcC||ddiS)aIndicate that the given attribute should be loaded using subquery eager loading. This function is part of the :class:`.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` rsubqueryrr ryr!r!r" subqueryloadsr!cGttj|diSrrrr!rr!r!r"r!rcGr"rNr#r$r!r!r"subqueryload_allrr%cCr)a5Indicate that the given attribute should be loaded using SELECT IN eager loading. This function is part of the :class:`.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` rselectinrr r!r!r" selectinloadsr'cGr"rrrr'r$r!r!r"r'rcGr"rNr(r$r!r!r"selectinload_allrr)cCr)aIndicate that the given attribute should be loaded using "lazy" loading. This function is part of the :class:`.Load` interface and supports both method-chained and standalone operation. .. seealso:: :ref:`loading_toplevel` :ref:`lazy_loading` rselectrr r!r!r"lazyloadsr+cGr"rrrr+r$r!r!r"r+1rcGr"rNr,r$r!r!r" lazyload_all6rr-cCs||ddi}|S)aIndicate that the given attribute should be loaded using an immediate load with a per-attribute SELECT statement. 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:`.Load` interface and supports both method-chained and standalone operation. .. seealso:: :ref:`loading_toplevel` :ref:`selectin_eager_loading` r immediater)r ryr+r!r!r" immediateload;sr/cGr"r)rrr/r$r!r!r"r/RrcCr)axIndicate that the given relationship attribute should remain unloaded. This function is part of the :class:`.Load` interface and supports both method-chained and standalone operation. :func:`.orm.noload` applies to :func:`.relationship` attributes; for column-based attributes, see :func:`.orm.defer`. .. seealso:: :ref:`loading_toplevel` rnoloadrr r!r!r"r0Wsr0cGr"r)rrr0r$r!r!r"r0jrFcCs||d|r diSdiS)aIndicate that the given relationship attribute should disallow lazy loads. 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. :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 lazyload. This function is part of the :class:`.Load` interface and supports both method-chained and standalone operation. :func:`.orm.raiseload` applies to :func:`.relationship` attributes only. .. versionadded:: 1.1 .. seealso:: :ref:`loading_toplevel` :ref:`prevent_lazy_with_raiseload` r raise_on_sqlraiser)r rysql_onlyr!r!r" raiseloados  r4cOrr)rrr4rr!r!r"r4rcCs ||dS)a6Indicate 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:`.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` Nrr r!r!r"rs "rcGr"r)rrrr$r!r!r"rrcCs||fdddS)atIndicate that the given column-oriented attribute should be deferred, e.g. not loaded until accessed. This function is part of the :class:`.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:`.Load` object that is present on a certain path can have :meth:`.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 \*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 r.r!r!r"defers: r6cG&|rtdttj|f|diS)Nz}The *addl_attrs on orm.defer is deprecated. Please use method chaining in conjunction with defaultload() to indicate a path.F)rwarn_deprecatedrrr6r. addl_attrsr!r!r"r6cCs||fdddS)acIndicate 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:`.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` FTrrr5r!r!r"undefers, r<cGr7)NzThe *addl_attrs on orm.undefer is deprecated. Please use method chaining in conjunction with defaultload() to indicate a path.F)rr8rrr<r9r!r!r"r<@r;cCs|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)r rr!r!r" undefer_groupMsr=cCs t|Sr$)rr=)rr!r!r"r=qrcCs(tt|}|j|fddid|idS)aYApply 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. .. seealso:: :ref:`mapper_query_expression` query_expressionTrr)sql_expr_labeledrr)r r.rr!r!r"with_expressionvsrBcCsttj|fdd|iS)NFr)rrrB)r.rr!r!r"rBscCs0|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:`inheritance_polymorphic_load` selectinload_polymorphicTrcsrr$r)r-r'r!r!r"rrz'selectin_polymorphic..rr?)rr<r>id)r classesr!r!r"selectin_polymorphicsrFcCs&t}d|_t|f|_|||SrN)rrrrrF)base_clsrEulr!r!r"rFs   r$r)6rr_rrn attributesrbaserrrr interfacesrr path_registryr r r r rrrersqlrr@sql.baserrrrobjectrr rrrrrr!r%r'r)r+r-r/r0r4rr6r<r=rBrFr!r!r!r"s                   r8 L  *  [      !          $  $  >  0  #  !