Skip to content

Instantly share code, notes, and snippets.

@owainlewis
Created January 4, 2014 18:04
Show Gist options
  • Save owainlewis/8258286 to your computer and use it in GitHub Desktop.
Save owainlewis/8258286 to your computer and use it in GitHub Desktop.
Backup task for Postgres
namespace :postgres do
desc 'Backup postgres database'
task :backup => :environment do
db_config = Rails.application.config.database_configuration[Rails.env]
backup_dir = '/home/deploy/backups'
outfile = "#{ backup_dir }/#{ Rails.env }_#{ DateTime.now.strftime("%Y%m%d_%H%M%S.sql.gz") }"
cmd = "pg_dump -h localhost -U #{ db_config['username'] } #{ db_config['database'] } | gzip -c > #{outfile}"
puts "Making database backup..."
system cmd
end
desc 'Restore postgres from an existing backup'
task :restore, [:backup] => [:environment] do |t, args|
db_config = Rails.application.config.database_configuration[Rails.env]
cmd = "psql -h localhost -U #{ db_config['username'] } #{ db_config['database'] } < #{ args[:backup] }"
puts cmd
end
end
@owainlewis
Copy link
Author

rake postgres:backup
# Making database backup ~/backups/development_20140104_180658.sql.gz
rake 'postgres:restore[~/backups/development_20140104_180658.sql.gz]'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment