Skip to content

Instantly share code, notes, and snippets.

@stevebartholomew
Created January 21, 2009 20:52
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevebartholomew/50180 to your computer and use it in GitHub Desktop.
Save stevebartholomew/50180 to your computer and use it in GitHub Desktop.
Simple database backup rake task for Rails using mysqldump
namespace :backup do
desc "Backup database"
task :db do
RAILS_ENV = "development" if !defined?(RAILS_ENV)
app_root = File.join(File.dirname(__FILE__), "..", "..")
settings = YAML.load(File.read(File.join(app_root, "config", "database.yml")))[RAILS_ENV]
output_file = File.join(app_root, "..", "backup", "#{settings['database']}-#{Time.now.strftime('%Y%M%d')}.sql")
system("/usr/bin/env mysqldump -u #{settings['username']} -p#{settings['password']} #{settings['database']} > #{output_file}")
end
end
@jordanstephens
Copy link

i think you mean %m in your time format

Time.now.strftime('%Y%m%d')

@mathieujobin
Copy link

many people will need the host parameter as well

thanks for the rake task though

my updated version

# Simple database backup rake task using mysqldump
namespace :backup do
  desc "Backup database"
  task :db do
    RAILS_ENV = "development" if !defined?(RAILS_ENV)
    app_root = File.join(File.dirname(__FILE__), "..", "..")

    settings = YAML.load(File.read(File.join(app_root, "config", "database.yml")))[RAILS_ENV]
    output_file = File.join(app_root, "..", "backup", "#{settings['database']}-#{Time.now.strftime('%Y%m%d')}.sql")

    system("/usr/bin/env mysqldump -h #{settings['host']} -u #{settings['username']} -p#{settings['password']} #{settings['database']} > #{output_file}")
  end
end

@lostapathy
Copy link

lostapathy commented Nov 28, 2017

This can be simplified quite a bit, actually, to get the config from rails

namespace :backup do
  desc "backup database"
  task db: :environment do
    settings = Rails.configuration.database_configuration[Rails.env]
    output_file = Rails.root.join('backups', "#{settings['database']}-#{Time.now.strftime('%Y%m%d-%H:%M')}.sql")

    system("/usr/bin/env mysqldump -h #{settings['host']} -u #{settings['username']} -p#{settings['password']} #{settings['database']} > #{output_file}")
  end
end

@devraj-weinvest
Copy link

But there is Command Injection

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