public
Last active

Easy migration between databases

  • Download Gist
backup.rake
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.