compiler.py 93 KB

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