macros.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package postgres
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/grafana/grafana/pkg/tsdb"
  9. )
  10. //const rsString = `(?:"([^"]*)")`;
  11. const rsIdentifier = `([_a-zA-Z0-9]+)`
  12. const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)`
  13. type PostgresMacroEngine struct {
  14. TimeRange *tsdb.TimeRange
  15. Query *tsdb.Query
  16. }
  17. func NewPostgresMacroEngine() tsdb.SqlMacroEngine {
  18. return &PostgresMacroEngine{}
  19. }
  20. func (m *PostgresMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string) (string, error) {
  21. m.TimeRange = timeRange
  22. m.Query = query
  23. rExp, _ := regexp.Compile(sExpr)
  24. var macroError error
  25. sql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {
  26. res, err := m.evaluateMacro(groups[1], strings.Split(groups[2], ","))
  27. if err != nil && macroError == nil {
  28. macroError = err
  29. return "macro_error()"
  30. }
  31. return res
  32. })
  33. if macroError != nil {
  34. return "", macroError
  35. }
  36. return sql, nil
  37. }
  38. func replaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string {
  39. result := ""
  40. lastIndex := 0
  41. for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) {
  42. groups := []string{}
  43. for i := 0; i < len(v); i += 2 {
  44. groups = append(groups, str[v[i]:v[i+1]])
  45. }
  46. result += str[lastIndex:v[0]] + repl(groups)
  47. lastIndex = v[1]
  48. }
  49. return result + str[lastIndex:]
  50. }
  51. func (m *PostgresMacroEngine) evaluateMacro(name string, args []string) (string, error) {
  52. switch name {
  53. case "__time":
  54. if len(args) == 0 {
  55. return "", fmt.Errorf("missing time column argument for macro %v", name)
  56. }
  57. return fmt.Sprintf("%s AS \"time\"", args[0]), nil
  58. case "__timeEpoch":
  59. if len(args) == 0 {
  60. return "", fmt.Errorf("missing time column argument for macro %v", name)
  61. }
  62. return fmt.Sprintf("extract(epoch from %s) as \"time\"", args[0]), nil
  63. case "__timeFilter":
  64. // dont use to_timestamp in this macro for redshift compatibility #9566
  65. if len(args) == 0 {
  66. return "", fmt.Errorf("missing time column argument for macro %v", name)
  67. }
  68. return fmt.Sprintf("extract(epoch from %s) BETWEEN %d AND %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  69. case "__timeFrom":
  70. return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil
  71. case "__timeTo":
  72. return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  73. case "__timeGroup":
  74. if len(args) < 2 {
  75. return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name)
  76. }
  77. interval, err := time.ParseDuration(strings.Trim(args[1], `' `))
  78. if err != nil {
  79. return "", fmt.Errorf("error parsing interval %v", args[1])
  80. }
  81. if len(args) == 3 {
  82. m.Query.Model.Set("fill", true)
  83. m.Query.Model.Set("fillInterval", interval.Seconds())
  84. if strings.Trim(args[2], " ") == "NULL" {
  85. m.Query.Model.Set("fillNull", true)
  86. } else {
  87. floatVal, err := strconv.ParseFloat(args[2], 64)
  88. if err != nil {
  89. return "", fmt.Errorf("error parsing fill value %v", args[2])
  90. }
  91. m.Query.Model.Set("fillValue", floatVal)
  92. }
  93. }
  94. return fmt.Sprintf("(extract(epoch from %s)/%v)::bigint*%v AS time", args[0], interval.Seconds(), interval.Seconds()), nil
  95. case "__unixEpochFilter":
  96. if len(args) == 0 {
  97. return "", fmt.Errorf("missing time column argument for macro %v", name)
  98. }
  99. return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  100. case "__unixEpochFrom":
  101. return fmt.Sprintf("%d", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil
  102. case "__unixEpochTo":
  103. return fmt.Sprintf("%d", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil
  104. default:
  105. return "", fmt.Errorf("Unknown macro %v", name)
  106. }
  107. }