1
+ CREATE TABLE notification_preferences
2
+ (
3
+ user_id uuid REFERENCES users ON DELETE CASCADE NOT NULL ,
4
+ notification_template_id uuid REFERENCES notification_templates ON DELETE CASCADE NOT NULL ,
5
+ disabled bool NOT NULL DEFAULT FALSE,
6
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP ,
7
+ updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
8
+ );
9
+
10
+ -- Ensure we cannot insert multiple entries for the same user/template combination
11
+ ALTER TABLE notification_preferences
12
+ ADD CONSTRAINT unique_user_notification_template UNIQUE (user_id, notification_template_id);
13
+
14
+ -- Allow per-template notification method (enterprise only)
15
+ ALTER TABLE notification_templates
16
+ ADD COLUMN method notification_method;
17
+ COMMENT ON COLUMN notification_templates.method IS ' NULL defers to the deployment-level method' ;
18
+
19
+ -- No equivalent in down migration because ENUM values cannot be deleted
20
+ ALTER TYPE notification_message_status ADD VALUE IF NOT EXISTS ' inhibited' ;
21
+
22
+ -- Function to prevent enqueuing notifications unnecessarily
23
+ CREATE OR REPLACE FUNCTION inhibit_enqueue_if_disabled ()
24
+ RETURNS TRIGGER AS
25
+ $$
26
+ BEGIN
27
+ -- Fail the insertion if the user has disabled this notification
28
+ IF EXISTS (SELECT 1
29
+ FROM notification_preferences
30
+ WHERE disabled = TRUE
31
+ AND user_id = NEW .user_id
32
+ AND notification_template_id = NEW .notification_template_id ) THEN
33
+ RAISE EXCEPTION ' cannot enqueue message: user has disabled this notification' ;
34
+ END IF;
35
+
36
+ RETURN NEW;
37
+ END;
38
+ $$ LANGUAGE plpgsql;
39
+
40
+ -- Trigger to execute above function on insertion
41
+ CREATE TRIGGER inhibit_enqueue_if_disabled_trigger
42
+ BEFORE INSERT
43
+ ON notification_messages
44
+ FOR EACH ROW
45
+ EXECUTE FUNCTION inhibit_enqueue_if_disabled();
0 commit comments