forked from coze-cloud/clerk
/
index_creator.go
70 lines (59 loc) 路 1.34 KB
/
index_creator.go
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
package mongodb
import (
"context"
"github.com/Becklyn/clerk/v4"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type indexCreator struct {
connection *Connection
collection *clerk.Collection
}
func newIndexCreator(connection *Connection, collection *clerk.Collection) *indexCreator {
return &indexCreator{
connection: connection,
collection: collection,
}
}
func (c *indexCreator) ExecuteCreate(
ctx context.Context,
create *clerk.Create[*clerk.Index],
) error {
models := []mongo.IndexModel{}
for _, index := range create.Data {
fields := bson.D{}
for _, field := range index.Fields {
fields = append(fields, bson.E{
Key: field.Key,
Value: func() any {
switch field.Type.String() {
case "ascending":
return 1
case "descending":
return -1
case "text":
return "text"
}
return nil
}(),
})
}
opts := options.
Index().
SetName(index.Name).
SetUnique(index.IsUnique)
models = append(models, mongo.IndexModel{
Keys: fields,
Options: opts,
})
}
createCtx, cancel := c.connection.config.GetContext(ctx)
defer cancel()
_, err := c.connection.client.
Database(c.collection.Database.Name).
Collection(c.collection.Name).
Indexes().
CreateMany(createCtx, models)
return err
}