
 X                 @   sv  d  d l  Z  d  d l m Z d  d l m Z d  d l m Z d  d l m Z m	 Z	 m
 Z
 m Z 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 d  d	 l m Z m Z d  d
 l m Z d  d l m Z d  d l m  Z  Gd d   d e!  Z" Gd d   d e"  Z# Gd d   d e"  Z$ Gd d   d e"  Z% Gd d   d e"  Z& d d   Z' d S)    N)chain)
FieldError)
LOOKUP_SEP)OrderByRandomRawSQLRef)QueryWrapperselect_related_descend)CURSORGET_ITERATOR_CHUNK_SIZEMULTI
NO_RESULTS	ORDER_DIRSINGLE)EmptyResultSet)Queryget_order_dir)TransactionManagementError)DatabaseError)zipc               @   so  e  Z 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 d d  Z d d   Z d d d d d  Z d d   Z d d  d d! d"  Z d# d$   Z d% d&   Z d d d' d d d( d)  Z d* d+   Z d, d-   Z d. d/   Z d d0 d1  Z d2 d3   Z e d4 d5  Z d6 d7   Z d S)8SQLCompilerc             C   se   | |  _  | |  _ | |  _ i d d 6|  _ d  |  _ d  |  _ d  |  _ t j d  |  _	 d |  _
 d  S)N*z(.*)\s(ASC|DESC)(.*)F)query
connectionusingquote_cacheselectannotation_col_map
klass_inforecompileordering_partssubquery)selfr   r   r    r%   K/home/ubuntu/projects/ifolica/build/django/django/db/models/sql/compiler.py__init__   s    						zSQLCompiler.__init__c                si   t    f d d     j j D  r5   j j   n    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   tablesget_initial_alias
get_selectr   r   r   len	col_count)r$   r%   )r$   r&   setup_query"   s    %zSQLCompiler.setup_queryc             C   so   |  j    |  j   } |  j j j   \ |  _ |  _ |  j | |  j  } |  j |  j | |  } | | | f S)z
        Does 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.
        )	r2   get_order_byr   whereZsplit_havinghavingget_extra_selectr   get_group_by)r$   order_byextra_selectgroup_byr%   r%   r&   pre_sql_setup(   s    
zSQLCompiler.pre_sql_setupc             C   s  |  j  j d k r g  Sg  } |  j  j d k	 r xO |  j  j D]> } t | d  sl | j |  j  j |   q; | j |  q; Wn  xA | D]9 \ } } } | j   } x | D] } | j |  q Wq WxK | D]C \ } \ } }	 }
 | j r q n  |
 r q n  | j | j    q W|  j	 r*|  j	 j   n f  } x | D] } | j |  q7Wg  } t
   } |  j | |  } xj | D]b } |  j |  \ } }	 | t |	  f | k rv| j | |	 f  | j | t |	  f  qvqvW| S)z
        Returns 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_sql)r   r:   hasattrappendZresolve_refZget_group_by_colscontains_aggregateextendZget_source_expressionsr5   setcollapse_group_byr!   tupleadd)r$   r   r8   expressionsexpr_colscolsqlparamsis_refZhaving_group_byresultseenr%   r%   r&   r7   5   s<    %		 zSQLCompiler.get_group_byc                s   |  j  j j r d  } x^ | D]V } t | d d   |  j j j j k r t | d d   |  j j d k r | } Pq q W| r | g  f d d   | D } q nT |  j  j j	 r d d   | D  d d    D      f d	 d   | D } n  | S)
