2013-12-25 21:13:18 +08:00
|
|
|
import copy
|
2010-12-22 11:34:04 +08:00
|
|
|
import datetime
|
Refactored qs.add_q() and utils/tree.py
The sql/query.py add_q method did a lot of where/having tree hacking to
get complex queries to work correctly. The logic was refactored so that
it should be simpler to understand. The new logic should also produce
leaner WHERE conditions.
The changes cascade somewhat, as some other parts of Django (like
add_filter() and WhereNode) expect boolean trees in certain format or
they fail to work. So to fix the add_q() one must fix utils/tree.py,
some things in add_filter(), WhereNode and so on.
This commit also fixed add_filter to see negate clauses up the path.
A query like .exclude(Q(reversefk__in=a_list)) didn't work similarly to
.filter(~Q(reversefk__in=a_list)). The reason for this is that only
the immediate parent negate clauses were seen by add_filter, and thus a
tree like AND: (NOT AND: (AND: condition)) will not be handled
correctly, as there is one intermediary AND node in the tree. The
example tree is generated by .exclude(~Q(reversefk__in=a_list)).
Still, aggregation lost connectors in OR cases, and F() objects and
aggregates in same filter clause caused GROUP BY problems on some
databases.
Fixed #17600, fixed #13198, fixed #17025, fixed #17000, fixed #11293.
2012-05-25 05:27:24 +08:00
|
|
|
|
2014-11-18 17:24:33 +08:00
|
|
|
from django.conf import settings
|
2013-12-25 21:13:18 +08:00
|
|
|
from django.core.exceptions import FieldError
|
|
|
|
from django.db.backends import utils as backend_utils
|
|
|
|
from django.db.models import fields
|
Refactored qs.add_q() and utils/tree.py
The sql/query.py add_q method did a lot of where/having tree hacking to
get complex queries to work correctly. The logic was refactored so that
it should be simpler to understand. The new logic should also produce
leaner WHERE conditions.
The changes cascade somewhat, as some other parts of Django (like
add_filter() and WhereNode) expect boolean trees in certain format or
they fail to work. So to fix the add_q() one must fix utils/tree.py,
some things in add_filter(), WhereNode and so on.
This commit also fixed add_filter to see negate clauses up the path.
A query like .exclude(Q(reversefk__in=a_list)) didn't work similarly to
.filter(~Q(reversefk__in=a_list)). The reason for this is that only
the immediate parent negate clauses were seen by add_filter, and thus a
tree like AND: (NOT AND: (AND: condition)) will not be handled
correctly, as there is one intermediary AND node in the tree. The
example tree is generated by .exclude(~Q(reversefk__in=a_list)).
Still, aggregation lost connectors in OR cases, and F() objects and
aggregates in same filter clause caused GROUP BY problems on some
databases.
Fixed #17600, fixed #13198, fixed #17025, fixed #17000, fixed #11293.
2012-05-25 05:27:24 +08:00
|
|
|
from django.db.models.constants import LOOKUP_SEP
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.db.models.query_utils import Q, refs_aggregate
|
2015-02-11 13:38:02 +08:00
|
|
|
from django.utils import six, timezone
|
2013-12-25 21:13:18 +08:00
|
|
|
from django.utils.functional import cached_property
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2015-01-27 10:42:48 +08:00
|
|
|
class Combinable(object):
|
2009-01-29 18:46:36 +08:00
|
|
|
"""
|
2013-12-25 21:13:18 +08:00
|
|
|
Provides the ability to combine one or two objects with
|
|
|
|
some connector. For example F('foo') + F('bar').
|
2009-01-29 18:46:36 +08:00
|
|
|
"""
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2009-01-29 18:46:36 +08:00
|
|
|
# Arithmetic connectors
|
|
|
|
ADD = '+'
|
|
|
|
SUB = '-'
|
|
|
|
MUL = '*'
|
|
|
|
DIV = '/'
|
2013-02-22 06:02:18 +08:00
|
|
|
POW = '^'
|
2014-04-21 18:25:43 +08:00
|
|
|
# The following is a quoted % operator - it is quoted because it can be
|
|
|
|
# used in strings that also have parameter substitution.
|
|
|
|
MOD = '%%'
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2012-10-03 23:53:40 +08:00
|
|
|
# Bitwise operators - note that these are generated by .bitand()
|
|
|
|
# and .bitor(), the '&' and '|' are reserved for boolean operator
|
|
|
|
# usage.
|
|
|
|
BITAND = '&'
|
|
|
|
BITOR = '|'
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
def _combine(self, other, connector, reversed, node=None):
|
2013-12-25 21:13:18 +08:00
|
|
|
if not hasattr(other, 'resolve_expression'):
|
|
|
|
# everything must be resolvable to an expression
|
2014-07-24 20:57:24 +08:00
|
|
|
if isinstance(other, datetime.timedelta):
|
|
|
|
other = DurationValue(other, output_field=fields.DurationField())
|
|
|
|
else:
|
|
|
|
other = Value(other)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
if reversed:
|
2015-03-17 08:38:55 +08:00
|
|
|
return CombinedExpression(other, connector, self)
|
|
|
|
return CombinedExpression(self, connector, other)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
#############
|
|
|
|
# OPERATORS #
|
|
|
|
#############
|
|
|
|
|
|
|
|
def __add__(self, other):
|
|
|
|
return self._combine(other, self.ADD, False)
|
|
|
|
|
|
|
|
def __sub__(self, other):
|
|
|
|
return self._combine(other, self.SUB, False)
|
|
|
|
|
|
|
|
def __mul__(self, other):
|
|
|
|
return self._combine(other, self.MUL, False)
|
|
|
|
|
2012-08-14 20:43:33 +08:00
|
|
|
def __truediv__(self, other):
|
2009-01-29 18:46:36 +08:00
|
|
|
return self._combine(other, self.DIV, False)
|
2012-11-04 04:43:11 +08:00
|
|
|
|
|
|
|
def __div__(self, other): # Python 2 compatibility
|
|
|
|
return type(self).__truediv__(self, other)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
def __mod__(self, other):
|
|
|
|
return self._combine(other, self.MOD, False)
|
|
|
|
|
2013-02-22 06:02:18 +08:00
|
|
|
def __pow__(self, other):
|
|
|
|
return self._combine(other, self.POW, False)
|
|
|
|
|
2009-01-29 18:46:36 +08:00
|
|
|
def __and__(self, other):
|
2012-10-03 23:53:40 +08:00
|
|
|
raise NotImplementedError(
|
|
|
|
"Use .bitand() and .bitor() for bitwise logical operations."
|
|
|
|
)
|
|
|
|
|
|
|
|
def bitand(self, other):
|
|
|
|
return self._combine(other, self.BITAND, False)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
def __or__(self, other):
|
2012-10-03 23:53:40 +08:00
|
|
|
raise NotImplementedError(
|
|
|
|
"Use .bitand() and .bitor() for bitwise logical operations."
|
|
|
|
)
|
|
|
|
|
|
|
|
def bitor(self, other):
|
|
|
|
return self._combine(other, self.BITOR, False)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
def __radd__(self, other):
|
|
|
|
return self._combine(other, self.ADD, True)
|
|
|
|
|
|
|
|
def __rsub__(self, other):
|
|
|
|
return self._combine(other, self.SUB, True)
|
|
|
|
|
|
|
|
def __rmul__(self, other):
|
|
|
|
return self._combine(other, self.MUL, True)
|
|
|
|
|
2012-08-15 19:27:40 +08:00
|
|
|
def __rtruediv__(self, other):
|
2009-01-29 18:46:36 +08:00
|
|
|
return self._combine(other, self.DIV, True)
|
2012-11-04 04:43:11 +08:00
|
|
|
|
|
|
|
def __rdiv__(self, other): # Python 2 compatibility
|
|
|
|
return type(self).__rtruediv__(self, other)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
def __rmod__(self, other):
|
|
|
|
return self._combine(other, self.MOD, True)
|
|
|
|
|
2013-02-22 06:02:18 +08:00
|
|
|
def __rpow__(self, other):
|
|
|
|
return self._combine(other, self.POW, True)
|
|
|
|
|
2009-01-29 18:46:36 +08:00
|
|
|
def __rand__(self, other):
|
2012-10-03 23:53:40 +08:00
|
|
|
raise NotImplementedError(
|
|
|
|
"Use .bitand() and .bitor() for bitwise logical operations."
|
|
|
|
)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
def __ror__(self, other):
|
2012-10-03 23:53:40 +08:00
|
|
|
raise NotImplementedError(
|
|
|
|
"Use .bitand() and .bitor() for bitwise logical operations."
|
|
|
|
)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2015-01-09 23:16:16 +08:00
|
|
|
class BaseExpression(object):
|
2009-01-29 18:46:36 +08:00
|
|
|
"""
|
2013-12-25 21:13:18 +08:00
|
|
|
Base class for all query expressions.
|
2009-01-29 18:46:36 +08:00
|
|
|
"""
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
# aggregate specific fields
|
|
|
|
is_summary = False
|
2015-06-01 05:45:03 +08:00
|
|
|
_output_field = None
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
def __init__(self, output_field=None):
|
2015-06-01 05:45:03 +08:00
|
|
|
if output_field is not None:
|
|
|
|
self._output_field = output_field
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2015-03-19 11:07:53 +08:00
|
|
|
def get_db_converters(self, connection):
|
|
|
|
return [self.convert_value] + self.output_field.get_db_converters(connection)
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def get_source_expressions(self):
|
|
|
|
return []
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
assert len(exprs) == 0
|
|
|
|
|
2015-02-11 13:38:02 +08:00
|
|
|
def _parse_expressions(self, *expressions):
|
|
|
|
return [
|
|
|
|
arg if hasattr(arg, 'resolve_expression') else (
|
|
|
|
F(arg) if isinstance(arg, six.string_types) else Value(arg)
|
|
|
|
) for arg in expressions
|
|
|
|
]
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
"""
|
|
|
|
Responsible for returning a (sql, [params]) tuple to be included
|
|
|
|
in the current query.
|
|
|
|
|
|
|
|
Different backends can provide their own implementation, by
|
|
|
|
providing an `as_{vendor}` method and patching the Expression:
|
|
|
|
|
|
|
|
```
|
|
|
|
def override_as_sql(self, compiler, connection):
|
|
|
|
# custom logic
|
2015-03-17 08:38:55 +08:00
|
|
|
return super(Expression, self).as_sql(compiler, connection)
|
|
|
|
setattr(Expression, 'as_' + connection.vendor, override_as_sql)
|
2013-12-25 21:13:18 +08:00
|
|
|
```
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
* compiler: the query compiler responsible for generating the query.
|
|
|
|
Must have a compile method, returning a (sql, [params]) tuple.
|
|
|
|
Calling compiler(value) will return a quoted `value`.
|
|
|
|
|
|
|
|
* connection: the database connection used for the current query.
|
|
|
|
|
|
|
|
Returns: (sql, params)
|
|
|
|
Where `sql` is a string containing ordered sql parameters to be
|
|
|
|
replaced with the elements of the list `params`.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError("Subclasses must implement as_sql()")
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def contains_aggregate(self):
|
|
|
|
for expr in self.get_source_expressions():
|
|
|
|
if expr and expr.contains_aggregate:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2015-08-03 22:34:19 +08:00
|
|
|
@cached_property
|
|
|
|
def contains_column_references(self):
|
|
|
|
for expr in self.get_source_expressions():
|
|
|
|
if expr and expr.contains_column_references:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2015-01-02 09:39:31 +08:00
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
Provides the chance to do any preprocessing or validation before being
|
|
|
|
added to the query.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
* query: the backend query implementation
|
|
|
|
* allow_joins: boolean allowing or denying use of joins
|
|
|
|
in this query
|
|
|
|
* reuse: a set of reusable joins for multijoins
|
|
|
|
* summarize: a terminal aggregate clause
|
2015-01-27 10:42:48 +08:00
|
|
|
* for_save: whether this expression about to be used in a save or update
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
Returns: an Expression to be added to the query.
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
c = self.copy()
|
|
|
|
c.is_summary = summarize
|
2015-01-09 23:16:16 +08:00
|
|
|
c.set_source_expressions([
|
|
|
|
expr.resolve_expression(query, allow_joins, reuse, summarize)
|
|
|
|
for expr in c.get_source_expressions()
|
|
|
|
])
|
2013-12-25 21:13:18 +08:00
|
|
|
return c
|
|
|
|
|
2016-02-11 14:39:37 +08:00
|
|
|
def _prepare(self, field):
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
Hook used by Field.get_prep_lookup() to do custom preparation.
|
|
|
|
"""
|
|
|
|
return self
|
2010-12-22 11:34:04 +08:00
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
@property
|
|
|
|
def field(self):
|
|
|
|
return self.output_field
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def output_field(self):
|
|
|
|
"""
|
|
|
|
Returns the output type of this expressions.
|
|
|
|
"""
|
|
|
|
if self._output_field_or_none is None:
|
|
|
|
raise FieldError("Cannot resolve expression type, unknown output_field")
|
|
|
|
return self._output_field_or_none
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def _output_field_or_none(self):
|
|
|
|
"""
|
|
|
|
Returns the output field of this expression, or None if no output type
|
|
|
|
can be resolved. Note that the 'output_field' property will raise
|
|
|
|
FieldError if no type can be resolved, but this attribute allows for
|
|
|
|
None values.
|
|
|
|
"""
|
|
|
|
if self._output_field is None:
|
|
|
|
self._resolve_output_field()
|
|
|
|
return self._output_field
|
|
|
|
|
|
|
|
def _resolve_output_field(self):
|
|
|
|
"""
|
|
|
|
Attempts to infer the output type of the expression. If the output
|
|
|
|
fields of all source fields match then we can simply infer the same
|
2015-03-20 12:47:43 +08:00
|
|
|
type here. This isn't always correct, but it makes sense most of the
|
|
|
|
time.
|
|
|
|
|
|
|
|
Consider the difference between `2 + 2` and `2 / 3`. Inferring
|
|
|
|
the type here is a convenience for the common case. The user should
|
|
|
|
supply their own output_field with more complex computations.
|
|
|
|
|
|
|
|
If a source does not have an `_output_field` then we exclude it from
|
|
|
|
this check. If all sources are `None`, then an error will be thrown
|
|
|
|
higher up the stack in the `output_field` property.
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
if self._output_field is None:
|
|
|
|
sources = self.get_source_fields()
|
|
|
|
num_sources = len(sources)
|
|
|
|
if num_sources == 0:
|
|
|
|
self._output_field = None
|
|
|
|
else:
|
|
|
|
for source in sources:
|
2015-03-20 12:47:43 +08:00
|
|
|
if self._output_field is None:
|
|
|
|
self._output_field = source
|
2013-12-25 21:13:18 +08:00
|
|
|
if source is not None and not isinstance(self._output_field, source.__class__):
|
|
|
|
raise FieldError(
|
|
|
|
"Expression contains mixed types. You must set output_field")
|
|
|
|
|
2015-02-20 18:53:59 +08:00
|
|
|
def convert_value(self, value, expression, connection, context):
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
Expressions provide their own converters because users have the option
|
|
|
|
of manually specifying the output_field which may be a different type
|
|
|
|
from the one the database returns.
|
|
|
|
"""
|
|
|
|
field = self.output_field
|
|
|
|
internal_type = field.get_internal_type()
|
|
|
|
if value is None:
|
|
|
|
return value
|
|
|
|
elif internal_type == 'FloatField':
|
|
|
|
return float(value)
|
|
|
|
elif internal_type.endswith('IntegerField'):
|
|
|
|
return int(value)
|
|
|
|
elif internal_type == 'DecimalField':
|
2014-12-01 14:11:23 +08:00
|
|
|
return backend_utils.typecast_decimal(value)
|
2013-12-25 21:13:18 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
def get_lookup(self, lookup):
|
|
|
|
return self.output_field.get_lookup(lookup)
|
|
|
|
|
|
|
|
def get_transform(self, name):
|
|
|
|
return self.output_field.get_transform(name)
|
|
|
|
|
|
|
|
def relabeled_clone(self, change_map):
|
|
|
|
clone = self.copy()
|
|
|
|
clone.set_source_expressions(
|
|
|
|
[e.relabeled_clone(change_map) for e in self.get_source_expressions()])
|
|
|
|
return clone
|
|
|
|
|
|
|
|
def copy(self):
|
|
|
|
c = copy.copy(self)
|
|
|
|
c.copied = True
|
|
|
|
return c
|
|
|
|
|
|
|
|
def refs_aggregate(self, existing_aggregates):
|
|
|
|
"""
|
|
|
|
Does this expression contain a reference to some of the
|
|
|
|
existing aggregates? If so, returns the aggregate and also
|
|
|
|
the lookup parts that *weren't* found. So, if
|
2015-12-03 07:55:50 +08:00
|
|
|
existing_aggregates = {'max_id': Max('id')}
|
2013-12-25 21:13:18 +08:00
|
|
|
self.name = 'max_id'
|
|
|
|
queryset.filter(max_id__range=[10,100])
|
|
|
|
then this method will return Max('id') and those parts of the
|
|
|
|
name that weren't found. In this case `max_id` is found and the range
|
|
|
|
portion is returned as ('range',).
|
|
|
|
"""
|
|
|
|
for node in self.get_source_expressions():
|
|
|
|
agg, lookup = node.refs_aggregate(existing_aggregates)
|
|
|
|
if agg:
|
|
|
|
return agg, lookup
|
|
|
|
return False, ()
|
|
|
|
|
|
|
|
def get_group_by_cols(self):
|
2014-12-01 15:28:01 +08:00
|
|
|
if not self.contains_aggregate:
|
|
|
|
return [self]
|
2013-12-25 21:13:18 +08:00
|
|
|
cols = []
|
|
|
|
for source in self.get_source_expressions():
|
|
|
|
cols.extend(source.get_group_by_cols())
|
|
|
|
return cols
|
|
|
|
|
|
|
|
def get_source_fields(self):
|
|
|
|
"""
|
|
|
|
Returns the underlying field types used by this
|
|
|
|
aggregate.
|
|
|
|
"""
|
|
|
|
return [e._output_field_or_none for e in self.get_source_expressions()]
|
|
|
|
|
2015-01-09 23:16:16 +08:00
|
|
|
def asc(self):
|
|
|
|
return OrderBy(self)
|
|
|
|
|
|
|
|
def desc(self):
|
|
|
|
return OrderBy(self, descending=True)
|
|
|
|
|
|
|
|
def reverse_ordering(self):
|
|
|
|
return self
|
|
|
|
|
2015-08-03 22:34:19 +08:00
|
|
|
def flatten(self):
|
|
|
|
"""
|
|
|
|
Recursively yield this expression and all subexpressions, in
|
|
|
|
depth-first order.
|
|
|
|
"""
|
|
|
|
yield self
|
|
|
|
for expr in self.get_source_expressions():
|
|
|
|
if expr:
|
|
|
|
for inner_expr in expr.flatten():
|
|
|
|
yield inner_expr
|
|
|
|
|
2015-01-09 23:16:16 +08:00
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class Expression(BaseExpression, Combinable):
|
2015-01-09 23:16:16 +08:00
|
|
|
"""
|
|
|
|
An expression that can be combined with other expressions.
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class CombinedExpression(Expression):
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
def __init__(self, lhs, connector, rhs, output_field=None):
|
2015-03-17 08:38:55 +08:00
|
|
|
super(CombinedExpression, self).__init__(output_field=output_field)
|
2013-12-25 21:13:18 +08:00
|
|
|
self.connector = connector
|
|
|
|
self.lhs = lhs
|
|
|
|
self.rhs = rhs
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "<{}: {}>".format(self.__class__.__name__, self)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return "{} {} {}".format(self.lhs, self.connector, self.rhs)
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def get_source_expressions(self):
|
|
|
|
return [self.lhs, self.rhs]
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
self.lhs, self.rhs = exprs
|
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
2014-07-24 20:57:24 +08:00
|
|
|
try:
|
|
|
|
lhs_output = self.lhs.output_field
|
|
|
|
except FieldError:
|
|
|
|
lhs_output = None
|
|
|
|
try:
|
|
|
|
rhs_output = self.rhs.output_field
|
|
|
|
except FieldError:
|
|
|
|
rhs_output = None
|
|
|
|
if (not connection.features.has_native_duration_field and
|
2016-04-04 08:37:32 +08:00
|
|
|
((lhs_output and lhs_output.get_internal_type() == 'DurationField') or
|
|
|
|
(rhs_output and rhs_output.get_internal_type() == 'DurationField'))):
|
2014-07-24 20:57:24 +08:00
|
|
|
return DurationExpression(self.lhs, self.connector, self.rhs).as_sql(compiler, connection)
|
2016-01-20 09:43:41 +08:00
|
|
|
if (lhs_output and rhs_output and self.connector == self.SUB and
|
|
|
|
lhs_output.get_internal_type() in {'DateField', 'DateTimeField', 'TimeField'} and
|
|
|
|
lhs_output.get_internal_type() == lhs_output.get_internal_type()):
|
|
|
|
return TemporalSubtraction(self.lhs, self.rhs).as_sql(compiler, connection)
|
2013-12-25 21:13:18 +08:00
|
|
|
expressions = []
|
|
|
|
expression_params = []
|
|
|
|
sql, params = compiler.compile(self.lhs)
|
|
|
|
expressions.append(sql)
|
|
|
|
expression_params.extend(params)
|
|
|
|
sql, params = compiler.compile(self.rhs)
|
|
|
|
expressions.append(sql)
|
|
|
|
expression_params.extend(params)
|
|
|
|
# order of precedence
|
|
|
|
expression_wrapper = '(%s)'
|
|
|
|
sql = connection.ops.combine_expression(self.connector, expressions)
|
|
|
|
return expression_wrapper % sql, expression_params
|
|
|
|
|
2015-01-02 09:39:31 +08:00
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
2013-12-25 21:13:18 +08:00
|
|
|
c = self.copy()
|
|
|
|
c.is_summary = summarize
|
2015-01-02 09:39:31 +08:00
|
|
|
c.lhs = c.lhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)
|
|
|
|
c.rhs = c.rhs.resolve_expression(query, allow_joins, reuse, summarize, for_save)
|
2013-12-25 21:13:18 +08:00
|
|
|
return c
|
|
|
|
|
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class DurationExpression(CombinedExpression):
|
2014-07-24 20:57:24 +08:00
|
|
|
def compile(self, side, compiler, connection):
|
|
|
|
if not isinstance(side, DurationValue):
|
|
|
|
try:
|
|
|
|
output = side.output_field
|
|
|
|
except FieldError:
|
|
|
|
pass
|
2015-03-16 12:51:23 +08:00
|
|
|
else:
|
|
|
|
if output.get_internal_type() == 'DurationField':
|
|
|
|
sql, params = compiler.compile(side)
|
|
|
|
return connection.ops.format_for_duration_arithmetic(sql), params
|
2014-07-24 20:57:24 +08:00
|
|
|
return compiler.compile(side)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
2015-01-17 13:03:46 +08:00
|
|
|
connection.ops.check_expression_support(self)
|
2014-07-24 20:57:24 +08:00
|
|
|
expressions = []
|
|
|
|
expression_params = []
|
|
|
|
sql, params = self.compile(self.lhs, compiler, connection)
|
|
|
|
expressions.append(sql)
|
|
|
|
expression_params.extend(params)
|
|
|
|
sql, params = self.compile(self.rhs, compiler, connection)
|
|
|
|
expressions.append(sql)
|
|
|
|
expression_params.extend(params)
|
|
|
|
# order of precedence
|
|
|
|
expression_wrapper = '(%s)'
|
|
|
|
sql = connection.ops.combine_duration_expression(self.connector, expressions)
|
|
|
|
return expression_wrapper % sql, expression_params
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
|
2016-01-20 09:43:41 +08:00
|
|
|
class TemporalSubtraction(CombinedExpression):
|
|
|
|
def __init__(self, lhs, rhs):
|
|
|
|
super(TemporalSubtraction, self).__init__(lhs, self.SUB, rhs, output_field=fields.DurationField())
|
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
connection.ops.check_expression_support(self)
|
|
|
|
lhs = compiler.compile(self.lhs, connection)
|
|
|
|
rhs = compiler.compile(self.rhs, connection)
|
|
|
|
return connection.ops.subtract_temporals(self.lhs.output_field.get_internal_type(), lhs, rhs)
|
|
|
|
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
class F(Combinable):
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
An object capable of resolving references to existing query objects.
|
|
|
|
"""
|
|
|
|
def __init__(self, name):
|
|
|
|
"""
|
|
|
|
Arguments:
|
|
|
|
* name: the name of the field this expression references
|
|
|
|
"""
|
|
|
|
self.name = name
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "{}({})".format(self.__class__.__name__, self.name)
|
|
|
|
|
2015-01-02 09:39:31 +08:00
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
2013-12-25 21:13:18 +08:00
|
|
|
return query.resolve_ref(self.name, allow_joins, reuse, summarize)
|
|
|
|
|
|
|
|
def refs_aggregate(self, existing_aggregates):
|
|
|
|
return refs_aggregate(self.name.split(LOOKUP_SEP), existing_aggregates)
|
|
|
|
|
2015-01-09 23:16:16 +08:00
|
|
|
def asc(self):
|
|
|
|
return OrderBy(self)
|
|
|
|
|
|
|
|
def desc(self):
|
|
|
|
return OrderBy(self, descending=True)
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class Func(Expression):
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
A SQL function call.
|
|
|
|
"""
|
|
|
|
function = None
|
|
|
|
template = '%(function)s(%(expressions)s)'
|
|
|
|
arg_joiner = ', '
|
2015-10-31 18:01:08 +08:00
|
|
|
arity = None # The number of arguments the function accepts.
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
def __init__(self, *expressions, **extra):
|
2015-10-31 18:01:08 +08:00
|
|
|
if self.arity is not None and len(expressions) != self.arity:
|
|
|
|
raise TypeError(
|
|
|
|
"'%s' takes exactly %s %s (%s given)" % (
|
|
|
|
self.__class__.__name__,
|
|
|
|
self.arity,
|
|
|
|
"argument" if self.arity == 1 else "arguments",
|
|
|
|
len(expressions),
|
|
|
|
)
|
|
|
|
)
|
2013-12-25 21:13:18 +08:00
|
|
|
output_field = extra.pop('output_field', None)
|
|
|
|
super(Func, self).__init__(output_field=output_field)
|
|
|
|
self.source_expressions = self._parse_expressions(*expressions)
|
|
|
|
self.extra = extra
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
args = self.arg_joiner.join(str(arg) for arg in self.source_expressions)
|
|
|
|
extra = ', '.join(str(key) + '=' + str(val) for key, val in self.extra.items())
|
|
|
|
if extra:
|
|
|
|
return "{}({}, {})".format(self.__class__.__name__, args, extra)
|
|
|
|
return "{}({})".format(self.__class__.__name__, args)
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def get_source_expressions(self):
|
|
|
|
return self.source_expressions
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
self.source_expressions = exprs
|
|
|
|
|
2015-01-02 09:39:31 +08:00
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
2013-12-25 21:13:18 +08:00
|
|
|
c = self.copy()
|
|
|
|
c.is_summary = summarize
|
|
|
|
for pos, arg in enumerate(c.source_expressions):
|
2015-01-02 09:39:31 +08:00
|
|
|
c.source_expressions[pos] = arg.resolve_expression(query, allow_joins, reuse, summarize, for_save)
|
2013-12-25 21:13:18 +08:00
|
|
|
return c
|
|
|
|
|
2016-02-16 04:42:24 +08:00
|
|
|
def as_sql(self, compiler, connection, function=None, template=None, arg_joiner=None, **extra_context):
|
2015-01-17 13:03:46 +08:00
|
|
|
connection.ops.check_expression_support(self)
|
2013-12-25 21:13:18 +08:00
|
|
|
sql_parts = []
|
|
|
|
params = []
|
|
|
|
for arg in self.source_expressions:
|
|
|
|
arg_sql, arg_params = compiler.compile(arg)
|
|
|
|
sql_parts.append(arg_sql)
|
|
|
|
params.extend(arg_params)
|
2016-02-16 04:42:24 +08:00
|
|
|
data = self.extra.copy()
|
|
|
|
data.update(**extra_context)
|
|
|
|
# Use the first supplied value in this order: the parameter to this
|
|
|
|
# method, a value supplied in __init__()'s **extra (the value in
|
|
|
|
# `data`), or the value defined on the class.
|
|
|
|
if function is not None:
|
|
|
|
data['function'] = function
|
2013-12-25 21:13:18 +08:00
|
|
|
else:
|
2016-02-16 04:42:24 +08:00
|
|
|
data.setdefault('function', self.function)
|
|
|
|
template = template or data.get('template', self.template)
|
|
|
|
arg_joiner = arg_joiner or data.get('arg_joiner', self.arg_joiner)
|
|
|
|
data['expressions'] = data['field'] = arg_joiner.join(sql_parts)
|
|
|
|
return template % data, params
|
2010-12-22 11:34:04 +08:00
|
|
|
|
2016-03-26 06:51:34 +08:00
|
|
|
def as_sqlite(self, compiler, connection):
|
|
|
|
sql, params = self.as_sql(compiler, connection)
|
2015-06-07 08:05:36 +08:00
|
|
|
try:
|
|
|
|
if self.output_field.get_internal_type() == 'DecimalField':
|
|
|
|
sql = 'CAST(%s AS NUMERIC)' % sql
|
|
|
|
except FieldError:
|
|
|
|
pass
|
|
|
|
return sql, params
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def copy(self):
|
|
|
|
copy = super(Func, self).copy()
|
|
|
|
copy.source_expressions = self.source_expressions[:]
|
|
|
|
copy.extra = self.extra.copy()
|
|
|
|
return copy
|
|
|
|
|
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class Value(Expression):
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
Represents a wrapped value as a node within an expression
|
|
|
|
"""
|
|
|
|
def __init__(self, value, output_field=None):
|
|
|
|
"""
|
|
|
|
Arguments:
|
|
|
|
* value: the value this expression represents. The value will be
|
|
|
|
added into the sql parameter list and properly quoted.
|
|
|
|
|
|
|
|
* output_field: an instance of the model field type that this
|
|
|
|
expression will return, such as IntegerField() or CharField().
|
|
|
|
"""
|
|
|
|
super(Value, self).__init__(output_field=output_field)
|
|
|
|
self.value = value
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "{}({})".format(self.__class__.__name__, self.value)
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def as_sql(self, compiler, connection):
|
2015-01-17 13:03:46 +08:00
|
|
|
connection.ops.check_expression_support(self)
|
2015-01-02 09:39:31 +08:00
|
|
|
val = self.value
|
|
|
|
# check _output_field to avoid triggering an exception
|
|
|
|
if self._output_field is not None:
|
|
|
|
if self.for_save:
|
|
|
|
val = self.output_field.get_db_prep_save(val, connection=connection)
|
|
|
|
else:
|
|
|
|
val = self.output_field.get_db_prep_value(val, connection=connection)
|
|
|
|
if val is None:
|
2015-01-07 18:30:25 +08:00
|
|
|
# cx_Oracle does not always convert None to the appropriate
|
|
|
|
# NULL type (like in case expressions using numbers), so we
|
|
|
|
# use a literal SQL NULL
|
|
|
|
return 'NULL', []
|
2015-01-02 09:39:31 +08:00
|
|
|
return '%s', [val]
|
|
|
|
|
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
|
|
|
c = super(Value, self).resolve_expression(query, allow_joins, reuse, summarize, for_save)
|
|
|
|
c.for_save = for_save
|
|
|
|
return c
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
def get_group_by_cols(self):
|
|
|
|
return []
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2014-07-24 20:57:24 +08:00
|
|
|
class DurationValue(Value):
|
|
|
|
def as_sql(self, compiler, connection):
|
2015-01-17 13:03:46 +08:00
|
|
|
connection.ops.check_expression_support(self)
|
2014-12-21 22:36:37 +08:00
|
|
|
if (connection.features.has_native_duration_field and
|
|
|
|
connection.features.driver_supports_timedelta_args):
|
2014-07-24 20:57:24 +08:00
|
|
|
return super(DurationValue, self).as_sql(compiler, connection)
|
|
|
|
return connection.ops.date_interval_sql(self.value)
|
|
|
|
|
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class RawSQL(Expression):
|
2014-12-01 15:28:01 +08:00
|
|
|
def __init__(self, sql, params, output_field=None):
|
|
|
|
if output_field is None:
|
|
|
|
output_field = fields.Field()
|
|
|
|
self.sql, self.params = sql, params
|
|
|
|
super(RawSQL, self).__init__(output_field=output_field)
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "{}({}, {})".format(self.__class__.__name__, self.sql, self.params)
|
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
return '(%s)' % self.sql, self.params
|
|
|
|
|
|
|
|
def get_group_by_cols(self):
|
|
|
|
return [self]
|
|
|
|
|
|
|
|
|
2015-09-11 00:07:09 +08:00
|
|
|
class Star(Expression):
|
|
|
|
def __repr__(self):
|
|
|
|
return "'*'"
|
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
return '*', []
|
|
|
|
|
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class Random(Expression):
|
2014-12-01 15:28:01 +08:00
|
|
|
def __init__(self):
|
|
|
|
super(Random, self).__init__(output_field=fields.FloatField())
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "Random()"
|
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
return connection.ops.random_function_sql(), []
|
|
|
|
|
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class Col(Expression):
|
2015-08-03 22:34:19 +08:00
|
|
|
|
|
|
|
contains_column_references = True
|
|
|
|
|
2015-02-15 03:37:12 +08:00
|
|
|
def __init__(self, alias, target, output_field=None):
|
|
|
|
if output_field is None:
|
|
|
|
output_field = target
|
|
|
|
super(Col, self).__init__(output_field=output_field)
|
2013-12-25 21:13:18 +08:00
|
|
|
self.alias, self.target = alias, target
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "{}({}, {})".format(
|
|
|
|
self.__class__.__name__, self.alias, self.target)
|
|
|
|
|
2014-11-16 09:56:42 +08:00
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
qn = compiler.quote_name_unless_alias
|
2013-12-25 21:13:18 +08:00
|
|
|
return "%s.%s" % (qn(self.alias), qn(self.target.column)), []
|
|
|
|
|
|
|
|
def relabeled_clone(self, relabels):
|
|
|
|
return self.__class__(relabels.get(self.alias, self.alias), self.target, self.output_field)
|
|
|
|
|
|
|
|
def get_group_by_cols(self):
|
2014-12-18 17:02:43 +08:00
|
|
|
return [self]
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
def get_db_converters(self, connection):
|
2015-02-15 03:37:12 +08:00
|
|
|
if self.target == self.output_field:
|
|
|
|
return self.output_field.get_db_converters(connection)
|
|
|
|
return (self.output_field.get_db_converters(connection) +
|
|
|
|
self.target.get_db_converters(connection))
|
2014-12-01 15:28:01 +08:00
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class Ref(Expression):
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
Reference to column alias of the query. For example, Ref('sum_cost') in
|
|
|
|
qs.annotate(sum_cost=Sum('cost')) query.
|
|
|
|
"""
|
|
|
|
def __init__(self, refs, source):
|
|
|
|
super(Ref, self).__init__()
|
2015-01-27 10:40:32 +08:00
|
|
|
self.refs, self.source = refs, source
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "{}({}, {})".format(self.__class__.__name__, self.refs, self.source)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
def get_source_expressions(self):
|
|
|
|
return [self.source]
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
self.source, = exprs
|
|
|
|
|
2015-03-05 14:10:48 +08:00
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
|
|
|
# The sub-expression `source` has already been resolved, as this is
|
|
|
|
# just a reference to the name of `source`.
|
|
|
|
return self
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def relabeled_clone(self, relabels):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
2014-12-01 15:28:01 +08:00
|
|
|
return "%s" % connection.ops.quote_name(self.refs), []
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
def get_group_by_cols(self):
|
2014-12-18 17:02:43 +08:00
|
|
|
return [self]
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
|
2015-03-19 11:07:53 +08:00
|
|
|
class ExpressionWrapper(Expression):
|
|
|
|
"""
|
|
|
|
An expression that can wrap another expression so that it can provide
|
|
|
|
extra context to the inner expression, such as the output_field.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, expression, output_field):
|
|
|
|
super(ExpressionWrapper, self).__init__(output_field=output_field)
|
|
|
|
self.expression = expression
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
self.expression = exprs[0]
|
|
|
|
|
|
|
|
def get_source_expressions(self):
|
|
|
|
return [self.expression]
|
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
return self.expression.as_sql(compiler, connection)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "{}({})".format(self.__class__.__name__, self.expression)
|
|
|
|
|
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class When(Expression):
|
2015-01-02 09:39:31 +08:00
|
|
|
template = 'WHEN %(condition)s THEN %(result)s'
|
|
|
|
|
2015-02-11 13:38:02 +08:00
|
|
|
def __init__(self, condition=None, then=None, **lookups):
|
2015-01-02 09:39:31 +08:00
|
|
|
if lookups and condition is None:
|
|
|
|
condition, lookups = Q(**lookups), None
|
|
|
|
if condition is None or not isinstance(condition, Q) or lookups:
|
|
|
|
raise TypeError("__init__() takes either a Q object or lookups as keyword arguments")
|
|
|
|
super(When, self).__init__(output_field=None)
|
|
|
|
self.condition = condition
|
2015-02-11 13:38:02 +08:00
|
|
|
self.result = self._parse_expressions(then)[0]
|
2015-01-02 09:39:31 +08:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return "WHEN %r THEN %r" % (self.condition, self.result)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "<%s: %s>" % (self.__class__.__name__, self)
|
|
|
|
|
|
|
|
def get_source_expressions(self):
|
|
|
|
return [self.condition, self.result]
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
self.condition, self.result = exprs
|
|
|
|
|
|
|
|
def get_source_fields(self):
|
|
|
|
# We're only interested in the fields of the result expressions.
|
|
|
|
return [self.result._output_field_or_none]
|
|
|
|
|
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
|
|
|
c = self.copy()
|
|
|
|
c.is_summary = summarize
|
2015-12-24 23:42:49 +08:00
|
|
|
if hasattr(c.condition, 'resolve_expression'):
|
|
|
|
c.condition = c.condition.resolve_expression(query, allow_joins, reuse, summarize, False)
|
2015-01-02 09:39:31 +08:00
|
|
|
c.result = c.result.resolve_expression(query, allow_joins, reuse, summarize, for_save)
|
|
|
|
return c
|
|
|
|
|
2016-02-16 04:42:24 +08:00
|
|
|
def as_sql(self, compiler, connection, template=None, **extra_context):
|
2015-01-17 13:03:46 +08:00
|
|
|
connection.ops.check_expression_support(self)
|
2016-02-16 04:42:24 +08:00
|
|
|
template_params = extra_context
|
2015-01-02 09:39:31 +08:00
|
|
|
sql_params = []
|
|
|
|
condition_sql, condition_params = compiler.compile(self.condition)
|
|
|
|
template_params['condition'] = condition_sql
|
|
|
|
sql_params.extend(condition_params)
|
|
|
|
result_sql, result_params = compiler.compile(self.result)
|
|
|
|
template_params['result'] = result_sql
|
|
|
|
sql_params.extend(result_params)
|
|
|
|
template = template or self.template
|
|
|
|
return template % template_params, sql_params
|
|
|
|
|
|
|
|
def get_group_by_cols(self):
|
|
|
|
# This is not a complete expression and cannot be used in GROUP BY.
|
|
|
|
cols = []
|
|
|
|
for source in self.get_source_expressions():
|
|
|
|
cols.extend(source.get_group_by_cols())
|
|
|
|
return cols
|
|
|
|
|
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class Case(Expression):
|
2015-01-02 09:39:31 +08:00
|
|
|
"""
|
|
|
|
An SQL searched CASE expression:
|
|
|
|
|
|
|
|
CASE
|
|
|
|
WHEN n > 0
|
|
|
|
THEN 'positive'
|
|
|
|
WHEN n < 0
|
|
|
|
THEN 'negative'
|
|
|
|
ELSE 'zero'
|
|
|
|
END
|
|
|
|
"""
|
|
|
|
template = 'CASE %(cases)s ELSE %(default)s END'
|
|
|
|
case_joiner = ' '
|
|
|
|
|
|
|
|
def __init__(self, *cases, **extra):
|
|
|
|
if not all(isinstance(case, When) for case in cases):
|
|
|
|
raise TypeError("Positional arguments must all be When objects.")
|
2015-02-11 13:38:02 +08:00
|
|
|
default = extra.pop('default', None)
|
2015-01-02 09:39:31 +08:00
|
|
|
output_field = extra.pop('output_field', None)
|
|
|
|
super(Case, self).__init__(output_field)
|
|
|
|
self.cases = list(cases)
|
2015-02-11 13:38:02 +08:00
|
|
|
self.default = self._parse_expressions(default)[0]
|
2016-02-16 04:42:24 +08:00
|
|
|
self.extra = extra
|
2015-01-02 09:39:31 +08:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return "CASE %s, ELSE %r" % (', '.join(str(c) for c in self.cases), self.default)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "<%s: %s>" % (self.__class__.__name__, self)
|
|
|
|
|
|
|
|
def get_source_expressions(self):
|
|
|
|
return self.cases + [self.default]
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
self.cases = exprs[:-1]
|
|
|
|
self.default = exprs[-1]
|
|
|
|
|
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
|
|
|
c = self.copy()
|
|
|
|
c.is_summary = summarize
|
|
|
|
for pos, case in enumerate(c.cases):
|
|
|
|
c.cases[pos] = case.resolve_expression(query, allow_joins, reuse, summarize, for_save)
|
|
|
|
c.default = c.default.resolve_expression(query, allow_joins, reuse, summarize, for_save)
|
|
|
|
return c
|
|
|
|
|
2015-05-05 19:11:58 +08:00
|
|
|
def copy(self):
|
|
|
|
c = super(Case, self).copy()
|
|
|
|
c.cases = c.cases[:]
|
|
|
|
return c
|
|
|
|
|
2016-02-16 04:42:24 +08:00
|
|
|
def as_sql(self, compiler, connection, template=None, case_joiner=None, **extra_context):
|
2015-01-17 13:03:46 +08:00
|
|
|
connection.ops.check_expression_support(self)
|
2015-01-02 09:39:31 +08:00
|
|
|
if not self.cases:
|
|
|
|
return compiler.compile(self.default)
|
2016-02-16 04:42:24 +08:00
|
|
|
template_params = self.extra.copy()
|
|
|
|
template_params.update(extra_context)
|
2015-01-02 09:39:31 +08:00
|
|
|
case_parts = []
|
|
|
|
sql_params = []
|
|
|
|
for case in self.cases:
|
|
|
|
case_sql, case_params = compiler.compile(case)
|
|
|
|
case_parts.append(case_sql)
|
|
|
|
sql_params.extend(case_params)
|
2016-02-16 04:42:24 +08:00
|
|
|
case_joiner = case_joiner or self.case_joiner
|
|
|
|
template_params['cases'] = case_joiner.join(case_parts)
|
2015-01-02 09:39:31 +08:00
|
|
|
default_sql, default_params = compiler.compile(self.default)
|
|
|
|
template_params['default'] = default_sql
|
|
|
|
sql_params.extend(default_params)
|
2016-02-16 04:42:24 +08:00
|
|
|
template = template or template_params.get('template', self.template)
|
2015-01-02 09:39:31 +08:00
|
|
|
sql = template % template_params
|
|
|
|
if self._output_field_or_none is not None:
|
|
|
|
sql = connection.ops.unification_cast_sql(self.output_field) % sql
|
|
|
|
return sql, sql_params
|
|
|
|
|
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class Date(Expression):
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
Add a date selection column.
|
|
|
|
"""
|
2014-11-18 17:24:33 +08:00
|
|
|
def __init__(self, lookup, lookup_type):
|
2013-12-25 21:13:18 +08:00
|
|
|
super(Date, self).__init__(output_field=fields.DateField())
|
2014-11-18 17:24:33 +08:00
|
|
|
self.lookup = lookup
|
|
|
|
self.col = None
|
2013-12-25 21:13:18 +08:00
|
|
|
self.lookup_type = lookup_type
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "{}({}, {})".format(self.__class__.__name__, self.lookup, self.lookup_type)
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def get_source_expressions(self):
|
|
|
|
return [self.col]
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
2014-11-18 17:24:33 +08:00
|
|
|
self.col, = exprs
|
|
|
|
|
2015-01-02 09:39:31 +08:00
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
2014-11-18 17:24:33 +08:00
|
|
|
copy = self.copy()
|
|
|
|
copy.col = query.resolve_ref(self.lookup, allow_joins, reuse, summarize)
|
|
|
|
field = copy.col.output_field
|
|
|
|
assert isinstance(field, fields.DateField), "%r isn't a DateField." % field.name
|
|
|
|
if settings.USE_TZ:
|
|
|
|
assert not isinstance(field, fields.DateTimeField), (
|
|
|
|
"%r is a DateTimeField, not a DateField." % field.name
|
|
|
|
)
|
|
|
|
return copy
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2014-11-16 09:56:42 +08:00
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
sql, params = self.col.as_sql(compiler, connection)
|
2013-12-25 21:13:18 +08:00
|
|
|
assert not(params)
|
|
|
|
return connection.ops.date_trunc_sql(self.lookup_type, sql), []
|
|
|
|
|
2014-11-18 17:24:33 +08:00
|
|
|
def copy(self):
|
|
|
|
copy = super(Date, self).copy()
|
|
|
|
copy.lookup = self.lookup
|
|
|
|
copy.lookup_type = self.lookup_type
|
|
|
|
return copy
|
|
|
|
|
2015-02-20 18:53:59 +08:00
|
|
|
def convert_value(self, value, expression, connection, context):
|
2014-11-18 17:24:33 +08:00
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
value = value.date()
|
|
|
|
return value
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2015-03-17 08:38:55 +08:00
|
|
|
class DateTime(Expression):
|
2013-12-25 21:13:18 +08:00
|
|
|
"""
|
|
|
|
Add a datetime selection column.
|
|
|
|
"""
|
2014-11-18 17:24:33 +08:00
|
|
|
def __init__(self, lookup, lookup_type, tzinfo):
|
2013-12-25 21:13:18 +08:00
|
|
|
super(DateTime, self).__init__(output_field=fields.DateTimeField())
|
2014-11-18 17:24:33 +08:00
|
|
|
self.lookup = lookup
|
|
|
|
self.col = None
|
2013-12-25 21:13:18 +08:00
|
|
|
self.lookup_type = lookup_type
|
2014-11-18 17:24:33 +08:00
|
|
|
if tzinfo is None:
|
|
|
|
self.tzname = None
|
|
|
|
else:
|
|
|
|
self.tzname = timezone._get_timezone_name(tzinfo)
|
|
|
|
self.tzinfo = tzinfo
|
2013-12-25 21:13:18 +08:00
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "{}({}, {}, {})".format(
|
|
|
|
self.__class__.__name__, self.lookup, self.lookup_type, self.tzinfo)
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
def get_source_expressions(self):
|
|
|
|
return [self.col]
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
self.col, = exprs
|
|
|
|
|
2015-01-02 09:39:31 +08:00
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
2014-11-18 17:24:33 +08:00
|
|
|
copy = self.copy()
|
|
|
|
copy.col = query.resolve_ref(self.lookup, allow_joins, reuse, summarize)
|
|
|
|
field = copy.col.output_field
|
|
|
|
assert isinstance(field, fields.DateTimeField), (
|
|
|
|
"%r isn't a DateTimeField." % field.name
|
|
|
|
)
|
|
|
|
return copy
|
|
|
|
|
2014-11-16 09:56:42 +08:00
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
sql, params = self.col.as_sql(compiler, connection)
|
2013-12-25 21:13:18 +08:00
|
|
|
assert not(params)
|
|
|
|
return connection.ops.datetime_trunc_sql(self.lookup_type, sql, self.tzname)
|
2014-11-18 17:24:33 +08:00
|
|
|
|
|
|
|
def copy(self):
|
|
|
|
copy = super(DateTime, self).copy()
|
|
|
|
copy.lookup = self.lookup
|
|
|
|
copy.lookup_type = self.lookup_type
|
|
|
|
copy.tzname = self.tzname
|
|
|
|
return copy
|
|
|
|
|
2015-02-20 18:53:59 +08:00
|
|
|
def convert_value(self, value, expression, connection, context):
|
2014-11-18 17:24:33 +08:00
|
|
|
if settings.USE_TZ:
|
|
|
|
if value is None:
|
|
|
|
raise ValueError(
|
|
|
|
"Database returned an invalid value in QuerySet.datetimes(). "
|
|
|
|
"Are time zone definitions for your database and pytz installed?"
|
|
|
|
)
|
|
|
|
value = value.replace(tzinfo=None)
|
|
|
|
value = timezone.make_aware(value, self.tzinfo)
|
|
|
|
return value
|
2015-01-09 23:16:16 +08:00
|
|
|
|
|
|
|
|
|
|
|
class OrderBy(BaseExpression):
|
|
|
|
template = '%(expression)s %(ordering)s'
|
|
|
|
|
|
|
|
def __init__(self, expression, descending=False):
|
|
|
|
self.descending = descending
|
|
|
|
if not hasattr(expression, 'resolve_expression'):
|
|
|
|
raise ValueError('expression must be an expression type')
|
|
|
|
self.expression = expression
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "{}({}, descending={})".format(
|
|
|
|
self.__class__.__name__, self.expression, self.descending)
|
|
|
|
|
2015-01-09 23:16:16 +08:00
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
self.expression = exprs[0]
|
|
|
|
|
|
|
|
def get_source_expressions(self):
|
|
|
|
return [self.expression]
|
|
|
|
|
2016-02-16 04:42:24 +08:00
|
|
|
def as_sql(self, compiler, connection, template=None, **extra_context):
|
2015-01-17 13:03:46 +08:00
|
|
|
connection.ops.check_expression_support(self)
|
2015-01-09 23:16:16 +08:00
|
|
|
expression_sql, params = compiler.compile(self.expression)
|
2015-11-07 18:46:22 +08:00
|
|
|
placeholders = {
|
|
|
|
'expression': expression_sql,
|
|
|
|
'ordering': 'DESC' if self.descending else 'ASC',
|
|
|
|
}
|
2016-02-16 04:42:24 +08:00
|
|
|
placeholders.update(extra_context)
|
|
|
|
template = template or self.template
|
|
|
|
return (template % placeholders).rstrip(), params
|
2015-01-09 23:16:16 +08:00
|
|
|
|
|
|
|
def get_group_by_cols(self):
|
|
|
|
cols = []
|
|
|
|
for source in self.get_source_expressions():
|
|
|
|
cols.extend(source.get_group_by_cols())
|
|
|
|
return cols
|
|
|
|
|
|
|
|
def reverse_ordering(self):
|
|
|
|
self.descending = not self.descending
|
|
|
|
return self
|
|
|
|
|
|
|
|
def asc(self):
|
|
|
|
self.descending = False
|
|
|
|
|
|
|
|
def desc(self):
|
|
|
|
self.descending = True
|