Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Like and NotLike condition builders #147

Merged
merged 1 commit into from
Sep 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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