Skip to content

Commit

Permalink
Merge pull request #95 from ftKnox/ftKnox-patch-add-haskey-query-oper…
Browse files Browse the repository at this point in the history
…ator

add support for matching against map keys
  • Loading branch information
timshannon committed Mar 8, 2020
2 parents 5752620 + 93de165 commit 0ac74f7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
9 changes: 9 additions & 0 deletions criteria.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const (
re // regular expression
fn // func
isnil // test's for nil
hk // match map keys

contains // slice only
any // slice only
Expand Down Expand Up @@ -328,6 +329,11 @@ func (c *Criterion) In(values ...interface{}) *Query {
return q
}

// HasKey tests if the field has a map key matching the passed in value
func (c *Criterion) HasKey(value interface{}) *Query {
return c.op(hk, value)
}

// RegExp will test if a field matches against the regular expression
// The Field Value will be converted to string (%s) before testing
func (c *Criterion) RegExp(expression *regexp.Regexp) *Query {
Expand Down Expand Up @@ -452,6 +458,9 @@ func (c *Criterion) test(s *Store, testValue interface{}, encoded bool, currentR
}

return false, nil
case hk:
v := reflect.ValueOf(recordValue).MapIndex(reflect.ValueOf(c.value))
return !reflect.ValueOf(v).IsZero(), nil
case re:
return c.value.(*regexp.Regexp).Match([]byte(fmt.Sprintf("%s", recordValue))), nil
case fn:
Expand Down
14 changes: 14 additions & 0 deletions find_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type ItemTest struct {
Fruit string
UpdateField string
UpdateIndex string `boltholdIndex:"UpdateIndex"`
MapVal map[string]string
}

func (i *ItemTest) equal(other *ItemTest) bool {
Expand Down Expand Up @@ -177,6 +178,9 @@ var testData = []ItemTest{
Name: "zebra",
Category: "animal",
Created: time.Now(),
MapVal: map[string]string{
"test": "testval",
},
},
}

Expand Down Expand Up @@ -578,6 +582,16 @@ var testResults = []test{
query: bolthold.Where("Category").Contains("cooked"),
result: []int{},
},
test{
name: "Map Has Key",
query: bolthold.Where("MapVal").HasKey("test"),
result: []int{16},
},
test{
name: "Map Has Key 2",
query: bolthold.Where("MapVal").HasKey("other"),
result: []int{},
},
}

func insertTestData(t *testing.T, store *bolthold.Store) {
Expand Down

0 comments on commit 0ac74f7

Please sign in to comment.