macros.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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 "__timeFrom":
  78. return fmt.Sprintf("'%s'", m.timeRange.GetFromAsTimeUTC().Format(time.RFC3339)), nil
  79. case "__timeTo":
  80. return fmt.Sprintf("'%s'", m.timeRange.GetToAsTimeUTC().Format(time.RFC3339)), nil
  81. case "__timeGroup":
  82. if len(args) < 2 {
  83. return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name)
  84. }
  85. interval, err := time.ParseDuration(strings.Trim(args[1], `'`))
  86. if err != nil {
  87. return "", fmt.Errorf("error parsing interval %v", args[1])
  88. }
  89. if len(args) == 3 {
  90. err := tsdb.SetupFillmode(m.query, interval, args[2])
  91. if err != nil {
  92. return "", err
  93. }
  94. }
  95. if m.timescaledb {
  96. return fmt.Sprintf("time_bucket('%vs',%s)", interval.Seconds(), args[0]), nil
  97. } else {
  98. return fmt.Sprintf("floor(extract(epoch from %s)/%v)*%v", args[0], interval.Seconds(), interval.Seconds()), nil
  99. }
  100. case "__timeGroupAlias":
  101. tg, err := m.evaluateMacro("__timeGroup", args)
  102. if err == nil {
  103. return tg + " AS \"time\"", err
  104. }
  105. return "", err
  106. case "__unixEpochFilter":
  107. if len(args) == 0 {
  108. return "", fmt.Errorf("missing time column argument for macro %v", name)
  109. }
  110. return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], m.timeRange.GetFromAsSecondsEpoch(), args[0], m.timeRange.GetToAsSecondsEpoch()), nil
  111. case "__unixEpochFrom":
  112. return fmt.Sprintf("%d", m.timeRange.GetFromAsSecondsEpoch()), nil
  113. case "__unixEpochTo":
  114. return fmt.Sprintf("%d", m.timeRange.GetToAsSecondsEpoch()), nil
  115. case "__unixEpochGroup":
  116. if len(args) < 2 {
  117. return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name)
  118. }
  119. interval, err := time.ParseDuration(strings.Trim(args[1], `'`))
  120. if err != nil {
  121. return "", fmt.Errorf("error parsing interval %v", args[1])
  122. }
  123. if len(args) == 3 {
  124. err := tsdb.SetupFillmode(m.query, interval, args[2])
  125. if err != nil {
  126. return "", err
  127. }
  128. }
  129. return fmt.Sprintf("floor(%s/%v)*%v", args[0], interval.Seconds(), interval.Seconds()), nil
  130. case "__unixEpochGroupAlias":
  131. tg, err := m.evaluateMacro("__unixEpochGroup", args)
  132. if err == nil {
  133. return tg + " AS \"time\"", err
  134. }
  135. return "", err
  136. default:
  137. return "", fmt.Errorf("Unknown macro %v", name)
  138. }
  139. }