Techtrekking

How to update Next.js prima app after doing database changes in prisma.schema

By Pravinā€¢

After updating your schema.prisma file, you need to apply the changes to your PostgreSQL database. Follow these steps to properly update your schema:


Step 1: Check Changes in schema.prisma

Modify your schema.prisma file with new fields, models, or relationships.

Example:
If you initially had:

model User { id String @id @default(uuid()) name String email String @unique createdAt DateTime @default(now()) }

And you add a new field age:

model User { id String @id @default(uuid()) name String email String @unique age Int? // New optional field createdAt DateTime @default(now()) }

Step 2: Create a New Migration

After updating schema.prisma, create a new migration:

npx prisma migrate dev --name add-age-field

āœ… This will:

  • Generate a SQL migration file inside prisma/migrations/.
  • Apply the migration to your PostgreSQL database.

Step 3: Regenerate Prisma Client

Whenever you make schema changes, regenerate the Prisma Client:

npx prisma generate

This ensures your application uses the latest schema.


Step 4: Check If Changes Applied

Run Prisma Studio to inspect your database:

npx prisma studio

Or check directly with SQL:

psql -d mydatabase -U myuser -c '\d+ "User"'

Step 5: Deploy Changes in Production

If running in production, apply migrations with:

npx prisma migrate deploy

šŸš€ This ensures the database schema is updated without affecting existing data.


Step 6: Handle Data Migration (If Needed)

If you removed or changed a column, you may need to migrate the data manually:

  • Use SQL:
    UPDATE "User" SET age = 25 WHERE age IS NULL;
  • Or write a Prisma script:
    import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); async function updateUsers() { await prisma.user.updateMany({ data: { age: 25 }, where: { age: null } }); console.log("Updated users!"); } updateUsers().finally(() => prisma.$disconnect());

Quick Summary

ActionCommand
Edit schema.prismaModify models & fields
Create new migrationnpx prisma migrate dev --name <migration-name>
Regenerate Prisma Clientnpx prisma generate
View databasenpx prisma studio
Apply changes in productionnpx prisma migrate deploy
Handle data migrationUse SQL or Prisma script

āœ… Now your database schema is updated and ready to use! Let me know if you need further guidance. šŸš€

Comments
No comments yet. Be the first to comment!
Leave a Comment
Your comment will be visible after approval.