Skip to content

Commit

Permalink
require non empty index key
Browse files Browse the repository at this point in the history
  • Loading branch information
256dpi committed Aug 30, 2021
1 parent d99c9fa commit 74916aa
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
9 changes: 8 additions & 1 deletion indexes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,15 @@ func TestIndexViewCreateOne(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, []bson.M{}, readAll(csr))

// invalid index
// empty index
name, err := c.Indexes().CreateOne(nil, mongo.IndexModel{
Keys: bson.M{},
})
assert.Error(t, err)
assert.Empty(t, name)

// invalid index
name, err = c.Indexes().CreateOne(nil, mongo.IndexModel{
Keys: bson.M{
"bar": false,
},
Expand Down
5 changes: 5 additions & 0 deletions mongokit/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ type Index struct {

// CreateIndex will create and return a new index.
func CreateIndex(config IndexConfig) (*Index, error) {
// check key
if len(*config.Key) == 0 {
return nil, fmt.Errorf("empty index key")
}

// clone key and partial
config.Key = bsonkit.Clone(config.Key)
config.Partial = bsonkit.Clone(config.Partial)
Expand Down
7 changes: 6 additions & 1 deletion mongokit/index_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,15 @@ func mustHas(ok bool, err error) bool {
}

func TestIndex(t *testing.T) {
index, err := CreateIndex(IndexConfig{
Key: bsonkit.MustConvert(bson.M{}),
})
assert.Error(t, err)

d1 := bsonkit.MustConvert(bson.M{"a": "1"})
d2 := bsonkit.MustConvert(bson.M{"a": "1"})

index, err := CreateIndex(IndexConfig{
index, err = CreateIndex(IndexConfig{
Key: bsonkit.MustConvert(bson.M{
"a": int32(1),
}),
Expand Down

0 comments on commit 74916aa

Please sign in to comment.