-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdatabase.go
More file actions
84 lines (71 loc) · 2.29 KB
/
database.go
File metadata and controls
84 lines (71 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package executor
import (
"context"
"fmt"
"github.com/bytebase/gomongo/internal/translator"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// executeShowCollections executes a show collections command.
func executeShowCollections(ctx context.Context, client *mongo.Client, database string) (*Result, error) {
names, err := client.Database(database).ListCollectionNames(ctx, bson.D{})
if err != nil {
return nil, fmt.Errorf("list collections failed: %w", err)
}
rows := make([]string, 0, len(names))
for _, name := range names {
doc := bson.M{"name": name}
jsonBytes, err := bson.MarshalExtJSONIndent(doc, false, false, "", " ")
if err != nil {
return nil, fmt.Errorf("marshal failed: %w", err)
}
rows = append(rows, string(jsonBytes))
}
return &Result{
Rows: rows,
RowCount: len(rows),
}, nil
}
// executeGetCollectionNames executes a db.getCollectionNames() command.
func executeGetCollectionNames(ctx context.Context, client *mongo.Client, database string) (*Result, error) {
return executeShowCollections(ctx, client, database)
}
// executeGetCollectionInfos executes a db.getCollectionInfos() command.
func executeGetCollectionInfos(ctx context.Context, client *mongo.Client, database string, op *translator.Operation) (*Result, error) {
filter := op.Filter
if filter == nil {
filter = bson.D{}
}
opts := options.ListCollections()
if op.NameOnly != nil {
opts.SetNameOnly(*op.NameOnly)
}
if op.AuthorizedCollections != nil {
opts.SetAuthorizedCollections(*op.AuthorizedCollections)
}
cursor, err := client.Database(database).ListCollections(ctx, filter, opts)
if err != nil {
return nil, fmt.Errorf("list collections failed: %w", err)
}
defer func() { _ = cursor.Close(ctx) }()
var rows []string
for cursor.Next(ctx) {
var doc bson.M
if err := cursor.Decode(&doc); err != nil {
return nil, fmt.Errorf("decode failed: %w", err)
}
jsonBytes, err := bson.MarshalExtJSONIndent(doc, false, false, "", " ")
if err != nil {
return nil, fmt.Errorf("marshal failed: %w", err)
}
rows = append(rows, string(jsonBytes))
}
if err := cursor.Err(); err != nil {
return nil, fmt.Errorf("cursor error: %w", err)
}
return &Result{
Rows: rows,
RowCount: len(rows),
}, nil
}