81 lines
2.2 KiB
Go
81 lines
2.2 KiB
Go
// Package database define database operation functions
|
|
package database
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"modelRT/orm"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func queryFirstByID(ctx context.Context, tx *gorm.DB, id any, dest any) error {
|
|
result := tx.WithContext(ctx).Where("id = ?", id).First(dest)
|
|
return result.Error
|
|
}
|
|
|
|
func queryFirstByTag(ctx context.Context, tx *gorm.DB, tagName any, dest any) error {
|
|
result := tx.WithContext(ctx).Where("tagname = ?", tagName).First(dest)
|
|
return result.Error
|
|
}
|
|
|
|
// QueryNodeInfoByID return the result of query circuit diagram node info by id and level from postgresDB
|
|
func QueryNodeInfoByID(ctx context.Context, tx *gorm.DB, id int64, level int) (orm.CircuitDiagramNodeInterface, orm.CircuitDiagramNodeInterface, error) {
|
|
// 设置 Context 超时
|
|
cancelCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
|
|
var currentNodeInfo orm.CircuitDiagramNodeInterface
|
|
var previousNodeInfo orm.CircuitDiagramNodeInterface
|
|
var err error
|
|
|
|
switch level {
|
|
case 0:
|
|
var grid orm.Grid
|
|
err = queryFirstByID(cancelCtx, tx, id, &grid)
|
|
currentNodeInfo = grid
|
|
case 1:
|
|
// current:Zone,Previous:Grid
|
|
var zone orm.Zone
|
|
err = queryFirstByID(cancelCtx, tx, id, &zone)
|
|
currentNodeInfo = zone
|
|
if err == nil {
|
|
var grid orm.Grid
|
|
err = queryFirstByID(cancelCtx, tx, zone.GridID, &grid)
|
|
previousNodeInfo = grid
|
|
}
|
|
case 2:
|
|
// current:Station,Previous:Zone
|
|
var station orm.Station
|
|
err = queryFirstByID(cancelCtx, tx, id, &station)
|
|
currentNodeInfo = station
|
|
if err == nil {
|
|
var zone orm.Zone
|
|
err = queryFirstByID(cancelCtx, tx, station.ZoneID, &zone)
|
|
previousNodeInfo = zone
|
|
}
|
|
case 3, 4:
|
|
// current:Component, Previous:Station
|
|
var component orm.Component
|
|
err = queryFirstByID(cancelCtx, tx, id, &component)
|
|
currentNodeInfo = component
|
|
if err == nil {
|
|
var station orm.Station
|
|
err = queryFirstByTag(cancelCtx, tx, component.StationTag, &station)
|
|
previousNodeInfo = station
|
|
}
|
|
case 5:
|
|
// TODO[NONEED-ISSUE]暂无此层级增加或删除需求 #2
|
|
return nil, nil, nil
|
|
default:
|
|
return nil, nil, fmt.Errorf("unsupported node level: %d", level)
|
|
}
|
|
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return previousNodeInfo, currentNodeInfo, nil
|
|
}
|