From 17e75cc690d65343057d725e0076a58130fedf56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AA=80=E8=BD=B6=E6=AD=A5=E6=A3=8B?= <57583509+oissevalt@users.noreply.github.com> Date: Sat, 19 Oct 2024 11:13:01 +0100 Subject: [PATCH] Refactor function to return last N records --- dice/ext_log.go | 4 ++-- dice/model/log.go | 13 +++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/dice/ext_log.go b/dice/ext_log.go index 3b629fc2f..5f71d55cf 100644 --- a/dice/ext_log.go +++ b/dice/ext_log.go @@ -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) diff --git a/dice/model/log.go b/dice/model/log.go index fc7e350a1..1785f551e 100644 --- a/dice/model/log.go +++ b/dice/model/log.go @@ -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 }