modelRT/database/create_model_info.go

37 lines
1.1 KiB
Go

// Package database define database operation functions
package database
import (
"context"
"fmt"
"time"
"modelRT/common/errcode"
"modelRT/model"
jsoniter "github.com/json-iterator/go"
"gorm.io/gorm"
)
// CreateModelIntoDB define create component model params of the circuit diagram into DB
func CreateModelIntoDB(ctx context.Context, tx *gorm.DB, componentID int64, componentType int, modelParas string) error {
cancelCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
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)
}
result := tx.Model(modelStruct).WithContext(cancelCtx).Create(modelStruct)
if result.Error != nil || result.RowsAffected == 0 {
err := result.Error
if result.RowsAffected == 0 {
err = fmt.Errorf("%w:please check insert model params", errcode.ErrInsertRowUnexpected)
}
return fmt.Errorf("insert component model params into table %s failed:%w", modelStruct.ReturnTableName(), err)
}
return nil
}