Skip to content

Commit

Permalink
SQL: Apply longer macros before shorter macros (#992)
Browse files Browse the repository at this point in the history
* SQL: Apply longer macros before shorter macros

* update existing test
  • Loading branch information
kevinwcyu authored May 27, 2024
1 parent 588021a commit 1f0e4c9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
13 changes: 12 additions & 1 deletion data/sqlutil/macros.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -218,16 +219,26 @@ func Interpolate(query *Query, macros Macros) (string, error) {
mergedMacros := Macros{}
maps.Copy(mergedMacros, DefaultMacros)
maps.Copy(mergedMacros, macros)
// sort macros so longer macros are applied first to prevent it from being
// overridden by a shorter macro that is a substring of the longer one
sortedMacroKeys := make([]string, 0, len(mergedMacros))
for key := range mergedMacros {
sortedMacroKeys = append(sortedMacroKeys, key)
}
sort.Slice(sortedMacroKeys, func(i, j int) bool {
return len(sortedMacroKeys[i]) > len(sortedMacroKeys[j])
})

rawSQL := query.RawSQL

for key, macro := range mergedMacros {
for _, key := range sortedMacroKeys {
matches, err := getMacroMatches(rawSQL, key)
if err != nil {
return rawSQL, err
}

for _, match := range matches {
macro := mergedMacros[key]
res, err := macro(query.WithSQL(rawSQL), match.args)
if err != nil {
return rawSQL, err
Expand Down
4 changes: 2 additions & 2 deletions data/sqlutil/macros_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ func TestInterpolate(t *testing.T) {
},
{
name: "this macro name's substring is another macro",
input: "select * from $__fooBaz()",
output: "select * from qux",
input: "select $__foo, $__fooBaz from foo",
output: "select baz, qux from foo",
},
{
name: "multiple instances of same macro",
Expand Down

0 comments on commit 1f0e4c9

Please sign in to comment.