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 68KB

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