Created
December 2, 2023 16:14
-
-
Save will/93963a1bcdf658640f661b7b52384470 to your computer and use it in GitHub Desktop.
start temporary postgres dbs with pre-created schema
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
schema = pkgs.stdenvNoCC.mkDerivation { | |
name = "schema"; | |
src = schemaSrc; | |
nativeBuildInputs = [ postgres ]; | |
installPhase = '' | |
mkdir $out | |
export PGDATA="$out" | |
export PGHOST="$out" | |
export PGUSER=postgres | |
export PGDATABASE=postgres | |
PGTZ=UTC initdb --no-locale --encoding=UTF8 --nosync -U "$PGUSER" | |
echo "fsync=off" >> $PGDATA/postgresql.conf | |
echo "listen_addresses='''" >> $PGDATA/postgresql.conf | |
echo "log_min_messages='fatal'" >> $PGDATA/postgresql.conf | |
trap 'pg_ctl stop' sigint sigterm | |
pg_ctl start -o "-k $PGDATA" | |
psql -f $src/db/schema.sql \ | |
-f $src/db/test_seed.sql \ | |
-c "CREATE DATABASE test TEMPLATE postgres" \ | |
-c "CREATE DATABASE test_1 TEMPLATE postgres" \ | |
-c "CREATE DATABASE test_2 TEMPLATE postgres" \ | |
-c "CREATE DATABASE test_3 TEMPLATE postgres" \ | |
-c "CREATE DATABASE test_4 TEMPLATE postgres" \ | |
-c "CREATE DATABASE test_5 TEMPLATE postgres" \ | |
-c "CREATE DATABASE test_6 TEMPLATE postgres" \ | |
-c "CREATE DATABASE test_7 TEMPLATE postgres" \ | |
-c "CREATE DATABASE test_8 TEMPLATE postgres" | |
pg_ctl stop | |
''; | |
}; | |
tempdb = pkgs.writeShellScriptBin "tempdb" '' | |
export PATH=${postgres}/bin:"$PATH" | |
tmpdir="$(mktemp -d)" | |
export PGDATA="$tmpdir" | |
export PGHOST="$tmpdir" | |
export PGUSER=postgres | |
export PGDATABASE=test | |
cp -r ${schema}/* $tmpdir | |
chmod -R +w $tmpdir | |
trap 'pg_ctl stop&& rm -rf "$tmpdir"' sigint sigterm exit | |
pg_ctl start -o "-k $PGDATA" | |
"$@" | |
''; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment