From 08362eab9d06ecb41f8004d4e1bddbdf50a7f961 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BF=83=E9=9A=A8=E7=B7=A3=E5=8B=95?= Date: Thu, 25 Sep 2025 22:59:44 +0800 Subject: [PATCH] Optimize the history record function of [One-click configuration] --- database/history.go | 51 ++++++++++++++++++++++++++++----------------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/database/history.go b/database/history.go index e624025c..f86a977f 100644 --- a/database/history.go +++ b/database/history.go @@ -2,6 +2,7 @@ package database import ( "time" + "gorm.io/gorm" // 【中文注释】: 确保 gorm 被导入,以便在函数签名中使用 ) // LinkHistory GORM aodel for link_history table @@ -12,34 +13,47 @@ type LinkHistory struct { CreatedAt time.Time `gorm:"not null"` } -// AddLinkHistory adds a new link record, trims old ones, and ensures data is persisted. +// AddLinkHistory 在一个事务中添加新链接记录并修剪旧记录。 +// 它确保了操作的原子性:所有更改要么全部应用,要么全部回滚。 func AddLinkHistory(record *LinkHistory) error { - // 1. Add the new record - if err := db.Create(record).Error; err != nil { - return err - } + // 【核心修正】: 使用 GORM 的事务功能来包装所有的数据库写入和删除操作。 + // 这样可以确保数据的一致性。 + return db.Transaction(func(tx *gorm.DB) error { + // 1. 添加新记录 + // 【重要】: 在事务内部,必须使用 tx 变量,而不是全局的 db 变量。 + if err := tx.Create(record).Error; err != nil { + return err // 如果这里出错,事务将自动回滚 + } - // 2. Trim old records, keeping only the 10 most recent - var count int64 - db.Model(&LinkHistory{}).Count(&count) - if count > 10 { - limit := int(count) - 10 - var recordsToDelete []LinkHistory - if err := db.Order("created_at asc").Limit(limit).Find(&recordsToDelete).Error; err != nil { + // 2. 修剪旧记录,仅保留最近的 10 条 + var count int64 + // 【重要】: 使用 tx 进行计数 + if err := tx.Model(&LinkHistory{}).Count(&count).Error; err != nil { return err } - if len(recordsToDelete) > 0 { - if err := db.Delete(&recordsToDelete).Error; err != nil { + + if count > 10 { + limit := int(count) - 10 + var recordsToDelete []LinkHistory + // 【重要】: 使用 tx 查找要删除的记录 + if err := tx.Order("created_at asc").Limit(limit).Find(&recordsToDelete).Error; err != nil { return err } + if len(recordsToDelete) > 0 { + // 【重要】: 使用 tx 删除记录 + if err := tx.Delete(&recordsToDelete).Error; err != nil { + return err + } + } } - } - // 【核心修正】: 在所有数据库写入和删除操作完成后, - // 立即在此处调用 Checkpoint,确保本次操作被完整持久化到数据库文件。 - return Checkpoint() + // 【核心修正】: 从此函数中移除了 Checkpoint() 调用。 + // 事务成功后返回 nil,GORM 会自动提交事务。 + return nil + }) } + // GetLinkHistory retrieves the 10 most recent link records func GetLinkHistory() ([]*LinkHistory, error) { var histories []*LinkHistory @@ -49,4 +63,3 @@ func GetLinkHistory() ([]*LinkHistory, error) { } return histories, nil } -