Skip to content

Commit 14ea102

Browse files
authored
Merge pull request #56 from grafana/refactor-regex
Refactor regex part of macros
2 parents 66e6715 + 03099c4 commit 14ea102

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

macros.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,10 @@ func interpolate(driver Driver, query *Query) (string, error) {
141141
}
142142
rawSQL := query.RawSQL
143143
for key, macro := range macros {
144-
rgx, err := regexp.Compile(getMacroRegex(key))
144+
matches, err := getMatches(key, rawSQL)
145145
if err != nil {
146146
return rawSQL, err
147147
}
148-
matches := rgx.FindAllStringSubmatch(rawSQL, -1)
149148
for _, match := range matches {
150149
if len(match) == 0 {
151150
// There were no matches for this macro
@@ -170,3 +169,11 @@ func interpolate(driver Driver, query *Query) (string, error) {
170169

171170
return rawSQL, nil
172171
}
172+
173+
func getMatches(macroName, rawSQL string) ([][]string, error) {
174+
rgx, err := regexp.Compile(getMacroRegex(macroName))
175+
if err != nil {
176+
return nil, err
177+
}
178+
return rgx.FindAllStringSubmatch(rawSQL, -1), nil
179+
}

macros_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,24 @@ func TestInterpolate(t *testing.T) {
7979
})
8080
}
8181
}
82+
83+
func TestGetMacroRegex_returns_composed_regular_expression(t *testing.T) {
84+
assert.Equal(t, `\$__some_string\b(?:\((.*?)\))?`, getMacroRegex("some_string"))
85+
}
86+
87+
func TestGetMatches(t *testing.T) {
88+
t.Run("FindAllStringSubmatch returns DefaultMacros", func(t *testing.T) {
89+
for macroName := range DefaultMacros {
90+
matches, err := getMatches(macroName, fmt.Sprintf("$__%s", macroName))
91+
92+
assert.NoError(t, err)
93+
assert.Equal(t, [][]string{{fmt.Sprintf("$__%s", macroName), ""}}, matches)
94+
}
95+
})
96+
t.Run("does not return matches for macro name which is substring", func(t *testing.T) {
97+
matches, err := getMatches("timeFilter", "$__timeFilterEpoch(time_column)")
98+
99+
assert.NoError(t, err)
100+
assert.Nil(t, matches)
101+
})
102+
}

0 commit comments

Comments
 (0)