query_builder.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package influxdb
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type QueryBuild struct{}
  7. func renderTags(query *Query) []string {
  8. var res []string
  9. for i, tag := range query.Tags {
  10. str := ""
  11. if i > 0 {
  12. if tag.Condition == "" {
  13. str += "AND"
  14. } else {
  15. str += tag.Condition
  16. }
  17. str += " "
  18. }
  19. res = append(res, fmt.Sprintf(`%s"%s" %s '%s'`, str, tag.Key, tag.Operator, tag.Value))
  20. }
  21. return res
  22. }
  23. func (*QueryBuild) Build(query *Query) (string, error) {
  24. res := "SELECT "
  25. var selectors []string
  26. for _, sel := range query.Selects {
  27. stk := ""
  28. for _, s := range *sel {
  29. stk = s.Render(stk)
  30. }
  31. selectors = append(selectors, stk)
  32. }
  33. res += strings.Join(selectors, ", ")
  34. policy := ""
  35. if query.Policy != "" {
  36. policy = `"` + query.Policy + `".`
  37. }
  38. res += fmt.Sprintf(` FROM %s"%s"`, policy, query.Measurement)
  39. res += " WHERE "
  40. conditions := renderTags(query)
  41. res += strings.Join(conditions, " ")
  42. if len(conditions) > 0 {
  43. res += " AND "
  44. }
  45. res += "$timeFilter"
  46. var groupBy []string
  47. for _, group := range query.GroupBy {
  48. groupBy = append(groupBy, group.Render(""))
  49. }
  50. if len(groupBy) > 0 {
  51. res += " GROUP BY " + strings.Join(groupBy, " ")
  52. }
  53. return res, nil
  54. }