Skip to content

Instantly share code, notes, and snippets.

@assembler
Created March 14, 2017 11:46
Show Gist options
  • Select an option

  • Save assembler/70bbddf8ac62170d45c485c0e55e08ff to your computer and use it in GitHub Desktop.

Select an option

Save assembler/70bbddf8ac62170d45c485c0e55e08ff to your computer and use it in GitHub Desktop.

Revisions

  1. assembler created this gist Mar 14, 2017.
    5 changes: 5 additions & 0 deletions db
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    #!/bin/bash

    OUTPUT="$(db.rb $1 $2)"
    echo "${OUTPUT}"
    eval "${OUTPUT}"
    75 changes: 75 additions & 0 deletions db.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,75 @@
    #!/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(" ")