Capistrano: Dump and clone to local database

  • Download Gist
capistrano_db_dump_and_clone_to_local.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
# Directly copied from eycap-0.5.2 (thanks!)
#
# With these tasks you can:
# - dump your production database and save it in shared_path/db_backups
# - dump your production into your local database (clone_to_local)
#
# Tested and fixed by fjguzman
Capistrano::Configuration.instance(:must_exist).load do
 
namespace :db do
task :backup_name, :roles => :db, :only => { :primary => true } do
now = Time.now
run "mkdir -p #{shared_path}/db_backups"
backup_time = [now.year,now.month,now.day,now.hour,now.min,now.sec].join('-')
set :backup_file, "#{shared_path}/db_backups/#{environment_database}-snapshot-#{backup_time}.sql"
end
 
desc "Backup your MySQL or PostgreSQL database to shared_path+/db_backups"
task dump, :roles => :db, :only => {:primary => true} do
backup_name
run("cat #{shared_path}/config/database.yml") { |channel, stream, data| @environment_info = YAML.load(data)[rails_env] }
dbuser = @environment_info['username']
dbpass = @environment_info['password']
environment_database = @environment_info['database']
dbhost = @environment_info['host']
if @environment_info['adapter'] == 'mysql'
#dbhost = environment_dbhost.sub('-master', '') + '-replica' if dbhost != 'localhost' # added for Solo offering, which uses localhost
run "mysqldump --add-drop-table -u #{dbuser} -h #{dbhost} -p #{environment_database} | bzip2 -c > #{backup_file}.bz2" do |ch, stream, out |
ch.send_data "#{dbpass}\n" if out=~ /^Enter password:/
end
else
run "pg_dump -W -c -U #{dbuser} -h #{dbhost} #{environment_database} | bzip2 -c > #{backup_file}.bz2" do |ch, stream, out |
ch.send_data "#{dbpass}\n" if out=~ /^Password:/
end
end
end
 
desc "Sync your production database to your local workstation"
task :clone_to_local, :roles => :db, :only => {:primary => true} do
backup_name
dump
get "#{backup_file}.bz2", "/tmp/#{application}.sql.bz2"
development_info = YAML.load_file("config/database.yml")['development']
if development_info['adapter'] == 'mysql'
run_str = "bzcat /tmp/#{application}.sql.bz2 | mysql -u #{development_info['username']} --password='#{development_info['password']}' -h #{development_info['host']} #{development_info['database']}"
else
run_str = "PGPASSWORD=#{development_info['password']} bzcat /tmp/#{application}.sql.bz2 | psql -U #{development_info['username']} -h #{development_info['host']} #{development_info['database']}"
end
%x!#{run_str}!
end
 
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.