Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to roll back migrations using Flyway?

MyBatis migrations splits each SQL file into two sections:

  1. One for migrating forward one version
  2. One for migrating back one version

How does one roll back versions using Flyway?

like image 906
Gili Avatar asked Feb 10 '11 15:02

Gili


People also ask

How do I undo migration?

Undoing Migrations​ With migration you can revert to old state by just running a command. You can use db:migrate:undo , this command will revert most the recent migration. You can revert back to the initial state by undoing all migrations with the db:migrate:undo:all command.

Where are Flyway migrations stored?

Flyway automatically discovers migrations on the filesystem and on the Java classpath.

What is repeatable migration in Flyway?

Introduction. Repeatable migrations are very useful for managing database objects whose definition can then simply be maintained in a single file in version control. Instead of being run just once, they are (re-)applied every time their checksum changes.


1 Answers

While Flyway supports rollbacks (as a commercial-only feature) its use is discouraged:

https://flywaydb.org/documentation/command/undo

While the idea of undo migrations is nice, unfortunately it sometimes breaks down in practice. As soon as you have destructive changes (drop, delete, truncate, …), you start getting into trouble. And even if you don’t, you end up creating home-made alternatives for restoring backups, which need to be properly tested as well.

Undo migrations assume the whole migration succeeded and should now be undone. This does not help with failed versioned migrations on databases without DDL transactions. Why? A migration can fail at any point. If you have 10 statements, it is possible for the 1st, the 5th, the 7th or the 10th to fail. There is simply no way to know in advance. In contrast, undo migrations are written to undo an entire versioned migration and will not help under such conditions.

An alternative approach which we find preferable is to maintain backwards compatibility between the DB and all versions of the code currently deployed in production. This way a failed migration is not a disaster. The old version of the application is still compatible with the DB, so you can simply roll back the application code, investigate, and take corrective measures.

This should be complemented with a proper, well tested, backup and restore strategy. It is independent of the database structure, and once it is tested and proven to work, no migration script can break it. For optimal performance, and if your infrastructure supports this, we recommend using the snapshot technology of your underlying storage solution. Especially for larger data volumes, this can be several orders of magnitude faster than traditional backups and restores.

like image 66
Gili Avatar answered Oct 21 '22 03:10

Gili