zero-to-production/chapter05/scripts/init_db.sh
Luca Palmieri 0a4addc6bb
Chapter 5 (#13)
* Add chapter 5

* Basic deployment stuff

* Fix Dockerfile.

* Add an explicit connection timeout.

* Align port with configuration.

* Use debug for faster feedback loops.

* Add address configuration.

* Provision database.

* Use structured options.

* Add configuration

* Fix typo.

* Customise deserialization logic.

* Change to Require.

* Fix spec.

* Add a few more things to the dockerignore file.

* Update to match chapter.

* Add base configuration.

* Amend configuratiohn.

Co-authored-by: LukeMathWalker <rust@lpalmieri.com>
2020-11-01 21:25:11 +00:00

41 lines
1.4 KiB
Bash
Executable file

#!/usr/bin/env bash
set -x
set -eo pipefail
# Check if a custom user has been set, otherwise default to '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 password 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}"
# Allow to skip Docker if a dockerized Postgres database is already running
if [[ -z "${SKIP_DOCKER}" ]]
then
# 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
# ^ Increased maximum number of connections for testing purposes
fi
# Keep pinging Postgres until it's ready to accept commands
until PGPASSWORD="${DB_PASSWORD}" psql -h "localhost" -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 create
sqlx migrate run
>&2 echo "Postgres has been migrated, ready to go!"