Skip to content
This repository was archived by the owner on Jul 22, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 19 additions & 17 deletions plugin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -291,23 +291,25 @@ def self.skip_db?

query = <<~SQL
WITH x AS (
SELECT p.user_id, COUNT(DISTINCT st.id) AS solutions
FROM discourse_solved_solved_topics AS st
JOIN posts AS p
ON p.id = st.answer_post_id
AND COALESCE(st.created_at, :since) > :since
AND p.deleted_at IS NULL
JOIN topics AS t
ON t.id = st.topic_id
AND t.archetype <> 'private_message'
AND t.deleted_at IS NULL
JOIN users AS u
ON u.id = p.user_id
WHERE u.id > 0
AND u.active
AND u.silenced_till IS NULL
AND u.suspended_till IS NULL
GROUP BY p.user_id
SELECT users.id AS user_id,
COUNT(DISTINCT st.topic_id) FILTER (WHERE
st.topic_id IS NOT NULL AND
t.id IS NOT NULL AND
t.archetype <> 'private_message' AND
t.deleted_at IS NULL AND
p.deleted_at IS NULL
) AS solutions
FROM users
LEFT JOIN posts p ON p.user_id = users.id
LEFT JOIN discourse_solved_solved_topics st
ON st.answer_post_id = p.id
AND st.created_at >= :since
LEFT JOIN topics t ON t.id = st.topic_id
WHERE users.id > 0
AND users.active
AND users.silenced_till IS NULL
AND users.suspended_till IS NULL
GROUP BY users.id
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have some performance concerns about the new query because it has to join the entire users table against the posts table. The previous query only looped through the discourse_solved_solved_topics which is going to have way less rows as compared to the users table.

To account for users with zero solutions, did you consider just setting the count for all users to zero first in an initial query before filling up the correct count using the original query?

)
UPDATE directory_items di
SET solutions = x.solutions
Expand Down
27 changes: 27 additions & 0 deletions spec/models/directory_item_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,5 +101,32 @@
).solutions,
).to eq(1)
end

context "when refreshing across dates" do
it "updates the user's solution count from 1 to 0" do
freeze_time 40.days.ago
DiscourseSolved.accept_answer!(topic_post1, Discourse.system_user)

DirectoryItem.refresh!

expect(
DirectoryItem.find_by(
user_id: user.id,
period_type: DirectoryItem.period_types[:monthly],
).solutions,
).to eq(1)

unfreeze_time

DirectoryItem.refresh!

expect(
DirectoryItem.find_by(
user_id: user.id,
period_type: DirectoryItem.period_types[:monthly],
).solutions,
).to eq(0)
end
end
end
end