constraints.py 8.0 KB

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