From e83d0cf713d1967a5904ec92a052bf52c9a8fdd1 Mon Sep 17 00:00:00 2001 From: Izan Gil <66965250+SrIzan10@users.noreply.github.com> Date: Mon, 31 Mar 2025 16:16:15 +0200 Subject: [PATCH] feat: db self following migration --- .../migration.sql | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 packages/db/prisma/migrations/20250331133341_remove_self_follows/migration.sql diff --git a/packages/db/prisma/migrations/20250331133341_remove_self_follows/migration.sql b/packages/db/prisma/migrations/20250331133341_remove_self_follows/migration.sql new file mode 100644 index 0000000..f9d5ade --- /dev/null +++ b/packages/db/prisma/migrations/20250331133341_remove_self_follows/migration.sql @@ -0,0 +1,28 @@ +-- Remove follows where a user is following their own personal channel +DELETE FROM "Follow" f +USING "User" u +WHERE f."userId" = u.id + AND f."channelId" = u."personalChannelId" + AND u."personalChannelId" IS NOT NULL; + +-- Create a function to prevent self follows +CREATE OR REPLACE FUNCTION prevent_self_follows() +RETURNS TRIGGER AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM "User" + WHERE id = NEW."userId" + AND "personalChannelId" = NEW."channelId" + AND "personalChannelId" IS NOT NULL + ) THEN + RAISE EXCEPTION 'Users cannot follow their own personal channel'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Create a trigger that uses this function +CREATE TRIGGER check_self_follow +BEFORE INSERT OR UPDATE ON "Follow" +FOR EACH ROW +EXECUTE FUNCTION prevent_self_follows(); \ No newline at end of file