Skip to content

Instantly share code, notes, and snippets.

@tb
Forked from tbprojects/gist:5150521
Created March 13, 2013 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tb/5152656 to your computer and use it in GitHub Desktop.
Save tb/5152656 to your computer and use it in GitHub Desktop.
namespace :server_db do
task :get, :roles => :app do
puts "This task is designed to get database from the server"
puts "Example: cap ENV server_db:get"
timestamp = Time.new.strftime("%Y-%m-%d-%H%M%S")
tmp_dir = '~/tmp'
db_name = "viclarity_#{rails_env}"
db_dump = "#{db_name}_#{timestamp}"
db_dump_gz = "#{tmp_dir}/#{db_dump}.gz"
puts ">> Cleaning remote and local #{tmp_dir}"
run "mkdir -p #{tmp_dir} && rm -f #{tmp_dir}/#{db_name}*"
run_locally "mkdir -p #{tmp_dir} && rm -f #{tmp_dir}/#{db_name}*"
puts ">> Dumping and compressing database"
run "pg_dump -x -O #{db_name} | gzip > #{db_dump_gz}"
puts ">> Downloading database"
run_locally "scp #{user}@#{application}:#{db_dump_gz} #{db_dump_gz}"
puts ">> Decompressing database"
run_locally "gunzip #{db_dump_gz}"
puts ">> Importing database"
run_locally "rake db:drop db:create"
yaml_cfg = YAML.load(File.open("./config/database.yml"))["development"]
local_db_dump = yaml_cfg["database"]
local_db_user = yaml_cfg["username"]
run "rm #{db_dump_gz}"
run_locally "psql --user #{local_db_user} #{local_db_dump} < #{tmp_dir}/#{db_dump}"
end
# TODO:
# user object for: dump and tmp ~/tmp (create,clear)
# support for downloading a backup file instead of doing live dump
# abstract to "get_server_db" gem like github.com/sosedoff/capistrano-unicorn
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment