52 lines
2.1 KiB
Go
52 lines
2.1 KiB
Go
package repository
|
|
|
|
import (
|
|
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// ExecutionLogRepository 定义了与执行日志交互的接口。
|
|
// 这为服务层提供了一个清晰的契约,并允许在测试中轻松地进行模拟。
|
|
type ExecutionLogRepository interface {
|
|
CreatePlanExecutionLog(log *models.PlanExecutionLog) error
|
|
UpdatePlanExecutionLog(log *models.PlanExecutionLog) error
|
|
CreateTaskExecutionLogsInBatch(logs []*models.TaskExecutionLog) error
|
|
UpdateTaskExecutionLog(log *models.TaskExecutionLog) error
|
|
}
|
|
|
|
// executionLogRepository 是使用 GORM 的具体实现。
|
|
type executionLogRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
// NewExecutionLogRepository 创建一个新的执行日志仓库。
|
|
// 它接收一个 GORM DB 实例作为依赖。
|
|
func NewExecutionLogRepository(db *gorm.DB) ExecutionLogRepository {
|
|
return &executionLogRepository{db: db}
|
|
}
|
|
|
|
// CreatePlanExecutionLog 为一次计划执行创建一条新的日志条目。
|
|
func (r *executionLogRepository) CreatePlanExecutionLog(log *models.PlanExecutionLog) error {
|
|
return r.db.Create(log).Error
|
|
}
|
|
|
|
// UpdatePlanExecutionLog 使用 Save 方法全量更新一个计划执行日志。
|
|
// GORM 的 Save 会自动根据主键是否存在来决定是执行 UPDATE 还是 INSERT。
|
|
// 在这里,我们期望传入的对象一定包含一个有效的 ID。
|
|
func (r *executionLogRepository) UpdatePlanExecutionLog(log *models.PlanExecutionLog) error {
|
|
return r.db.Save(log).Error
|
|
}
|
|
|
|
// CreateTaskExecutionLogsInBatch 在一次数据库调用中创建多个任务执行日志条目。
|
|
// 这是“预写日志”步骤的关键。
|
|
func (r *executionLogRepository) CreateTaskExecutionLogsInBatch(logs []*models.TaskExecutionLog) error {
|
|
// GORM 的 Create 传入一个切片指针会执行批量插入。
|
|
return r.db.Create(&logs).Error
|
|
}
|
|
|
|
// UpdateTaskExecutionLog 使用 Save 方法全量更新一个任务执行日志。
|
|
// 这种方式代码更直观,上层服务可以直接修改模型对象后进行保存。
|
|
func (r *executionLogRepository) UpdateTaskExecutionLog(log *models.TaskExecutionLog) error {
|
|
return r.db.Save(log).Error
|
|
}
|