Created
June 7, 2010 09:49
-
-
Save davidchua/428480 to your computer and use it in GitHub Desktop.
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
namespace :db do | |
desc "Backup database to #{RAILS_ROOT}/db/backup" | |
task :backup => :environment do | |
max_backups = (ENV["MAX"] || 14).to_i | |
timestamp = Time.now.strftime("%Y%m%d_%H%M%S") | |
backup_folder = File.join("db", "backup") | |
backup_file = File.join(backup_folder, "#{RAILS_ENV}_dump_#{timestamp}.sql.gz") | |
FileUtils.makedirs(backup_folder) | |
db_config = ActiveRecord::Base.configurations[RAILS_ENV] | |
command = "mysqldump -u #{db_config['username']} -p#{db_config['password']} --default-character-set=utf8 --single-transaction --quick #{db_config['database']} | gzip -c > #{backup_file}" | |
command = command.sub(/mysqldump/, "mysqldump -h #{db_config['host']}") unless db_config['host'].nil? | |
sh command | |
puts "+ Created backup: #{backup_file}" | |
dir = Dir.new(backup_folder) | |
all_backups = dir.entries.select {|e| e.to_s =~ /#{RAILS_ENV}/}.sort.reverse | |
unwanted_backups = all_backups[max_backups..-1] || [] | |
unwanted_backups.each do |unwanted_backup| | |
FileUtils.rm_rf(File.join(backup_folder, unwanted_backup)) | |
puts "- Deleted backup: #{unwanted_backup}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment