Last active
December 31, 2015 12:39
-
-
Save letsspeak/7988055 to your computer and use it in GitHub Desktop.
Ruby on Rails mysql backup rake task
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
# encoding: utf-8 | |
namespace :mysql do | |
desc 'backup mysql database' | |
task :backup => :environment do | |
filename = "#{Rails.root}/config/database.yml" | |
config = YAML::load(File.open(filename))[Rails.env] | |
if config.nil? | |
p "database config file (#{filename}) has no environment setting for #{Rails.env}" | |
return | |
end | |
if config["adapter"] != "mysql2" | |
p "database setting for #{Rails.env} is not mysql2" | |
return | |
end | |
database = config["database"] | |
host = config["host"] || "localhost" | |
username = config["username"] | |
password = config["password"] | |
outdir = config["backupdir"] || "#{Rails.root}/tmp" | |
outfile = "#{outdir}/#{Rails.env}_#{DateTime.now.strftime("%Y%m%d_%H%M%S.sql")}" | |
if username.nil? | |
p "database setting for #{Rails.env} has no username" | |
return | |
end | |
if password.nil? | |
p "database setting for #{Rails.env} has no password" | |
return | |
end | |
begin | |
Dir::mkdir(outdir) unless File.exists?(outdir) | |
rescue | |
p "makedir #{outdir} failed" | |
return | |
end | |
"created: #{outdir}" | |
command = "mysqldump --default-character-set=binary #{database} --host=#{host} --user=#{username} --password=#{password} > #{outfile}" | |
begin | |
exec command | |
rescue | |
p "execute command failed: #{command}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment