Refactor message retrieval logic to improve pagination and ordering
- Update GetMessages function to ensure that when a limit is specified, the most recent messages are retrieved in descending order and then reversed for chronological output. - Adjust pagination handling to apply a large limit when only an offset is provided, maintaining clarity in message retrieval. - Enhance query ordering to prioritize message creation time and sequence for consistent results.
This commit is contained in:
parent
ea9e070f29
commit
6c81bab8f2
1 changed files with 17 additions and 7 deletions
|
|
@ -140,20 +140,24 @@ func (store *Xun) GetMessages(chatID string, filter types.MessageFilter) ([]*typ
|
|||
qb.Where("type", filter.Type)
|
||||
}
|
||||
|
||||
// Apply pagination (MySQL requires LIMIT when using OFFSET)
|
||||
// When a Limit is specified we want the N most-recent messages (not the
|
||||
// N oldest). Strategy: query DESC to get the latest rows, then reverse
|
||||
// the slice so the caller receives them in chronological (ASC) order.
|
||||
needReverse := false
|
||||
if filter.Limit > 0 {
|
||||
qb.Limit(filter.Limit)
|
||||
if filter.Offset > 0 {
|
||||
qb.Offset(filter.Offset)
|
||||
}
|
||||
} else if filter.Offset > 0 {
|
||||
// If only offset is specified, use a large limit
|
||||
qb.Limit(1000000).Offset(filter.Offset)
|
||||
qb.OrderBy("id", "desc")
|
||||
needReverse = true
|
||||
} else {
|
||||
if filter.Offset > 0 {
|
||||
qb.Limit(1000000).Offset(filter.Offset)
|
||||
}
|
||||
qb.OrderBy("id", "asc")
|
||||
}
|
||||
|
||||
// Order by created_at first, then by sequence within the same request
|
||||
qb.OrderBy("created_at", "asc").OrderBy("sequence", "asc")
|
||||
|
||||
rows, err := qb.Get()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -173,6 +177,12 @@ func (store *Xun) GetMessages(chatID string, filter types.MessageFilter) ([]*typ
|
|||
messages = append(messages, msg)
|
||||
}
|
||||
|
||||
if needReverse {
|
||||
for i, j := 0, len(messages)-1; i < j; i, j = i+1, j-1 {
|
||||
messages[i], messages[j] = messages[j], messages[i]
|
||||
}
|
||||
}
|
||||
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue