o
    ·„jôL  ã                   @   s  d Z ddl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mZmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ e d¡ZeddƒZdd„ ZG dd„ dejƒZG dd„ dƒZG dd„ dƒZG dd„ dƒZ dd„ Z!dd„ Z"dd„ Z#G dd„ dƒZ$dS ) zî
Various data structures used in query construction.

Factored out from django.db.models.query to avoid making the main module very
large and/or so that they can be used by other modules without getting into
circular import difficulties.
é    N)Ú
namedtuple)Únullcontext)Ú
FieldError)ÚDEFAULT_DB_ALIASÚDatabaseErrorÚconnectionsÚmodelsÚtransaction)Ú
LOOKUP_SEP)Útree)Úcached_property)Úmake_hashableúdjango.db.modelsÚPathInfozGfrom_opts to_opts target_fields join_field m2m direct filtered_relationc                 c   s(   � | V  |   ¡ D ]	}t|ƒE d H  qd S ©N)Ú__subclasses__Ú
subclasses©ÚclsÚsubclass© r   úZ/var/www/html/django_cbt/venv/lib/python3.10/site-packages/django/db/models/query_utils.pyr   !   s
   €ÿr   c                       sÈ   e Zd ZdZdZdZdZeZdZdeeefZ	dddœ‡ fd	d
„
Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Z	d'dd„Zdd„ Zdd„ Zefdd„Zdd„ Zedd „ ƒZd!d"„ Zd#d$„ Zed%d&„ ƒZ‡  ZS )(ÚQze
    Encapsulate filters as objects that can then be combined logically (using
    `&` and `|`).
    ÚANDÚORÚXORTNF)Ú
_connectorÚ_negatedc                   s^   || j vrd dd„ | j dd … D ƒ¡}td|› d�ƒ‚tƒ jg |¢t| ¡ ƒ¢||d� d S )Nz, c                 s   s   � | ]}|›V  qd S r   r   )Ú.0Úconnr   r   r   Ú	<genexpr>7   s   € zQ.__init__.<locals>.<genexpr>é   z_connector must be one of z
, or None.)ÚchildrenÚ	connectorÚnegated)Ú
connectorsÚjoinÚ
ValueErrorÚsuperÚ__init__ÚsortedÚitems)Úselfr   r   ÚargsÚkwargsÚconnector_reprs©Ú	__class__r   r   r)   5   s   

ýz
Q.__init__c                 C   sb   t |ddƒdu rt|ƒ‚| s| ¡ S |st|tƒr|  ¡ S | j|d�}| | |¡ | ||¡ |S )NÚconditionalF)r#   )ÚgetattrÚ	TypeErrorÚcopyÚ
isinstancer   ÚcreateÚadd)r,   Úotherr   Úobjr   r   r   Ú_combine?   s   z
Q._combinec                 C   ó   |   || j¡S r   )r;   r   ©r,   r9   r   r   r   Ú__or__L   ó   zQ.__or__c                 C   r<   r   )r;   r   r=   r   r   r   Ú__and__O   r?   z	Q.__and__c                 C   r<   r   )r;   r   r=   r   r   r   Ú__xor__R   r?   z	Q.__xor__c                 C   s   |   ¡ }| ¡  |S r   )r5   Únegate)r,   r:   r   r   r   Ú
__invert__U   s   zQ.__invert__c                 C   s(   |j | ||dd|d�\}}| |¡ |S )NF)Úallow_joinsÚ
split_subqÚcheck_filterableÚ	summarize)Ú_add_qÚpromote_joins)r,   ÚqueryrD   ÚreuserG   Úfor_saveÚclauseÚjoinsr   r   r   Úresolve_expressionZ   s   
ú
zQ.resolve_expressionc                 C   s  |s| S | j | j| jd�}| jD ]s}|}t|tƒrx|\}}t|v r*| td¡\}}n|}d }t 	|¡}	|	 
|¡ }
|	urw|d u rBd}|
 |¡ }d u r_|
 |¡ }d ur_||
