macros.go 3.9 KB

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