| 1 |
from types import NoneType |
| 2 |
|
| 3 |
from django.core.exceptions import ValidationError |
| 4 |
from django.db import DEFAULT_DB_ALIAS |
| 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 |
|
| 12 |
__all__ = ["ExclusionConstraint"] |
| 13 |
|
| 14 |
|
| 15 |
class ExclusionConstraintExpression(IndexExpression): |
| 16 |
template = "%(expressions)s WITH %(operator)s" |
| 17 |
|
| 18 |
|
| 19 |
class ExclusionConstraint(BaseConstraint): |
| 20 |
template = ( |
| 21 |
"CONSTRAINT %(name)s EXCLUDE USING %(index_type)s " |
| 22 |
"(%(expressions)s)%(include)s%(where)s%(deferrable)s" |
| 23 |
) |
| 24 |
|
| 25 |
def __init__( |
| 26 |
self, |
| 27 |
*, |
| 28 |
name, |
| 29 |
expressions, |
| 30 |
index_type=None, |
| 31 |
condition=None, |
| 32 |
deferrable=None, |
| 33 |
include=None, |
| 34 |
violation_error_code=None, |
| 35 |
violation_error_message=None, |
| 36 |
): |
| 37 |
if index_type and index_type.lower() not in {"gist", "spgist"}: |
| 38 |
raise ValueError( |
| 39 |
"Exclusion constraints only support GiST or SP-GiST indexes." |
| 40 |
) |
| 41 |
if not expressions: |
| 42 |
raise ValueError( |
| 43 |
"At least one expression is required to define an exclusion " |
| 44 |
"constraint." |
| 45 |
) |
| 46 |
if not all( |
| 47 |
isinstance(expr, (list, tuple)) and len(expr) == 2 for expr in expressions |
| 48 |
): |
| 49 |
raise ValueError("The expressions must be a list of 2-tuples.") |
| 50 |
if not isinstance(condition, (NoneType, Q)): |
| 51 |
raise ValueError("ExclusionConstraint.condition must be a Q instance.") |
| 52 |
if not isinstance(deferrable, (NoneType, Deferrable)): |
| 53 |
raise ValueError( |
| 54 |
"ExclusionConstraint.deferrable must be a Deferrable instance." |
| 55 |
) |
| 56 |
if not isinstance(include, (NoneType, list, tuple)): |
| 57 |
raise ValueError("ExclusionConstraint.include must be a list or tuple.") |
| 58 |
self.expressions = expressions |
| 59 |
self.index_type = index_type or "GIST" |
| 60 |
self.condition = condition |
| 61 |
self.deferrable = deferrable |
| 62 |
self.include = tuple(include) if include else () |
| 63 |
super().__init__( |
| 64 |
name=name, |
| 65 |
violation_error_code=violation_error_code, |
| 66 |
violation_error_message=violation_error_message, |
| 67 |
) |
| 68 |
|
| 69 |
def _get_expressions(self, schema_editor, query): |
| 70 |
expressions = [] |
| 71 |
for idx, (expression, operator) in enumerate(self.expressions): |
| 72 |
if isinstance(expression, str): |
| 73 |
expression = F(expression) |
| 74 |
expression = ExclusionConstraintExpression(expression, operator=operator) |
| 75 |
expression.set_wrapper_classes(schema_editor.connection) |
| 76 |
expressions.append(expression) |
| 77 |
return ExpressionList(*expressions).resolve_expression(query) |
| 78 |
|
| 79 |
def _check(self, model, connection): |
| 80 |
references = set() |
| 81 |
for expr, _ in self.expressions: |
| 82 |
if isinstance(expr, str): |
| 83 |
expr = F(expr) |
| 84 |
references.update(model._get_expr_references(expr)) |
| 85 |
return self._check_references(model, references) |
| 86 |
|
| 87 |
def _get_condition_sql(self, compiler, schema_editor, query): |
| 88 |
if self.condition is None: |
| 89 |
return None |
| 90 |
where = query.build_where(self.condition) |
| 91 |
sql, params = where.as_sql(compiler, schema_editor.connection) |
| 92 |
return sql % tuple(schema_editor.quote_value(p) for p in params) |
| 93 |
|
| 94 |
def constraint_sql(self, model, schema_editor): |
| 95 |
query = Query(model, alias_cols=False) |
| 96 |
compiler = query.get_compiler(connection=schema_editor.connection) |
| 97 |
expressions = self._get_expressions(schema_editor, query) |
| 98 |
table = model._meta.db_table |
| 99 |
condition = self._get_condition_sql(compiler, schema_editor, query) |
| 100 |
include = [ |
| 101 |
model._meta.get_field(field_name).column for field_name in self.include |
| 102 |
] |
| 103 |
return Statement( |
| 104 |
self.template, |
| 105 |
table=Table(table, schema_editor.quote_name), |
| 106 |
name=schema_editor.quote_name(self.name), |
| 107 |
index_type=self.index_type, |
| 108 |
expressions=Expressions( |
| 109 |
table, expressions, compiler, schema_editor.quote_value |
| 110 |
), |
| 111 |
where=" WHERE (%s)" % condition if condition else "", |
| 112 |
include=schema_editor._index_include_sql(model, include), |
| 113 |
deferrable=schema_editor._deferrable_constraint_sql(self.deferrable), |
| 114 |
) |
| 115 |
|
| 116 |
def create_sql(self, model, schema_editor): |
| 117 |
return Statement( |
| 118 |
"ALTER TABLE %(table)s ADD %(constraint)s", |
| 119 |
table=Table(model._meta.db_table, schema_editor.quote_name), |
| 120 |
constraint=self.constraint_sql(model, schema_editor), |
| 121 |
) |
| 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 |
|
| 130 |
def deconstruct(self): |
| 131 |
path, args, kwargs = super().deconstruct() |
| 132 |
kwargs["expressions"] = self.expressions |
| 133 |
if self.condition is not None: |
| 134 |
kwargs["condition"] = self.condition |
| 135 |
if self.index_type.lower() != "gist": |
| 136 |
kwargs["index_type"] = self.index_type |
| 137 |
if self.deferrable: |
| 138 |
kwargs["deferrable"] = self.deferrable |
| 139 |
if self.include: |
| 140 |
kwargs["include"] = self.include |
| 141 |
return path, args, kwargs |
| 142 |
|
| 143 |
def __eq__(self, other): |
| 144 |
if isinstance(other, self.__class__): |
| 145 |
return ( |
| 146 |
self.name == other.name |
| 147 |
and self.index_type == other.index_type |
| 148 |
and self.expressions == other.expressions |
| 149 |
and self.condition == other.condition |
| 150 |
and self.deferrable == other.deferrable |
| 151 |
and self.include == other.include |
| 152 |
and self.violation_error_code == other.violation_error_code |
| 153 |
and self.violation_error_message == other.violation_error_message |
| 154 |
) |
| 155 |
return super().__eq__(other) |
| 156 |
|
| 157 |
def __repr__(self): |
| 158 |
return "<%s: index_type=%s expressions=%s name=%s%s%s%s%s%s>" % ( |
| 159 |
self.__class__.__qualname__, |
| 160 |
repr(self.index_type), |
| 161 |
repr(self.expressions), |
| 162 |
repr(self.name), |
| 163 |
"" if self.condition is None else " condition=%s" % self.condition, |
| 164 |
"" if self.deferrable is None else " deferrable=%r" % self.deferrable, |
| 165 |
"" if not self.include else " include=%s" % repr(self.include), |
| 166 |
( |
| 167 |
"" |
| 168 |
if self.violation_error_code is None |
| 169 |
else " violation_error_code=%r" % self.violation_error_code |
| 170 |
), |
| 171 |
( |
| 172 |
"" |
| 173 |
if self.violation_error_message is None |
| 174 |
or self.violation_error_message == self.default_violation_error_message |
| 175 |
else " violation_error_message=%r" % self.violation_error_message |
| 176 |
), |
| 177 |
) |
| 178 |
|
| 179 |
def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): |
| 180 |
queryset = model._default_manager.using(using) |
| 181 |
replacement_map = instance._get_field_expression_map( |
| 182 |
meta=model._meta, exclude=exclude |
| 183 |
) |
| 184 |
replacements = {F(field): value for field, value in replacement_map.items()} |
| 185 |
lookups = [] |
| 186 |
for expression, operator in self.expressions: |
| 187 |
if isinstance(expression, str): |
| 188 |
expression = F(expression) |
| 189 |
if exclude and self._expression_refs_exclude(model, expression, exclude): |
| 190 |
return |
| 191 |
rhs_expression = expression.replace_expressions(replacements) |
| 192 |
if hasattr(expression, "get_expression_for_validation"): |
| 193 |
expression = expression.get_expression_for_validation() |
| 194 |
if hasattr(rhs_expression, "get_expression_for_validation"): |
| 195 |
rhs_expression = rhs_expression.get_expression_for_validation() |
| 196 |
lookup = PostgresOperatorLookup(lhs=expression, rhs=rhs_expression) |
| 197 |
lookup.postgres_operator = operator |
| 198 |
lookups.append(lookup) |
| 199 |
queryset = queryset.filter(*lookups) |
| 200 |
model_class_pk = instance._get_pk_val(model._meta) |
| 201 |
if not instance._state.adding and instance._is_pk_set(model._meta): |
| 202 |
queryset = queryset.exclude(pk=model_class_pk) |
| 203 |
if not self.condition: |
| 204 |
if queryset.exists(): |
| 205 |
raise ValidationError( |
| 206 |
self.get_violation_error_message(), code=self.violation_error_code |
| 207 |
) |
| 208 |
else: |
| 209 |
if (self.condition & Exists(queryset.filter(self.condition))).check( |
| 210 |
replacement_map, using=using |
| 211 |
): |
| 212 |
raise ValidationError( |
| 213 |
self.get_violation_error_message(), code=self.violation_error_code |
| 214 |
) |