Skip to content

Instantly share code, notes, and snippets.

@williamn
Created October 7, 2010 15:39
Show Gist options
  • Save williamn/615303 to your computer and use it in GitHub Desktop.
Save williamn/615303 to your computer and use it in GitHub Desktop.
Easy migration between databases
#
# Original blog here http://bit.ly/5AutLA
#
namespace :db do
namespace :backup do
def tables
ActiveRecord::Base.connection.tables.sort.reject do |tbl|
['schema_migrations'].include?(tbl)
end
end
desc "Dump entire db."
task :write => :environment do
dir = RAILS_ROOT + '/db/backup'
FileUtils.mkdir_p(dir)
FileUtils.chdir(dir)
tables.each do |tbl|
klass = tbl.classify.constantize
puts "Writing #{tbl}..."
File.open("#{tbl}.yml", 'w+') { |f| YAML.dump klass.find(:all).collect(&:attributes), f }
end
end
desc "Load YML files from /db/backup/ into the database"
task :read => :environment do
dir = RAILS_ROOT + '/db/backup'
FileUtils.mkdir_p(dir)
FileUtils.chdir(dir)
tables.each do |tbl|
klass = tbl.classify.constantize
ActiveRecord::Base.transaction do
if File::exists?("#{tbl}.yml")
puts "Loading #{tbl}..."
YAML.load_file("#{tbl}.yml").each do |fixture|
ActiveRecord::Base.connection.execute "INSERT INTO #{tbl} (#{fixture.keys.join(",")}) VALUES (#{fixture.values.collect { |value| ActiveRecord::Base.connection.quote(value) }.join(",")})", 'Fixture Insert'
end
end
end
end
end
end
end
@williamn
Copy link
Author

williamn commented Oct 7, 2010

Originally taken from http://bit.ly/5AutLA

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment