| 1 |
import warnings |
| 2 |
from enum import Enum |
| 3 |
from types import NoneType |
| 4 |
|
| 5 |
from django.core import checks |
| 6 |
from django.core.exceptions import FieldDoesNotExist, FieldError, ValidationError |
| 7 |
from django.db import connections |
| 8 |
from django.db.models.constants import LOOKUP_SEP |
| 9 |
from django.db.models.expressions import Exists, ExpressionList, F, RawSQL |
| 10 |
from django.db.models.indexes import IndexExpression |
| 11 |
from django.db.models.lookups import Exact, IsNull |
| 12 |
from django.db.models.query_utils import Q |
| 13 |
from django.db.models.sql.query import Query |
| 14 |
from django.db.utils import DEFAULT_DB_ALIAS |
| 15 |
from django.utils.deprecation import RemovedInDjango60Warning |
| 16 |
from django.utils.translation import gettext_lazy as _ |
| 17 |
|
| 18 |
__all__ = ["BaseConstraint", "CheckConstraint", "Deferrable", "UniqueConstraint"] |
| 19 |
|
| 20 |
|
| 21 |
class BaseConstraint: |
| 22 |
default_violation_error_message = _("Constraint ā%(name)sā is violated.") |
| 23 |
violation_error_code = None |
| 24 |
violation_error_message = None |
| 25 |
|
| 26 |
non_db_attrs = ("violation_error_code", "violation_error_message") |
| 27 |
|
| 28 |
# RemovedInDjango60Warning: When the deprecation ends, replace with: |
| 29 |
# def __init__( |
| 30 |
# self, *, name, violation_error_code=None, violation_error_message=None |
| 31 |
# ): |
| 32 |
def __init__( |
| 33 |
self, *args, name=None, violation_error_code=None, violation_error_message=None |
| 34 |
): |
| 35 |
# RemovedInDjango60Warning. |
| 36 |
if name is None and not args: |
| 37 |
raise TypeError( |
| 38 |
f"{self.__class__.__name__}.__init__() missing 1 required keyword-only " |
| 39 |
f"argument: 'name'" |
| 40 |
) |
| 41 |
self.name = name |
| 42 |
if violation_error_code is not None: |
| 43 |
self.violation_error_code = violation_error_code |
| 44 |
if violation_error_message is not None: |
| 45 |
self.violation_error_message = violation_error_message |
| 46 |
else: |
| 47 |
self.violation_error_message = self.default_violation_error_message |
| 48 |
# RemovedInDjango60Warning. |
| 49 |
if args: |
| 50 |
warnings.warn( |
| 51 |
f"Passing positional arguments to {self.__class__.__name__} is " |
| 52 |
f"deprecated.", |
| 53 |
RemovedInDjango60Warning, |
| 54 |
stacklevel=2, |
| 55 |
) |
| 56 |
for arg, attr in zip(args, ["name", "violation_error_message"]): |
| 57 |
if arg: |
| 58 |
setattr(self, attr, arg) |
| 59 |
|
| 60 |
@property |
| 61 |
def contains_expressions(self): |
| 62 |
return False |
| 63 |
|
| 64 |
def constraint_sql(self, model, schema_editor): |
| 65 |
raise NotImplementedError("This method must be implemented by a subclass.") |
| 66 |
|
| 67 |
def create_sql(self, model, schema_editor): |
| 68 |
raise NotImplementedError("This method must be implemented by a subclass.") |
| 69 |
|
| 70 |
def remove_sql(self, model, schema_editor): |
| 71 |
raise NotImplementedError("This method must be implemented by a subclass.") |
| 72 |
|
| 73 |
@classmethod |
| 74 |
def _expression_refs_exclude(cls, model, expression, exclude): |
| 75 |
get_field = model._meta.get_field |
| 76 |
for field_name, *__ in model._get_expr_references(expression): |
| 77 |
if field_name in exclude: |
| 78 |
return True |
| 79 |
field = get_field(field_name) |
| 80 |
if field.generated and cls._expression_refs_exclude( |
| 81 |
model, field.expression, exclude |
| 82 |
): |
| 83 |
return True |
| 84 |
return False |
| 85 |
|
| 86 |
def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): |
| 87 |
raise NotImplementedError("This method must be implemented by a subclass.") |
| 88 |
|
| 89 |
def get_violation_error_message(self): |
| 90 |
return self.violation_error_message % {"name": self.name} |
| 91 |
|
| 92 |
def _check(self, model, connection): |
| 93 |
return [] |
| 94 |
|
| 95 |
def _check_references(self, model, references): |
| 96 |
from django.db.models.fields.composite import CompositePrimaryKey |
| 97 |
|
| 98 |
errors = [] |
| 99 |
fields = set() |
| 100 |
for field_name, *lookups in references: |
| 101 |
# pk is an alias that won't be found by opts.get_field(). |
| 102 |
if field_name != "pk" or isinstance(model._meta.pk, CompositePrimaryKey): |
| 103 |
fields.add(field_name) |
| 104 |
if not lookups: |
| 105 |
# If it has no lookups it cannot result in a JOIN. |
| 106 |
continue |
| 107 |
try: |
| 108 |
if field_name == "pk": |
| 109 |
field = model._meta.pk |
| 110 |
else: |
| 111 |
field = model._meta.get_field(field_name) |
| 112 |
if not field.is_relation or field.many_to_many or field.one_to_many: |
| 113 |
continue |
| 114 |
except FieldDoesNotExist: |
| 115 |
continue |
| 116 |
# JOIN must happen at the first lookup. |
| 117 |
first_lookup = lookups[0] |
| 118 |
if ( |
| 119 |
hasattr(field, "get_transform") |
| 120 |
and hasattr(field, "get_lookup") |
| 121 |
and field.get_transform(first_lookup) is None |
| 122 |
and field.get_lookup(first_lookup) is None |
| 123 |
): |
| 124 |
errors.append( |
| 125 |
checks.Error( |
| 126 |
"'constraints' refers to the joined field '%s'." |
| 127 |
% LOOKUP_SEP.join([field_name] + lookups), |
| 128 |
obj=model, |
| 129 |
id="models.E041", |
| 130 |
) |
| 131 |
) |
| 132 |
errors.extend(model._check_local_fields(fields, "constraints")) |
| 133 |
return errors |
| 134 |
|
| 135 |
def deconstruct(self): |
| 136 |
path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) |
| 137 |
path = path.replace("django.db.models.constraints", "django.db.models") |
| 138 |
kwargs = {"name": self.name} |
| 139 |
if ( |
| 140 |
self.violation_error_message is not None |
| 141 |
and self.violation_error_message != self.default_violation_error_message |
| 142 |
): |
| 143 |
kwargs["violation_error_message"] = self.violation_error_message |
| 144 |
if self.violation_error_code is not None: |
| 145 |
kwargs["violation_error_code"] = self.violation_error_code |
| 146 |
return (path, (), kwargs) |
| 147 |
|
| 148 |
def clone(self): |
| 149 |
_, args, kwargs = self.deconstruct() |
| 150 |
return self.__class__(*args, **kwargs) |
| 151 |
|
| 152 |
|
| 153 |
class CheckConstraint(BaseConstraint): |
| 154 |
# RemovedInDjango60Warning: when the deprecation ends, replace with |
| 155 |
# def __init__( |
| 156 |
# self, *, condition, name, violation_error_code=None, violation_error_message=None |
| 157 |
# ) |
| 158 |
def __init__( |
| 159 |
self, |
| 160 |
*, |
| 161 |
name, |
| 162 |
condition=None, |
| 163 |
check=None, |
| 164 |
violation_error_code=None, |
| 165 |
violation_error_message=None, |
| 166 |
): |
| 167 |
if check is not None: |
| 168 |
warnings.warn( |
| 169 |
"CheckConstraint.check is deprecated in favor of `.condition`.", |
| 170 |
RemovedInDjango60Warning, |
| 171 |
stacklevel=2, |
| 172 |
) |
| 173 |
condition = check |
| 174 |
self.condition = condition |
| 175 |
if not getattr(condition, "conditional", False): |
| 176 |
raise TypeError( |
| 177 |
"CheckConstraint.condition must be a Q instance or boolean expression." |
| 178 |
) |
| 179 |
super().__init__( |
| 180 |
name=name, |
| 181 |
violation_error_code=violation_error_code, |
| 182 |
violation_error_message=violation_error_message, |
| 183 |
) |
| 184 |
|
| 185 |
def _get_check(self): |
| 186 |
warnings.warn( |
| 187 |
"CheckConstraint.check is deprecated in favor of `.condition`.", |
| 188 |
RemovedInDjango60Warning, |
| 189 |
stacklevel=2, |
| 190 |
) |
| 191 |
return self.condition |
| 192 |
|
| 193 |
def _set_check(self, value): |
| 194 |
warnings.warn( |
| 195 |
"CheckConstraint.check is deprecated in favor of `.condition`.", |
| 196 |
RemovedInDjango60Warning, |
| 197 |
stacklevel=2, |
| 198 |
) |
| 199 |
self.condition = value |
| 200 |
|
| 201 |
check = property(_get_check, _set_check) |
| 202 |
|
| 203 |
def _check(self, model, connection): |
| 204 |
errors = [] |
| 205 |
if not ( |
| 206 |
connection.features.supports_table_check_constraints |
| 207 |
or "supports_table_check_constraints" in model._meta.required_db_features |
| 208 |
): |
| 209 |
errors.append( |
| 210 |
checks.Warning( |
| 211 |
f"{connection.display_name} does not support check constraints.", |
| 212 |
hint=( |
| 213 |
"A constraint won't be created. Silence this warning if you " |
| 214 |
"don't care about it." |
| 215 |
), |
| 216 |
obj=model, |
| 217 |
id="models.W027", |
| 218 |
) |
| 219 |
) |
| 220 |
elif ( |
| 221 |
connection.features.supports_table_check_constraints |
| 222 |
or "supports_table_check_constraints" |
| 223 |
not in model._meta.required_db_features |
| 224 |
): |
| 225 |
references = set() |
| 226 |
condition = self.condition |
| 227 |
if isinstance(condition, Q): |
| 228 |
references.update(model._get_expr_references(condition)) |
| 229 |
if any(isinstance(expr, RawSQL) for expr in condition.flatten()): |
| 230 |
errors.append( |
| 231 |
checks.Warning( |
| 232 |
f"Check constraint {self.name!r} contains RawSQL() expression " |
| 233 |
"and won't be validated during the model full_clean().", |
| 234 |
hint="Silence this warning if you don't care about it.", |
| 235 |
obj=model, |
| 236 |
id="models.W045", |
| 237 |
), |
| 238 |
) |
| 239 |
errors.extend(self._check_references(model, references)) |
| 240 |
return errors |
| 241 |
|
| 242 |
def _get_check_sql(self, model, schema_editor): |
| 243 |
query = Query(model=model, alias_cols=False) |
| 244 |
where = query.build_where(self.condition) |
| 245 |
compiler = query.get_compiler(connection=schema_editor.connection) |
| 246 |
sql, params = where.as_sql(compiler, schema_editor.connection) |
| 247 |
return sql % tuple(schema_editor.quote_value(p) for p in params) |
| 248 |
|
| 249 |
def constraint_sql(self, model, schema_editor): |
| 250 |
check = self._get_check_sql(model, schema_editor) |
| 251 |
return schema_editor._check_sql(self.name, check) |
| 252 |
|
| 253 |
def create_sql(self, model, schema_editor): |
| 254 |
check = self._get_check_sql(model, schema_editor) |
| 255 |
return schema_editor._create_check_sql(model, self.name, check) |
| 256 |
|
| 257 |
def remove_sql(self, model, schema_editor): |
| 258 |
return schema_editor._delete_check_sql(model, self.name) |
| 259 |
|
| 260 |
def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): |
| 261 |
against = instance._get_field_expression_map(meta=model._meta, exclude=exclude) |
| 262 |
try: |
| 263 |
if not Q(self.condition).check(against, using=using): |
| 264 |
raise ValidationError( |
| 265 |
self.get_violation_error_message(), code=self.violation_error_code |
| 266 |
) |
| 267 |
except FieldError: |
| 268 |
pass |
| 269 |
|
| 270 |
def __repr__(self): |
| 271 |
return "<%s: condition=%s name=%s%s%s>" % ( |
| 272 |
self.__class__.__qualname__, |
| 273 |
self.condition, |
| 274 |
repr(self.name), |
| 275 |
( |
| 276 |
"" |
| 277 |
if self.violation_error_code is None |
| 278 |
else " violation_error_code=%r" % self.violation_error_code |
| 279 |
), |
| 280 |
( |
| 281 |
"" |
| 282 |
if self.violation_error_message is None |
| 283 |
or self.violation_error_message == self.default_violation_error_message |
| 284 |
else " violation_error_message=%r" % self.violation_error_message |
| 285 |
), |
| 286 |
) |
| 287 |
|
| 288 |
def __eq__(self, other): |
| 289 |
if isinstance(other, CheckConstraint): |
| 290 |
return ( |
| 291 |
self.name == other.name |
| 292 |
and self.condition == other.condition |
| 293 |
and self.violation_error_code == other.violation_error_code |
| 294 |
and self.violation_error_message == other.violation_error_message |
| 295 |
) |
| 296 |
return super().__eq__(other) |
| 297 |
|
| 298 |
def deconstruct(self): |
| 299 |
path, args, kwargs = super().deconstruct() |
| 300 |
kwargs["condition"] = self.condition |
| 301 |
return path, args, kwargs |
| 302 |
|
| 303 |
|
| 304 |
class Deferrable(Enum): |
| 305 |
DEFERRED = "deferred" |
| 306 |
IMMEDIATE = "immediate" |
| 307 |
|
| 308 |
# A similar format was proposed for Python 3.10. |
| 309 |
def __repr__(self): |
| 310 |
return f"{self.__class__.__qualname__}.{self._name_}" |
| 311 |
|
| 312 |
|
| 313 |
class UniqueConstraint(BaseConstraint): |
| 314 |
def __init__( |
| 315 |
self, |
| 316 |
*expressions, |
| 317 |
fields=(), |
| 318 |
name=None, |
| 319 |
condition=None, |
| 320 |
deferrable=None, |
| 321 |
include=None, |
| 322 |
opclasses=(), |
| 323 |
nulls_distinct=None, |
| 324 |
violation_error_code=None, |
| 325 |
violation_error_message=None, |
| 326 |
): |
| 327 |
if not name: |
| 328 |
raise ValueError("A unique constraint must be named.") |
| 329 |
if not expressions and not fields: |
| 330 |
raise ValueError( |
| 331 |
"At least one field or expression is required to define a " |
| 332 |
"unique constraint." |
| 333 |
) |
| 334 |
if expressions and fields: |
| 335 |
raise ValueError( |
| 336 |
"UniqueConstraint.fields and expressions are mutually exclusive." |
| 337 |
) |
| 338 |
if not isinstance(condition, (NoneType, Q)): |
| 339 |
raise ValueError("UniqueConstraint.condition must be a Q instance.") |
| 340 |
if condition and deferrable: |
| 341 |
raise ValueError("UniqueConstraint with conditions cannot be deferred.") |
| 342 |
if include and deferrable: |
| 343 |
raise ValueError("UniqueConstraint with include fields cannot be deferred.") |
| 344 |
if opclasses and deferrable: |
| 345 |
raise ValueError("UniqueConstraint with opclasses cannot be deferred.") |
| 346 |
if expressions and deferrable: |
| 347 |
raise ValueError("UniqueConstraint with expressions cannot be deferred.") |
| 348 |
if expressions and opclasses: |
| 349 |
raise ValueError( |
| 350 |
"UniqueConstraint.opclasses cannot be used with expressions. " |
| 351 |
"Use django.contrib.postgres.indexes.OpClass() instead." |
| 352 |
) |
| 353 |
if not isinstance(deferrable, (NoneType, Deferrable)): |
| 354 |
raise TypeError( |
| 355 |
"UniqueConstraint.deferrable must be a Deferrable instance." |
| 356 |
) |
| 357 |
if not isinstance(include, (NoneType, list, tuple)): |
| 358 |
raise TypeError("UniqueConstraint.include must be a list or tuple.") |
| 359 |
if not isinstance(opclasses, (list, tuple)): |
| 360 |
raise TypeError("UniqueConstraint.opclasses must be a list or tuple.") |
| 361 |
if not isinstance(nulls_distinct, (NoneType, bool)): |
| 362 |
raise TypeError("UniqueConstraint.nulls_distinct must be a bool.") |
| 363 |
if opclasses and len(fields) != len(opclasses): |
| 364 |
raise ValueError( |
| 365 |
"UniqueConstraint.fields and UniqueConstraint.opclasses must " |
| 366 |
"have the same number of elements." |
| 367 |
) |
| 368 |
self.fields = tuple(fields) |
| 369 |
self.condition = condition |
| 370 |
self.deferrable = deferrable |
| 371 |
self.include = tuple(include) if include else () |
| 372 |
self.opclasses = opclasses |
| 373 |
self.nulls_distinct = nulls_distinct |
| 374 |
self.expressions = tuple( |
| 375 |
F(expression) if isinstance(expression, str) else expression |
| 376 |
for expression in expressions |
| 377 |
) |
| 378 |
super().__init__( |
| 379 |
name=name, |
| 380 |
violation_error_code=violation_error_code, |
| 381 |
violation_error_message=violation_error_message, |
| 382 |
) |
| 383 |
|
| 384 |
@property |
| 385 |
def contains_expressions(self): |
| 386 |
return bool(self.expressions) |
| 387 |
|
| 388 |
def _check(self, model, connection): |
| 389 |
errors = model._check_local_fields({*self.fields, *self.include}, "constraints") |
| 390 |
required_db_features = model._meta.required_db_features |
| 391 |
if self.condition is not None and not ( |
| 392 |
connection.features.supports_partial_indexes |
| 393 |
or "supports_partial_indexes" in required_db_features |
| 394 |
): |
| 395 |
errors.append( |
| 396 |
checks.Warning( |
| 397 |
f"{connection.display_name} does not support unique constraints " |
| 398 |
"with conditions.", |
| 399 |
hint=( |
| 400 |
"A constraint won't be created. Silence this warning if you " |
| 401 |
"don't care about it." |
| 402 |
), |
| 403 |
obj=model, |
| 404 |
id="models.W036", |
| 405 |
) |
| 406 |
) |
| 407 |
if self.deferrable is not None and not ( |
| 408 |
connection.features.supports_deferrable_unique_constraints |
| 409 |
or "supports_deferrable_unique_constraints" in required_db_features |
| 410 |
): |
| 411 |
errors.append( |
| 412 |
checks.Warning( |
| 413 |
f"{connection.display_name} does not support deferrable unique " |
| 414 |
"constraints.", |
| 415 |
hint=( |
| 416 |
"A constraint won't be created. Silence this warning if you " |
| 417 |
"don't care about it." |
| 418 |
), |
| 419 |
obj=model, |
| 420 |
id="models.W038", |
| 421 |
) |
| 422 |
) |
| 423 |
if self.include and not ( |
| 424 |
connection.features.supports_covering_indexes |
| 425 |
or "supports_covering_indexes" in required_db_features |
| 426 |
): |
| 427 |
errors.append( |
| 428 |
checks.Warning( |
| 429 |
f"{connection.display_name} does not support unique constraints " |
| 430 |
"with non-key columns.", |
| 431 |
hint=( |
| 432 |
"A constraint won't be created. Silence this warning if you " |
| 433 |
"don't care about it." |
| 434 |
), |
| 435 |
obj=model, |
| 436 |
id="models.W039", |
| 437 |
) |
| 438 |
) |
| 439 |
if self.contains_expressions and not ( |
| 440 |
connection.features.supports_expression_indexes |
| 441 |
or "supports_expression_indexes" in required_db_features |
| 442 |
): |
| 443 |
errors.append( |
| 444 |
checks.Warning( |
| 445 |
f"{connection.display_name} does not support unique constraints on " |
| 446 |
"expressions.", |
| 447 |
hint=( |
| 448 |
"A constraint won't be created. Silence this warning if you " |
| 449 |
"don't care about it." |
| 450 |
), |
| 451 |
obj=model, |
| 452 |
id="models.W044", |
| 453 |
) |
| 454 |
) |
| 455 |
if self.nulls_distinct is not None and not ( |
| 456 |
connection.features.supports_nulls_distinct_unique_constraints |
| 457 |
or "supports_nulls_distinct_unique_constraints" in required_db_features |
| 458 |
): |
| 459 |
errors.append( |
| 460 |
checks.Warning( |
| 461 |
f"{connection.display_name} does not support unique constraints " |
| 462 |
"with nulls distinct.", |
| 463 |
hint=( |
| 464 |
"A constraint won't be created. Silence this warning if you " |
| 465 |
"don't care about it." |
| 466 |
), |
| 467 |
obj=model, |
| 468 |
id="models.W047", |
| 469 |
) |
| 470 |
) |
| 471 |
references = set() |
| 472 |
if ( |
| 473 |
connection.features.supports_partial_indexes |
| 474 |
or "supports_partial_indexes" not in required_db_features |
| 475 |
) and isinstance(self.condition, Q): |
| 476 |
references.update(model._get_expr_references(self.condition)) |
| 477 |
if self.contains_expressions and ( |
| 478 |
connection.features.supports_expression_indexes |
| 479 |
or "supports_expression_indexes" not in required_db_features |
| 480 |
): |
| 481 |
for expression in self.expressions: |
| 482 |
references.update(model._get_expr_references(expression)) |
| 483 |
errors.extend(self._check_references(model, references)) |
| 484 |
return errors |
| 485 |
|
| 486 |
def _get_condition_sql(self, model, schema_editor): |
| 487 |
if self.condition is None: |
| 488 |
return None |
| 489 |
query = Query(model=model, alias_cols=False) |
| 490 |
where = query.build_where(self.condition) |
| 491 |
compiler = query.get_compiler(connection=schema_editor.connection) |
| 492 |
sql, params = where.as_sql(compiler, schema_editor.connection) |
| 493 |
return sql % tuple(schema_editor.quote_value(p) for p in params) |
| 494 |
|
| 495 |
def _get_index_expressions(self, model, schema_editor): |
| 496 |
if not self.expressions: |
| 497 |
return None |
| 498 |
index_expressions = [] |
| 499 |
for expression in self.expressions: |
| 500 |
index_expression = IndexExpression(expression) |
| 501 |
index_expression.set_wrapper_classes(schema_editor.connection) |
| 502 |
index_expressions.append(index_expression) |
| 503 |
return ExpressionList(*index_expressions).resolve_expression( |
| 504 |
Query(model, alias_cols=False), |
| 505 |
) |
| 506 |
|
| 507 |
def constraint_sql(self, model, schema_editor): |
| 508 |
fields = [model._meta.get_field(field_name) for field_name in self.fields] |
| 509 |
include = [ |
| 510 |
model._meta.get_field(field_name).column for field_name in self.include |
| 511 |
] |
| 512 |
condition = self._get_condition_sql(model, schema_editor) |
| 513 |
expressions = self._get_index_expressions(model, schema_editor) |
| 514 |
return schema_editor._unique_sql( |
| 515 |
model, |
| 516 |
fields, |
| 517 |
self.name, |
| 518 |
condition=condition, |
| 519 |
deferrable=self.deferrable, |
| 520 |
include=include, |
| 521 |
opclasses=self.opclasses, |
| 522 |
expressions=expressions, |
| 523 |
nulls_distinct=self.nulls_distinct, |
| 524 |
) |
| 525 |
|
| 526 |
def create_sql(self, model, schema_editor): |
| 527 |
fields = [model._meta.get_field(field_name) for field_name in self.fields] |
| 528 |
include = [ |
| 529 |
model._meta.get_field(field_name).column for field_name in self.include |
| 530 |
] |
| 531 |
condition = self._get_condition_sql(model, schema_editor) |
| 532 |
expressions = self._get_index_expressions(model, schema_editor) |
| 533 |
return schema_editor._create_unique_sql( |
| 534 |
model, |
| 535 |
fields, |
| 536 |
self.name, |
| 537 |
condition=condition, |
| 538 |
deferrable=self.deferrable, |
| 539 |
include=include, |
| 540 |
opclasses=self.opclasses, |
| 541 |
expressions=expressions, |
| 542 |
nulls_distinct=self.nulls_distinct, |
| 543 |
) |
| 544 |
|
| 545 |
def remove_sql(self, model, schema_editor): |
| 546 |
condition = self._get_condition_sql(model, schema_editor) |
| 547 |
include = [ |
| 548 |
model._meta.get_field(field_name).column for field_name in self.include |
| 549 |
] |
| 550 |
expressions = self._get_index_expressions(model, schema_editor) |
| 551 |
return schema_editor._delete_unique_sql( |
| 552 |
model, |
| 553 |
self.name, |
| 554 |
condition=condition, |
| 555 |
deferrable=self.deferrable, |
| 556 |
include=include, |
| 557 |
opclasses=self.opclasses, |
| 558 |
expressions=expressions, |
| 559 |
nulls_distinct=self.nulls_distinct, |
| 560 |
) |
| 561 |
|
| 562 |
def __repr__(self): |
| 563 |
return "<%s:%s%s%s%s%s%s%s%s%s%s>" % ( |
| 564 |
self.__class__.__qualname__, |
| 565 |
"" if not self.fields else " fields=%s" % repr(self.fields), |
| 566 |
"" if not self.expressions else " expressions=%s" % repr(self.expressions), |
| 567 |
" name=%s" % repr(self.name), |
| 568 |
"" if self.condition is None else " condition=%s" % self.condition, |
| 569 |
"" if self.deferrable is None else " deferrable=%r" % self.deferrable, |
| 570 |
"" if not self.include else " include=%s" % repr(self.include), |
| 571 |
"" if not self.opclasses else " opclasses=%s" % repr(self.opclasses), |
| 572 |
( |
| 573 |
"" |
| 574 |
if self.nulls_distinct is None |
| 575 |
else " nulls_distinct=%r" % self.nulls_distinct |
| 576 |
), |
| 577 |
( |
| 578 |
"" |
| 579 |
if self.violation_error_code is None |
| 580 |
else " violation_error_code=%r" % self.violation_error_code |
| 581 |
), |
| 582 |
( |
| 583 |
"" |
| 584 |
if self.violation_error_message is None |
| 585 |
or self.violation_error_message == self.default_violation_error_message |
| 586 |
else " violation_error_message=%r" % self.violation_error_message |
| 587 |
), |
| 588 |
) |
| 589 |
|
| 590 |
def __eq__(self, other): |
| 591 |
if isinstance(other, UniqueConstraint): |
| 592 |
return ( |
| 593 |
self.name == other.name |
| 594 |
and self.fields == other.fields |
| 595 |
and self.condition == other.condition |
| 596 |
and self.deferrable == other.deferrable |
| 597 |
and self.include == other.include |
| 598 |
and self.opclasses == other.opclasses |
| 599 |
and self.expressions == other.expressions |
| 600 |
and self.nulls_distinct is other.nulls_distinct |
| 601 |
and self.violation_error_code == other.violation_error_code |
| 602 |
and self.violation_error_message == other.violation_error_message |
| 603 |
) |
| 604 |
return super().__eq__(other) |
| 605 |
|
| 606 |
def deconstruct(self): |
| 607 |
path, args, kwargs = super().deconstruct() |
| 608 |
if self.fields: |
| 609 |
kwargs["fields"] = self.fields |
| 610 |
if self.condition: |
| 611 |
kwargs["condition"] = self.condition |
| 612 |
if self.deferrable: |
| 613 |
kwargs["deferrable"] = self.deferrable |
| 614 |
if self.include: |
| 615 |
kwargs["include"] = self.include |
| 616 |
if self.opclasses: |
| 617 |
kwargs["opclasses"] = self.opclasses |
| 618 |
if self.nulls_distinct is not None: |
| 619 |
kwargs["nulls_distinct"] = self.nulls_distinct |
| 620 |
return path, self.expressions, kwargs |
| 621 |
|
| 622 |
def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): |
| 623 |
queryset = model._default_manager.using(using) |
| 624 |
if self.fields: |
| 625 |
lookup_kwargs = {} |
| 626 |
generated_field_names = [] |
| 627 |
for field_name in self.fields: |
| 628 |
if exclude and field_name in exclude: |
| 629 |
return |
| 630 |
field = model._meta.get_field(field_name) |
| 631 |
if field.generated: |
| 632 |
if exclude and self._expression_refs_exclude( |
| 633 |
model, field.expression, exclude |
| 634 |
): |
| 635 |
return |
| 636 |
generated_field_names.append(field.name) |
| 637 |
else: |
| 638 |
lookup_value = getattr(instance, field.attname) |
| 639 |
if ( |
| 640 |
self.nulls_distinct is not False |
| 641 |
and lookup_value is None |
| 642 |
or ( |
| 643 |
lookup_value == "" |
| 644 |
and connections[ |
| 645 |
using |
| 646 |
].features.interprets_empty_strings_as_nulls |
| 647 |
) |
| 648 |
): |
| 649 |
# A composite constraint containing NULL value cannot cause |
| 650 |
# a violation since NULL != NULL in SQL. |
| 651 |
return |
| 652 |
lookup_kwargs[field.name] = lookup_value |
| 653 |
lookup_args = [] |
| 654 |
if generated_field_names: |
| 655 |
field_expression_map = instance._get_field_expression_map( |
| 656 |
meta=model._meta, exclude=exclude |
| 657 |
) |
| 658 |
for field_name in generated_field_names: |
| 659 |
expression = field_expression_map[field_name] |
| 660 |
if self.nulls_distinct is False: |
| 661 |
lhs = F(field_name) |
| 662 |
condition = Q(Exact(lhs, expression)) | Q( |
| 663 |
IsNull(lhs, True), IsNull(expression, True) |
| 664 |
) |
| 665 |
lookup_args.append(condition) |
| 666 |
else: |
| 667 |
lookup_kwargs[field_name] = expression |
| 668 |
queryset = queryset.filter(*lookup_args, **lookup_kwargs) |
| 669 |
else: |
| 670 |
# Ignore constraints with excluded fields. |
| 671 |
if exclude and any( |
| 672 |
self._expression_refs_exclude(model, expression, exclude) |
| 673 |
for expression in self.expressions |
| 674 |
): |
| 675 |
return |
| 676 |
replacements = { |
| 677 |
F(field): value |
| 678 |
for field, value in instance._get_field_expression_map( |
| 679 |
meta=model._meta, exclude=exclude |
| 680 |
).items() |
| 681 |
} |
| 682 |
filters = [] |
| 683 |
for expr in self.expressions: |
| 684 |
if hasattr(expr, "get_expression_for_validation"): |
| 685 |
expr = expr.get_expression_for_validation() |
| 686 |
rhs = expr.replace_expressions(replacements) |
| 687 |
condition = Exact(expr, rhs) |
| 688 |
if self.nulls_distinct is False: |
| 689 |
condition = Q(condition) | Q(IsNull(expr, True), IsNull(rhs, True)) |
| 690 |
filters.append(condition) |
| 691 |
queryset = queryset.filter(*filters) |
| 692 |
model_class_pk = instance._get_pk_val(model._meta) |
| 693 |
if not instance._state.adding and instance._is_pk_set(model._meta): |
| 694 |
queryset = queryset.exclude(pk=model_class_pk) |
| 695 |
if not self.condition: |
| 696 |
if queryset.exists(): |
| 697 |
if ( |
| 698 |
self.fields |
| 699 |
and self.violation_error_message |
| 700 |
== self.default_violation_error_message |
| 701 |
): |
| 702 |
# When fields are defined, use the unique_error_message() as |
| 703 |
# a default for backward compatibility. |
| 704 |
validation_error_message = instance.unique_error_message( |
| 705 |
model, self.fields |
| 706 |
) |
| 707 |
raise ValidationError( |
| 708 |
validation_error_message, |
| 709 |
code=validation_error_message.code, |
| 710 |
) |
| 711 |
raise ValidationError( |
| 712 |
self.get_violation_error_message(), |
| 713 |
code=self.violation_error_code, |
| 714 |
) |
| 715 |
else: |
| 716 |
against = instance._get_field_expression_map( |
| 717 |
meta=model._meta, exclude=exclude |
| 718 |
) |
| 719 |
try: |
| 720 |
if (self.condition & Exists(queryset.filter(self.condition))).check( |
| 721 |
against, using=using |
| 722 |
): |
| 723 |
raise ValidationError( |
| 724 |
self.get_violation_error_message(), |
| 725 |
code=self.violation_error_code, |
| 726 |
) |
| 727 |
except FieldError: |
| 728 |
pass |