Add a migration to replace notifications_template foreign key

Removes notifications.template_id foreign key and replaces it with
a composite foreign key constraint to TemplateHistory using the
existing notification columns for template ID and template version.

Foreign key constraint is created as NOT VALID to avoid locking the
notifications table while postgres verifies that existing records
don't break the constraint. From postgres docs:

> If the constraint is marked NOT VALID, the potentially-lengthy initial
> check to verify that all rows in the table satisfy the constraint is
> skipped. The constraint will still be enforced against subsequent
> inserts or updates (that is, they'll fail unless there is a matching
> row in the referenced table, in the case of foreign keys; and they'll
> fail unless the new row matches the specified check constraints). But
> the database will not assume that the constraint holds for all rows
> in the table, until it is validated by using the VALIDATE CONSTRAINT
> option.

VALIDATE CONSTRAINT will be issued as a separate migration in a
follow-up PR.
This commit is contained in:
Alexey Bezhan
2017-11-08 10:36:11 +00:00
parent 0825177f2d
commit 9d4b8961cb

View File

@@ -0,0 +1,36 @@
"""
Revision ID: 0136_notification_template_hist
Revises: 0135_stats_template_usage
Create Date: 2017-11-08 10:15:07.039227
"""
from alembic import op
revision = '0136_notification_template_hist'
down_revision = '0135_stats_template_usage'
def upgrade():
op.drop_constraint('notifications_template_id_fkey', 'notifications', type_='foreignkey')
op.execute("""
ALTER TABLE notifications ADD CONSTRAINT "notifications_templates_history_fkey"
FOREIGN KEY ("template_id", "template_version") REFERENCES "templates_history" ("id", "version")
NOT VALID
""")
op.drop_constraint('notification_history_template_id_fkey', 'notification_history', type_='foreignkey')
op.execute("""
ALTER TABLE notification_history ADD CONSTRAINT "notification_history_templates_history_fkey"
FOREIGN KEY ("template_id", "template_version") REFERENCES "templates_history" ("id", "version")
NOT VALID
""")
def downgrade():
op.drop_constraint('notifications_templates_history_fkey', 'notifications', type_='foreignkey')
op.create_foreign_key('notifications_template_id_fkey', 'notifications', 'templates', ['template_id'], ['id'])
op.drop_constraint('notification_history_templates_history_fkey', 'notification_history', type_='foreignkey')
op.create_foreign_key('notification_history_template_id_fkey', 'notification_history', 'templates',
['template_id'], ['id'])