Last Updated: February 25, 2016
·
630
· ttoni

Useful Rake task to restart database and import SQL dump

Very often, when testing new migrations on development env, I want the feeling of a fresh new reset in my DB plus the state of the most recent backup of the production database.

This is a rake task that accomplishes both those steps in an easy manner:

namespace :db do
  task reset_to_backup: :environment do
    Rake::Task['db:drop'].invoke
    Rake::Task['db:create'].invoke
    Rake::Task['db:migrate'].invoke
    Rake::Task['db:test:prepare'].invoke
    sh 'psql -h localhost -d appname_development -U pgusername -f ../backups/appname/appname_production.sql'
  end
end

Note: I place my backups out of the project's folder. Hence the ../backups/appname route

Now, simply by

$bundle exec rake db:reset_to_backup

we'll have a fresh new start of our development database.