rembrembdocs

Workflows

How to generate a down migration SQL file that reverses a given migration file

When generating a migration SQL file, you may wish to also create a "down migration" SQL file that reverses the schema changes in the corresponding "up migration" file. Note that "down migrations" are also sometimes called "migration rollbacks".

This guide explains how to use Prisma Migrate's migrate diff command to create a down migration, and how to apply it to your production database with the db execute command in the case of a failed up migration.

When generating a down migration file, there are some considerations to be aware of:

This section describes how to generate a down migration SQL file along with the corresponding up migration, and then run it to revert your database schema after a failed up migration on production.

As an example, take the following Prisma schema with a User and Post model as a starting point:

schema.prisma

model Post {
  id       Int     @id @default(autoincrement())
  title    String  @db.VarChar(255)
  content  String?
  author   User    @relation(fields: [authorId], references: [id])
  authorId Int
}

model User {
  id    Int     @id @default(autoincrement())
  name  String?
  posts Post[]
}

You will need to create the down migration first, before creating the corresponding up migration.

Generating the migrations

This will create a new <timestamp>_add_profile directory inside the prisma/migrations directory, with your new migration.sql up migration file inside.

How to apply your down migration to a failed migration

If your previous up migration failed, you can apply your down migration on your production database with the following steps:

To apply the down migration on your production database after a failed up migration: