Skip to content

Instantly share code, notes, and snippets.

@Lockyy
Last active June 6, 2023 16:22
Show Gist options
  • Save Lockyy/70fd87b6580b90f2438b64f8899e11b0 to your computer and use it in GitHub Desktop.
Save Lockyy/70fd87b6580b90f2438b64f8899e11b0 to your computer and use it in GitHub Desktop.
namespace :db do
desc 'Dumps the database to db/backups'
task :dump, [:backup_name] => :environment do |_task, args|
params = gather_required_data(args)
cmd = [
'pg_dump',
'-F c',
'-v',
'-h', params[:host],
'-d', params[:database],
'-f',
Rails.root.join('db', 'backups', "#{params[:backup_name]}_#{params[:database]}.psql")
].join(' ')
puts cmd
exec cmd
end
desc 'Restores the database from db/backups'
task :restore, [:backup_name] => :environment do |_task, args|
params = gather_required_data(args)
cmd = [
'pg_restore',
'-F c',
'-v',
'-h', params[:host],
'-d', params[:database],
Rails.root.join('db', 'backups', "#{params[:backup_name]}_#{params[:database]}.psql")
].join(' ')
Rake::Task['db:drop'].invoke
Rake::Task['db:create'].invoke
puts cmd
exec cmd
end
private
def gather_required_data(args)
with_config do |_app, host, database, _user|
{
backup_name: args.backup_name,
host: host,
database: database
}.tap do |params|
return params if params.values.reject(&:blank?).count == 3
end
end
raise 'Missing required information. You need to pass in a backup name and your database.yml needs a host and a database name for this environment.'
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment