57 lines
1.7 KiB
Nix
57 lines
1.7 KiB
Nix
{
|
|
# original via @estebxn
|
|
description = "Tiny PostgreSQL flake";
|
|
|
|
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
|
|
|
outputs =
|
|
{ nixpkgs, ... }:
|
|
let
|
|
system = "x86_64-linux";
|
|
pkgs = import nixpkgs { inherit system; };
|
|
pg = pkgs.postgresql_16;
|
|
in
|
|
{
|
|
apps.${system}.default = {
|
|
type = "app";
|
|
program = toString (
|
|
pkgs.writeShellScript "run-postgres" ''
|
|
set -euo pipefail
|
|
|
|
: ''${PGDATA:=$PWD/.postgres}
|
|
: ''${PGHOST:=$PWD/.postgres-socket}
|
|
: ''${PGPORT:=5432}
|
|
: ''${PGUSER:=postgres}
|
|
: ''${PGDATABASE:=app}
|
|
|
|
mkdir -p "$PGHOST"
|
|
|
|
if [ ! -d "$PGDATA" ]; then
|
|
${pg}/bin/initdb -D "$PGDATA" --auth=trust --username="$PGUSER"
|
|
cat >> "$PGDATA/postgresql.conf" <<EOF
|
|
listen_addresses = '127.0.0.1'
|
|
port = $PGPORT
|
|
unix_socket_directories = '$PGHOST'
|
|
EOF
|
|
fi
|
|
|
|
${pg}/bin/pg_ctl -D "$PGDATA" -l "$PGDATA/postgres.log" start
|
|
trap '${pg}/bin/pg_ctl -D "$PGDATA" stop' EXIT
|
|
|
|
until ${pg}/bin/pg_isready -h "$PGHOST" -p "$PGPORT" >/dev/null 2>&1; do
|
|
sleep 1
|
|
done
|
|
|
|
${pg}/bin/psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" postgres \
|
|
-tc "SELECT 1 FROM pg_database WHERE datname = '$PGDATABASE'" \
|
|
| grep -q 1 || ${pg}/bin/createdb -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" "$PGDATABASE"
|
|
|
|
echo "Postgres is running on port $PGPORT"
|
|
echo "psql -h $PGHOST -p $PGPORT -U $PGUSER $PGDATABASE"
|
|
|
|
while true; do sleep 60; done
|
|
''
|
|
);
|
|
};
|
|
};
|
|
}
|