Skip to content

Instantly share code, notes, and snippets.

@abstractcoder
Last active December 18, 2016 12:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save abstractcoder/5886291 to your computer and use it in GitHub Desktop.
Save abstractcoder/5886291 to your computer and use it in GitHub Desktop.
Rails Rake task for restoring your latest Heroku database locally. Add this to a new or existing .rake file under lib/tasks and run it from command line using rake db:restore
namespace :db do
desc "Restore latest Heroku db backup locally"
task restore: :environment do
# Get the current db config
config = Rails.configuration.database_configuration[Rails.env]
# Get around an issue with the Heroku Toolbelt https://github.com/sstephenson/rbenv/issues/400#issuecomment-18742700
Bundler.with_clean_env do
# Download the latest backup to a file called latest.dump in tmp folder
`curl -o tmp/latest.dump \`heroku pg:backups public-url -q --remote production\``
# Restore the backup to the current database
`export PGPASSWORD=#{config["password"]} && pg_restore --verbose --clean --no-acl --no-owner --host=#{config["host"]} --port=#{config["port"]} --username=#{config["username"]} --dbname=#{config["database"]} tmp/latest.dump`
end
end
end
@abstractcoder
Copy link
Author

Remove --remote production if your app doesn't have multiple Heroku environments, or change production to whatever your git remote is named.

@humancopy
Copy link

humancopy commented Dec 18, 2016

You could actually use heroku:pull to insert it directly into the local database. Something like this:

namespace :db do
  task :pull, [:app, :database_url, :local_db, :drop_db] => :environment do |t, args|
    # Get the current db config
    config = Rails.configuration.database_configuration[Rails.env]
    # Set default options
    args.with_defaults(app: 'DEFAULT_APP_NAME', database_url: 'DATABASE_URL', local_db: config['database'], drop_db: true)

    # Drop DB
    Rake::Task['db:drop'].invoke if args[:drop_db]

    # Pull from Heroku
    Bundler.with_clean_env { `heroku pg:pull #{args[:database_url]} #{args[:local_db]} -a #{args[:app]}` }
  end
end

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