-
-
Save aguynamedloren/05bd0b403b1ba992d313f352a0fb65ce to your computer and use it in GitHub Desktop.
Rails rake tasks for dump & restore of PostgreSQL databases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| namespace :db do | |
| desc "Dumps the database to db/backups/env-time.dump" | |
| task :dump => :environment do | |
| cmd = nil | |
| filename = "#{Rails.env}-#{Time.now.to_i}.dump" | |
| with_config do |host, db, user| | |
| cmd = "pg_dump --host #{host} --username #{user} --verbose --clean \ | |
| --no-owner --no-acl --format=c #{db} > \ | |
| #{Rails.root}/db/backups/#{filename}" | |
| end | |
| puts ">> Creating database backup #{filename}" | |
| exec cmd | |
| end | |
| desc "Restores the most recent database dump" | |
| task :restore => :environment do | |
| cmd = nil | |
| filename = `ls -t #{Rails.root}/db/backups | head -1`.strip | |
| with_config do |host, db, user| | |
| cmd = "pg_restore --verbose --host #{host} --username #{user} --clean \ | |
| --no-owner --no-acl --dbname #{db} #{Rails.root}/db/backups/#{filename}" | |
| end | |
| puts ">> Restoring database from #{filename}" | |
| Rake::Task["db:drop"].invoke | |
| Rake::Task["db:create"].invoke | |
| exec cmd | |
| end | |
| private | |
| def with_config | |
| yield ActiveRecord::Base.connection_config[:host], | |
| ActiveRecord::Base.connection_config[:database], | |
| ActiveRecord::Base.connection_config[:username] | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # dump the development db | |
| rake db:dump | |
| # dump the production db | |
| RAILS_ENV=production rake db:dump | |
| # dump the production db & restore it to the development db | |
| RAILS_ENV=production rake db:dump | |
| rake db:restore | |
| # note: config/database.yml is used for database configuration, | |
| # but you will be prompted for the database user's password |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment