43 lines
1.7 KiB
Python
43 lines
1.7 KiB
Python
from django.db import migrations, transaction
|
|
from django.db.utils import InternalError, OperationalError, ProgrammingError
|
|
|
|
sql_forwards = """
|
|
ALTER TABLE agendas_event
|
|
ADD CONSTRAINT tstzrange_constraint
|
|
EXCLUDE USING GIST(desk_id WITH =, tstzrange(start_datetime, _end_datetime) WITH &&)
|
|
WHERE (_ignore_reason IS NULL AND _end_datetime IS NOT NULL and desk_id IS NOT NULL);
|
|
"""
|
|
|
|
sql_backwards = """
|
|
ALTER TABLE agendas_event DROP CONSTRAINT tstzrange_constraint;
|
|
"""
|
|
|
|
|
|
class Migration(migrations.Migration):
|
|
|
|
dependencies = [
|
|
('agendas', '0052_event_date_range_constraint'),
|
|
]
|
|
|
|
operations = [migrations.RunSQL(sql=sql_forwards, reverse_sql=sql_backwards)]
|
|
|
|
def _check_db(self, project_state, schema_editor):
|
|
try:
|
|
with transaction.atomic():
|
|
try:
|
|
# will fail if extension does not exist and can not be created
|
|
schema_editor.execute('CREATE EXTENSION IF NOT EXISTS btree_Gist SCHEMA public')
|
|
except (OperationalError, ProgrammingError):
|
|
# if no extension, columns and triggers does not exist and constraint can not be added
|
|
return project_state
|
|
except InternalError:
|
|
return project_state
|
|
|
|
def apply(self, project_state, schema_editor, *args, **kwargs):
|
|
result = self._check_db(project_state, schema_editor)
|
|
return result or super().apply(project_state, schema_editor, *args, **kwargs)
|
|
|
|
def unapply(self, project_state, schema_editor, *args, **kwargs):
|
|
result = self._check_db(project_state, schema_editor)
|
|
return result or super().unapply(project_state, schema_editor, *args, **kwargs)
|