Skip to content
This repository has been archived by the owner on Jan 28, 2021. It is now read-only.

Commit

Permalink
Convert LIKE patterns to specific Go regexes (#817)
Browse files Browse the repository at this point in the history
Convert LIKE patterns to specific Go regexes
  • Loading branch information
ajnavarro committed Sep 13, 2019
2 parents b78fa77 + 97328f6 commit 77d8c27
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 16 deletions.
7 changes: 4 additions & 3 deletions sql/expression/like.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,11 @@ func (l *Like) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
if err != nil {
return nil, err
}
right = patternToRegex(v.(string))
right = patternToGoRegex(v.(string))
}
// for non-cached regex every time create a new matcher
if !l.cached {
matcher, disposer, err = regex.New(regex.Default(), right)
matcher, disposer, err = regex.New("go", right)
} else {
if l.pool == nil {
l.pool = &sync.Pool{
Expand Down Expand Up @@ -115,8 +115,9 @@ func (l *Like) WithChildren(children ...sql.Expression) (sql.Expression, error)
return NewLike(children[0], children[1]), nil
}

func patternToRegex(pattern string) string {
func patternToGoRegex(pattern string) string {
var buf bytes.Buffer
buf.WriteString("(?s)")
buf.WriteRune('^')
var escaped bool
for _, r := range strings.Replace(regexp.QuoteMeta(pattern), `\\`, `\`, -1) {
Expand Down
26 changes: 13 additions & 13 deletions sql/expression/like_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,23 @@ func TestPatternToRegex(t *testing.T) {
testCases := []struct {
in, out string
}{
{`__`, `^..$`},
{`_%_`, `^..*.$`},
{`%_`, `^.*.$`},
{`_%`, `^..*$`},
{`a_b`, `^a.b$`},
{`a%b`, `^a.*b$`},
{`a.%b`, `^a\..*b$`},
{`a\%b`, `^a%b$`},
{`a\_b`, `^a_b$`},
{`a\\b`, `^a\\b$`},
{`a\\\_b`, `^a\\_b$`},
{`(ab)`, `^\(ab\)$`},
{`__`, `(?s)^..$`},
{`_%_`, `(?s)^..*.$`},
{`%_`, `(?s)^.*.$`},
{`_%`, `(?s)^..*$`},
{`a_b`, `(?s)^a.b$`},
{`a%b`, `(?s)^a.*b$`},
{`a.%b`, `(?s)^a\..*b$`},
{`a\%b`, `(?s)^a%b$`},
{`a\_b`, `(?s)^a_b$`},
{`a\\b`, `(?s)^a\\b$`},
{`a\\\_b`, `(?s)^a\\_b$`},
{`(ab)`, `(?s)^\(ab\)$`},
}

for _, tt := range testCases {
t.Run(tt.in, func(t *testing.T) {
require.Equal(t, tt.out, patternToRegex(tt.in))
require.Equal(t, tt.out, patternToGoRegex(tt.in))
})
}
}
Expand Down

0 comments on commit 77d8c27

Please sign in to comment.