Files
lms-be/prisma/migrations/20260604143000_add_student_enrollments/migration.sql
T
2026-07-07 16:09:12 +09:00

30 lines
1.3 KiB
SQL

CREATE TABLE "student_enrollments" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"user_id" UUID NOT NULL,
"organization_id" UUID,
"organization_name" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'ACTIVE',
"removed_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "student_enrollments_pkey" PRIMARY KEY ("id")
);
CREATE UNIQUE INDEX "student_enrollments_user_id_organization_name_key" ON "student_enrollments"("user_id", "organization_name");
CREATE INDEX "student_enrollments_organization_id_status_idx" ON "student_enrollments"("organization_id", "status");
CREATE INDEX "student_enrollments_organization_name_status_idx" ON "student_enrollments"("organization_name", "status");
ALTER TABLE "student_enrollments" ADD CONSTRAINT "student_enrollments_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
INSERT INTO "student_enrollments" ("user_id", "organization_id", "organization_name", "status")
SELECT
u."id",
u."primary_organization_id",
u."primary_organization_name",
'ACTIVE'
FROM "users" u
WHERE u."primary_organization_name" IS NOT NULL
AND (u."auth_role" IS NULL OR u."auth_role" IN ('USER', 'STUDENT'))
ON CONFLICT ("user_id", "organization_name") DO NOTHING;