Make user non-optional for a comment

This commit is contained in:
Luke Vella 2024-12-19 15:44:37 +00:00
parent 2cd7d5a581
commit 3a526d53b4
No known key found for this signature in database
GPG key ID: 469CAD687F0D784C
2 changed files with 35 additions and 2 deletions

View file

@ -0,0 +1,33 @@
-- Create guest users for comments without user_id and link them
DO $$
DECLARE
comment_record RECORD;
BEGIN
FOR comment_record IN
SELECT id, author_name
FROM comments
WHERE user_id IS NULL
LOOP
WITH new_user AS (
INSERT INTO users (id, is_guest, created_at)
VALUES (
gen_random_uuid()::text,
TRUE,
NOW()
)
RETURNING id
)
UPDATE comments
SET user_id = (SELECT id FROM new_user)
WHERE id = comment_record.id;
END LOOP;
END;
$$;
-- DropForeignKey
ALTER TABLE "comments" DROP CONSTRAINT "comments_user_id_fkey";
-- AlterTable
ALTER TABLE "comments" ALTER COLUMN "user_id" SET NOT NULL;
-- AddForeignKey
ALTER TABLE "comments" ADD CONSTRAINT "comments_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View file

@ -243,12 +243,12 @@ model Comment {
content String
pollId String @map("poll_id")
authorName String @map("author_name")
user User? @relation(fields: [userId], references: [id])
userId String? @map("user_id")
userId String @map("user_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime? @updatedAt @map("updated_at")
poll Poll @relation("PollToComments", fields: [pollId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id])
@@index([pollId], type: Hash)
@@map("comments")