From 04b8cd5c957e7f63c533e77681249a434cfe5082 Mon Sep 17 00:00:00 2001 From: Sam Date: Thu, 16 May 2013 17:50:14 +1000 Subject: [PATCH] consistency check, need to also ensure delete cleans stuff up, maybe make notifications trashable --- app/models/notification.rb | 11 +++++++++++ lib/jobs/ensure_db_consistency.rb | 1 + spec/models/notification_spec.rb | 23 +++++++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/app/models/notification.rb b/app/models/notification.rb index d2142c592a1..fd94cfbec82 100644 --- a/app/models/notification.rb +++ b/app/models/notification.rb @@ -13,6 +13,17 @@ class Notification < ActiveRecord::Base after_save :refresh_notification_count after_destroy :refresh_notification_count + def self.ensure_consistency! + Notification.exec_sql(" + DELETE FROM Notifications n WHERE notification_type = :id AND + NOT EXISTS( + SELECT 1 FROM posts p + JOIN topics t ON t.id = p.topic_id + WHERE p.deleted_at is null AND t.deleted_at IS NULL + AND p.post_number = n.post_number AND t.id = n.topic_id + )" , id: Notification.types[:private_message]) + end + def self.types @types ||= Enum.new( :mentioned, :replied, :quoted, :edited, :liked, :private_message, diff --git a/lib/jobs/ensure_db_consistency.rb b/lib/jobs/ensure_db_consistency.rb index 154fdf62298..9030889874c 100644 --- a/lib/jobs/ensure_db_consistency.rb +++ b/lib/jobs/ensure_db_consistency.rb @@ -5,6 +5,7 @@ module Jobs TopicUser.ensure_consistency! UserVisit.ensure_consistency! Group.refresh_automatic_groups! + Notification.ensure_consistency! end end end diff --git a/spec/models/notification_spec.rb b/spec/models/notification_spec.rb index d43b8995a64..d00a824b23b 100644 --- a/spec/models/notification_spec.rb +++ b/spec/models/notification_spec.rb @@ -201,4 +201,27 @@ describe Notification do end end + describe 'ensure consistency' do + it 'deletes notifications if post is missing or deleted' do + + ActiveRecord::Base.observers.disable :all + p = Fabricate(:post) + p2 = Fabricate(:post) + + Notification.create!(read: false, user_id: p.user_id, topic_id: p.topic_id, post_number: p.post_number, data: '[]', + notification_type: Notification.types[:private_message]) + Notification.create!(read: false, user_id: p2.user_id, topic_id: p2.topic_id, post_number: p2.post_number, data: '[]', + notification_type: Notification.types[:private_message]) + + Notification.create!(read: false, user_id: p2.user_id, topic_id: p2.topic_id, post_number: p2.post_number, data: '[]', + notification_type: Notification.types[:liked]) + p2.trash! + + # we may want to make notification "trashable" but for now we nuke pm notifications from deleted topics/posts + Notification.ensure_consistency! + + Notification.count.should == 2 + end + end + end