Skip to content

Commit

Permalink
[FEAT] Do not use single-user mode when initializing postgres
Browse files Browse the repository at this point in the history
  • Loading branch information
penguincoder committed Jul 21, 2023
1 parent ff78ecd commit fba5a36
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions src/modules/services/postgres.nix
Original file line number Diff line number Diff line change
Expand Up @@ -23,29 +23,29 @@ let
# Create initial databases
dbAlreadyExists="$(
echo "SELECT 1 as exists FROM pg_database WHERE datname = '${database.name}';" | \
postgres --single -E postgres | \
psql --dbname postgres | \
${pkgs.gnugrep}/bin/grep -c 'exists = "1"' || true
)"
echo $dbAlreadyExists
if [ 1 -ne "$dbAlreadyExists" ]; then
echo "Creating database: ${database.name}"
echo 'create database "${database.name}";' | postgres --single -E postgres
echo 'create database "${database.name}";' | psql
${lib.optionalString (database.schema != null) ''
echo "Applying database schema on ${database.name}"
if [ -f "${database.schema}" ]
then
echo "Running file ${database.schema}"
${pkgs.gawk}/bin/awk 'NF' "${database.schema}" | postgres --single -j -E ${database.name}
${pkgs.gawk}/bin/awk 'NF' "${database.schema}" | psql --dbname ${database.name}
elif [ -d "${database.schema}" ]
then
# Read sql files in version order. Apply one file
# at a time to handle files where the last statement
# doesn't end in a ;.
ls -1v "${database.schema}"/*.sql | while read f ; do
echo "Applying sql file: $f"
${pkgs.gawk}/bin/awk 'NF' "$f" | postgres --single -j -E ${database.name}
${pkgs.gawk}/bin/awk 'NF' "$f" | psql --dbname ${database.name}
done
else
echo "ERROR: Could not determine how to apply schema with ${database.schema}"
Expand All @@ -57,12 +57,12 @@ let
cfg.initialDatabases)
else
lib.optionalString cfg.createDatabase ''
echo "CREATE DATABASE ''${USER:-$(id -nu)};" | postgres --single -E postgres '';
echo "CREATE DATABASE ''${USER:-$(id -nu)};" | psql '';

runInitialScript =
if cfg.initialScript != null then
''
echo ${lib.escapeShellArg cfg.initialScript} | postgres --single -E postgres
echo ${lib.escapeShellArg cfg.initialScript} | psql
''
else
"";
Expand All @@ -85,13 +85,30 @@ let
if [[ ! -d "$PGDATA" ]]; then
initdb ${lib.concatStringsSep " " cfg.initdbArgs}
${setupInitialDatabases}
${runInitialScript}
fi
# Setup config
cp ${configFile} "$PGDATA/postgresql.conf"
if [[ ! -f "$PGDATA/.configured" ]]; then
touch "$PGDATA/.configured"
cat <<-'EOM'
PostgreSQL init process complete; ready for start up.
EOM
pg_ctl -D "$PGDATA" -w start -o "--auth-local=trust"
${setupInitialDatabases}
${runInitialScript}
pg_ctl -D "$PGDATA" -m fast -w stop
else
cat <<-'EOM'
PostgreSQL Database directory appears to contain a database; Skipping initialization
EOM
fi
'';
startScript = pkgs.writeShellScriptBin "start-postgres" ''
set -euo pipefail
Expand Down

0 comments on commit fba5a36

Please sign in to comment.