macros.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package postgres
  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 PostgresMacroEngine struct {
  13. TimeRange *tsdb.TimeRange
  14. }
  15. func NewPostgresMacroEngine() tsdb.SqlMacroEngine {
  16. return &PostgresMacroEngine{}
  17. }
  18. func (m *PostgresMacroEngine) Interpolate(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 *PostgresMacroEngine) 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("%s AS \"time\"", args[0]), nil
  55. case "__timeEpoch":
  56. if len(args) == 0 {
  57. return "", fmt.Errorf("missing time column argument for macro %v", name)
  58. }
  59. return fmt.Sprintf("extract(epoch from %s) as \"time\"", args[0]), nil
  60. case "__timeFilter":
  61. // dont use to_timestamp in this macro for redshift compatibility #9566
  62. if len(args) == 0 {
  63. return "", fmt.Errorf("missing time column argument for macro %v", name)
  64. }
  65. return fmt.Sprintf("extract(epoch from %s) BETWEEN %d AND %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  66. case "__timeFrom":
  67. return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil
  68. case "__timeTo":
  69. return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), 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. return fmt.Sprintf("(extract(epoch from %s)/%v)::bigint*%v AS time", args[0], interval.Seconds(), interval.Seconds()), nil
  79. case "__unixEpochFilter":
  80. if len(args) == 0 {
  81. return "", fmt.Errorf("missing time column argument for macro %v", name)
  82. }
  83. return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  84. case "__unixEpochFrom":
  85. return fmt.Sprintf("%d", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil
  86. case "__unixEpochTo":
  87. return fmt.Sprintf("%d", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  88. default:
  89. return "", fmt.Errorf("Unknown macro %v", name)
  90. }
  91. }