query.py 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133
  1. """
  2. Create SQL statements for QuerySets.
  3. The code in here encapsulates all of the SQL construction so that QuerySets
  4. themselves do not have to (and could be backed by things other than SQL
  5. databases). The abstraction barrier only works one way: this module has to know
  6. all about the internals of models in order to get the information it needs.
  7. """
  8. from collections import Mapping, OrderedDict
  9. import copy
  10. import warnings
  11. from django.core.exceptions import FieldError
  12. from django.db import connections, DEFAULT_DB_ALIAS
  13. from django.db.models.constants import LOOKUP_SEP
  14. from django.db.models.aggregates import refs_aggregate
  15. from django.db.models.expressions import ExpressionNode
  16. from django.db.models.fields import FieldDoesNotExist
  17. from django.db.models.query_utils import Q
  18. from django.db.models.related import PathInfo
  19. from django.db.models.sql import aggregates as base_aggregates_module
  20. from django.db.models.sql.constants import (QUERY_TERMS, ORDER_DIR, SINGLE,
  21. ORDER_PATTERN, JoinInfo, SelectInfo)
  22. from django.db.models.sql.datastructures import EmptyResultSet, Empty, MultiJoin, Col
  23. from django.db.models.sql.expressions import SQLEvaluator
  24. from django.db.models.sql.where import (WhereNode, Constraint, EverythingNode,
  25. ExtraWhere, AND, OR, EmptyWhere)
  26. from django.utils import six
  27. from django.utils.deprecation import RemovedInDjango19Warning
  28. from django.utils.encoding import force_text
  29. from django.utils.tree import Node
  30. __all__ = ['Query', 'RawQuery']
  31. class RawQuery(object):
  32. """
  33. A single raw SQL query
  34. """
  35. def __init__(self, sql, using, params=None):
  36. self.params = params or ()
  37. self.sql = sql
  38. self.using = using
  39. self.cursor = None
  40. # Mirror some properties of a normal query so that
  41. # the compiler can be used to process results.
  42. self.low_mark, self.high_mark = 0, None # Used for offset/limit
  43. self.extra_select = {}
  44. self.aggregate_select = {}
  45. def clone(self, using):
  46. return RawQuery(self.sql, using, params=self.params)
  47. def get_columns(self):
  48. if self.cursor is None:
  49. self._execute_query()
  50. converter = connections[self.using].introspection.column_name_converter
  51. return [converter(column_meta[0])
  52. for column_meta in self.cursor.description]
  53. def __iter__(self):
  54. # Always execute a new query for a new iterator.
  55. # This could be optimized with a cache at the expense of RAM.
  56. self._execute_query()
  57. if not connections[self.using].features.can_use_chunked_reads:
  58. # If the database can't use chunked reads we need to make sure we
  59. # evaluate the entire query up front.
  60. result = list(self.cursor)
  61. else:
  62. result = self.cursor
  63. return iter(result)
  64. def __repr__(self):
  65. return "<RawQuery: %s>" % self
  66. def __str__(self):
  67. _type = dict if isinstance(self.params, Mapping) else tuple
  68. return self.sql % _type(self.params)
  69. def _execute_query(self):
  70. self.cursor = connections[self.using].cursor()
  71. self.cursor.execute(self.sql, self.params)
  72. class Query(object):
  73. """
  74. A single SQL query.
  75. """
  76. # SQL join types. These are part of the class because their string forms
  77. # vary from database to database and can be customised by a subclass.
  78. INNER = 'INNER JOIN'
  79. LOUTER = 'LEFT OUTER JOIN'
  80. alias_prefix = 'T'
  81. subq_aliases = frozenset([alias_prefix])
  82. query_terms = QUERY_TERMS
  83. aggregates_module = base_aggregates_module
  84. compiler = 'SQLCompiler'
  85. def __init__(self, model, where=WhereNode):
  86. self.model = model
  87. self.alias_refcount = {}
  88. # alias_map is the most important data structure regarding joins.
  89. # It's used for recording which joins exist in the query and what
  90. # type they are. The key is the alias of the joined table (possibly
  91. # the table name) and the value is JoinInfo from constants.py.
  92. self.alias_map = {}
  93. self.table_map = {} # Maps table names to list of aliases.
  94. self.join_map = {}
  95. self.default_cols = True
  96. self.default_ordering = True
  97. self.standard_ordering = True
  98. self.used_aliases = set()
  99. self.filter_is_sticky = False
  100. self.included_inherited_models = {}
  101. # SQL-related attributes
  102. # Select and related select clauses as SelectInfo instances.
  103. # The select is used for cases where we want to set up the select
  104. # clause to contain other than default fields (values(), annotate(),
  105. # subqueries...)
  106. self.select = []
  107. # The related_select_cols is used for columns needed for
  108. # select_related - this is populated in the compile stage.
  109. self.related_select_cols = []
  110. self.tables = [] # Aliases in the order they are created.
  111. self.where = where()
  112. self.where_class = where
  113. self.group_by = None
  114. self.having = where()
  115. self.order_by = []
  116. self.low_mark, self.high_mark = 0, None # Used for offset/limit
  117. self.distinct = False
  118. self.distinct_fields = []
  119. self.select_for_update = False
  120. self.select_for_update_nowait = False
  121. self.select_related = False
  122. # SQL aggregate-related attributes
  123. # The _aggregates will be an OrderedDict when used. Due to the cost
  124. # of creating OrderedDict this attribute is created lazily (in
  125. # self.aggregates property).
  126. self._aggregates = None # Maps alias -> SQL aggregate function
  127. self.aggregate_select_mask = None
  128. self._aggregate_select_cache = None
  129. # Arbitrary maximum limit for select_related. Prevents infinite
  130. # recursion. Can be changed by the depth parameter to select_related().
  131. self.max_depth = 5
  132. # These are for extensions. The contents are more or less appended
  133. # verbatim to the appropriate clause.
  134. # The _extra attribute is an OrderedDict, lazily created similarly to
  135. # .aggregates
  136. self._extra = None # Maps col_alias -> (col_sql, params).
  137. self.extra_select_mask = None
  138. self._extra_select_cache = None
  139. self.extra_tables = ()
  140. self.extra_order_by = ()
  141. # A tuple that is a set of model field names and either True, if these
  142. # are the fields to defer, or False if these are the only fields to
  143. # load.
  144. self.deferred_loading = (set(), True)
  145. @property
  146. def extra(self):
  147. if self._extra is None:
  148. self._extra = OrderedDict()
  149. return self._extra
  150. @property
  151. def aggregates(self):
  152. if self._aggregates is None:
  153. self._aggregates = OrderedDict()
  154. return self._aggregates
  155. def __str__(self):
  156. """
  157. Returns the query as a string of SQL with the parameter values
  158. substituted in (use sql_with_params() to see the unsubstituted string).
  159. Parameter values won't necessarily be quoted correctly, since that is
  160. done by the database interface at execution time.
  161. """
  162. sql, params = self.sql_with_params()
  163. return sql % params
  164. def sql_with_params(self):
  165. """
  166. Returns the query as an SQL string and the parameters that will be
  167. substituted into the query.
  168. """
  169. return self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
  170. def __deepcopy__(self, memo):
  171. result = self.clone(memo=memo)
  172. memo[id(self)] = result
  173. return result
  174. def prepare(self):
  175. return self
  176. def get_compiler(self, using=None, connection=None):
  177. if using is None and connection is None:
  178. raise ValueError("Need either using or connection")
  179. if using:
  180. connection = connections[using]
  181. # Check that the compiler will be able to execute the query
  182. for alias, aggregate in self.aggregate_select.items():
  183. connection.ops.check_aggregate_support(aggregate)
  184. return connection.ops.compiler(self.compiler)(self, connection, using)
  185. def get_meta(self):
  186. """
  187. Returns the Options instance (the model._meta) from which to start
  188. processing. Normally, this is self.model._meta, but it can be changed
  189. by subclasses.
  190. """
  191. return self.model._meta
  192. def clone(self, klass=None, memo=None, **kwargs):
  193. """
  194. Creates a copy of the current instance. The 'kwargs' parameter can be
  195. used by clients to update attributes after copying has taken place.
  196. """
  197. obj = Empty()
  198. obj.__class__ = klass or self.__class__
  199. obj.model = self.model
  200. obj.alias_refcount = self.alias_refcount.copy()
  201. obj.alias_map = self.alias_map.copy()
  202. obj.table_map = self.table_map.copy()
  203. obj.join_map = self.join_map.copy()
  204. obj.default_cols = self.default_cols
  205. obj.default_ordering = self.default_ordering
  206. obj.standard_ordering = self.standard_ordering
  207. obj.included_inherited_models = self.included_inherited_models.copy()
  208. obj.select = self.select[:]
  209. obj.related_select_cols = []
  210. obj.tables = self.tables[:]
  211. obj.where = self.where.clone()
  212. obj.where_class = self.where_class
  213. if self.group_by is None:
  214. obj.group_by = None
  215. else:
  216. obj.group_by = self.group_by[:]
  217. obj.having = self.having.clone()
  218. obj.order_by = self.order_by[:]
  219. obj.low_mark, obj.high_mark = self.low_mark, self.high_mark
  220. obj.distinct = self.distinct
  221. obj.distinct_fields = self.distinct_fields[:]
  222. obj.select_for_update = self.select_for_update
  223. obj.select_for_update_nowait = self.select_for_update_nowait
  224. obj.select_related = self.select_related
  225. obj.related_select_cols = []
  226. obj._aggregates = self._aggregates.copy() if self._aggregates is not None else None
  227. if self.aggregate_select_mask is None:
  228. obj.aggregate_select_mask = None
  229. else:
  230. obj.aggregate_select_mask = self.aggregate_select_mask.copy()
  231. # _aggregate_select_cache cannot be copied, as doing so breaks the
  232. # (necessary) state in which both aggregates and
  233. # _aggregate_select_cache point to the same underlying objects.
  234. # It will get re-populated in the cloned queryset the next time it's
  235. # used.
  236. obj._aggregate_select_cache = None
  237. obj.max_depth = self.max_depth
  238. obj._extra = self._extra.copy() if self._extra is not None else None
  239. if self.extra_select_mask is None:
  240. obj.extra_select_mask = None
  241. else:
  242. obj.extra_select_mask = self.extra_select_mask.copy()
  243. if self._extra_select_cache is None:
  244. obj._extra_select_cache = None
  245. else:
  246. obj._extra_select_cache = self._extra_select_cache.copy()
  247. obj.extra_tables = self.extra_tables
  248. obj.extra_order_by = self.extra_order_by
  249. obj.deferred_loading = copy.copy(self.deferred_loading[0]), self.deferred_loading[1]
  250. if self.filter_is_sticky and self.used_aliases:
  251. obj.used_aliases = self.used_aliases.copy()
  252. else:
  253. obj.used_aliases = set()
  254. obj.filter_is_sticky = False
  255. if 'alias_prefix' in self.__dict__:
  256. obj.alias_prefix = self.alias_prefix
  257. if 'subq_aliases' in self.__dict__:
  258. obj.subq_aliases = self.subq_aliases.copy()
  259. obj.__dict__.update(kwargs)
  260. if hasattr(obj, '_setup_query'):
  261. obj._setup_query()
  262. return obj
  263. def resolve_aggregate(self, value, aggregate, connection):
  264. """Resolve the value of aggregates returned by the database to
  265. consistent (and reasonable) types.
  266. This is required because of the predisposition of certain backends
  267. to return Decimal and long types when they are not needed.
  268. """
  269. if value is None:
  270. if aggregate.is_ordinal:
  271. return 0
  272. # Return None as-is
  273. return value
  274. elif aggregate.is_ordinal:
  275. # Any ordinal aggregate (e.g., count) returns an int
  276. return int(value)
  277. elif aggregate.is_computed:
  278. # Any computed aggregate (e.g., avg) returns a float
  279. return float(value)
  280. else:
  281. # Return value depends on the type of the field being processed.
  282. backend_converters = connection.ops.get_db_converters(aggregate.field.get_internal_type())
  283. field_converters = aggregate.field.get_db_converters(connection)
  284. for converter in backend_converters:
  285. value = converter(value, aggregate.field)
  286. for converter in field_converters:
  287. value = converter(value, connection)
  288. return value
  289. def get_aggregation(self, using, force_subq=False):
  290. """
  291. Returns the dictionary with the values of the existing aggregations.
  292. """
  293. if not self.aggregate_select:
  294. return {}
  295. # If there is a group by clause, aggregating does not add useful
  296. # information but retrieves only the first row. Aggregate
  297. # over the subquery instead.
  298. if self.group_by is not None or force_subq:
  299. from django.db.models.sql.subqueries import AggregateQuery
  300. query = AggregateQuery(self.model)
  301. obj = self.clone()
  302. if not force_subq:
  303. # In forced subq case the ordering and limits will likely
  304. # affect the results.
  305. obj.clear_ordering(True)
  306. obj.clear_limits()
  307. obj.select_for_update = False
  308. obj.select_related = False
  309. obj.related_select_cols = []
  310. relabels = dict((t, 'subquery') for t in self.tables)
  311. # Remove any aggregates marked for reduction from the subquery
  312. # and move them to the outer AggregateQuery.
  313. for alias, aggregate in self.aggregate_select.items():
  314. if aggregate.is_summary:
  315. query.aggregates[alias] = aggregate.relabeled_clone(relabels)
  316. del obj.aggregate_select[alias]
  317. try:
  318. query.add_subquery(obj, using)
  319. except EmptyResultSet:
  320. return dict(
  321. (alias, None)
  322. for alias in query.aggregate_select
  323. )
  324. else:
  325. query = self
  326. self.select = []
  327. self.default_cols = False
  328. self._extra = {}
  329. self.remove_inherited_models()
  330. query.clear_ordering(True)
  331. query.clear_limits()
  332. query.select_for_update = False
  333. query.select_related = False
  334. query.related_select_cols = []
  335. result = query.get_compiler(using).execute_sql(SINGLE)
  336. if result is None:
  337. result = [None for q in query.aggregate_select.items()]
  338. return dict(
  339. (alias, self.resolve_aggregate(val, aggregate, connection=connections[using]))
  340. for (alias, aggregate), val
  341. in zip(query.aggregate_select.items(), result)
  342. )
  343. def get_count(self, using):
  344. """
  345. Performs a COUNT() query using the current filter constraints.
  346. """
  347. obj = self.clone()
  348. if len(self.select) > 1 or self.aggregate_select or (self.distinct and self.distinct_fields):
  349. # If a select clause exists, then the query has already started to
  350. # specify the columns that are to be returned.
  351. # In this case, we need to use a subquery to evaluate the count.
  352. from django.db.models.sql.subqueries import AggregateQuery
  353. subquery = obj
  354. subquery.clear_ordering(True)
  355. subquery.clear_limits()
  356. obj = AggregateQuery(obj.model)
  357. try:
  358. obj.add_subquery(subquery, using=using)
  359. except EmptyResultSet:
  360. # add_subquery evaluates the query, if it's an EmptyResultSet
  361. # then there are can be no results, and therefore there the
  362. # count is obviously 0
  363. return 0
  364. obj.add_count_column()
  365. number = obj.get_aggregation(using=using)[None]
  366. # Apply offset and limit constraints manually, since using LIMIT/OFFSET
  367. # in SQL (in variants that provide them) doesn't change the COUNT
  368. # output.
  369. number = max(0, number - self.low_mark)
  370. if self.high_mark is not None:
  371. number = min(number, self.high_mark - self.low_mark)
  372. return number
  373. def has_filters(self):
  374. return self.where or self.having
  375. def has_results(self, using):
  376. q = self.clone()
  377. if not q.distinct:
  378. q.clear_select_clause()
  379. q.clear_ordering(True)
  380. q.set_limits(high=1)
  381. compiler = q.get_compiler(using=using)
  382. return compiler.has_results()
  383. def combine(self, rhs, connector):
  384. """
  385. Merge the 'rhs' query into the current one (with any 'rhs' effects
  386. being applied *after* (that is, "to the right of") anything in the
  387. current query. 'rhs' is not modified during a call to this function.
  388. The 'connector' parameter describes how to connect filters from the
  389. 'rhs' query.
  390. """
  391. assert self.model == rhs.model, \
  392. "Cannot combine queries on two different base models."
  393. assert self.can_filter(), \
  394. "Cannot combine queries once a slice has been taken."
  395. assert self.distinct == rhs.distinct, \
  396. "Cannot combine a unique query with a non-unique query."
  397. assert self.distinct_fields == rhs.distinct_fields, \
  398. "Cannot combine queries with different distinct fields."
  399. self.remove_inherited_models()
  400. # Work out how to relabel the rhs aliases, if necessary.
  401. change_map = {}
  402. conjunction = (connector == AND)
  403. # Determine which existing joins can be reused. When combining the
  404. # query with AND we must recreate all joins for m2m filters. When
  405. # combining with OR we can reuse joins. The reason is that in AND
  406. # case a single row can't fulfill a condition like:
  407. # revrel__col=1 & revrel__col=2
  408. # But, there might be two different related rows matching this
  409. # condition. In OR case a single True is enough, so single row is
  410. # enough, too.
  411. #
  412. # Note that we will be creating duplicate joins for non-m2m joins in
  413. # the AND case. The results will be correct but this creates too many
  414. # joins. This is something that could be fixed later on.
  415. reuse = set() if conjunction else set(self.tables)
  416. # Base table must be present in the query - this is the same
  417. # table on both sides.
  418. self.get_initial_alias()
  419. joinpromoter = JoinPromoter(connector, 2, False)
  420. joinpromoter.add_votes(
  421. j for j in self.alias_map if self.alias_map[j].join_type == self.INNER)
  422. rhs_votes = set()
  423. # Now, add the joins from rhs query into the new query (skipping base
  424. # table).
  425. for alias in rhs.tables[1:]:
  426. table, _, join_type, lhs, join_cols, nullable, join_field = rhs.alias_map[alias]
  427. # If the left side of the join was already relabeled, use the
  428. # updated alias.
  429. lhs = change_map.get(lhs, lhs)
  430. new_alias = self.join(
  431. (lhs, table, join_cols), reuse=reuse,
  432. nullable=nullable, join_field=join_field)
  433. if join_type == self.INNER:
  434. rhs_votes.add(new_alias)
  435. # We can't reuse the same join again in the query. If we have two
  436. # distinct joins for the same connection in rhs query, then the
  437. # combined query must have two joins, too.
  438. reuse.discard(new_alias)
  439. change_map[alias] = new_alias
  440. if not rhs.alias_refcount[alias]:
  441. # The alias was unused in the rhs query. Unref it so that it
  442. # will be unused in the new query, too. We have to add and
  443. # unref the alias so that join promotion has information of
  444. # the join type for the unused alias.
  445. self.unref_alias(new_alias)
  446. joinpromoter.add_votes(rhs_votes)
  447. joinpromoter.update_join_types(self)
  448. # Now relabel a copy of the rhs where-clause and add it to the current
  449. # one.
  450. if rhs.where:
  451. w = rhs.where.clone()
  452. w.relabel_aliases(change_map)
  453. if not self.where:
  454. # Since 'self' matches everything, add an explicit "include
  455. # everything" where-constraint so that connections between the
  456. # where clauses won't exclude valid results.
  457. self.where.add(EverythingNode(), AND)
  458. elif self.where:
  459. # rhs has an empty where clause.
  460. w = self.where_class()
  461. w.add(EverythingNode(), AND)
  462. else:
  463. w = self.where_class()
  464. self.where.add(w, connector)
  465. # Selection columns and extra extensions are those provided by 'rhs'.
  466. self.select = []
  467. for col, field in rhs.select:
  468. if isinstance(col, (list, tuple)):
  469. new_col = change_map.get(col[0], col[0]), col[1]
  470. self.select.append(SelectInfo(new_col, field))
  471. else:
  472. new_col = col.relabeled_clone(change_map)
  473. self.select.append(SelectInfo(new_col, field))
  474. if connector == OR:
  475. # It would be nice to be able to handle this, but the queries don't
  476. # really make sense (or return consistent value sets). Not worth
  477. # the extra complexity when you can write a real query instead.
  478. if self._extra and rhs._extra:
  479. raise ValueError("When merging querysets using 'or', you "
  480. "cannot have extra(select=...) on both sides.")
  481. self.extra.update(rhs.extra)
  482. extra_select_mask = set()
  483. if self.extra_select_mask is not None:
  484. extra_select_mask.update(self.extra_select_mask)
  485. if rhs.extra_select_mask is not None:
  486. extra_select_mask.update(rhs.extra_select_mask)
  487. if extra_select_mask:
  488. self.set_extra_mask(extra_select_mask)
  489. self.extra_tables += rhs.extra_tables
  490. # Ordering uses the 'rhs' ordering, unless it has none, in which case
  491. # the current ordering is used.
  492. self.order_by = rhs.order_by[:] if rhs.order_by else self.order_by
  493. self.extra_order_by = rhs.extra_order_by or self.extra_order_by
  494. def deferred_to_data(self, target, callback):
  495. """
  496. Converts the self.deferred_loading data structure to an alternate data
  497. structure, describing the field that *will* be loaded. This is used to
  498. compute the columns to select from the database and also by the
  499. QuerySet class to work out which fields are being initialized on each
  500. model. Models that have all their fields included aren't mentioned in
  501. the result, only those that have field restrictions in place.
  502. The "target" parameter is the instance that is populated (in place).
  503. The "callback" is a function that is called whenever a (model, field)
  504. pair need to be added to "target". It accepts three parameters:
  505. "target", and the model and list of fields being added for that model.
  506. """
  507. field_names, defer = self.deferred_loading
  508. if not field_names:
  509. return
  510. orig_opts = self.get_meta()
  511. seen = {}
  512. must_include = {orig_opts.concrete_model: {orig_opts.pk}}
  513. for field_name in field_names:
  514. parts = field_name.split(LOOKUP_SEP)
  515. cur_model = self.model._meta.concrete_model
  516. opts = orig_opts
  517. for name in parts[:-1]:
  518. old_model = cur_model
  519. source = opts.get_field_by_name(name)[0]
  520. if is_reverse_o2o(source):
  521. cur_model = source.model
  522. else:
  523. cur_model = source.rel.to
  524. opts = cur_model._meta
  525. # Even if we're "just passing through" this model, we must add
  526. # both the current model's pk and the related reference field
  527. # (if it's not a reverse relation) to the things we select.
  528. if not is_reverse_o2o(source):
  529. must_include[old_model].add(source)
  530. add_to_dict(must_include, cur_model, opts.pk)
  531. field, model, _, _ = opts.get_field_by_name(parts[-1])
  532. if model is None:
  533. model = cur_model
  534. if not is_reverse_o2o(field):
  535. add_to_dict(seen, model, field)
  536. if defer:
  537. # We need to load all fields for each model, except those that
  538. # appear in "seen" (for all models that appear in "seen"). The only
  539. # slight complexity here is handling fields that exist on parent
  540. # models.
  541. workset = {}
  542. for model, values in six.iteritems(seen):
  543. for field, m in model._meta.get_fields_with_model():
  544. if field in values:
  545. continue
  546. add_to_dict(workset, m or model, field)
  547. for model, values in six.iteritems(must_include):
  548. # If we haven't included a model in workset, we don't add the
  549. # corresponding must_include fields for that model, since an
  550. # empty set means "include all fields". That's why there's no
  551. # "else" branch here.
  552. if model in workset:
  553. workset[model].update(values)
  554. for model, values in six.iteritems(workset):
  555. callback(target, model, values)
  556. else:
  557. for model, values in six.iteritems(must_include):
  558. if model in seen:
  559. seen[model].update(values)
  560. else:
  561. # As we've passed through this model, but not explicitly
  562. # included any fields, we have to make sure it's mentioned
  563. # so that only the "must include" fields are pulled in.
  564. seen[model] = values
  565. # Now ensure that every model in the inheritance chain is mentioned
  566. # in the parent list. Again, it must be mentioned to ensure that
  567. # only "must include" fields are pulled in.
  568. for model in orig_opts.get_parent_list():
  569. if model not in seen:
  570. seen[model] = set()
  571. for model, values in six.iteritems(seen):
  572. callback(target, model, values)
  573. def deferred_to_columns_cb(self, target, model, fields):
  574. """
  575. Callback used by deferred_to_columns(). The "target" parameter should
  576. be a set instance.
  577. """
  578. table = model._meta.db_table
  579. if table not in target:
  580. target[table] = set()
  581. for field in fields:
  582. target[table].add(field.column)
  583. def table_alias(self, table_name, create=False):
  584. """
  585. Returns a table alias for the given table_name and whether this is a
  586. new alias or not.
  587. If 'create' is true, a new alias is always created. Otherwise, the
  588. most recently created alias for the table (if one exists) is reused.
  589. """
  590. alias_list = self.table_map.get(table_name)
  591. if not create and alias_list:
  592. alias = alias_list[0]
  593. self.alias_refcount[alias] += 1
  594. return alias, False
  595. # Create a new alias for this table.
  596. if alias_list:
  597. alias = '%s%d' % (self.alias_prefix, len(self.alias_map) + 1)
  598. alias_list.append(alias)
  599. else:
  600. # The first occurrence of a table uses the table name directly.
  601. alias = table_name
  602. self.table_map[alias] = [alias]
  603. self.alias_refcount[alias] = 1
  604. self.tables.append(alias)
  605. return alias, True
  606. def ref_alias(self, alias):
  607. """ Increases the reference count for this alias. """
  608. self.alias_refcount[alias] += 1
  609. def unref_alias(self, alias, amount=1):
  610. """ Decreases the reference count for this alias. """
  611. self.alias_refcount[alias] -= amount
  612. def promote_joins(self, aliases):
  613. """
  614. Promotes recursively the join type of given aliases and its children to
  615. an outer join. If 'unconditional' is False, the join is only promoted if
  616. it is nullable or the parent join is an outer join.
  617. The children promotion is done to avoid join chains that contain a LOUTER
  618. b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted,
  619. then we must also promote b->c automatically, or otherwise the promotion
  620. of a->b doesn't actually change anything in the query results.
  621. """
  622. aliases = list(aliases)
  623. while aliases:
  624. alias = aliases.pop(0)
  625. if self.alias_map[alias].join_cols[0][1] is None:
  626. # This is the base table (first FROM entry) - this table
  627. # isn't really joined at all in the query, so we should not
  628. # alter its join type.
  629. continue
  630. # Only the first alias (skipped above) should have None join_type
  631. assert self.alias_map[alias].join_type is not None
  632. parent_alias = self.alias_map[alias].lhs_alias
  633. parent_louter = (
  634. parent_alias
  635. and self.alias_map[parent_alias].join_type == self.LOUTER)
  636. already_louter = self.alias_map[alias].join_type == self.LOUTER
  637. if ((self.alias_map[alias].nullable or parent_louter) and
  638. not already_louter):
  639. data = self.alias_map[alias]._replace(join_type=self.LOUTER)
  640. self.alias_map[alias] = data
  641. # Join type of 'alias' changed, so re-examine all aliases that
  642. # refer to this one.
  643. aliases.extend(
  644. join for join in self.alias_map.keys()
  645. if (self.alias_map[join].lhs_alias == alias
  646. and join not in aliases))
  647. def demote_joins(self, aliases):
  648. """
  649. Change join type from LOUTER to INNER for all joins in aliases.
  650. Similarly to promote_joins(), this method must ensure no join chains
  651. containing first an outer, then an inner join are generated. If we
  652. are demoting b->c join in chain a LOUTER b LOUTER c then we must
  653. demote a->b automatically, or otherwise the demotion of b->c doesn't
  654. actually change anything in the query results. .
  655. """
  656. aliases = list(aliases)
  657. while aliases:
  658. alias = aliases.pop(0)
  659. if self.alias_map[alias].join_type == self.LOUTER:
  660. self.alias_map[alias] = self.alias_map[alias]._replace(join_type=self.INNER)
  661. parent_alias = self.alias_map[alias].lhs_alias
  662. if self.alias_map[parent_alias].join_type == self.INNER:
  663. aliases.append(parent_alias)
  664. def reset_refcounts(self, to_counts):
  665. """
  666. This method will reset reference counts for aliases so that they match
  667. the value passed in :param to_counts:.
  668. """
  669. for alias, cur_refcount in self.alias_refcount.copy().items():
  670. unref_amount = cur_refcount - to_counts.get(alias, 0)
  671. self.unref_alias(alias, unref_amount)
  672. def change_aliases(self, change_map):
  673. """
  674. Changes the aliases in change_map (which maps old-alias -> new-alias),
  675. relabelling any references to them in select columns and the where
  676. clause.
  677. """
  678. assert set(change_map.keys()).intersection(set(change_map.values())) == set()
  679. def relabel_column(col):
  680. if isinstance(col, (list, tuple)):
  681. old_alias = col[0]
  682. return (change_map.get(old_alias, old_alias), col[1])
  683. else:
  684. return col.relabeled_clone(change_map)
  685. # 1. Update references in "select" (normal columns plus aliases),
  686. # "group by", "where" and "having".
  687. self.where.relabel_aliases(change_map)
  688. self.having.relabel_aliases(change_map)
  689. if self.group_by:
  690. self.group_by = [relabel_column(col) for col in self.group_by]
  691. self.select = [SelectInfo(relabel_column(s.col), s.field)
  692. for s in self.select]
  693. if self._aggregates:
  694. self._aggregates = OrderedDict(
  695. (key, relabel_column(col)) for key, col in self._aggregates.items())
  696. # 2. Rename the alias in the internal table/alias datastructures.
  697. for ident, aliases in self.join_map.items():
  698. del self.join_map[ident]
  699. aliases = tuple(change_map.get(a, a) for a in aliases)
  700. ident = (change_map.get(ident[0], ident[0]),) + ident[1:]
  701. self.join_map[ident] = aliases
  702. for old_alias, new_alias in six.iteritems(change_map):
  703. alias_data = self.alias_map[old_alias]
  704. alias_data = alias_data._replace(rhs_alias=new_alias)
  705. self.alias_refcount[new_alias] = self.alias_refcount[old_alias]
  706. del self.alias_refcount[old_alias]
  707. self.alias_map[new_alias] = alias_data
  708. del self.alias_map[old_alias]
  709. table_aliases = self.table_map[alias_data.table_name]
  710. for pos, alias in enumerate(table_aliases):
  711. if alias == old_alias:
  712. table_aliases[pos] = new_alias
  713. break
  714. for pos, alias in enumerate(self.tables):
  715. if alias == old_alias:
  716. self.tables[pos] = new_alias
  717. break
  718. for key, alias in self.included_inherited_models.items():
  719. if alias in change_map:
  720. self.included_inherited_models[key] = change_map[alias]
  721. # 3. Update any joins that refer to the old alias.
  722. for alias, data in six.iteritems(self.alias_map):
  723. lhs = data.lhs_alias
  724. if lhs in change_map:
  725. data = data._replace(lhs_alias=change_map[lhs])
  726. self.alias_map[alias] = data
  727. def bump_prefix(self, outer_query):
  728. """
  729. Changes the alias prefix to the next letter in the alphabet in a way
  730. that the outer query's aliases and this query's aliases will not
  731. conflict. Even tables that previously had no alias will get an alias
  732. after this call.
  733. """
  734. if self.alias_prefix != outer_query.alias_prefix:
  735. # No clashes between self and outer query should be possible.
  736. return
  737. self.alias_prefix = chr(ord(self.alias_prefix) + 1)
  738. while self.alias_prefix in self.subq_aliases:
  739. self.alias_prefix = chr(ord(self.alias_prefix) + 1)
  740. assert self.alias_prefix < 'Z'
  741. self.subq_aliases = self.subq_aliases.union([self.alias_prefix])
  742. outer_query.subq_aliases = outer_query.subq_aliases.union(self.subq_aliases)
  743. change_map = OrderedDict()
  744. for pos, alias in enumerate(self.tables):
  745. new_alias = '%s%d' % (self.alias_prefix, pos)
  746. change_map[alias] = new_alias
  747. self.tables[pos] = new_alias
  748. self.change_aliases(change_map)
  749. def get_initial_alias(self):
  750. """
  751. Returns the first alias for this query, after increasing its reference
  752. count.
  753. """
  754. if self.tables:
  755. alias = self.tables[0]
  756. self.ref_alias(alias)
  757. else:
  758. alias = self.join((None, self.get_meta().db_table, None))
  759. return alias
  760. def count_active_tables(self):
  761. """
  762. Returns the number of tables in this query with a non-zero reference
  763. count. Note that after execution, the reference counts are zeroed, so
  764. tables added in compiler will not be seen by this method.
  765. """
  766. return len([1 for count in self.alias_refcount.values() if count])
  767. def join(self, connection, reuse=None, nullable=False, join_field=None):
  768. """
  769. Returns an alias for the join in 'connection', either reusing an
  770. existing alias for that join or creating a new one. 'connection' is a
  771. tuple (lhs, table, join_cols) where 'lhs' is either an existing
  772. table alias or a table name. 'join_cols' is a tuple of tuples containing
  773. columns to join on ((l_id1, r_id1), (l_id2, r_id2)). The join corresponds
  774. to the SQL equivalent of::
  775. lhs.l_id1 = table.r_id1 AND lhs.l_id2 = table.r_id2
  776. The 'reuse' parameter can be either None which means all joins
  777. (matching the connection) are reusable, or it can be a set containing
  778. the aliases that can be reused.
  779. A join is always created as LOUTER if the lhs alias is LOUTER to make
  780. sure we do not generate chains like t1 LOUTER t2 INNER t3. All new
  781. joins are created as LOUTER if nullable is True.
  782. If 'nullable' is True, the join can potentially involve NULL values and
  783. is a candidate for promotion (to "left outer") when combining querysets.
  784. The 'join_field' is the field we are joining along (if any).
  785. """
  786. lhs, table, join_cols = connection
  787. assert lhs is None or join_field is not None
  788. existing = self.join_map.get(connection, ())
  789. if reuse is None:
  790. reuse = existing
  791. else:
  792. reuse = [a for a in existing if a in reuse]
  793. for alias in reuse:
  794. if join_field and self.alias_map[alias].join_field != join_field:
  795. # The join_map doesn't contain join_field (mainly because
  796. # fields in Query structs are problematic in pickling), so
  797. # check that the existing join is created using the same
  798. # join_field used for the under work join.
  799. continue
  800. self.ref_alias(alias)
  801. return alias
  802. # No reuse is possible, so we need a new alias.
  803. alias, _ = self.table_alias(table, create=True)
  804. if not lhs:
  805. # Not all tables need to be joined to anything. No join type
  806. # means the later columns are ignored.
  807. join_type = None
  808. elif self.alias_map[lhs].join_type == self.LOUTER or nullable:
  809. join_type = self.LOUTER
  810. else:
  811. join_type = self.INNER
  812. join = JoinInfo(table, alias, join_type, lhs, join_cols or ((None, None),), nullable,
  813. join_field)
  814. self.alias_map[alias] = join
  815. if connection in self.join_map:
  816. self.join_map[connection] += (alias,)
  817. else:
  818. self.join_map[connection] = (alias,)
  819. return alias
  820. def setup_inherited_models(self):
  821. """
  822. If the model that is the basis for this QuerySet inherits other models,
  823. we need to ensure that those other models have their tables included in
  824. the query.
  825. We do this as a separate step so that subclasses know which
  826. tables are going to be active in the query, without needing to compute
  827. all the select columns (this method is called from pre_sql_setup(),
  828. whereas column determination is a later part, and side-effect, of
  829. as_sql()).
  830. """
  831. opts = self.get_meta()
  832. root_alias = self.tables[0]
  833. seen = {None: root_alias}
  834. for field, model in opts.get_fields_with_model():
  835. if model not in seen:
  836. self.join_parent_model(opts, model, root_alias, seen)
  837. self.included_inherited_models = seen
  838. def join_parent_model(self, opts, model, alias, seen):
  839. """
  840. Makes sure the given 'model' is joined in the query. If 'model' isn't
  841. a parent of 'opts' or if it is None this method is a no-op.
  842. The 'alias' is the root alias for starting the join, 'seen' is a dict
  843. of model -> alias of existing joins. It must also contain a mapping
  844. of None -> some alias. This will be returned in the no-op case.
  845. """
  846. if model in seen:
  847. return seen[model]
  848. chain = opts.get_base_chain(model)
  849. if chain is None:
  850. return alias
  851. curr_opts = opts
  852. for int_model in chain:
  853. if int_model in seen:
  854. return seen[int_model]
  855. # Proxy model have elements in base chain
  856. # with no parents, assign the new options
  857. # object and skip to the next base in that
  858. # case
  859. if not curr_opts.parents[int_model]:
  860. curr_opts = int_model._meta
  861. continue
  862. link_field = curr_opts.get_ancestor_link(int_model)
  863. _, _, _, joins, _ = self.setup_joins(
  864. [link_field.name], curr_opts, alias)
  865. curr_opts = int_model._meta
  866. alias = seen[int_model] = joins[-1]
  867. return alias or seen[None]
  868. def remove_inherited_models(self):
  869. """
  870. Undoes the effects of setup_inherited_models(). Should be called
  871. whenever select columns (self.select) are set explicitly.
  872. """
  873. for key, alias in self.included_inherited_models.items():
  874. if key:
  875. self.unref_alias(alias)
  876. self.included_inherited_models = {}
  877. def add_aggregate(self, aggregate, model, alias, is_summary):
  878. """
  879. Adds a single aggregate expression to the Query
  880. """
  881. opts = model._meta
  882. field_list = aggregate.lookup.split(LOOKUP_SEP)
  883. if len(field_list) == 1 and self._aggregates and aggregate.lookup in self.aggregates:
  884. # Aggregate is over an annotation
  885. field_name = field_list[0]
  886. col = field_name
  887. source = self.aggregates[field_name]
  888. if not is_summary:
  889. raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (
  890. aggregate.name, field_name, field_name))
  891. elif ((len(field_list) > 1) or
  892. (field_list[0] not in [i.name for i in opts.fields]) or
  893. self.group_by is None or
  894. not is_summary):
  895. # If:
  896. # - the field descriptor has more than one part (foo__bar), or
  897. # - the field descriptor is referencing an m2m/m2o field, or
  898. # - this is a reference to a model field (possibly inherited), or
  899. # - this is an annotation over a model field
  900. # then we need to explore the joins that are required.
  901. # Join promotion note - we must not remove any rows here, so use
  902. # outer join if there isn't any existing join.
  903. _, sources, opts, join_list, path = self.setup_joins(
  904. field_list, opts, self.get_initial_alias())
  905. # Process the join chain to see if it can be trimmed
  906. targets, _, join_list = self.trim_joins(sources, join_list, path)
  907. col = targets[0].column
  908. source = sources[0]
  909. col = (join_list[-1], col)
  910. else:
  911. # The simplest cases. No joins required -
  912. # just reference the provided column alias.
  913. field_name = field_list[0]
  914. source = opts.get_field(field_name)
  915. col = field_name
  916. # We want to have the alias in SELECT clause even if mask is set.
  917. self.append_aggregate_mask([alias])
  918. # Add the aggregate to the query
  919. aggregate.add_to_query(self, alias, col=col, source=source, is_summary=is_summary)
  920. def prepare_lookup_value(self, value, lookups, can_reuse):
  921. # Default lookup if none given is exact.
  922. if len(lookups) == 0:
  923. lookups = ['exact']
  924. # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all
  925. # uses of None as a query value.
  926. if value is None:
  927. if lookups[-1] not in ('exact', 'iexact'):
  928. raise ValueError("Cannot use None as a query value")
  929. lookups[-1] = 'isnull'
  930. value = True
  931. elif callable(value):
  932. warnings.warn(
  933. "Passing callable arguments to queryset is deprecated.",
  934. RemovedInDjango19Warning, stacklevel=2)
  935. value = value()
  936. elif isinstance(value, ExpressionNode):
  937. # If value is a query expression, evaluate it
  938. value = SQLEvaluator(value, self, reuse=can_reuse)
  939. if hasattr(value, 'query') and hasattr(value.query, 'bump_prefix'):
  940. value = value._clone()
  941. value.query.bump_prefix(self)
  942. if hasattr(value, 'bump_prefix'):
  943. value = value.clone()
  944. value.bump_prefix(self)
  945. # For Oracle '' is equivalent to null. The check needs to be done
  946. # at this stage because join promotion can't be done at compiler
  947. # stage. Using DEFAULT_DB_ALIAS isn't nice, but it is the best we
  948. # can do here. Similar thing is done in is_nullable(), too.
  949. if (connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls and
  950. lookups[-1] == 'exact' and value == ''):
  951. value = True
  952. lookups[-1] = 'isnull'
  953. return value, lookups
  954. def solve_lookup_type(self, lookup):
  955. """
  956. Solve the lookup type from the lookup (eg: 'foobar__id__icontains')
  957. """
  958. lookup_splitted = lookup.split(LOOKUP_SEP)
  959. if self._aggregates:
  960. aggregate, aggregate_lookups = refs_aggregate(lookup_splitted, self.aggregates)
  961. if aggregate:
  962. return aggregate_lookups, (), aggregate
  963. _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  964. field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]
  965. if len(lookup_parts) == 0:
  966. lookup_parts = ['exact']
  967. elif len(lookup_parts) > 1:
  968. if not field_parts:
  969. raise FieldError(
  970. 'Invalid lookup "%s" for model %s".' %
  971. (lookup, self.get_meta().model.__name__))
  972. return lookup_parts, field_parts, False
  973. def check_query_object_type(self, value, opts):
  974. """
  975. Checks whether the object passed while querying is of the correct type.
  976. If not, it raises a ValueError specifying the wrong object.
  977. """
  978. if hasattr(value, '_meta'):
  979. if not (value._meta.concrete_model == opts.concrete_model
  980. or opts.concrete_model in value._meta.get_parent_list()
  981. or value._meta.concrete_model in opts.get_parent_list()):
  982. raise ValueError(
  983. 'Cannot query "%s": Must be "%s" instance.' %
  984. (value, opts.object_name))
  985. def check_related_objects(self, field, value, opts):
  986. """
  987. Checks the type of object passed to query relations.
  988. """
  989. if field.rel:
  990. # testing for iterable of models
  991. if hasattr(value, '__iter__'):
  992. # Check if the iterable has a model attribute, if so
  993. # it is likely something like a QuerySet.
  994. if hasattr(value, 'model') and hasattr(value.model, '_meta'):
  995. model = value.model
  996. if not (model == opts.concrete_model
  997. or opts.concrete_model in model._meta.get_parent_list()
  998. or model in opts.get_parent_list()):
  999. raise ValueError(
  1000. 'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' %
  1001. (model._meta.model_name, opts.object_name))
  1002. else:
  1003. for v in value:
  1004. self.check_query_object_type(v, opts)
  1005. else:
  1006. # expecting single model instance here
  1007. self.check_query_object_type(value, opts)
  1008. def build_lookup(self, lookups, lhs, rhs):
  1009. lookups = lookups[:]
  1010. while lookups:
  1011. lookup = lookups[0]
  1012. if len(lookups) == 1:
  1013. final_lookup = lhs.get_lookup(lookup)
  1014. if final_lookup:
  1015. return final_lookup(lhs, rhs)
  1016. # We didn't find a lookup, so we are going to try get_transform
  1017. # + get_lookup('exact').
  1018. lookups.append('exact')
  1019. next = lhs.get_transform(lookup)
  1020. if next:
  1021. lhs = next(lhs, lookups)
  1022. else:
  1023. raise FieldError(
  1024. "Unsupported lookup '%s' for %s or join on the field not "
  1025. "permitted." %
  1026. (lookup, lhs.output_field.__class__.__name__))
  1027. lookups = lookups[1:]
  1028. def build_filter(self, filter_expr, branch_negated=False, current_negated=False,
  1029. can_reuse=None, connector=AND):
  1030. """
  1031. Builds a WhereNode for a single filter clause, but doesn't add it
  1032. to this Query. Query.add_q() will then add this filter to the where
  1033. or having Node.
  1034. The 'branch_negated' tells us if the current branch contains any
  1035. negations. This will be used to determine if subqueries are needed.
  1036. The 'current_negated' is used to determine if the current filter is
  1037. negated or not and this will be used to determine if IS NULL filtering
  1038. is needed.
  1039. The difference between current_netageted and branch_negated is that
  1040. branch_negated is set on first negation, but current_negated is
  1041. flipped for each negation.
  1042. Note that add_filter will not do any negating itself, that is done
  1043. upper in the code by add_q().
  1044. The 'can_reuse' is a set of reusable joins for multijoins.
  1045. The method will create a filter clause that can be added to the current
  1046. query. However, if the filter isn't added to the query then the caller
  1047. is responsible for unreffing the joins used.
  1048. """
  1049. arg, value = filter_expr
  1050. if not arg:
  1051. raise FieldError("Cannot parse keyword query %r" % arg)
  1052. lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
  1053. # Work out the lookup type and remove it from the end of 'parts',
  1054. # if necessary.
  1055. value, lookups = self.prepare_lookup_value(value, lookups, can_reuse)
  1056. used_joins = getattr(value, '_used_joins', [])
  1057. clause = self.where_class()
  1058. if reffed_aggregate:
  1059. condition = self.build_lookup(lookups, reffed_aggregate, value)
  1060. if not condition:
  1061. # Backwards compat for custom lookups
  1062. assert len(lookups) == 1
  1063. condition = (reffed_aggregate, lookups[0], value)
  1064. clause.add(condition, AND)
  1065. return clause, []
  1066. opts = self.get_meta()
  1067. alias = self.get_initial_alias()
  1068. allow_many = not branch_negated
  1069. try:
  1070. field, sources, opts, join_list, path = self.setup_joins(
  1071. parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many)
  1072. self.check_related_objects(field, value, opts)
  1073. # split_exclude() needs to know which joins were generated for the
  1074. # lookup parts
  1075. self._lookup_joins = join_list
  1076. except MultiJoin as e:
  1077. return self.split_exclude(filter_expr, LOOKUP_SEP.join(parts[:e.level]),
  1078. can_reuse, e.names_with_path)
  1079. if can_reuse is not None:
  1080. can_reuse.update(join_list)
  1081. used_joins = set(used_joins).union(set(join_list))
  1082. # Process the join list to see if we can remove any non-needed joins from
  1083. # the far end (fewer tables in a query is better).
  1084. targets, alias, join_list = self.trim_joins(sources, join_list, path)
  1085. if hasattr(field, 'get_lookup_constraint'):
  1086. # For now foreign keys get special treatment. This should be
  1087. # refactored when composite fields lands.
  1088. condition = field.get_lookup_constraint(self.where_class, alias, targets, sources,
  1089. lookups, value)
  1090. lookup_type = lookups[-1]
  1091. else:
  1092. assert(len(targets) == 1)
  1093. col = Col(alias, targets[0], field)
  1094. condition = self.build_lookup(lookups, col, value)
  1095. if not condition:
  1096. # Backwards compat for custom lookups
  1097. if lookups[0] not in self.query_terms:
  1098. raise FieldError(
  1099. "Join on field '%s' not permitted. Did you "
  1100. "misspell '%s' for the lookup type?" %
  1101. (col.output_field.name, lookups[0]))
  1102. if len(lookups) > 1:
  1103. raise FieldError("Nested lookup '%s' not supported." %
  1104. LOOKUP_SEP.join(lookups))
  1105. condition = (Constraint(alias, targets[0].column, field), lookups[0], value)
  1106. lookup_type = lookups[-1]
  1107. else:
  1108. lookup_type = condition.lookup_name
  1109. clause.add(condition, AND)
  1110. require_outer = lookup_type == 'isnull' and value is True and not current_negated
  1111. if current_negated and (lookup_type != 'isnull' or value is False):
  1112. require_outer = True
  1113. if (lookup_type != 'isnull' and (
  1114. self.is_nullable(targets[0]) or
  1115. self.alias_map[join_list[-1]].join_type == self.LOUTER)):
  1116. # The condition added here will be SQL like this:
  1117. # NOT (col IS NOT NULL), where the first NOT is added in
  1118. # upper layers of code. The reason for addition is that if col
  1119. # is null, then col != someval will result in SQL "unknown"
  1120. # which isn't the same as in Python. The Python None handling
  1121. # is wanted, and it can be gotten by
  1122. # (col IS NULL OR col != someval)
  1123. # <=>
  1124. # NOT (col IS NOT NULL AND col = someval).
  1125. lookup_class = targets[0].get_lookup('isnull')
  1126. clause.add(lookup_class(Col(alias, targets[0], sources[0]), False), AND)
  1127. return clause, used_joins if not require_outer else ()
  1128. def add_filter(self, filter_clause):
  1129. self.add_q(Q(**{filter_clause[0]: filter_clause[1]}))
  1130. def need_having(self, obj):
  1131. """
  1132. Returns whether or not all elements of this q_object need to be put
  1133. together in the HAVING clause.
  1134. """
  1135. if not self._aggregates:
  1136. return False
  1137. if not isinstance(obj, Node):
  1138. return (refs_aggregate(obj[0].split(LOOKUP_SEP), self.aggregates)[0]
  1139. or (hasattr(obj[1], 'contains_aggregate')
  1140. and obj[1].contains_aggregate(self.aggregates)))
  1141. return any(self.need_having(c) for c in obj.children)
  1142. def split_having_parts(self, q_object, negated=False):
  1143. """
  1144. Returns a list of q_objects which need to go into the having clause
  1145. instead of the where clause. Removes the splitted out nodes from the
  1146. given q_object. Note that the q_object is altered, so cloning it is
  1147. needed.
  1148. """
  1149. having_parts = []
  1150. for c in q_object.children[:]:
  1151. # When constructing the having nodes we need to take care to
  1152. # preserve the negation status from the upper parts of the tree
  1153. if isinstance(c, Node):
  1154. # For each negated child, flip the in_negated flag.
  1155. in_negated = c.negated ^ negated
  1156. if c.connector == OR and self.need_having(c):
  1157. # A subtree starting from OR clause must go into having in
  1158. # whole if any part of that tree references an aggregate.
  1159. q_object.children.remove(c)
  1160. having_parts.append(c)
  1161. c.negated = in_negated
  1162. else:
  1163. having_parts.extend(
  1164. self.split_having_parts(c, in_negated)[1])
  1165. elif self.need_having(c):
  1166. q_object.children.remove(c)
  1167. new_q = self.where_class(children=[c], negated=negated)
  1168. having_parts.append(new_q)
  1169. return q_object, having_parts
  1170. def add_q(self, q_object):
  1171. """
  1172. A preprocessor for the internal _add_q(). Responsible for
  1173. splitting the given q_object into where and having parts and
  1174. setting up some internal variables.
  1175. """
  1176. if not self.need_having(q_object):
  1177. where_part, having_parts = q_object, []
  1178. else:
  1179. where_part, having_parts = self.split_having_parts(
  1180. q_object.clone(), q_object.negated)
  1181. # For join promotion this case is doing an AND for the added q_object
  1182. # and existing conditions. So, any existing inner join forces the join
  1183. # type to remain inner. Existing outer joins can however be demoted.
  1184. # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if
  1185. # rel_a doesn't produce any rows, then the whole condition must fail.
  1186. # So, demotion is OK.
  1187. existing_inner = set(
  1188. (a for a in self.alias_map if self.alias_map[a].join_type == self.INNER))
  1189. clause, require_inner = self._add_q(where_part, self.used_aliases)
  1190. self.where.add(clause, AND)
  1191. for hp in having_parts:
  1192. clause, _ = self._add_q(hp, self.used_aliases)
  1193. self.having.add(clause, AND)
  1194. self.demote_joins(existing_inner)
  1195. def _add_q(self, q_object, used_aliases, branch_negated=False,
  1196. current_negated=False):
  1197. """
  1198. Adds a Q-object to the current filter.
  1199. """
  1200. connector = q_object.connector
  1201. current_negated = current_negated ^ q_object.negated
  1202. branch_negated = branch_negated or q_object.negated
  1203. target_clause = self.where_class(connector=connector,
  1204. negated=q_object.negated)
  1205. joinpromoter = JoinPromoter(q_object.connector, len(q_object.children), current_negated)
  1206. for child in q_object.children:
  1207. if isinstance(child, Node):
  1208. child_clause, needed_inner = self._add_q(
  1209. child, used_aliases, branch_negated,
  1210. current_negated)
  1211. joinpromoter.add_votes(needed_inner)
  1212. else:
  1213. child_clause, needed_inner = self.build_filter(
  1214. child, can_reuse=used_aliases, branch_negated=branch_negated,
  1215. current_negated=current_negated, connector=connector)
  1216. joinpromoter.add_votes(needed_inner)
  1217. target_clause.add(child_clause, connector)
  1218. needed_inner = joinpromoter.update_join_types(self)
  1219. return target_clause, needed_inner
  1220. def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):
  1221. """
  1222. Walks the names path and turns them PathInfo tuples. Note that a
  1223. single name in 'names' can generate multiple PathInfos (m2m for
  1224. example).
  1225. 'names' is the path of names to travel, 'opts' is the model Options we
  1226. start the name resolving from, 'allow_many' is as for setup_joins().
  1227. Returns a list of PathInfo tuples. In addition returns the final field
  1228. (the last used join field), and target (which is a field guaranteed to
  1229. contain the same value as the final field).
  1230. """
  1231. path, names_with_path = [], []
  1232. for pos, name in enumerate(names):
  1233. cur_names_with_path = (name, [])
  1234. if name == 'pk':
  1235. name = opts.pk.name
  1236. try:
  1237. field, model, direct, m2m = opts.get_field_by_name(name)
  1238. except FieldDoesNotExist:
  1239. # We didn't find the current field, so move position back
  1240. # one step.
  1241. pos -= 1
  1242. if pos == -1 or fail_on_missing:
  1243. available = opts.get_all_field_names() + list(self.aggregate_select)
  1244. raise FieldError("Cannot resolve keyword %r into field. "
  1245. "Choices are: %s" % (name, ", ".join(available)))
  1246. break
  1247. # Check if we need any joins for concrete inheritance cases (the
  1248. # field lives in parent, but we are currently in one of its
  1249. # children)
  1250. if model:
  1251. # The field lives on a base class of the current model.
  1252. # Skip the chain of proxy to the concrete proxied model
  1253. proxied_model = opts.concrete_model
  1254. for int_model in opts.get_base_chain(model):
  1255. if int_model is proxied_model:
  1256. opts = int_model._meta
  1257. else:
  1258. final_field = opts.parents[int_model]
  1259. targets = (final_field.rel.get_related_field(),)
  1260. opts = int_model._meta
  1261. path.append(PathInfo(final_field.model._meta, opts, targets, final_field, False, True))
  1262. cur_names_with_path[1].append(
  1263. PathInfo(final_field.model._meta, opts, targets, final_field, False, True)
  1264. )
  1265. if hasattr(field, 'get_path_info'):
  1266. pathinfos = field.get_path_info()
  1267. if not allow_many:
  1268. for inner_pos, p in enumerate(pathinfos):
  1269. if p.m2m:
  1270. cur_names_with_path[1].extend(pathinfos[0:inner_pos + 1])
  1271. names_with_path.append(cur_names_with_path)
  1272. raise MultiJoin(pos + 1, names_with_path)
  1273. last = pathinfos[-1]
  1274. path.extend(pathinfos)
  1275. final_field = last.join_field
  1276. opts = last.to_opts
  1277. targets = last.target_fields
  1278. cur_names_with_path[1].extend(pathinfos)
  1279. names_with_path.append(cur_names_with_path)
  1280. else:
  1281. # Local non-relational field.
  1282. final_field = field
  1283. targets = (field,)
  1284. if fail_on_missing and pos + 1 != len(names):
  1285. raise FieldError(
  1286. "Cannot resolve keyword %r into field. Join on '%s'"
  1287. " not permitted." % (names[pos + 1], name))
  1288. break
  1289. return path, final_field, targets, names[pos + 1:]
  1290. def setup_joins(self, names, opts, alias, can_reuse=None, allow_many=True):
  1291. """
  1292. Compute the necessary table joins for the passage through the fields
  1293. given in 'names'. 'opts' is the Options class for the current model
  1294. (which gives the table we are starting from), 'alias' is the alias for
  1295. the table to start the joining from.
  1296. The 'can_reuse' defines the reverse foreign key joins we can reuse. It
  1297. can be None in which case all joins are reusable or a set of aliases
  1298. that can be reused. Note that non-reverse foreign keys are always
  1299. reusable when using setup_joins().
  1300. If 'allow_many' is False, then any reverse foreign key seen will
  1301. generate a MultiJoin exception.
  1302. Returns the final field involved in the joins, the target field (used
  1303. for any 'where' constraint), the final 'opts' value, the joins and the
  1304. field path travelled to generate the joins.
  1305. The target field is the field containing the concrete value. Final
  1306. field can be something different, for example foreign key pointing to
  1307. that value. Final field is needed for example in some value
  1308. conversions (convert 'obj' in fk__id=obj to pk val using the foreign
  1309. key field for example).
  1310. """
  1311. joins = [alias]
  1312. # First, generate the path for the names
  1313. path, final_field, targets, rest = self.names_to_path(
  1314. names, opts, allow_many, fail_on_missing=True)
  1315. # Then, add the path to the query's joins. Note that we can't trim
  1316. # joins at this stage - we will need the information about join type
  1317. # of the trimmed joins.
  1318. for pos, join in enumerate(path):
  1319. opts = join.to_opts
  1320. if join.direct:
  1321. nullable = self.is_nullable(join.join_field)
  1322. else:
  1323. nullable = True
  1324. connection = alias, opts.db_table, join.join_field.get_joining_columns()
  1325. reuse = can_reuse if join.m2m else None
  1326. alias = self.join(
  1327. connection, reuse=reuse, nullable=nullable, join_field=join.join_field)
  1328. joins.append(alias)
  1329. if hasattr(final_field, 'field'):
  1330. final_field = final_field.field
  1331. return final_field, targets, opts, joins, path
  1332. def trim_joins(self, targets, joins, path):
  1333. """
  1334. The 'target' parameter is the final field being joined to, 'joins'
  1335. is the full list of join aliases. The 'path' contain the PathInfos
  1336. used to create the joins.
  1337. Returns the final target field and table alias and the new active
  1338. joins.
  1339. We will always trim any direct join if we have the target column
  1340. available already in the previous table. Reverse joins can't be
  1341. trimmed as we don't know if there is anything on the other side of
  1342. the join.
  1343. """
  1344. joins = joins[:]
  1345. for pos, info in enumerate(reversed(path)):
  1346. if len(joins) == 1 or not info.direct:
  1347. break
  1348. join_targets = set(t.column for t in info.join_field.foreign_related_fields)
  1349. cur_targets = set(t.column for t in targets)
  1350. if not cur_targets.issubset(join_targets):
  1351. break
  1352. targets = tuple(r[0] for r in info.join_field.related_fields if r[1].column in cur_targets)
  1353. self.unref_alias(joins.pop())
  1354. return targets, joins[-1], joins
  1355. def split_exclude(self, filter_expr, prefix, can_reuse, names_with_path):
  1356. """
  1357. When doing an exclude against any kind of N-to-many relation, we need
  1358. to use a subquery. This method constructs the nested query, given the
  1359. original exclude filter (filter_expr) and the portion up to the first
  1360. N-to-many relation field.
  1361. As an example we could have original filter ~Q(child__name='foo').
  1362. We would get here with filter_expr = child__name, prefix = child and
  1363. can_reuse is a set of joins usable for filters in the original query.
  1364. We will turn this into equivalent of:
  1365. WHERE NOT (pk IN (SELECT parent_id FROM thetable
  1366. WHERE name = 'foo' AND parent_id IS NOT NULL))
  1367. It might be worth it to consider using WHERE NOT EXISTS as that has
  1368. saner null handling, and is easier for the backend's optimizer to
  1369. handle.
  1370. """
  1371. # Generate the inner query.
  1372. query = Query(self.model)
  1373. query.add_filter(filter_expr)
  1374. query.clear_ordering(True)
  1375. # Try to have as simple as possible subquery -> trim leading joins from
  1376. # the subquery.
  1377. trimmed_prefix, contains_louter = query.trim_start(names_with_path)
  1378. query.remove_inherited_models()
  1379. # Add extra check to make sure the selected field will not be null
  1380. # since we are adding an IN <subquery> clause. This prevents the
  1381. # database from tripping over IN (...,NULL,...) selects and returning
  1382. # nothing
  1383. alias, col = query.select[0].col
  1384. if self.is_nullable(query.select[0].field):
  1385. lookup_class = query.select[0].field.get_lookup('isnull')
  1386. lookup = lookup_class(Col(alias, query.select[0].field, query.select[0].field), False)
  1387. query.where.add(lookup, AND)
  1388. if alias in can_reuse:
  1389. select_field = query.select[0].field
  1390. pk = select_field.model._meta.pk
  1391. # Need to add a restriction so that outer query's filters are in effect for
  1392. # the subquery, too.
  1393. query.bump_prefix(self)
  1394. lookup_class = select_field.get_lookup('exact')
  1395. lookup = lookup_class(Col(query.select[0].col[0], pk, pk),
  1396. Col(alias, pk, pk))
  1397. query.where.add(lookup, AND)
  1398. condition, needed_inner = self.build_filter(
  1399. ('%s__in' % trimmed_prefix, query),
  1400. current_negated=True, branch_negated=True, can_reuse=can_reuse)
  1401. if contains_louter:
  1402. or_null_condition, _ = self.build_filter(
  1403. ('%s__isnull' % trimmed_prefix, True),
  1404. current_negated=True, branch_negated=True, can_reuse=can_reuse)
  1405. condition.add(or_null_condition, OR)
  1406. # Note that the end result will be:
  1407. # (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL.
  1408. # This might look crazy but due to how IN works, this seems to be
  1409. # correct. If the IS NOT NULL check is removed then outercol NOT
  1410. # IN will return UNKNOWN. If the IS NULL check is removed, then if
  1411. # outercol IS NULL we will not match the row.
  1412. return condition, needed_inner
  1413. def set_empty(self):
  1414. self.where = EmptyWhere()
  1415. self.having = EmptyWhere()
  1416. def is_empty(self):
  1417. return isinstance(self.where, EmptyWhere) or isinstance(self.having, EmptyWhere)
  1418. def set_limits(self, low=None, high=None):
  1419. """
  1420. Adjusts the limits on the rows retrieved. We use low/high to set these,
  1421. as it makes it more Pythonic to read and write. When the SQL query is
  1422. created, they are converted to the appropriate offset and limit values.
  1423. Any limits passed in here are applied relative to the existing
  1424. constraints. So low is added to the current low value and both will be
  1425. clamped to any existing high value.
  1426. """
  1427. if high is not None:
  1428. if self.high_mark is not None:
  1429. self.high_mark = min(self.high_mark, self.low_mark + high)
  1430. else:
  1431. self.high_mark = self.low_mark + high
  1432. if low is not None:
  1433. if self.high_mark is not None:
  1434. self.low_mark = min(self.high_mark, self.low_mark + low)
  1435. else:
  1436. self.low_mark = self.low_mark + low
  1437. def clear_limits(self):
  1438. """
  1439. Clears any existing limits.
  1440. """
  1441. self.low_mark, self.high_mark = 0, None
  1442. def can_filter(self):
  1443. """
  1444. Returns True if adding filters to this instance is still possible.
  1445. Typically, this means no limits or offsets have been put on the results.
  1446. """
  1447. return not self.low_mark and self.high_mark is None
  1448. def clear_select_clause(self):
  1449. """
  1450. Removes all fields from SELECT clause.
  1451. """
  1452. self.select = []
  1453. self.default_cols = False
  1454. self.select_related = False
  1455. self.set_extra_mask(())
  1456. self.set_aggregate_mask(())
  1457. def clear_select_fields(self):
  1458. """
  1459. Clears the list of fields to select (but not extra_select columns).
  1460. Some queryset types completely replace any existing list of select
  1461. columns.
  1462. """
  1463. self.select = []
  1464. def add_distinct_fields(self, *field_names):
  1465. """
  1466. Adds and resolves the given fields to the query's "distinct on" clause.
  1467. """
  1468. self.distinct_fields = field_names
  1469. self.distinct = True
  1470. def add_fields(self, field_names, allow_m2m=True):
  1471. """
  1472. Adds the given (model) fields to the select set. The field names are
  1473. added in the order specified.
  1474. """
  1475. alias = self.get_initial_alias()
  1476. opts = self.get_meta()
  1477. try:
  1478. for name in field_names:
  1479. # Join promotion note - we must not remove any rows here, so
  1480. # if there is no existing joins, use outer join.
  1481. _, targets, _, joins, path = self.setup_joins(
  1482. name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m)
  1483. targets, final_alias, joins = self.trim_joins(targets, joins, path)
  1484. for target in targets:
  1485. self.select.append(SelectInfo((final_alias, target.column), target))
  1486. except MultiJoin:
  1487. raise FieldError("Invalid field name: '%s'" % name)
  1488. except FieldError:
  1489. if LOOKUP_SEP in name:
  1490. # For lookups spanning over relationships, show the error
  1491. # from the model on which the lookup failed.
  1492. raise
  1493. else:
  1494. names = sorted(opts.get_all_field_names() + list(self.extra)
  1495. + list(self.aggregate_select))
  1496. raise FieldError("Cannot resolve keyword %r into field. "
  1497. "Choices are: %s" % (name, ", ".join(names)))
  1498. self.remove_inherited_models()
  1499. def add_ordering(self, *ordering):
  1500. """
  1501. Adds items from the 'ordering' sequence to the query's "order by"
  1502. clause. These items are either field names (not column names) --
  1503. possibly with a direction prefix ('-' or '?') -- or ordinals,
  1504. corresponding to column positions in the 'select' list.
  1505. If 'ordering' is empty, all ordering is cleared from the query.
  1506. """
  1507. errors = []
  1508. for item in ordering:
  1509. if not ORDER_PATTERN.match(item):
  1510. errors.append(item)
  1511. if errors:
  1512. raise FieldError('Invalid order_by arguments: %s' % errors)
  1513. if ordering:
  1514. self.order_by.extend(ordering)
  1515. else:
  1516. self.default_ordering = False
  1517. def clear_ordering(self, force_empty):
  1518. """
  1519. Removes any ordering settings. If 'force_empty' is True, there will be
  1520. no ordering in the resulting query (not even the model's default).
  1521. """
  1522. self.order_by = []
  1523. self.extra_order_by = ()
  1524. if force_empty:
  1525. self.default_ordering = False
  1526. def set_group_by(self):
  1527. """
  1528. Expands the GROUP BY clause required by the query.
  1529. This will usually be the set of all non-aggregate fields in the
  1530. return data. If the database backend supports grouping by the
  1531. primary key, and the query would be equivalent, the optimization
  1532. will be made automatically.
  1533. """
  1534. self.group_by = []
  1535. for col, _ in self.select:
  1536. self.group_by.append(col)
  1537. def add_count_column(self):
  1538. """
  1539. Converts the query to do count(...) or count(distinct(pk)) in order to
  1540. get its size.
  1541. """
  1542. if not self.distinct:
  1543. if not self.select:
  1544. count = self.aggregates_module.Count('*', is_summary=True)
  1545. else:
  1546. assert len(self.select) == 1, \
  1547. "Cannot add count col with multiple cols in 'select': %r" % self.select
  1548. count = self.aggregates_module.Count(self.select[0].col)
  1549. else:
  1550. opts = self.get_meta()
  1551. if not self.select:
  1552. count = self.aggregates_module.Count(
  1553. (self.join((None, opts.db_table, None)), opts.pk.column),
  1554. is_summary=True, distinct=True)
  1555. else:
  1556. # Because of SQL portability issues, multi-column, distinct
  1557. # counts need a sub-query -- see get_count() for details.
  1558. assert len(self.select) == 1, \
  1559. "Cannot add count col with multiple cols in 'select'."
  1560. count = self.aggregates_module.Count(self.select[0].col, distinct=True)
  1561. # Distinct handling is done in Count(), so don't do it at this
  1562. # level.
  1563. self.distinct = False
  1564. # Set only aggregate to be the count column.
  1565. # Clear out the select cache to reflect the new unmasked aggregates.
  1566. self._aggregates = {None: count}
  1567. self.set_aggregate_mask(None)
  1568. self.group_by = None
  1569. def add_select_related(self, fields):
  1570. """
  1571. Sets up the select_related data structure so that we only select
  1572. certain related models (as opposed to all models, when
  1573. self.select_related=True).
  1574. """
  1575. if isinstance(self.select_related, bool):
  1576. field_dict = {}
  1577. else:
  1578. field_dict = self.select_related
  1579. for field in fields:
  1580. d = field_dict
  1581. for part in field.split(LOOKUP_SEP):
  1582. d = d.setdefault(part, {})
  1583. self.select_related = field_dict
  1584. self.related_select_cols = []
  1585. def add_extra(self, select, select_params, where, params, tables, order_by):
  1586. """
  1587. Adds data to the various extra_* attributes for user-created additions
  1588. to the query.
  1589. """
  1590. if select:
  1591. # We need to pair any placeholder markers in the 'select'
  1592. # dictionary with their parameters in 'select_params' so that
  1593. # subsequent updates to the select dictionary also adjust the
  1594. # parameters appropriately.
  1595. select_pairs = OrderedDict()
  1596. if select_params:
  1597. param_iter = iter(select_params)
  1598. else:
  1599. param_iter = iter([])
  1600. for name, entry in select.items():
  1601. entry = force_text(entry)
  1602. entry_params = []
  1603. pos = entry.find("%s")
  1604. while pos != -1:
  1605. if pos == 0 or entry[pos - 1] != '%':
  1606. entry_params.append(next(param_iter))
  1607. pos = entry.find("%s", pos + 2)
  1608. select_pairs[name] = (entry, entry_params)
  1609. # This is order preserving, since self.extra_select is an OrderedDict.
  1610. self.extra.update(select_pairs)
  1611. if where or params:
  1612. self.where.add(ExtraWhere(where, params), AND)
  1613. if tables:
  1614. self.extra_tables += tuple(tables)
  1615. if order_by:
  1616. self.extra_order_by = order_by
  1617. def clear_deferred_loading(self):
  1618. """
  1619. Remove any fields from the deferred loading set.
  1620. """
  1621. self.deferred_loading = (set(), True)
  1622. def add_deferred_loading(self, field_names):
  1623. """
  1624. Add the given list of model field names to the set of fields to
  1625. exclude from loading from the database when automatic column selection
  1626. is done. The new field names are added to any existing field names that
  1627. are deferred (or removed from any existing field names that are marked
  1628. as the only ones for immediate loading).
  1629. """
  1630. # Fields on related models are stored in the literal double-underscore
  1631. # format, so that we can use a set datastructure. We do the foo__bar
  1632. # splitting and handling when computing the SQL column names (as part of
  1633. # get_columns()).
  1634. existing, defer = self.deferred_loading
  1635. if defer:
  1636. # Add to existing deferred names.
  1637. self.deferred_loading = existing.union(field_names), True
  1638. else:
  1639. # Remove names from the set of any existing "immediate load" names.
  1640. self.deferred_loading = existing.difference(field_names), False
  1641. def add_immediate_loading(self, field_names):
  1642. """
  1643. Add the given list of model field names to the set of fields to
  1644. retrieve when the SQL is executed ("immediate loading" fields). The
  1645. field names replace any existing immediate loading field names. If
  1646. there are field names already specified for deferred loading, those
  1647. names are removed from the new field_names before storing the new names
  1648. for immediate loading. (That is, immediate loading overrides any
  1649. existing immediate values, but respects existing deferrals.)
  1650. """
  1651. existing, defer = self.deferred_loading
  1652. field_names = set(field_names)
  1653. if 'pk' in field_names:
  1654. field_names.remove('pk')
  1655. field_names.add(self.get_meta().pk.name)
  1656. if defer:
  1657. # Remove any existing deferred names from the current set before
  1658. # setting the new names.
  1659. self.deferred_loading = field_names.difference(existing), False
  1660. else:
  1661. # Replace any existing "immediate load" field names.
  1662. self.deferred_loading = field_names, False
  1663. def get_loaded_field_names(self):
  1664. """
  1665. If any fields are marked to be deferred, returns a dictionary mapping
  1666. models to a set of names in those fields that will be loaded. If a
  1667. model is not in the returned dictionary, none of its fields are
  1668. deferred.
  1669. If no fields are marked for deferral, returns an empty dictionary.
  1670. """
  1671. # We cache this because we call this function multiple times
  1672. # (compiler.fill_related_selections, query.iterator)
  1673. try:
  1674. return self._loaded_field_names_cache
  1675. except AttributeError:
  1676. collection = {}
  1677. self.deferred_to_data(collection, self.get_loaded_field_names_cb)
  1678. self._loaded_field_names_cache = collection
  1679. return collection
  1680. def get_loaded_field_names_cb(self, target, model, fields):
  1681. """
  1682. Callback used by get_deferred_field_names().
  1683. """
  1684. target[model] = set(f.name for f in fields)
  1685. def set_aggregate_mask(self, names):
  1686. "Set the mask of aggregates that will actually be returned by the SELECT"
  1687. if names is None:
  1688. self.aggregate_select_mask = None
  1689. else:
  1690. self.aggregate_select_mask = set(names)
  1691. self._aggregate_select_cache = None
  1692. def append_aggregate_mask(self, names):
  1693. if self.aggregate_select_mask is not None:
  1694. self.set_aggregate_mask(set(names).union(self.aggregate_select_mask))
  1695. def set_extra_mask(self, names):
  1696. """
  1697. Set the mask of extra select items that will be returned by SELECT,
  1698. we don't actually remove them from the Query since they might be used
  1699. later
  1700. """
  1701. if names is None:
  1702. self.extra_select_mask = None
  1703. else:
  1704. self.extra_select_mask = set(names)
  1705. self._extra_select_cache = None
  1706. @property
  1707. def aggregate_select(self):
  1708. """The OrderedDict of aggregate columns that are not masked, and should
  1709. be used in the SELECT clause.
  1710. This result is cached for optimization purposes.
  1711. """
  1712. if self._aggregate_select_cache is not None:
  1713. return self._aggregate_select_cache
  1714. elif not self._aggregates:
  1715. return {}
  1716. elif self.aggregate_select_mask is not None:
  1717. self._aggregate_select_cache = OrderedDict(
  1718. (k, v) for k, v in self.aggregates.items()
  1719. if k in self.aggregate_select_mask
  1720. )
  1721. return self._aggregate_select_cache
  1722. else:
  1723. return self.aggregates
  1724. @property
  1725. def extra_select(self):
  1726. if self._extra_select_cache is not None:
  1727. return self._extra_select_cache
  1728. if not self._extra:
  1729. return {}
  1730. elif self.extra_select_mask is not None:
  1731. self._extra_select_cache = OrderedDict(
  1732. (k, v) for k, v in self.extra.items()
  1733. if k in self.extra_select_mask
  1734. )
  1735. return self._extra_select_cache
  1736. else:
  1737. return self.extra
  1738. def trim_start(self, names_with_path):
  1739. """
  1740. Trims joins from the start of the join path. The candidates for trim
  1741. are the PathInfos in names_with_path structure that are m2m joins.
  1742. Also sets the select column so the start matches the join.
  1743. This method is meant to be used for generating the subquery joins &
  1744. cols in split_exclude().
  1745. Returns a lookup usable for doing outerq.filter(lookup=self). Returns
  1746. also if the joins in the prefix contain a LEFT OUTER join.
  1747. _"""
  1748. all_paths = []
  1749. for _, paths in names_with_path:
  1750. all_paths.extend(paths)
  1751. contains_louter = False
  1752. # Trim and operate only on tables that were generated for
  1753. # the lookup part of the query. That is, avoid trimming
  1754. # joins generated for F() expressions.
  1755. lookup_tables = [t for t in self.tables if t in self._lookup_joins or t == self.tables[0]]
  1756. for trimmed_paths, path in enumerate(all_paths):
  1757. if path.m2m:
  1758. break
  1759. if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == self.LOUTER:
  1760. contains_louter = True
  1761. self.unref_alias(lookup_tables[trimmed_paths])
  1762. # The path.join_field is a Rel, lets get the other side's field
  1763. join_field = path.join_field.field
  1764. # Build the filter prefix.
  1765. paths_in_prefix = trimmed_paths
  1766. trimmed_prefix = []
  1767. for name, path in names_with_path:
  1768. if paths_in_prefix - len(path) < 0:
  1769. break
  1770. trimmed_prefix.append(name)
  1771. paths_in_prefix -= len(path)
  1772. trimmed_prefix.append(
  1773. join_field.foreign_related_fields[0].name)
  1774. trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix)
  1775. # Lets still see if we can trim the first join from the inner query
  1776. # (that is, self). We can't do this for LEFT JOINs because we would
  1777. # miss those rows that have nothing on the outer side.
  1778. if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type != self.LOUTER:
  1779. select_fields = [r[0] for r in join_field.related_fields]
  1780. select_alias = lookup_tables[trimmed_paths + 1]
  1781. self.unref_alias(lookup_tables[trimmed_paths])
  1782. extra_restriction = join_field.get_extra_restriction(
  1783. self.where_class, None, lookup_tables[trimmed_paths + 1])
  1784. if extra_restriction:
  1785. self.where.add(extra_restriction, AND)
  1786. else:
  1787. # TODO: It might be possible to trim more joins from the start of the
  1788. # inner query if it happens to have a longer join chain containing the
  1789. # values in select_fields. Lets punt this one for now.
  1790. select_fields = [r[1] for r in join_field.related_fields]
  1791. select_alias = lookup_tables[trimmed_paths]
  1792. self.select = [SelectInfo((select_alias, f.column), f) for f in select_fields]
  1793. return trimmed_prefix, contains_louter
  1794. def is_nullable(self, field):
  1795. """
  1796. A helper to check if the given field should be treated as nullable.
  1797. Some backends treat '' as null and Django treats such fields as
  1798. nullable for those backends. In such situations field.null can be
  1799. False even if we should treat the field as nullable.
  1800. """
  1801. # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have
  1802. # (nor should it have) knowledge of which connection is going to be
  1803. # used. The proper fix would be to defer all decisions where
  1804. # is_nullable() is needed to the compiler stage, but that is not easy
  1805. # to do currently.
  1806. if ((connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls)
  1807. and field.empty_strings_allowed):
  1808. return True
  1809. else:
  1810. return field.null
  1811. def get_order_dir(field, default='ASC'):
  1812. """
  1813. Returns the field name and direction for an order specification. For
  1814. example, '-foo' is returned as ('foo', 'DESC').
  1815. The 'default' param is used to indicate which way no prefix (or a '+'
  1816. prefix) should sort. The '-' prefix always sorts the opposite way.
  1817. """
  1818. dirn = ORDER_DIR[default]
  1819. if field[0] == '-':
  1820. return field[1:], dirn[1]
  1821. return field, dirn[0]
  1822. def add_to_dict(data, key, value):
  1823. """
  1824. A helper function to add "value" to the set of values for "key", whether or
  1825. not "key" already exists.
  1826. """
  1827. if key in data:
  1828. data[key].add(value)
  1829. else:
  1830. data[key] = {value}
  1831. def is_reverse_o2o(field):
  1832. """
  1833. A little helper to check if the given field is reverse-o2o. The field is
  1834. expected to be some sort of relation field or related object.
  1835. """
  1836. return not hasattr(field, 'rel') and field.field.unique
  1837. def alias_diff(refcounts_before, refcounts_after):
  1838. """
  1839. Given the before and after copies of refcounts works out which aliases
  1840. have been added to the after copy.
  1841. """
  1842. # Use -1 as default value so that any join that is created, then trimmed
  1843. # is seen as added.
  1844. return set(t for t in refcounts_after
  1845. if refcounts_after[t] > refcounts_before.get(t, -1))
  1846. class JoinPromoter(object):
  1847. """
  1848. A class to abstract away join promotion problems for complex filter
  1849. conditions.
  1850. """
  1851. def __init__(self, connector, num_children, negated):
  1852. self.connector = connector
  1853. self.negated = negated
  1854. if self.negated:
  1855. if connector == AND:
  1856. self.effective_connector = OR
  1857. else:
  1858. self.effective_connector = AND
  1859. else:
  1860. self.effective_connector = self.connector
  1861. self.num_children = num_children
  1862. # Maps of table alias to how many times it is seen as required for
  1863. # inner and/or outer joins.
  1864. self.outer_votes = {}
  1865. self.inner_votes = {}
  1866. def add_votes(self, inner_votes):
  1867. """
  1868. Add single vote per item to self.inner_votes. Parameter can be any
  1869. iterable.
  1870. """
  1871. for voted in inner_votes:
  1872. self.inner_votes[voted] = self.inner_votes.get(voted, 0) + 1
  1873. def update_join_types(self, query):
  1874. """
  1875. Change join types so that the generated query is as efficient as
  1876. possible, but still correct. So, change as many joins as possible
  1877. to INNER, but don't make OUTER joins INNER if that could remove
  1878. results from the query.
  1879. """
  1880. to_promote = set()
  1881. to_demote = set()
  1882. # The effective_connector is used so that NOT (a AND b) is treated
  1883. # similarly to (a OR b) for join promotion.
  1884. for table, votes in self.inner_votes.items():
  1885. # We must use outer joins in OR case when the join isn't contained
  1886. # in all of the joins. Otherwise the INNER JOIN itself could remove
  1887. # valid results. Consider the case where a model with rel_a and
  1888. # rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now,
  1889. # if rel_a join doesn't produce any results is null (for example
  1890. # reverse foreign key or null value in direct foreign key), and
  1891. # there is a matching row in rel_b with col=2, then an INNER join
  1892. # to rel_a would remove a valid match from the query. So, we need
  1893. # to promote any existing INNER to LOUTER (it is possible this
  1894. # promotion in turn will be demoted later on).
  1895. if self.effective_connector == 'OR' and votes < self.num_children:
  1896. to_promote.add(table)
  1897. # If connector is AND and there is a filter that can match only
  1898. # when there is a joinable row, then use INNER. For example, in
  1899. # rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL
  1900. # as join output, then the col=1 or col=2 can't match (as
  1901. # NULL=anything is always false).
  1902. # For the OR case, if all children voted for a join to be inner,
  1903. # then we can use INNER for the join. For example:
  1904. # (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell)
  1905. # then if rel_a doesn't produce any rows, the whole condition
  1906. # can't match. Hence we can safely use INNER join.
  1907. if self.effective_connector == 'AND' or (
  1908. self.effective_connector == 'OR' and votes == self.num_children):
  1909. to_demote.add(table)
  1910. # Finally, what happens in cases where we have:
  1911. # (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0
  1912. # Now, we first generate the OR clause, and promote joins for it
  1913. # in the first if branch above. Both rel_a and rel_b are promoted
  1914. # to LOUTER joins. After that we do the AND case. The OR case
  1915. # voted no inner joins but the rel_a__col__gte=0 votes inner join
  1916. # for rel_a. We demote it back to INNER join (in AND case a single
  1917. # vote is enough). The demotion is OK, if rel_a doesn't produce
  1918. # rows, then the rel_a__col__gte=0 clause can't be true, and thus
  1919. # the whole clause must be false. So, it is safe to use INNER
  1920. # join.
  1921. # Note that in this example we could just as well have the __gte
  1922. # clause and the OR clause swapped. Or we could replace the __gte
  1923. # clause with an OR clause containing rel_a__col=1|rel_a__col=2,
  1924. # and again we could safely demote to INNER.
  1925. query.promote_joins(to_promote)
  1926. query.demote_joins(to_demote)
  1927. return to_demote