Last active
January 31, 2017 13:02
-
-
Save vishalzambre/303eafbb2d9b6a6eb161e8bf724d2d13 to your computer and use it in GitHub Desktop.
Dumps the database to db/APP_NAME.dump using rake rake db:dump and to restore rake db:restore
This file contains hidden or 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
# lib/tasks/db.rake | |
namespace :db do | |
desc 'Dumps the database to db/APP_NAME.dump' | |
task dump: :environment do | |
cmd = nil | |
with_config do |app, host, port, db, user, password| | |
cmd = "PGPASSWORD='#{password}' pg_dump --host #{host} --username #{user} -p #{port} --verbose --clean --no-owner --no-acl --format=c #{db} > #{Rails.root}/db/#{app}.dump" | |
end | |
puts cmd | |
exec cmd | |
end | |
desc 'Restores the database dump at db/APP_NAME.dump.' | |
task restore: :environment do | |
cmd = nil | |
with_config do |app, host, port, db, user, password| | |
cmd = "PGPASSWORD='#{password}' pg_restore --verbose --host #{host} --username #{user} -p #{port} --clean --no-owner --no-acl --dbname #{db} #{Rails.root}/db/#{app}.dump" | |
end | |
Rake::Task["db:drop"].invoke | |
Rake::Task["db:create"].invoke | |
puts cmd | |
exec cmd | |
end | |
private | |
def with_config | |
yield Rails.application.class.parent_name.underscore, | |
ActiveRecord::Base.connection_config[:host], | |
ActiveRecord::Base.connection_config[:port], | |
ActiveRecord::Base.connection_config[:database], | |
ActiveRecord::Base.connection_config[:username], | |
ActiveRecord::Base.connection_config[:password] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment