Run an ephemeral Postgres container and connect to it
#!/bin/bash | |
set -Eeu -o pipefail | |
PG_VERSION="${PG_VERSION:-9.6-alpine}" | |
psqltmp() { | |
( | |
set -Eeu -o pipefail | |
local _pgcmd | |
if [ -n "${1:-}" ]; then | |
_pgcmd="${1}" | |
elif command -v pgcli >/dev/null 2>&1; then | |
_pgcmd=pgcli | |
else | |
_pgcmd=psql | |
fi | |
local POSTGRES_USER POSTGRES_PASSWORD | |
POSTGRES_USER=localuser | |
POSTGRES_PASSWORD=password | |
export POSTGRES_USER POSTGRES_PASSWORD | |
# Create a docker container for the DB. | |
local _container_id | |
_container_id="$(docker run -dP -e POSTGRES_USER -e POSTGRES_PASSWORD postgres:"${PG_VERSION}")" | |
# When done, remove the container. | |
trap 'docker rm -f "${_container_id}" >/dev/null' EXIT | |
# Get the bound localhost port corresponding to the standard 5432 postgres port of the container. | |
local _pg_port _pg_uri | |
_pg_port="$(docker inspect "${_container_id}" -f '{{index .NetworkSettings.Ports "5432/tcp" 0 "HostPort"}}')" | |
_pg_uri="postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@127.0.0.1:${_pg_port}" | |
# Wait for DB to start. | |
while ! psql -q "${_pg_uri}" -c 'SELECT 1' >/dev/null 2>&1; do printf . >&2; sleep 0.1; done; | |
printf '\n' | |
echo "${_pg_uri}" | |
${_pgcmd} "${_pg_uri}" | |
) | |
} | |
psqltmp "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment