-- test user INSERT INTO user(name) VALUES('Marie'); INSERT INTO "user_role" (user_id, role_id) VALUES((SELECT id from user where name = 'Marie'),(SELECT id FROM role where name = 'Donau Linz')); INSERT INTO user(name) VALUES('Philipp'); INSERT INTO "user_role" (user_id, role_id) VALUES((SELECT id from user where name = 'Philipp'),(SELECT id FROM role where name = 'Donau Linz')); ALTER TABLE "role" ADD COLUMN "cluster" text; CREATE TRIGGER IF NOT EXISTS prevent_multiple_roles_same_cluster BEFORE INSERT ON user_role BEGIN SELECT CASE WHEN EXISTS ( SELECT 1 FROM user_role ur JOIN role r1 ON ur.role_id = r1.id JOIN role r2 ON r1."cluster" = r2."cluster" WHERE ur.user_id = NEW.user_id AND r2.id = NEW.role_id AND r1.id != NEW.role_id ) THEN RAISE(ABORT, 'User already has a role in this cluster') END; END; UPDATE role SET 'cluster'='skill' WHERE id=2; UPDATE role SET 'cluster'='membership_type' WHERE id=3; UPDATE role SET 'cluster'='skill' WHERE id=5; UPDATE role SET 'cluster'='skill' WHERE id=6; UPDATE role SET 'cluster'='membership_type' WHERE id=7; UPDATE role SET 'cluster'='financial' WHERE id=8; UPDATE role SET 'cluster'='membership_type' WHERE id=9; UPDATE role SET 'cluster'='membership_type' WHERE id=14; UPDATE role SET 'cluster'='financial' WHERE id=17; UPDATE role SET 'cluster'='financial' WHERE id=18; UPDATE role SET 'cluster'='membership_type' WHERE id=20; UPDATE role SET 'cluster'='membership_type' WHERE id=22;