macros.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package mysql
  2. import (
  3. "fmt"
  4. "regexp"
  5. "github.com/grafana/grafana/pkg/tsdb"
  6. )
  7. //const rsString = `(?:"([^"]*)")`;
  8. const rsIdentifier = `([_a-zA-Z0-9]+)`
  9. const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)`
  10. type SqlMacroEngine interface {
  11. Interpolate(sql string) (string, error)
  12. }
  13. type MySqlMacroEngine struct {
  14. TimeRange *tsdb.TimeRange
  15. }
  16. func NewMysqlMacroEngine(timeRange *tsdb.TimeRange) SqlMacroEngine {
  17. return &MySqlMacroEngine{
  18. TimeRange: timeRange,
  19. }
  20. }
  21. func (m *MySqlMacroEngine) Interpolate(sql string) (string, error) {
  22. rExp, _ := regexp.Compile(sExpr)
  23. var macroError error
  24. sql = ReplaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {
  25. res, err := m.EvaluateMacro(groups[1], groups[2:])
  26. if err != nil && macroError == nil {
  27. macroError = err
  28. return "macro_error()"
  29. }
  30. return res
  31. })
  32. if macroError != nil {
  33. return "", macroError
  34. }
  35. return sql, nil
  36. }
  37. func ReplaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
  38. result := ""
  39. lastIndex := 0
  40. for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) {
  41. groups := []string{}
  42. for i := 0; i < len(v); i += 2 {
  43. groups = append(groups, str[v[i]:v[i+1]])
  44. }
  45. result += str[lastIndex:v[0]] + repl(groups)
  46. lastIndex = v[1]
  47. }
  48. return result + str[lastIndex:]
  49. }
  50. func (m *MySqlMacroEngine) EvaluateMacro(name string, args []string) (string, error) {
  51. switch name {
  52. case "__time":
  53. if len(args) == 0 {
  54. return "", fmt.Errorf("missing time column argument for macro %v", name)
  55. }
  56. return fmt.Sprintf("UNIX_TIMESTAMP(%s) as time_sec", args[0]), nil
  57. case "__timeFilter":
  58. if len(args) == 0 {
  59. return "", fmt.Errorf("missing time column argument for macro %v", name)
  60. }
  61. return fmt.Sprintf("UNIX_TIMESTAMP(%s) > %d AND UNIX_TIMESTAMP(%s) < %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  62. default:
  63. return "", fmt.Errorf("Unknown macro %v", name)
  64. }
  65. }