Skip to content

Instantly share code, notes, and snippets.

@KellerFuchs
Created March 25, 2018 18:51
Show Gist options
  • Save KellerFuchs/78a654f5cd020a7c56b844a9577b3569 to your computer and use it in GitHub Desktop.
Save KellerFuchs/78a654f5cd020a7c56b844a9577b3569 to your computer and use it in GitHub Desktop.
Overengineered and overly-portable script for doing stuff in a temporary pgsql database
#!/bin/sh -e
# Adapted from the Hashbang userdb testing script:
# https://github.com/hashbang/userdb/blob/master/test.sh
run() {
normal='\e[0m'
yellow='\e[33m'
printf "${yellow}%s${normal}\n" "$*" >&2
"$@"
}
# Some distros support multiple installed versions of PostgreSQL
if ! command -v initdb 2>/dev/null; then
for dir in /usr/lib/postgresql/*; do
export PATH="${dir}/bin:${PATH}"
done
fi
if ! command -v initdb 2>/dev/null; then
echo "No PostgreSQL utilities in PATH" >&2
exit 1
fi
trap 'pg_ctl -D "${WORKDIR}" stop; rm -rf -- "${WORKDIR}"' EXIT
WORKDIR=$(mktemp -d)
run initdb -D "${WORKDIR}"
run pg_ctl -D "${WORKDIR}" start -w -o " \
-c unix_socket_directories=${WORKDIR} \
-c listen_addresses='' \
"
# Set the environment to use the temporary pgsql by default
export PGHOST="${WORKDIR}"
export PGDATABASE="postgres"
# Do your things here
## Either run a user-provided command...
if [ $# -gt 0 ]; then
"$@"
## ...or a fancy Postgres terminal UI...
elif command -v pgcli 2>/dev/null; then
pgcli
## ...or a not-fancy one.
else
psql
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment