influxdb.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package model
  2. import (
  3. "encoding/json"
  4. iclient "github.com/influxdata/influxdb/client/v2"
  5. "github.com/jaryhe/gopkgs/influxdb"
  6. "time"
  7. )
  8. func QueryInfluxdb(sql string, db string, result interface{}) ([]map[string]interface{}, error) {
  9. qt := iclient.Query{
  10. Database:db,
  11. Command:sql,
  12. }
  13. r, err := influxdb.InfluxCli.Query(qt)
  14. if err != nil {
  15. return nil, err
  16. }
  17. if r == nil {
  18. return nil, nil
  19. }
  20. if len(r.Results) == 0 {
  21. return nil, nil
  22. }
  23. if len(r.Results[0].Series) == 0 {
  24. return nil, nil
  25. }
  26. colNames := r.Results[0].Series[0].Columns
  27. var marray = make([]map[string]interface{}, len(r.Results[0].Series[0].Values))
  28. for i, row := range r.Results[0].Series[0].Values {
  29. item := map[string]interface{}{}
  30. for j , v := range row {
  31. if colNames[j] == "time" {
  32. t,_ := time.Parse(time.RFC3339, v.(string))
  33. v = t.Format("2006-01-02 15:04:05")
  34. }
  35. item[colNames[j]] = v
  36. }
  37. marray[i] = item
  38. }
  39. if result != nil {
  40. bytes, _ := json.Marshal(marray)
  41. err = json.Unmarshal(bytes, result)
  42. if err != nil {
  43. return nil, err
  44. }
  45. }
  46. return marray, nil
  47. }