Java.DBMigrationTools.How do you undo a Flyway migration?

Short Answer

Flyway lets you undo a migration using special undo scripts — but only if you’re using Flyway Teams Edition.

In open-source Flyway, undo must be done manually (e.g., with a rollback script or by reverting migrations in Git and resetting the DB).

🔍 Flyway Teams Edition: Undo Scripts

To enable automatic rollbacks, you write U__ undo scripts that correspond to versioned migrations.

🛠️ Example

If you have this migration:

V2__add_users_table.sql

You can write this undo file:

U2__drop_users_table.sql

Content:

DROP TABLE users;

Then you can call:

flyway undo

✅ Flyway looks up the most recently applied versioned migration (V2)
✅ Finds the corresponding U2 script
✅ Executes it and removes V2 from flyway_schema_history

⚠️ Notes on Undo Scripts

  • Undo is not repeatable — it’s only for the latest applied migration
  • Only one version can be undone per command
  • Undo does not apply to repeatable migrations (R__)

🧱 Open Source Workarounds

If you’re using Flyway Community Edition (open-source):

  1. Create a manual rollback script (e.g., rollback.sql)
  2. Run it manually if something goes wrong
  3. Or, if you’re in dev: reset the DB + clean + re-migrate:
flyway clean
flyway migrate

⚠️ flyway clean deletes all schema objects — only use in dev/test environments.

📌 Key Takeaways

✅ In Flyway Teams, use U__ scripts + flyway undo to rollback versioned migrations
❌ In Community Edition, there is no automatic undo — handle rollbacks manually
✅ Best practice: write custom rollback scripts or ensure your migrations are idempotent and safe

This entry was posted in Без рубрики. Bookmark the permalink.