macros.go 4.6 KB

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