ƒ}
d}|
 |¡}|d u rn|dkrn|
 d¡}d}|d urw||
|ƒ}n| 
|¡}|j |¡ q|S )N)r#   r$   r!   ÚexactÚisnullT)r7   r#   r$   r"   r6   Útupler
   Úrsplitr   ÚFÚreplace_expressionsÚ
get_lookupÚget_transformÚappend)r,   ÚreplacementsÚcloneÚchildÚchild_replacementÚlhsÚrhsÚpathÚlookupÚfieldÚfield_replacementÚlookup_classÚtransform_classr   r   r   rU   j   sB   


þþ


€
zQ.replace_expressionsc                 c   sJ   � | V  | j D ]}t|tƒr|d }t|dƒr| ¡ E dH  q|V  qdS )zg
        Recursively yield this Q object and all subexpressions, in depth-first
        order.
        r!   ÚflattenN)r"   r6   rR   Úhasattrre   )r,   r[   r   r   r   re   ‘   s   €


ùz	Q.flattenc              
   C   sJ  ddl m}m} ddlm} ddlm} ddlm} |dƒ}| 	¡ D ]\}	}
t
|
dƒs/||
ƒ}
|j|
|	dd	� q"| |d
ƒd¡ t| }|jjrV| t|| d|ƒ d�ƒ¡ n| | ¡ |j|d�}|jrjtj|d�ntƒ }z|� | |¡duW  d  ƒ W S 1 sƒw   Y  W dS  ty¤ } zt d| |¡ W Y d}~dS d}~ww )z|
        Do a database query to check if the expressions of the Q instance
        matches against the expressions.
        r   )ÚBooleanFieldÚValue)ÚCoalesce)ÚQuery)ÚSINGLENrO   F)Úselectr!   Ú_checkT)Úoutput_field)Úusingz.Got a database error calling check() on %r: %s)Údjango.db.modelsrg   rh   Údjango.db.models.functionsri   Údjango.db.models.sqlrj   Údjango.db.models.sql.constantsrk   r+   rf   Úadd_annotationr   ÚfeaturesÚsupports_comparing_boolean_exprÚadd_qr   Úget_compilerÚin_atomic_blockr	   Úatomicr   Úexecute_sqlr   ÚloggerÚwarning)r,   Úagainstro   rg   rh   ri   rj   rk   rJ   ÚnameÚvalueÚ
connectionÚcompilerÚcontext_managerÚer   r   r   Úcheck    s8   

ÿý(ÿ€þzQ.checkc                 C   sf   d| j j| j jf }| d¡r| dd¡}t| jƒ}i }| j| jkr'| j|d< | j	r.d|d< |||fS )Nz%s.%szdjango.db.models.query_utilsr   r   Tr   )
r1   Ú
__module__Ú__name__Ú
startswithÚreplacerR   r"   r#   Údefaultr$   )r,   r_   r-   r.   r   r   r   ÚdeconstructÄ   s   



zQ.deconstructc                 C   sb   |   ¡ \}}}|g| ¡ ¢}|D ]}t|tƒr'|\}}t|ƒ}| ||f¡ q| |¡ qt|ƒS r   )r‹   r+   r6   rR   r   rX   )r,   r_   r-   r.   Úidentityr[   Úargr€   r   r   r   rŒ   Ð   s   
z
Q.identityc                 C   s   t |tƒstS |j| jkS r   )r6   r   ÚNotImplementedrŒ   r=   r   r   r   Ú__eq__Ý   s   
zQ.__eq__c                 C   s
   t | jƒS r   )ÚhashrŒ   )r,   r   r   r   Ú__hash__â   ó   
z
Q.__hash__c                 C   s    ddl m} dd„ | | ¡D ƒS )zŽ
        Retrieve all base fields referenced directly or through F expressions
        excluding any fields referenced through joins.
        r   )rJ   c                 S   s   h | ]
}|  td ¡d ’qS )r!   r   )Úsplitr
   )r   r[   r   r   r   Ú	<setcomp>î   s    ÿz+Q.referenced_base_fields.<locals>.<setcomp>)rr   rJ   Úget_children_from_q)r,   rJ   r   r   r   Úreferenced_base_fieldså   s   ÿzQ.referenced_base_fields)NTNFF)r‡   r†   Ú__qualname__Ú__doc__r   r   r   rŠ   r2   r%   r)   r;   r>   r@   rA   rC   rO   rU   re   r   r…   r‹   r   rŒ   r�   r‘   r–   Ú__classcell__r   r   r0   r   r   '   s4    

ÿ'$
r   c                   @   s*   e Zd ZdZdd„ Zd	dd„Zdd„ ZdS )
ÚDeferredAttributez„
    A wrapper for a deferred-loading field. When the value is read from this
    object the first time, the query is executed.
    c                 C   s
   || _ d S r   )ra   )r,   ra   r   r   r   r)   ù   r’   zDeferredAttribute.__init__Nc                 C   sr   |du r| S |j }| jj}||vr5|  |¡}|du r1| ¡ s&| jjr&tdƒ‚|j|gd� || S |||< || S )zx
        Retrieve and caches the value from the datastore on the first lookup.
        Return the cached value.
        Nz4Cannot read a generated field from an unsaved model.)Úfields)Ú__dict__ra   ÚattnameÚ_check_parent_chainÚ
_is_pk_setÚ	generatedÚAttributeErrorÚrefresh_from_db)r,   Úinstancer   ÚdataÚ
field_nameÚvalr   r   r   Ú__get__ü   s   
ÿÿzDeferredAttribute.__get__c                 C   s6   |j }| | jj¡}| jjr| j|krt||jƒS dS )zÁ
        Check if the field value can be fetched from a parent field already
        loaded in the instance. This can be done if the to-be fetched
        field is a primary key field.
        N)Ú_metaÚget_ancestor_linkra   ÚmodelÚprimary_keyr3   r�   )r,   r£   ÚoptsÚ
link_fieldr   r   r   rž     s
   z%DeferredAttribute._check_parent_chainr   )r‡   r†   r—   r˜   r)   r§   rž   r   r   r   r   rš   ó   s
    
rš   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )Úclass_or_instance_methodzŒ
    Hook used in RegisterLookupMixin to return partial functions depending on
    the caller type (instance or class of models.Field).
    c                 C   s   || _ || _d S r   )Úclass_methodÚinstance_method)r,   r¯   r°   r   r   r   r)   &  s   
z!class_or_instance_method.__init__c                 C   s$   |d u rt  | j|¡S t  | j|¡S r   )Ú	functoolsÚpartialr¯   r°   )r,   r£   Úownerr   r   r   r§   *  s   z class_or_instance_method.__get__N)r‡   r†   r—   r˜   r)   r§   r   r   r   r   r®      s    r®   c                   @   s°   e Zd Zdd„ Zejdd„ ƒZdd„ ZeeeƒZ	e
eƒZdd„ Zd	d
„ Zedd„ ƒZe
dd„ ƒZddd„Zddd„ZeeeƒZe
eƒZddd„Zddd„ZeeeƒZe
eƒZdS )ÚRegisterLookupMixinc                 C   s   |   ¡  |d ¡S r   )Úget_lookupsÚget)r,   Úlookup_namer   r   r   Ú_get_lookup1  s   zRegisterLookupMixin._get_lookupc                 C   s   dd„ t  | ¡D ƒ}|  |¡S )Nc                 S   s   g | ]	}|j  d i ¡‘qS )Úclass_lookups)rœ   r¶   )r   Úparentr   r   r   Ú
<listcomp>6  s    ÿz9RegisterLookupMixin.get_class_lookups.<locals>.<listcomp>)ÚinspectÚgetmroÚmerge_dicts)r   r¹   r   r   r   Úget_class_lookups4  s   ÿ
z%RegisterLookupMixin.get_class_lookupsc                 C   s(   |   ¡ }t| dd ƒ }ri |¥|¥S |S ©NÚinstance_lookups)r¿   r3   )r,   r¹   rÁ   r   r   r   Úget_instance_lookups;  s   z(RegisterLookupMixin.get_instance_lookupsc                 C   óN   ddl m} |  |¡}|d u rt| dƒr| j |¡S |d ur%t||ƒs%d S |S )Nr   )ÚLookuprn   )Údjango.db.models.lookupsrÄ   r¸   rf   rn   rV   Ú
issubclass)r,   r·   rÄ   Úfoundr   r   r   rV   D  ó   
zRegisterLookupMixin.get_lookupc                 C   rÃ   )Nr   )Ú	Transformrn   )rÅ   rÉ   r¸   rf   rn   rW   rÆ   )r,   r·   rÉ   rÇ   r   r   r   rW   N  rÈ   z!RegisterLookupMixin.get_transformc                 C   s    i }t | ƒD ]}| |¡ q|S )z«
        Merge dicts in reverse to preference the order of the original list. e.g.,
        merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
        )ÚreversedÚupdate)ÚdictsÚmergedÚdr   r   r   r¾   X  s   zRegisterLookupMixin.merge_dictsc                 C   s   t | ƒD ]}|j ¡  qd S r   )r   r¿   Úcache_clearr   r   r   r   Ú_clear_cached_class_lookupsc  s   ÿz/RegisterLookupMixin._clear_cached_class_lookupsNc                 C   s4   |d u r|j }d| jvri | _|| j|< |  ¡  |S )Nr¹   )r·   rœ   r¹   rÐ   ©r   r`   r·   r   r   r   Úregister_class_lookuph  s   

z)RegisterLookupMixin.register_class_lookupc                 C   s,   |d u r|j }d| jvri | _|| j|< |S rÀ   )r·   rœ   rÁ   ©r,   r`   r·   r   r   r   Úregister_instance_lookupq  s   

z,RegisterLookupMixin.register_instance_lookupc                 C   s"   |du r|j }| j|= |  ¡  dS )zn
        Remove given lookup from cls lookups. For use in tests only as it's
        not thread-safe.
        N)r·   r¹   rÐ   rÑ   r   r   r   Ú_unregister_class_lookup~  s   z,RegisterLookupMixin._unregister_class_lookupc                 C   s   |du r|j }| j|= dS )zs
        Remove given lookup from instance lookups. For use in tests only as
        it's not thread-safe.
        N)r·   rÁ   rÓ   r   r   r   Ú_unregister_instance_lookupˆ  s   z/RegisterLookupMixin._unregister_instance_lookupr   )r‡   r†   r—   r¸   r±   Úcacher¿   rÂ   r®   rµ   ÚclassmethodrV   rW   Ústaticmethodr¾   rÐ   rÒ   rÔ   Úregister_lookuprÕ   rÖ   Ú_unregister_lookupr   r   r   r   r´   0  s2    








	ÿ


	ÿr´   c                 C   sd   | j sdS t| j ddƒrdS |s| j S | j|vrdS |r0| |vr0td| jjj› d| j› d�ƒ‚dS )aØ  
    Return whether `field` should be used to descend deeper for
    `select_related()` purposes.

    Arguments:
     * `field` - the field to be checked. Can be either a `Field` or
       `ForeignObjectRel` instance.
     * `restricted` - a boolean field, indicating if the field list has been
       manually restricted using a select_related() clause.
     * `requested` - the select_related() dictionary.
     * `select_mask` - the dictionary of selected fields.
    FÚparent_linkzField Ú.zM cannot be both deferred and traversed using select_related at the same time.T)Úremote_fieldr3   Únullr   r   rª   r¨   Úobject_name)ra   Ú
restrictedÚ	requestedÚselect_maskr   r   r   Úselect_related_descend—  s   
ÿrä   c                 C   sL   t dt| ƒd ƒD ]}t | d|… ¡}| |¡r#|| |d… f  S q	dS )zÕ
    Check if the lookup_parts contains references to the given annotations set.
    Because the LOOKUP_SEP is contained in the default annotation names, check
    each prefix of the lookup_parts for a match.
    r!   r   N)Nr   )ÚrangeÚlenr
   r&   r¶   )Úlookup_partsÚannotationsÚnÚlevel_n_lookupr   r   r   Úrefs_expression½  s   
ÿrë   c                    s,   ‡ fdd„}||ƒpt |ddƒo||jjƒS )zÞ
    Check that self.model is compatible with target_opts. Compatibility
    is OK if:
      1) model and opts match (where proxy inheritance is removed)
      2) model is parent of opts' model or the other way around
    c                    s&   ˆ j j| jkp| jˆ j jv pˆ | jv S r   )r¨   Úconcrete_modelÚall_parents)r¬   ©rª   r   r   r…   Ò  s
   ÿýz-check_rel_lookup_compatibility.<locals>.checkr«   F)r3   rª   r¨   )rª   Útarget_optsra   r…   r   rî   r   Úcheck_rel_lookup_compatibilityÊ  s   ÿrð   c                   @   sH   e Zd ZdZeƒ dœdd„Zdd„ Zdd„ Zd	d
„ Zdd„ Z	dd„ Z
dS )ÚFilteredRelationz7Specify custom filtering in the ON clause of SQL joins.©Ú	conditionc                C   s:   |st dƒ‚|| _d | _t|tƒst dƒ‚|| _d | _d S )Nzrelation_name cannot be empty.z*condition argument must be a Q() instance.)r'   Úrelation_nameÚaliasr6   r   ró   Úresolved_condition)r,   rô   ró   r   r   r   r)   ê  s   

zFilteredRelation.__init__c                 C   s4   t || jƒstS | j|jko| j|jko| j|jkS r   )r6   r1   rŽ   rô   rõ   ró   r=   r   r   r   r�   ÷  s   
ÿ
ýzFilteredRelation.__eq__c                 C   s4   t | j| jd�}| j|_| j }d ur| ¡ |_|S )Nrò   )rñ   rô   ró   rõ   rö   rZ   )r,   rZ   rö   r   r   r   rZ      s
   
zFilteredRelation.clonec                 C   s"   |   ¡ }|j }r| |¡|_|S r   )rZ   rö   Úrelabeled_clone)r,   Ú
change_maprZ   rö   r   r   r   r÷     s   
z FilteredRelation.relabeled_clonec                 O   s(   |   ¡ }|j| j|dddd�d |_|S )NTF)Ú	can_reuserD   rE   Úupdate_join_typesr   )rZ   Úbuild_filterró   rö   )r,   rJ   rK   r-   r.   rZ   r   r   r   rO     s   ûúz#FilteredRelation.resolve_expressionc                 C   s   |  | j¡S r   )Úcompilerö   )r,   r‚   r�   r   r   r   Úas_sql  s   zFilteredRelation.as_sqlN)r‡   r†   r—   r˜   r   r)   r�   rZ   r÷   rO   rý   r   r   r   r   rñ   ç  s    	rñ   )%r˜   r±   r¼   ÚloggingÚcollectionsr   Ú
contextlibr   Údjango.core.exceptionsr   Ú	django.dbr   r   r   r   r	   Údjango.db.models.constantsr
   Údjango.utilsr   Údjango.utils.functionalr   Údjango.utils.hashabler   Ú	getLoggerr|   r   r   ÚNoder   rš   r®   r´   rä   rë   rð   rñ   r   r   r   r   Ú<module>   s6    
þ M-g&