Backing up or transfering your data via YAML 4

Posted by Tim Connor Mon, 26 Mar 2007 21:27:00 GMT

Thanks to http://snippets.dzone.com/tag/fixtures. No warranties and no guarantees it’ll work on your full DB. I’m just using it for transferring around my starting data during dev.

Yes, I know part of this can be done with db:fixtures:load – but I don’t want to use ‘tests/fixtures’

lib/tasks/fixtures.rake


namespace :db do
namespace :YAML do
desc ‘Create YAML backup fixtures’
task :backup => :environment do
sql = “SELECT * FROM %s”
skip_tables = [“schema_info”, “sessions”]
ActiveRecord::Base.establish_connection
tables = ENV[‘FIXTURES’] ? ENV[‘FIXTURES’].split(/,/) : ActiveRecord::Base.connection.tables – skip_tables
tables.each do |table_name|
i = “000”
File.open(“#{RAILS_ROOT}/db/fixtures/#{table_name}.yml”, ‘w’) do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name)
file.write data.inject({}) { |hash, record|
hash[“#{table_name}_#{i.succ!}”] = record
hash
}.to_yaml
end
end
end

desc “Load db/fixtures in fixtures_load_order” task :restore => :environment do ActiveRecord::Base.establish_connection require ‘active_record/fixtures’ Fixtures.create_fixtures(“db/fixtures”, ActiveRecord::Base.configurations[:fixtures_load_order]) puts "Loaded these fixtures: " + ActiveRecord::Base.configurations[:fixtures_load_order].collect { |f| f.to_s }.join(’, ’) end end

end

config/environments.rb


ActiveRecord::Base.configurations[:fixtures_load_order] = [
:users,
:locations,
:reports,
:conditions
]