-
Notifications
You must be signed in to change notification settings - Fork 21
/
mongo_index.go
147 lines (127 loc) · 3.67 KB
/
mongo_index.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package orm
import (
"bytes"
"context"
"fmt"
"strconv"
"strings"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var setupIndexFunc []func(im *IndexModifier) error
type IndexModifier struct {
Key bson.D
Option *options.IndexOptions
Result IndexResult
}
func IndexKey(i any) string {
if _, ok := i.(bson.D); !ok {
panic("the key must be the bson.D type")
}
return buildKeyFromD(i.(bson.D))
}
func buildKeyFromD(k bson.D) string {
// hack the key builder
// see the default behavior in mongo.IndexModel.Options.Name
// > The default value is "[field1]_[direction1]_[field2]_[direction2]..."
var keys []string
for _, e := range k {
key := bytes.NewBuffer(nil)
key.WriteString(e.Key)
key.WriteString("_")
direction := strconv.FormatInt(int64(e.Value.(int)), 10)
key.WriteString(direction)
keys = append(keys, key.String())
}
return strings.Join(keys, "_")
}
type IndexResult struct {
ExistsIndex int
CreatedIndex int
}
func SetupIndexModel(c *mongo.Collection, keys []mongo.IndexModel) {
ctx := context.Background()
setupIndexFunc = append(setupIndexFunc, func(im *IndexModifier) error {
for index, k := range keys {
if buildKeyFromD(im.Key) == buildKeyFromD(k.Keys.(bson.D)) && im.Option != nil {
keys[index].Options = im.Option
}
}
res, err := ensureIndex(ctx, c, keys)
if err != nil {
return err
}
im.Result = res
return nil
})
}
type IndexOptionsHandler func(im *IndexModifier) error
func WithIndexNameHandler(index bson.D, opt *options.IndexOptions) IndexOptionsHandler {
return func(im *IndexModifier) error {
im.Key = index
im.Option = opt
return nil
}
}
func IndexCreateResult(exist *int, created *int) IndexOptionsHandler {
return func(im *IndexModifier) error {
ex, cr := im.Result.ExistsIndex, im.Result.CreatedIndex
exist = &ex
created = &cr
return nil
}
}
func EnsureAllIndex(fns ...IndexOptionsHandler) error {
opt := &IndexModifier{}
for _, f := range fns {
f(opt)
}
for _, f := range setupIndexFunc {
if err := f(opt); err != nil {
return err
}
}
return nil
}
// ensureIndex will ensure the index model provided is on the given collection.
// we should directly create the provided index , per the mongo doc, mongo will :
// 1. (before version v4.2), create the index even if the index (name) already exist , and not returns any errors.
// 2. (after version v4.2), returns an already exist error if the index (name) already exist , but the duplicate index will still be created.
func ensureIndex(ctx context.Context, c *mongo.Collection, keys []mongo.IndexModel) (IndexResult, error) {
idxs := c.Indexes()
cur, err := idxs.List(ctx, options.ListIndexes().SetBatchSize(1))
if err != nil {
return IndexResult{}, fmt.Errorf("ensureIndex: unable to list indexes: %w", err)
}
var idx []bson.M
if err := cur.All(ctx, &idx); err != nil {
return IndexResult{}, fmt.Errorf("ensureIndex: range indexes: %w", err)
}
exKeys := make(map[string]struct{})
for _, m := range idx {
exKeys[m["name"].(string)] = struct{}{}
}
keysToCreate := make([]mongo.IndexModel, 0, len(keys))
for _, k := range keys {
var keyName string
switch {
case k.Options == nil, k.Options.Name == nil:
keyName = buildKeyFromD(k.Keys.(bson.D))
case k.Options.Name != nil:
keyName = *k.Options.Name
}
if _, ok := exKeys[keyName]; !ok {
keysToCreate = append(keysToCreate, k)
}
}
if len(keysToCreate) > 0 {
if _, err := idxs.CreateMany(ctx, keysToCreate); err != nil {
return IndexResult{}, fmt.Errorf("ensureIndex: unable to create index: %w", err)
}
}
return IndexResult{
ExistsIndex: len(exKeys),
CreatedIndex: len(keysToCreate),
}, nil
}