From b3ac8b1e8ca825e819c61b3e013e945ef87c9c35 Mon Sep 17 00:00:00 2001 From: Manuel Raynaud Date: Mon, 11 May 2026 15:22:20 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7(postgres)=20create=20a=20user=20wi?= =?UTF-8?q?thout=20superuser=20role?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In development environment we wanto tu use the application with a postgres user not having superuser role. The migration 0027 needs superuser role to be executed, so we want to be able to test migrations and other scenarios with a normal user. In order to create this user, the compose service must be deleted first and then recreated with DB_USER and DB_PASSWORD environment variable values different with POSTGRES_USER and POSTGRES_PASSWORD --- compose.yml | 2 ++ .../01_create_app_user.sh | 25 +++++++++++++++++++ env.d/development/postgresql | 5 ++++ 3 files changed, 32 insertions(+) create mode 100755 docker/files/docker-entrypoint-initdb.d/01_create_app_user.sh 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