B 4]S@s<dZddlZddlZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z dd lmZdd lmZddlmZeeZGd d d eZGd ddeZGdddeZeddddZeddddZe ddZejeddddZejeddddZ ej!Ze j"Z ej#Z#dS)zBaked query extension. Provides a creational pattern for the :class:`.query.Query` object which allows the fully constructed object, Core select statement, and string compiled result to be fully cached. N)exc)util)strategy_options)Query)Session)func)literal_columnc@s$eZdZdZdZddZddZdS)BakeryzCallable which returns a :class:`.BakedQuery`. This object is returned by the class method :meth:`.BakedQuery.bakery`. It exists as an object so that the "cache" can be easily inspected. .. versionadded:: 1.2 )clscachecCs||_||_dS)N)r r )selfZcls_r rG/opt/alt/python37/lib64/python3.7/site-packages/sqlalchemy/ext/baked.py__init__/szBakery.__init__cGs||j||S)N)r r )r initial_fnargsrrr__call__3szBakery.__call__N)__name__ __module__ __qualname____doc__ __slots__rrrrrrr !s r c@seZdZdZdZd/ddZed0dd Zd d Zd1d d Z ddZ ddZ ddZ ddZ ddZddZd2ddZddZd3dd Zd4d!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.ZdS)5 BakedQueryz3A builder object for :class:`.query.Query` objects.)steps_bakery _cache_key_spoiledrcCs*d|_||||g|_d|_||_dS)NrF)r_update_cache_keyrrr)r bakeryrrrrrr<s  zBakedQuery.__init__NcCst|tj||dS)zSConstruct a new bakery. :return: an instance of :class:`.Bakery` )Z size_alert)r rZLRUCache)r sizeZ _size_alertrrrrCszBakedQuery.bakerycCs2tt}|j|_t|j|_|j|_|j|_|S)N)r__new__rlistrrr)r Zb1rrr_cloneMs   zBakedQuery._clonecCs|j|jf|7_dS)N)r__code__)r fnrrrrrUszBakedQuery._update_cache_keycCs$t|tr|j|n |||S)N) isinstancetuple add_criteria)r otherrrr__iadd__Xs   zBakedQuery.__iadd__cCs"t|tr|j|S||SdS)N)r'r( with_criteria)r r*rrr__add___s  zBakedQuery.__add__cGs||||j||S)zAdd a criteria function to this :class:`.BakedQuery`. This is equivalent to using the ``+=`` operator to modify a :class:`.BakedQuery` in-place. )rrappend)r r&rrrrr)es  zBakedQuery.add_criteriacGs|j|f|S)zAdd a criteria function to a :class:`.BakedQuery` cloned from this one. This is equivalent to using the ``+`` operator to produce a new :class:`.BakedQuery` with modifications. )r$r))r r&rrrrr,pszBakedQuery.with_criteriacCs t||S)zReturn a :class:`.Result` object for this :class:`.BakedQuery`. This is equivalent to calling the :class:`.BakedQuery` as a Python callable, e.g. ``result = my_baked_query(session)``. )Result)r sessionrrr for_sessionyszBakedQuery.for_sessioncCs ||S)N)r1)r r0rrrrszBakedQuery.__call__FcCs4|s*|js*|}|jd7_|jg|_d|_|S)azCancel any query caching that will occur on this BakedQuery object. The BakedQuery can continue to be used normally, however additional creational functions will not be cached; they will be called on every invocation. This is to support the case where a particular step in constructing a baked query disqualifies the query from being cacheable, such as a variant that relies upon some uncacheable value. :param full: if False, only functions added to this :class:`.BakedQuery` object subsequent to the spoil step will be non-cached; the state of the :class:`.BakedQuery` up until this point will be pulled from the cache. If True, then the entire :class:`.Query` object is built from scratch each time, with all creational functions being called on each invocation. )Z _query_onlyT)rr$r_retrieve_baked_queryr)r ZfullZ _spoil_pointrrrspoils   zBakedQuery.spoilcCs|j|jfS)aReturn the key that actually goes into the cache dictionary for this :class:`.BakedQuery`, taking into account the given :class:`.Session`. This basically means we also will include the session's query_class, as the actual :class:`.Query` object is part of what's cached and needs to match the type of :class:`.Query` that a later session will want to use. )rZ _query_cls)r r0rrr_effective_keys zBakedQuery._effective_keycCs|}|j|||d|S)z2Cloning version of _add_lazyload_options. ) cache_path)r$_add_lazyload_options)r optionseffective_pathr5qrrr_with_lazyload_optionssz!BakedQuery._with_lazyload_optionscszd}|s }|jdjr"|n:x8D]0}||}|dkrH|q(|dk r(||7}q(W|fdd|j|dS)a*Used by per-state lazy loaders to add options to the "lazy load" query from a parent query. Creates a cache key based on given load path and query options; if a repeatable cache key cannot be generated, the query is "spoiled" so that it won't use caching. rrFNcs|jS)N)Z_with_current_pathZ_conditional_options)r9)r8r7rrsz2BakedQuery._add_lazyload_options..)pathZis_aliased_classr3Z_generate_cache_keyr))r r7r8r5keyopt cache_keyr)r8r7rr6s        z BakedQuery._add_lazyload_optionscCsF|j||d}|dkr<||}|d|j||<||S)N)rgetr4 _as_query with_session)r r0queryrrrr2s  z BakedQuery._retrieve_baked_querycCsz||}|}|||d|_|jd|_}|jd|ji|_xdD]}|j |dqPW||j| |<|S)NZcompiled_cache)Z _correlateZ _from_objZ_mapper_adapter_mapZ _joinpathZ _joinpoint) rAZ_compile_context_bake_subquery_loadersr0rCrBZ_execution_optionsunionr__dict__popr4)r r0rCcontextattrrrr_bakes  zBakedQuery._bakecCsNt|tr|}n4t|tr4|j}|dkrDtdntdt|||S)a#Return the :class:`.Query` object for use as a subquery. This method should be used within the lambda callable being used to generate a step of an enclosing :class:`.BakedQuery`. The parameter should normally be the :class:`.Query` object that is passed to the lambda:: sub_bq = self.bakery(lambda s: s.query(User.name)) sub_bq += lambda q: q.filter( User.id == Address.user_id).correlate(Address) main_bq = self.bakery(lambda s: s.query(Address)) main_bq += lambda q: q.filter( sub_bq.to_query(q).exists()) In the case where the subquery is used in the first callable against a :class:`.Session`, the :class:`.Session` is also accepted:: sub_bq = self.bakery(lambda s: s.query(User.name)) sub_bq += lambda q: q.filter( User.id == Address.user_id).correlate(Address) main_bq = self.bakery( lambda s: s.query(Address.id, sub_bq.to_query(q).as_scalar()) ) :param query_or_session: a :class:`.Query` object or a class :class:`.Session` object, that is assumed to be within the context of an enclosing :class:`.BakedQuery` callable. .. versionadded:: 1.3 Nz1Given Query needs to be associated with a Sessionz)Query or Session object expected, got %r.) r'rrr0sa_exc ArgumentError TypeErrortyperA)r Zquery_or_sessionr0rrrto_querys%   zBakedQuery.to_querycCs2|jd|}x|jddD] }||}qW|S)Nr)r)r r0rCsteprrrrA,s zBakedQuery._as_querycsg|jd<}xpt|jD]^\}ttrd|krtt|jfdd}|j||_||| ||jf|j|=qWdS)abconvert subquery eager loaders in the cache into baked queries. For subquery eager loading to work, all we need here is that the Query point to the correct session when it is run. However, since we are "baking" anyway, we may as well also turn the query into a "baked" query so that we save on performance too. baked_queriesZsubquerycsS)Nr)r)vrrr;@z3BakedQuery._bake_subquery_loaders..N) attributesr#itemsr'rrrrrJr.)r r0rHrRkbkr)rSrrD3s    z!BakedQuery._bake_subquery_loadersc Cslxf|jdD]X\}}}t|j|fdd}||_||} x|D]} | | } q@W| jf||j|<q WdS)zRetrieve subquery eager loaders stored by _bake_subquery_loaders and turn them back into Result objects that will iterate just like a Query object. rRcSs ||S)N)rB)Zsessr9rrrr;PrTz5BakedQuery._unbake_subquery_loaders..N)rUrrrr1with_post_criteriaparams) r r0rHrZZ post_criteriarWr?rCrXr9r&rrr_unbake_subquery_loadersFs  z#BakedQuery._unbake_subquery_loaders)r)r N)r)F)N)N)rrrrrr classmethodrr$rr+r-r)r,r1rr3r4r:r6r2rJrOrArDr[rrrrr7s.         # 4rc@seZdZdZdZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!S)"r/a Invokes a :class:`.BakedQuery` against a :class:`.Session`. The :class:`.Result` object is where the actual :class:`.query.Query` object gets created, or retrieved from the cache, against a target :class:`.Session`, and is then invoked for results. )bqr0_params_post_criteriacCs||_||_i|_g|_dS)N)r]r0r^r_)r r]r0rrrrdszResult.__init__cOsBt|dkr||dnt|dkr2td|j||S)z@Specify parameters to be replaced into the string SQL statement.rPrzFparams() takes zero or one positional argument, which is a dictionary.)lenupdaterKrLr^)r rkwrrrrZjs   z Result.paramscCs|r|j||S)N)r_extend)r Zfnsrrr_using_post_criteriaws zResult._using_post_criteriacCs ||gS)aAdd a criteria function that will be applied post-cache. This adds a function that will be run against the :class:`.Query` object after it is retrieved from the cache. Functions here can be used to alter the query in ways that **do not affect the SQL output**, such as execution options and shard identifiers (when using a shard-enabled query object) .. warning:: :meth:`.Result.with_post_criteria` functions are applied to the :class:`.Query` object **after** the query's SQL statement object has been retrieved from the cache. Any operations here which intend to modify the SQL should ensure that :meth:`.BakedQuery.spoil` was called first. .. versionadded:: 1.2 )rd)r r&rrrrY|szResult.with_post_criteriacCs2|j|j|j}x|jD] }||}qW|S)N)r]rAr0rZr^r_)r r9r&rrrrAs  zResult._as_querycCs t|S)N)strrA)r rrr__str__szResult.__str__cCs|j}|jjr|jr t|S|j||jd}|dkrJ| |j}t |}|j|_|j |_ | |j||j |jd|j_|jr|js|j|j|j |j}x|jD] }||}qW||S)NT)r]r0Zenable_baked_queriesriterrArr@r4rJcopyrUr[r^r_Z statementZ use_labelsZ autoflushZpopulate_existingZ _autoflushrCrZrBZ_execute_and_instances)r r]Z baked_contextrHr9r&rrr__iter__s$        zResult.__iter__cs:ttd|jfdd}||j|j S)zreturn the 'count'. Equivalent to :meth:`.Query.count`. Note this uses a subquery to ensure an accurate count regardless of the structure of the original statement. .. versionadded:: 1.1.6 *cs |S)N)Z from_self)r9)colrrr;rTzResult.count..) rcountr r]r,r1r0rZr^scalar)r r]r)rkrrls z Result.countcCs:y|}t|ts|S|dStjk r4dSXdS)zReturn the first element of the first result or None if no rows present. If multiple rows are returned, raises MultipleResultsFound. Equivalent to :meth:`.Query.scalar`. .. versionadded:: 1.1.6 rN)oner'r(orm_exc NoResultFound)r retrrrrms  z Result.scalarcCsL|jdd}t||j|j|j}t |dkrD|dSdSdS)zLReturn the first row. Equivalent to :meth:`.Query.first`. cSs |ddS)NrrP)slice)r9rrrr;rTzResult.first..rN) r]r,r#r1r0rZr^rdr_r`)r r]rqrrrfirsts   z Result.firstcCsHy |}Wn tjk r,tdYnX|dkr@td|SdS)zeReturn exactly one result or raise an exception. Equivalent to :meth:`.Query.one`. z"Multiple rows were found for one()NzNo row was found for one()) one_or_noneroMultipleResultsFoundrp)r rqrrrrns   z Result.onecCs:t|}t|}|dkr |dS|dkr,dStddS)zReturn one or zero results, or raise an exception for multiple rows. Equivalent to :meth:`.Query.one_or_none`. .. versionadded:: 1.0.9 rPrNz*Multiple rows were found for one_or_none())r#r`roru)r rqlrrrrts zResult.one_or_nonecCst|S)zEReturn all rows. Equivalent to :meth:`.Query.all`. )r#)r rrrall sz Result.allcCs |jjd|j}|||jS)zZRetrieve an object based on identity. Equivalent to :meth:`.Query.get`. r)r]rr0Z _get_impl_load_on_pk_identity)r ZidentrCrrrr@sz Result.getcs|j\fdd}j}|}|jf7_||tddD}tfddtj D}t | j j f|}t|}|dkrtn|r|dSd Sd S) z6Load the given primary key identity from the database.cs|}|}|d|_dkrLtfddtjD}t||}||dd}||_ xj D] }||}qhW|S)Ncs"g|]\}}|dkr|jqS)N)r=).0rkvalue) _get_paramsrr 1sz>Result._load_on_pk_identity..setup..TF) r$Z_get_conditionZ _order_bysetzip primary_keysql_utilZadapt_criterion_to_nullZ _adapt_clauseZ _criterionr_)rCZ_lcl_get_clauser9Znonesr&) _get_clauser{mapperprimary_key_identityr rrsetup&s    z*Result._load_on_pk_identity..setupcss|]}|dkVqdS)Nr)ryelemrrr Nsz.Result._load_on_pk_identity..csg|]\}}|j|fqSr)r=)ryZid_valr)r{rrr|Ssz/Result._load_on_pk_identity..rPrN)Z _mapper_zerorr]r$rr,r(dictr~rr#r1r0rZr`roru)r rCrrr]rZresultrvr)rr{rrr rrxs&   zResult._load_on_pk_identityN)rrrrrrrZrdrYrArfrirlrmrsrnrtrwr@rxrrrrr/Ys"  r/z1.2z5Baked lazy loading is now the default implementation.cCsdS)zEnable the use of baked queries for all lazyloaders systemwide. The "baked" implementation of lazy loading is now the sole implementation for the base lazy loader; this method has no effect except for a warning. Nrrrrrbake_lazy_loadersds rcCs tddS)aDDisable the use of baked queries for all lazyloaders systemwide. This method now raises NotImplementedError() as the "baked" implementation is the only lazy load implementation. The :paramref:`.relationship.bake_queries` flag may be used to disable the caching of queries on a per-relationship basis. z4Baked lazy loading is now the default implementationN)NotImplementedErrorrrrrunbake_lazy_loadersqs rcCs||ddiS)zxIndicate that the given attribute should be loaded using "lazy" loading with a "baked" query used in the load. ZlazyZ baked_select)Zset_relationship_strategy)ZloadoptrIrrrbaked_lazyloadsrzFBaked lazy loading is now the default implementation for lazy loading.cGstjtjj|diS)NF)r _UnboundLoad _from_keysr)keysrrrrscGstjtjj|diS)NT)rrrr)rrrrbaked_lazyload_allsr)$rrhZloggingrrKrZormrorZ orm.queryrZ orm.sessionrZsqlrr rZ getLoggerrlogobjectr rr/Z deprecatedrrZ loader_optionrZ_add_unbound_fnZ_add_unbound_all_fnrZ _unbound_fnZ_unbound_all_fnrrrrrsF          $