Skip to content

Commit

Permalink
1) Now we support query filter of string implemented types.
Browse files Browse the repository at this point in the history
2) We can pass commas to filter multiple values
  • Loading branch information
susyo committed Jul 17, 2018
1 parent 5e76480 commit 6c84d82
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
15 changes: 14 additions & 1 deletion query/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,9 @@ func (b *Builder) parseFilter(params url.Values) (string, []interface{}, error)
if !ok {
continue
}
if b.SplitValueOnComma && len(args) == 1 && strings.Contains(args[0], ",") {
args = strings.Split(args[0], ",")
}
// there are two expression formats:
// 1. "KEY = VAL" - when only one argument is given.
// 2. "(KEY = VAL OR KEY = VAL2 ...)" - when multiple values are given.
Expand Down Expand Up @@ -273,6 +276,9 @@ func (b *Builder) parseField(field *structs.Field) {
if contains(options, sortTag) {
b.sortFields[gorm.ToDBName(field.Name())] = true
}
if contains(options, splitTag) {
b.SplitValueOnComma = true
}
// struct field has a filter option.
if !contains(options, filterTag) {
return
Expand Down Expand Up @@ -310,10 +316,17 @@ func (b *Builder) parseField(field *structs.Field) {
b.addFilterField(withSep+opGreaterThanOrEqual, colName+" >= ?", parseFn)
default:
typ := reflect.TypeOf(v)
_, isStringer := v.(fmt.Stringer)
// add more cases if needed.
if typ.ConvertibleTo(reflect.TypeOf([]string{})) {
switch {
case typ.ConvertibleTo(reflect.TypeOf([]string{})):
b.addStringField(colName, withSep, wrapFn)
case isStringer:
b.addStringField(colName, withSep, wrapFn)
default:
panic(fmt.Sprintf("Could not use field %s (%T) with query filter", field.Name(), v))
}

}
}

Expand Down
3 changes: 3 additions & 0 deletions query/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import "errors"
const (
// fields in the struct tag.
sortTag = "sort"
splitTag = "split"
filterTag = "filter"
paramTag = "param"
// search param in query string.
Expand Down Expand Up @@ -53,6 +54,8 @@ type Config struct {
OffsetParam string
// SearchOperator used to combine search condition together. defaults to "AND".
SearchOperator string
// SplitValueOnComma used to split the values on comma in the filter values in order to read multiple columns
SplitValueOnComma bool
}

func (c *Config) defaults() error {
Expand Down

0 comments on commit 6c84d82

Please sign in to comment.