From 0b6fd3cd43a0cd8d7aef15886d4184e3c3e62bc2 Mon Sep 17 00:00:00 2001 From: Nick Bland Date: Fri, 5 Nov 2021 12:16:04 +1000 Subject: [PATCH] Stage changes to implement postgres DB as well as initialise its state --- ...11105005738_create_subscriptions_table.sql | 8 +++ scripts/init_db.sh | 52 +++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 migrations/20211105005738_create_subscriptions_table.sql create mode 100644 scripts/init_db.sh diff --git a/migrations/20211105005738_create_subscriptions_table.sql b/migrations/20211105005738_create_subscriptions_table.sql new file mode 100644 index 0000000..34098b3 --- /dev/null +++ b/migrations/20211105005738_create_subscriptions_table.sql @@ -0,0 +1,8 @@ +-- Create Subscriptions Table +CREATE TABLE Subscriptions( + id uuid NOT NULL, + PRIMARY KEY (id), + email TEXT NOT NULL UNIQUE, + name TEXT NOT NULL, + subscribed_at timestamptz NOT NULL +); \ No newline at end of file diff --git a/scripts/init_db.sh b/scripts/init_db.sh new file mode 100644 index 0000000..a6f7893 --- /dev/null +++ b/scripts/init_db.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -x +set -eo pipefail + +if ! [ -x "$(command -v psql)" ]; then + echo >&2 "Error: `psql` is not installed." + echo >&2 "Use:" + echo >&2 " sudo apt update && sudo apt install postgresql-client" + echo >&2 "to install it." + exit 1 +fi + +if ! [ -x "$(command -v sqlx)" ]; then + echo >&2 "Error: `sqlx` is not installed." + echo >&2 "Use:" + echo >&2 " sudo apt install build-essentials pkg-config openssl libssl-dev" + echo >&2 " cargo install --version=0.5.7 sqlx-cli --no-default-features --features postgres" + echo >&2 "to install it." + exit 1 +fi + +DB_USER=${POSTGRES_USER:=postgres} +DB_PASSWORD="${POSTGRES_PASSWORD:=password}" +DB_NAME="${POSTGRES_DB:=newsletter}" +DB_PORT="${POSTGRES_PORT:=5432}" + +# Allow to skip Docker installation if Postgres is already running +if [[ -z "${SKIP_DOCKER}" ]] +then + docker run \ + --name postgres-db \ + -e POSTGRES_USER=${DB_USER} \ + -e POSTGRES_PASSWORD=${DB_PASSWORD} \ + -e POSTGRES_DB=${DB_NAME} \ + -p "${DB_PORT}":5432 \ + -d postgres \ + postgres -N 1000 +fi + +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 +done + +>&2 echo "Postgres is up anad running on port ${DB_PORT} - running migrations." + +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. Jobs Complete."