modelRT/database/create_component.go

52 lines
1.5 KiB
Go
Raw Normal View History

// Package database define database operation functions
package database
import (
"context"
"fmt"
"strconv"
"time"
"modelRT/constant"
"modelRT/network"
"modelRT/orm"
"github.com/gofrs/uuid"
"gorm.io/gorm"
)
// CreateComponentIntoDB define create component info of the circuit diagram into DB
func CreateComponentIntoDB(ctx context.Context, tx *gorm.DB, componentInfo network.ComponentCreateInfo) (int64, error) {
cancelCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
globalUUID, err := uuid.FromString(componentInfo.UUID)
if err != nil {
return -1, fmt.Errorf("format uuid from string type failed:%w", err)
}
component := orm.Component{
GlobalUUID: globalUUID,
GridID: strconv.FormatInt(componentInfo.GridID, 10),
ZoneID: strconv.FormatInt(componentInfo.ZoneID, 10),
StationID: strconv.FormatInt(componentInfo.StationID, 10),
PageID: componentInfo.PageID,
Tag: componentInfo.Tag,
ComponentType: componentInfo.ComponentType,
Name: componentInfo.Name,
Context: componentInfo.Context,
Op: componentInfo.Op,
Ts: time.Now(),
}
result := tx.WithContext(cancelCtx).Create(&component)
if result.Error != nil || result.RowsAffected == 0 {
err := result.Error
if result.RowsAffected == 0 {
err = fmt.Errorf("%w:please check insert component slice", constant.ErrInsertRowUnexpected)
}
return -1, fmt.Errorf("insert component info failed:%w", err)
}
return component.ID, nil
}