macros.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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:len(groups)])
  26. if 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 "UNIX_TIMESTAMP(" + args[0] + ") as time_sec", nil
  57. default:
  58. return "", fmt.Errorf("Unknown macro %v", name)
  59. }
  60. }