diff --git a/app/jobs/scheduled/ensure_db_consistency.rb b/app/jobs/scheduled/ensure_db_consistency.rb index 83896fb2773..bb1bb8e6b16 100644 --- a/app/jobs/scheduled/ensure_db_consistency.rb +++ b/app/jobs/scheduled/ensure_db_consistency.rb @@ -8,6 +8,7 @@ module Jobs Group.refresh_automatic_groups! Notification.ensure_consistency! UserAction.ensure_consistency! + TopicFeaturedUsers.ensure_consistency! UserStat.update_view_counts(13.hours.ago) end end diff --git a/app/models/topic_featured_users.rb b/app/models/topic_featured_users.rb index 1efb4cd48ce..45771d28e85 100644 --- a/app/models/topic_featured_users.rb +++ b/app/models/topic_featured_users.rb @@ -24,6 +24,50 @@ class TopicFeaturedUsers topic.featured_user4_id].uniq.compact end + def self.ensure_consistency! + + sql = < t.user_id AND + p.user_id <> t.last_post_user_id + GROUP BY t.id, p.user_id +) + +UPDATE topics tt +SET + featured_user1_id = featured_user1, + featured_user2_id = featured_user2, + featured_user3_id = featured_user3, + featured_user4_id = featured_user4 +FROM ( + SELECT + c.id, + MAX(case when c.rank = 1 then c.user_id end) featured_user1, + MAX(case when c.rank = 2 then c.user_id end) featured_user2, + MAX(case when c.rank = 3 then c.user_id end) featured_user3, + MAX(case when c.rank = 4 then c.user_id end) featured_user4 + FROM cte as c + WHERE c.rank <= 4 + GROUP BY c.id +) x +WHERE x.id = tt.id AND +( + COALESCE(featured_user1_id,-99) <> COALESCE(featured_user1,-99) OR + COALESCE(featured_user2_id,-99) <> COALESCE(featured_user2,-99) OR + COALESCE(featured_user3_id,-99) <> COALESCE(featured_user3,-99) OR + COALESCE(featured_user4_id,-99) <> COALESCE(featured_user4,-99) +) +SQL + + Topic.exec_sql(sql) + end + private def keys(args) diff --git a/spec/models/topic_featured_users_spec.rb b/spec/models/topic_featured_users_spec.rb new file mode 100644 index 00000000000..2603d965087 --- /dev/null +++ b/spec/models/topic_featured_users_spec.rb @@ -0,0 +1,31 @@ +require 'spec_helper' + +describe TopicFeaturedUsers do + it 'ensures consistenct' do + + t = Fabricate(:topic) + Fabricate(:post, topic_id: t.id, user_id: t.user_id) + p2 = Fabricate(:post, topic_id: t.id) + Fabricate(:post, topic_id: t.id, user_id: p2.user_id) + p4 = Fabricate(:post, topic_id: t.id) + p5 = Fabricate(:post, topic_id: t.id) + + t.update_columns(featured_user1_id: 66, + featured_user2_id: 70, + featured_user3_id: 12, + featured_user4_id: 7, + last_post_user_id: p5.user_id + ) + + TopicFeaturedUsers.ensure_consistency! + + t.reload + + t.featured_user1_id.should == p2.user_id + t.featured_user2_id.should == p4.user_id + t.featured_user3_id.should == nil + t.featured_user4_id.should == nil + + + end +end