package data import ( "database/sql" "time" "git.fuyu.moe/5GPowerQuality/parser/internal/model" "git.ultraware.nl/NiseVoid/qb" "git.ultraware.nl/NiseVoid/qb/qc" "git.ultraware.nl/NiseVoid/qb/qf" ) // GetMeterID gets the meter ID, if there is none yet a new record is add to meter func GetMeterID(source Source, meterID string) (id int) { me := model.Meter() q := me.Select(me.ID). Where( qc.Eq(me.UID, meterID), qc.Eq(me.Source, source), ) err := db.QueryRow(q).Scan(&id) switch err { case nil: case sql.ErrNoRows: iq := me.Insert(me.Name, me.UID, me.Source). Values(``, meterID, source) err = db.QueryRow(qb.Returning(iq, me.ID)).Scan(&id) if err != nil { panic(err) } default: panic(err) } return } // GetStartDate gets the last measurement date func GetStartDate(source Source) time.Time { m, me := model.Measurement(), model.Meter() q := m.Select(qf.Max(m.Time)). InnerJoin(me.ID, m.MeterID). Where(qc.Eq(me.Source, source)) var t *time.Time err := db.QueryRow(q).Scan(&t) if (err == nil && t == nil) || err == sql.ErrNoRows { return time.Date(2018, 4, 1, 0, 0, 0, 0, time.Local) } if err != nil { panic(err) } *t = t.Add(time.Second) return *t } func InsertSets(sets Sets) { if len(sets) == 0 { return } m := model.Measurement() q := m.Insert(m.Time, m.MeterID, m.CGem1, m.CGem2, m.CGem3, m.CGemN, m.Ep1, m.Ep2, m.Ep3, m.IGem1, m.IGem2, m.IGem3, m.IGemN, m.IMax1, m.IMax2, m.IMax3, m.PMax1, m.PMax2, m.PMax3, m.SMax1, m.SMax2, m.SMax3, m.UGem1, m.UGem2, m.UGem3, m.UGemN, m.BGem1, m.BGem2, m.BGem3, m.BGemN, m.SGem1, m.SGem2, m.SGem3, m.SGemN, m.PGem1, m.PGem2, m.PGem3, m.PGemN, m.Ithd1, m.Ithd2, m.Ithd3, m.IthdN, m.Uthd1, m.Uthd2, m.Uthd3, m.UthdN, m.Freq, ) for k, v := range sets { q.Values(k.Time, k.Meter, v[`CGem1`], v[`CGem2`], v[`CGem3`], ifExists(v, `CGemN`), v[`EP1`], v[`EP2`], v[`EP3`], v[`IGem1`], v[`IGem2`], v[`IGem3`], ifExists(v, `IGemN`), v[`IMax1`], v[`IMax2`], v[`IMax3`], v[`PMax1`], v[`PMax2`], v[`PMax3`], v[`SMax1`], v[`SMax2`], v[`SMax3`], v[`UGem1`], v[`UGem2`], v[`UGem3`], ifExists(v, `UGemN`), v[`BGem1`], v[`BGem2`], v[`BGem3`], ifExists(v, `BGemN`), v[`SGem1`], v[`SGem2`], v[`SGem3`], ifExists(v, `SGemN`), v[`PGem1`], v[`PGem2`], v[`PGem3`], ifExists(v, `PGemN`), v[`ITHD1`], v[`ITHD2`], v[`ITHD3`], ifExists(v, `ITHDN`), v[`UTHD1`], v[`UTHD2`], v[`UTHD3`], ifExists(v, `UTHDN`), v[`FREQ`], ) } err := db.Exec(q) if err != nil { panic(err) } } func ifExists(set Set, k string) interface{} { v, ok := set[k] if !ok { return nil } return v }