Catch Unsafe Migrations With The Strong Migrations Gem
It is possible to do database migrations without incurring any downtime as long as we follow certain patterns. For example, instead of renaming a column (which is not backwards-compatible with currently running web servers) in one step, you would so in 3 steps:
- Add the new column and start writing to both columns but keep reading from the old column
- Sync the new column with the old and stop writing to the old column
- Drop the old column
A very useful tool in this context is the Strong Migrations gem. This gem will detect potentially unsafe migrations and prevent them from running. It will even give you some guidelines on safer ways to do what you want!
If you’re sure a migration is safe - for example, if you’re dropping a column as the 3rd step of renaming a column - you need to wrap your migration in a safety_assured
block.
I really like this since it’s an obvious conversation point during code reviews. It’s not going to catch all errors, but it’s a great tool - it adds value without any real overhead.