macros.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. package postgres
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/grafana/grafana/pkg/tsdb"
  9. )
  10. //const rsString = `(?:"([^"]*)")`;
  11. const rsIdentifier = `([_a-zA-Z0-9]+)`
  12. const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)`
  13. type postgresMacroEngine struct {
  14. timeRange *tsdb.TimeRange
  15. query *tsdb.Query
  16. }
  17. func newPostgresMacroEngine() tsdb.SqlMacroEngine {
  18. return &postgresMacroEngine{}
  19. }
  20. func (m *postgresMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string) (string, error) {
  21. m.timeRange = timeRange
  22. m.query = query
  23. rExp, _ := regexp.Compile(sExpr)
  24. var macroError error
  25. sql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {
  26. // detect if $__timeGroup is supposed to add AS time for pre 5.3 compatibility
  27. // if there is a ',' directly after the macro call $__timeGroup is probably used
  28. // in the old way. Inside window function ORDER BY $__timeGroup will be followed
  29. // by ')'
  30. if groups[1] == "__timeGroup" {
  31. if index := strings.Index(sql, groups[0]); index >= 0 {
  32. index += len(groups[0])
  33. if len(sql) > index {
  34. // check for character after macro expression
  35. if sql[index] == ',' {
  36. groups[1] = "__timeGroupAlias"
  37. }
  38. }
  39. }
  40. }
  41. args := strings.Split(groups[2], ",")
  42. for i, arg := range args {
  43. args[i] = strings.Trim(arg, " ")
  44. }
  45. res, err := m.evaluateMacro(groups[1], args)
  46. if err != nil && macroError == nil {
  47. macroError = err
  48. return "macro_error()"
  49. }
  50. return res
  51. })
  52. if macroError != nil {
  53. return "", macroError
  54. }
  55. return sql, nil
  56. }
  57. func replaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
  58. result := ""
  59. lastIndex := 0
  60. for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) {
  61. groups := []string{}
  62. for i := 0; i < len(v); i += 2 {
  63. groups = append(groups, str[v[i]:v[i+1]])
  64. }
  65. result += str[lastIndex:v[0]] + repl(groups)
  66. lastIndex = v[1]
  67. }
  68. return result + str[lastIndex:]
  69. }
  70. func (m *postgresMacroEngine) evaluateMacro(name string, args []string) (string, error) {
  71. switch name {
  72. case "__time":
  73. if len(args) == 0 {
  74. return "", fmt.Errorf("missing time column argument for macro %v", name)
  75. }
  76. return fmt.Sprintf("%s AS \"time\"", args[0]), nil
  77. case "__timeEpoch":
  78. if len(args) == 0 {
  79. return "", fmt.Errorf("missing time column argument for macro %v", name)
  80. }
  81. return fmt.Sprintf("extract(epoch from %s) as \"time\"", args[0]), nil
  82. case "__timeFilter":
  83. if len(args) == 0 {
  84. return "", fmt.Errorf("missing time column argument for macro %v", name)
  85. }
  86. return fmt.Sprintf("%s BETWEEN '%s' AND '%s'", args[0], m.timeRange.GetFromAsTimeUTC().Format(time.RFC3339), m.timeRange.GetToAsTimeUTC().Format(time.RFC3339)), nil
  87. case "__timeFrom":
  88. return fmt.Sprintf("'%s'", m.timeRange.GetFromAsTimeUTC().Format(time.RFC3339)), nil
  89. case "__timeTo":
  90. return fmt.Sprintf("'%s'", m.timeRange.GetToAsTimeUTC().Format(time.RFC3339)), nil
  91. case "__timeGroup":
  92. if len(args) < 2 {
  93. return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name)
  94. }
  95. interval, err := time.ParseDuration(strings.Trim(args[1], `'`))
  96. if err != nil {
  97. return "", fmt.Errorf("error parsing interval %v", args[1])
  98. }
  99. if len(args) == 3 {
  100. m.query.Model.Set("fill", true)
  101. m.query.Model.Set("fillInterval", interval.Seconds())
  102. switch args[2] {
  103. case "NULL":
  104. m.query.Model.Set("fillMode", "null")
  105. case "previous":
  106. m.query.Model.Set("fillMode", "previous")
  107. default:
  108. m.query.Model.Set("fillMode", "value")
  109. floatVal, err := strconv.ParseFloat(args[2], 64)
  110. if err != nil {
  111. return "", fmt.Errorf("error parsing fill value %v", args[2])
  112. }
  113. m.query.Model.Set("fillValue", floatVal)
  114. }
  115. }
  116. return fmt.Sprintf("floor(extract(epoch from %s)/%v)*%v", args[0], interval.Seconds(), interval.Seconds()), nil
  117. case "__timeGroupAlias":
  118. tg, err := m.evaluateMacro("__timeGroup", args)
  119. if err == nil {
  120. return tg + " AS \"time\"", err
  121. }
  122. return "", err
  123. case "__unixEpochFilter":
  124. if len(args) == 0 {
  125. return "", fmt.Errorf("missing time column argument for macro %v", name)
  126. }
  127. return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], m.timeRange.GetFromAsSecondsEpoch(), args[0], m.timeRange.GetToAsSecondsEpoch()), nil
  128. case "__unixEpochFrom":
  129. return fmt.Sprintf("%d", m.timeRange.GetFromAsSecondsEpoch()), nil
  130. case "__unixEpochTo":
  131. return fmt.Sprintf("%d", m.timeRange.GetToAsSecondsEpoch()), nil
  132. default:
  133. return "", fmt.Errorf("Unknown macro %v", name)
  134. }
  135. }