2024-12-05 14:57:23 +08:00
|
|
|
// Package database define database operation functions
|
|
|
|
|
package database
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
|
|
|
|
"time"
|
|
|
|
|
|
2025-06-13 15:34:49 +08:00
|
|
|
"modelRT/common/errcode"
|
2024-12-05 14:57:23 +08:00
|
|
|
"modelRT/model"
|
|
|
|
|
|
|
|
|
|
jsoniter "github.com/json-iterator/go"
|
|
|
|
|
"gorm.io/gorm"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// CreateModelIntoDB define create component model params of the circuit diagram into DB
|
2024-12-30 16:39:11 +08:00
|
|
|
func CreateModelIntoDB(ctx context.Context, tx *gorm.DB, componentID int64, componentType int, modelParas string) error {
|
2024-12-05 14:57:23 +08:00
|
|
|
cancelCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
|
|
|
defer cancel()
|
2024-12-30 16:39:11 +08:00
|
|
|
modelStruct := model.SelectModelByType(componentType)
|
|
|
|
|
modelStruct.SetComponentID(componentID)
|
|
|
|
|
err := jsoniter.Unmarshal([]byte(modelParas), modelStruct)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("unmarshal component model params failed:%w", err)
|
|
|
|
|
}
|
2024-12-05 14:57:23 +08:00
|
|
|
|
2024-12-30 16:39:11 +08:00
|
|
|
result := tx.Model(modelStruct).WithContext(cancelCtx).Create(modelStruct)
|
|
|
|
|
if result.Error != nil || result.RowsAffected == 0 {
|
|
|
|
|
err := result.Error
|
|
|
|
|
if result.RowsAffected == 0 {
|
2025-06-13 15:34:49 +08:00
|
|
|
err = fmt.Errorf("%w:please check insert model params", errcode.ErrInsertRowUnexpected)
|
2024-12-05 14:57:23 +08:00
|
|
|
}
|
2024-12-30 16:39:11 +08:00
|
|
|
return fmt.Errorf("insert component model params into table %s failed:%w", modelStruct.ReturnTableName(), err)
|
2024-12-05 14:57:23 +08:00
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|