2014-11-22 11:14:43 +08:00
|
|
|
"""
|
|
|
|
Classes that represent database functions.
|
|
|
|
"""
|
2016-03-26 06:49:45 +08:00
|
|
|
from django.db.models import Func, Transform, Value, fields
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
|
2015-06-05 22:20:37 +08:00
|
|
|
class Cast(Func):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Coerce an expression to a new field type."""
|
2015-06-05 22:20:37 +08:00
|
|
|
function = 'CAST'
|
|
|
|
template = '%(function)s(%(expressions)s AS %(db_type)s)'
|
|
|
|
|
|
|
|
mysql_types = {
|
|
|
|
fields.CharField: 'char',
|
|
|
|
fields.IntegerField: 'signed integer',
|
|
|
|
fields.FloatField: 'signed',
|
|
|
|
}
|
|
|
|
|
|
|
|
def __init__(self, expression, output_field):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(expression, output_field=output_field)
|
2015-06-05 22:20:37 +08:00
|
|
|
|
|
|
|
def as_sql(self, compiler, connection, **extra_context):
|
|
|
|
if 'db_type' not in extra_context:
|
|
|
|
extra_context['db_type'] = self._output_field.db_type(connection)
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().as_sql(compiler, connection, **extra_context)
|
2015-06-05 22:20:37 +08:00
|
|
|
|
|
|
|
def as_mysql(self, compiler, connection):
|
|
|
|
extra_context = {}
|
|
|
|
output_field_class = type(self._output_field)
|
|
|
|
if output_field_class in self.mysql_types:
|
|
|
|
extra_context['db_type'] = self.mysql_types[output_field_class]
|
|
|
|
return self.as_sql(compiler, connection, **extra_context)
|
|
|
|
|
|
|
|
def as_postgresql(self, compiler, connection):
|
|
|
|
# CAST would be valid too, but the :: shortcut syntax is more readable.
|
|
|
|
return self.as_sql(compiler, connection, template='%(expressions)s::%(db_type)s')
|
|
|
|
|
|
|
|
|
2014-11-22 11:14:43 +08:00
|
|
|
class Coalesce(Func):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Return, from left to right, the first non-null expression."""
|
2014-11-22 11:14:43 +08:00
|
|
|
function = 'COALESCE'
|
|
|
|
|
|
|
|
def __init__(self, *expressions, **extra):
|
|
|
|
if len(expressions) < 2:
|
|
|
|
raise ValueError('Coalesce must take at least two expressions')
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*expressions, **extra)
|
2014-11-22 11:14:43 +08:00
|
|
|
|
2014-12-29 06:15:00 +08:00
|
|
|
def as_oracle(self, compiler, connection):
|
|
|
|
# we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert
|
|
|
|
# all fields to NCLOB when we expect NCLOB
|
|
|
|
if self.output_field.get_internal_type() == 'TextField':
|
|
|
|
class ToNCLOB(Func):
|
|
|
|
function = 'TO_NCLOB'
|
|
|
|
|
|
|
|
expressions = [
|
|
|
|
ToNCLOB(expression) for expression in self.get_source_expressions()]
|
2016-03-16 23:05:24 +08:00
|
|
|
clone = self.copy()
|
|
|
|
clone.set_source_expressions(expressions)
|
|
|
|
return super(Coalesce, clone).as_sql(compiler, connection)
|
|
|
|
return self.as_sql(compiler, connection)
|
2014-12-29 06:15:00 +08:00
|
|
|
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
class ConcatPair(Func):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Concatenate two arguments together. This is used by `Concat` because not
|
|
|
|
all backend databases support more than two arguments.
|
2014-11-22 11:14:43 +08:00
|
|
|
"""
|
|
|
|
function = 'CONCAT'
|
|
|
|
|
|
|
|
def __init__(self, left, right, **extra):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(left, right, **extra)
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
def as_sqlite(self, compiler, connection):
|
2015-10-14 07:07:42 +08:00
|
|
|
coalesced = self.coalesce()
|
2016-03-16 23:05:24 +08:00
|
|
|
return super(ConcatPair, coalesced).as_sql(
|
2016-02-16 04:42:24 +08:00
|
|
|
compiler, connection, template='%(expressions)s', arg_joiner=' || '
|
2016-03-16 23:05:24 +08:00
|
|
|
)
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
def as_mysql(self, compiler, connection):
|
2015-04-09 05:26:09 +08:00
|
|
|
# Use CONCAT_WS with an empty separator so that NULLs are ignored.
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().as_sql(
|
2016-03-16 23:05:24 +08:00
|
|
|
compiler, connection, function='CONCAT_WS', template="%(function)s('', %(expressions)s)"
|
|
|
|
)
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
def coalesce(self):
|
|
|
|
# null on either side results in null for expression, wrap with coalesce
|
2015-10-14 07:07:42 +08:00
|
|
|
c = self.copy()
|
2014-11-22 11:14:43 +08:00
|
|
|
expressions = [
|
2015-10-14 07:07:42 +08:00
|
|
|
Coalesce(expression, Value('')) for expression in c.get_source_expressions()
|
|
|
|
]
|
|
|
|
c.set_source_expressions(expressions)
|
|
|
|
return c
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Concat(Func):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Concatenate text fields together. Backends that result in an entire
|
2014-11-22 11:14:43 +08:00
|
|
|
null expression when any arguments are null will wrap each argument in
|
2017-01-25 07:04:12 +08:00
|
|
|
coalesce functions to ensure a non-null result.
|
2014-11-22 11:14:43 +08:00
|
|
|
"""
|
|
|
|
function = None
|
|
|
|
template = "%(expressions)s"
|
|
|
|
|
|
|
|
def __init__(self, *expressions, **extra):
|
|
|
|
if len(expressions) < 2:
|
|
|
|
raise ValueError('Concat must take at least two expressions')
|
|
|
|
paired = self._paired(expressions)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(paired, **extra)
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
def _paired(self, expressions):
|
|
|
|
# wrap pairs of expressions in successive concat functions
|
|
|
|
# exp = [a, b, c, d]
|
|
|
|
# -> ConcatPair(a, ConcatPair(b, ConcatPair(c, d))))
|
|
|
|
if len(expressions) == 2:
|
|
|
|
return ConcatPair(*expressions)
|
|
|
|
return ConcatPair(expressions[0], self._paired(expressions[1:]))
|
|
|
|
|
|
|
|
|
2015-05-09 19:55:03 +08:00
|
|
|
class Greatest(Func):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the maximum expression.
|
2015-05-09 19:55:03 +08:00
|
|
|
|
|
|
|
If any expression is null the return value is database-specific:
|
|
|
|
On Postgres, the maximum not-null expression is returned.
|
2015-06-05 23:40:10 +08:00
|
|
|
On MySQL, Oracle, and SQLite, if any expression is null, null is returned.
|
2015-05-09 19:55:03 +08:00
|
|
|
"""
|
|
|
|
function = 'GREATEST'
|
|
|
|
|
|
|
|
def __init__(self, *expressions, **extra):
|
|
|
|
if len(expressions) < 2:
|
|
|
|
raise ValueError('Greatest must take at least two expressions')
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*expressions, **extra)
|
2015-05-09 19:55:03 +08:00
|
|
|
|
|
|
|
def as_sqlite(self, compiler, connection):
|
|
|
|
"""Use the MAX function on SQLite."""
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().as_sql(compiler, connection, function='MAX')
|
2015-05-09 19:55:03 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Least(Func):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the minimum expression.
|
2015-05-09 19:55:03 +08:00
|
|
|
|
|
|
|
If any expression is null the return value is database-specific:
|
2017-01-25 07:04:12 +08:00
|
|
|
On Postgres, return the minimum not-null expression.
|
|
|
|
On MySQL, Oracle, and SQLite, if any expression is null, return null.
|
2015-05-09 19:55:03 +08:00
|
|
|
"""
|
|
|
|
function = 'LEAST'
|
|
|
|
|
|
|
|
def __init__(self, *expressions, **extra):
|
|
|
|
if len(expressions) < 2:
|
|
|
|
raise ValueError('Least must take at least two expressions')
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*expressions, **extra)
|
2015-05-09 19:55:03 +08:00
|
|
|
|
|
|
|
def as_sqlite(self, compiler, connection):
|
|
|
|
"""Use the MIN function on SQLite."""
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().as_sql(compiler, connection, function='MIN')
|
2015-05-09 19:55:03 +08:00
|
|
|
|
|
|
|
|
2015-08-03 10:30:06 +08:00
|
|
|
class Length(Transform):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Return the number of characters in the expression."""
|
2014-11-22 11:14:43 +08:00
|
|
|
function = 'LENGTH'
|
2015-08-03 10:30:06 +08:00
|
|
|
lookup_name = 'length'
|
2014-11-22 11:14:43 +08:00
|
|
|
|
2017-02-02 00:41:56 +08:00
|
|
|
def __init__(self, expression, *, output_field=None, **extra):
|
|
|
|
super().__init__(expression, output_field=output_field or fields.IntegerField(), **extra)
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
def as_mysql(self, compiler, connection):
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().as_sql(compiler, connection, function='CHAR_LENGTH')
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
|
2015-08-03 10:30:06 +08:00
|
|
|
class Lower(Transform):
|
2014-11-22 11:14:43 +08:00
|
|
|
function = 'LOWER'
|
2015-08-03 10:30:06 +08:00
|
|
|
lookup_name = 'lower'
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
|
2015-05-29 22:54:10 +08:00
|
|
|
class Now(Func):
|
|
|
|
template = 'CURRENT_TIMESTAMP'
|
|
|
|
|
|
|
|
def __init__(self, output_field=None, **extra):
|
|
|
|
if output_field is None:
|
2016-03-26 06:49:45 +08:00
|
|
|
output_field = fields.DateTimeField()
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(output_field=output_field, **extra)
|
2015-05-29 22:54:10 +08:00
|
|
|
|
|
|
|
def as_postgresql(self, compiler, connection):
|
|
|
|
# Postgres' CURRENT_TIMESTAMP means "the time at the start of the
|
|
|
|
# transaction". We use STATEMENT_TIMESTAMP to be cross-compatible with
|
|
|
|
# other databases.
|
2016-03-16 23:05:24 +08:00
|
|
|
return self.as_sql(compiler, connection, template='STATEMENT_TIMESTAMP()')
|
2015-05-29 22:54:10 +08:00
|
|
|
|
|
|
|
|
2017-02-21 14:43:38 +08:00
|
|
|
class StrIndex(Func):
|
|
|
|
"""
|
|
|
|
Return a positive integer corresponding to the 1-indexed position of the
|
|
|
|
first occurrence of a substring inside another string, or 0 if the
|
|
|
|
substring is not found.
|
|
|
|
"""
|
|
|
|
function = 'INSTR'
|
|
|
|
arity = 2
|
|
|
|
|
|
|
|
def __init__(self, expression, substring, **extra):
|
|
|
|
"""
|
|
|
|
expression: the name of a field, or an expression returning a string
|
|
|
|
substring: a string to find inside expression
|
|
|
|
"""
|
|
|
|
if not hasattr(substring, 'resolve_expression'):
|
|
|
|
substring = Value(substring)
|
|
|
|
expressions = [expression, substring]
|
|
|
|
super().__init__(*expressions, output_field=fields.IntegerField(), **extra)
|
|
|
|
|
|
|
|
def as_postgresql(self, compiler, connection):
|
|
|
|
return super().as_sql(compiler, connection, function='STRPOS')
|
|
|
|
|
|
|
|
|
2014-11-22 11:14:43 +08:00
|
|
|
class Substr(Func):
|
|
|
|
function = 'SUBSTRING'
|
|
|
|
|
|
|
|
def __init__(self, expression, pos, length=None, **extra):
|
|
|
|
"""
|
|
|
|
expression: the name of a field, or an expression returning a string
|
|
|
|
pos: an integer > 0, or an expression returning an integer
|
|
|
|
length: an optional number of characters to return
|
|
|
|
"""
|
2015-01-20 08:47:13 +08:00
|
|
|
if not hasattr(pos, 'resolve_expression'):
|
2014-11-22 11:14:43 +08:00
|
|
|
if pos < 1:
|
|
|
|
raise ValueError("'pos' must be greater than 0")
|
|
|
|
expressions = [expression, pos]
|
|
|
|
if length is not None:
|
|
|
|
expressions.append(length)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*expressions, **extra)
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
def as_sqlite(self, compiler, connection):
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().as_sql(compiler, connection, function='SUBSTR')
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
def as_oracle(self, compiler, connection):
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().as_sql(compiler, connection, function='SUBSTR')
|
2014-11-22 11:14:43 +08:00
|
|
|
|
|
|
|
|
2015-08-03 10:30:06 +08:00
|
|
|
class Upper(Transform):
|
2014-11-22 11:14:43 +08:00
|
|
|
function = 'UPPER'
|
2015-08-03 10:30:06 +08:00
|
|
|
lookup_name = 'upper'
|