gotelem/internal/db/getters.go

48 lines
1.1 KiB
Go
Raw Normal View History

2024-02-18 01:26:13 +00:00
package db
import (
"context"
"fmt"
2024-02-18 01:26:13 +00:00
"time"
)
// Datum is a single measurement - it is more granular than a packet.
// the classic example is bms_measurement.current
type Datum struct {
Timestamp time.Time `db:"timestamp"`
Value any `db:"val"`
}
// GetValues queries the database for values in a given time range.
// A value is a specific data point. For example, bms_measurement.current
// would be a value.
func (tdb *TelemDb) GetValues(ctx context.Context, packetName, field string, start time.Time,
2024-02-18 01:26:13 +00:00
end time.Time) ([]Datum, error) {
// this fragment uses json_extract from sqlite to get a single
// nested value.
SqlFrag := `
2024-02-18 01:26:13 +00:00
SELECT
ts as timestamp,
json_extract(data, '$.current') as val
FROM bus_events WHERE name IS 'bms_measurement'
2024-02-18 01:26:13 +00:00
`
rows, err := tdb.db.QueryxContext(ctx, SqlFrag)
2024-02-18 01:26:13 +00:00
if err != nil {
return nil, err
}
defer rows.Close()
2024-02-18 01:26:13 +00:00
data := make([]Datum, 0, 10)
for rows.Next() {
var d Datum = Datum{}
2024-02-18 01:26:13 +00:00
err = rows.StructScan(&d)
if err != nil {
fmt.Print(err)
2024-02-18 01:26:13 +00:00
return data, err
}
data = append(data, d)
}
fmt.Print(rows.Err())
2024-02-18 01:26:13 +00:00
return data, nil
}