Skip to content

Commit

Permalink
nixos/lemmy: use PostgreSQL module to ensure database/user existence
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
5 people authored and Yt committed Sep 21, 2022
1 parent 3de898f commit e5f798f
Showing 1 changed file with 8 additions and 24 deletions.
32 changes: 8 additions & 24 deletions nixos/modules/services/web-apps/lemmy.nix
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
};
};
};

}

0 comments on commit e5f798f

Please sign in to comment.