goinfluxdb

How do I check if an influxdb query returns no records in Go?


I have a simple query which retreives measurements for a given a time frame:

query := fmt.Sprintf(`from(bucket: "mybucket")
    |> range(start: time(v: %d), stop: time(v: %d))
    |> filter(fn: (r) => r["_measurement"] == "Xnode")
    |> filter(fn: (r) => r["serial"] == "%s")
    |> filter(fn: (r) => r["_field"] == "value")
    |> mean()
    `, start, end, serial)

    results, err := db.Api.Query(context.Background(), query)

    values := results.Record().Values()
    return core.ShiftResults{
        Begin:   start,
        End:     shiftend,
        Gasname: values["name"].(string),
        Value:   values["_value"].(float64)}, nil

However, when querying for a non-existing serial number, the program panics:

panic({0x6cd740?, 0x96ff70?})
    /usr/local/go/src/runtime/panic.go:920 +0x270
github.com/influxdata/influxdb-client-go/v2/api/query.(*FluxRecord).Values(0xc00007a190?)
    /go/pkg/mod/github.com/influxdata/influxdb-client-go/v2@v2.12.4/api/query/table.go:199

It works with existing devices and existing data. How can I check for empty results to avoid panic?


Solution

  • I am pretty sure that the problem results from accessing results.Record().Values() even though it is empty.

    The API suggest to first check the returned err and after that result.Next() before accessing a result. See the example here