package db import ( "context" "fmt" "testing" "bj_power_mes/ent" "bj_power_mes/ent/workpiece" ) func TestNewDBWithParams(t *testing.T) { client, _, err := NewDBWithParams("postgres", "postgres", "127.0.0.1", 5432, "bj_power_mes", false) if err != nil { t.Errorf("NewDBWithParams() error = %v", err) return } defer client.Close() ctx := context.Background() slot, err := nextEmptyTempSlot(ctx, client) if err != nil { t.Errorf("nextEmptyTempSlot() error = %v", err) return } t.Logf("nextEmptyTempSlot() = %v", slot) } // tempSlotCapacity 暂存台槽位总数。 const tempSlotCapacity = 8 // nextEmptyTempSlot 通过数据库查询已占用的 tempSlot,找第一个空位(1-8)。 func nextEmptyTempSlot(ctx context.Context, entClient *ent.Client) (int, error) { occupied, err := entClient.Workpiece.Query(). Where(workpiece.TempSlotNotNil()). Select(workpiece.FieldTempSlot). All(ctx) if err != nil { return 0, fmt.Errorf("查询暂存台占用失败: %w", err) } used := make(map[int]struct{}, len(occupied)) for _, wp := range occupied { used[wp.TempSlot] = struct{}{} } for i := 1; i <= tempSlotCapacity; i++ { if _, ok := used[i]; !ok { return i, nil } } return 0, fmt.Errorf("暂存台无空位") }