
    g@_                       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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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"m#Z# d dl$m%Z%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  G d de      Z1 G d d      Z2 G d de2      Z3 G d de2      Z4 G d de2      Z5 G d de2      Z6d Z7y)    N)partial)chain)EmptyResultSet
FieldErrorFullResultSet)DatabaseErrorNotSupportedError)
LOOKUP_SEP)FOrderByRawSQLRefValue)CastRandom)Lookup)select_related_descend)CURSORGET_ITERATOR_CHUNK_SIZEMULTI
NO_RESULTS	ORDER_DIRSINGLE)Queryget_order_dir)AND)TransactionManagementError)cached_property)make_hashable)_lazy_re_compilec                   $     e Zd Z fdZd Z xZS )PositionRefc                 4    || _         t        | 	  ||       y N)ordinalsuper__init__)selfr%   refssource	__class__s       u/var/www/python.vincentserveurtest.ovh/public_html/venv/lib/python3.12/site-packages/django/db/models/sql/compiler.pyr'   zPositionRef.__init__   s    v&    c                 0    t        | j                        dfS )N )strr%   )r(   compiler
connections      r,   as_sqlzPositionRef.as_sql#   s    4<< "$$r-   )__name__
__module____qualname__r'   r3   __classcell__r+   s   @r,   r"   r"      s    '%r-   r"   c                   *   e Zd Z edej
                  ej                  z        Zd!dZd Z	d"dZ
d"dZd Zd Zd"d	Zd
 Zd Zd Zd Zd Zd Zd Zd#dZ	 d$dZd Z	 d%dZd Zd Z	 	 	 	 	 d&dZd Zd Zd Zddde fdZ!d Z"e#de fdZ$d Z%d  Z&y)'SQLCompilerz^(.*)\s(?:ASC|DESC).*c                     || _         || _        || _        || _        ddi| _        d | _        d | _        d | _        d | _        y )N*)	queryr2   usingelide_emptyquote_cacheselectannotation_col_map
klass_info_meta_ordering)r(   r=   r2   r>   r?   s        r,   r'   zSQLCompiler.__init__.   sM    
$
 ':
 "&"r-   c           	          d| j                   j                   d| j                  j                  j                   d| j                  d| j
                  d	S )N<z model=z connection=z using=>)r+   r6   r=   modelr2   r>   r(   s    r,   __repr__zSQLCompiler.__repr__?   sU    ++, -ZZ%%223 4//,GDJJ>D	
r-   Fc                     t         fd j                  j                  D              r j                  j                           j	                  |      \   _         _         _        t         j
                         _	        y )Nc              3   V   K   | ]   }j                   j                  |   d k(   " ywr   Nr=   alias_refcount).0ar(   s     r,   	<genexpr>z*SQLCompiler.setup_query.<locals>.<genexpr>G   s(     O:NQtzz((+q0:N   &)with_col_aliases)
allr=   	alias_mapget_initial_alias
get_selectrA   rC   rB   len	col_count)r(   rU   s   ` r,   setup_queryzSQLCompiler.setup_queryF   sd    O$**:N:NOOJJ((*@D- AP A
=T_d&= T[[)r-   c                    | j                  |       | j                         }| j                  j                  j	                  | j                  j
                  du      \  | _        | _        | _        | j                  || j                        }t        |      | _        | j                  | j                  |z   |      }|||fS )z
        Do any necessary class setup immediately prior to producing SQL. This
        is for things that can't necessarily be done in __init__ because we
        might not have all the pieces in place at that time.
        rT   N)must_group_by)r\   get_order_byr=   wheresplit_having_qualifygroup_byhavingqualifyget_extra_selectrA   boolhas_extra_selectget_group_by)r(   rU   order_byextra_selectrb   s        r,   pre_sql_setupzSQLCompiler.pre_sql_setupN   s     	*:;$$&04

0@0@0U0U**--T9 1V 1
-
DK ,,Xt{{C $\ 2$$T[[<%?JXx//r-   c                    | j                   j                  g S g }t               }| j                   j                  dur| j                   j                  D ]  }t        |d      s| j                   j	                  |      }t        |t              rF|j                  |vsI|j                  |j                         |j                  |j                         |j                  |        i }t        |d      D ]4  \  }\  }}}	|	r|||<   |	|v r|j                  |j                                6 | j                  s0|D ]+  \  }\  }
}}|r|j                  |j                                - | j                  r| j                  j                         nd}|D ]  }|j                  |        g }t               }| j!                  ||      }| j"                  j$                  j&                  }|D ]  }	 | j)                  |      \  }
}|r!|j/                  |      x}t1        |      d}}
n|j3                  | |
|      \  }
}t5        |      }|
|f|vsc|j                  |
|f       |j                  |
|f        |S # t*        t,        f$ r Y w xY w)z
        Return a list of 2-tuples of form (sql, params).

        The logic of what exactly the GROUP BY clause contains is hard
        to describe in other words than "if it passes the test suite,
        then it is correct".
        Tr3      startr/   )r=   rb   sethasattrresolve_ref
isinstancer   r)   addappendr*   	enumerateextendget_group_by_colsrD   rc   collapse_group_byr2   featuresallows_group_by_select_indexcompiler   r   getr0   select_formatr   )r(   rA   ri   expressionsgroup_by_refsexprselected_expr_positionsr%   _aliassqlparamsis_refhaving_group_byresultseenr{   positionparams_hashs                      r,   rh   zSQLCompiler.get_group_by^   sq   L ::&I::d* 

++tX.::11$7DdC(yy5%))$))4#**4;;7&&t, , #%)26)C%G%dAu07'- %t5578 *D ""/7++sFF &&t'='='?@	 08
 >B[[$++779b#Dt$ $u,,[/J OO$$AA 	%  D"ll40V -!8!<!<T!BBXO!(mRV"00sFCV'/K[!-sFm,#{+,     #M2 s   ,I55JJc                    | j                   j                  j                  r|D ch c]_  }t        |d      rQ|j                  j
                  r;| j                   j                  j                  |j                  j                        r|a }}|D ch c]  }|j                   }}|D cg c]  }||v s||v st        |dd       |vr| }}|S c c}w c c}w c c}w )Ntargetr   )
r2   rz   allows_group_by_selected_pksrq   r   primary_key%allows_group_by_selected_pks_on_modelrH   r   getattr)r(   r   rc   r   pksaliasess         r,   ry   zSQLCompiler.collapse_group_by   s     ??##@@ (
'DD(+//00VV)) '  
 /22cdtzzcG2 ('D3;6>4$/w>	 '   '
 3s   A$CC( Cc                    g }d}i }d}| j                   j                  j                         D ]/  \  }\  }}|||<   |j                  t	        ||      |f       |dz  }1 | j                   j
                  r| j                   j                  rJ | j                   j                         }	| j                   j                  r| j                  |	      }
n| j                   j
                  }
|
rKg }|
D ]+  }|j                  |       |j                  |df       |dz  }- | j                   j                  |d}| j                   j                  j                         D ]"  \  }}|||<   |j                  ||f       |dz  }$ | j                   j                  r$| j                  ||	      }||d<   fd |       g }d}|D ]T  \  }}	 | j                  |      \  }}|j                  | ||      \  }}||r
d
| }|dz  }|j                  |||f|f       V |||fS # t        $ r? t!        |dt"              }|t"        u rd\  }}n| j                  t%        |            \  }}Y rt&        $ r  | j                  t%        d	            \  }}Y w xY w)a  
        Return three values:
        - a list of 3-tuples of (expression, (sql, params), alias)
        - a klass_info structure,
        - a dictionary of annotations

        The (sql, params) is what the expression will produce, and alias is the
        "AS alias" for the column (possibly None).

        The klass_info structure contains the following information:
        - The base model of the query.
        - Which columns for that model are present in the query (by
          position of the select clause).
        - related_klass_infos: [f, klass_info] to descent into

        The annotations is a dictionary of {'attname': column position} values.
        Nr   rm   )rH   select_fieldsrelated_klass_infosc                 P    | d   D ]  }|d   r| d   |d   z   |d<    |        y )Nr   from_parentr   r/   )rC   kiget_select_from_parents     r,   r   z6SQLCompiler.get_select.<locals>.get_select_from_parent  sA    $%:;B-(&7"_:MM ?+ +2. <r-   empty_result_set_value)0r/   Tcol)r=   rj   itemsru   r   rA   default_colsget_select_maskget_default_columnsrH   annotation_selectselect_relatedget_related_selectionsr|   r~   r   r   NotImplementedr   r   )r(   rU   rA   rC   annotations
select_idxr   r   r   select_maskcolsselect_listr   
annotationr   retcol_idxr   r   s                     @r,   rY   zSQLCompiler.get_select   s   $ 

$(JJ$;$;$A$A$C E=C!+KMM6#v.67!OJ %D JJ%%$***A*ABBjj002::""++K8D ::$$DK"":.sDk*a
 
 ))!,J "&!=!=!C!C!EE:!+KMM:u-.!OJ "F
 ::$$"&"="=fk"R0CJ,-/ #:. JCC"ll3/V "//c6BV}!1gY1JJc6]E23' !( J++# " N)01>*& *^;")KC"&,,u5K/L"MKC  8"ll5;7V8s   HAJ%JJc           
   #   6  K   | j                   j                  r| j                   j                  }n| j                   j                  s| j                   j                  }nk| j                   j                  r| j                   j                  }n>| j                   j	                         x}r |j
                  r|j
                  }|| _        ng }| j                   j                  rt        d   \  }}nt        d   \  }}i }|r@| j                  x}r2t        |d      D ]"  \  }\  }}}	t        ||	|      }
|	r|
||	<   |
||<   $ |D ]U  }t        |d      rt        |t              rt        ||j                         }t        |t"              s|j%                         }| j                   j                  s |j'                         }|j)                          |j+                  |j,                        }|sAt        |j,                  t.              r|j+                  |j,                  j0                        x}r|j2                  |j4                   | j6                  j8                  j:                  r|j'                         }||_        nK| j                   j<                  r5|j'                         }t?        |j@                  |jB                        |_        ||d uf |dk(  rt#        tE                     df tG        ||      \  }}|dk(  }|j+                  |      x}rt#        ||      d	f | j                   jH                  j+                  |      x}r|}g }n<|jK                  tL              ^}}| j                   jH                  j+                  |      }|r| j                   j<                  r$| j                  r|rtO        d
      t/        |      }|r#|D ]  }| j                   jQ                  ||      }  t        |t              rt        ||j                         }t#        ||      df d|v rF|jK                  dd      \  }}t#        tS        | jU                  |      d|g       |      df 4| j                   jV                  r|| j                   jV                  v r|| j                   jX                  v r:t#        t?        |tS        | j                   jV                  |          |      d	f t#        tS        | j                   jV                  |    |      df | j                   j<                  r(| j                  rt#        t/        |      |      df "| j[                  || j                   j	                         |      E d {    X y 7 w)NASCDESCrm   rn   resolve_expression?F
descendingTz;Ordering combined queries by transforms is not implemented..)default_order).r=   extra_order_bydefault_orderingri   get_metaorderingrD   standard_orderingr   rA   rv   r"   rq   rs   r   r   output_fieldr   asccopyreverse_orderingr}   
expressionr   namenulls_first
nulls_lastr2   rz    supports_order_by_nulls_modifier
combinatorr   r)   r*   r   r   r   splitr
   NotImplementedErrortry_transformr   quote_name_unless_aliasextrarj   find_ordering_name)r(   r   metar   r   selected_exprsrA   r%   r   r   pos_exprfield
select_refr   orderr   ref
transformsr   tables                       r,   _order_by_pairszSQLCompiler._order_by_pairs<  s    ::$$zz00H,,zz**HZZ  zz**Hjj))++d+}}H"*DH::''(/M1(0M1 4;;..-6vQ-G))$5&wt<,4N5)'/t$	 .H Eu23eU+ (:(:;E!%1!IIKEzz33!JJLE**,+//0@0@A
u//3'5'9'9%:J:J:O:O'PPP
 ))1e6F6F6N11RR %

+5( .. %

+.z
@Q@Q+R(Zt333|fh'..&um<JC&J+//44z4 "#-   zz--11#66t6
#&99Z#8 jzz--11#6::((T[[!1+  S6D *#zz77dC !+dE*d&7&78Ddz:EAAe| !YYsA.
s'+'C'CE'JCPRT $.	   zzC4::+;+;$;$**111VTZZ-=-=c-B%CD'1    

(8(8(= >:V 
 ::((T[[ "!C&Z@%GG  $66

++-&3  7    ] \s   VVV	Vc                 j   g }t               }| j                         D ]  \  }}|j                  | j                  dd      }|s}| j                  j                  rf| j
                  rY|j                  }|j                  }| j
                  D ]  \  }}	}
||k(  s| j                  j                  r8|
| j                  j                  v r t        |t              r|
|j                  k(  s[|j                  t        |
r|
n|j                  j                  |      g        n t!        | j                  j
                        dz   }d| }
| j                  j"                  D ]+  }|j                  rt%        d      |j'                  ||
       - | j                  j)                  ||
       |j                  t        |
|      g       | j+                  |      \  }}| j,                  j/                  |      d   }t1        |      }||f|v r|j3                  ||f       |j5                  ||||ff        |S )a/  
        Return a list of 2-tuples of the form (expr, (sql, params, is_ref)) for
        the ORDER BY clause.

        The order_by clause can alter the select clause (for example it can add
        aliases to clauses that do not yet have one, or it can add totally new
        select clauses).
        TN)allow_joinsreuserm   __orderbycolz:ORDER BY term does not match any column in the result set.)rp   r   r   r=   r   rA   r   has_select_fieldsr   rs   r   r   set_source_expressionsr   r   columnrZ   combined_queriesr   add_annotationadd_select_colr|   ordering_partssearchr   rt   ru   )r(   r   r   r   r   resolvedsrcexpr_srcsel_exprr   	col_aliasorder_by_idxqr   r   without_orderingr   s                    r,   r_   zSQLCompiler.get_order_by  s    u 002LD&..tzztSW.XHdjj33))??.2kk*Hah !JJ88 )TZZ-I-I I *8Q 7I<V % 77 iSZZ=N=NPSTU  /:& $'tzz'8'8#9A#=L".|n =I!ZZ88 .."/!2#  ((9= 9 JJ--h	B33SC5H4IJ,,x0KC
  $2299#>qA'/K +.$6HH&45MM8c66%:;<_ 3` r-   c                 (   g }| j                   j                  rt| j                   j                  s^|D cg c]  }|d   	 }}|D ]G  \  }\  }}}	| j                  j	                  |      d   }
|	r+|
|f|vs2|j                  ||
|fd f       I |S c c}w Nrm   )r=   distinctdistinct_fieldsr   r   ru   )r(   ri   rA   rj   t
select_sqlr   r   r   r   r   s              r,   re   zSQLCompiler.get_extra_select  s    ::tzz'A'A(./1!A$J//7++sFF#'#6#6#=#=c#B1#E #3V"<J"N ''0@&/I4(PQ 08  0s   Bc                    || j                   v r| j                   |   S || j                  j                  v r|| j                  j                  vsU|| j                  j                  v s=| j                  j
                  j                  |      r)|| j                  j                  vr|| j                   |<   |S | j                  j                  j                  |      }|| j                   |<   |S )z
        A wrapper around connection.ops.quote_name that doesn't quote aliases
        for table names. This avoids problems with some SQL dialects that treat
        quoted strings specially (e.g. PostgreSQL).
        )
r@   r=   rW   	table_maprj   external_aliasesr}   r2   ops
quote_name)r(   r   rs      r,   r   z#SQLCompiler.quote_name_unless_alias  s     4#####D))TZZ)))d$**:N:N.Ntzz...

++//5

 4 44 &*DT"KOO**40!"r-   c                     t        |d| j                  j                  z   d       }|r || | j                        \  }}||fS |j                  | | j                        \  }}||fS )Nas_)r   r2   vendorr3   )r(   nodevendor_implr   r   s        r,   r|   zSQLCompiler.compile(  sf    dEDOO,B,B$BDI%dDOO<KC F{ ++dDOO<KCF{r-   c                 D   | j                   j                  }| j                  j                  D cg c]3  }|j	                  | j
                  | j                   | j                        5 }}|j                  sD|D ]>  }|j                  j                  rt        d      |j                         s5t        d       n)| j                  j                  r|dk(  r|D ]	  }d|_         d}|D ]e  }	 |j                  j                  s| j                  j                  r}|j                  j                         |_        |j                  j                  g | j                  j                  | j                  j                  | j                  j                         |j!                  d      \  }}	|j                  j"                  rR|j$                  sdj'                  |      }ng| j                  j(                  s|j                  sEd	j'                  |      }n3| j                  j(                  r|j                  rd	j'                  |      }|||	ffz  }h |st*        | j                   j,                  j.                  |   }
|r
|dk(  r|
dz  }
d| j                  j(                  s|j                  rd	t1        fd|D         \  }}dj'                  |
      j3                  |      g}g }|D ]  }|j5                  |        ||fS c c}w # t*        $ r |dk(  s|d
