a
    ~g:                    @  s  d Z ddlm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 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 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% 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m0Z0 d'dlmZ1 d'd)lm2Z2 d'd*lm3Z3 d'd+lm4Z4 d'dlmZ d'dl4mZ5 d'd,l4m6Z6 d'd-l7m8Z8 d'd.l7m9Z9 d'd/l:m;Z; e
rfd
d0l<m=Z= d
d1lm>Z> d'd2l?m@Z@ dfd4d5ZAejBjCd3d3d6G d7d8 d8e&ZDe3jEejBjCd9d3d6G d:d; d;e&ZFe3jEejBjCd9d<G d=d> d>eFZGe3jEejBjCd9d9d?ejBjCd9d9d9d@ejBjCd9dAG dBdC dCe&ZHG dDdE dEZIG dFdG dGe&ZJe3jEej>jCd9dAG dHdI dIe&ZKe3jEej>jCdJdKej>jCddKG dLdM dMeJZLe3jEej>jCd9dKej>jCdNdKej>jCdOdKej>jCdPdKej>jCdQdKG dRdS dSeJejMe3jNZOG dTdU dUZPG dVdW dWeJZQej>jCdXdKG dYdZ dZeQZRe3jEej>jCd[dKG d\d] d]eQZSe3jEej>jCd^dKej>jCd3dKG d_d` d`eJZTe3jEej>jCdadKG dbdc dceQejMZUddde ZVdS )gzWsqlalchemy.orm.interfaces.LoaderStrategy
   implementations, and related MapperOptions.    )annotationsN)Any)Dict)Optional)Tuple)TYPE_CHECKING)Union   )
attributes)exc)
interfaces)loading)path_registry)
properties)query)relationships)
unitofwork)util)_DEFER_FOR_STATE)_RAISE_FOR_STATE)_SET_DEFERRED_EXPIRED)ATTR_WAS_SET)LoaderCallableStatus)PASSIVE_OFF)PassiveFlag)_column_descriptions)ORMCompileState)ORMSelectCompileState)QueryContext)LoaderStrategy)StrategizedProperty)_state_session)InstanceState)Load)_none_only_set)AliasedClass   )event)inspect)log)sql)visitors)LABEL_STYLE_TABLENAME_PLUS_COL)Select)Literal)Mapper)RelationshipProperty)ColumnElementFc	                   s"  g }
|o| j |r"| jr"|
t | j| jjv rV| jj| j \|
fdd |rf|
tj |r| j	  r| j
r|
 fdd |jD ]}| |j| ju r|j| jstj|j| jf| |||o| jp| jtju ||||| p| j | jd|	}|
D ]}|||  q
qd S )Nc                   s   t j| |j fi S N)orm_util_validator_eventskeydescprop)fnopts ^/var/www/html/emsaiapi.evdpl.com/venv/lib/python3.9/site-packages/sqlalchemy/orm/strategies.py<lambda>\   s   z%_register_attribute.<locals>.<lambda>c                   s   t |  S r2   )r
   backref_listenersr6   )backrefuselistr;   r<   r=   j   s   )parent_tokenr@   compare_function	useobjecttrackparenttypecallable	callable_active_history
impl_classsend_modified_eventsdoc)r@   single_parentappendsingle_parent_validatorr5   parent
validatorsr   track_cascade_eventsback_populates_effective_sync_backrefself_and_descendants_propsgetclass_manager_attr_has_implr
   register_attribute_implclass_	directionr   	ONETOMANYviewonlyrJ   )r8   mapperrC   rB   rE   rF   Zproxy_propertyrG   rH   kwZlisten_hooksmr7   hookr;   )r?   r9   r:   r@   r<   _register_attributeF   sZ    





ra   )
instrumentdeferredc                      s6   e Zd ZdZdZ fddZd
ddZdd	 Z  ZS )UninstrumentedColumnLoaderzRepresent a non-instrumented MapperProperty.

    The polymorphic_on argument of mapper() often results in this,
    if the argument is against the with_polymorphic selectable.

    columnsc                   s   t  || | jj| _d S r2   )super__init__parent_propertyrf   selfrN   strategy_key	__class__r;   r<   rh      s    z#UninstrumentedColumnLoader.__init__Nc           	      K  s*   | j D ]}|r|j | }||| qd S r2   )rf   _append_dedupe_col_collection)	rk   compile_statequery_entitypathloadoptadaptercolumn_collectionkwargscr;   r;   r<   setup_query   s    


z&UninstrumentedColumnLoader.setup_queryc	           	      C  s   d S r2   r;   	rk   contextrq   rr   rs   r]   resultrt   
populatorsr;   r;   r<   create_row_processor   s    z/UninstrumentedColumnLoader.create_row_processor)N)	__name__
__module____qualname____doc__	__slots__rh   rx   r}   __classcell__r;   r;   rm   r<   rd      s    
rd   Tc                      s>   e Zd ZdZdZ fddZdddZdd	 Zd
d Z  Z	S )ColumnLoaderz8Provide loading behavior for a :class:`.ColumnProperty`.)rf   is_compositec                   s*   t  || | jj| _t| jd| _d S )Ncomposite_class)rg   rh   ri   rf   hasattrr   rj   rm   r;   r<   rh      s    
zColumnLoader.__init__Fc	                 K  sv   | j D ]<}
|r6|r,||
}
|
d u r6 d S n
|j |
 }
||
| q| j d }|rh|j | }|d u rhd S ||| j< d S Nr   )rf   adapt_check_presentro   ri   )rk   rp   rq   rr   rs   rt   ru   memoized_populatorscheck_for_adaptrv   rw   fetchr;   r;   r<   rx      s    




zColumnLoader.setup_queryc                 C  s`   d| _ | jd j}| jjpD| jd jpD|jd uoD|j|jd | ju }t	| j|d|j
|d d S )NTr   F)rC   rB   rG   )is_class_levelrf   typeri   rG   primary_keyversion_id_col_columntopropertyrU   ra   compare_values)rk   r]   coltyperG   r;   r;   r<   init_class_attribute   s"    


z!ColumnLoader.init_class_attributec	                 C  sZ   | j D ]:}	|r|j |	 }	||	d}
|
r|d | j|
f  qVq|d | jdf d S NFquickexpireT)rf   _getterrL   r5   )rk   rz   rq   rr   rs   r]   r{   rt   r|   colgetterr;   r;   r<   r}     s    

z!ColumnLoader.create_row_processor)F)
r~   r   r   r   r   rh   rx   r   r}   r   r;   r;   rm   r<   r      s    
!r   )query_expressionc                      s4   e Zd Z fddZdd Zdd Zdd Z  ZS )	ExpressionColumnLoaderc                   s<   t  || t d  t fdd| jjD | _d S )Nc                 3  s   | ]}|   V  qd S r2   )compare.0rw   nullr;   r<   	<genexpr>)  s   z2ExpressionColumnLoader.__init__.<locals>.<genexpr>)	rg   rh   r*   r   labelanyri   rf   _have_default_expressionrj   rm   r   r<   rh   "  s
    zExpressionColumnLoader.__init__c                 K  s   d }	|r|j r|j }	n| jr$| jj}	|	d u r0d S |	D ]}
|rF|j|
 }
||
| q4|	d }|rv|j| }|d u rvd S ||| j< d S r   )_extra_criteriar   ri   rf   ro   )rk   rp   rq   rr   rs   rt   ru   r   rv   rf   rw   r   r;   r;   r<   rx   -  s"    


z"ExpressionColumnLoader.setup_queryc	                 C  sh   |rd|j rd|j }	|	D ]:}
|r&|j|
 }
||
d}|r|d | j|f  qdq|d | jdf d S r   )r   rf   r   rL   r5   )rk   rz   rq   rr   rs   r]   r{   rt   r|   rf   r   r   r;   r;   r<   r}   R  s    

z+ExpressionColumnLoader.create_row_processorc                 C  s(   d| _ t| j|d| jd jjdd d S )NTFr   )rC   rB   accepts_scalar_loader)r   ra   ri   rf   r   r   rk   r]   r;   r;   r<   r   l  s    z+ExpressionColumnLoader.init_class_attribute)r~   r   r   rh   rx   r}   r   r   r;   r;   rm   r<   r     s   %r   )rc   rb   )rc   rb   	raiseload)
do_nothingc                      sN   e Zd ZdZdZ fddZdd Zdd Zdd
dZdd Z	dd Z
  ZS )DeferredColumnLoaderzAProvide loading behavior for a deferred :class:`.ColumnProperty`.)rf   groupr   c                   sJ   t  || t| jdr"td| jdd| _| jj| _| jj	| _	d S )Nr   z8Deferred loading for composite types not implemented yetr   F)
rg   rh   r   ri   NotImplementedErrorstrategy_optsrU   r   rf   r   rj   rm   r;   r<   rh     s    
zDeferredColumnLoader.__init__c	           
   
   C  s   |j rB|jjjrB| j|jjjv rB| jd|||||||| nH| jsv| j	rX| jj
}	n| jj}	|d | j|	f n|d | jdf d S )N)rc   Frb   Tnewr   F)refresh_stater   _compile_options_only_load_propsr5   ri   _get_strategyr}   r   r   _raise_column_loader_deferred_column_loaderrL   )
rk   rz   rq   rr   rs   r]   r{   rt   r|   Zset_deferred_for_local_stater;   r;   r<   r}     s4    z)DeferredColumnLoader.create_row_processorc                 C  s,   d| _ t| j|d| jd jj| jdd d S )NTFr   )rC   rB   rF   load_on_unexpire)r   ra   ri   rf   r   r   _load_for_stater   r;   r;   r<   r     s    z)DeferredColumnLoader.init_class_attributeNc	           
      K  s   |j jr| jjsT|r(t| j| jjsT|rF| j	rF|j
d| j	 dsT|r|| j|v r|| jdj|||||||fi |	 n.| jrt|| j< n| jst|| j< n
t|| j< d S )Nzundefer_group_%sFr   )compile_options_render_for_subqueryri   _renders_in_subqueriessetrf   intersectionrN   _should_undefer_in_wildcardr   
local_optsrU   r5   r   rx   r   r   r   r   r   )
rk   rp   rq   rr   rs   rt   ru   r   only_load_propsr^   r;   r;   r<   rx     sP    


z DeferredColumnLoader.setup_queryc                   s   j stjS |tj@ stjS jj} jr@ fdd|j	D }n j g}fdd|D }t
}|d u rtdt j f  jr |d tjt|t tjS )Nc                   s4   g | ],}t |trt |jtr|j jkr|jqS r;   )
isinstancer    strategyr   r   r5   )r   prk   r;   r<   
<listcomp>	  s
   
z8DeferredColumnLoader._load_for_state.<locals>.<listcomp>c                   s   g | ]}| j v r|qS r;   )
unmodified)r   k)stater;   r<   r         zfParent instance %s is not bound to a Session; deferred load operation of attribute '%s' cannot proceedraise)r5   r   
ATTR_EMPTYr   SQL_OKPASSIVE_NO_RESULTmanagerr]   r   iterate_propertiesr!   orm_excDetachedInstanceErrorr3   	state_strr   _invoke_raise_loadr   load_scalar_attributesr   r   r   )rk   r   passivelocalparenttoloadr   sessionr;   )rk   r   r<   r     s0    

z$DeferredColumnLoader._load_for_statec                 C  s   t d| f d S )Nz+'%s' is not available due to raiseload=Truesa_excInvalidRequestErrorrk   r   r   lazyr;   r;   r<   r   '  s    z'DeferredColumnLoader._invoke_raise_load)N)r~   r   r   r   r   rh   r}   r   rx   r   r   r   r;   r;   rm   r<   r   x  s   
3 
3(r   c                   @  s0   e Zd ZdZddddddZejfdd	Zd
S )LoadDeferredColumnsz7serializable loader object used by DeferredColumnLoaderFstrboolr5   r   c                 C  s   || _ || _d S r2   r   )rk   r5   r   r;   r;   r<   rh   0  s    zLoadDeferredColumns.__init__c                 C  s>   | j }|jj}|j| }| jr$d}nd}||}|||S )N)rc   Tr   )r   T)r   r   )r5   r   r]   rT   r   r   r   )rk   r   r   r5   r   r8   rl   r   r;   r;   r<   __call__4  s    

zLoadDeferredColumns.__call__N)F)r~   r   r   r   rh   r
   r   r   r;   r;   r;   r<   r   -  s   r   c                      s,   e Zd ZdZdZ fddZdd Z  ZS )AbstractRelationshipLoaderz0LoaderStratgies which deal with related objects.)r]   targetr@   entityc                   s:   t  || | jj| _| jj| _| jj| _| jj| _d S r2   )rg   rh   ri   r]   r   r   r@   rj   rm   r;   r<   rh   J  s
    


z#AbstractRelationshipLoader.__init__c	           	   
   C  s    | j d||||||||S )N))r   	immediate)ri   r   r}   ry   r;   r;   r<   #_immediateload_create_row_processorQ  s    z>AbstractRelationshipLoader._immediateload_create_row_processor)r~   r   r   r   r   rh   r   r   r;   r;   rm   r<   r   E  s   r   c                   @  s   e Zd ZdZdS )DoNothingLoaderzRelationship loader that makes no change to the object's state.

    Compared to NoLoader, this loader does not initialize the
    collection/attribute to empty/none; the usual default LazyLoader will
    take effect.

    N)r~   r   r   r   r;   r;   r;   r<   r   j  s   r   noload)r   c                   @  s$   e Zd ZdZdZdd Zdd ZdS )NoLoaderzQProvide loading behavior for a :class:`.Relationship`
    with "lazy=None".

    r;   c                 C  s    d| _ t| j|d| jjd d S )NT)rC   rE   )r   ra   ri   collection_classr   r;   r;   r<   r     s    zNoLoader.init_class_attributec	           
        s$    fdd}	|d   j|	f d S )Nc                   s&    j rt| | j n
d | j< d S r2   )r@   r
   init_state_collectionr5   r   dict_rowr   r;   r<   invoke_no_load  s    z5NoLoader.create_row_processor.<locals>.invoke_no_loadr   )rL   r5   )
rk   rz   rq   rr   rs   r]   r{   rt   r|   r   r;   r   r<   r}     s    zNoLoader.create_row_processorN)r~   r   r   r   r   r   r}   r;   r;   r;   r<   r   v  s   
r   selectr   raise_on_sqlZbaked_selectc                      s   e Zd ZU dZdZded< ded< ded< ded< d	ed
< d	dd fddZdd Zdd Zdd Z	dd Z
ddddejfddZdd Zeddd Zd d! Z  ZS )"
LazyLoaderztProvide loading behavior for a :class:`.Relationship`
    with "lazy=True", that is loads when first accessed.

    )
_lazywhere_rev_lazywhereZ_lazyload_reverse_option	_order_byuse_getis_aliased_class_bind_to_col_equated_columns_rev_bind_to_col_rev_equated_columns_simple_lazy_clause_raise_always_raise_on_sqlzColumnElement[bool]r   zDict[str, ColumnElement[Any]]r   r   r   zRelationshipProperty[Any]ri   zTuple[Any, ...])rN   rl   c                   s8  t  || | jd dk| _| jd dk| _t| jj| _| jj	}|
 \| _| _| _|j
dd\| _| _| _| jjrdd t| jjD | _nd | _| jd| | j | j o| j o| jjd	 j| jdd
| jjd| _| jr4t| jD ]4}|| jjv r| jj| D ]}| j| | j|< qq| jd|  d S )Nr   r   r   T)reverse_directionc                 S  s   g | ]}t |d diqS )
_orm_adaptT)sql_util_deep_annotater   elemr;   r;   r<   r     s   z'LazyLoader.__init__.<locals>.<listcomp>z%s lazy loading clause %sr   Fuse_proxiescompare_keysequivalentsz4%s will use Session.get() to optimize instance loads)rg   rh   r   r   r  r(   r   r   ri   _join_conditioncreate_lazy_clauser   r   r   r   r   r   order_byr   to_listr   loggerinfor@   _get_clauser   r]   _equivalent_columnsr   list)rk   rN   rl   join_conditionr   rw   rm   r;   r<   rh     sN    


zLazyLoader.__init__c              	   C  sv   d| _ | jj}| jjr d}d}n4| jjtjus4| jsL|rBd}d}qTd}d}nd }}t| j|d| j	| jj
||d d S )NTF)rC   rF   rE   rG   _deferred_history)r   ri   _legacy_inactive_history_stylerG   rZ   r   	MANYTOONEr   ra   r   r   )rk   r]   r  rG   r  r;   r;   r<   r      s2    zLazyLoader.init_class_attributec                   sd   t | jddi}|| j } g dd }t|i d|i  fdd}t|i d|i}|fS )Nr  Tc                 S  s
   d| _ d S )NF)unique	bindparamr;   r;   r<   visit_bindparam+  s    zFLazyLoader._memoized_attr__simple_lazy_clause.<locals>.visit_bindparamr  c                   sF   | j  v r$| j | j  d f n| jd u rB| jd | jf d S r2   )_identifying_keyrL   r5   callablevaluer  bind_to_colparamsr;   r<   r  0  s    

)r  r  r   r   r+   traversecloned_traverse)rk   	lazywhere	criterionr  r;   r   r<   "_memoized_attr__simple_lazy_clause"  s    

z-LazyLoader._memoized_attr__simple_lazy_clausec                 C  s   | j \}}|d u r(t|dd |D S | jj}| }t|}|tj	@ rV|tj	N }i }|D ]J\}	}
}|
d ur|r|tj
@ r||||
|}n||||
|}|||	< q^||fS )Nc                 S  s   g | ]\}}}|qS r;   r;   )r   r5   identr  r;   r;   r<   r   G  r   z4LazyLoader._generate_lazy_clause.<locals>.<listcomp>)r   r  adapt_criterion_to_nullri   rN   objr
   instance_dictr   INIT_OKLOAD_AGAINST_COMMITTED#_get_committed_state_attr_by_column_get_state_attr_by_column)rk   r   r   r&  Z
param_keysr]   or   r"  r5   r(  r  r;   r;   r<   _generate_lazy_clauseB  s,    




z LazyLoader._generate_lazy_clausec                 C  s   t d| |f d S )Nz&'%s' is not available due to lazy='%s'r   r   r;   r;   r<   r   b  s    
zLazyLoader._invoke_raise_loadNr;   c                 C  s  |j s | jjs|jr|js tjS |j  }d }	| jo>| p>|j }
|t	j
@ sN|
r\|tj@ sb|rbtjS | jr|t	j@ s|
r|t	j@ r| ||d t|}|s|t	j@ rtjS tdt|| j f |
r| |||}	tj|	v rtjS tj|	v rtjS | jjst|	r$d S nt|	r$d S | j |jv rD|t	j@ sDtj S |j!| j"|	||d}|d urx|tj#u rrd S |S n|t	j
@ r|t	j@ stjS | $|||	||||||	S )Nr   zbParent instance %s is not bound to a Session; lazy load operation of attribute '%s' cannot proceed)r   lazy_loaded_from)%r5   ri   load_on_pending_load_pending
session_idr   r   r   r   r   r   r
   NON_PERSISTENT_OKr   r   NO_RAISERELATED_OBJECT_OKr   r!   r   r   r3   r   _get_ident_for_use_get	NEVER_SETr]   allow_partial_pksr$   r   
issupersetdictDEFERRED_HISTORY_LOADr   _identity_lookupr   PASSIVE_CLASS_MISMATCH_emit_lazyload)rk   r   r   rs   extra_criteriaextra_optionsalternate_effective_pathexecution_optionspendingprimary_key_identityr   r   instancer;   r;   r<   r   g  s    






zLazyLoader._load_for_statec                   sD   j j}tj@ r|jn|jj  fddjjD S )Nc                   s"   g | ]} j | d qS )r   r   r   pkr   Zget_attrr   rk   r   r;   r<   r     s   z5LazyLoader._get_ident_for_use_get.<locals>.<listcomp>)r   r]   r   r-  r.  r/  r=  r   )rk   r   r   r   instance_mapperr;   rM  r<   r9    s    
z!LazyLoader._get_ident_for_use_getzsqlalchemy.orm.strategy_optionsc
                   s  t jj j }
tj|
g|
jtt	j
d}tj}|d|d7 } jjd ur\| j jj}|j }|sr|tj@ rt ddi|_ j}|js|r|jr|d u r|j j }n
| j }|j}|r|jrd}|t j|f7 }||_n$|d u r|jj j }n
| j }|r | j|7  _| jd|i7  _|rn jrZ|t j!@ sZ "||d t#j$|||||	dS  j%r~ j%|_& fdd	}| j'| jff7  _' (||\}}|	rt j)*|	d
|i}	nd
|i}	 j|j+v r|t j,@ st-j.S |rt /tj0|1 r,d S nt /tj2|1 r,d S  jrN|t j!@ sN "||d |f|_3|j4|||	d}|5 6 7 } j8r|S t9|}|r|dkrt :d j  |d S d S d S )N)_raw_columns_propagate_attrs_label_styler   F)_invoke_all_eagers_lazy_loaded_from	autoflush_current_pathr   )load_optionsrE  c                   sR    j jD ]D}|jtju r|jrt|jtsj	
| jj|j ||  qd S r2   )ri   _reverse_propertyrZ   r   r  _use_getr   r   r   r#   _construct_for_existing_pathr   rU  rN   lazyloadprocess_compile_state)compile_contextZrevrk   strategy_optionsr;   r<   _lazyload_reverseB  s     

z4LazyLoader._emit_lazyload.<locals>._lazyload_reverse_sa_orm_load_options)rE  r	   zKMultiple rows returned with uselist=False for lazily-loaded attribute '%s' r   );r   	preloadedorm_strategy_optionsr   __clause_element__r-   _create_raw_selectrP  r,   r   default_compile_optionsr   default_load_optionsri   	secondaryselect_fromr]   r5   r
   NO_AUTOFLUSHimmutabledict_execution_optionsr   rV  r   	load_pathr3   LoaderCriteriaOption_with_options_path_registryr   r  r   r7  r   r   load_on_pk_identityr   _order_by_clauses_with_context_optionsr1  
EMPTY_DICT
merge_withr=  r>  r   r   has_intersection	_none_setvalues
_never_set_where_criteriaexecuter  scalarsallr@   lenwarn)rk   r   r   rG  r   rs   rB  rC  rD  rE  clauseelementstmtrV  rF  r   effective_pathr:   r_  Zlazy_clauser"  r{   lr;   r]  r<   rA    s    







zLazyLoader._emit_lazyloadc	              
     s   | j  |jjr@|jjjr@| j |jjjv r@| ||||||||S | jrP|r|jrt	
|jt | ||jrp||nd  }	|d | j |	f n,|js|jr fdd}
|d | j |
f d S )Nr   c                   s   |  |  d S r2   )_resetr   r5   r;   r<   reset_for_lazy_callable  s    	z@LazyLoader.create_row_processor.<locals>.reset_for_lazy_callable)r5   rV  _is_user_refreshr   r   r   r   r   r   r"   "_instance_level_callable_processorrV   LoadLazyAttribute_generate_extra_criteriarL   populate_existingalways_refresh)rk   rz   rq   rr   rs   r]   r{   rt   r|   Zset_lazy_callabler  r;   r  r<   r}     sF    

zLazyLoader.create_row_processor)r~   r   r   r   r   __annotations__rh   r   r'  r1  r   r   rs  r   r9  preload_modulerA  r}   r   r;   r;   rm   r<   r     s.   
	<"  	
w
 r   c                   @  s.   e Zd ZdZdd Zdd ZejfddZdS )	r  a  semi-serializable loader object used by LazyLoader

    Historically, this object would be carried along with instances that
    needed to run lazyloaders, so it had to be serializable to support
    cached instances.

    this is no longer a general requirement, and the case where this object
    is used is exactly the case where we can't really serialize easily,
    which is when extra criteria in the loader option is present.

    We can't reliably serialize that as it refers to mapped entities and
    AliasedClass objects that are local to the current process, which would
    need to be matched up on deserialize e.g. the sqlalchemy.ext.serializer
    approach.

    c                 C  s   || _ |j| _|| _|| _d S r2   r5   rl   rs   rB  )rk   r5   Zinitiating_strategyrs   rB  r;   r;   r<   rh     s    zLoadLazyAttribute.__init__c                 C  s(   | j d urtd | j| j| jddS )NzvCan't reliably serialize a lazyload() option that contains additional criteria; please use eager loading for this caser;   r  )rB  r   r~  r5   rl   rs   r   r;   r;   r<   __getstate__  s    
zLoadLazyAttribute.__getstate__c                 C  s:   | j }|jj}|j| }|j| j }|j||| j| jdS )N)rs   rB  )	r5   r   r]   rT   _strategiesrl   r   rs   rB  )rk   r   r   r5   rN  r8   r   r;   r;   r<   r     s    
zLoadLazyAttribute.__call__N)	r~   r   r   r   rh   r  r
   r   r   r;   r;   r;   r<   r    s   r  c                   @  s   e Zd ZdZdZdddZdS )
PostLoaderz;A relationship loader that emits a second SELECT statement.r;   Nc                 C  sN  |j jptjj| }| }td|i}|rF|j	dd }|dk}	nd }d}	|d ur| j
jsrtd| j
 d|j	dt|  |}|	s|dk r|d||fS |	s|dt|  |d	 i}tj||| j
r|d||fS || j
 }
|| j
 }|
|jd
sB|r(|jd |krB|d||fS n|| jrB|d||fS |d||fS )Nsa_top_level_orm_contextrecursion_depthFz'recursion_depth option on relationship z0 not valid for non-self-referential relationshipZ_recursion_depth_r   r	   loaderr&   T)rp   current_pathr3   PathRegistryroot_get_top_level_contextr   rj  r   rU   ri   _is_self_referentialr   r   rE  idunionr   PostLoadpath_existscontainsr
   lengthcontains_mapperr]   )rk   rz   rr   rs   
join_depthr  top_level_contextrE  r  Zunlimited_recursionpath_w_propZeffective_path_w_propr;   r;   r<   _setup_for_recursion  sl    


zPostLoader._setup_for_recursion)N)r~   r   r   r   r   r  r;   r;   r;   r<   r    s   r  r   c                      s8   e Zd ZdZ fddZdd Zdd Zdd	 Z  ZS )
ImmediateLoaderr  c                   s   t  || | jj| _d S r2   rg   rh   ri   r  rj   rm   r;   r<   rh   W  s    zImmediateLoader.__init__c                 C  s   | j d| d S N)r   r   ri   r   r   r   r;   r;   r<   r   [  s
    z$ImmediateLoader.init_class_attributec	                 C  sl   |j jjsd S | |||| j\}	}
}}|
s:tjtjB }ntj	tjB }t
j||	| j| j| j||||	 d S r2   )rp   r   _enable_eagerloadsr  r  r
   PASSIVE_NO_FETCH_RELATEDr   r7  r   r   r  callable_for_pathrN   ri   _load_for_path)rk   rz   rq   rr   rs   r]   r{   rt   r|   r  
run_loaderrE  r  flagsr;   r;   r<   r}   `  s,    
z$ImmediateLoader.create_row_processorc	                 C  s   |r.t |jj}	|| f|	_| }
|	f}nd }	|}
d}| j}| jd}|D ]P\}}|j	}|sj||vrP|j
||||
|d}|ttjfvrP||||| qPd S )Nr;   r  )rC  rD  rE  )r#   rr   r   _recurserz   _truncate_recursiver5   ri   r   r=  r   r   r   r   get_implset_committed_value)rk   rz   rr   states	load_onlyrs   r  r  rE  Znew_optrD  rC  r5   
lazyloaderr   	overwriter   r  r;   r;   r<   r    s:    
zImmediateLoader._load_for_path)	r~   r   r   r   rh   r   r}   r  r   r;   r;   rm   r<   r  S  s
   *r  subqueryc                      s   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd ZG dd dZdd Zdd Zdd Zdd Z  ZS )SubqueryLoaderr  c                   s   t  || | jj| _d S r2   r  rj   rm   r;   r<   rh     s    zSubqueryLoader.__init__c                 C  s   | j d| d S r  r  r   r;   r;   r<   r     s
    z#SubqueryLoader.init_class_attributec                   s   |}|j }t|d }| j|rB| j|d u rB| j| j  }n||d   }|r|j| jj| t	|t	 }|rt
j|| d  7 n||j}	 fdd|	D }
 |
|fS )Nr   r	   c                   s&   g | ]}t jd  j j| jqS r   )getattrrr   r   r   r5   r   leftmost_mapperZnew_subq_pathr;   r<   r     s
   

z0SubqueryLoader._get_leftmost.<locals>.<listcomp>)rr   r3   _class_to_mapperrN   isari   	_entitiesentity_zeroro  r}  r   r  coercelocal_columns)rk   orig_query_entity_index	subq_pathZcurrent_compile_stateis_rootZgiven_subq_pathZsubq_mapperZleftmost_prop
additionalZleftmost_colsleftmost_attrr;   r  r<   _get_leftmost  s4    
zSubqueryLoader._get_leftmostc                 C  s0  |  d }tjtj}|j|j |}|js`d|_|j	j
|gdd t||dD R   |dd |D | }	|	|_|j}
|
du rd|_n6|
d u rdd |	D D ]}t|	|jsd|_ qq|jsd	|_|jdu r|jrt|	|j}|r||	|  |t }tj||dd
}|S )NFc                 S  s    h | ]}|d  dur|d  qS )r   Nr;   )r   entr;   r;   r<   	<setcomp>  s   z?SubqueryLoader._generate_from_original_query.<locals>.<setcomp>)rp   c                 S  s   g | ]}t jt jj|qS r;   )r*   	coercionsexpectrolesColumnsClauseRole)r   r0  r;   r;   r<   r   0  s   z@SubqueryLoader._generate_from_original_query.<locals>.<listcomp>Tc                 S  s   h | ]
}|j qS r;   )tabler   r;   r;   r<   r  ?  r   r;   use_mapper_path)_clone	correlater   Query__new____dict__update	_from_obj_enable_assertionsrh  non_generativer   _adapt_col_list_get_current_adapterrO  distinct_target_key	_distinctr   r<  r   _has_row_limiting_clauserq  r   expand_column_list_from_order_by_set_entitiesset_label_styler,   r  r3   r%   )rk   orig_compile_state
orig_queryr  r  leftmost_relationshipZorig_entityqq2Ztarget_colsr  tZto_addZembed_q
left_aliasr;   r;   r<   _generate_from_original_query  sV    z,SubqueryLoader._generate_from_original_queryc                   s   g }t | }t|D ]N\}\}}|dkrR||d  d j}||rL|n|}	n|}	||	|jf qt|dk rz| n.t|d d }
|
j	r|
j
 ntj|
j
dd jj} fdd|D }|| fS )	Nr   r	   r&   r  Tr  c                   s    g | ]}t  jj| jqS r;   )r  rN   r   r5   r   parent_aliasrk   r;   r<   r     s   z2SubqueryLoader._prep_for_joins.<locals>.<listcomp>)r  pairs	enumerater]   r  rL   r5   r}  r(   r   r   r3   r%   ri   r  )rk   r  r  to_joinr  ir]   r8   Zprev_mapperZ	to_appendr  
local_cols
local_attrr;   r  r<   _prep_for_joins[  s*    zSubqueryLoader._prep_for_joinsc                 C  s0  t |}|dkr,t||d d |g}n|dkrft||d d |t||d d |g}n|dkrdd |dd D }g }|r|d}	t|	d |	d }
|r|
|d d }
n
|
|}
||
 qt||d d |d jg| t||d d |g }|D ]}
||
}q|S )Nr	   r   r&   r  c                 S  s:   g | ]2}t |d  js$t|d  n|d  j|d fqS )r   r	   )r(   r   r3   r%   r   )r   itemr;   r;   r<   r     s   	z/SubqueryLoader._apply_joins.<locals>.<listcomp>)r}  r  of_typepoprL   rN   join)rk   r  r  r  r  effective_entityZltjmiddleinnerr  attrr;   r;   r<   _apply_joins  sD    
	



zSubqueryLoader._apply_joinsc           	      C  sB   |j }|r*|jr*|t| j||f7 }||}|j| }|S r2   )rn  r   r3   rm  r   r  _with_current_pathoptions)	rk   rz   r  r  rewritten_pathr  r  rs   new_optionsr;   r;   r<   _setup_options  s    
	

zSubqueryLoader._setup_optionsc                   s&    j jr" fdd}|| j }|S )Nc                   s    |  j tt jj7  _ d S r2   eager_order_bytupler   r  ri   r  r\  r   r;   r<   _setup_outermost_orderby  s    zISubqueryLoader._setup_outermost_orderby.<locals>._setup_outermost_orderby)ri   r  _add_context_option)rk   r  r	  r;   r   r<   r	    s    z'SubqueryLoader._setup_outermost_orderbyc                   @  s4   e Zd ZdZdZdd Zdd Zdd Zd	d
 ZdS )zSubqueryLoader._SubqCollectionszGiven a :class:`_query.Query` used to emit the "subquery load",
        provide a load interface that executes the query at the
        first moment a value is needed.

        r   rE  rV  r"  subq_datac                 C  s4   |j | _ |j| _|j| _|jp i | _|| _d | _d S r2   r  )rk   rz   r  r;   r;   r<   rh      s    z(SubqueryLoader._SubqCollections.__init__c                 C  s    | j d u r|   | j ||S r2   )r  _loadrU   )rk   r5   defaultr;   r;   r<   rU   
  s    
z#SubqueryLoader._SubqCollections.getc                 C  s   t t| _| j}|jd u s J || j}| jjr<|	 }t|
| j
}t|dd D ]"\}}| j| dd |D  q\d S )Nc                 S  s   | dd  S )Nr	   r;   xr;   r;   r<   r=     r   z7SubqueryLoader._SubqCollections._load.<locals>.<lambda>c                 s  s   | ]}|d  V  qdS )r   Nr;   r   Zvvr;   r;   r<   r     r   z8SubqueryLoader._SubqCollections._load.<locals>.<genexpr>)collectionsdefaultdictr  r  r  r   with_sessionrV  _populate_existingr  r"  	itertoolsgroupbyextend)rk   r  rowsr   vr;   r;   r<   r    s    z%SubqueryLoader._SubqCollections._loadc                 C  s   | j d u r|   d S r2   )r  r  )rk   r   r   r   r;   r;   r<   r     s    
z&SubqueryLoader._SubqCollections.loaderN)	r~   r   r   r   r   rh   rU   r  r  r;   r;   r;   r<   _SubqCollections  s   	
r  c              	   C  s  |j }|jjr|jjrd S |j|}d|_|| j }||j	dd }	|	d urT|	}
n| j
}
|jjdtjjtjjf\}}|tjju }|| }|| }|jjdtf|j}t|d}|jr|jjd u rtd| |f  |j}|j|dd}| ||||\}}}}| ||||||}t|
}|jj|jdtf|d||fi|_|d}|  ||\}}}|j!| }| "|||||
}| #||||||
|}| $|}|S )	NTpath_with_polymorphic)Zsubquery_pathsNr  ormzsubqueryloader for "%s" must invoke lambda callable at %r in order to produce a new query, decreasing the efficiency of caching for this statement.  Consider using selectinload() for more effective full-lambda cachingF)legacy)%rp   r   r  _for_refresh_stater  indexloaders_require_bufferingri   rU   r
   r   r   rk  r3   r  r  r  r   _get_plugin_class_for_plugin_is_lambda_elementrV  rS  r   r~  	_resolved_create_entities_collectionr  r  r  rt  rE  _set_enable_single_critr  add_columnsr  r  r	  )rk   rz   rq   rr   r   rs   rt   rp   r  with_poly_entityr  r  r  r  r  compile_state_clsr  r  r  r  r  r  r  r  r  r;   r;   r<   _setup_query_from_rowproc$  s    	

	





	
z(SubqueryLoader._setup_query_from_rowprocc	              
     s  |r&|j jd ur&|j jjr&tdd |jrD| |||||| |S | |||| j\}	}
}	}	|
sfd S t	|j t
svd S | jj| j jjstd|  t|dkrt|j| jsd S nt|d | jsd S | ||||d | }|d u rd S |jd u sJ || j }| jj}||jd}|d u rH| ||}||jd|  r` fdd|D }| jr|| ||||| n|  ||||| d S )	NzThe subqueryload loader option is not compatible with DML statements such as INSERT, UPDATE.  Only SELECT may be used.This warning will become an exception in a future release.2.0J'%s' does not support object population - eager loading cannot be applied.r	   r  r  c                   s   g | ]} j | qS r;   re   r   rt   r;   r<   r     r   z7SubqueryLoader.create_row_processor.<locals>.<listcomp>)!rp   	statementis_dmlr   warn_deprecatedr   r   r  r  r   r   rN   rV   r5   implsupports_populationr   r   r}  r3   _entity_isar  r+  r   ri   r  rU   r
   r  r   r@   _create_collection_loader_create_scalar_loader)rk   rz   rq   rr   rs   r]   r{   rt   r|   _r  r  r  r  r;   r.  r<   r}     s    

		



z#SubqueryLoader.create_row_processorc                   sp   | | fddfdd}|d jf |d j|f |jrl|d j jf d S )Nc                   s*     |d}| j| || d S )Nr;   )rU   r  r5   r  )r   r   r   
collectionr  rk   tuple_getterr;   r<   load_collection_from_subq  s    zKSubqueryLoader._create_collection_loader.<locals>.load_collection_from_subqc                   s   j |vr | || d S r2   r  r   )r;  rk   r;   r<   &load_collection_from_subq_existing_row  s    
zXSubqueryLoader._create_collection_loader.<locals>.load_collection_from_subq_existing_rowr   existingeager_tuple_getterrL   r5   invoke_all_eagersr  )rk   rz   r{   r  r  r|   r<  r;   )r  r;  rk   r:  r<   r5    s    
z(SubqueryLoader._create_collection_loaderc                   sp   | | fddfdd}|d jf |d j|f |jrl|d j jf d S )Nc                   sL     |d}t|dkr*td  |d }| j| || d S )Nr2   r	   LMultiple rows returned with uselist=False for eagerly-loaded attribute '%s' r   )rU   r}  r   r~  r  r5   r  )r   r   r   r8  scalarr9  r;   r<   load_scalar_from_subq-  s    zCSubqueryLoader._create_scalar_loader.<locals>.load_scalar_from_subqc                   s   j |vr | || d S r2   r  r   )rD  rk   r;   r<   "load_scalar_from_subq_existing_row8  s    
zPSubqueryLoader._create_scalar_loader.<locals>.load_scalar_from_subq_existing_rowr   r=  r>  r?  )rk   rz   r{   r  r  r|   rE  r;   )r  rD  rk   r:  r<   r6  (  s    
z$SubqueryLoader._create_scalar_loader)r~   r   r   r   rh   r   r  r  r  r  r  r	  r  r+  r}   r5  r6  r   r;   r;   rm   r<   r    s   1d/6"4 	er  joinedc                      s   e Zd ZdZdZ fddZdd Zd d	d
Zdd Zdd Z	dd Z
dd Zd!dddddZdd Zdd Zdd Zdd Z  ZS )"JoinedLoaderz[Provide loading behavior for a :class:`.Relationship`
    using joined eager loading.

    r  c                   s   t  || | jj| _d S r2   r  rj   rm   r;   r<   rh   O  s    zJoinedLoader.__init__c                 C  s   | j d| d S r  r  r   r;   r;   r<   r   S  s
    z!JoinedLoader.init_class_attributeNFc	                 K  sx  |j jsdS |r0|jdur0|jjr0tdd n| jr<d|_|| j }d}
