Rails/MySql consolidation of migrations
I have a Rails app running over a MySql DB.
Is there a way to consolidate migrations? for example:
lets say I have a very large table called members
and I create a migration to add column name
to that table, later on I create another migration that adds another field address
and adds index to the address
field.
when i run the migration now, it will change the tab开发者_Go百科le 3 times: add name
, add address
and add index. and in each of the times, the alter table command will actually create a new table, copy all the data to it and drop the old table.
in my case, the members
table is very big, over 10M records so each alter takes a few hours.
is there a way to consolidate the changes into one alter?
Your question is a bit difficult to understand, as you're not limited to one operation per migration.
you can easily do :
class AddNameAddressAndIndexToMembers < ActiveRecord::Migration
def up
change_table :members do |t|
t.string :name
t.text :address
t.index :name
end
end
def down
change_table :members do |t|
t.remove_index :name
t.remove :name, :address
end
end
end
just reverse your migrations, delete previous migration files, run this migration and all should be well.
Now, if you mean that these are old migrations, it can be tricky because you don't want to reverse tons of migrations. But what do you want to achieve ? if you only need to deploy, use the current schema.rb with rake db:schema:dump and rake db:schema:load
If you're really wanting to maximize speed, you probably should consider deploying SQL in an execute call, in which you can for instance create a temporary result set with your desired structure, empty, drop, and/or alter the existing table, and re-populate that table from the temporary result set:
class SQLRevisions < ActiveRecord::Migration
def change
execute "
[SQL PROCESS CALL]
[SQL PROCESS CALL]
[ETC.]"
end
end
Test your migration locally for the intended results, and then run it on your production instance.
精彩评论