Skip to content

Instantly share code, notes, and snippets.

@torkale
Created October 3, 2011 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torkale/1258918 to your computer and use it in GitHub Desktop.
Save torkale/1258918 to your computer and use it in GitHub Desktop.
Sygen version of mysql backup using rake
require 'find'
namespace :db do
desc "Backup the database to a file. Options: DIR=base_dir RAILS_ENV=production MAX=7 SKIP_DEV=true"
task :backup => [:environment] do
skip = ENV["SKIP_DEV"] || ""
unless(RAILS_ENV == "development" && skip == "")
base_path = ENV["DIR"] || Dir.home
backup_base = File.join(base_path, 'backup')
backup_file = create_folder_and_get_file_name backup_base
sh dump_command backup_file # run the command
dir = Dir.new(backup_base)
all_backups = dir.entries.select{|entry| entry.match(/\d+-\d+-\d+_\d+-\d+-\d+/)}.sort.reverse
deleted_backups = delete_unwanted(all_backups, backup_base)
print_remaining(all_backups - deleted_backups, backup_base)
end
end
def create_folder_and_get_file_name(backup_base)
datestamp = Time.now.strftime("%Y-%m-%d_%H-%M-%S")
backup_folder = File.join(backup_base, datestamp)
FileUtils.mkdir_p(backup_folder)
File.join(backup_folder, "#{RAILS_ENV}_dump.sql.gz")
end
def dump_command(backup_file)
pass = try_config_entry("password", "-p")
port = try_config_entry("port", "-P ")
host = try_config_entry("host", "-h ")
puts "Creating backup: #{backup_file}"
"mysqldump#{port}#{host} -u #{db_config["username"]}#{pass} --database #{db_config["database"]} -Q --add-drop-table | gzip -c > #{backup_file}"
end
def delete_unwanted(all_backups, backup_base)
max_backups = (ENV["MAX"] || 7).to_i
puts "Keeping #{max_backups} backup files"
unwanted_backups = all_backups[max_backups..-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"
unwanted_backups
end
def print_remaining(remaining_backups, dir)
puts "Remaining backup files on #{dir}"
remaining_backups.each do |backup|
puts "\t#{backup}"
end
end
def db_config
ActiveRecord::Base.configurations[RAILS_ENV]
end
def try_config_entry(name, arg)
db_config[name] ? " #{arg}#{db_config[name]}" : ""
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment