#!/usr/bin/env ruby # USAGE: # * db postgres://xxx # with connection url # * db (echo $DATABASE_URL) # with subshell # * db heroku # same as: db (heroku config:get DATABASE_URL) # * db heroku:production catalog # same as: db (heroku config:get CATALOG_DATABASE_URL -r production) # * db development # specific env from database.yml require "yaml" require "fileutils" require "uri" arg = ARGV.fetch(0, "development") def clean(hash) hash.reject do |key, val| val.nil? || val == '' end end def yml_to_config(config) clean \ type: config["adapter"]&.to_sym, database: config["database"], username: config["username"], password: config["password"], port: config["port"], host: config["host"] end def uri_to_config(uri) uri = URI(uri) clean \ type: uri.scheme.to_sym, database: uri.path[1..-1], username: uri.user, password: URI.unescape(uri.password.to_s), port: uri.port, host: uri.host end db = case arg.downcase when lambda { |a| a.start_with?("postgres://", "mysql2://") } uri_to_config(arg) when lambda { |a| a.start_with?("heroku") } remote = arg.split(":")[1] env_var = ARGV[1] ? "#{ARGV[1].upcase}_DATABASE_URL" : "DATABASE_URL" cmd = "heroku config:get #{env_var}" cmd += " -r #{remote}" if remote uri_to_config(`#{cmd}`.strip) else env = arg || "development" yml_to_config YAML.load_file(Dir.pwd + '/config/database.yml')[env] end cmd = [] case db[:type] when :postgres, :postgresql then cmd<< %{env PGPASSWORD="#{db[:password]}"} if db[:password] cmd<< "psql" cmd<< "-d#{db[:database]}" cmd<< "-U#{db[:username]}" if db[:username] cmd<< "-h#{db[:host]}" if db[:host] cmd<< "-p#{db[:port]}" if db[:port] when :mysql2 then cmd<< "mysql" cmd<< "-h #{db[:host]}" if db[:host] cmd<< "-P #{db[:port]}" if db[:port] cmd<< "-u #{db[:username]}" if db[:username] cmd<< "-p#{db[:password]}" if db[:password] cmd<< " #{db[:database]}" end $stdout << cmd.join(" ")