#!/usr/bin/env bash
# bin/pg — psql into the current directory's docker-compose db service.
# Picks the first service whose name contains "db" or "postgres".
set -euo pipefail
if ! command -v docker >/dev/null 2>&1; then
printf 'pg: docker is not installed\n' >&2
exit 127
fi
compose_file=""
for f in docker-compose.yml docker-compose.yaml compose.yml compose.yaml; do
if [[ -f "$f" ]]; then compose_file="$f"; break; fi
done
if [[ -z "$compose_file" ]]; then
printf 'pg: no compose file in %s\n' "$PWD" >&2
exit 1
fi
svc="${1-}"
if [[ -z "$svc" ]]; then
svc=$(docker compose config --services \
| grep -Ei 'db|postgres|pg' \
| head -n1 || true)
fi
if [[ -z "$svc" ]]; then
printf 'pg: could not guess a db service. services:\n' >&2
docker compose config --services >&2
exit 1
fi
# Prefer PGUSER/PGDATABASE from env; otherwise rely on psql defaults in the container.
user="${PGUSER:-postgres}"
db="${PGDATABASE:-postgres}"
printf 'pg: psql %s/%s via %s\n' "$user" "$db" "$svc"
exec docker compose exec \
-e PAGER=less \
"$svc" \
psql -U "$user" -d "$db"