FIX: Error when loading a channel with threading enabled but no threads (#22434)

Without this fix, the following error is raised:

```
ActiveRecord::StatementInvalid:
  PG::SyntaxError: ERROR:  syntax error at or near ")"
  LINE 4:   WHERE thread_id IN ()
```
This commit is contained in:
Alan Guo Xiang Tan 2023-07-05 14:33:49 +08:00 committed by GitHub
parent 96b20077d9
commit 1e26a521c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 17 deletions

View File

@ -84,24 +84,26 @@ module Chat
threads = unread_threads + read_threads threads = unread_threads + read_threads
last_replies = if threads.present?
Chat::Message last_replies =
.strict_loading Chat::Message
.includes(:user, :uploads) .strict_loading
.from(<<~SQL) .includes(:user, :uploads)
( .from(<<~SQL)
SELECT thread_id, MAX(created_at) AS latest_created_at, MAX(id) AS latest_message_id (
FROM chat_messages SELECT thread_id, MAX(created_at) AS latest_created_at, MAX(id) AS latest_message_id
WHERE thread_id IN (#{threads.map(&:id).join(",")}) FROM chat_messages
GROUP BY thread_id WHERE thread_id IN (#{threads.map(&:id).join(",")})
) AS last_replies_subquery GROUP BY thread_id
SQL ) AS last_replies_subquery
.joins( SQL
"INNER JOIN chat_messages ON chat_messages.id = last_replies_subquery.latest_message_id", .joins(
) "INNER JOIN chat_messages ON chat_messages.id = last_replies_subquery.latest_message_id",
.index_by(&:thread_id) )
.index_by(&:thread_id)
threads.each { |thread| thread.last_reply = last_replies[thread.id] } threads.each { |thread| thread.last_reply = last_replies[thread.id] }
end
threads threads
end end

View File

@ -10,6 +10,7 @@ RSpec.describe Chat::LookupChannelThreads do
fab!(:current_user) { Fabricate(:user) } fab!(:current_user) { Fabricate(:user) }
fab!(:channel) { Fabricate(:chat_channel, threading_enabled: true) } fab!(:channel) { Fabricate(:chat_channel, threading_enabled: true) }
fab!(:channel_with_no_threads) { Fabricate(:chat_channel, threading_enabled: true) }
fab!(:thread_1) { Fabricate(:chat_thread, channel: channel) } fab!(:thread_1) { Fabricate(:chat_thread, channel: channel) }
fab!(:thread_2) { Fabricate(:chat_thread, channel: channel) } fab!(:thread_2) { Fabricate(:chat_thread, channel: channel) }
fab!(:thread_3) { Fabricate(:chat_thread, channel: channel) } fab!(:thread_3) { Fabricate(:chat_thread, channel: channel) }
@ -32,6 +33,12 @@ RSpec.describe Chat::LookupChannelThreads do
end end
end end
it "does not return any threads when a channel has no threads" do
expect(
described_class.call(channel_id: channel_with_no_threads.id, guardian:).threads,
).to eq([])
end
context "when all steps pass" do context "when all steps pass" do
before do before do
msg_1 = msg_1 =