compiler.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  1. import collections
  2. import re
  3. import warnings
  4. from functools import partial
  5. from itertools import chain
  6. from django.core.exceptions import EmptyResultSet, FieldError
  7. from django.db.models.constants import LOOKUP_SEP
  8. from django.db.models.expressions import OrderBy, Random, RawSQL, Ref, Value
  9. from django.db.models.functions import Cast
  10. from django.db.models.query_utils import QueryWrapper, select_related_descend
  11. from django.db.models.sql.constants import (
  12. CURSOR, GET_ITERATOR_CHUNK_SIZE, MULTI, NO_RESULTS, ORDER_DIR, SINGLE,
  13. )
  14. from django.db.models.sql.query import Query, get_order_dir
  15. from django.db.transaction import TransactionManagementError
  16. from django.db.utils import DatabaseError, NotSupportedError
  17. from django.utils.deprecation import RemovedInDjango31Warning
  18. from django.utils.hashable import make_hashable
  19. class SQLCompiler:
  20. def __init__(self, query, connection, using):
  21. self.query = query
  22. self.connection = connection
  23. self.using = using
  24. self.quote_cache = {'*': '*'}
  25. # The select, klass_info, and annotations are needed by QuerySet.iterator()
  26. # these are set as a side-effect of executing the query. Note that we calculate
  27. # separately a list of extra select columns needed for grammatical correctness
  28. # of the query, but these columns are not included in self.select.
  29. self.select = None
  30. self.annotation_col_map = None
  31. self.klass_info = None
  32. # Multiline ordering SQL clause may appear from RawSQL.
  33. self.ordering_parts = re.compile(r'^(.*)\s(ASC|DESC)(.*)', re.MULTILINE | re.DOTALL)
  34. self._meta_ordering = None
  35. def setup_query(self):
  36. if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map):
  37. self.query.get_initial_alias()
  38. self.select, self.klass_info, self.annotation_col_map = self.get_select()
  39. self.col_count = len(self.select)
  40. def pre_sql_setup(self):
  41. """
  42. Do any necessary class setup immediately prior to producing SQL. This
  43. is for things that can't necessarily be done in __init__ because we
  44. might not have all the pieces in place at that time.
  45. """
  46. self.setup_query()
  47. order_by = self.get_order_by()
  48. self.where, self.having = self.query.where.split_having()
  49. extra_select = self.get_extra_select(order_by, self.select)
  50. self.has_extra_select = bool(extra_select)
  51. group_by = self.get_group_by(self.select + extra_select, order_by)
  52. return extra_select, order_by, group_by
  53. def get_group_by(self, select, order_by):
  54. """
  55. Return a list of 2-tuples of form (sql, params).
  56. The logic of what exactly the GROUP BY clause contains is hard
  57. to describe in other words than "if it passes the test suite,
  58. then it is correct".
  59. """
  60. # Some examples:
  61. # SomeModel.objects.annotate(Count('somecol'))
  62. # GROUP BY: all fields of the model
  63. #
  64. # SomeModel.objects.values('name').annotate(Count('somecol'))
  65. # GROUP BY: name
  66. #
  67. # SomeModel.objects.annotate(Count('somecol')).values('name')
  68. # GROUP BY: all cols of the model
  69. #
  70. # SomeModel.objects.values('name', 'pk').annotate(Count('somecol')).values('pk')
  71. # GROUP BY: name, pk
  72. #
  73. # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk')
  74. # GROUP BY: name, pk
  75. #
  76. # In fact, the self.query.group_by is the minimal set to GROUP BY. It
  77. # can't be ever restricted to a smaller set, but additional columns in
  78. # HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately
  79. # the end result is that it is impossible to force the query to have
  80. # a chosen GROUP BY clause - you can almost do this by using the form:
  81. # .values(*wanted_cols).annotate(AnAggregate())
  82. # but any later annotations, extra selects, values calls that
  83. # refer some column outside of the wanted_cols, order_by, or even
  84. # filter calls can alter the GROUP BY clause.
  85. # The query.group_by is either None (no GROUP BY at all), True
  86. # (group by select fields), or a list of expressions to be added
  87. # to the group by.
  88. if self.query.group_by is None:
  89. return []
  90. expressions = []
  91. if self.query.group_by is not True:
  92. # If the group by is set to a list (by .values() call most likely),
  93. # then we need to add everything in it to the GROUP BY clause.
  94. # Backwards compatibility hack for setting query.group_by. Remove
  95. # when we have public API way of forcing the GROUP BY clause.
  96. # Converts string references to expressions.
  97. for expr in self.query.group_by:
  98. if not hasattr(expr, 'as_sql'):
  99. expressions.append(self.query.resolve_ref(expr))
  100. else:
  101. expressions.append(expr)
  102. # Note that even if the group_by is set, it is only the minimal
  103. # set to group by. So, we need to add cols in select, order_by, and
  104. # having into the select in any case.
  105. ref_sources = {
  106. expr.source for expr in expressions if isinstance(expr, Ref)
  107. }
  108. for expr, _, _ in select:
  109. # Skip members of the select clause that are already included
  110. # by reference.
  111. if expr in ref_sources:
  112. continue
  113. cols = expr.get_group_by_cols()
  114. for col in cols:
  115. expressions.append(col)
  116. for expr, (sql, params, is_ref) in order_by:
  117. # Skip References to the select clause, as all expressions in the
  118. # select clause are already part of the group by.
  119. if not is_ref:
  120. expressions.extend(expr.get_group_by_cols())
  121. having_group_by = self.having.get_group_by_cols() if self.having else ()
  122. for expr in having_group_by:
  123. expressions.append(expr)
  124. result = []
  125. seen = set()
  126. expressions = self.collapse_group_by(expressions, having_group_by)
  127. for expr in expressions:
  128. sql, params = self.compile(expr)
  129. params_hash = make_hashable(params)
  130. if (sql, params_hash) not in seen:
  131. result.append((sql, params))
  132. seen.add((sql, params_hash))
  133. return result
  134. def collapse_group_by(self, expressions, having):
  135. # If the DB can group by primary key, then group by the primary key of
  136. # query's main model. Note that for PostgreSQL the GROUP BY clause must
  137. # include the primary key of every table, but for MySQL it is enough to
  138. # have the main table's primary key.
  139. if self.connection.features.allows_group_by_pk:
  140. # Determine if the main model's primary key is in the query.
  141. pk = None
  142. for expr in expressions:
  143. # Is this a reference to query's base table primary key? If the
  144. # expression isn't a Col-like, then skip the expression.
  145. if (getattr(expr, 'target', None) == self.query.model._meta.pk and
  146. getattr(expr, 'alias', None) == self.query.base_table):
  147. pk = expr
  148. break
  149. # If the main model's primary key is in the query, group by that
  150. # field, HAVING expressions, and expressions associated with tables
  151. # that don't have a primary key included in the grouped columns.
  152. if pk:
  153. pk_aliases = {
  154. expr.alias for expr in expressions
  155. if hasattr(expr, 'target') and expr.target.primary_key
  156. }
  157. expressions = [pk] + [
  158. expr for expr in expressions
  159. if expr in having or (
  160. getattr(expr, 'alias', None) is not None and expr.alias not in pk_aliases
  161. )
  162. ]
  163. elif self.connection.features.allows_group_by_selected_pks:
  164. # Filter out all expressions associated with a table's primary key
  165. # present in the grouped columns. This is done by identifying all
  166. # tables that have their primary key included in the grouped
  167. # columns and removing non-primary key columns referring to them.
  168. # Unmanaged models are excluded because they could be representing
  169. # database views on which the optimization might not be allowed.
  170. pks = {
  171. expr for expr in expressions
  172. if (
  173. hasattr(expr, 'target') and
  174. expr.target.primary_key and
  175. self.connection.features.allows_group_by_selected_pks_on_model(expr.target.model)
  176. )
  177. }
  178. aliases = {expr.alias for expr in pks}
  179. expressions = [
  180. expr for expr in expressions if expr in pks or getattr(expr, 'alias', None) not in aliases
  181. ]
  182. return expressions
  183. def get_select(self):
  184. """
  185. Return three values:
  186. - a list of 3-tuples of (expression, (sql, params), alias)
  187. - a klass_info structure,
  188. - a dictionary of annotations
  189. The (sql, params) is what the expression will produce, and alias is the
  190. "AS alias" for the column (possibly None).
  191. The klass_info structure contains the following information:
  192. - The base model of the query.
  193. - Which columns for that model are present in the query (by
  194. position of the select clause).
  195. - related_klass_infos: [f, klass_info] to descent into
  196. The annotations is a dictionary of {'attname': column position} values.
  197. """
  198. select = []
  199. klass_info = None
  200. annotations = {}
  201. select_idx = 0
  202. for alias, (sql, params) in self.query.extra_select.items():
  203. annotations[alias] = select_idx
  204. select.append((RawSQL(sql, params), alias))
  205. select_idx += 1
  206. assert not (self.query.select and self.query.default_cols)
  207. if self.query.default_cols:
  208. cols = self.get_default_columns()
  209. else:
  210. # self.query.select is a special case. These columns never go to
  211. # any model.
  212. cols = self.query.select
  213. if cols:
  214. select_list = []
  215. for col in cols:
  216. select_list.append(select_idx)
  217. select.append((col, None))
  218. select_idx += 1
  219. klass_info = {
  220. 'model': self.query.model,
  221. 'select_fields': select_list,
  222. }
  223. for alias, annotation in self.query.annotation_select.items():
  224. annotations[alias] = select_idx
  225. select.append((annotation, alias))
  226. select_idx += 1
  227. if self.query.select_related:
  228. related_klass_infos = self.get_related_selections(select)
  229. klass_info['related_klass_infos'] = related_klass_infos
  230. def get_select_from_parent(klass_info):
  231. for ki in klass_info['related_klass_infos']:
  232. if ki['from_parent']:
  233. ki['select_fields'] = (klass_info['select_fields'] +
  234. ki['select_fields'])
  235. get_select_from_parent(ki)
  236. get_select_from_parent(klass_info)
  237. ret = []
  238. for col, alias in select:
  239. try:
  240. sql, params = self.compile(col)
  241. except EmptyResultSet:
  242. # Select a predicate that's always False.
  243. sql, params = '0', ()
  244. else:
  245. sql, params = col.select_format(self, sql, params)
  246. ret.append((col, (sql, params), alias))
  247. return ret, klass_info, annotations
  248. def get_order_by(self):
  249. """
  250. Return a list of 2-tuples of form (expr, (sql, params, is_ref)) for the
  251. ORDER BY clause.
  252. The order_by clause can alter the select clause (for example it
  253. can add aliases to clauses that do not yet have one, or it can
  254. add totally new select clauses).
  255. """
  256. if self.query.extra_order_by:
  257. ordering = self.query.extra_order_by
  258. elif not self.query.default_ordering:
  259. ordering = self.query.order_by
  260. elif self.query.order_by:
  261. ordering = self.query.order_by
  262. elif self.query.get_meta().ordering:
  263. ordering = self.query.get_meta().ordering
  264. self._meta_ordering = ordering
  265. else:
  266. ordering = []
  267. if self.query.standard_ordering:
  268. asc, desc = ORDER_DIR['ASC']
  269. else:
  270. asc, desc = ORDER_DIR['DESC']
  271. order_by = []
  272. for field in ordering:
  273. if hasattr(field, 'resolve_expression'):
  274. if isinstance(field, Value):
  275. # output_field must be resolved for constants.
  276. field = Cast(field, field.output_field)
  277. if not isinstance(field, OrderBy):
  278. field = field.asc()
  279. if not self.query.standard_ordering:
  280. field = field.copy()
  281. field.reverse_ordering()
  282. order_by.append((field, False))
  283. continue
  284. if field == '?': # random
  285. order_by.append((OrderBy(Random()), False))
  286. continue
  287. col, order = get_order_dir(field, asc)
  288. descending = order == 'DESC'
  289. if col in self.query.annotation_select:
  290. # Reference to expression in SELECT clause
  291. order_by.append((
  292. OrderBy(Ref(col, self.query.annotation_select[col]), descending=descending),
  293. True))
  294. continue
  295. if col in self.query.annotations:
  296. # References to an expression which is masked out of the SELECT
  297. # clause.
  298. expr = self.query.annotations[col]
  299. if isinstance(expr, Value):
  300. # output_field must be resolved for constants.
  301. expr = Cast(expr, expr.output_field)
  302. order_by.append((OrderBy(expr, descending=descending), False))
  303. continue
  304. if '.' in field:
  305. # This came in through an extra(order_by=...) addition. Pass it
  306. # on verbatim.
  307. table, col = col.split('.', 1)
  308. order_by.append((
  309. OrderBy(
  310. RawSQL('%s.%s' % (self.quote_name_unless_alias(table), col), []),
  311. descending=descending
  312. ), False))
  313. continue
  314. if not self.query.extra or col not in self.query.extra:
  315. # 'col' is of the form 'field' or 'field1__field2' or
  316. # '-field1__field2__field', etc.
  317. order_by.extend(self.find_ordering_name(
  318. field, self.query.get_meta(), default_order=asc))
  319. else:
  320. if col not in self.query.extra_select:
  321. order_by.append((
  322. OrderBy(RawSQL(*self.query.extra[col]), descending=descending),
  323. False))
  324. else:
  325. order_by.append((
  326. OrderBy(Ref(col, RawSQL(*self.query.extra[col])), descending=descending),
  327. True))
  328. result = []
  329. seen = set()
  330. for expr, is_ref in order_by:
  331. resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
  332. if self.query.combinator:
  333. src = resolved.get_source_expressions()[0]
  334. # Relabel order by columns to raw numbers if this is a combined
  335. # query; necessary since the columns can't be referenced by the
  336. # fully qualified name and the simple column names may collide.
  337. for idx, (sel_expr, _, col_alias) in enumerate(self.select):
  338. if is_ref and col_alias == src.refs:
  339. src = src.source
  340. elif col_alias:
  341. continue
  342. if src == sel_expr:
  343. resolved.set_source_expressions([RawSQL('%d' % (idx + 1), ())])
  344. break
  345. else:
  346. if col_alias:
  347. raise DatabaseError('ORDER BY term does not match any column in the result set.')
  348. # Add column used in ORDER BY clause without an alias to
  349. # the selected columns.
  350. self.query.add_select_col(src)
  351. resolved.set_source_expressions([RawSQL('%d' % len(self.query.select), ())])
  352. sql, params = self.compile(resolved)
  353. # Don't add the same column twice, but the order direction is
  354. # not taken into account so we strip it. When this entire method
  355. # is refactored into expressions, then we can check each part as we
  356. # generate it.
  357. without_ordering = self.ordering_parts.search(sql).group(1)
  358. params_hash = make_hashable(params)
  359. if (without_ordering, params_hash) in seen:
  360. continue
  361. seen.add((without_ordering, params_hash))
  362. result.append((resolved, (sql, params, is_ref)))
  363. return result
  364. def get_extra_select(self, order_by, select):
  365. extra_select = []
  366. if self.query.distinct and not self.query.distinct_fields:
  367. select_sql = [t[1] for t in select]
  368. for expr, (sql, params, is_ref) in order_by:
  369. without_ordering = self.ordering_parts.search(sql).group(1)
  370. if not is_ref and (without_ordering, params) not in select_sql:
  371. extra_select.append((expr, (without_ordering, params), None))
  372. return extra_select
  373. def quote_name_unless_alias(self, name):
  374. """
  375. A wrapper around connection.ops.quote_name that doesn't quote aliases
  376. for table names. This avoids problems with some SQL dialects that treat
  377. quoted strings specially (e.g. PostgreSQL).
  378. """
  379. if name in self.quote_cache:
  380. return self.quote_cache[name]
  381. if ((name in self.query.alias_map and name not in self.query.table_map) or
  382. name in self.query.extra_select or (
  383. self.query.external_aliases.get(name) and name not in self.query.table_map)):
  384. self.quote_cache[name] = name
  385. return name
  386. r = self.connection.ops.quote_name(name)
  387. self.quote_cache[name] = r
  388. return r
  389. def compile(self, node):
  390. vendor_impl = getattr(node, 'as_' + self.connection.vendor, None)
  391. if vendor_impl:
  392. sql, params = vendor_impl(self, self.connection)
  393. else:
  394. sql, params = node.as_sql(self, self.connection)
  395. return sql, params
  396. def get_combinator_sql(self, combinator, all):
  397. features = self.connection.features
  398. compilers = [
  399. query.get_compiler(self.using, self.connection)
  400. for query in self.query.combined_queries if not query.is_empty()
  401. ]
  402. if not features.supports_slicing_ordering_in_compound:
  403. for query, compiler in zip(self.query.combined_queries, compilers):
  404. if query.low_mark or query.high_mark:
  405. raise DatabaseError('LIMIT/OFFSET not allowed in subqueries of compound statements.')
  406. if compiler.get_order_by():
  407. raise DatabaseError('ORDER BY not allowed in subqueries of compound statements.')
  408. parts = ()
  409. for compiler in compilers:
  410. try:
  411. # If the columns list is limited, then all combined queries
  412. # must have the same columns list. Set the selects defined on
  413. # the query on all combined queries, if not already set.
  414. if not compiler.query.values_select and self.query.values_select:
  415. compiler.query = compiler.query.clone()
  416. compiler.query.set_values((
  417. *self.query.extra_select,
  418. *self.query.values_select,
  419. *self.query.annotation_select,
  420. ))
  421. part_sql, part_args = compiler.as_sql()
  422. if compiler.query.combinator:
  423. # Wrap in a subquery if wrapping in parentheses isn't
  424. # supported.
  425. if not features.supports_parentheses_in_compound:
  426. part_sql = 'SELECT * FROM ({})'.format(part_sql)
  427. # Add parentheses when combining with compound query if not
  428. # already added for all compound queries.
  429. elif not features.supports_slicing_ordering_in_compound:
  430. part_sql = '({})'.format(part_sql)
  431. parts += ((part_sql, part_args),)
  432. except EmptyResultSet:
  433. # Omit the empty queryset with UNION and with DIFFERENCE if the
  434. # first queryset is nonempty.
  435. if combinator == 'union' or (combinator == 'difference' and parts):
  436. continue
  437. raise
  438. if not parts:
  439. raise EmptyResultSet
  440. combinator_sql = self.connection.ops.set_operators[combinator]
  441. if all and combinator == 'union':
  442. combinator_sql += ' ALL'
  443. braces = '({})' if features.supports_slicing_ordering_in_compound else '{}'
  444. sql_parts, args_parts = zip(*((braces.format(sql), args) for sql, args in parts))
  445. result = [' {} '.format(combinator_sql).join(sql_parts)]
  446. params = []
  447. for part in args_parts:
  448. params.extend(part)
  449. return result, params
  450. def as_sql(self, with_limits=True, with_col_aliases=False):
  451. """
  452. Create the SQL for this query. Return the SQL string and list of
  453. parameters.
  454. If 'with_limits' is False, any limit/offset information is not included
  455. in the query.
  456. """
  457. refcounts_before = self.query.alias_refcount.copy()
  458. try:
  459. extra_select, order_by, group_by = self.pre_sql_setup()
  460. for_update_part = None
  461. # Is a LIMIT/OFFSET clause needed?
  462. with_limit_offset = with_limits and (self.query.high_mark is not None or self.query.low_mark)
  463. combinator = self.query.combinator
  464. features = self.connection.features
  465. if combinator:
  466. if not getattr(features, 'supports_select_{}'.format(combinator)):
  467. raise NotSupportedError('{} is not supported on this database backend.'.format(combinator))
  468. result, params = self.get_combinator_sql(combinator, self.query.combinator_all)
  469. else:
  470. distinct_fields, distinct_params = self.get_distinct()
  471. # This must come after 'select', 'ordering', and 'distinct'
  472. # (see docstring of get_from_clause() for details).
  473. from_, f_params = self.get_from_clause()
  474. where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  475. having, h_params = self.compile(self.having) if self.having is not None else ("", [])
  476. result = ['SELECT']
  477. params = []
  478. if self.query.distinct:
  479. distinct_result, distinct_params = self.connection.ops.distinct_sql(
  480. distinct_fields,
  481. distinct_params,
  482. )
  483. result += distinct_result
  484. params += distinct_params
  485. out_cols = []
  486. col_idx = 1
  487. for _, (s_sql, s_params), alias in self.select + extra_select:
  488. if alias:
  489. s_sql = '%s AS %s' % (s_sql, self.connection.ops.quote_name(alias))
  490. elif with_col_aliases:
  491. s_sql = '%s AS %s' % (s_sql, 'Col%d' % col_idx)
  492. col_idx += 1
  493. params.extend(s_params)
  494. out_cols.append(s_sql)
  495. result += [', '.join(out_cols), 'FROM', *from_]
  496. params.extend(f_params)
  497. if self.query.select_for_update and self.connection.features.has_select_for_update:
  498. if self.connection.get_autocommit():
  499. raise TransactionManagementError('select_for_update cannot be used outside of a transaction.')
  500. if with_limit_offset and not self.connection.features.supports_select_for_update_with_limit:
  501. raise NotSupportedError(
  502. 'LIMIT/OFFSET is not supported with '
  503. 'select_for_update on this database backend.'
  504. )
  505. nowait = self.query.select_for_update_nowait
  506. skip_locked = self.query.select_for_update_skip_locked
  507. of = self.query.select_for_update_of
  508. # If it's a NOWAIT/SKIP LOCKED/OF query but the backend
  509. # doesn't support it, raise NotSupportedError to prevent a
  510. # possible deadlock.
  511. if nowait and not self.connection.features.has_select_for_update_nowait:
  512. raise NotSupportedError('NOWAIT is not supported on this database backend.')
  513. elif skip_locked and not self.connection.features.has_select_for_update_skip_locked:
  514. raise NotSupportedError('SKIP LOCKED is not supported on this database backend.')
  515. elif of and not self.connection.features.has_select_for_update_of:
  516. raise NotSupportedError('FOR UPDATE OF is not supported on this database backend.')
  517. for_update_part = self.connection.ops.for_update_sql(
  518. nowait=nowait,
  519. skip_locked=skip_locked,
  520. of=self.get_select_for_update_of_arguments(),
  521. )
  522. if for_update_part and self.connection.features.for_update_after_from:
  523. result.append(for_update_part)
  524. if where:
  525. result.append('WHERE %s' % where)
  526. params.extend(w_params)
  527. grouping = []
  528. for g_sql, g_params in group_by:
  529. grouping.append(g_sql)
  530. params.extend(g_params)
  531. if grouping:
  532. if distinct_fields:
  533. raise NotImplementedError('annotate() + distinct(fields) is not implemented.')
  534. order_by = order_by or self.connection.ops.force_no_ordering()
  535. result.append('GROUP BY %s' % ', '.join(grouping))
  536. if self._meta_ordering:
  537. # When the deprecation ends, replace with:
  538. # order_by = None
  539. warnings.warn(
  540. "%s QuerySet won't use Meta.ordering in Django 3.1. "
  541. "Add .order_by(%s) to retain the current query." % (
  542. self.query.model.__name__,
  543. ', '.join(repr(f) for f in self._meta_ordering),
  544. ),
  545. RemovedInDjango31Warning,
  546. stacklevel=4,
  547. )
  548. if having:
  549. result.append('HAVING %s' % having)
  550. params.extend(h_params)
  551. if self.query.explain_query:
  552. result.insert(0, self.connection.ops.explain_query_prefix(
  553. self.query.explain_format,
  554. **self.query.explain_options
  555. ))
  556. if order_by:
  557. ordering = []
  558. for _, (o_sql, o_params, _) in order_by:
  559. ordering.append(o_sql)
  560. params.extend(o_params)
  561. result.append('ORDER BY %s' % ', '.join(ordering))
  562. if with_limit_offset:
  563. result.append(self.connection.ops.limit_offset_sql(self.query.low_mark, self.query.high_mark))
  564. if for_update_part and not self.connection.features.for_update_after_from:
  565. result.append(for_update_part)
  566. if self.query.subquery and extra_select:
  567. # If the query is used as a subquery, the extra selects would
  568. # result in more columns than the left-hand side expression is
  569. # expecting. This can happen when a subquery uses a combination
  570. # of order_by() and distinct(), forcing the ordering expressions
  571. # to be selected as well. Wrap the query in another subquery
  572. # to exclude extraneous selects.
  573. sub_selects = []
  574. sub_params = []
  575. for index, (select, _, alias) in enumerate(self.select, start=1):
  576. if not alias and with_col_aliases:
  577. alias = 'col%d' % index
  578. if alias:
  579. sub_selects.append("%s.%s" % (
  580. self.connection.ops.quote_name('subquery'),
  581. self.connection.ops.quote_name(alias),
  582. ))
  583. else:
  584. select_clone = select.relabeled_clone({select.alias: 'subquery'})
  585. subselect, subparams = select_clone.as_sql(self, self.connection)
  586. sub_selects.append(subselect)
  587. sub_params.extend(subparams)
  588. return 'SELECT %s FROM (%s) subquery' % (
  589. ', '.join(sub_selects),
  590. ' '.join(result),
  591. ), tuple(sub_params + params)
  592. return ' '.join(result), tuple(params)
  593. finally:
  594. # Finally do cleanup - get rid of the joins we created above.
  595. self.query.reset_refcounts(refcounts_before)
  596. def get_default_columns(self, start_alias=None, opts=None, from_parent=None):
  597. """
  598. Compute the default columns for selecting every field in the base
  599. model. Will sometimes be called to pull in related models (e.g. via
  600. select_related), in which case "opts" and "start_alias" will be given
  601. to provide a starting point for the traversal.
  602. Return a list of strings, quoted appropriately for use in SQL
  603. directly, as well as a set of aliases used in the select statement (if
  604. 'as_pairs' is True, return a list of (alias, col_name) pairs instead
  605. of strings as the first component and None as the second component).
  606. """
  607. result = []
  608. if opts is None:
  609. opts = self.query.get_meta()
  610. only_load = self.deferred_to_columns()
  611. start_alias = start_alias or self.query.get_initial_alias()
  612. # The 'seen_models' is used to optimize checking the needed parent
  613. # alias for a given field. This also includes None -> start_alias to
  614. # be used by local fields.
  615. seen_models = {None: start_alias}
  616. for field in opts.concrete_fields:
  617. model = field.model._meta.concrete_model
  618. # A proxy model will have a different model and concrete_model. We
  619. # will assign None if the field belongs to this model.
  620. if model == opts.model:
  621. model = None
  622. if from_parent and model is not None and issubclass(
  623. from_parent._meta.concrete_model, model._meta.concrete_model):
  624. # Avoid loading data for already loaded parents.
  625. # We end up here in the case select_related() resolution
  626. # proceeds from parent model to child model. In that case the
  627. # parent model data is already present in the SELECT clause,
  628. # and we want to avoid reloading the same data again.
  629. continue
  630. if field.model in only_load and field.attname not in only_load[field.model]:
  631. continue
  632. alias = self.query.join_parent_model(opts, model, start_alias,
  633. seen_models)
  634. column = field.get_col(alias)
  635. result.append(column)
  636. return result
  637. def get_distinct(self):
  638. """
  639. Return a quoted list of fields to use in DISTINCT ON part of the query.
  640. This method can alter the tables in the query, and thus it must be
  641. called before get_from_clause().
  642. """
  643. result = []
  644. params = []
  645. opts = self.query.get_meta()
  646. for name in self.query.distinct_fields:
  647. parts = name.split(LOOKUP_SEP)
  648. _, targets, alias, joins, path, _, transform_function = self._setup_joins(parts, opts, None)
  649. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  650. for target in targets:
  651. if name in self.query.annotation_select:
  652. result.append(name)
  653. else:
  654. r, p = self.compile(transform_function(target, alias))
  655. result.append(r)
  656. params.append(p)
  657. return result, params
  658. def find_ordering_name(self, name, opts, alias=None, default_order='ASC',
  659. already_seen=None):
  660. """
  661. Return the table alias (the name might be ambiguous, the alias will
  662. not be) and column name for ordering by the given 'name' parameter.
  663. The 'name' is of the form 'field1__field2__...__fieldN'.
  664. """
  665. name, order = get_order_dir(name, default_order)
  666. descending = order == 'DESC'
  667. pieces = name.split(LOOKUP_SEP)
  668. field, targets, alias, joins, path, opts, transform_function = self._setup_joins(pieces, opts, alias)
  669. # If we get to this point and the field is a relation to another model,
  670. # append the default ordering for that model unless the attribute name
  671. # of the field is specified.
  672. if field.is_relation and opts.ordering and getattr(field, 'attname', None) != name:
  673. # Firstly, avoid infinite loops.
  674. already_seen = already_seen or set()
  675. join_tuple = tuple(getattr(self.query.alias_map[j], 'join_cols', None) for j in joins)
  676. if join_tuple in already_seen:
  677. raise FieldError('Infinite loop caused by ordering.')
  678. already_seen.add(join_tuple)
  679. results = []
  680. for item in opts.ordering:
  681. if hasattr(item, 'resolve_expression') and not isinstance(item, OrderBy):
  682. item = item.desc() if descending else item.asc()
  683. if isinstance(item, OrderBy):
  684. results.append((item, False))
  685. continue
  686. results.extend(self.find_ordering_name(item, opts, alias,
  687. order, already_seen))
  688. return results
  689. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  690. return [(OrderBy(transform_function(t, alias), descending=descending), False) for t in targets]
  691. def _setup_joins(self, pieces, opts, alias):
  692. """
  693. Helper method for get_order_by() and get_distinct().
  694. get_ordering() and get_distinct() must produce same target columns on
  695. same input, as the prefixes of get_ordering() and get_distinct() must
  696. match. Executing SQL where this is not true is an error.
  697. """
  698. alias = alias or self.query.get_initial_alias()
  699. field, targets, opts, joins, path, transform_function = self.query.setup_joins(pieces, opts, alias)
  700. alias = joins[-1]
  701. return field, targets, alias, joins, path, opts, transform_function
  702. def get_from_clause(self):
  703. """
  704. Return a list of strings that are joined together to go after the
  705. "FROM" part of the query, as well as a list any extra parameters that
  706. need to be included. Subclasses, can override this to create a
  707. from-clause via a "select".
  708. This should only be called after any SQL construction methods that
  709. might change the tables that are needed. This means the select columns,
  710. ordering, and distinct must be done first.
  711. """
  712. result = []
  713. params = []
  714. for alias in tuple(self.query.alias_map):
  715. if not self.query.alias_refcount[alias]:
  716. continue
  717. try:
  718. from_clause = self.query.alias_map[alias]
  719. except KeyError:
  720. # Extra tables can end up in self.tables, but not in the
  721. # alias_map if they aren't in a join. That's OK. We skip them.
  722. continue
  723. clause_sql, clause_params = self.compile(from_clause)
  724. result.append(clause_sql)
  725. params.extend(clause_params)
  726. for t in self.query.extra_tables:
  727. alias, _ = self.query.table_alias(t)
  728. # Only add the alias if it's not already present (the table_alias()
  729. # call increments the refcount, so an alias refcount of one means
  730. # this is the only reference).
  731. if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1:
  732. result.append(', %s' % self.quote_name_unless_alias(alias))
  733. return result, params
  734. def get_related_selections(self, select, opts=None, root_alias=None, cur_depth=1,
  735. requested=None, restricted=None):
  736. """
  737. Fill in the information needed for a select_related query. The current
  738. depth is measured as the number of connections away from the root model
  739. (for example, cur_depth=1 means we are looking at models with direct
  740. connections to the root model).
  741. """
  742. def _get_field_choices():
  743. direct_choices = (f.name for f in opts.fields if f.is_relation)
  744. reverse_choices = (
  745. f.field.related_query_name()
  746. for f in opts.related_objects if f.field.unique
  747. )
  748. return chain(direct_choices, reverse_choices, self.query._filtered_relations)
  749. related_klass_infos = []
  750. if not restricted and cur_depth > self.query.max_depth:
  751. # We've recursed far enough; bail out.
  752. return related_klass_infos
  753. if not opts:
  754. opts = self.query.get_meta()
  755. root_alias = self.query.get_initial_alias()
  756. only_load = self.query.get_loaded_field_names()
  757. # Setup for the case when only particular related fields should be
  758. # included in the related selection.
  759. fields_found = set()
  760. if requested is None:
  761. restricted = isinstance(self.query.select_related, dict)
  762. if restricted:
  763. requested = self.query.select_related
  764. def get_related_klass_infos(klass_info, related_klass_infos):
  765. klass_info['related_klass_infos'] = related_klass_infos
  766. for f in opts.fields:
  767. field_model = f.model._meta.concrete_model
  768. fields_found.add(f.name)
  769. if restricted:
  770. next = requested.get(f.name, {})
  771. if not f.is_relation:
  772. # If a non-related field is used like a relation,
  773. # or if a single non-relational field is given.
  774. if next or f.name in requested:
  775. raise FieldError(
  776. "Non-relational field given in select_related: '%s'. "
  777. "Choices are: %s" % (
  778. f.name,
  779. ", ".join(_get_field_choices()) or '(none)',
  780. )
  781. )
  782. else:
  783. next = False
  784. if not select_related_descend(f, restricted, requested,
  785. only_load.get(field_model)):
  786. continue
  787. klass_info = {
  788. 'model': f.remote_field.model,
  789. 'field': f,
  790. 'reverse': False,
  791. 'local_setter': f.set_cached_value,
  792. 'remote_setter': f.remote_field.set_cached_value if f.unique else lambda x, y: None,
  793. 'from_parent': False,
  794. }
  795. related_klass_infos.append(klass_info)
  796. select_fields = []
  797. _, _, _, joins, _, _ = self.query.setup_joins(
  798. [f.name], opts, root_alias)
  799. alias = joins[-1]
  800. columns = self.get_default_columns(start_alias=alias, opts=f.remote_field.model._meta)
  801. for col in columns:
  802. select_fields.append(len(select))
  803. select.append((col, None))
  804. klass_info['select_fields'] = select_fields
  805. next_klass_infos = self.get_related_selections(
  806. select, f.remote_field.model._meta, alias, cur_depth + 1, next, restricted)
  807. get_related_klass_infos(klass_info, next_klass_infos)
  808. if restricted:
  809. related_fields = [
  810. (o.field, o.related_model)
  811. for o in opts.related_objects
  812. if o.field.unique and not o.many_to_many
  813. ]
  814. for f, model in related_fields:
  815. if not select_related_descend(f, restricted, requested,
  816. only_load.get(model), reverse=True):
  817. continue
  818. related_field_name = f.related_query_name()
  819. fields_found.add(related_field_name)
  820. join_info = self.query.setup_joins([related_field_name], opts, root_alias)
  821. alias = join_info.joins[-1]
  822. from_parent = issubclass(model, opts.model) and model is not opts.model
  823. klass_info = {
  824. 'model': model,
  825. 'field': f,
  826. 'reverse': True,
  827. 'local_setter': f.remote_field.set_cached_value,
  828. 'remote_setter': f.set_cached_value,
  829. 'from_parent': from_parent,
  830. }
  831. related_klass_infos.append(klass_info)
  832. select_fields = []
  833. columns = self.get_default_columns(
  834. start_alias=alias, opts=model._meta, from_parent=opts.model)
  835. for col in columns:
  836. select_fields.append(len(select))
  837. select.append((col, None))
  838. klass_info['select_fields'] = select_fields
  839. next = requested.get(f.related_query_name(), {})
  840. next_klass_infos = self.get_related_selections(
  841. select, model._meta, alias, cur_depth + 1,
  842. next, restricted)
  843. get_related_klass_infos(klass_info, next_klass_infos)
  844. def remote_setter(name, obj, from_obj):
  845. setattr(from_obj, name, obj)
  846. for name in list(requested):
  847. # Filtered relations work only on the topmost level.
  848. if cur_depth > 1:
  849. break
  850. if name in self.query._filtered_relations:
  851. fields_found.add(name)
  852. f, _, join_opts, joins, _, _ = self.query.setup_joins([name], opts, root_alias)
  853. model = join_opts.model
  854. alias = joins[-1]
  855. from_parent = issubclass(model, opts.model) and model is not opts.model
  856. def local_setter(obj, from_obj):
  857. # Set a reverse fk object when relation is non-empty.
  858. if from_obj:
  859. f.remote_field.set_cached_value(from_obj, obj)
  860. klass_info = {
  861. 'model': model,
  862. 'field': f,
  863. 'reverse': True,
  864. 'local_setter': local_setter,
  865. 'remote_setter': partial(remote_setter, name),
  866. 'from_parent': from_parent,
  867. }
  868. related_klass_infos.append(klass_info)
  869. select_fields = []
  870. columns = self.get_default_columns(
  871. start_alias=alias, opts=model._meta,
  872. from_parent=opts.model,
  873. )
  874. for col in columns:
  875. select_fields.append(len(select))
  876. select.append((col, None))
  877. klass_info['select_fields'] = select_fields
  878. next_requested = requested.get(name, {})
  879. next_klass_infos = self.get_related_selections(
  880. select, opts=model._meta, root_alias=alias,
  881. cur_depth=cur_depth + 1, requested=next_requested,
  882. restricted=restricted,
  883. )
  884. get_related_klass_infos(klass_info, next_klass_infos)
  885. fields_not_found = set(requested).difference(fields_found)
  886. if fields_not_found:
  887. invalid_fields = ("'%s'" % s for s in fields_not_found)
  888. raise FieldError(
  889. 'Invalid field name(s) given in select_related: %s. '
  890. 'Choices are: %s' % (
  891. ', '.join(invalid_fields),
  892. ', '.join(_get_field_choices()) or '(none)',
  893. )
  894. )
  895. return related_klass_infos
  896. def get_select_for_update_of_arguments(self):
  897. """
  898. Return a quoted list of arguments for the SELECT FOR UPDATE OF part of
  899. the query.
  900. """
  901. def _get_parent_klass_info(klass_info):
  902. for parent_model, parent_link in klass_info['model']._meta.parents.items():
  903. parent_list = parent_model._meta.get_parent_list()
  904. yield {
  905. 'model': parent_model,
  906. 'field': parent_link,
  907. 'reverse': False,
  908. 'select_fields': [
  909. select_index
  910. for select_index in klass_info['select_fields']
  911. # Selected columns from a model or its parents.
  912. if (
  913. self.select[select_index][0].target.model == parent_model or
  914. self.select[select_index][0].target.model in parent_list
  915. )
  916. ],
  917. }
  918. def _get_first_selected_col_from_model(klass_info):
  919. """
  920. Find the first selected column from a model. If it doesn't exist,
  921. don't lock a model.
  922. select_fields is filled recursively, so it also contains fields
  923. from the parent models.
  924. """
  925. for select_index in klass_info['select_fields']:
  926. if self.select[select_index][0].target.model == klass_info['model']:
  927. return self.select[select_index][0]
  928. def _get_field_choices():
  929. """Yield all allowed field paths in breadth-first search order."""
  930. queue = collections.deque([(None, self.klass_info)])
  931. while queue:
  932. parent_path, klass_info = queue.popleft()
  933. if parent_path is None:
  934. path = []
  935. yield 'self'
  936. else:
  937. field = klass_info['field']
  938. if klass_info['reverse']:
  939. field = field.remote_field
  940. path = parent_path + [field.name]
  941. yield LOOKUP_SEP.join(path)
  942. queue.extend(
  943. (path, klass_info)
  944. for klass_info in _get_parent_klass_info(klass_info)
  945. )
  946. queue.extend(
  947. (path, klass_info)
  948. for klass_info in klass_info.get('related_klass_infos', [])
  949. )
  950. result = []
  951. invalid_names = []
  952. for name in self.query.select_for_update_of:
  953. klass_info = self.klass_info
  954. if name == 'self':
  955. col = _get_first_selected_col_from_model(klass_info)
  956. else:
  957. for part in name.split(LOOKUP_SEP):
  958. klass_infos = (
  959. *klass_info.get('related_klass_infos', []),
  960. *_get_parent_klass_info(klass_info),
  961. )
  962. for related_klass_info in klass_infos:
  963. field = related_klass_info['field']
  964. if related_klass_info['reverse']:
  965. field = field.remote_field
  966. if field.name == part:
  967. klass_info = related_klass_info
  968. break
  969. else:
  970. klass_info = None
  971. break
  972. if klass_info is None:
  973. invalid_names.append(name)
  974. continue
  975. col = _get_first_selected_col_from_model(klass_info)
  976. if col is not None:
  977. if self.connection.features.select_for_update_of_column:
  978. result.append(self.compile(col)[0])
  979. else:
  980. result.append(self.quote_name_unless_alias(col.alias))
  981. if invalid_names:
  982. raise FieldError(
  983. 'Invalid field name(s) given in select_for_update(of=(...)): %s. '
  984. 'Only relational fields followed in the query are allowed. '
  985. 'Choices are: %s.' % (
  986. ', '.join(invalid_names),
  987. ', '.join(_get_field_choices()),
  988. )
  989. )
  990. return result
  991. def deferred_to_columns(self):
  992. """
  993. Convert the self.deferred_loading data structure to mapping of table
  994. names to sets of column names which are to be loaded. Return the
  995. dictionary.
  996. """
  997. columns = {}
  998. self.query.deferred_to_data(columns, self.query.get_loaded_field_names_cb)
  999. return columns
  1000. def get_converters(self, expressions):
  1001. converters = {}
  1002. for i, expression in enumerate(expressions):
  1003. if expression:
  1004. backend_converters = self.connection.ops.get_db_converters(expression)
  1005. field_converters = expression.get_db_converters(self.connection)
  1006. if backend_converters or field_converters:
  1007. converters[i] = (backend_converters + field_converters, expression)
  1008. return converters
  1009. def apply_converters(self, rows, converters):
  1010. connection = self.connection
  1011. converters = list(converters.items())
  1012. for row in map(list, rows):
  1013. for pos, (convs, expression) in converters:
  1014. value = row[pos]
  1015. for converter in convs:
  1016. value = converter(value, expression, connection)
  1017. row[pos] = value
  1018. yield row
  1019. def results_iter(self, results=None, tuple_expected=False, chunked_fetch=False,
  1020. chunk_size=GET_ITERATOR_CHUNK_SIZE):
  1021. """Return an iterator over the results from executing this query."""
  1022. if results is None:
  1023. results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
  1024. fields = [s[0] for s in self.select[0:self.col_count]]
  1025. converters = self.get_converters(fields)
  1026. rows = chain.from_iterable(results)
  1027. if converters:
  1028. rows = self.apply_converters(rows, converters)
  1029. if tuple_expected:
  1030. rows = map(tuple, rows)
  1031. return rows
  1032. def has_results(self):
  1033. """
  1034. Backends (e.g. NoSQL) can override this in order to use optimized
  1035. versions of "query has any results."
  1036. """
  1037. # This is always executed on a query clone, so we can modify self.query
  1038. self.query.add_extra({'a': 1}, None, None, None, None, None)
  1039. self.query.set_extra_mask(['a'])
  1040. return bool(self.execute_sql(SINGLE))
  1041. def execute_sql(self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE):
  1042. """
  1043. Run the query against the database and return the result(s). The
  1044. return value is a single data item if result_type is SINGLE, or an
  1045. iterator over the results if the result_type is MULTI.
  1046. result_type is either MULTI (use fetchmany() to retrieve all rows),
  1047. SINGLE (only retrieve a single row), or None. In this last case, the
  1048. cursor is returned if any query is executed, since it's used by
  1049. subclasses such as InsertQuery). It's possible, however, that no query
  1050. is needed, as the filters describe an empty set. In that case, None is
  1051. returned, to avoid any unnecessary database interaction.
  1052. """
  1053. result_type = result_type or NO_RESULTS
  1054. try:
  1055. sql, params = self.as_sql()
  1056. if not sql:
  1057. raise EmptyResultSet
  1058. except EmptyResultSet:
  1059. if result_type == MULTI:
  1060. return iter([])
  1061. else:
  1062. return
  1063. if chunked_fetch:
  1064. cursor = self.connection.chunked_cursor()
  1065. else:
  1066. cursor = self.connection.cursor()
  1067. try:
  1068. cursor.execute(sql, params)
  1069. except Exception:
  1070. # Might fail for server-side cursors (e.g. connection closed)
  1071. cursor.close()
  1072. raise
  1073. if result_type == CURSOR:
  1074. # Give the caller the cursor to process and close.
  1075. return cursor
  1076. if result_type == SINGLE:
  1077. try:
  1078. val = cursor.fetchone()
  1079. if val:
  1080. return val[0:self.col_count]
  1081. return val
  1082. finally:
  1083. # done with the cursor
  1084. cursor.close()
  1085. if result_type == NO_RESULTS:
  1086. cursor.close()
  1087. return
  1088. result = cursor_iter(
  1089. cursor, self.connection.features.empty_fetchmany_value,
  1090. self.col_count if self.has_extra_select else None,
  1091. chunk_size,
  1092. )
  1093. if not chunked_fetch or not self.connection.features.can_use_chunked_reads:
  1094. try:
  1095. # If we are using non-chunked reads, we return the same data
  1096. # structure as normally, but ensure it is all read into memory
  1097. # before going any further. Use chunked_fetch if requested,
  1098. # unless the database doesn't support it.
  1099. return list(result)
  1100. finally:
  1101. # done with the cursor
  1102. cursor.close()
  1103. return result
  1104. def as_subquery_condition(self, alias, columns, compiler):
  1105. qn = compiler.quote_name_unless_alias
  1106. qn2 = self.connection.ops.quote_name
  1107. for index, select_col in enumerate(self.query.select):
  1108. lhs_sql, lhs_params = self.compile(select_col)
  1109. rhs = '%s.%s' % (qn(alias), qn2(columns[index]))
  1110. self.query.where.add(
  1111. QueryWrapper('%s = %s' % (lhs_sql, rhs), lhs_params), 'AND')
  1112. sql, params = self.as_sql()
  1113. return 'EXISTS (%s)' % sql, params
  1114. def explain_query(self):
  1115. result = list(self.execute_sql())
  1116. # Some backends return 1 item tuples with strings, and others return
  1117. # tuples with integers and strings. Flatten them out into strings.
  1118. for row in result[0]:
  1119. if not isinstance(row, str):
  1120. yield ' '.join(str(c) for c in row)
  1121. else:
  1122. yield row
  1123. class SQLInsertCompiler(SQLCompiler):
  1124. returning_fields = None
  1125. def field_as_sql(self, field, val):
  1126. """
  1127. Take a field and a value intended to be saved on that field, and
  1128. return placeholder SQL and accompanying params. Check for raw values,
  1129. expressions, and fields with get_placeholder() defined in that order.
  1130. When field is None, consider the value raw and use it as the
  1131. placeholder, with no corresponding parameters returned.
  1132. """
  1133. if field is None:
  1134. # A field value of None means the value is raw.
  1135. sql, params = val, []
  1136. elif hasattr(val, 'as_sql'):
  1137. # This is an expression, let's compile it.
  1138. sql, params = self.compile(val)
  1139. elif hasattr(field, 'get_placeholder'):
  1140. # Some fields (e.g. geo fields) need special munging before
  1141. # they can be inserted.
  1142. sql, params = field.get_placeholder(val, self, self.connection), [val]
  1143. else:
  1144. # Return the common case for the placeholder
  1145. sql, params = '%s', [val]
  1146. # The following hook is only used by Oracle Spatial, which sometimes
  1147. # needs to yield 'NULL' and [] as its placeholder and params instead
  1148. # of '%s' and [None]. The 'NULL' placeholder is produced earlier by
  1149. # OracleOperations.get_geom_placeholder(). The following line removes
  1150. # the corresponding None parameter. See ticket #10888.
  1151. params = self.connection.ops.modify_insert_params(sql, params)
  1152. return sql, params
  1153. def prepare_value(self, field, value):
  1154. """
  1155. Prepare a value to be used in a query by resolving it if it is an
  1156. expression and otherwise calling the field's get_db_prep_save().
  1157. """
  1158. if hasattr(value, 'resolve_expression'):
  1159. value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
  1160. # Don't allow values containing Col expressions. They refer to
  1161. # existing columns on a row, but in the case of insert the row
  1162. # doesn't exist yet.
  1163. if value.contains_column_references:
  1164. raise ValueError(
  1165. 'Failed to insert expression "%s" on %s. F() expressions '
  1166. 'can only be used to update, not to insert.' % (value, field)
  1167. )
  1168. if value.contains_aggregate:
  1169. raise FieldError(
  1170. 'Aggregate functions are not allowed in this query '
  1171. '(%s=%r).' % (field.name, value)
  1172. )
  1173. if value.contains_over_clause:
  1174. raise FieldError(
  1175. 'Window expressions are not allowed in this query (%s=%r).'
  1176. % (field.name, value)
  1177. )
  1178. else:
  1179. value = field.get_db_prep_save(value, connection=self.connection)
  1180. return value
  1181. def pre_save_val(self, field, obj):
  1182. """
  1183. Get the given field's value off the given obj. pre_save() is used for
  1184. things like auto_now on DateTimeField. Skip it if this is a raw query.
  1185. """
  1186. if self.query.raw:
  1187. return getattr(obj, field.attname)
  1188. return field.pre_save(obj, add=True)
  1189. def assemble_as_sql(self, fields, value_rows):
  1190. """
  1191. Take a sequence of N fields and a sequence of M rows of values, and
  1192. generate placeholder SQL and parameters for each field and value.
  1193. Return a pair containing:
  1194. * a sequence of M rows of N SQL placeholder strings, and
  1195. * a sequence of M rows of corresponding parameter values.
  1196. Each placeholder string may contain any number of '%s' interpolation
  1197. strings, and each parameter row will contain exactly as many params
  1198. as the total number of '%s's in the corresponding placeholder row.
  1199. """
  1200. if not value_rows:
  1201. return [], []
  1202. # list of (sql, [params]) tuples for each object to be saved
  1203. # Shape: [n_objs][n_fields][2]
  1204. rows_of_fields_as_sql = (
  1205. (self.field_as_sql(field, v) for field, v in zip(fields, row))
  1206. for row in value_rows
  1207. )
  1208. # tuple like ([sqls], [[params]s]) for each object to be saved
  1209. # Shape: [n_objs][2][n_fields]
  1210. sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql)
  1211. # Extract separate lists for placeholders and params.
  1212. # Each of these has shape [n_objs][n_fields]
  1213. placeholder_rows, param_rows = zip(*sql_and_param_pair_rows)
  1214. # Params for each field are still lists, and need to be flattened.
  1215. param_rows = [[p for ps in row for p in ps] for row in param_rows]
  1216. return placeholder_rows, param_rows
  1217. def as_sql(self):
  1218. # We don't need quote_name_unless_alias() here, since these are all
  1219. # going to be column names (so we can avoid the extra overhead).
  1220. qn = self.connection.ops.quote_name
  1221. opts = self.query.get_meta()
  1222. insert_statement = self.connection.ops.insert_statement(ignore_conflicts=self.query.ignore_conflicts)
  1223. result = ['%s %s' % (insert_statement, qn(opts.db_table))]
  1224. fields = self.query.fields or [opts.pk]
  1225. result.append('(%s)' % ', '.join(qn(f.column) for f in fields))
  1226. if self.query.fields:
  1227. value_rows = [
  1228. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  1229. for obj in self.query.objs
  1230. ]
  1231. else:
  1232. # An empty object.
  1233. value_rows = [[self.connection.ops.pk_default_value()] for _ in self.query.objs]
  1234. fields = [None]
  1235. # Currently the backends just accept values when generating bulk
  1236. # queries and generate their own placeholders. Doing that isn't
  1237. # necessary and it should be possible to use placeholders and
  1238. # expressions in bulk inserts too.
  1239. can_bulk = (not self.returning_fields and self.connection.features.has_bulk_insert)
  1240. placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows)
  1241. ignore_conflicts_suffix_sql = self.connection.ops.ignore_conflicts_suffix_sql(
  1242. ignore_conflicts=self.query.ignore_conflicts
  1243. )
  1244. if self.returning_fields and self.connection.features.can_return_columns_from_insert:
  1245. if self.connection.features.can_return_rows_from_bulk_insert:
  1246. result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
  1247. params = param_rows
  1248. else:
  1249. result.append("VALUES (%s)" % ", ".join(placeholder_rows[0]))
  1250. params = [param_rows[0]]
  1251. if ignore_conflicts_suffix_sql:
  1252. result.append(ignore_conflicts_suffix_sql)
  1253. # Skip empty r_sql to allow subclasses to customize behavior for
  1254. # 3rd party backends. Refs #19096.
  1255. r_sql, r_params = self.connection.ops.return_insert_columns(self.returning_fields)
  1256. if r_sql:
  1257. result.append(r_sql)
  1258. params += [r_params]
  1259. return [(" ".join(result), tuple(chain.from_iterable(params)))]
  1260. if can_bulk:
  1261. result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
  1262. if ignore_conflicts_suffix_sql:
  1263. result.append(ignore_conflicts_suffix_sql)
  1264. return [(" ".join(result), tuple(p for ps in param_rows for p in ps))]
  1265. else:
  1266. if ignore_conflicts_suffix_sql:
  1267. result.append(ignore_conflicts_suffix_sql)
  1268. return [
  1269. (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
  1270. for p, vals in zip(placeholder_rows, param_rows)
  1271. ]
  1272. def execute_sql(self, returning_fields=None):
  1273. assert not (
  1274. returning_fields and len(self.query.objs) != 1 and
  1275. not self.connection.features.can_return_rows_from_bulk_insert
  1276. )
  1277. self.returning_fields = returning_fields
  1278. with self.connection.cursor() as cursor:
  1279. for sql, params in self.as_sql():
  1280. cursor.execute(sql, params)
  1281. if not self.returning_fields:
  1282. return []
  1283. if self.connection.features.can_return_rows_from_bulk_insert and len(self.query.objs) > 1:
  1284. return self.connection.ops.fetch_returned_insert_rows(cursor)
  1285. if self.connection.features.can_return_columns_from_insert:
  1286. if (
  1287. len(self.returning_fields) > 1 and
  1288. not self.connection.features.can_return_multiple_columns_from_insert
  1289. ):
  1290. raise NotSupportedError(
  1291. 'Returning multiple columns from INSERT statements is '
  1292. 'not supported on this database backend.'
  1293. )
  1294. assert len(self.query.objs) == 1
  1295. return self.connection.ops.fetch_returned_insert_columns(cursor)
  1296. return [self.connection.ops.last_insert_id(
  1297. cursor, self.query.get_meta().db_table, self.query.get_meta().pk.column
  1298. )]
  1299. class SQLDeleteCompiler(SQLCompiler):
  1300. def as_sql(self):
  1301. """
  1302. Create the SQL for this query. Return the SQL string and list of
  1303. parameters.
  1304. """
  1305. assert len([t for t in self.query.alias_map if self.query.alias_refcount[t] > 0]) == 1, \
  1306. "Can only delete from one table at a time."
  1307. qn = self.quote_name_unless_alias
  1308. result = ['DELETE FROM %s' % qn(self.query.base_table)]
  1309. where, params = self.compile(self.query.where)
  1310. if where:
  1311. result.append('WHERE %s' % where)
  1312. return ' '.join(result), tuple(params)
  1313. class SQLUpdateCompiler(SQLCompiler):
  1314. def as_sql(self):
  1315. """
  1316. Create the SQL for this query. Return the SQL string and list of
  1317. parameters.
  1318. """
  1319. self.pre_sql_setup()
  1320. if not self.query.values:
  1321. return '', ()
  1322. qn = self.quote_name_unless_alias
  1323. values, update_params = [], []
  1324. for field, model, val in self.query.values:
  1325. if hasattr(val, 'resolve_expression'):
  1326. val = val.resolve_expression(self.query, allow_joins=False, for_save=True)
  1327. if val.contains_aggregate:
  1328. raise FieldError(
  1329. 'Aggregate functions are not allowed in this query '
  1330. '(%s=%r).' % (field.name, val)
  1331. )
  1332. if val.contains_over_clause:
  1333. raise FieldError(
  1334. 'Window expressions are not allowed in this query '
  1335. '(%s=%r).' % (field.name, val)
  1336. )
  1337. elif hasattr(val, 'prepare_database_save'):
  1338. if field.remote_field:
  1339. val = field.get_db_prep_save(
  1340. val.prepare_database_save(field),
  1341. connection=self.connection,
  1342. )
  1343. else:
  1344. raise TypeError(
  1345. "Tried to update field %s with a model instance, %r. "
  1346. "Use a value compatible with %s."
  1347. % (field, val, field.__class__.__name__)
  1348. )
  1349. else:
  1350. val = field.get_db_prep_save(val, connection=self.connection)
  1351. # Getting the placeholder for the field.
  1352. if hasattr(field, 'get_placeholder'):
  1353. placeholder = field.get_placeholder(val, self, self.connection)
  1354. else:
  1355. placeholder = '%s'
  1356. name = field.column
  1357. if hasattr(val, 'as_sql'):
  1358. sql, params = self.compile(val)
  1359. values.append('%s = %s' % (qn(name), placeholder % sql))
  1360. update_params.extend(params)
  1361. elif val is not None:
  1362. values.append('%s = %s' % (qn(name), placeholder))
  1363. update_params.append(val)
  1364. else:
  1365. values.append('%s = NULL' % qn(name))
  1366. table = self.query.base_table
  1367. result = [
  1368. 'UPDATE %s SET' % qn(table),
  1369. ', '.join(values),
  1370. ]
  1371. where, params = self.compile(self.query.where)
  1372. if where:
  1373. result.append('WHERE %s' % where)
  1374. return ' '.join(result), tuple(update_params + params)
  1375. def execute_sql(self, result_type):
  1376. """
  1377. Execute the specified update. Return the number of rows affected by
  1378. the primary update query. The "primary update query" is the first
  1379. non-empty query that is executed. Row counts for any subsequent,
  1380. related queries are not available.
  1381. """
  1382. cursor = super().execute_sql(result_type)
  1383. try:
  1384. rows = cursor.rowcount if cursor else 0
  1385. is_empty = cursor is None
  1386. finally:
  1387. if cursor:
  1388. cursor.close()
  1389. for query in self.query.get_related_updates():
  1390. aux_rows = query.get_compiler(self.using).execute_sql(result_type)
  1391. if is_empty and aux_rows:
  1392. rows = aux_rows
  1393. is_empty = False
  1394. return rows
  1395. def pre_sql_setup(self):
  1396. """
  1397. If the update depends on results from other tables, munge the "where"
  1398. conditions to match the format required for (portable) SQL updates.
  1399. If multiple updates are required, pull out the id values to update at
  1400. this point so that they don't change as a result of the progressive
  1401. updates.
  1402. """
  1403. refcounts_before = self.query.alias_refcount.copy()
  1404. # Ensure base table is in the query
  1405. self.query.get_initial_alias()
  1406. count = self.query.count_active_tables()
  1407. if not self.query.related_updates and count == 1:
  1408. return
  1409. query = self.query.chain(klass=Query)
  1410. query.select_related = False
  1411. query.clear_ordering(True)
  1412. query.extra = {}
  1413. query.select = []
  1414. query.add_fields([query.get_meta().pk.name])
  1415. super().pre_sql_setup()
  1416. must_pre_select = count > 1 and not self.connection.features.update_can_self_select
  1417. # Now we adjust the current query: reset the where clause and get rid
  1418. # of all the tables we don't need (since they're in the sub-select).
  1419. self.query.where = self.query.where_class()
  1420. if self.query.related_updates or must_pre_select:
  1421. # Either we're using the idents in multiple update queries (so
  1422. # don't want them to change), or the db backend doesn't support
  1423. # selecting from the updating table (e.g. MySQL).
  1424. idents = []
  1425. for rows in query.get_compiler(self.using).execute_sql(MULTI):
  1426. idents.extend(r[0] for r in rows)
  1427. self.query.add_filter(('pk__in', idents))
  1428. self.query.related_ids = idents
  1429. else:
  1430. # The fast path. Filters and updates in one query.
  1431. self.query.add_filter(('pk__in', query))
  1432. self.query.reset_refcounts(refcounts_before)
  1433. class SQLAggregateCompiler(SQLCompiler):
  1434. def as_sql(self):
  1435. """
  1436. Create the SQL for this query. Return the SQL string and list of
  1437. parameters.
  1438. """
  1439. sql, params = [], []
  1440. for annotation in self.query.annotation_select.values():
  1441. ann_sql, ann_params = self.compile(annotation)
  1442. ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params)
  1443. sql.append(ann_sql)
  1444. params.extend(ann_params)
  1445. self.col_count = len(self.query.annotation_select)
  1446. sql = ', '.join(sql)
  1447. params = tuple(params)
  1448. sql = 'SELECT %s FROM (%s) subquery' % (sql, self.query.subquery)
  1449. params = params + self.query.sub_params
  1450. return sql, params
  1451. def cursor_iter(cursor, sentinel, col_count, itersize):
  1452. """
  1453. Yield blocks of rows from a cursor and ensure the cursor is closed when
  1454. done.
  1455. """
  1456. try:
  1457. for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
  1458. yield rows if col_count is None else [r[:col_count] for r in rows]
  1459. finally:
  1460. cursor.close()