|
1 | 1 | { config, pkgs, lib }:
|
2 | 2 | let
|
3 |
| - psqlUserArg = lib.optionalString (config.superuser != null) "-U ${config.superuser}"; |
4 | 3 | setupInitialSchema = dbName: schema: ''
|
5 | 4 | echo "Applying database schema on ${dbName}"
|
6 | 5 | if [ -f "${schema}" ]
|
7 | 6 | then
|
8 | 7 | echo "Running file ${schema}"
|
9 |
| - awk 'NF' "${schema}" | psql ${psqlUserArg} -d ${dbName} |
| 8 | + awk 'NF' "${schema}" | psql_with_args -d ${dbName} |
10 | 9 | elif [ -d "${schema}" ]
|
11 | 10 | then
|
12 | 11 | # Read sql files in version order. Apply one file
|
13 | 12 | # at a time to handle files where the last statement
|
14 | 13 | # doesn't end in a ;.
|
15 | 14 | find "${schema}"/*.sql | while read -r f ; do
|
16 | 15 | echo "Applying sql file: $f"
|
17 |
| - awk 'NF' "$f" | psql ${psqlUserArg} -d ${dbName} |
| 16 | + awk 'NF' "$f" | psql_with_args -d ${dbName} |
18 | 17 | done
|
19 | 18 | else
|
20 | 19 | echo "ERROR: Could not determine how to apply schema with ${schema}"
|
|
29 | 28 | # Create initial databases
|
30 | 29 | dbAlreadyExists=$(
|
31 | 30 | echo "SELECT 1 as exists FROM pg_database WHERE datname = '${database.name}';" | \
|
32 |
| - psql ${psqlUserArg} -d postgres | \ |
| 31 | + psql_with_args -d postgres | \ |
33 | 32 | grep -c 'exists = "1"' || true
|
34 | 33 | )
|
35 | 34 | echo "$dbAlreadyExists"
|
36 | 35 | if [ 1 -ne "$dbAlreadyExists" ]; then
|
37 | 36 | echo "Creating database: ${database.name}"
|
38 |
| - echo 'create database "${database.name}";' | psql ${psqlUserArg} -d postgres |
| 37 | + echo 'create database "${database.name}";' | psql_with_args -d postgres |
39 | 38 | ${lib.optionalString (database.schemas != null)
|
40 | 39 | (lib.concatMapStrings (schema: setupInitialSchema (database.name) schema) database.schemas)}
|
41 | 40 | fi
|
42 | 41 | '')
|
43 | 42 | config.initialDatabases)
|
44 | 43 | else
|
45 | 44 | lib.optionalString config.createDatabase ''
|
46 |
| - echo "CREATE DATABASE ''${USER:-$(id -nu)};" | psql ${psqlUserArg} -d postgres ''; |
| 45 | + echo "CREATE DATABASE ''${USER:-$(id -nu)};" | psql_with_args -d postgres ''; |
47 | 46 |
|
48 | 47 |
|
49 | 48 | runInitialScript =
|
50 | 49 | let
|
51 | 50 | scriptCmd = sqlScript: ''
|
52 |
| - echo "${sqlScript}" | psql ${psqlUserArg} -d postgres |
| 51 | + echo "${sqlScript}" | psql_with_args -d postgres |
53 | 52 | '';
|
54 | 53 | in
|
55 | 54 | {
|
|
79 | 78 | name = "setup-postgres";
|
80 | 79 | runtimeInputs = with pkgs; [ config.package coreutils gnugrep gawk ];
|
81 | 80 | text = ''
|
82 |
| - set -euo pipefail |
| 81 | + set -x |
| 82 | + # Execute the `psql` command with default arguments |
| 83 | + function psql_with_args() { |
| 84 | + psql ${lib.optionalString (config.superuser != null) "-U ${config.superuser}"} -v "ON_ERROR_STOP=1" "$@" |
| 85 | + } |
83 | 86 | # Setup postgres ENVs
|
84 | 87 | export PGDATA="${config.dataDir}"
|
85 | 88 | export PGPORT="${toString config.port}"
|
|
0 commit comments