Skip to content

Instantly share code, notes, and snippets.

@dfl
Created April 12, 2011 04:34
Show Gist options
  • Save dfl/914932 to your computer and use it in GitHub Desktop.
Save dfl/914932 to your computer and use it in GitHub Desktop.
rails rake tasks for dumping and reloading mysql databases
# mysql db backup and restore for rails
# by David Lowenfels <[email protected]> 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
@a7medfahmy94
Copy link

a7medfahmy94 commented Dec 21, 2016

I had to change RAILS_ROOT & RAILS_ENV to Rails.root & Rails.env respectively.
the directory from which you do the backup is called 'dump' not 'backup'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment