constraints.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. from django.db import NotSupportedError
  2. from django.db.backends.ddl_references import Statement, Table
  3. from django.db.models import Deferrable, F, Q
  4. from django.db.models.constraints import BaseConstraint
  5. from django.db.models.sql import Query
  6. __all__ = ['ExclusionConstraint']
  7. class ExclusionConstraint(BaseConstraint):
  8. template = 'CONSTRAINT %(name)s EXCLUDE USING %(index_type)s (%(expressions)s)%(include)s%(where)s%(deferrable)s'
  9. def __init__(
  10. self, *, name, expressions, index_type=None, condition=None,
  11. deferrable=None, include=None, opclasses=(),
  12. ):
  13. if index_type and index_type.lower() not in {'gist', 'spgist'}:
  14. raise ValueError(
  15. 'Exclusion constraints only support GiST or SP-GiST indexes.'
  16. )
  17. if not expressions:
  18. raise ValueError(
  19. 'At least one expression is required to define an exclusion '
  20. 'constraint.'
  21. )
  22. if not all(
  23. isinstance(expr, (list, tuple)) and len(expr) == 2
  24. for expr in expressions
  25. ):
  26. raise ValueError('The expressions must be a list of 2-tuples.')
  27. if not isinstance(condition, (type(None), Q)):
  28. raise ValueError(
  29. 'ExclusionConstraint.condition must be a Q instance.'
  30. )
  31. if condition and deferrable:
  32. raise ValueError(
  33. 'ExclusionConstraint with conditions cannot be deferred.'
  34. )
  35. if not isinstance(deferrable, (type(None), Deferrable)):
  36. raise ValueError(
  37. 'ExclusionConstraint.deferrable must be a Deferrable instance.'
  38. )
  39. if not isinstance(include, (type(None), list, tuple)):
  40. raise ValueError(
  41. 'ExclusionConstraint.include must be a list or tuple.'
  42. )
  43. if include and index_type and index_type.lower() != 'gist':
  44. raise ValueError(
  45. 'Covering exclusion constraints only support GiST indexes.'
  46. )
  47. if not isinstance(opclasses, (list, tuple)):
  48. raise ValueError(
  49. 'ExclusionConstraint.opclasses must be a list or tuple.'
  50. )
  51. if opclasses and len(expressions) != len(opclasses):
  52. raise ValueError(
  53. 'ExclusionConstraint.expressions and '
  54. 'ExclusionConstraint.opclasses must have the same number of '
  55. 'elements.'
  56. )
  57. self.expressions = expressions
  58. self.index_type = index_type or 'GIST'
  59. self.condition = condition
  60. self.deferrable = deferrable
  61. self.include = tuple(include) if include else ()
  62. self.opclasses = opclasses
  63. super().__init__(name=name)
  64. def _get_expression_sql(self, compiler, schema_editor, query):
  65. expressions = []
  66. for idx, (expression, operator) in enumerate(self.expressions):
  67. if isinstance(expression, str):
  68. expression = F(expression)
  69. expression = expression.resolve_expression(query=query)
  70. sql, params = compiler.compile(expression)
  71. try:
  72. opclass = self.opclasses[idx]
  73. if opclass:
  74. sql = '%s %s' % (sql, opclass)
  75. except IndexError:
  76. pass
  77. sql = sql % tuple(schema_editor.quote_value(p) for p in params)
  78. expressions.append('%s WITH %s' % (sql, operator))
  79. return expressions
  80. def _get_condition_sql(self, compiler, schema_editor, query):
  81. if self.condition is None:
  82. return None
  83. where = query.build_where(self.condition)
  84. sql, params = where.as_sql(compiler, schema_editor.connection)
  85. return sql % tuple(schema_editor.quote_value(p) for p in params)
  86. def constraint_sql(self, model, schema_editor):
  87. query = Query(model, alias_cols=False)
  88. compiler = query.get_compiler(connection=schema_editor.connection)
  89. expressions = self._get_expression_sql(compiler, schema_editor, query)
  90. condition = self._get_condition_sql(compiler, schema_editor, query)
  91. include = [model._meta.get_field(field_name).column for field_name in self.include]
  92. return self.template % {
  93. 'name': schema_editor.quote_name(self.name),
  94. 'index_type': self.index_type,
  95. 'expressions': ', '.join(expressions),
  96. 'include': schema_editor._index_include_sql(model, include),
  97. 'where': ' WHERE (%s)' % condition if condition else '',
  98. 'deferrable': schema_editor._deferrable_constraint_sql(self.deferrable),
  99. }
  100. def create_sql(self, model, schema_editor):
  101. self.check_supported(schema_editor)
  102. return Statement(
  103. 'ALTER TABLE %(table)s ADD %(constraint)s',
  104. table=Table(model._meta.db_table, schema_editor.quote_name),
  105. constraint=self.constraint_sql(model, schema_editor),
  106. )
  107. def remove_sql(self, model, schema_editor):
  108. return schema_editor._delete_constraint_sql(
  109. schema_editor.sql_delete_check,
  110. model,
  111. schema_editor.quote_name(self.name),
  112. )
  113. def check_supported(self, schema_editor):
  114. if self.include and not schema_editor.connection.features.supports_covering_gist_indexes:
  115. raise NotSupportedError(
  116. 'Covering exclusion constraints requires PostgreSQL 12+.'
  117. )
  118. def deconstruct(self):
  119. path, args, kwargs = super().deconstruct()
  120. kwargs['expressions'] = self.expressions
  121. if self.condition is not None:
  122. kwargs['condition'] = self.condition
  123. if self.index_type.lower() != 'gist':
  124. kwargs['index_type'] = self.index_type
  125. if self.deferrable:
  126. kwargs['deferrable'] = self.deferrable
  127. if self.include:
  128. kwargs['include'] = self.include
  129. if self.opclasses:
  130. kwargs['opclasses'] = self.opclasses
  131. return path, args, kwargs
  132. def __eq__(self, other):
  133. if isinstance(other, self.__class__):
  134. return (
  135. self.name == other.name and
  136. self.index_type == other.index_type and
  137. self.expressions == other.expressions and
  138. self.condition == other.condition and
  139. self.deferrable == other.deferrable and
  140. self.include == other.include and
  141. self.opclasses == other.opclasses
  142. )
  143. return super().__eq__(other)
  144. def __repr__(self):
  145. return '<%s: index_type=%s, expressions=%s%s%s%s%s>' % (
  146. self.__class__.__qualname__,
  147. self.index_type,
  148. self.expressions,
  149. '' if self.condition is None else ', condition=%s' % self.condition,
  150. '' if self.deferrable is None else ', deferrable=%s' % self.deferrable,
  151. '' if not self.include else ', include=%s' % repr(self.include),
  152. '' if not self.opclasses else ', opclasses=%s' % repr(self.opclasses),
  153. )