Skip to content

Commit 3b60559

Browse files
authored
Godriver 1657 pass interface to cursor.all (#431)
1 parent c8156b0 commit 3b60559

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

mongo/cursor.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ package mongo
99
import (
1010
"context"
1111
"errors"
12+
"fmt"
1213
"io"
1314
"reflect"
1415

@@ -186,10 +187,18 @@ func (c *Cursor) Close(ctx context.Context) error {
186187
func (c *Cursor) All(ctx context.Context, results interface{}) error {
187188
resultsVal := reflect.ValueOf(results)
188189
if resultsVal.Kind() != reflect.Ptr {
189-
return errors.New("results argument must be a pointer to a slice")
190+
return fmt.Errorf("results argument must be a pointer to a slice, but was a %s", resultsVal.Kind())
190191
}
191192

192193
sliceVal := resultsVal.Elem()
194+
if sliceVal.Kind() == reflect.Interface {
195+
sliceVal = sliceVal.Elem()
196+
}
197+
198+
if sliceVal.Kind() != reflect.Slice {
199+
return fmt.Errorf("results argument must be a pointer to a slice, but was a pointer to %s", sliceVal.Kind())
200+
}
201+
193202
elementType := sliceVal.Type().Elem()
194203
var index int
195204
var err error

mongo/cursor_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,5 +157,25 @@ func TestCursor(t *testing.T) {
157157
assert.Nil(t, err, "All error: %v", err)
158158
assert.True(t, tbc.closed, "expected batch cursor to be closed but was not")
159159
})
160+
161+
t.Run("does not error given interface as parameter", func(t *testing.T) {
162+
var docs interface{} = []bson.D{}
163+
164+
cursor, err := newCursor(newTestBatchCursor(1, 5), nil)
165+
assert.Nil(t, err, "newCursor error: %v", err)
166+
167+
err = cursor.All(context.Background(), &docs)
168+
assert.Nil(t, err, "expected Nil, got error: %v", err)
169+
assert.Equal(t, 5, len(docs.([]bson.D)), "expected 5 documents, got %v", len(docs.([]bson.D)))
170+
})
171+
t.Run("errors when not given pointer to slice", func(t *testing.T) {
172+
var docs interface{} = "test"
173+
174+
cursor, err := newCursor(newTestBatchCursor(1, 5), nil)
175+
assert.Nil(t, err, "newCursor error: %v", err)
176+
177+
err = cursor.All(context.Background(), &docs)
178+
assert.NotNil(t, err, "expected error, got: %v", err)
179+
})
160180
})
161181
}

0 commit comments

Comments
 (0)