o znhU@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||_||_dSNr )selfcls_r r?/usr/local/lib/python3.10/dist-packages/sqlalchemy/ext/baked.py__init__/s zBakery.__init__cGs||j||Srr )r initial_fnargsrrr__call__3szBakery.__call__N)__name__ __module__ __qualname____doc__ __slots__rrrrrrr !s   r c@seZdZdZdZd/ddZed0dd Zd d Zd/d d Z ddZ ddZ ddZ ddZ ddZddZd1ddZddZd2dd Zd2d!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.ZdS)3 BakedQueryz3A builder object for :class:`.query.Query` objects.)steps_bakery _cache_key_spoiledrcCs*d|_||||g|_d|_||_dS)NrF)r_update_cache_keyrr r)rbakeryrrrrrr<s   zBakedQuery.__init__NcCst|tj||dS)zSConstruct a new bakery. :return: an instance of :class:`.Bakery` ) size_alert)r rLRUCache)r size _size_alertrrrr"CszBakedQuery.bakerycCs2tt}|j|_t|j|_|j|_|j|_|Sr)r__new__rlistrrr )rb1rrr_cloneMs  zBakedQuery._clonecCs|j|jf|7_dSr)r__code__rfnrrrrr!UszBakedQuery._update_cache_keycCs&t|tr |j||S|||Sr) isinstancetuple add_criteriarotherrrr__iadd__Xs   zBakedQuery.__iadd__cCst|tr |j|S||Sr)r/r0 with_criteriar2rrr__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. )r!rappendr-rrrr1es  zBakedQuery.add_criteriacGs|j|g|RS)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+r1r-rrrr5pszBakedQuery.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)``. )Resultrsessionrrr for_sessionys zBakedQuery.for_sessioncCs ||Sr)r;r9rrrrs zBakedQuery.__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. ) _query_onlyT)r r+r_retrieve_baked_queryr)rfull _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. )r _query_clsr9rrr_effective_keys zBakedQuery._effective_keycCs|}|j|||d|S)z2Cloning version of _add_lazyload_options. ) cache_path)r+_add_lazyload_options)roptionseffective_pathrCqrrr_with_lazyload_optionssz!BakedQuery._with_lazyload_optionscsvd}|s}|jdjr|nD]}||}|dur#|q|dur+||7}q|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|jSr)_with_current_path_conditional_optionsrGrFrErrs z2BakedQuery._add_lazyload_options..)pathis_aliased_classr@_generate_cache_keyr1)rrErFrCkeyopt cache_keyrrLrrDs"      z BakedQuery._add_lazyload_optionscCsF|j||d}|dur||}|d|j||<||Sr)rgetrB _as_query with_session)rr:queryrrrr=s  z BakedQuery._retrieve_baked_querycCs~||}|}|||d|_|jd|_}|jd|ji|_dD] }|j |dq'|jj r=||j| |<|S)Ncompiled_cache) _correlate _from_obj_mapper_adapter_map _joinpath _joinpoint) rU_compile_context_bake_subquery_loadersr:rWrV_execution_optionsunionr__dict__pop_bake_okrB)rr:rWcontextattrrrr_bakes  zBakedQuery._bakecCsNt|tr|}nt|tr|j}|durtdntdt|||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/rrr:sa_exc ArgumentError TypeErrortyperU)rquery_or_sessionr:rrrto_querys %  zBakedQuery.to_querycCs.|jd|}|jddD]}||}q|SNr)r)rr:rWsteprrrrU3s zBakedQuery._as_querycsg|jd<}t|jD]/\}ttr=d|vr9t|jfdd}|j||_||| ||jf|j|=qdS)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_queriessubquerycsSrr)rvrrrMGsz3BakedQuery._bake_subquery_loaders..N) attributesr)itemsr/rrrrrgr7)rr:rerqkbkrrsrr_:s    z!BakedQuery._bake_subquery_loadersc Csvd|jvrdS|jdD],\}}}t|j|fdd}||_||} |D]} | | } q%| jdi||j|<q dS)zRetrieve subquery eager loaders stored by _bake_subquery_loaders and turn them back into Result objects that will iterate just like a Query object. rqNcSs ||Sr)rV)sessrGrrrrMZ z5BakedQuery._unbake_subquery_loaders..r)rurrrr;with_post_criteriaparams) rr:rer| post_criteriarwrSrWrxrGr.rrr_unbake_subquery_loadersMs   z#BakedQuery._unbake_subquery_loaders)r)r#N)Fr)rrrrrr classmethodr"r+r!r4r6r1r5r;rr@rBrHrDr=rgrmrUr_r~rrrrr7s0       # 4 rc@seZdZdZdZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!S)"r8a 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. bqr:_params_post_criteriacCs||_||_i|_g|_dSrr)rrr:rrrrns zResult.__init__cOsBt|dkr||dn t|dkrtd|j||S)z@Specify parameters to be replaced into the string SQL statement.rorzFparams() takes zero or one positional argument, which is a dictionary.)lenupdaterhrir)rrkwrrrr|ts   z Result.paramscCs|r|j||Sr)rextend)rfnsrrr_using_post_criterias 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 )r)rr.rrrr{s zResult.with_post_criteriacCs.|j|j|j}|jD]}||}q|Sr)rrUr:r|rr)rrGr.rrrrUs  zResult._as_querycCs t|Sr)strrUrrrr__str__s zResult.__str__cCs|j}|jjr |jrt|S|j||jd}|dur%| |j}t |}|j|_|j |_ | |j||j |jd|j_|jrN|jsN|j|j|j |j}|jD]}||}q\||SNT)rr:enable_baked_queriesr iterrUrrTrBrgcopyrur~rr statement use_labels autoflushpopulate_existing _autoflushrWr|rV_execute_and_instances)rr baked_contextrerGr.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 |Sr) from_selfrKcolrrrMrzzResult.count..) rcountr rr5r;r:r|rscalar)rrrrrrs z Result.countcCs:z|}t|ts |WS|dWStjyYdSw)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/r0orm_exc NoResultFoundrretrrrrs   z Result.scalarcCsH|jdd}t||j|j|j}t |dkr"|dSdS)zLReturn the first row. Equivalent to :meth:`.Query.first`. cSs |ddSrn)slicerKrrrrMs zResult.first..rN) rr5r)r;r:r|rrrr)rrrrrrfirsts  z Result.firstcCs>z|}Wn tjytdw|durtd|S)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_nonerMultipleResultsFoundrrrrrrs  z Result.onecCs6t|}t|}|dkr|dS|dkrdStd)zReturn one or zero results, or raise an exception for multiple rows. Equivalent to :meth:`.Query.one_or_none`. .. versionadded:: 1.0.9 rorNz*Multiple rows were found for one_or_none())r)rrr)rrlrrrrs zResult.one_or_nonecCst|S)zEReturn all rows. Equivalent to :meth:`.Query.all`. )r)rrrrallsz Result.allcCs |jjd|j}|||jS)zZRetrieve an object based on identity. Equivalent to :meth:`.Query.get`. r)rrr: _get_impl_load_on_pk_identity)ridentrWrrrrTsz Result.getcs|j\fdd}j}|}|jf7_||tddD}tfddtj D}t | j j d i|}t|}|dkrXt|r^|dSd S) z6Load the given primary key identity from the database.csx}|}|d|_dvr&tfddtjD}t||}||dd}||_ j D]}||}q3|S)Ncs"g|] \}}|dur|jqSrrQ).0rvalue _get_paramsrr :s z>Result._load_on_pk_identity..setup..TF) r+_get_condition _order_bysetzip primary_keysql_utiladapt_criterion_to_null _adapt_clause _criterionr)rW_lcl_get_clauserGnonesr. _get_clausermapperprimary_key_identityrrrsetup0s(    z*Result._load_on_pk_identity..setupcss|]}|duVqdSrr)relemrrr Xsz.Result._load_on_pk_identity..csg|] \}}|j|fqSrr)rid_valrrrrr\s z/Result._load_on_pk_identity..rorNr) _mapper_zerorrr+rr5r0dictrrr)r;r:r|rrr)rrWrrrr|resultrrrrr)s.   zResult._load_on_pk_identityN)rrrrrrr|rr{rUrrrrrrrrrTrrrrrr8cs$  r8z1.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_loadersns rcCstd)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 implementation)NotImplementedErrorrrrrunbake_lazy_loaders{s rcCs||ddiS)zxIndicate that the given attribute should be loaded using "lazy" loading with a "baked" query used in the load. lazy baked_select)set_relationship_strategy)loadoptrfrrrbaked_lazyloadsrzFBaked lazy loading is now the default implementation for lazy loading.cGtjtjj|diS)NFr _UnboundLoad _from_keysrkeysrrrr cGrrrrrrrbaked_lazyload_allrr)$rrloggingrrhrormrr orm.queryr orm.sessionrsqlrr r getLoggerrlogobjectr rr8 deprecatedrr loader_optionr_add_unbound_fn_add_unbound_all_fnr _unbound_fn_unbound_all_fnr"rrrrsZ           .