macros.go 3.7 KB

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