Skip to content

Commit 521fc51

Browse files
authored
Allow macros with no arguments (#23)
1 parent 1823bc8 commit 521fc51

File tree

2 files changed

+6
-9
lines changed

2 files changed

+6
-9
lines changed

macros.go

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,6 @@ import (
99
)
1010

1111
var (
12-
// ErrorNoArguments is returned when a macro is used but there were no arguments
13-
// TODO: Note that it's possible that not every macro has an argument, and we should maybe adjust for this case
14-
ErrorNoArguments = errors.New("there were no arguments provided to the macro")
1512
// ErrorBadArgumentCount is returned from macros when the wrong number of arguments were provided
1613
ErrorBadArgumentCount = errors.New("unexpected number of arguments")
1714
)
@@ -34,7 +31,7 @@ func trimAll(s []string) []string {
3431
}
3532

3633
func getMacroRegex(name string) string {
37-
return fmt.Sprintf("\\$__%s\\((.*?)\\)", name)
34+
return fmt.Sprintf("\\$__%s(?:\\((.*?)\\))?", name)
3835
}
3936

4037
func interpolate(driver Driver, query *Query) (string, error) {
@@ -52,12 +49,12 @@ func interpolate(driver Driver, query *Query) (string, error) {
5249
continue
5350
}
5451

55-
if len(match) == 1 {
56-
// This macro has no arguments
57-
return "", ErrorNoArguments
52+
args := []string{}
53+
if len(match) > 1 {
54+
// This macro has arguments
55+
args = trimAll(strings.Split(match[1], ","))
5856
}
5957

60-
args := trimAll(strings.Split(match[1], ","))
6158
res, err := macro(query.WithSQL(rawSQL), args)
6259
if err != nil {
6360
return "", err

macros_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func TestInterpolate(t *testing.T) {
4848
{input: "select * from $__foo()", output: "select * from bar", name: "correct macro"},
4949
{input: "select '$__foo()' from $__foo()", output: "select 'bar' from bar", name: "multiple instances of same macro"},
5050
{input: "select * from $__foo()$__foo()", output: "select * from barbar", name: "multiple instances of same macro without space"},
51-
{input: "select * from $__foo", output: "select * from $__foo", name: "macro without paranthesis"},
51+
{input: "select * from $__foo", output: "select * from bar", name: "macro without paranthesis"},
5252
{input: "select * from $__params()", output: "select * from bar", name: "macro without params"},
5353
{input: "select * from $__params(hello)", output: "select * from bar_hello", name: "with param"},
5454
{input: "select * from $__params(hello) AND $__params(hello)", output: "select * from bar_hello AND bar_hello", name: "same macro multiple times with same param"},

0 commit comments

Comments
 (0)