What are Database Migrations?

Imagine you've deployed your application and users are actively using it. Now, you need to add a new feature that requires a new column in your User table. How do you update the database?

You could connect directly to the production database and run an ALTER TABLE command, but this is risky! What if you make a typo? What if you need to roll back the change? How do your teammates update their local databases?

Migrations are the solution. They are like version control for your database schema. A migration is a file that contains a set of instructions (usually SQL commands) describing how to upgrade your database schema from one version to the next, and sometimes, how to downgrade it.

The Migration Workflow with Prisma

Prisma has a built-in migration system that makes this process very straightforward.

Step 1: Change Your Schema You start by editing your schema.prisma file. Let's add a role field to our User model.

schema.prisma:

Code snippet


model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  role  String  @default("USER") // Our new field
  posts Post[]
}
// ... rest of the schema

Step 2: Generate and Run the Migration Next, you run a single command in your terminal:

Bash


npx prisma migrate dev --name added_user_role

This command does several things automatically:

  1. It compares your schema.prisma file to the state of your database.
  2. It generates a new SQL file containing the necessary ALTER TABLE command.
  3. It creates a new folder (e.g., prisma/migrations/20250923..._added_user_role) to store this SQL file.
  4. It applies the migration to your database, running the SQL file.
  5. It regenerates the Prisma Client to include the new role field.

The generated SQL file looks something like this:

SQL


-- prisma/migrations/20250923..._added_user_role/migration.sql
-- AlterTable
ALTER TABLE "User" ADD COLUMN "role" TEXT NOT NULL DEFAULT 'USER';

Now your database is in sync with your schema, and the change is documented in a file that can be committed to Git and run by your teammates and deployment scripts.

What is Seeding?

A seed script is a file that populates your database with initial data. This is incredibly useful for:

  • Development: Having dummy data (e.g., fake users and posts) to work with as you build features.
  • Testing: Ensuring your database is in a consistent state before running automated tests.
  • Initial Setup: Creating essential data for a new production environment, like a default admin account.

Seeding with Prisma

Prisma has built-in support for seeding.

Step 1: Create a Seed Script You create a script file (e.g., prisma/seed.ts) that uses Prisma Client to create the data you need.

prisma/seed.ts:

TypeScript


import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

async function main() {
  console.log('Start seeding...');
  
  // Create a default admin user
  const admin = await prisma.user.create({
    data: {
      email: 'admin@example.com',
      name: 'Admin',
      role: 'ADMIN',
    },
  });

  // Create some dummy posts
  await prisma.post.create({
    data: {
      title: 'Welcome to the Blog!',
      content: 'This is the very first post.',
      published: true,
      authorId: admin.id,
    },
  });

  console.log('Seeding finished.');
}

main()
  .catch((e) => console.error(e))
  .finally(async () => await prisma.$disconnect());

Step 2: Run the Seed Script After configuring the path to your script in your package.json file, you can run the seed command:

Bash


npx prisma db seed

This command will execute your script, and just like that, your database is populated with the necessary initial data.