Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

compiler.py 65KB

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