Skip to content

Commit 431fe7c

Browse files
author
Alice Thum
committed
Close cursor before returning from All.
GODRIVER-1246 Change-Id: I907f4113c4f8c8428b176622edcb2bedc34fc9a6
1 parent a08c089 commit 431fe7c

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

mongo/cursor.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ func (c *Cursor) Close(ctx context.Context) error {
156156
// All iterates the cursor and decodes each document into results.
157157
// The results parameter must be a pointer to a slice. The slice pointed to by results will be completely overwritten.
158158
// If the cursor has been iterated, any previously iterated documents will not be included in results.
159+
// The cursor will be closed after the method has returned.
159160
func (c *Cursor) All(ctx context.Context, results interface{}) error {
160161
resultsVal := reflect.ValueOf(results)
161162
if resultsVal.Kind() != reflect.Ptr {
@@ -167,6 +168,8 @@ func (c *Cursor) All(ctx context.Context, results interface{}) error {
167168
var index int
168169
var err error
169170

171+
defer c.Close(ctx)
172+
170173
batch := c.batch // exhaust the current batch before iterating the batch cursor
171174
for {
172175
sliceVal, index, err = c.addFromBatch(sliceVal, elementType, batch, index)

mongo/cursor_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
type testBatchCursor struct {
1414
batches []*bsoncore.DocumentSequence
1515
batch *bsoncore.DocumentSequence
16+
closed bool
1617
}
1718

1819
func newTestBatchCursor(numBatches, batchSize int) *testBatchCursor {
@@ -74,6 +75,7 @@ func (tbc *testBatchCursor) Err() error {
7475
}
7576

7677
func (tbc *testBatchCursor) Close(context.Context) error {
78+
tbc.closed = true
7779
return nil
7880
}
7981

@@ -133,6 +135,17 @@ func TestCursor(t *testing.T) {
133135
require.Equal(t, doc, bson.D{{"foo", int32(index)}})
134136
}
135137
})
138+
139+
t.Run("cursor is closed after All is called", func(t *testing.T) {
140+
var docs []bson.D
141+
142+
tbc := newTestBatchCursor(1, 5)
143+
cursor, err := newCursor(tbc, nil)
144+
err = cursor.All(context.Background(), &docs)
145+
146+
require.Nil(t, err)
147+
require.True(t, tbc.closed)
148+
})
136149
})
137150
}
138151

0 commit comments

Comments
 (0)