macros.go 4.9 KB

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