k(  r|rY 6 w xY w)Nz>LIMIT/OFFSET not allowed in subqueries of compound statements.z:ORDER BY not allowed in subqueries of compound statements.unionFr/   TrT   zSELECT * FROM ({})z({})
differencez ALLz{}c              3   J   K   | ]  \  }}j                  |      |f  y wr$   )format)rP   r   argsbracess      r,   rR   z1SQLCompiler.get_combinator_sql.<locals>.<genexpr>x  s$     @%YS$v}}S!4(%s    #z {} )r2   rz   r=   r   get_compilerr>   r?   %supports_slicing_ordering_in_compound	is_slicedr   r_   values_selectclone
set_valuesrj   r   r3   r    supports_parentheses_in_compoundr   subqueryr   r   set_operatorszipjoinrw   )r(   r   rV   rz   r=   	compilersr1   partspart_sql	part_argscombinator_sql	sql_parts
args_partsr   r   partr  s                   @r,   get_combinator_sqlzSQLCompiler.get_combinator_sql0  s   ??++ 44
4 tzz4??D<L<LM4 	 
 ==%>>++'X  ((*'T  & ZZ!!jG&;%
 (-$ & !H%  ~~33

8P8P%-^^%9%9%;HNNN--!ZZ44!ZZ55 "ZZ99 '/ooto&L#)>>,, $DD#7#>#>x#H 

++'MM#)==#:JJ'' FF%}}X6H8Y/11A "N   ,,:::F:(f$Nzz""x'U'UF #@%@!
	: --/44Y?@DMM$ v~Y
n "  (Z<-GEs   8L ,E!LLLc                    g }| j                   r|j                  | j                          | j                  r|j                  | j                         | j                  j	                         d_        j                   j                  |      _         | j                  d      d   D ci c]	  \  }}}|| c}}}t        j                               t               i fd} |t        | j                  j                                      | j                  j                  j                         D ci c]  \  }}|t        ||       c}}      | _        g }| j!                         D ]f  ^}} ||j#                                |j                  |j                  j                         D ci c]  \  }}|t        ||       c}}             h j%                  | j&                  | j(                  | j*                        }|j-                  dd      \  }	}
| j/                  | j                        \  }}d|	d	| j(                  j0                  j3                  d
      d|g}r}j                         D cg c]'  }| j(                  j0                  j3                  |      ) }}ddj5                  |      dg|d	| j(                  j0                  j3                  d      }t        |
      |z   }|rag }|D ]8  }| j/                  |      \  }}|j                  |       |j7                  |       : |j7                  ddj5                  |      g       ||fS c c}}}w c c}}w c c}}w c c}w )NTrT   r   c                    | r| j                         }|v rj                  |      x}r||<   nt        |t              r | j	                  |j                                nvt        |t              r.|j                  vrX| j	                  |j                                n8t              }d| }j                  |       j                  ||       ||<   | ry y )Nqual)popr}   rs   r   rw   get_source_expressionsr   r)   rZ   rt   r   )	r   r   select_aliasnum_qual_aliasinner_queryqual_aliasesreplacementsrA   select_aliasess	       r,   collect_replacementsz9SQLCompiler.get_qualify_sql.<locals>.collect_replacements  s    "(<'%+ZZ%55\5)5L&f-&&t'B'B'DEc*yy6#**4+F+F+HI%(%6N%).)9#:L $$\2..t\B)5L&! r-   )r2   r?   F)with_limitsrU   SELECT * FROM ()rd   WHERESELECT, zFROM (qualify_maskzORDER BY)r`   ru   rc   r=   r  r
  r+   rY   rp   valueslistrd   leavesreplace_expressionsr   r   r_   r  r  r>   r2   r?   r3   r|   r   r   r  rw   )r(   where_partsr   r   r   r"  ri   order_by_exprinner_query_compiler	inner_sqlinner_paramsqualify_sqlqualify_paramsr   r   r   ordering_sqlsr   ordering_sqlordering_paramsr  r  r   rA   r!  s                       @@@@@r,   get_qualify_sqlzSQLCompiler.get_qualify_sql  sO   ::tzz*;;t{{+jj&&(#'--77D /3ooto.TUV.W
.WND!UD%K.W
 V]]_-u	6 	6& 	T$,,"5"5"789||777C7I7I7KL7KeT3ud##7KL
 !%!2!2!4MA !E!E!GHOO11?K?Q?Q?ST?SeT3ud++?ST "5  +77JJ4??@P@P  8  
 #7"="=  " #> #
	< '+ll4<<&@#^OO**95
  HN}}WeDOO''2259DW		$ 	
  ##..~>F l#n4 M$04X0F-o$$\2o. % MM:tyy'?@Av~c
8 M U4 Xs   0M&M-
<M3,M9c                    | j                   j                  j                         }	 | j                   j                  }| j	                  |xs t        |            \  }}}d}|xr | j                   j                  }	| j                   j                  }| j                  j                  }
|r`t        |
dj                  |            st        dj                  |            | j                  || j                   j                        \  }}nn| j                  r| j                         \  }}d}nK| j!                         \  }}| j#                         \  }}	 | j$                  | j'                  | j$                        ndg f\  }}	 | j.                  | j'                  | j.                        ndg f\  }}dg}g }| j                   j0                  r3| j                  j2                  j5                  ||      \  }}||z  }||z  }g }| j6                  |z   D ]W  \  }\  }}}|r*|d| j                  j2                  j9                  |      }|j;                  |       |j=                  |       Y |d	j?                  |      gz  }|r	|d
g|z  }nD| j                  j                  j@                  r$|| j                  j                  j@                  gz  }|j;                  |       | j                   jB                  rJ|
jD                  r=| j                  jG                         r|
jH                  rtK        d      |	r|
jL                  st        d      | j                   jN                  }| j                   jP                  }| j                   jR                  }| j                   jT                  }|r|
jV                  st        d      |r|
jX                  st        d      |r|
jZ                  st        d      |r|
j\                  st        d      | j                  j2                  j_                  ||| ja                         |      }|r|
jb                  r|j=                  |       |r%|j=                  d|z         |j;                  |       g }|D ]'  \  } }!|j=                  |        |j;                  |!       ) |rf|rte        d      |xs$ | j                  j2                  jg                         }|j=                  dd	j?                  |      z         | jh                  rd}|rZ|s3|j;                  | j                  j2                  jk                                |j=                  d|z         |j;                  |       | j                   jl                  rs|jo                  d | j                  j2                  jp                  | j                   jl                  j                  fi | j                   jl                  jr                         |rog }"|D ]+  \  }\  }#}$}|"j=                  |#       |j;                  |$       - dd	j?                  |"      z  }%|r|
jt                  r
dg|d|%}n|j=                  |%       |	r]|j=                  | j                  j2                  jw                  | j                   jx                  | j                   jz                               |r|
jb                  s|j=                  |       | j                   j|                  r7|r4g }&g }'t        | j6                  d      D ]  \  }(\  })}}|r]|&j=                  | j                  j2                  j9                  d      d| j                  j2                  j9                  |             i|)j                  |)j                  di      }*|*j                  | | j                        \  }+},|&j=                  |+       |'j;                  |,        dd	j?                  |&      dd j?                  |      d!t        |'|z         f| j                   j                  |       S d j?                  |      t        |      f| j                   j                  |       S # t(        $ r | j*                  r dg }}Y t,        $ r dg }}Y w xY w# t,        $ r dg }}Y w xY w# | j                   j                  |       w xY w)"z
        Create the SQL for this query. Return the SQL string and list of
        parameters.

        If 'with_limits' is False, any limit/offset information is not included
        in the query.
        rT   Nzsupports_select_{}z-{} is not supported on this database backend. z0 = 1r'  z AS r(  FROMz:select_for_update cannot be used outside of a transaction.zNLIMIT/OFFSET is not supported with select_for_update on this database backend.z1NOWAIT is not supported on this database backend.z6SKIP LOCKED is not supported on this database backend.z8FOR UPDATE OF is not supported on this database backend.z<FOR NO KEY UPDATE is not supported on this database backend.)nowaitskip_lockedofno_keyWHERE %sz1annotate() + distinct(fields) is not implemented.zGROUP BY %sz	HAVING %sr   zORDER BY %sr$  r%  rm   rn   r
  r   SELECT  FROM ( 
) subquery)Er=   rO   r   r   rk   rf   r  r2   rz   r   r   r	   r  combinator_allrd   r8  get_distinctget_from_clauser`   r|   r   r?   r   rc   r   r   distinct_sqlrA   r   rw   ru   r  bare_select_suffixselect_for_updatehas_select_for_updateget_autocommitsupports_transactionsr   %supports_select_for_update_with_limitselect_for_update_nowaitselect_for_update_skip_lockedselect_for_update_ofselect_for_no_key_updatehas_select_for_update_nowait!has_select_for_update_skip_lockedhas_select_for_update_ofhas_select_for_no_key_updatefor_update_sql"get_select_for_update_of_argumentsfor_update_after_fromr   force_no_orderingrD   force_group_byexplain_infoinsertexplain_query_prefixoptions#requires_compound_order_by_subquerylimit_offset_sqllow_mark	high_markr
  rv   relabeled_cloner   r3   tuplereset_refcounts)-r(   r#  rU   refcounts_beforer   rj   ri   rb   for_update_partwith_limit_offsetrz   r   r   r   distinct_paramsfrom_f_paramsr`   w_paramsrc   h_paramsdistinct_resultout_colsr   s_sqls_paramsr   r<  r=  r>  r?  groupingg_sqlg_paramsr   o_sqlo_paramsorder_by_sqlsub_selects
sub_paramsindexrA   select_clone	subselect	subparamss-                                                r,   r3   zSQLCompiler.as_sql  s     ::4499;X	9..J/3/A/A!1!ET*5E 0B 0,L(H #O + D

0D0D..J//Hx)=)D)DZ)PQ+GNN& 
 "&!8!8

 9 9" !%!5!5!7373D3D3F0 #'"6"6"8x
-48JJ4JTZZ0QSUWPX $E8.  ;;2 T[[1 "X %FH #::&&7;7J7J7W7W''84O_ o-Fo-F37;;3M/A(x%! OO//::5A! MM(+OOE* 4N 499X.//v...F__--@@t77JJKKFh':://H4R4R668 %::8X 
 * ( N N/J  "ZZ@@F"&**"J"JK88B!ZZ@@F h&K&K/O  %X-W-W/T  H$E$E/V   (M(M/0  '+oo&9&9&H&H%$/BBD%	 'I 'O #x'E'EMM/2MM*u"45MM(+'/OE8OOE*MM(+ (0 &1O   (R4??+>+>+P+P+RHMM-$))H2E"EF**#'#doo&9&9&H&H&JKMM+"67MM(+zz&&<DOO''<<

//66**1199 /7+A+xOOE*MM(+ 08  -tyy/BB("N"N/L&L#L|LFMM,/ OO''88

++TZZ-A-A x'E'Eo.zz""| !
1:4;;a1P-E-FAu#** !% 3 3 > >z J $ 3 3 > >u E (.'='=#\\:6( 0</B/B $//0,	9 $**95")))4# 2Q& IIk*HHV$ f,-. JJ&&'78 88F#U6]2 JJ&&'78q & 2''&-r8E$ -&("8E- % .')2HF.V JJ&&'78sa   D,b8 .a4 .b$ 0Y1b8 =b8 4b!b8 b!b8  b!!b8 $b51b8 4b55b8 8cNc                    g }|| j                   j                         x}|S |xs | j                   j                         }d|i}|j                  D ]  }|j                  j
                  j                  }||j                  k(  rd}|r7|5t        |j
                  j                  |j
                  j                        rm|r||vrt| j                   j                  ||||      }	|j                  |	      }
|j                  |
        |S )aT  
        Compute the default columns for selecting every field in the base
        model. Will sometimes be called to pull in related models (e.g. via
        select_related), in which case "opts" and "start_alias" will be given
        to provide a starting point for the traversal.

        Return a list of strings, quoted appropriately for use in SQL
        directly, as well as a set of aliases used in the select statement (if
        'as_pairs' is True, return a list of (alias, col_name) pairs instead
        of strings as the first component and None as the second component).
        N)r=   r   rX   concrete_fieldsrH   _metaconcrete_model
issubclassjoin_parent_modelget_colru   )r(   r   start_aliasoptsr   r   seen_modelsr   rH   r   r   s              r,   r   zSQLCompiler.get_default_columns  s     <

++--6!CTZZ%A%A%C [)))EKK%%44E 

"%%%44ekk6P6P uK7JJ00uk;WE]]5)FMM&!/ *0 r-   c                 @   g }g }| j                   j                         }| j                   j                  D ]  }|j                  t              }| j                  ||d      \  }}}}	}
}}| j                   j                  ||	|
      \  }}}|D ]  }|| j                   j                  v r5|j                  | j                  j                  j                  |             P| j                   |||            \  }}|j                  |       |j                  |         ||fS )z
        Return a quoted list of fields to use in DISTINCT ON part of the query.

        This method can alter the tables in the query, and thus it must be
        called before get_from_clause().
        N)r=   r   r   r   r
   _setup_joins
trim_joinsr   ru   r2   r   r   r|   )r(   r   r   r  r   r  r   targetsr   joinspathtransform_functionr   r   ps                  r,   rF  zSQLCompiler.get_distinct  s    zz""$JJ..DJJz*EDHDUDUtTEAAwudA/A !%

 5 5gud KGUA!4::777MM$//"5"5"@"@"FG<<(:65(IJDAqMM!$MM!$ " / v~r-   c                     t        |      \  }|dk(  }j                  t              } j                  |||      \  }	}
}}}}}|	j                  r1|j
                  r$t        |	dd      |d   k7  rdk7  r
t        |dd      s|xs
 t               }t         fd|D              }||v rt        d	      |j                  |       g }|j
                  D ]  }t        |d
      r2t        |t              s"|r|j                         n|j                         }t        |t              r+|j!                  |j#                   t               df       ||j%                  fd j'                  |||||      D                |S  j(                  j+                  |
||      \  }
}}|
D cg c]  }t         |||      |      df c}S c c}w )z
        Return the table alias (the name might be ambiguous, the alias will
        not be) and column name for ordering by the given 'name' parameter.
        The 'name' is of the form 'field1__field2__...__fieldN'.
        r   attnameNpkhas_transformsFc              3   f   K   | ](  }t        j                  j                  |   d d       * yw)	join_colsN)r   r=   rW   )rP   jr(   s     r,   rR   z1SQLCompiler.find_ordering_name.<locals>.<genexpr>1  s-      MR

,,Q/dCUs   .1z!Infinite loop caused by ordering.r   c              3   Z   K   | ]"  \  }}|j                   t               |f $ y wr$   )prefix_referencesr
   )rP   r   r   r   s      r,   rR   z1SQLCompiler.find_ordering_name.<locals>.<genexpr>C  s:      )f ++tfZL,ABFK)s   (+r   )r   r   r
   r  is_relationr   r   rp   re  r   rt   rq   rs   r   descr   ru   r  rw   r   r=   r  )r(   r   r  r   r   already_seenr   r   piecesr   r  r  r  r  
join_tupleresultsitemr   r   s   ``                 r,   r   zSQLCompiler.find_ordering_name  s    $D-8ef_
J' fdE2	
 y$/6":=.0@%H (035L MR J \) !DEEZ(G4!56z'@ +5499;$((*DdG,NN//4&0EFN  (,(?(?dE5,)  &  N JJ11'5$G 
 '51jI5Q
 	
 
s   *G
c                     |xs | j                   j                         }| j                   j                  |||      \  }}}}}}|d   }|||||||fS )a$  
        Helper method for get_order_by() and get_distinct().

        get_ordering() and get_distinct() must produce same target columns on
        same input, as the prefixes of get_ordering() and get_distinct() must
        match. Executing SQL where this is not true is an error.
        r  )r=   rX   setup_joins)	r(   r  r  r   r   r  r  r  r  s	            r,   r  zSQLCompiler._setup_joinsP  sf     7557@D

@V@VD%A
=weT+= b	gueT49KKKr-   c                 p   g }g }t        | j                  j                        D ]l  }| j                  j                  |   s	 | j                  j                  |   }| j                  |      \  }}|j                  |       |j                  |       n | j                  j                  D ]x  }| j                  j                  |      \  }}|| j                  j                  vs| j                  j                  |   dk(  sV|j                  d| j                  |      z         z ||fS # t        $ r Y w xY w)a  
        Return a list of strings that are joined together to go after the
        "FROM" part of the query, as well as a list any extra parameters that
        need to be included. Subclasses, can override this to create a
        from-clause via a "select".

        This should only be called after any SQL construction methods that
        might change the tables that are needed. This means the select columns,
        ordering, and distinct must be done first.
        rm   z, %s)re  r=   rW   rO   KeyErrorr|   ru   rw   extra_tablestable_aliasr   )	r(   r   r   r   from_clause
clause_sqlclause_paramsr   r   s	            r,   rG  zSQLCompiler.get_from_clause_  s    4:://0E::,,U3"jj2259
 )-[(A%JMM*%MM-( 1 ((Azz--a0HE1
 TZZ111::,,U3q8ft'C'CE'JJK ) v~#   s   D((	D54D5c           
           fd}g }	|s| j                   j                  kD  r|	S s4 j                   j                          j                   j                         }t	               }
|<t         j                   j                  t              }|r j                   j                  }d }j                  D ]  }|
j                  |j                         |rk|j                  |j                  i       }|j                  sE|s|j                  |v r5t        d|j                  ddj                   |             xs d      d}t        ||||      s|j                  |      xs i }|j                   j"                  |d|j$                  |j&                  r|j                   j$                  nd	 dd
}|	j)                  |       g } j                   j+                  |j                  g|      \  }}}}}}|d   } j-                  |||j                   j"                  j.                        }|D ]/  }|j)                  t1        |             |j)                  |df       1 ||d<    j3                  |||j                   j"                  j.                  ||dz   ||      } |||        |rǉj4                  D cg c]=  }|j6                  j&                  r%|j8                  s||j6                  |j:                  f? }}|D ]p  \  }}}t        ||||      s|j                  |      xs i }|j=                         }|
j                  |        j                   j+                  |g|      }|j>                  d   }tA        |j"                        xr |j"                  u}||d|j$                  |j$                  |d
}|	j)                  |       g } j-                  |||j.                  j"                        }|D ]/  }|j)                  t1        |             |j)                  |df       1 ||d<   |j                  |i       } j3                  |||j.                  ||dz   ||      } |||       s d }d } d }!tC        |      D ]  }"|dkD  r n|" j                   jD                  v s%|
j                  |"        j                   j+                  |"g|      \  }#}}$}}}|$j"                  }|d   }tA        |j"                        xr |j"                  u}||#dt1        |      dk  rtG        ||#      n| tG        |!|"      |d
}|	j)                  |       g }|j                  |"|#f      xs i }% j-                  |%||j.                  j"                        }|D ]/  }|j)                  t1        |             |j)                  |df       1 ||d<   |j                  |"i       }& j3                  ||%|j.                  ||dz   |&|      } |||        t	        |      jI                  |
      }'|'rAd |'D        }(t        ddj                  |(      ddj                   |             xs d      |	S c c}w )a  
        Fill in the information needed for a select_related query. The current
        depth is measured as the number of connections away from the root model
        (for example, cur_depth=1 means we are looking at models with direct
        connections to the root model).
        c                      d j                   D        } d j                  D        }t        | |j                  j                        S )Nc              3   N   K   | ]  }|j                   s|j                    y wr$   )r  r   rP   fs     r,   rR   zQSQLCompiler.get_related_selections.<locals>._get_field_choices.<locals>.<genexpr>  s     KkQ]]affks   %%c              3   |   K   | ]4  }|j                   j                  r|j                   j                          6 y wr$   )r   uniquerelated_query_namer  s     r,   rR   zQSQLCompiler.get_related_selections.<locals>._get_field_choices.<locals>.<genexpr>  s0      -A77>> **,-s   :<)fieldsrelated_objectsr   r=   _filtered_relations)direct_choicesreverse_choicesr  r(   s     r,   _get_field_choicesz>SQLCompiler.get_related_selections.<locals>._get_field_choices  sF    KdkkKN--O
 1O1O r-   Nc                     || d<   y )Nr   r/   )rC   r   s     r,   get_related_klass_infoszCSQLCompiler.get_related_selections.<locals>.get_related_klass_infos  s    0CJ,-r-   z/Non-relational field given in select_related: 'z'. Choices are: r(  z(none)Fc                      y r$   r/   )xys     r,   <lambda>z4SQLCompiler.get_related_selections.<locals>.<lambda>  s    RVr-   )rH   r   reverselocal_setterremote_setterr   r  )r  r  r   rm   T)r  r  r   c                 B    |r| j                   j                  ||       y y r$   )remote_fieldset_cached_value)final_fieldobjfrom_objs      r,   r  z8SQLCompiler.get_related_selections.<locals>.local_setter#  s     ,,==hL r-   c                      y r$   r/   )r  r  s     r,   local_setter_noopz=SQLCompiler.get_related_selections.<locals>.local_setter_noop(  s    r-   c                     t        || |       y r$   )setattr)r   r  r  s      r,   r  z9SQLCompiler.get_related_selections.<locals>.remote_setter+  s    $,r-      )r  
