Skip to content

Instantly share code, notes, and snippets.

@dmichael
Created July 8, 2009 16:36
Show Gist options
  • Select an option

  • Save dmichael/142950 to your computer and use it in GitHub Desktop.

Select an option

Save dmichael/142950 to your computer and use it in GitHub Desktop.
# http://blog.craigambrose.com/articles/2007/03/01/a-rake-task-for-database-backups
# http://edge.matrixprojects.com/2008/5/21/backing-up-your-rails-mysql-db-via-a-rake-task
require 'find'
namespace :db do desc "Backup the database to a file. Options: DIR=base_dir RAILS_ENV=production MAX=20"
task :backup => [:environment] do
datestamp = Time.now.strftime("%Y-%m-%d_%H-%M-%S")
base_path = ENV["DIR"] || "db"
backup_base = File.join(base_path, 'backup')
backup_folder = File.join(backup_base, datestamp)
backup_file = File.join(backup_folder, "#{RAILS_ENV}_dump.sql.gz")
db_config = ActiveRecord::Base.configurations[RAILS_ENV]
FileUtils.mkdir_p(backup_folder)
sh "mysqldump -u #{db_config['username'].to_s} #{'-p' if db_config['password']}#{db_config['password'].to_s} --opt #{db_config['database']} | gzip -c > #{backup_file}"
puts "Created backup: #{backup_file}"
max_backups = ENV["MAX"] || 20
all_backups = (Dir.entries(backup_base) - ['.', '..']).sort.reverse
unwanted_backups = all_backups[max_backups.to_i..-1] || []
for unwanted_backup in unwanted_backups
FileUtils.rm_rf(File.join(backup_base, unwanted_backup))
puts "deleted #{unwanted_backup}"
end
puts "Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment