Clone the remote db from heroku into local for rails projects

Clone the remote db from heroku into local for rails projects

Well I’m using heroku.com for staging purposes for one of our Customer projects and I found really useful to clone from time to time the staging db especially when the bugs arise, if you want to do that I’m going to show how to do it using the command line tool or using a rake task you can use whichever you prefer:

Before to start with running commands make sure you have the heroku toolbelt installed:
https://github.com/heroku/toolbelt

Using the command line tool

Production
heroku pg:backups capture -a the-name-of-your-app

//download the latest dump file into local
curl -o latest.dump `heroku pg:backups public-url --app the-name-of-your-app`
// delete the previous data in your local db
rake db:drop:all
// just create the db without data
rake db:create
// restore the dump
pg_restore --verbose --clean --no-acl --no-owner -h localhost -U postgres -d your_db_name latest.dump
// just invoke the db:migrate
bundle exec rake db:migrate
// just invoke rake db:test:prepare
bundle exec rake db:test:prepare

And now using a rake task

namespace :db do
  desc "Clone the db from heroku remote"
  task :clone, :app, :expire do |t, args|
    Bundler.with_clean_env do
      puts args.inspect
      args.with_defaults(app: 'your-defaul-app-name', expire: false)

      puts "Running rake db:drop"
      Rake.application.invoke_task("db:drop")

      puts "Running rake db:create"
      Rake.application.invoke_task("db:create")

      puts "Creating pg backup of #{args.app}"
      if args[:expire] == 'expire'
        system "heroku pgbackups:capture --expire --app #{args.app}"
      end
      puts "Downloading pg backup of #{args.app}"
      system "curl -o latest_db.dump `heroku pgbackups:url --app #{args.app}`"

      puts "Restoring database from backup"
      system "pg_restore --verbose --clean --no-acl --no-owner -h localhost -U postgres -d your_db_name latest_db.dump"

      puts "Removing the dumpfile"
      system "rm latest_db.dump"

      puts "Running rake db:migrate"
      Rake.application.invoke_task("db:migrate")

      puts "Running rake db:test:prepare"
      Rake.application.invoke_task("db:test:prepare")
    end
  end
end

Clone the remote db using the rake task:

rake db:clone
// If you have production and stage and you want to specify which one you want to clone specify the app name for instance:
rake db:clone[my-app-name, expire]

That’s it just simple as that

H.

No Comments

Post A Comment