Created
October 7, 2010 15:39
-
-
Save williamn/615303 to your computer and use it in GitHub Desktop.
Easy migration between databases
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
# | |
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Originally taken from http://bit.ly/5AutLA