Ntargetaliasr   c                s"   g  |  ] } |   k r |  q Sr%   r%   )r)   rF   )r5   r%   r&   
<listcomp>   s   	 z1SQLCompiler.collapse_group_by.<locals>.<listcomp>c             S   s1   h  |  ]' } t  | d   r | j j r |  q S)rO   )r=   rO   Zprimary_key)r)   rF   r%   r%   r&   	<setcomp>   s   	 z0SQLCompiler.collapse_group_by.<locals>.<setcomp>c             S   s   h  |  ] } | j   q Sr%   )rP   )r)   rF   r%   r%   r&   rR      s   	 c                s:   g  |  ]0 } |  k s0 t  | d  d    k r |  q S)rP   N)getattr)r)   rF   )aliasespksr%   r&   rQ      s   	 )
r   featuresZallows_group_by_pkrS   r   model_metapkr-   Zallows_group_by_selected_pks)r$   rE   r5   rY   rF   r%   )rT   r5   rU   r&   rB      s    $"&zSQLCompiler.collapse_group_byc                s  g  } d } i  } d } xV |  j  j j   D]B \ } \ } } | | | <| j t | |  | f  | d 7} q+ W|  j  j o |  j  j s t  |  j  j r g  } x> |  j   D]0 }	 | j |  | j |	 d f  | d 7} q Wi |  j  j	 d 6| d 6} n  x1 |  j  j D]# }
 | j |
 d f  | d 7} qWxG |  j  j
 j   D]3 \ } } | | | <| j | | f  | d 7} qGW|  j  j r|  j |  } | | d <  f d d       |  n  g  } x9 | D]1 \ }
 } | j |
 |  j |
 d	 d
 | f  qW| | | f S)a  
        Returns 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:
        - Which model to instantiate
        - 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      rW   select_fieldsrelated_klass_infosc                sF   x? |  d D]3 } | d r4 |  d | d | d <n    |  q Wd  S)Nr\   from_parentr[   r%   )r   Zki)get_select_from_parentr%   r&   r^      s
    
z6SQLCompiler.get_select.<locals>.get_select_from_parentselect_formatT)r   r9   itemsr>   r   r   Zdefault_colsAssertionErrorget_default_columnsrW   annotation_selectselect_relatedget_related_selectionsr!   )r$   r   r   annotationsZ
select_idxrP   rJ   rK   Zselect_listcrI   
annotationr\   retr%   )r^   r&   r/      sD    %


)zSQLCompiler.get_selectc             C   s  |  j  j r |  j  j } n? |  j  j s6 |  j  j } n$ |  j  j pW |  j  j   j pW g  } |  j  j ry t d \ } } n t d \ } } g  } xt |  D]|\ } } t	 | d  rt
 | t  s | j   } n  |  j  j s | j   n  | j | d f  q n  | d k r5| j t t    d f  q n  t | |  \ } } | d k r\d n d }	 | |  j  j k r| j t t | |  j  j |  d |	 d f  q n  | |  j  j k r| j t |  j  j | d |	 d f  q n  d | k rR| j d d	  \ }
 } | j t t d
 |  j |
  | f g   d |	 d f  q n  |  j  j sq| |  j  j k r| 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  q Wg  } t   } x | D] \ } } | j |  j  d d d d } |  j |  \ } } |  j j  |  j! d	  } | t" |  f | k rq2n  | j# | t" |  f  | j | | | | f f  q2W| S)a,  
        Returns 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?T
descending.rZ   z%s.%sdefault_orderallow_joinsZreuseN)$r   Zextra_order_byZdefault_orderingr8   get_metaorderingZstandard_orderingr   	enumerater=   
isinstancer   ascZreverse_orderingr>   r   r   rc   r   rf   splitr   quote_name_unless_alias_extrar@   find_ordering_namer9   extrarA   rl   r!   r"   searchgrouprC   rD   )r$   rs   rv   descr8   posfieldrI   orderrn   tablerM   rN   rF   rL   ZresolvedrJ   rK   without_orderingr%   r%   r&   r3      s|    	$"

"
(	 zSQLCompiler.get_order_byc       
      C   s   g  } d d   | D } |  j  j r |  j  j r xs | D]h \ } \ } } } |  j j |  j d  }	 | r9 |	 | f | k r9 | j | |	 | f d  f  q9 q9 Wn  | S)Nc             S   s   g  |  ] } | d   q S)rZ   r%   )r)   tr%   r%   r&   rQ   C  s   	 z0SQLCompiler.get_extra_select.<locals>.<listcomp>rZ   )r   distinctdistinct_fieldsr"   r|   r}   r>   )
