Skip to content

Commit 0305851

Browse files
Merge pull request #23 from NeedleInAJayStack/fix/unit-interpretation
fix: Improves unit detection
2 parents d274eb4 + 2e671a5 commit 0305851

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

pkg/plugin/datasource.go

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -421,14 +421,8 @@ func dataFrameFromGrid(grid haystack.Grid) (*data.Frame, error) {
421421
// Set Grafana field info from Haystack grid info
422422
config := &data.FieldConfig{}
423423
config.DisplayName = col.Name()
424-
switch unit := col.Meta().Get("unit").(type) {
425-
case haystack.Str:
426-
config.Unit = unit.String()
427-
default:
428-
config.Unit = ""
429-
}
424+
config.Unit = unitFromGrid(grid, col)
430425
field.Config = config
431-
432426
fields = append(fields, field)
433427
}
434428

@@ -443,6 +437,29 @@ func dataFrameFromGrid(grid haystack.Grid) (*data.Frame, error) {
443437
return frame, nil
444438
}
445439

440+
// unitFromGrid returns the unit of a column in a haystack grid
441+
// It is expected that the column is from the grid
442+
// The unit is determined in the following order:
443+
// 1. If the column has a unit meta, return it
444+
// 2. If the column has a unit in the first row, return it
445+
// 3. Return empty string
446+
func unitFromGrid(grid haystack.Grid, col haystack.Col) string {
447+
switch unit := col.Meta().Get("unit").(type) {
448+
case haystack.Str:
449+
return unit.String()
450+
default:
451+
if grid.RowCount() >= 1 {
452+
row := grid.RowAt(0)
453+
val := row.Get(col.Name())
454+
switch val := val.(type) {
455+
case haystack.Number:
456+
return val.Unit()
457+
}
458+
}
459+
return ""
460+
}
461+
}
462+
446463
type colType int
447464

448465
// colType represents the type of a column in a haystack grid

pkg/plugin/datasource_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ func TestQueryData_HisRead(t *testing.T) {
6666
v0Val := 5.0
6767
expected := data.NewFrame("",
6868
data.NewField("ts", nil, []*time.Time{&tsVal}).SetConfig(&data.FieldConfig{DisplayName: "ts"}),
69-
data.NewField("v0", nil, []*float64{&v0Val}).SetConfig(&data.FieldConfig{DisplayName: "v0"}),
69+
data.NewField("v0", nil, []*float64{&v0Val}).SetConfig(&data.FieldConfig{DisplayName: "v0", Unit: "kWh"}),
7070
)
7171

7272
if !cmp.Equal(actual, expected, data.FrameTestCompareOptions()...) {

0 commit comments

Comments
 (0)