增加AreaControllerProperties

This commit is contained in:
2025-12-01 17:29:28 +08:00
parent 7ec9fb3f0b
commit 1e685340f8
3 changed files with 52 additions and 0 deletions

View File

@@ -18,6 +18,8 @@ type AreaControllerRepository interface {
Create(ctx context.Context, ac *models.AreaController) error
ListAll(ctx context.Context) ([]*models.AreaController, error)
Update(ctx context.Context, ac *models.AreaController) error
// UpdateFirmwareVersion 更新指定ID的区域主控的固件版本号。
UpdateFirmwareVersion(ctx context.Context, id uint32, version string) error
Delete(ctx context.Context, id uint32) error
// IsAreaControllerUsedByTasks 检查区域主控是否被特定任务类型使用,可以忽略指定任务类型
IsAreaControllerUsedByTasks(ctx context.Context, areaControllerID uint32, ignoredTaskTypes []models.TaskType) (bool, error)
@@ -59,6 +61,25 @@ func (r *gormAreaControllerRepository) Update(ctx context.Context, ac *models.Ar
return r.db.WithContext(repoCtx).Save(ac).Error
}
// UpdateFirmwareVersion 使用 jsonb_set 函数原子性地更新 properties 字段中的固件版本号。
func (r *gormAreaControllerRepository) UpdateFirmwareVersion(ctx context.Context, id uint32, version string) error {
repoCtx := logs.AddFuncName(ctx, r.ctx, "UpdateFirmwareVersion")
// 使用 gorm.Expr 包装 PostgreSQL 的 jsonb_set 函数
// jsonb_set(properties, '{firmware_version}', '"new_version"', true)
// 注意jsonb_set 的第三个参数需要是有效的 JSON 值,所以字符串需要被双引号包围。
jsonbExpr := gorm.Expr(`jsonb_set(COALESCE(properties, '{}'::jsonb), '{firmware_version}', ?::jsonb)`, fmt.Sprintf(`"%s"`, version))
result := r.db.WithContext(repoCtx).Model(&models.AreaController{}).Where("id = ?", id).Update("properties", jsonbExpr)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return fmt.Errorf("更新固件版本失败未找到ID为 %d 的区域主控", id)
}
return nil
}
// Delete 删除一个 AreaController 记录。
func (r *gormAreaControllerRepository) Delete(ctx context.Context, id uint32) error {
repoCtx := logs.AddFuncName(ctx, r.ctx, "Delete")