-
-
Save Azzawie/12613976f4152de26f448b95eefd0587 to your computer and use it in GitHub Desktop.
rails rake tasks for dumping and reloading mysql databases
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
# mysql db backup and restore for rails | |
# by David Lowenfels <david@internautdesign.com> 4/2011 | |
require 'yaml' | |
namespace :db do | |
def backup_prep | |
@directory = File.join(RAILS_ROOT, 'db', 'backup') | |
@db = YAML::load( File.open( File.join(RAILS_ROOT, 'config', 'database.yml') ) )[ RAILS_ENV ] | |
@db_params = "-u #{@db['username']} #{@db['database']}" | |
@db_params = "-p#{@db['password']} #{@db_params}" unless @db['password'].blank? | |
end | |
desc 'Backup database by mysqldump' | |
task :backup => :environment do | |
backup_prep | |
FileUtils.mkdir @directory unless File.exists?(@directory) | |
file = File.join( @directory, "#{RAILS_ENV}_#{DateTime.now.to_s}.sql" ) | |
command = "mysqldump #{@db_params} | gzip > #{file}.gz" #--opt --skip-add-locks | |
puts "dumping to #{file}..." | |
# p command | |
exec command | |
end | |
desc "restore most recent mysqldump (from db/backup/*.sql.*) into the current environment's database." | |
task :restore => :environment do | |
unless RAILS_ENV=='development' | |
puts "Are you sure you want to import into #{RAILS_ENV}?! [y/N]" | |
return unless STDIN.gets =~ /^y/i | |
end | |
backup_prep | |
wildcard = File.join( @directory, ENV['FILE'] || "#{ENV['FROM']}*.sql*" ) | |
puts file = `ls -t #{wildcard} | head -1`.chomp # default to file, or most recent ENV['FROM'] or just plain most recent | |
if file =~ /\.gz(ip)?$/ | |
command = "gunzip < #{file} | mysql #{@db_params}" | |
else | |
command = "mysql #{@db_params} < #{file}" | |
end | |
p command | |
puts "please wait, this may take a minute or two..." | |
exec command | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment