How to Create Prisma Migrations
Migrations are needed to update your database as your application evolves.
Prisma offers a simple way to manage migrations.
Here's a concise article with an example to show you how:
Example Changes
Suppose you're adding a UserProfile table to your database. You would start by defining this new model in your Prisma schema file (prisma/schema.prisma):
model UserProfile {
id Int @id @default(autoincrement())
bio String?
userId Int @unique
user User @relation(fields: [userId], references: [id])
}
Applying Changes with Migrations
After updating your schema, you apply these changes with the following command:
npx prisma migrate dev --name add_user_profile
This command does two main things:
- It creates a new migration file in
prisma/migrationsthat records your schema changes. - Then updates your database schema according to the changes in your Prisma schema file.
Some notes
- Naming Your Migration: Replace
add_user_profilewith a descriptive name. This helps track and understand the purpose of each migration. - Review and Apply: Prisma prompts you to review your migration. Ensure everything is correct before applying the changes to your database.
- Rolling Back: Use
prisma migrate resetto revert your database to an initial state if necessary. Be cautious, as this deletes all data.
Always back up your data before executing significant schema changes.
