Skip to content

Commit e70b240

Browse files
committed
Add notification preferences migrations
Signed-off-by: Danny Kopping <danny@coder.com>
1 parent b5c418d commit e70b240

File tree

3 files changed

+94
-2
lines changed

3 files changed

+94
-2
lines changed

coderd/database/dump.sql

Lines changed: 42 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
DROP TABLE IF EXISTS notification_preferences;
2+
3+
ALTER TABLE notification_templates
4+
DROP COLUMN IF EXISTS method;
5+
6+
DROP TRIGGER IF EXISTS inhibit_enqueue_if_disabled_trigger ON notification_messages;
7+
DROP FUNCTION IF EXISTS inhibit_enqueue_if_disabled;
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

Comments
 (0)