macros.go 5.0 KB

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