-
Notifications
You must be signed in to change notification settings - Fork 262
/
postgres.nix
316 lines (283 loc) · 9.46 KB
/
postgres.nix
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
{ pkgs, lib, config, ... }:
let
cfg = config.services.postgres;
types = lib.types;
postgresPkg =
if cfg.extensions != null then
if builtins.hasAttr "withPackages" cfg.package
then cfg.package.withPackages cfg.extensions
else
builtins.throw ''
Cannot add extensions to the PostgreSQL package.
`services.postgres.package` is missing the `withPackages` attribute. Did you already add extensions to the package?
''
else cfg.package;
setupInitialDatabases =
if cfg.initialDatabases != [ ] then
(lib.concatMapStrings
(database: ''
echo "Checking presence of database: ${database.name}"
# Create initial databases
dbAlreadyExists="$(
echo "SELECT 1 as exists FROM pg_database WHERE datname = '${database.name}';" | \
psql --dbname postgres | \
${pkgs.gnugrep}/bin/grep -c 'exists = "1"' || true
)"
echo $dbAlreadyExists
if [ 1 -ne "$dbAlreadyExists" ]; then
echo "Creating database: ${database.name}"
echo 'create database "${database.name}";' | psql --dbname postgres
${lib.optionalString (database.schema != null) ''
echo "Applying database schema on ${database.name}"
if [ -f "${database.schema}" ]
then
echo "Running file ${database.schema}"
${pkgs.gawk}/bin/awk 'NF' "${database.schema}" | psql --dbname ${database.name}
elif [ -d "${database.schema}" ]
then
# Read sql files in version order. Apply one file
# at a time to handle files where the last statement
# doesn't end in a ;.
ls -1v "${database.schema}"/*.sql | while read f ; do
echo "Applying sql file: $f"
${pkgs.gawk}/bin/awk 'NF' "$f" | psql --dbname ${database.name}
done
else
echo "ERROR: Could not determine how to apply schema with ${database.schema}"
exit 1
fi
''}
fi
'')
cfg.initialDatabases)
else
lib.optionalString cfg.createDatabase ''
echo "CREATE DATABASE ''${USER:-$(id -nu)};" | psql --dbname postgres'';
runInitialScript =
if cfg.initialScript != null then
''
echo ${lib.escapeShellArg cfg.initialScript} | psql --dbname postgres
''
else
"";
toStr = value:
if true == value then
"yes"
else if false == value then
"no"
else if lib.isString value then
"'${lib.replaceStrings [ "'" ] [ "''" ] value}'"
else
toString value;
configFile = pkgs.writeText "postgresql.conf" (lib.concatStringsSep "\n"
(lib.mapAttrsToList (n: v: "${n} = ${toStr v}") cfg.settings));
setupScript = pkgs.writeShellScriptBin "setup-postgres" ''
set -euo pipefail
export PATH=${postgresPkg}/bin:${pkgs.coreutils}/bin
POSTGRES_RUN_INITIAL_SCRIPT="false"
if [[ ! -d "$PGDATA" ]]; then
initdb ${lib.concatStringsSep " " cfg.initdbArgs}
POSTGRES_RUN_INITIAL_SCRIPT="true"
echo
echo "PostgreSQL initdb process complete."
echo
fi
# Setup config
cp ${configFile} "$PGDATA/postgresql.conf"
if [[ "$POSTGRES_RUN_INITIAL_SCRIPT" = "true" ]]; then
echo
echo "PostgreSQL is setting up the initial database."
echo
OLDPGHOST="$PGHOST"
PGHOST=$(mktemp -d "$DEVENV_STATE/pg-init-XXXXXX")
function remove_tmp_pg_init_sock_dir() {
if [[ -d "$1" ]]; then
rm -rf "$1"
fi
}
trap "remove_tmp_pg_init_sock_dir '$PGHOST'" EXIT
pg_ctl -D "$PGDATA" -w start -o "-c unix_socket_directories=$PGHOST -c listen_addresses= -p ${toString cfg.port}"
${setupInitialDatabases}
${runInitialScript}
pg_ctl -D "$PGDATA" -m fast -w stop
remove_tmp_pg_init_sock_dir "$PGHOST"
PGHOST="$OLDPGHOST"
unset OLDPGHOST
else
echo
echo "PostgreSQL Database directory appears to contain a database; Skipping initialization"
echo
fi
unset POSTGRES_RUN_INITIAL_SCRIPT
'';
startScript = pkgs.writeShellScriptBin "start-postgres" ''
set -euo pipefail
${setupScript}/bin/setup-postgres
exec ${postgresPkg}/bin/postgres
'';
in
{
imports = [
(lib.mkRenamedOptionModule [ "postgres" "enable" ] [
"services"
"postgres"
"enable"
])
];
options.services.postgres = {
enable = lib.mkEnableOption ''
Add PostgreSQL process.
'';
package = lib.mkOption {
type = types.package;
description = ''
The PostgreSQL package to use. Use this to override the default with a specific version.
'';
default = pkgs.postgresql;
defaultText = lib.literalExpression "pkgs.postgresql";
example = lib.literalExpression ''
pkgs.postgresql_15
'';
};
extensions = lib.mkOption {
type = with types; nullOr (functionTo (listOf package));
default = null;
example = lib.literalExpression ''
extensions: [
extensions.pg_cron
extensions.postgis
extensions.timescaledb
];
'';
description = ''
Additional PostgreSQL extensions to install.
The available extensions are:
${lib.concatLines (builtins.map (x: "- " + x) (builtins.attrNames pkgs.postgresql.pkgs))}
'';
};
listen_addresses = lib.mkOption {
type = types.str;
description = "Listen address";
default = "";
example = "127.0.0.1";
};
port = lib.mkOption {
type = types.port;
default = 5432;
description = ''
The TCP port to accept connections.
'';
};
createDatabase = lib.mkOption {
type = types.bool;
default = true;
description = ''
Create a database named like current user on startup. Only applies when initialDatabases is an empty list.
'';
};
initdbArgs = lib.mkOption {
type = types.listOf types.lines;
default = [ "--locale=C" "--encoding=UTF8" ];
example = [ "--data-checksums" "--allow-group-access" ];
description = ''
Additional arguments passed to `initdb` during data dir
initialisation.
'';
};
settings = lib.mkOption {
type = with types; attrsOf (oneOf [ bool float int str ]);
default = { };
description = ''
PostgreSQL configuration. Refer to
<https://www.postgresql.org/docs/11/config-setting.html#CONFIG-SETTING-CONFIGURATION-FILE>
for an overview of `postgresql.conf`.
String values will automatically be enclosed in single quotes. Single quotes will be
escaped with two single quotes as described by the upstream documentation linked above.
'';
example = lib.literalExpression ''
{
log_connections = true;
log_statement = "all";
logging_collector = true
log_disconnections = true
log_destination = lib.mkForce "syslog";
}
'';
};
initialDatabases = lib.mkOption {
type = types.listOf (types.submodule {
options = {
name = lib.mkOption {
type = types.str;
description = ''
The name of the database to create.
'';
};
schema = lib.mkOption {
type = types.nullOr types.path;
default = null;
description = ''
The initial schema of the database; if null (the default),
an empty database is created.
'';
};
};
});
default = [ ];
description = ''
List of database names and their initial schemas that should be used to create databases on the first startup
of Postgres. The schema attribute is optional: If not specified, an empty database is created.
'';
example = lib.literalExpression ''
[
{
name = "foodatabase";
schema = ./foodatabase.sql;
}
{ name = "bardatabase"; }
]
'';
};
initialScript = lib.mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Initial SQL commands to run during database initialization. This can be multiple
SQL expressions separated by a semi-colon.
'';
example = lib.literalExpression ''
CREATE USER postgres SUPERUSER;
CREATE USER bar;
'';
};
};
config = lib.mkIf cfg.enable {
packages = [ postgresPkg startScript ];
env.PGDATA = config.env.DEVENV_STATE + "/postgres";
env.PGHOST = config.env.PGDATA;
env.PGPORT = cfg.port;
services.postgres.settings = {
listen_addresses = cfg.listen_addresses;
port = cfg.port;
# relative to PGDATA
unix_socket_directories = lib.mkDefault ".";
};
processes.postgres = {
exec = "${startScript}/bin/start-postgres";
process-compose = {
# SIGINT (= 2) for faster shutdown: https://www.postgresql.org/docs/current/server-shutdown.html
shutdown.signal = 2;
readiness_probe = {
exec.command = "${postgresPkg}/bin/pg_isready -h $PGDATA -d template1";
initial_delay_seconds = 2;
period_seconds = 10;
timeout_seconds = 4;
success_threshold = 1;
failure_threshold = 5;
};
# https://github.com/F1bonacc1/process-compose#-auto-restart-if-not-healthy
availability.restart = "on_failure";
};
};
};
}