Skip to content

Commit e84e6a8

Browse files
committed
Combine line count and last record query
1 parent bd13a15 commit e84e6a8

File tree

2 files changed

+34
-9
lines changed

2 files changed

+34
-9
lines changed

dice/ext_log.go

+3-9
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ func RegisterBuiltinExtLog(self *Dice) {
196196
}
197197

198198
if name != "" {
199-
lines, exists := model.LogLinesCountGet(ctx.Dice.DBLogs, group.GroupID, name)
199+
lineCount, lastLine, exists := model.LogGetCountAndLastLine(ctx.Dice.DBLogs, group.GroupID, name)
200200

201201
if exists {
202202
if groupNotActiveCheck() {
@@ -208,15 +208,9 @@ func RegisterBuiltinExtLog(self *Dice) {
208208
group.UpdatedAtTime = time.Now().Unix()
209209

210210
VarSetValueStr(ctx, "$t记录名称", name)
211-
VarSetValueInt64(ctx, "$t当前记录条数", lines)
212-
213-
logEnabledPrompt := DiceFormatTmpl(ctx, "日志:记录_开启_成功")
214-
// TODO: 到这里相当于全文 query 了两遍日志。可以优化吗?
215-
lastRecord, err := model.LogGetLastLine(ctx.Dice.DBLogs, group.GroupID, name)
216-
if err == nil {
217-
logEnabledPrompt = fmt.Sprintf("[CQ:reply,id=%v] %s", lastRecord.RawMsgID, logEnabledPrompt)
218-
}
211+
VarSetValueInt64(ctx, "$t当前记录条数", lineCount)
219212

213+
logEnabledPrompt := fmt.Sprintf("[CQ:reply,id=%v] %s", lastLine.RawMsgID, DiceFormatTmpl(ctx, "日志:记录_开启_成功"))
220214
ReplyToSender(ctx, msg, logEnabledPrompt)
221215
} else {
222216
VarSetValueStr(ctx, "$t记录名称", name)

dice/model/log.go

+31
Original file line numberDiff line numberDiff line change
@@ -532,3 +532,34 @@ LIMIT 1`
532532
}
533533
return &record, nil
534534
}
535+
536+
// LogGetCountAndLastLine performs a specialised union search.
537+
func LogGetCountAndLastLine(db *sqlx.DB, groupID, logName string) (lineCount int64, lastLine *LogOneItem, exists bool) {
538+
logID, err := LogGetIDByGroupIDAndName(db, groupID, logName)
539+
if err != nil {
540+
return
541+
}
542+
543+
const filterQuery = `
544+
WITH filtered AS (
545+
SELECT id, nickname, im_userid, time, message, is_dice, command_id, command_info, raw_msg_id, user_uniform_id
546+
FROM log_items
547+
WHERE log_id=$1 AND removed IS NULL
548+
)
549+
SELECT COUNT(*) OVER () AS line_count, *
550+
FROM filtered
551+
ORDER BY time DESC
552+
LIMIT 1`
553+
554+
type QueryResult struct {
555+
LineCount int64 `db:"line_count"`
556+
LogOneItem
557+
}
558+
559+
var result QueryResult
560+
if err = db.Get(&result, filterQuery, logID); err != nil {
561+
return
562+
}
563+
564+
return result.LineCount, &result.LogOneItem, true
565+
}

0 commit comments

Comments
 (0)