2020-06-12 03:05:38 +08:00
|
|
|
from django.db import NotSupportedError
|
2019-07-12 19:08:00 +08:00
|
|
|
from django.db.backends.ddl_references import Statement, Table
|
2020-04-12 18:43:16 +08:00
|
|
|
from django.db.models import Deferrable, F, Q
|
2019-07-12 19:08:00 +08:00
|
|
|
from django.db.models.constraints import BaseConstraint
|
|
|
|
from django.db.models.sql import Query
|
|
|
|
|
|
|
|
__all__ = ['ExclusionConstraint']
|
|
|
|
|
|
|
|
|
|
|
|
class ExclusionConstraint(BaseConstraint):
|
2020-06-12 03:05:38 +08:00
|
|
|
template = 'CONSTRAINT %(name)s EXCLUDE USING %(index_type)s (%(expressions)s)%(include)s%(where)s%(deferrable)s'
|
2019-07-12 19:08:00 +08:00
|
|
|
|
2020-04-12 18:43:16 +08:00
|
|
|
def __init__(
|
|
|
|
self, *, name, expressions, index_type=None, condition=None,
|
2020-06-15 02:50:39 +08:00
|
|
|
deferrable=None, include=None, opclasses=(),
|
2020-04-12 18:43:16 +08:00
|
|
|
):
|
2019-07-12 19:08:00 +08:00
|
|
|
if index_type and index_type.lower() not in {'gist', 'spgist'}:
|
|
|
|
raise ValueError(
|
|
|
|
'Exclusion constraints only support GiST or SP-GiST indexes.'
|
|
|
|
)
|
|
|
|
if not expressions:
|
|
|
|
raise ValueError(
|
|
|
|
'At least one expression is required to define an exclusion '
|
|
|
|
'constraint.'
|
|
|
|
)
|
|
|
|
if not all(
|
|
|
|
isinstance(expr, (list, tuple)) and len(expr) == 2
|
|
|
|
for expr in expressions
|
|
|
|
):
|
|
|
|
raise ValueError('The expressions must be a list of 2-tuples.')
|
|
|
|
if not isinstance(condition, (type(None), Q)):
|
|
|
|
raise ValueError(
|
|
|
|
'ExclusionConstraint.condition must be a Q instance.'
|
|
|
|
)
|
2020-04-12 18:43:16 +08:00
|
|
|
if condition and deferrable:
|
|
|
|
raise ValueError(
|
|
|
|
'ExclusionConstraint with conditions cannot be deferred.'
|
|
|
|
)
|
|
|
|
if not isinstance(deferrable, (type(None), Deferrable)):
|
|
|
|
raise ValueError(
|
|
|
|
'ExclusionConstraint.deferrable must be a Deferrable instance.'
|
|
|
|
)
|
2020-06-12 03:05:38 +08:00
|
|
|
if not isinstance(include, (type(None), list, tuple)):
|
|
|
|
raise ValueError(
|
|
|
|
'ExclusionConstraint.include must be a list or tuple.'
|
|
|
|
)
|
|
|
|
if include and index_type and index_type.lower() != 'gist':
|
|
|
|
raise ValueError(
|
|
|
|
'Covering exclusion constraints only support GiST indexes.'
|
|
|
|
)
|
2020-06-15 02:50:39 +08:00
|
|
|
if not isinstance(opclasses, (list, tuple)):
|
|
|
|
raise ValueError(
|
|
|
|
'ExclusionConstraint.opclasses must be a list or tuple.'
|
|
|
|
)
|
|
|
|
if opclasses and len(expressions) != len(opclasses):
|
|
|
|
raise ValueError(
|
|
|
|
'ExclusionConstraint.expressions and '
|
|
|
|
'ExclusionConstraint.opclasses must have the same number of '
|
|
|
|
'elements.'
|
|
|
|
)
|
2019-07-12 19:08:00 +08:00
|
|
|
self.expressions = expressions
|
|
|
|
self.index_type = index_type or 'GIST'
|
|
|
|
self.condition = condition
|
2020-04-12 18:43:16 +08:00
|
|
|
self.deferrable = deferrable
|
2020-06-12 03:05:38 +08:00
|
|
|
self.include = tuple(include) if include else ()
|
2020-06-15 02:50:39 +08:00
|
|
|
self.opclasses = opclasses
|
2019-07-12 19:08:00 +08:00
|
|
|
super().__init__(name=name)
|
|
|
|
|
2020-08-19 10:22:12 +08:00
|
|
|
def _get_expression_sql(self, compiler, schema_editor, query):
|
2019-07-12 19:08:00 +08:00
|
|
|
expressions = []
|
2020-06-15 02:50:39 +08:00
|
|
|
for idx, (expression, operator) in enumerate(self.expressions):
|
2019-07-12 19:08:00 +08:00
|
|
|
if isinstance(expression, str):
|
|
|
|
expression = F(expression)
|
2019-09-10 11:58:29 +08:00
|
|
|
expression = expression.resolve_expression(query=query)
|
2020-10-14 19:09:24 +08:00
|
|
|
sql, params = compiler.compile(expression)
|
2020-06-15 02:50:39 +08:00
|
|
|
try:
|
|
|
|
opclass = self.opclasses[idx]
|
|
|
|
if opclass:
|
|
|
|
sql = '%s %s' % (sql, opclass)
|
|
|
|
except IndexError:
|
|
|
|
pass
|
2020-08-19 10:22:12 +08:00
|
|
|
sql = sql % tuple(schema_editor.quote_value(p) for p in params)
|
|
|
|
expressions.append('%s WITH %s' % (sql, operator))
|
2019-07-12 19:08:00 +08:00
|
|
|
return expressions
|
|
|
|
|
|
|
|
def _get_condition_sql(self, compiler, schema_editor, query):
|
|
|
|
if self.condition is None:
|
|
|
|
return None
|
|
|
|
where = query.build_where(self.condition)
|
|
|
|
sql, params = where.as_sql(compiler, schema_editor.connection)
|
|
|
|
return sql % tuple(schema_editor.quote_value(p) for p in params)
|
|
|
|
|
|
|
|
def constraint_sql(self, model, schema_editor):
|
2019-09-10 11:58:29 +08:00
|
|
|
query = Query(model, alias_cols=False)
|
2019-07-12 19:08:00 +08:00
|
|
|
compiler = query.get_compiler(connection=schema_editor.connection)
|
2020-08-19 10:22:12 +08:00
|
|
|
expressions = self._get_expression_sql(compiler, schema_editor, query)
|
2019-07-12 19:08:00 +08:00
|
|
|
condition = self._get_condition_sql(compiler, schema_editor, query)
|
2020-06-12 03:05:38 +08:00
|
|
|
include = [model._meta.get_field(field_name).column for field_name in self.include]
|
2019-07-12 19:08:00 +08:00
|
|
|
return self.template % {
|
|
|
|
'name': schema_editor.quote_name(self.name),
|
|
|
|
'index_type': self.index_type,
|
|
|
|
'expressions': ', '.join(expressions),
|
2020-06-12 03:05:38 +08:00
|
|
|
'include': schema_editor._index_include_sql(model, include),
|
2019-07-12 19:08:00 +08:00
|
|
|
'where': ' WHERE (%s)' % condition if condition else '',
|
2020-04-12 18:43:16 +08:00
|
|
|
'deferrable': schema_editor._deferrable_constraint_sql(self.deferrable),
|
2019-07-12 19:08:00 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
def create_sql(self, model, schema_editor):
|
2020-06-12 03:05:38 +08:00
|
|
|
self.check_supported(schema_editor)
|
2019-07-12 19:08:00 +08:00
|
|
|
return Statement(
|
|
|
|
'ALTER TABLE %(table)s ADD %(constraint)s',
|
|
|
|
table=Table(model._meta.db_table, schema_editor.quote_name),
|
|
|
|
constraint=self.constraint_sql(model, schema_editor),
|
|
|
|
)
|
|
|
|
|
|
|
|
def remove_sql(self, model, schema_editor):
|
|
|
|
return schema_editor._delete_constraint_sql(
|
|
|
|
schema_editor.sql_delete_check,
|
|
|
|
model,
|
|
|
|
schema_editor.quote_name(self.name),
|
|
|
|
)
|
|
|
|
|
2020-06-12 03:05:38 +08:00
|
|
|
def check_supported(self, schema_editor):
|
|
|
|
if self.include and not schema_editor.connection.features.supports_covering_gist_indexes:
|
|
|
|
raise NotSupportedError(
|
|
|
|
'Covering exclusion constraints requires PostgreSQL 12+.'
|
|
|
|
)
|
|
|
|
|
2019-07-12 19:08:00 +08:00
|
|
|
def deconstruct(self):
|
|
|
|
path, args, kwargs = super().deconstruct()
|
|
|
|
kwargs['expressions'] = self.expressions
|
|
|
|
if self.condition is not None:
|
|
|
|
kwargs['condition'] = self.condition
|
|
|
|
if self.index_type.lower() != 'gist':
|
|
|
|
kwargs['index_type'] = self.index_type
|
2020-04-12 18:43:16 +08:00
|
|
|
if self.deferrable:
|
|
|
|
kwargs['deferrable'] = self.deferrable
|
2020-06-12 03:05:38 +08:00
|
|
|
if self.include:
|
|
|
|
kwargs['include'] = self.include
|
2020-06-15 02:50:39 +08:00
|
|
|
if self.opclasses:
|
|
|
|
kwargs['opclasses'] = self.opclasses
|
2019-07-12 19:08:00 +08:00
|
|
|
return path, args, kwargs
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
2019-09-03 10:09:31 +08:00
|
|
|
if isinstance(other, self.__class__):
|
|
|
|
return (
|
|
|
|
self.name == other.name and
|
|
|
|
self.index_type == other.index_type and
|
|
|
|
self.expressions == other.expressions and
|
2020-04-12 18:43:16 +08:00
|
|
|
self.condition == other.condition and
|
2020-06-12 03:05:38 +08:00
|
|
|
self.deferrable == other.deferrable and
|
2020-06-15 02:50:39 +08:00
|
|
|
self.include == other.include and
|
|
|
|
self.opclasses == other.opclasses
|
2019-09-03 10:09:31 +08:00
|
|
|
)
|
|
|
|
return super().__eq__(other)
|
2019-07-12 19:08:00 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
2020-06-15 02:50:39 +08:00
|
|
|
return '<%s: index_type=%s, expressions=%s%s%s%s%s>' % (
|
2019-07-12 19:08:00 +08:00
|
|
|
self.__class__.__qualname__,
|
|
|
|
self.index_type,
|
|
|
|
self.expressions,
|
|
|
|
'' if self.condition is None else ', condition=%s' % self.condition,
|
2020-04-12 18:43:16 +08:00
|
|
|
'' if self.deferrable is None else ', deferrable=%s' % self.deferrable,
|
2020-06-12 03:05:38 +08:00
|
|
|
'' if not self.include else ', include=%s' % repr(self.include),
|
2020-06-15 02:50:39 +08:00
|
|
|
'' if not self.opclasses else ', opclasses=%s' % repr(self.opclasses),
|
2019-07-12 19:08:00 +08:00
|
|
|
)
|