diff --git a/packages/database/prisma/migrations/20241219153556_comments_user/migration.sql b/packages/database/prisma/migrations/20241219153556_comments_user/migration.sql new file mode 100644 index 000000000..838d63eb5 --- /dev/null +++ b/packages/database/prisma/migrations/20241219153556_comments_user/migration.sql @@ -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; diff --git a/packages/database/prisma/schema.prisma b/packages/database/prisma/schema.prisma index a283beb15..0cf5c8bad 100644 --- a/packages/database/prisma/schema.prisma +++ b/packages/database/prisma/schema.prisma @@ -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")