Estou usando algo como o seguinte:
./ shell.nix:
let
pkgs = import <nixpkgs> { };
in with pkgs; mkShell {
buildInputs = [ glibcLocales postgresql ];
shellHook = ''
export LANG=en_US.UTF-8
PGDATABASE=some-dbname \
PGDATA="$PWD/nix/pgdata" \
PGHOST="$PWD/nix/sockets" \
PGPORT="5433" \
PGUSER="$USER"
trap "'$PWD/nix/client' remove" EXIT
nix/client add
'';
}
./ nix / client
#! /usr/bin/env bash
set -eu
client_pid=$PPID
start_postgres() {
if postgres_is_stopped
then
logfile="$PWD/log/pg.log"
mkdir -p "$PGHOST" "${logfile%/*}"
(set -m
pg_ctl start --silent -w --log "$logfile" -o "-k $PGHOST -h ''")
fi
}
postgres_is_stopped() {
pg_ctl status >/dev/null
(( $? == 3 ))
}
case "$1" in
add)
mkdir -p nix/pids touch nix/pids/$client_pid
if [ -d "$PGDATA" ]
then
start_postgres
else
pg_ctl initdb --silent -o '--auth=trust' && start_postgres && createdb $PGDATABASE
fi
;;
remove)
rm nix/pids/$client_pid
if [ -n "$(find nix/pids -prune -empty)" ]
then
pg_ctl stop --silent -W
fi
;;
*)
echo "Usage: ${BASH_SOURCE[0]##*/} {add | remove}"
exit 1
;;
esac
A armadilha EXIT
encerrará o servidor de banco de dados se nenhuma outra sessão nix-shell ainda estiver sendo usada.