macros.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. Query *tsdb.Query
  15. }
  16. func NewPostgresMacroEngine() tsdb.SqlMacroEngine {
  17. return &PostgresMacroEngine{}
  18. }
  19. func (m *PostgresMacroEngine) 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. res, err := m.evaluateMacro(groups[1], strings.Split(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 *PostgresMacroEngine) 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("%s AS \"time\"", args[0]), nil
  57. case "__timeEpoch":
  58. if len(args) == 0 {
  59. return "", fmt.Errorf("missing time column argument for macro %v", name)
  60. }
  61. return fmt.Sprintf("extract(epoch from %s) as \"time\"", args[0]), nil
  62. case "__timeFilter":
  63. // dont use to_timestamp in this macro for redshift compatibility #9566
  64. if len(args) == 0 {
  65. return "", fmt.Errorf("missing time column argument for macro %v", name)
  66. }
  67. return fmt.Sprintf("extract(epoch from %s) BETWEEN %d AND %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  68. case "__timeFrom":
  69. return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil
  70. case "__timeTo":
  71. return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  72. case "__timeGroup":
  73. if len(args) != 2 {
  74. return "", fmt.Errorf("macro %v needs time column and interval", name)
  75. }
  76. interval, err := time.ParseDuration(strings.Trim(args[1], `' `))
  77. if err != nil {
  78. return "", fmt.Errorf("error parsing interval %v", args[1])
  79. }
  80. return fmt.Sprintf("(extract(epoch from %s)/%v)::bigint*%v AS time", args[0], interval.Seconds(), interval.Seconds()), nil
  81. case "__unixEpochFilter":
  82. if len(args) == 0 {
  83. return "", fmt.Errorf("missing time column argument for macro %v", name)
  84. }
  85. return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  86. case "__unixEpochFrom":
  87. return fmt.Sprintf("%d", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil
  88. case "__unixEpochTo":
  89. return fmt.Sprintf("%d", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  90. default:
  91. return "", fmt.Errorf("Unknown macro %v", name)
  92. }
  93. }