2024-02-18 01:26:13 +00:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-02-18 19:10:27 +00:00
|
|
|
"fmt"
|
2024-02-18 01:26:13 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2024-02-24 22:48:19 +00:00
|
|
|
// Modifier augments SQL strings.
|
|
|
|
type Modifier interface {
|
|
|
|
ModifyStatement(string) string
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type LimitOffsetModifier struct {
|
|
|
|
Limit int
|
|
|
|
Offset int
|
|
|
|
}
|
|
|
|
|
|
|
|
// BusEventFilter is a filter for bus events.
|
|
|
|
type BusEventFilter struct {
|
|
|
|
Names []string
|
|
|
|
TimerangeStart time.Time
|
|
|
|
TimerangeEnd time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
// now we can optionally add a limit.
|
|
|
|
|
2024-02-18 01:26:13 +00:00
|
|
|
// 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.
|
2024-02-18 19:40:41 +00:00
|
|
|
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.
|
2024-02-19 04:41:22 +00:00
|
|
|
SqlFrag := `
|
2024-02-18 01:26:13 +00:00
|
|
|
SELECT
|
2024-02-19 04:41:22 +00:00
|
|
|
ts as timestamp,
|
2024-02-24 22:48:19 +00:00
|
|
|
json_extract(data, '$.' || ?) as val
|
|
|
|
FROM bus_events WHERE name IS ?
|
2024-02-18 01:26:13 +00:00
|
|
|
`
|
2024-02-24 22:48:19 +00:00
|
|
|
rows, err := tdb.db.QueryxContext(ctx, SqlFrag, field, packetName)
|
2024-02-18 01:26:13 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2024-02-18 19:10:27 +00:00
|
|
|
defer rows.Close()
|
2024-02-18 01:26:13 +00:00
|
|
|
data := make([]Datum, 0, 10)
|
|
|
|
for rows.Next() {
|
2024-02-19 04:41:22 +00:00
|
|
|
var d Datum = Datum{}
|
2024-02-18 01:26:13 +00:00
|
|
|
err = rows.StructScan(&d)
|
|
|
|
if err != nil {
|
2024-02-18 19:40:41 +00:00
|
|
|
fmt.Print(err)
|
2024-02-18 01:26:13 +00:00
|
|
|
return data, err
|
|
|
|
}
|
|
|
|
data = append(data, d)
|
|
|
|
}
|
2024-02-19 04:41:22 +00:00
|
|
|
fmt.Print(rows.Err())
|
2024-02-18 01:26:13 +00:00
|
|
|
|
|
|
|
return data, nil
|
|
|
|
}
|