macros.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package postgres
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strings"
  6. "time"
  7. "github.com/grafana/grafana/pkg/tsdb"
  8. )
  9. //const rsString = `(?:"([^"]*)")`;
  10. const rsIdentifier = `([_a-zA-Z0-9]+)`
  11. const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)`
  12. type postgresMacroEngine struct {
  13. timeRange *tsdb.TimeRange
  14. query *tsdb.Query
  15. timescaledb bool
  16. }
  17. func newPostgresMacroEngine(timescaledb bool) tsdb.SqlMacroEngine {
  18. return &postgresMacroEngine{timescaledb: timescaledb}
  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. err := tsdb.SetupFillmode(m.query, interval, args[2])
  101. if err != nil {
  102. return "", err
  103. }
  104. }
  105. if m.timescaledb {
  106. return fmt.Sprintf("time_bucket('%vs',%s)", interval.Seconds(), args[0]), nil
  107. } else {
  108. return fmt.Sprintf("floor(extract(epoch from %s)/%v)*%v", args[0], interval.Seconds(), interval.Seconds()), nil
  109. }
  110. case "__timeGroupAlias":
  111. tg, err := m.evaluateMacro("__timeGroup", args)
  112. if err == nil {
  113. return tg + " AS \"time\"", err
  114. }
  115. return "", err
  116. case "__unixEpochFilter":
  117. if len(args) == 0 {
  118. return "", fmt.Errorf("missing time column argument for macro %v", name)
  119. }
  120. return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], m.timeRange.GetFromAsSecondsEpoch(), args[0], m.timeRange.GetToAsSecondsEpoch()), nil
  121. case "__unixEpochFrom":
  122. return fmt.Sprintf("%d", m.timeRange.GetFromAsSecondsEpoch()), nil
  123. case "__unixEpochTo":
  124. return fmt.Sprintf("%d", m.timeRange.GetToAsSecondsEpoch()), nil
  125. case "__unixEpochGroup":
  126. if len(args) < 2 {
  127. return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name)
  128. }
  129. interval, err := time.ParseDuration(strings.Trim(args[1], `'`))
  130. if err != nil {
  131. return "", fmt.Errorf("error parsing interval %v", args[1])
  132. }
  133. if len(args) == 3 {
  134. err := tsdb.SetupFillmode(m.query, interval, args[2])
  135. if err != nil {
  136. return "", err
  137. }
  138. }
  139. return fmt.Sprintf("floor(%s/%v)*%v", args[0], interval.Seconds(), interval.Seconds()), nil
  140. case "__unixEpochGroupAlias":
  141. tg, err := m.evaluateMacro("__unixEpochGroup", args)
  142. if err == nil {
  143. return tg + " AS \"time\"", err
  144. }
  145. return "", err
  146. default:
  147. return "", fmt.Errorf("Unknown macro %v", name)
  148. }
  149. }