constraints.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. from enum import Enum
  2. from django.db.models.query_utils import Q
  3. from django.db.models.sql.query import Query
  4. __all__ = ['CheckConstraint', 'Deferrable', 'UniqueConstraint']
  5. class BaseConstraint:
  6. def __init__(self, name):
  7. self.name = name
  8. def constraint_sql(self, model, schema_editor):
  9. raise NotImplementedError('This method must be implemented by a subclass.')
  10. def create_sql(self, model, schema_editor):
  11. raise NotImplementedError('This method must be implemented by a subclass.')
  12. def remove_sql(self, model, schema_editor):
  13. raise NotImplementedError('This method must be implemented by a subclass.')
  14. def deconstruct(self):
  15. path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
  16. path = path.replace('django.db.models.constraints', 'django.db.models')
  17. return (path, (), {'name': self.name})
  18. def clone(self):
  19. _, args, kwargs = self.deconstruct()
  20. return self.__class__(*args, **kwargs)
  21. class CheckConstraint(BaseConstraint):
  22. def __init__(self, *, check, name):
  23. self.check = check
  24. if not getattr(check, 'conditional', False):
  25. raise TypeError(
  26. 'CheckConstraint.check must be a Q instance or boolean '
  27. 'expression.'
  28. )
  29. super().__init__(name)
  30. def _get_check_sql(self, model, schema_editor):
  31. query = Query(model=model, alias_cols=False)
  32. where = query.build_where(self.check)
  33. compiler = query.get_compiler(connection=schema_editor.connection)
  34. sql, params = where.as_sql(compiler, schema_editor.connection)
  35. return sql % tuple(schema_editor.quote_value(p) for p in params)
  36. def constraint_sql(self, model, schema_editor):
  37. check = self._get_check_sql(model, schema_editor)
  38. return schema_editor._check_sql(self.name, check)
  39. def create_sql(self, model, schema_editor):
  40. check = self._get_check_sql(model, schema_editor)
  41. return schema_editor._create_check_sql(model, self.name, check)
  42. def remove_sql(self, model, schema_editor):
  43. return schema_editor._delete_check_sql(model, self.name)
  44. def __repr__(self):
  45. return "<%s: check='%s' name=%r>" % (self.__class__.__name__, self.check, self.name)
  46. def __eq__(self, other):
  47. if isinstance(other, CheckConstraint):
  48. return self.name == other.name and self.check == other.check
  49. return super().__eq__(other)
  50. def deconstruct(self):
  51. path, args, kwargs = super().deconstruct()
  52. kwargs['check'] = self.check
  53. return path, args, kwargs
  54. class Deferrable(Enum):
  55. DEFERRED = 'deferred'
  56. IMMEDIATE = 'immediate'
  57. class UniqueConstraint(BaseConstraint):
  58. def __init__(self, *, fields, name, condition=None, deferrable=None, include=None):
  59. if not fields:
  60. raise ValueError('At least one field is required to define a unique constraint.')
  61. if not isinstance(condition, (type(None), Q)):
  62. raise ValueError('UniqueConstraint.condition must be a Q instance.')
  63. if condition and deferrable:
  64. raise ValueError(
  65. 'UniqueConstraint with conditions cannot be deferred.'
  66. )
  67. if not isinstance(deferrable, (type(None), Deferrable)):
  68. raise ValueError(
  69. 'UniqueConstraint.deferrable must be a Deferrable instance.'
  70. )
  71. if not isinstance(include, (type(None), list, tuple)):
  72. raise ValueError('UniqueConstraint.include must be a list or tuple.')
  73. self.fields = tuple(fields)
  74. self.condition = condition
  75. self.deferrable = deferrable
  76. self.include = tuple(include) if include else ()
  77. super().__init__(name)
  78. def _get_condition_sql(self, model, schema_editor):
  79. if self.condition is None:
  80. return None
  81. query = Query(model=model, alias_cols=False)
  82. where = query.build_where(self.condition)
  83. compiler = query.get_compiler(connection=schema_editor.connection)
  84. sql, params = where.as_sql(compiler, schema_editor.connection)
  85. return sql % tuple(schema_editor.quote_value(p) for p in params)
  86. def constraint_sql(self, model, schema_editor):
  87. fields = [model._meta.get_field(field_name).column for field_name in self.fields]
  88. include = [model._meta.get_field(field_name).column for field_name in self.include]
  89. condition = self._get_condition_sql(model, schema_editor)
  90. return schema_editor._unique_sql(
  91. model, fields, self.name, condition=condition,
  92. deferrable=self.deferrable, include=include,
  93. )
  94. def create_sql(self, model, schema_editor):
  95. fields = [model._meta.get_field(field_name).column for field_name in self.fields]
  96. include = [model._meta.get_field(field_name).column for field_name in self.include]
  97. condition = self._get_condition_sql(model, schema_editor)
  98. return schema_editor._create_unique_sql(
  99. model, fields, self.name, condition=condition,
  100. deferrable=self.deferrable, include=include,
  101. )
  102. def remove_sql(self, model, schema_editor):
  103. condition = self._get_condition_sql(model, schema_editor)
  104. include = [model._meta.get_field(field_name).column for field_name in self.include]
  105. return schema_editor._delete_unique_sql(
  106. model, self.name, condition=condition, deferrable=self.deferrable,
  107. include=include,
  108. )
  109. def __repr__(self):
  110. return '<%s: fields=%r name=%r%s%s%s>' % (
  111. self.__class__.__name__, self.fields, self.name,
  112. '' if self.condition is None else ' condition=%s' % self.condition,
  113. '' if self.deferrable is None else ' deferrable=%s' % self.deferrable,
  114. '' if not self.include else ' include=%s' % repr(self.include),
  115. )
  116. def __eq__(self, other):
  117. if isinstance(other, UniqueConstraint):
  118. return (
  119. self.name == other.name and
  120. self.fields == other.fields and
  121. self.condition == other.condition and
  122. self.deferrable == other.deferrable and
  123. self.include == other.include
  124. )
  125. return super().__eq__(other)
  126. def deconstruct(self):
  127. path, args, kwargs = super().deconstruct()
  128. kwargs['fields'] = self.fields
  129. if self.condition:
  130. kwargs['condition'] = self.condition
  131. if self.deferrable:
  132. kwargs['deferrable'] = self.deferrable
  133. if self.include:
  134. kwargs['include'] = self.include
  135. return path, args, kwargs