api/app/stats.go
2018-05-17 12:08:47 +02:00

72 lines
1.5 KiB
Go

package app
import (
"reflect"
"time"
"git.fuyu.moe/5GPowerQuality/api/app/internal/model"
"git.ultraware.nl/NiseVoid/qb"
"git.ultraware.nl/NiseVoid/qb/qc"
"git.ultraware.nl/NiseVoid/qb/qf"
)
// Count returns the number of measurements
func Count() int {
m := model.Measurement()
q := m.Select(qf.CountAll())
var count *int
err := db.QueryRow(q).Scan(&count)
if err != nil {
panic(err)
}
if count == nil {
return 0
}
return *count
}
// GetAttribute returns the specified attribute for all phases since the specified date
func GetAttribute(attr string, date time.Time) (data []Phases) {
m := model.Measurement()
f := reflect.ValueOf(m).Elem().FieldByName(attr + `1`)
if !f.IsValid() || f.Type().Name() != `Field` {
return nil
}
f1 := f.Interface().(*qb.TableField)
f2 := reflect.ValueOf(m).Elem().FieldByName(attr + `2`).Interface().(*qb.TableField)
f3 := reflect.ValueOf(m).Elem().FieldByName(attr + `3`).Interface().(*qb.TableField)
q := m.Select(m.Time, f1, f2, f3).
OrderBy(qb.Desc(m.Time)).
Where(qc.Gte(m.Time, date))
rows, err := db.Query(q)
if err != nil {
panic(err)
}
for rows.Next() {
var phases Phases
err := rows.Scan(&phases.Time, &phases.P1, &phases.P2, &phases.P3)
if err != nil {
panic(err)
}
data = append(data, phases)
}
return
}
// Phases contains data for all phases
type Phases struct {
Time time.Time `json:"time"`
P1 float64 `json:"phase_1"`
P2 float64 `json:"phase_2"`
P3 float64 `json:"phase_3"`
}