Default Values for Required Fields - globe-and-citizen/cnc-portal GitHub Wiki
π§ Why You Should Set Default Values for Required Fields When Updating Your Prisma Database Schema
When working with Prisma and updating your database schema, especially by adding new required fields, it's crucial to think carefully about default values.
π¨ The Problem
If you add a new required field (e.g., isActive Boolean @default(true)
), and your database already has existing records, Prisma (and your database) will require that field to have a value for all records.
If you donβt provide a default value, any existing rows will be invalid because they lack data for that required column. This can lead to:
- β Migration errors (e.g.,
null value in column "isActive" violates not-null constraint
) - β Runtime application crashes
- β Data inconsistency
β The Solution: Use Default Values
When adding a new required field in your Prisma schema, always consider using @default(...)
, especially if you already have data in the table.
model User {
id Int @id @default(autoincrement())
email String @unique
isActive Boolean @default(true) // β
Safe default
}
This tells Prisma to apply a sensible default for all new and existing records when running the migration.
π οΈ When to Think About Defaults
You must think about defaults when:
- β Adding a new required field to an existing model
- π Changing an optional field to required
- π¦ Running a migration on a table that already has data
π§° Tips for Safe Migrations
-
Use
@default(...)
on required fields when possible. -
If no sensible default exists, add the field as optional first, update the data manually, then make it required.
-
Always run migrations on a staging copy of your DB first.
-
Use Prisma Migrateβs preview command:
npx prisma migrate dev --preview-feature
π Summary
Adding a required field without a default value to a populated database is risky. Avoid migration issues and data errors by setting defaults or planning manual data updates in advance.