-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathpostgres.nix
More file actions
119 lines (104 loc) · 2.74 KB
/
postgres.nix
File metadata and controls
119 lines (104 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# This module automatically configures postgres when the user enters the
# devshell.
#
# To start the server, invoke `postgres` in one devshell. Then start a second
# devshell to run the clients.
{
lib,
pkgs,
config,
...
}:
let
inherit (lib)
mkOption
types
mkEnableOption
;
# Because we want to be able to push pure JSON-like data into the
# environment.
strOrPackage = import ../../nix/strOrPackage.nix { inherit lib pkgs; };
cfg = config.services.postgres;
createDB = lib.optionalString cfg.createUserDB ''
echo "CREATE DATABASE ''${USER:-$(id -nu)};" | postgres --single -E postgres
'';
setup-postgres = pkgs.writeShellScriptBin "setup-postgres" ''
set -euo pipefail
export PATH=${cfg.package}/bin:${pkgs.coreutils}/bin
# Abort if the data dir already exists
[[ ! -d "$PGDATA" ]] || exit 0
initdb ${lib.concatStringsSep " " cfg.initdbArgs}
cat >> "$PGDATA/postgresql.conf" <<EOF
listen_addresses = '''
unix_socket_directories = '$PGHOST'
EOF
${createDB}
'';
start-postgres = pkgs.writeShellScriptBin "start-postgres" ''
set -euo pipefail
${setup-postgres}/bin/setup-postgres
exec ${cfg.package}/bin/postgres
'';
in
{
options.services.postgres = {
package = mkOption {
type = strOrPackage;
description = "Which version of postgres to use";
default = pkgs.postgresql;
defaultText = "pkgs.postgresql";
};
setupPostgresOnStartup = mkEnableOption "call setup-postgres on startup";
createUserDB = mkOption {
type = types.bool;
default = true;
description = ''
Create a database named like current user on startup.
This option only makes sense when `setupPostgresOnStartup` is true.
'';
};
initdbArgs = mkOption {
type = with types; listOf str;
default = [ "--no-locale" ];
example = [
"--data-checksums"
"--allow-group-access"
];
description = ''
Additional arguments passed to `initdb` during data dir
initialisation.
'';
};
};
config = {
packages = [
cfg.package
];
env = [
{
name = "PGDATA";
eval = "$PRJ_DATA_DIR/postgres";
}
{
name = "PGHOST";
eval = "$PGDATA";
}
];
devshell.startup.setup-postgres.text = lib.optionalString cfg.setupPostgresOnStartup ''
${setup-postgres}/bin/setup-postgres
'';
commands = [
{
name = "setup-postgres";
package = setup-postgres;
help = "Setup the postgres data directory";
}
{
name = "start-postgres";
package = start-postgres;
help = "Start the postgres server";
category = "databases";
}
];
};
}