0
0
NestJSframework~5 mins

Prisma migrations in NestJS

Choose your learning style9 modes available
Introduction

Prisma migrations help you change your database structure safely and easily. They keep your database and code in sync as your app grows.

When you add a new table or model to your database.
When you change a column type or add a new column.
When you remove or rename a field in your data model.
When you want to share database changes with your team.
When deploying updates to production databases.
Syntax
NestJS
npx prisma migrate dev --name descriptive_migration_name

This command creates a new migration file based on your Prisma schema changes.

The --name should describe what the migration does, like add_user_table.

Examples
Creates a migration to add a new Post model to the database.
NestJS
npx prisma migrate dev --name add_post_model
Creates a migration to make the email field unique.
NestJS
npx prisma migrate dev --name change_email_to_unique
Applies all pending migrations to a production database without prompting.
NestJS
npx prisma migrate deploy
Sample Program

This example shows how to add a new User model and create a migration to update the database.

NestJS
/*
1. Update your Prisma schema file (schema.prisma):
model User {
  id    Int    @id @default(autoincrement())
  name  String
  email String @unique
}

2. Run migration command:
npx prisma migrate dev --name add_user_model

3. Prisma creates migration files and updates your database.
*/
OutputSuccess
Important Notes

Always review migration files before applying them to production.

Use npx prisma migrate reset to reset your local database during development (this deletes all data).

Keep migration names clear and descriptive for easy tracking.

Summary

Prisma migrations keep your database structure matched with your code.

Use npx prisma migrate dev --name to create migrations during development.

Apply migrations safely to production with npx prisma migrate deploy.