Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Database management for Heroku production apps. Backup locally and restore to either the local or production database.
namespace :msc do
namespace :db do
APP = 'fake-app-namer'
desc 'Backup the Postgres db'
task :backup => :environment do
`heroku pgbackups:capture --app #{APP}`
`curl -o #{backup_filename} \`heroku pgbackups:url --app #{APP}\``
end
namespace :restore do
desc 'Restore a db dump to the local database'
task :local => :environment do
database_name = 'msc_development'
database_filename = ENV['file'] || backup_filename
unless File.exist?(database_filename)
puts "You must specify the file to backup, eg 'file=<filename> rake msc:db:local_restore'"
return
end
puts "Restoring #{database_filename} to #{database_name} on localhost"
`pg_restore --verbose --clean --no-acl --no-owner -h localhost -U campbell -d #{database_name} #{database_filename}`
end
desc 'Restore a db dump to the production database'
task :heroku => :environment do
database_name = 'msc_production'
unless ENV['file']
puts "You must specify the S3 file location for the backup, eg 'file=<filename> rake msc:db:local_restore'"
return
end
puts "Restoring #{ENV['file']} to #{ENV['file']} on Heroku"
`heroku pgbackups:restore DATABASE '#{ENV['file']}'`
end
end
desc 'Sync the local DB with production'
task :sync => [:environment, :backup, 'restore:local']
end
end
def backup_filename
@filename ||= "pg_backups/app-name-#{ Time.now.strftime('%Y-%m-%d.%H-%M-%S') }.dump"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment