Skip to content

Instantly share code, notes, and snippets.

@Jamedjo
Forked from asciant/db.rake
Created June 5, 2015 16:12
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 Jamedjo/039fc172e78536b62999 to your computer and use it in GitHub Desktop.
Save Jamedjo/039fc172e78536b62999 to your computer and use it in GitHub Desktop.
# lib/tasks/db.rake
namespace :db do
desc "Dumps the database to db/APP_NAME.dump"
task :dump => :environment do
cmd = nil
epoch = Time.now.to_i
with_config do |app, host, db, user|
cmd = "pg_dump --verbose #{pg_login_config(host, user)} --clean --format=c #{db} > #{Rails.root}/db/#{app}-#{epoch}.dump"
end
puts cmd
exec cmd
end
desc "List database dumps in db/ directory"
task :list => :environment do
cmd = nil
cmd = "find #{Rails.root}/db -name \*.dump"
puts cmd
exec cmd
end
desc "Restores the database dump at db/APP_NAME-EPOCH.dump."
task :restore, [:epoch] => :environment do |task, args|
cmd = nil
with_config do |app, host, db, user|
cmd = "pg_restore --verbose #{pg_login_config(host, user)} --clean --dbname #{db} #{Rails.root}/db/#{app}-#{args.epoch}.dump"
end
Rake::Task["db:drop"].invoke
Rake::Task["db:create"].invoke
puts cmd
exec cmd
end
private
def with_config
app = Rails.application.class.parent_name.underscore
host = ActiveRecord::Base.connection_config[:host]
db = ActiveRecord::Base.connection_config[:database]
username = ActiveRecord::Base.connection_config[:username]
yield(app, host, db, username)
end
def pg_login_config(host, user)
hoststring = host ? " --host #{host}" : ""
userstring = user ? " --username #{user}" : ""
"#{hoststring}#{userstring} --no-owner --no-acl "
end
end
# dump the development db
rake db:dump
# dump the production db
RAILS_ENV=production rake db:dump
# List the database dumps
rake db:list
db/app-1414796108.dump
db/app-1414796244.dump
# Restore a specific database into development
rake db:restore:1414796244
# 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