Skip to content

Commit

Permalink
Refactor function to return last N records
Browse files Browse the repository at this point in the history
  • Loading branch information
oissevalt committed Oct 19, 2024
1 parent bd13a15 commit 17e75cc
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
4 changes: 2 additions & 2 deletions dice/ext_log.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,9 @@ func RegisterBuiltinExtLog(self *Dice) {

logEnabledPrompt := DiceFormatTmpl(ctx, "日志:记录_开启_成功")
// TODO: 到这里相当于全文 query 了两遍日志。可以优化吗?
lastRecord, err := model.LogGetLastLine(ctx.Dice.DBLogs, group.GroupID, name)
lastLines, err := model.LogGetLastLineN(ctx.Dice.DBLogs, group.GroupID, name, 1)
if err == nil {
logEnabledPrompt = fmt.Sprintf("[CQ:reply,id=%v] %s", lastRecord.RawMsgID, logEnabledPrompt)
logEnabledPrompt = fmt.Sprintf("[CQ:reply,id=%v] %s", lastLines[0].RawMsgID, logEnabledPrompt)
}

ReplyToSender(ctx, msg, logEnabledPrompt)
Expand Down
13 changes: 7 additions & 6 deletions dice/model/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -513,22 +513,23 @@ WHERE log_id = ? AND raw_msg_id = ?`, newContent, logID, rid)
return nil
}

func LogGetLastLine(db *sqlx.DB, groupID, logName string) (*LogOneItem, error) {
func LogGetLastLineN(db *sqlx.DB, groupID, logName string, n int) ([]*LogOneItem, error) {
logID, err := LogGetIDByGroupIDAndName(db, groupID, logName)
if err != nil {
return nil, err
}

const recentLineQuery = `
const lineQuery = `
SELECT id, nickname, im_userid, time, message, is_dice, command_id, command_info, raw_msg_id, user_uniform_id
FROM log_items
WHERE log_id=$1
ORDER BY time DESC
LIMIT 1`
LIMIT $2`

var record LogOneItem
if err = db.Get(&record, recentLineQuery, logID); err != nil {
records := make([]*LogOneItem, 0, n)
if err = db.Select(&records, lineQuery, logID, n); err != nil {
return nil, err
}
return &record, nil

return records, nil
}

0 comments on commit 17e75cc

Please sign in to comment.