// TODO: returns weft.NotFound when query result is empty? func fieldLatestProto(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result { typeID := r.URL.Query().Get("typeID") var err error var rows *sql.Rows switch typeID { case "": rows, err = dbR.Query(`select deviceID, modelID, typeid, time, value, lower, upper, scale FROM field.metric_summary JOIN field.device using (devicePK) JOIN field.model using (modelPK) JOIN field.threshold using (devicePK, typePK) JOIN field.type using (typePK)`) default: rows, err = dbR.Query(`select deviceID, modelID, typeid, time, value, lower, upper, scale FROM field.metric_summary JOIN field.device using (devicePK) JOIN field.model using (modelPK) JOIN field.threshold using (devicePK, typePK) JOIN field.type using (typePK) WHERE typeID = $1;`, typeID) } if err != nil { return weft.InternalServerError(err) } defer rows.Close() var t time.Time var fmlr mtrpb.FieldMetricSummaryResult for rows.Next() { var fmr mtrpb.FieldMetricSummary if err = rows.Scan(&fmr.DeviceID, &fmr.ModelID, &fmr.TypeID, &t, &fmr.Value, &fmr.Lower, &fmr.Upper, &fmr.Scale); err != nil { return weft.InternalServerError(err) } fmr.Seconds = t.Unix() fmlr.Result = append(fmlr.Result, &fmr) } rows.Close() var by []byte if by, err = proto.Marshal(&fmlr); err != nil { return weft.InternalServerError(err) } b.Write(by) return &weft.StatusOK }
//search metric by tag or the place name part of deviceID func (a *tagSearch) fieldMetric() <-chan *weft.Result { out := make(chan *weft.Result) go func() { defer close(out) var err error var rows *sql.Rows if rows, err = dbR.Query(`SELECT deviceID, modelID, typeid, time, value, lower, upper FROM field.metric_tag JOIN field.metric_summary USING (devicepk, typepk) JOIN field.device USING (devicePK) JOIN field.type USING (typePK) JOIN field.model USING (modelPK) JOIN field.threshold using (devicePK, typePK) WHERE tagPK = (SELECT tagPK FROM mtr.tag WHERE tag = $1) OR deviceID LIKE $2`, a.tag, "%"+a.tag); err != nil { out <- weft.InternalServerError(err) return } defer rows.Close() var tm time.Time for rows.Next() { var fmr mtrpb.FieldMetricSummary if err = rows.Scan(&fmr.DeviceID, &fmr.ModelID, &fmr.TypeID, &tm, &fmr.Value, &fmr.Lower, &fmr.Upper); err != nil { out <- weft.InternalServerError(err) return } fmr.Seconds = tm.Unix() a.tagResult.FieldMetric = append(a.tagResult.FieldMetric, &fmr) } out <- &weft.StatusOK return }() return out }