|r^| 	|||j
nd}|dur| |||||\}}}n`||j
ds| jr|jd | jkrdS n|| jrdS | ||||||||\}}}}d|_||j
dd}|dur
t|j}
nd}
|| j }tj|| j|||||
| j|d		 tj|j}|rt|durbtd
ndd |jD |_dS )z@Add a left outer join to the statement that's being constructed.NzThe joinedload loader option is not compatible with DML statements such as INSERT, UPDATE.  Only SELECT may be used.This warning will become an exception in a future release.r,  TFr  r&   r  )with_polymorphicparentmapperchained_from_outerjoinzDetected unaliased columns when generating joined load.  Make sure to use aliased=True or flat=True when using joined loading with with_polymorphic().c                 S  s   g | ]}|d ur|qS r2   r;   r   r;   r;   r<   r     s   z,JoinedLoader.setup_query.<locals>.<listcomp>)r   r  r/  r0  r   r1  r@   multi_row_eager_loadersri   _init_user_defined_eager_procr
   $_setup_query_on_user_defined_adapterr  r  r  r  r]   _generate_row_adaptereager_adding_joinsrU   r(   with_polymorphic_mappersr   r   _setup_entity_queryNONE_SETr   secondary_columnsr   r   )rk   rp   rq   rr   rs   rt   ru   rI  rJ  rv   rH  user_defined_adapterclausesadd_to_collectionr)  Z	has_nonesr;   r;   r<   rx   X  s    



zJoinedLoader.setup_queryc           
      C  s   d|j vrdS |jj}||jdd}|dur2|S |j d }|dd  \}}|d urt|trj|j|}t	j
t	jj|j||jjdd}nF||jdr||jd}	t	j
t	jj|	|jjd}n|j|jd }||d| |S )Neager_from_aliasF user_defined_eager_row_processor)
selectabler  limit_on_entityr  )r  )r   rr   rN   rU   r
   r   r   r   aliasr3   
ORMAdapter_TraceAdaptRoleJOINEDLOAD_USER_DEFINED_ALIASr]   r  r   JOINEDLOAD_PATH_WITH_POLYMORPHIC_polymorphic_adaptersr   )
rk   rs   rp   Ztarget_attributesrr   rt   r\  Zroot_mapperr8   r)  r;   r;   r<   rL    sP    


z*JoinedLoader._init_user_defined_eager_procc                 C  sV   | |}|r.|r.||}||jd| n|rF|}||jd| |j}|||fS )NrX  )_get_entity_clauseswrapr   r
   primary_columns)rk   rz   r   rr   rt   rT  rV  r;   r;   r<   rM  	  s"    

z1JoinedLoader._setup_query_on_user_defined_adapterc	                 C  s  | |jdd }	|	r|	}
nDt| j}|jr2|j}nd }tj| j|d urR|j	ddnd ddd}
t|
}|j
d| ftjtjj|| jjdddd}|jsJ |d ur|j d| jjn| jj}|sd}|j| j||||||||r|jnd	f	 |j}||jd
| ||||fS )Nr  T)flat)r\  re  r  Zjoinedloader_ormadapterF)r  adapt_requiredallow_label_resolveanonymize_labels	innerjoinr;   eager_row_processor)rU   r
   r(   r   r   rZ  r3   r%   r]   _anonymous_fromclause_memor]  r^  JOINEDLOAD_MEMOIZED_ADAPTERr  r   ri   ri  create_eager_joinsrL   _create_eager_joinr   rS  r   )rk   rp   r   rr   rs   rt   ru   rI  rJ  r)  Zto_adaptinspZalt_selectableZto_adapt_insprU  ri  rV  r;   r;   r<   rN  ,	  sd    

z"JoinedLoader._generate_row_adapterc
              	     sb  |d u r|j }
n|}
|jo|j}d }||jvr~|s~|jr~t|j|j}t|dkr^t	
d|r~|j|d  }|d | }}|d u r||j }}|j||}|rt|ddr|j|
 jr|
n j}t|j j j}n ttj j|jdd j j}n j}|jsJ | p8| p8|dkp8|jj}|	}|jd	 j fd
}|rr|t fdd|D 7 }|rtj||j|| p|jjp|ot|tj j| j  |d}n  ||d ||||}||j|< |j|_!|s0t" jj#D ]4}|
j$j%&|r|r|j'| }|(||j) q jj*r^| j+t|j,-t./ jj*7  _+d S )Nr	   zCan't identify which query entity in which to joined eager load from.   Please use an exact match when specifying the join path.r   r   FTr  Zunnestedadditional_entity_criteriar;   c                 3  s    | ]}|j r| jV  qd S r2   )propagate_to_loaders_resolve_where_criteriar]   )r   aer   r;   r<   r   	  s   z2JoinedLoader._create_eager_join.<locals>.<genexpr>isouter
_left_memo_right_memor   rY  )0r]   rK  _should_nest_selectableeager_joinsfrom_clausesr  #find_left_clause_that_matches_givenrZ  r}  r   r   
setdefaultr  aliased_insp_entity_for_mapperr  rN   r   r5   ri   r3   r%   r   r  represents_outer_joinglobal_attributesrU   r  _ORMJoinr   r*   Join_splice_nested_inner_joinstop_on_find_columnsprimaryjoinpersist_selectablerw   contains_columnrf   ro   rd  r  r  _target_adaptercopy_and_processr   r  )rk   rp   rq   rr   rt   rI  rU  ri  rJ  rB  r   Zshould_nest_selectableZquery_entity_keyindexesclauseZdefault_towrapZtowrapZefmonclauseZattach_on_outsideZextra_join_criteriarq  	eagerjoinr   r;   r   r<   ro  {	  s    

	




zJoinedLoader._create_eager_joinz#Union[Mapper, None, Literal[False]]z$Optional[path_registry.PathRegistry]entity_inside_join_structuredetected_existing_pathc	              
   C  s  ||d u sJ |du r(t |tjs(J t |tjjrN| |||j||||S t |tjrB|j}	| j|||j	||||	d ur|	d j
nd d}
|
d ur|js|
js||
}ntj|j|
|j|j|jd}|
j|_|S | j|||j||||j|	d}
|
d ur&tj|
|j	|j|j|jd}|
j|_|S |du r>ds>J dd S ||sRd S |rt|d	kr|d
 |u sxJ |dd |jdd krd S tj||j|d|||d j
 |dS )NrY  Fr  )r  )rv  rw  r  )rv  rx  z9assertion failed attempting to produce joined eager loadsr&   r   ru  )r   r3   r  r*   rZ  FromGroupingr  elementrx  rightr]   rv  _splice_into_centerleftr  rw  r  r  r}  rr   r~  )rk   rr   Zentity_we_want_to_splice_ontoZjoin_objrU  r  rB  r  r  Zjoin_right_pathZtarget_joinr  r;   r;   r<   r  
  s    	

$z&JoinedLoader._splice_nested_inner_joinc           	      C  s   |j }|r| |||jnd}|durP|}|jrB|rB||j}qj|jrj|j}n||jd}|d u rjdS | j||r||S dS d S )NFrj  )rp   rL  r
   compound_eager_adapterrc  rU   r]   _result_has_identity_key)	rk   rz   r{   rt   rr   rs   rp   rT  	decoratorr;   r;   r<   _create_eager_adapter
  s.    
z"JoinedLoader._create_eager_adapterc	              
   C  s   |j jjsd S | jj| j jjs.t	d|  | j
r:d|_|| j }	| ||||	|}
|
dur| j}t|| j|||	| j |
}| j
s| |||| q| |||| n | jd|||||||| d S )Nr-  TFr  )rp   r   r  rN   rV   r5   r2  r3  r   r   r@   loaders_require_uniquingri   r  r   _instance_processorr]   r   r6  r5  r   r}   )rk   rz   rq   rr   rs   r]   r{   rt   r|   Zour_pathZeager_adapterr5   	_instancer;   r;   r<   r}   
  sR    


	z!JoinedLoader.create_row_processorc                   sr    fdd} fdd} fdd}|d  | j|f |d  | j|f jrn|d	  | j|f d S )
Nc                   sF   t | |}t|d}|j | f<  |}|d urB|| d S Nappend_without_eventr
   r   r   UniqueAppenderrL   )r   r   r   r8  result_listinstr  rz   r5   r;   r<   #load_collection_from_joined_new_row*  s    zSJoinedLoader._create_collection_loader.<locals>.load_collection_from_joined_new_rowc                   sd   | fj v rj | f }n(t | |}t|d}|j | f<  |}|d ur`|| d S r  r  )r   r   r   r  r8  r  r  r;   r<   (load_collection_from_joined_existing_row7  s    zXJoinedLoader._create_collection_loader.<locals>.load_collection_from_joined_existing_rowc                   s    | d S r2   r;   r   r  r;   r<    load_collection_from_joined_execJ  s    zPJoinedLoader._create_collection_loader.<locals>.load_collection_from_joined_execr   r=  r>  rL   r5   rA  )rk   rz   r5   r  r|   r  r  r  r;   r  r<   r5  )  s    z&JoinedLoader._create_collection_loaderc                   sp    fdd} fdd} fdd}|d  j|f |d  j|f |jrl|d	  j|f d S )
