3
gd%                @   sJ  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 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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+ G dd dZ,G dd de,Z-G dd de,Z.G dd de,Z/G dd de,Z0dd Z1dS )    N)partial)chain)EmptyResultSet
FieldError)DatabaseErrorNotSupportedError)
LOOKUP_SEP)FOrderByRawSQLRefValue)CastRandom)Qselect_related_descend)CURSORGET_ITERATOR_CHUNK_SIZEMULTI
NO_RESULTS	ORDER_DIRSINGLE)Queryget_order_dir)TransactionManagementError)cached_property)make_hashable)_lazy_re_compilec               @   s  e Zd ZedejejB Zdd Zdd Z	dd Z
dd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zdd Zd=ddZd>ddZdd  Zd?d"d#Zd$d% Zd&d' Zd@d)d*Zd+d, Zd-d. Zd/d0 Zd1d2 Zdddefd3d4Zd5d6 Z e!defd7d8Z"d9d: Z#d;d< Z$dS )ASQLCompilerz^(.*)\s(?:ASC|DESC).*c             C   s8   || _ || _|| _ddi| _d | _d | _d | _d | _d S )N*)query
connectionusingquote_cacheselectannotation_col_map
klass_info_meta_ordering)selfr    r!   r"    r)   [/var/www/tester-filtro-web/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py__init__   s    
zSQLCompiler.__init__c                sH   t  fdd jjD r$ jj   j \ _ _ _t j _	d S )Nc             3   s   | ]} j j| d kV  qdS )r   N)r    alias_refcount).0a)r(   r)   r*   	<genexpr>,   s    z*SQLCompiler.setup_query.<locals>.<genexpr>)
allr    	alias_mapget_initial_alias
get_selectr$   r&   r%   len	col_count)r(   r)   )r(   r*   setup_query+   s    
zSQLCompiler.setup_queryc             C   sX   | j   | j }| jjj \| _| _| j|| j}t|| _	| j
| j| |}|||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.
        )r6   get_order_byr    whereZsplit_havinghavingget_extra_selectr$   boolhas_extra_selectget_group_by)r(   order_byextra_selectgroup_byr)   r)   r*   pre_sql_setup1   s    
zSQLCompiler.pre_sql_setupc             C   sx  | j jdkrg S g }| j jdk	rZx8| j jD ],}t|dsL|j| j j| q*|j| q*W dd |D }x<|D ]4\}}}||krqn|j }x|D ]}|j| qW qnW x(|D ] \}\}	}
}|s|j|j  qW | jr| jj nf }x|D ]}|j| qW g }t }| j	||}x`|D ]X}| j
|\}	}
|j| |	|
\}	}
t|
}|	|f|kr|j|	|
f |j|	|f qW |S )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".
        NTas_sqlc             S   s   h | ]}t |tr|jqS r)   )
isinstancer   source)r-   exprr)   r)   r*   	<setcomp>u   s   z+SQLCompiler.get_group_by.<locals>.<setcomp>)r    r@   hasattrappendZresolve_refZget_group_by_colsextendr9   setcollapse_group_bycompileselect_formatr   add)r(   r$   r>   expressionsrE   Zref_sources_colscolsqlparamsis_refZhaving_group_byresultseenparams_hashr)   r)   r*   r=   ?   sB    %



zSQLCompiler.get_group_byc                s   j jjr|d }x>|D ]6}t|dd jjjjkrt|dd jjkr|}P qW |rdd |D |gfdd|D  }n>j jj	rfdd|D dd D   fd	d|D }|S )
Ntargetaliasc             S   s$   h | ]}t |d r|jjr|jqS )rY   )rG   rY   primary_keyrZ   )r-   rE   r)   r)   r*   rF      s   z0SQLCompiler.collapse_group_by.<locals>.<setcomp>c                s2   g | ]*}| ks*t |d ddk	r|jkr|qS )rZ   N)getattrrZ   )r-   rE   )r9   
pk_aliasesr)   r*   
<listcomp>   s    z1SQLCompiler.collapse_group_by.<locals>.<listcomp>c                s4   h | ],}t |d r|jjr jjj|jjr|qS )rY   )rG   rY   r[   r!   featuresZ%allows_group_by_selected_pks_on_modelmodel)r-   rE   )r(   r)   r*   rF      s   
c             S   s   h | ]
}|j qS r)   )rZ   )r-   rE   r)   r)   r*   rF      s    c                s(   g | ] }|ks t |d d kr|qS )rZ   N)r\   )r-   rE   )aliasespksr)   r*   r^      s    )
r!   r_   Zallows_group_by_pkr\   r    r`   _metapk
base_tableZallows_group_by_selected_pks)r(   rO   r9   rd   rE   r)   )ra   r9   r]   rb   r(   r*   rK      s$    



zSQLCompiler.collapse_group_byc                s  g }d}i }d}x@| j jj D ]0\}\}}|||< |jt|||f |d7 }qW | j jo`| j j sht| j jrz| j }n| j j}|rg }	x,|D ]$}
|	j| |j|
df |d7 }qW | j j	|	d}x6| j j
j D ]&\}}|||< |j||f |d7 }qW | j jr.| j|}||d<  fdd  | g }xl|D ]d\}
}y| j|
\}}W n  tk
rr   df  }}Y nX |
j| ||\}}|j|
||f|f q8W |||fS )	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      )r`   select_fieldsrelated_klass_infosc                s:   x4| d D ](}|d r*| d |d  |d<  | q
W d S )Nrh   from_parentrg   r)   )r&   Zki)get_select_from_parentr)   r*   rj      s
    z6SQLCompiler.get_select.<locals>.get_select_from_parent0)r    r?   itemsrH   r   r$   Zdefault_colsAssertionErrorget_default_columnsr`   annotation_selectselect_relatedget_related_selectionsrL   r   rM   )r(   r$   r&   annotationsZ
select_idxrZ   rS   rT   rQ   Zselect_listrR   
annotationrh   retr)   )rj   r*   r3      sL    




zSQLCompiler.get_selectc             C   sl  | j jr| j j}nH| j js$| j j}n6| j jr6| j j}n$| j j jrV| j j j}|| _ng }| j jrptd \}}ntd \}}g }x>|D ]4}t	|drt
|trt||j}t
|ts|j }| j js|j }|j  |j|df q|dkr|jtt df qt||\}}|dk}|| j jkrR|jtt|| j j| |ddf q|| j jkr| j jr|| jr|t|}	n$| j j| }	t
|	trt|	|	j}	|jt|	|ddf qd|kr|jdd	\}
}|jttd
| j|
|f g |ddf q| j j s|| j jkrd| j jrF| jrF|jtt||ddf n|j| j || j j |d q|| j j!kr|jtt| j j|  |ddf q|jtt|t| j j|  |ddf qW g }t" }x|D ]\}	}|	j#| j ddd}| j jr| jr|j$ d }|	j$ d }xt%| jD ]t\}\}}}|rN||j&krN|j'}n$|rrt
|toh||j(k rrq&||kr&|j)td|d	  f g P q&W |rt*dt+| j jd	 }d| }x| j j,D ]}|j-|| qW | j j.|| |j)t| f g | j/|\}}| j0j1|d	 }t2|}||f|kr@q|j3||f |j||||ff qW |S )a+  
        Return a list of 2-tuples of 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).
        ASCDESCresolve_expressionF?)
descendingT.rf   z%s.%s)default_orderN)allow_joinsZreuser   z%dz:ORDER BY term does not match any column in the result set.Z__orderbycol)4r    Zextra_order_byZdefault_orderingr>   get_metaorderingr'   Zstandard_orderingr   rG   rC   r   r   Zoutput_fieldr
   asccopyZreverse_orderingrH   r   r   ro   r   rr   
combinatorr$   r	   splitr   quote_name_unless_aliasextrarI   find_ordering_namer?   rJ   rw   get_source_expressions	enumeraterefsrD   nameZset_source_expressionsr   r4   combined_queriesZadd_annotationZadd_select_colrL   ordering_partssearchr   rN   )r(   r~   r   descr>   fieldrR   orderry   rE   tablerV   rW   rU   resolvedsrcZexpr_srcidxZsel_exprrP   Z	col_aliasZorder_by_idxZcol_nameqrS   rT   without_orderingrX   r)   r)   r*   r7     s    	











zSQLCompiler.get_order_byc       
      C   sv   g }| j jrr| j j rrdd |D }xL|D ]D\}\}}}| jj|d }	| r*|	|f|kr*|j||	|fd f q*W |S )Nc             S   s   g | ]}|d  qS )rf   r)   )r-   tr)   r)   r*   r^     s    z0SQLCompiler.get_extra_select.<locals>.<listcomp>rf   )r    distinctdistinct_fieldsr   r   rH   )
r(   r>   r$   r?   Z
select_sqlrE   rS   rT   rU   r   r)   r)   r*   r:     s    zSQLCompiler.get_extra_selectc             C   s|   || j kr| j | S || jjkr,|| jjksR|| jjksR| jjj|r`|| jjk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    r1   Z	table_mapr?   Zexternal_aliasesgetr!   ops
quote_name)r(   r   rr)   r)   r*   r     s    



z#SQLCompiler.quote_name_unless_aliasc             C   sD   t |d| jj d }|r*|| | j\}}n|j| | j\}}||fS )NZas_)r\   r!   vendorrB   )r(   nodeZvendor_implrS   rT   r)   r)   r*   rL     s
    zSQLCompiler.compilec                s  j j}fddjjD }|jsdx>tjj|D ],\}}|jsH|jrPtd|j	 r4tdq4W f }x|D ]}y|jj
 rjj
r|jj |_|jjjjjj
jj |j \}}	|jjr|jsdj|}n|jsdj|}|||	ff7 }W qn tk
r*   |dks"|dkr$|r$wn Y qnX qnW |s:tj jj| }
|r`|dkr`|
d	7 }
|jrldnd
 t fdd|D  \}}dj|
j|g}g }x|D ]}|j| qW ||fS )Nc                s$   g | ]}|j  s|j j jqS r)   )is_emptyget_compilerr"   r!   )r-   r    )r(   r)   r*   r^     s   z2SQLCompiler.get_combinator_sql.<locals>.<listcomp>z>LIMIT/OFFSET not allowed in subqueries of compound statements.z:ORDER BY not allowed in subqueries of compound statements.zSELECT * FROM ({})z({})union
differencez ALLz{}c             3   s    | ]\}} j ||fV  qd S )N)format)r-   rS   args)bracesr)   r*   r/     s    z1SQLCompiler.get_combinator_sql.<locals>.<genexpr>z {} )r!   r_   r    r   Z%supports_slicing_ordering_in_compoundziplow_mark	high_markr   r7   Zvalues_selectcloneZ
set_valuesr?   ro   rB   r   Z supports_parentheses_in_compoundr   r   r   Zset_operatorsjoinrI   )r(   r   r0   r_   Z	compilersr    compilerpartsZpart_sqlZ	part_argsZcombinator_sqlZ	sql_partsZ
args_partsrV   rT   partr)   )r   r(   r*   get_combinator_sql  sR    



zSQLCompiler.get_combinator_sqlTFc       -      C   s(  | j jj }z| j \}}}d}|o8| j jdk	p8| j j}| j j}	| jj}
|	rt	|
dj
|	sltdj
|	| j|	| j j\}}n| j \}}| j \}}| jdk	r| j| jndg f\}}| jdk	r| j| jndg f\}}dg}g }| j jr| jjj||\}}||7 }||7 }g }d}xn| j| D ]`\}\}}}|rXd|| jjj|f }n|rvd|d| f }|d7 }|j| |j| q,W |d	j|d
f|7 }|j| | j jr| jjjr| jj rtd|r| jjj rtd| j j }| j j!}| j j"}| j j#}|r4| jjj$ r4tdnX|rR| jjj% rRtdn:|rp| jjj& rptdn|r| jjj' rtd| jjj(||| j) |d}|r| jjj*r|j| |r|jd|  |j| g } x&|D ]\}!}"| j|! |j|" qW | rR|r t+d|p0| jjj, }|jdd	j|   | j-rRd}|rp|jd|  |j| | j j.r|j/d| jjj0| j j1f| j j2 |rg }#x,|D ]$\}\}$}%}|#j|$ |j|% qW |jdd	j|#  |r|j| jjj3| j j| j j |r*| jjj* r*|j| | j j4r|rg }&g }'xt5| jddD ]\}(\})}}| rv|rvd|( }|r|&jd| jjjd| jjj|f  n6|)j6|)j7di}*|*j8| | j\}+},|&j|+ |'j|, qRW dd	j|&dj|f t9|'| fS dj|t9|fS | j j:| X dS )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.
        Nzsupports_select_{}z-{} is not supported on this database backend. ZSELECTrf   z%s AS %szCol%dz, Z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_keyzWHERE %sz1annotate() + distinct(fields) is not implemented.zGROUP BY %sz	HAVING %sr   zORDER BY %s)startzcol%dz%s.%ssubqueryzSELECT %s FROM (%s) subquery );r    r,   r   rA   r   r   r   r!   r_   r\   r   r   r   Zcombinator_allget_distinctget_from_clauser8   rL   r9   r   r   Zdistinct_sqlr$   r   rI   rH   r   Zselect_for_updateZhas_select_for_updateZget_autocommitr   Z%supports_select_for_update_with_limitZselect_for_update_nowaitZselect_for_update_skip_lockedselect_for_update_ofZselect_for_no_key_updateZhas_select_for_update_nowaitZ!has_select_for_update_skip_lockedZhas_select_for_update_ofZhas_select_for_no_key_updateZfor_update_sql"get_select_for_update_of_argumentsZfor_update_after_fromNotImplementedErrorZforce_no_orderingr'   explain_queryinsertZexplain_query_prefixZexplain_formatZexplain_optionsZlimit_offset_sqlr   r   Zrelabeled_clonerZ   rB   tuplereset_refcounts)-r(   Zwith_limitswith_col_aliasesrefcounts_beforer?   r>   r@   Zfor_update_partZwith_limit_offsetr   r_   rV   rT   r   Zdistinct_paramsfrom_Zf_paramsr8   Zw_paramsr9   Zh_paramsZdistinct_resultZout_colsZcol_idxrP   Zs_sqlZs_paramsrZ   r   r   r   r   groupingZg_sqlZg_paramsr~   Zo_sqlZo_paramsZsub_selectsZ
sub_paramsindexr$   Zselect_cloneZ	subselectZ	subparamsr)   r)   r*   rB     s    ""














zSQLCompiler.as_sqlNc             C   s   g }|dkr| j j }| j }|p*| j j }d|i}x|jD ]~}|jjj}||jkrXd}|rx|dk	rxt|jj|jjrxq<|j|kr|j	||j krq<| j j
||||}	|j|	}
|j|
 q<W |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}   deferred_to_columnsr2   Zconcrete_fieldsr`   rc   concrete_model
issubclassattnameZjoin_parent_modelget_colrH   )r(   start_aliasoptsri   rV   	only_loadZseen_modelsr   r`   rZ   columnr)   r)   r*   rn     s(    



zSQLCompiler.get_default_columnsc             C   s   g }g }| j j }x| j jD ]}|jt}| j||d\}}}}	}
}}| j j||	|
\}}}xL|D ]D}|| j jkr~|j| qb| j	|||\}}|j| |j| qbW qW ||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_joinsro   rH   rL   )r(   rV   rT   r   r   r   rP   targetsrZ   joinspathtransform_functionrY   r   pr)   r)   r*   r     s    



zSQLCompiler.get_distinctru   c                s@  t ||\}}|dk|jt}j|| \}}	 }
}}|job|jobt|dd|d kob|dkr|pnt }tfdd|
D }||krt	d|j
| g }xj|jD ]`}t|d	rt|t rڈr|j n|j }t|tr|j|d
f q|jj|| || qW |S jj|	|
|\}	 } fdd|	D S )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'.
        rv   r   Nrf   rd   c             3   s"   | ]}t  jj| d dV  qdS )Z	join_colsN)r\   r    r1   )r-   j)r(   r)   r*   r/     s    z1SQLCompiler.find_ordering_name.<locals>.<genexpr>z!Infinite loop caused by ordering.rw   Fc                s"   g | ]}t | d dfqS ))ry   F)r
   )r-   r   )rZ   ry   r   r)   r*   r^     s    z2SQLCompiler.find_ordering_name.<locals>.<listcomp>)r   r   r   r   is_relationr~   r\   rJ   r   r   rN   rG   rC   r
   r   r   rH   rI   r   r    r   )r(   r   r   rZ   r{   Zalready_seenr   piecesr   r   r   r   Z
join_tupleresultsitemrP   r)   )rZ   ry   r(   r   r*   r     s2    




zSQLCompiler.find_ordering_namec       	      C   sD   |p| 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.
        rf   r   )r    r2   setup_joins)	r(   r   r   rZ   r   r   r   r   r   r)   r)   r*   r     s    zSQLCompiler._setup_joinsc       	      C   s   g }g }xlt | jjD ]\}| jj| s(qy| jj| }W n tk
rN   wY nX | j|\}}|j| |j| qW xP| jjD ]D}| jj	|\}}|| jjks| jj| dkr|jd| j
|  qW ||fS )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.
        rf   z, %s)r   r    r1   r,   KeyErrorrL   rH   rI   Zextra_tablesZtable_aliasr   )	r(   rV   rT   rZ   Zfrom_clauseZ
clause_sqlZclause_paramsr   rP   r)   r)   r*   r     s"    
zSQLCompiler.get_from_clauserf   c       "   	      s  fdd}g }| r(|j jkr(|S s@j j j j }j j }	t }
|dkrrtj jt}|rrj j}dd }xZj	D ]N  j
jj}|
j j |r|j ji } js|sƈ j|krtd jdj| pdf nd	}t |||	j|sq jj
 d	 j jr  jjnd
d d	d}|j| g }j j jg|\}}}}}}|d }j| jj
jd}x*|D ]"}|jt| |j|df q~W ||d< j| jj
j||d ||}||| qW |rdd jD }x|D ]\ }t |||	j|ddsq j }|
j| j j|g|}|jd }t|j
ob|j
k	}| d jj j|d}|j| g }j||jj
d}x*|D ]"}|jt| |j|df qW ||d< |j j i }j||j||d ||}||| qW  fdd}dd }xt |D ]}|dkr>P |j j!kr,|
j| j j|g|\ }}}}}|j
}|d }t|j
o|j
k	}| d|t"|||d}|j| g }j||jj
d}x*|D ]"}|jt| |j|df qW ||d< |j|i }j||j||d ||d}||| q,W t|j#|
} | rdd | D }!tddj|!dj| p~df |S ) 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                 s0   dd  j D } dd  jD }t| |jjS )Nc             s   s   | ]}|j r|jV  qd S )N)r   r   )r-   fr)   r)   r*   r/   ;  s    zQSQLCompiler.get_related_selections.<locals>._get_field_choices.<locals>.<genexpr>c             s   s    | ]}|j jr|j j V  qd S )N)r   uniquerelated_query_name)r-   r   r)   r)   r*   r/   =  s   )fieldsrelated_objectsr   r    _filtered_relations)Zdirect_choicesZreverse_choices)r   r(   r)   r*   _get_field_choices:  s    
z>SQLCompiler.get_related_selections.<locals>._get_field_choicesNc             S   s   || d< d S )Nrh   r)   )r&   rh   r)   r)   r*   get_related_klass_infosT  s    zCSQLCompiler.get_related_selections.<locals>.get_related_klass_infoszCNon-relational field given in select_related: '%s'. Choices are: %sz, z(none)Fc             S   s   d S )Nr)   )xyr)   r)   r*   <lambda>s  s    z4SQLCompiler.get_related_selections.<locals>.<lambda>)r`   r   reverselocal_setterremote_setterri   rf   )r   r   rg   c             S   s(   g | ] }|j jr|j r|j |jfqS r)   )r   r   Zmany_to_manyZrelated_model)r-   or)   r)   r*   r^     s   z6SQLCompiler.get_related_selections.<locals>.<listcomp>T)r   )r   r   ri   c                s   |r j j||  d S )N)remote_fieldset_cached_value)objfrom_obj)r   r)   r*   r     s    z8SQLCompiler.get_related_selections.<locals>.local_setterc             S   s   t || | d S )N)setattr)r   r   r   r)   r)   r*   r     s    z9SQLCompiler.get_related_selections.<locals>.remote_setter)r   
root_alias	cur_depth	requested
restrictedc             s   s   | ]}d | V  qdS )z'%s'Nr)   )r-   sr)   r)   r*   r/     s    z5SQLCompiler.get_related_selections.<locals>.<genexpr>zBInvalid field name(s) given in select_related: %s. Choices are: %sr   r   r   )$r    Z	max_depthr}   r2   Zget_loaded_field_namesrJ   rC   rp   dictr   r`   rc   r   rN   r   r   r   r   r   r   r   r   r   rH   r   rn   r4   rq   r   r   r   r   listr   r   r   )"r(   r$   r   r   r   r   r   r   rh   r   Zfields_foundr   Zfield_modelnextr&   rg   rP   r   rZ   columnsrR   Znext_klass_infosZrelated_fieldsr`   Zrelated_field_nameZ	join_infori   r   r   r   Z	join_optsZnext_requestedZfields_not_foundZinvalid_fieldsr)   )r   r   r(   r*   rq   2  s    















