Skip to content

Commit

Permalink
add Like and NotLike condition builders (#147)
Browse files Browse the repository at this point in the history
  • Loading branch information
mccolljr authored and taylorchu committed Sep 27, 2018
1 parent 03f4468 commit 37261c0
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
33 changes: 32 additions & 1 deletion condition.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package dbr

import "reflect"
import (
"reflect"
)

func buildCond(d Dialect, buf Buffer, pred string, cond ...Builder) error {
for i, c := range cond {
Expand Down Expand Up @@ -117,3 +119,32 @@ func Lte(column string, value interface{}) Builder {
return buildCmp(d, buf, "<=", column, value)
})
}

func buildLike(d Dialect, buf Buffer, column, pattern string, isNot bool, escape []string) error {
buf.WriteString(d.QuoteIdent(column))
if isNot {
buf.WriteString(" NOT LIKE ")
} else {
buf.WriteString(" LIKE ")
}
buf.WriteString(d.EncodeString(pattern))
if len(escape) > 0 {
buf.WriteString(" ESCAPE ")
buf.WriteString(d.EncodeString(escape[0]))
}
return nil
}

// Like is `LIKE`, with an optional `ESCAPE` clause
func Like(column, value string, escape ...string) Builder {
return BuildFunc(func(d Dialect, buf Buffer) error {
return buildLike(d, buf, column, value, false, escape)
})
}

// NotLike is `NOT LIKE`, with an optional `ESCAPE` clause
func NotLike(column, value string, escape ...string) Builder {
return BuildFunc(func(d Dialect, buf Buffer) error {
return buildLike(d, buf, column, value, true, escape)
})
}
30 changes: 30 additions & 0 deletions condition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,36 @@ func TestCondition(t *testing.T) {
query: "(`a` < ?) AND ((`b` > ?) OR (`c` != ?))",
value: []interface{}{1, 2, 3},
},
{
cond: Like("a", "%BLAH%", "#"),
query: "`a` LIKE '%BLAH%' ESCAPE '#'",
value: nil,
},
{
cond: Like("a", "%50#%%", "#"),
query: "`a` LIKE '%50#%%' ESCAPE '#'",
value: nil,
},
{
cond: NotLike("a", "%BLAH%", "#"),
query: "`a` NOT LIKE '%BLAH%' ESCAPE '#'",
value: nil,
},
{
cond: NotLike("a", "%50#%%", "#"),
query: "`a` NOT LIKE '%50#%%' ESCAPE '#'",
value: nil,
},
{
cond: Like("a", "_x_"),
query: "`a` LIKE '_x_'",
value: nil,
},
{
cond: NotLike("a", "_x_"),
query: "`a` NOT LIKE '_x_'",
value: nil,
},
} {
buf := NewBuffer()
err := test.cond.Build(dialect.MySQL, buf)
Expand Down

0 comments on commit 37261c0

Please sign in to comment.