// 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" ) // CreateModelIntoDB define create component model params of the circuit diagram into DB func CreateModelIntoDB(ctx context.Context, tx *gorm.DB, componentInfos []network.ComponentCreateInfo) error { cancelCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() for _, componentInfo := range componentInfos { modelStruct := model.SelectModelByType(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) err = jsoniter.Unmarshal([]byte(componentInfo.Params), 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", constant.ErrInsertRowUnexpected) } return fmt.Errorf("insert component model params into table %s failed:%w", modelStruct.ReturnTableName(), err) } } return nil }