You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

query.py 91 KiB

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