macros.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. }
  15. func NewMysqlMacroEngine() tsdb.SqlMacroEngine {
  16. return &MySqlMacroEngine{}
  17. }
  18. func (m *MySqlMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string) (string, error) {
  19. m.TimeRange = timeRange
  20. rExp, _ := regexp.Compile(sExpr)
  21. var macroError error
  22. sql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {
  23. res, err := m.evaluateMacro(groups[1], strings.Split(groups[2], ","))
  24. if err != nil && macroError == nil {
  25. macroError = err
  26. return "macro_error()"
  27. }
  28. return res
  29. })
  30. if macroError != nil {
  31. return "", macroError
  32. }
  33. return sql, nil
  34. }
  35. func replaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
  36. result := ""
  37. lastIndex := 0
  38. for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) {
  39. groups := []string{}
  40. for i := 0; i < len(v); i += 2 {
  41. groups = append(groups, str[v[i]:v[i+1]])
  42. }
  43. result += str[lastIndex:v[0]] + repl(groups)
  44. lastIndex = v[1]
  45. }
  46. return result + str[lastIndex:]
  47. }
  48. func (m *MySqlMacroEngine) evaluateMacro(name string, args []string) (string, error) {
  49. switch name {
  50. case "__time":
  51. if len(args) == 0 {
  52. return "", fmt.Errorf("missing time column argument for macro %v", name)
  53. }
  54. return fmt.Sprintf("UNIX_TIMESTAMP(%s) as time_sec", args[0]), nil
  55. case "__timeFilter":
  56. if len(args) == 0 {
  57. return "", fmt.Errorf("missing time column argument for macro %v", name)
  58. }
  59. return fmt.Sprintf("%s >= FROM_UNIXTIME(%d) AND %s <= FROM_UNIXTIME(%d)", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  60. case "__timeFrom":
  61. return fmt.Sprintf("FROM_UNIXTIME(%d)", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil
  62. case "__timeTo":
  63. return fmt.Sprintf("FROM_UNIXTIME(%d)", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  64. case "__timeGroup":
  65. if len(args) != 2 {
  66. return "", fmt.Errorf("macro %v needs time column and interval", name)
  67. }
  68. interval, err := time.ParseDuration(strings.Trim(args[1], `'" `))
  69. if err != nil {
  70. return "", fmt.Errorf("error parsing interval %v", args[1])
  71. }
  72. return fmt.Sprintf("cast(cast(UNIX_TIMESTAMP(%s)/(%.0f) as signed)*%.0f as signed)", args[0], interval.Seconds(), interval.Seconds()), nil
  73. case "__unixEpochFilter":
  74. if len(args) == 0 {
  75. return "", fmt.Errorf("missing time column argument for macro %v", name)
  76. }
  77. return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  78. case "__unixEpochFrom":
  79. return fmt.Sprintf("%d", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil
  80. case "__unixEpochTo":
  81. return fmt.Sprintf("%d", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  82. default:
  83. return "", fmt.Errorf("Unknown macro %v", name)
  84. }
  85. }