constraints.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import warnings
  2. from django.contrib.postgres.indexes import OpClass
  3. from django.core.exceptions import ValidationError
  4. from django.db import DEFAULT_DB_ALIAS, NotSupportedError
  5. from django.db.backends.ddl_references import Expressions, Statement, Table
  6. from django.db.models import BaseConstraint, Deferrable, F, Q
  7. from django.db.models.expressions import Exists, ExpressionList
  8. from django.db.models.indexes import IndexExpression
  9. from django.db.models.lookups import PostgresOperatorLookup
  10. from django.db.models.sql import Query
  11. from django.utils.deprecation import RemovedInDjango50Warning
  12. __all__ = ["ExclusionConstraint"]
  13. class ExclusionConstraintExpression(IndexExpression):
  14. template = "%(expressions)s WITH %(operator)s"
  15. class ExclusionConstraint(BaseConstraint):
  16. template = (
  17. "CONSTRAINT %(name)s EXCLUDE USING %(index_type)s "
  18. "(%(expressions)s)%(include)s%(where)s%(deferrable)s"
  19. )
  20. def __init__(
  21. self,
  22. *,
  23. name,
  24. expressions,
  25. index_type=None,
  26. condition=None,
  27. deferrable=None,
  28. include=None,
  29. opclasses=(),
  30. violation_error_message=None,
  31. ):
  32. if index_type and index_type.lower() not in {"gist", "spgist"}:
  33. raise ValueError(
  34. "Exclusion constraints only support GiST or SP-GiST indexes."
  35. )
  36. if not expressions:
  37. raise ValueError(
  38. "At least one expression is required to define an exclusion "
  39. "constraint."
  40. )
  41. if not all(
  42. isinstance(expr, (list, tuple)) and len(expr) == 2 for expr in expressions
  43. ):
  44. raise ValueError("The expressions must be a list of 2-tuples.")
  45. if not isinstance(condition, (type(None), Q)):
  46. raise ValueError("ExclusionConstraint.condition must be a Q instance.")
  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, violation_error_message=violation_error_message)
  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() == "spgist"
  133. and not schema_editor.connection.features.supports_covering_spgist_indexes
  134. ):
  135. raise NotSupportedError(
  136. "Covering exclusion constraints using an SP-GiST index "
  137. "require PostgreSQL 14+."
  138. )
  139. def deconstruct(self):
  140. path, args, kwargs = super().deconstruct()
  141. kwargs["expressions"] = self.expressions
  142. if self.condition is not None:
  143. kwargs["condition"] = self.condition
  144. if self.index_type.lower() != "gist":
  145. kwargs["index_type"] = self.index_type
  146. if self.deferrable:
  147. kwargs["deferrable"] = self.deferrable
  148. if self.include:
  149. kwargs["include"] = self.include
  150. if self.opclasses:
  151. kwargs["opclasses"] = self.opclasses
  152. return path, args, kwargs
  153. def __eq__(self, other):
  154. if isinstance(other, self.__class__):
  155. return (
  156. self.name == other.name
  157. and self.index_type == other.index_type
  158. and self.expressions == other.expressions
  159. and self.condition == other.condition
  160. and self.deferrable == other.deferrable
  161. and self.include == other.include
  162. and self.opclasses == other.opclasses
  163. and self.violation_error_message == other.violation_error_message
  164. )
  165. return super().__eq__(other)
  166. def __repr__(self):
  167. return "<%s: index_type=%s expressions=%s name=%s%s%s%s%s>" % (
  168. self.__class__.__qualname__,
  169. repr(self.index_type),
  170. repr(self.expressions),
  171. repr(self.name),
  172. "" if self.condition is None else " condition=%s" % self.condition,
  173. "" if self.deferrable is None else " deferrable=%r" % self.deferrable,
  174. "" if not self.include else " include=%s" % repr(self.include),
  175. "" if not self.opclasses else " opclasses=%s" % repr(self.opclasses),
  176. )
  177. def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS):
  178. queryset = model._default_manager.using(using)
  179. replacement_map = instance._get_field_value_map(
  180. meta=model._meta, exclude=exclude
  181. )
  182. replacements = {F(field): value for field, value in replacement_map.items()}
  183. lookups = []
  184. for idx, (expression, operator) in enumerate(self.expressions):
  185. if isinstance(expression, str):
  186. expression = F(expression)
  187. if exclude:
  188. if isinstance(expression, F):
  189. if expression.name in exclude:
  190. return
  191. else:
  192. for expr in expression.flatten():
  193. if isinstance(expr, F) and expr.name in exclude:
  194. return
  195. rhs_expression = expression.replace_expressions(replacements)
  196. # Remove OpClass because it only has sense during the constraint
  197. # creation.
  198. if isinstance(expression, OpClass):
  199. expression = expression.get_source_expressions()[0]
  200. if isinstance(rhs_expression, OpClass):
  201. rhs_expression = rhs_expression.get_source_expressions()[0]
  202. lookup = PostgresOperatorLookup(lhs=expression, rhs=rhs_expression)
  203. lookup.postgres_operator = operator
  204. lookups.append(lookup)
  205. queryset = queryset.filter(*lookups)
  206. model_class_pk = instance._get_pk_val(model._meta)
  207. if not instance._state.adding and model_class_pk is not None:
  208. queryset = queryset.exclude(pk=model_class_pk)
  209. if not self.condition:
  210. if queryset.exists():
  211. raise ValidationError(self.get_violation_error_message())
  212. else:
  213. if (self.condition & Exists(queryset.filter(self.condition))).check(
  214. replacement_map, using=using
  215. ):
  216. raise ValidationError(self.get_violation_error_message())