@@ -71,16 +71,31 @@ ALTER TABLE notification_events
7171
7272CREATE INDEX notification_events_scope_user_and_project ON notification_events(scope_user_id, project_id, occurred_at DESC );
7373
74+ -- There may be some existing subscriptions and events with a projectId for a project which no longer exists.
75+ -- It's safe to delete them.
76+ DELETE FROM notification_subscriptions
77+ WHERE filter ? ' projectId'
78+ AND NOT EXISTS (SELECT FROM projects p WHERE p .id = regexp_replace(filter- >> ' projectId' , ' ^P-' , ' ' )::UUID)
79+ ;
80+
81+ DELETE FROM notification_events
82+ WHERE data ? ' projectId'
83+ AND NOT EXISTS (SELECT FROM projects p WHERE p .id = regexp_replace(data- >> ' projectId' , ' ^P-' , ' ' )::UUID)
84+ ;
85+
7486-- Migrate existing filters to the new column, and also remove
7587-- the projectId from the JSONB filter.
7688UPDATE notification_subscriptions
7789 SET scope_project_id = regexp_replace(filter- >> ' projectId' , ' ^P-' , ' ' )::UUID,
7890 filter = filter - ' projectId'
79- WHERE filter ? ' projectId' ;
91+ WHERE filter ? ' projectId'
92+ AND EXISTS (SELECT FROM projects p WHERE p .id = regexp_replace(filter- >> ' projectId' , ' ^P-' , ' ' )::UUID)
93+ ;
8094
8195UPDATE notification_events
8296 SET project_id = regexp_replace(data- >> ' projectId' , ' ^P-' , ' ' )::UUID
83- WHERE data ? ' projectId' ;
97+ WHERE data ? ' projectId'
98+ AND EXISTS (SELECT FROM projects p WHERE p .id = regexp_replace(data- >> ' projectId' , ' ^P-' , ' ' )::UUID);
8499
85100-- Rework the trigger to use the new topic groups.
86101CREATE OR REPLACE FUNCTION trigger_notification_event_subscriptions ()
@@ -104,11 +119,13 @@ BEGIN
104119 )
105120 AND (ns .filter IS NULL OR NEW .data @> ns .filter )
106121 AND
107- -- A subscriber can be notified if the event is in their scope or if they have permission to the resource.
122+ -- A subscriber can be notified if the event is in their scope or if they have permission to the resource,
123+ -- or if the subscription is owned by the project which the event is scoped to.
108124 -- The latter is usually a superset of the former, but the former is trivial to compute so it can help
109125 -- performance to include it.
110126 (NEW .scope_user_id = ns .subscriber_user_id
111127 OR user_has_permission(ns .subscriber_user_id , NEW .resource_id , topic_permission(NEW .topic ))
128+ OR (ns .subscriber_project_id IS NOT NULL AND ns .subscriber_project_id = NEW .project_id )
112129 )
113130 )
114131 LOOP
0 commit comments