~emersion/goguma

5027675b754dc1a74d2f18a005b8644308af1c5a — Simon Ser 16 days ago 4a4834a
database: fix and optimize DB.listMessagesBefore()

The previous assumption was that IDs of older messages were smaller
than IDs of newer messages. This isn't true in general: scrolling
up will fetch chat history from the server and insert these old
messages with new IDs.

Let's stop using IDs altogether and purely rely on time (like
DB.listMessages() was doing).

As a nice side effect we can also take better advantage of the
index_message_buffer_time index:

    SEARCH Message USING INDEX index_message_buffer_time (buffer=? AND time<?)

ie, we no longer need to put all of the messages for that buffer in
a separate temporary b-tree for sorting.

Fixes: 60ddee67aeef ("Load messages in chunks from the DB")
1 files changed, 3 insertions(+), 3 deletions(-)

M lib/database.dart
M lib/database.dart => lib/database.dart +3 -3
@@ 564,14 564,14 @@ class DB {
		var where = 'buffer = ?';
		var params = [buffer];
		if (msg != null) {
			where += ' AND id < ?';
			params.add(msg);
			where += ' AND id != ? AND time <= (SELECT time FROM Message WHERE id = ?)';
			params += [msg, msg];
		}
		var entries = await _db.rawQuery('''
			SELECT id, time, buffer, raw
			FROM Message
			WHERE $where
			ORDER BY id DESC LIMIT ?
			ORDER BY time DESC LIMIT ?
		'''
		, [...params, limit]);
		var l = entries.map((m) => MessageEntry.fromMap(m)).toList();