z"SQLCompiler.get_related_selectionsc                s8  fdd fdd} fdd}g }g }xj jD ]}j}|dkrT||}n~x`|jtD ]R}|jdg  |}	x8|	D ]*}
|
d	 }|
d
 r|j}|j|kr~|
}P q~W d}P q`W |dkr|j| q8||}|dk	r8j	j
jr|jj|d  q8|jj|j q8W |r4tddj|dj| f |S )zk
        Return a quoted list of arguments for the SELECT FOR UPDATE OF part of
        the query.
        c             3   sZ   | d j j}xH|j jj D ]8\}j j  |d fdd| d D dV  qW d S )Nr`   Fc                s<   g | ]4}j | d  jjks4j | d  jj kr|qS )r   )r$   rY   r`   )r-   select_index)parent_listparent_modelr(   r)   r*   r^     s   zbSQLCompiler.get_select_for_update_of_arguments.<locals>._get_parent_klass_info.<locals>.<listcomp>rg   )r`   r   r   rg   )rc   r   parentsrl   Zget_parent_list)r&   r   Zparent_link)r(   )r   r   r*   _get_parent_klass_info  s    
zNSQLCompiler.get_select_for_update_of_arguments.<locals>._get_parent_klass_infoc                sF   | d j j}x4| d D ](} j| d jj|kr j| d S qW dS )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.
            r`   rg   r   N)rc   r   r$   rY   r`   )r&   r   r   )r(   r)   r*   "_get_first_selected_col_from_model  s    zZSQLCompiler.get_select_for_update_of_arguments.<locals>._get_first_selected_col_from_modelc              3   s   t jdjfg} x| r| j \}}|dkr8g  dV  n.|d }|d rN|j}||jg  tj V  | j fdd|D  | j fdd|j	dg D  qW dS )	z<Yield all allowed field paths in breadth-first search order.Nr(   r   r   c             3   s   | ]} |fV  qd S )Nr)   )r-   r&   )r   r)   r*   r/     s   z]SQLCompiler.get_select_for_update_of_arguments.<locals>._get_field_choices.<locals>.<genexpr>c             3   s   | ]} |fV  qd S )Nr)   )r-   r&   )r   r)   r*   r/     s   rh   )
collectionsdequer&   popleftr   r   r   r   rI   r   )queueparent_pathr&   r   )r   r(   )r   r*   r     s"    

zJSQLCompiler.get_select_for_update_of_arguments.<locals>._get_field_choicesr(   rh   r   r   Nr   zInvalid field name(s) given in select_for_update(of=(...)): %s. Only relational fields followed in the query are allowed. Choices are: %s.z, )r    r   r&   r   r   r   r   r   rH   r!   r_   Zselect_for_update_of_columnrL   r   rZ   r   r   )r(   r   r   rV   invalid_namesr   r&   rR   r   Zklass_infosZrelated_klass_infor   r)   )r   r(   r*   r     sF    






z.SQLCompiler.get_select_for_update_of_argumentsc             C   s   i }| j j|| j j |S )z
        Convert the self.deferred_loading data structure to mapping of table
        names to sets of column names which are to be loaded. Return the
        dictionary.
        )r    Zdeferred_to_dataZget_loaded_field_names_cb)r(   r   r)   r)   r*   r   G  s    zSQLCompiler.deferred_to_columnsc             C   sT   i }xJt |D ]>\}}|r| jjj|}|j| j}|s<|r|| |f||< qW |S )N)r   r!   r   Zget_db_converters)r(   rO   
convertersi
expressionZbackend_convertersZfield_convertersr)   r)   r*   get_convertersQ  s    zSQLCompiler.get_convertersc       
      c   sp   | j }t|j }xXtt|D ]J}x>|D ]6\}\}}|| }x|D ]}	|	|||}qBW |||< q(W |V  qW d S )N)r!   r   rl   map)
r(   rowsr  r!   rowposZconvsr  value	converterr)   r)   r*   apply_converters[  s    
zSQLCompiler.apply_convertersc             C   sh   |dkr| j t||d}dd | jd| j D }| j|}tj|}|rd| j||}|rdtt	|}|S )z>Return an iterator over the results from executing this query.N)chunked_fetch
chunk_sizec             S   s   g | ]}|d  qS )r   r)   )r-   r   r)   r)   r*   r^   k  s    z,SQLCompiler.results_iter.<locals>.<listcomp>r   )
execute_sqlr   r$   r5   r	  r   from_iterabler  r
  r   )r(   r   Ztuple_expectedr  r  r   r  r  r)   r)   r*   results_iterf  s    


zSQLCompiler.results_iterc             C   s   t | jtS )z
        Backends (e.g. NoSQL) can override this in order to use optimized
        versions of "query has any results."
        )r;   r  r   )r(   r)   r)   r*   has_resultst  s    zSQLCompiler.has_resultsc       	   "   C   s6  |pt }y| j \}}|stW n( tk
rH   |tkr@tg S dS Y nX |rZ| jj }n
| jj }y|j|| W n t	k
r   |j
   Y nX |tkr|S |tkrz|j }|r|d| j S |S |j
  X |t kr|j
  dS t|| jjj| jr | jnd|}| s| jjj r2zt|S |j
  X |S )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   rB   r   r   iterr!   Zchunked_cursorcursorexecute	Exceptioncloser   r   Zfetchoner5   cursor_iterr_   Zempty_fetchmany_valuer<   Zcan_use_chunked_readsr   )	r(   result_typer  r  rS   rT   r  valrV   r)   r)   r*   r  {  sL    




zSQLCompiler.execute_sqlc             C   s   |j }| jjj}x\t| jjD ]L\}}| j|\}}	d||||| f }
| jjj	t
d||
f |	d qW | j \}}d| |fS )Nz%s.%sz%s = %sANDzEXISTS (%s))r   r!   r   r   r   r    r$   rL   r8   rN   r   rB   )r(   rZ   r   r   qnZqn2r   Z
select_colZlhs_sqlZ
lhs_paramsrhsrS   rT   r)   r)   r*   as_subquery_condition  s    
z!SQLCompiler.as_subquery_conditionc             c   sJ   t | j }x8|d D ],}t|ts<djdd |D V  q|V  qW d S )Nr   r   c             s   s   | ]}t |V  qd S )N)str)r-   cr)   r)   r*   r/     s    z,SQLCompiler.explain_query.<locals>.<genexpr>)r   r  rC   r#  r   )r(   rV   r  r)   r)   r*   r     s
    
zSQLCompiler.explain_query)TF)NNN)Nru   N)NNrf   NN)%__name__
__module____qualname__r   re	MULTILINEDOTALLr   r+   r6   rA   r=   rK   r3   r7   r:   r   rL   r   rB   rn   r   r   r   r   rq   r   r   r	  r  r   r  r  r   r  r"  r   r)   r)   r)   r*   r      sH   V2H 
7
  
, 
(" 
 0e

Cr   c               @   sH   e Zd ZdZe Zdd Zdd Zdd Zdd	 Z	d
d Z
dddZdS )SQLInsertCompilerNc             C   sv   |dkr|g  }}nJt |dr.| j|\}}n0t |drR|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.
        NrB   get_placeholderz%s)rG   rL   r,  r!   r   Zmodify_insert_params)r(   r   r  rS   rT   r)   r)   r*   field_as_sql  s    	

zSQLInsertCompiler.field_as_sqlc             C   sx   t |drd|j| jddd}|jr2td||f |jrJtd|j|f |jrttd|j|f n|j	|| j
d}|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().
        rw   FT)r|   for_savezbFailed to insert expression "%s" on %s. F() expressions can only be used to update, not to insert.z:Aggregate functions are not allowed in this query (%s=%r).z9Window expressions are not allowed in this query (%s=%r).)r!   )rG   rw   r    Zcontains_column_references
ValueErrorcontains_aggregater   r   contains_over_clauseget_db_prep_saver!   )r(   r   r  r)   r)   r*   prepare_value  s     
zSQLInsertCompiler.prepare_valuec             C   s"   | j jrt||jS |j|d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)rN   )r    rawr\   r   Zpre_save)r(   r   r   r)   r)   r*   pre_save_val  s    zSQLInsertCompiler.pre_save_valc                sP   |sg g fS  fdd|D }dd |D }t | \}}dd |D }||fS )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   s&   | ]}fd dt  |D V  qdS )c             3   s   | ]\}} j ||V  qd S )N)r-  )r-   r   v)r(   r)   r*   r/   2  s    z>SQLInsertCompiler.assemble_as_sql.<locals>.<genexpr>.<genexpr>N)r   )r-   r  )r   r(   r)   r*   r/   2  s   z4SQLInsertCompiler.assemble_as_sql.<locals>.<genexpr>c             s   s   | ]}t | V  qd S )N)r   )r-   r  r)   r)   r*   r/   8  s    c             S   s   g | ]}d d |D qS )c             S   s   g | ]}|D ]}|qqS r)   r)   )r-   psr   r)   r)   r*   r^   ?  s    z@SQLInsertCompiler.assemble_as_sql.<locals>.<listcomp>.<listcomp>r)   )r-   r  r)   r)   r*   r^   ?  s    z5SQLInsertCompiler.assemble_as_sql.<locals>.<listcomp>)r   )r(   r   
value_rowsZrows_of_fields_as_sqlZsql_and_param_pair_rowsplaceholder_rows
param_rowsr)   )r   r(   r*   assemble_as_sql   s    z!SQLInsertCompiler.assemble_as_sqlc       
         s  j jjjj }j jjjjd}d||jf gjjpJ|j	g j
