query_builder.go 1.4 KB

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