B 4]@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 dSd"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 dTd=d>Z/e/j"d?d>Z/e d@dAZ0e0j"dBdAZ0e dCdDZ1e1j"dEdDZ1e dFdGZ2e2j"dHdGZ2e dIdJZ3e3j"dKdJZ3e dLdMZ4e4j"dNdMZ4e dOdPZ5e5j"dQdPZ5dS)Uz )util)QueryableAttribute)_class_to_mapper)_is_aliased_class)_is_mapped_class)InspectionAttr) MapperOption)PropComparator)_DEFAULT_TOKEN)_WILDCARD_TOKEN) PathRegistry) TokenRegistry)_orm_full_deannotate)exc)inspect) expression) _generative) GenerativecseZdZdZddZeddZddZfdd Zd Z d Z d Z d Z d d Z ddZddZd/ddZddZddZddZeddZed0ddZed1dd Zed!d"Zed#d$Zd2d%d&Zd'd(Zd)d*Zd+d,Zd-d.ZZS)3LoadaqRepresents 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` cCs0t|}|j|_t|_i|_d|_d|_dS)NF) rZ_path_registrypathr OrderedDictcontext local_opts_of_typeis_class_strategy)selfentityZinsprR/opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/orm/strategy_options.py__init__Hs  z Load.__init__cCs&||}||_i|_i|_d|_|S)N)__new__rrrr)clsrloadrrrfor_existing_pathRs  zLoad.for_existing_pathc sx|jdjrdSg}xJ|jD]:\\}}|dkr:q"x t|jj|D]\}}||k rLPqLWjprjjd}|||}|dks"|sjsq"g} xN|D]F} t| tj r| | q| jrdS| j r| | j q| | j qW| r|| dkr|jr| |j n |jrdS| t| jp0djrVtfddtjDndq"W|sldSt|SdS)NFloaderrcsg|]}|j|fqSr)r).0key)objrr sz,Load._generate_cache_key..)ris_aliased_classritemszipr _chop_path isinstancer string_typesappendZ is_propertyr)class_ is_mappertuplestrategyrsorted) rr serializedr)Z loader_path local_elemZobj_elemZendpointZchoppedZserialized_pathtokenr)r*r_generate_cache_key[sJ     $ zLoad._generate_cache_keycstt|}i|_|S)N)superr _generater)rcloned) __class__rrr=szLoad._generateFNcCs||ddS)NT)_process)rqueryrrr process_queryszLoad.process_querycCs||ddS)NF)r@)rrArrrprocess_query_conditionallysz Load.process_query_conditionallycCs\|j}|rJxL|jD].\\}}}|||}|dk r||j||f<qWn|j|jdS)N) _current_pathrr-r/ _attributesupdate)rrAraiseerr current_pathr: start_pathr&Zchopped_start_pathrrrr@s z Load._processTcCs|j}d|_|r>|js>t|tr,tdntd|jft|tjr| t }| t sd|r|rnd|_ |r~d||f}|r|j s|j|}||}||_|S|rt|}n|j}yt|j|}Wn0tk r|rtd||fndSYn X|j}} ||}nHt|rTt|j|dsZ|rLtd||jfndSn|j} } t|j|ds|rtd||jt|d kr|jjr|jj rd |d |jjfnd fndSt|d drR|j} t| } } |j| |jd}| j s(tj | j!j"| j!dd|d} t| } |j| #|jd| || | }| |_n|| }|dk rn| $||jr||j}||_|S)Nz3Wildcard token cannot be followed by another entityz7Mapped attribute '%s' does not refer to a mapped entityFz%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)?rZpath_with_polymorphicT)ZaliasedZ_use_mapper_pathZ_existing_alias)%r has_entityr0r sa_exc ArgumentErrorproprr1endswithr r propagate_to_loadersr,parentr:rrrgetattrr3AttributeErrorpropertyrorm_utilZ$_entity_corresponds_to_use_path_impllenr4__name__Z entity_pathgetrZwith_polymorphicmapperZ base_mappersetZ _get_strategy)rrattr for_strategy wildcard_keyrGZexisting_of_typeZ default_tokenentZfound_propertyrOZacZext_infoZ of_type_infoexistingrrr_generate_paths                        zLoad._generate_pathcCs d|jfS)NzLoad(strategy=%r))r6)rrrr__str__>sz Load.__str__cCs|dk rtt|}|S)N)r5r7r-)rr6rrr _coerce_stratAszLoad._coerce_stratcCs tddS)NzHOnly 'unbound' loader options may be used with the Load.options() method)NotImplementedError)rrRappliedboundrrr_apply_to_parentFszLoad._apply_to_parentcGs<i}t|t }|rtdx|D]}||||q"WdS)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)r0 _UnboundLoadrdrg)roptsZ apply_cacherfoptrrroptionsLs   z Load.optionscCsB||}d|_||_||j||d||_|dk r>|dS)NFZ relationship)rcrrQrarr6_set_path_strategy)rr\r6rQrrrset_relationship_strategyvs zLoad.set_relationship_strategycCsp||}d|_xT|D]L}|}||_||j||dd|_|rP|j||rZd|_ | qWd|_dS)NFcolumnT) rcrr=r6rarrQrrF is_opts_onlyrl)rattrsr6ri opts_onlyr\r>rrrset_column_strategys    zLoad.set_column_strategycCsP||}x@|D]8}||j||d}|}||_||_d|_|qWdS)NT)rcrarr=r6rQrl)rrpr6r\rr>rrrset_generic_strategys  zLoad.set_generic_strategycCsT||}|}d|_||jd|d}||_||_d|_||j |dS)NT) rcr=rrarr6rQrlrrF)rr6rir>rrrrset_class_strategys zLoad.set_class_strategycCsv|s|s>||jd}|r.|r<|j|jqr||d|n4||jd}||d||rr|jrr|j|jdS)Nr&)rYrrrFr[ro)rrrreplace merge_optsr`rrr _set_for_paths zLoad._set_for_pathcCsh|js|jjr|jj}n|j}|jrNx>|D]}|j|j|d|jdq.Wn|j|j|d|jddS)NT)rurv) rrrLrRis_tokengenerate_for_superclassesrwrro)reffective_pathrrrrrls zLoad._set_path_strategycCs|j}|j|d<|S)Nr)__dict__copyrZ serialize)rdrrr __getstate__s zLoad.__getstate__cCs|j|t|j|_dS)N)r{rFr Z deserializer)rstaterrr __setstate__s zLoad.__setstate__cCsd}xtt||jD]\}\}}t|tjrd|dkrH|dtrH|S|dtfkrd||j krddS||krpqqt|t r|j r|j r| |rqqdSqW||ddS)Nr'r%:zrelationship:%sr) enumerater.rr0rr1rPr r r)rr4isa)rto_chopric_tokenZp_tokenrrrr/s"    zLoad._chop_path)T)T)NF)TF) rX __module__ __qualname____doc__r classmethodr$r;r=rorr6rQrBrCr@rarbrcrgrrkrmrrrsrtrwrlr~rr/ __classcell__rr)r?rr s:& F   *   rc@seZdZdZddZdZddZddZd d Zd d Z d dZ ddZ ddZ e ddZddZd ddZddZddZddZdS)!rha2Represent 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_bindr)rrrrr sz_UnboundLoad.__init__FcCsd}xr|jD]h}xbt|j|jD]\}}||k r Pq W||jdgddd}|r ||}|dkrhdS|r ||7}q W|sdS|SdS)Nrr%F)rr.r _bind_loaderr;)rrr8valr9Zval_elemrjZc_keyrrrr; s   z _UnboundLoad._generate_cache_keycCs|j|dS)N)rr2)rrrrrlsz_UnboundLoad._set_path_strategycs|kr|S|}||<|j|_|jr|jd}t|tjrd|trd|dddt }| j|jdd||jdfdd|j D}j |_ |j ||j |j |S)Nr'rr%csh|]}|qSr)rg)r(elem)rerfrRrr 9sz0_UnboundLoad._apply_to_parent..)r=r6rr0rr1rPr splitr rarextendrrF)rrRrerfr>r\Z new_to_bindr)rerfrRrrg s$    z_UnboundLoad._apply_to_parentcCsp|r6t|tjr6|ttfkr6|tkr*d|_d||f}|rXt|drX|jsX|dd}|rf||f}||_|S)NFz%s:%sr'r%) r0rr1r r rQrrr)rrr\r]r^rrrraCs     z_UnboundLoad._generate_pathcCs"|j}|j|jdd|d<|S)NT)filter_aliased_classr)r{r|_serialize_pathr)rr}rrrr~Ss z_UnboundLoad.__getstate__cCsg}xl|dD]`}t|trdt|dkr6|\}}d}n |\}}}t||}|rX||}||q||qWt||d<||_dS)Nrr)r0r5rWrSof_typer2r{)rrretr)r"ZpropkeyrrOrrrrXs       z_UnboundLoad.__setstate__cCsP|jd}x@|jD]6}||kr|||dd|jD|j|j|qWdS)NZ_unbound_load_dedupescSsg|] }|jqSr)Z entity_zero)r(r_rrrr+qsz)_UnboundLoad._process..)rEraddrZ_mapper_entitiesrD)rrArGZdedupesrrrrr@ks   z_UnboundLoad._processcsvt}ddfdd|D}x8|ddD](}|rF|||f|}n ||}d|_q.W|||df|}d|_|S) NcSsHt|tjr>|tkrtfS|dtr4|dd}|dS|fSdS)N.r)r0rr1r r startswithr)r)rrr _split_key{s   z+_UnboundLoad._from_keys.._split_keycsg|]}|D]}|qqSrr)r(r)r:)rrrr+sz+_UnboundLoad._from_keys..r%r'TF)rh defaultload_is_chain_link)r"ZmethkeysZchainedkwrjZ all_tokensr:r)rr _from_keysws   z_UnboundLoad._from_keyscCsd}xtt||D]\}\}\}}t|tjrl|dkrN|dtrN|S|dtfkr||j krdSqt|t r|j |k s|j |k r|j j r|j |sdSqW|d7}||dS)Nr'r%rzrelationship:%sr)rr.Zpairsr0rr1rPr r r)r rU _parententityr4r)rrrrrZp_entityZp_proprrrr/s"       z_UnboundLoad._chop_pathcCsg}x|D]}t|tr`|rF|jrFt|jjrF||jj|jdfq||jj|j|jfq t|t r||jj|jdfq ||q W|S)N) r0rrrr,r2Z _parentmapperr3r)r )rrrrr:rrrrs    z_UnboundLoad._serialize_pathcCs|j}|jr|r||df7}|r.|||}|s6dS|d}t|tjrZ||||}nRt|tr~|j}| |||j |}n.|jrt |rt |}||krd}n t d|sdS|} t| } |dk r|| _n| j}|j| _|j| _|j| _| j} | jsFxHt|D]<\} }| | j|| t|dkr0|jndd|sdSqW| j|j| jsp| jjrp| jj} n| j} | jrxD| D]} | j|| |j |jdqWn| 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 attributesr)rurv)rrr/r0rr1_find_entity_basestringr rU_find_entity_prop_comparatorrrrrMrNrrr6rorrarWrrFrLrRrxryrwr)rentitiesrHrrGrIr:rrOZ path_elementr&ridxrzrrrrsr$       z_UnboundLoad._bind_loadercCst|r|}nt|}xn|D]}t||r|SqW|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. z, css|]}t|VqdS)N)str)r(xrrr ^sz<_UnboundLoad._find_entity_prop_comparator..) rrrVZ_entity_corresponds_tolistrMrNrZclsname_as_plain_nametypejoin)rrrOrZrGZ searchforr_rrrrGs  z)_UnboundLoad._find_entity_prop_comparatorcCs|dtrVtt|dkrd|rdtdddd|Dddd|Dfn|trdd}x(|D]}|SW|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.z, css|]}t|VqdS)N)r)r(r_rrrrmsz7_UnboundLoad._find_entity_basestring..css|]}d|VqdS)zLoad(%s).some_option('*')Nr)r(r_rrrrosFzJQuery has only expression-based entities - can't find property named "%s".)rPr rWrrMrNrr )rrr:rGr_rrrrcs$   z$_UnboundLoad._find_entity_basestringN)F)rXrrrr rr;rlrgrar~rr@rrr/rrrrrrrrrhs" #  rhc@s,eZdZddZddZddZddZd S) loader_optioncCsdS)Nr)rrrrr szloader_option.__init__cCs8|j|_}||_tt|r(td|tt|||S)Nz#Load class already has a %s method.)rXnamefnhasattrr TypeErrorsetattr)rrrrrr__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)Z _unbound_fnrrr)rrZfn_docrrr_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)Zadd_deprecation_to_docstring)rrrZ deprecatedZ_unbound_all_fn)rrrrr_add_unbound_all_fns  z!loader_option._add_unbound_all_fnN)rXrrr rrrrrrrrs rNcCs`|dk r"t|ts>t|}|j}nt|ddr>t|j}|j}|j|ddidd}||jd<|S)anIndicate 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. :func:`.contains_eager` also accepts an `alias` argument, which is the string name of an alias, an :func:`~sqlalchemy.sql.expression.alias` construct, or an :func:`~sqlalchemy.orm.aliased` construct. Use this when the eagerly-loaded rows are to come from an aliased table:: user_alias = aliased(User) sess.query(Order).\ join((user_alias, Order.user)).\ options(contains_eager(Order.user, alias=user_alias)) When using :func:`.contains_eager` in conjunction with inherited subclasses, the :meth:`.RelationshipProperty.of_type` modifier should also be used in order to set up the pathing properly:: sess.query(Company).\ outerjoin(Company.employees.of_type(Manager)).\ options( contains_eager( Company.employees.of_type(Manager), alias=Manager) ) .. seealso:: :ref:`loading_toplevel` :ref:`contains_eager` NrlazyjoinedF)rQZeager_from_alias)r0rrZ selectablerSrrmr)loadoptr\aliasinfoZotr>rrrcontains_eagers0    rcOsttj|d|S)NT)rhrr)rrrrrrscGs.||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 FT)deferred instrument*Z undefer_pks)rr)rrpr>rrr load_onlys "rcGs tj|S)N)rhr)rprrrr0scCs&||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:`.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)rmr)rr\rr&rrr joinedload5sV rcOsttj|d|S)NF)rhrr)rrrrrrscOsttj|d|S)NT)rhrr)rrrrrjoinedload_allsrcCs||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` rZsubquery)rm)rr\rrr subqueryloadsrcGsttj|diS)NF)rhrr)rrrrrscGsttj|diS)NT)rhrr)rrrrsubqueryload_allsrcCs||ddiS)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` rZselectin)rm)rr\rrr selectinloadsrcGsttj|diS)NF)rhrr)rrrrrscGsttj|diS)NT)rhrr)rrrrselectinload_allsrcCs||ddiS)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` rZselect)rm)rr\rrrlazyloadsrcGsttj|diS)NF)rhrr)rrrrrscGsttj|diS)NT)rhrr)rrrr lazyload_all srcCs||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` rZ immediate)rm)rr\r&rrr immediateloadsrcGsttj|diS)NF)rhrr)rrrrr%scCs||ddiS)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` rnoload)rm)rr\rrrr*srcGsttj|diS)NF)rhrr)rrrrr=sFcCs||d|rdndiS)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` rZ raise_on_sqlraise)rm)rr\Zsql_onlyrrr raiseloadBs rcOsttj|d|S)NF)rhrr)rrrrrrgscCs ||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` N)rm)rr\rrrrls"rcGsttj|diS)NF)rhrr)rrrrrscCs||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` T)rr)rr)rr)rrrdefers:rcGs&|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_deprecatedrhrr)r) addl_attrsrrrrs cCs||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` FT)rr)rr)rr)rrrundefers,rcGs&|rtdttj|f|diS)NzThe *addl_attrs on orm.undefer is deprecated. Please use method chaining in conjunction with defaultload() to indicate a path.F)rrrhrr)r)rrrrrs 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)rq)rr)rrrrr undefer_group srcCs t|S)N)rhr)rrrrrDscCs(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` Zquery_expressionTr)ri)sql_exprZ_labeledrrr)rr)rrrrwith_expressionIsrcCsttj|fdd|iS)NFr)rhrr)r)rrrrrkscCs0|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` Zselectinload_polymorphicTrcss|]}t|VqdS)N)r)r(r"rrrrsz'selectin_polymorphic..)r))ri)rtr5r7id)rclassesrrrselectin_polymorphicrs rcCs&t}d|_t|f|_|||S)NT)rhrrrr)Zbase_clsrZulrrrrs   )N)N)F)6rrKrrVZ attributesrbaserrrrZ interfacesrr Z path_registryr r r r rrrMrZsqlrrZsql.baserrrrhobjectrrrrrrrrrrrrrrrrrrrrrrrrrr s                   [8 ?+ [!" $%? 1 $"