1
2# `postgresqlTestHook` {#sec-postgresqlTestHook}
3
4This hook starts a PostgreSQL server during the `checkPhase`. Example:
5
6```nix
7{ stdenv, postgresql, postgresqlTestHook }:
8stdenv.mkDerivation {
9
10 # ...
11
12 checkInputs = [
13 postgresql
14 postgresqlTestHook
15 ];
16}
17```
18
19If you use a custom `checkPhase`, remember to add the `runHook` calls:
20```nix
21 checkPhase ''
22 runHook preCheck
23
24 # ... your tests
25
26 runHook postCheck
27 ''
28```
29
30## Variables {#sec-postgresqlTestHook-variables}
31
32The hook logic will read a number of variables and set them to a default value if unset or empty.
33
34Exported variables:
35
36 - `PGDATA`: location of server files.
37 - `PGHOST`: location of UNIX domain socket directory; the default `host` in a connection string.
38 - `PGUSER`: user to create / log in with, default: `test_user`.
39 - `PGDATABASE`: database name, default: `test_db`.
40
41Bash-only variables:
42
43 - `postgresqlTestUserOptions`: SQL options to use when creating the `$PGUSER` role, default: `"LOGIN"`. Example: `"LOGIN SUPERUSER"`
44 - `postgresqlTestSetupSQL`: SQL commands to run as database administrator after startup, default: statements that create `$PGUSER` and `$PGDATABASE`.
45 - `postgresqlTestSetupCommands`: bash commands to run after database start, defaults to running `$postgresqlTestSetupSQL` as database administrator.
46 - `postgresqlEnableTCP`: set to `1` to enable TCP listening. Flaky; not recommended.
47 - `postgresqlStartCommands`: defaults to `pg_ctl start`.
48
49## TCP and the Nix sandbox {#sec-postgresqlTestHook-tcp}
50
51`postgresqlEnableTCP` relies on network sandboxing, which is not available on macOS and some custom Nix installations, resulting in flaky tests.
52For this reason, it is disabled by default.
53
54The 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.
55Some 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.
56
57::: {.note}
58The 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.
59:::