r$   r8   r   r9   Z
select_sqlrF   rJ   rK   rL   r   r%   r%   r&   r6   A  s    &zSQLCompiler.get_extra_selectc             C   s   | |  j  k r |  j  | S| |  j j k r> | |  j j k st | |  j j k st | |  j j k 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   	alias_mapZ	table_mapr9   Zexternal_aliasesr   ops
quote_name)r$   namerr%   r%   r&   rx   K  s    $$z#SQLCompiler.quote_name_unless_aliasFc             C   s   t  | d |  j j d   } | r= | |  |  j  \ } } n | j |  |  j  \ } } | r~ |  j r~ | j j |  | |  S| | f S)NZas_)rS   r   vendorr<   r#   Zoutput_fieldr_   )r$   noder_   Zvendor_implrJ   rK   r%   r%   r&   r!   \  s    zSQLCompiler.compileTc             C   si  | |  _  |  j j j   } z6|  j   \ } } } |  j   } |  j   \ }	 }
 |  j d k	 rr |  j |  j  n	 d g  f \ } } |  j	 d k	 r |  j |  j	  n	 d g  f \ } } g  } d g } |  j j
 r | j |  j j j |   n  g  } d } x |  j | D]~ \ } \ } } } | rHd | |  j j j |  f } n' | rod | d | f } | d 7} n  | j |  | j |  qW| j d j |   | j d  | j |	  | j |
  | r| j d	 |  | j |  n  g  } x. | D]& \ } } | j |  | j |  qW| r{| rCt d
   n  | s^|  j j j   } n  | j d d j |   n  | r| j d |  | j |  n  | rg  } x7 | D]/ \ } \ } } } | j |  | j |  qW| j d d j |   n  | r|  j j d k	 rA| j d |  j j |  j j  n  |  j j r|  j j d k r|  j j j   } | r| j d |  qn  | j d |  j j  qn  |  j j r7|  j j j r7|  j j   rt d   n  |  j j } | r|  j j j rt d   n  | j |  j j j  d |   n  d j |  t! |  f SWd |  j j" |  Xd S)z
        Creates the SQL for this query. Returns the SQL string and list of
        parameters.

        If 'with_limits' is False, any limit/offset information is not included
        in the query.
        N ZSELECTrZ   z%s AS %szCol%dz, ZFROMzWHERE %sz1annotate() + distinct(fields) is not implemented.zGROUP BY %sz	HAVING %szORDER BY %szLIMIT %dz	OFFSET %dz:select_for_update cannot be used outside of a transaction.z1NOWAIT is not supported on this database backend.nowait )#r#   r   r(   copyr;   get_distinctget_from_clauser4   r!   r5   r   r>   r   r   Zdistinct_sqlr   r   r@   joinNotImplementedErrorZforce_no_ordering	high_marklow_markZno_limit_valueZselect_for_updaterV   Zhas_select_for_updateZget_autocommitr   Zselect_for_update_nowaitZhas_select_for_update_nowaitr   Zfor_update_sqlrC   reset_refcounts)r$   Zwith_limitsZwith_col_aliasesr#   refcounts_beforer9   r8   r:   r   Zfrom_Zf_paramsr4   Zw_paramsr5   Zh_paramsrK   rM   Zout_colsZcol_idxrG   Zs_sqlZs_paramsrP   groupingZg_sqlZg_paramsrs   Zo_sqlZo_paramsvalr   r%   r%   r&   r<   f  s    	33	#"$"zSQLCompiler.as_sqlc             C   s   |  j  j   } | j d k rJ | j d k rJ |  j  j rJ | j d  n  | j d |  j  j d d  } | d f  f k r t	  n  | S)aV  
        Perform the same functionality as the as_sql() method, returning an
        SQL string and parameters. However, the alias prefixes are bumped
        beforehand (in a copy -- the current query isn't changed), and any
        ordering is removed if the query is unsliced.

        Used when nesting this query inside another.
        r   NTr   r#   r   )
r   cloner   r   r   clear_orderingget_compilerr   r<   r   )r$   objZ
nested_sqlr%   r%   r&   as_nested_sql  s    	+!	zSQLCompiler.as_nested_sqlNc             C   s)  g  } | d k r$ |  j  j   } n  |  j   } | sH |  j  j   } n  i | d 6} x | j D] } | j j j } | | j k r d } n  | r | d k	 r t | j j | j j  r q_ n  | j | k r | j	 | | j k r q_ n  |  j  j
 | | | |  }	 | j |	  }
 | j |
  q_ W| S)aW  
        Computes 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.

        Returns 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, returns a list of (alias, col_name) pairs instead
        of strings as the first component and None as the second component).
        N)r   rr   deferred_to_columnsr.   Zconcrete_fieldsrW   rX   concrete_model
issubclassattnameZjoin_parent_modelget_colr>   )r$   start_aliasoptsr]   rM   	only_loadZseen_modelsr   rW   rP   columnr%   r%   r&   rb     s*    	%	zSQLCompiler.get_default_columnsc             C   s   |  j  } |  j j j } g  } |  j j   } x |  j j D] } | j t  } |  j	 | | d  \ } } }	 }
 } } |  j j
 | |
 |  \ } }	 } xV | D]N } | |  j j k r | j |  q | j d | |	  | | j  f  q Wq: W| S)z
        Returns a quoted list of fields to use in DISTINCT ON part of the query.

        Note that this method can alter the tables in the query, and thus it
        must be called before get_from_clause().
        Nz%s.%s)rx   r   r   r   r   rr   r   rw   r   _setup_joins
trim_joinsrc   r>   r   )r$   qnqn2rM   r   r   partsrG   targetsrP   joinspathrO   r%   r%   r&   r     s    	'!.zSQLCompiler.get_distinctrj   c                sa  t  | |  \ } } | d k r' d n d  | j t  }  j | |    \ } }	   }
 } } | j r&| j r&t | d d  | k r&| s t   } n  t  f d d   |
 D  } | | k r t	 d   n  | j
 |  g  } x3 | j D]( } | j  j | |   | |   q W| S j j |	 |
 |  \ }	   }    f d	 d
   |	 D S)z
        Returns 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'.
        rk   TFr   Nc             3   s+   |  ]! } t    j j | d  d  Vq d S)Z	join_colsN)rS   r   r   )r)   j)r$   r%   r&   r+   2  s    z1SQLCompiler.find_ordering_name.<locals>.<genexpr>z!Infinite loop caused by ordering.c                s1   g  |  ]' } t  | j    d   d f  q S)rn   F)r   r   )r)   r   )rP   rn   r%   r&   rQ   =  s   	 z2SQLCompiler.find_ordering_name.<locals>.<listcomp>)r   rw   r   r   is_relationrs   rS   rA   rC   r   rD   r@   rz   r   r   )r$   r   r   rP   rp   Zalready_seenr   piecesr   r   r   r   Z
join_tupleresultsitemrG   r%   )rP   rn   r$   r&   rz     s$    '*!zSQLCompiler.find_ordering_namec             C   s_   | s |  j  j   } n  |  j  j | | |  \ } } } } } | d } | | | | | | f S)a$  
        A helper method for get_order_by and get_distinct.

        Note that 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.
        rZ   )r   r.   setup_joins)r$   r   r   rP   r   r   r   r   r%   r%   r&   r   ?  s    	
zSQLCompiler._setup_joinsc       	      C   s  g  } g  } x |  j  j D]w } |  j  j | s5 q n  y |  j  j | } Wn t k
 r` w Yn X|  j |  \ } } | j |  | j |  q Wxq |  j  j D]c } |  j  j	 |  \ } } | |  j  j k s |  j  j | d k r | j d |  j
 |   q q W| | f S)a  
        Returns 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. Sub-classes, 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 we need. This means the select columns,
        ordering and distinct must be done first.
        rZ   z, %s)r   r-   r(   r   KeyErrorr!   r>   r@   Zextra_tablesZtable_aliasrx   )	r$   rM   rK   rP   Zfrom_clauseZ
clause_sqlZclause_paramsr   rG   r%   r%   r&   r   N  s"    (!zSQLCompiler.get_from_clauserZ   c                s    f d d   } g  } | rA |  j  j rA | |  j  j k rA | S  sh |  j  j     |  j  j   } n  |  j  j   }	 t   }
 | d k r t |  j  j t  r |  j  j } d } q d } n  d d   } x  j	 D]} | j
 j j } |
 j | j  | rg| j | j i   } | j sm| s3| j | k rdt d | j d	 j |    pTd
 f   qdqmn d } t | | | |	 j |   sq n  i | j j
 d 6| d 6d d 6d d 6} | j |  g  } |  j  j | j g   |  \ } } } } } | d } |  j d | d | j j
 j  } x4 | D], } | j t |   | j | d f  q+W| | d <|  j | | j j
 j | | d | |  } | | |  q W| rd d     j D } x| D]y\ } } t | | | |	 j |  d d sqn  | j   } |
 j |  |  j  j | g   |  \ } } } } } | d } t |   j
  } i | d 6| d 6d d 6| d 6} | j |  g  } |  j d | d | j d   j
  } x4 | D], } | j t |   | j | d f  qW| | d <| j | j   i   } |  j | | j | | d | |  } | | |  qWt | j    j |
  } | rd d   | D } t d d	 j |  d	 j |    pd
 f   qn  | 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                 s9   d d     j  D }  d d     j D } t |  |  S)Nc             s   s!   |  ] } | j  r | j Vq d  S)N)r   r   )r)   fr%   r%   r&   r+   y  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   )Zdirect_choicesZreverse_choices)r   r%   r&   _get_field_choicesx  s    	z>SQLCompiler.get_related_selections.<locals>._get_field_choicesNTFc             S   s   | |  d <d  S)Nr\   r%   )r   r\   r%   r%   r&   get_related_klass_infos  s    zCSQLCompiler.get_related_selections.<locals>.get_related_klass_infoszCNon-relational field given in select_related: '%s'. Choices are: %sz, z(none)rW   r   reverser]   rZ   r   r   r[   c             S   s8   g  |  ]. } | j  j r | j r | j  | j f  q Sr%   )r   r   Zmany_to_manyZrelated_model)r)   or%   r%   r&   rQ     s   	z6SQLCompiler.get_related_selections.<locals>.<listcomp>c             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   Z	max_depthrr   r.   Zget_loaded_field_namesrA   ru   rd   dictr   rW   rX   r   rD   r   getr   r   r   r
   remote_fieldr>   r   rb   r0   re   r   r   r   keys
difference)r$   r   r   Z
root_aliasZ	cur_depth	requestedZ
restrictedr   r\   r   Zfields_foundr   r   Zfield_modelnextr   r[   rG   r   rP   columnsrI   Znext_klass_infosZrelated_fieldsrW   Zrelated_field_namer]   Zfields_not_foundZinvalid_fieldsr%   )r   r&   re   p  s    %				(
	$
!
%	*

	
%z"SQLCompiler.get_related_selectionsc             C   s#   i  } |  j  j | |  j  j  | S)z
        Converts the self.deferred_loading data structure to mapping of table
        names to sets of column names which are to be loaded. Returns the
        dictionary.
        )r   Zdeferred_to_dataZget_loaded_field_names_cb)r$   r   r%   r%   r&   r     s    zSQLCompiler.deferred_to_columnsc             C   sz   i  } xm t  |  D]_ \ } } | r |  j j j |  } | j |  j  } | sX | rr | | | f | | <qr q q W| S)N)rt   r   r   Zget_db_converters)r$   rE   
convertersi
expressionZbackend_convertersZfield_convertersr%   r%   r&   get_converters  s    zSQLCompiler.get_convertersc             C   s|   t  |  } xc | j   D]U \ } \ } } | | } x, | D]$ } | | | |  j |  j j  } q< W| | | <q Wt |  S)N)listr`   r   r   contextrC   )r$   rowr   r   Zconvsr   value	converterr%   r%   r&   apply_converters  s    
"zSQLCompiler.apply_convertersc             c   s   d } | d k r$ |  j  t  } n  d d   |  j d |  j  D } |  j |  } x? | D]7 } x. | D]& } | r |  j | |  } n  | Vqj Wq] Wd S)zQ
        Returns an iterator over the results from executing this query.
        Nc             S   s   g  |  ] } | d   q S)r   r%   )r)   r   r%   r%   r&   rQ     s   	 z,SQLCompiler.results_iter.<locals>.<listcomp>r   )execute_sqlr   r   r1   r   r   )r$   r   r   r   rowsr   r%   r%   r&   results_iter  s    #zSQLCompiler.results_iterc             C   sL   |  j  j i d d 6d d d d d  |  j  j d g  t |  j t   S)z
        Backends (e.g. NoSQL) can override this in order to use optimized
        versions of "query has any results."
        rZ   r*   N)r   Z	add_extraZset_extra_maskboolr   r   )r$   r%   r%   r&   has_results  s    &zSQLCompiler.has_resultsc          "   C   sj  | s t  } n  y% |  j   \ } } | s3 t  n  Wn, t k
 rb | t k rZ t g   Sd SYn X|  j j   } y | j | |  Wn t k
 r | j	     Yn X| t
 k r | S| t k r z+ | j   } | r | d |  j  S| SWd | j	   Xn  | t  k r| j	   d St | |  j j j |  j  } |  j j j sfz t |  SWd | j	   Xn  | S)a  
        Run the query against the database and returns 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   r<   r   r   iterr   cursorexecute	Exceptioncloser   r   Zfetchoner1   cursor_iterrV   Zempty_fetchmany_valueZcan_use_chunked_readsr   )r$   result_typerJ   rK   r   r   rM   r%   r%   r&   r   (  sH    	
	

zSQLCompiler.execute_sqlc             C   s  | j  } |  j j j } t |  d k rc |  j   \ } } d | |  | | d  | f | f Sx~ t |  j j  D]j \ } }	 |  j	 |	  \ }
 } d | |  | | |  f } |  j j
 j t d |
 | f |  d  qv W|  j   \ } } d | | f S)NrZ   z%s.%s IN (%s)r   z%s.%sz%s = %sZANDzEXISTS (%s))rx   r   r   r   r0   r<   rt   r   r   r!   r4   rD   r	   )r$   rP   r   compilerr   r   rJ   rK   indexZ
