Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

constraints.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 condition and deferrable:
  48. raise ValueError("ExclusionConstraint with conditions cannot be deferred.")
  49. if not isinstance(deferrable, (type(None), Deferrable)):
  50. raise ValueError(
  51. "ExclusionConstraint.deferrable must be a Deferrable instance."
  52. )
  53. if not isinstance(include, (type(None), list, tuple)):
  54. raise ValueError("ExclusionConstraint.include must be a list or tuple.")
  55. if not isinstance(opclasses, (list, tuple)):
  56. raise ValueError("ExclusionConstraint.opclasses must be a list or tuple.")
  57. if opclasses and len(expressions) != len(opclasses):
  58. raise ValueError(
  59. "ExclusionConstraint.expressions and "
  60. "ExclusionConstraint.opclasses must have the same number of "
  61. "elements."
  62. )
  63. self.expressions = expressions
  64. self.index_type = index_type or "GIST"
  65. self.condition = condition
  66. self.deferrable = deferrable
  67. self.include = tuple(include) if include else ()
  68. self.opclasses = opclasses
  69. if self.opclasses:
  70. warnings.warn(
  71. "The opclasses argument is deprecated in favor of using "
  72. "django.contrib.postgres.indexes.OpClass in "
  73. "ExclusionConstraint.expressions.",
  74. category=RemovedInDjango50Warning,
  75. stacklevel=2,
  76. )
  77. super().__init__(name=name, violation_error_message=violation_error_message)
  78. def _get_expressions(self, schema_editor, query):
  79. expressions = []
  80. for idx, (expression, operator) in enumerate(self.expressions):
  81. if isinstance(expression, str):
  82. expression = F(expression)
  83. try:
  84. expression = OpClass(expression, self.opclasses[idx])
  85. except IndexError:
  86. pass
  87. expression = ExclusionConstraintExpression(expression, operator=operator)
  88. expression.set_wrapper_classes(schema_editor.connection)
  89. expressions.append(expression)
  90. return ExpressionList(*expressions).resolve_expression(query)
  91. def _get_condition_sql(self, compiler, schema_editor, query):
  92. if self.condition is None:
  93. return None
  94. where = query.build_where(self.condition)
  95. sql, params = where.as_sql(compiler, schema_editor.connection)
  96. return sql % tuple(schema_editor.quote_value(p) for p in params)
  97. def constraint_sql(self, model, schema_editor):
  98. query = Query(model, alias_cols=False)
  99. compiler = query.get_compiler(connection=schema_editor.connection)
  100. expressions = self._get_expressions(schema_editor, query)
  101. table = model._meta.db_table
  102. condition = self._get_condition_sql(compiler, schema_editor, query)
  103. include = [
  104. model._meta.get_field(field_name).column for field_name in self.include
  105. ]
  106. return Statement(
  107. self.template,
  108. table=Table(table, schema_editor.quote_name),
  109. name=schema_editor.quote_name(self.name),
  110. index_type=self.index_type,
  111. expressions=Expressions(
  112. table, expressions, compiler, schema_editor.quote_value
  113. ),
  114. where=" WHERE (%s)" % condition if condition else "",
  115. include=schema_editor._index_include_sql(model, include),
  116. deferrable=schema_editor._deferrable_constraint_sql(self.deferrable),
  117. )
  118. def create_sql(self, model, schema_editor):
  119. self.check_supported(schema_editor)
  120. return Statement(
  121. "ALTER TABLE %(table)s ADD %(constraint)s",
  122. table=Table(model._meta.db_table, schema_editor.quote_name),
  123. constraint=self.constraint_sql(model, schema_editor),
  124. )
  125. def remove_sql(self, model, schema_editor):
  126. return schema_editor._delete_constraint_sql(
  127. schema_editor.sql_delete_check,
  128. model,
  129. schema_editor.quote_name(self.name),
  130. )
  131. def check_supported(self, schema_editor):
  132. if (
  133. self.include
  134. and self.index_type.lower() == "gist"
  135. and not schema_editor.connection.features.supports_covering_gist_indexes
  136. ):
  137. raise NotSupportedError(
  138. "Covering exclusion constraints using a GiST index require "
  139. "PostgreSQL 12+."
  140. )
  141. if (
  142. self.include
  143. and self.index_type.lower() == "spgist"
  144. and not schema_editor.connection.features.supports_covering_spgist_indexes
  145. ):
  146. raise NotSupportedError(
  147. "Covering exclusion constraints using an SP-GiST index "
  148. "require PostgreSQL 14+."
  149. )
  150. def deconstruct(self):
  151. path, args, kwargs = super().deconstruct()
  152. kwargs["expressions"] = self.expressions
  153. if self.condition is not None:
  154. kwargs["condition"] = self.condition
  155. if self.index_type.lower() != "gist":
  156. kwargs["index_type"] = self.index_type
  157. if self.deferrable:
  158. kwargs["deferrable"] = self.deferrable
  159. if self.include:
  160. kwargs["include"] = self.include
  161. if self.opclasses:
  162. kwargs["opclasses"] = self.opclasses
  163. return path, args, kwargs
  164. def __eq__(self, other):
  165. if isinstance(other, self.__class__):
  166. return (
  167. self.name == other.name
  168. and self.index_type == other.index_type
  169. and self.expressions == other.expressions
  170. and self.condition == other.condition
  171. and self.deferrable == other.deferrable
  172. and self.include == other.include
  173. and self.opclasses == other.opclasses
  174. and self.violation_error_message == other.violation_error_message
  175. )
  176. return super().__eq__(other)
  177. def __repr__(self):
  178. return "<%s: index_type=%s expressions=%s name=%s%s%s%s%s>" % (
  179. self.__class__.__qualname__,
  180. repr(self.index_type),
  181. repr(self.expressions),
  182. repr(self.name),
  183. "" if self.condition is None else " condition=%s" % self.condition,
  184. "" if self.deferrable is None else " deferrable=%r" % self.deferrable,
  185. "" if not self.include else " include=%s" % repr(self.include),
  186. "" if not self.opclasses else " opclasses=%s" % repr(self.opclasses),
  187. )
  188. def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS):
  189. queryset = model._default_manager.using(using)
  190. replacement_map = instance._get_field_value_map(
  191. meta=model._meta, exclude=exclude
  192. )
  193. lookups = []
  194. for idx, (expression, operator) in enumerate(self.expressions):
  195. if isinstance(expression, str):
  196. expression = F(expression)
  197. if isinstance(expression, F):
  198. if exclude and expression.name in exclude:
  199. return
  200. rhs_expression = replacement_map.get(expression.name, expression)
  201. else:
  202. rhs_expression = expression.replace_references(replacement_map)
  203. if exclude:
  204. for expr in rhs_expression.flatten():
  205. if isinstance(expr, F) and expr.name in exclude:
  206. return
  207. # Remove OpClass because it only has sense during the constraint
  208. # creation.
  209. if isinstance(expression, OpClass):
  210. expression = expression.get_source_expressions()[0]
  211. if isinstance(rhs_expression, OpClass):
  212. rhs_expression = rhs_expression.get_source_expressions()[0]
  213. lookup = PostgresOperatorLookup(lhs=expression, rhs=rhs_expression)
  214. lookup.postgres_operator = operator
  215. lookups.append(lookup)
  216. queryset = queryset.filter(*lookups)
  217. model_class_pk = instance._get_pk_val(model._meta)
  218. if not instance._state.adding and model_class_pk is not None:
  219. queryset = queryset.exclude(pk=model_class_pk)
  220. if not self.condition:
  221. if queryset.exists():
  222. raise ValidationError(self.get_violation_error_message())
  223. else:
  224. if (self.condition & Exists(queryset.filter(self.condition))).check(
  225. replacement_map, using=using
  226. ):
  227. raise ValidationError(self.get_violation_error_message())