macros.go 4.7 KB

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