select_colZlhs_sqlZ
lhs_paramsZrhsr%   r%   r&   as_subquery_conditionh  s    	' !z!SQLCompiler.as_subquery_condition)__name__
__module____qualname__r'   r2   r;   r7   rB   r/   r3   r6   rx   r!   r<   r   rb   r   rz   r   r   re   r   r   r   r   r   r   r   r   r%   r%   r%   r&   r      s6   P @\

c-"	

	
@r   c                   sm   e  Z d  Z   f d d   Z d d   Z d d   Z d d   Z d	 d
   Z d d   Z d d d  Z	   S)SQLInsertCompilerc                s&   d |  _  t t |   j | |   d  S)NF)	return_idsuperr   r'   )r$   argskwargs)	__class__r%   r&   r'   {  s    	zSQLInsertCompiler.__init__c             C   s   | d k r | g  } } nk t  | d  rC |  j |  \ } } nD t  | d  rw | j | |  |  j  | g } } n d | g } } |  j j j | |  } | | f S)az  
        Take a field and a value intended to be saved on that field, and
        return placeholder SQL and accompanying params. Checks for raw values,
        expressions and fields with get_placeholder() defined in that order.

        When field is None, the value is considered raw and is used as the
        placeholder, with no corresponding parameters returned.
        Nr<   get_placeholderz%s)r=   r!   r   r   r   Zmodify_insert_params)r$   r   r   rJ   rK   r%   r%   r&   field_as_sql  s    	%zSQLInsertCompiler.field_as_sqlc             C   s   t  | d  rj | j |  j d d d d } | j rO t d | | f   n  | j r t d   q n | j | d |  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().
        rl   rq   Ffor_saveTzbFailed to insert expression "%s" on %s. F() expressions can only be used to update, not to insert.z1Aggregate functions are not allowed in this queryr   )	r=   rl   r   Zcontains_column_references
ValueErrorr?   r   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.
        rD   T)r   rawrS   r   Zpre_save)r$   r   r   r%   r%   r&   pre_save_val  s    zSQLInsertCompiler.pre_save_valc                sn   | 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,
        generate placeholder SQL and parameters for each field and value, and
        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   s1   |  ]' }  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+     s    z>SQLInsertCompiler.assemble_as_sql.<locals>.<genexpr>.<genexpr>N)r   )r)   r   )r   r$   r%   r&   r+     s   z4SQLInsertCompiler.assemble_as_sql.<locals>.<genexpr>c             s   s   |  ] } t  |   Vq d  S)N)r   )r)   r   r%   r%   r&   r+     s    c             S   s#   g  |  ] } d  d   | D  q S)c             S   s#   g  |  ] } | D] } |  q q Sr%   r%   )r)   pspr%   r%   r&   rQ     s   	 z@SQLInsertCompiler.assemble_as_sql.<locals>.<listcomp>.<listcomp>r%   )r)   r   r%   r%   r&   rQ     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   } d  | j  g  t  j j  } | rX  j j n	 | j g    j	 d d j
  f d d     D   | r    f d d    j j D } n(  f d d    j j D } d  g    j o  j  j j }  j   |  \ } }  j r j  j j r j  j j rd j	  j  j j   |   | } n+  j	 d	 d j
 | d
   | d
 g } d  | j   | j j  f }  j  j j   \ }	 }
 |	 r j	 |	 |  | |
 g 7} n  d j
   t t j |   f g S| rf j	  j  j j   |   d j
   t d d   | D  f g S f d d   t | |  D Sd  S)NzINSERT INTO %sz(%s)z, c             3   s   |  ] }   | j   Vq d  S)N)r   )r)   r   )r   r%   r&   r+     s    z+SQLInsertCompiler.as_sql.<locals>.<genexpr>c                s,   g  |  ]"      f d  d    D  q S)c                s.   g  |  ]$ }  j  |  j |      q Sr%   )r   r   )r)   r   )r   r$   r%   r&   rQ     s   	 z7SQLInsertCompiler.as_sql.<locals>.<listcomp>.<listcomp>r%   )r)   )r   r$   )r   r&   rQ     s   	z,SQLInsertCompiler.as_sql.<locals>.<listcomp>c                s%   g  |  ] }   j  j j   g  q Sr%   )r   r   Zpk_default_value)r)   rG   )r$   r%   r&   rQ     s   	 zVALUES (%s)r   z%s.%sr   c             s   s"   |  ] } | D] } | Vq q d  S)Nr%   )r)   r   r   r%   r%   r&   r+     s    c                s?   g  |  ]5 \ } } d  j    d d j  |  g  | f  q S)r   zVALUES (%s)z, )r   )r)   r   vals)rM   r%   r&   rQ     s   	)r   r   r   r   rr   db_tabler   r   rY   r>   r   objsr   rV   Zhas_bulk_insertr   can_return_id_from_insertcan_return_ids_from_bulk_insertZbulk_insert_sqlr   Zreturn_insert_idrC   r   from_iterabler   )r$   r   Z
has_fieldsr   Zcan_bulkr   r   rK   rI   Zr_fmtZr_paramsr%   )r   r   rM   r$   r&   r<     s<    -		%%)zSQLInsertCompiler.as_sqlFc             C   sE  | o+ t  |  j j  d k o+ |  j j j s5 t  | |  _ |  j j    } x* |  j	   D] \ } } | j
 | |  q] W| o | s d  S|  j j j r t  |  j j  d k r |  j j j |  S|  j j j rt  |  j j  d k s t  |  j j j |  S|  j j j | |  j j   j |  j j   j j  SWd  QXd  S)NrZ   )r0   r   r   r   rV   r  ra   r   r   r<   r   r   Zfetch_returned_insert_idsr   Zfetch_returned_insert_idZlast_insert_idrr   r   rY   r   )r$   r   r   rJ   rK   r%   r%   r&   r     s    	'zSQLInsertCompiler.execute_sql)
r   r   r   r'   r   r   r   r   r<   r   r%   r%   )r   r&   r   y  s    	#6r   c               @   s   e  Z d  Z d d   Z d S)SQLDeleteCompilerc                s   t    f d d     j j D  d k s7 t d     j } d |   j j d  g }   j   j j  \ } } | r | j d |  n  d j |  t	 |  f S)	zh
        Creates the SQL for this query. Returns the SQL string and list of
        parameters.
        c                s,   g  |  ]" }   j  j | d  k r |  q S)r   )r   r(   )r)   r   )r$   r%   r&   rQ   1  s   	 z,SQLDeleteCompiler.as_sql.<locals>.<listcomp>rZ   z)Can only delete from one table at a time.zDELETE FROM %sr   zWHERE %sr   )
r0   r   r-   ra   rx   r!   r4   r>   r   rC   )r$   r   rM   r4   rK   r%   )r$   r&   r<   ,  s    .		zSQLDeleteCompiler.as_sqlN)r   r   r   r<   r%   r%   r%   r&   r  +  s   r  c                   s@   e  Z d  Z d d   Z   f d d   Z   f d d   Z   S)SQLUpdateCompilerc             C   s  |  j    |  j j s  d f  f S|  j } g  g  } } x|  j j D]\ } } } t | d  r | j |  j d d d d } | j rt d   qnv t | d  r | j r | j	 | j
 |  d	 |  j } qt d
 | | | j j f   n | j	 | d	 |  j } t | d  r:| j | |  |  j  } n d } | j } t | d  r|  j |  \ }	 }
 | j d | |  |	 f  | j |
  qC | d k	 r| j d | |  | f  | j |  qC | j d | |   qC W| sd f  f S|  j j d } d | |  d j |  g } |  j |  j j  \ } }
 | rb| j d |  n  d j |  t | |
  f S)zh
        Creates the SQL for this query. Returns the SQL string and list of
        parameters.
        r   rl   rq   Fr   Tz1Aggregate functions are not allowed in this queryprepare_database_saver   zSTried to update field %s with a model instance, %r. Use a value compatible with %s.r   z%sr<   z%s = %sNz	%s = NULLr   zUPDATE %s SETz, zWHERE %sr   )r;   r   valuesrx   r=   rl   r?   r   r   r   r  r   	TypeErrorr   r   r   r   r!   r>   r@   r-   r   r4   rC   )r$   r   r  Zupdate_paramsr   rW   r   placeholderr   rJ   rK   r   rM   r4   r%   r%   r&   r<   <  sP    

				
