constraints.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. from django.db.backends.ddl_references import Statement, Table
  2. from django.db.models import F, Q
  3. from django.db.models.constraints import BaseConstraint
  4. from django.db.models.sql import Query
  5. __all__ = ['ExclusionConstraint']
  6. class ExclusionConstraint(BaseConstraint):
  7. template = 'CONSTRAINT %(name)s EXCLUDE USING %(index_type)s (%(expressions)s)%(where)s'
  8. def __init__(self, *, name, expressions, index_type=None, condition=None):
  9. if index_type and index_type.lower() not in {'gist', 'spgist'}:
  10. raise ValueError(
  11. 'Exclusion constraints only support GiST or SP-GiST indexes.'
  12. )
  13. if not expressions:
  14. raise ValueError(
  15. 'At least one expression is required to define an exclusion '
  16. 'constraint.'
  17. )
  18. if not all(
  19. isinstance(expr, (list, tuple)) and len(expr) == 2
  20. for expr in expressions
  21. ):
  22. raise ValueError('The expressions must be a list of 2-tuples.')
  23. if not isinstance(condition, (type(None), Q)):
  24. raise ValueError(
  25. 'ExclusionConstraint.condition must be a Q instance.'
  26. )
  27. self.expressions = expressions
  28. self.index_type = index_type or 'GIST'
  29. self.condition = condition
  30. super().__init__(name=name)
  31. def _get_expression_sql(self, compiler, connection, query):
  32. expressions = []
  33. for expression, operator in self.expressions:
  34. if isinstance(expression, str):
  35. expression = F(expression)
  36. if isinstance(expression, F):
  37. expression = expression.resolve_expression(query=query, simple_col=True)
  38. else:
  39. expression = expression.resolve_expression(query=query)
  40. sql, params = expression.as_sql(compiler, connection)
  41. expressions.append('%s WITH %s' % (sql % params, operator))
  42. return expressions
  43. def _get_condition_sql(self, compiler, schema_editor, query):
  44. if self.condition is None:
  45. return None
  46. where = query.build_where(self.condition)
  47. sql, params = where.as_sql(compiler, schema_editor.connection)
  48. return sql % tuple(schema_editor.quote_value(p) for p in params)
  49. def constraint_sql(self, model, schema_editor):
  50. query = Query(model)
  51. compiler = query.get_compiler(connection=schema_editor.connection)
  52. expressions = self._get_expression_sql(compiler, schema_editor.connection, query)
  53. condition = self._get_condition_sql(compiler, schema_editor, query)
  54. return self.template % {
  55. 'name': schema_editor.quote_name(self.name),
  56. 'index_type': self.index_type,
  57. 'expressions': ', '.join(expressions),
  58. 'where': ' WHERE (%s)' % condition if condition else '',
  59. }
  60. def create_sql(self, model, schema_editor):
  61. return Statement(
  62. 'ALTER TABLE %(table)s ADD %(constraint)s',
  63. table=Table(model._meta.db_table, schema_editor.quote_name),
  64. constraint=self.constraint_sql(model, schema_editor),
  65. )
  66. def remove_sql(self, model, schema_editor):
  67. return schema_editor._delete_constraint_sql(
  68. schema_editor.sql_delete_check,
  69. model,
  70. schema_editor.quote_name(self.name),
  71. )
  72. def deconstruct(self):
  73. path, args, kwargs = super().deconstruct()
  74. kwargs['expressions'] = self.expressions
  75. if self.condition is not None:
  76. kwargs['condition'] = self.condition
  77. if self.index_type.lower() != 'gist':
  78. kwargs['index_type'] = self.index_type
  79. return path, args, kwargs
  80. def __eq__(self, other):
  81. return (
  82. isinstance(other, self.__class__) and
  83. self.name == other.name and
  84. self.index_type == other.index_type and
  85. self.expressions == other.expressions and
  86. self.condition == other.condition
  87. )
  88. def __repr__(self):
  89. return '<%s: index_type=%s, expressions=%s%s>' % (
  90. self.__class__.__qualname__,
  91. self.index_type,
  92. self.expressions,
  93. '' if self.condition is None else ', condition=%s' % self.condition,
  94. )