2013-12-25 21:13:18 +08:00
|
|
|
|
import copy
|
2010-12-22 11:34:04 +08:00
|
|
|
|
import datetime
|
2019-05-13 05:17:47 +08:00
|
|
|
|
import functools
|
2018-10-03 07:15:20 +08:00
|
|
|
|
import inspect
|
2022-05-12 17:30:03 +08:00
|
|
|
|
import warnings
|
2022-03-31 14:10:22 +08:00
|
|
|
|
from collections import defaultdict
|
2017-08-11 21:22:40 +08:00
|
|
|
|
from decimal import Decimal
|
2019-05-13 05:17:47 +08:00
|
|
|
|
from uuid import UUID
|
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
|
|
|
|
|
2016-05-26 03:00:20 +08:00
|
|
|
|
from django.core.exceptions import EmptyResultSet, FieldError
|
2021-04-07 00:14:16 +08:00
|
|
|
|
from django.db import DatabaseError, NotSupportedError, connection
|
2013-12-25 21:13:18 +08:00
|
|
|
|
from django.db.models import fields
|
2020-03-02 20:20:36 +08:00
|
|
|
|
from django.db.models.constants import LOOKUP_SEP
|
2016-04-15 19:37:50 +08:00
|
|
|
|
from django.db.models.query_utils import Q
|
2016-11-05 23:49:29 +08:00
|
|
|
|
from django.utils.deconstruct import deconstructible
|
2022-05-12 17:30:03 +08:00
|
|
|
|
from django.utils.deprecation import RemovedInDjango50Warning
|
2013-12-25 21:13:18 +08:00
|
|
|
|
from django.utils.functional import cached_property
|
2018-10-16 23:01:31 +08:00
|
|
|
|
from django.utils.hashable import make_hashable
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
|
2017-08-11 05:42:30 +08:00
|
|
|
|
class SQLiteNumericMixin:
|
|
|
|
|
"""
|
|
|
|
|
Some expressions with output_field=DecimalField() must be cast to
|
|
|
|
|
numeric to be properly filtered.
|
|
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
|
2017-08-11 05:42:30 +08:00
|
|
|
|
def as_sqlite(self, compiler, connection, **extra_context):
|
|
|
|
|
sql, params = self.as_sql(compiler, connection, **extra_context)
|
2017-09-07 20:16:21 +08:00
|
|
|
|
try:
|
2017-08-11 05:42:30 +08:00
|
|
|
|
if self.output_field.get_internal_type() == "DecimalField":
|
|
|
|
|
sql = "CAST(%s AS NUMERIC)" % sql
|
2017-09-07 20:16:21 +08:00
|
|
|
|
except FieldError:
|
|
|
|
|
pass
|
2017-08-11 05:42:30 +08:00
|
|
|
|
return sql, params
|
|
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
|
class Combinable:
|
2009-01-29 18:46:36 +08:00
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
|
Provide the ability to combine one or two objects with
|
2013-12-25 21:13:18 +08:00
|
|
|
|
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 = "|"
|
2015-12-15 03:13:21 +08:00
|
|
|
|
BITLEFTSHIFT = "<<"
|
|
|
|
|
BITRIGHTSHIFT = ">>"
|
2020-03-21 06:08:32 +08:00
|
|
|
|
BITXOR = "#"
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
2017-08-03 09:21:32 +08:00
|
|
|
|
def _combine(self, other, connector, reversed):
|
2013-12-25 21:13:18 +08:00
|
|
|
|
if not hasattr(other, "resolve_expression"):
|
|
|
|
|
# everything must be resolvable to an expression
|
2019-05-13 05:17:47 +08:00
|
|
|
|
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 #
|
|
|
|
|
#############
|
|
|
|
|
|
2018-01-28 18:27:15 +08:00
|
|
|
|
def __neg__(self):
|
|
|
|
|
return self._combine(-1, self.MUL, False)
|
|
|
|
|
|
2009-01-29 18:46:36 +08:00
|
|
|
|
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
|
|
|
|
|
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):
|
2017-02-27 17:01:52 +08:00
|
|
|
|
if getattr(self, "conditional", False) and getattr(other, "conditional", False):
|
|
|
|
|
return Q(self) & Q(other)
|
2012-10-03 23:53:40 +08:00
|
|
|
|
raise NotImplementedError(
|
2021-07-03 04:09:13 +08:00
|
|
|
|
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
|
2012-10-03 23:53:40 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def bitand(self, other):
|
|
|
|
|
return self._combine(other, self.BITAND, False)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
2015-12-15 03:13:21 +08:00
|
|
|
|
def bitleftshift(self, other):
|
|
|
|
|
return self._combine(other, self.BITLEFTSHIFT, False)
|
|
|
|
|
|
|
|
|
|
def bitrightshift(self, other):
|
|
|
|
|
return self._combine(other, self.BITRIGHTSHIFT, False)
|
|
|
|
|
|
2021-07-03 04:09:13 +08:00
|
|
|
|
def __xor__(self, other):
|
|
|
|
|
if getattr(self, "conditional", False) and getattr(other, "conditional", False):
|
|
|
|
|
return Q(self) ^ Q(other)
|
|
|
|
|
raise NotImplementedError(
|
|
|
|
|
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
|
|
|
|
|
)
|
|
|
|
|
|
2020-03-21 06:08:32 +08:00
|
|
|
|
def bitxor(self, other):
|
|
|
|
|
return self._combine(other, self.BITXOR, False)
|
|
|
|
|
|
2009-01-29 18:46:36 +08:00
|
|
|
|
def __or__(self, other):
|
2017-02-27 17:01:52 +08:00
|
|
|
|
if getattr(self, "conditional", False) and getattr(other, "conditional", False):
|
|
|
|
|
return Q(self) | Q(other)
|
2012-10-03 23:53:40 +08:00
|
|
|
|
raise NotImplementedError(
|
2021-07-03 04:09:13 +08:00
|
|
|
|
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
|
2012-10-03 23:53:40 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
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(
|
2021-07-03 04:09:13 +08:00
|
|
|
|
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
|
2012-10-03 23:53:40 +08:00
|
|
|
|
)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
|
|
|
|
def __ror__(self, other):
|
2012-10-03 23:53:40 +08:00
|
|
|
|
raise NotImplementedError(
|
2021-07-03 04:09:13 +08:00
|
|
|
|
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def __rxor__(self, other):
|
|
|
|
|
raise NotImplementedError(
|
|
|
|
|
"Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations."
|
2012-10-03 23:53:40 +08:00
|
|
|
|
)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
|
class BaseExpression:
|
2017-01-25 07:04:12 +08:00
|
|
|
|
"""Base class for all query expressions."""
|
2009-01-29 18:46:36 +08:00
|
|
|
|
|
2021-09-25 04:05:02 +08:00
|
|
|
|
empty_result_set_value = NotImplemented
|
2013-12-25 21:13:18 +08:00
|
|
|
|
# aggregate specific fields
|
|
|
|
|
is_summary = False
|
2017-07-15 09:56:01 +08:00
|
|
|
|
_output_field_resolved_to_none = False
|
2017-09-18 21:42:29 +08:00
|
|
|
|
# Can the expression be used in a WHERE clause?
|
|
|
|
|
filterable = True
|
|
|
|
|
# Can the expression can be used as a source expression in Window?
|
|
|
|
|
window_compatible = False
|
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:
|
2017-07-15 09:56:01 +08:00
|
|
|
|
self.output_field = output_field
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
2018-04-16 21:10:13 +08:00
|
|
|
|
def __getstate__(self):
|
|
|
|
|
state = self.__dict__.copy()
|
|
|
|
|
state.pop("convert_value", None)
|
|
|
|
|
return state
|
|
|
|
|
|
2015-03-19 11:07:53 +08:00
|
|
|
|
def get_db_converters(self, connection):
|
2017-08-12 06:34:50 +08:00
|
|
|
|
return (
|
|
|
|
|
[]
|
|
|
|
|
if self.convert_value is self._convert_value_noop
|
|
|
|
|
else [self.convert_value]
|
|
|
|
|
) + self.output_field.get_db_converters(connection)
|
2015-03-19 11:07:53 +08:00
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
def get_source_expressions(self):
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
2017-11-30 00:54:34 +08:00
|
|
|
|
assert not exprs
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
2015-02-11 13:38:02 +08:00
|
|
|
|
def _parse_expressions(self, *expressions):
|
|
|
|
|
return [
|
|
|
|
|
arg
|
|
|
|
|
if hasattr(arg, "resolve_expression")
|
2016-12-29 23:27:49 +08:00
|
|
|
|
else (F(arg) if isinstance(arg, str) else Value(arg))
|
2015-02-11 13:38:02 +08:00
|
|
|
|
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
|
2017-01-21 21:13:44 +08:00
|
|
|
|
return super().as_sql(compiler, connection)
|
2015-03-17 08:38:55 +08:00
|
|
|
|
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.
|
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
|
Return: (sql, params)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
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):
|
2017-12-27 02:44:12 +08:00
|
|
|
|
return any(
|
|
|
|
|
expr and expr.contains_aggregate for expr in self.get_source_expressions()
|
2022-02-04 03:24:19 +08:00
|
|
|
|
)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
2017-09-18 21:42:29 +08:00
|
|
|
|
@cached_property
|
|
|
|
|
def contains_over_clause(self):
|
2017-12-27 02:44:12 +08:00
|
|
|
|
return any(
|
|
|
|
|
expr and expr.contains_over_clause for expr in self.get_source_expressions()
|
2022-02-04 03:24:19 +08:00
|
|
|
|
)
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
2015-08-03 22:34:19 +08:00
|
|
|
|
@cached_property
|
|
|
|
|
def contains_column_references(self):
|
2017-12-27 02:44:12 +08:00
|
|
|
|
return any(
|
|
|
|
|
expr and expr.contains_column_references
|
|
|
|
|
for expr in self.get_source_expressions()
|
2022-02-04 03:24:19 +08:00
|
|
|
|
)
|
2015-08-03 22:34:19 +08:00
|
|
|
|
|
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
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
|
Provide the chance to do any preprocessing or validation before being
|
2013-12-25 21:13:18 +08:00
|
|
|
|
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
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
|
Return: 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)
|
2017-09-18 21:42:29 +08:00
|
|
|
|
if expr
|
|
|
|
|
else None
|
2015-01-09 23:16:16 +08:00
|
|
|
|
for expr in c.get_source_expressions()
|
|
|
|
|
]
|
|
|
|
|
)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
return c
|
|
|
|
|
|
2017-02-27 17:01:52 +08:00
|
|
|
|
@property
|
|
|
|
|
def conditional(self):
|
|
|
|
|
return isinstance(self.output_field, fields.BooleanField)
|
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
@property
|
|
|
|
|
def field(self):
|
|
|
|
|
return self.output_field
|
|
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
|
def output_field(self):
|
2017-01-25 07:04:12 +08:00
|
|
|
|
"""Return the output type of this expressions."""
|
2017-07-15 09:56:01 +08:00
|
|
|
|
output_field = self._resolve_output_field()
|
|
|
|
|
if output_field is None:
|
|
|
|
|
self._output_field_resolved_to_none = True
|
|
|
|
|
raise FieldError("Cannot resolve expression type, unknown output_field")
|
|
|
|
|
return output_field
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
|
def _output_field_or_none(self):
|
|
|
|
|
"""
|
2017-07-15 09:56:01 +08:00
|
|
|
|
Return the output field of this expression, or None if
|
|
|
|
|
_resolve_output_field() didn't return an output type.
|
2013-12-25 21:13:18 +08:00
|
|
|
|
"""
|
2017-07-15 09:56:01 +08:00
|
|
|
|
try:
|
|
|
|
|
return self.output_field
|
|
|
|
|
except FieldError:
|
|
|
|
|
if not self._output_field_resolved_to_none:
|
|
|
|
|
raise
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
|
|
def _resolve_output_field(self):
|
|
|
|
|
"""
|
2021-12-29 22:00:50 +08:00
|
|
|
|
Attempt to infer the output type of the expression.
|
2015-03-20 12:47:43 +08:00
|
|
|
|
|
2021-12-29 22:00:50 +08:00
|
|
|
|
As a guess, if the output fields of all source fields match then simply
|
|
|
|
|
infer the same type here.
|
2015-03-20 12:47:43 +08:00
|
|
|
|
|
2017-07-15 09:56:01 +08:00
|
|
|
|
If a source's output field resolves to None, exclude it from this check.
|
|
|
|
|
If all sources are None, then an error is raised higher up the stack in
|
|
|
|
|
the output_field property.
|
2013-12-25 21:13:18 +08:00
|
|
|
|
"""
|
2021-12-29 22:00:50 +08:00
|
|
|
|
# This guess is mostly a bad idea, but there is quite a lot of code
|
|
|
|
|
# (especially 3rd party Func subclasses) that depend on it, we'd need a
|
|
|
|
|
# deprecation path to fix it.
|
2017-07-07 12:04:37 +08:00
|
|
|
|
sources_iter = (
|
|
|
|
|
source for source in self.get_source_fields() if source is not None
|
|
|
|
|
)
|
|
|
|
|
for output_field in sources_iter:
|
2019-06-10 06:02:40 +08:00
|
|
|
|
for source in sources_iter:
|
|
|
|
|
if not isinstance(output_field, source.__class__):
|
|
|
|
|
raise FieldError(
|
|
|
|
|
"Expression contains mixed types: %s, %s. You must "
|
|
|
|
|
"set output_field."
|
|
|
|
|
% (
|
|
|
|
|
output_field.__class__.__name__,
|
|
|
|
|
source.__class__.__name__,
|
|
|
|
|
)
|
|
|
|
|
)
|
2017-07-07 12:04:37 +08:00
|
|
|
|
return output_field
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
2017-08-12 06:34:50 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
def _convert_value_noop(value, expression, connection):
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
|
def convert_value(self):
|
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()
|
2017-08-12 06:34:50 +08:00
|
|
|
|
if internal_type == "FloatField":
|
|
|
|
|
return (
|
|
|
|
|
lambda value, expression, connection: None
|
|
|
|
|
if value is None
|
|
|
|
|
else float(value)
|
2022-02-04 03:24:19 +08:00
|
|
|
|
)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
elif internal_type.endswith("IntegerField"):
|
2017-08-12 06:34:50 +08:00
|
|
|
|
return (
|
|
|
|
|
lambda value, expression, connection: None
|
|
|
|
|
if value is None
|
|
|
|
|
else int(value)
|
2022-02-04 03:24:19 +08:00
|
|
|
|
)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
elif internal_type == "DecimalField":
|
2017-08-12 06:34:50 +08:00
|
|
|
|
return (
|
|
|
|
|
lambda value, expression, connection: None
|
|
|
|
|
if value is None
|
|
|
|
|
else Decimal(value)
|
2022-02-04 03:24:19 +08:00
|
|
|
|
)
|
2017-08-12 06:34:50 +08:00
|
|
|
|
return self._convert_value_noop
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
|
|
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()
|
2018-03-01 15:55:05 +08:00
|
|
|
|
clone.set_source_expressions(
|
|
|
|
|
[
|
|
|
|
|
e.relabeled_clone(change_map) if e is not None else None
|
|
|
|
|
for e in self.get_source_expressions()
|
|
|
|
|
]
|
|
|
|
|
)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
return clone
|
|
|
|
|
|
2022-08-10 19:51:07 +08:00
|
|
|
|
def replace_expressions(self, replacements):
|
|
|
|
|
if replacement := replacements.get(self):
|
|
|
|
|
return replacement
|
2022-01-31 23:04:13 +08:00
|
|
|
|
clone = self.copy()
|
2022-08-10 19:51:07 +08:00
|
|
|
|
source_expressions = clone.get_source_expressions()
|
2022-01-31 23:04:13 +08:00
|
|
|
|
clone.set_source_expressions(
|
|
|
|
|
[
|
2022-08-10 19:51:07 +08:00
|
|
|
|
expr.replace_expressions(replacements) if expr else None
|
|
|
|
|
for expr in source_expressions
|
2022-01-31 23:04:13 +08:00
|
|
|
|
]
|
|
|
|
|
)
|
|
|
|
|
return clone
|
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
def copy(self):
|
2017-07-13 14:51:24 +08:00
|
|
|
|
return copy.copy(self)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
2022-05-05 08:10:53 +08:00
|
|
|
|
def prefix_references(self, prefix):
|
|
|
|
|
clone = self.copy()
|
|
|
|
|
clone.set_source_expressions(
|
|
|
|
|
[
|
|
|
|
|
F(f"{prefix}{expr.name}")
|
|
|
|
|
if isinstance(expr, F)
|
|
|
|
|
else expr.prefix_references(prefix)
|
|
|
|
|
for expr in self.get_source_expressions()
|
|
|
|
|
]
|
|
|
|
|
)
|
|
|
|
|
return clone
|
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
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):
|
2017-01-25 07:04:12 +08:00
|
|
|
|
"""Return the underlying field types used by this aggregate."""
|
2013-12-25 21:13:18 +08:00
|
|
|
|
return [e._output_field_or_none for e in self.get_source_expressions()]
|
|
|
|
|
|
2016-07-27 21:17:05 +08:00
|
|
|
|
def asc(self, **kwargs):
|
|
|
|
|
return OrderBy(self, **kwargs)
|
2015-01-09 23:16:16 +08:00
|
|
|
|
|
2016-07-27 21:17:05 +08:00
|
|
|
|
def desc(self, **kwargs):
|
|
|
|
|
return OrderBy(self, descending=True, **kwargs)
|
2015-01-09 23:16:16 +08:00
|
|
|
|
|
|
|
|
|
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:
|
2019-10-11 02:04:17 +08:00
|
|
|
|
if hasattr(expr, "flatten"):
|
|
|
|
|
yield from expr.flatten()
|
|
|
|
|
else:
|
|
|
|
|
yield expr
|
2015-08-03 22:34:19 +08:00
|
|
|
|
|
2019-08-10 02:30:23 +08:00
|
|
|
|
def select_format(self, compiler, sql, params):
|
|
|
|
|
"""
|
|
|
|
|
Custom format for select clauses. For example, EXISTS expressions need
|
|
|
|
|
to be wrapped in CASE WHEN on Oracle.
|
|
|
|
|
"""
|
2020-06-08 13:21:54 +08:00
|
|
|
|
if hasattr(self.output_field, "select_format"):
|
|
|
|
|
return self.output_field.select_format(compiler, sql, params)
|
|
|
|
|
return sql, params
|
2019-08-10 02:30:23 +08:00
|
|
|
|
|
2021-04-24 13:07:18 +08:00
|
|
|
|
|
|
|
|
|
@deconstructible
|
|
|
|
|
class Expression(BaseExpression, Combinable):
|
|
|
|
|
"""An expression that can be combined with other expressions."""
|
|
|
|
|
|
2018-10-03 07:15:20 +08:00
|
|
|
|
@cached_property
|
|
|
|
|
def identity(self):
|
|
|
|
|
constructor_signature = inspect.signature(self.__init__)
|
|
|
|
|
args, kwargs = self._constructor_args
|
|
|
|
|
signature = constructor_signature.bind_partial(*args, **kwargs)
|
|
|
|
|
signature.apply_defaults()
|
|
|
|
|
arguments = signature.arguments.items()
|
|
|
|
|
identity = [self.__class__]
|
|
|
|
|
for arg, value in arguments:
|
|
|
|
|
if isinstance(value, fields.Field):
|
2019-07-10 05:26:37 +08:00
|
|
|
|
if value.name and value.model:
|
|
|
|
|
value = (value.model._meta.label, value.name)
|
|
|
|
|
else:
|
|
|
|
|
value = type(value)
|
2018-10-03 07:15:20 +08:00
|
|
|
|
else:
|
|
|
|
|
value = make_hashable(value)
|
|
|
|
|
identity.append((arg, value))
|
|
|
|
|
return tuple(identity)
|
|
|
|
|
|
2016-11-05 23:49:29 +08:00
|
|
|
|
def __eq__(self, other):
|
2021-04-24 13:07:18 +08:00
|
|
|
|
if not isinstance(other, Expression):
|
2019-09-03 10:09:31 +08:00
|
|
|
|
return NotImplemented
|
|
|
|
|
return other.identity == self.identity
|
2016-11-05 23:49:29 +08:00
|
|
|
|
|
|
|
|
|
def __hash__(self):
|
2018-10-03 07:15:20 +08:00
|
|
|
|
return hash(self.identity)
|
2016-11-05 23:49:29 +08:00
|
|
|
|
|
2015-01-09 23:16:16 +08:00
|
|
|
|
|
2022-03-31 14:10:22 +08:00
|
|
|
|
# Type inference for CombinedExpression.output_field.
|
2021-12-29 22:00:50 +08:00
|
|
|
|
# Missing items will result in FieldError, by design.
|
|
|
|
|
#
|
|
|
|
|
# The current approach for NULL is based on lowest common denominator behavior
|
|
|
|
|
# i.e. if one of the supported databases is raising an error (rather than
|
|
|
|
|
# return NULL) for `val <op> NULL`, then Django raises FieldError.
|
|
|
|
|
NoneType = type(None)
|
|
|
|
|
|
2022-03-31 14:10:22 +08:00
|
|
|
|
_connector_combinations = [
|
|
|
|
|
# Numeric operations - operands of same type.
|
|
|
|
|
{
|
|
|
|
|
connector: [
|
|
|
|
|
(fields.IntegerField, fields.IntegerField, fields.IntegerField),
|
|
|
|
|
(fields.FloatField, fields.FloatField, fields.FloatField),
|
|
|
|
|
(fields.DecimalField, fields.DecimalField, fields.DecimalField),
|
|
|
|
|
]
|
|
|
|
|
for connector in (
|
|
|
|
|
Combinable.ADD,
|
|
|
|
|
Combinable.SUB,
|
|
|
|
|
Combinable.MUL,
|
|
|
|
|
# Behavior for DIV with integer arguments follows Postgres/SQLite,
|
|
|
|
|
# not MySQL/Oracle.
|
|
|
|
|
Combinable.DIV,
|
2021-12-29 22:00:50 +08:00
|
|
|
|
Combinable.MOD,
|
|
|
|
|
Combinable.POW,
|
2022-03-31 14:10:22 +08:00
|
|
|
|
)
|
|
|
|
|
},
|
|
|
|
|
# Numeric operations - operands of different type.
|
|
|
|
|
{
|
|
|
|
|
connector: [
|
|
|
|
|
(fields.IntegerField, fields.DecimalField, fields.DecimalField),
|
|
|
|
|
(fields.DecimalField, fields.IntegerField, fields.DecimalField),
|
|
|
|
|
(fields.IntegerField, fields.FloatField, fields.FloatField),
|
|
|
|
|
(fields.FloatField, fields.IntegerField, fields.FloatField),
|
|
|
|
|
]
|
|
|
|
|
for connector in (
|
|
|
|
|
Combinable.ADD,
|
|
|
|
|
Combinable.SUB,
|
|
|
|
|
Combinable.MUL,
|
|
|
|
|
Combinable.DIV,
|
2022-09-28 02:41:10 +08:00
|
|
|
|
Combinable.MOD,
|
2022-03-31 14:10:22 +08:00
|
|
|
|
)
|
|
|
|
|
},
|
2021-12-29 22:00:50 +08:00
|
|
|
|
# Bitwise operators.
|
|
|
|
|
{
|
|
|
|
|
connector: [
|
|
|
|
|
(fields.IntegerField, fields.IntegerField, fields.IntegerField),
|
|
|
|
|
]
|
|
|
|
|
for connector in (
|
|
|
|
|
Combinable.BITAND,
|
|
|
|
|
Combinable.BITOR,
|
|
|
|
|
Combinable.BITLEFTSHIFT,
|
|
|
|
|
Combinable.BITRIGHTSHIFT,
|
|
|
|
|
Combinable.BITXOR,
|
|
|
|
|
)
|
|
|
|
|
},
|
|
|
|
|
# Numeric with NULL.
|
|
|
|
|
{
|
|
|
|
|
connector: [
|
|
|
|
|
(field_type, NoneType, field_type),
|
|
|
|
|
(NoneType, field_type, field_type),
|
|
|
|
|
]
|
|
|
|
|
for connector in (
|
|
|
|
|
Combinable.ADD,
|
|
|
|
|
Combinable.SUB,
|
|
|
|
|
Combinable.MUL,
|
|
|
|
|
Combinable.DIV,
|
|
|
|
|
Combinable.MOD,
|
|
|
|
|
Combinable.POW,
|
|
|
|
|
)
|
|
|
|
|
for field_type in (fields.IntegerField, fields.DecimalField, fields.FloatField)
|
|
|
|
|
},
|
|
|
|
|
# Date/DateTimeField/DurationField/TimeField.
|
|
|
|
|
{
|
|
|
|
|
Combinable.ADD: [
|
|
|
|
|
# Date/DateTimeField.
|
|
|
|
|
(fields.DateField, fields.DurationField, fields.DateTimeField),
|
|
|
|
|
(fields.DateTimeField, fields.DurationField, fields.DateTimeField),
|
|
|
|
|
(fields.DurationField, fields.DateField, fields.DateTimeField),
|
|
|
|
|
(fields.DurationField, fields.DateTimeField, fields.DateTimeField),
|
|
|
|
|
# DurationField.
|
|
|
|
|
(fields.DurationField, fields.DurationField, fields.DurationField),
|
|
|
|
|
# TimeField.
|
|
|
|
|
(fields.TimeField, fields.DurationField, fields.TimeField),
|
|
|
|
|
(fields.DurationField, fields.TimeField, fields.TimeField),
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
Combinable.SUB: [
|
|
|
|
|
# Date/DateTimeField.
|
|
|
|
|
(fields.DateField, fields.DurationField, fields.DateTimeField),
|
|
|
|
|
(fields.DateTimeField, fields.DurationField, fields.DateTimeField),
|
|
|
|
|
(fields.DateField, fields.DateField, fields.DurationField),
|
|
|
|
|
(fields.DateField, fields.DateTimeField, fields.DurationField),
|
|
|
|
|
(fields.DateTimeField, fields.DateField, fields.DurationField),
|
|
|
|
|
(fields.DateTimeField, fields.DateTimeField, fields.DurationField),
|
|
|
|
|
# DurationField.
|
|
|
|
|
(fields.DurationField, fields.DurationField, fields.DurationField),
|
|
|
|
|
# TimeField.
|
|
|
|
|
(fields.TimeField, fields.DurationField, fields.TimeField),
|
|
|
|
|
(fields.TimeField, fields.TimeField, fields.DurationField),
|
|
|
|
|
],
|
|
|
|
|
},
|
2022-03-31 14:10:22 +08:00
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
_connector_combinators = defaultdict(list)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def register_combinable_fields(lhs, connector, rhs, result):
|
|
|
|
|
"""
|
|
|
|
|
Register combinable types:
|
|
|
|
|
lhs <connector> rhs -> result
|
|
|
|
|
e.g.
|
|
|
|
|
register_combinable_fields(
|
|
|
|
|
IntegerField, Combinable.ADD, FloatField, FloatField
|
|
|
|
|
)
|
|
|
|
|
"""
|
|
|
|
|
_connector_combinators[connector].append((lhs, rhs, result))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
for d in _connector_combinations:
|
|
|
|
|
for connector, field_types in d.items():
|
|
|
|
|
for lhs, rhs, result in field_types:
|
|
|
|
|
register_combinable_fields(lhs, connector, rhs, result)
|
2019-05-13 05:17:47 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@functools.lru_cache(maxsize=128)
|
|
|
|
|
def _resolve_combined_type(connector, lhs_type, rhs_type):
|
|
|
|
|
combinators = _connector_combinators.get(connector, ())
|
|
|
|
|
for combinator_lhs_type, combinator_rhs_type, combined_type in combinators:
|
|
|
|
|
if issubclass(lhs_type, combinator_lhs_type) and issubclass(
|
|
|
|
|
rhs_type, combinator_rhs_type
|
|
|
|
|
):
|
|
|
|
|
return combined_type
|
|
|
|
|
|
|
|
|
|
|
2017-08-11 05:42:30 +08:00
|
|
|
|
class CombinedExpression(SQLiteNumericMixin, Expression):
|
2013-12-25 21:13:18 +08:00
|
|
|
|
def __init__(self, lhs, connector, rhs, output_field=None):
|
2017-01-21 21:13:44 +08:00
|
|
|
|
super().__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
|
|
|
|
|
|
2019-05-13 05:17:47 +08:00
|
|
|
|
def _resolve_output_field(self):
|
2021-12-29 22:00:50 +08:00
|
|
|
|
# We avoid using super() here for reasons given in
|
|
|
|
|
# Expression._resolve_output_field()
|
|
|
|
|
combined_type = _resolve_combined_type(
|
|
|
|
|
self.connector,
|
|
|
|
|
type(self.lhs._output_field_or_none),
|
|
|
|
|
type(self.rhs._output_field_or_none),
|
|
|
|
|
)
|
|
|
|
|
if combined_type is None:
|
|
|
|
|
raise FieldError(
|
|
|
|
|
f"Cannot infer type of {self.connector!r} expression involving these "
|
|
|
|
|
f"types: {self.lhs.output_field.__class__.__name__}, "
|
|
|
|
|
f"{self.rhs.output_field.__class__.__name__}. You must set "
|
|
|
|
|
f"output_field."
|
2019-05-13 05:17:47 +08:00
|
|
|
|
)
|
2021-12-29 22:00:50 +08:00
|
|
|
|
return combined_type()
|
2019-05-13 05:17:47 +08:00
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
|
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
|
|
|
|
|
):
|
2020-06-30 18:37:35 +08:00
|
|
|
|
lhs = self.lhs.resolve_expression(
|
|
|
|
|
query, allow_joins, reuse, summarize, for_save
|
|
|
|
|
)
|
|
|
|
|
rhs = self.rhs.resolve_expression(
|
|
|
|
|
query, allow_joins, reuse, summarize, for_save
|
|
|
|
|
)
|
|
|
|
|
if not isinstance(self, (DurationExpression, TemporalSubtraction)):
|
|
|
|
|
try:
|
|
|
|
|
lhs_type = lhs.output_field.get_internal_type()
|
|
|
|
|
except (AttributeError, FieldError):
|
|
|
|
|
lhs_type = None
|
|
|
|
|
try:
|
|
|
|
|
rhs_type = rhs.output_field.get_internal_type()
|
|
|
|
|
except (AttributeError, FieldError):
|
|
|
|
|
rhs_type = None
|
|
|
|
|
if "DurationField" in {lhs_type, rhs_type} and lhs_type != rhs_type:
|
|
|
|
|
return DurationExpression(
|
|
|
|
|
self.lhs, self.connector, self.rhs
|
|
|
|
|
).resolve_expression(
|
|
|
|
|
query,
|
|
|
|
|
allow_joins,
|
|
|
|
|
reuse,
|
|
|
|
|
summarize,
|
|
|
|
|
for_save,
|
|
|
|
|
)
|
|
|
|
|
datetime_fields = {"DateField", "DateTimeField", "TimeField"}
|
|
|
|
|
if (
|
|
|
|
|
self.connector == self.SUB
|
|
|
|
|
and lhs_type in datetime_fields
|
|
|
|
|
and lhs_type == rhs_type
|
|
|
|
|
):
|
|
|
|
|
return TemporalSubtraction(self.lhs, self.rhs).resolve_expression(
|
|
|
|
|
query,
|
|
|
|
|
allow_joins,
|
|
|
|
|
reuse,
|
|
|
|
|
summarize,
|
|
|
|
|
for_save,
|
|
|
|
|
)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
c = self.copy()
|
|
|
|
|
c.is_summary = summarize
|
2020-06-30 18:37:35 +08:00
|
|
|
|
c.lhs = lhs
|
|
|
|
|
c.rhs = rhs
|
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):
|
2020-06-29 14:28:06 +08:00
|
|
|
|
try:
|
|
|
|
|
output = side.output_field
|
|
|
|
|
except FieldError:
|
|
|
|
|
pass
|
|
|
|
|
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):
|
2020-06-30 18:37:35 +08:00
|
|
|
|
if connection.features.has_native_duration_field:
|
|
|
|
|
return super().as_sql(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
|
|
|
|
|
2021-04-07 00:14:16 +08:00
|
|
|
|
def as_sqlite(self, compiler, connection, **extra_context):
|
|
|
|
|
sql, params = self.as_sql(compiler, connection, **extra_context)
|
|
|
|
|
if self.connector in {Combinable.MUL, Combinable.DIV}:
|
|
|
|
|
try:
|
|
|
|
|
lhs_type = self.lhs.output_field.get_internal_type()
|
|
|
|
|
rhs_type = self.rhs.output_field.get_internal_type()
|
|
|
|
|
except (AttributeError, FieldError):
|
|
|
|
|
pass
|
|
|
|
|
else:
|
|
|
|
|
allowed_fields = {
|
|
|
|
|
"DecimalField",
|
|
|
|
|
"DurationField",
|
|
|
|
|
"FloatField",
|
|
|
|
|
"IntegerField",
|
|
|
|
|
}
|
|
|
|
|
if lhs_type not in allowed_fields or rhs_type not in allowed_fields:
|
|
|
|
|
raise DatabaseError(
|
|
|
|
|
f"Invalid arguments for operator {self.connector}."
|
|
|
|
|
)
|
|
|
|
|
return sql, params
|
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
2016-01-20 09:43:41 +08:00
|
|
|
|
class TemporalSubtraction(CombinedExpression):
|
2017-08-09 01:31:59 +08:00
|
|
|
|
output_field = fields.DurationField()
|
|
|
|
|
|
2016-01-20 09:43:41 +08:00
|
|
|
|
def __init__(self, lhs, rhs):
|
2017-08-09 01:31:59 +08:00
|
|
|
|
super().__init__(lhs, self.SUB, rhs)
|
2016-01-20 09:43:41 +08:00
|
|
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
|
connection.ops.check_expression_support(self)
|
2019-08-10 09:17:45 +08:00
|
|
|
|
lhs = compiler.compile(self.lhs)
|
|
|
|
|
rhs = compiler.compile(self.rhs)
|
2016-01-20 09:43:41 +08:00
|
|
|
|
return connection.ops.subtract_temporals(
|
|
|
|
|
self.lhs.output_field.get_internal_type(), lhs, rhs
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2021-02-25 17:52:59 +08:00
|
|
|
|
@deconstructible(path="django.db.models.F")
|
2015-01-27 10:40:32 +08:00
|
|
|
|
class F(Combinable):
|
2017-01-25 07:04:12 +08:00
|
|
|
|
"""An object capable of resolving references to existing query objects."""
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
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)
|
|
|
|
|
|
2016-11-05 21:12:12 +08:00
|
|
|
|
def resolve_expression(
|
|
|
|
|
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
|
2019-09-10 11:58:29 +08:00
|
|
|
|
):
|
|
|
|
|
return query.resolve_ref(self.name, allow_joins, reuse, summarize)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
2022-08-10 19:51:07 +08:00
|
|
|
|
def replace_expressions(self, replacements):
|
|
|
|
|
return replacements.get(self, self)
|
2022-08-09 12:08:48 +08:00
|
|
|
|
|
2016-07-27 21:17:05 +08:00
|
|
|
|
def asc(self, **kwargs):
|
|
|
|
|
return OrderBy(self, **kwargs)
|
2015-01-09 23:16:16 +08:00
|
|
|
|
|
2016-07-27 21:17:05 +08:00
|
|
|
|
def desc(self, **kwargs):
|
|
|
|
|
return OrderBy(self, descending=True, **kwargs)
|
2015-01-09 23:16:16 +08:00
|
|
|
|
|
2016-11-05 23:49:29 +08:00
|
|
|
|
def __eq__(self, other):
|
|
|
|
|
return self.__class__ == other.__class__ and self.name == other.name
|
|
|
|
|
|
|
|
|
|
def __hash__(self):
|
|
|
|
|
return hash(self.name)
|
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
2016-04-20 14:56:51 +08:00
|
|
|
|
class ResolvedOuterRef(F):
|
|
|
|
|
"""
|
|
|
|
|
An object that contains a reference to an outer query.
|
|
|
|
|
|
|
|
|
|
In this case, the reference to the outer query has been resolved because
|
|
|
|
|
the inner query has been used as a subquery.
|
|
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
|
2019-03-27 15:24:05 +08:00
|
|
|
|
contains_aggregate = False
|
2022-08-10 20:22:01 +08:00
|
|
|
|
contains_over_clause = False
|
2019-03-27 15:24:05 +08:00
|
|
|
|
|
2016-04-20 14:56:51 +08:00
|
|
|
|
def as_sql(self, *args, **kwargs):
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"This queryset contains a reference to an outer query and may "
|
|
|
|
|
"only be used in a subquery."
|
|
|
|
|
)
|
|
|
|
|
|
2020-03-02 20:20:36 +08:00
|
|
|
|
def resolve_expression(self, *args, **kwargs):
|
|
|
|
|
col = super().resolve_expression(*args, **kwargs)
|
|
|
|
|
# FIXME: Rename possibly_multivalued to multivalued and fix detection
|
|
|
|
|
# for non-multivalued JOINs (e.g. foreign key fields). This should take
|
|
|
|
|
# into account only many-to-many and one-to-many relationships.
|
|
|
|
|
col.possibly_multivalued = LOOKUP_SEP in self.name
|
|
|
|
|
return col
|
|
|
|
|
|
2018-02-23 15:31:01 +08:00
|
|
|
|
def relabeled_clone(self, relabels):
|
|
|
|
|
return self
|
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
def get_group_by_cols(self):
|
2020-02-25 03:32:15 +08:00
|
|
|
|
return []
|
|
|
|
|
|
2016-04-20 14:56:51 +08:00
|
|
|
|
|
|
|
|
|
class OuterRef(F):
|
2020-07-01 17:01:46 +08:00
|
|
|
|
contains_aggregate = False
|
|
|
|
|
|
2019-09-10 11:58:29 +08:00
|
|
|
|
def resolve_expression(self, *args, **kwargs):
|
2016-04-20 14:56:51 +08:00
|
|
|
|
if isinstance(self.name, self.__class__):
|
|
|
|
|
return self.name
|
|
|
|
|
return ResolvedOuterRef(self.name)
|
|
|
|
|
|
2020-04-03 17:05:10 +08:00
|
|
|
|
def relabeled_clone(self, relabels):
|
|
|
|
|
return self
|
|
|
|
|
|
2016-04-20 14:56:51 +08:00
|
|
|
|
|
2021-12-06 16:47:22 +08:00
|
|
|
|
@deconstructible(path="django.db.models.Func")
|
2017-08-11 05:42:30 +08:00
|
|
|
|
class Func(SQLiteNumericMixin, Expression):
|
2017-01-25 07:04:12 +08:00
|
|
|
|
"""An SQL function call."""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
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
|
|
|
|
|
2017-02-02 00:41:56 +08:00
|
|
|
|
def __init__(self, *expressions, output_field=None, **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),
|
|
|
|
|
)
|
|
|
|
|
)
|
2017-01-21 21:13:44 +08:00
|
|
|
|
super().__init__(output_field=output_field)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
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)
|
2017-12-11 20:08:45 +08:00
|
|
|
|
extra = {**self.extra, **self._get_repr_options()}
|
2015-01-27 10:40:32 +08:00
|
|
|
|
if extra:
|
2017-07-21 08:51:07 +08:00
|
|
|
|
extra = ", ".join(
|
|
|
|
|
str(key) + "=" + str(val) for key, val in sorted(extra.items())
|
2022-02-04 03:24:19 +08:00
|
|
|
|
)
|
2015-01-27 10:40:32 +08:00
|
|
|
|
return "{}({}, {})".format(self.__class__.__name__, args, extra)
|
|
|
|
|
return "{}({})".format(self.__class__.__name__, args)
|
|
|
|
|
|
2017-07-17 22:07:19 +08:00
|
|
|
|
def _get_repr_options(self):
|
|
|
|
|
"""Return a dict of extra __init__() options to include in the repr."""
|
|
|
|
|
return {}
|
|
|
|
|
|
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:
|
2021-09-29 06:00:50 +08:00
|
|
|
|
try:
|
|
|
|
|
arg_sql, arg_params = compiler.compile(arg)
|
|
|
|
|
except EmptyResultSet:
|
|
|
|
|
empty_result_set_value = getattr(
|
|
|
|
|
arg, "empty_result_set_value", NotImplemented
|
|
|
|
|
)
|
|
|
|
|
if empty_result_set_value is NotImplemented:
|
|
|
|
|
raise
|
|
|
|
|
arg_sql, arg_params = compiler.compile(Value(empty_result_set_value))
|
2013-12-25 21:13:18 +08:00
|
|
|
|
sql_parts.append(arg_sql)
|
|
|
|
|
params.extend(arg_params)
|
2017-12-11 20:08:45 +08:00
|
|
|
|
data = {**self.extra, **extra_context}
|
2016-02-16 04:42:24 +08:00
|
|
|
|
# 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
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
def copy(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
|
copy = super().copy()
|
2013-12-25 21:13:18 +08:00
|
|
|
|
copy.source_expressions = self.source_expressions[:]
|
|
|
|
|
copy.extra = self.extra.copy()
|
|
|
|
|
return copy
|
|
|
|
|
|
|
|
|
|
|
2021-12-06 16:47:22 +08:00
|
|
|
|
@deconstructible(path="django.db.models.Value")
|
2021-03-28 19:06:29 +08:00
|
|
|
|
class Value(SQLiteNumericMixin, Expression):
|
2017-01-25 07:04:12 +08:00
|
|
|
|
"""Represent a wrapped value as a node within an expression."""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
|
2020-07-12 12:49:43 +08:00
|
|
|
|
# Provide a default value for `for_save` in order to allow unresolved
|
|
|
|
|
# instances to be compiled until a decision is taken in #25425.
|
|
|
|
|
for_save = False
|
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
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().
|
|
|
|
|
"""
|
2017-01-21 21:13:44 +08:00
|
|
|
|
super().__init__(output_field=output_field)
|
2013-12-25 21:13:18 +08:00
|
|
|
|
self.value = value
|
|
|
|
|
|
2015-01-27 10:40:32 +08:00
|
|
|
|
def __repr__(self):
|
2021-05-24 13:23:00 +08:00
|
|
|
|
return f"{self.__class__.__name__}({self.value!r})"
|
2015-01-27 10:40:32 +08:00
|
|
|
|
|
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
|
2017-07-15 09:56:01 +08:00
|
|
|
|
output_field = self._output_field_or_none
|
|
|
|
|
if output_field is not None:
|
2015-01-02 09:39:31 +08:00
|
|
|
|
if self.for_save:
|
2017-07-15 09:56:01 +08:00
|
|
|
|
val = output_field.get_db_prep_save(val, connection=connection)
|
2015-01-02 09:39:31 +08:00
|
|
|
|
else:
|
2017-07-15 09:56:01 +08:00
|
|
|
|
val = output_field.get_db_prep_value(val, connection=connection)
|
|
|
|
|
if hasattr(output_field, "get_placeholder"):
|
|
|
|
|
return output_field.get_placeholder(val, compiler, connection), [val]
|
2015-01-02 09:39:31 +08:00
|
|
|
|
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
|
|
|
|
|
):
|
2017-01-21 21:13:44 +08:00
|
|
|
|
c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
|
2015-01-02 09:39:31 +08:00
|
|
|
|
c.for_save = for_save
|
|
|
|
|
return c
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
def get_group_by_cols(self):
|
2014-12-01 15:28:01 +08:00
|
|
|
|
return []
|
|
|
|
|
|
2019-05-13 05:17:47 +08:00
|
|
|
|
def _resolve_output_field(self):
|
|
|
|
|
if isinstance(self.value, str):
|
|
|
|
|
return fields.CharField()
|
|
|
|
|
if isinstance(self.value, bool):
|
|
|
|
|
return fields.BooleanField()
|
|
|
|
|
if isinstance(self.value, int):
|
|
|
|
|
return fields.IntegerField()
|
|
|
|
|
if isinstance(self.value, float):
|
|
|
|
|
return fields.FloatField()
|
|
|
|
|
if isinstance(self.value, datetime.datetime):
|
|
|
|
|
return fields.DateTimeField()
|
|
|
|
|
if isinstance(self.value, datetime.date):
|
|
|
|
|
return fields.DateField()
|
|
|
|
|
if isinstance(self.value, datetime.time):
|
|
|
|
|
return fields.TimeField()
|
|
|
|
|
if isinstance(self.value, datetime.timedelta):
|
|
|
|
|
return fields.DurationField()
|
|
|
|
|
if isinstance(self.value, Decimal):
|
|
|
|
|
return fields.DecimalField()
|
|
|
|
|
if isinstance(self.value, bytes):
|
|
|
|
|
return fields.BinaryField()
|
|
|
|
|
if isinstance(self.value, UUID):
|
|
|
|
|
return fields.UUIDField()
|
|
|
|
|
|
2021-05-22 10:32:16 +08:00
|
|
|
|
@property
|
2021-09-25 04:05:02 +08:00
|
|
|
|
def empty_result_set_value(self):
|
2021-05-22 10:32:16 +08:00
|
|
|
|
return self.value
|
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
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
|
2017-01-21 21:13:44 +08:00
|
|
|
|
super().__init__(output_field=output_field)
|
2014-12-01 15:28:01 +08:00
|
|
|
|
|
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
|
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
def get_group_by_cols(self):
|
2014-12-01 15:28:01 +08:00
|
|
|
|
return [self]
|
|
|
|
|
|
2019-07-10 20:07:48 +08:00
|
|
|
|
def resolve_expression(
|
|
|
|
|
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
|
|
|
|
|
):
|
|
|
|
|
# Resolve parents fields used in raw SQL.
|
2022-01-31 22:51:38 +08:00
|
|
|
|
if query.model:
|
|
|
|
|
for parent in query.model._meta.get_parent_list():
|
|
|
|
|
for parent_field in parent._meta.local_fields:
|
|
|
|
|
_, column_name = parent_field.get_attname_column()
|
|
|
|
|
if column_name.lower() in self.sql.lower():
|
|
|
|
|
query.resolve_ref(
|
|
|
|
|
parent_field.name, allow_joins, reuse, summarize
|
|
|
|
|
)
|
|
|
|
|
break
|
2019-07-10 20:07:48 +08:00
|
|
|
|
return super().resolve_expression(
|
|
|
|
|
query, allow_joins, reuse, summarize, for_save
|
|
|
|
|
)
|
|
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
|
|
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 Col(Expression):
|
2015-08-03 22:34:19 +08:00
|
|
|
|
|
|
|
|
|
contains_column_references = True
|
2020-03-02 20:20:36 +08:00
|
|
|
|
possibly_multivalued = False
|
2015-08-03 22:34:19 +08:00
|
|
|
|
|
2015-02-15 03:37:12 +08:00
|
|
|
|
def __init__(self, alias, target, output_field=None):
|
|
|
|
|
if output_field is None:
|
|
|
|
|
output_field = target
|
2017-01-21 21:13:44 +08:00
|
|
|
|
super().__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):
|
2019-09-10 11:58:29 +08:00
|
|
|
|
alias, target = self.alias, self.target
|
|
|
|
|
identifiers = (alias, str(target)) if alias else (str(target),)
|
|
|
|
|
return "{}({})".format(self.__class__.__name__, ", ".join(identifiers))
|
2015-01-27 10:40:32 +08:00
|
|
|
|
|
2014-11-16 09:56:42 +08:00
|
|
|
|
def as_sql(self, compiler, connection):
|
2019-09-10 11:58:29 +08:00
|
|
|
|
alias, column = self.alias, self.target.column
|
|
|
|
|
identifiers = (alias, column) if alias else (column,)
|
|
|
|
|
sql = ".".join(map(compiler.quote_name_unless_alias, identifiers))
|
|
|
|
|
return sql, []
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
|
|
|
|
def relabeled_clone(self, relabels):
|
2019-09-10 11:58:29 +08:00
|
|
|
|
if self.alias is None:
|
|
|
|
|
return self
|
2013-12-25 21:13:18 +08:00
|
|
|
|
return self.__class__(
|
|
|
|
|
relabels.get(self.alias, self.alias), self.target, self.output_field
|
|
|
|
|
)
|
|
|
|
|
|
2022-09-28 22:51:06 +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
|
|
|
|
|
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.
|
|
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
|
2013-12-25 21:13:18 +08:00
|
|
|
|
def __init__(self, refs, source):
|
2017-01-21 21:13:44 +08:00
|
|
|
|
super().__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):
|
2019-01-15 10:04:00 +08:00
|
|
|
|
return connection.ops.quote_name(self.refs), []
|
2013-12-25 21:13:18 +08:00
|
|
|
|
|
2022-09-28 22:51:06 +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
|
|
|
|
|
|
|
|
|
|
2017-09-18 21:42:29 +08:00
|
|
|
|
class ExpressionList(Func):
|
|
|
|
|
"""
|
|
|
|
|
An expression containing multiple expressions. Can be used to provide a
|
2021-11-23 13:34:48 +08:00
|
|
|
|
list of expressions as an argument to another expression, like a partition
|
|
|
|
|
clause.
|
2017-09-18 21:42:29 +08:00
|
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
|
2017-09-18 21:42:29 +08:00
|
|
|
|
template = "%(expressions)s"
|
|
|
|
|
|
|
|
|
|
def __init__(self, *expressions, **extra):
|
2017-11-30 00:54:34 +08:00
|
|
|
|
if not expressions:
|
2017-09-18 21:42:29 +08:00
|
|
|
|
raise ValueError(
|
|
|
|
|
"%s requires at least one expression." % self.__class__.__name__
|
|
|
|
|
)
|
|
|
|
|
super().__init__(*expressions, **extra)
|
|
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
|
return self.arg_joiner.join(str(arg) for arg in self.source_expressions)
|
|
|
|
|
|
2019-10-11 02:04:17 +08:00
|
|
|
|
def as_sqlite(self, compiler, connection, **extra_context):
|
|
|
|
|
# Casting to numeric is unnecessary.
|
|
|
|
|
return self.as_sql(compiler, connection, **extra_context)
|
|
|
|
|
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
2021-11-23 13:34:48 +08:00
|
|
|
|
class OrderByList(Func):
|
|
|
|
|
template = "ORDER BY %(expressions)s"
|
|
|
|
|
|
|
|
|
|
def __init__(self, *expressions, **extra):
|
|
|
|
|
expressions = (
|
|
|
|
|
(
|
|
|
|
|
OrderBy(F(expr[1:]), descending=True)
|
|
|
|
|
if isinstance(expr, str) and expr[0] == "-"
|
|
|
|
|
else expr
|
|
|
|
|
)
|
|
|
|
|
for expr in expressions
|
|
|
|
|
)
|
|
|
|
|
super().__init__(*expressions, **extra)
|
|
|
|
|
|
|
|
|
|
def as_sql(self, *args, **kwargs):
|
|
|
|
|
if not self.source_expressions:
|
|
|
|
|
return "", ()
|
|
|
|
|
return super().as_sql(*args, **kwargs)
|
|
|
|
|
|
2022-08-10 20:22:01 +08:00
|
|
|
|
def get_group_by_cols(self):
|
|
|
|
|
group_by_cols = []
|
|
|
|
|
for order_by in self.get_source_expressions():
|
|
|
|
|
group_by_cols.extend(order_by.get_group_by_cols())
|
|
|
|
|
return group_by_cols
|
|
|
|
|
|
2021-11-23 13:34:48 +08:00
|
|
|
|
|
2021-12-06 16:47:22 +08:00
|
|
|
|
@deconstructible(path="django.db.models.ExpressionWrapper")
|
2021-11-05 01:24:19 +08:00
|
|
|
|
class ExpressionWrapper(SQLiteNumericMixin, Expression):
|
2015-03-19 11:07:53 +08:00
|
|
|
|
"""
|
|
|
|
|
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):
|
2017-01-21 21:13:44 +08:00
|
|
|
|
super().__init__(output_field=output_field)
|
2015-03-19 11:07:53 +08:00
|
|
|
|
self.expression = expression
|
|
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
|
self.expression = exprs[0]
|
|
|
|
|
|
|
|
|
|
def get_source_expressions(self):
|
|
|
|
|
return [self.expression]
|
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
def get_group_by_cols(self):
|
2020-11-18 06:31:58 +08:00
|
|
|
|
if isinstance(self.expression, Expression):
|
|
|
|
|
expression = self.expression.copy()
|
|
|
|
|
expression.output_field = self.output_field
|
2022-09-28 22:51:06 +08:00
|
|
|
|
return expression.get_group_by_cols()
|
2020-11-18 06:31:58 +08:00
|
|
|
|
# For non-expressions e.g. an SQL WHERE clause, the entire
|
|
|
|
|
# `expression` must be included in the GROUP BY clause.
|
2022-09-28 22:51:06 +08:00
|
|
|
|
return super().get_group_by_cols()
|
2020-06-03 05:14:01 +08:00
|
|
|
|
|
2015-03-19 11:07:53 +08:00
|
|
|
|
def as_sql(self, compiler, connection):
|
2020-10-14 17:09:49 +08:00
|
|
|
|
return compiler.compile(self.expression)
|
2015-03-19 11:07:53 +08:00
|
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
|
return "{}({})".format(self.__class__.__name__, self.expression)
|
|
|
|
|
|
|
|
|
|
|
2021-12-06 16:47:22 +08:00
|
|
|
|
@deconstructible(path="django.db.models.When")
|
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"
|
2017-02-27 17:01:52 +08:00
|
|
|
|
# This isn't a complete conditional expression, must be used in Case().
|
|
|
|
|
conditional = False
|
2015-01-02 09:39:31 +08:00
|
|
|
|
|
2015-02-11 13:38:02 +08:00
|
|
|
|
def __init__(self, condition=None, then=None, **lookups):
|
2020-05-19 13:47:56 +08:00
|
|
|
|
if lookups:
|
|
|
|
|
if condition is None:
|
|
|
|
|
condition, lookups = Q(**lookups), None
|
|
|
|
|
elif getattr(condition, "conditional", False):
|
|
|
|
|
condition, lookups = Q(condition, **lookups), None
|
2017-12-08 23:59:49 +08:00
|
|
|
|
if condition is None or not getattr(condition, "conditional", False) or lookups:
|
2017-02-27 17:01:52 +08:00
|
|
|
|
raise TypeError(
|
|
|
|
|
"When() supports a Q object, a boolean expression, or lookups "
|
|
|
|
|
"as a condition."
|
|
|
|
|
)
|
2017-11-06 05:34:02 +08:00
|
|
|
|
if isinstance(condition, Q) and not condition:
|
|
|
|
|
raise ValueError("An empty Q() can't be used as a When() condition.")
|
2017-01-21 21:13:44 +08:00
|
|
|
|
super().__init__(output_field=None)
|
2015-01-02 09:39:31 +08:00
|
|
|
|
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)
|
2022-08-07 23:25:43 +08:00
|
|
|
|
# Filters that match everything are handled as empty strings in the
|
|
|
|
|
# WHERE clause, but in a CASE WHEN expression they must use a predicate
|
|
|
|
|
# that's always True.
|
|
|
|
|
if condition_sql == "":
|
2022-08-10 18:28:39 +08:00
|
|
|
|
if connection.features.supports_boolean_expr_in_select_clause:
|
|
|
|
|
condition_sql, condition_params = compiler.compile(Value(True))
|
|
|
|
|
else:
|
|
|
|
|
condition_sql, condition_params = "1=1", ()
|
2015-01-02 09:39:31 +08:00
|
|
|
|
template_params["condition"] = condition_sql
|
|
|
|
|
result_sql, result_params = compiler.compile(self.result)
|
|
|
|
|
template_params["result"] = result_sql
|
|
|
|
|
template = template or self.template
|
2022-08-10 18:28:39 +08:00
|
|
|
|
return template % template_params, (
|
|
|
|
|
*sql_params,
|
|
|
|
|
*condition_params,
|
|
|
|
|
*result_params,
|
|
|
|
|
)
|
2015-01-02 09:39:31 +08:00
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
def get_group_by_cols(self):
|
2015-01-02 09:39:31 +08:00
|
|
|
|
# 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
|
|
|
|
|
|
|
|
|
|
|
2021-12-06 16:47:22 +08:00
|
|
|
|
@deconstructible(path="django.db.models.Case")
|
2021-11-05 01:24:19 +08:00
|
|
|
|
class Case(SQLiteNumericMixin, 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
|
|
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
|
2015-01-02 09:39:31 +08:00
|
|
|
|
template = "CASE %(cases)s ELSE %(default)s END"
|
|
|
|
|
case_joiner = " "
|
|
|
|
|
|
2017-02-02 00:41:56 +08:00
|
|
|
|
def __init__(self, *cases, default=None, output_field=None, **extra):
|
2015-01-02 09:39:31 +08:00
|
|
|
|
if not all(isinstance(case, When) for case in cases):
|
|
|
|
|
raise TypeError("Positional arguments must all be When objects.")
|
2017-01-21 21:13:44 +08:00
|
|
|
|
super().__init__(output_field)
|
2015-01-02 09:39:31 +08:00
|
|
|
|
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):
|
2018-09-28 21:57:12 +08:00
|
|
|
|
*self.cases, self.default = 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
|
|
|
|
|
):
|
|
|
|
|
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):
|
2017-01-21 21:13:44 +08:00
|
|
|
|
c = super().copy()
|
2015-05-05 19:11:58 +08:00
|
|
|
|
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)
|
2017-12-11 20:08:45 +08:00
|
|
|
|
template_params = {**self.extra, **extra_context}
|
2015-01-02 09:39:31 +08:00
|
|
|
|
case_parts = []
|
|
|
|
|
sql_params = []
|
|
|
|
|
for case in self.cases:
|
2016-08-05 20:58:36 +08:00
|
|
|
|
try:
|
|
|
|
|
case_sql, case_params = compiler.compile(case)
|
|
|
|
|
except EmptyResultSet:
|
|
|
|
|
continue
|
2015-01-02 09:39:31 +08:00
|
|
|
|
case_parts.append(case_sql)
|
|
|
|
|
sql_params.extend(case_params)
|
2016-08-05 20:58:36 +08:00
|
|
|
|
default_sql, default_params = compiler.compile(self.default)
|
|
|
|
|
if not case_parts:
|
|
|
|
|
return default_sql, default_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
|
|
|
|
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
|
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
def get_group_by_cols(self):
|
2020-10-20 04:36:24 +08:00
|
|
|
|
if not self.cases:
|
2022-09-28 22:51:06 +08:00
|
|
|
|
return self.default.get_group_by_cols()
|
|
|
|
|
return super().get_group_by_cols()
|
2020-10-20 04:36:24 +08:00
|
|
|
|
|
2015-01-02 09:39:31 +08:00
|
|
|
|
|
2021-04-24 13:07:18 +08:00
|
|
|
|
class Subquery(BaseExpression, Combinable):
|
2016-04-20 14:56:51 +08:00
|
|
|
|
"""
|
|
|
|
|
An explicit subquery. It may contain OuterRef() references to the outer
|
|
|
|
|
query which will be resolved when it is applied to that query.
|
|
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
|
2016-04-20 14:56:51 +08:00
|
|
|
|
template = "(%(subquery)s)"
|
2019-01-15 04:52:09 +08:00
|
|
|
|
contains_aggregate = False
|
2021-09-29 06:00:50 +08:00
|
|
|
|
empty_result_set_value = None
|
2016-04-20 14:56:51 +08:00
|
|
|
|
|
|
|
|
|
def __init__(self, queryset, output_field=None, **extra):
|
2020-10-26 04:04:21 +08:00
|
|
|
|
# Allow the usage of both QuerySet and sql.Query objects.
|
2022-01-15 07:38:31 +08:00
|
|
|
|
self.query = getattr(queryset, "query", queryset).clone()
|
|
|
|
|
self.query.subquery = True
|
2016-04-20 14:56:51 +08:00
|
|
|
|
self.extra = extra
|
2017-01-21 21:13:44 +08:00
|
|
|
|
super().__init__(output_field)
|
2016-04-20 14:56:51 +08:00
|
|
|
|
|
2019-03-06 14:05:55 +08:00
|
|
|
|
def get_source_expressions(self):
|
|
|
|
|
return [self.query]
|
|
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
|
self.query = exprs[0]
|
|
|
|
|
|
2018-03-08 15:06:19 +08:00
|
|
|
|
def _resolve_output_field(self):
|
2019-03-06 14:05:55 +08:00
|
|
|
|
return self.query.output_field
|
2018-03-08 15:06:19 +08:00
|
|
|
|
|
2016-04-20 14:56:51 +08:00
|
|
|
|
def copy(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
|
clone = super().copy()
|
2019-03-06 12:34:12 +08:00
|
|
|
|
clone.query = clone.query.clone()
|
2016-04-20 14:56:51 +08:00
|
|
|
|
return clone
|
|
|
|
|
|
2019-03-06 14:05:55 +08:00
|
|
|
|
@property
|
|
|
|
|
def external_aliases(self):
|
|
|
|
|
return self.query.external_aliases
|
2016-04-20 14:56:51 +08:00
|
|
|
|
|
2021-02-24 09:56:29 +08:00
|
|
|
|
def get_external_cols(self):
|
|
|
|
|
return self.query.get_external_cols()
|
|
|
|
|
|
2022-09-28 12:44:46 +08:00
|
|
|
|
def as_sql(self, compiler, connection, template=None, **extra_context):
|
2016-04-20 14:56:51 +08:00
|
|
|
|
connection.ops.check_expression_support(self)
|
2017-12-11 20:08:45 +08:00
|
|
|
|
template_params = {**self.extra, **extra_context}
|
2022-09-28 12:44:46 +08:00
|
|
|
|
subquery_sql, sql_params = self.query.as_sql(compiler, connection)
|
2019-03-06 14:24:41 +08:00
|
|
|
|
template_params["subquery"] = subquery_sql[1:-1]
|
2016-04-20 14:56:51 +08:00
|
|
|
|
|
|
|
|
|
template = template or template_params.get("template", self.template)
|
|
|
|
|
sql = template % template_params
|
|
|
|
|
return sql, sql_params
|
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
def get_group_by_cols(self):
|
|
|
|
|
return self.query.get_group_by_cols(wrapper=self)
|
2019-02-27 13:48:41 +08:00
|
|
|
|
|
2016-04-20 14:56:51 +08:00
|
|
|
|
|
|
|
|
|
class Exists(Subquery):
|
|
|
|
|
template = "EXISTS(%(subquery)s)"
|
2017-08-09 01:31:59 +08:00
|
|
|
|
output_field = fields.BooleanField()
|
2016-04-20 14:56:51 +08:00
|
|
|
|
|
2019-03-06 12:34:12 +08:00
|
|
|
|
def __init__(self, queryset, negated=False, **kwargs):
|
2017-02-02 00:41:56 +08:00
|
|
|
|
self.negated = negated
|
2019-03-06 12:34:12 +08:00
|
|
|
|
super().__init__(queryset, **kwargs)
|
2022-09-28 12:44:46 +08:00
|
|
|
|
self.query = self.query.exists()
|
2016-04-20 14:56:51 +08:00
|
|
|
|
|
|
|
|
|
def __invert__(self):
|
2019-03-06 12:34:12 +08:00
|
|
|
|
clone = self.copy()
|
|
|
|
|
clone.negated = not self.negated
|
|
|
|
|
return clone
|
2016-04-20 14:56:51 +08:00
|
|
|
|
|
2022-09-28 12:44:46 +08:00
|
|
|
|
def as_sql(self, compiler, connection, **extra_context):
|
2022-02-02 02:27:41 +08:00
|
|
|
|
try:
|
|
|
|
|
sql, params = super().as_sql(
|
|
|
|
|
compiler,
|
|
|
|
|
connection,
|
|
|
|
|
**extra_context,
|
|
|
|
|
)
|
|
|
|
|
except EmptyResultSet:
|
|
|
|
|
if self.negated:
|
2022-02-08 03:34:21 +08:00
|
|
|
|
features = compiler.connection.features
|
|
|
|
|
if not features.supports_boolean_expr_in_select_clause:
|
|
|
|
|
return "1=1", ()
|
|
|
|
|
return compiler.compile(Value(True))
|
2022-02-02 02:27:41 +08:00
|
|
|
|
raise
|
2016-04-20 14:56:51 +08:00
|
|
|
|
if self.negated:
|
|
|
|
|
sql = "NOT {}".format(sql)
|
|
|
|
|
return sql, params
|
|
|
|
|
|
2019-08-11 14:12:11 +08:00
|
|
|
|
def select_format(self, compiler, sql, params):
|
|
|
|
|
# Wrap EXISTS() with a CASE WHEN expression if a database backend
|
2020-05-14 21:07:08 +08:00
|
|
|
|
# (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP
|
|
|
|
|
# BY list.
|
2019-08-11 14:12:11 +08:00
|
|
|
|
if not compiler.connection.features.supports_boolean_expr_in_select_clause:
|
|
|
|
|
sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql)
|
2016-04-20 14:56:51 +08:00
|
|
|
|
return sql, params
|
|
|
|
|
|
|
|
|
|
|
2021-12-06 16:47:22 +08:00
|
|
|
|
@deconstructible(path="django.db.models.OrderBy")
|
2021-05-05 05:49:46 +08:00
|
|
|
|
class OrderBy(Expression):
|
2015-01-09 23:16:16 +08:00
|
|
|
|
template = "%(expression)s %(ordering)s"
|
2017-02-27 17:01:52 +08:00
|
|
|
|
conditional = False
|
2015-01-09 23:16:16 +08:00
|
|
|
|
|
2022-05-12 17:30:03 +08:00
|
|
|
|
def __init__(self, expression, descending=False, nulls_first=None, nulls_last=None):
|
2016-07-27 21:17:05 +08:00
|
|
|
|
if nulls_first and nulls_last:
|
|
|
|
|
raise ValueError("nulls_first and nulls_last are mutually exclusive")
|
2022-05-12 17:30:03 +08:00
|
|
|
|
if nulls_first is False or nulls_last is False:
|
|
|
|
|
# When the deprecation ends, replace with:
|
|
|
|
|
# raise ValueError(
|
|
|
|
|
# "nulls_first and nulls_last values must be True or None."
|
|
|
|
|
# )
|
|
|
|
|
warnings.warn(
|
|
|
|
|
"Passing nulls_first=False or nulls_last=False is deprecated, use None "
|
|
|
|
|
"instead.",
|
|
|
|
|
RemovedInDjango50Warning,
|
|
|
|
|
stacklevel=2,
|
|
|
|
|
)
|
2016-07-27 21:17:05 +08:00
|
|
|
|
self.nulls_first = nulls_first
|
|
|
|
|
self.nulls_last = nulls_last
|
2015-01-09 23:16:16 +08:00
|
|
|
|
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):
|
2019-11-04 21:47:58 +08:00
|
|
|
|
template = template or self.template
|
|
|
|
|
if connection.features.supports_order_by_nulls_modifier:
|
|
|
|
|
if self.nulls_last:
|
|
|
|
|
template = "%s NULLS LAST" % template
|
|
|
|
|
elif self.nulls_first:
|
|
|
|
|
template = "%s NULLS FIRST" % template
|
|
|
|
|
else:
|
2020-03-18 10:00:28 +08:00
|
|
|
|
if self.nulls_last and not (
|
|
|
|
|
self.descending and connection.features.order_by_nulls_first
|
|
|
|
|
):
|
2019-11-04 21:47:58 +08:00
|
|
|
|
template = "%%(expression)s IS NULL, %s" % template
|
2020-03-18 10:00:28 +08:00
|
|
|
|
elif self.nulls_first and not (
|
|
|
|
|
not self.descending and connection.features.order_by_nulls_first
|
|
|
|
|
):
|
2019-11-04 21:47:58 +08:00
|
|
|
|
template = "%%(expression)s IS NOT NULL, %s" % template
|
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",
|
2017-12-11 20:08:45 +08:00
|
|
|
|
**extra_context,
|
2015-11-07 18:46:22 +08:00
|
|
|
|
}
|
2017-11-27 00:32:17 +08:00
|
|
|
|
params *= template.count("%(expression)s")
|
2016-02-16 04:42:24 +08:00
|
|
|
|
return (template % placeholders).rstrip(), params
|
2015-01-09 23:16:16 +08:00
|
|
|
|
|
2019-08-11 14:12:11 +08:00
|
|
|
|
def as_oracle(self, compiler, connection):
|
2021-04-03 01:25:20 +08:00
|
|
|
|
# Oracle doesn't allow ORDER BY EXISTS() or filters unless it's wrapped
|
|
|
|
|
# in a CASE WHEN.
|
|
|
|
|
if connection.ops.conditional_expression_supported_in_where_clause(
|
|
|
|
|
self.expression
|
|
|
|
|
):
|
2019-08-11 14:12:11 +08:00
|
|
|
|
copy = self.copy()
|
2019-08-29 17:56:12 +08:00
|
|
|
|
copy.expression = Case(
|
|
|
|
|
When(self.expression, then=True),
|
|
|
|
|
default=False,
|
|
|
|
|
)
|
2019-08-11 14:12:11 +08:00
|
|
|
|
return copy.as_sql(compiler, connection)
|
|
|
|
|
return self.as_sql(compiler, connection)
|
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
def get_group_by_cols(self):
|
2015-01-09 23:16:16 +08:00
|
|
|
|
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
|
2022-05-12 17:30:03 +08:00
|
|
|
|
if self.nulls_first:
|
|
|
|
|
self.nulls_last = True
|
|
|
|
|
self.nulls_first = None
|
|
|
|
|
elif self.nulls_last:
|
|
|
|
|
self.nulls_first = True
|
|
|
|
|
self.nulls_last = None
|
2015-01-09 23:16:16 +08:00
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
def asc(self):
|
|
|
|
|
self.descending = False
|
|
|
|
|
|
|
|
|
|
def desc(self):
|
|
|
|
|
self.descending = True
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
|
|
|
|
|
2020-09-22 21:01:52 +08:00
|
|
|
|
class Window(SQLiteNumericMixin, Expression):
|
2017-09-18 21:42:29 +08:00
|
|
|
|
template = "%(expression)s OVER (%(window)s)"
|
|
|
|
|
# Although the main expression may either be an aggregate or an
|
|
|
|
|
# expression with an aggregate function, the GROUP BY that will
|
|
|
|
|
# be introduced in the query as a result is not desired.
|
|
|
|
|
contains_aggregate = False
|
|
|
|
|
contains_over_clause = True
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
expression,
|
|
|
|
|
partition_by=None,
|
|
|
|
|
order_by=None,
|
|
|
|
|
frame=None,
|
|
|
|
|
output_field=None,
|
|
|
|
|
):
|
|
|
|
|
self.partition_by = partition_by
|
|
|
|
|
self.order_by = order_by
|
|
|
|
|
self.frame = frame
|
|
|
|
|
|
|
|
|
|
if not getattr(expression, "window_compatible", False):
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"Expression '%s' isn't compatible with OVER clauses."
|
|
|
|
|
% expression.__class__.__name__
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if self.partition_by is not None:
|
|
|
|
|
if not isinstance(self.partition_by, (tuple, list)):
|
|
|
|
|
self.partition_by = (self.partition_by,)
|
|
|
|
|
self.partition_by = ExpressionList(*self.partition_by)
|
|
|
|
|
|
|
|
|
|
if self.order_by is not None:
|
|
|
|
|
if isinstance(self.order_by, (list, tuple)):
|
2021-11-23 13:39:04 +08:00
|
|
|
|
self.order_by = OrderByList(*self.order_by)
|
|
|
|
|
elif isinstance(self.order_by, (BaseExpression, str)):
|
|
|
|
|
self.order_by = OrderByList(self.order_by)
|
|
|
|
|
else:
|
2017-09-18 21:42:29 +08:00
|
|
|
|
raise ValueError(
|
2021-11-23 13:39:04 +08:00
|
|
|
|
"Window.order_by must be either a string reference to a "
|
|
|
|
|
"field, an expression, or a list or tuple of them."
|
2017-09-18 21:42:29 +08:00
|
|
|
|
)
|
|
|
|
|
super().__init__(output_field=output_field)
|
|
|
|
|
self.source_expression = self._parse_expressions(expression)[0]
|
|
|
|
|
|
|
|
|
|
def _resolve_output_field(self):
|
|
|
|
|
return self.source_expression.output_field
|
|
|
|
|
|
|
|
|
|
def get_source_expressions(self):
|
|
|
|
|
return [self.source_expression, self.partition_by, self.order_by, self.frame]
|
|
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
|
self.source_expression, self.partition_by, self.order_by, self.frame = exprs
|
|
|
|
|
|
2018-08-21 04:16:27 +08:00
|
|
|
|
def as_sql(self, compiler, connection, template=None):
|
2017-09-18 21:42:29 +08:00
|
|
|
|
connection.ops.check_expression_support(self)
|
2019-01-16 11:48:12 +08:00
|
|
|
|
if not connection.features.supports_over_clause:
|
|
|
|
|
raise NotSupportedError("This backend does not support window expressions.")
|
2017-09-18 21:42:29 +08:00
|
|
|
|
expr_sql, params = compiler.compile(self.source_expression)
|
2022-08-06 23:59:31 +08:00
|
|
|
|
window_sql, window_params = [], ()
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
|
|
|
|
if self.partition_by is not None:
|
|
|
|
|
sql_expr, sql_params = self.partition_by.as_sql(
|
|
|
|
|
compiler=compiler,
|
|
|
|
|
connection=connection,
|
|
|
|
|
template="PARTITION BY %(expressions)s",
|
|
|
|
|
)
|
2021-11-23 13:39:04 +08:00
|
|
|
|
window_sql.append(sql_expr)
|
2022-08-06 23:59:31 +08:00
|
|
|
|
window_params += tuple(sql_params)
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
|
|
|
|
if self.order_by is not None:
|
|
|
|
|
order_sql, order_params = compiler.compile(self.order_by)
|
2021-11-23 13:39:04 +08:00
|
|
|
|
window_sql.append(order_sql)
|
2022-08-06 23:59:31 +08:00
|
|
|
|
window_params += tuple(order_params)
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
|
|
|
|
if self.frame:
|
|
|
|
|
frame_sql, frame_params = compiler.compile(self.frame)
|
2021-11-23 13:39:04 +08:00
|
|
|
|
window_sql.append(frame_sql)
|
2022-08-06 23:59:31 +08:00
|
|
|
|
window_params += tuple(frame_params)
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
|
|
|
|
template = template or self.template
|
|
|
|
|
|
|
|
|
|
return (
|
2021-11-23 13:39:04 +08:00
|
|
|
|
template % {"expression": expr_sql, "window": " ".join(window_sql).strip()},
|
2022-08-06 23:59:31 +08:00
|
|
|
|
(*params, *window_params),
|
2022-02-04 03:24:19 +08:00
|
|
|
|
)
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
2020-09-22 21:01:52 +08:00
|
|
|
|
def as_sqlite(self, compiler, connection):
|
|
|
|
|
if isinstance(self.output_field, fields.DecimalField):
|
|
|
|
|
# Casting to numeric must be outside of the window expression.
|
|
|
|
|
copy = self.copy()
|
|
|
|
|
source_expressions = copy.get_source_expressions()
|
|
|
|
|
source_expressions[0].output_field = fields.FloatField()
|
|
|
|
|
copy.set_source_expressions(source_expressions)
|
|
|
|
|
return super(Window, copy).as_sqlite(compiler, connection)
|
|
|
|
|
return self.as_sql(compiler, connection)
|
|
|
|
|
|
2017-09-18 21:42:29 +08:00
|
|
|
|
def __str__(self):
|
|
|
|
|
return "{} OVER ({}{}{})".format(
|
|
|
|
|
str(self.source_expression),
|
|
|
|
|
"PARTITION BY " + str(self.partition_by) if self.partition_by else "",
|
2021-11-23 13:39:04 +08:00
|
|
|
|
str(self.order_by or ""),
|
2017-09-18 21:42:29 +08:00
|
|
|
|
str(self.frame or ""),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
|
return "<%s: %s>" % (self.__class__.__name__, self)
|
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
def get_group_by_cols(self):
|
2022-08-10 20:22:01 +08:00
|
|
|
|
group_by_cols = []
|
|
|
|
|
if self.partition_by:
|
|
|
|
|
group_by_cols.extend(self.partition_by.get_group_by_cols())
|
|
|
|
|
if self.order_by is not None:
|
|
|
|
|
group_by_cols.extend(self.order_by.get_group_by_cols())
|
|
|
|
|
return group_by_cols
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class WindowFrame(Expression):
|
|
|
|
|
"""
|
|
|
|
|
Model the frame clause in window expressions. There are two types of frame
|
|
|
|
|
clauses which are subclasses, however, all processing and validation (by no
|
|
|
|
|
means intended to be complete) is done here. Thus, providing an end for a
|
|
|
|
|
frame is optional (the default is UNBOUNDED FOLLOWING, which is the last
|
|
|
|
|
row in the frame).
|
|
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
|
2017-09-18 21:42:29 +08:00
|
|
|
|
template = "%(frame_type)s BETWEEN %(start)s AND %(end)s"
|
|
|
|
|
|
|
|
|
|
def __init__(self, start=None, end=None):
|
2018-12-28 03:21:57 +08:00
|
|
|
|
self.start = Value(start)
|
|
|
|
|
self.end = Value(end)
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
|
|
|
|
def set_source_expressions(self, exprs):
|
|
|
|
|
self.start, self.end = exprs
|
|
|
|
|
|
|
|
|
|
def get_source_expressions(self):
|
2018-12-28 03:21:57 +08:00
|
|
|
|
return [self.start, self.end]
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
|
connection.ops.check_expression_support(self)
|
|
|
|
|
start, end = self.window_frame_start_end(
|
|
|
|
|
connection, self.start.value, self.end.value
|
|
|
|
|
)
|
|
|
|
|
return (
|
|
|
|
|
self.template
|
|
|
|
|
% {
|
|
|
|
|
"frame_type": self.frame_type,
|
|
|
|
|
"start": start,
|
|
|
|
|
"end": end,
|
|
|
|
|
},
|
|
|
|
|
[],
|
2022-02-04 03:24:19 +08:00
|
|
|
|
)
|
2017-09-18 21:42:29 +08:00
|
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
|
return "<%s: %s>" % (self.__class__.__name__, self)
|
|
|
|
|
|
2022-09-28 22:51:06 +08:00
|
|
|
|
def get_group_by_cols(self):
|
2017-09-18 21:42:29 +08:00
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
def __str__(self):
|
2018-12-28 03:21:57 +08:00
|
|
|
|
if self.start.value is not None and self.start.value < 0:
|
|
|
|
|
start = "%d %s" % (abs(self.start.value), connection.ops.PRECEDING)
|
|
|
|
|
elif self.start.value is not None and self.start.value == 0:
|
2017-09-18 21:42:29 +08:00
|
|
|
|
start = connection.ops.CURRENT_ROW
|
|
|
|
|
else:
|
|
|
|
|
start = connection.ops.UNBOUNDED_PRECEDING
|
|
|
|
|
|
2018-12-28 03:21:57 +08:00
|
|
|
|
if self.end.value is not None and self.end.value > 0:
|
|
|
|
|
end = "%d %s" % (self.end.value, connection.ops.FOLLOWING)
|
|
|
|
|
elif self.end.value is not None and self.end.value == 0:
|
2017-09-18 21:42:29 +08:00
|
|
|
|
end = connection.ops.CURRENT_ROW
|
|
|
|
|
else:
|
|
|
|
|
end = connection.ops.UNBOUNDED_FOLLOWING
|
|
|
|
|
return self.template % {
|
|
|
|
|
"frame_type": self.frame_type,
|
|
|
|
|
"start": start,
|
|
|
|
|
"end": end,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
def window_frame_start_end(self, connection, start, end):
|
|
|
|
|
raise NotImplementedError("Subclasses must implement window_frame_start_end().")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class RowRange(WindowFrame):
|
|
|
|
|
frame_type = "ROWS"
|
|
|
|
|
|
|
|
|
|
def window_frame_start_end(self, connection, start, end):
|
|
|
|
|
return connection.ops.window_frame_rows_start_end(start, end)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ValueRange(WindowFrame):
|
|
|
|
|
frame_type = "RANGE"
|
|
|
|
|
|
|
|
|
|
def window_frame_start_end(self, connection, start, end):
|
|
|
|
|
return connection.ops.window_frame_range_start_end(start, end)
|