56 lines
1.4 KiB
Plaintext
56 lines
1.4 KiB
Plaintext
1.
|
|
```
|
|
npx prisma migrate dev --create-only --name add_patient_status_enum
|
|
```
|
|
|
|
2.
|
|
```
|
|
|
|
-- Create the enum type (quoted name keeps exact case)
|
|
DO $$
|
|
BEGIN
|
|
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'PatientStatus') THEN
|
|
CREATE TYPE "PatientStatus" AS ENUM ('ACTIVE', 'INACTIVE', 'UNKNOWN');
|
|
END IF;
|
|
END$$;
|
|
|
|
-- 1) Add new enum column (nullable for backfill)
|
|
ALTER TABLE "Patient"
|
|
ADD COLUMN IF NOT EXISTS "status_new" "PatientStatus";
|
|
|
|
-- 2) Backfill from old text column to enum (case-insensitive)
|
|
UPDATE "Patient"
|
|
SET "status_new" = CASE
|
|
WHEN "status" IS NULL THEN 'UNKNOWN'::"PatientStatus"
|
|
WHEN lower("status") = 'active' THEN 'ACTIVE'::"PatientStatus"
|
|
WHEN lower("status") = 'inactive' THEN 'INACTIVE'::"PatientStatus"
|
|
ELSE 'UNKNOWN'::"PatientStatus"
|
|
END
|
|
WHERE "status_new" IS NULL;
|
|
|
|
-- 3) Safety: ensure no NULLs remain
|
|
DO $$
|
|
DECLARE cnt INTEGER;
|
|
BEGIN
|
|
SELECT count(*) INTO cnt FROM "Patient" WHERE "status_new" IS NULL;
|
|
IF cnt > 0 THEN
|
|
RAISE EXCEPTION 'Migration abort: % rows have NULL status_new', cnt;
|
|
END IF;
|
|
END$$;
|
|
|
|
-- 4) Make new column NOT NULL and set DB default to UNKNOWN
|
|
ALTER TABLE "Patient"
|
|
ALTER COLUMN "status_new" SET DEFAULT 'UNKNOWN',
|
|
ALTER COLUMN "status_new" SET NOT NULL;
|
|
|
|
-- 5) Drop old column and rename new -> status
|
|
ALTER TABLE "Patient" DROP COLUMN IF EXISTS "status";
|
|
ALTER TABLE "Patient" RENAME COLUMN "status_new" TO "status";
|
|
|
|
```
|
|
|
|
|
|
3.
|
|
```
|
|
npx prisma migrate dev
|
|
``` |