Skip to content

Instantly share code, notes, and snippets.

@miharekar
Last active December 30, 2015 21:49
Show Gist options
  • Save miharekar/7889758 to your computer and use it in GitHub Desktop.
Save miharekar/7889758 to your computer and use it in GitHub Desktop.
A simple thor script for imporing Heroku database into localhost. This is the original: http://antonzolotov.com/2012/03/04/rails-scripts-clone-heroku-database-to-development.html
#!/usr/bin/env ruby
module HerokuImport
class Db < Thor
method_option :keep, :type => :boolean, :default => false
method_option :remote, :type => :string, :default => "heroku"
method_option :host, :type => :string, :default => "localhost"
method_option :user, :type => :string, :default => `whoami`.strip
method_option :dbname, :type => :string
method_option :dump, :type => :string, :default => "latest.dump"
desc "clone", "clone a remote heroku database to the local environment"
def clone
Bundler.with_clean_env {
puts "Cloning production database to local environment. This might take a few minutes\n"
puts "(1/4) capturing production database snapshot..."
puts `heroku pgbackups:capture --expire --remote #{options[:remote]}`
puts "(2/4) downloading snapshot..."
puts `curl -o #{options[:dump]} \`heroku pgbackups:url --remote #{options[:remote]}\``
puts "(3/4) restoring snapshot..."
puts `pg_restore --verbose --clean --no-acl --no-owner -h #{options[:host]} -U #{options[:user]} -d #{options[:dbname] || dbname} #{options[:dump]}`
if options[:keep]
puts "(4/4) skipping cleaning..."
else
puts "(4/4) cleaning up..."
puts `rm #{options[:dump]}`
end
}
end
no_tasks do
def dbname
YAML.load_file('config/database.yml')["development"]["database"]
end
end
end
end
@miharekar
Copy link
Author

Usage: thor heroku_import:db:clone

To keep the dump file after importing it: thor heroku:db:clone --keep
To change the name of the remote: thor heroku:db:clone --remote staging
To change the name of the user: thor heroku:db:clone --user bob

You need Thor to run it: gem install thor

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