From 82930f63f3b17aad52fcb180df00983459ef4fbe Mon Sep 17 00:00:00 2001 From: Nikkuss Date: Mon, 17 Mar 2025 11:19:48 +0400 Subject: [PATCH] fix postgres init script --- lib.nix | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/lib.nix b/lib.nix index 167445e..143bab5 100644 --- a/lib.nix +++ b/lib.nix @@ -66,6 +66,8 @@ in extra_config ? '''', package ? pkgs.postgresql, data_dir ? ".data/", + port ? 5432, + listen_addresses ? "localhost", ... }: let @@ -83,7 +85,11 @@ in else { } ) - // config; + // config + // { + unix_socket_directories = data_dir; + inherit port listen_addresses; + }; toStr = value: if true == value then @@ -102,15 +108,36 @@ in ) ); }; + setupScript = pkgs.writeShellScript "setup-postgres" '' + set -euo pipefail + export PATH=${package}/bin:${pkgs.coreutils}/bin + POSTGRES_RUN_INITIAL_SCRIPT="false" + if [[ ! -d "${data_dir}" ]]; then + echo "Database directory does not exist. Initializing" + POSTGRES_RUN_INITIAL_SCRIPT="true" + ${package}/bin/initdb -D ${data_dir} --no-instructions + fi + cp ${configFile} ${data_dir}/postgresql.conf + if [[ "$POSTGRES_RUN_INITIAL_SCRIPT" == "true" ]]; then + echo "Running initial script" + pg_ctl -D "${data_dir}" -w start -o "-c unix_socket_directories=${data_dir} -c listen_addresses= -p ${lib.toString port}" + pg_ctl -D "${data_dir}" -m fast -w stop + else + echo + echo "Database directory exists. Skipping initialization" + echo + fi + + unset POSTGRES_RUN_INITIAL_SCRIPT + ''; + script = pkgs.writeShellApplication { name = "run-postgres"; text = '' - if [ ! -d "${data_dir}" ]; then - echo "Database directory does not exist. Initializing" - ${package}/bin/initdb -D ${data_dir} --no-instructions - fi + set -euo pipefail + mkdir -p ${lib.escapeShellArg data_dir} + ${setupScript}/bin/setup-postgres ${package}/bin/postgres -D${data_dir} --config-file=${configFile} - ''; }; in