fix(portal): Update flows fkey constraints to cascade deletes (#8645)

The `flows` table currently has `ON DELETE SET NULL` behavior for many
of its foreign key constraints. The problem is that if we try to delete
any of the associated entities, setting a null here causes the DB
operation to fail with:

```
ERROR:  null value in column "policy_id" of relation "flows" violates not-null constraint
```

I can understand why it was originally architected like this to preserve
connection log data, but we'll be using another approach for that that
doesn't require maintaining relational data in perpetuity.

Related: #949
This commit is contained in:
Jamil
2025-04-03 16:29:19 -07:00
committed by GitHub
parent f17b045469
commit 6e336fc3bc

View File

@@ -0,0 +1,40 @@
defmodule Domain.Repo.Migrations.AddCascadeDeleteToFlows do
use Ecto.Migration
def change do
# Drop existing foreign key constraints that need to change
execute("""
ALTER TABLE flows
DROP CONSTRAINT flows_policy_id_fkey,
DROP CONSTRAINT flows_client_id_fkey,
DROP CONSTRAINT flows_gateway_id_fkey,
DROP CONSTRAINT flows_resource_id_fkey,
DROP CONSTRAINT flows_token_id_fkey;
""")
# Add new foreign key constraints with ON DELETE CASCADE
execute("""
ALTER TABLE flows
ADD CONSTRAINT flows_policy_id_fkey
FOREIGN KEY (policy_id)
REFERENCES policies(id)
ON DELETE CASCADE,
ADD CONSTRAINT flows_client_id_fkey
FOREIGN KEY (client_id)
REFERENCES clients(id)
ON DELETE CASCADE,
ADD CONSTRAINT flows_gateway_id_fkey
FOREIGN KEY (gateway_id)
REFERENCES gateways(id)
ON DELETE CASCADE,
ADD CONSTRAINT flows_resource_id_fkey
FOREIGN KEY (resource_id)
REFERENCES resources(id)
ON DELETE CASCADE,
ADD CONSTRAINT flows_token_id_fkey
FOREIGN KEY (token_id)
REFERENCES tokens(id)
ON DELETE CASCADE;
""")
end
end