diff --git a/compose.yml b/compose.yml index 100ab6bb4..ed42f75b2 100644 --- a/compose.yml +++ b/compose.yml @@ -13,6 +13,8 @@ services: - env.d/development/postgresql.local ports: - "15432:5432" + volumes: + - ./docker/files/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d:ro redis: image: redis:5 diff --git a/docker/files/docker-entrypoint-initdb.d/01_create_app_user.sh b/docker/files/docker-entrypoint-initdb.d/01_create_app_user.sh new file mode 100755 index 000000000..a4c7c0e2c --- /dev/null +++ b/docker/files/docker-entrypoint-initdb.d/01_create_app_user.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -e + +# Create a non-superuser for the application to test migrations. +# Uses DB_USER and DB_PASSWORD from the environment so it stays in +# sync with the application database configuration. +# Only creates the user when DB_USER differs from POSTGRES_USER. + + +# Validate required environment variables +if [ -z "${POSTGRES_USER}" ] || [ -z "${POSTGRES_DB}" ] || [ -z "${DB_USER}" ] || [ -z "${DB_PASSWORD}" ]; then + echo "Required environment variables (POSTGRES_USER, POSTGRES_DB, DB_USER, DB_PASSWORD) must be set." + exit 0 +fi + + +if [ "${DB_USER}" = "${POSTGRES_USER}" ]; then + echo "DB_USER is the same as POSTGRES_USER, skipping non-superuser creation." + exit 0 +fi + +psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL + CREATE USER "${DB_USER}" WITH PASSWORD '${DB_PASSWORD}'; + ALTER DATABASE "${POSTGRES_DB}" OWNER TO "${DB_USER}"; +EOSQL diff --git a/env.d/development/postgresql b/env.d/development/postgresql index 81daebab1..f845af5a3 100644 --- a/env.d/development/postgresql +++ b/env.d/development/postgresql @@ -9,3 +9,8 @@ DB_NAME=impress DB_USER=dinum DB_PASSWORD=pass DB_PORT=5432 + +# If you want to create a user without superuser permissions, you can change it. +# The database must be deleted in order to be recreated. +# DB_USER=docs +# DB_PASSWORD=docs