Skip to content

Instantly share code, notes, and snippets.

@xuanxu
Created April 11, 2013 10:19
Show Gist options
  • Select an option

  • Save xuanxu/5362270 to your computer and use it in GitHub Desktop.

Select an option

Save xuanxu/5362270 to your computer and use it in GitHub Desktop.
Dump and download postgres production db
# Dump production postgres database and save it locally
Capistrano::Configuration.instance(:must_exist).load do
namespace :db do
desc "Backup the PostgreSQL database and download file to local"
task :localdump, :roles => :db, :only => {:primary => true} do
now = Time.now
backup_time = [now.year,now.month,now.day,now.hour,now.min,now.sec].join('-')
set :backup_file, "#{shared_path}/tmp/#{environment_database}-snapshot-#{backup_time}.sql"
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']
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
get "#{backup_file}.bz2", "/tmp/#{application}.sql.bz2"
# clone data to local db:
# development_info = YAML.load_file("config/database.yml")['development']
# cmd = "PGPASSWORD=#{development_info['password']} bzcat /tmp/#{application}.sql.bz2 | psql -U #{development_info['username']} -h #{development_info['host']} #{development_info['database']}"
# %x!#{cmd}!
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment