Skip to content

Commit 891cbae

Browse files
committed
fix: update trigger
1 parent eed03fe commit 891cbae

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

coderd/database/migrations/000296_organization_soft_delete.up.sql

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ DECLARE
1717
template_count int;
1818
group_count int;
1919
member_count int;
20+
provisioner_keys_count int;
2021
BEGIN
2122
workspace_count := (
2223
SELECT count(*) as count FROM workspaces
@@ -44,6 +45,12 @@ BEGIN
4445
organization_members.organization_id = OLD.id
4546
);
4647

48+
provisioner_keys_count := (
49+
Select count(*) as count FROM provisioner_keys
50+
WHERE
51+
provisioner_keys.organization_id = OLD.id
52+
)
53+
4754
-- Fail the deletion if one of the following:
4855
-- * the organization has 1 or more workspaces
4956
-- * the organization has 1 or more templates
@@ -54,8 +61,20 @@ BEGIN
5461
RAISE EXCEPTION 'cannot delete organization: organization has % workspaces and % templates that must be deleted first', workspace_count, template_count;
5562
END IF;
5663

57-
IF (group_count + member_count) > 2 THEN
58-
RAISE EXCEPTION 'cannot delete organization: organization has % groups and % members that must be deleted first', group_count - 1, member_count - 1;
64+
IF (group_count) > 1 THEN
65+
RAISE EXCEPTION 'cannot delete organization: organization has % groups that must be deleted first', group_count - 1;
66+
END IF;
67+
68+
IF (provisioner_keys_count) > 0 THEN
69+
RAISE EXCEPTION 'cannot delete organization: organization has % provisioner keys that must be deleted first', provisioner_keys_count;
70+
END IF;
71+
72+
-- If member count > 1
73+
-- Allow 1 member to exist, because you cannot remove yourself. You can
74+
-- remove everyone else. Ideally, we only omit the member that matches
75+
-- the user_id of the caller, however in a trigger, the caller is unknown.
76+
IF (member_count) > 1 THEN
77+
RAISE EXCEPTION 'cannot delete organization: organization has % members that must be deleted first', member_count - 1;
5978
END IF;
6079

6180
RETURN NEW;

0 commit comments

Comments
 (0)