Skip to content

Commit

Permalink
postgres init: use -U ${config.superuser} with psql if superuser != n…
Browse files Browse the repository at this point in the history
…ull (#106)
  • Loading branch information
adrian-gierakowski authored Feb 21, 2024
1 parent dafaeb0 commit f8cd3fb
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions nix/postgres/setup-script.nix
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
{ config, pkgs, lib }:
let
psqlUserArg = lib.optionalString (config.superuser != null) "-U ${config.superuser}";
setupInitialSchema = dbName: schema: ''
echo "Applying database schema on ${dbName}"
if [ -f "${schema}" ]
then
echo "Running file ${schema}"
awk 'NF' "${schema}" | psql -d ${dbName}
awk 'NF' "${schema}" | psql ${psqlUserArg} -d ${dbName}
elif [ -d "${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 ;.
find "${schema}"/*.sql | while read -r f ; do
echo "Applying sql file: $f"
awk 'NF' "$f" | psql -d ${dbName}
awk 'NF' "$f" | psql ${psqlUserArg} -d ${dbName}
done
else
echo "ERROR: Could not determine how to apply schema with ${schema}"
Expand All @@ -28,27 +29,27 @@ let
# Create initial databases
dbAlreadyExists=$(
echo "SELECT 1 as exists FROM pg_database WHERE datname = '${database.name}';" | \
psql -d postgres | \
psql ${psqlUserArg} -d postgres | \
grep -c 'exists = "1"' || true
)
echo "$dbAlreadyExists"
if [ 1 -ne "$dbAlreadyExists" ]; then
echo "Creating database: ${database.name}"
echo 'create database "${database.name}";' | psql -d postgres
echo 'create database "${database.name}";' | psql ${psqlUserArg} -d postgres
${lib.optionalString (database.schemas != null)
(lib.concatMapStrings (schema: setupInitialSchema (database.name) schema) database.schemas)}
fi
'')
config.initialDatabases)
else
lib.optionalString config.createDatabase ''
echo "CREATE DATABASE ''${USER:-$(id -nu)};" | psql -d postgres '';
echo "CREATE DATABASE ''${USER:-$(id -nu)};" | psql ${psqlUserArg} -d postgres '';


runInitialScript =
let
scriptCmd = sqlScript: ''
echo "${sqlScript}" | psql -d postgres
echo "${sqlScript}" | psql ${psqlUserArg} -d postgres
'';
in
{
Expand Down

0 comments on commit f8cd3fb

Please sign in to comment.