FIX: Ensure order when moving chat messages to another channel (#21447)

What is the problem?

Previously, this was the query used to move change messages into another
channel.

```
INSERT INTO chat_messages(
  chat_channel_id, user_id, last_editor_id, message, cooked, cooked_version, created_at, updated_at
)
SELECT :destination_channel_id,
        user_id,
        last_editor_id,
        message,
        cooked,
        cooked_version,
        CLOCK_TIMESTAMP(),
        CLOCK_TIMESTAMP()
FROM chat_messages
WHERE id IN (:message_ids)
RETURNING id
```

The problem is that this incorrectly assumes that the insertion will be based on the order of `message_ids`. However, that
is not the case as PostgreSQL provides no such guarantee. Instead we need to explicitly order the messages to ensure
the right order of insertion.

This problem was discovered by a flaky test which exposed the non-guarantee order of insertion.
This commit is contained in:
Alan Guo Xiang Tan 2023-05-09 10:37:12 +08:00 committed by GitHub
parent 0c8d3f8542
commit 9c39053d6f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -111,6 +111,7 @@ module Chat
message_ids: @ordered_source_message_ids,
destination_channel_id: destination_channel.id,
}
moved_message_ids = DB.query_single(<<~SQL, query_args)
INSERT INTO chat_messages(
chat_channel_id, user_id, last_editor_id, message, cooked, cooked_version, created_at, updated_at
@ -125,6 +126,7 @@ module Chat
CLOCK_TIMESTAMP()
FROM chat_messages
WHERE id IN (:message_ids)
ORDER BY created_at ASC, id ASC
RETURNING id
SQL