1
2# `postgresqlTestHook` {#sec-postgresqlTestHook}
3
4This hook starts a PostgreSQL server during the `checkPhase`. Example:
5
6```nix
7{
8 stdenv,
9 postgresql,
10 postgresqlTestHook,
11}:
12stdenv.mkDerivation {
13
14 # ...
15
16 nativeCheckInputs = [
17 postgresql
18 postgresqlTestHook
19 ];
20}
21```
22
23If you use a custom `checkPhase`, remember to add the `runHook` calls:
24```nix
25checkPhase ''
26 runHook preCheck
27
28 # ... your tests
29
30 runHook postCheck
31''
32```
33
34## Variables {#sec-postgresqlTestHook-variables}
35
36The hook logic will read a number of variables and set them to a default value if unset or empty.
37
38Exported variables:
39
40 - `PGDATA`: location of server files.
41 - `PGHOST`: location of UNIX domain socket directory; the default `host` in a connection string.
42 - `PGUSER`: user to create / log in with, default: `test_user`.
43 - `PGDATABASE`: database name, default: `test_db`.
44
45Bash-only variables:
46
47 - `postgresqlTestUserOptions`: SQL options to use when creating the `$PGUSER` role, default: `"LOGIN"`. Example: `"LOGIN SUPERUSER"`
48 - `postgresqlTestSetupSQL`: SQL commands to run as database administrator after startup, default: statements that create `$PGUSER` and `$PGDATABASE`.
49 - `postgresqlTestSetupCommands`: bash commands to run after database start, defaults to running `$postgresqlTestSetupSQL` as database administrator.
50 - `postgresqlEnableTCP`: set to `1` to enable TCP listening. Flaky; not recommended.
51 - `postgresqlStartCommands`: defaults to `pg_ctl start`.
52 - `postgresqlExtraSettings`: Additional configuration to add to `postgresql.conf`
53
54## Hooks {#sec-postgresqlTestHook-hooks}
55
56A number of additional hooks are ran in postgresqlTestHook
57
58 - `postgresqlTestSetupPost`: ran after postgresql has been set up.
59
60## TCP and the Nix sandbox {#sec-postgresqlTestHook-tcp}
61
62`postgresqlEnableTCP` relies on network sandboxing, which is not available on macOS and some custom Nix installations, resulting in flaky tests.
63For this reason, it is disabled by default.
64
65The preferred solution is to make the test suite use a UNIX domain socket connection. This is the default behavior when no `host` connection parameter is provided.
66Some test suites hardcode a value for `host` though, so a patch may be required. If you can upstream the patch, you can make `host` default to the `PGHOST` environment variable when set. Otherwise, you can patch it locally to omit the `host` connection string parameter altogether.
67
68::: {.note}
69The error `libpq: failed (could not receive data from server: Connection refused` is generally an indication that the test suite is trying to connect through TCP.
70:::