diff --git a/templates/templates.go b/templates/templates.go index aca5bff75..e7992db56 100644 --- a/templates/templates.go +++ b/templates/templates.go @@ -60,9 +60,32 @@ func query(q string, timestamp clientmodel.Timestamp, queryEngine *promql.Engine if err != nil { return nil, err } - vector, err := query.Exec().Vector() - if err != nil { - return nil, err + res := query.Exec() + if res.Err != nil { + return nil, res.Err + } + var vector promql.Vector + + switch v := res.Value.(type) { + case promql.Matrix: + return nil, errors.New("matrix return values not supported") + case promql.Vector: + vector = v + case *promql.Scalar: + vector = promql.Vector{&promql.Sample{ + Value: v.Value, + Timestamp: v.Timestamp, + }} + case *promql.String: + vector = promql.Vector{&promql.Sample{ + Metric: clientmodel.COWMetric{ + Metric: clientmodel.Metric{"__value__": clientmodel.LabelValue(v.Value)}, + Copied: true, + }, + Timestamp: v.Timestamp, + }} + default: + panic("template.query: unhandled result value type") } // promql.Vector is hard to work with in templates, so convert to diff --git a/templates/templates_test.go b/templates/templates_test.go index b65e237d7..b53b0656c 100644 --- a/templates/templates_test.go +++ b/templates/templates_test.go @@ -65,6 +65,15 @@ func TestTemplateExpansion(t *testing.T) { text: "{{define \"x\"}}{{.arg0}} {{.arg1}}{{end}}{{template \"x\" (args 1 \"2\")}}", output: "1 2", }, + { + text: "{{ query \"1.5\" | first | value }}", + output: "1.5", + }, + { + // Get value from scalar query. + text: "{{ query \"scalar(count(metric))\" | first | value }}", + output: "2", + }, { // Get value from query. text: "{{ query \"metric{instance='a'}\" | first | value }}",