Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding option initialDumps to Postgres #67

Merged
merged 6 commits into from
Dec 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions nix/postgres/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,16 @@ in
'';
};

initialDumps = lib.mkOption {
type = types.listOf types.path;
default = [ ];
description = ''List of SQL dumps to run during the database initialization.
These dumps are loaded after `initalScript` and `initialDatabases`.'';
example = lib.literalExpression ''
[ ./foo.sql ./bar.sql ]
'';
};

initialScript = lib.mkOption {
type = types.submodule ({ config, ... }: {
options = {
Expand Down
4 changes: 4 additions & 0 deletions nix/postgres/postgres_test.nix
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
listen_addresses = "127.0.0.1";
initialScript.before = "CREATE USER bar;";
initialScript.after = "CREATE DATABASE foo OWNER bar;";
initialDumps = [ ./test.sql ];
};
settings.processes.test =
let
Expand All @@ -21,6 +22,9 @@

# initialScript.after test
echo "SELECT 1 FROM pg_database WHERE datname = 'foo';" | psql -h 127.0.0.1 | grep -q 1

#intialDumps test
echo "SELECT * from users where user_name = 'test_user';" | psql -h 127.0.0.1 -d postgres | grep -q test_user
'';
name = "postgres-test";
};
Expand Down
10 changes: 10 additions & 0 deletions nix/postgres/setup-script.nix
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ let
else
lib.optionalString config.createDatabase ''
echo "CREATE DATABASE ''${USER:-$(id -nu)};" | psql -d postgres '';

runInitialDumps =
let
scriptCmd = dump: ''
psql -d postgres < ${dump}
'';
in
builtins.concatStringsSep "\n" (map scriptCmd config.initialDumps);

runInitialScript =
let
scriptCmd = sqlScript: ''
Expand Down Expand Up @@ -112,6 +121,7 @@ in
${runInitialScript.before}
${setupInitialDatabases}
${runInitialScript.after}
${runInitialDumps}
pg_ctl -D "$PGDATA" -m fast -w stop
remove_tmp_pg_init_sock_dir "$PGHOST"
else
Expand Down
4 changes: 4 additions & 0 deletions nix/postgres/test.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
CREATE TABLE users (id INT PRIMARY KEY, user_name VARCHAR(25));

INSERT INTO users values (1, 'test_user');