Skip to content

Instantly share code, notes, and snippets.

@reneweteling
Created August 12, 2015 07:58
Show Gist options
  • Save reneweteling/195091c36a0bcb367e58 to your computer and use it in GitHub Desktop.
Save reneweteling/195091c36a0bcb367e58 to your computer and use it in GitHub Desktop.
Heroku rake task to import your remote database locally
namespace :heroku do
task :import_remote_database => :environment do
return 'Only in development' unless Rails.env.development?
puts "From what heroku app do you want to import the database?"
remote = STDIN.gets.chomp
puts "Creating dump on heroku, takes a while"
heroku_command('pg:backups capture', remote)
# check to see if its done
while !heroku_command('pg:backups info', remote).include? "pg_dump done" do
puts "Not done yet, just a moment"
sleep 1
end
# get the db
db_dump_url = URI.parse(heroku_command('pg:backups public-url', remote)).to_s
db_dump_filename = Rails.root.join('latest.dump')
`curl -o #{db_dump_filename} '#{db_dump_url}'`
# restore the db
%w(pg:disconnect db:drop db:create)
config = Rails.configuration.database_configuration[Rails.env]
pg_restore = "pg_restore --verbose --clean --no-acl --no-owner -h #{config['host']} -d #{config['database']} #{db_dump_filename}"
pg_restore << " -U #{config['user']}" if config['user']
`#{pg_restore}`
# remove the dump
`rm #{db_dump_filename}`
end
private
def heroku_command(command, remote)
command("heroku #{command} --app #{app}")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment