query_builder.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package influxdb
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/grafana/grafana/pkg/tsdb"
  6. )
  7. type QueryBuilder 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 (*QueryBuilder) Build(query *Query, queryContext *tsdb.QueryContext) (string, error) {
  25. res := renderSelectors(query)
  26. res += renderMeasurement(query)
  27. res += renderWhereClause(query)
  28. res += renderTimeFilter(query)
  29. res += renderGroupBy(query)
  30. return res, nil
  31. }
  32. func renderTimeFilter(query *Query) string {
  33. //res += "$timeFilter"
  34. //res += "time > now() -" + strings.Replace(queryContext.TimeRange.From, "now", "", 1)
  35. return "time > now() - 5m"
  36. }
  37. func renderSelectors(query *Query) string {
  38. res := "SELECT "
  39. var selectors []string
  40. for _, sel := range query.Selects {
  41. stk := ""
  42. for _, s := range *sel {
  43. stk = s.Render(stk)
  44. }
  45. selectors = append(selectors, stk)
  46. }
  47. return res + strings.Join(selectors, ", ")
  48. }
  49. func renderMeasurement(query *Query) string {
  50. policy := ""
  51. if query.Policy == "" || query.Policy == "default" {
  52. policy = ""
  53. } else {
  54. policy = `"` + query.Policy + `".`
  55. }
  56. return fmt.Sprintf(` FROM %s"%s"`, policy, query.Measurement)
  57. }
  58. func renderWhereClause(query *Query) string {
  59. res := " WHERE "
  60. conditions := renderTags(query)
  61. res += strings.Join(conditions, " ")
  62. if len(conditions) > 0 {
  63. res += " AND "
  64. }
  65. return res
  66. }
  67. func renderGroupBy(query *Query) string {
  68. var groupBy []string
  69. for _, group := range query.GroupBy {
  70. groupBy = append(groupBy, group.Render(""))
  71. }
  72. if len(groupBy) > 0 {
  73. return " GROUP BY " + strings.Join(groupBy, " ")
  74. }
  75. return ""
  76. }