Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails database migrations using transactions

I'm just learning Rails and have begun the section on database migrations. I built 2 migrations and both migrated up successfully. Migrating down, the latest migration, the one that runs first, failed because of a typo in my code. I fixed the typo but the migration continued to fail after that. I discovered the reason why was that the migrating down aborted half way through changes and then when I tried to migrate down again it failed because some of the changes had already been made and so column names were different and other issues like that. I ended up fixing it by fiddling with the schema_migrations table and manually rolling back my changes to a previous version and then migrating back up and down from there.

My question is, is there a way to tell Rails to run migrations in transaction mode and if the code fails, not to commit the transaction?

like image 326
richbai90 Avatar asked Jun 14 '16 19:06

richbai90


People also ask

Are rails migrations run in a transaction?

On databases that support transactions with statements that change the schema, migrations are wrapped in a transaction. If the database does not support this then when a migration fails the parts of it that succeeded will not be rolled back. You will have to rollback the changes that were made by hand.

How rails db Migrate works?

When you run db:migrate, rails will check a special table in the database which contains the timestamp of the last migration applied to the database. It will then apply all of the migrations with timestamps after that date and update the database table with the timestamp of the last migration.

How do I migrate a database in Ruby on Rails?

Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor. The ID column will be created automatically, so don't do it here as well. The method self. up is used when migrating to a new version, self.

What does Add_index do in rails?

It adds a multi-column index on columns one and two in resources table. The advantage of multi-column index is that it helps when you have a query with conditions on those multiple columns.


1 Answers

Rails will already run your migrations inside a transaction if your database supports it:

On databases that support transactions with statements that change the schema, migrations are wrapped in a transaction. If the database does not support this then when a migration fails the parts of it that succeeded will not be rolled back. You will have to rollback the changes that were made by hand.

It's up to you to use a database that respects transactions when performing schema changes. MySQL (as far as I know) doesn't, but Postgres absolutely does.

like image 77
meagar Avatar answered Oct 14 '22 10:10

meagar