Skip to content

Instantly share code, notes, and snippets.

@bastienrobert
Forked from ssaunier/db.rake
Created April 21, 2020 12:34
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 bastienrobert/3be262da99d9117334e809cdd0082d80 to your computer and use it in GitHub Desktop.
Save bastienrobert/3be262da99d9117334e809cdd0082d80 to your computer and use it in GitHub Desktop.
Rake task to back up heroku database and restore it locally.
namespace :db do
desc "Backs up heroku database and restores it locally."
task import_from_heroku: [ :environment, :create ] do
HEROKU_APP_NAME = nil # Change this if app name is not picked up by `heroku` git remote.
c = Rails.configuration.database_configuration[Rails.env]
heroku_app_flag = HEROKU_APP_NAME ? " --app #{HEROKU_APP_NAME}" : nil
Bundler.with_clean_env do
puts "[1/4] Capturing backup on Heroku"
`heroku pg:backups capture DATABASE_URL#{heroku_app_flag}`
puts "[2/4] Downloading backup onto disk"
`curl -o tmp/latest.dump \`heroku pg:backups public-url #{heroku_app_flag} | cat\``
puts "[3/4] Mounting backup on local database"
`pg_restore --clean --verbose --no-acl --no-owner -h localhost -d #{c["database"]} tmp/latest.dump`
puts "[4/4] Removing local backup"
`rm tmp/latest.dump`
puts "Done."
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment