// HACKER NEWS — CYBERSECURITY
Flyway for freeloaders, rollback implemented in Python
A single command to roll back applied migrations with Flyway Community Edition, no license, no undo command, no crying in the club.
If you’ve ever priced Flyway Teams just for the undo command, you know what I’m talking about. Managed rollback functionality is the most delectable morsel that lives behind the Flyway paywall, and it’s the one feature everyone wants at 2am when a migration hits the fan in prod. The Community edition gives you migrate, info, validate, repair, and stubs its cigarette out in your eye when you ask it to go backwards.
A solution you ask? It turns out you don’t need the paid undo, you just need to be a little bit devious about what “rollback” actually is. The following rollback implementation is achieved entirely via Flyway commands, without running any SQL directly against the database via a separate driver (#minimalism). Here’s how it works, buckle up girls.
Here’s the mental unlock. Flyway Community will happily run any versioned migration you hand it. It doesn’t care whether that migration creates a table or drops one, SQL is SQL.
There are however, two things Flyway is very passionate about, and this solution is built around them: version numbers must always go up and the schema history table is bible.
So instead of asking Flyway to reverse V2, we write a new, higher-versioned migration whose body happens to be the reverse of V2, and we ask Flyway to migrate forward into it. Basically an “undo” expressed as migrate, and the database ends up back where it started.
Then we clean up the paper trail of the migrations, and their respective “undo” migrations, in the flyway_schema_history table so it lines back up with the database state, and the files on disk.
Two directories per scope. Your intended migrations, and a parallel set of “down” scripts that reverse the logic applied by these migrations. Something like:
The naming convention is load-bearing. “down” scripts should be matched to their initial migration by the V__ prefix.
As part of the rollback the down script versions will be incremented, so Flyway sees them as new migrations to be applied (we’ll get to this shortly). I’d recommend validating that there is equivalent “down” script for every migration ready to go up front, so nothing is found to be missing mid-rollback:
An important question: when someone runs rollback, what exactly are they rolling back? The last migration? The last batch? What if the last migrate applied three files at once?