influx.go 1.4 KB

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