Skip to content

Commit

Permalink
Add function ForEach() to allow document iteration
Browse files Browse the repository at this point in the history
  • Loading branch information
ostafen committed Apr 13, 2022
1 parent 15f63db commit e17a2ce
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
30 changes: 30 additions & 0 deletions db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,36 @@ func TestFindFirst(t *testing.T) {
})
}

func TestForEach(t *testing.T) {
runCloverTest(t, "test-data/todos.json", func(t *testing.T, db *c.DB) {
n, err := db.Query("todos").Where(c.Field("completed").IsTrue()).Count()
require.NoError(t, err)

m := 0
err = db.Query("todos").Where(c.Field("completed").IsTrue()).ForEach(func(doc *c.Document) bool {
m++
return true
})
require.NoError(t, err)
require.Equal(t, n, m)
})
}

func TestForEachStop(t *testing.T) {
runCloverTest(t, "test-data/todos.json", func(t *testing.T, db *c.DB) {
n := 0
err := db.Query("todos").ForEach(func(doc *c.Document) bool {
if n < 100 {
n++
return true
}
return false
})
require.NoError(t, err)
require.Equal(t, n, 100)
})
}

func genRandomFieldName() string {
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

Expand Down
11 changes: 11 additions & 0 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ func (q *Query) FindFirst() (*Document, error) {
return doc, err
}

// ForEach runs the consumer function for each document matching the provied query.
// If false is returned from the consumer function, then the iteration is stopped.
func (q *Query) ForEach(consumer func(_ *Document) bool) error {
return q.engine.IterateDocs(q, func(doc *Document) error {
if !consumer(doc) {
return errStopIteration
}
return nil
})
}

// Update updates all the document selected by q using the provided updateMap.
// Each update is specified by a mapping fieldName -> newValue.
func (q *Query) Update(updateMap map[string]interface{}) error {
Expand Down

0 comments on commit e17a2ce

Please sign in to comment.