Nc                   s    ||< d S r2   r;   r   )r  r5   r;   r<   load_scalar_from_joined_new_rowY  s    zKJoinedLoader._create_scalar_loader.<locals>.load_scalar_from_joined_new_rowc                   s8    |}|v r,|| ur4t d  n||< d S )NrB  )r   r~  )r   r   r   r=  r  r5   rk   r;   r<   $load_scalar_from_joined_existing_row^  s    	zPJoinedLoader._create_scalar_loader.<locals>.load_scalar_from_joined_existing_rowc                   s    | d S r2   r;   r   r  r;   r<   load_scalar_from_joined_execq  s    zHJoinedLoader._create_scalar_loader.<locals>.load_scalar_from_joined_execr   r=  r>  r  )rk   rz   r5   r  r|   r  r  r  r;   r  r<   r6  X  s    z"JoinedLoader._create_scalar_loader)NNF)FN)r~   r   r   r   r   rh   r   rx   rL  rM  rN  ro  r  r  r}   r5  r6  r   r;   r;   rm   r<   rG  D  s,      
 9O *   .$>/rG  selectinc                      st   e Zd ZdZedg dZdZ f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  ZS )SelectInLoader)r  	omit_join_parent_alias_query_info_fallback_query_infoZ	queryinfo)load_only_childload_with_joinin_exprpk_colszero_idxchild_lookup_colsi  c                   s   t  || | jj| _| jjtju }| jjd ur>| jj| _n<| jd}|rX|j	| _n"| j
jd j|jdd| j
jd| _| jr|r|  | _|  | _q|  | _n
|  | _d S )Nr  r   TFr  )rg   rh   ri   r  rZ   r   r  r  r   r   rN   r  r   r   r  _init_for_omit_join_m2or  _init_for_joinr  _init_for_omit_join)rk   rN   rl   Zis_m2or  rm   r;   r<   rh     s,    


zSelectInLoader.__init__c                   s   t jjj   fddt D   fddjjD  }}t|dkrbt	j
| }d}n|d }d}dd|||d S )	Nc                 3  s0   | ](}j j|d D ]}| | fV  qqdS )r;   N)rN   r  rU   )r   r   equivpk_to_fkrk   r;   r<   r     s   z5SelectInLoader._init_for_omit_join.<locals>.<genexpr>c                   s   g | ]}| v r | qS r;   r;   r   r   )r  r;   r<   r     s   z6SelectInLoader._init_for_omit_join.<locals>.<listcomp>r	   Fr   T)r=  ri   r  local_remote_pairsr  r  rN   r   r}  r*   tuple_
query_info)rk   r  Zfk_colsr  r  r;   r  r<   r    s    


z"SelectInLoader._init_for_omit_joinc                   sb   | j j}t|dkr$tj| }d}n|d }d}| jd  fdd|D }| dd||||S )Nr	   Fr   Tr  c                   s   g | ]} j | qS r;   rJ  rK  r  r;   r<   r     r   z:SelectInLoader._init_for_omit_join_m2o.<locals>.<listcomp>)r]   r   r}  r*   r  ri   r   r  )rk   r  r  r  Zlookup_colsr;   r  r<   r    s    
z&SelectInLoader._init_for_omit_join_m2oc                   sj   t | jj| _t| j  fdd| jjD }t|dkrJtj| }d}n|d }d}| 	dd|||d S )Nc                   s   g | ]}  |qS r;   _adapt_elementr  Zpa_inspr;   r<   r     s   z1SelectInLoader._init_for_join.<locals>.<listcomp>r	   Fr   T)
r%   rN   rY   r  r(   r   r}  r*   r  r  )rk   r  r  r  r;   r  r<   r    s    


zSelectInLoader._init_for_joinc                 C  s   | j d| d S r  r  r   r;   r;   r<   r     s
    z#SelectInLoader.init_class_attributec	                 C  s  |j r| ||||||||S | j|||| jd\}	}
}}|
sBd S |jjjsPd S | jj| j	 j
jsptd|  t|dkrt|j| jsd S nt|d | jsd S |	}|| j }||jdd }|d urt|}n| j}tj||| j| j| j||||	 d S )Nr  r-  r	   r  r  )r   r   r  r  rp   r   r  rN   rV   r5   r2  r3  r   r   r}  r3   r4  r  ri   rU   r
   r(   r   r   r  r  r  )rk   rz   rq   rr   rs   r]   r{   rt   r|   r  r  rE  r  Zselectin_pathr  r)  r  r;   r;   r<   r}     sj    

	

z#SelectInLoader.create_row_processorc	                   s  |rj |vrd S j}	|	jrtt}
g }j|D ]l\}jtfdd|	j	D }t
j|v rtj}	 qd |vr|
| |f q6||f q6|	jsdd |D }
|	j}|	j}|	jsjrfdd|D }|}tjdg|R  }| } }tj||gttjddd	}|	js@|}n$|jtjjj  }|!|"t#$d
} j%j&}|j }| j'u r|j(}n&|j(} j'j(} fddt)||D }|r|j*r|t+|, f7 }|d ur|- }|j.| }|/d|i} j0r*|j1dd}jj2r|	jsjjj2}jr^fdd|D }|j2| }nfdd}|3|j}|	jr4|
||	| | n5|
|	| | d S )Nc                 3  s"   | ]} j |tjd V  qdS )rI  N)r/  r
   PASSIVE_NO_FETCH)r   lk)r]   r   
state_dictr;   r<   r   V  s   z0SelectInLoader._load_for_path.<locals>.<genexpr>c                 S  s$   g | ]\}}|j d  ||j|fqS )r	   )r5   r=  )r   r   r  r;   r;   r<   r   s  s   z1SelectInLoader._load_for_path.<locals>.<listcomp>c                   s   g | ]}  |qS r;   r  r  r  r;   r<   r     s   rL  r  )compile_state_pluginplugin_subject)rO  rQ  r   rP  primary_keysc                   s   g | ]\}}|  |qS r;   )'_adapt_cached_option_to_uncached_option)r   Zorig_optuncached_opt)rz   r;   r<   r     s   rU  T)r  c                   s   g | ]}  |qS r;   r  r  r  r;   r<   r     s   c                   s    |  j tt jj7  _ d S r2   r  r  r   r;   r<   r	    s    z?SelectInLoader._load_for_path.<locals>._setup_outermost_orderby)6r5   r  r  r  r  r  rN   r=  r  r  r   r   r  rL   r  r  r  r   r  r3   Bundlerc  r-   rd  r,   r   re  rh  r  r  r  ri   r  filterin_r*   r  rp   select_statementuser_passed_queryrn  zipr   rm  r  r  r  _update_compile_optionsr  rE  r  r
  _load_via_child_load_via_parent)rk   rz   rr   r  r  r  rs   r  rE  r  
our_statesnone_statesr  Zrelated_identr  r  Z
bundle_entZ
bundle_sqlZ
entity_sqlr  r  r  r  cached_optionsuncached_optionsr  r	  r;   )rz   r  r]   rk   r   r  r<   r  >  s    






	



	
zSelectInLoader._load_for_pathc                   s   | j }t|}|r|d| j }	|| jd  }dd |jj|d fdd|	D i|d D }
|	D ]T}|
|d }|| D ]:\}}}|s| j|v rq||| j	|||s|n|g q|qdq|D ]0\}}}|s| j|v rq|| j	||d  qd S )Nr   c                 S  s   i | ]\}}||qS r;   r;   )r   r   r  r;   r;   r<   
<dictcomp>!  s   z2SelectInLoader._load_via_child.<locals>.<dictcomp>r  c                   s   g | ]} j r|d  n|qS r  r  )r   r5   r  r;   r<   r   &  s   z2SelectInLoader._load_via_child.<locals>.<listcomp>r"  rE  )
r@   sorted
_chunksizer   rz  r  rU   r5   r  r  )rk   r  r  r  r  rz   rE  r@   Zour_keyschunkdatar5   Zrelated_objr   r   r  r;   r  r<   r    s:    	
zSelectInLoader._load_via_childc                   s$  | j }|rdnd }|r |d| j }|| jd  } fdd|D }	tt}
t|jj|d|	i|d	 dd D ] \}}|
| 
d	d
 |D  qv|D ]\}}}}|s| j|v rq|
||}|s|rt|dkrtd|   || j|||d  q|| j||| qqd S )Nr;   r   c                   s&   g | ]\}}}} j r|d  n|qS r  r  )r   r5   r   r  r  r  r;   r<   r   R  s   
z3SelectInLoader._load_via_parent.<locals>.<listcomp>r  r  c                 S  s   | d S r   r;   r  r;   r;   r<   r=   ^  r   z1SelectInLoader._load_via_parent.<locals>.<lambda>c                 s  s   | ]}|d  V  qdS )r	   Nr;   r  r;   r;   r<   r   `  r   z2SelectInLoader._load_via_parent.<locals>.<genexpr>r	   rB  )r@   r  r  r  r  r  r  r   rz  r  r  r5   rU   r}  r   r~  r  r  )rk   r  r  r  rz   rE  r@   Z_empty_resultr  r  r  r   r  r5   r   r  r  r8  r;   r  r<   r  H  sF    


zSelectInLoader._load_via_parent)r~   r   r   r   r  
namedtupler  r  rh   r  r  r  r   r}   r  r  r  r   r;   r;   rm   r<   r  ~  s    P T7r  c                   sT   fdd  fdd} fdd}t j| d|dddd	 t j| d
|dddd	 d S )Nc                   sT   |d urP|j  j krP|t|}|rP||urPtjdt|| j f dd|S )NzsInstance %s is already associated with an instance of %s via its %s attribute, and is only allowed a single parent.Zbbf1)code)	r5   	hasparentr
   instance_stater   r   r3   instance_strrY   )r   r  oldvalue	initiatorr  )r8   r;   r<   	_do_check{  s    z*single_parent_validator.<locals>._do_checkc                   s    | |d |S r2   r;   )r   r  r  r  r;   r<   rL     s    z'single_parent_validator.<locals>.appendc                   s    | |||S r2   r;   )r   r  r  r  r  r;   r<   set_  s    z%single_parent_validator.<locals>.set_rL   T)rawretvalrG   r   )r'   listen)r7   r8   rL   r  r;   )r  r8   r<   rM   z  s    rM   )NNNNFN)Wr   
__future__r   r  r  typingr   r   r   r   r   r    r
   r   r   r   r   r   r   r   r   r   r   r3   baser   r   r   r   r   r   r   rz   r   r   r   r   r   r    r   r!   r   r"   r^  r#   r$   r%   r'   r   r(   r)   r*   r  r+   sql.selectabler,   r-   util.typingr.   r]   r/   r0   sql.elementsr1   ra   ColumnPropertystrategy_forrd   class_loggerr   r   r   r   r   r   r   MemoizedSlots
Identifiedr   r  r  r  r  rG  r  rM   r;   r;   r;   r<   <module>
   s         
Q+ZW 0%
&

    24Ld           =   }