Skip to content

Instantly share code, notes, and snippets.

@ssaunier
Forked from abstractcoder/import.rake
Last active January 8, 2021 11:46
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ssaunier/8c88cbdce09d47581975 to your computer and use it in GitHub Desktop.
Save ssaunier/8c88cbdce09d47581975 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
@ssaunier
Copy link
Author

Copy this file in you rails app to the lib/tasks repository. Make sure you have the heroku PG Backups add-on in place on your app. Then you can run:

$ rake db:import_from_heroku

This will remove all your local data and replace it with the production data on your local database.

@augnustin
Copy link

👍

@jmsevold
Copy link

jmsevold commented Mar 9, 2015

On the project I am working on, we have both our development and production database on Heroku. When I ran this task, it pulled down the development database dump. Is there anyway I could specify the production database within this task?

@ssaunier
Copy link
Author

@jmsevold: you can add --app YOUR_PRODUCTION_APP to line 7 (heroku pg:backups capture) of the script to specify which database app you want to dump.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment