feat: add batch inserter (#2755)

master
MarkJoyMa 2 years ago committed by GitHub
parent fc9b3ffdc1
commit a5fcf24c04
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -25,8 +25,23 @@ type (
}
)
// NewBulkInserter returns a BulkInserter.
// Deprecated. Use NewBatchInserter instead.
func NewBulkInserter(coll *mongo.Collection, interval ...time.Duration) *BulkInserter {
return newBulkInserter(coll, interval...)
}
// NewBatchInserter returns a BulkInserter.
func NewBatchInserter(coll Collection, interval ...time.Duration) (*BulkInserter, error) {
cloneColl, err := coll.Clone()
if err != nil {
return nil, err
}
return newBulkInserter(cloneColl, interval...), nil
}
// newBulkInserter returns a BulkInserter.
func newBulkInserter(coll *mongo.Collection, interval ...time.Duration) *BulkInserter {
inserter := &dbInserter{
collection: coll,
}

@ -25,3 +25,21 @@ func TestBulkInserter(t *testing.T) {
bulk.Flush()
})
}
func TestBatchInserter(t *testing.T) {
mt := mtest.New(t, mtest.NewOptions().ClientType(mtest.Mock))
defer mt.Close()
mt.Run("test", func(mt *mtest.T) {
mt.AddMockResponses(mtest.CreateSuccessResponse(bson.D{{Key: "ok", Value: 1}}...))
bulk, err := NewBatchInserter(createModel(mt).Collection)
assert.Equal(t, err, nil)
bulk.SetResultHandler(func(result *mongo.InsertManyResult, err error) {
assert.Nil(t, err)
assert.Equal(t, 2, len(result.InsertedIDs))
})
bulk.Insert(bson.D{{Key: "foo", Value: "bar"}})
bulk.Insert(bson.D{{Key: "foo", Value: "baz"}})
bulk.Flush()
})
}

Loading…
Cancel
Save