Skip to content

Instantly share code, notes, and snippets.

@foloinfo
Created October 19, 2023 05:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foloinfo/942b8f2c59cb45c355529f68eb63521b to your computer and use it in GitHub Desktop.
Save foloinfo/942b8f2c59cb45c355529f68eb63521b to your computer and use it in GitHub Desktop.
Prisma rollback shell script
#!/bin/bash
# prisma does not generate rollback (down script by default)
# this script will generate the down script for each migration
name=$1
dir=$(pwd)
if [ -z "$name" ]
then
echo "Please provide a name for the migration"
exit 1
fi
echo "Generating migration $name"
echo "Generating down.sql"
# generate the down.sql first before the migration
dotenv -e .env.development -- npx prisma migrate diff --from-schema-datamodel prisma/schema.prisma --to-schema-datasource prisma/schema.prisma --script > tmp/down.sql
echo "run yarn db:migrate"
# generate the migration file using prisma
dotenv -e .env.development -- npx prisma migrate dev --create-only --name $name
# find the latest migration
migration_path="${dir}/prisma/migrations"
latest_path=$(ls -td -- "${migration_path}"/*/ | head -n 1)
migration_name=$(basename "${latest_path%/}")
# adding the rollback for migration table
echo "-- remove the last migration from the _prisma_migrations table" >> tmp/down.sql
echo "DELETE FROM _prisma_migrations WHERE migration_name = '${migration_name}';" >> tmp/down.sql
mv ${dir}/tmp/down.sql ${dir}/prisma/migrations/${migration_name}/
echo "Done"
#!/bin/bash
# rollback the latest migration (only apply to the db)
dir=$(pwd)
echo "Rollback the latest migration"
# confirm with the user
read -p "Are you sure you want to rollback the latest migration? (y/n) " -n 1 -r
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
echo "Aborted"
exit 1
fi
# find the latest migration
migration_path="${dir}/prisma/migrations"
latest_path=$(ls -td -- "${migration_path}"/*/ | head -n 1)
migration_name=$(basename "${latest_path%/}")
echo "Executing: $dir/prisma/migrations/${migration_name}/down.sql"
dotenv -e .env.development -- npx prisma db execute --file ${dir}/prisma/migrations/${migration_name}/down.sql
echo "Done"
@foloinfo
Copy link
Author

I have placed the files into ${project_root}/bin, from where I run bin/generate_migration and bin/rollback.
I only use these commands in the development environment, aiming for a rake db:rollback-like behaviour, which I mostly utilize for rollbacks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment