compiler.py 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099
  1. import collections
  2. import json
  3. import re
  4. from functools import partial
  5. from itertools import chain
  6. from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet
  7. from django.db import DatabaseError, NotSupportedError
  8. from django.db.models.constants import LOOKUP_SEP
  9. from django.db.models.expressions import F, OrderBy, RawSQL, Ref, Value
  10. from django.db.models.functions import Cast, Random
  11. from django.db.models.lookups import Lookup
  12. from django.db.models.query_utils import select_related_descend
  13. from django.db.models.sql.constants import (
  14. CURSOR,
  15. GET_ITERATOR_CHUNK_SIZE,
  16. MULTI,
  17. NO_RESULTS,
  18. ORDER_DIR,
  19. SINGLE,
  20. )
  21. from django.db.models.sql.query import Query, get_order_dir
  22. from django.db.models.sql.where import AND
  23. from django.db.transaction import TransactionManagementError
  24. from django.utils.functional import cached_property
  25. from django.utils.hashable import make_hashable
  26. from django.utils.regex_helper import _lazy_re_compile
  27. class PositionRef(Ref):
  28. def __init__(self, ordinal, refs, source):
  29. self.ordinal = ordinal
  30. super().__init__(refs, source)
  31. def as_sql(self, compiler, connection):
  32. return str(self.ordinal), ()
  33. class SQLCompiler:
  34. # Multiline ordering SQL clause may appear from RawSQL.
  35. ordering_parts = _lazy_re_compile(
  36. r"^(.*)\s(?:ASC|DESC).*",
  37. re.MULTILINE | re.DOTALL,
  38. )
  39. def __init__(self, query, connection, using, elide_empty=True):
  40. self.query = query
  41. self.connection = connection
  42. self.using = using
  43. # Some queries, e.g. coalesced aggregation, need to be executed even if
  44. # they would return an empty result set.
  45. self.elide_empty = elide_empty
  46. self.quote_cache = {"*": "*"}
  47. # The select, klass_info, and annotations are needed by QuerySet.iterator()
  48. # these are set as a side-effect of executing the query. Note that we calculate
  49. # separately a list of extra select columns needed for grammatical correctness
  50. # of the query, but these columns are not included in self.select.
  51. self.select = None
  52. self.annotation_col_map = None
  53. self.klass_info = None
  54. self._meta_ordering = None
  55. def __repr__(self):
  56. return (
  57. f"<{self.__class__.__qualname__} "
  58. f"model={self.query.model.__qualname__} "
  59. f"connection={self.connection!r} using={self.using!r}>"
  60. )
  61. def setup_query(self, with_col_aliases=False):
  62. if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map):
  63. self.query.get_initial_alias()
  64. self.select, self.klass_info, self.annotation_col_map = self.get_select(
  65. with_col_aliases=with_col_aliases,
  66. )
  67. self.col_count = len(self.select)
  68. def pre_sql_setup(self, with_col_aliases=False):
  69. """
  70. Do any necessary class setup immediately prior to producing SQL. This
  71. is for things that can't necessarily be done in __init__ because we
  72. might not have all the pieces in place at that time.
  73. """
  74. self.setup_query(with_col_aliases=with_col_aliases)
  75. order_by = self.get_order_by()
  76. self.where, self.having, self.qualify = self.query.where.split_having_qualify(
  77. must_group_by=self.query.group_by is not None
  78. )
  79. extra_select = self.get_extra_select(order_by, self.select)
  80. self.has_extra_select = bool(extra_select)
  81. group_by = self.get_group_by(self.select + extra_select, order_by)
  82. return extra_select, order_by, group_by
  83. def get_group_by(self, select, order_by):
  84. """
  85. Return a list of 2-tuples of form (sql, params).
  86. The logic of what exactly the GROUP BY clause contains is hard
  87. to describe in other words than "if it passes the test suite,
  88. then it is correct".
  89. """
  90. # Some examples:
  91. # SomeModel.objects.annotate(Count('somecol'))
  92. # GROUP BY: all fields of the model
  93. #
  94. # SomeModel.objects.values('name').annotate(Count('somecol'))
  95. # GROUP BY: name
  96. #
  97. # SomeModel.objects.annotate(Count('somecol')).values('name')
  98. # GROUP BY: all cols of the model
  99. #
  100. # SomeModel.objects.values('name', 'pk')
  101. # .annotate(Count('somecol')).values('pk')
  102. # GROUP BY: name, pk
  103. #
  104. # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk')
  105. # GROUP BY: name, pk
  106. #
  107. # In fact, the self.query.group_by is the minimal set to GROUP BY. It
  108. # can't be ever restricted to a smaller set, but additional columns in
  109. # HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately
  110. # the end result is that it is impossible to force the query to have
  111. # a chosen GROUP BY clause - you can almost do this by using the form:
  112. # .values(*wanted_cols).annotate(AnAggregate())
  113. # but any later annotations, extra selects, values calls that
  114. # refer some column outside of the wanted_cols, order_by, or even
  115. # filter calls can alter the GROUP BY clause.
  116. # The query.group_by is either None (no GROUP BY at all), True
  117. # (group by select fields), or a list of expressions to be added
  118. # to the group by.
  119. if self.query.group_by is None:
  120. return []
  121. expressions = []
  122. group_by_refs = set()
  123. if self.query.group_by is not True:
  124. # If the group by is set to a list (by .values() call most likely),
  125. # then we need to add everything in it to the GROUP BY clause.
  126. # Backwards compatibility hack for setting query.group_by. Remove
  127. # when we have public API way of forcing the GROUP BY clause.
  128. # Converts string references to expressions.
  129. for expr in self.query.group_by:
  130. if not hasattr(expr, "as_sql"):
  131. expr = self.query.resolve_ref(expr)
  132. if isinstance(expr, Ref):
  133. if expr.refs not in group_by_refs:
  134. group_by_refs.add(expr.refs)
  135. expressions.append(expr.source)
  136. else:
  137. expressions.append(expr)
  138. # Note that even if the group_by is set, it is only the minimal
  139. # set to group by. So, we need to add cols in select, order_by, and
  140. # having into the select in any case.
  141. selected_expr_positions = {}
  142. for ordinal, (expr, _, alias) in enumerate(select, start=1):
  143. if alias:
  144. selected_expr_positions[expr] = ordinal
  145. # Skip members of the select clause that are already explicitly
  146. # grouped against.
  147. if alias in group_by_refs:
  148. continue
  149. expressions.extend(expr.get_group_by_cols())
  150. if not self._meta_ordering:
  151. for expr, (sql, params, is_ref) in order_by:
  152. # Skip references to the SELECT clause, as all expressions in
  153. # the SELECT clause are already part of the GROUP BY.
  154. if not is_ref:
  155. expressions.extend(expr.get_group_by_cols())
  156. having_group_by = self.having.get_group_by_cols() if self.having else ()
  157. for expr in having_group_by:
  158. expressions.append(expr)
  159. result = []
  160. seen = set()
  161. expressions = self.collapse_group_by(expressions, having_group_by)
  162. allows_group_by_select_index = (
  163. self.connection.features.allows_group_by_select_index
  164. )
  165. for expr in expressions:
  166. try:
  167. sql, params = self.compile(expr)
  168. except (EmptyResultSet, FullResultSet):
  169. continue
  170. if (
  171. allows_group_by_select_index
  172. and (position := selected_expr_positions.get(expr)) is not None
  173. ):
  174. sql, params = str(position), ()
  175. else:
  176. sql, params = expr.select_format(self, sql, params)
  177. params_hash = make_hashable(params)
  178. if (sql, params_hash) not in seen:
  179. result.append((sql, params))
  180. seen.add((sql, params_hash))
  181. return result
  182. def collapse_group_by(self, expressions, having):
  183. # If the database supports group by functional dependence reduction,
  184. # then the expressions can be reduced to the set of selected table
  185. # primary keys as all other columns are functionally dependent on them.
  186. if self.connection.features.allows_group_by_selected_pks:
  187. # Filter out all expressions associated with a table's primary key
  188. # present in the grouped columns. This is done by identifying all
  189. # tables that have their primary key included in the grouped
  190. # columns and removing non-primary key columns referring to them.
  191. # Unmanaged models are excluded because they could be representing
  192. # database views on which the optimization might not be allowed.
  193. pks = {
  194. expr
  195. for expr in expressions
  196. if (
  197. hasattr(expr, "target")
  198. and expr.target.primary_key
  199. and self.connection.features.allows_group_by_selected_pks_on_model(
  200. expr.target.model
  201. )
  202. )
  203. }
  204. aliases = {expr.alias for expr in pks}
  205. expressions = [
  206. expr
  207. for expr in expressions
  208. if expr in pks
  209. or expr in having
  210. or getattr(expr, "alias", None) not in aliases
  211. ]
  212. return expressions
  213. def get_select(self, with_col_aliases=False):
  214. """
  215. Return three values:
  216. - a list of 3-tuples of (expression, (sql, params), alias)
  217. - a klass_info structure,
  218. - a dictionary of annotations
  219. The (sql, params) is what the expression will produce, and alias is the
  220. "AS alias" for the column (possibly None).
  221. The klass_info structure contains the following information:
  222. - The base model of the query.
  223. - Which columns for that model are present in the query (by
  224. position of the select clause).
  225. - related_klass_infos: [f, klass_info] to descent into
  226. The annotations is a dictionary of {'attname': column position} values.
  227. """
  228. select = []
  229. klass_info = None
  230. annotations = {}
  231. select_idx = 0
  232. for alias, (sql, params) in self.query.extra_select.items():
  233. annotations[alias] = select_idx
  234. select.append((RawSQL(sql, params), alias))
  235. select_idx += 1
  236. assert not (self.query.select and self.query.default_cols)
  237. select_mask = self.query.get_select_mask()
  238. if self.query.default_cols:
  239. cols = self.get_default_columns(select_mask)
  240. else:
  241. # self.query.select is a special case. These columns never go to
  242. # any model.
  243. cols = self.query.select
  244. if cols:
  245. select_list = []
  246. for col in cols:
  247. select_list.append(select_idx)
  248. select.append((col, None))
  249. select_idx += 1
  250. klass_info = {
  251. "model": self.query.model,
  252. "select_fields": select_list,
  253. }
  254. for alias, annotation in self.query.annotation_select.items():
  255. annotations[alias] = select_idx
  256. select.append((annotation, alias))
  257. select_idx += 1
  258. if self.query.select_related:
  259. related_klass_infos = self.get_related_selections(select, select_mask)
  260. klass_info["related_klass_infos"] = related_klass_infos
  261. def get_select_from_parent(klass_info):
  262. for ki in klass_info["related_klass_infos"]:
  263. if ki["from_parent"]:
  264. ki["select_fields"] = (
  265. klass_info["select_fields"] + ki["select_fields"]
  266. )
  267. get_select_from_parent(ki)
  268. get_select_from_parent(klass_info)
  269. ret = []
  270. col_idx = 1
  271. for col, alias in select:
  272. try:
  273. sql, params = self.compile(col)
  274. except EmptyResultSet:
  275. empty_result_set_value = getattr(
  276. col, "empty_result_set_value", NotImplemented
  277. )
  278. if empty_result_set_value is NotImplemented:
  279. # Select a predicate that's always False.
  280. sql, params = "0", ()
  281. else:
  282. sql, params = self.compile(Value(empty_result_set_value))
  283. except FullResultSet:
  284. sql, params = self.compile(Value(True))
  285. else:
  286. sql, params = col.select_format(self, sql, params)
  287. if alias is None and with_col_aliases:
  288. alias = f"col{col_idx}"
  289. col_idx += 1
  290. ret.append((col, (sql, params), alias))
  291. return ret, klass_info, annotations
  292. def _order_by_pairs(self):
  293. if self.query.extra_order_by:
  294. ordering = self.query.extra_order_by
  295. elif not self.query.default_ordering:
  296. ordering = self.query.order_by
  297. elif self.query.order_by:
  298. ordering = self.query.order_by
  299. elif (meta := self.query.get_meta()) and meta.ordering:
  300. ordering = meta.ordering
  301. self._meta_ordering = ordering
  302. else:
  303. ordering = []
  304. if self.query.standard_ordering:
  305. default_order, _ = ORDER_DIR["ASC"]
  306. else:
  307. default_order, _ = ORDER_DIR["DESC"]
  308. selected_exprs = {}
  309. # Avoid computing `selected_exprs` if there is no `ordering` as it's
  310. # relatively expensive.
  311. if ordering and (select := self.select):
  312. for ordinal, (expr, _, alias) in enumerate(select, start=1):
  313. pos_expr = PositionRef(ordinal, alias, expr)
  314. if alias:
  315. selected_exprs[alias] = pos_expr
  316. selected_exprs[expr] = pos_expr
  317. for field in ordering:
  318. if hasattr(field, "resolve_expression"):
  319. if isinstance(field, Value):
  320. # output_field must be resolved for constants.
  321. field = Cast(field, field.output_field)
  322. if not isinstance(field, OrderBy):
  323. field = field.asc()
  324. if not self.query.standard_ordering:
  325. field = field.copy()
  326. field.reverse_ordering()
  327. select_ref = selected_exprs.get(field.expression)
  328. if select_ref or (
  329. isinstance(field.expression, F)
  330. and (select_ref := selected_exprs.get(field.expression.name))
  331. ):
  332. # Emulation of NULLS (FIRST|LAST) cannot be combined with
  333. # the usage of ordering by position.
  334. if (
  335. field.nulls_first is None and field.nulls_last is None
  336. ) or self.connection.features.supports_order_by_nulls_modifier:
  337. field = field.copy()
  338. field.expression = select_ref
  339. # Alias collisions are not possible when dealing with
  340. # combined queries so fallback to it if emulation of NULLS
  341. # handling is required.
  342. elif self.query.combinator:
  343. field = field.copy()
  344. field.expression = Ref(select_ref.refs, select_ref.source)
  345. yield field, select_ref is not None
  346. continue
  347. if field == "?": # random
  348. yield OrderBy(Random()), False
  349. continue
  350. col, order = get_order_dir(field, default_order)
  351. descending = order == "DESC"
  352. if select_ref := selected_exprs.get(col):
  353. # Reference to expression in SELECT clause
  354. yield (
  355. OrderBy(
  356. select_ref,
  357. descending=descending,
  358. ),
  359. True,
  360. )
  361. continue
  362. if col in self.query.annotations:
  363. # References to an expression which is masked out of the SELECT
  364. # clause.
  365. if self.query.combinator and self.select:
  366. # Don't use the resolved annotation because other
  367. # combinated queries might define it differently.
  368. expr = F(col)
  369. else:
  370. expr = self.query.annotations[col]
  371. if isinstance(expr, Value):
  372. # output_field must be resolved for constants.
  373. expr = Cast(expr, expr.output_field)
  374. yield OrderBy(expr, descending=descending), False
  375. continue
  376. if "." in field:
  377. # This came in through an extra(order_by=...) addition. Pass it
  378. # on verbatim.
  379. table, col = col.split(".", 1)
  380. yield (
  381. OrderBy(
  382. RawSQL(
  383. "%s.%s" % (self.quote_name_unless_alias(table), col), []
  384. ),
  385. descending=descending,
  386. ),
  387. False,
  388. )
  389. continue
  390. if self.query.extra and col in self.query.extra:
  391. if col in self.query.extra_select:
  392. yield (
  393. OrderBy(
  394. Ref(col, RawSQL(*self.query.extra[col])),
  395. descending=descending,
  396. ),
  397. True,
  398. )
  399. else:
  400. yield (
  401. OrderBy(RawSQL(*self.query.extra[col]), descending=descending),
  402. False,
  403. )
  404. else:
  405. if self.query.combinator and self.select:
  406. # Don't use the first model's field because other
  407. # combinated queries might define it differently.
  408. yield OrderBy(F(col), descending=descending), False
  409. else:
  410. # 'col' is of the form 'field' or 'field1__field2' or
  411. # '-field1__field2__field', etc.
  412. yield from self.find_ordering_name(
  413. field,
  414. self.query.get_meta(),
  415. default_order=default_order,
  416. )
  417. def get_order_by(self):
  418. """
  419. Return a list of 2-tuples of the form (expr, (sql, params, is_ref)) for
  420. the ORDER BY clause.
  421. The order_by clause can alter the select clause (for example it can add
  422. aliases to clauses that do not yet have one, or it can add totally new
  423. select clauses).
  424. """
  425. result = []
  426. seen = set()
  427. for expr, is_ref in self._order_by_pairs():
  428. resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
  429. if not is_ref and self.query.combinator and self.select:
  430. src = resolved.expression
  431. expr_src = expr.expression
  432. for sel_expr, _, col_alias in self.select:
  433. if src == sel_expr:
  434. # When values() is used the exact alias must be used to
  435. # reference annotations.
  436. if (
  437. self.query.has_select_fields
  438. and col_alias in self.query.annotation_select
  439. and not (
  440. isinstance(expr_src, F) and col_alias == expr_src.name
  441. )
  442. ):
  443. continue
  444. resolved.set_source_expressions(
  445. [Ref(col_alias if col_alias else src.target.column, src)]
  446. )
  447. break
  448. else:
  449. # Add column used in ORDER BY clause to the selected
  450. # columns and to each combined query.
  451. order_by_idx = len(self.query.select) + 1
  452. col_alias = f"__orderbycol{order_by_idx}"
  453. for q in self.query.combined_queries:
  454. # If fields were explicitly selected through values()
  455. # combined queries cannot be augmented.
  456. if q.has_select_fields:
  457. raise DatabaseError(
  458. "ORDER BY term does not match any column in "
  459. "the result set."
  460. )
  461. q.add_annotation(expr_src, col_alias)
  462. self.query.add_select_col(resolved, col_alias)
  463. resolved.set_source_expressions([Ref(col_alias, src)])
  464. sql, params = self.compile(resolved)
  465. # Don't add the same column twice, but the order direction is
  466. # not taken into account so we strip it. When this entire method
  467. # is refactored into expressions, then we can check each part as we
  468. # generate it.
  469. without_ordering = self.ordering_parts.search(sql)[1]
  470. params_hash = make_hashable(params)
  471. if (without_ordering, params_hash) in seen:
  472. continue
  473. seen.add((without_ordering, params_hash))
  474. result.append((resolved, (sql, params, is_ref)))
  475. return result
  476. def get_extra_select(self, order_by, select):
  477. extra_select = []
  478. if self.query.distinct and not self.query.distinct_fields:
  479. select_sql = [t[1] for t in select]
  480. for expr, (sql, params, is_ref) in order_by:
  481. without_ordering = self.ordering_parts.search(sql)[1]
  482. if not is_ref and (without_ordering, params) not in select_sql:
  483. extra_select.append((expr, (without_ordering, params), None))
  484. return extra_select
  485. def quote_name_unless_alias(self, name):
  486. """
  487. A wrapper around connection.ops.quote_name that doesn't quote aliases
  488. for table names. This avoids problems with some SQL dialects that treat
  489. quoted strings specially (e.g. PostgreSQL).
  490. """
  491. if name in self.quote_cache:
  492. return self.quote_cache[name]
  493. if (
  494. (name in self.query.alias_map and name not in self.query.table_map)
  495. or name in self.query.extra_select
  496. or (
  497. self.query.external_aliases.get(name)
  498. and name not in self.query.table_map
  499. )
  500. ):
  501. self.quote_cache[name] = name
  502. return name
  503. r = self.connection.ops.quote_name(name)
  504. self.quote_cache[name] = r
  505. return r
  506. def compile(self, node):
  507. vendor_impl = getattr(node, "as_" + self.connection.vendor, None)
  508. if vendor_impl:
  509. sql, params = vendor_impl(self, self.connection)
  510. else:
  511. sql, params = node.as_sql(self, self.connection)
  512. return sql, params
  513. def get_combinator_sql(self, combinator, all):
  514. features = self.connection.features
  515. compilers = [
  516. query.get_compiler(self.using, self.connection, self.elide_empty)
  517. for query in self.query.combined_queries
  518. ]
  519. if not features.supports_slicing_ordering_in_compound:
  520. for compiler in compilers:
  521. if compiler.query.is_sliced:
  522. raise DatabaseError(
  523. "LIMIT/OFFSET not allowed in subqueries of compound statements."
  524. )
  525. if compiler.get_order_by():
  526. raise DatabaseError(
  527. "ORDER BY not allowed in subqueries of compound statements."
  528. )
  529. elif self.query.is_sliced and combinator == "union":
  530. for compiler in compilers:
  531. # A sliced union cannot have its parts elided as some of them
  532. # might be sliced as well and in the event where only a single
  533. # part produces a non-empty resultset it might be impossible to
  534. # generate valid SQL.
  535. compiler.elide_empty = False
  536. parts = ()
  537. for compiler in compilers:
  538. try:
  539. # If the columns list is limited, then all combined queries
  540. # must have the same columns list. Set the selects defined on
  541. # the query on all combined queries, if not already set.
  542. if not compiler.query.values_select and self.query.values_select:
  543. compiler.query = compiler.query.clone()
  544. compiler.query.set_values(
  545. (
  546. *self.query.extra_select,
  547. *self.query.values_select,
  548. *self.query.annotation_select,
  549. )
  550. )
  551. part_sql, part_args = compiler.as_sql(with_col_aliases=True)
  552. if compiler.query.combinator:
  553. # Wrap in a subquery if wrapping in parentheses isn't
  554. # supported.
  555. if not features.supports_parentheses_in_compound:
  556. part_sql = "SELECT * FROM ({})".format(part_sql)
  557. # Add parentheses when combining with compound query if not
  558. # already added for all compound queries.
  559. elif (
  560. self.query.subquery
  561. or not features.supports_slicing_ordering_in_compound
  562. ):
  563. part_sql = "({})".format(part_sql)
  564. elif (
  565. self.query.subquery
  566. and features.supports_slicing_ordering_in_compound
  567. ):
  568. part_sql = "({})".format(part_sql)
  569. parts += ((part_sql, part_args),)
  570. except EmptyResultSet:
  571. # Omit the empty queryset with UNION and with DIFFERENCE if the
  572. # first queryset is nonempty.
  573. if combinator == "union" or (combinator == "difference" and parts):
  574. continue
  575. raise
  576. if not parts:
  577. raise EmptyResultSet
  578. combinator_sql = self.connection.ops.set_operators[combinator]
  579. if all and combinator == "union":
  580. combinator_sql += " ALL"
  581. braces = "{}"
  582. if not self.query.subquery and features.supports_slicing_ordering_in_compound:
  583. braces = "({})"
  584. sql_parts, args_parts = zip(
  585. *((braces.format(sql), args) for sql, args in parts)
  586. )
  587. result = [" {} ".format(combinator_sql).join(sql_parts)]
  588. params = []
  589. for part in args_parts:
  590. params.extend(part)
  591. return result, params
  592. def get_qualify_sql(self):
  593. where_parts = []
  594. if self.where:
  595. where_parts.append(self.where)
  596. if self.having:
  597. where_parts.append(self.having)
  598. inner_query = self.query.clone()
  599. inner_query.subquery = True
  600. inner_query.where = inner_query.where.__class__(where_parts)
  601. # Augment the inner query with any window function references that
  602. # might have been masked via values() and alias(). If any masked
  603. # aliases are added they'll be masked again to avoid fetching
  604. # the data in the `if qual_aliases` branch below.
  605. select = {
  606. expr: alias for expr, _, alias in self.get_select(with_col_aliases=True)[0]
  607. }
  608. select_aliases = set(select.values())
  609. qual_aliases = set()
  610. replacements = {}
  611. def collect_replacements(expressions):
  612. while expressions:
  613. expr = expressions.pop()
  614. if expr in replacements:
  615. continue
  616. elif select_alias := select.get(expr):
  617. replacements[expr] = select_alias
  618. elif isinstance(expr, Lookup):
  619. expressions.extend(expr.get_source_expressions())
  620. elif isinstance(expr, Ref):
  621. if expr.refs not in select_aliases:
  622. expressions.extend(expr.get_source_expressions())
  623. else:
  624. num_qual_alias = len(qual_aliases)
  625. select_alias = f"qual{num_qual_alias}"
  626. qual_aliases.add(select_alias)
  627. inner_query.add_annotation(expr, select_alias)
  628. replacements[expr] = select_alias
  629. collect_replacements(list(self.qualify.leaves()))
  630. self.qualify = self.qualify.replace_expressions(
  631. {expr: Ref(alias, expr) for expr, alias in replacements.items()}
  632. )
  633. order_by = []
  634. for order_by_expr, *_ in self.get_order_by():
  635. collect_replacements(order_by_expr.get_source_expressions())
  636. order_by.append(
  637. order_by_expr.replace_expressions(
  638. {expr: Ref(alias, expr) for expr, alias in replacements.items()}
  639. )
  640. )
  641. inner_query_compiler = inner_query.get_compiler(
  642. self.using, connection=self.connection, elide_empty=self.elide_empty
  643. )
  644. inner_sql, inner_params = inner_query_compiler.as_sql(
  645. # The limits must be applied to the outer query to avoid pruning
  646. # results too eagerly.
  647. with_limits=False,
  648. # Force unique aliasing of selected columns to avoid collisions
  649. # and make rhs predicates referencing easier.
  650. with_col_aliases=True,
  651. )
  652. qualify_sql, qualify_params = self.compile(self.qualify)
  653. result = [
  654. "SELECT * FROM (",
  655. inner_sql,
  656. ")",
  657. self.connection.ops.quote_name("qualify"),
  658. "WHERE",
  659. qualify_sql,
  660. ]
  661. if qual_aliases:
  662. # If some select aliases were unmasked for filtering purposes they
  663. # must be masked back.
  664. cols = [self.connection.ops.quote_name(alias) for alias in select.values()]
  665. result = [
  666. "SELECT",
  667. ", ".join(cols),
  668. "FROM (",
  669. *result,
  670. ")",
  671. self.connection.ops.quote_name("qualify_mask"),
  672. ]
  673. params = list(inner_params) + qualify_params
  674. # As the SQL spec is unclear on whether or not derived tables
  675. # ordering must propagate it has to be explicitly repeated on the
  676. # outer-most query to ensure it's preserved.
  677. if order_by:
  678. ordering_sqls = []
  679. for ordering in order_by:
  680. ordering_sql, ordering_params = self.compile(ordering)
  681. ordering_sqls.append(ordering_sql)
  682. params.extend(ordering_params)
  683. result.extend(["ORDER BY", ", ".join(ordering_sqls)])
  684. return result, params
  685. def as_sql(self, with_limits=True, with_col_aliases=False):
  686. """
  687. Create the SQL for this query. Return the SQL string and list of
  688. parameters.
  689. If 'with_limits' is False, any limit/offset information is not included
  690. in the query.
  691. """
  692. refcounts_before = self.query.alias_refcount.copy()
  693. try:
  694. combinator = self.query.combinator
  695. extra_select, order_by, group_by = self.pre_sql_setup(
  696. with_col_aliases=with_col_aliases or bool(combinator),
  697. )
  698. for_update_part = None
  699. # Is a LIMIT/OFFSET clause needed?
  700. with_limit_offset = with_limits and self.query.is_sliced
  701. combinator = self.query.combinator
  702. features = self.connection.features
  703. if combinator:
  704. if not getattr(features, "supports_select_{}".format(combinator)):
  705. raise NotSupportedError(
  706. "{} is not supported on this database backend.".format(
  707. combinator
  708. )
  709. )
  710. result, params = self.get_combinator_sql(
  711. combinator, self.query.combinator_all
  712. )
  713. elif self.qualify:
  714. result, params = self.get_qualify_sql()
  715. order_by = None
  716. else:
  717. distinct_fields, distinct_params = self.get_distinct()
  718. # This must come after 'select', 'ordering', and 'distinct'
  719. # (see docstring of get_from_clause() for details).
  720. from_, f_params = self.get_from_clause()
  721. try:
  722. where, w_params = (
  723. self.compile(self.where) if self.where is not None else ("", [])
  724. )
  725. except EmptyResultSet:
  726. if self.elide_empty:
  727. raise
  728. # Use a predicate that's always False.
  729. where, w_params = "0 = 1", []
  730. except FullResultSet:
  731. where, w_params = "", []
  732. try:
  733. having, h_params = (
  734. self.compile(self.having)
  735. if self.having is not None
  736. else ("", [])
  737. )
  738. except FullResultSet:
  739. having, h_params = "", []
  740. result = ["SELECT"]
  741. params = []
  742. if self.query.distinct:
  743. distinct_result, distinct_params = self.connection.ops.distinct_sql(
  744. distinct_fields,
  745. distinct_params,
  746. )
  747. result += distinct_result
  748. params += distinct_params
  749. out_cols = []
  750. for _, (s_sql, s_params), alias in self.select + extra_select:
  751. if alias:
  752. s_sql = "%s AS %s" % (
  753. s_sql,
  754. self.connection.ops.quote_name(alias),
  755. )
  756. params.extend(s_params)
  757. out_cols.append(s_sql)
  758. result += [", ".join(out_cols)]
  759. if from_:
  760. result += ["FROM", *from_]
  761. elif self.connection.features.bare_select_suffix:
  762. result += [self.connection.features.bare_select_suffix]
  763. params.extend(f_params)
  764. if self.query.select_for_update and features.has_select_for_update:
  765. if (
  766. self.connection.get_autocommit()
  767. # Don't raise an exception when database doesn't
  768. # support transactions, as it's a noop.
  769. and features.supports_transactions
  770. ):
  771. raise TransactionManagementError(
  772. "select_for_update cannot be used outside of a transaction."
  773. )
  774. if (
  775. with_limit_offset
  776. and not features.supports_select_for_update_with_limit
  777. ):
  778. raise NotSupportedError(
  779. "LIMIT/OFFSET is not supported with "
  780. "select_for_update on this database backend."
  781. )
  782. nowait = self.query.select_for_update_nowait
  783. skip_locked = self.query.select_for_update_skip_locked
  784. of = self.query.select_for_update_of
  785. no_key = self.query.select_for_no_key_update
  786. # If it's a NOWAIT/SKIP LOCKED/OF/NO KEY query but the
  787. # backend doesn't support it, raise NotSupportedError to
  788. # prevent a possible deadlock.
  789. if nowait and not features.has_select_for_update_nowait:
  790. raise NotSupportedError(
  791. "NOWAIT is not supported on this database backend."
  792. )
  793. elif skip_locked and not features.has_select_for_update_skip_locked:
  794. raise NotSupportedError(
  795. "SKIP LOCKED is not supported on this database backend."
  796. )
  797. elif of and not features.has_select_for_update_of:
  798. raise NotSupportedError(
  799. "FOR UPDATE OF is not supported on this database backend."
  800. )
  801. elif no_key and not features.has_select_for_no_key_update:
  802. raise NotSupportedError(
  803. "FOR NO KEY UPDATE is not supported on this "
  804. "database backend."
  805. )
  806. for_update_part = self.connection.ops.for_update_sql(
  807. nowait=nowait,
  808. skip_locked=skip_locked,
  809. of=self.get_select_for_update_of_arguments(),
  810. no_key=no_key,
  811. )
  812. if for_update_part and features.for_update_after_from:
  813. result.append(for_update_part)
  814. if where:
  815. result.append("WHERE %s" % where)
  816. params.extend(w_params)
  817. grouping = []
  818. for g_sql, g_params in group_by:
  819. grouping.append(g_sql)
  820. params.extend(g_params)
  821. if grouping:
  822. if distinct_fields:
  823. raise NotImplementedError(
  824. "annotate() + distinct(fields) is not implemented."
  825. )
  826. order_by = order_by or self.connection.ops.force_no_ordering()
  827. result.append("GROUP BY %s" % ", ".join(grouping))
  828. if self._meta_ordering:
  829. order_by = None
  830. if having:
  831. result.append("HAVING %s" % having)
  832. params.extend(h_params)
  833. if self.query.explain_info:
  834. result.insert(
  835. 0,
  836. self.connection.ops.explain_query_prefix(
  837. self.query.explain_info.format,
  838. **self.query.explain_info.options,
  839. ),
  840. )
  841. if order_by:
  842. ordering = []
  843. for _, (o_sql, o_params, _) in order_by:
  844. ordering.append(o_sql)
  845. params.extend(o_params)
  846. order_by_sql = "ORDER BY %s" % ", ".join(ordering)
  847. if combinator and features.requires_compound_order_by_subquery:
  848. result = ["SELECT * FROM (", *result, ")", order_by_sql]
  849. else:
  850. result.append(order_by_sql)
  851. if with_limit_offset:
  852. result.append(
  853. self.connection.ops.limit_offset_sql(
  854. self.query.low_mark, self.query.high_mark
  855. )
  856. )
  857. if for_update_part and not features.for_update_after_from:
  858. result.append(for_update_part)
  859. if self.query.subquery and extra_select:
  860. # If the query is used as a subquery, the extra selects would
  861. # result in more columns than the left-hand side expression is
  862. # expecting. This can happen when a subquery uses a combination
  863. # of order_by() and distinct(), forcing the ordering expressions
  864. # to be selected as well. Wrap the query in another subquery
  865. # to exclude extraneous selects.
  866. sub_selects = []
  867. sub_params = []
  868. for index, (select, _, alias) in enumerate(self.select, start=1):
  869. if alias:
  870. sub_selects.append(
  871. "%s.%s"
  872. % (
  873. self.connection.ops.quote_name("subquery"),
  874. self.connection.ops.quote_name(alias),
  875. )
  876. )
  877. else:
  878. select_clone = select.relabeled_clone(
  879. {select.alias: "subquery"}
  880. )
  881. subselect, subparams = select_clone.as_sql(
  882. self, self.connection
  883. )
  884. sub_selects.append(subselect)
  885. sub_params.extend(subparams)
  886. return "SELECT %s FROM (%s) subquery" % (
  887. ", ".join(sub_selects),
  888. " ".join(result),
  889. ), tuple(sub_params + params)
  890. return " ".join(result), tuple(params)
  891. finally:
  892. # Finally do cleanup - get rid of the joins we created above.
  893. self.query.reset_refcounts(refcounts_before)
  894. def get_default_columns(
  895. self, select_mask, start_alias=None, opts=None, from_parent=None
  896. ):
  897. """
  898. Compute the default columns for selecting every field in the base
  899. model. Will sometimes be called to pull in related models (e.g. via
  900. select_related), in which case "opts" and "start_alias" will be given
  901. to provide a starting point for the traversal.
  902. Return a list of strings, quoted appropriately for use in SQL
  903. directly, as well as a set of aliases used in the select statement (if
  904. 'as_pairs' is True, return a list of (alias, col_name) pairs instead
  905. of strings as the first component and None as the second component).
  906. """
  907. result = []
  908. if opts is None:
  909. if (opts := self.query.get_meta()) is None:
  910. return result
  911. start_alias = start_alias or self.query.get_initial_alias()
  912. # The 'seen_models' is used to optimize checking the needed parent
  913. # alias for a given field. This also includes None -> start_alias to
  914. # be used by local fields.
  915. seen_models = {None: start_alias}
  916. for field in opts.concrete_fields:
  917. model = field.model._meta.concrete_model
  918. # A proxy model will have a different model and concrete_model. We
  919. # will assign None if the field belongs to this model.
  920. if model == opts.model:
  921. model = None
  922. if (
  923. from_parent
  924. and model is not None
  925. and issubclass(
  926. from_parent._meta.concrete_model, model._meta.concrete_model
  927. )
  928. ):
  929. # Avoid loading data for already loaded parents.
  930. # We end up here in the case select_related() resolution
  931. # proceeds from parent model to child model. In that case the
  932. # parent model data is already present in the SELECT clause,
  933. # and we want to avoid reloading the same data again.
  934. continue
  935. if select_mask and field not in select_mask:
  936. continue
  937. alias = self.query.join_parent_model(opts, model, start_alias, seen_models)
  938. column = field.get_col(alias)
  939. result.append(column)
  940. return result
  941. def get_distinct(self):
  942. """
  943. Return a quoted list of fields to use in DISTINCT ON part of the query.
  944. This method can alter the tables in the query, and thus it must be
  945. called before get_from_clause().
  946. """
  947. result = []
  948. params = []
  949. opts = self.query.get_meta()
  950. for name in self.query.distinct_fields:
  951. parts = name.split(LOOKUP_SEP)
  952. _, targets, alias, joins, path, _, transform_function = self._setup_joins(
  953. parts, opts, None
  954. )
  955. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  956. for target in targets:
  957. if name in self.query.annotation_select:
  958. result.append(self.connection.ops.quote_name(name))
  959. else:
  960. r, p = self.compile(transform_function(target, alias))
  961. result.append(r)
  962. params.append(p)
  963. return result, params
  964. def find_ordering_name(
  965. self, name, opts, alias=None, default_order="ASC", already_seen=None
  966. ):
  967. """
  968. Return the table alias (the name might be ambiguous, the alias will
  969. not be) and column name for ordering by the given 'name' parameter.
  970. The 'name' is of the form 'field1__field2__...__fieldN'.
  971. """
  972. name, order = get_order_dir(name, default_order)
  973. descending = order == "DESC"
  974. pieces = name.split(LOOKUP_SEP)
  975. (
  976. field,
  977. targets,
  978. alias,
  979. joins,
  980. path,
  981. opts,
  982. transform_function,
  983. ) = self._setup_joins(pieces, opts, alias)
  984. # If we get to this point and the field is a relation to another model,
  985. # append the default ordering for that model unless it is the pk
  986. # shortcut or the attribute name of the field that is specified or
  987. # there are transforms to process.
  988. if (
  989. field.is_relation
  990. and opts.ordering
  991. and getattr(field, "attname", None) != pieces[-1]
  992. and name != "pk"
  993. and not getattr(transform_function, "has_transforms", False)
  994. ):
  995. # Firstly, avoid infinite loops.
  996. already_seen = already_seen or set()
  997. join_tuple = tuple(
  998. getattr(self.query.alias_map[j], "join_cols", None) for j in joins
  999. )
  1000. if join_tuple in already_seen:
  1001. raise FieldError("Infinite loop caused by ordering.")
  1002. already_seen.add(join_tuple)
  1003. results = []
  1004. for item in opts.ordering:
  1005. if hasattr(item, "resolve_expression") and not isinstance(
  1006. item, OrderBy
  1007. ):
  1008. item = item.desc() if descending else item.asc()
  1009. if isinstance(item, OrderBy):
  1010. results.append(
  1011. (item.prefix_references(f"{name}{LOOKUP_SEP}"), False)
  1012. )
  1013. continue
  1014. results.extend(
  1015. (expr.prefix_references(f"{name}{LOOKUP_SEP}"), is_ref)
  1016. for expr, is_ref in self.find_ordering_name(
  1017. item, opts, alias, order, already_seen
  1018. )
  1019. )
  1020. return results
  1021. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  1022. return [
  1023. (OrderBy(transform_function(t, alias), descending=descending), False)
  1024. for t in targets
  1025. ]
  1026. def _setup_joins(self, pieces, opts, alias):
  1027. """
  1028. Helper method for get_order_by() and get_distinct().
  1029. get_ordering() and get_distinct() must produce same target columns on
  1030. same input, as the prefixes of get_ordering() and get_distinct() must
  1031. match. Executing SQL where this is not true is an error.
  1032. """
  1033. alias = alias or self.query.get_initial_alias()
  1034. field, targets, opts, joins, path, transform_function = self.query.setup_joins(
  1035. pieces, opts, alias
  1036. )
  1037. alias = joins[-1]
  1038. return field, targets, alias, joins, path, opts, transform_function
  1039. def get_from_clause(self):
  1040. """
  1041. Return a list of strings that are joined together to go after the
  1042. "FROM" part of the query, as well as a list any extra parameters that
  1043. need to be included. Subclasses, can override this to create a
  1044. from-clause via a "select".
  1045. This should only be called after any SQL construction methods that
  1046. might change the tables that are needed. This means the select columns,
  1047. ordering, and distinct must be done first.
  1048. """
  1049. result = []
  1050. params = []
  1051. for alias in tuple(self.query.alias_map):
  1052. if not self.query.alias_refcount[alias]:
  1053. continue
  1054. try:
  1055. from_clause = self.query.alias_map[alias]
  1056. except KeyError:
  1057. # Extra tables can end up in self.tables, but not in the
  1058. # alias_map if they aren't in a join. That's OK. We skip them.
  1059. continue
  1060. clause_sql, clause_params = self.compile(from_clause)
  1061. result.append(clause_sql)
  1062. params.extend(clause_params)
  1063. for t in self.query.extra_tables:
  1064. alias, _ = self.query.table_alias(t)
  1065. # Only add the alias if it's not already present (the table_alias()
  1066. # call increments the refcount, so an alias refcount of one means
  1067. # this is the only reference).
  1068. if (
  1069. alias not in self.query.alias_map
  1070. or self.query.alias_refcount[alias] == 1
  1071. ):
  1072. result.append(", %s" % self.quote_name_unless_alias(alias))
  1073. return result, params
  1074. def get_related_selections(
  1075. self,
  1076. select,
  1077. select_mask,
  1078. opts=None,
  1079. root_alias=None,
  1080. cur_depth=1,
  1081. requested=None,
  1082. restricted=None,
  1083. ):
  1084. """
  1085. Fill in the information needed for a select_related query. The current
  1086. depth is measured as the number of connections away from the root model
  1087. (for example, cur_depth=1 means we are looking at models with direct
  1088. connections to the root model).
  1089. """
  1090. def _get_field_choices():
  1091. direct_choices = (f.name for f in opts.fields if f.is_relation)
  1092. reverse_choices = (
  1093. f.field.related_query_name()
  1094. for f in opts.related_objects
  1095. if f.field.unique
  1096. )
  1097. return chain(
  1098. direct_choices, reverse_choices, self.query._filtered_relations
  1099. )
  1100. related_klass_infos = []
  1101. if not restricted and cur_depth > self.query.max_depth:
  1102. # We've recursed far enough; bail out.
  1103. return related_klass_infos
  1104. if not opts:
  1105. opts = self.query.get_meta()
  1106. root_alias = self.query.get_initial_alias()
  1107. # Setup for the case when only particular related fields should be
  1108. # included in the related selection.
  1109. fields_found = set()
  1110. if requested is None:
  1111. restricted = isinstance(self.query.select_related, dict)
  1112. if restricted:
  1113. requested = self.query.select_related
  1114. def get_related_klass_infos(klass_info, related_klass_infos):
  1115. klass_info["related_klass_infos"] = related_klass_infos
  1116. for f in opts.fields:
  1117. fields_found.add(f.name)
  1118. if restricted:
  1119. next = requested.get(f.name, {})
  1120. if not f.is_relation:
  1121. # If a non-related field is used like a relation,
  1122. # or if a single non-relational field is given.
  1123. if next or f.name in requested:
  1124. raise FieldError(
  1125. "Non-relational field given in select_related: '%s'. "
  1126. "Choices are: %s"
  1127. % (
  1128. f.name,
  1129. ", ".join(_get_field_choices()) or "(none)",
  1130. )
  1131. )
  1132. else:
  1133. next = False
  1134. if not select_related_descend(f, restricted, requested, select_mask):
  1135. continue
  1136. related_select_mask = select_mask.get(f) or {}
  1137. klass_info = {
  1138. "model": f.remote_field.model,
  1139. "field": f,
  1140. "reverse": False,
  1141. "local_setter": f.set_cached_value,
  1142. "remote_setter": f.remote_field.set_cached_value
  1143. if f.unique
  1144. else lambda x, y: None,
  1145. "from_parent": False,
  1146. }
  1147. related_klass_infos.append(klass_info)
  1148. select_fields = []
  1149. _, _, _, joins, _, _ = self.query.setup_joins([f.name], opts, root_alias)
  1150. alias = joins[-1]
  1151. columns = self.get_default_columns(
  1152. related_select_mask, start_alias=alias, opts=f.remote_field.model._meta
  1153. )
  1154. for col in columns:
  1155. select_fields.append(len(select))
  1156. select.append((col, None))
  1157. klass_info["select_fields"] = select_fields
  1158. next_klass_infos = self.get_related_selections(
  1159. select,
  1160. related_select_mask,
  1161. f.remote_field.model._meta,
  1162. alias,
  1163. cur_depth + 1,
  1164. next,
  1165. restricted,
  1166. )
  1167. get_related_klass_infos(klass_info, next_klass_infos)
  1168. if restricted:
  1169. related_fields = [
  1170. (o.field, o.related_model)
  1171. for o in opts.related_objects
  1172. if o.field.unique and not o.many_to_many
  1173. ]
  1174. for related_field, model in related_fields:
  1175. related_select_mask = select_mask.get(related_field) or {}
  1176. if not select_related_descend(
  1177. related_field,
  1178. restricted,
  1179. requested,
  1180. related_select_mask,
  1181. reverse=True,
  1182. ):
  1183. continue
  1184. related_field_name = related_field.related_query_name()
  1185. fields_found.add(related_field_name)
  1186. join_info = self.query.setup_joins(
  1187. [related_field_name], opts, root_alias
  1188. )
  1189. alias = join_info.joins[-1]
  1190. from_parent = issubclass(model, opts.model) and model is not opts.model
  1191. klass_info = {
  1192. "model": model,
  1193. "field": related_field,
  1194. "reverse": True,
  1195. "local_setter": related_field.remote_field.set_cached_value,
  1196. "remote_setter": related_field.set_cached_value,
  1197. "from_parent": from_parent,
  1198. }
  1199. related_klass_infos.append(klass_info)
  1200. select_fields = []
  1201. columns = self.get_default_columns(
  1202. related_select_mask,
  1203. start_alias=alias,
  1204. opts=model._meta,
  1205. from_parent=opts.model,
  1206. )
  1207. for col in columns:
  1208. select_fields.append(len(select))
  1209. select.append((col, None))
  1210. klass_info["select_fields"] = select_fields
  1211. next = requested.get(related_field.related_query_name(), {})
  1212. next_klass_infos = self.get_related_selections(
  1213. select,
  1214. related_select_mask,
  1215. model._meta,
  1216. alias,
  1217. cur_depth + 1,
  1218. next,
  1219. restricted,
  1220. )
  1221. get_related_klass_infos(klass_info, next_klass_infos)
  1222. def local_setter(final_field, obj, from_obj):
  1223. # Set a reverse fk object when relation is non-empty.
  1224. if from_obj:
  1225. final_field.remote_field.set_cached_value(from_obj, obj)
  1226. def local_setter_noop(obj, from_obj):
  1227. pass
  1228. def remote_setter(name, obj, from_obj):
  1229. setattr(from_obj, name, obj)
  1230. for name in list(requested):
  1231. # Filtered relations work only on the topmost level.
  1232. if cur_depth > 1:
  1233. break
  1234. if name in self.query._filtered_relations:
  1235. fields_found.add(name)
  1236. final_field, _, join_opts, joins, _, _ = self.query.setup_joins(
  1237. [name], opts, root_alias
  1238. )
  1239. model = join_opts.model
  1240. alias = joins[-1]
  1241. from_parent = (
  1242. issubclass(model, opts.model) and model is not opts.model
  1243. )
  1244. klass_info = {
  1245. "model": model,
  1246. "field": final_field,
  1247. "reverse": True,
  1248. "local_setter": (
  1249. partial(local_setter, final_field)
  1250. if len(joins) <= 2
  1251. else local_setter_noop
  1252. ),
  1253. "remote_setter": partial(remote_setter, name),
  1254. "from_parent": from_parent,
  1255. }
  1256. related_klass_infos.append(klass_info)
  1257. select_fields = []
  1258. field_select_mask = select_mask.get((name, final_field)) or {}
  1259. columns = self.get_default_columns(
  1260. field_select_mask,
  1261. start_alias=alias,
  1262. opts=model._meta,
  1263. from_parent=opts.model,
  1264. )
  1265. for col in columns:
  1266. select_fields.append(len(select))
  1267. select.append((col, None))
  1268. klass_info["select_fields"] = select_fields
  1269. next_requested = requested.get(name, {})
  1270. next_klass_infos = self.get_related_selections(
  1271. select,
  1272. field_select_mask,
  1273. opts=model._meta,
  1274. root_alias=alias,
  1275. cur_depth=cur_depth + 1,
  1276. requested=next_requested,
  1277. restricted=restricted,
  1278. )
  1279. get_related_klass_infos(klass_info, next_klass_infos)
  1280. fields_not_found = set(requested).difference(fields_found)
  1281. if fields_not_found:
  1282. invalid_fields = ("'%s'" % s for s in fields_not_found)
  1283. raise FieldError(
  1284. "Invalid field name(s) given in select_related: %s. "
  1285. "Choices are: %s"
  1286. % (
  1287. ", ".join(invalid_fields),
  1288. ", ".join(_get_field_choices()) or "(none)",
  1289. )
  1290. )
  1291. return related_klass_infos
  1292. def get_select_for_update_of_arguments(self):
  1293. """
  1294. Return a quoted list of arguments for the SELECT FOR UPDATE OF part of
  1295. the query.
  1296. """
  1297. def _get_parent_klass_info(klass_info):
  1298. concrete_model = klass_info["model"]._meta.concrete_model
  1299. for parent_model, parent_link in concrete_model._meta.parents.items():
  1300. parent_list = parent_model._meta.get_parent_list()
  1301. yield {
  1302. "model": parent_model,
  1303. "field": parent_link,
  1304. "reverse": False,
  1305. "select_fields": [
  1306. select_index
  1307. for select_index in klass_info["select_fields"]
  1308. # Selected columns from a model or its parents.
  1309. if (
  1310. self.select[select_index][0].target.model == parent_model
  1311. or self.select[select_index][0].target.model in parent_list
  1312. )
  1313. ],
  1314. }
  1315. def _get_first_selected_col_from_model(klass_info):
  1316. """
  1317. Find the first selected column from a model. If it doesn't exist,
  1318. don't lock a model.
  1319. select_fields is filled recursively, so it also contains fields
  1320. from the parent models.
  1321. """
  1322. concrete_model = klass_info["model"]._meta.concrete_model
  1323. for select_index in klass_info["select_fields"]:
  1324. if self.select[select_index][0].target.model == concrete_model:
  1325. return self.select[select_index][0]
  1326. def _get_field_choices():
  1327. """Yield all allowed field paths in breadth-first search order."""
  1328. queue = collections.deque([(None, self.klass_info)])
  1329. while queue:
  1330. parent_path, klass_info = queue.popleft()
  1331. if parent_path is None:
  1332. path = []
  1333. yield "self"
  1334. else:
  1335. field = klass_info["field"]
  1336. if klass_info["reverse"]:
  1337. field = field.remote_field
  1338. path = parent_path + [field.name]
  1339. yield LOOKUP_SEP.join(path)
  1340. queue.extend(
  1341. (path, klass_info)
  1342. for klass_info in _get_parent_klass_info(klass_info)
  1343. )
  1344. queue.extend(
  1345. (path, klass_info)
  1346. for klass_info in klass_info.get("related_klass_infos", [])
  1347. )
  1348. if not self.klass_info:
  1349. return []
  1350. result = []
  1351. invalid_names = []
  1352. for name in self.query.select_for_update_of:
  1353. klass_info = self.klass_info
  1354. if name == "self":
  1355. col = _get_first_selected_col_from_model(klass_info)
  1356. else:
  1357. for part in name.split(LOOKUP_SEP):
  1358. klass_infos = (
  1359. *klass_info.get("related_klass_infos", []),
  1360. *_get_parent_klass_info(klass_info),
  1361. )
  1362. for related_klass_info in klass_infos:
  1363. field = related_klass_info["field"]
  1364. if related_klass_info["reverse"]:
  1365. field = field.remote_field
  1366. if field.name == part:
  1367. klass_info = related_klass_info
  1368. break
  1369. else:
  1370. klass_info = None
  1371. break
  1372. if klass_info is None:
  1373. invalid_names.append(name)
  1374. continue
  1375. col = _get_first_selected_col_from_model(klass_info)
  1376. if col is not None:
  1377. if self.connection.features.select_for_update_of_column:
  1378. result.append(self.compile(col)[0])
  1379. else:
  1380. result.append(self.quote_name_unless_alias(col.alias))
  1381. if invalid_names:
  1382. raise FieldError(
  1383. "Invalid field name(s) given in select_for_update(of=(...)): %s. "
  1384. "Only relational fields followed in the query are allowed. "
  1385. "Choices are: %s."
  1386. % (
  1387. ", ".join(invalid_names),
  1388. ", ".join(_get_field_choices()),
  1389. )
  1390. )
  1391. return result
  1392. def get_converters(self, expressions):
  1393. converters = {}
  1394. for i, expression in enumerate(expressions):
  1395. if expression:
  1396. backend_converters = self.connection.ops.get_db_converters(expression)
  1397. field_converters = expression.get_db_converters(self.connection)
  1398. if backend_converters or field_converters:
  1399. converters[i] = (backend_converters + field_converters, expression)
  1400. return converters
  1401. def apply_converters(self, rows, converters):
  1402. connection = self.connection
  1403. converters = list(converters.items())
  1404. for row in map(list, rows):
  1405. for pos, (convs, expression) in converters:
  1406. value = row[pos]
  1407. for converter in convs:
  1408. value = converter(value, expression, connection)
  1409. row[pos] = value
  1410. yield row
  1411. def results_iter(
  1412. self,
  1413. results=None,
  1414. tuple_expected=False,
  1415. chunked_fetch=False,
  1416. chunk_size=GET_ITERATOR_CHUNK_SIZE,
  1417. ):
  1418. """Return an iterator over the results from executing this query."""
  1419. if results is None:
  1420. results = self.execute_sql(
  1421. MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size
  1422. )
  1423. fields = [s[0] for s in self.select[0 : self.col_count]]
  1424. converters = self.get_converters(fields)
  1425. rows = chain.from_iterable(results)
  1426. if converters:
  1427. rows = self.apply_converters(rows, converters)
  1428. if tuple_expected:
  1429. rows = map(tuple, rows)
  1430. return rows
  1431. def has_results(self):
  1432. """
  1433. Backends (e.g. NoSQL) can override this in order to use optimized
  1434. versions of "query has any results."
  1435. """
  1436. return bool(self.execute_sql(SINGLE))
  1437. def execute_sql(
  1438. self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE
  1439. ):
  1440. """
  1441. Run the query against the database and return the result(s). The
  1442. return value is a single data item if result_type is SINGLE, or an
  1443. iterator over the results if the result_type is MULTI.
  1444. result_type is either MULTI (use fetchmany() to retrieve all rows),
  1445. SINGLE (only retrieve a single row), or None. In this last case, the
  1446. cursor is returned if any query is executed, since it's used by
  1447. subclasses such as InsertQuery). It's possible, however, that no query
  1448. is needed, as the filters describe an empty set. In that case, None is
  1449. returned, to avoid any unnecessary database interaction.
  1450. """
  1451. result_type = result_type or NO_RESULTS
  1452. try:
  1453. sql, params = self.as_sql()
  1454. if not sql:
  1455. raise EmptyResultSet
  1456. except EmptyResultSet:
  1457. if result_type == MULTI:
  1458. return iter([])
  1459. else:
  1460. return
  1461. if chunked_fetch:
  1462. cursor = self.connection.chunked_cursor()
  1463. else:
  1464. cursor = self.connection.cursor()
  1465. try:
  1466. cursor.execute(sql, params)
  1467. except Exception:
  1468. # Might fail for server-side cursors (e.g. connection closed)
  1469. cursor.close()
  1470. raise
  1471. if result_type == CURSOR:
  1472. # Give the caller the cursor to process and close.
  1473. return cursor
  1474. if result_type == SINGLE:
  1475. try:
  1476. val = cursor.fetchone()
  1477. if val:
  1478. return val[0 : self.col_count]
  1479. return val
  1480. finally:
  1481. # done with the cursor
  1482. cursor.close()
  1483. if result_type == NO_RESULTS:
  1484. cursor.close()
  1485. return
  1486. result = cursor_iter(
  1487. cursor,
  1488. self.connection.features.empty_fetchmany_value,
  1489. self.col_count if self.has_extra_select else None,
  1490. chunk_size,
  1491. )
  1492. if not chunked_fetch or not self.connection.features.can_use_chunked_reads:
  1493. # If we are using non-chunked reads, we return the same data
  1494. # structure as normally, but ensure it is all read into memory
  1495. # before going any further. Use chunked_fetch if requested,
  1496. # unless the database doesn't support it.
  1497. return list(result)
  1498. return result
  1499. def as_subquery_condition(self, alias, columns, compiler):
  1500. qn = compiler.quote_name_unless_alias
  1501. qn2 = self.connection.ops.quote_name
  1502. for index, select_col in enumerate(self.query.select):
  1503. lhs_sql, lhs_params = self.compile(select_col)
  1504. rhs = "%s.%s" % (qn(alias), qn2(columns[index]))
  1505. self.query.where.add(RawSQL("%s = %s" % (lhs_sql, rhs), lhs_params), AND)
  1506. sql, params = self.as_sql()
  1507. return "EXISTS (%s)" % sql, params
  1508. def explain_query(self):
  1509. result = list(self.execute_sql())
  1510. # Some backends return 1 item tuples with strings, and others return
  1511. # tuples with integers and strings. Flatten them out into strings.
  1512. format_ = self.query.explain_info.format
  1513. output_formatter = json.dumps if format_ and format_.lower() == "json" else str
  1514. for row in result[0]:
  1515. if not isinstance(row, str):
  1516. yield " ".join(output_formatter(c) for c in row)
  1517. else:
  1518. yield row
  1519. class SQLInsertCompiler(SQLCompiler):
  1520. returning_fields = None
  1521. returning_params = ()
  1522. def field_as_sql(self, field, val):
  1523. """
  1524. Take a field and a value intended to be saved on that field, and
  1525. return placeholder SQL and accompanying params. Check for raw values,
  1526. expressions, and fields with get_placeholder() defined in that order.
  1527. When field is None, consider the value raw and use it as the
  1528. placeholder, with no corresponding parameters returned.
  1529. """
  1530. if field is None:
  1531. # A field value of None means the value is raw.
  1532. sql, params = val, []
  1533. elif hasattr(val, "as_sql"):
  1534. # This is an expression, let's compile it.
  1535. sql, params = self.compile(val)
  1536. elif hasattr(field, "get_placeholder"):
  1537. # Some fields (e.g. geo fields) need special munging before
  1538. # they can be inserted.
  1539. sql, params = field.get_placeholder(val, self, self.connection), [val]
  1540. else:
  1541. # Return the common case for the placeholder
  1542. sql, params = "%s", [val]
  1543. # The following hook is only used by Oracle Spatial, which sometimes
  1544. # needs to yield 'NULL' and [] as its placeholder and params instead
  1545. # of '%s' and [None]. The 'NULL' placeholder is produced earlier by
  1546. # OracleOperations.get_geom_placeholder(). The following line removes
  1547. # the corresponding None parameter. See ticket #10888.
  1548. params = self.connection.ops.modify_insert_params(sql, params)
  1549. return sql, params
  1550. def prepare_value(self, field, value):
  1551. """
  1552. Prepare a value to be used in a query by resolving it if it is an
  1553. expression and otherwise calling the field's get_db_prep_save().
  1554. """
  1555. if hasattr(value, "resolve_expression"):
  1556. value = value.resolve_expression(
  1557. self.query, allow_joins=False, for_save=True
  1558. )
  1559. # Don't allow values containing Col expressions. They refer to
  1560. # existing columns on a row, but in the case of insert the row
  1561. # doesn't exist yet.
  1562. if value.contains_column_references:
  1563. raise ValueError(
  1564. 'Failed to insert expression "%s" on %s. F() expressions '
  1565. "can only be used to update, not to insert." % (value, field)
  1566. )
  1567. if value.contains_aggregate:
  1568. raise FieldError(
  1569. "Aggregate functions are not allowed in this query "
  1570. "(%s=%r)." % (field.name, value)
  1571. )
  1572. if value.contains_over_clause:
  1573. raise FieldError(
  1574. "Window expressions are not allowed in this query (%s=%r)."
  1575. % (field.name, value)
  1576. )
  1577. return field.get_db_prep_save(value, connection=self.connection)
  1578. def pre_save_val(self, field, obj):
  1579. """
  1580. Get the given field's value off the given obj. pre_save() is used for
  1581. things like auto_now on DateTimeField. Skip it if this is a raw query.
  1582. """
  1583. if self.query.raw:
  1584. return getattr(obj, field.attname)
  1585. return field.pre_save(obj, add=True)
  1586. def assemble_as_sql(self, fields, value_rows):
  1587. """
  1588. Take a sequence of N fields and a sequence of M rows of values, and
  1589. generate placeholder SQL and parameters for each field and value.
  1590. Return a pair containing:
  1591. * a sequence of M rows of N SQL placeholder strings, and
  1592. * a sequence of M rows of corresponding parameter values.
  1593. Each placeholder string may contain any number of '%s' interpolation
  1594. strings, and each parameter row will contain exactly as many params
  1595. as the total number of '%s's in the corresponding placeholder row.
  1596. """
  1597. if not value_rows:
  1598. return [], []
  1599. # list of (sql, [params]) tuples for each object to be saved
  1600. # Shape: [n_objs][n_fields][2]
  1601. rows_of_fields_as_sql = (
  1602. (self.field_as_sql(field, v) for field, v in zip(fields, row))
  1603. for row in value_rows
  1604. )
  1605. # tuple like ([sqls], [[params]s]) for each object to be saved
  1606. # Shape: [n_objs][2][n_fields]
  1607. sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql)
  1608. # Extract separate lists for placeholders and params.
  1609. # Each of these has shape [n_objs][n_fields]
  1610. placeholder_rows, param_rows = zip(*sql_and_param_pair_rows)
  1611. # Params for each field are still lists, and need to be flattened.
  1612. param_rows = [[p for ps in row for p in ps] for row in param_rows]
  1613. return placeholder_rows, param_rows
  1614. def as_sql(self):
  1615. # We don't need quote_name_unless_alias() here, since these are all
  1616. # going to be column names (so we can avoid the extra overhead).
  1617. qn = self.connection.ops.quote_name
  1618. opts = self.query.get_meta()
  1619. insert_statement = self.connection.ops.insert_statement(
  1620. on_conflict=self.query.on_conflict,
  1621. )
  1622. result = ["%s %s" % (insert_statement, qn(opts.db_table))]
  1623. fields = self.query.fields or [opts.pk]
  1624. result.append("(%s)" % ", ".join(qn(f.column) for f in fields))
  1625. if self.query.fields:
  1626. value_rows = [
  1627. [
  1628. self.prepare_value(field, self.pre_save_val(field, obj))
  1629. for field in fields
  1630. ]
  1631. for obj in self.query.objs
  1632. ]
  1633. else:
  1634. # An empty object.
  1635. value_rows = [
  1636. [self.connection.ops.pk_default_value()] for _ in self.query.objs
  1637. ]
  1638. fields = [None]
  1639. # Currently the backends just accept values when generating bulk
  1640. # queries and generate their own placeholders. Doing that isn't
  1641. # necessary and it should be possible to use placeholders and
  1642. # expressions in bulk inserts too.
  1643. can_bulk = (
  1644. not self.returning_fields and self.connection.features.has_bulk_insert
  1645. )
  1646. placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows)
  1647. on_conflict_suffix_sql = self.connection.ops.on_conflict_suffix_sql(
  1648. fields,
  1649. self.query.on_conflict,
  1650. (f.column for f in self.query.update_fields),
  1651. (f.column for f in self.query.unique_fields),
  1652. )
  1653. if (
  1654. self.returning_fields
  1655. and self.connection.features.can_return_columns_from_insert
  1656. ):
  1657. if self.connection.features.can_return_rows_from_bulk_insert:
  1658. result.append(
  1659. self.connection.ops.bulk_insert_sql(fields, placeholder_rows)
  1660. )
  1661. params = param_rows
  1662. else:
  1663. result.append("VALUES (%s)" % ", ".join(placeholder_rows[0]))
  1664. params = [param_rows[0]]
  1665. if on_conflict_suffix_sql:
  1666. result.append(on_conflict_suffix_sql)
  1667. # Skip empty r_sql to allow subclasses to customize behavior for
  1668. # 3rd party backends. Refs #19096.
  1669. r_sql, self.returning_params = self.connection.ops.return_insert_columns(
  1670. self.returning_fields
  1671. )
  1672. if r_sql:
  1673. result.append(r_sql)
  1674. params += [self.returning_params]
  1675. return [(" ".join(result), tuple(chain.from_iterable(params)))]
  1676. if can_bulk:
  1677. result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
  1678. if on_conflict_suffix_sql:
  1679. result.append(on_conflict_suffix_sql)
  1680. return [(" ".join(result), tuple(p for ps in param_rows for p in ps))]
  1681. else:
  1682. if on_conflict_suffix_sql:
  1683. result.append(on_conflict_suffix_sql)
  1684. return [
  1685. (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
  1686. for p, vals in zip(placeholder_rows, param_rows)
  1687. ]
  1688. def execute_sql(self, returning_fields=None):
  1689. assert not (
  1690. returning_fields
  1691. and len(self.query.objs) != 1
  1692. and not self.connection.features.can_return_rows_from_bulk_insert
  1693. )
  1694. opts = self.query.get_meta()
  1695. self.returning_fields = returning_fields
  1696. with self.connection.cursor() as cursor:
  1697. for sql, params in self.as_sql():
  1698. cursor.execute(sql, params)
  1699. if not self.returning_fields:
  1700. return []
  1701. if (
  1702. self.connection.features.can_return_rows_from_bulk_insert
  1703. and len(self.query.objs) > 1
  1704. ):
  1705. rows = self.connection.ops.fetch_returned_insert_rows(cursor)
  1706. elif self.connection.features.can_return_columns_from_insert:
  1707. assert len(self.query.objs) == 1
  1708. rows = [
  1709. self.connection.ops.fetch_returned_insert_columns(
  1710. cursor,
  1711. self.returning_params,
  1712. )
  1713. ]
  1714. else:
  1715. rows = [
  1716. (
  1717. self.connection.ops.last_insert_id(
  1718. cursor,
  1719. opts.db_table,
  1720. opts.pk.column,
  1721. ),
  1722. )
  1723. ]
  1724. cols = [field.get_col(opts.db_table) for field in self.returning_fields]
  1725. converters = self.get_converters(cols)
  1726. if converters:
  1727. rows = list(self.apply_converters(rows, converters))
  1728. return rows
  1729. class SQLDeleteCompiler(SQLCompiler):
  1730. @cached_property
  1731. def single_alias(self):
  1732. # Ensure base table is in aliases.
  1733. self.query.get_initial_alias()
  1734. return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1
  1735. @classmethod
  1736. def _expr_refs_base_model(cls, expr, base_model):
  1737. if isinstance(expr, Query):
  1738. return expr.model == base_model
  1739. if not hasattr(expr, "get_source_expressions"):
  1740. return False
  1741. return any(
  1742. cls._expr_refs_base_model(source_expr, base_model)
  1743. for source_expr in expr.get_source_expressions()
  1744. )
  1745. @cached_property
  1746. def contains_self_reference_subquery(self):
  1747. return any(
  1748. self._expr_refs_base_model(expr, self.query.model)
  1749. for expr in chain(
  1750. self.query.annotations.values(), self.query.where.children
  1751. )
  1752. )
  1753. def _as_sql(self, query):
  1754. delete = "DELETE FROM %s" % self.quote_name_unless_alias(query.base_table)
  1755. try:
  1756. where, params = self.compile(query.where)
  1757. except FullResultSet:
  1758. return delete, ()
  1759. return f"{delete} WHERE {where}", tuple(params)
  1760. def as_sql(self):
  1761. """
  1762. Create the SQL for this query. Return the SQL string and list of
  1763. parameters.
  1764. """
  1765. if self.single_alias and (
  1766. self.connection.features.delete_can_self_reference_subquery
  1767. or not self.contains_self_reference_subquery
  1768. ):
  1769. return self._as_sql(self.query)
  1770. innerq = self.query.clone()
  1771. innerq.__class__ = Query
  1772. innerq.clear_select_clause()
  1773. pk = self.query.model._meta.pk
  1774. innerq.select = [pk.get_col(self.query.get_initial_alias())]
  1775. outerq = Query(self.query.model)
  1776. if not self.connection.features.update_can_self_select:
  1777. # Force the materialization of the inner query to allow reference
  1778. # to the target table on MySQL.
  1779. sql, params = innerq.get_compiler(connection=self.connection).as_sql()
  1780. innerq = RawSQL("SELECT * FROM (%s) subquery" % sql, params)
  1781. outerq.add_filter("pk__in", innerq)
  1782. return self._as_sql(outerq)
  1783. class SQLUpdateCompiler(SQLCompiler):
  1784. def as_sql(self):
  1785. """
  1786. Create the SQL for this query. Return the SQL string and list of
  1787. parameters.
  1788. """
  1789. self.pre_sql_setup()
  1790. if not self.query.values:
  1791. return "", ()
  1792. qn = self.quote_name_unless_alias
  1793. values, update_params = [], []
  1794. for field, model, val in self.query.values:
  1795. if hasattr(val, "resolve_expression"):
  1796. val = val.resolve_expression(
  1797. self.query, allow_joins=False, for_save=True
  1798. )
  1799. if val.contains_aggregate:
  1800. raise FieldError(
  1801. "Aggregate functions are not allowed in this query "
  1802. "(%s=%r)." % (field.name, val)
  1803. )
  1804. if val.contains_over_clause:
  1805. raise FieldError(
  1806. "Window expressions are not allowed in this query "
  1807. "(%s=%r)." % (field.name, val)
  1808. )
  1809. elif hasattr(val, "prepare_database_save"):
  1810. if field.remote_field:
  1811. val = val.prepare_database_save(field)
  1812. else:
  1813. raise TypeError(
  1814. "Tried to update field %s with a model instance, %r. "
  1815. "Use a value compatible with %s."
  1816. % (field, val, field.__class__.__name__)
  1817. )
  1818. val = field.get_db_prep_save(val, connection=self.connection)
  1819. # Getting the placeholder for the field.
  1820. if hasattr(field, "get_placeholder"):
  1821. placeholder = field.get_placeholder(val, self, self.connection)
  1822. else:
  1823. placeholder = "%s"
  1824. name = field.column
  1825. if hasattr(val, "as_sql"):
  1826. sql, params = self.compile(val)
  1827. values.append("%s = %s" % (qn(name), placeholder % sql))
  1828. update_params.extend(params)
  1829. elif val is not None:
  1830. values.append("%s = %s" % (qn(name), placeholder))
  1831. update_params.append(val)
  1832. else:
  1833. values.append("%s = NULL" % qn(name))
  1834. table = self.query.base_table
  1835. result = [
  1836. "UPDATE %s SET" % qn(table),
  1837. ", ".join(values),
  1838. ]
  1839. try:
  1840. where, params = self.compile(self.query.where)
  1841. except FullResultSet:
  1842. params = []
  1843. else:
  1844. result.append("WHERE %s" % where)
  1845. return " ".join(result), tuple(update_params + params)
  1846. def execute_sql(self, result_type):
  1847. """
  1848. Execute the specified update. Return the number of rows affected by
  1849. the primary update query. The "primary update query" is the first
  1850. non-empty query that is executed. Row counts for any subsequent,
  1851. related queries are not available.
  1852. """
  1853. cursor = super().execute_sql(result_type)
  1854. try:
  1855. rows = cursor.rowcount if cursor else 0
  1856. is_empty = cursor is None
  1857. finally:
  1858. if cursor:
  1859. cursor.close()
  1860. for query in self.query.get_related_updates():
  1861. aux_rows = query.get_compiler(self.using).execute_sql(result_type)
  1862. if is_empty and aux_rows:
  1863. rows = aux_rows
  1864. is_empty = False
  1865. return rows
  1866. def pre_sql_setup(self):
  1867. """
  1868. If the update depends on results from other tables, munge the "where"
  1869. conditions to match the format required for (portable) SQL updates.
  1870. If multiple updates are required, pull out the id values to update at
  1871. this point so that they don't change as a result of the progressive
  1872. updates.
  1873. """
  1874. refcounts_before = self.query.alias_refcount.copy()
  1875. # Ensure base table is in the query
  1876. self.query.get_initial_alias()
  1877. count = self.query.count_active_tables()
  1878. if not self.query.related_updates and count == 1:
  1879. return
  1880. query = self.query.chain(klass=Query)
  1881. query.select_related = False
  1882. query.clear_ordering(force=True)
  1883. query.extra = {}
  1884. query.select = []
  1885. meta = query.get_meta()
  1886. fields = [meta.pk.name]
  1887. related_ids_index = []
  1888. for related in self.query.related_updates:
  1889. if all(
  1890. path.join_field.primary_key for path in meta.get_path_to_parent(related)
  1891. ):
  1892. # If a primary key chain exists to the targeted related update,
  1893. # then the meta.pk value can be used for it.
  1894. related_ids_index.append((related, 0))
  1895. else:
  1896. # This branch will only be reached when updating a field of an
  1897. # ancestor that is not part of the primary key chain of a MTI
  1898. # tree.
  1899. related_ids_index.append((related, len(fields)))
  1900. fields.append(related._meta.pk.name)
  1901. query.add_fields(fields)
  1902. super().pre_sql_setup()
  1903. must_pre_select = (
  1904. count > 1 and not self.connection.features.update_can_self_select
  1905. )
  1906. # Now we adjust the current query: reset the where clause and get rid
  1907. # of all the tables we don't need (since they're in the sub-select).
  1908. self.query.clear_where()
  1909. if self.query.related_updates or must_pre_select:
  1910. # Either we're using the idents in multiple update queries (so
  1911. # don't want them to change), or the db backend doesn't support
  1912. # selecting from the updating table (e.g. MySQL).
  1913. idents = []
  1914. related_ids = collections.defaultdict(list)
  1915. for rows in query.get_compiler(self.using).execute_sql(MULTI):
  1916. idents.extend(r[0] for r in rows)
  1917. for parent, index in related_ids_index:
  1918. related_ids[parent].extend(r[index] for r in rows)
  1919. self.query.add_filter("pk__in", idents)
  1920. self.query.related_ids = related_ids
  1921. else:
  1922. # The fast path. Filters and updates in one query.
  1923. self.query.add_filter("pk__in", query)
  1924. self.query.reset_refcounts(refcounts_before)
  1925. class SQLAggregateCompiler(SQLCompiler):
  1926. def as_sql(self):
  1927. """
  1928. Create the SQL for this query. Return the SQL string and list of
  1929. parameters.
  1930. """
  1931. sql, params = [], []
  1932. for annotation in self.query.annotation_select.values():
  1933. ann_sql, ann_params = self.compile(annotation)
  1934. ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params)
  1935. sql.append(ann_sql)
  1936. params.extend(ann_params)
  1937. self.col_count = len(self.query.annotation_select)
  1938. sql = ", ".join(sql)
  1939. params = tuple(params)
  1940. inner_query_sql, inner_query_params = self.query.inner_query.get_compiler(
  1941. self.using,
  1942. elide_empty=self.elide_empty,
  1943. ).as_sql(with_col_aliases=True)
  1944. sql = "SELECT %s FROM (%s) subquery" % (sql, inner_query_sql)
  1945. params += inner_query_params
  1946. return sql, params
  1947. def cursor_iter(cursor, sentinel, col_count, itersize):
  1948. """
  1949. Yield blocks of rows from a cursor and ensure the cursor is closed when
  1950. done.
  1951. """
  1952. try:
  1953. for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
  1954. yield rows if col_count is None else [r[:col_count] for r in rows]
  1955. finally:
  1956. cursor.close()