Skip to content

Commit

Permalink
Improved the query matching.
Browse files Browse the repository at this point in the history
  • Loading branch information
zond committed Feb 6, 2024
1 parent ba4c80e commit b443def
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
23 changes: 23 additions & 0 deletions find_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1303,6 +1303,29 @@ type queryMatchTest struct {
Created time.Time
}

func TestComplexQueryMatch(t *testing.T) {
testWrap(t, func(store *badgerhold.Store, t *testing.T) {
item := queryMatchTest{
Key: 1,
Age: 2,
Color: "color",
Created: time.UnixMicro(0),
}
query := badgerhold.Where("Key").Eq(1).And("Age").Eq(3).Or(badgerhold.Where("Key").Eq(2).And("Age").Eq(2))
if m, err := query.Matches(store, item); m || err != nil {
t.Errorf("wanted %+v to not match %+v, but got %v, %v", query, item, m, err)
}
query = badgerhold.Where("Key").Eq(1).And("Age").Eq(3).Or(badgerhold.Where("Key").Eq(1).And("Age").Eq(2))
if m, err := query.Matches(store, item); !m || err != nil {
t.Errorf("wanted %+v to match %+v, but got %v, %v", query, item, m, err)
}
query = badgerhold.Where("Key").Eq(1).And("Age").Eq(1).Or(badgerhold.Where("Key").Eq(2).And("Age").Eq(2).Or(badgerhold.Where("Key").Eq(1).And("Age").Eq(2)))
if m, err := query.Matches(store, item); !m || err != nil {
t.Errorf("wanted %+v to match %+v, but got %v, %v", query, item, m, err)
}
})
}

func TestQueryMatch(t *testing.T) {
testWrap(t, func(store *badgerhold.Store, t *testing.T) {
item := queryMatchTest{
Expand Down
9 changes: 7 additions & 2 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ func (q *Query) Or(query *Query) *Query {
}

// Matches returns whether the provided data matches the query.
// Will match all field criteria, including nested OR queries, but ignores limits, skips, sort orders, etc.
func (q *Query) Matches(s *Store, data interface{}) (bool, error) {
var key []byte
dataVal := reflect.ValueOf(data)
Expand All @@ -308,11 +309,15 @@ func (q *Query) Matches(s *Store, data interface{}) (bool, error) {
return false, err
}
}
if result, err := q.matchesAllFields(s, key, dataVal, data); result || err != nil {
return q.matches(s, key, dataVal, data)
}

func (q *Query) matches(s *Store, key []byte, value reflect.Value, data interface{}) (bool, error) {
if result, err := q.matchesAllFields(s, key, value, data); result || err != nil {
return result, err
}
for _, orQuery := range q.ors {
if result, err := orQuery.matchesAllFields(s, key, dataVal, data); result || err != nil {
if result, err := orQuery.matches(s, key, value, data); result || err != nil {
return result, err
}
}
Expand Down

0 comments on commit b443def

Please sign in to comment.