zero-to-production/scripts/init_db.sh

66 lines
2.3 KiB
Bash
Raw Normal View History

2020-08-25 21:19:53 +00:00
#!/usr/bin/env bash
set -x
set -eo pipefail
if ! [ -x "$(command -v sqlx)" ]; then
echo >&2 "Error: sqlx is not installed."
echo >&2 "Use:"
2024-08-29 12:54:52 +00:00
echo >&2 " cargo install --version='~0.8' sqlx-cli --no-default-features --features rustls,postgres"
echo >&2 "to install it."
exit 1
fi
2020-08-25 21:19:53 +00:00
# Check if a custom user has been set, otherwise default to 'postgres'
DB_USER="${POSTGRES_USER:=postgres}"
2020-08-25 21:19:53 +00:00
# Check if a custom password has been set, otherwise default to 'password'
DB_PASSWORD="${POSTGRES_PASSWORD:=password}"
2022-07-05 16:47:21 +00:00
# Check if a custom database name has been set, otherwise default to 'newsletter'
2020-08-25 21:19:53 +00:00
DB_NAME="${POSTGRES_DB:=newsletter}"
# Check if a custom port has been set, otherwise default to '5432'
DB_PORT="${POSTGRES_PORT:=5432}"
2021-04-02 10:51:23 +00:00
# Check if a custom host has been set, otherwise default to 'localhost'
DB_HOST="${POSTGRES_HOST:=localhost}"
2020-08-25 21:19:53 +00:00
# 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
CONTAINER_NAME="postgres_$(date '+%s')"
2020-08-25 21:19:53 +00:00
# Launch postgres using Docker
docker run \
-e POSTGRES_USER=${DB_USER} \
-e POSTGRES_PASSWORD=${DB_PASSWORD} \
-e POSTGRES_DB=${DB_NAME} \
--health-cmd="pg_isready -U ${DB_USER} || exit 1" \
--health-interval=1s \
--health-timeout=5s \
--health-retries=5 \
2020-08-25 21:19:53 +00:00
-p "${DB_PORT}":5432 \
2021-04-28 19:42:24 +00:00
-d \
--name "${CONTAINER_NAME}" \
2020-08-25 21:19:53 +00:00
postgres -N 1000
# ^ Increased maximum number of connections for testing purposes
until [ \
"$(docker inspect -f "{{.State.Health.Status}}" ${CONTAINER_NAME})" == \
"healthy" \
]; do
>&2 echo "Postgres is still unavailable - sleeping"
sleep 1
done
2020-08-25 21:19:53 +00:00
fi
>&2 echo "Postgres is up and running on port ${DB_PORT} - running migrations now!"
2023-02-18 16:24:47 +00:00
export DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}
2020-08-25 21:19:53 +00:00
sqlx database create
sqlx migrate run
>&2 echo "Postgres has been migrated, ready to go!"