Skip to content

Commit be86a51

Browse files
committed
Refactor regex part of macros
1 parent f3b2510 commit be86a51

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-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: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,28 @@ func TestInterpolate(t *testing.T) {
7979
})
8080
}
8181
}
82+
83+
func TestGetMacroRegex(t *testing.T) {
84+
t.Run("returns composed regular expression", func(t *testing.T) {
85+
assert.Equal(t, `\$__some_string\b(?:\((.*?)\))?`, getMacroRegex("some_string"))
86+
})
87+
t.Run("FindAllStringSubmatch returns DefaultMacros", func(t *testing.T) {
88+
for macroName := range DefaultMacros {
89+
matches, err := getMatches(macroName, fmt.Sprintf("$__%s", macroName))
90+
91+
assert.NoError(t, err)
92+
assert.Equal(t, [][]string{{fmt.Sprintf("$__%s", macroName), ""}}, matches)
93+
}
94+
})
95+
}
96+
97+
func TestGetMacroRegex_returns_composed_regular_expression(t *testing.T) {
98+
assert.Equal(t, `\$__some_string\b(?:\((.*?)\))?`, getMacroRegex("some_string"))
99+
}
100+
101+
func TestGetMatches_does_not_match_for_macro_name_which_is_substring(t *testing.T) {
102+
matches, err := getMatches("timeFilter", "$__timeFilterEpoch(time_column)")
103+
104+
assert.NoError(t, err)
105+
assert.Nil(t, matches)
106+
}

0 commit comments

Comments
 (0)