Rake task to import a production DB dump
Every now and then I need to write a script (rake task) to import a production database dump.
This is code I usually use:
ruby
require 'yaml'
namespace :db do
desc 'Downloads and imports a production DB dump'
task :import_production_dump do
puts '➙ Generating production DB dump...'
execute_on_server %(
PGPASSWORD="`cat /var/www/project/current/config/database.yml | \
grep password | awk '{ print $2 }'`" \
pg_dump database_name -h custom_url.rds.amazonaws.com -U user_name \
--column-inserts --no-owner --no-privileges > backup.sql
)
puts '➙ Downloading production DB dump...'
system "scp #{server_user_and_host}:#{backup_file_name} ."
puts '➙ Deleting production DB dump...'
execute_on_server "rm #{backup_file_name}"
puts '➙ Cleaning your local DB...'
%w[drop create].each { |task| Rake::Task["db:#{task}"].invoke }
puts '➙ Importing production DB dump...'
system "bin/rails db development < #{backup_file_name} > /dev/null"
puts '➙ Removing local dump...'
system "rm #{backup_file_name}"
puts '➙ Done!'
end
def execute_on_server(commands)
system %(ssh -T #{server_user_and_host} << 'SSH'
#{commands}
SSH).split("\n").map(&:strip).join("\n")
end
def server_user_and_host
'[email protected]'
end
def backup_file_name
'backup.sql'
end
end
Let me know in the comments if you have a better solution! Perhaps a small gem? :)