zSQLUpdateCompiler.as_sqlc                s   t  t |   j |  } z% | r* | j n d } | d k } Wd | rS | j   n  XxM |  j j   D]< } | j |  j  j |  } | rd | rd | } d } qd qd W| S)a  
        Execute the specified update. Returns 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  r   Zrowcountr   r   Zget_related_updatesr   r   )r$   r   r   r   Zis_emptyr   Zaux_rows)r   r%   r&   r   u  s    zSQLUpdateCompiler.execute_sqlc                s  |  j  j j   } |  j  j   |  j  j   } |  j  j rK | d k rK d S|  j  j d t  } d | _ | j	 d  i  | _
 g  | _ | j | j   j j g  t t |   j   | d k o |  j j j } |  j  j   |  j  _ |  j  j s | reg  } x= | j |  j  j t  D]  } | j d d   | D  qW|  j  j d | f  | |  j  _ n |  j  j d | f  |  j  j |  d S)	a  
        If the update depends on results from other tables, we need to do some
        munging of the "where" conditions to match the format required for
        (portable) SQL updates. That is done here.

        Further, if we are going to be running multiple updates, we pull out
        the id values to update at this point so that they don't change as a
        result of the progressive updates.
        rZ   NklassFTc             s   s   |  ] } | d  Vq d S)r   Nr%   )r)   r   r%   r%   r&   r+     s    z2SQLUpdateCompiler.pre_sql_setup.<locals>.<genexpr>Zpk__in) r   r(   r   r.   Zcount_active_tablesZrelated_updatesr   r   rd   r   ry   r   Z
add_fieldsrr   rY   r   r   r  r;   r   rV   Zupdate_can_self_selectZwhere_classr4   r   r   r   r   r@   Z
add_filterZrelated_idsr   )r$   r   countr   Zmust_pre_selectZidentsr   )r   r%   r&   r;     s,    
			"zSQLUpdateCompiler.pre_sql_setup)r   r   r   r<   r   r;   r%   r%   )r   r&   r  ;  s   9r  c               @   s   e  Z d  Z d d   Z d S)SQLAggregateCompilerc             C   s   |  j  j s t  n  g  g  } } xO |  j  j j   D]; } |  j | d d \ } } | j |  | j |  q5 Wt |  j  j  |  _	 d j
 |  } t |  } d | |  j  j f } | |  j  j } | | f S)zh
        Creates the SQL for this query. Returns the SQL string and list of
        parameters.
        r_   Tz, zSELECT %s FROM (%s) subquery)r   r#   r   rc   r  r!   r>   r@   r0   r1   r   rC   Z
sub_params)r$   rJ   rK   rh   Zann_sqlZ
ann_paramsr%   r%   r&   r<     s    	zSQLAggregateCompiler.as_sqlN)r   r   r   r<   r%   r%   r%   r&   r    s   r  c          
   #   sT   zB x; t   f d d   |  D] }   f d d   | D Vq WWd  j   Xd S)z]
    Yields blocks of rows from a cursor and ensures the cursor is closed when
    done.
    c                  s     j  t  S)N)Z	fetchmanyr   r%   )r   r%   r&   <lambda>  s    zcursor_iter.<locals>.<lambda>c                s    g  |  ] } | d      q S)r   r%   )r)   r   )r1   r%   r&   rQ     s   	 zcursor_iter.<locals>.<listcomp>N)r   r   )r   sentinelr1   r   r%   )r1   r   r&   r     s
     r   )(r    	itertoolsr   Zdjango.core.exceptionsr   Zdjango.db.models.constantsr   Zdjango.db.models.expressionsr   r   r   r   Zdjango.db.models.query_utilsr	   r
   Zdjango.db.models.sql.constantsr   r   r   r   r   r   Z#django.db.models.sql.datastructuresr   Zdjango.db.models.sql.queryr   r   Zdjango.db.transactionr   Zdjango.db.utilsr   Zdjango.utils.six.movesr   objectr   r   r  r  r  r   r%   r%   r%   r&   <module>   s(   ".   j{