compiler.py 88 KB

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