From e3759a2e5c8aebd0579a1f30767fb103749a551b Mon Sep 17 00:00:00 2001 From: Drew DeVault Date: Thu, 3 Nov 2022 13:26:23 +0100 Subject: [PATCH] Schema: fix more missing cascades --- .../8bf166ebda01_fix_missing_cascades.py | 37 +++++++++++++++++++ schema.sql | 6 +-- 2 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 metasrht/alembic/versions/8bf166ebda01_fix_missing_cascades.py diff --git a/metasrht/alembic/versions/8bf166ebda01_fix_missing_cascades.py b/metasrht/alembic/versions/8bf166ebda01_fix_missing_cascades.py new file mode 100644 index 0000000..0718008 --- /dev/null +++ b/metasrht/alembic/versions/8bf166ebda01_fix_missing_cascades.py @@ -0,0 +1,37 @@ +"""Fix missing cascades + +Revision ID: 8bf166ebda01 +Revises: dd0274654d4e +Create Date: 2022-11-03 13:23:36.572482 + +""" + +# revision identifiers, used by Alembic. +revision = '8bf166ebda01' +down_revision = 'dd0274654d4e' + +from alembic import op +import sqlalchemy as sa + +cascades = [ + ("user", "pgpkey", "pgp_key_id", "SET NULL"), + ("user_webhook_subscription", "oauthtoken", "token_id", "CASCADE"), + ("user_webhook_delivery", "user_webhook_subscription", "subscription_id", "CASCADE"), +] + +def upgrade(): + for (table, relation, col, do) in cascades: + op.execute(f""" + ALTER TABLE "{table}" DROP CONSTRAINT IF EXISTS {table}_{col}_fkey; + ALTER TABLE "{table}" ADD CONSTRAINT {table}_{col}_fkey + FOREIGN KEY ({col}) + REFERENCES "{relation}"(id) ON DELETE {do}; + """) + + +def downgrade(): + for (table, relation, col, do) in tables: + op.execute(f""" + ALTER TABLE "{table}" DROP CONSTRAINT IF EXISTS {table}_{col}_fkey; + ALTER TABLE "{table}" ADD CONSTRAINT {table}_{col}_fkey FOREIGN KEY ({col}) REFERENCES "{relation}"(id); + """) diff --git a/schema.sql b/schema.sql index 92d2568..4b34b89 100644 --- a/schema.sql +++ b/schema.sql @@ -79,7 +79,7 @@ CREATE TABLE pgpkey ( ALTER TABLE "user" ADD CONSTRAINT user_pgp_key_id_fkey - FOREIGN KEY (pgp_key_id) REFERENCES pgpkey(id); + FOREIGN KEY (pgp_key_id) REFERENCES pgpkey(id) ON DELETE SET NULL; CREATE TABLE sshkey ( id serial PRIMARY KEY, @@ -242,7 +242,7 @@ CREATE TABLE user_webhook_subscription ( url character varying(2048) NOT NULL, events character varying NOT NULL, user_id integer REFERENCES "user"(id) ON DELETE CASCADE, - token_id integer REFERENCES oauthtoken(id) + token_id integer REFERENCES oauthtoken(id) ON DELETE CASCADE ); CREATE TABLE user_webhook_delivery ( @@ -256,7 +256,7 @@ CREATE TABLE user_webhook_delivery ( response character varying(16384), response_status integer NOT NULL, response_headers character varying(16384), - subscription_id integer REFERENCES user_webhook_subscription(id) + subscription_id integer REFERENCES user_webhook_subscription(id) ON DELETE CASCADE ); CREATE TABLE webhook_subscription (