macros.go 4.3 KB

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