Optimize the history record function of [One-click configuration]
This commit is contained in:
parent
de7a45656c
commit
08362eab9d
@ -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 {
|
||||
// 【核心修正】: 使用 GORM 的事务功能来包装所有的数据库写入和删除操作。
|
||||
// 这样可以确保数据的一致性。
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
// 1. 添加新记录
|
||||
// 【重要】: 在事务内部,必须使用 tx 变量,而不是全局的 db 变量。
|
||||
if err := tx.Create(record).Error; err != nil {
|
||||
return err // 如果这里出错,事务将自动回滚
|
||||
}
|
||||
|
||||
// 2. 修剪旧记录,仅保留最近的 10 条
|
||||
var count int64
|
||||
// 【重要】: 使用 tx 进行计数
|
||||
if err := tx.Model(&LinkHistory{}).Count(&count).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 {
|
||||
// 【重要】: 使用 tx 查找要删除的记录
|
||||
if err := tx.Order("created_at asc").Limit(limit).Find(&recordsToDelete).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(recordsToDelete) > 0 {
|
||||
if err := db.Delete(&recordsToDelete).Error; err != nil {
|
||||
// 【重要】: 使用 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
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user