comparison.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. """Database functions that do comparisons or type conversions."""
  2. from django.db.models.expressions import Func, Value
  3. from django.utils.regex_helper import _lazy_re_compile
  4. class Cast(Func):
  5. """Coerce an expression to a new field type."""
  6. function = "CAST"
  7. template = "%(function)s(%(expressions)s AS %(db_type)s)"
  8. def __init__(self, expression, output_field):
  9. super().__init__(expression, output_field=output_field)
  10. def as_sql(self, compiler, connection, **extra_context):
  11. extra_context["db_type"] = self.output_field.cast_db_type(connection)
  12. return super().as_sql(compiler, connection, **extra_context)
  13. def as_sqlite(self, compiler, connection, **extra_context):
  14. db_type = self.output_field.db_type(connection)
  15. if db_type in {"datetime", "time"}:
  16. # Use strftime as datetime/time don't keep fractional seconds.
  17. template = "strftime(%%s, %(expressions)s)"
  18. sql, params = super().as_sql(
  19. compiler, connection, template=template, **extra_context
  20. )
  21. format_string = "%H:%M:%f" if db_type == "time" else "%Y-%m-%d %H:%M:%f"
  22. params = (format_string, *params)
  23. return sql, params
  24. elif db_type == "date":
  25. template = "date(%(expressions)s)"
  26. return super().as_sql(
  27. compiler, connection, template=template, **extra_context
  28. )
  29. return self.as_sql(compiler, connection, **extra_context)
  30. def as_mysql(self, compiler, connection, **extra_context):
  31. template = None
  32. output_type = self.output_field.get_internal_type()
  33. # MySQL doesn't support explicit cast to float.
  34. if output_type == "FloatField":
  35. template = "(%(expressions)s + 0.0)"
  36. # MariaDB doesn't support explicit cast to JSON.
  37. elif output_type == "JSONField" and connection.mysql_is_mariadb:
  38. template = "JSON_EXTRACT(%(expressions)s, '$')"
  39. return self.as_sql(compiler, connection, template=template, **extra_context)
  40. def as_postgresql(self, compiler, connection, **extra_context):
  41. # CAST would be valid too, but the :: shortcut syntax is more readable.
  42. # 'expressions' is wrapped in parentheses in case it's a complex
  43. # expression.
  44. return self.as_sql(
  45. compiler,
  46. connection,
  47. template="(%(expressions)s)::%(db_type)s",
  48. **extra_context,
  49. )
  50. def as_oracle(self, compiler, connection, **extra_context):
  51. if self.output_field.get_internal_type() == "JSONField":
  52. # Oracle doesn't support explicit cast to JSON.
  53. template = "JSON_QUERY(%(expressions)s, '$')"
  54. return super().as_sql(
  55. compiler, connection, template=template, **extra_context
  56. )
  57. return self.as_sql(compiler, connection, **extra_context)
  58. class Coalesce(Func):
  59. """Return, from left to right, the first non-null expression."""
  60. function = "COALESCE"
  61. def __init__(self, *expressions, **extra):
  62. if len(expressions) < 2:
  63. raise ValueError("Coalesce must take at least two expressions")
  64. super().__init__(*expressions, **extra)
  65. @property
  66. def empty_result_set_value(self):
  67. for expression in self.get_source_expressions():
  68. result = expression.empty_result_set_value
  69. if result is NotImplemented or result is not None:
  70. return result
  71. return None
  72. def as_oracle(self, compiler, connection, **extra_context):
  73. # Oracle prohibits mixing TextField, JSONField (NCLOB) and CharField
  74. # (NVARCHAR2), so convert all fields to NCLOB when that type is
  75. # expected.
  76. if self.output_field.get_internal_type() in ("TextField", "JSONField"):
  77. clone = self.copy()
  78. clone.set_source_expressions(
  79. [
  80. Func(expression, function="TO_NCLOB")
  81. for expression in self.get_source_expressions()
  82. ]
  83. )
  84. return super(Coalesce, clone).as_sql(compiler, connection, **extra_context)
  85. return self.as_sql(compiler, connection, **extra_context)
  86. class Collate(Func):
  87. function = "COLLATE"
  88. template = "%(expressions)s %(function)s %(collation)s"
  89. allowed_default = False
  90. # Inspired from
  91. # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
  92. collation_re = _lazy_re_compile(r"^[\w-]+$")
  93. def __init__(self, expression, collation):
  94. if not (collation and self.collation_re.match(collation)):
  95. raise ValueError("Invalid collation name: %r." % collation)
  96. self.collation = collation
  97. super().__init__(expression)
  98. def as_sql(self, compiler, connection, **extra_context):
  99. extra_context.setdefault("collation", connection.ops.quote_name(self.collation))
  100. return super().as_sql(compiler, connection, **extra_context)
  101. class Greatest(Func):
  102. """
  103. Return the maximum expression.
  104. If any expression is null the return value is database-specific:
  105. On PostgreSQL, the maximum not-null expression is returned.
  106. On MySQL, Oracle, and SQLite, if any expression is null, null is returned.
  107. """
  108. function = "GREATEST"
  109. def __init__(self, *expressions, **extra):
  110. if len(expressions) < 2:
  111. raise ValueError("Greatest must take at least two expressions")
  112. super().__init__(*expressions, **extra)
  113. def as_sqlite(self, compiler, connection, **extra_context):
  114. """Use the MAX function on SQLite."""
  115. return super().as_sqlite(compiler, connection, function="MAX", **extra_context)
  116. class Least(Func):
  117. """
  118. Return the minimum expression.
  119. If any expression is null the return value is database-specific:
  120. On PostgreSQL, return the minimum not-null expression.
  121. On MySQL, Oracle, and SQLite, if any expression is null, return null.
  122. """
  123. function = "LEAST"
  124. def __init__(self, *expressions, **extra):
  125. if len(expressions) < 2:
  126. raise ValueError("Least must take at least two expressions")
  127. super().__init__(*expressions, **extra)
  128. def as_sqlite(self, compiler, connection, **extra_context):
  129. """Use the MIN function on SQLite."""
  130. return super().as_sqlite(compiler, connection, function="MIN", **extra_context)
  131. class NullIf(Func):
  132. function = "NULLIF"
  133. arity = 2
  134. def as_oracle(self, compiler, connection, **extra_context):
  135. expression1 = self.get_source_expressions()[0]
  136. if isinstance(expression1, Value) and expression1.value is None:
  137. raise ValueError("Oracle does not allow Value(None) for expression1.")
  138. return super().as_sql(compiler, connection, **extra_context)