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
]
  1. Tieg about 24 hours later:

    YES! Thanks, I’ll probably use this.

  2. David Richards 7 months later:

    http://pastie.caboo.se/118689

    Thats a link to an improved version

  3. Tim Connor 7 months later:

    Sweet, thanks for the link, David.

  4. Tim Connor about 1 year later:
    Since we don’t use db based RFI at work, I instead had it just load all the yml files in db/fixtures:
    
        task :load => :environment do
          ActiveRecord::Base.establish_connection
          require 'active_record/fixtures'
          #fixtures = ActiveRecord::Base.configurations[:fixtures_load_order]
          fixtures = Dir.entries("#{RAILS_ROOT}/db/fixtures/").slice(2..-1).collect { |f| f.slice(0..-5) }
    
          Fixtures.create_fixtures("db/fixtures", fixtures)
    
          puts "Loaded these fixtures: " 
          puts fixtures
          #puts ActiveRecord::Base.configurations[:fixtures_load_order].collect { |f| f.to_s }.join(', ')
        end
    
Comment form

(leave url/email »)

Help with Textile (code)