macros.go 4.2 KB

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