Skip to content

Instantly share code, notes, and snippets.

@TheKidCoder
Created April 24, 2014 16:25
Show Gist options
  • Save TheKidCoder/11260623 to your computer and use it in GitHub Desktop.
Save TheKidCoder/11260623 to your computer and use it in GitHub Desktop.
Rake task to make binary backups/restores using pg_dump/pg_restore. Mainly used for breaking data changes in dev.
namespace :db do
namespace :binary do
desc "Dump current database to db/dumps"
task :dump => :environment do
#Get current info for git.
current_git_branch = `git rev-parse --abbrev-ref HEAD`.strip.gsub('/', '_')
current_git_hash = `git rev-parse HEAD`.strip
#Load DB config.
db_config = Rails.application.config.database_configuration[Rails.env]
#Create file path
file_name = File.join(Rails.root, "db", "dumps", "db_#{db_config['database']}_#{current_git_branch}_#{current_git_hash}.dump")
#Dump DB. This currently doesn't use any username/password info. This can be added using the db_config hash.
`pg_dump -x -Fc -f #{Shellwords.escape(file_name)} #{db_config['database']}`
raise 'Error dumping database' if $?.exitstatus == 1
puts "Dump saved to #{file_name}"
end
desc "Restore the last dump from db/dumps"
task :restore => :environment do
#Get the last dump created.
dump_dir = File.join(Rails.root, "db", "dumps")
last_dump_path = Dir.glob(File.join(dump_dir, '*.dump')).max { |a,b| File.ctime(a) <=> File.ctime(b) }
#Load db config
db_config = Rails.application.config.database_configuration[Rails.env]
# Prompt to make really sure we want to restore from dump
puts "\n\e[0;31m ######################################################################"
puts " #\n # Are you REALLY sure you want to restore db?"
puts " #\n # Last Dump: #{last_dump_path.split('/').last}"
puts " #\n # Enter y/N + enter to continue\n #"
puts " ######################################################################\e[0m\n"
proceed = STDIN.gets[0..0] rescue nil
exit unless proceed == 'y' || proceed == 'Y'
# ActiveRecord::Tasks::DatabaseTasks.drop_current
# ActiveRecord::Tasks::DatabaseTasks.create_current
`dropdb #{db_config['database']}`
`createdb #{db_config['database']}`
`pg_restore -d #{db_config['database']} #{Shellwords.escape(last_dump_path)}`
raise 'Error restoring database' if $?.exitstatus == 1
puts "Database Restored"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment