you are here: codestackercodes [RSS] → tag task [RSS]

task for database backup

another solutions:

http://blog.craigambrose.com/articles/2007/03/01/a-rake-task-for-database-backups
http://tiago.zusee.com/blog/2007/06/12/rake-task-para-backup-de-banco-de-dados-em-rails/
http://derenci.us/2007/7/backup-do-banco-com-rake

require 'ftools'
require 'find'
namespace :db do
  desc "Backup the database to a file. Options: DIR=base_dir RAILS_ENV=production COMPACT=true MAX=2"
  task :backup => [:environment] do
    datestamp = Time.now.strftime("%Y-%m-%d")
    hourstamp = Time.now.strftime("%H-%M-%S")
    base_path = ENV["DIR"] || "db"
    backup_base = File.join(base_path, 'backup')
    backup_file = File.join(backup_base, "#{RAILS_ENV}_#{datestamp}_#{hourstamp}_dump.sql")
    File.makedirs(backup_base)
    db_config = ActiveRecord::Base.configurations[RAILS_ENV]
    host = " -h #{db_config['host']} " if db_config['host'] and !db_config['socket']

    sh "mysqldump #{host} -u #{db_config['username']} -p#{db_config['password']} #{db_config['database']} > #{backup_file}"
    puts "Created backup: #{backup_file}"
    
    sh "bzip2 -z #{backup_file}" if ENV["COMPACT"] == "true" 
    puts "Compacted backup: #{backup_file}.bz2" if ENV["COMPACT"] == "true" 
    
    dir = Dir.new(backup_base)
    all_backups = dir.entries[2..-1].sort
    max_backups = ENV["MAX"].to_i || 5
    unwanted_backups = all_backups[max_backups..-2] || []
    for unwanted_backup in unwanted_backups
      FileUtils.rm_rf(File.join(backup_base, unwanted_backup))
      puts "- Deleted old backup: #{unwanted_backup}" 
    end
    puts "Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available"
  end
end
Displaying 1 Code