Created
April 3, 2017 21:27
-
-
Save rzane/5f3e295704b61badad8f1f3de4456b7f to your computer and use it in GitHub Desktop.
Transfer everything from one postgres instance to another
This file contains 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
#!/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