macros.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package mysql
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strings"
  6. "time"
  7. "github.com/grafana/grafana/pkg/tsdb"
  8. )
  9. //const rsString = `(?:"([^"]*)")`;
  10. const rsIdentifier = `([_a-zA-Z0-9]+)`
  11. const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)`
  12. type mySqlMacroEngine struct {
  13. timeRange *tsdb.TimeRange
  14. query *tsdb.Query
  15. }
  16. func newMysqlMacroEngine() tsdb.SqlMacroEngine {
  17. return &mySqlMacroEngine{}
  18. }
  19. func (m *mySqlMacroEngine) 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 *mySqlMacroEngine) evaluateMacro(name string, args []string) (string, error) {
  55. switch name {
  56. case "__timeEpoch", "__time":
  57. if len(args) == 0 {
  58. return "", fmt.Errorf("missing time column argument for macro %v", name)
  59. }
  60. return fmt.Sprintf("UNIX_TIMESTAMP(%s) as time_sec", args[0]), nil
  61. case "__timeFilter":
  62. if len(args) == 0 {
  63. return "", fmt.Errorf("missing time column argument for macro %v", name)
  64. }
  65. return fmt.Sprintf("%s BETWEEN '%s' AND '%s'", args[0], m.timeRange.GetFromAsTimeUTC().Format(time.RFC3339), m.timeRange.GetToAsTimeUTC().Format(time.RFC3339)), nil
  66. case "__timeFrom":
  67. return fmt.Sprintf("'%s'", m.timeRange.GetFromAsTimeUTC().Format(time.RFC3339)), nil
  68. case "__timeTo":
  69. return fmt.Sprintf("'%s'", m.timeRange.GetToAsTimeUTC().Format(time.RFC3339)), nil
  70. case "__timeGroup":
  71. if len(args) < 2 {
  72. return "", fmt.Errorf("macro %v needs time column and interval", name)
  73. }
  74. interval, err := time.ParseDuration(strings.Trim(args[1], `'"`))
  75. if err != nil {
  76. return "", fmt.Errorf("error parsing interval %v", args[1])
  77. }
  78. if len(args) == 3 {
  79. err := tsdb.SetupFillmode(m.query, interval, args[2])
  80. if err != nil {
  81. return "", err
  82. }
  83. }
  84. return fmt.Sprintf("UNIX_TIMESTAMP(%s) DIV %.0f * %.0f", args[0], interval.Seconds(), interval.Seconds()), nil
  85. case "__timeGroupAlias":
  86. tg, err := m.evaluateMacro("__timeGroup", args)
  87. if err == nil {
  88. return tg + " AS \"time\"", err
  89. }
  90. return "", err
  91. case "__unixEpochFilter":
  92. if len(args) == 0 {
  93. return "", fmt.Errorf("missing time column argument for macro %v", name)
  94. }
  95. return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], m.timeRange.GetFromAsSecondsEpoch(), args[0], m.timeRange.GetToAsSecondsEpoch()), nil
  96. case "__unixEpochFrom":
  97. return fmt.Sprintf("%d", m.timeRange.GetFromAsSecondsEpoch()), nil
  98. case "__unixEpochTo":
  99. return fmt.Sprintf("%d", m.timeRange.GetToAsSecondsEpoch()), nil
  100. case "__unixEpochGroup":
  101. if len(args) < 2 {
  102. return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name)
  103. }
  104. interval, err := time.ParseDuration(strings.Trim(args[1], `'`))
  105. if err != nil {
  106. return "", fmt.Errorf("error parsing interval %v", args[1])
  107. }
  108. if len(args) == 3 {
  109. err := tsdb.SetupFillmode(m.query, interval, args[2])
  110. if err != nil {
  111. return "", err
  112. }
  113. }
  114. return fmt.Sprintf("%s DIV %v * %v", args[0], interval.Seconds(), interval.Seconds()), nil
  115. case "__unixEpochGroupAlias":
  116. tg, err := m.evaluateMacro("__unixEpochGroup", args)
  117. if err == nil {
  118. return tg + " AS \"time\"", err
  119. }
  120. return "", err
  121. default:
  122. return "", fmt.Errorf("Unknown macro %v", name)
  123. }
  124. }