Skip to content

Commit 3501a14

Browse files
Merge pull request #49 from Scalingo/fix/12/missing_index
Add EnsureParanoidIndices method
2 parents 7ac84bf + a573000 commit 3501a14

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

mongo/document/document.go

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"fmt"
66
"time"
77

8+
"github.com/sirupsen/logrus"
9+
810
"gopkg.in/mgo.v2"
911
"gopkg.in/mgo.v2/bson"
1012

@@ -22,14 +24,23 @@ type document interface {
2224
Validable
2325
}
2426

27+
var _ document = &Base{}
28+
var _ document = &Paranoid{}
29+
2530
type scopable interface {
2631
scope(bson.M) bson.M
2732
}
2833

34+
var _ scopable = Base{}
35+
var _ scopable = Paranoid{}
36+
2937
type destroyable interface {
3038
destroy(ctx context.Context, collectionName string) error
3139
}
3240

41+
var _ destroyable = &Base{}
42+
var _ destroyable = &Paranoid{}
43+
3344
type Closer interface {
3445
Close()
3546
}
@@ -38,7 +49,10 @@ type Validable interface {
3849
Validate(ctx context.Context) *ValidationErrors
3950
}
4051

41-
// Create inser the document in the database, returns an error if document already exists and set CreatedAt timestamp
52+
var _ Validable = &Base{}
53+
54+
// Create inserts the document in the database, returns an error if document
55+
// already exists and set CreatedAt timestamp
4256
func Create(ctx context.Context, collectionName string, doc document) error {
4357
log := logger.Get(ctx)
4458
doc.ensureID()
@@ -221,3 +235,24 @@ func Update(ctx context.Context, collectionName string, update bson.M, doc docum
221235
log.WithField("query", update).Debugf("update %v", collectionName)
222236
return c.UpdateId(doc.getID(), update)
223237
}
238+
239+
func EnsureParanoidIndices(ctx context.Context, collectionNames ...string) {
240+
log := logger.Get(ctx)
241+
242+
for _, collectionName := range collectionNames {
243+
log = logger.Get(ctx).WithFields(logrus.Fields{
244+
"init": "setup-indices",
245+
"collection": collectionName,
246+
})
247+
ctx = logger.ToCtx(ctx, log)
248+
log.Info("Setup the MongoDB index")
249+
250+
c := mongo.Session(log).Clone().DB("").C(collectionName)
251+
defer c.Database.Session.Close()
252+
err := c.EnsureIndexKey("deleted_at")
253+
if err != nil {
254+
log.WithError(err).Error("fail to setup the deleted_at index")
255+
continue
256+
}
257+
}
258+
}

0 commit comments

Comments
 (0)