// Package database define database operation functions package database import ( "context" "fmt" "time" "modelRT/common/errcode" "modelRT/constants" "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 constants.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 constants.UUIDToChangeType: var delTopologic orm.Topologic result = tx.WithContext(cancelCtx).Model(&orm.Topologic{}).Where("page_id = ? and uuid_to = ?", pageID, changeInfo.NewUUIDTo).Find(&delTopologic) if result.Error != nil { return fmt.Errorf("find topologic link by new_uuid_to failed:%w", result.Error) } if result.RowsAffected == 1 { // delete old topologic link result = tx.WithContext(cancelCtx).Where("id = ?", delTopologic.ID).Delete(&delTopologic) if result.Error != nil || result.RowsAffected == 0 { err := result.Error if result.RowsAffected == 0 { err = fmt.Errorf("%w:please check delete topologic where conditions", errcode.ErrDeleteRowZero) } return fmt.Errorf("del old topologic link by new_uuid_to failed:%w", err) } } 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 constants.UUIDAddChangeType: topologic := orm.Topologic{ Flag: changeInfo.Flag, UUIDFrom: changeInfo.NewUUIDFrom, UUIDTo: changeInfo.NewUUIDTo, 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", errcode.ErrUpdateRowZero) } return fmt.Errorf("insert or update topologic link failed:%w", err) } return nil }