Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat: add ListIndexes and ListCollectionNames api #284

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,64 @@ func generateDroppedIndex(index []string) string {
return res
}

// ListIndex returns all indexes in collection
Copy link
Collaborator

@jiangz222 jiangz222 May 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo,ListIndexes

func (c *Collection) ListIndexes(ctx context.Context) ([]opts.IndexModel, error) {
cursor, err := c.collection.Indexes().List(ctx)
if err != nil {
return nil, err
}
defer cursor.Close(ctx)

var indexInfos []bson.M
err = cursor.All(ctx, &indexInfos)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use options.IndexOptions to make ListIndexes and transIndexInfoToIndexModel simpler?

	var indexOptions []options.IndexOptions
	err = cursor.All(ctx, &indexOptions)
	if err != nil {
		return nil, err
	}

if err != nil {
return nil, err
}

res := make([]opts.IndexModel, 0, len(indexInfos))
for _, indexInfo := range indexInfos {
model, err := transIndexInfoToIndexModel(indexInfo)
if err != nil {
return nil, err
}
res = append(res, model)
}
return res, err
}

// transIndexInfoToIndexModel transfer bson.M to qmgo opts.IndexModel
func transIndexInfoToIndexModel(indexInfo bson.M) (opts.IndexModel, error) {
bytes, err := bson.Marshal(indexInfo)
res := opts.IndexModel{}
if err != nil {
return res, err
}

indexOptions := options.IndexOptions{}
err = bson.Unmarshal(bytes, &indexOptions)
if err != nil {
return res, err
}

indexName := indexInfo["name"].(string)
keySlice := make([]string, 0)
if indexName == "_id_" {
keySlice = append(keySlice, "_id")
} else {
sortFields := strings.Split(indexName, "_")
for i := 0; i < len(sortFields); i += 2 {
field := sortFields[i]
if sortFields[i+1] == "-1" {
field = fmt.Sprintf("-%s", field)
}
keySlice = append(keySlice, field)
}
}
res.Key = keySlice
res.IndexOptions = &indexOptions
return res, nil
}

// DropCollection drops collection
// it's safe even collection is not exists
func (c *Collection) DropCollection(ctx context.Context) error {
Expand Down
26 changes: 26 additions & 0 deletions collection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,32 @@ func TestCollection_DropIndex(t *testing.T) {
ast.Error(err)
}

func TestCollection_ListIndexes(t *testing.T) {
ast := require.New(t)

cli := initClient("test")
defer cli.DropCollection(context.Background())

unique := []string{"id1"}
common := []string{"id2,id3", "id4,-id5"}
cli.EnsureIndexes(context.Background(), unique, common)

indexes, err := cli.ListIndexes(context.Background())
indexKeys := make([][]string, 0, len(indexes))
for _, index := range indexes {
indexKeys = append(indexKeys, index.Key)
}
ast.NoError(err)
ast.Equal(4, len(indexes))
ast.Contains(indexKeys, []string{"_id"})
ast.Contains(indexKeys, []string{"id1"})
ast.Contains(indexKeys, []string{"id2", "id3"})
ast.Contains(indexKeys, []string{"id4", "-id5"})

// same index,error
ast.Error(cli.EnsureIndexes(context.Background(), nil, unique))
}

func TestCollection_Insert(t *testing.T) {
ast := require.New(t)

Expand Down
6 changes: 6 additions & 0 deletions database.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"context"

opts "github.com/qiniu/qmgo/options"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
Expand Down Expand Up @@ -50,6 +51,11 @@ func (d *Database) DropDatabase(ctx context.Context) error {
return d.database.Drop(ctx)
}

// ListCollections lists all collections in the database.
func (d *Database) ListCollectionNames(ctx context.Context) ([]string, error) {
return d.database.ListCollectionNames(ctx, bson.D{}, nil)
}

// RunCommand executes the given command against the database.
//
// The runCommand parameter must be a document for the command to be executed. It cannot be nil.
Expand Down
7 changes: 6 additions & 1 deletion database_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,14 @@ func TestDatabase(t *testing.T) {
ast.Equal(dbName, cli.GetDatabaseName())
coll := cli.Collection(collName)
ast.Equal(collName, coll.GetCollectionName())
res, err := coll.InsertOne(context.Background(), bson.D{{Key: "x", Value: 1}})
ast.NoError(err)
ast.NotNil(res)
collNames, err := cli.ListCollectionNames(context.Background())
ast.NoError(err)
ast.Contains(collNames, collName)
cli.Collection(collName).DropCollection(context.Background())
cli.DropDatabase(context.Background())

}

func TestRunCommand(t *testing.T) {
Expand Down