From 83c3c7e1db81c0e51e500d28df36a03227161a68 Mon Sep 17 00:00:00 2001 From: Brendan Abolivier Date: Wed, 7 Nov 2018 19:12:23 +0000 Subject: [PATCH] Fix the ordering of events in a response to /sync (#588) --- .../dendrite/syncapi/storage/output_room_events_table.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/github.com/matrix-org/dendrite/syncapi/storage/output_room_events_table.go b/src/github.com/matrix-org/dendrite/syncapi/storage/output_room_events_table.go index ceb2601f..035db988 100644 --- a/src/github.com/matrix-org/dendrite/syncapi/storage/output_room_events_table.go +++ b/src/github.com/matrix-org/dendrite/syncapi/storage/output_room_events_table.go @@ -17,6 +17,7 @@ package storage import ( "context" "database/sql" + "sort" "github.com/matrix-org/dendrite/roomserver/api" @@ -65,7 +66,7 @@ const selectEventsSQL = "" + const selectRecentEventsSQL = "" + "SELECT id, event_json, device_id, transaction_id FROM syncapi_output_room_events" + " WHERE room_id = $1 AND id > $2 AND id <= $3" + - " ORDER BY id ASC LIMIT $4" + " ORDER BY id DESC LIMIT $4" const selectMaxEventIDSQL = "" + "SELECT MAX(id) FROM syncapi_output_room_events" @@ -234,6 +235,12 @@ func (s *outputRoomEventsStatements) selectRecentEvents( if err != nil { return nil, err } + // The events need to be returned from oldest to latest, which isn't + // necessary the way the SQL query returns them, so a sort is necessary to + // ensure the events are in the right order in the slice. + sort.SliceStable(events, func(i int, j int) bool { + return events[i].streamPosition < events[j].streamPosition + }) return events, nil }