Skip to content

Commit

Permalink
Fix for Issue 105 - ForEach not setting key values
Browse files Browse the repository at this point in the history
  • Loading branch information
timshannon committed Oct 19, 2023
1 parent 7c18134 commit 9cb5df5
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
33 changes: 33 additions & 0 deletions foreach_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package badgerhold_test
import (
"fmt"
"testing"
"time"

"github.com/timshannon/badgerhold/v4"
)
Expand Down Expand Up @@ -48,3 +49,35 @@ func TestForEach(t *testing.T) {
}
})
}

func TestIssue105ForEachKeys(t *testing.T) {

type Person struct {
ID uint64 `badgerhold:"key"`
Name string
Gender string
Birth time.Time
}

testWrap(t, func(store *badgerhold.Store, t *testing.T) {
data := &Person{Name: "tester1"}
ok(t, store.Insert(badgerhold.NextSequence(), data))
equals(t, uint64(0), data.ID)

data = &Person{Name: "tester2"}
ok(t, store.Insert(badgerhold.NextSequence(), data))
equals(t, uint64(1), data.ID)

data = &Person{Name: "tester3"}
ok(t, store.Insert(badgerhold.NextSequence(), data))
equals(t, uint64(2), data.ID)

var id uint64 = 0

ok(t, store.ForEach(nil, func(record *Person) error {
assert(t, id == record.ID, record.Name+" incorrectly set key")
id++
return nil
}))
})
}
12 changes: 12 additions & 0 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -1263,10 +1263,22 @@ func (s *Store) forEach(tx *badger.Txn, query *Query, fn interface{}) error {
argType = argType.Elem()
}

keyField, hasKeyField := getKeyField(argType)

dataType := reflect.New(argType).Interface()
storer := s.newStorer(dataType)

return s.runQuery(tx, dataType, query, nil, query.skip, func(r *record) error {

if hasKeyField {
err := s.decodeKey(r.key, r.value.Elem().FieldByName(keyField.Name).Addr().Interface(), storer.Type())
if err != nil {
return err
}
}

out := fnVal.Call([]reflect.Value{r.value})

if len(out) != 1 {
return fmt.Errorf("foreach function does not return an error")
}
Expand Down

0 comments on commit 9cb5df5

Please sign in to comment.