ddjfdd D   jjr fddjjD }nfd	djjD }d g j oj jj}j |\}}j jjjjd}joj jjrj jjrj
j jj | |}n"j
d
dj|d   |d g}|rNj
| j jjj\}	_|	rj
|	 |jg7 }djttj|fgS |rj
j jj | |rƈj
| djtdd |D fgS |rj
| fddt||D S d S )N)ignore_conflictsz%s %sz(%s)z, c             3   s   | ]} |j V  qd S )N)r   )r-   r   )r   r)   r*   r/   K  s    z+SQLInsertCompiler.as_sql.<locals>.<genexpr>c                s    g | ]  fd dD qS )c                s    g | ]}j |j| qS r)   )r3  r5  )r-   r   )r   r(   r)   r*   r^   O  s    z7SQLInsertCompiler.as_sql.<locals>.<listcomp>.<listcomp>r)   )r-   )r   r(   )r   r*   r^   O  s   z,SQLInsertCompiler.as_sql.<locals>.<listcomp>c                s   g | ]} j jj gqS r)   )r!   r   Zpk_default_value)r-   rP   )r(   r)   r*   r^   T  s    zVALUES (%s)r   r   c             s   s   | ]}|D ]
}|V  q
qd S )Nr)   )r-   r7  r   r)   r)   r*   r/   w  s    c                s.   g | ]&\}}d j  ddj | g |fqS )r   zVALUES (%s)z, )r   )r-   r   vals)rV   r)   r*   r^   |  s   )r!   r   r   r    r}   insert_statementr<  db_tabler   rd   rH   r   objsreturning_fieldsr_   Zhas_bulk_insertr;  ignore_conflicts_suffix_sqlcan_return_columns_from_insert can_return_rows_from_bulk_insertZbulk_insert_sqlZreturn_insert_columnsreturning_paramsr   r   r  r   )
r(   r   r>  r8  Zcan_bulkr9  r:  rB  rT   Zr_sqlr)   )r   r   rV   r(   r*   rB   C  sJ    

"





zSQLInsertCompiler.as_sqlc             C   s   |ot | jjdko| jjj  s&t|| _| jj }x | j	 D ]\}}|j
|| qBW | jsdg S | jjjrt | jjdkr| jjj|S | jjjrt | jjdkst| jjj|| jgS | jjj|| jj j| jj jjfgS Q R X d S )Nrf   )r4   r    r@  r!   r_   rD  rm   rA  r  rB   r  r   Zfetch_returned_insert_rowsrC  Zfetch_returned_insert_columnsrE  Zlast_insert_idr}   r?  rd   r   )r(   rA  r  rS   rT   r)   r)   r*   r    s    
zSQLInsertCompiler.execute_sql)N)r%  r&  r'  rA  r   rE  r-  r3  r5  r;  rB   r  r)   r)   r)   r*   r+    s    	#=r+  c               @   s@   e Zd Zedd Zedd Zedd Zdd Zd	d
 Z	dS )SQLDeleteCompilerc                s(    j j  t fdd j jD dkS )Nc             3   s   | ]} j j| d kV  qdS )r   N)r    r,   )r-   r   )r(   r)   r*   r/     s    z1SQLDeleteCompiler.single_alias.<locals>.<genexpr>rf   )r    r2   sumr1   )r(   r)   )r(   r*   single_alias  s    
zSQLDeleteCompiler.single_aliasc                s>   t |tr|j kS t|ds"dS t fdd|j D S )Nr   Fc             3   s   | ]}j | V  qd S )N)_expr_refs_base_model)r-   Zsource_expr)
base_modelclsr)   r*   r/     s   z:SQLDeleteCompiler._expr_refs_base_model.<locals>.<genexpr>)rC   r   r`   rG   anyr   )rK  rE   rJ  r)   )rJ  rK  r*   rI    s    


z'SQLDeleteCompiler._expr_refs_base_modelc                s*   t  fddt jjj  jjjD S )Nc             3   s   | ]} j | jjV  qd S )N)rI  r    r`   )r-   rE   )r(   r)   r*   r/     s   zESQLDeleteCompiler.contains_self_reference_subquery.<locals>.<genexpr>)rL  r   r    rr   valuesr8   children)r(   r)   )r(   r*    contains_self_reference_subquery  s    
z2SQLDeleteCompiler.contains_self_reference_subqueryc             C   sF   d| j |j g}| j|j\}}|r4|jd|  dj|t|fS )NzDELETE FROM %szWHERE %sr   )r   re   rL   r8   rH   r   r   )r(   r    rV   r8   rT   r)   r)   r*   _as_sql  s
    zSQLDeleteCompiler._as_sqlc             C   s   | j r| j r| j| jS | jj }t|_|j  | jjj	j
}|j| jj g|_t| jj}| jj |_| jjjs|j| jdj \}}td| |}|jt|d | j|S )zf
        Create the SQL for this query. Return the SQL string and list of
        parameters.
        )r!   zSELECT * FROM (%s) subquery)pk__in)rH  rO  rP  r    r   r   	__class__Zclear_select_clauser`   rc   rd   r   r2   r$   where_classr8   r!   r_   update_can_self_selectr   rB   r   Zadd_qr   )r(   Zinnerqrd   ZouterqrS   rT   r)   r)   r*   rB     s    

zSQLDeleteCompiler.as_sqlN)
r%  r&  r'  r   rH  classmethodrI  rO  rP  rB   r)   r)   r)   r*   rF    s
   	rF  c                   s0   e Zd Zdd Z fddZ fddZ  ZS )SQLUpdateCompilerc             C   s  | j   | jjsdf fS | j}g g  }}xZ| jjD ]L\}}}t|dr|j| jddd}|jrttd|j|f |j	rtd|j|f nPt|dr|j
r|j|j|| jd	}qtd
|||jjf n|j|| jd	}t|dr|j|| | j}nd}|j}t|drD| j|\}	}
|jd||||	 f  |j|
 q4|dk	rp|jd|||f  |j| q4|jd||  q4W | jj}d|| dj|g}| j| jj\}}
|r|jd|  dj|t||
 fS )zf
        Create the SQL for this query. Return the SQL string and list of
        parameters.
        r   rw   FT)r|   r.  z:Aggregate functions are not allowed in this query (%s=%r).z9Window expressions are not allowed in this query (%s=%r).prepare_database_save)r!   zSTried to update field %s with a model instance, %r. Use a value compatible with %s.r,  z%srB   z%s = %sNz	%s = NULLzUPDATE %s SETz, zWHERE %sr   )rA   r    rM  r   rG   rw   r0  r   r   r1  r   r2  rW  r!   	TypeErrorrR  r%  r,  r   rL   rH   rI   re   r   r8   r   )r(   r   rM  Zupdate_paramsr   r`   r  placeholderr   rS   rT   r   rV   r8   r)   r)   r*   rB     sX    





zSQLUpdateCompiler.as_sqlc                sp   t  j|}z|r|jnd}|dk}W d|r4|j  X x4| jj D ]&}|j| jj|}|rB|rB|}d}qBW |S )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)superr  Zrowcountr  r    Zget_related_updatesr   r"   )r(   r  r  r  r   r    Zaux_rows)rR  r)   r*   r    s    
zSQLUpdateCompiler.execute_sqlc                s  | j jj }| j j  | j j }| j j r6|dkr6dS | j jtd}d|_|j	d i |_
g |_|j|j jjg t j  |dko| jjj }| j j | j _| j js|rg }x.|j| jjtD ]}|jdd |D  qW | j jd|f || j _n| j jd|f | j j| dS )	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.
        rf   N)klassFTc             s   s   | ]}|d  V  qdS )r   Nr)   )r-   r   r)   r)   r*   r/   G  s    z2SQLUpdateCompiler.pre_sql_setup.<locals>.<genexpr>rQ  )r    r,   r   r2   Zcount_active_tablesZrelated_updatesr   r   rp   Zclear_orderingr   r$   Z
add_fieldsr}   rd   r   rZ  rA   r!   r_   rT  rS  r8   r   r"   r  r   rI   Z
add_filterZrelated_idsr   )r(   r   countr    Zmust_pre_selectZidentsr  )rR  r)   r*   rA   %  s,    	




zSQLUpdateCompiler.pre_sql_setup)r%  r&  r'  rB   r  rA   __classcell__r)   r)   )rR  r*   rV    s   ?rV  c               @   s   e Zd Zdd ZdS )SQLAggregateCompilerc             C   s   g g  }}xH| j jj D ]8}| j|\}}|j| ||\}}|j| |j| qW t| j j| _dj	|}t
|}| j jj| jjdd\}}d||f }|| }||fS )zf
        Create the SQL for this query. Return the SQL string and list of
        parameters.
        z, T)r   zSELECT %s FROM (%s) subquery)r    ro   rM  rL   rM   rH   rI   r4   r5   r   r   Zinner_queryr   r"   rB   )r(   rS   rT   rs   Zann_sqlZ
ann_paramsZinner_query_sqlZinner_query_paramsr)   r)   r*   rB   Q  s    


zSQLAggregateCompiler.as_sqlN)r%  r&  r'  rB   r)   r)   r)   r*   r^  P  s   r^  c          
   #   sR   zBx<t fdd|D ]$} dkr(|n fdd|D V  qW W dj  X dS )z[
    Yield blocks of rows from a cursor and ensure the cursor is closed when
    done.
    c                  s
    j S )N)Z	fetchmanyr)   )r  itersizer)   r*   r   n  s    zcursor_iter.<locals>.<lambda>Nc                s   g | ]}|d   qS )Nr)   )r-   r   )r5   r)   r*   r^   o  s    zcursor_iter.<locals>.<listcomp>)r  r  )r  sentinelr5   r_  r  r)   )r5   r  r_  r*   r  h  s    (r  )2r   r(  	functoolsr   	itertoolsr   Zdjango.core.exceptionsr   r   Z	django.dbr   r   Zdjango.db.models.constantsr   Zdjango.db.models.expressionsr	   r
   r   r   r   Zdjango.db.models.functionsr   r   Zdjango.db.models.query_utilsr   r   Zdjango.db.models.sql.constantsr   r   r   r   r   r   Zdjango.db.models.sql.queryr   r   Zdjango.db.transactionr   Zdjango.utils.functionalr   Zdjango.utils.hashabler   Zdjango.utils.regex_helperr   r   r+  rF  rV  r^  r  r)   r)   r)   r*   <module>   s@             I @; 