#!/usr/bin/env bash stderr() { echo "$@" >&2 } fail() { stderr "$@" exit 1 } execd() { case "$@" in *SECRET*) ;; *) stderr "$@" esac "$@" } putd() { local __var="$1"; shift stderr "$__var=[${!__var}]" } check-exe() { local exe="$1"; shift local msg="$1"; shift type "$exe" >&2 || fail "$msg" } db-migrate() { check-exe migrate "install golang-migrate first:\nhttps://github.com/golang-migrate/migrate/tree/master/cmd/migrate" local crdb_url="${DYNA_URL/postgres:/cockroachdb:}" execd migrate -path=db/migrations -database="$crdb_url" "$@" } check-pwd() { # in docker, we have to be in /app if [[ -n "$IS_DOCKER" ]]; then [[ "$PWD" = /app ]] # outside of docker, we have to have a defaults.sh else [[ -s ./scripts/defaults.sh ]] fi } check-pwd || fail "please run scripts from the project root, with ./scripts/thing.sh" # load the dotenv files in export mode # loading defaults.sh later because it won't override previously-set variables, # and needs overrides set for derived vars. set -a [[ -s .env ]] && source ./.env [[ -s ./scripts/defaults.sh ]] && source ./scripts/defaults.sh set +a dbconsole() { init-dbconsole dbconsole "$@" } sql() { init-dbconsole sql "$@" } init-dbconsole() { [[ "$DB_CONSOLE_TYPE" = auto ]] && type cockroach >&2 && { export DB_CONSOLE_TYPE=cockroach cockroach-sql() { cockroach sql "$@" ;} } [[ "$DB_CONSOLE_TYPE" = auto ]] && type cockroach-sql >&2 && export DB_CONSOLE_TYPE=cockroach [[ "$DB_CONSOLE_TYPE" = auto ]] && type psql >&2 && export DB_CONSOLE_TYPE=psql case "$DB_CONSOLE_TYPE" in cockroach) dbconsole() { execd cockroach sql --url="${DYNA_URL}" "$@" } sql() { dbconsole --execute "$@" } ;; cockroach-sql) dbconsole() { execd cockroach-sql --url="${DYNA_URL}" "$@" } sql() { dbconsole --execute "$@" } ;; psql) dbconsole() { PGCLIENTENCODING='utf-8' execd psql "$DYNA_URL" } sql() { dbconsole --command "$@;" } ;; *) dbconsole() { fail 'you must install either cockroachdb or psql to use db scripts.' } sql() { dbconsole } ;; esac }