o
    [hU                     @   s<  d Z ddlZddlZddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
mZ ddlmZ dd	lmZ dd
lmZ ddlmZ eeZG dd deZG dd deZG dd deZedddd Zedddd Ze	 dd Zejedddd Zejedddd Z ej!Ze j"Z ej#Z#dS )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$   e Zd ZdZdZdd Zdd ZdS )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


    clscachec                 C   s   || _ || _d S Nr   )selfZcls_r    r   {/home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/site-packages/sqlalchemy/ext/baked.py__init__/   s   
zBakery.__init__c                 G   s   |  | j||S r   r   )r   
initial_fnargsr   r   r   __call__3   s   zBakery.__call__N)__name__
__module____qualname____doc__	__slots__r   r   r   r   r   r   r
   !   s
    r
   c                   @   s   e Zd ZdZdZd/ddZed0dd	Zd
d Zd/ddZ	dd Z
dd Zdd Zdd Zdd Zdd Zd1ddZdd Zd2dd Zd2d!d"Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. ZdS )3
BakedQueryz3A builder object for :class:`.query.Query` objects.)steps_bakery
_cache_key_spoiledr   c                 C   s*   d| _ | || |g| _d| _|| _d S )Nr   F)r   _update_cache_keyr   r   r   )r   bakeryr   r   r   r   r   r   <   s
   
zBakedQuery.__init__   Nc                 C   s   t | tj||dS )zSConstruct a new bakery.

        :return: an instance of :class:`.Bakery`

        )Z
size_alert)r
   r   ZLRUCache)r   sizeZ_size_alertr   r   r   r!   C   s   zBakedQuery.bakeryc                 C   s2   t t }| j|_t| j|_| j|_| j|_|S r   )r   __new__r   listr   r   r   )r   b1r   r   r   _cloneM   s   
zBakedQuery._clonec                 C   s   |  j |jf| 7  _ d S r   )r   __code__r   fnr   r   r   r   r    U   s   zBakedQuery._update_cache_keyc                 C   s&   t |tr| j|  | S | | | S r   )
isinstancetupleadd_criteriar   otherr   r   r   __iadd__X   s
   


zBakedQuery.__iadd__c                 C   s   t |tr
| j| S | |S r   )r+   r,   with_criteriar.   r   r   r   __add___   s   


zBakedQuery.__add__c                 G   s   |  || | 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    r   appendr)   r   r   r   r-   e   s   zBakedQuery.add_criteriac                 G   s   |   j|g|R  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   r   r   r1   p   s   zBakedQuery.with_criteriac                 C   s
   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   sessionr   r   r   for_sessiony   s   
zBakedQuery.for_sessionc                 C   s
   |  |S r   )r7   r5   r   r   r   r      s   
zBakedQuery.__call__Fc                 C   s4   |s| j s|  }| jd7  _|jg| _d| _ | S )a  Cancel 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.Query` object is built from scratch each
         time, with all creational functions being called on each
         invocation.

        )Z_query_onlyT)r   r'   r   _retrieve_baked_queryr   )r   fullZ_spoil_pointr   r   r   spoil   s   

zBakedQuery.spoilc                 C   s   | j |jf S )a  Return 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.Query` object is part of what's cached
        and needs to match the type of :class:`_query.Query` that a later
        session will want to use.

        )r   Z
_query_clsr5   r   r   r   _effective_key   s   zBakedQuery._effective_keyc                 C   s   |   }|j|||d |S )z)Cloning version of _add_lazyload_options.)
cache_path)r'   _add_lazyload_options)r   optionseffective_pathr<   qr   r   r   _with_lazyload_options   s   z!BakedQuery._with_lazyload_optionsc                    s~   d}|s }|j d jr| jdd nD ]}||}|du r'| jdd q|dur/||7 }q|  fdd|j | dS )	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.

        r   r   T)r9   FNc                    s   |   j S r   )Z_with_current_pathZ_conditional_optionsr@   r?   r>   r   r   <lambda>   s
    z2BakedQuery._add_lazyload_options.<locals>.<lambda>)pathZis_aliased_classr:   Z_generate_cache_keyr-   )r   r>   r?   r<   keyopt	cache_keyr   rC   r   r=      s"   

z BakedQuery._add_lazyload_optionsc                 C   sF   | j | |d }|d u r| |}|d | j | |< ||S r   )r   getr;   	_as_querywith_session)r   r6   queryr   r   r   r8      s   

z BakedQuery._retrieve_baked_queryc                 C   s~   |  |}| }| || d |_|jd  |_}|jd| ji|_dD ]	}|j	
|d  q'|jjr=|| j| |< |S )NZcompiled_cache)Z
_correlateZ	_from_objZ_mapper_adapter_mapZ	_joinpathZ
_joinpoint)rJ   Z_compile_context_bake_subquery_loadersr6   rL   rK   Z_execution_optionsunionr   __dict__popZ_bake_okr;   )r   r6   rL   contextattrr   r   r   _bake   s   
zBakedQuery._bakec                 C   sN   t |tr|}nt |tr|j}|du rtdntdt| | |S )a5  Return the :class:`_query.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.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.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+   r   r   r6   sa_excArgumentError	TypeErrortyperJ   )r   Zquery_or_sessionr6   r   r   r   to_query   s   
%

zBakedQuery.to_queryc                 C   s.   | j d |}| j dd  D ]}||}q|S Nr      )r   )r   r6   rL   stepr   r   r   rJ   2  s   
zBakedQuery._as_queryc                    s   g  |j d< }t|j  D ]/\} t tr=d|v r9t| j fdd}| j| |_|| |	||j f |j |= qdS )ab  convert 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_queriesZsubqueryc                     s    S r   r   )r   vr   r   rD   F  s    z3BakedQuery._bake_subquery_loaders.<locals>.<lambda>N)

attributesr%   itemsr+   r   r   r   r   rS   r3   )r   r6   rQ   r\   kbkr   r]   r   rM   9  s   	

z!BakedQuery._bake_subquery_loadersc                 C   sv   d|j vrdS |j d D ],\}}}t| j|fdd}||_||}	|D ]}
|	|
}	q%|	jdi ||j |< qdS )zRetrieve subquery eager loaders stored by _bake_subquery_loaders
        and turn them back into Result objects that will iterate just
        like a Query object.

        r\   Nc                 S   s
   | | S r   )rK   )sessr@   r   r   r   rD   Y     
 z5BakedQuery._unbake_subquery_loaders.<locals>.<lambda>r   )r_   r   r   r   r7   with_post_criteriaparams)r   r6   rQ   rf   Zpost_criteriara   rH   rL   rb   r@   r*   r   r   r   _unbake_subquery_loadersL  s   

z#BakedQuery._unbake_subquery_loaders)r   )r"   N)Fr   )r   r   r   r   r   r   classmethodr!   r'   r    r0   r2   r-   r1   r7   r   r:   r;   rA   r=   r8   rS   rX   rJ   rM   rg   r   r   r   r   r   7   s0    
	
		


#	4r   c                   @   s   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!S )"r4   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.

    bqr6   _params_post_criteriac                 C   s   || _ || _i | _g | _d S r   ri   )r   rj   r6   r   r   r   r   m  s   
zResult.__init__c                 O   sB   t |dkr||d  nt |dkrtd| j| | S )z@Specify parameters to be replaced into the string SQL statement.rZ   r   zFparams() takes zero or one positional argument, which is a dictionary.)lenupdaterT   rU   rk   )r   r   kwr   r   r   rf   s  s   zResult.paramsc                 C   s   |r| j | | S r   )rl   extend)r   Zfnsr   r   r   _using_post_criteria  s   zResult._using_post_criteriac                 C   s   |  |gS )a'  Add a criteria function that will be applied post-cache.

        This adds a function that will be run against the
        :class:`_query.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.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


        )rq   )r   r*   r   r   r   re     s   zResult.with_post_criteriac                 C   s.   | j | j| j}| jD ]}||}q|S r   )rj   rJ   r6   rf   rk   rl   )r   r@   r*   r   r   r   rJ     s   

zResult._as_queryc                 C   s   t |  S r   )strrJ   r   r   r   r   __str__  s   zResult.__str__c                 C   s   | j }| jjr
|jrt|  S |j|| jd }|d u r%|	| j}t

|}| j|_|j
 |_|| j|| j| j d|j_|jrN|jsN| j  |j| j| j}| jD ]}||}q\||S NT)rj   r6   Zenable_baked_queriesr   iterrJ   r   rI   r;   rS   copyr_   rg   rk   rl   Z	statementZ
use_labelsZ	autoflushZpopulate_existingZ
_autoflushrL   rf   rK   Z_execute_and_instances)r   rj   Zbaked_contextrQ   r@   r*   r   r   r   __iter__  s&   




zResult.__iter__c                    s:   t td | j fdd}|| j| j	 S )zreturn the 'count'.

        Equivalent to :meth:`_query.Query.count`.

        Note this uses a subquery to ensure an accurate count regardless
        of the structure of the original statement.

        .. versionadded:: 1.1.6

        *c                    s
   |   S r   )Z	from_selfrB   colr   r   rD     rd   zResult.count.<locals>.<lambda>)
r   countr	   rj   r1   r7   r6   rf   rk   scalar)r   rj   r   rz   r   r|     s   zResult.countc                 C   s:   z|   }t|ts|W S |d W S  tjy   Y dS w )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.Query.scalar`.

        .. versionadded:: 1.1.6

        r   N)oner+   r,   orm_excNoResultFound)r   retr   r   r   r}     s   


zResult.scalarc                 C   sH   | j dd }t|| j| j| j}t	|dkr"|d S dS )zRReturn the first row.

        Equivalent to :meth:`_query.Query.first`.

        c                 S   s   |  ddS rY   )slicerB   r   r   r   rD     s    zResult.first.<locals>.<lambda>r   N)
rj   r1   r%   r7   r6   rf   rk   rq   rl   rm   )r   rj   r   r   r   r   first  s   
zResult.firstc              
   C   s`   z|   }W n tjy$ } ztjtd|d W Y d}~dS d}~ww |du r.td|S )zkReturn exactly one result or raise an exception.

        Equivalent to :meth:`_query.Query.one`.

        z"Multiple rows were found for one())Zreplace_contextNzNo row was found for one())one_or_noner   MultipleResultsFoundr   Zraise_r   )r   r   errr   r   r   r~     s   
z
Result.onec                 C   s6   t | }t|}|dkr|d S |dkrdS td)zReturn one or zero results, or raise an exception for multiple
        rows.

        Equivalent to :meth:`_query.Query.one_or_none`.

        .. versionadded:: 1.0.9

        rZ   r   Nz*Multiple rows were found for one_or_none())r%   rm   r   r   )r   r   lr   r   r   r     s   	zResult.one_or_nonec                 C   s   t | S )zKReturn all rows.

        Equivalent to :meth:`_query.Query.all`.

        )r%   rs   r   r   r   all  s   z
Result.allc                 C   s    | j jd | j}||| jS )z`Retrieve an object based on identity.

        Equivalent to :meth:`_query.Query.get`.

        r   )rj   r   r6   Z	_get_impl_load_on_pk_identity)r   identrL   r   r   r   rI   "  s   z
Result.getc                    s   |  j\  fdd}j}| }| j f7  _||tdd D }tfddtj	D }t
|jjd
i |}t|}|dkrXt |r^|d S d	S )z6Load the given primary key identity from the database.c                    sx    }|   }|  d |_d v r&tfddtjD }t||}||dd}||_	j
D ]}||}q3|S )Nc                    s"   g | ]\}}|d u r | j qS r   rF   ).0r{   value_get_paramsr   r   
<listcomp>=  s
    z>Result._load_on_pk_identity.<locals>.setup.<locals>.<listcomp>TF)r'   Z_get_conditionZ	_order_bysetzipprimary_keysql_utilZadapt_criterion_to_nullZ_adapt_clauseZ
_criterionrl   )rL   Z_lcl_get_clauser@   Znonesr*   _get_clauser   Zmapperprimary_key_identityr   r   r   setup3  s(   
	

z*Result._load_on_pk_identity.<locals>.setupc                 s   s    | ]}|d u V  qd S r   r   )r   elemr   r   r   	<genexpr>[  s    z.Result._load_on_pk_identity.<locals>.<genexpr>c                    s   g | ]\}} | j |fqS r   r   )r   Zid_valr   r   r   r   r   _  s    z/Result._load_on_pk_identity.<locals>.<listcomp>rZ   r   Nr   )Z_mapper_zeror   rj   r'   r   r1   r,   dictr   r   r%   r7   r6   rf   rm   r   r   )r   rL   r   r   rj   rf   resultr   r   r   r   r   ,  s.   

	zResult._load_on_pk_identityN)r   r   r   r   r   r   rf   rq   re   rJ   rt   rx   r|   r}   r   r~   r   r   rI   r   r   r   r   r   r4   b  s$    
r4   z1.2z5Baked lazy loading is now the default implementation.c                   C   s   dS )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.

    Nr   r   r   r   r   bake_lazy_loadersq  s   
r   c                   C   s   t d)aH  Disable 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:`_orm.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)NotImplementedErrorr   r   r   r   unbake_lazy_loaders~  s   r   c                 C   s   |  |ddiS )zxIndicate that the given attribute should be loaded using "lazy"
    loading with a "baked" query used in the load.

    ZlazyZbaked_select)Zset_relationship_strategy)ZloadoptrR   r   r   r   baked_lazyload  s   r   zFBaked lazy loading is now the default implementation for lazy loading.c                  G      t jt jj| di S )NFr   Z_UnboundLoadZ
_from_keysr   keysr   r   r   r        c                  G   r   ru   r   r   r   r   r   baked_lazyload_all  r   r   )$r   rw   logging r   rT   r   Zormr   r   Z	orm.queryr   Zorm.sessionr   sqlr   r	   r   	getLoggerr   logobjectr
   r   r4   
deprecatedr   r   Zloader_optionr   Z_add_unbound_fnZ_add_unbound_all_fnr   Z_unbound_fnZ_unbound_all_fnr!   r   r   r   r   <module>   sZ   	
  -  




