/
indexes.go
93 lines (65 loc) · 1.91 KB
/
indexes.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
package indexes
import (
"strings"
"github.com/globalsign/mgo"
"go.aporeto.io/elemental"
"go.aporeto.io/manipulate"
"go.aporeto.io/manipulate/manipmongo"
"go.uber.org/zap"
)
// Ensure ensures the indexes declared in the specs are aligned.
func Ensure(m manipulate.Manipulator, model elemental.ModelManager, packageName string) (err error) {
indexes := GetIndexes(packageName, model)
for ident, mIndexes := range indexes {
if err = manipmongo.EnsureIndex(m, ident, mIndexes...); err != nil {
zap.L().Warn("Unable to ensure index", zap.Error(err))
}
}
return nil
}
// GetIndexes returns all the indexes for all the identity in the model
func GetIndexes(packageName string, model elemental.ModelManager) (mIndexes map[elemental.Identity][]mgo.Index) {
var indexes [][]string
mIndexes = map[elemental.Identity][]mgo.Index{}
for _, ident := range model.AllIdentities() {
if ident.Package != packageName {
continue
}
indexes = model.Indexes(ident)
if len(indexes) == 0 {
continue
}
iName := "index_" + ident.Name + "_"
for i := range indexes {
idx := mgo.Index{}
piName := iName
var hashedApplied bool
for _, name := range indexes[i] {
if hashedApplied {
panic("hashed index must not be a compound index")
}
switch name {
case ":shard":
piName = "shard_" + iName
case ":unique":
idx.Unique = true
default:
name = strings.ToLower(name)
if attSpec, ok := model.Identifiable(ident).(elemental.AttributeSpecifiable); ok {
if bsonName := attSpec.SpecificationForAttribute(name).BSONFieldName; bsonName != "" {
name = bsonName
}
}
idx.Key = append(idx.Key, name)
if strings.HasPrefix(name, "$hashed:") {
hashedApplied = true
}
}
}
idx.Name = piName + strings.Join(idx.Key, "_")
idx.Background = true
mIndexes[ident] = append(mIndexes[ident], idx)
}
}
return mIndexes
}