You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

comparison.py 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. """Database functions that do comparisons or type conversions."""
  2. from django.db.models.expressions import Func, Value
  3. class Cast(Func):
  4. """Coerce an expression to a new field type."""
  5. function = 'CAST'
  6. template = '%(function)s(%(expressions)s AS %(db_type)s)'
  7. def __init__(self, expression, output_field):
  8. super().__init__(expression, output_field=output_field)
  9. def as_sql(self, compiler, connection, **extra_context):
  10. extra_context['db_type'] = self.output_field.cast_db_type(connection)
  11. return super().as_sql(compiler, connection, **extra_context)
  12. def as_sqlite(self, compiler, connection, **extra_context):
  13. db_type = self.output_field.db_type(connection)
  14. if db_type in {'datetime', 'time'}:
  15. # Use strftime as datetime/time don't keep fractional seconds.
  16. template = 'strftime(%%s, %(expressions)s)'
  17. sql, params = super().as_sql(compiler, connection, template=template, **extra_context)
  18. format_string = '%H:%M:%f' if db_type == 'time' else '%Y-%m-%d %H:%M:%f'
  19. params.insert(0, format_string)
  20. return sql, params
  21. elif db_type == 'date':
  22. template = 'date(%(expressions)s)'
  23. return super().as_sql(compiler, connection, template=template, **extra_context)
  24. return self.as_sql(compiler, connection, **extra_context)
  25. def as_mysql(self, compiler, connection, **extra_context):
  26. # MySQL doesn't support explicit cast to float.
  27. template = '(%(expressions)s + 0.0)' if self.output_field.get_internal_type() == 'FloatField' else None
  28. return self.as_sql(compiler, connection, template=template, **extra_context)
  29. def as_postgresql(self, compiler, connection, **extra_context):
  30. # CAST would be valid too, but the :: shortcut syntax is more readable.
  31. # 'expressions' is wrapped in parentheses in case it's a complex
  32. # expression.
  33. return self.as_sql(compiler, connection, template='(%(expressions)s)::%(db_type)s', **extra_context)
  34. class Coalesce(Func):
  35. """Return, from left to right, the first non-null expression."""
  36. function = 'COALESCE'
  37. def __init__(self, *expressions, **extra):
  38. if len(expressions) < 2:
  39. raise ValueError('Coalesce must take at least two expressions')
  40. super().__init__(*expressions, **extra)
  41. def as_oracle(self, compiler, connection, **extra_context):
  42. # Oracle prohibits mixing TextField (NCLOB) and CharField (NVARCHAR2),
  43. # so convert all fields to NCLOB when that type is expected.
  44. if self.output_field.get_internal_type() == 'TextField':
  45. clone = self.copy()
  46. clone.set_source_expressions([
  47. Func(expression, function='TO_NCLOB') for expression in self.get_source_expressions()
  48. ])
  49. return super(Coalesce, clone).as_sql(compiler, connection, **extra_context)
  50. return self.as_sql(compiler, connection, **extra_context)
  51. class Greatest(Func):
  52. """
  53. Return the maximum expression.
  54. If any expression is null the return value is database-specific:
  55. On PostgreSQL, the maximum not-null expression is returned.
  56. On MySQL, Oracle, and SQLite, if any expression is null, null is returned.
  57. """
  58. function = 'GREATEST'
  59. def __init__(self, *expressions, **extra):
  60. if len(expressions) < 2:
  61. raise ValueError('Greatest must take at least two expressions')
  62. super().__init__(*expressions, **extra)
  63. def as_sqlite(self, compiler, connection, **extra_context):
  64. """Use the MAX function on SQLite."""
  65. return super().as_sqlite(compiler, connection, function='MAX', **extra_context)
  66. class Least(Func):
  67. """
  68. Return the minimum expression.
  69. If any expression is null the return value is database-specific:
  70. On PostgreSQL, return the minimum not-null expression.
  71. On MySQL, Oracle, and SQLite, if any expression is null, return null.
  72. """
  73. function = 'LEAST'
  74. def __init__(self, *expressions, **extra):
  75. if len(expressions) < 2:
  76. raise ValueError('Least must take at least two expressions')
  77. super().__init__(*expressions, **extra)
  78. def as_sqlite(self, compiler, connection, **extra_context):
  79. """Use the MIN function on SQLite."""
  80. return super().as_sqlite(compiler, connection, function='MIN', **extra_context)
  81. class NullIf(Func):
  82. function = 'NULLIF'
  83. arity = 2
  84. def as_oracle(self, compiler, connection, **extra_context):
  85. expression1 = self.get_source_expressions()[0]
  86. if isinstance(expression1, Value) and expression1.value is None:
  87. raise ValueError('Oracle does not allow Value(None) for expression1.')
  88. return super().as_sql(compiler, connection, **extra_context)