Last active
August 29, 2015 13:57
-
-
Save pjaspers/9804017 to your computer and use it in GitHub Desktop.
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 "yaml" | |
require "pathname" | |
banner = <<BANNER | |
Looks for a config/database.yml file and supplies the command to get a | |
database dump/import. (mysql or postgres) | |
dumper <rails_env> | |
BANNER | |
abort banner if ARGV[0] == "-h" | |
def pg_dump(config, name) | |
"PGPASSWORD=#{config["password"]} pg_dump -Fc --no-acl --no-owner --clean -U #{config["username"]} -h #{config["host"]} #{config["database"]} > #{name}.dump" | |
end | |
def pg_restore(config, name) | |
"PGPASSWORD=#{config["password"]} pg_restore --verbose --clean --no-acl --no-owner -h #{config["host"]} -U #{config["username"]} -d #{config["database"]} #{name}.dump" | |
end | |
def mysql_dump(config, name) | |
password = "Password: #{config["password"]}" | |
command = "mysqldump -u #{config["username"]} -p -h #{config["localhost"]} #{config["database"]} > #{name}.sql" | |
[password, command].join("\n\n") | |
end | |
def mysql_restore(config, name) | |
password = "Password: #{config["password"]}" | |
command = "mysql -u #{config["username"]} -p -h #{config["localhost"]} #{config["database"]} < #{name}.sql" | |
[password, command].join("\n\n") | |
end | |
def green(s); "\e[32m#{s}\e[0m";end | |
rails_env = ARGV[0] || "development" | |
abort "No config/datase.yml in sight." unless File.exist?("config/database.yml") | |
config = YAML.load_file("config/database.yml")[rails_env] | |
dirname = Pathname.new(Dir.getwd).basename.to_s | |
name = "#{dirname}_#{rails_env[0..2]}_#{Time.now.strftime("%Y%m%d")}" | |
if config["adapter"] =~ /postgres/ | |
puts green("Dump:") | |
puts pg_dump(config, name) | |
puts "" | |
puts green("Restore:") | |
puts pg_restore(config, name) | |
elsif config["adapter"] =~ /mysql/ | |
puts green("Dump:") | |
puts mysql_dump(config, name) | |
puts "" | |
puts green("Restore:") | |
puts mysql_restore(config, name) | |
else | |
puts "I don't know how to dump a #{config["adapter"]}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment