Skip to content

Instantly share code, notes, and snippets.

@bradurani
Last active September 5, 2017 04:37
Show Gist options
  • Save bradurani/255245c99cb9009b757e4bc65a50c8df to your computer and use it in GitHub Desktop.
Save bradurani/255245c99cb9009b757e4bc65a50c8df to your computer and use it in GitHub Desktop.
DB management script
#! /usr/bin/env bash
CMD="${1?valid commands are psql, seed, create, drop, reset}"
set -eux pipefail
export $(sed '/^#/ d' .env)
HOST="${DB_HOST-localhost}"
USERNAME="${DB_USERNAME-postgres}"
PASSWORD="${DB_PASSWORD-postgres}"
PORT="${DB_PORT-5432}"
S_ENV="${PROJECT_ENV-development}"
if [ -z "${DB_DATABASE+x}" ]; then
DATABASE="project_$S_ENV"
else
DATABASE="$DB_DATABASE"
fi
if [[ "$CMD" == "psql" ]]; then
PGPASSWORD="$PASSWORD" psql -h "$HOST" -U "$USERNAME" -p "$PORT" "$DATABASE"
elif [[ "$CMD" == "seed" ]]; then
PGPASSWORD="$PASSWORD" psql -h "$HOST" -U "$USERNAME" -p "$PORT" -d "$DATABASE" -f schema/seed.sql
elif [[ "$CMD" == "create" ]]; then
PGPASSWORD="$PASSWORD" psql -h "$HOST" -U "$USERNAME" -p "$PORT" -c "CREATE DATABASE $DATABASE;"
PGPASSWORD="$PASSWORD" psql -h "$HOST" -U "$USERNAME" -p "$PORT" -d "$DATABASE" -f schema/create.sql
elif [[ "$CMD" == "drop" ]]; then
PGPASSWORD="$PASSWORD" psql -h "$HOST" -U "$USERNAME" -p "$PORT" -c "DROP DATABASE $DATABASE;"
elif [[ "$CMD" == "reset" ]]; then
PGPASSWORD="$PASSWORD" psql -h "$HOST" -U "$USERNAME" -p "$PORT" -c "DROP DATABASE IF EXISTS $DATABASE;"
PGPASSWORD="$PASSWORD" psql -h "$HOST" -U "$USERNAME" -p "$PORT" -c "CREATE DATABASE $DATABASE;"
PGPASSWORD="$PASSWORD" psql -h "$HOST" -U "$USERNAME" -p "$PORT" -d "$DATABASE" -f schema/create.sql
PGPASSWORD="$PASSWORD" psql -h "$HOST" -U "$USERNAME" -p "$PORT" -d "$DATABASE" -f schema/seed.sql
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment