summaryrefslogtreecommitdiff
path: root/hosts/surtr/postgresql.nix
blob: ca56f60c4e613d5351085523a9ee42ec38861bed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
{ pkgs, sources, ... }:
let
  versioning = sources.psql-versioning.src;
in {
  config = {
    services.postgresql = {
      enable = true;
      package = pkgs.postgresql_14;
      initialScript = pkgs.writeText "schema.sql" ''
        CREATE DATABASE "matrix-synapse" WITH TEMPLATE "template0" ENCODING "UTF8" LOCALE "C";
        CREATE USER "matrix-synapse";
        GRANT ALL PRIVILEGES ON DATABASE "matrix-synapse" TO "matrix-synapse";
        GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "matrix-synapse";

        CREATE DATABASE "email" WITH TEMPLATE "template0" ENCODING "UTF8" LOCALE "C";
        CREATE USER "postfix";
        GRANT CONNECT ON DATABASE "email" TO "postfix";
        GRANT SELECT ON ALL TABLES IN SCHEMA public TO "postfix";
        CREATE USER "dovecot2";
        GRANT CONNECT ON DATABASE "email" TO "dovecot2";
        GRANT SELECT ON ALL TABLES IN SCHEMA public TO "dovecot2";
      '';
    };

    systemd.services.postgresql = {
      postStart = ''
        psql email postgres -eXf ${pkgs.writeText "email.sql" ''
          \i ${versioning + "/install.versioning.sql"}

          BEGIN;
          SELECT _v.register_patch('000-base', null, null);

          CREATE TABLE virtual_mailbox (
            id uuid PRIMARY KEY NOT NULL DEFAULT gen_random_uuid(),
            local text CONSTRAINT local_non_empty CHECK (local IS DISTINCT FROM '''),
            domain text NOT NULL CONSTRAINT domain_non_empty CHECK (domain <> '''),
            mailbox text NOT NULL CONSTRAINT mailbox_non_empty CHECK (mailbox <> '''),
            CONSTRAINT local_domain_unique UNIQUE (local, domain)
          );
          CREATE UNIQUE INDEX domain_unique ON TABLE virtual_mailbox (domain) WHERE local IS NULL;
          COMMIT;
        ''}
      '';
    };
  };
}