Skip to content

Instantly share code, notes, and snippets.

@ksinkar
Created October 17, 2012 08:56
Show Gist options
  • Save ksinkar/3904573 to your computer and use it in GitHub Desktop.
Save ksinkar/3904573 to your computer and use it in GitHub Desktop.
This rake task is used for downloading the Postgres databackup of a Heroku app. The Heroku db:pull doesn't seem to be working due to some taps gem versioning problem. Also this rake task works faster for restoring your databases from the Heroku pgbackups
######################################################################################
##### Copyright(C) Koustubh Sinkar <[email protected]> #####
##### #####
##### This program is free software: you can redistribute it and/or modify #####
##### it under the terms of the GNU Lesser General Public License as #####
##### published by the Free Software Foundation, either version 2 of the #####
##### License, or (at your option) any later version. #####
##### #####
##### This program is distributed in the hope that it will be useful, #####
##### but WITHOUT ANY WARRANTY; without even the implied warranty of #####
##### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #####
##### GNU Lesser General Public License for more details. #####
##### #####
##### You should have received a copy of the GNU Lesser GPL #####
##### along with this program. If not, see <http://www.gnu.org/licenses/>. #####
##### #####
######################################################################################
require 'yaml'
namespace :heroku do
def environment
if Rails.respond_to?(:env)
Rails.env
else
ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
end
end
def config
@config ||= begin
cfg = begin
cfg = YAML.load(ERB.new(IO.read("config/database.yml")).result)
rescue SyntaxError, StandardError
require APP_PATH
Rails.application.config.database_configuration
end
unless cfg[environment]
abort "No database is configured for the environment '#{environment}'"
end
cfg[environment]
end
end
def run(command)
puts %x{#{command}}
throw "PLEASE FIX #{command}" if $?.exitstatus != 0
end
namespace :pgbackups do
desc "Download the pgbackups dump from heroku and restore it locally"
task :pull, :app do |t, args|
heroku_app = args[:app]
if config["adapter"] == 'postgresql'
begin
run("curl -o latest.dump `/usr/bin/heroku pgbackups:url --app #{heroku_app}`")
ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
ENV['PGPASSWORD'] = config["password"].to_s if config["password"]
system("pg_restore --verbose --clean --no-acl --no-owner -h #{config['host']} -U #{config['username']} -d #{config['database']} latest.dump")
run("rm latest.dump")
rescue Exception => msg
puts msg
end
else
puts 'ONLY WORKS WITH POSTGRESQL DATABASES'
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment