PageRenderTime 55ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/django/db/models/sql/compiler.py

https://gitlab.com/Guy1394/django
Python | 1137 lines | 1068 code | 10 blank | 59 comment | 33 complexity | 8bea78ed2a128eb272905656eeef5101 MD5 | raw file
  1. import re
  2. from itertools import chain
  3. from django.core.exceptions import FieldError
  4. from django.db.models.constants import LOOKUP_SEP
  5. from django.db.models.expressions import OrderBy, Random, RawSQL, Ref
  6. from django.db.models.query_utils import QueryWrapper, select_related_descend
  7. from django.db.models.sql.constants import (
  8. CURSOR, GET_ITERATOR_CHUNK_SIZE, MULTI, NO_RESULTS, ORDER_DIR, SINGLE,
  9. )
  10. from django.db.models.sql.datastructures import EmptyResultSet
  11. from django.db.models.sql.query import Query, get_order_dir
  12. from django.db.transaction import TransactionManagementError
  13. from django.db.utils import DatabaseError
  14. from django.utils.six.moves import zip
  15. class SQLCompiler(object):
  16. def __init__(self, query, connection, using):
  17. self.query = query
  18. self.connection = connection
  19. self.using = using
  20. self.quote_cache = {'*': '*'}
  21. # The select, klass_info, and annotations are needed by QuerySet.iterator()
  22. # these are set as a side-effect of executing the query. Note that we calculate
  23. # separately a list of extra select columns needed for grammatical correctness
  24. # of the query, but these columns are not included in self.select.
  25. self.select = None
  26. self.annotation_col_map = None
  27. self.klass_info = None
  28. self.ordering_parts = re.compile(r'(.*)\s(ASC|DESC)(.*)')
  29. self.subquery = False
  30. def setup_query(self):
  31. if all(self.query.alias_refcount[a] == 0 for a in self.query.tables):
  32. self.query.get_initial_alias()
  33. self.select, self.klass_info, self.annotation_col_map = self.get_select()
  34. self.col_count = len(self.select)
  35. def pre_sql_setup(self):
  36. """
  37. Does any necessary class setup immediately prior to producing SQL. This
  38. is for things that can't necessarily be done in __init__ because we
  39. might not have all the pieces in place at that time.
  40. """
  41. self.setup_query()
  42. order_by = self.get_order_by()
  43. self.where, self.having = self.query.where.split_having()
  44. extra_select = self.get_extra_select(order_by, self.select)
  45. group_by = self.get_group_by(self.select + extra_select, order_by)
  46. return extra_select, order_by, group_by
  47. def get_group_by(self, select, order_by):
  48. """
  49. Returns a list of 2-tuples of form (sql, params).
  50. The logic of what exactly the GROUP BY clause contains is hard
  51. to describe in other words than "if it passes the test suite,
  52. then it is correct".
  53. """
  54. # Some examples:
  55. # SomeModel.objects.annotate(Count('somecol'))
  56. # GROUP BY: all fields of the model
  57. #
  58. # SomeModel.objects.values('name').annotate(Count('somecol'))
  59. # GROUP BY: name
  60. #
  61. # SomeModel.objects.annotate(Count('somecol')).values('name')
  62. # GROUP BY: all cols of the model
  63. #
  64. # SomeModel.objects.values('name', 'pk').annotate(Count('somecol')).values('pk')
  65. # GROUP BY: name, pk
  66. #
  67. # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk')
  68. # GROUP BY: name, pk
  69. #
  70. # In fact, the self.query.group_by is the minimal set to GROUP BY. It
  71. # can't be ever restricted to a smaller set, but additional columns in
  72. # HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately
  73. # the end result is that it is impossible to force the query to have
  74. # a chosen GROUP BY clause - you can almost do this by using the form:
  75. # .values(*wanted_cols).annotate(AnAggregate())
  76. # but any later annotations, extra selects, values calls that
  77. # refer some column outside of the wanted_cols, order_by, or even
  78. # filter calls can alter the GROUP BY clause.
  79. # The query.group_by is either None (no GROUP BY at all), True
  80. # (group by select fields), or a list of expressions to be added
  81. # to the group by.
  82. if self.query.group_by is None:
  83. return []
  84. expressions = []
  85. if self.query.group_by is not True:
  86. # If the group by is set to a list (by .values() call most likely),
  87. # then we need to add everything in it to the GROUP BY clause.
  88. # Backwards compatibility hack for setting query.group_by. Remove
  89. # when we have public API way of forcing the GROUP BY clause.
  90. # Converts string references to expressions.
  91. for expr in self.query.group_by:
  92. if not hasattr(expr, 'as_sql'):
  93. expressions.append(self.query.resolve_ref(expr))
  94. else:
  95. expressions.append(expr)
  96. # Note that even if the group_by is set, it is only the minimal
  97. # set to group by. So, we need to add cols in select, order_by, and
  98. # having into the select in any case.
  99. for expr, _, _ in select:
  100. cols = expr.get_group_by_cols()
  101. for col in cols:
  102. expressions.append(col)
  103. for expr, (sql, params, is_ref) in order_by:
  104. if expr.contains_aggregate:
  105. continue
  106. # We can skip References to select clause, as all expressions in
  107. # the select clause are already part of the group by.
  108. if is_ref:
  109. continue
  110. expressions.extend(expr.get_source_expressions())
  111. having_group_by = self.having.get_group_by_cols() if self.having else ()
  112. for expr in having_group_by:
  113. expressions.append(expr)
  114. result = []
  115. seen = set()
  116. expressions = self.collapse_group_by(expressions, having_group_by)
  117. for expr in expressions:
  118. sql, params = self.compile(expr)
  119. if (sql, tuple(params)) not in seen:
  120. result.append((sql, params))
  121. seen.add((sql, tuple(params)))
  122. return result
  123. def collapse_group_by(self, expressions, having):
  124. # If the DB can group by primary key, then group by the primary key of
  125. # query's main model. Note that for PostgreSQL the GROUP BY clause must
  126. # include the primary key of every table, but for MySQL it is enough to
  127. # have the main table's primary key.
  128. if self.connection.features.allows_group_by_pk:
  129. # The logic here is: if the main model's primary key is in the
  130. # query, then set new_expressions to that field. If that happens,
  131. # then also add having expressions to group by.
  132. pk = None
  133. for expr in expressions:
  134. # Is this a reference to query's base table primary key? If the
  135. # expression isn't a Col-like, then skip the expression.
  136. if (getattr(expr, 'target', None) == self.query.model._meta.pk and
  137. getattr(expr, 'alias', None) == self.query.tables[0]):
  138. pk = expr
  139. break
  140. if pk:
  141. # MySQLism: Columns in HAVING clause must be added to the GROUP BY.
  142. expressions = [pk] + [expr for expr in expressions if expr in having]
  143. elif self.connection.features.allows_group_by_selected_pks:
  144. # Filter out all expressions associated with a table's primary key
  145. # present in the grouped columns. This is done by identifying all
  146. # tables that have their primary key included in the grouped
  147. # columns and removing non-primary key columns referring to them.
  148. pks = {expr for expr in expressions if hasattr(expr, 'target') and expr.target.primary_key}
  149. aliases = {expr.alias for expr in pks}
  150. expressions = [
  151. expr for expr in expressions if expr in pks or getattr(expr, 'alias', None) not in aliases
  152. ]
  153. return expressions
  154. def get_select(self):
  155. """
  156. Returns three values:
  157. - a list of 3-tuples of (expression, (sql, params), alias)
  158. - a klass_info structure,
  159. - a dictionary of annotations
  160. The (sql, params) is what the expression will produce, and alias is the
  161. "AS alias" for the column (possibly None).
  162. The klass_info structure contains the following information:
  163. - Which model to instantiate
  164. - Which columns for that model are present in the query (by
  165. position of the select clause).
  166. - related_klass_infos: [f, klass_info] to descent into
  167. The annotations is a dictionary of {'attname': column position} values.
  168. """
  169. select = []
  170. klass_info = None
  171. annotations = {}
  172. select_idx = 0
  173. for alias, (sql, params) in self.query.extra_select.items():
  174. annotations[alias] = select_idx
  175. select.append((RawSQL(sql, params), alias))
  176. select_idx += 1
  177. assert not (self.query.select and self.query.default_cols)
  178. if self.query.default_cols:
  179. select_list = []
  180. for c in self.get_default_columns():
  181. select_list.append(select_idx)
  182. select.append((c, None))
  183. select_idx += 1
  184. klass_info = {
  185. 'model': self.query.model,
  186. 'select_fields': select_list,
  187. }
  188. # self.query.select is a special case. These columns never go to
  189. # any model.
  190. for col in self.query.select:
  191. select.append((col, None))
  192. select_idx += 1
  193. for alias, annotation in self.query.annotation_select.items():
  194. annotations[alias] = select_idx
  195. select.append((annotation, alias))
  196. select_idx += 1
  197. if self.query.select_related:
  198. related_klass_infos = self.get_related_selections(select)
  199. klass_info['related_klass_infos'] = related_klass_infos
  200. def get_select_from_parent(klass_info):
  201. for ki in klass_info['related_klass_infos']:
  202. if ki['from_parent']:
  203. ki['select_fields'] = (klass_info['select_fields'] +
  204. ki['select_fields'])
  205. get_select_from_parent(ki)
  206. get_select_from_parent(klass_info)
  207. ret = []
  208. for col, alias in select:
  209. ret.append((col, self.compile(col, select_format=True), alias))
  210. return ret, klass_info, annotations
  211. def get_order_by(self):
  212. """
  213. Returns a list of 2-tuples of form (expr, (sql, params, is_ref)) for the
  214. ORDER BY clause.
  215. The order_by clause can alter the select clause (for example it
  216. can add aliases to clauses that do not yet have one, or it can
  217. add totally new select clauses).
  218. """
  219. if self.query.extra_order_by:
  220. ordering = self.query.extra_order_by
  221. elif not self.query.default_ordering:
  222. ordering = self.query.order_by
  223. else:
  224. ordering = (self.query.order_by or self.query.get_meta().ordering or [])
  225. if self.query.standard_ordering:
  226. asc, desc = ORDER_DIR['ASC']
  227. else:
  228. asc, desc = ORDER_DIR['DESC']
  229. order_by = []
  230. for pos, field in enumerate(ordering):
  231. if hasattr(field, 'resolve_expression'):
  232. if not isinstance(field, OrderBy):
  233. field = field.asc()
  234. if not self.query.standard_ordering:
  235. field.reverse_ordering()
  236. order_by.append((field, False))
  237. continue
  238. if field == '?': # random
  239. order_by.append((OrderBy(Random()), False))
  240. continue
  241. col, order = get_order_dir(field, asc)
  242. descending = True if order == 'DESC' else False
  243. if col in self.query.annotation_select:
  244. # Reference to expression in SELECT clause
  245. order_by.append((
  246. OrderBy(Ref(col, self.query.annotation_select[col]), descending=descending),
  247. True))
  248. continue
  249. if col in self.query.annotations:
  250. # References to an expression which is masked out of the SELECT clause
  251. order_by.append((
  252. OrderBy(self.query.annotations[col], descending=descending),
  253. False))
  254. continue
  255. if '.' in field:
  256. # This came in through an extra(order_by=...) addition. Pass it
  257. # on verbatim.
  258. table, col = col.split('.', 1)
  259. order_by.append((
  260. OrderBy(
  261. RawSQL('%s.%s' % (self.quote_name_unless_alias(table), col), []),
  262. descending=descending
  263. ), False))
  264. continue
  265. if not self.query._extra or col not in self.query._extra:
  266. # 'col' is of the form 'field' or 'field1__field2' or
  267. # '-field1__field2__field', etc.
  268. order_by.extend(self.find_ordering_name(
  269. field, self.query.get_meta(), default_order=asc))
  270. else:
  271. if col not in self.query.extra_select:
  272. order_by.append((
  273. OrderBy(RawSQL(*self.query.extra[col]), descending=descending),
  274. False))
  275. else:
  276. order_by.append((
  277. OrderBy(Ref(col, RawSQL(*self.query.extra[col])), descending=descending),
  278. True))
  279. result = []
  280. seen = set()
  281. for expr, is_ref in order_by:
  282. resolved = expr.resolve_expression(
  283. self.query, allow_joins=True, reuse=None)
  284. sql, params = self.compile(resolved)
  285. # Don't add the same column twice, but the order direction is
  286. # not taken into account so we strip it. When this entire method
  287. # is refactored into expressions, then we can check each part as we
  288. # generate it.
  289. without_ordering = self.ordering_parts.search(sql).group(1)
  290. if (without_ordering, tuple(params)) in seen:
  291. continue
  292. seen.add((without_ordering, tuple(params)))
  293. result.append((resolved, (sql, params, is_ref)))
  294. return result
  295. def get_extra_select(self, order_by, select):
  296. extra_select = []
  297. select_sql = [t[1] for t in select]
  298. if self.query.distinct and not self.query.distinct_fields:
  299. for expr, (sql, params, is_ref) in order_by:
  300. without_ordering = self.ordering_parts.search(sql).group(1)
  301. if not is_ref and (without_ordering, params) not in select_sql:
  302. extra_select.append((expr, (without_ordering, params), None))
  303. return extra_select
  304. def quote_name_unless_alias(self, name):
  305. """
  306. A wrapper around connection.ops.quote_name that doesn't quote aliases
  307. for table names. This avoids problems with some SQL dialects that treat
  308. quoted strings specially (e.g. PostgreSQL).
  309. """
  310. if name in self.quote_cache:
  311. return self.quote_cache[name]
  312. if ((name in self.query.alias_map and name not in self.query.table_map) or
  313. name in self.query.extra_select or (
  314. name in self.query.external_aliases and name not in self.query.table_map)):
  315. self.quote_cache[name] = name
  316. return name
  317. r = self.connection.ops.quote_name(name)
  318. self.quote_cache[name] = r
  319. return r
  320. def compile(self, node, select_format=False):
  321. vendor_impl = getattr(node, 'as_' + self.connection.vendor, None)
  322. if vendor_impl:
  323. sql, params = vendor_impl(self, self.connection)
  324. else:
  325. sql, params = node.as_sql(self, self.connection)
  326. if select_format and not self.subquery:
  327. return node.output_field.select_format(self, sql, params)
  328. return sql, params
  329. def as_sql(self, with_limits=True, with_col_aliases=False, subquery=False):
  330. """
  331. Creates the SQL for this query. Returns the SQL string and list of
  332. parameters.
  333. If 'with_limits' is False, any limit/offset information is not included
  334. in the query.
  335. """
  336. self.subquery = subquery
  337. refcounts_before = self.query.alias_refcount.copy()
  338. try:
  339. extra_select, order_by, group_by = self.pre_sql_setup()
  340. distinct_fields = self.get_distinct()
  341. # This must come after 'select', 'ordering', and 'distinct' -- see
  342. # docstring of get_from_clause() for details.
  343. from_, f_params = self.get_from_clause()
  344. where, w_params = self.compile(self.where) if self.where is not None else ("", [])
  345. having, h_params = self.compile(self.having) if self.having is not None else ("", [])
  346. params = []
  347. result = ['SELECT']
  348. if self.query.distinct:
  349. result.append(self.connection.ops.distinct_sql(distinct_fields))
  350. out_cols = []
  351. col_idx = 1
  352. for _, (s_sql, s_params), alias in self.select + extra_select:
  353. if alias:
  354. s_sql = '%s AS %s' % (s_sql, self.connection.ops.quote_name(alias))
  355. elif with_col_aliases:
  356. s_sql = '%s AS %s' % (s_sql, 'Col%d' % col_idx)
  357. col_idx += 1
  358. params.extend(s_params)
  359. out_cols.append(s_sql)
  360. result.append(', '.join(out_cols))
  361. result.append('FROM')
  362. result.extend(from_)
  363. params.extend(f_params)
  364. if where:
  365. result.append('WHERE %s' % where)
  366. params.extend(w_params)
  367. grouping = []
  368. for g_sql, g_params in group_by:
  369. grouping.append(g_sql)
  370. params.extend(g_params)
  371. if grouping:
  372. if distinct_fields:
  373. raise NotImplementedError(
  374. "annotate() + distinct(fields) is not implemented.")
  375. if not order_by:
  376. order_by = self.connection.ops.force_no_ordering()
  377. result.append('GROUP BY %s' % ', '.join(grouping))
  378. if having:
  379. result.append('HAVING %s' % having)
  380. params.extend(h_params)
  381. if order_by:
  382. ordering = []
  383. for _, (o_sql, o_params, _) in order_by:
  384. ordering.append(o_sql)
  385. params.extend(o_params)
  386. result.append('ORDER BY %s' % ', '.join(ordering))
  387. if with_limits:
  388. if self.query.high_mark is not None:
  389. result.append('LIMIT %d' % (self.query.high_mark - self.query.low_mark))
  390. if self.query.low_mark:
  391. if self.query.high_mark is None:
  392. val = self.connection.ops.no_limit_value()
  393. if val:
  394. result.append('LIMIT %d' % val)
  395. result.append('OFFSET %d' % self.query.low_mark)
  396. if self.query.select_for_update and self.connection.features.has_select_for_update:
  397. if self.connection.get_autocommit():
  398. raise TransactionManagementError(
  399. "select_for_update cannot be used outside of a transaction."
  400. )
  401. # If we've been asked for a NOWAIT query but the backend does
  402. # not support it, raise a DatabaseError otherwise we could get
  403. # an unexpected deadlock.
  404. nowait = self.query.select_for_update_nowait
  405. if nowait and not self.connection.features.has_select_for_update_nowait:
  406. raise DatabaseError('NOWAIT is not supported on this database backend.')
  407. result.append(self.connection.ops.for_update_sql(nowait=nowait))
  408. return ' '.join(result), tuple(params)
  409. finally:
  410. # Finally do cleanup - get rid of the joins we created above.
  411. self.query.reset_refcounts(refcounts_before)
  412. def as_nested_sql(self):
  413. """
  414. Perform the same functionality as the as_sql() method, returning an
  415. SQL string and parameters. However, the alias prefixes are bumped
  416. beforehand (in a copy -- the current query isn't changed), and any
  417. ordering is removed if the query is unsliced.
  418. Used when nesting this query inside another.
  419. """
  420. obj = self.query.clone()
  421. if obj.low_mark == 0 and obj.high_mark is None and not self.query.distinct_fields:
  422. # If there is no slicing in use, then we can safely drop all ordering
  423. obj.clear_ordering(True)
  424. nested_sql = obj.get_compiler(connection=self.connection).as_sql(subquery=True)
  425. if nested_sql == ('', ()):
  426. raise EmptyResultSet
  427. return nested_sql
  428. def get_default_columns(self, start_alias=None, opts=None, from_parent=None):
  429. """
  430. Computes the default columns for selecting every field in the base
  431. model. Will sometimes be called to pull in related models (e.g. via
  432. select_related), in which case "opts" and "start_alias" will be given
  433. to provide a starting point for the traversal.
  434. Returns a list of strings, quoted appropriately for use in SQL
  435. directly, as well as a set of aliases used in the select statement (if
  436. 'as_pairs' is True, returns a list of (alias, col_name) pairs instead
  437. of strings as the first component and None as the second component).
  438. """
  439. result = []
  440. if opts is None:
  441. opts = self.query.get_meta()
  442. only_load = self.deferred_to_columns()
  443. if not start_alias:
  444. start_alias = self.query.get_initial_alias()
  445. # The 'seen_models' is used to optimize checking the needed parent
  446. # alias for a given field. This also includes None -> start_alias to
  447. # be used by local fields.
  448. seen_models = {None: start_alias}
  449. for field in opts.concrete_fields:
  450. model = field.model._meta.concrete_model
  451. # A proxy model will have a different model and concrete_model. We
  452. # will assign None if the field belongs to this model.
  453. if model == opts.model:
  454. model = None
  455. if from_parent and model is not None and issubclass(
  456. from_parent._meta.concrete_model, model._meta.concrete_model):
  457. # Avoid loading data for already loaded parents.
  458. # We end up here in the case select_related() resolution
  459. # proceeds from parent model to child model. In that case the
  460. # parent model data is already present in the SELECT clause,
  461. # and we want to avoid reloading the same data again.
  462. continue
  463. if field.model in only_load and field.attname not in only_load[field.model]:
  464. continue
  465. alias = self.query.join_parent_model(opts, model, start_alias,
  466. seen_models)
  467. column = field.get_col(alias)
  468. result.append(column)
  469. return result
  470. def get_distinct(self):
  471. """
  472. Returns a quoted list of fields to use in DISTINCT ON part of the query.
  473. Note that this method can alter the tables in the query, and thus it
  474. must be called before get_from_clause().
  475. """
  476. qn = self.quote_name_unless_alias
  477. qn2 = self.connection.ops.quote_name
  478. result = []
  479. opts = self.query.get_meta()
  480. for name in self.query.distinct_fields:
  481. parts = name.split(LOOKUP_SEP)
  482. _, targets, alias, joins, path, _ = self._setup_joins(parts, opts, None)
  483. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  484. for target in targets:
  485. if name in self.query.annotation_select:
  486. result.append(name)
  487. else:
  488. result.append("%s.%s" % (qn(alias), qn2(target.column)))
  489. return result
  490. def find_ordering_name(self, name, opts, alias=None, default_order='ASC',
  491. already_seen=None):
  492. """
  493. Returns the table alias (the name might be ambiguous, the alias will
  494. not be) and column name for ordering by the given 'name' parameter.
  495. The 'name' is of the form 'field1__field2__...__fieldN'.
  496. """
  497. name, order = get_order_dir(name, default_order)
  498. descending = True if order == 'DESC' else False
  499. pieces = name.split(LOOKUP_SEP)
  500. field, targets, alias, joins, path, opts = self._setup_joins(pieces, opts, alias)
  501. # If we get to this point and the field is a relation to another model,
  502. # append the default ordering for that model unless the attribute name
  503. # of the field is specified.
  504. if field.is_relation and path and opts.ordering and name != field.attname:
  505. # Firstly, avoid infinite loops.
  506. if not already_seen:
  507. already_seen = set()
  508. join_tuple = tuple(getattr(self.query.alias_map[j], 'join_cols', None) for j in joins)
  509. if join_tuple in already_seen:
  510. raise FieldError('Infinite loop caused by ordering.')
  511. already_seen.add(join_tuple)
  512. results = []
  513. for item in opts.ordering:
  514. results.extend(self.find_ordering_name(item, opts, alias,
  515. order, already_seen))
  516. return results
  517. targets, alias, _ = self.query.trim_joins(targets, joins, path)
  518. return [(OrderBy(t.get_col(alias), descending=descending), False) for t in targets]
  519. def _setup_joins(self, pieces, opts, alias):
  520. """
  521. A helper method for get_order_by and get_distinct.
  522. Note that get_ordering and get_distinct must produce same target
  523. columns on same input, as the prefixes of get_ordering and get_distinct
  524. must match. Executing SQL where this is not true is an error.
  525. """
  526. if not alias:
  527. alias = self.query.get_initial_alias()
  528. field, targets, opts, joins, path = self.query.setup_joins(
  529. pieces, opts, alias)
  530. alias = joins[-1]
  531. return field, targets, alias, joins, path, opts
  532. def get_from_clause(self):
  533. """
  534. Returns a list of strings that are joined together to go after the
  535. "FROM" part of the query, as well as a list any extra parameters that
  536. need to be included. Sub-classes, can override this to create a
  537. from-clause via a "select".
  538. This should only be called after any SQL construction methods that
  539. might change the tables we need. This means the select columns,
  540. ordering and distinct must be done first.
  541. """
  542. result = []
  543. params = []
  544. for alias in self.query.tables:
  545. if not self.query.alias_refcount[alias]:
  546. continue
  547. try:
  548. from_clause = self.query.alias_map[alias]
  549. except KeyError:
  550. # Extra tables can end up in self.tables, but not in the
  551. # alias_map if they aren't in a join. That's OK. We skip them.
  552. continue
  553. clause_sql, clause_params = self.compile(from_clause)
  554. result.append(clause_sql)
  555. params.extend(clause_params)
  556. for t in self.query.extra_tables:
  557. alias, _ = self.query.table_alias(t)
  558. # Only add the alias if it's not already present (the table_alias()
  559. # call increments the refcount, so an alias refcount of one means
  560. # this is the only reference).
  561. if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1:
  562. result.append(', %s' % self.quote_name_unless_alias(alias))
  563. return result, params
  564. def get_related_selections(self, select, opts=None, root_alias=None, cur_depth=1,
  565. requested=None, restricted=None):
  566. """
  567. Fill in the information needed for a select_related query. The current
  568. depth is measured as the number of connections away from the root model
  569. (for example, cur_depth=1 means we are looking at models with direct
  570. connections to the root model).
  571. """
  572. def _get_field_choices():
  573. direct_choices = (f.name for f in opts.fields if f.is_relation)
  574. reverse_choices = (
  575. f.field.related_query_name()
  576. for f in opts.related_objects if f.field.unique
  577. )
  578. return chain(direct_choices, reverse_choices)
  579. related_klass_infos = []
  580. if not restricted and self.query.max_depth and cur_depth > self.query.max_depth:
  581. # We've recursed far enough; bail out.
  582. return related_klass_infos
  583. if not opts:
  584. opts = self.query.get_meta()
  585. root_alias = self.query.get_initial_alias()
  586. only_load = self.query.get_loaded_field_names()
  587. # Setup for the case when only particular related fields should be
  588. # included in the related selection.
  589. fields_found = set()
  590. if requested is None:
  591. if isinstance(self.query.select_related, dict):
  592. requested = self.query.select_related
  593. restricted = True
  594. else:
  595. restricted = False
  596. def get_related_klass_infos(klass_info, related_klass_infos):
  597. klass_info['related_klass_infos'] = related_klass_infos
  598. for f in opts.fields:
  599. field_model = f.model._meta.concrete_model
  600. fields_found.add(f.name)
  601. if restricted:
  602. next = requested.get(f.name, {})
  603. if not f.is_relation:
  604. # If a non-related field is used like a relation,
  605. # or if a single non-relational field is given.
  606. if next or f.name in requested:
  607. raise FieldError(
  608. "Non-relational field given in select_related: '%s'. "
  609. "Choices are: %s" % (
  610. f.name,
  611. ", ".join(_get_field_choices()) or '(none)',
  612. )
  613. )
  614. else:
  615. next = False
  616. if not select_related_descend(f, restricted, requested,
  617. only_load.get(field_model)):
  618. continue
  619. klass_info = {
  620. 'model': f.remote_field.model,
  621. 'field': f,
  622. 'reverse': False,
  623. 'from_parent': False,
  624. }
  625. related_klass_infos.append(klass_info)
  626. select_fields = []
  627. _, _, _, joins, _ = self.query.setup_joins(
  628. [f.name], opts, root_alias)
  629. alias = joins[-1]
  630. columns = self.get_default_columns(start_alias=alias, opts=f.remote_field.model._meta)
  631. for col in columns:
  632. select_fields.append(len(select))
  633. select.append((col, None))
  634. klass_info['select_fields'] = select_fields
  635. next_klass_infos = self.get_related_selections(
  636. select, f.remote_field.model._meta, alias, cur_depth + 1, next, restricted)
  637. get_related_klass_infos(klass_info, next_klass_infos)
  638. if restricted:
  639. related_fields = [
  640. (o.field, o.related_model)
  641. for o in opts.related_objects
  642. if o.field.unique and not o.many_to_many
  643. ]
  644. for f, model in related_fields:
  645. if not select_related_descend(f, restricted, requested,
  646. only_load.get(model), reverse=True):
  647. continue
  648. related_field_name = f.related_query_name()
  649. fields_found.add(related_field_name)
  650. _, _, _, joins, _ = self.query.setup_joins([related_field_name], opts, root_alias)
  651. alias = joins[-1]
  652. from_parent = issubclass(model, opts.model)
  653. klass_info = {
  654. 'model': model,
  655. 'field': f,
  656. 'reverse': True,
  657. 'from_parent': from_parent,
  658. }
  659. related_klass_infos.append(klass_info)
  660. select_fields = []
  661. columns = self.get_default_columns(
  662. start_alias=alias, opts=model._meta, from_parent=opts.model)
  663. for col in columns:
  664. select_fields.append(len(select))
  665. select.append((col, None))
  666. klass_info['select_fields'] = select_fields
  667. next = requested.get(f.related_query_name(), {})
  668. next_klass_infos = self.get_related_selections(
  669. select, model._meta, alias, cur_depth + 1,
  670. next, restricted)
  671. get_related_klass_infos(klass_info, next_klass_infos)
  672. fields_not_found = set(requested.keys()).difference(fields_found)
  673. if fields_not_found:
  674. invalid_fields = ("'%s'" % s for s in fields_not_found)
  675. raise FieldError(
  676. 'Invalid field name(s) given in select_related: %s. '
  677. 'Choices are: %s' % (
  678. ', '.join(invalid_fields),
  679. ', '.join(_get_field_choices()) or '(none)',
  680. )
  681. )
  682. return related_klass_infos
  683. def deferred_to_columns(self):
  684. """
  685. Converts the self.deferred_loading data structure to mapping of table
  686. names to sets of column names which are to be loaded. Returns the
  687. dictionary.
  688. """
  689. columns = {}
  690. self.query.deferred_to_data(columns, self.query.get_loaded_field_names_cb)
  691. return columns
  692. def get_converters(self, expressions):
  693. converters = {}
  694. for i, expression in enumerate(expressions):
  695. if expression:
  696. backend_converters = self.connection.ops.get_db_converters(expression)
  697. field_converters = expression.get_db_converters(self.connection)
  698. if backend_converters or field_converters:
  699. converters[i] = (backend_converters + field_converters, expression)
  700. return converters
  701. def apply_converters(self, row, converters):
  702. row = list(row)
  703. for pos, (convs, expression) in converters.items():
  704. value = row[pos]
  705. for converter in convs:
  706. value = converter(value, expression, self.connection, self.query.context)
  707. row[pos] = value
  708. return tuple(row)
  709. def results_iter(self, results=None):
  710. """
  711. Returns an iterator over the results from executing this query.
  712. """
  713. converters = None
  714. if results is None:
  715. results = self.execute_sql(MULTI)
  716. fields = [s[0] for s in self.select[0:self.col_count]]
  717. converters = self.get_converters(fields)
  718. for rows in results:
  719. for row in rows:
  720. if converters:
  721. row = self.apply_converters(row, converters)
  722. yield row
  723. def has_results(self):
  724. """
  725. Backends (e.g. NoSQL) can override this in order to use optimized
  726. versions of "query has any results."
  727. """
  728. # This is always executed on a query clone, so we can modify self.query
  729. self.query.add_extra({'a': 1}, None, None, None, None, None)
  730. self.query.set_extra_mask(['a'])
  731. return bool(self.execute_sql(SINGLE))
  732. def execute_sql(self, result_type=MULTI):
  733. """
  734. Run the query against the database and returns the result(s). The
  735. return value is a single data item if result_type is SINGLE, or an
  736. iterator over the results if the result_type is MULTI.
  737. result_type is either MULTI (use fetchmany() to retrieve all rows),
  738. SINGLE (only retrieve a single row), or None. In this last case, the
  739. cursor is returned if any query is executed, since it's used by
  740. subclasses such as InsertQuery). It's possible, however, that no query
  741. is needed, as the filters describe an empty set. In that case, None is
  742. returned, to avoid any unnecessary database interaction.
  743. """
  744. if not result_type:
  745. result_type = NO_RESULTS
  746. try:
  747. sql, params = self.as_sql()
  748. if not sql:
  749. raise EmptyResultSet
  750. except EmptyResultSet:
  751. if result_type == MULTI:
  752. return iter([])
  753. else:
  754. return
  755. cursor = self.connection.cursor()
  756. try:
  757. cursor.execute(sql, params)
  758. except Exception:
  759. cursor.close()
  760. raise
  761. if result_type == CURSOR:
  762. # Caller didn't specify a result_type, so just give them back the
  763. # cursor to process (and close).
  764. return cursor
  765. if result_type == SINGLE:
  766. try:
  767. val = cursor.fetchone()
  768. if val:
  769. return val[0:self.col_count]
  770. return val
  771. finally:
  772. # done with the cursor
  773. cursor.close()
  774. if result_type == NO_RESULTS:
  775. cursor.close()
  776. return
  777. result = cursor_iter(
  778. cursor, self.connection.features.empty_fetchmany_value,
  779. self.col_count
  780. )
  781. if not self.connection.features.can_use_chunked_reads:
  782. try:
  783. # If we are using non-chunked reads, we return the same data
  784. # structure as normally, but ensure it is all read into memory
  785. # before going any further.
  786. return list(result)
  787. finally:
  788. # done with the cursor
  789. cursor.close()
  790. return result
  791. def as_subquery_condition(self, alias, columns, compiler):
  792. qn = compiler.quote_name_unless_alias
  793. qn2 = self.connection.ops.quote_name
  794. if len(columns) == 1:
  795. sql, params = self.as_sql()
  796. return '%s.%s IN (%s)' % (qn(alias), qn2(columns[0]), sql), params
  797. for index, select_col in enumerate(self.query.select):
  798. lhs_sql, lhs_params = self.compile(select_col)
  799. rhs = '%s.%s' % (qn(alias), qn2(columns[index]))
  800. self.query.where.add(
  801. QueryWrapper('%s = %s' % (lhs_sql, rhs), lhs_params), 'AND')
  802. sql, params = self.as_sql()
  803. return 'EXISTS (%s)' % sql, params
  804. class SQLInsertCompiler(SQLCompiler):
  805. def __init__(self, *args, **kwargs):
  806. self.return_id = False
  807. super(SQLInsertCompiler, self).__init__(*args, **kwargs)
  808. def field_as_sql(self, field, val):
  809. """
  810. Take a field and a value intended to be saved on that field, and
  811. return placeholder SQL and accompanying params. Checks for raw values,
  812. expressions and fields with get_placeholder() defined in that order.
  813. When field is None, the value is considered raw and is used as the
  814. placeholder, with no corresponding parameters returned.
  815. """
  816. if field is None:
  817. # A field value of None means the value is raw.
  818. sql, params = val, []
  819. elif hasattr(val, 'as_sql'):
  820. # This is an expression, let's compile it.
  821. sql, params = self.compile(val)
  822. elif hasattr(field, 'get_placeholder'):
  823. # Some fields (e.g. geo fields) need special munging before
  824. # they can be inserted.
  825. sql, params = field.get_placeholder(val, self, self.connection), [val]
  826. else:
  827. # Return the common case for the placeholder
  828. sql, params = '%s', [val]
  829. # The following hook is only used by Oracle Spatial, which sometimes
  830. # needs to yield 'NULL' and [] as its placeholder and params instead
  831. # of '%s' and [None]. The 'NULL' placeholder is produced earlier by
  832. # OracleOperations.get_geom_placeholder(). The following line removes
  833. # the corresponding None parameter. See ticket #10888.
  834. params = self.connection.ops.modify_insert_params(sql, params)
  835. return sql, params
  836. def prepare_value(self, field, value):
  837. """
  838. Prepare a value to be used in a query by resolving it if it is an
  839. expression and otherwise calling the field's get_db_prep_save().
  840. """
  841. if hasattr(value, 'resolve_expression'):
  842. value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
  843. # Don't allow values containing Col expressions. They refer to
  844. # existing columns on a row, but in the case of insert the row
  845. # doesn't exist yet.
  846. if value.contains_column_references:
  847. raise ValueError(
  848. 'Failed to insert expression "%s" on %s. F() expressions '
  849. 'can only be used to update, not to insert.' % (value, field)
  850. )
  851. if value.contains_aggregate:
  852. raise FieldError("Aggregate functions are not allowed in this query")
  853. else:
  854. value = field.get_db_prep_save(value, connection=self.connection)
  855. return value
  856. def pre_save_val(self, field, obj):
  857. """
  858. Get the given field's value off the given obj. pre_save() is used for
  859. things like auto_now on DateTimeField. Skip it if this is a raw query.
  860. """
  861. if self.query.raw:
  862. return getattr(obj, field.attname)
  863. return field.pre_save(obj, add=True)
  864. def assemble_as_sql(self, fields, value_rows):
  865. """
  866. Take a sequence of N fields and a sequence of M rows of values,
  867. generate placeholder SQL and parameters for each field and value, and
  868. return a pair containing:
  869. * a sequence of M rows of N SQL placeholder strings, and
  870. * a sequence of M rows of corresponding parameter values.
  871. Each placeholder string may contain any number of '%s' interpolation
  872. strings, and each parameter row will contain exactly as many params
  873. as the total number of '%s's in the corresponding placeholder row.
  874. """
  875. if not value_rows:
  876. return [], []
  877. # list of (sql, [params]) tuples for each object to be saved
  878. # Shape: [n_objs][n_fields][2]
  879. rows_of_fields_as_sql = (
  880. (self.field_as_sql(field, v) for field, v in zip(fields, row))
  881. for row in value_rows
  882. )
  883. # tuple like ([sqls], [[params]s]) for each object to be saved
  884. # Shape: [n_objs][2][n_fields]
  885. sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql)
  886. # Extract separate lists for placeholders and params.
  887. # Each of these has shape [n_objs][n_fields]
  888. placeholder_rows, param_rows = zip(*sql_and_param_pair_rows)
  889. # Params for each field are still lists, and need to be flattened.
  890. param_rows = [[p for ps in row for p in ps] for row in param_rows]
  891. return placeholder_rows, param_rows
  892. def as_sql(self):
  893. # We don't need quote_name_unless_alias() here, since these are all
  894. # going to be column names (so we can avoid the extra overhead).
  895. qn = self.connection.ops.quote_name
  896. opts = self.query.get_meta()
  897. result = ['INSERT INTO %s' % qn(opts.db_table)]
  898. has_fields = bool(self.query.fields)
  899. fields = self.query.fields if has_fields else [opts.pk]
  900. result.append('(%s)' % ', '.join(qn(f.column) for f in fields))
  901. if has_fields:
  902. value_rows = [
  903. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  904. for obj in self.query.objs
  905. ]
  906. else:
  907. # An empty object.
  908. value_rows = [[self.connection.ops.pk_default_value()] for _ in self.query.objs]
  909. fields = [None]
  910. # Currently the backends just accept values when generating bulk
  911. # queries and generate their own placeholders. Doing that isn't
  912. # necessary and it should be possible to use placeholders and
  913. # expressions in bulk inserts too.
  914. can_bulk = (not self.return_id and self.connection.features.has_bulk_insert)
  915. placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows)
  916. if self.return_id and self.connection.features.can_return_id_from_insert:
  917. params = param_rows[0]
  918. col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column))
  919. result.append("VALUES (%s)" % ", ".join(placeholder_rows[0]))
  920. r_fmt, r_params = self.connection.ops.return_insert_id()
  921. # Skip empty r_fmt to allow subclasses to customize behavior for
  922. # 3rd party backends. Refs #19096.
  923. if r_fmt:
  924. result.append(r_fmt % col)
  925. params += r_params
  926. return [(" ".join(result), tuple(params))]
  927. if can_bulk:
  928. result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
  929. return [(" ".join(result), tuple(p for ps in param_rows for p in ps))]
  930. else:
  931. return [
  932. (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
  933. for p, vals in zip(placeholder_rows, param_rows)
  934. ]
  935. def execute_sql(self, return_id=False):
  936. assert not (return_id and len(self.query.objs) != 1)
  937. self.return_id = return_id
  938. with self.connection.cursor() as cursor:
  939. for sql, params in self.as_sql():
  940. cursor.execute(sql, params)
  941. if not (return_id and cursor):
  942. return
  943. if self.connection.features.can_return_id_from_insert:
  944. return self.connection.ops.fetch_returned_insert_id(cursor)
  945. return self.connection.ops.last_insert_id(cursor,
  946. self.query.get_meta().db_table, self.query.get_meta().pk.column)
  947. class SQLDeleteCompiler(SQLCompiler):
  948. def as_sql(self):
  949. """
  950. Creates the SQL for this query. Returns the SQL string and list of
  951. parameters.
  952. """
  953. assert len([t for t in self.query.tables if self.query.alias_refcount[t] > 0]) == 1, \
  954. "Can only delete from one table at a time."
  955. qn = self.quote_name_unless_alias
  956. result = ['DELETE FROM %s' % qn(self.query.tables[0])]
  957. where, params = self.compile(self.query.where)
  958. if where:
  959. result.append('WHERE %s' % where)
  960. return ' '.join(result), tuple(params)
  961. class SQLUpdateCompiler(SQLCompiler):
  962. def as_sql(self):
  963. """
  964. Creates the SQL for this query. Returns the SQL string and list of
  965. parameters.
  966. """
  967. self.pre_sql_setup()
  968. if not self.query.values:
  969. return '', ()
  970. qn = self.quote_name_unless_alias
  971. values, update_params = [], []
  972. for field, model, val in self.query.values:
  973. if hasattr(val, 'resolve_expression'):
  974. val = val.resolve_expression(self.query, allow_joins=False, for_save=True)
  975. if val.contains_aggregate:
  976. raise FieldError("Aggregate functions are not allowed in this query")
  977. elif hasattr(val, 'prepare_database_save'):
  978. if field.remote_field:
  979. val = field.get_db_prep_save(
  980. val.prepare_database_save(field),
  981. connection=self.connection,
  982. )
  983. else:
  984. raise TypeError(
  985. "Tried to update field %s with a model instance, %r. "
  986. "Use a value compatible with %s."
  987. % (field, val, field.__class__.__name__)
  988. )
  989. else:
  990. val = field.get_db_prep_save(val, connection=self.connection)
  991. # Getting the placeholder for the field.
  992. if hasattr(field, 'get_placeholder'):
  993. placeholder = field.get_placeholder(val, self, self.connection)
  994. else:
  995. placeholder = '%s'
  996. name = field.column
  997. if hasattr(val, 'as_sql'):
  998. sql, params = self.compile(val)
  999. values.append('%s = %s' % (qn(name), sql))
  1000. update_params.extend(params)
  1001. elif val is not None:
  1002. values.append('%s = %s' % (qn(name), placeholder))
  1003. update_params.append(val)
  1004. else:
  1005. values.append('%s = NULL' % qn(name))
  1006. if not values:
  1007. return '', ()
  1008. table = self.query.tables[0]
  1009. result = [
  1010. 'UPDATE %s SET' % qn(table),
  1011. ', '.join(values),
  1012. ]
  1013. where, params = self.compile(self.query.where)
  1014. if where:
  1015. result.append('WHERE %s' % where)
  1016. return ' '.join(result), tuple(update_params + params)
  1017. def execute_sql(self, result_type):
  1018. """
  1019. Execute the specified update. Returns the number of rows affected by
  1020. the primary update query. The "primary update query" is the first
  1021. non-empty query that is executed. Row counts for any subsequent,
  1022. related queries are not available.
  1023. """