nixos/lemmy: use PostgreSQL module to ensure database/user existence

Co-authored-by: Shahar Dawn Or <mightyiampresence@gmail.com>
Co-authored-by: a-kenji <aks.kenji@protonmail.com>
Co-authored-by: Valentin Gagarin <valentin.gagarin@tweag.io>
Co-authored-by: Ilan Joselevich <personal@ilanjoselevich.com>
This commit is contained in:
Brian Leung 2022-09-21 00:48:02 -07:00 committed by Yt
parent 3de898f262
commit e5f798f3b9

View file

@ -98,7 +98,12 @@ in
});
services.postgresql = mkIf cfg.database.createLocally {
enable = mkDefault true;
enable = true;
ensureDatabases = [ cfg.settings.database.database ];
ensureUsers = [{
name = cfg.settings.database.user;
ensurePermissions."DATABASE ${cfg.settings.database.database}" = "ALL PRIVILEGES";
}];
};
services.pict-rs.enable = true;
@ -159,9 +164,9 @@ in
wantedBy = [ "multi-user.target" ];
after = [ "pict-rs.service" ] ++ lib.optionals cfg.database.createLocally [ "lemmy-postgresql.service" ];
after = [ "pict-rs.service" ] ++ lib.optionals cfg.database.createLocally [ "postgresql.service" ];
requires = lib.optionals cfg.database.createLocally [ "lemmy-postgresql.service" ];
requires = lib.optionals cfg.database.createLocally [ "postgresql.service" ];
serviceConfig = {
DynamicUser = true;
@ -198,27 +203,6 @@ in
ExecStart = "${pkgs.nodejs}/bin/node ${pkgs.lemmy-ui}/dist/js/server.js";
};
};
systemd.services.lemmy-postgresql = mkIf cfg.database.createLocally {
description = "Lemmy postgresql db";
after = [ "postgresql.service" ];
partOf = [ "lemmy.service" ];
script = with cfg.settings.database; ''
PSQL() {
${config.services.postgresql.package}/bin/psql --port=${toString cfg.settings.database.port} "$@"
}
# check if the database already exists
if ! PSQL -lqt | ${pkgs.coreutils}/bin/cut -d \| -f 1 | ${pkgs.gnugrep}/bin/grep -qw ${database} ; then
PSQL -tAc "CREATE ROLE ${user} WITH LOGIN;"
PSQL -tAc "CREATE DATABASE ${database} WITH OWNER ${user};"
fi
'';
serviceConfig = {
User = config.services.postgresql.superUser;
Type = "oneshot";
RemainAfterExit = true;
};
};
};
}