anita codes logo
Published on

Resolving Prisma Schema Drift with Supabase (A Step-by-Step Guide)

Prisma Supabase

Managing database schemas efficiently while ensuring that migrations are in sync can be a challenge, particularly when using tools like Prisma with Supabase. At FluentlyFlow, we faced a similar challenge and developed a systematic approach to handle Prisma schema drift. Here's a simple, step-by-step guide to help you manage schema changes smoothly.

Understanding Schema Drift

Schema drift occurs when changes made in the database schema do not match the state expected by Prisma migrations. This can lead to discrepancies that affect the stability and functionality of your application.

Step-by-Step Solution to Resolve Prisma Schema Drift

Step 1: Modify the Prisma Schema

Start by making the necessary changes directly in your Prisma schema file (schema.prisma). For instance, add a new model or adjust a field type according to your application's requirements.

model User {
  id    Int    @id @default(autoincrement())
  name  String
  email String @unique
}

Step 2: Create SQL Statement for the Modification

Next, write the SQL statement that corresponds to your schema modification. This SQL is what you would manually apply to the database.

ALTER TABLE "User" ADD COLUMN "email" TEXT UNIQUE;

Step 3: Paste SQL Statement into the Most Recent Migration

Incorporate the SQL statement into the latest migration file located in your Prisma migrations directory. For example, if adding a unique constraint to an email field:

echo 'ALTER TABLE "User" ADD COLUMN "email" TEXT UNIQUE;' >> prisma/migrations/20240313021513_feature_request/migration.sql

Step 4: Update Migration Checksum

To ensure Prisma recognizes the changes, update the checksum of the modified migration file using the shasum command:

shasum -a 256 prisma/migrations/20240313021513_feature_request/migration.sql
shasum -a 256 prisma/migrations/2132323232_remove_id/migration.sql

Step 5: Update Prisma Migrations Table in Supabase

Copy the new checksum values and update the corresponding entries in the _prisma_migrations table within your Supabase database. This step is crucial as it helps Prisma recognize that the migrations are up to date.

UPDATE "_prisma_migrations" SET "checksum" = 'new_checksum_here' WHERE "name" = '2132323232_remove_id';

Conclusion

By following these steps, you can resolve issues related to Prisma schema drift when using a Supabase database. This process has proven effective for us at FluentlyFlow, ensuring that our language learning platform remains robust and scalable. Managing schema changes meticulously allows for smoother development cycles and minimizes disruptions to service.

For more tips and detailed guides on managing your database effectively, keep following our posts at FluentlyFlow.