Last active
December 18, 2016 12:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Remove
--remote production
if your app doesn't have multiple Heroku environments, or change production to whatever your git remote is named.