root_alias	cur_depth	requested
restrictedc              3   &   K   | ]	  }d |z    yw)z'%s'Nr/   )rP   ss     r,   rR   z5SQLCompiler.get_related_selections.<locals>.<genexpr>b  s     !G6F&1*6F   z/Invalid field name(s) given in select_related: z. Choices are: )%r=   	max_depthr   rX   rp   rs   r   dictr  rt   r   r}   r  r   r  r   r  rH   r  r  ru   r  r   r  rZ   r   r  r   many_to_manyrelated_modelr  r  r  r+  r  r   r   ))r(   rA   r   r  r  r  r  r  r  r   fields_foundr  r  nextrelated_select_maskrC   r   r   r  r   columnsr   next_klass_infosorelated_fieldsrelated_objectrelated_fieldrH   related_field_name	join_infor   r  r  r  r   r  	join_optsfield_select_masknext_requestedfields_not_foundinvalid_fieldss)   `  `                                     r,   r   z"SQLCompiler.get_related_selections  s   "		 !i$***>*>>&&::&&(D557J u#DJJ$=$=tDJ JJ55		D AQVV$ }}QVVR0}} qvv2( !" $		*<*> ? K8 K	  )!ZKP"-//!"4":--  ! 2 278xxANN33EV$	J  &&z2M#'::#9#9166(D*#U Aq!UAq"IE..#Q^^=Q=Q=W=W / G $$S[1sDk*  +8J'#::#$$**A  $J0@Ak n  ---A77>>!.. AGGQ__--  
 9G4u-"	 &1oon&E&K#%2%E%E%G"  !34 JJ22'($
	 "+(

;WTZZ@W"*#$2$C$C%2%C%C#.
 $**:6 "22' % $

	 3  #C!((V5MM3+. # /<
?+ }}%7<#'#>#>'KKM$  (
4DEa 9GdM
- Yq=4::999 $$T*=AZZ=S=Sj>:KIua &OOE!"IE"5$**5Q%tzz:Q   "'!,#'  #5zQ $L+>!2)0)E'2"J (..z:$&M(3{8K(L(RPR%"66)$)"[[$(JJ	 7 G  '%,,S[9sDk2  ' 3@J/%.]]4%<N'+'B'B)"[[#("+a-"0#- (C ($ ,J8HIc (d  #9~88F!G6F!G  		.1		"4"67C8C	  #"s   8AY3c           	           fd fd} fd} j                   sg S g }g } j                  j                  D ]  } j                   }|dk(  r	 ||      }n|j                  t              D ]R  }g |j                  dg        |      }	|	D ]+  }
|
d   }|
d   r|j                  }|j                  |k(  s)|
} O d} n ||j                  |        ||      }| j                  j                  j                  r$|j                   j                  |      d	          |j                   j                  |j                                |r5t        d
dj!                  |      ddj!                   |             d      |S )zk
        Return a quoted list of arguments for the SELECT FOR UPDATE OF part of
        the query.
        c           	   3     K   | d   j                   j                  }|j                   j                  j                         D ]  \  }}|j                   j                  }||d| d   D cg c]U  }j
                  |   d   j                  j                  |k(  s(j
                  |   d   j                  j                  |v r|W c}d  y c c}w w)NrH   Fr   r   )rH   r   r  r   )r  r  parentsr   all_parentsrA   r   rH   )rC   r  parent_modelparent_linkr  select_indexr(   s         r,   _get_parent_klass_infozNSQLCompiler.get_select_for_update_of_arguments.<locals>._get_parent_klass_infos  s     '066EEN-;-A-A-I-I-O-O-Q)k*00<<)($ -7,G&,GL !KK5a8??EEU#{{<8;BBHHKW %,G&	  .R&s   A$C'ACCc                     | d   j                   j                  }| d   D ]?  }j                  |   d   j                  j                  |k(  s-j                  |   d   c S  y)z
            Find the first selected column from a model. If it doesn't exist,
            don't lock a model.

            select_fields is filled recursively, so it also contains fields
            from the parent models.
            rH   r   r   N)r  r  rA   r   rH   )rC   r  r  r(   s      r,   "_get_first_selected_col_from_modelzZSQLCompiler.get_select_for_update_of_arguments.<locals>._get_first_selected_col_from_model  s`     (066EEN *? ;;;|,Q/66<<N;;|4Q77 !<r-   c               3     K   t        j                  dj                  fg      } | r| j                         \  }}|g d n=|d   }|d   r|j                  }||j
                  gz   t        j                         | j                  fd |      D               | j                  fd|j                  dg       D               | ryyw)z<Yield all allowed field paths in breadth-first search order.Nr(   r   r  c              3   &   K   | ]  }|f 
 y wr$   r/   rP   rC   r  s     r,   rR   z]SQLCompiler.get_select_for_update_of_arguments.<locals>._get_field_choices.<locals>.<genexpr>  s      &H
 :&&H   c              3   &   K   | ]  }|f 
 y wr$   r/   r  s     r,   rR   z]SQLCompiler.get_select_for_update_of_arguments.<locals>._get_field_choices.<locals>.<genexpr>  s      &O
 :&&Or  r   )
collectionsdequerC   popleftr  r   r
   r  rw   r}   )queueparent_pathrC   r   r  r  r(   s       @r,   r  zJSQLCompiler.get_select_for_update_of_arguments.<locals>._get_field_choices  s     %%doo'>&?@E*/--/'Z&D L&w/E!), % 2 2&%**5D$//$// &<Z&H   &0nn5JB&O  s   C
CCr(   r   r   r  Nr   z<Invalid field name(s) given in select_for_update(of=(...)): r(  zI. Only relational fields followed in the query are allowed. Choices are: r   )rC   r=   rQ  r   r
   r}   r  r   ru   r2   rz   select_for_update_of_columnr|   r   r   r   r  )r(   r  r  r   invalid_namesr   rC   r   r  klass_infosrelated_klass_infor   r  s   `           @r,   rX  z.SQLCompiler.get_select_for_update_of_argumentsm  s   	&	8	. IJJ33DJv~8D JJz2D##(=rB#/
;#K /:* 27 ;-i8$)$6$6E ::-);J! /: &*
 3 %!((.8D??++GGMM$,,s"3A"67MM$">">syy"IJ9 4: 
 IIm,II023  r-   c                     i }t        |      D ]W  \  }}|s	| j                  j                  j                  |      }|j                  | j                        }|s|sN||z   |f||<   Y |S r$   )rv   r2   r   get_db_converters)r(   r   
convertersir   backend_convertersfield_converterss          r,   get_converterszSQLCompiler.get_converters  so    
&{3MAz%)__%8%8%J%J:%V"#-#?#?#P %)9%7:J%JJ$WJqM 4 r-   c              #      K   | j                   }t        |j                               }t        t        |      D ].  }|D ]#  \  }\  }}||   }|D ]  }	 |	|||      } |||<   % | 0 y wr$   )r2   r+  r   map)
r(   rowsr  r2   rowposconvsr   value	converters
             r,   apply_converterszSQLCompiler.apply_converters  sw     __
***,-
tT?C,6((eZC!&I%eZDE "' C	 -7
 I #s   A(A*c                 .   || j                  t        ||      }| j                  d| j                   D cg c]  }|d   	 }}| j	                  |      }t        j                  |      }|r$| j                  ||      }|rt        t        |      }|S c c}w )z>Return an iterator over the results from executing this query.)chunked_fetch
chunk_sizer   )
execute_sqlr   rA   r[   r  r   from_iterabler  r  re  )	r(   r  tuple_expectedr  r  r  r  r  r	  s	            r,   results_iterzSQLCompiler.results_iter  s     ?&&]z ' G !%A ?@ ?1!A$ ?@((0
""7+((z:D5$' As   Bc                 >    t        | j                  t                    S )z
        Backends (e.g. NoSQL) can override this in order to use optimized
        versions of "query has any results."
        )rf   r  r   rI   s    r,   has_resultszSQLCompiler.has_results  s    
 D$$V,--r-   c                 ^   |xs t         }	 | j                         \  }}|st        	 |r| j
                  j                         }n| j
                  j                         }	 |j                  ||       |t        k(  r|S |t        k(  rD	 |j                         }|r|d| j                   |j                          S ||j                          S |t         k(  r|j                          yt        || j
                  j                   j"                  | j$                  r| j                  nd|      }|r | j
                  j                   j&                  st)        |      S |S # t        $ r |t        k(  rt	        g       cY S Y yw xY w# t        $ r |j                           w xY w# |j                          w xY w)a  
        Run the query against the database and return the result(s). The
        return value is a single data item if result_type is SINGLE, or an
        iterator over the results if the result_type is MULTI.

        result_type is either MULTI (use fetchmany() to retrieve all rows),
        SINGLE (only retrieve a single row), or None. In this last case, the
        cursor is returned if any query is executed, since it's used by
        subclasses such as InsertQuery). It's possible, however, that no query
        is needed, as the filters describe an empty set. In that case, None is
        returned, to avoid any unnecessary database interaction.
        Nr   )r   r3   r   r   iterr2   chunked_cursorcursorexecute	Exceptioncloser   r   fetchoner[   cursor_iterrz   empty_fetchmany_valuerg   can_use_chunked_readsr+  )	r(   result_typer  r  r   r   r  valr   s	            r,   r  zSQLCompiler.execute_sql  s~    "/Z	++-KC$$  __335F__++-F	NN3' & M& oo'q4>>2   *$LLNOO$$::"33DNN	
 DOO$<$<$R$R
 <Y  	e#Bx		  	LLN	  s/   E  E<  F 8F E98E9<FF,c                    |j                   }| j                  j                  j                  }t	        | j
                  j                        D ]h  \  }}| j                  |      \  }}	 ||      d |||         }
| j
                  j                  j                  t        |d|
|	      t               j | j                         \  }}d|z  |fS )Nr    = zEXISTS (%s))r   r2   r   r   rv   r=   rA   r|   r`   rt   r   r   r3   )r(   r   r  r1   qnqn2r{  
select_collhs_sql
lhs_paramsrhsr   r   s                r,   as_subquery_conditionz!SQLCompiler.as_subquery_conditionJ  s    --oo!!,,!*4::+<+<!=E:"&,,z":GZYGEN(;<CJJ  Wc(BJ!OQTU ">
 kkmVs"F**r-   c           
   #   r  K   t        | j                               }| j                  j                  j                  }|r#|j                         dk(  rt        j                  nt        }|D ]E  }|D ]>  }t        |t              s(dj                  |D cg c]
  } ||       c}       ;| @ G y c c}w w)NjsonrC  )r+  r  r=   r\  r   lowerr0  dumpsr0   rs   r  )r(   r   format_output_formatterr
  r  cs          r,   explain_queryzSQLCompiler.explain_queryV  s     d&&() **))00)0W]]_5N4::TWC!%-((#GA$4Q$7#GHHK	   $Hs   BB7B2B7)T)F)TF)NNN)Nr   N)NNrm   NN)'r4   r5   r6   r    re	MULTILINEDOTALLr   r'   rJ   r\   rk   rh   ry   rY   r   r_   re   r   r|   r  r8  r3   r   rF  r   r  rG  r   rX  r  r  r   r  r  r   r  r.  r6  r/   r-   r,   r:   r:   '   s    % 
ryy N
#"
*0 eN@U,nM^;z,N`^@a9H EI0d6 IM?
BL#R g#RhT	 **.  uAX@D
+ r-   r:   c                   :    e Zd ZdZdZd Zd Zd Zd Zd Z	d	dZ
y)
SQLInsertCompilerNr/   c                 
   ||g }}nSt        |d      r| j                  |      \  }}n2t        |d      r!|j                  || | j                        |g}}nd|g}}| j                  j                  j                  ||      }||fS )at  
        Take a field and a value intended to be saved on that field, and
        return placeholder SQL and accompanying params. Check for raw values,
        expressions, and fields with get_placeholder() defined in that order.

        When field is None, consider the value raw and use it as the
        placeholder, with no corresponding parameters returned.
        r3   get_placeholder%s)rq   r|   r=  r2   r   modify_insert_params)r(   r   r%  r   r   s        r,   field_as_sqlzSQLInsertCompiler.field_as_sqlh  s     =rCS(#,,s+KCU-.  //T4??KcUC C $$99#vFF{r-   c                 l   t        |d      r|j                  | j                  dd      }|j                  rt	        d|d|d      |j
                  rt        d|j                  d	|d
      |j                  rt        d|j                  d	|d
      |j                  || j                        S )z
        Prepare a value to be used in a query by resolving it if it is an
        expression and otherwise calling the field's get_db_prep_save().
        r   FTr   for_savezFailed to insert expression "z" on z<. F() expressions can only be used to update, not to insert.3Aggregate functions are not allowed in this query (=).2Window expressions are not allowed in this query (r2   )rq   r   r=   contains_column_references
ValueErrorcontains_aggregater   r   contains_over_clauseget_db_prep_saver2   )r(   r   r  s      r,   prepare_valuezSQLInsertCompiler.prepare_value  s    
 5./,,

 - E // DI5R  '' "'**e5  )) zz5*  %%e%HHr-   c                     | j                   j                  rt        ||j                        S |j	                  |d      S )z
        Get the given field's value off the given obj. pre_save() is used for
        things like auto_now on DateTimeField. Skip it if this is a raw query.
        T)rt   )r=   rawr   r  pre_save)r(   r   r  s      r,   pre_save_valzSQLInsertCompiler.pre_save_val  s3    
 ::>>3..~~ct~,,r-   c                      |sg g fS  fd|D        }d |D        }t        | \  }}|D 	cg c]  }|D 	cg c]  }|D ]  }	|	  c}	} }}}}	||fS c c}	}w c c}	}}w )a+  
        Take a sequence of N fields and a sequence of M rows of values, and
        generate placeholder SQL and parameters for each field and value.
        Return a pair containing:
         * a sequence of M rows of N SQL placeholder strings, and
         * a sequence of M rows of corresponding parameter values.

        Each placeholder string may contain any number of '%s' interpolation
        strings, and each parameter row will contain exactly as many params
        as the total number of '%s's in the corresponding placeholder row.
        c              3   H   K   | ]  }fd t        |      D          yw)c              3   H   K   | ]  \  }}j                  ||        y wr$   )r@  )rP   r   vr(   s      r,   rR   z>SQLInsertCompiler.assemble_as_sql.<locals>.<genexpr>.<genexpr>  s%     J9IXUATua(9I   "Nr  )rP   r
  r  r(   s     r,   rR   z4SQLInsertCompiler.assemble_as_sql.<locals>.<genexpr>  s&      !
! KVS9IJ!rW  c              3   ,   K   | ]  }t        |   y wr$   rX  )rP   r
  s     r,   rR   z4SQLInsertCompiler.assemble_as_sql.<locals>.<genexpr>  s     "N8M398Ms   rX  )
r(   r  
value_rowsrows_of_fields_as_sqlsql_and_param_pair_rowsplaceholder_rows
param_rowsr
  psr  s
   ``        r,   assemble_as_sqlz!SQLInsertCompiler.assemble_as_sql  s     r6M!
!!
 #O8M"N (+,C'D$* @JJz333R1qq33z
J++ 4Js   
AA	AAc                    | j                   j                  j                  | j                  j	                         }| j                   j                  j                  | j                  j                        }|d |j                        g}| j                  j                  xs |j                  g}|j                  ddj                  fd|D              z         | j                  j                  rT| j                  j                  D cg c]2  }|D cg c]$  }| j                  || j                  ||            & c}4 }}}nI| j                  j                  D cg c]'  }| j                   j                  j                         g) }}d g}| j                    xr  | j                   j"                  j$                  }	| j'                  ||      \  }
}| j                   j                  j)                  || j                  j                  d | j                  j*                  D        d | j                  j,                  D              }| j                   rB| j                   j"                  j.                  r!| j                   j"                  j0                  r8|j                  | j                   j                  j3                  ||
             |}n,|j                  ddj                  |
d	         z         |d	   g}|r|j                  |       | j                   j                  j5                  | j                         \  }| _        |r!|j                  |       || j6                  gz  }dj                  |      t9        t;        j<                  |            fgS |	rl|j                  | j                   j                  j3                  ||
             |r|j                  |       dj                  |      t9        d
 |D              fgS |r|j                  |       t?        |
|      D cg c].  \  }}dj                  |ddj                  |      z  gz         |f0 c}}S c c}w c c}}w c c}w c c}}w )N)on_conflictrC  z(%s)r(  c              3   B   K   | ]  } |j                           y wr$   r   )rP   r  r(  s     r,   rR   z+SQLInsertCompiler.as_sql.<locals>.<genexpr>  s     (Fv!AHHv   c              3   4   K   | ]  }|j                     y wr$   rd  r  s     r,   rR   z+SQLInsertCompiler.as_sql.<locals>.<genexpr>       87!QXX7   c              3   4   K   | ]  }|j                     y wr$   rd  r  s     r,   rR   z+SQLInsertCompiler.as_sql.<locals>.<genexpr>  rg  rh  zVALUES (%s)r   c              3   .   K   | ]  }|D ]  }|   y wr$   r/   )rP   r_  r  s      r,   rR   z+SQLInsertCompiler.as_sql.<locals>.<genexpr>  s     ,P2RQRQs   ) r2   r   r   r=   r   insert_statementrb  db_tabler  r  ru   r  objsrN  rR  pk_default_valuereturning_fieldsrz   has_bulk_insertr`  on_conflict_suffix_sqlupdate_fieldsunique_fieldscan_return_columns_from_insert can_return_rows_from_bulk_insertbulk_insert_sqlreturn_insert_columnsreturning_paramsre  r   r  r  )r(   r  rk  r   r  r  r   rZ  r   can_bulkr]  r^  rq  r   r_sqlr  valsr(  s                    @r,   r3   zSQLInsertCompiler.as_sql  s    __  ++zz""$??..??

.. @ 
 .r$--/@AB""/twwiftyy(Fv(FFFG::  ::??
 +C "(!' &&ud.?.?s.KL!' +   CG**//BQQ$$5578/   VF %%%R$//*B*B*R*R 	 (,';';FJ'O$*!%!4!4!K!KJJ""8tzz7788tzz778	"
 !!((GG''HHOO''77@PQ $mdii8H8K.LLM$Q-%45 ,0??+>+>+T+T%%,(E4( e$40011XXf%uU-@-@-H'IJKKMM$//--==fFVWX%45XXf%u,P,P'PQRR%45  ##3Z@@GAt &MDIIaL$@#AABDI@ {js$   	Q#)Q Q#!,Q)'3Q.Q#c                    |rDt        | j                  j                        dk7  r"| j                  j                  j
                  sJ | j                  j                         }|| _        g }| j                  j                         5 }| j                         D ]  \  }}|j                  ||        | j                  sg cd d d        S | j                  j                  j
                  r{t        | j                  j                        dkD  rY| j                  j                  j                  |      }| j                  D cg c]  }|j                  |j                         }}n| j                  j                  j                  rt        | j                  j                        dk(  sJ | j                  j                  j!                  || j"                        g}| j                  D cg c]  }|j                  |j                         }}nm|j$                  j                  |j                        g}| j                  j                  j'                  ||j                  |j$                  j(                        fg}d d d        | j+                  |      }	|	rt-        | j/                  |	            }S c c}w c c}w # 1 sw Y   CxY wr   )rZ   r=   rm  r2   rz   ru  r   ro  r  r3   r  r   fetch_returned_insert_rowsr  rl  rt  fetch_returned_insert_columnsrx  r  last_insert_idr   r  r+  r  )
r(   ro  r  r   r  r   r   r	  r   r  s
             r,   r  zSQLInsertCompiler.execute_sql!  s2   DJJOO$)OO,,MM	
 

 zz""$ 0__##%#{{}VsF+  -((	 &% ((II

(1,**EEfMBFBWBWXBWdmm4BWX))HH4::??+q000OO''EE-- CGBWBWXBWdmm4BWX67 ++::" MM GGNN- &> ((.
--dJ?@D1 Y Y' &%s3   8J8A5J8;"J.BJ8$"J3A0J8.
J88Kr$   )r4   r5   r6   ro  rx  r@  rN  rR  r`  r3   r  r/   r-   r,   r;  r;  d  s1    @I:-!,FN`+r-   r;  c                   H    e Zd Zed        Zed        Zed        Zd Zd Z	y)SQLDeleteCompilerc                       j                   j                          t         fd j                   j                  D              dk(  S )Nc              3   V   K   | ]   }j                   j                  |   d kD   " ywrM   rN   )rP   r   r(   s     r,   rR   z1SQLDeleteCompiler.single_alias.<locals>.<genexpr>T  s(     R=Q4::,,Q/!3=QrS   rm   )r=   rX   sumrW   rI   s   `r,   single_aliaszSQLDeleteCompiler.single_aliasP  s6     	

$$&RTZZ=Q=QRRVWWWr-   c                      t        |t              r|j                  k(  S t        |d      syt	         fd|j                         D              S )Nr  Fc              3   B   K   | ]  }j                  |        y wr$   )_expr_refs_base_model)rP   source_expr
base_modelclss     r,   rR   z:SQLDeleteCompiler._expr_refs_base_model.<locals>.<genexpr>\  s&      
< %%k:><re  )rs   r   rH   rq   anyr  )r  r   r  s   ` `r,   r  z'SQLDeleteCompiler._expr_refs_base_modelV  sM    dE"::++t56 
#::<
 
 	
r-   c                      t         fdt         j                  j                  j	                          j                  j
                  j                        D              S )Nc              3   j   K   | ]*  }j                  |j                  j                         , y wr$   )r  r=   rH   )rP   r   r(   s     r,   rR   zESQLDeleteCompiler.contains_self_reference_subquery.<locals>.<genexpr>c  s4      
 &&tTZZ-=-=>s   03)r  r   r=   r   r*  r`   childrenrI   s   `r,    contains_self_reference_subqueryz2SQLDeleteCompiler.contains_self_reference_subquerya  sJ     


&&--/1A1A1J1J
 
 	
r-   c                     d| j                  |j                        z  }	 | j                  |j                        \  }}| d| t        |      fS # t        $ r |dfcY S w xY w)NzDELETE FROM %sr/   z WHERE )r   
base_tabler|   r`   r   re  )r(   r=   deleter`   r   s        r,   _as_sqlzSQLDeleteCompiler._as_sqlj  so    !D$@$@AQAQ$RR	 LL5ME6 (%-77  	2:	s   A A A c                     | j                   rG| j                  j                  j                  s| j                  s| j                  | j                        S | j                  j                         }t        |_	        |j                          | j                  j                  j                  j                  }|j                  | j                  j                               g|_        t        | j                  j                        }| j                  j                  j"                  s<|j%                  | j                        j'                         \  }}t)        d|z  |      }|j+                  d|       | j                  |      S )f
        Create the SQL for this query. Return the SQL string and list of
        parameters.
        rH  zSELECT * FROM (%s) subquerypk__in)r  r2   rz   "delete_can_self_reference_subqueryr  r  r=   r  r   r+   clear_select_clauserH   r  r  r  rX   rA   update_can_self_selectr  r3   r   
add_filter)r(   innerqr  outerqr   r   s         r,   r3   zSQLDeleteCompiler.as_sqlr  s   
 OO$$GG88<<

++!!# ""$ZZ##&&DJJ$@$@$BCDtzz''(''>> !---IPPRKC9C?HF(F+||F##r-   N)
r4   r5   r6   r   r  classmethodr  r  r  r3   r/   r-   r,   r  r  O  sH    X X
 
 
 
 
8$r-   r  c                   .     e Zd Zd Z fdZ fdZ xZS )SQLUpdateCompilerc           
      n   | j                          | j                  j                  sy| j                  }g g }}| j                  j                  D ]  \  }}}t	        |d      rn|j                  | j                  dd      }|j                  rt        d|j                  d|d      |j                  rot        d	|j                  d|d      t	        |d
      rG|j                  r|j                  |      }n)t        d|d|d|j                  j                  d      |j                  || j                         }t	        |d      r|j#                  || | j                         }nd}|j$                  }t	        |d      rF| j'                  |      \  }	}
|j)                   ||      d||	z         |j+                  |
       ||/|j)                   ||      d|       |j)                  |       |j)                  d ||      z          | j                  j,                  }d ||      z  dj/                  |      g}	 | j'                  | j                  j0                        \  }}
|j)                  d|z         dj/                  |      t5        ||
z         fS # t2        $ r g }
Y ,w xY w)r  )r:  r/   r   FTrB  rD  rE  rF  rG  prepare_database_savezTried to update field z with a model instance, z. Use a value compatible with r   rH  r=  r>  r3   r'  z	%s = NULLzUPDATE %s SETr(  r@  rC  )rk   r=   r*  r   rq   r   rK  r   r   rL  r  r  	TypeErrorr+   r4   rM  r2   r=  r   r|   ru   rw   r  r  r`   r   re  )r(   r(  r*  update_paramsr   rH   r%  placeholderr   r   r   r   r   r`   s                 r,   r3   zSQLUpdateCompiler.as_sql  s{   
 	zz  )) "B!%!2!2E5#s01,,JJED -  ))$&+jj#7  ++$&+jj#7  56%%33E:C# !#u'?'?A 
 (((IC u/0#33CtO"<<DsH%"ll3/V2d8[35FGH$$V,2d8[AB$$S)kBtH45Q "3R 

%%bi'IIf
	. LL)9)9:ME6 MM*u,-xx}v'=!>>>	  	F	s   (J& &J43J4c                 L   t         |   |      }	 |r|j                  nd}|du }|r|j                          	 | j                  j                         D ]6  }|j                  | j                        j                  |      }|s0|s3|}d}8 |S # |r|j                          w w xY w)a  
        Execute the specified update. Return the number of rows affected by
        the primary update query. The "primary update query" is the first
        non-empty query that is executed. Row counts for any subsequent,
        related queries are not available.
        r   NF)r&   r  rowcountr  r=   get_related_updatesr  r>   )r(   r$  r  r	  is_emptyr=   aux_rowsr+   s          r,   r  zSQLUpdateCompiler.execute_sql  s     $[1	&,6??!D~HZZ335E))$**5AA+NHH 	 6
   s   B B#c                    | j                   j                  j                         }| j                   j                          | j                   j	                         }| j                   j
                  s|dk(  ry| j                   j                  t              }d|_        |j                  d       i |_
        g |_        |j                         }|j                  j                  g}g }| j                   j
                  D ]  }t        d |j!                  |      D              r|j#                  |df       8|j#                  |t%        |      f       |j#                  |j&                  j                  j                          |j)                  |       t*        | Y          |dkD  xr! | j.                  j0                  j2                   }| j                   j5                          | j                   j
                  s|rg }	t7        j8                  t:              }
|j=                  | j>                        jA                  tB              D ]A  }|	jE                  d	 |D               |D ]"  \  }|
|   jE                  fd
|D               $ C | j                   jG                  d|	       |
| j                   _$        n| j                   jG                  d|       | j                   jK                  |       y)aO  
        If the update depends on results from other tables, munge the "where"
        conditions to match the format required for (portable) SQL updates.

        If multiple updates are required, pull out the id values to update at
        this point so that they don't change as a result of the progressive
        updates.
        rm   N)klassFT)forcec              3   H   K   | ]  }|j                   j                    y wr$   )
join_fieldr   )rP   r  s     r,   rR   z2SQLUpdateCompiler.pre_sql_setup.<locals>.<genexpr>  s      8X++8Xs    "r   c              3   &   K   | ]	  }|d      ywrM   r/   )rP   r   s     r,   rR   z2SQLUpdateCompiler.pre_sql_setup.<locals>.<genexpr>  s     1DqadDr  c              3   (   K   | ]	  }|     y wr$   r/   )rP   r   r{  s     r,   rR   z2SQLUpdateCompiler.pre_sql_setup.<locals>.<genexpr>  s     .FAqxs   r  )&r=   rO   r   rX   count_active_tablesrelated_updatesr   r   r   clear_orderingr   rA   r   r  r   rV   get_path_to_parentru   rZ   r  
add_fieldsr&   rk   r2   rz   r  clear_wherer  defaultdictr+  r  r>   r  r   rw   r  related_idsrf  )r(   rg  countr=   r   r  related_ids_indexrelatedmust_pre_selectidentsr  r	  parentr{  r+   s                @r,   rk   zSQLUpdateCompiler.pre_sql_setup  sU     ::4499;

$$&

..0zz))eqj

  u -$4(~~'',,zz11G 8<8O8OPW8X 
 "(('16
 "(('3v;)?@gmm..334 2 	  AIMdoo66MMM 	 	

 ::%% F%11$7K**4::6BB5I1D11%6MFE'...F.FF &7 J JJ!!(F3%0DJJ" JJ!!(E2

""#34r-   )r4   r5   r6   r3   r  rk   r7   r8   s   @r,   r  r    s    >?@*=5 =5r-   r  c                       e Zd Zd Zy)SQLAggregateCompilerc                 4   g g }}| j                   j                  j                         D ]N  }| j                  |      \  }}|j	                  | ||      \  }}|j                  |       |j                  |       P t        | j                   j                        | _        dj                  |      }t        |      }| j                   j                  j                  | j                  | j                        j                  d      \  }}d|d|d}||z  }||fS )r  r(  )r?   TrT   rA  rB  rD  )r=   r   r*  r|   r~   ru   rw   rZ   r[   r  re  r  r  r>   r?   r3   )r(   r   r   r   ann_sql
ann_paramsinner_query_sqlinner_query_paramss           r,   r3   zSQLAggregateCompiler.as_sql"  s   
 "V**66==?J"&,,z":GZ",":":4*"UGZJJwMM*%	 @
 TZZ99:iinv.2jj.D.D.Q.QJJ(( /R /
 &$&
' 	,+ 14_E$$F{r-   N)r4   r5   r6   r3   r/   r-   r,   r  r  !  s    r-   r  c              #       K   	 t         fd|      D ]  }||n|D cg c]  }|d| 	 c}  	  j                          yc c}w #  j                          w xY ww)z[
    Yield blocks of rows from a cursor and ensure the cursor is closed when
    done.
    c                  &     j                        S r$   )	fetchmany)r  itersizes   r,   r  zcursor_iter.<locals>.<lambda>@  s    &"2"28"<r-   N)r  r  )r  sentinelr[   r  r	  r   s   `  `  r,   r!  r!  :  s\     
<xHD#+$1NA!JY-1NN I 	 2Os+   A A AA A A AA )8r  r0  r7  	functoolsr   	itertoolsr   django.core.exceptionsr   r   r   	django.dbr   r	   django.db.models.constantsr
   django.db.models.expressionsr   r   r   r   r   django.db.models.functionsr   r   django.db.models.lookupsr   django.db.models.query_utilsr   django.db.models.sql.constantsr   r   r   r   r   r   django.db.models.sql.queryr   r   django.db.models.sql.wherer   django.db.transactionr   django.utils.functionalr   django.utils.hashabler   django.utils.regex_helperr    r"   r:   r;  r  r  r  r!  r/   r-   r,   <module>r     s      	   L L 6 1 G G 3 + ?  < * < 3 / 6%# %z  z z1h hV9$ 9$xS5 S5l; 2	r-   