modelRT/database/update_topologic.go

50 lines
1.8 KiB
Go
Raw Normal View History

// Package database define database operation functions
package database
import (
"context"
"fmt"
"time"
"modelRT/constant"
"modelRT/network"
"modelRT/orm"
"gorm.io/gorm"
)
// UpdateTopologicIntoDB define update topologic info of the circuit diagram query by pageID and topologic info
func UpdateTopologicIntoDB(ctx context.Context, tx *gorm.DB, pageID int64, changeInfo network.TopologicUUIDChangeInfos) error {
var result *gorm.DB
cancelCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
switch changeInfo.ChangeType {
case constant.UUIDFromChangeType:
result = tx.WithContext(cancelCtx).Model(&orm.Topologic{}).Where("page_id = ? and uuid_from = ? and uuid_to = ?", pageID, changeInfo.OldUUIDFrom, changeInfo.OldUUIDTo).Updates(orm.Topologic{UUIDFrom: changeInfo.NewUUIDFrom})
case constant.UUIDToChangeType:
result = tx.WithContext(cancelCtx).Model(&orm.Topologic{}).Where("page_id = ? and uuid_from = ? and uuid_to = ?", pageID, changeInfo.OldUUIDFrom, changeInfo.OldUUIDTo).Updates(&orm.Topologic{UUIDTo: changeInfo.NewUUIDTo})
case constant.UUIDAddChangeType:
topologic := orm.Topologic{
PageID: pageID,
Flag: changeInfo.Flag,
UUIDFrom: changeInfo.NewUUIDFrom,
UUIDTo: changeInfo.OldUUIDFrom,
Comment: changeInfo.Comment,
}
result = tx.WithContext(cancelCtx).Create(&topologic)
}
// update 检查 result.RowsAffected 结果时,RowsAffected==0
// 可能存在 result.Error 为 nil 的情况,谨慎使用 result.Error.Error()
// 函数,避免造成空指针问题
if result.Error != nil || result.RowsAffected == 0 {
err := result.Error
if result.RowsAffected == 0 {
err = fmt.Errorf("%w:please check update topologic where conditions", constant.ErrUpdateRowZero)
}
return fmt.Errorf("insert or update topologic link failed:%w", err)
}
return nil
}