2017-06-30 04:00:15 +08:00
|
|
|
import collections
|
2015-01-09 23:16:16 +08:00
|
|
|
import re
|
2019-10-11 03:13:21 +08:00
|
|
|
from functools import partial
|
2015-01-28 20:35:27 +08:00
|
|
|
from itertools import chain
|
2011-09-10 03:22:28 +08:00
|
|
|
|
2016-05-26 03:00:20 +08:00
|
|
|
from django.core.exceptions import EmptyResultSet, FieldError
|
2019-08-20 15:54:41 +08:00
|
|
|
from django.db import DatabaseError, NotSupportedError
|
2012-09-09 07:51:36 +08:00
|
|
|
from django.db.models.constants import LOOKUP_SEP
|
2020-05-26 15:11:11 +08:00
|
|
|
from django.db.models.expressions import F, OrderBy, Random, RawSQL, Ref, Value
|
2019-05-22 02:10:24 +08:00
|
|
|
from django.db.models.functions import Cast
|
2019-11-18 17:45:24 +08:00
|
|
|
from django.db.models.query_utils import Q, select_related_descend
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.db.models.sql.constants import (
|
|
|
|
CURSOR, GET_ITERATOR_CHUNK_SIZE, MULTI, NO_RESULTS, ORDER_DIR, SINGLE,
|
|
|
|
)
|
|
|
|
from django.db.models.sql.query import Query, get_order_dir
|
2014-03-31 01:03:35 +08:00
|
|
|
from django.db.transaction import TransactionManagementError
|
2019-10-17 13:57:39 +08:00
|
|
|
from django.utils.functional import cached_property
|
2019-04-17 14:24:28 +08:00
|
|
|
from django.utils.hashable import make_hashable
|
2020-04-23 02:28:01 +08:00
|
|
|
from django.utils.regex_helper import _lazy_re_compile
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2011-09-10 03:22:28 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class SQLCompiler:
|
2020-04-23 02:28:01 +08:00
|
|
|
# Multiline ordering SQL clause may appear from RawSQL.
|
|
|
|
ordering_parts = _lazy_re_compile(
|
|
|
|
r'^(.*)\s(?:ASC|DESC).*',
|
|
|
|
re.MULTILINE | re.DOTALL,
|
|
|
|
)
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def __init__(self, query, connection, using):
|
|
|
|
self.query = query
|
|
|
|
self.connection = connection
|
|
|
|
self.using = using
|
2013-09-25 04:00:31 +08:00
|
|
|
self.quote_cache = {'*': '*'}
|
2014-12-01 15:28:01 +08:00
|
|
|
# The select, klass_info, and annotations are needed by QuerySet.iterator()
|
|
|
|
# these are set as a side-effect of executing the query. Note that we calculate
|
|
|
|
# separately a list of extra select columns needed for grammatical correctness
|
|
|
|
# of the query, but these columns are not included in self.select.
|
|
|
|
self.select = None
|
|
|
|
self.annotation_col_map = None
|
|
|
|
self.klass_info = None
|
2018-09-14 00:29:48 +08:00
|
|
|
self._meta_ordering = None
|
2014-12-01 15:28:01 +08:00
|
|
|
|
|
|
|
def setup_query(self):
|
2017-06-28 14:23:37 +08:00
|
|
|
if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map):
|
2014-12-01 15:28:01 +08:00
|
|
|
self.query.get_initial_alias()
|
|
|
|
self.select, self.klass_info, self.annotation_col_map = self.get_select()
|
|
|
|
self.col_count = len(self.select)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
def pre_sql_setup(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Do any necessary class setup immediately prior to producing SQL. This
|
2009-12-22 23:18:51 +08:00
|
|
|
is for things that can't necessarily be done in __init__ because we
|
|
|
|
might not have all the pieces in place at that time.
|
|
|
|
"""
|
2014-12-01 15:28:01 +08:00
|
|
|
self.setup_query()
|
|
|
|
order_by = self.get_order_by()
|
2014-12-23 21:16:56 +08:00
|
|
|
self.where, self.having = self.query.where.split_having()
|
2014-12-01 15:28:01 +08:00
|
|
|
extra_select = self.get_extra_select(order_by, self.select)
|
2017-08-09 02:07:03 +08:00
|
|
|
self.has_extra_select = bool(extra_select)
|
2014-12-01 15:28:01 +08:00
|
|
|
group_by = self.get_group_by(self.select + extra_select, order_by)
|
|
|
|
return extra_select, order_by, group_by
|
|
|
|
|
|
|
|
def get_group_by(self, select, order_by):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return a list of 2-tuples of form (sql, params).
|
2014-12-01 15:28:01 +08:00
|
|
|
|
|
|
|
The logic of what exactly the GROUP BY clause contains is hard
|
|
|
|
to describe in other words than "if it passes the test suite,
|
|
|
|
then it is correct".
|
|
|
|
"""
|
|
|
|
# Some examples:
|
|
|
|
# SomeModel.objects.annotate(Count('somecol'))
|
|
|
|
# GROUP BY: all fields of the model
|
|
|
|
#
|
|
|
|
# SomeModel.objects.values('name').annotate(Count('somecol'))
|
|
|
|
# GROUP BY: name
|
|
|
|
#
|
|
|
|
# SomeModel.objects.annotate(Count('somecol')).values('name')
|
|
|
|
# GROUP BY: all cols of the model
|
|
|
|
#
|
|
|
|
# SomeModel.objects.values('name', 'pk').annotate(Count('somecol')).values('pk')
|
|
|
|
# GROUP BY: name, pk
|
|
|
|
#
|
|
|
|
# SomeModel.objects.values('name').annotate(Count('somecol')).values('pk')
|
|
|
|
# GROUP BY: name, pk
|
|
|
|
#
|
|
|
|
# In fact, the self.query.group_by is the minimal set to GROUP BY. It
|
|
|
|
# can't be ever restricted to a smaller set, but additional columns in
|
|
|
|
# HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately
|
|
|
|
# the end result is that it is impossible to force the query to have
|
|
|
|
# a chosen GROUP BY clause - you can almost do this by using the form:
|
|
|
|
# .values(*wanted_cols).annotate(AnAggregate())
|
|
|
|
# but any later annotations, extra selects, values calls that
|
|
|
|
# refer some column outside of the wanted_cols, order_by, or even
|
|
|
|
# filter calls can alter the GROUP BY clause.
|
|
|
|
|
|
|
|
# The query.group_by is either None (no GROUP BY at all), True
|
|
|
|
# (group by select fields), or a list of expressions to be added
|
|
|
|
# to the group by.
|
|
|
|
if self.query.group_by is None:
|
|
|
|
return []
|
|
|
|
expressions = []
|
|
|
|
if self.query.group_by is not True:
|
|
|
|
# If the group by is set to a list (by .values() call most likely),
|
|
|
|
# then we need to add everything in it to the GROUP BY clause.
|
|
|
|
# Backwards compatibility hack for setting query.group_by. Remove
|
|
|
|
# when we have public API way of forcing the GROUP BY clause.
|
|
|
|
# Converts string references to expressions.
|
|
|
|
for expr in self.query.group_by:
|
|
|
|
if not hasattr(expr, 'as_sql'):
|
|
|
|
expressions.append(self.query.resolve_ref(expr))
|
|
|
|
else:
|
|
|
|
expressions.append(expr)
|
|
|
|
# Note that even if the group_by is set, it is only the minimal
|
|
|
|
# set to group by. So, we need to add cols in select, order_by, and
|
|
|
|
# having into the select in any case.
|
2019-12-17 14:21:13 +08:00
|
|
|
ref_sources = {
|
|
|
|
expr.source for expr in expressions if isinstance(expr, Ref)
|
|
|
|
}
|
2014-12-01 15:28:01 +08:00
|
|
|
for expr, _, _ in select:
|
2019-12-17 14:21:13 +08:00
|
|
|
# Skip members of the select clause that are already included
|
|
|
|
# by reference.
|
|
|
|
if expr in ref_sources:
|
|
|
|
continue
|
2014-12-01 15:28:01 +08:00
|
|
|
cols = expr.get_group_by_cols()
|
|
|
|
for col in cols:
|
|
|
|
expressions.append(col)
|
2015-01-09 23:16:16 +08:00
|
|
|
for expr, (sql, params, is_ref) in order_by:
|
2018-01-12 22:05:16 +08:00
|
|
|
# Skip References to the select clause, as all expressions in the
|
|
|
|
# select clause are already part of the group by.
|
2020-02-03 14:48:11 +08:00
|
|
|
if not is_ref:
|
|
|
|
expressions.extend(expr.get_group_by_cols())
|
2014-12-23 21:16:56 +08:00
|
|
|
having_group_by = self.having.get_group_by_cols() if self.having else ()
|
|
|
|
for expr in having_group_by:
|
2014-12-01 15:28:01 +08:00
|
|
|
expressions.append(expr)
|
|
|
|
result = []
|
|
|
|
seen = set()
|
2014-12-23 21:16:56 +08:00
|
|
|
expressions = self.collapse_group_by(expressions, having_group_by)
|
2014-12-01 15:28:01 +08:00
|
|
|
|
|
|
|
for expr in expressions:
|
|
|
|
sql, params = self.compile(expr)
|
2020-05-14 21:07:08 +08:00
|
|
|
sql, params = expr.select_format(self, sql, params)
|
2019-04-17 14:24:28 +08:00
|
|
|
params_hash = make_hashable(params)
|
|
|
|
if (sql, params_hash) not in seen:
|
2014-12-01 15:28:01 +08:00
|
|
|
result.append((sql, params))
|
2019-04-17 14:24:28 +08:00
|
|
|
seen.add((sql, params_hash))
|
2014-12-01 15:28:01 +08:00
|
|
|
return result
|
|
|
|
|
|
|
|
def collapse_group_by(self, expressions, having):
|
|
|
|
# If the DB can group by primary key, then group by the primary key of
|
|
|
|
# query's main model. Note that for PostgreSQL the GROUP BY clause must
|
|
|
|
# include the primary key of every table, but for MySQL it is enough to
|
2015-03-27 04:54:43 +08:00
|
|
|
# have the main table's primary key.
|
2014-12-01 15:28:01 +08:00
|
|
|
if self.connection.features.allows_group_by_pk:
|
2017-03-29 12:47:07 +08:00
|
|
|
# Determine if the main model's primary key is in the query.
|
2014-12-01 15:28:01 +08:00
|
|
|
pk = None
|
|
|
|
for expr in expressions:
|
2015-05-05 19:44:33 +08:00
|
|
|
# Is this a reference to query's base table primary key? If the
|
|
|
|
# expression isn't a Col-like, then skip the expression.
|
|
|
|
if (getattr(expr, 'target', None) == self.query.model._meta.pk and
|
2017-06-28 14:23:37 +08:00
|
|
|
getattr(expr, 'alias', None) == self.query.base_table):
|
2014-12-01 15:28:01 +08:00
|
|
|
pk = expr
|
2015-05-05 19:44:33 +08:00
|
|
|
break
|
2017-03-29 12:47:07 +08:00
|
|
|
# If the main model's primary key is in the query, group by that
|
|
|
|
# field, HAVING expressions, and expressions associated with tables
|
|
|
|
# that don't have a primary key included in the grouped columns.
|
2014-12-01 15:28:01 +08:00
|
|
|
if pk:
|
2017-03-29 12:47:07 +08:00
|
|
|
pk_aliases = {
|
|
|
|
expr.alias for expr in expressions
|
|
|
|
if hasattr(expr, 'target') and expr.target.primary_key
|
|
|
|
}
|
|
|
|
expressions = [pk] + [
|
|
|
|
expr for expr in expressions
|
2018-05-28 06:25:19 +08:00
|
|
|
if expr in having or (
|
|
|
|
getattr(expr, 'alias', None) is not None and expr.alias not in pk_aliases
|
|
|
|
)
|
2017-03-29 12:47:07 +08:00
|
|
|
]
|
2015-03-27 04:54:43 +08:00
|
|
|
elif self.connection.features.allows_group_by_selected_pks:
|
|
|
|
# Filter out all expressions associated with a table's primary key
|
|
|
|
# present in the grouped columns. This is done by identifying all
|
|
|
|
# tables that have their primary key included in the grouped
|
|
|
|
# columns and removing non-primary key columns referring to them.
|
2017-04-30 02:53:43 +08:00
|
|
|
# Unmanaged models are excluded because they could be representing
|
|
|
|
# database views on which the optimization might not be allowed.
|
|
|
|
pks = {
|
|
|
|
expr for expr in expressions
|
2019-07-29 22:40:27 +08:00
|
|
|
if (
|
|
|
|
hasattr(expr, 'target') and
|
|
|
|
expr.target.primary_key and
|
|
|
|
self.connection.features.allows_group_by_selected_pks_on_model(expr.target.model)
|
|
|
|
)
|
2017-04-30 02:53:43 +08:00
|
|
|
}
|
2015-03-27 04:54:43 +08:00
|
|
|
aliases = {expr.alias for expr in pks}
|
|
|
|
expressions = [
|
|
|
|
expr for expr in expressions if expr in pks or getattr(expr, 'alias', None) not in aliases
|
|
|
|
]
|
2014-12-01 15:28:01 +08:00
|
|
|
return expressions
|
|
|
|
|
|
|
|
def get_select(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return three values:
|
2014-12-01 15:28:01 +08:00
|
|
|
- a list of 3-tuples of (expression, (sql, params), alias)
|
|
|
|
- a klass_info structure,
|
|
|
|
- a dictionary of annotations
|
|
|
|
|
|
|
|
The (sql, params) is what the expression will produce, and alias is the
|
|
|
|
"AS alias" for the column (possibly None).
|
|
|
|
|
|
|
|
The klass_info structure contains the following information:
|
2017-12-23 17:35:08 +08:00
|
|
|
- The base model of the query.
|
2014-12-01 15:28:01 +08:00
|
|
|
- Which columns for that model are present in the query (by
|
|
|
|
position of the select clause).
|
|
|
|
- related_klass_infos: [f, klass_info] to descent into
|
|
|
|
|
|
|
|
The annotations is a dictionary of {'attname': column position} values.
|
|
|
|
"""
|
|
|
|
select = []
|
|
|
|
klass_info = None
|
|
|
|
annotations = {}
|
|
|
|
select_idx = 0
|
|
|
|
for alias, (sql, params) in self.query.extra_select.items():
|
|
|
|
annotations[alias] = select_idx
|
|
|
|
select.append((RawSQL(sql, params), alias))
|
|
|
|
select_idx += 1
|
|
|
|
assert not (self.query.select and self.query.default_cols)
|
|
|
|
if self.query.default_cols:
|
2017-12-23 17:35:08 +08:00
|
|
|
cols = self.get_default_columns()
|
|
|
|
else:
|
|
|
|
# self.query.select is a special case. These columns never go to
|
|
|
|
# any model.
|
|
|
|
cols = self.query.select
|
|
|
|
if cols:
|
2014-12-01 15:28:01 +08:00
|
|
|
select_list = []
|
2017-12-23 17:35:08 +08:00
|
|
|
for col in cols:
|
2014-12-01 15:28:01 +08:00
|
|
|
select_list.append(select_idx)
|
2017-12-23 17:35:08 +08:00
|
|
|
select.append((col, None))
|
2014-12-01 15:28:01 +08:00
|
|
|
select_idx += 1
|
|
|
|
klass_info = {
|
|
|
|
'model': self.query.model,
|
|
|
|
'select_fields': select_list,
|
|
|
|
}
|
|
|
|
for alias, annotation in self.query.annotation_select.items():
|
|
|
|
annotations[alias] = select_idx
|
|
|
|
select.append((annotation, alias))
|
|
|
|
select_idx += 1
|
|
|
|
|
|
|
|
if self.query.select_related:
|
|
|
|
related_klass_infos = self.get_related_selections(select)
|
|
|
|
klass_info['related_klass_infos'] = related_klass_infos
|
|
|
|
|
|
|
|
def get_select_from_parent(klass_info):
|
|
|
|
for ki in klass_info['related_klass_infos']:
|
|
|
|
if ki['from_parent']:
|
|
|
|
ki['select_fields'] = (klass_info['select_fields'] +
|
|
|
|
ki['select_fields'])
|
|
|
|
get_select_from_parent(ki)
|
|
|
|
get_select_from_parent(klass_info)
|
|
|
|
|
|
|
|
ret = []
|
|
|
|
for col, alias in select:
|
2016-08-05 21:09:01 +08:00
|
|
|
try:
|
2019-08-10 02:30:23 +08:00
|
|
|
sql, params = self.compile(col)
|
2016-08-05 21:09:01 +08:00
|
|
|
except EmptyResultSet:
|
|
|
|
# Select a predicate that's always False.
|
|
|
|
sql, params = '0', ()
|
2019-08-10 02:30:23 +08:00
|
|
|
else:
|
|
|
|
sql, params = col.select_format(self, sql, params)
|
2016-08-05 21:09:01 +08:00
|
|
|
ret.append((col, (sql, params), alias))
|
2014-12-01 15:28:01 +08:00
|
|
|
return ret, klass_info, annotations
|
|
|
|
|
|
|
|
def get_order_by(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return a list of 2-tuples of form (expr, (sql, params, is_ref)) for the
|
2014-12-01 15:28:01 +08:00
|
|
|
ORDER BY clause.
|
|
|
|
|
|
|
|
The order_by clause can alter the select clause (for example it
|
|
|
|
can add aliases to clauses that do not yet have one, or it can
|
|
|
|
add totally new select clauses).
|
|
|
|
"""
|
|
|
|
if self.query.extra_order_by:
|
|
|
|
ordering = self.query.extra_order_by
|
|
|
|
elif not self.query.default_ordering:
|
|
|
|
ordering = self.query.order_by
|
2018-09-14 00:29:48 +08:00
|
|
|
elif self.query.order_by:
|
|
|
|
ordering = self.query.order_by
|
|
|
|
elif self.query.get_meta().ordering:
|
|
|
|
ordering = self.query.get_meta().ordering
|
|
|
|
self._meta_ordering = ordering
|
2014-12-01 15:28:01 +08:00
|
|
|
else:
|
2018-09-14 00:29:48 +08:00
|
|
|
ordering = []
|
2014-12-01 15:28:01 +08:00
|
|
|
if self.query.standard_ordering:
|
|
|
|
asc, desc = ORDER_DIR['ASC']
|
|
|
|
else:
|
|
|
|
asc, desc = ORDER_DIR['DESC']
|
|
|
|
|
|
|
|
order_by = []
|
2016-12-29 21:55:17 +08:00
|
|
|
for field in ordering:
|
2015-01-09 23:16:16 +08:00
|
|
|
if hasattr(field, 'resolve_expression'):
|
2019-05-22 02:10:24 +08:00
|
|
|
if isinstance(field, Value):
|
|
|
|
# output_field must be resolved for constants.
|
|
|
|
field = Cast(field, field.output_field)
|
2015-01-09 23:16:16 +08:00
|
|
|
if not isinstance(field, OrderBy):
|
|
|
|
field = field.asc()
|
|
|
|
if not self.query.standard_ordering:
|
2019-05-24 02:33:37 +08:00
|
|
|
field = field.copy()
|
2015-01-09 23:16:16 +08:00
|
|
|
field.reverse_ordering()
|
|
|
|
order_by.append((field, False))
|
2014-12-01 15:28:01 +08:00
|
|
|
continue
|
2015-01-09 23:16:16 +08:00
|
|
|
if field == '?': # random
|
|
|
|
order_by.append((OrderBy(Random()), False))
|
2014-12-01 15:28:01 +08:00
|
|
|
continue
|
2015-01-09 23:16:16 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
col, order = get_order_dir(field, asc)
|
2018-01-12 22:05:16 +08:00
|
|
|
descending = order == 'DESC'
|
2015-01-09 23:16:16 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
if col in self.query.annotation_select:
|
2015-04-15 13:46:19 +08:00
|
|
|
# Reference to expression in SELECT clause
|
2015-01-09 23:16:16 +08:00
|
|
|
order_by.append((
|
|
|
|
OrderBy(Ref(col, self.query.annotation_select[col]), descending=descending),
|
|
|
|
True))
|
2014-12-01 15:28:01 +08:00
|
|
|
continue
|
2015-04-15 13:46:19 +08:00
|
|
|
if col in self.query.annotations:
|
2019-05-22 02:10:24 +08:00
|
|
|
# References to an expression which is masked out of the SELECT
|
|
|
|
# clause.
|
|
|
|
expr = self.query.annotations[col]
|
|
|
|
if isinstance(expr, Value):
|
|
|
|
# output_field must be resolved for constants.
|
|
|
|
expr = Cast(expr, expr.output_field)
|
|
|
|
order_by.append((OrderBy(expr, descending=descending), False))
|
2015-04-15 13:46:19 +08:00
|
|
|
continue
|
2015-01-09 23:16:16 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
if '.' in field:
|
|
|
|
# This came in through an extra(order_by=...) addition. Pass it
|
|
|
|
# on verbatim.
|
|
|
|
table, col = col.split('.', 1)
|
2015-01-09 23:16:16 +08:00
|
|
|
order_by.append((
|
2015-01-19 07:35:10 +08:00
|
|
|
OrderBy(
|
|
|
|
RawSQL('%s.%s' % (self.quote_name_unless_alias(table), col), []),
|
|
|
|
descending=descending
|
|
|
|
), False))
|
2014-12-01 15:28:01 +08:00
|
|
|
continue
|
2015-01-09 23:16:16 +08:00
|
|
|
|
2019-02-05 19:22:08 +08:00
|
|
|
if not self.query.extra or col not in self.query.extra:
|
2014-12-01 15:28:01 +08:00
|
|
|
# 'col' is of the form 'field' or 'field1__field2' or
|
|
|
|
# '-field1__field2__field', etc.
|
2015-01-09 23:16:16 +08:00
|
|
|
order_by.extend(self.find_ordering_name(
|
|
|
|
field, self.query.get_meta(), default_order=asc))
|
2014-12-01 15:28:01 +08:00
|
|
|
else:
|
|
|
|
if col not in self.query.extra_select:
|
2015-01-09 23:16:16 +08:00
|
|
|
order_by.append((
|
|
|
|
OrderBy(RawSQL(*self.query.extra[col]), descending=descending),
|
|
|
|
False))
|
2014-12-01 15:28:01 +08:00
|
|
|
else:
|
2015-01-09 23:16:16 +08:00
|
|
|
order_by.append((
|
|
|
|
OrderBy(Ref(col, RawSQL(*self.query.extra[col])), descending=descending),
|
|
|
|
True))
|
2014-12-01 15:28:01 +08:00
|
|
|
result = []
|
|
|
|
seen = set()
|
2015-01-09 23:16:16 +08:00
|
|
|
|
|
|
|
for expr, is_ref in order_by:
|
2019-01-14 23:28:11 +08:00
|
|
|
resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
|
2017-01-14 21:32:07 +08:00
|
|
|
if self.query.combinator:
|
2019-01-14 23:28:11 +08:00
|
|
|
src = resolved.get_source_expressions()[0]
|
2020-05-26 15:11:11 +08:00
|
|
|
expr_src = expr.get_source_expressions()[0]
|
2017-01-14 21:32:07 +08:00
|
|
|
# Relabel order by columns to raw numbers if this is a combined
|
|
|
|
# query; necessary since the columns can't be referenced by the
|
|
|
|
# fully qualified name and the simple column names may collide.
|
|
|
|
for idx, (sel_expr, _, col_alias) in enumerate(self.select):
|
|
|
|
if is_ref and col_alias == src.refs:
|
|
|
|
src = src.source
|
2020-05-26 15:11:11 +08:00
|
|
|
elif col_alias and not (
|
|
|
|
isinstance(expr_src, F) and col_alias == expr_src.name
|
|
|
|
):
|
2017-01-14 21:32:07 +08:00
|
|
|
continue
|
|
|
|
if src == sel_expr:
|
2019-01-14 23:28:11 +08:00
|
|
|
resolved.set_source_expressions([RawSQL('%d' % (idx + 1), ())])
|
2017-01-14 21:32:07 +08:00
|
|
|
break
|
|
|
|
else:
|
2019-03-28 02:18:18 +08:00
|
|
|
if col_alias:
|
|
|
|
raise DatabaseError('ORDER BY term does not match any column in the result set.')
|
|
|
|
# Add column used in ORDER BY clause without an alias to
|
|
|
|
# the selected columns.
|
|
|
|
self.query.add_select_col(src)
|
|
|
|
resolved.set_source_expressions([RawSQL('%d' % len(self.query.select), ())])
|
2015-01-09 23:16:16 +08:00
|
|
|
sql, params = self.compile(resolved)
|
|
|
|
# Don't add the same column twice, but the order direction is
|
|
|
|
# not taken into account so we strip it. When this entire method
|
|
|
|
# is refactored into expressions, then we can check each part as we
|
|
|
|
# generate it.
|
2020-05-11 04:03:39 +08:00
|
|
|
without_ordering = self.ordering_parts.search(sql)[1]
|
2019-04-17 14:24:28 +08:00
|
|
|
params_hash = make_hashable(params)
|
|
|
|
if (without_ordering, params_hash) in seen:
|
2014-12-01 15:28:01 +08:00
|
|
|
continue
|
2019-04-17 14:24:28 +08:00
|
|
|
seen.add((without_ordering, params_hash))
|
2015-01-09 23:16:16 +08:00
|
|
|
result.append((resolved, (sql, params, is_ref)))
|
2014-12-01 15:28:01 +08:00
|
|
|
return result
|
|
|
|
|
|
|
|
def get_extra_select(self, order_by, select):
|
|
|
|
extra_select = []
|
|
|
|
if self.query.distinct and not self.query.distinct_fields:
|
2017-09-03 04:39:51 +08:00
|
|
|
select_sql = [t[1] for t in select]
|
2015-01-09 23:16:16 +08:00
|
|
|
for expr, (sql, params, is_ref) in order_by:
|
2020-05-11 04:03:39 +08:00
|
|
|
without_ordering = self.ordering_parts.search(sql)[1]
|
2015-01-09 23:16:16 +08:00
|
|
|
if not is_ref and (without_ordering, params) not in select_sql:
|
|
|
|
extra_select.append((expr, (without_ordering, params), None))
|
2014-12-01 15:28:01 +08:00
|
|
|
return extra_select
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2014-11-18 09:05:14 +08:00
|
|
|
def quote_name_unless_alias(self, name):
|
2009-12-22 23:18:51 +08:00
|
|
|
"""
|
|
|
|
A wrapper around connection.ops.quote_name that doesn't quote aliases
|
|
|
|
for table names. This avoids problems with some SQL dialects that treat
|
|
|
|
quoted strings specially (e.g. PostgreSQL).
|
|
|
|
"""
|
|
|
|
if name in self.quote_cache:
|
|
|
|
return self.quote_cache[name]
|
|
|
|
if ((name in self.query.alias_map and name not in self.query.table_map) or
|
2015-04-16 13:39:31 +08:00
|
|
|
name in self.query.extra_select or (
|
2019-12-17 14:21:13 +08:00
|
|
|
self.query.external_aliases.get(name) and name not in self.query.table_map)):
|
2009-12-22 23:18:51 +08:00
|
|
|
self.quote_cache[name] = name
|
|
|
|
return name
|
|
|
|
r = self.connection.ops.quote_name(name)
|
|
|
|
self.quote_cache[name] = r
|
|
|
|
return r
|
|
|
|
|
2019-08-10 02:30:23 +08:00
|
|
|
def compile(self, node):
|
2014-12-01 15:28:01 +08:00
|
|
|
vendor_impl = getattr(node, 'as_' + self.connection.vendor, None)
|
2014-01-18 17:09:43 +08:00
|
|
|
if vendor_impl:
|
2014-12-01 15:28:01 +08:00
|
|
|
sql, params = vendor_impl(self, self.connection)
|
2014-01-18 17:09:43 +08:00
|
|
|
else:
|
2014-12-01 15:28:01 +08:00
|
|
|
sql, params = node.as_sql(self, self.connection)
|
|
|
|
return sql, params
|
2014-01-18 17:09:43 +08:00
|
|
|
|
2017-01-14 21:32:07 +08:00
|
|
|
def get_combinator_sql(self, combinator, all):
|
|
|
|
features = self.connection.features
|
|
|
|
compilers = [
|
|
|
|
query.get_compiler(self.using, self.connection)
|
2017-06-13 14:16:16 +08:00
|
|
|
for query in self.query.combined_queries if not query.is_empty()
|
2017-01-14 21:32:07 +08:00
|
|
|
]
|
|
|
|
if not features.supports_slicing_ordering_in_compound:
|
|
|
|
for query, compiler in zip(self.query.combined_queries, compilers):
|
|
|
|
if query.low_mark or query.high_mark:
|
|
|
|
raise DatabaseError('LIMIT/OFFSET not allowed in subqueries of compound statements.')
|
|
|
|
if compiler.get_order_by():
|
|
|
|
raise DatabaseError('ORDER BY not allowed in subqueries of compound statements.')
|
2017-07-11 01:45:09 +08:00
|
|
|
parts = ()
|
|
|
|
for compiler in compilers:
|
|
|
|
try:
|
2017-11-12 21:28:11 +08:00
|
|
|
# If the columns list is limited, then all combined queries
|
|
|
|
# must have the same columns list. Set the selects defined on
|
|
|
|
# the query on all combined queries, if not already set.
|
2018-04-13 18:15:52 +08:00
|
|
|
if not compiler.query.values_select and self.query.values_select:
|
2019-06-19 16:44:53 +08:00
|
|
|
compiler.query = compiler.query.clone()
|
2018-08-29 16:00:15 +08:00
|
|
|
compiler.query.set_values((
|
|
|
|
*self.query.extra_select,
|
|
|
|
*self.query.values_select,
|
|
|
|
*self.query.annotation_select,
|
|
|
|
))
|
2018-12-03 06:17:32 +08:00
|
|
|
part_sql, part_args = compiler.as_sql()
|
|
|
|
if compiler.query.combinator:
|
|
|
|
# Wrap in a subquery if wrapping in parentheses isn't
|
|
|
|
# supported.
|
|
|
|
if not features.supports_parentheses_in_compound:
|
|
|
|
part_sql = 'SELECT * FROM ({})'.format(part_sql)
|
|
|
|
# Add parentheses when combining with compound query if not
|
|
|
|
# already added for all compound queries.
|
|
|
|
elif not features.supports_slicing_ordering_in_compound:
|
|
|
|
part_sql = '({})'.format(part_sql)
|
|
|
|
parts += ((part_sql, part_args),)
|
2017-07-11 01:45:09 +08:00
|
|
|
except EmptyResultSet:
|
|
|
|
# Omit the empty queryset with UNION and with DIFFERENCE if the
|
|
|
|
# first queryset is nonempty.
|
|
|
|
if combinator == 'union' or (combinator == 'difference' and parts):
|
|
|
|
continue
|
|
|
|
raise
|
|
|
|
if not parts:
|
2017-07-15 00:11:29 +08:00
|
|
|
raise EmptyResultSet
|
2017-01-14 21:32:07 +08:00
|
|
|
combinator_sql = self.connection.ops.set_operators[combinator]
|
|
|
|
if all and combinator == 'union':
|
|
|
|
combinator_sql += ' ALL'
|
|
|
|
braces = '({})' if features.supports_slicing_ordering_in_compound else '{}'
|
|
|
|
sql_parts, args_parts = zip(*((braces.format(sql), args) for sql, args in parts))
|
|
|
|
result = [' {} '.format(combinator_sql).join(sql_parts)]
|
|
|
|
params = []
|
|
|
|
for part in args_parts:
|
|
|
|
params.extend(part)
|
|
|
|
return result, params
|
|
|
|
|
2016-10-28 23:20:23 +08:00
|
|
|
def as_sql(self, with_limits=True, with_col_aliases=False):
|
2009-12-22 23:18:51 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Create the SQL for this query. Return the SQL string and list of
|
2009-12-22 23:18:51 +08:00
|
|
|
parameters.
|
|
|
|
|
|
|
|
If 'with_limits' is False, any limit/offset information is not included
|
|
|
|
in the query.
|
|
|
|
"""
|
2014-06-14 18:48:47 +08:00
|
|
|
refcounts_before = self.query.alias_refcount.copy()
|
2014-12-01 15:28:01 +08:00
|
|
|
try:
|
|
|
|
extra_select, order_by, group_by = self.pre_sql_setup()
|
2017-01-14 21:32:07 +08:00
|
|
|
for_update_part = None
|
2017-10-10 00:07:03 +08:00
|
|
|
# Is a LIMIT/OFFSET clause needed?
|
|
|
|
with_limit_offset = with_limits and (self.query.high_mark is not None or self.query.low_mark)
|
2017-01-14 21:32:07 +08:00
|
|
|
combinator = self.query.combinator
|
|
|
|
features = self.connection.features
|
|
|
|
if combinator:
|
|
|
|
if not getattr(features, 'supports_select_{}'.format(combinator)):
|
2017-04-11 00:49:27 +08:00
|
|
|
raise NotSupportedError('{} is not supported on this database backend.'.format(combinator))
|
2017-01-14 21:32:07 +08:00
|
|
|
result, params = self.get_combinator_sql(combinator, self.query.combinator_all)
|
|
|
|
else:
|
2017-06-18 23:53:40 +08:00
|
|
|
distinct_fields, distinct_params = self.get_distinct()
|
2017-07-11 01:45:09 +08:00
|
|
|
# This must come after 'select', 'ordering', and 'distinct'
|
|
|
|
# (see docstring of get_from_clause() for details).
|
|
|
|
from_, f_params = self.get_from_clause()
|
|
|
|
where, w_params = self.compile(self.where) if self.where is not None else ("", [])
|
|
|
|
having, h_params = self.compile(self.having) if self.having is not None else ("", [])
|
2017-01-14 21:32:07 +08:00
|
|
|
result = ['SELECT']
|
|
|
|
params = []
|
|
|
|
|
|
|
|
if self.query.distinct:
|
2017-06-18 23:53:40 +08:00
|
|
|
distinct_result, distinct_params = self.connection.ops.distinct_sql(
|
|
|
|
distinct_fields,
|
|
|
|
distinct_params,
|
|
|
|
)
|
|
|
|
result += distinct_result
|
|
|
|
params += distinct_params
|
2017-01-14 21:32:07 +08:00
|
|
|
|
|
|
|
out_cols = []
|
|
|
|
col_idx = 1
|
|
|
|
for _, (s_sql, s_params), alias in self.select + extra_select:
|
|
|
|
if alias:
|
|
|
|
s_sql = '%s AS %s' % (s_sql, self.connection.ops.quote_name(alias))
|
|
|
|
elif with_col_aliases:
|
|
|
|
s_sql = '%s AS %s' % (s_sql, 'Col%d' % col_idx)
|
|
|
|
col_idx += 1
|
|
|
|
params.extend(s_params)
|
|
|
|
out_cols.append(s_sql)
|
|
|
|
|
2017-12-11 20:08:45 +08:00
|
|
|
result += [', '.join(out_cols), 'FROM', *from_]
|
2017-01-14 21:32:07 +08:00
|
|
|
params.extend(f_params)
|
|
|
|
|
|
|
|
if self.query.select_for_update and self.connection.features.has_select_for_update:
|
|
|
|
if self.connection.get_autocommit():
|
|
|
|
raise TransactionManagementError('select_for_update cannot be used outside of a transaction.')
|
|
|
|
|
2017-10-10 00:07:03 +08:00
|
|
|
if with_limit_offset and not self.connection.features.supports_select_for_update_with_limit:
|
2017-04-07 20:08:07 +08:00
|
|
|
raise NotSupportedError(
|
2017-04-11 00:49:27 +08:00
|
|
|
'LIMIT/OFFSET is not supported with '
|
|
|
|
'select_for_update on this database backend.'
|
2017-04-07 20:08:07 +08:00
|
|
|
)
|
2017-01-14 21:32:07 +08:00
|
|
|
nowait = self.query.select_for_update_nowait
|
|
|
|
skip_locked = self.query.select_for_update_skip_locked
|
2017-06-30 04:00:15 +08:00
|
|
|
of = self.query.select_for_update_of
|
2020-05-11 00:25:06 +08:00
|
|
|
no_key = self.query.select_for_no_key_update
|
|
|
|
# If it's a NOWAIT/SKIP LOCKED/OF/NO KEY query but the
|
|
|
|
# backend doesn't support it, raise NotSupportedError to
|
|
|
|
# prevent a possible deadlock.
|
2017-01-14 21:32:07 +08:00
|
|
|
if nowait and not self.connection.features.has_select_for_update_nowait:
|
2017-04-11 00:49:27 +08:00
|
|
|
raise NotSupportedError('NOWAIT is not supported on this database backend.')
|
2017-01-14 21:32:07 +08:00
|
|
|
elif skip_locked and not self.connection.features.has_select_for_update_skip_locked:
|
2017-04-11 00:49:27 +08:00
|
|
|
raise NotSupportedError('SKIP LOCKED is not supported on this database backend.')
|
2017-06-30 04:00:15 +08:00
|
|
|
elif of and not self.connection.features.has_select_for_update_of:
|
|
|
|
raise NotSupportedError('FOR UPDATE OF is not supported on this database backend.')
|
2020-05-11 00:25:06 +08:00
|
|
|
elif no_key and not self.connection.features.has_select_for_no_key_update:
|
|
|
|
raise NotSupportedError(
|
|
|
|
'FOR NO KEY UPDATE is not supported on this '
|
|
|
|
'database backend.'
|
|
|
|
)
|
2017-06-30 04:00:15 +08:00
|
|
|
for_update_part = self.connection.ops.for_update_sql(
|
|
|
|
nowait=nowait,
|
|
|
|
skip_locked=skip_locked,
|
|
|
|
of=self.get_select_for_update_of_arguments(),
|
2020-05-11 00:25:06 +08:00
|
|
|
no_key=no_key,
|
2017-06-30 04:00:15 +08:00
|
|
|
)
|
2017-01-14 21:32:07 +08:00
|
|
|
|
|
|
|
if for_update_part and self.connection.features.for_update_after_from:
|
|
|
|
result.append(for_update_part)
|
|
|
|
|
|
|
|
if where:
|
|
|
|
result.append('WHERE %s' % where)
|
|
|
|
params.extend(w_params)
|
|
|
|
|
|
|
|
grouping = []
|
|
|
|
for g_sql, g_params in group_by:
|
|
|
|
grouping.append(g_sql)
|
|
|
|
params.extend(g_params)
|
|
|
|
if grouping:
|
|
|
|
if distinct_fields:
|
|
|
|
raise NotImplementedError('annotate() + distinct(fields) is not implemented.')
|
2018-01-04 07:52:12 +08:00
|
|
|
order_by = order_by or self.connection.ops.force_no_ordering()
|
2017-01-14 21:32:07 +08:00
|
|
|
result.append('GROUP BY %s' % ', '.join(grouping))
|
2018-09-14 00:29:48 +08:00
|
|
|
if self._meta_ordering:
|
2019-09-08 01:28:19 +08:00
|
|
|
order_by = None
|
2017-01-14 21:32:07 +08:00
|
|
|
if having:
|
|
|
|
result.append('HAVING %s' % having)
|
|
|
|
params.extend(h_params)
|
2014-12-01 15:28:01 +08:00
|
|
|
|
2017-09-10 22:34:18 +08:00
|
|
|
if self.query.explain_query:
|
|
|
|
result.insert(0, self.connection.ops.explain_query_prefix(
|
|
|
|
self.query.explain_format,
|
|
|
|
**self.query.explain_options
|
|
|
|
))
|
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
if order_by:
|
|
|
|
ordering = []
|
2015-01-09 23:16:16 +08:00
|
|
|
for _, (o_sql, o_params, _) in order_by:
|
|
|
|
ordering.append(o_sql)
|
2014-12-01 15:28:01 +08:00
|
|
|
params.extend(o_params)
|
|
|
|
result.append('ORDER BY %s' % ', '.join(ordering))
|
|
|
|
|
2017-10-10 00:07:03 +08:00
|
|
|
if with_limit_offset:
|
|
|
|
result.append(self.connection.ops.limit_offset_sql(self.query.low_mark, self.query.high_mark))
|
2014-12-01 15:28:01 +08:00
|
|
|
|
2015-11-16 12:14:55 +08:00
|
|
|
if for_update_part and not self.connection.features.for_update_after_from:
|
|
|
|
result.append(for_update_part)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2017-04-27 12:49:17 +08:00
|
|
|
if self.query.subquery and extra_select:
|
|
|
|
# If the query is used as a subquery, the extra selects would
|
|
|
|
# result in more columns than the left-hand side expression is
|
|
|
|
# expecting. This can happen when a subquery uses a combination
|
|
|
|
# of order_by() and distinct(), forcing the ordering expressions
|
|
|
|
# to be selected as well. Wrap the query in another subquery
|
|
|
|
# to exclude extraneous selects.
|
|
|
|
sub_selects = []
|
|
|
|
sub_params = []
|
2018-02-08 22:59:25 +08:00
|
|
|
for index, (select, _, alias) in enumerate(self.select, start=1):
|
|
|
|
if not alias and with_col_aliases:
|
|
|
|
alias = 'col%d' % index
|
2017-04-27 12:49:17 +08:00
|
|
|
if alias:
|
|
|
|
sub_selects.append("%s.%s" % (
|
|
|
|
self.connection.ops.quote_name('subquery'),
|
|
|
|
self.connection.ops.quote_name(alias),
|
|
|
|
))
|
|
|
|
else:
|
|
|
|
select_clone = select.relabeled_clone({select.alias: 'subquery'})
|
|
|
|
subselect, subparams = select_clone.as_sql(self, self.connection)
|
|
|
|
sub_selects.append(subselect)
|
|
|
|
sub_params.extend(subparams)
|
2017-10-07 00:47:41 +08:00
|
|
|
return 'SELECT %s FROM (%s) subquery' % (
|
2017-04-27 12:49:17 +08:00
|
|
|
', '.join(sub_selects),
|
|
|
|
' '.join(result),
|
2018-02-08 22:59:25 +08:00
|
|
|
), tuple(sub_params + params)
|
2017-04-27 12:49:17 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
return ' '.join(result), tuple(params)
|
|
|
|
finally:
|
|
|
|
# Finally do cleanup - get rid of the joins we created above.
|
|
|
|
self.query.reset_refcounts(refcounts_before)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
def get_default_columns(self, start_alias=None, opts=None, from_parent=None):
|
2009-12-22 23:18:51 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Compute the default columns for selecting every field in the base
|
2009-12-22 23:18:51 +08:00
|
|
|
model. Will sometimes be called to pull in related models (e.g. via
|
|
|
|
select_related), in which case "opts" and "start_alias" will be given
|
|
|
|
to provide a starting point for the traversal.
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Return a list of strings, quoted appropriately for use in SQL
|
2009-12-22 23:18:51 +08:00
|
|
|
directly, as well as a set of aliases used in the select statement (if
|
2017-01-25 07:04:12 +08:00
|
|
|
'as_pairs' is True, return a list of (alias, col_name) pairs instead
|
2009-12-22 23:18:51 +08:00
|
|
|
of strings as the first component and None as the second component).
|
|
|
|
"""
|
|
|
|
result = []
|
|
|
|
if opts is None:
|
2013-05-14 03:40:39 +08:00
|
|
|
opts = self.query.get_meta()
|
2009-12-22 23:18:51 +08:00
|
|
|
only_load = self.deferred_to_columns()
|
2018-01-04 07:52:12 +08:00
|
|
|
start_alias = start_alias or self.query.get_initial_alias()
|
2013-02-21 17:12:08 +08:00
|
|
|
# The 'seen_models' is used to optimize checking the needed parent
|
|
|
|
# alias for a given field. This also includes None -> start_alias to
|
|
|
|
# be used by local fields.
|
|
|
|
seen_models = {None: start_alias}
|
|
|
|
|
2015-01-07 08:16:35 +08:00
|
|
|
for field in opts.concrete_fields:
|
|
|
|
model = field.model._meta.concrete_model
|
|
|
|
# A proxy model will have a different model and concrete_model. We
|
|
|
|
# will assign None if the field belongs to this model.
|
|
|
|
if model == opts.model:
|
|
|
|
model = None
|
2014-12-01 15:28:01 +08:00
|
|
|
if from_parent and model is not None and issubclass(
|
|
|
|
from_parent._meta.concrete_model, model._meta.concrete_model):
|
2012-11-10 02:21:46 +08:00
|
|
|
# Avoid loading data for already loaded parents.
|
2014-12-01 15:28:01 +08:00
|
|
|
# We end up here in the case select_related() resolution
|
|
|
|
# proceeds from parent model to child model. In that case the
|
|
|
|
# parent model data is already present in the SELECT clause,
|
|
|
|
# and we want to avoid reloading the same data again.
|
|
|
|
continue
|
|
|
|
if field.model in only_load and field.attname not in only_load[field.model]:
|
2010-03-20 23:02:59 +08:00
|
|
|
continue
|
2013-02-21 17:12:08 +08:00
|
|
|
alias = self.query.join_parent_model(opts, model, start_alias,
|
|
|
|
seen_models)
|
2014-12-01 15:28:01 +08:00
|
|
|
column = field.get_col(alias)
|
|
|
|
result.append(column)
|
|
|
|
return result
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2011-12-23 04:42:40 +08:00
|
|
|
def get_distinct(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return a quoted list of fields to use in DISTINCT ON part of the query.
|
2011-12-23 04:42:40 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
This method can alter the tables in the query, and thus it must be
|
|
|
|
called before get_from_clause().
|
2011-12-23 04:42:40 +08:00
|
|
|
"""
|
|
|
|
result = []
|
2017-06-18 23:53:40 +08:00
|
|
|
params = []
|
2013-05-14 03:40:39 +08:00
|
|
|
opts = self.query.get_meta()
|
2011-12-23 04:42:40 +08:00
|
|
|
|
|
|
|
for name in self.query.distinct_fields:
|
|
|
|
parts = name.split(LOOKUP_SEP)
|
2017-06-18 23:53:40 +08:00
|
|
|
_, targets, alias, joins, path, _, transform_function = self._setup_joins(parts, opts, None)
|
2013-08-20 15:32:18 +08:00
|
|
|
targets, alias, _ = self.query.trim_joins(targets, joins, path)
|
|
|
|
for target in targets:
|
2015-08-15 02:22:08 +08:00
|
|
|
if name in self.query.annotation_select:
|
|
|
|
result.append(name)
|
|
|
|
else:
|
2017-06-18 23:53:40 +08:00
|
|
|
r, p = self.compile(transform_function(target, alias))
|
|
|
|
result.append(r)
|
|
|
|
params.append(p)
|
|
|
|
return result, params
|
2011-12-23 04:42:40 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def find_ordering_name(self, name, opts, alias=None, default_order='ASC',
|
2013-08-20 15:32:18 +08:00
|
|
|
already_seen=None):
|
2009-12-22 23:18:51 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the table alias (the name might be ambiguous, the alias will
|
2009-12-22 23:18:51 +08:00
|
|
|
not be) and column name for ordering by the given 'name' parameter.
|
|
|
|
The 'name' is of the form 'field1__field2__...__fieldN'.
|
|
|
|
"""
|
|
|
|
name, order = get_order_dir(name, default_order)
|
2018-01-12 22:05:16 +08:00
|
|
|
descending = order == 'DESC'
|
2009-12-22 23:18:51 +08:00
|
|
|
pieces = name.split(LOOKUP_SEP)
|
2017-06-18 23:53:40 +08:00
|
|
|
field, targets, alias, joins, path, opts, transform_function = self._setup_joins(pieces, opts, alias)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
# If we get to this point and the field is a relation to another model,
|
2020-02-19 12:09:48 +08:00
|
|
|
# append the default ordering for that model unless it is the pk
|
|
|
|
# shortcut or the attribute name of the field that is specified.
|
2020-06-07 22:50:47 +08:00
|
|
|
if (
|
|
|
|
field.is_relation and
|
|
|
|
opts.ordering and
|
|
|
|
getattr(field, 'attname', None) != pieces[-1] and
|
|
|
|
name != 'pk'
|
|
|
|
):
|
2009-12-22 23:18:51 +08:00
|
|
|
# Firstly, avoid infinite loops.
|
2018-01-04 07:52:12 +08:00
|
|
|
already_seen = already_seen or set()
|
2015-04-19 14:06:17 +08:00
|
|
|
join_tuple = tuple(getattr(self.query.alias_map[j], 'join_cols', None) for j in joins)
|
2009-12-22 23:18:51 +08:00
|
|
|
if join_tuple in already_seen:
|
|
|
|
raise FieldError('Infinite loop caused by ordering.')
|
|
|
|
already_seen.add(join_tuple)
|
|
|
|
|
|
|
|
results = []
|
|
|
|
for item in opts.ordering:
|
2019-07-11 19:40:36 +08:00
|
|
|
if hasattr(item, 'resolve_expression') and not isinstance(item, OrderBy):
|
|
|
|
item = item.desc() if descending else item.asc()
|
2019-07-11 02:02:51 +08:00
|
|
|
if isinstance(item, OrderBy):
|
|
|
|
results.append((item, False))
|
|
|
|
continue
|
2009-12-22 23:18:51 +08:00
|
|
|
results.extend(self.find_ordering_name(item, opts, alias,
|
2013-08-20 15:32:18 +08:00
|
|
|
order, already_seen))
|
2009-12-22 23:18:51 +08:00
|
|
|
return results
|
2013-08-20 15:32:18 +08:00
|
|
|
targets, alias, _ = self.query.trim_joins(targets, joins, path)
|
2017-06-18 23:53:40 +08:00
|
|
|
return [(OrderBy(transform_function(t, alias), descending=descending), False) for t in targets]
|
2011-12-23 04:42:40 +08:00
|
|
|
|
|
|
|
def _setup_joins(self, pieces, opts, alias):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Helper method for get_order_by() and get_distinct().
|
2011-12-23 04:42:40 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
get_ordering() and get_distinct() must produce same target columns on
|
|
|
|
same input, as the prefixes of get_ordering() and get_distinct() must
|
|
|
|
match. Executing SQL where this is not true is an error.
|
2011-12-23 04:42:40 +08:00
|
|
|
"""
|
2018-01-04 07:52:12 +08:00
|
|
|
alias = alias or self.query.get_initial_alias()
|
2017-06-18 23:53:40 +08:00
|
|
|
field, targets, opts, joins, path, transform_function = self.query.setup_joins(pieces, opts, alias)
|
2011-12-23 04:42:40 +08:00
|
|
|
alias = joins[-1]
|
2017-06-18 23:53:40 +08:00
|
|
|
return field, targets, alias, joins, path, opts, transform_function
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
def get_from_clause(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return a list of strings that are joined together to go after the
|
2009-12-22 23:18:51 +08:00
|
|
|
"FROM" part of the query, as well as a list any extra parameters that
|
2017-01-25 07:04:12 +08:00
|
|
|
need to be included. Subclasses, can override this to create a
|
2009-12-22 23:18:51 +08:00
|
|
|
from-clause via a "select".
|
|
|
|
|
|
|
|
This should only be called after any SQL construction methods that
|
2017-01-25 07:04:12 +08:00
|
|
|
might change the tables that are needed. This means the select columns,
|
|
|
|
ordering, and distinct must be done first.
|
2009-12-22 23:18:51 +08:00
|
|
|
"""
|
|
|
|
result = []
|
2014-11-17 16:26:10 +08:00
|
|
|
params = []
|
2017-09-22 23:53:17 +08:00
|
|
|
for alias in tuple(self.query.alias_map):
|
2009-12-22 23:18:51 +08:00
|
|
|
if not self.query.alias_refcount[alias]:
|
|
|
|
continue
|
|
|
|
try:
|
2014-11-17 16:26:10 +08:00
|
|
|
from_clause = self.query.alias_map[alias]
|
2009-12-22 23:18:51 +08:00
|
|
|
except KeyError:
|
|
|
|
# Extra tables can end up in self.tables, but not in the
|
|
|
|
# alias_map if they aren't in a join. That's OK. We skip them.
|
|
|
|
continue
|
2014-11-17 16:26:10 +08:00
|
|
|
clause_sql, clause_params = self.compile(from_clause)
|
|
|
|
result.append(clause_sql)
|
|
|
|
params.extend(clause_params)
|
2009-12-22 23:18:51 +08:00
|
|
|
for t in self.query.extra_tables:
|
2014-06-14 18:50:18 +08:00
|
|
|
alias, _ = self.query.table_alias(t)
|
2009-12-22 23:18:51 +08:00
|
|
|
# Only add the alias if it's not already present (the table_alias()
|
2014-11-17 16:26:10 +08:00
|
|
|
# call increments the refcount, so an alias refcount of one means
|
|
|
|
# this is the only reference).
|
2009-12-22 23:18:51 +08:00
|
|
|
if alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1:
|
2014-11-17 16:26:10 +08:00
|
|
|
result.append(', %s' % self.quote_name_unless_alias(alias))
|
|
|
|
return result, params
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
def get_related_selections(self, select, opts=None, root_alias=None, cur_depth=1,
|
|
|
|
requested=None, restricted=None):
|
2009-12-22 23:18:51 +08:00
|
|
|
"""
|
|
|
|
Fill in the information needed for a select_related query. The current
|
|
|
|
depth is measured as the number of connections away from the root model
|
|
|
|
(for example, cur_depth=1 means we are looking at models with direct
|
|
|
|
connections to the root model).
|
|
|
|
"""
|
2014-12-05 04:47:48 +08:00
|
|
|
def _get_field_choices():
|
2015-01-07 08:16:35 +08:00
|
|
|
direct_choices = (f.name for f in opts.fields if f.is_relation)
|
2014-12-05 04:47:48 +08:00
|
|
|
reverse_choices = (
|
|
|
|
f.field.related_query_name()
|
2015-01-07 08:16:35 +08:00
|
|
|
for f in opts.related_objects if f.field.unique
|
2014-12-05 04:47:48 +08:00
|
|
|
)
|
2017-09-22 23:53:17 +08:00
|
|
|
return chain(direct_choices, reverse_choices, self.query._filtered_relations)
|
2014-12-05 04:47:48 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
related_klass_infos = []
|
2017-09-15 20:37:46 +08:00
|
|
|
if not restricted and cur_depth > self.query.max_depth:
|
2009-12-22 23:18:51 +08:00
|
|
|
# We've recursed far enough; bail out.
|
2014-12-01 15:28:01 +08:00
|
|
|
return related_klass_infos
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
if not opts:
|
|
|
|
opts = self.query.get_meta()
|
|
|
|
root_alias = self.query.get_initial_alias()
|
2012-06-26 23:08:42 +08:00
|
|
|
only_load = self.query.get_loaded_field_names()
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
# Setup for the case when only particular related fields should be
|
|
|
|
# included in the related selection.
|
2014-12-05 04:47:48 +08:00
|
|
|
fields_found = set()
|
2010-01-27 21:30:29 +08:00
|
|
|
if requested is None:
|
2018-01-12 22:05:16 +08:00
|
|
|
restricted = isinstance(self.query.select_related, dict)
|
|
|
|
if restricted:
|
2009-12-22 23:18:51 +08:00
|
|
|
requested = self.query.select_related
|
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
def get_related_klass_infos(klass_info, related_klass_infos):
|
|
|
|
klass_info['related_klass_infos'] = related_klass_infos
|
|
|
|
|
2015-01-07 08:16:35 +08:00
|
|
|
for f in opts.fields:
|
|
|
|
field_model = f.model._meta.concrete_model
|
2014-12-05 04:47:48 +08:00
|
|
|
fields_found.add(f.name)
|
|
|
|
|
|
|
|
if restricted:
|
|
|
|
next = requested.get(f.name, {})
|
2015-01-07 08:16:35 +08:00
|
|
|
if not f.is_relation:
|
2014-12-05 04:47:48 +08:00
|
|
|
# If a non-related field is used like a relation,
|
|
|
|
# or if a single non-relational field is given.
|
2015-10-10 09:03:04 +08:00
|
|
|
if next or f.name in requested:
|
2014-12-05 04:47:48 +08:00
|
|
|
raise FieldError(
|
|
|
|
"Non-relational field given in select_related: '%s'. "
|
|
|
|
"Choices are: %s" % (
|
|
|
|
f.name,
|
|
|
|
", ".join(_get_field_choices()) or '(none)',
|
|
|
|
)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
next = False
|
|
|
|
|
2012-06-26 23:08:42 +08:00
|
|
|
if not select_related_descend(f, restricted, requested,
|
2012-09-16 02:11:14 +08:00
|
|
|
only_load.get(field_model)):
|
2009-12-22 23:18:51 +08:00
|
|
|
continue
|
2014-12-01 15:28:01 +08:00
|
|
|
klass_info = {
|
2015-02-26 22:19:17 +08:00
|
|
|
'model': f.remote_field.model,
|
2014-12-01 15:28:01 +08:00
|
|
|
'field': f,
|
2017-10-17 11:28:00 +08:00
|
|
|
'reverse': False,
|
2017-09-22 23:53:17 +08:00
|
|
|
'local_setter': f.set_cached_value,
|
|
|
|
'remote_setter': f.remote_field.set_cached_value if f.unique else lambda x, y: None,
|
2014-12-01 15:28:01 +08:00
|
|
|
'from_parent': False,
|
|
|
|
}
|
|
|
|
related_klass_infos.append(klass_info)
|
|
|
|
select_fields = []
|
2017-06-18 23:53:40 +08:00
|
|
|
_, _, _, joins, _, _ = self.query.setup_joins(
|
2013-11-07 03:31:19 +08:00
|
|
|
[f.name], opts, root_alias)
|
2013-06-16 01:31:46 +08:00
|
|
|
alias = joins[-1]
|
2015-02-26 22:19:17 +08:00
|
|
|
columns = self.get_default_columns(start_alias=alias, opts=f.remote_field.model._meta)
|
2014-12-01 15:28:01 +08:00
|
|
|
for col in columns:
|
|
|
|
select_fields.append(len(select))
|
|
|
|
select.append((col, None))
|
|
|
|
klass_info['select_fields'] = select_fields
|
|
|
|
next_klass_infos = self.get_related_selections(
|
2015-02-26 22:19:17 +08:00
|
|
|
select, f.remote_field.model._meta, alias, cur_depth + 1, next, restricted)
|
2014-12-01 15:28:01 +08:00
|
|
|
get_related_klass_infos(klass_info, next_klass_infos)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2010-01-27 21:30:29 +08:00
|
|
|
if restricted:
|
|
|
|
related_fields = [
|
2015-01-07 08:16:35 +08:00
|
|
|
(o.field, o.related_model)
|
|
|
|
for o in opts.related_objects
|
|
|
|
if o.field.unique and not o.many_to_many
|
2010-01-27 21:30:29 +08:00
|
|
|
]
|
|
|
|
for f, model in related_fields:
|
2012-06-26 23:08:42 +08:00
|
|
|
if not select_related_descend(f, restricted, requested,
|
|
|
|
only_load.get(model), reverse=True):
|
2010-01-27 21:30:29 +08:00
|
|
|
continue
|
|
|
|
|
2014-12-05 04:47:48 +08:00
|
|
|
related_field_name = f.related_query_name()
|
|
|
|
fields_found.add(related_field_name)
|
|
|
|
|
2017-08-01 22:37:02 +08:00
|
|
|
join_info = self.query.setup_joins([related_field_name], opts, root_alias)
|
|
|
|
alias = join_info.joins[-1]
|
2016-12-13 22:06:54 +08:00
|
|
|
from_parent = issubclass(model, opts.model) and model is not opts.model
|
2014-12-01 15:28:01 +08:00
|
|
|
klass_info = {
|
|
|
|
'model': model,
|
|
|
|
'field': f,
|
2017-10-17 11:28:00 +08:00
|
|
|
'reverse': True,
|
2017-09-22 23:53:17 +08:00
|
|
|
'local_setter': f.remote_field.set_cached_value,
|
|
|
|
'remote_setter': f.set_cached_value,
|
2014-12-01 15:28:01 +08:00
|
|
|
'from_parent': from_parent,
|
|
|
|
}
|
|
|
|
related_klass_infos.append(klass_info)
|
|
|
|
select_fields = []
|
|
|
|
columns = self.get_default_columns(
|
|
|
|
start_alias=alias, opts=model._meta, from_parent=opts.model)
|
|
|
|
for col in columns:
|
|
|
|
select_fields.append(len(select))
|
|
|
|
select.append((col, None))
|
|
|
|
klass_info['select_fields'] = select_fields
|
2010-01-27 21:30:29 +08:00
|
|
|
next = requested.get(f.related_query_name(), {})
|
2014-12-01 15:28:01 +08:00
|
|
|
next_klass_infos = self.get_related_selections(
|
|
|
|
select, model._meta, alias, cur_depth + 1,
|
|
|
|
next, restricted)
|
|
|
|
get_related_klass_infos(klass_info, next_klass_infos)
|
2019-10-11 13:56:02 +08:00
|
|
|
|
|
|
|
def local_setter(obj, from_obj):
|
|
|
|
# Set a reverse fk object when relation is non-empty.
|
|
|
|
if from_obj:
|
|
|
|
f.remote_field.set_cached_value(from_obj, obj)
|
|
|
|
|
2019-10-11 03:13:21 +08:00
|
|
|
def remote_setter(name, obj, from_obj):
|
|
|
|
setattr(from_obj, name, obj)
|
|
|
|
|
2017-09-22 23:53:17 +08:00
|
|
|
for name in list(requested):
|
|
|
|
# Filtered relations work only on the topmost level.
|
|
|
|
if cur_depth > 1:
|
|
|
|
break
|
|
|
|
if name in self.query._filtered_relations:
|
|
|
|
fields_found.add(name)
|
2017-06-18 23:53:40 +08:00
|
|
|
f, _, join_opts, joins, _, _ = self.query.setup_joins([name], opts, root_alias)
|
2017-09-22 23:53:17 +08:00
|
|
|
model = join_opts.model
|
|
|
|
alias = joins[-1]
|
|
|
|
from_parent = issubclass(model, opts.model) and model is not opts.model
|
|
|
|
klass_info = {
|
|
|
|
'model': model,
|
|
|
|
'field': f,
|
2017-10-17 11:28:00 +08:00
|
|
|
'reverse': True,
|
2017-09-22 23:53:17 +08:00
|
|
|
'local_setter': local_setter,
|
2019-10-11 03:13:21 +08:00
|
|
|
'remote_setter': partial(remote_setter, name),
|
2017-09-22 23:53:17 +08:00
|
|
|
'from_parent': from_parent,
|
|
|
|
}
|
|
|
|
related_klass_infos.append(klass_info)
|
|
|
|
select_fields = []
|
|
|
|
columns = self.get_default_columns(
|
|
|
|
start_alias=alias, opts=model._meta,
|
|
|
|
from_parent=opts.model,
|
|
|
|
)
|
|
|
|
for col in columns:
|
|
|
|
select_fields.append(len(select))
|
|
|
|
select.append((col, None))
|
|
|
|
klass_info['select_fields'] = select_fields
|
|
|
|
next_requested = requested.get(name, {})
|
|
|
|
next_klass_infos = self.get_related_selections(
|
|
|
|
select, opts=model._meta, root_alias=alias,
|
|
|
|
cur_depth=cur_depth + 1, requested=next_requested,
|
|
|
|
restricted=restricted,
|
|
|
|
)
|
|
|
|
get_related_klass_infos(klass_info, next_klass_infos)
|
|
|
|
fields_not_found = set(requested).difference(fields_found)
|
2014-12-05 04:47:48 +08:00
|
|
|
if fields_not_found:
|
|
|
|
invalid_fields = ("'%s'" % s for s in fields_not_found)
|
|
|
|
raise FieldError(
|
|
|
|
'Invalid field name(s) given in select_related: %s. '
|
|
|
|
'Choices are: %s' % (
|
|
|
|
', '.join(invalid_fields),
|
|
|
|
', '.join(_get_field_choices()) or '(none)',
|
|
|
|
)
|
|
|
|
)
|
2014-12-01 15:28:01 +08:00
|
|
|
return related_klass_infos
|
2014-12-05 04:47:48 +08:00
|
|
|
|
2017-06-30 04:00:15 +08:00
|
|
|
def get_select_for_update_of_arguments(self):
|
|
|
|
"""
|
|
|
|
Return a quoted list of arguments for the SELECT FOR UPDATE OF part of
|
|
|
|
the query.
|
|
|
|
"""
|
2019-12-02 14:57:19 +08:00
|
|
|
def _get_parent_klass_info(klass_info):
|
2020-02-08 12:52:09 +08:00
|
|
|
for parent_model, parent_link in klass_info['model']._meta.parents.items():
|
|
|
|
parent_list = parent_model._meta.get_parent_list()
|
|
|
|
yield {
|
2019-12-02 14:57:19 +08:00
|
|
|
'model': parent_model,
|
|
|
|
'field': parent_link,
|
|
|
|
'reverse': False,
|
|
|
|
'select_fields': [
|
|
|
|
select_index
|
|
|
|
for select_index in klass_info['select_fields']
|
2020-02-08 12:52:09 +08:00
|
|
|
# Selected columns from a model or its parents.
|
|
|
|
if (
|
|
|
|
self.select[select_index][0].target.model == parent_model or
|
|
|
|
self.select[select_index][0].target.model in parent_list
|
|
|
|
)
|
2019-12-02 14:57:19 +08:00
|
|
|
],
|
|
|
|
}
|
2020-02-08 12:52:09 +08:00
|
|
|
|
|
|
|
def _get_first_selected_col_from_model(klass_info):
|
|
|
|
"""
|
|
|
|
Find the first selected column from a model. If it doesn't exist,
|
|
|
|
don't lock a model.
|
|
|
|
|
|
|
|
select_fields is filled recursively, so it also contains fields
|
|
|
|
from the parent models.
|
|
|
|
"""
|
|
|
|
for select_index in klass_info['select_fields']:
|
|
|
|
if self.select[select_index][0].target.model == klass_info['model']:
|
|
|
|
return self.select[select_index][0]
|
2019-12-02 14:57:19 +08:00
|
|
|
|
2017-06-30 04:00:15 +08:00
|
|
|
def _get_field_choices():
|
|
|
|
"""Yield all allowed field paths in breadth-first search order."""
|
|
|
|
queue = collections.deque([(None, self.klass_info)])
|
|
|
|
while queue:
|
|
|
|
parent_path, klass_info = queue.popleft()
|
|
|
|
if parent_path is None:
|
|
|
|
path = []
|
|
|
|
yield 'self'
|
|
|
|
else:
|
2017-10-17 11:28:00 +08:00
|
|
|
field = klass_info['field']
|
|
|
|
if klass_info['reverse']:
|
|
|
|
field = field.remote_field
|
|
|
|
path = parent_path + [field.name]
|
2017-06-30 04:00:15 +08:00
|
|
|
yield LOOKUP_SEP.join(path)
|
2019-12-02 14:57:19 +08:00
|
|
|
queue.extend(
|
|
|
|
(path, klass_info)
|
|
|
|
for klass_info in _get_parent_klass_info(klass_info)
|
|
|
|
)
|
2017-06-30 04:00:15 +08:00
|
|
|
queue.extend(
|
|
|
|
(path, klass_info)
|
|
|
|
for klass_info in klass_info.get('related_klass_infos', [])
|
|
|
|
)
|
|
|
|
result = []
|
|
|
|
invalid_names = []
|
|
|
|
for name in self.query.select_for_update_of:
|
|
|
|
klass_info = self.klass_info
|
2019-12-02 14:57:19 +08:00
|
|
|
if name == 'self':
|
2020-02-08 12:52:09 +08:00
|
|
|
col = _get_first_selected_col_from_model(klass_info)
|
2017-06-30 04:00:15 +08:00
|
|
|
else:
|
2019-12-02 14:57:19 +08:00
|
|
|
for part in name.split(LOOKUP_SEP):
|
|
|
|
klass_infos = (
|
|
|
|
*klass_info.get('related_klass_infos', []),
|
|
|
|
*_get_parent_klass_info(klass_info),
|
|
|
|
)
|
|
|
|
for related_klass_info in klass_infos:
|
|
|
|
field = related_klass_info['field']
|
|
|
|
if related_klass_info['reverse']:
|
|
|
|
field = field.remote_field
|
|
|
|
if field.name == part:
|
|
|
|
klass_info = related_klass_info
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
klass_info = None
|
|
|
|
break
|
|
|
|
if klass_info is None:
|
|
|
|
invalid_names.append(name)
|
|
|
|
continue
|
2020-02-08 12:52:09 +08:00
|
|
|
col = _get_first_selected_col_from_model(klass_info)
|
2019-12-02 14:57:19 +08:00
|
|
|
if col is not None:
|
|
|
|
if self.connection.features.select_for_update_of_column:
|
|
|
|
result.append(self.compile(col)[0])
|
|
|
|
else:
|
|
|
|
result.append(self.quote_name_unless_alias(col.alias))
|
2017-06-30 04:00:15 +08:00
|
|
|
if invalid_names:
|
|
|
|
raise FieldError(
|
|
|
|
'Invalid field name(s) given in select_for_update(of=(...)): %s. '
|
|
|
|
'Only relational fields followed in the query are allowed. '
|
|
|
|
'Choices are: %s.' % (
|
|
|
|
', '.join(invalid_names),
|
|
|
|
', '.join(_get_field_choices()),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
return result
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def deferred_to_columns(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Convert the self.deferred_loading data structure to mapping of table
|
|
|
|
names to sets of column names which are to be loaded. Return the
|
2009-12-22 23:18:51 +08:00
|
|
|
dictionary.
|
|
|
|
"""
|
|
|
|
columns = {}
|
2014-12-01 15:28:01 +08:00
|
|
|
self.query.deferred_to_data(columns, self.query.get_loaded_field_names_cb)
|
2009-12-22 23:18:51 +08:00
|
|
|
return columns
|
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
def get_converters(self, expressions):
|
2014-08-12 20:08:40 +08:00
|
|
|
converters = {}
|
2014-12-01 15:28:01 +08:00
|
|
|
for i, expression in enumerate(expressions):
|
|
|
|
if expression:
|
|
|
|
backend_converters = self.connection.ops.get_db_converters(expression)
|
|
|
|
field_converters = expression.get_db_converters(self.connection)
|
2014-08-12 20:08:40 +08:00
|
|
|
if backend_converters or field_converters:
|
2018-12-28 08:58:22 +08:00
|
|
|
converters[i] = (backend_converters + field_converters, expression)
|
2014-08-12 20:08:40 +08:00
|
|
|
return converters
|
|
|
|
|
2017-08-08 05:06:15 +08:00
|
|
|
def apply_converters(self, rows, converters):
|
|
|
|
connection = self.connection
|
|
|
|
converters = list(converters.items())
|
2017-08-24 04:26:24 +08:00
|
|
|
for row in map(list, rows):
|
2017-08-08 05:06:15 +08:00
|
|
|
for pos, (convs, expression) in converters:
|
|
|
|
value = row[pos]
|
|
|
|
for converter in convs:
|
|
|
|
value = converter(value, expression, connection)
|
|
|
|
row[pos] = value
|
2017-08-24 04:26:24 +08:00
|
|
|
yield row
|
2014-08-12 20:08:40 +08:00
|
|
|
|
2017-11-19 23:13:10 +08:00
|
|
|
def results_iter(self, results=None, tuple_expected=False, chunked_fetch=False,
|
|
|
|
chunk_size=GET_ITERATOR_CHUNK_SIZE):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Return an iterator over the results from executing this query."""
|
2014-12-01 15:28:01 +08:00
|
|
|
if results is None:
|
2017-11-19 23:13:10 +08:00
|
|
|
results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
|
2014-12-01 15:28:01 +08:00
|
|
|
fields = [s[0] for s in self.select[0:self.col_count]]
|
|
|
|
converters = self.get_converters(fields)
|
2017-08-08 05:06:15 +08:00
|
|
|
rows = chain.from_iterable(results)
|
|
|
|
if converters:
|
|
|
|
rows = self.apply_converters(rows, converters)
|
2017-08-24 04:26:24 +08:00
|
|
|
if tuple_expected:
|
|
|
|
rows = map(tuple, rows)
|
2017-08-08 05:06:15 +08:00
|
|
|
return rows
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2013-07-08 23:05:08 +08:00
|
|
|
def has_results(self):
|
|
|
|
"""
|
|
|
|
Backends (e.g. NoSQL) can override this in order to use optimized
|
|
|
|
versions of "query has any results."
|
|
|
|
"""
|
|
|
|
# This is always executed on a query clone, so we can modify self.query
|
|
|
|
self.query.add_extra({'a': 1}, None, None, None, None, None)
|
|
|
|
self.query.set_extra_mask(['a'])
|
|
|
|
return bool(self.execute_sql(SINGLE))
|
|
|
|
|
2017-06-02 04:56:51 +08:00
|
|
|
def execute_sql(self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE):
|
2009-12-22 23:18:51 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Run the query against the database and return the result(s). The
|
2009-12-22 23:18:51 +08:00
|
|
|
return value is a single data item if result_type is SINGLE, or an
|
|
|
|
iterator over the results if the result_type is MULTI.
|
|
|
|
|
|
|
|
result_type is either MULTI (use fetchmany() to retrieve all rows),
|
|
|
|
SINGLE (only retrieve a single row), or None. In this last case, the
|
|
|
|
cursor is returned if any query is executed, since it's used by
|
|
|
|
subclasses such as InsertQuery). It's possible, however, that no query
|
|
|
|
is needed, as the filters describe an empty set. In that case, None is
|
|
|
|
returned, to avoid any unnecessary database interaction.
|
|
|
|
"""
|
2018-01-04 07:52:12 +08:00
|
|
|
result_type = result_type or NO_RESULTS
|
2009-12-22 23:18:51 +08:00
|
|
|
try:
|
|
|
|
sql, params = self.as_sql()
|
|
|
|
if not sql:
|
|
|
|
raise EmptyResultSet
|
|
|
|
except EmptyResultSet:
|
|
|
|
if result_type == MULTI:
|
2012-09-07 22:58:17 +08:00
|
|
|
return iter([])
|
2009-12-22 23:18:51 +08:00
|
|
|
else:
|
|
|
|
return
|
2016-06-04 06:31:21 +08:00
|
|
|
if chunked_fetch:
|
|
|
|
cursor = self.connection.chunked_cursor()
|
|
|
|
else:
|
|
|
|
cursor = self.connection.cursor()
|
2014-01-09 12:31:34 +08:00
|
|
|
try:
|
|
|
|
cursor.execute(sql, params)
|
2014-01-09 23:05:15 +08:00
|
|
|
except Exception:
|
2017-01-22 09:02:00 +08:00
|
|
|
# Might fail for server-side cursors (e.g. connection closed)
|
|
|
|
cursor.close()
|
2014-01-09 12:31:34 +08:00
|
|
|
raise
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2014-01-09 12:31:34 +08:00
|
|
|
if result_type == CURSOR:
|
2017-10-02 23:14:08 +08:00
|
|
|
# Give the caller the cursor to process and close.
|
2009-12-22 23:18:51 +08:00
|
|
|
return cursor
|
|
|
|
if result_type == SINGLE:
|
2014-01-09 12:31:34 +08:00
|
|
|
try:
|
2014-12-01 15:28:01 +08:00
|
|
|
val = cursor.fetchone()
|
|
|
|
if val:
|
|
|
|
return val[0:self.col_count]
|
|
|
|
return val
|
2014-01-09 12:31:34 +08:00
|
|
|
finally:
|
|
|
|
# done with the cursor
|
|
|
|
cursor.close()
|
|
|
|
if result_type == NO_RESULTS:
|
|
|
|
cursor.close()
|
|
|
|
return
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
result = cursor_iter(
|
|
|
|
cursor, self.connection.features.empty_fetchmany_value,
|
2017-08-09 02:07:03 +08:00
|
|
|
self.col_count if self.has_extra_select else None,
|
2017-06-02 04:56:51 +08:00
|
|
|
chunk_size,
|
2014-12-01 15:28:01 +08:00
|
|
|
)
|
2018-07-21 02:54:14 +08:00
|
|
|
if not chunked_fetch or not self.connection.features.can_use_chunked_reads:
|
2014-01-09 12:31:34 +08:00
|
|
|
try:
|
|
|
|
# If we are using non-chunked reads, we return the same data
|
|
|
|
# structure as normally, but ensure it is all read into memory
|
2018-07-21 02:54:14 +08:00
|
|
|
# before going any further. Use chunked_fetch if requested,
|
|
|
|
# unless the database doesn't support it.
|
2014-01-09 12:31:34 +08:00
|
|
|
return list(result)
|
|
|
|
finally:
|
|
|
|
# done with the cursor
|
|
|
|
cursor.close()
|
2009-12-22 23:18:51 +08:00
|
|
|
return result
|
|
|
|
|
2014-11-18 09:05:14 +08:00
|
|
|
def as_subquery_condition(self, alias, columns, compiler):
|
|
|
|
qn = compiler.quote_name_unless_alias
|
2013-03-25 00:40:40 +08:00
|
|
|
qn2 = self.connection.ops.quote_name
|
|
|
|
|
|
|
|
for index, select_col in enumerate(self.query.select):
|
2014-12-01 15:28:01 +08:00
|
|
|
lhs_sql, lhs_params = self.compile(select_col)
|
2013-03-25 00:40:40 +08:00
|
|
|
rhs = '%s.%s' % (qn(alias), qn2(columns[index]))
|
|
|
|
self.query.where.add(
|
2019-11-18 17:45:24 +08:00
|
|
|
RawSQL('%s = %s' % (lhs_sql, rhs), lhs_params), 'AND')
|
2013-03-25 00:40:40 +08:00
|
|
|
|
|
|
|
sql, params = self.as_sql()
|
|
|
|
return 'EXISTS (%s)' % sql, params
|
|
|
|
|
2017-09-10 22:34:18 +08:00
|
|
|
def explain_query(self):
|
|
|
|
result = list(self.execute_sql())
|
|
|
|
# Some backends return 1 item tuples with strings, and others return
|
|
|
|
# tuples with integers and strings. Flatten them out into strings.
|
|
|
|
for row in result[0]:
|
|
|
|
if not isinstance(row, str):
|
|
|
|
yield ' '.join(str(c) for c in row)
|
|
|
|
else:
|
|
|
|
yield row
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
class SQLInsertCompiler(SQLCompiler):
|
2019-07-24 14:42:41 +08:00
|
|
|
returning_fields = None
|
2019-09-15 05:50:14 +08:00
|
|
|
returning_params = tuple()
|
2013-04-09 03:28:15 +08:00
|
|
|
|
2015-08-03 22:34:19 +08:00
|
|
|
def field_as_sql(self, field, val):
|
|
|
|
"""
|
|
|
|
Take a field and a value intended to be saved on that field, and
|
2017-01-25 07:04:12 +08:00
|
|
|
return placeholder SQL and accompanying params. Check for raw values,
|
|
|
|
expressions, and fields with get_placeholder() defined in that order.
|
2015-08-03 22:34:19 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
When field is None, consider the value raw and use it as the
|
2015-08-03 22:34:19 +08:00
|
|
|
placeholder, with no corresponding parameters returned.
|
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
if field is None:
|
|
|
|
# A field value of None means the value is raw.
|
2015-08-03 22:34:19 +08:00
|
|
|
sql, params = val, []
|
|
|
|
elif hasattr(val, 'as_sql'):
|
|
|
|
# This is an expression, let's compile it.
|
|
|
|
sql, params = self.compile(val)
|
2009-12-22 23:18:51 +08:00
|
|
|
elif hasattr(field, 'get_placeholder'):
|
|
|
|
# Some fields (e.g. geo fields) need special munging before
|
|
|
|
# they can be inserted.
|
2015-08-03 22:34:19 +08:00
|
|
|
sql, params = field.get_placeholder(val, self, self.connection), [val]
|
2009-12-22 23:18:51 +08:00
|
|
|
else:
|
|
|
|
# Return the common case for the placeholder
|
2015-08-03 22:34:19 +08:00
|
|
|
sql, params = '%s', [val]
|
|
|
|
|
|
|
|
# The following hook is only used by Oracle Spatial, which sometimes
|
|
|
|
# needs to yield 'NULL' and [] as its placeholder and params instead
|
|
|
|
# of '%s' and [None]. The 'NULL' placeholder is produced earlier by
|
|
|
|
# OracleOperations.get_geom_placeholder(). The following line removes
|
|
|
|
# the corresponding None parameter. See ticket #10888.
|
|
|
|
params = self.connection.ops.modify_insert_params(sql, params)
|
|
|
|
|
|
|
|
return sql, params
|
|
|
|
|
|
|
|
def prepare_value(self, field, value):
|
|
|
|
"""
|
|
|
|
Prepare a value to be used in a query by resolving it if it is an
|
|
|
|
expression and otherwise calling the field's get_db_prep_save().
|
|
|
|
"""
|
|
|
|
if hasattr(value, 'resolve_expression'):
|
|
|
|
value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
|
|
|
|
# Don't allow values containing Col expressions. They refer to
|
|
|
|
# existing columns on a row, but in the case of insert the row
|
|
|
|
# doesn't exist yet.
|
|
|
|
if value.contains_column_references:
|
|
|
|
raise ValueError(
|
|
|
|
'Failed to insert expression "%s" on %s. F() expressions '
|
|
|
|
'can only be used to update, not to insert.' % (value, field)
|
|
|
|
)
|
|
|
|
if value.contains_aggregate:
|
2019-02-15 07:58:08 +08:00
|
|
|
raise FieldError(
|
|
|
|
'Aggregate functions are not allowed in this query '
|
|
|
|
'(%s=%r).' % (field.name, value)
|
|
|
|
)
|
2017-09-18 21:42:29 +08:00
|
|
|
if value.contains_over_clause:
|
2019-02-15 07:58:08 +08:00
|
|
|
raise FieldError(
|
|
|
|
'Window expressions are not allowed in this query (%s=%r).'
|
|
|
|
% (field.name, value)
|
|
|
|
)
|
2015-08-03 22:34:19 +08:00
|
|
|
else:
|
|
|
|
value = field.get_db_prep_save(value, connection=self.connection)
|
|
|
|
return value
|
|
|
|
|
|
|
|
def pre_save_val(self, field, obj):
|
|
|
|
"""
|
|
|
|
Get the given field's value off the given obj. pre_save() is used for
|
|
|
|
things like auto_now on DateTimeField. Skip it if this is a raw query.
|
|
|
|
"""
|
|
|
|
if self.query.raw:
|
|
|
|
return getattr(obj, field.attname)
|
|
|
|
return field.pre_save(obj, add=True)
|
|
|
|
|
|
|
|
def assemble_as_sql(self, fields, value_rows):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Take a sequence of N fields and a sequence of M rows of values, and
|
|
|
|
generate placeholder SQL and parameters for each field and value.
|
|
|
|
Return a pair containing:
|
2015-08-03 22:34:19 +08:00
|
|
|
* a sequence of M rows of N SQL placeholder strings, and
|
|
|
|
* a sequence of M rows of corresponding parameter values.
|
|
|
|
|
|
|
|
Each placeholder string may contain any number of '%s' interpolation
|
|
|
|
strings, and each parameter row will contain exactly as many params
|
|
|
|
as the total number of '%s's in the corresponding placeholder row.
|
|
|
|
"""
|
|
|
|
if not value_rows:
|
|
|
|
return [], []
|
|
|
|
|
|
|
|
# list of (sql, [params]) tuples for each object to be saved
|
|
|
|
# Shape: [n_objs][n_fields][2]
|
|
|
|
rows_of_fields_as_sql = (
|
|
|
|
(self.field_as_sql(field, v) for field, v in zip(fields, row))
|
|
|
|
for row in value_rows
|
|
|
|
)
|
|
|
|
|
|
|
|
# tuple like ([sqls], [[params]s]) for each object to be saved
|
|
|
|
# Shape: [n_objs][2][n_fields]
|
|
|
|
sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql)
|
|
|
|
|
|
|
|
# Extract separate lists for placeholders and params.
|
|
|
|
# Each of these has shape [n_objs][n_fields]
|
|
|
|
placeholder_rows, param_rows = zip(*sql_and_param_pair_rows)
|
|
|
|
|
|
|
|
# Params for each field are still lists, and need to be flattened.
|
|
|
|
param_rows = [[p for ps in row for p in ps] for row in param_rows]
|
|
|
|
|
|
|
|
return placeholder_rows, param_rows
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
def as_sql(self):
|
|
|
|
# We don't need quote_name_unless_alias() here, since these are all
|
|
|
|
# going to be column names (so we can avoid the extra overhead).
|
|
|
|
qn = self.connection.ops.quote_name
|
2013-05-14 03:40:39 +08:00
|
|
|
opts = self.query.get_meta()
|
2017-10-03 07:35:38 +08:00
|
|
|
insert_statement = self.connection.ops.insert_statement(ignore_conflicts=self.query.ignore_conflicts)
|
|
|
|
result = ['%s %s' % (insert_statement, qn(opts.db_table))]
|
2017-12-08 06:13:07 +08:00
|
|
|
fields = self.query.fields or [opts.pk]
|
2013-08-30 07:20:00 +08:00
|
|
|
result.append('(%s)' % ', '.join(qn(f.column) for f in fields))
|
2011-09-10 03:22:28 +08:00
|
|
|
|
2017-12-08 06:13:07 +08:00
|
|
|
if self.query.fields:
|
2015-08-03 22:34:19 +08:00
|
|
|
value_rows = [
|
|
|
|
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
|
2011-09-10 03:22:28 +08:00
|
|
|
for obj in self.query.objs
|
|
|
|
]
|
|
|
|
else:
|
2015-08-03 22:34:19 +08:00
|
|
|
# An empty object.
|
|
|
|
value_rows = [[self.connection.ops.pk_default_value()] for _ in self.query.objs]
|
2011-09-10 03:22:28 +08:00
|
|
|
fields = [None]
|
|
|
|
|
2015-08-03 22:34:19 +08:00
|
|
|
# Currently the backends just accept values when generating bulk
|
|
|
|
# queries and generate their own placeholders. Doing that isn't
|
|
|
|
# necessary and it should be possible to use placeholders and
|
|
|
|
# expressions in bulk inserts too.
|
2019-07-24 14:42:41 +08:00
|
|
|
can_bulk = (not self.returning_fields and self.connection.features.has_bulk_insert)
|
2015-08-03 22:34:19 +08:00
|
|
|
|
|
|
|
placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows)
|
|
|
|
|
2017-10-03 07:35:38 +08:00
|
|
|
ignore_conflicts_suffix_sql = self.connection.ops.ignore_conflicts_suffix_sql(
|
|
|
|
ignore_conflicts=self.query.ignore_conflicts
|
|
|
|
)
|
2019-07-24 14:42:41 +08:00
|
|
|
if self.returning_fields and self.connection.features.can_return_columns_from_insert:
|
2019-01-31 04:31:56 +08:00
|
|
|
if self.connection.features.can_return_rows_from_bulk_insert:
|
2015-08-21 13:38:58 +08:00
|
|
|
result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
|
|
|
|
params = param_rows
|
|
|
|
else:
|
|
|
|
result.append("VALUES (%s)" % ", ".join(placeholder_rows[0]))
|
2016-03-06 03:02:35 +08:00
|
|
|
params = [param_rows[0]]
|
2017-10-03 07:35:38 +08:00
|
|
|
if ignore_conflicts_suffix_sql:
|
|
|
|
result.append(ignore_conflicts_suffix_sql)
|
2019-07-24 14:42:41 +08:00
|
|
|
# Skip empty r_sql to allow subclasses to customize behavior for
|
2012-10-10 05:06:37 +08:00
|
|
|
# 3rd party backends. Refs #19096.
|
2019-09-15 05:50:14 +08:00
|
|
|
r_sql, self.returning_params = self.connection.ops.return_insert_columns(self.returning_fields)
|
2019-07-24 14:42:41 +08:00
|
|
|
if r_sql:
|
|
|
|
result.append(r_sql)
|
2019-09-15 05:50:14 +08:00
|
|
|
params += [self.returning_params]
|
2015-08-21 13:38:58 +08:00
|
|
|
return [(" ".join(result), tuple(chain.from_iterable(params)))]
|
2015-08-03 22:34:19 +08:00
|
|
|
|
2011-09-11 06:02:13 +08:00
|
|
|
if can_bulk:
|
2015-08-03 22:34:19 +08:00
|
|
|
result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows))
|
2017-10-03 07:35:38 +08:00
|
|
|
if ignore_conflicts_suffix_sql:
|
|
|
|
result.append(ignore_conflicts_suffix_sql)
|
2015-08-03 22:34:19 +08:00
|
|
|
return [(" ".join(result), tuple(p for ps in param_rows for p in ps))]
|
2011-09-10 03:22:28 +08:00
|
|
|
else:
|
2017-10-03 07:35:38 +08:00
|
|
|
if ignore_conflicts_suffix_sql:
|
|
|
|
result.append(ignore_conflicts_suffix_sql)
|
2011-09-10 03:22:28 +08:00
|
|
|
return [
|
|
|
|
(" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
|
2015-08-03 22:34:19 +08:00
|
|
|
for p, vals in zip(placeholder_rows, param_rows)
|
2011-09-10 03:22:28 +08:00
|
|
|
]
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2019-07-24 14:42:41 +08:00
|
|
|
def execute_sql(self, returning_fields=None):
|
2015-08-21 13:38:58 +08:00
|
|
|
assert not (
|
2019-07-24 14:42:41 +08:00
|
|
|
returning_fields and len(self.query.objs) != 1 and
|
2019-01-31 04:31:56 +08:00
|
|
|
not self.connection.features.can_return_rows_from_bulk_insert
|
2015-08-21 13:38:58 +08:00
|
|
|
)
|
2019-07-24 14:42:41 +08:00
|
|
|
self.returning_fields = returning_fields
|
2014-01-09 23:05:15 +08:00
|
|
|
with self.connection.cursor() as cursor:
|
|
|
|
for sql, params in self.as_sql():
|
|
|
|
cursor.execute(sql, params)
|
2019-07-24 14:42:41 +08:00
|
|
|
if not self.returning_fields:
|
|
|
|
return []
|
2019-01-31 04:31:56 +08:00
|
|
|
if self.connection.features.can_return_rows_from_bulk_insert and len(self.query.objs) > 1:
|
2019-07-24 14:42:41 +08:00
|
|
|
return self.connection.ops.fetch_returned_insert_rows(cursor)
|
2019-01-31 04:31:56 +08:00
|
|
|
if self.connection.features.can_return_columns_from_insert:
|
2015-08-21 13:38:58 +08:00
|
|
|
assert len(self.query.objs) == 1
|
2020-03-26 19:31:02 +08:00
|
|
|
return [self.connection.ops.fetch_returned_insert_columns(cursor, self.returning_params)]
|
|
|
|
return [(self.connection.ops.last_insert_id(
|
2016-03-29 06:33:29 +08:00
|
|
|
cursor, self.query.get_meta().db_table, self.query.get_meta().pk.column
|
2020-03-26 19:31:02 +08:00
|
|
|
),)]
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
|
|
|
|
class SQLDeleteCompiler(SQLCompiler):
|
2019-10-17 13:57:39 +08:00
|
|
|
@cached_property
|
|
|
|
def single_alias(self):
|
2020-05-24 21:18:12 +08:00
|
|
|
# Ensure base table is in aliases.
|
|
|
|
self.query.get_initial_alias()
|
2019-10-17 13:57:39 +08:00
|
|
|
return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1
|
|
|
|
|
|
|
|
def _as_sql(self, query):
|
|
|
|
result = [
|
|
|
|
'DELETE FROM %s' % self.quote_name_unless_alias(query.base_table)
|
|
|
|
]
|
|
|
|
where, params = self.compile(query.where)
|
|
|
|
if where:
|
|
|
|
result.append('WHERE %s' % where)
|
|
|
|
return ' '.join(result), tuple(params)
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def as_sql(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Create the SQL for this query. Return the SQL string and list of
|
2009-12-22 23:18:51 +08:00
|
|
|
parameters.
|
|
|
|
"""
|
2019-10-17 13:57:39 +08:00
|
|
|
if self.single_alias:
|
|
|
|
return self._as_sql(self.query)
|
|
|
|
innerq = self.query.clone()
|
|
|
|
innerq.__class__ = Query
|
|
|
|
innerq.clear_select_clause()
|
|
|
|
pk = self.query.model._meta.pk
|
|
|
|
innerq.select = [
|
|
|
|
pk.get_col(self.query.get_initial_alias())
|
|
|
|
]
|
|
|
|
outerq = Query(self.query.model)
|
|
|
|
outerq.where = self.query.where_class()
|
|
|
|
outerq.add_q(Q(pk__in=innerq))
|
|
|
|
return self._as_sql(outerq)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
class SQLUpdateCompiler(SQLCompiler):
|
|
|
|
def as_sql(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Create the SQL for this query. Return the SQL string and list of
|
2009-12-22 23:18:51 +08:00
|
|
|
parameters.
|
|
|
|
"""
|
|
|
|
self.pre_sql_setup()
|
|
|
|
if not self.query.values:
|
|
|
|
return '', ()
|
2014-11-18 09:05:14 +08:00
|
|
|
qn = self.quote_name_unless_alias
|
2009-12-22 23:18:51 +08:00
|
|
|
values, update_params = [], []
|
|
|
|
for field, model, val in self.query.values:
|
2013-12-25 21:13:18 +08:00
|
|
|
if hasattr(val, 'resolve_expression'):
|
2015-01-02 09:39:31 +08:00
|
|
|
val = val.resolve_expression(self.query, allow_joins=False, for_save=True)
|
|
|
|
if val.contains_aggregate:
|
2019-02-15 07:58:08 +08:00
|
|
|
raise FieldError(
|
|
|
|
'Aggregate functions are not allowed in this query '
|
|
|
|
'(%s=%r).' % (field.name, val)
|
|
|
|
)
|
2017-09-18 21:42:29 +08:00
|
|
|
if val.contains_over_clause:
|
2019-02-15 07:58:08 +08:00
|
|
|
raise FieldError(
|
|
|
|
'Window expressions are not allowed in this query '
|
|
|
|
'(%s=%r).' % (field.name, val)
|
|
|
|
)
|
2013-12-25 21:13:18 +08:00
|
|
|
elif hasattr(val, 'prepare_database_save'):
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field:
|
2015-04-10 02:47:05 +08:00
|
|
|
val = field.get_db_prep_save(
|
|
|
|
val.prepare_database_save(field),
|
|
|
|
connection=self.connection,
|
|
|
|
)
|
2014-03-10 23:17:57 +08:00
|
|
|
else:
|
2015-08-03 22:34:19 +08:00
|
|
|
raise TypeError(
|
|
|
|
"Tried to update field %s with a model instance, %r. "
|
|
|
|
"Use a value compatible with %s."
|
|
|
|
% (field, val, field.__class__.__name__)
|
|
|
|
)
|
2009-12-22 23:18:51 +08:00
|
|
|
else:
|
|
|
|
val = field.get_db_prep_save(val, connection=self.connection)
|
|
|
|
|
|
|
|
# Getting the placeholder for the field.
|
|
|
|
if hasattr(field, 'get_placeholder'):
|
2013-12-25 21:13:18 +08:00
|
|
|
placeholder = field.get_placeholder(val, self, self.connection)
|
2009-12-22 23:18:51 +08:00
|
|
|
else:
|
|
|
|
placeholder = '%s'
|
|
|
|
name = field.column
|
|
|
|
if hasattr(val, 'as_sql'):
|
2014-01-18 17:09:43 +08:00
|
|
|
sql, params = self.compile(val)
|
2017-04-11 01:26:26 +08:00
|
|
|
values.append('%s = %s' % (qn(name), placeholder % sql))
|
2009-12-22 23:18:51 +08:00
|
|
|
update_params.extend(params)
|
|
|
|
elif val is not None:
|
|
|
|
values.append('%s = %s' % (qn(name), placeholder))
|
|
|
|
update_params.append(val)
|
|
|
|
else:
|
|
|
|
values.append('%s = NULL' % qn(name))
|
2017-06-28 14:23:37 +08:00
|
|
|
table = self.query.base_table
|
2015-11-09 00:05:45 +08:00
|
|
|
result = [
|
|
|
|
'UPDATE %s SET' % qn(table),
|
|
|
|
', '.join(values),
|
|
|
|
]
|
2014-01-18 17:09:43 +08:00
|
|
|
where, params = self.compile(self.query.where)
|
2009-12-22 23:18:51 +08:00
|
|
|
if where:
|
|
|
|
result.append('WHERE %s' % where)
|
|
|
|
return ' '.join(result), tuple(update_params + params)
|
|
|
|
|
|
|
|
def execute_sql(self, result_type):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Execute the specified update. Return the number of rows affected by
|
2009-12-22 23:18:51 +08:00
|
|
|
the primary update query. The "primary update query" is the first
|
|
|
|
non-empty query that is executed. Row counts for any subsequent,
|
|
|
|
related queries are not available.
|
|
|
|
"""
|
2017-01-21 21:13:44 +08:00
|
|
|
cursor = super().execute_sql(result_type)
|
2014-01-09 12:31:34 +08:00
|
|
|
try:
|
|
|
|
rows = cursor.rowcount if cursor else 0
|
|
|
|
is_empty = cursor is None
|
|
|
|
finally:
|
|
|
|
if cursor:
|
|
|
|
cursor.close()
|
2009-12-22 23:18:51 +08:00
|
|
|
for query in self.query.get_related_updates():
|
|
|
|
aux_rows = query.get_compiler(self.using).execute_sql(result_type)
|
2014-01-09 12:31:34 +08:00
|
|
|
if is_empty and aux_rows:
|
2009-12-22 23:18:51 +08:00
|
|
|
rows = aux_rows
|
|
|
|
is_empty = False
|
|
|
|
return rows
|
|
|
|
|
|
|
|
def pre_sql_setup(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
If the update depends on results from other tables, munge the "where"
|
|
|
|
conditions to match the format required for (portable) SQL updates.
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
If multiple updates are required, pull out the id values to update at
|
|
|
|
this point so that they don't change as a result of the progressive
|
|
|
|
updates.
|
2009-12-22 23:18:51 +08:00
|
|
|
"""
|
2014-12-01 15:28:01 +08:00
|
|
|
refcounts_before = self.query.alias_refcount.copy()
|
|
|
|
# Ensure base table is in the query
|
|
|
|
self.query.get_initial_alias()
|
2009-12-22 23:18:51 +08:00
|
|
|
count = self.query.count_active_tables()
|
|
|
|
if not self.query.related_updates and count == 1:
|
|
|
|
return
|
2017-07-08 00:49:23 +08:00
|
|
|
query = self.query.chain(klass=Query)
|
2014-12-01 15:28:01 +08:00
|
|
|
query.select_related = False
|
|
|
|
query.clear_ordering(True)
|
2019-02-05 19:22:08 +08:00
|
|
|
query.extra = {}
|
2009-12-22 23:18:51 +08:00
|
|
|
query.select = []
|
2013-05-14 03:40:39 +08:00
|
|
|
query.add_fields([query.get_meta().pk.name])
|
2017-01-21 21:13:44 +08:00
|
|
|
super().pre_sql_setup()
|
2012-05-12 18:01:45 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
must_pre_select = count > 1 and not self.connection.features.update_can_self_select
|
|
|
|
|
|
|
|
# Now we adjust the current query: reset the where clause and get rid
|
|
|
|
# of all the tables we don't need (since they're in the sub-select).
|
|
|
|
self.query.where = self.query.where_class()
|
|
|
|
if self.query.related_updates or must_pre_select:
|
|
|
|
# Either we're using the idents in multiple update queries (so
|
|
|
|
# don't want them to change), or the db backend doesn't support
|
|
|
|
# selecting from the updating table (e.g. MySQL).
|
|
|
|
idents = []
|
|
|
|
for rows in query.get_compiler(self.using).execute_sql(MULTI):
|
2013-08-30 07:20:00 +08:00
|
|
|
idents.extend(r[0] for r in rows)
|
2009-12-22 23:18:51 +08:00
|
|
|
self.query.add_filter(('pk__in', idents))
|
|
|
|
self.query.related_ids = idents
|
|
|
|
else:
|
|
|
|
# The fast path. Filters and updates in one query.
|
|
|
|
self.query.add_filter(('pk__in', query))
|
2014-12-01 15:28:01 +08:00
|
|
|
self.query.reset_refcounts(refcounts_before)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
class SQLAggregateCompiler(SQLCompiler):
|
2014-11-20 19:18:08 +08:00
|
|
|
def as_sql(self):
|
2009-12-22 23:18:51 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Create the SQL for this query. Return the SQL string and list of
|
2009-12-22 23:18:51 +08:00
|
|
|
parameters.
|
|
|
|
"""
|
2013-02-10 23:15:49 +08:00
|
|
|
sql, params = [], []
|
2013-12-25 21:13:18 +08:00
|
|
|
for annotation in self.query.annotation_select.values():
|
2019-08-10 02:30:23 +08:00
|
|
|
ann_sql, ann_params = self.compile(annotation)
|
|
|
|
ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params)
|
2015-01-29 20:20:56 +08:00
|
|
|
sql.append(ann_sql)
|
|
|
|
params.extend(ann_params)
|
2014-12-01 15:28:01 +08:00
|
|
|
self.col_count = len(self.query.annotation_select)
|
2013-02-10 23:15:49 +08:00
|
|
|
sql = ', '.join(sql)
|
|
|
|
params = tuple(params)
|
|
|
|
|
|
|
|
sql = 'SELECT %s FROM (%s) subquery' % (sql, self.query.subquery)
|
|
|
|
params = params + self.query.sub_params
|
|
|
|
return sql, params
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2017-06-02 04:56:51 +08:00
|
|
|
def cursor_iter(cursor, sentinel, col_count, itersize):
|
2014-01-09 12:31:34 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Yield blocks of rows from a cursor and ensure the cursor is closed when
|
2014-01-09 12:31:34 +08:00
|
|
|
done.
|
|
|
|
"""
|
|
|
|
try:
|
2017-06-02 04:56:51 +08:00
|
|
|
for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel):
|
2017-08-09 02:07:03 +08:00
|
|
|
yield rows if col_count is None else [r[:col_count] for r in rows]
|
2014-01-09 12:31:34 +08:00
|
|
|
finally:
|
|
|
|
cursor.close()
|