From 35db29078e373c153698d8b5c47ae6b3203f48e4 Mon Sep 17 00:00:00 2001 From: Dibakar Sutra Dhar Date: Sun, 14 Apr 2024 19:11:51 +0600 Subject: [PATCH] init db script updated --- scripts/init_db.sh | 45 +++++++++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/scripts/init_db.sh b/scripts/init_db.sh index 62b5897..b58e9a9 100755 --- a/scripts/init_db.sh +++ b/scripts/init_db.sh @@ -16,34 +16,47 @@ if ! [ -x "$(command -v sqlx)" ]; then fi # Check if a custom user has been set, otherwise default to 'postgres' -DB_USER=${POSTGRES_USER:=postgres} +DB_USER="${POSTGRES_USER:=postgres}" # Check if a custom password has been set, otherwise default to 'password' DB_PASSWORD="${POSTGRES_PASSWORD:=password}" # Check if a custom database name has been set, otherwise default to 'newsletter' DB_NAME="${POSTGRES_DB:=newsletter}" # Check if a custom port has been set, otherwise default to '5432' DB_PORT="${POSTGRES_PORT:=5432}" - -# Launch postgres using Docker -docker run \ - -e POSTGRES_USER=${DB_USER} \ - -e POSTGRES_PASSWORD=${DB_PASSWORD} \ - -e POSTGRES_DB=${DB_NAME} \ - -p "${DB_PORT}":5432 \ - -d postgres \ - postgres -N 1000 +# Check if a custom host has been set, otherwise default to 'localhost' +DB_HOST="${POSTGRES_HOST:=localhost}" + +# Allow to skip Docker if a dockerized Postgres database is already running +if [[ -z "${SKIP_DOCKER}" ]] +then + # if a postgres container is running, print instructions to kill it and exit + RUNNING_POSTGRES_CONTAINER=${docker ps --filter 'name=postgres' --format '{{.ID}}'} + if [[ -n $RUNNING_POSTGRES_CONTAINER ]]; then + echo >&2 "there is a postgres container already running, kill it with" + echo >&2 " docker kill ${RUNNING_POSTGRES_CONTAINER}" + exit 1 + fi + # Launch postgres using Docker + docker run \ + -e POSTGRES_USER=${DB_USER} \ + -e POSTGRES_PASSWORD=${DB_PASSWORD} \ + -e POSTGRES_DB=${DB_NAME} \ + -p "${DB_PORT}":5432 \ + -d \ + --name "postgres_$(date '+%s')" \ + postgres -N 1000 +fi # Keep pinging Postgres until it's ready to accept commands -export PGPASSWORD="${DB_PASSWORD}" -until psql -h "localhost" -U "${DB_USER}" -p "${DB_PORT}" -d "postgres" -c '\q'; do - >&2 echo "Postgres is still unavailable - sleeping" - sleep 1 +until PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -U "${DB_USER}" -p "${DB_PORT}" -d "postgres" -c '\q'; do + >&2 echo "Postgres is still unavailable - sleeping" + sleep 1 done >&2 echo "Postgres is up and running on port ${DB_PORT} - running migrations now!" -export DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@localhost:${DB_PORT}/${DB_NAME} -sqlx database +export DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME} +sqlx database create sqlx migrate run >&2 echo "Postgres has been migrated, ready to go!" \ No newline at end of file