made asc sorting optional and added regression tests

This commit is contained in:
ston1th 2017-11-13 19:29:43 +01:00
commit dc8463a290
4 changed files with 36 additions and 17 deletions

View file

@ -29,6 +29,7 @@ Bool does not support the wildcard operator, only the literal strings `true` and
The sort statement consists of the literal string `sort`, the field name (nesting like above is supported) and the literal strings `asc` or `desc`.
```
sort:<struct field> (short version for asc)
sort:<struct field>:asc
sort:<struct field>:desc
sort:<struct field>.<struct field>:desc

View file

@ -115,27 +115,23 @@ func NewQuery(s string) (q *Query, err error) {
}
if !q.s.enabled {
s := strings.SplitN(v, ":", 3)
if len(s) == 3 {
if s[0] == "sort" {
if s[0] == "sort" && len(s) >= 2 {
q.s.fields = strings.Split(s[1], ".")
if err = checkFields(q.s.fields, v); err != nil {
return
}
if len(s) == 3 {
switch s[2] {
case asc, desc:
q.s.fields = strings.Split(s[1], ".")
if err = checkFields(q.s.fields, v); err != nil {
return
}
if len(q.s.fields) > 0 {
if s[2] == desc {
q.s.desc = true
}
q.s.enabled = true
}
continue
case desc:
q.s.desc = true
case asc:
default:
err = newErr("invalid sort: " + v)
return
}
}
q.s.enabled = true
continue
}
}
m := strings.SplitN(v, ":", 2)

View file

@ -1,7 +1,6 @@
package filter
import (
"errors"
"reflect"
"strconv"
"strings"
@ -13,9 +12,12 @@ const (
)
func checkFields(s []string, val string) error {
if len(s) == 0 {
return newErr("invalid field: " + val)
}
for _, v := range s {
if v == "" {
return errors.New("invalid subfield: " + val)
return newErr("invalid subfield: " + val)
}
}
return nil

20
regression_test.go Normal file
View file

@ -0,0 +1,20 @@
package filter
import "testing"
func TestRegression(t *testing.T) {
data := []string{
"sort::asc",
"Int.:",
"String.:",
"sort::desc",
".:",
"sort:.0:asc",
}
for _, v := range data {
_, err := NewQuery(v)
if err == nil {
t.Errorf("regression: '%s'", v)
}
}
}