Skip to content

Instantly share code, notes, and snippets.

@bithive
Last active December 10, 2015 01:09
Show Gist options
  • Save bithive/4356688 to your computer and use it in GitHub Desktop.
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.
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