To rollback a single Go migration in Bun.js, follow these steps:
Rollback a Single Migration
1. Identify the migration you want to rollback. Let's say you want to rollback the migration with the timestamp `20210505110026`.
2. In your `main.go` file, locate the migration collection you created using `migrate.NewMigrations()`.
3. Find the corresponding `MustRegister` call for the migration you want to rollback. It will look something like this:
go
Migrations.MustRegister(
func(ctx context.Context, db *bun.DB) error {
// Up migration logic here
return nil
},
func(ctx context.Context, db *bun.DB) error {
// Down migration logic here
return nil
},
)
4. Comment out or remove the `MustRegister` call for the migration you want to rollback. This effectively removes the migration from being applied.
5. Run the migrations again using the `migrate` command:
bash
BUNDEBUG=2 go run . db migrate
This will rollback the specific migration you removed from the `MustRegister` calls.
Rollback Multiple Migrations
To rollback multiple migrations, you can remove or comment out multiple `MustRegister` calls for the migrations you want to rollback.
Bun will rollback migrations in reverse order, so the last migration you remove will be the first one rolled back.
After removing the desired `MustRegister` calls, run `go run . db migrate` again to apply the remaining migrations.
Considerations
- Removing a `MustRegister` call will only rollback that specific migration. It will not rollback any other migrations that were applied before or after it.
- Be careful when rolling back migrations, as it may leave your database in an inconsistent state if the migrations are interdependent. Always test your rollbacks in a non-production environment first.
- If you want to rollback all migrations, you can use `go run . db rollback` instead of manually removing `MustRegister` calls.
By selectively removing `MustRegister` calls for specific migrations, you can rollback individual Go migrations in Bun.js. This gives you fine-grained control over your database schema changes.
Citations:[1] https://bun.uptrace.dev/guide/migrations.html
[2] https://pkg.go.dev/github.com/uptrace/bun/example/migrate
[3] https://stackoverflow.com/questions/3647685/how-can-i-rollback-a-specific-migration
[4] https://v5-docs.adonisjs.com/guides/database/migrations
[5] https://blog.openreplay.com/how-to--migrating-from-node-to-bun/
[6] https://github.com/redraskal/bun-migrate
[7] https://github.com/golang-migrate/migrate/issues/183
[8] https://www.reddit.com/r/golang/comments/18g9w4a/what_does_your_company_use_for_migrations_and_db/