o
    [h/                     @   sT  d Z ddlm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 e Zdd Zedd/ddZdd Z	d0ddZ				d1ddZ			d0ddZdd Z				d1dd Zd!d" Zd#d$ Zd%d& Z d'd( Z!d)d* Z"G d+d, d,e#Z$d-d. Z%dS )2zprivate module containing functions used to convert database
rows into object instances and associated state.

the functions here are called primarily by Query, Mapper,
as well as some of the attribute loading strategies.

    )absolute_importN   )
attributes)exc)path_registry)strategy_options)_DEFER_FOR_STATE)_SET_DEFERRED_EXPIRED)	_none_set)	state_str   )utilc                 #   sd   t   _i  _j}j}|r|rt}nfdd}zrtt fddjD  \}|s6t	
d|	 i  _jrIj}|sHW d
S n }|r]d fdd|D }n
fd	d|D } j D ]
\}	}
|
 |	 ql|rt	||}|D ]}|V  qjsW d
S q7 ty   t	    W d
   Y d
S 1 sw   Y  Y d
S w )z$Return an ORM result as an iterator.c                    s   t dd t j| D S )Nc                 s   s&    | ]\}}|j rt|n|V  qd S N)Zuse_id_for_hashid).0entitem r   }/home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/site-packages/sqlalchemy/orm/loading.py	<genexpr>2   s
    
z/instances.<locals>.filter_fn.<locals>.<genexpr>)tuplezip	_entitiesrow)queryr   r   	filter_fn1   s   
zinstances.<locals>.filter_fnc                    s   g | ]	}|  qS r   )Zrow_processor)r   query_entity)contextcursorr   r   r   
<listcomp>:   s    zinstances.<locals>.<listcomp>resultTr   c                    s   g | ]} |qS r   r   )r   r   )procr   r   r    P       c                    s"   g | ]  fd dD qS )c                    s   g | ]}| qS r   r   )r   r"   r   r   r   r    S   r#   z(instances.<locals>.<listcomp>.<listcomp>r   )r   )keyed_tupleprocessr   r   r    R   s    N)
_new_runidrunidpost_load_pathsZ_has_mapper_entitiesZis_single_entityr   listr   r   r   lightweight_named_tuplepartialsZ
_yield_perZ	fetchmanyZfetchallitemsinvokeZunique_list	ExceptionZsafe_reraiseclose)r   r   r   filteredsingle_entityr   labelsfetchrowspath	post_loadr   r   )r   r   r$   r"   r%   r   r   	instances"   s^   	

&r7   zsqlalchemy.orm.queryTc              	      s  |j  r	  j}zzd_t|jdk}|r2t|jd jr- fdd|D }nRt|}nMfddt|jD }g }dd |jD }t	
d|}	|D ].}
t|
}|D ]}|| d	urvjt|| t||  i i d
||< qX||	| qPt|W |_S |_w )z@Merge a result into this :class:`_query.Query` object's Session.Fr   r   c              	      s,   g | ]}j t|t| i i d qS )loadZ
_recursiveZ_resolve_conflict_map)_merger   instance_stateinstance_dict)r   instance)r9   sessionr   r   r    v   s    z merge_result.<locals>.<listcomp>c                    s    g | ]\}}t | jr|qS r   )
isinstance_MapperEntity)r   ie)querylibr   r   r       s    
c                 S   s   g | ]}|j qS r   )Z_label_name)r   r   r   r   r   r       s    r!   Nr8   )r>   Z
_autoflush	autoflushlenr   r?   r@   r)   	enumerater   r*   r:   r   r;   r<   appenditer)rC   r   iteratorr9   rD   r1   r!   Zmapped_entitieskeysr$   r   ZnewrowrA   r   )r9   rC   r>   r   merge_resultg   sD   


rK   c                 C   s   | j |}|durJt|}|jr|j|stjS |jrH|tj	@ s&tj
S |tj@ s-|S z	||| W |S  tjyG   | |g Y dS w |S dS )zqLook up the given key in the given session's identity map,
    check the object for expired state if found.

    N)identity_mapgetr   r;   inheritsmapperisaZPASSIVE_CLASS_MISMATCHZexpiredZSQL_OKZPASSIVE_NO_RESULTZRELATED_OBJECT_OKZ_load_expiredorm_excObjectDeletedErrorZ_remove_newly_deleted)r>   rO   keyZpassiver=   stater   r   r   get_from_identity   s&   


rU   c                 C   s6   |dur|d }|d }nd }}t | |||||dS )z.Load the given identity key from the database.Nr   r   )refresh_statewith_for_updateonly_load_propsidentity_token)load_on_pk_identity)r   rS   rV   rW   rX   identrY   r   r   r   load_on_ident   s   
r\   c                    s0  |du r|   }|  n|   }|dur`|  }|j\} d|v rDt fddt|j|D }	t||	}t	|	t	|krDt
d ||dd}||_t fddt||jD }
|
|_|durjd}||_n| jdurvd}| j|_nd}|jt|||||d d|_z| W S  tjy   Y dS w )	z6Load the given primary key identity from the database.Nc                    s"   g | ]\}}|d u r | j qS r   rS   )r   colvalueZ_get_paramsr   r   r       s
    z'load_on_pk_identity.<locals>.<listcomp>zofully NULL primary key identity cannot load any object.  This condition may raise an error in a future release.TFc                    s   g | ]\}} | j |fqS r   r]   )r   Zid_valprimary_keyr`   r   r   r       s    )populate_existingversion_checkrX   rV   rY   )Z_cloneZ_get_conditionZ_mapper_zero_get_clausesetr   ra   sql_utilZadapt_criterion_to_nullrE   r   warnZ_adapt_clauseZ
_criteriondict_paramsZ_for_update_argZ_get_optionsboolZ	_order_byonerQ   ZNoResultFound)r   Zprimary_key_identityrV   rW   rX   rY   qrO   rd   Znonesparamsrc   r   r`   r   rZ      sd   


	
	


rZ   c	                 K   s   |r| |}
n|j}
i }|| jd| |
D ]}|r!|j|vr!q|j| |||f|||d|	 q|d urL||jurN|rC|j| }n|}|| d S d S d S )Nmemoized_setups)rX   column_collectionZmemoized_populators)	Z_iterate_polymorphic_propertiesZ_polymorphic_propertiesre   r   rS   setuppolymorphic_oncolumnsrG   )r   rO   r   r5   adapterro   Zwith_polymorphicrX   polymorphic_discriminatorkwZpoly_propertiesquick_populatorsr_   pdr   r   r   _setup_entity_query#  s<   
rx   c                 C   s   t dt| f  d S )Nam  Loading context for %s has changed within a load/refresh handler, suggesting a row refresh operation took place. If this event handler is expected to be emitting row refresh operations within an existing load or refresh operation, set restore_load_context=True when establishing the listener to ensure the context remains unchanged when the event handler completes.)r   rg   r   )rT   r   r   r   _warn_for_runid_changedU  s
   ry   c	                    s  
j  r fddD 
jtt
j}	dur)|	
fddD }	|jdt	}
|	D ]f}||
v r|
| }|t
u rMd |j|jf q3|tu r\d |jd	f q3d} ro j| }|duro||d	}|sw||d	}|rd
 |j|f q3||
|  q3||
|  q3jjjjrjj| n|jjjp
jt
jjjt
jjjtjjjrЈjjj	tj tj!jj"j#j$j%s2|dur2d|jf}|jv rj| j&dkr
'j| j(d |}n
'd|}|r2||ur2du s!J t)||}t*+|j,||| t*-rJjdu rI
.nd
j/rTt	j0nt	j 	
fdd}
j1r|sst2|
||| }|S )z]Produce a mapper level row processor callable
    which processes rows into mapped instances.c                    s   g | ]} j | qS r   )rr   )r   c)rs   r   r   r    x  s    z'_instance_processor.<locals>.<listcomp>Nc                 3   s    | ]} j | V  qd S r   )Z_props)r   krO   r   r   r     s    z&_instance_processor.<locals>.<genexpr>rn   newexpireFquickloader))Zselectinload_polymorphicTentitiesc              
      s  r}|  }|}|jk}d}d}n`t fddD f}|}|d urL|}|}|jk}| }d}rK|sKt||  n*|d rTd S d}d}d}j }|}|}||_|_|_	
|| |szr|rss|_	|_t |||	|	 |r|j}|rr|jj| |j|krt| r
j| |j|krt| nr|jj| |jkrt| s|jrrr|| n|| r|d |S |j}	|jv}|r|	sd r2t |||	|	}
|r2r,|j}|jj||
 |j|kr,t| |||
 r?jr?|d |S )NTFc                    s   g | ]} | qS r   r   )r   columnr   r   r   r      r#   z:_instance_processor.<locals>._instance.<locals>.<listcomp>r   eager)objr'   r   rM   _validate_version_idclass_managerZnew_instancerS   rY   
session_idZ_add_unpresentZload_options	load_path_populate_fullmanagerdispatchr9   ry   r>   refreshmodifiedZ_commitZ_commit_all	add_stateunloadedr+   _populate_partialZinvoke_all_eagers)r   rT   r=   dict_isnewZcurrentloadloaded_instanceZidentitykeyZexisting_runidr   to_loadrs   r   Zidentity_classrY   r<   r;   Zis_not_primary_keyZload_evtr   loaded_as_persistentrO   rX   Zpersistent_evtZpk_colsrb   
populatorsr6   propagate_optionsZrefresh_evtZrefresh_identity_keyrV   r'   r   Zsession_identity_maprc   r   r   	_instance  s   







%
z&_instance_processor.<locals>._instance)3ra   Z_identity_classcollectionsdefaultdictr)   Z	_prop_setintersectionrM   r   r
   r   rG   rS   Z_deferred_column_loaderr	   rr   _getterZcreate_row_processorr   r   Z_current_pathr5   r>   rL   rb   Zalways_refreshrj   r   r   r9   r   r   r;   r<   Zhash_keyrc   r'   rY   ZstrategyZ_should_selectin_loadZ
local_opts_load_subclass_via_inPostLoadcallable_for_pathrO   for_context_identity_key_from_stateallow_partial_pks
issupersetpolymorphic_map_decorate_polymorphic_switch)rO   r   r!   r5   rs   rX   rV   rt   _polymorphic_frompropsrv   propr^   getterZadapted_colrS   Zselectin_load_viaZ	callable_r   r   r   r   _instance_processora  s   




	
< 
r   c                    sP   |j }t|jjdk|jr||\ n|j\  fdd}|S )Nr   c                    sb   | j }jf|j  f |j|d}|jr|dd  || jjfdd|D d  d S )N)
cache_pathc                 S   s   |   S r   )rb   )rl   r   r   r   <lambda>  s    z8_load_subclass_via_in.<locals>.do_load.<locals>.<lambda>c                    s,   g | ]\}} r|j d  d n|j d  qS )r   r   r]   )r   rT   Z
load_attrs)zero_idxr   r   r      s    z:_load_subclass_via_in.<locals>.do_load.<locals>.<listcomp>)Zprimary_keys)	r   Z_with_lazyload_optionsZ_with_optionsparentZ_populate_existingZadd_criteriar>   rm   all)r   r5   states	load_onlyZeffective_entityZ
orig_queryq2Zdisable_optZ
enable_optrl   r   r   r   do_load  s   


z&_load_subclass_via_in.<locals>.do_load)rO   rE   Zbase_mapperra   Zis_aliased_classZ_subclass_load_via_inZ_subclass_load_via_in_mapper)r   r5   entityrO   r   r   r   r   r     s   r   c	                 C   s:  |r`| j |_ |d D ]
\}	}
|
|||	< q
|r/|d D ]\}	}||	d  |r-|j|	 qn|d D ]\}	}|r?|j|	 q3|d D ]
\}	}|||| qD|d D ]
\}	}|||| qSd S ||jkr||_|d D ]\}	}
|	|vrz|
|||	< ql|d D ]
\}	}|||| qd S |d D ]
\}	}|||| qd S )Nr   r~   r}   delayedexisting)r'   popexpired_attributesaddr   )r   r   rT   r   r   r   r   rb   r   rS   r   set_callable	populatorr   r   r   r     s@   
r   c                 C   s  |s| j | }|d D ]\}	}
|	|v r|
||| qn[|}|| j |< |d D ]\}	}|	|v r4||||	< q&|d D ]\}	}|	|v rO||	d  |rO|j|	 q9|d D ]\}	}
|	|v rb|
||| qT|d D ]\}	}
|	|v ru|
||| qg|d D ]\}	}
|	|vr|
||| qz|S )Nr   r   r~   r}   r   r   )r+   r   r   r   )r   r   rT   r   r   r   r   r   r   rS   r   r   r   r   r   r   r     s@   

r   c              	   C   sd   | j }|d u r	d S |r|j| }| ||| j || kr0tdt|| ||| j || f d S )NzWInstance '%s' has version id '%s' which does not match database-loaded version id '%s'.)version_id_colrr   Z_get_state_attr_by_columnrQ   ZStaleDataErrorr   )rO   rT   r   r   rs   r   r   r   r   r   !  s&   
r   c           	         s`   |d ur|nj d u rS  r j  fdd}t|fdd}|S )Nc                    sJ   zj |  }W n ty   td|  w |u rd S t| dS )Nz*No such polymorphic_identity %r is defined)r   )r   KeyErrorAssertionErrorr   )discriminatorZ
sub_mapper)rs   r   rO   r5   r!   r   r   configure_subclass_mapperO  s"   z?_decorate_polymorphic_switch.<locals>.configure_subclass_mapperc                    s,   |  }|d ur| }|r|| S  | S r   r   )r   r   r   )instance_fnpolymorphic_instancesrq   r   r   polymorphic_instancee  s   z:_decorate_polymorphic_switch.<locals>.polymorphic_instance)rq   rr   r   ZPopulateDict)	r   r   rO   r!   r5   rt   rs   r   r   r   )rs   r   r   rO   r5   r   rq   r!   r   r   <  s   	

r   c                   @   sP   e Zd ZdZdZdd Zdd Zdd Zed	d
 Z	edd Z
edd ZdS )r   z4Track loaders and states for "post load" operations.)loadersr   	load_keysc                 C   s   i | _ t | _d | _d S r   )r   r   OrderedDictr   r   )selfr   r   r   __init__u  s   

zPostLoad.__init__c                 C   s   || j |< d S r   )r   )r   rT   	overwriter   r   r   r   z  s   zPostLoad.add_statec                    sx   | j sd S tj|}| j D ]$\} }}} fdd| j  D }|r4||||| jg|R i | q| j   d S )Nc                    s&   g | ]\}}|j j r||fqS r   )r   rO   rP   )r   rT   r   limit_to_mapperr   r   r      s    z#PostLoad.invoke.<locals>.<listcomp>)	r   r   ZPathRegistryZcoercer   valuesr,   r   clear)r   r   r5   tokenr   argru   r   r   r   r   r-     s   
zPostLoad.invokec                 C   s$   |j |j}|d ur|r||_|S r   )r(   rM   r5   r   )clsr   r5   rX   plr   r   r   r     s   zPostLoad.for_contextc                 C   s   |j |jv o||j|j  jv S r   )r5   r(   r   )r   r   r5   rS   r   r   r   path_exists  s   zPostLoad.path_existsc           	      O   sD   |j |jv r|j|j  }n	t  }|j|j < |||||f|j|< d S r   )r5   r(   r   r   )	r   r   r5   r   r   Zloader_callabler   ru   r   r   r   r   r     s   zPostLoad.callable_for_pathN)__name__
__module____qualname____doc__	__slots__r   r   r-   classmethodr   r   r   r   r   r   r   r   p  s    

r   c           	         s>  |j }|stdt| t|j}d}|r| j } j	rF j
sF ||}|durFt| t d|d||d}|du r|rP|j}n fdd jD }|j|ritdt|  |}t|rv jr{t|rtd	t| dS t| |||d
}|r|du rt|dS dS )z4initiate a column-based attribute refresh operation.zQInstance %s is not bound to a Session; attribute refresh operation cannot proceedFN*)rX   rV   c                    s   g | ]} j | jqS r   )Z_columntopropertyrS   )r   r^   r|   r   r   r      s    z*load_scalar_attributes.<locals>.<listcomp>z_Instance %s cannot be refreshed - it's not  persistent and does not contain a full primary key.zwInstance %s to be refreshed doesn't contain a full primary key - can't be refreshed (and shouldn't be expired, either).)rV   rX   )r>   rQ   ZDetachedInstanceErrorr   rj   rS   r   attrsrJ   rN   ZconcreteZ_optimized_get_statementr\   r   optionsr   LoadZundeferZfrom_statementra   r   sa_excZInvalidRequestErrorr   r
   issubsetr   r   r   Zwarn_limitedrR   )	rO   rT   Zattribute_namesr>   Zhas_keyr!   Z	statementZidentity_keyZpk_attrsr   r|   r   load_scalar_attributes  sn   
	

	
r   )T)NNN)NNNN)&r   
__future__r   r    r   r   rQ   r   r   baser   r	   r   r
   r   r   sqlrf   Zcounterr&   r7   dependenciesrK   rU   r\   rZ   rx   ry   r   r   r   r   r   r   objectr   r   r   r   r   r   <module>   sZ   E5!

X
2
  F :"48