Short version:
What's up with down
migrations? In what scenario(s) would you need to use one?
Long version:
Many frameworks that support database schema versions (including, not limited to, Rails' "migrations") allow the developer to specify how data upgrades (an up
operation) can be reversed (aka down
), or even automatically generate a downgrade operation by analysing the code (as in Rails' change
method).
Indeed, it seems extremely common to do so in all the Rails migration code I've come across, which makes me wonder if it's considered a best practice.
Personally, I've never needed to downgrade a database schema, and I can't imagine a reasonable scenario where I would want to, either in dev or production. My experience seems at odds with the prevalence of down
migrations, so I'm guessing I'm missing something...
What are the most common scenarios where a down
is useful?
Say you've pushed a new version to production and run the migrations, and some time later you find a bug that can't be solved immediately. Since you need to keep the production server running, you revert to a previous commit. However, this wouldn't revert the changes made to the database, which would result in errors. So you'd need a way to roll back the changes made to the database, and then revert to the older version. This situation may not arise too frequently, but it's important to have the mechanism for when it does.
In development, you might run some migrations and later decide that you want to change, add, or remove something. Having a way to undo them means you don't need to create a new migration for every small change.