macros.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. package mssql
  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 msSqlMacroEngine struct {
  12. timeRange *tsdb.TimeRange
  13. query *tsdb.Query
  14. }
  15. func newMssqlMacroEngine() tsdb.SqlMacroEngine {
  16. return &msSqlMacroEngine{}
  17. }
  18. func (m *msSqlMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string) (string, error) {
  19. m.timeRange = timeRange
  20. m.query = query
  21. rExp, _ := regexp.Compile(sExpr)
  22. var macroError error
  23. sql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {
  24. args := strings.Split(groups[2], ",")
  25. for i, arg := range args {
  26. args[i] = strings.Trim(arg, " ")
  27. }
  28. res, err := m.evaluateMacro(groups[1], args)
  29. if err != nil && macroError == nil {
  30. macroError = err
  31. return "macro_error()"
  32. }
  33. return res
  34. })
  35. if macroError != nil {
  36. return "", macroError
  37. }
  38. return sql, nil
  39. }
  40. func replaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
  41. result := ""
  42. lastIndex := 0
  43. for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) {
  44. groups := []string{}
  45. for i := 0; i < len(v); i += 2 {
  46. groups = append(groups, str[v[i]:v[i+1]])
  47. }
  48. result += str[lastIndex:v[0]] + repl(groups)
  49. lastIndex = v[1]
  50. }
  51. return result + str[lastIndex:]
  52. }
  53. func (m *msSqlMacroEngine) evaluateMacro(name string, args []string) (string, error) {
  54. switch name {
  55. case "__time":
  56. if len(args) == 0 {
  57. return "", fmt.Errorf("missing time column argument for macro %v", name)
  58. }
  59. return fmt.Sprintf("%s AS time", args[0]), nil
  60. case "__timeEpoch":
  61. if len(args) == 0 {
  62. return "", fmt.Errorf("missing time column argument for macro %v", name)
  63. }
  64. return fmt.Sprintf("DATEDIFF(second, '1970-01-01', %s) AS time", args[0]), nil
  65. case "__timeFilter":
  66. if len(args) == 0 {
  67. return "", fmt.Errorf("missing time column argument for macro %v", name)
  68. }
  69. return fmt.Sprintf("%s BETWEEN '%s' AND '%s'", args[0], m.timeRange.GetFromAsTimeUTC().Format(time.RFC3339), m.timeRange.GetToAsTimeUTC().Format(time.RFC3339)), nil
  70. case "__timeFrom":
  71. return fmt.Sprintf("'%s'", m.timeRange.GetFromAsTimeUTC().Format(time.RFC3339)), nil
  72. case "__timeTo":
  73. return fmt.Sprintf("'%s'", m.timeRange.GetToAsTimeUTC().Format(time.RFC3339)), nil
  74. case "__timeGroup":
  75. if len(args) < 2 {
  76. return "", fmt.Errorf("macro %v needs time column and interval", name)
  77. }
  78. interval, err := time.ParseDuration(strings.Trim(args[1], `'"`))
  79. if err != nil {
  80. return "", fmt.Errorf("error parsing interval %v", args[1])
  81. }
  82. if len(args) == 3 {
  83. err := tsdb.SetupFillmode(m.query, interval, args[2])
  84. if err != nil {
  85. return "", err
  86. }
  87. }
  88. return fmt.Sprintf("FLOOR(DATEDIFF(second, '1970-01-01', %s)/%.0f)*%.0f", args[0], interval.Seconds(), interval.Seconds()), nil
  89. case "__timeGroupAlias":
  90. tg, err := m.evaluateMacro("__timeGroup", args)
  91. if err == nil {
  92. return tg + " AS [time]", err
  93. }
  94. return "", err
  95. case "__unixEpochFilter":
  96. if len(args) == 0 {
  97. return "", fmt.Errorf("missing time column argument for macro %v", name)
  98. }
  99. return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], m.timeRange.GetFromAsSecondsEpoch(), args[0], m.timeRange.GetToAsSecondsEpoch()), nil
  100. case "__unixEpochFrom":
  101. return fmt.Sprintf("%d", m.timeRange.GetFromAsSecondsEpoch()), nil
  102. case "__unixEpochTo":
  103. return fmt.Sprintf("%d", m.timeRange.GetToAsSecondsEpoch()), nil
  104. case "__unixEpochGroup":
  105. if len(args) < 2 {
  106. return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name)
  107. }
  108. interval, err := time.ParseDuration(strings.Trim(args[1], `'`))
  109. if err != nil {
  110. return "", fmt.Errorf("error parsing interval %v", args[1])
  111. }
  112. if len(args) == 3 {
  113. err := tsdb.SetupFillmode(m.query, interval, args[2])
  114. if err != nil {
  115. return "", err
  116. }
  117. }
  118. return fmt.Sprintf("FLOOR(%s/%v)*%v", args[0], interval.Seconds(), interval.Seconds()), nil
  119. case "__unixEpochGroupAlias":
  120. tg, err := m.evaluateMacro("__unixEpochGroup", args)
  121. if err == nil {
  122. return tg + " AS [time]", err
  123. }
  124. return "", err
  125. default:
  126. return "", fmt.Errorf("Unknown macro %v", name)
  127. }
  128. }