Skip to content

Instantly share code, notes, and snippets.

@rzane
Created April 3, 2017 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rzane/5f3e295704b61badad8f1f3de4456b7f to your computer and use it in GitHub Desktop.
Save rzane/5f3e295704b61badad8f1f3de4456b7f to your computer and use it in GitHub Desktop.
Transfer everything from one postgres instance to another
#!/usr/bin/env ruby
require 'uri'
require 'delegate'
class PG < SimpleDelegator
FLAGS = ['--verbose', '--clean', '--no-owner', '--no-acl', '-j', '4']
def initialize(url)
super URI.parse(url)
end
def db
path[1..-1]
end
def port
super.to_s if super
end
def to_env
{
'PGHOST' => host,
'PGPORT' => port,
'PGUSER' => user,
'PGPASSWORD' => password
}
end
def dump(to:)
run 'pg_dump', '-Fd', db, *FLAGS, '-f', to
end
def restore(from:)
run 'pg_restore', '--create', *FLAGS, '-d', db, from
end
def run(*args)
opts = args.last.respond_to?(:keys) ? args.pop : {}
unless system(to_env, *args, opts)
abort "Command failed: #{args.join(' ')}"
end
end
end
if ARGV.length != 2
example = 'postgres://user:pass@host:port/db'
abort "Usage: #{$0} #{example} #{example}"
end
source, destination = ARGV.map { |v| PG.new(v) }
source.dump(to: 'dump')
destination.restore(from: 'dump')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment