Last active
December 10, 2015 01:09
-
-
Save bithive/4356688 to your computer and use it in GitHub Desktop.
A Rake task for destructively copying one environment's database to another, preserving IDs. Should support different database adapters, but aborts if the schema versions don't match. Not recommended for large tables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace :clone do | |
desc 'destructively copy the source environment database to the target' | |
task :database, [:source, :target] => :environment do |t, args| | |
source = args[:source].to_sym | |
target = args[:target].to_sym | |
versions = {} | |
[ source, target ].each do |db| | |
ActiveRecord::Base.establish_connection db | |
versions[db] = ActiveRecord::Migrator.current_version | |
end | |
if versions[source] != versions[target] | |
abort "Schema mismatch! #{source}: #{versions[source]}, #{target}: #{versions[target]}" | |
end | |
tables = ActiveRecord::Base.connection.tables - %w(schema_migrations) | |
tables.sort.each do |table| | |
ActiveRecord::Base.connection.execute "delete from #{table}" | |
print table | |
ActiveRecord::Base.establish_connection source | |
fixtures = ActiveRecord::Base.connection.select_all("select * from #{table}") | |
ActiveRecord::Base.establish_connection target | |
fixtures.each do |fixture| | |
print '.' | |
ActiveRecord::Base.connection.insert_fixture fixture, table | |
end | |
puts | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment