Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjelline/82ea37bfbde66532ed2089da9ba42ea8 to your computer and use it in GitHub Desktop.
Save bjelline/82ea37bfbde66532ed2089da9ba42ea8 to your computer and use it in GitHub Desktop.
Capistrano: Dump and clone to local database
# 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
# migrated to capistrano 3 by bjelline
namespace :db do
task :backup_name do
on roles(:db), primary: true do
execute "mkdir -p #{shared_path}/db_backups"
backup_time = Time.now.strftime('%Y-%m-%d--%H-%M-%S')
set :backup_file, "#{shared_path}/db_backups/#{backup_time}-dump.sql"
end
end
desc 'Backup your MySQL or PostgreSQL database to shared_path+/db_backups'
task :dump do
on roles(:db), primary: true do
invoke 'db:backup_name'
rails_env = fetch(:stage).to_s
data = capture("cat #{shared_path}/config/database.yml")
environment_info = YAML.safe_load(data)[rails_env]
dbuser = environment_info['username']
dbpass = environment_info['password']
environment_database = environment_info['database']
adapter = environment_info['adapter']
dbhost = environment_info['host']
pipe = "| bzip2 -c > #{fetch(:backup_file)}.bz2"
if adapter == 'mysql2'
cmd = "mysqldump --add-drop-table -u #{dbuser} -h #{dbhost} -p #{environment_database} #{pipe}"
execute(cmd, interaction_handler: { /Enter password/ => "#{dbpass}\n" })
elsif adapter == 'pg'
cmd = "pg_dump -W -c -U #{dbuser} -h #{dbhost} #{environment_database} #{pipe}"
execute(cmd, interaction_handler: { /Password/ => "#{dbpass}\n" })
else
execute "echo \"I don't know how to dump your database adapter=#{adapter}\""
end
end
end
desc 'Sync your production database to your local workstation'
task :clone_to_local do
on roles(:db), primary: true do
invoke 'db:dump'
remote_file = fetch(:backup_file)
filename = Pathname.new(remote_file).basename
execute "echo \"Will download #{remote_file}.bz2 to #{filename}.bz2\""
download! "#{remote_file}.bz2", "/tmp/#{filename}.bz2"
info = YAML.load_file('config/database.yml')['development']
pipe = "bzcat /tmp/#{filename}.bz2 | "
if info['adapter'] == 'mysql2'
cmd = "#{pipe} mysql -u #{info['username']} -h #{info['host']} #{info['database']}"
run_locally do
execute(cmd, interaction_handler: { /Enter password/ => "#{info['password']}\n" })
end
elsif adapter == 'pg'
cmd = "#{pipe} psql -U #{info['username']} -h #{info['host']} #{info['database']}"
run_locally do
execute(cmd, interaction_handler: { /Password/ => "#{info['password']}\n" })
end
else
execute "echo \"I don't know how to load dump for database adapter=#{adapter}\""
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment