diff --git a/app/models/user_stat.rb b/app/models/user_stat.rb index 894a888c1f4..6796d9aad5e 100644 --- a/app/models/user_stat.rb +++ b/app/models/user_stat.rb @@ -175,19 +175,23 @@ class UserStat < ActiveRecord::Base # Update denormalized posts_read_count DB.exec(<<~SQL, seen_at: last_seen) + WITH filtered_users AS ( + SELECT id FROM users u + JOIN user_stats ON user_id = u.id + WHERE last_seen_at > :seen_at + AND posts_read_count < 10000 + ) UPDATE user_stats SET posts_read_count = X.c - FROM - (SELECT pt.user_id, - COUNT(*) AS c - FROM users AS u - JOIN post_timings AS pt ON pt.user_id = u.id - JOIN topics t ON t.id = pt.topic_id - WHERE u.last_seen_at > :seen_at AND - t.archetype = 'regular' AND - t.deleted_at IS NULL - GROUP BY pt.user_id) AS X - WHERE X.user_id = user_stats.user_id AND - X.c <> posts_read_count + FROM (SELECT pt.user_id, COUNT(*) as c + FROM filtered_users AS u + JOIN post_timings AS pt ON pt.user_id = u.id + JOIN topics t ON t.id = pt.topic_id + WHERE t.archetype = 'regular' + AND t.deleted_at IS NULL + GROUP BY pt.user_id + ) AS X + WHERE X.user_id = user_stats.user_id + AND X.c <> posts_read_count SQL end diff --git a/spec/models/user_stat_spec.rb b/spec/models/user_stat_spec.rb index c879d301031..8827061dd25 100644 --- a/spec/models/user_stat_spec.rb +++ b/spec/models/user_stat_spec.rb @@ -27,19 +27,18 @@ RSpec.describe UserStat do fab!(:topic) { Fabricate(:topic) } let!(:view) { TopicViewItem.add(topic.id, "127.0.0.1", user.id) } - before { user.update_column :last_seen_at, 1.second.ago } + before do + user.update_column :last_seen_at, 1.second.ago + stat.update_column :topics_entered, 0 + end it "adds one to the topics entered" do - UserStat.update_view_counts - stat.reload - expect(stat.topics_entered).to eq(1) + expect { UserStat.update_view_counts }.to change { stat.reload.topics_entered }.to 1 end it "won't record a second view as a different topic" do TopicViewItem.add(topic.id, "127.0.0.1", user.id) - UserStat.update_view_counts - stat.reload - expect(stat.topics_entered).to eq(1) + expect { UserStat.update_view_counts }.to change { stat.reload.topics_entered }.to 1 end end end @@ -65,12 +64,13 @@ RSpec.describe UserStat do ) end - before { user.update_column :last_seen_at, 1.second.ago } + before do + user.update_column :last_seen_at, 1.second.ago + stat.update_column :posts_read_count, 0 + end it "increases posts_read_count" do - UserStat.update_view_counts - stat.reload - expect(stat.posts_read_count).to eq(1) + expect { UserStat.update_view_counts }.to change { stat.reload.posts_read_count }.to 1 end end end