
 Xi                @   sC  d  Z  d d l Z d d l Z d d l m Z m Z m Z m Z d d l m	 Z	 m
 Z
 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 d d
 l m Z 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$ m% Z% m& Z& m' Z' m( Z( d d l) m* Z* m+ Z+ m, Z, m- Z- m. Z. d d l/ m0 Z0 m1 Z1 m2 Z2 m3 Z3 m4 Z4 d d l5 m6 Z6 d d l7 m8 Z8 d d l9 m: Z: d d l; m< Z< d d g Z= d d   Z> Gd d   d e?  Z@ Gd d   d e?  ZA d d d  ZB d d   ZC d d    ZD Gd! d"   d" e?  ZE d S)#aW  
Create SQL statements for QuerySets.

The code in here encapsulates all of the SQL construction so that QuerySets
themselves do not have to (and could be backed by things other than SQL
databases). The abstraction barrier only works one way: this module has to know
all about the internals of models in order to get the information it needs.
    N)CounterIteratorMappingOrderedDict)chaincountproduct)ascii_uppercase)FieldDoesNotExist
FieldError)DEFAULT_DB_ALIASconnections)Count)
LOOKUP_SEP)ColRef)MultiColSource)PathInfoQcheck_rel_lookup_compatibilityrefs_expression)INNERLOUTER	ORDER_DIRORDER_PATTERNQUERY_TERMSSINGLE)	BaseTableEmptyEmptyResultSetJoin	MultiJoin)ANDOR
ExtraWhereNothingNode	WhereNode)six)RemovedInDjango20Warning)
force_text)NodeQueryRawQueryc             C   s&   t  t j d d   |  j   D   S)Nc             s   s6   |  ], } | j  r$ | j | j f n	 | j f Vq d  S)N)concretenameattname).0f r2   H/home/ubuntu/projects/ifolica/build/django/django/db/models/sql/query.py	<genexpr>+   s   z,get_field_names_from_opts.<locals>.<genexpr>)setr   from_iterableZ
get_fields)optsr2   r2   r3   get_field_names_from_opts)   s    		r8   c               @   s   e  Z d  Z d Z d d d d  Z d d   Z d d   Z d	 d
   Z d d   Z e	 d d    Z
 d d   Z d d   Z d S)r,   z 
    A single raw SQL query
    Nc             C   sa   | p	 f  |  _  | |  _ | |  _ d  |  _ d \ |  _ |  _ i  |  _ i  |  _ | pW i  |  _ d  S)Nr   )r   N)	paramssqlusingcursorlow_mark	high_markextra_selectannotation_selectcontext)selfr:   r;   r9   rA   r2   r2   r3   __init__5   s    					zRawQuery.__init__c             C   s(   t  |  j | d |  j d |  j j   S)Nr9   rA   )r,   r:   r9   rA   copy)rB   r;   r2   r2   r3   cloneB   s    zRawQuery.clonec                sL   |  j  d  k r |  j   n  t |  j j j     f d d   |  j  j D S)Nc                s    g  |  ] }   | d    q S)r   r2   )r0   Zcolumn_meta)	converterr2   r3   
<listcomp>I   s   	z(RawQuery.get_columns.<locals>.<listcomp>)r<   _execute_queryr   r;   ZintrospectionZcolumn_name_converterdescription)rB   r2   )rF   r3   get_columnsE   s
    zRawQuery.get_columnsc             C   sB   |  j    t |  j j j s/ t |  j  } n	 |  j } t |  S)N)rH   r   r;   featuresZcan_use_chunked_readslistr<   iter)rB   resultr2   r2   r3   __iter__L   s
    
	zRawQuery.__iter__c             C   s   d |  S)Nz<RawQuery: %s>r2   )rB   r2   r2   r3   __repr__X   s    zRawQuery.__repr__c             C   s   t  |  j t  r t St S)N)
isinstancer9   r   dicttuple)rB   r2   r2   r3   params_type[   s    zRawQuery.params_typec             C   s   |  j  |  j |  j  S)N)r:   rT   r9   )rB   r2   r2   r3   __str___   s    zRawQuery.__str__c                s   t  |  j } |  j } | j j   | t k rS t   f d d   |  j D  } nJ | t k r t   f d d   t j	 |  j  D  } n t
 d |   | j   |  _ |  j j |  j |  d  S)Nc             3   s   |  ] }   |  Vq d  S)Nr2   )r0   val)adapterr2   r3   r4   j   s    z*RawQuery._execute_query.<locals>.<genexpr>c             3   s'   |  ] \ } } |   |  f Vq d  S)Nr2   )r0   keyrV   )rW   r2   r3   r4   l   s    zUnexpected params type: %s)r   r;   rT   opsZadapt_unknown_valuerS   r9   rR   r'   	iteritemsRuntimeErrorr<   executer:   )rB   
connectionrT   r9   r2   )rW   r3   rH   b   s    	%.zRawQuery._execute_query)__name__
__module____qualname____doc__rC   rE   rJ   rO   rP   propertyrT   rU   rH   r2   r2   r2   r3   r,   0   s   c               @   s<  e  Z d  Z d Z d Z e e g  Z e Z d Z	 e
 d d  Z e d d    Z e d d	    Z d
 d   Z d d   Z d d   Z d d   Z d d d d  Z d d   Z d d d d  Z d d   Z d 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  d0 d1   Z! d2 d3 d4  Z" d5 d6   Z# d7 d8   Z$ d9 d:   Z% d; d<   Z& d= d>   Z' d? d@   Z( dA dB   Z) d dC dD  Z* dE dF   Z+ d- dG dH  Z, dI dJ dK  Z- dL dM   Z. dN dO   Z/ dP dQ   Z0 dR dS   Z1 dT dU   Z2 d- d- d e3 dI dI dV dW  Z4 dX dY   Z5 dZ d[   Z6 d- d- dI dI d\ d]  Z7 dI d- d^ d_  Z8 d dI d` da  Z9 db dc   Z: dI d d- dd de  Z; df dg   Z< dh di   Z= dj dk   Z> d d dl dm  Z? dn do   Z@ dp dq   ZA dr ds   ZB dt du   ZC dv dw   ZD dx dy   ZE dz d{   ZF dI d| d}  ZG d~ d   ZH d d   ZI d d   ZJ d d   ZK d d   ZL d d   ZM d d   ZN d d   ZO d d   ZP d d   ZQ d d   ZR d d   ZS d d   ZT e d d    ZU e d d    ZV d d   ZW d d   ZX d S)r+   z
    A single SQL query.
    TZSQLCompilerc             C   sQ  | |  _  i  |  _ i  |  _ t   |  _ i  |  _ d |  _ d |  _ d |  _ t   |  _	 d |  _
 g  |  _ g  |  _ |   |  _ | |  _ d  |  _ g  |  _ d \ |  _ |  _ d |  _ g  |  _ d |  _ d |  _ d |  _ d |  _ g  |  _ d  |  _ d  |  _ d  |  _ d  |  _ d  |  _ d  |  _ f  |  _  f  |  _! t   d f |  _" i  |  _# d  S)NTFr      )r   N)$modelalias_refcount	alias_mapr5   external_aliases	table_mapdefault_colsdefault_orderingstandard_orderingused_aliasesfilter_is_stickyselecttableswherewhere_classgroup_byorder_byr=   r>   distinctdistinct_fieldsselect_for_updateselect_for_update_nowaitselect_related	max_depthvalues_select_annotationsannotation_select_mask_annotation_select_cache_extraextra_select_mask_extra_select_cacheextra_tablesextra_order_bydeferred_loadingrA   )rB   re   rq   r2   r2   r3   rC      sD    																												zQuery.__init__c             C   s%   |  j  d  k r t   |  _  n  |  j  S)N)r   r   )rB   r2   r2   r3   extra   s    zQuery.extrac             C   s%   |  j  d  k r t   |  _  n  |  j  S)N)r|   r   )rB   r2   r2   r3   annotations   s    zQuery.annotationsc             C   s   |  j    \ } } | | S)a)  
        Returns the query as a string of SQL with the parameter values
        substituted in (use sql_with_params() to see the unsubstituted string).

        Parameter values won't necessarily be quoted correctly, since that is
        done by the database interface at execution time.
        )sql_with_params)rB   r:   r9   r2   r2   r3   rU      s    zQuery.__str__c             C   s   |  j  t  j   S)zx
        Returns the query as an SQL string and the parameters that will be
        substituted into the query.
        )get_compilerr   Zas_sql)rB   r2   r2   r3   r      s    zQuery.sql_with_paramsc             C   s&   |  j  d |  } | | t |   <| S)Nmemo)rE   id)rB   r   rN   r2   r2   r3   __deepcopy__   s    zQuery.__deepcopy__c             C   s   |  S)Nr2   )rB   fieldr2   r2   r3   _prepare   s    zQuery._prepareNc             C   sY   | d  k r' | d  k r' t  d   n  | r: t | } n  | j j |  j  |  | |  S)NzNeed either using or connection)
ValueErrorr   rY   compiler)rB   r;   r]   r2   r2   r3   r      s
    zQuery.get_compilerc             C   s
   |  j  j S)z
        Returns the Options instance (the model._meta) from which to start
        processing. Normally, this is self.model._meta, but it can be changed
        by subclasses.
        )re   _meta)rB   r2   r2   r3   get_meta   s    zQuery.get_metac             K   s  t    } | p |  j | _ |  j | _ |  j j   | _ |  j j   | _ |  j j   | _ |  j j   | _ |  j | _ |  j	 | _	 |  j
 | _
 |  j d d  | _ |  j d d  | _ |  j j   | _ |  j | _ |  j d k r d | _ n1 |  j d k rd | _ n |  j d d  | _ |  j d d  | _ |  j |  j | _ | _ |  j | _ |  j d d  | _ |  j | _ |  j | _ |  j | _ |  j d d  | _ |  j d k	 r|  j j   n d | _ |  j d k rd | _ n |  j j   | _ d | _ |  j | _ |  j d k	 r;|  j j   n d | _ |  j d k r_d | _ n |  j j   | _ |  j  d k rd | _  n |  j  j   | _  |  j! | _! |  j" | _" t j |  j# d  |  j# d f | _# |  j$ r|  j% r|  j% j   | _% n t&   | _% d | _$ d |  j' k r6|  j( | _( n  d |  j' k rZ|  j) j   | _) n  | j' j* |  t+ | d  r| j,   n  |  j- j   | _- | S)	z
        Creates a copy of the current instance. The 'kwargs' parameter can be
        used by clients to update attributes after copying has taken place.
        NTr      Falias_prefixsubq_aliases_setup_query).r   	__class__re   rf   rD   rg   rh   ri   rj   rk   rl   ro   rp   rq   rE   rr   rs   rt   r=   r>   ru   rv   rw   rx   ry   r{   r|   r}   r~   rz   r   r   r   r   r   r   rn   rm   r5   __dict__r   r   updatehasattrr   rA   )rB   klassr   kwargsobjr2   r2   r3   rE     sp    	'	'&	zQuery.clonec             C   s   | |  j  | <d  S)N)rA   )rB   rX   valuer2   r2   r3   add_contextK  s    zQuery.add_contextc             C   s   |  j  j | |  S)N)rA   get)rB   rX   defaultr2   r2   r3   get_contextN  s    zQuery.get_contextc             C   s   |  j    } | j |  | S)N)rE   change_aliases)rB   
change_maprE   r2   r2   r3   relabeled_cloneQ  s    zQuery.relabeled_clonec             C   s   | j    } g  } x | D] } t | t  r> | j |  q t | t  r | d 7} d | } | |  j | <|  j | g  | j t | |   q |  j | |  \ } } | j |  q W| j |  | | f S)Nr   z__col%d)	Zget_source_expressionsrQ   r   appendr   r   append_annotation_maskrewrite_colsZset_source_expressions)rB   
annotationcol_cntZ
orig_exprsZ	new_exprsexprZ	col_aliasZnew_exprr2   r2   r3   r   V  s    

zQuery.rewrite_colsc                s-  |  j  s i  S|  j d k p( |  j d k	 } t   f d d   |  j j   D  } t |  j t  sz | sz | sz |  j	 rMd d l
 m } | |  j  } |  j   } d | _ d | _ | r |  j r | j d  n  | j	 s#| j r| r|  j j j j | j    g | _ n  d | _ n  d d	   | j D } d
 | d <d }	 xw t | j  j    D]` \ }
 } | j r| j | |	  \ } }	 | j |  | j |
 <| j |
 =n  | j | j  q_W| j g  k r| j r| j r|  j j j j | j    g | _ n  y | j | |  Wqnt k
 rId d	   | j  D SYqnXn! |  } g  |  _ d |  _ i  |  _  | j d  | j!   d | _ d | _ | j" |  } | j# t$  } | d k rd d   | j  j   D } n  | j% | j  j&    } | j' | |  } d d	   t( | j  j   |  D S)zV
        Returns the dictionary with the values of the existing aggregations.
        r   Nc             3   s'   |  ] \ } } |   k r | Vq d  S)Nr2   )r0   aliasr   )added_aggregate_namesr2   r3   r4     s    	z(Query.get_aggregation.<locals>.<genexpr>)AggregateQueryFTc             S   s   i  |  ] } d  |  q S)subqueryr2   )r0   tr2   r2   r3   
<dictcomp>  s   	 z)Query.get_aggregation.<locals>.<dictcomp>r   c             S   s   i  |  ] } d  |  q S)Nr2   )r0   r   r2   r2   r3   r     s   	c             S   s   g  |  ] } d   q S)Nr2   )r0   qr2   r2   r3   rG     s   	 z)Query.get_aggregation.<locals>.<listcomp>c             S   s%   i  |  ] \ \ } } } | |  q Sr2   r2   )r0   r   r   rV   r2   r2   r3   r     s   	))r@   r=   r>   anyr   itemsrQ   rs   rL   ru   Zdjango.db.models.sql.subqueriesr   re   rE   rw   ry   rv   clear_orderingrj   r   pkget_colget_initial_aliasrp   
is_summaryr   r   set_annotation_maskr}   ro   Zadd_subqueryr   r   clear_limitsr   Zexecute_sqlr   Zget_convertersvaluesZapply_converterszip)rB   r;   r   Z	has_limitZhas_existing_annotationsr   outer_queryZinner_queryZrelabelsr   r   
expressionr   rN   Z
convertersr2   )r   r3   get_aggregationy  sf    					'
"	#'				
			zQuery.get_aggregationc             C   s]   |  j    } | j t d  d d d d | j | d g  d } | d k rY d } n  | S)zP
        Performs a COUNT() query using the current filter constraints.
        *r   Z__countr   TNr   )rE   add_annotationr   r   )rB   r;   r   numberr2   r2   r3   	get_count  s    	zQuery.get_countc             C   s   |  j  S)N)rq   )rB   r2   r2   r3   has_filters  s    zQuery.has_filtersc             C   s   |  j    } | j sd | j d k rW | j d d   |  j j j D d  | j   n  | j   n  | j	 d  | j
 d d  | j d |  } | j   S)NTc             s   s   |  ] } | j  Vq d  S)N)r/   )r0   r1   r2   r2   r3   r4     s    z$Query.has_results.<locals>.<genexpr>Fhighr   r;   )rE   ru   rs   
add_fieldsre   r   Zconcrete_fieldsset_group_byclear_select_clauser   
set_limitsr   has_results)rB   r;   r   r   r2   r2   r3   r     s    	&zQuery.has_resultsc                s    j  | j  k s t d     j   s6 t d     j | j k sT t d     j | j k sr t d   i  } | t k } | r t   n t   j  }   j   t	 | d d  } | j
   f d d     j D  t   } x | j d	 d
  D] } | j | }	 |	 j |  }	   j |	 d | }
 |	 j t k rT| j |
  n  | j |
  | |
 k rz|
 | | <n  | j | s   j |
  q q W| j
 |  | j    | j j   } | j |    j j | |  g    _ x' | j D] }   j | j |   qW| t k rG  j rG| j rGt d   qGn    j j | j  t   }   j d
 k	 r| j   j  n  | j d
 k	 r| j | j  n  | r  j  |  n    j! | j! 7_! | j" r| j" d
 d
  n   j"   _" | j# p  j#   _# d
 S)aN  
        Merge the 'rhs' query into the current one (with any 'rhs' effects
        being applied *after* (that is, "to the right of") anything in the
        current query. 'rhs' is not modified during a call to this function.

        The 'connector' parameter describes how to connect filters from the
        'rhs' query.
        z4Cannot combine queries on two different base models.z3Cannot combine queries once a slice has been taken.z6Cannot combine a unique query with a non-unique query.z6Cannot combine queries with different distinct fields.   Fc             3   s+   |  ]! }   j  | j t k r | Vq d  S)N)rg   	join_typer   )r0   j)rB   r2   r3   r4     s    z Query.combine.<locals>.<genexpr>r   NreusezSWhen merging querysets using 'or', you cannot have extra(select=...) on both sides.)$re   AssertionError
can_filterru   rv   r"   r5   rp   r   JoinPromoter	add_votesrg   r   joinr   r   adddiscardrf   unref_aliasupdate_join_typesrq   rE   relabel_aliasesro   
add_selectr#   r   r   r   r   r   set_extra_maskr   rt   r   )rB   rhs	connectorr   Zconjunctionr   joinpromoterZ	rhs_votesr   r   	new_aliaswcolr   r2   )rB   r3   combine  sb    					
			(zQuery.combinec             C   s  |  j  \ } } | s d S|  j   } i  } i | j h | j 6} xC| D];} | j t  }	 |  j j j }
 | } x |	 d d  D]{ } |
 } | j |  } t	 |  r | j
 }
 n | j j }
 |
 j } t	 |  s | | j |  n  t | |
 | j  q W| j |	 d  } | j o%| j } | r7| j
 n | j } | j j } | | j k rd|
 } n  t	 |  sH t | | |  qH qH W| rni  } xe t j |  D]T \ } } xE | j j D]7 } | | k rqn  | j j j } t | | |  qWqWx= t j |  D], \ } } | | k r| | j |  qqWx t j |  D] \ } } | | | |  qKWn xG t j |  D]6 \ } } | | k r| | j |  q~| | | <q~Wx0 | j   D]" } | | k rt   | | <qqWx- t j |  D] \ } } | | | |  qWd S)a  
        Converts the self.deferred_loading data structure to an alternate data
        structure, describing the field that *will* be loaded. This is used to
        compute the columns to select from the database and also by the
        QuerySet class to work out which fields are being initialized on each
        model. Models that have all their fields included aren't mentioned in
        the result, only those that have field restrictions in place.

        The "target" parameter is the instance that is populated (in place).
        The "callback" is a function that is called whenever a (model, field)
        pair need to be added to "target". It accepts three parameters:
        "target", and the model and list of fields being added for that model.
        Nr   r   )r   r   r   concrete_modelsplitr   re   r   	get_fieldis_reverse_o2orelated_modelremote_fieldr   add_to_dictZauto_createdr-   r'   rZ   fieldsr   Zget_parent_listr5   )rB   targetcallbackfield_namesdeferZ	orig_optsseenZmust_include
field_namepartsZ	cur_modelr7   r.   Z	old_modelsourcer   Zis_reverse_objectre   Zworksetr   mr2   r2   r3   deferred_to_dataS  sd    		zQuery.deferred_to_dataFc             C   s   |  j  j |  } | rD | rD | d } |  j | d 7<| d f S| rz d |  j t |  j  d f } | j |  n | } | g |  j  | <d |  j | <|  j j |  | d f S)a	  
        Returns a table alias for the given table_name and whether this is a
        new alias or not.

        If 'create' is true, a new alias is always created. Otherwise, the
        most recently created alias for the table (if one exists) is reused.
        r   r   Fz%s%dT)ri   r   rf   r   lenrg   r   rp   )rB   
table_namecreateZ
alias_listr   r2   r2   r3   table_alias  s    

 zQuery.table_aliasc             C   s   |  j  | d 7<d S)z/ Increases the reference count for this alias. r   N)rf   )rB   r   r2   r2   r3   	ref_alias  s    zQuery.ref_aliasr   c             C   s   |  j  | | 8<d S)z/ Decreases the reference count for this alias. N)rf   )rB   r   amountr2   r2   r3   r     s    zQuery.unref_aliasc                s  t     x  r
 j d     j   j d k r@ q n   j   j d k	 s\ t   j   j } | o  j | j t k }  j   j t k }  j   j s | r | r  j   j    j   < j	     f d d    j j
   D  q q Wd S)a%  
        Promotes recursively the join type of given aliases and its children to
        an outer join. If 'unconditional' is False, the join is only promoted if
        it is nullable or the parent join is an outer join.

        The children promotion is done to avoid join chains that contain a LOUTER
        b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted,
        then we must also promote b->c automatically, or otherwise the promotion
        of a->b doesn't actually change anything in the query results.
        r   Nc             3   s7   |  ]- }  j  | j   k r |  k r | Vq d  S)N)rg   parent_alias)r0   r   )r   aliasesrB   r2   r3   r4     s    z&Query.promote_joins.<locals>.<genexpr>)rL   poprg   r   r   r   r   nullableZpromoteextendkeys)rB   r   r   Zparent_louterZalready_louterr2   )r   r   rB   r3   promote_joins  s    	zQuery.promote_joinsc             C   s   t  |  } x | r | j d  } |  j | j t k r |  j | j   |  j | <|  j | j } |  j | j t k r | j |  q q q Wd S)a  
        Change join type from LOUTER to INNER for all joins in aliases.

        Similarly to promote_joins(), this method must ensure no join chains
        containing first an outer, then an inner join are generated. If we
        are demoting b->c join in chain a LOUTER b LOUTER c then we must
        demote a->b automatically, or otherwise the demotion of b->c doesn't
        actually change anything in the query results. .
        r   N)	rL   r   rg   r   r   Zdemoter   r   r   )rB   r   r   r   r2   r2   r3   demote_joins  s    
	zQuery.demote_joinsc             C   sP   xI |  j  j   j   D]2 \ } } | | j | d  } |  j | |  q Wd S)z
        This method will reset reference counts for aliases so that they match
        the value passed in :param to_counts:.
        r   N)rf   rD   r   r   r   )rB   Z	to_countsr   Zcur_refcountZunref_amountr2   r2   r3   reset_refcounts   s    "zQuery.reset_refcountsc                s	  t    j    j t    j     t    k s6 t    f d d    |  j j    t |  j t	  r  f d d   |  j D |  _ n    f d d   |  j
 D |  _
 |  j r t  f d d   |  j j   D  |  _ n  xt j    D] \ } } | |  j k rq n  |  j | j    } | |  j | <|  j | |  j | <|  j | =|  j | =|  j | j } x4 t |  D]& \ } } | | k r{| | | <Pq{q{Wx: t |  j  D]) \ } } | | k r| |  j | <PqqWq W  f d d	   |  j D |  _ d
 S)z
        Changes the aliases in change_map (which maps old-alias -> new-alias),
        relabelling any references to them in select columns and the where
        clause.
        c                sJ   t  |  t t f  r9 |  d }   j | |  |  d f S|  j    Sd  S)Nr   r   )rQ   rL   rS   r   r   )r   	old_alias)r   r2   r3   relabel_column  s    
z,Query.change_aliases.<locals>.relabel_columnc                s   g  |  ] }   |   q Sr2   r2   )r0   r   )r  r2   r3   rG     s   	 z(Query.change_aliases.<locals>.<listcomp>c                s   g  |  ] } | j      q Sr2   )r   )r0   r   )r   r2   r3   rG     s   	 c             3   s'   |  ] \ } } |   |  f Vq d  S)Nr2   )r0   rX   r   )r  r2   r3   r4     s    z'Query.change_aliases.<locals>.<genexpr>c                s"   h  |  ] }   j  | |   q Sr2   )r   )r0   r   )r   r2   r3   	<setcomp>4  s   	z'Query.change_aliases.<locals>.<setcomp>N)r5   r   intersectionr   r   rq   r   rQ   rs   rL   ro   r|   r   r   r'   rZ   rg   r   rf   ri   r   	enumeraterp   rh   )rB   r   r  r   Z
alias_dataZtable_aliasesposr   r2   )r   r  r3   r   	  s8    6"	+


zQuery.change_aliasesc       	         s    f d d   }   j  | j  k r( d Sd } xT t |    D]C \ } } |   j k rf |   _  Pn  | | k r> t d   q> q> W  j j   j  g    _ | j j   j  | _ t   } xG t   j  D]6 \ } } d   j  | f } | | | <|   j | <q W  j |  d S)a  
        Changes the alias prefix to the next letter in the alphabet in a way
        that the outer query's aliases and this query's aliases will not
        conflict. Even tables that previously had no alias will get an alias
        after this call.
        c              3   s   t  }  t t   j  d  } | Vxj t d  D]\ } | rV |  |  j |  d  n |  } x( t | d | D] } d j |  Vqo Wd } q1 Wd S)a  
            Generates a sequence of characters in alphabetical order:
                -> 'A', 'B', 'C', ...

            When the alphabet is finished, the sequence will continue with the
            Cartesian product:
                -> 'AA', 'AB', 'AC', ...
            r   Nrepeat )r	   chrordr   r   indexr   r   )Zalphabetprefixnseqs)rB   r2   r3   
prefix_gen>  s    	%z%Query.bump_prefix.<locals>.prefix_genN   z6Maximum recursion depth exceeded: too many subqueries.z%s%d)r   r  r   r[   unionr   rp   r   )	rB   r   r  Zlocal_recursion_limitr	  r  r   r   r   r2   )rB   r3   bump_prefix7  s&    		
zQuery.bump_prefixc             C   sK   |  j  r& |  j  d } |  j |  n! |  j t |  j   j d   } | S)zg
        Returns the first alias for this query, after increasing its reference
        count.
        r   N)rp   r   r   r   r   db_table)rB   r   r2   r2   r3   r   f  s
    	!zQuery.get_initial_aliasc             C   s    t  d d   |  j j   D  S)z
        Returns the number of tables in this query with a non-zero reference
        count. Note that after execution, the reference counts are zeroed, so
        tables added in compiler will not be seen by this method.
        c             S   s   g  |  ] } | r d   q S)r   r2   )r0   r   r2   r2   r3   rG   x  s   	 z-Query.count_active_tables.<locals>.<listcomp>)r   rf   r   )rB   r2   r2   r3   count_active_tablesr  s    zQuery.count_active_tablesc                s      f d d   |  j  j   D   rD |  j  d   d S|  j   j d d \ } }   j r |  j    j j t k s   j r t } n t	 } |   _ n  |   _   |  j  | <| S)ah  
        Returns an alias for the join in 'connection', either reusing an
        existing alias for that join or creating a new one. 'connection' is a
        tuple (lhs, table, join_cols) where 'lhs' is either an existing
        table alias or a table name. 'join_cols' is a tuple of tuples containing
        columns to join on ((l_id1, r_id1), (l_id2, r_id2)). The join corresponds
        to the SQL equivalent of::

            lhs.l_id1 = table.r_id1 AND lhs.l_id2 = table.r_id2

        The 'reuse' parameter can be either None which means all joins
        (matching the connection) are reusable, or it can be a set containing
        the aliases that can be reused.

        A join is always created as LOUTER if the lhs alias is LOUTER to make
        sure we do not generate chains like t1 LOUTER t2 INNER t3. All new
        joins are created as LOUTER if nullable is True.

        If 'nullable' is True, the join can potentially involve NULL values and
        is a candidate for promotion (to "left outer") when combining querysets.

        The 'join_field' is the field we are joining along (if any).
        c                s@   g  |  ]6 \ } }  d  k s* |  k r |   k r |  q S)Nr2   )r0   ar   )r   r   r2   r3   rG     s   	 	zQuery.join.<locals>.<listcomp>r   r   T)
rg   r   r   r   r   r   r   r   r   r   )rB   r   r   r   _r   r2   )r   r   r3   r   z  s    %	"		z
Query.joinc             C   s   | | k r | | S| j  |  } | s- | S| } x | D] } | | k re | j } | | } q: n  | j | s | j } q: n  | j |  } |  j | j g | |  \ }	 }	 }	 }
 }	 | j } |
 d } | | <q: W| p | d S)a~  
        Makes sure the given 'model' is joined in the query. If 'model' isn't
        a parent of 'opts' or if it is None this method is a no-op.

        The 'alias' is the root alias for starting the join, 'seen' is a dict
        of model -> alias of existing joins. It must also contain a mapping
        of None -> some alias. This will be returned in the no-op case.
        r   Nr   )get_base_chainr   parentsZget_ancestor_linksetup_joinsr.   )rB   r7   re   r   r   r   Z	curr_opts	int_modelZ
link_fieldr  joinsr2   r2   r3   join_parent_model  s(    		
	$	zQuery.join_parent_modelc             C   sB   | j  |  d d d d d | } |  j | g  | |  j | <d S)zB
        Adds a single annotation expression to the Query
        allow_joinsTr   N	summarize)resolve_expressionr   r   )rB   r   r   r   r2   r2   r3   r     s    	zQuery.add_annotationTc                sw  g  } t  |  d k r$ d g } n  | d  k rb | d d k rO t d   n  d | d <d } n^ t | d  r |  j j     | j |  d	 | d
 | }   f d d   |  j j   D } n  t | d  r t | j d  r | j   } | j j	 |   n  t | d  r+| j
   } | j	 |   n  t t j j rj| d d k rj| d k rjd } d | d <n  | | | f S)Nr   exactr   iexactz Cannot use None as a query valueisnullTr#  r   r!  c                s4   g  |  ]* \ } } |   j  | d   k r |  q S)r   )r   )r0   kv)	pre_joinsr2   r3   rG     s   	 z.Query.prepare_lookup_value.<locals>.<listcomp>queryr  r  r   )zexactr%  r   r   r   )r   r   r   rf   rD   r#  r   r*  Z_cloner  rE   r   r   rK   !interprets_empty_strings_as_nulls)rB   r   lookups	can_reuser!  
used_joinsr2   )r)  r3   prepare_lookup_value  s.    
	%!zQuery.prepare_lookup_valuec       	      C   s   | j  t  } |  j rF t | |  j  \ } } | rF | f  | f Sn  |  j | |  j    \ } } } } | d t |  t |   } t |  d k r d g } n@ t |  d k r | s t d | |  j   j	 j
 f   q n  | | d f S)zU
        Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
        r   r$  r   z"Invalid lookup "%s" for model %s".F)r   r   r|   r   r   names_to_pathr   r   r   re   r^   )	rB   lookupZlookup_splittedr   Zexpression_lookupsr  r   Zlookup_partsZfield_partsr2   r2   r3   solve_lookup_type  s    	$ "zQuery.solve_lookup_typec             C   sJ   t  | d  rF t | j j | |  sF t d | | j f   qF n  d S)z
        Checks whether the object passed while querying is of the correct type.
        If not, it raises a ValueError specifying the wrong object.
        r   z)Cannot query "%s": Must be "%s" instance.N)r   r   r   re   r   object_name)rB   r   r7   r   r2   r2   r3   check_query_object_type  s
    zQuery.check_query_object_typec             C   s   | j  r t | d  rR | j | |  s t d | j j j | j f   q q t | d  rw |  j | | |  q t | d  r x$ | D] } |  j | | |  q Wq n  d S)zF
        Checks the type of object passed to query relations.
        is_compatible_query_object_typez6Cannot use QuerySet for "%s": Use a QuerySet for "%s".r   rO   N)	is_relationr   r5  r   re   r   
model_namer3  r4  )rB   r   r   r7   r(  r2   r2   r3   check_related_objects  s    	"zQuery.check_related_objectsc             C   s   | d d  } x | r | d } t  |  d k r~ | j |  } | sq |  j | | |  } | j d  } n  | | |  S|  j | | |  } | d d  } q Wd S)a3  
        Tries to extract transforms and lookup from given lhs.

        The lhs value is something that works like SQLExpression.
        The rhs value is what the lookup is going to compare against.
        The lookups is a list of names to extract using get_lookup()
        and get_transform().
        Nr   r   r$  )r   
get_lookuptry_transform)rB   r,  lhsr   r.   Zfinal_lookupr2   r2   r3   build_lookup$  s    		
zQuery.build_lookupc             C   sB   | j  |  } | r | |  St d | | j j j f   d S)z
        Helper method for build_lookup. Tries to fetch and initialize
        a transform for name parameter from lhs.
        zBUnsupported lookup '%s' for %s or join on the field not permitted.N)Zget_transformr   output_fieldr   r^   )rB   r;  r.   Zrest_of_lookupsZtransform_classr2   r2   r3   r:  ?  s    
zQuery.try_transformc             C   s  t  | t  r t d   n  | \ } }	 | sC t d |   n  |  j |  \ }
 } } | r t |  d k r t d   n  |  j |	 |
 | |  \ }	 }
 } |  j   } | r |  j |
 | |	  } | j | t	  | g  f S|  j
   } |  j   } | p| } yn |  j | | | d | d | \ } } } } } t  |	 t  r\t |	  }	 n  |  j | |	 |  | |  _ WnT t k
 r} z4 |  j | t j | d | j   | | j  SWYd d } ~ Xn X| d k	 r| j |  n  t |  j t |   } |  j | | |  \ } } } | j rt |
  } | d k rbt d j |
 d	    n  | d	 k stt  | j |
 d	  } t |  d k r| d	 j | |  } n t  | | | |  } | | |	  } | j! } n4 | d	 j | |  } |  j |
 | |	  } | j! } | j | t	  | d
 k oB|	 d k oB| } | r| d
 k sc|	 d k rd } | d
 k r|  j" | d	  s|  j# | d j$ t% k r| d	 j d
  } | j | | d	 j | | d	  d  t	  qn  | | s| n f  f S)a5  
        Builds a WhereNode for a single filter clause, but doesn't add it
        to this Query. Query.add_q() will then add this filter to the where
        Node.

        The 'branch_negated' tells us if the current branch contains any
        negations. This will be used to determine if subqueries are needed.

        The 'current_negated' is used to determine if the current filter is
        negated or not and this will be used to determine if IS NULL filtering
        is needed.

        The difference between current_netageted and branch_negated is that
        branch_negated is set on first negation, but current_negated is
        flipped for each negation.

        Note that add_filter will not do any negating itself, that is done
        upper in the code by add_q().

        The 'can_reuse' is a set of reusable joins for multijoins.

        The method will create a filter clause that can be added to the current
        query. However, if the filter isn't added to the query then the caller
        is responsible for unreffing the joins used.
        z"Cannot parse keyword query as dictzCannot parse keyword query %rr   z7Joined field references are not permitted in this queryr-  
allow_manyNz$Related Field got invalid lookup: {}r   r&  TFr   )&rQ   rR   r   r2  r   r/  rr   r<  r   r"   r   r   r  r   rL   r8  _lookup_joinsr!   split_excluder   r   levelnames_with_pathr   r5   r  
trim_joinsr6  formatr   r9  r   r   lookup_nameis_nullablerg   r   r   )rB   filter_exprbranch_negatedcurrent_negatedr-  r   r!  
split_subqargr   r,  r   Zreffed_expressionr.  clause	conditionr7   r   r>  r   sources	join_listpathetargetsZnum_lookupslookup_classr;  Zlookup_typer   Zrequire_outerr2   r2   r3   build_filterM  sn    !
*" 		
3zQuery.build_filterc             C   s&   |  j  t i | d | d 6   d  S)Nr   r   )add_qr   )rB   Zfilter_clauser2   r2   r3   
add_filter  s    zQuery.add_filterc                sj   t    f d d     j D  }   j |   j  \ } } | rY   j j | t  n    j |  d S)zo
        A preprocessor for the internal _add_q(). Responsible for doing final
        join promotion.
        c             3   s+   |  ]! }   j  | j t k r | Vq d  S)N)rg   r   r   )r0   r  )rB   r2   r3   r4     s    zQuery.add_q.<locals>.<genexpr>N)r5   rg   _add_qrm   rq   r   r"   r  )rB   q_objectZexisting_innerrL  r  r2   )rB   r3   rU    s    zQuery.add_qc             C   s-  | j  } | | j A} | p" | j } |  j d | d | j  } t | j  t | j  |  }	 x | j D] }
 t |
 t  r |  j |
 | | | | |  \ } } |	 j	 |  nF |  j
 |
 d | d | d | d | d | d | \ } } |	 j	 |  | rh | j | |  qh qh W|	 j |   } | | f S)z8
        Adds a Q-object to the current filter.
        r   negatedr-  rH  rI  r!  rJ  )r   rY  rr   r   r   childrenrQ   r*   rW  r   rT  r   r   )rB   rX  rm   rH  rI  r!  rJ  r   Ztarget_clauser   childZchild_clauseneeded_innerr2   r2   r3   rW    s*    		zQuery._add_qc             C   s
  g  g  } } xt  |  D]\ } } | g  f }	 | d k rM | j j } n  d }
 y | j |  }
 Wn t k
 r%| |  j k r |  j | j }
 n | d k r!xz | j D]l } | | j j	 j
 k r | j | j j	 j k r | j } | j |  }
 t j d | | f t d  Pq q Wn  Yn X|
 d k	 r|
 j rX|
 j rXt d |   n  y |
 j j	 j } Wqt k
 rd } YqXnj | d 8} | d k s| rt t |   } t | t |  j   } t d | d	 j |  f   n  P| | j k	 r| j } x | j |  D] } | | k r9| j	 } q| j | } | j j   f } | j	 } | j t | j j	 | | | d
 d   |	 d j t | j j	 | | | d
 d   qWn  t |
 d  r|
 j    } | sHxh t  |  D]W \ } } | j! r|	 d j" | d | d   | j |	  t# | d |   qqWn  | d } | j" |  | j$ } | j% } | j& } |	 d j" |  | j |	  q |
 } |
 f } | r| d t' |  k rt d | | d | f   n  Pq W| | | | | d d  f S)a  
        Walks the list of names and turns them into PathInfo tuples. Note that
        a single name in 'names' can generate multiple PathInfos (m2m for
        example).

        'names' is the path of names to travel, 'opts' is the model Options we
        start the name resolving from, 'allow_many' is as for setup_joins().
        If fail_on_missing is set to True, then a name that can't be resolved
        will generate a FieldError.

        Returns a list of PathInfo tuples. In addition returns the final field
        (the last used join field), and target (which is a field guaranteed to
        contain the same value as the final field). Finally, the method returns
        those names that weren't found (which are likely transforms and the
        final lookup).
        r   Nr   zKQuery lookup '%s' is deprecated in favor of Meta.default_related_name '%s'.r   zField %r does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation.r   z5Cannot resolve keyword %r into field. Choices are: %sz, FTget_path_infozACannot resolve keyword %r into field. Join on '%s' not permitted.r   r   )(r  r   r.   r   r
   r@   r=  Zrelated_objectsr   r   r7  related_nameZdefault_related_namewarningswarnr(   r6  r   re   r   AttributeErrorrL   r8   sortedr   r  r  r   Zget_related_fieldr   r   r   r]  m2mr   r!   
join_fieldto_optsZtarget_fieldsr   )rB   namesr7   r>  fail_on_missingrP  rB  r	  r.   Zcur_names_with_pathr   relr^  re   r   	availableZproxied_modelr  final_fieldrR  Z	pathinfosZ	inner_posplastr2   r2   r3   r0    s    	


		(
)	
				zQuery.names_to_pathc             C   s   | g } |  j  | | | d d \ } } }	 }
 x | D] } | j } | j rd |  j | j  } n d } t | j | d t | j |  } | j r | n d } |  j	 | d | } | j
 |  q7 W| |	 | | | f S)a  
        Compute the necessary table joins for the passage through the fields
        given in 'names'. 'opts' is the Options class for the current model
        (which gives the table we are starting from), 'alias' is the alias for
        the table to start the joining from.

        The 'can_reuse' defines the reverse foreign key joins we can reuse. It
        can be None in which case all joins are reusable or a set of aliases
        that can be reused. Note that non-reverse foreign keys are always
        reusable when using setup_joins().

        If 'allow_many' is False, then any reverse foreign key seen will
        generate a MultiJoin exception.

        Returns the final field involved in the joins, the target field (used
        for any 'where' constraint), the final 'opts' value, the joins and the
        field path travelled to generate the joins.

        The target field is the field containing the concrete value. Final
        field can be something different, for example foreign key pointing to
        that value. Final field is needed for example in some value
        conversions (convert 'obj' in fk__id=obj to pk val using the foreign
        key field for example).
        rg  TNr   )r0  re  directrF  rd  r    r  r   rc  r   r   )rB   rf  r7   r   r-  r>  r  rP  rj  rR  restr   r   r]   r   r2   r2   r3   r  ^  s    	!		!zQuery.setup_joinsc                s   | d d  } x t  t |   D] \ } } t |  d k sK | j rO Pn  t d d   | j j D  } t d d   | D      j |  s Pn    f d d   | j j D  t	  f d d   | D  } |  j
 | j    q# W| | d	 | f S)
a
  
        The 'target' parameter is the final field being joined to, 'joins'
        is the full list of join aliases. The 'path' contain the PathInfos
        used to create the joins.

        Returns the final target field and table alias and the new active
        joins.

        We will always trim any direct join if we have the target column
        available already in the previous table. Reverse joins can't be
        trimmed as we don't know if there is anything on the other side of
        the join.
        Nr   c             s   s   |  ] } | j  Vq d  S)N)column)r0   r   r2   r2   r3   r4     s    z#Query.trim_joins.<locals>.<genexpr>c             s   s   |  ] } | j  Vq d  S)N)ro  )r0   r   r2   r2   r3   r4     s    c                s7   i  |  ]- } | d  j    k r | d | d  j   q S)r   r   )ro  )r0   r)cur_targetsr2   r3   r     s   	 z$Query.trim_joins.<locals>.<dictcomp>c             3   s   |  ] }   | j  Vq d  S)N)ro  )r0   r   )targets_dictr2   r3   r4     s    r   )r  reversedr   rm  r5   rd  foreign_related_fieldsissubsetrelated_fieldsrS   r   r   )rB   rR  r  rP  r	  infoZjoin_targetsr2   )rq  rr  r3   rC    s    zQuery.trim_joinsc             C   s  | r" t  | k r" t d   n  | |  j k rY | rK t | |  j |  S|  j | Sn | j t   } |  j | |  j   |  j   |  \ } } } }	 }
 |  j	 | |	 |
  \ } } }	 t
 |  d k r t d   n  | d  k	 r | j |	  n  | d j |	 d | d  } | Sd  S)Nz7Joined field references are not permitted in this queryr   z?Referencing multicolumn fields with F() objects isn't supportedr   r   )r   r   r   r   r@   r   r  r   r   rC  r   r   r   )rB   r.   r!  r   r"  Z
field_listr   rN  r7   rO  rP  rR  r  r   r2   r2   r3   resolve_ref  s"    !zQuery.resolve_refc             C   s  t  |  j  } | j |  | j d  | j |  \ } } | j d } | j }	 | j }
 |  j |	  r |	 j	 d  } | |	 j
 |
  d  } | j j | t  n  |
 | k r1|	 j j j } | j |   |	 j	 d  } | | j
 | j d j  | j
 |
   } | j j | t  | j j |
  n  |  j d | | f d d d d d	 | \ } } | r|  j d
 | d f d d d d d	 | \ } } | j | t  n  | | f S)a\  
        When doing an exclude against any kind of N-to-many relation, we need
        to use a subquery. This method constructs the nested query, given the
        original exclude filter (filter_expr) and the portion up to the first
        N-to-many relation field.

        As an example we could have original filter ~Q(child__name='foo').
        We would get here with filter_expr = child__name, prefix = child and
        can_reuse is a set of joins usable for filters in the original query.

        We will turn this into equivalent of:
            WHERE NOT (pk IN (SELECT parent_id FROM thetable
                              WHERE name = 'foo' AND parent_id IS NOT NULL))

        It might be worth it to consider using WHERE NOT EXISTS as that has
        saner null handling, and is easier for the backend's optimizer to
        handle.
        Tr   r&  Fr$  z%s__inrI  rH  r-  z
%s__isnull)r+   re   rV  r   
trim_startro   r   r   rF  r9  r   rq   r   r"   r   r   r  rh   rT  r#   )rB   rG  r  r-  rB  r*  trimmed_prefixcontains_louterr   Zselect_fieldr   rS  r1  r   rM  r\  Zor_null_conditionr  r2   r2   r3   r@    s8    		zQuery.split_excludec             C   s   |  j  j t   t  d  S)N)rq   r   r%   r"   )rB   r2   r2   r3   	set_empty  s    zQuery.set_emptyc             C   s   t  d d   |  j j D  S)Nc             s   s   |  ] } t  | t  Vq d  S)N)rQ   r%   )r0   cr2   r2   r3   r4     s    z!Query.is_empty.<locals>.<genexpr>)r   rq   rZ  )rB   r2   r2   r3   is_empty  s    zQuery.is_emptyc             C   s   | d k	 rM |  j  d k	 r: t |  j  |  j |  |  _  qM |  j | |  _  n  | d k	 r |  j  d k	 r t |  j  |  j |  |  _ q |  j | |  _ n  |  j |  j  k r |  j   n  d S)a  
        Adjusts the limits on the rows retrieved. We use low/high to set these,
        as it makes it more Pythonic to read and write. When the SQL query is
        created, they are converted to the appropriate offset and limit values.

        Any limits passed in here are applied relative to the existing
        constraints. So low is added to the current low value and both will be
        clamped to any existing high value.
        N)r>   minr=   r|  )rB   lowr   r2   r2   r3   r   	  s    
zQuery.set_limitsc             C   s   d \ |  _  |  _ d S)z-
        Clears any existing limits.
        r   N)r   N)r=   r>   )rB   r2   r2   r3   r   !  s    zQuery.clear_limitsc             C   s   |  j  o |  j d k S)z
        Returns True if adding filters to this instance is still possible.

        Typically, this means no limits or offsets have been put on the results.
        N)r=   r>   )rB   r2   r2   r3   r   '  s    zQuery.can_filterc             C   s9   g  |  _  d |  _ d |  _ |  j f   |  j f   d S)z8
        Removes all fields from SELECT clause.
        FN)ro   rj   ry   r   r   )rB   r2   r2   r3   r   /  s
    			zQuery.clear_select_clausec             C   s   g  |  _  g  |  _ d S)z
        Clears the list of fields to select (but not extra_select columns).
        Some queryset types completely replace any existing list of select
        columns.
        N)ro   r{   )rB   r2   r2   r3   clear_select_fields9  s    	zQuery.clear_select_fieldsc             C   s   d |  _  |  j j |  d  S)NF)rj   ro   r   )rB   r   r2   r2   r3   r   B  s    	zQuery.add_selectc             C   s   d |  _  | |  _ d  S)NF)rj   ro   )rB   colsr2   r2   r3   
set_selectF  s    	zQuery.set_selectc             G   s   | |  _  d |  _ d S)zY
        Adds and resolves the given fields to the query's "distinct on" clause.
        TN)rv   ru   )rB   r   r2   r2   r3   add_distinct_fieldsJ  s    	zQuery.add_distinct_fieldsc             C   sB  |  j    } |  j   } y x | D]~ } |  j | j t  | | d | \ } } } } }	 |  j | | |	  \ } }
 } x$ | D] } |  j | j |
   q Wq" WWn t k
 r t	 d |   Ynu t	 k
 r=t | k r   nQ t
 t t |   t |  j  t |  j   } t	 d | d j |  f   Yn Xd S)z|
        Adds the given (model) fields to the select set. The field names are
        added in the order specified.
        r>  zInvalid field name: '%s'z5Cannot resolve keyword %r into field. Choices are: %sz, N)r   r   r  r   r   rC  r   r   r!   r   rb  rL   r8   r   r@   r   )rB   r   Z	allow_m2mr   r7   r.   r  rR  r  rP  Zfinal_aliasr   rf  r2   r2   r3   r   Q  s"    -"2zQuery.add_fieldsc             G   s   g  } xc | D][ } t  | d  rC t j |  rC | j |  n  t | d d  r t d |   q q W| r t d |   n  | r |  j j |  n	 d |  _ d S)a>  
        Adds items from the 'ordering' sequence to the query's "order by"
        clause. These items are either field names (not column names) --
        possibly with a direction prefix ('-' or '?') -- or OrderBy
        expressions.

        If 'ordering' is empty, all ordering is cleared from the query.
        r#  Zcontains_aggregateFz[Using an aggregate in order_by() without also including it in annotate() is not allowed: %szInvalid order_by arguments: %sN)	r   r   matchr   getattrr   rt   r   rk   )rB   Zorderingerrorsitemr2   r2   r3   add_orderingn  s    	 zQuery.add_orderingc             C   s(   g  |  _  f  |  _ | r$ d |  _ n  d S)z
        Removes any ordering settings. If 'force_empty' is True, there will be
        no ordering in the resulting query (not even the model's default).
        FN)rt   r   rk   )rB   Zforce_emptyr2   r2   r3   r     s    		zQuery.clear_orderingc             C   s   g  |  _  x! |  j D] } |  j  j |  q W|  j r xJ t j |  j  D]3 \ } } x$ | j   D] } |  j  j |  qb WqI Wn  d S)a@  
        Expands the GROUP BY clause required by the query.

        This will usually be the set of all non-aggregate fields in the
        return data. If the database backend supports grouping by the
        primary key, and the query would be equivalent, the optimization
        will be made automatically.
        N)rs   ro   r   r@   r'   rZ   Zget_group_by_cols)rB   r   r   r   r2   r2   r3   r     s    			zQuery.set_group_byc             C   st   t  |  j t  r i  } n	 |  j } x@ | D]8 } | } x) | j t  D] } | j | i   } qG Wq+ W| |  _ d S)z
        Sets up the select_related data structure so that we only select
        certain related models (as opposed to all models, when
        self.select_related=True).
        N)rQ   ry   boolr   r   
setdefault)rB   r   Z
field_dictr   dpartr2   r2   r3   add_select_related  s    		zQuery.add_select_relatedc             C   sO  | r t    } | r$ t |  } n t g   } x | j   D] \ }	 }
 t |
  }
 g  } |
 j d  } x\ | d k r | d k s |
 | d d k r | j t |   n  |
 j d | d  } qm W|
 | f | |	 <q= W|  j j |  n  | s | r|  j	 j
 t | |  t  n  | r9|  j t |  7_ n  | rK| |  _ n  d S)zn
        Adds data to the various extra_* attributes for user-created additions
        to the query.
        z%sr   r   %r   Nr   )r   rM   r   r)   findr   nextr   r   rq   r   r$   r"   r   rS   r   )rB   ro   Zselect_paramsrq   r9   rp   rt   Zselect_pairsZ
param_iterr.   entryZentry_paramsr	  r2   r2   r3   	add_extra  s*    	 zQuery.add_extrac             C   s   t    d f |  _ d S)zB
        Remove any fields from the deferred loading set.
        TN)r5   r   )rB   r2   r2   r3   clear_deferred_loading  s    zQuery.clear_deferred_loadingc             C   sL   |  j  \ } } | r0 | j |  d f |  _  n | j |  d f |  _  d S)ap  
        Add the given list of model field names to the set of fields to
        exclude from loading from the database when automatic column selection
        is done. The new field names are added to any existing field names that
        are deferred (or removed from any existing field names that are marked
        as the only ones for immediate loading).
        TFN)r   r  
difference)rB   r   existingr   r2   r2   r3   add_deferred_loading  s    zQuery.add_deferred_loadingc             C   s   |  j  \ } } t |  } d | k rP | j d  | j |  j   j j  n  | rq | j |  d f |  _  n | d f |  _  d S)a  
        Add the given list of model field names to the set of fields to
        retrieve when the SQL is executed ("immediate loading" fields). The
        field names replace any existing immediate loading field names. If
        there are field names already specified for deferred loading, those
        names are removed from the new field_names before storing the new names
        for immediate loading. (That is, immediate loading overrides any
        existing immediate values, but respects existing deferrals.)
        r   FN)r   r5   remover   r   r   r.   r  )rB   r   r  r   r2   r2   r3   add_immediate_loading  s    
zQuery.add_immediate_loadingc             C   sJ   y |  j  SWn8 t k
 rE i  } |  j | |  j  | |  _  | SYn Xd S)aH  
        If any fields are marked to be deferred, returns a dictionary mapping
        models to a set of names in those fields that will be loaded. If a
        model is not in the returned dictionary, none of its fields are
        deferred.

        If no fields are marked for deferral, returns an empty dictionary.
        N)Z_loaded_field_names_cachera  r   get_loaded_field_names_cb)rB   Z
collectionr2   r2   r3   get_loaded_field_names  s    	zQuery.get_loaded_field_namesc             C   s   d d   | D | | <d S)z>
        Callback used by get_deferred_field_names().
        c             S   s   h  |  ] } | j   q Sr2   )r/   )r0   r1   r2   r2   r3   r    s   	 z2Query.get_loaded_field_names_cb.<locals>.<setcomp>Nr2   )rB   r   re   r   r2   r2   r3   r    s    zQuery.get_loaded_field_names_cbc             C   s4   | d k r d |  _  n t |  |  _  d |  _ d S)zHSet the mask of annotations that will actually be returned by the SELECTN)r}   r5   r~   )rB   rf  r2   r2   r3   r      s    zQuery.set_annotation_maskc             C   s5   |  j  d  k	 r1 |  j t |  j |  j    n  d  S)N)r}   r   r5   r  )rB   rf  r2   r2   r3   r   (  s    zQuery.append_annotation_maskc             C   s4   | d k r d |  _  n t |  |  _  d |  _ d S)z
        Set the mask of extra select items that will be returned by SELECT,
        we don't actually remove them from the Query since they might be used
        later
        N)r   r5   r   )rB   rf  r2   r2   r3   r   ,  s    zQuery.set_extra_maskc                so     j  d k	 r   j  S  j s# i  S  j d k	 rd t   f d d     j j   D    _    j  S  j Sd S)zThe OrderedDict of aggregate columns that are not masked, and should
        be used in the SELECT clause.

        This result is cached for optimization purposes.
        Nc             3   s0   |  ]& \ } } |   j  k r | | f Vq d  S)N)r}   )r0   r'  r(  )rB   r2   r3   r4   E  s    	z*Query.annotation_select.<locals>.<genexpr>)r~   r|   r}   r   r   r   )rB   r2   )rB   r3   r@   8  s    	(zQuery.annotation_selectc                so     j  d  k	 r   j  S  j s# i  S  j d  k	 rd t   f d d     j j   D    _    j  S  j Sd  S)Nc             3   s0   |  ]& \ } } |   j  k r | | f Vq d  S)N)r   )r0   r'  r(  )rB   r2   r3   r4   T  s    	z%Query.extra_select.<locals>.<genexpr>)r   r   r   r   r   r   )rB   r2   )rB   r3   r?   L  s    	(zQuery.extra_selectc                sg  g  } x! | D] \ } } | j  |  q Wd }  f d d    j D } xe t |  D]W \ } } | j rr Pn   j | | d j t k r d } n  | | }	  j |	  qY W| j j	 }
 | } g  } xK | D]C \ } } | t
 |  d k  r Pn  | j |  | t
 |  8} q W| j |
 j d j  t j |  }  j | | d j t k rd d   |
 j D } | | d    j | |  |
 j  j d | | d  } | r j j | t  qn  d	 d   |
 j D } | |   xH  j D]= }  j | d k rt  j | j |   j | <PqqW j   f d
 d   | D  | | f S)a  
        Trims joins from the start of the join path. The candidates for trim
        are the PathInfos in names_with_path structure that are m2m joins.

        Also sets the select column so the start matches the join.

        This method is meant to be used for generating the subquery joins &
        cols in split_exclude().

        Returns a lookup usable for doing outerq.filter(lookup=self). Returns
        also if the joins in the prefix contain a LEFT OUTER join.
        _Fc                s8   g  |  ]. } |   j  k s. |   j d  k r |  q S)r   )r?  rp   )r0   r   )rB   r2   r3   rG   o  s   	 z$Query.trim_start.<locals>.<listcomp>r   Tr   c             S   s   g  |  ] } | d   q S)r   r2   )r0   rp  r2   r2   r3   rG     s   	 Nc             S   s   g  |  ] } | d   q S)r   r2   )r0   rp  r2   r2   r3   rG     s   	 c                s   g  |  ] } | j      q Sr2   )r   )r0   r1   )select_aliasr2   r3   rG     s   	 )r   rp   r  rc  rg   r   r   r   rd  r   r   r   rt  r.   r   r   rv  Zget_extra_restrictionrr   rq   r   r"   rf   r   r   r  )rB   rB  Z	all_pathsr  pathsr{  Zlookup_tablesZtrimmed_pathsrP  r   rd  Zpaths_in_prefixrz  r.   Zselect_fieldsZextra_restrictiontabler2   )r  rB   r3   ry  [  sN    		

  zQuery.trim_startc             C   s(   t  t j j r | j r d S| j Sd S)a%  
        A helper to check if the given field should be treated as nullable.

        Some backends treat '' as null and Django treats such fields as
        nullable for those backends. In such situations field.null can be
        False even if we should treat the field as nullable.
        TN)r   r   rK   r+  Zempty_strings_allowednull)rB   r   r2   r2   r3   rF    s    zQuery.is_nullable)Yr^   r_   r`   ra   r   	frozensetr   r   Zquery_termsr   r&   rC   rb   r   r   rU   r   r   r   r   r   rE   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r  r   r  r   r   r   r/  r2  r4  r8  r<  r:  r"   rT  rV  rU  rW  r0  r  rC  rx  r@  r|  r~  r   r   r   r   r  r   r  r  r   r  r   r   r  r  r  r  r  r  r  r   r   r   r@   r?   ry  rF  r2   r2   r2   r3   r+   t   s   NI#]cV"	./*"	#mq-C
	
!CZASCc             C   s@   t  | } |  d d k r2 |  d d  | d f S|  | d f S)a  
    Returns the field name and direction for an order specification. For
    example, '-foo' is returned as ('foo', 'DESC').

    The 'default' param is used to indicate which way no prefix (or a '+'
    prefix) should sort. The '-' prefix always sorts the opposite way.
    r   -r   N)r   )r   r   Zdirnr2   r2   r3   get_order_dir  s    
r  c             C   s1   | |  k r  |  | j  |  n | h |  | <d S)zs
    A helper function to add "value" to the set of values for "key", whether or
    not "key" already exists.
    N)r   )datarX   r   r2   r2   r3   r     s    r   c             C   s   |  j  o |  j o |  j S)z
    A little helper to check if the given field is reverse-o2o. The field is
    expected to be some sort of relation field or related object.
    )r6  Z
one_to_oner-   )r   r2   r2   r3   r     s    r   c               @   s:   e  Z d  Z d Z d d   Z d d   Z d d   Z d S)	r   z]
    A class to abstract away join promotion problems for complex filter
    conditions.
    c             C   sd   | |  _  | |  _ |  j r? | t k r3 t |  _ qK t |  _ n |  j  |  _ | |  _ t   |  _ d  S)N)r   rY  r"   r#   effective_connectornum_childrenr   votes)rB   r   r  rY  r2   r2   r3   rC     s    				zJoinPromoter.__init__c             C   s   |  j  j |  d S)z`
        Add single vote per item to self.votes. Parameter can be any
        iterable.
        N)r  r   )rB   r  r2   r2   r3   r     s    zJoinPromoter.add_votesc             C   s   t    } t    } x |  j j   D]w \ } } |  j d k r\ | |  j k  r\ | j |  n  |  j d k s |  j d k r" | |  j k r" | j |  q" q" W| j |  | j |  | S)a  
        Change join types so that the generated query is as efficient as
        possible, but still correct. So, change as many joins as possible
        to INNER, but don't make OUTER joins INNER if that could remove
        results from the query.
        r#   r"   )r5   r  r   r  r  r   r  r  )rB   r*  Z
to_promoteZ	to_demoter  r  r2   r2   r3   r     s    		zJoinPromoter.update_join_typesN)r^   r_   r`   ra   rC   r   r   r2   r2   r2   r3   r     s   r   )Fra   rD   r_  collectionsr   r   r   r   	itertoolsr   r   r   stringr	   Zdjango.core.exceptionsr
   r   Z	django.dbr   r   Zdjango.db.models.aggregatesr   Zdjango.db.models.constantsr   Zdjango.db.models.expressionsr   r   Z'django.db.models.fields.related_lookupsr   Zdjango.db.models.query_utilsr   r   r   r   Zdjango.db.models.sql.constantsr   r   r   r   r   r   Z#django.db.models.sql.datastructuresr   r   r   r    r!   Zdjango.db.models.sql.wherer"   r#   r$   r%   r&   Zdjango.utilsr'   Zdjango.utils.deprecationr(   Zdjango.utils.encodingr)   Zdjango.utils.treer*   __all__r8   objectr,   r+   r  r   r   r   r2   r2   r2   r3   <module>   sD   "".((D       D