Skip to content

Instantly share code, notes, and snippets.

@alexanderadam
Forked from hopsoft/db.rake
Last active October 19, 2016 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexanderadam/dcc3a28fca9e86cb7e84a3b1f050d5e8 to your computer and use it in GitHub Desktop.
Save alexanderadam/dcc3a28fca9e86cb7e84a3b1f050d5e8 to your computer and use it in GitHub Desktop.
Rails rake tasks for dump & restore of PostgreSQL databases
# 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, db, user|
cmd = "pg_dump #{pg_options(host, user)} --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, db, user|
cmd = "pg_restore --verbose #{pg_options(host, user)} --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 pg_options(host, user)
result = []
result << "--host #{host}" if host.present?
result << "--username #{user}" if user.present?
result.join(' ')
end
def with_config
yield Rails.application.class.parent_name.underscore,
ActiveRecord::Base.connection_config[:host],
ActiveRecord::Base.connection_config[:database],
ActiveRecord::Base.connection_config[:username]
end
end
# dump the development db
rake db:dump
# dump the production db
RAILS_ENV=production rake db:dump
# dump the production db & restore it to the development db
RAILS_ENV=production rake db:dump
rake db:restore
# note: config/database.yml is used for database configuration,
# but you will be prompted for the database user's password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment