
    bhi<                     .   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	m
Z
mZ ddlmZ ddlmZ  ej                   d      Z ed	d
      Zd Z G d dej(                        Z G d d      Z G d d      Z G d d      ZddZd Zd Z G d d      Zy)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)
FieldError)DEFAULT_DB_ALIASDatabaseErrorconnections)
LOOKUP_SEP)treedjango.db.modelsPathInfozGfrom_opts to_opts target_fields join_field m2m direct filtered_relationc              #   h   K   |  | j                         D ]  }t        |      E d {     y 7 wN)__subclasses__
subclassesclssubclasss     R/var/www/alwasay/venv/lib/python3.12/site-packages/django/db/models/query_utils.pyr   r      s4     
I&&( (h'''('s   &202c                        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	
Z
d
 Zd Zd Zd Zd Z	 ddZd ZefdZd Z xZS )Qze
    Encapsulate filters as objects that can then be combined logically (using
    `&` and `|`).
    ANDORXORTNF)
_connector_negatedc                    || j                   vr4dj                  d | j                   dd  D              }t        d| d      t        |   g |t        |j                               ||       y )Nz, c              3   "   K   | ]  }| 	 y wr    ).0conns     r   	<genexpr>zQ.__init__.<locals>.<genexpr>3   s     'T4('Ts      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__s         r   r)   z
Q.__init__1   sv    T__,"ii'TPQPR@S'TTO9/9J*UVV5t5fV\\^45  	 	
    c                    t        |dd      du rt        |      | s|j                         S |s t        |t              r| j                         S | j                  |      }|j                  | |       |j                  ||       |S )NconditionalF)r#   )getattr	TypeErrorcopy
isinstancer   createadd)r,   otherr   objs       r   _combinez
Q._combine;   sv    5-/58E""::<E1-99;kkDk)dt
r1   c                 :    | j                  || j                        S r   )r<   r   r,   r:   s     r   __or__zQ.__or__H   s    }}UDGG,,r1   c                 :    | j                  || j                        S r   )r<   r   r>   s     r   __and__z	Q.__and__K       }}UDHH--r1   c                 :    | j                  || j                        S r   )r<   r   r>   s     r   __xor__z	Q.__xor__N   rB   r1   c                 F    | j                         }|j                          |S r   )r6   negate)r,   r;   s     r   
__invert__zQ.__invert__Q   s    iik


r1   c                 \    |j                  | ||dd|      \  }}|j                  |       |S )NF)allow_joins
split_subqcheck_filterable	summarize)_add_qpromote_joins)r,   queryrI   reuserL   for_saveclausejoinss           r   resolve_expressionzQ.resolve_expressionV   sB    
 #" % 
 	E"r1   c              #      K   |  | j                   D ]@  }t        |t              r|d   }t        |d      r|j	                         E d{    =| B y7 w)zg
        Recursively yield this Q object and all subexpressions, in depth-first
        order.
        r!   flattenN)r"   r7   tuplehasattrrV   )r,   childs     r   rV   z	Q.flattenf   sV     
 
]] 	E%'aui( ==?**	
 +s   AA
AAc           
      J   ddl m}m} ddlm} ddlm} ddlm}  |d      }|j                         D ]-  \  }	}
t        |
d      s ||
      }
|j                  |
|	d	       / |j                   |d
      d       t        |   j                  j                  r)|j                  t!         || d |                          n|j                  |        |j#                  |      }	 |j%                  |      duS # t&        $ r!}t(        j+                  d| |       Y d}~yd}~ww xY w)z|
        Do a database query to check if the expressions of the Q instance
        matches against the expressions.
        r   )BooleanFieldValue)Coalesce)Query)SINGLENrT   F)selectr!   _checkT)output_field)usingz.Got a database error calling check() on %r: %s)django.db.modelsr[   r\   django.db.models.functionsr]   django.db.models.sqlr^   django.db.models.sql.constantsr_   r+   rX   add_annotationr   featuressupports_comparing_boolean_expradd_qr   get_compilerexecute_sqlr   loggerwarning)r,   againstrc   r[   r\   r]   r^   r_   rO   namevaluecompileres                r   checkzQ.checku   s     	97.9d"==? 	<KD%5"67e  U ;	< 	U1Xx0u&&FFKK(4LNKLMKK%%E%2	''/t;; 	NNKTSTU	s   %C8 8	D"DD"c                 P   | j                   j                  d| j                   j                  }|j                  d      r|j	                  dd      }t        | j                        }i }| j                  | j                  k7  r| j                  |d<   | j                  rd|d<   |||fS )N.zdjango.db.models.query_utilsr
   r   Tr   )
r0   
__module____name__
startswithreplacerW   r"   r#   defaultr$   )r,   pathr-   r.   s       r   deconstructzQ.deconstruct   s    ..33T^^5L5LM??9:<< >@RSDT]]#>>T\\)#'>>F< <<!%F:T6!!r1   )NTNFF)ry   rx   __qualname____doc__r   r   r   r|   r3   r%   r)   r<   r?   rA   rD   rG   rT   rV   r   ru   r~   __classcell__)r0   s   @r   r   r   #   st     C	B
CGKR%J)- 
-.. SX  $4 :
"r1   r   c                   $    e Zd ZdZd ZddZd Zy)DeferredAttributez
    A wrapper for a deferred-loading field. When the value is read from this
    object the first time, the query is executed.
    c                     || _         y r   )field)r,   r   s     r   r)   zDeferredAttribute.__init__   s	    
r1   Nc                     || S |j                   }| j                  j                  }||vr0| j                  |      }||j	                  |g       ||   S |||<   ||   S )zx
        Retrieve and caches the value from the datastore on the first lookup.
        Return the cached value.
        )fields)__dict__r   attname_check_parent_chainrefresh_from_db)r,   instancer   data
field_namevals         r   __get__zDeferredAttribute.__get__   s    
 K  ZZ''
T! **84C{(((= J $'Z Jr1   c                     |j                   }|j                  | j                  j                        }| j                  j                  r%| j                  |k7  rt        ||j                        S y)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_linkr   modelprimary_keyr4   r   )r,   r   opts
link_fields       r   r   z%DeferredAttribute._check_parent_chain   sU     ~~++DJJ,<,<=
::!!djjJ&>8Z%7%788r1   r   )ry   rx   r   r   r)   r   r   r   r1   r   r   r      s    
 &
r1   r   c                       e Zd ZdZd Zd Zy)class_or_instance_methodz
    Hook used in RegisterLookupMixin to return partial functions depending on
    the caller type (instance or class of models.Field).
    c                      || _         || _        y r   )class_methodinstance_method)r,   r   r   s      r   r)   z!class_or_instance_method.__init__   s    (.r1   c                     | t        j                  | j                  |      S t        j                  | j                  |      S r   )	functoolspartialr   r   )r,   r   owners      r   r   z class_or_instance_method.__get__   s:    $$T%6%6>>  !5!5x@@r1   N)ry   rx   r   r   r)   r   r   r1   r   r   r      s    
/Ar1   r   c                       e Zd Zd Z ej
                  d      d        Zd Z eee      Z	 e
e      Zd Zd Zed        Ze
d	        Zdd
ZddZ eee      Z e
e      ZddZddZ eee      Z e
e      Zy)RegisterLookupMixinc                 B    | j                         j                  |d       S r   )get_lookupsget)r,   lookup_names     r   _get_lookupzRegisterLookupMixin._get_lookup   s    !%%k488r1   N)maxsizec                     t        j                  |       D cg c]  }|j                  j                  di         }}| j	                  |      S c c}w Nclass_lookups)inspectgetmror   r   merge_dicts)r   parentr   s      r   get_class_lookupsz%RegisterLookupMixin.get_class_lookups   sQ     DK>>RUCV
9?FOO4
 
 }--
s   #Ac                 P    | j                         }t        | dd       x}ri ||S |S Ninstance_lookups)r   r4   )r,   r   r   s      r   get_instance_lookupsz(RegisterLookupMixin.get_instance_lookups   s=    ..0&t-?FFF8m8'788r1   c                     ddl m} | j                  |      }|'t        | d      r| j                  j                  |      S |t        ||      sy |S )Nr   )Lookuprb   )django.db.models.lookupsr   r   rX   rb   
get_lookup
issubclass)r,   r   r   founds       r   r   zRegisterLookupMixin.get_lookup   sQ    3  -=WT>:$$//<<Zv%>r1   c                     ddl m} | j                  |      }|'t        | d      r| j                  j                  |      S |t        ||      sy |S )Nr   )	Transformrb   )r   r   r   rX   rb   get_transformr   )r,   r   r   r   s       r   r   z!RegisterLookupMixin.get_transform   sQ    6  -=WT>:$$22;??Zy%Ar1   c                 L    i }t        |       D ]  }|j                  |        |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ds      r   r   zRegisterLookupMixin.merge_dicts   s-     % 	AMM!	r1   c                 X    t        |       D ]  }|j                  j                           y r   )r   r   cache_clearr   s     r   _clear_cached_class_lookupsz/RegisterLookupMixin._clear_cached_class_lookups  s'    "3 	5H&&224	5r1   c                     ||j                   }d| j                  vri | _        || j                  |<   | j                          |S r   )r   r   r   r   r   lookupr   s      r   register_class_lookupz)RegisterLookupMixin.register_class_lookup  sH     ,,K#,,. "C)/+&'')r1   c                 j    ||j                   }d| j                  vri | _        || j                  |<   |S r   )r   r   r   r,   r   r   s      r   register_instance_lookupz,RegisterLookupMixin.register_instance_lookup  s<     ,,KT]]2$&D!-3k*r1   c                 Z    ||j                   }| j                  |= | j                          y)zn
        Remove given lookup from cls lookups. For use in tests only as it's
        not thread-safe.
        N)r   r   r   r   s      r   _unregister_class_lookupz,RegisterLookupMixin._unregister_class_lookup&  s/    
  ,,Kk*'')r1   c                 :    ||j                   }| j                  |= y)zs
        Remove given lookup from instance lookups. For use in tests only as
        it's not thread-safe.
        N)r   r   r   s      r   _unregister_instance_lookupz/RegisterLookupMixin._unregister_instance_lookup0  s#    
  ,,K!!+.r1   r   )ry   rx   r   r   r   	lru_cacher   r   r   r   classmethodr   r   staticmethodr   r   r   r   register_lookupr   r   _unregister_lookupr   r1   r   r   r      s    9 Y&. '. ++<>RSK#$56   5 5 /7O ((=>*/ 2 "=  ++CDr1   r   c                 ^   | j                   sy| j                   j                  r|sy|r&|r| j                         |vry|s| j                  |vry|s| j                  ry|rN|rL| j                  |v r>| |vr:t        d| j                  j                  j                   d| j                   d      y)af  
    Return True if this field should be used to descend deeper for
    select_related() purposes. Used by both the query construction code
    (compiler.get_related_selections()) and the model instance creation code
    (compiler.klass_info).

    Arguments:
     * field - the field to be checked
     * restricted - a boolean field, indicating if the field list has been
       manually restricted using a requested clause)
     * requested - The select_related() dictionary.
     * select_mask - the dictionary of selected fields.
     * reverse - boolean, True if we are checking a reverse select related
    FzField rw   zM cannot be both deferred and traversed using select_related at the same time.T)	remote_fieldparent_linkrelated_query_namerq   nullr   r   r   object_name)r   
restricted	requestedselect_maskreverses        r   select_related_descendr   ?  s     %%gu//1B5::Y6%**JJ)#$U[[&&2231UZZL AL L
 	
 r1   c                     t        dt        |       dz         D ]4  }t        j                  | d|       }|j	                  |      s-|| |d fc S  y)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_lookups       r   refs_expressionr   f  s\     1c,'!+, 4#a):;??>*!<#3334 r1   c                 x      fd} ||      xs+ t        |dd      xr  ||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                     j                   j                  | j                  k(  xs: | j                  j                   j                         v xs | j                         v S r   )r   concrete_modelget_parent_list)r   r   s    r   ru   z-check_rel_lookup_compatibility.<locals>.check{  sV    KK&&$*=*== /""ekk&A&A&CC/,,..	
r1   r   F)r4   r   r   )r   target_optsr   ru   s   `   r   check_rel_lookup_compatibilityr   s  s<    
   }e,Iu{{7H7H1Ir1   c                   >    e Zd ZdZ e       ddZd Zd Zd Zd Z	y)	FilteredRelationz7Specify custom filtering in the ON clause of SQL joins.	conditionc                    |st        d      || _        d | _        t        |t              st        d      || _        g | _        y )Nzrelation_name cannot be empty.z*condition argument must be a Q() instance.)r'   relation_namealiasr7   r   r   r}   )r,   r   r   s      r   r)   zFilteredRelation.__init__  sD    =>>*
)Q'IJJ"	r1   c                     t        || j                        st        S | j                  |j                  k(  xr4 | j                  |j                  k(  xr | j
                  |j
                  k(  S r   )r7   r0   NotImplementedr   r   r   r>   s     r   __eq__zFilteredRelation.__eq__  sY    %0!!%"5"55 2

ekk)2%//1	
r1   c                     t        | j                  | j                        }| j                  |_        | j                  d d  |_        |S )Nr   )r   r   r   r   r}   )r,   clones     r   r   zFilteredRelation.clone  s7     !3!3t~~NjjYYq\
r1   c                     t        d      )zz
        QuerySet.annotate() only accepts expression-like arguments
        (with a resolve_expression() method).
        z0FilteredRelation.resolve_expression() is unused.)NotImplementedError)r,   r-   r.   s      r   rT   z#FilteredRelation.resolve_expression  s    
 ""TUUr1   c                     |j                   }|j                  | j                  t        | j                              }|j                  |      S )N)rP   )rO   build_filtered_relation_qr   setr}   compile)r,   rs   
connectionrO   wheres        r   as_sqlzFilteredRelation.as_sql  s=    //c$))n/U&&r1   N)
ry   rx   r   r   r   r)   r   r   rT   r  r   r1   r   r   r     s$    A343 
V'r1   r   )F)r   r   r   loggingcollectionsr   django.core.exceptionsr   	django.dbr   r   r   django.db.models.constantsr   django.utilsr	   	getLoggerrn   r   r   Noder   r   r   r   r   r   r   r   r   r1   r   <module>r     s       " - B B 1 			-	.
 M(y"		 y"x& &RA A dE dEN$N
:'' ''r1   