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

Commit 77d8c27

Browse files
authored
Convert LIKE patterns to specific Go regexes (#817)
Convert LIKE patterns to specific Go regexes
2 parents b78fa77 + 97328f6 commit 77d8c27

File tree

2 files changed

+17
-16
lines changed

2 files changed

+17
-16
lines changed

sql/expression/like.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,11 @@ func (l *Like) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
6868
if err != nil {
6969
return nil, err
7070
}
71-
right = patternToRegex(v.(string))
71+
right = patternToGoRegex(v.(string))
7272
}
7373
// for non-cached regex every time create a new matcher
7474
if !l.cached {
75-
matcher, disposer, err = regex.New(regex.Default(), right)
75+
matcher, disposer, err = regex.New("go", right)
7676
} else {
7777
if l.pool == nil {
7878
l.pool = &sync.Pool{
@@ -115,8 +115,9 @@ func (l *Like) WithChildren(children ...sql.Expression) (sql.Expression, error)
115115
return NewLike(children[0], children[1]), nil
116116
}
117117

118-
func patternToRegex(pattern string) string {
118+
func patternToGoRegex(pattern string) string {
119119
var buf bytes.Buffer
120+
buf.WriteString("(?s)")
120121
buf.WriteRune('^')
121122
var escaped bool
122123
for _, r := range strings.Replace(regexp.QuoteMeta(pattern), `\\`, `\`, -1) {

sql/expression/like_test.go

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,23 +12,23 @@ func TestPatternToRegex(t *testing.T) {
1212
testCases := []struct {
1313
in, out string
1414
}{
15-
{`__`, `^..$`},
16-
{`_%_`, `^..*.$`},
17-
{`%_`, `^.*.$`},
18-
{`_%`, `^..*$`},
19-
{`a_b`, `^a.b$`},
20-
{`a%b`, `^a.*b$`},
21-
{`a.%b`, `^a\..*b$`},
22-
{`a\%b`, `^a%b$`},
23-
{`a\_b`, `^a_b$`},
24-
{`a\\b`, `^a\\b$`},
25-
{`a\\\_b`, `^a\\_b$`},
26-
{`(ab)`, `^\(ab\)$`},
15+
{`__`, `(?s)^..$`},
16+
{`_%_`, `(?s)^..*.$`},
17+
{`%_`, `(?s)^.*.$`},
18+
{`_%`, `(?s)^..*$`},
19+
{`a_b`, `(?s)^a.b$`},
20+
{`a%b`, `(?s)^a.*b$`},
21+
{`a.%b`, `(?s)^a\..*b$`},
22+
{`a\%b`, `(?s)^a%b$`},
23+
{`a\_b`, `(?s)^a_b$`},
24+
{`a\\b`, `(?s)^a\\b$`},
25+
{`a\\\_b`, `(?s)^a\\_b$`},
26+
{`(ab)`, `(?s)^\(ab\)$`},
2727
}
2828

2929
for _, tt := range testCases {
3030
t.Run(tt.in, func(t *testing.T) {
31-
require.Equal(t, tt.out, patternToRegex(tt.in))
31+
require.Equal(t, tt.out, patternToGoRegex(tt.in))
3232
})
3333
}
3434
}

0 commit comments

Comments
 (0)