// Package database define database operation functions package database import ( "context" "fmt" "time" "modelRT/constant" "modelRT/model" "modelRT/network" "github.com/gofrs/uuid" jsoniter "github.com/json-iterator/go" "gorm.io/gorm" ) // UpdateModelIntoDB define update component model params of the circuit diagram into DB func UpdateModelIntoDB(ctx context.Context, tx *gorm.DB, componentInfos []network.ComponentUpdateInfo) error { cancelCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() for _, componentInfo := range componentInfos { modelStruct := model.SelectModelByType(componentInfo.ComponentType) if modelStruct == nil { return fmt.Errorf("can not get component model by model type %d", componentInfo.ComponentType) } err := jsoniter.Unmarshal([]byte(componentInfo.Params), modelStruct) if err != nil { return fmt.Errorf("unmarshal component info by component struct %s,failed", model.SelectModelNameByType(componentInfo.ComponentType)) } globalUUID, err := uuid.FromString(componentInfo.UUID) if err != nil { return fmt.Errorf("format uuid from string type failed:%w", err) } modelStruct.SetUUID(globalUUID) result := tx.Model(modelStruct).WithContext(cancelCtx).Where("uuid = ?", componentInfo.UUID).Updates(modelStruct) if result.Error != nil || result.RowsAffected == 0 { err := result.Error if result.RowsAffected == 0 { err = fmt.Errorf("%w:please check where conditions", constant.ErrUpdateRowZero) } return err } } return nil }