/
new_collection_dialer.go
69 lines (58 loc) · 1.63 KB
/
new_collection_dialer.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
package integrations
import (
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
)
//NewCollectionDialer -- dials a new mongo connection
func NewCollectionDialer(url string, dbname string, collectionname string) (collection Collection, err error) {
var session *mgo.Session
if session, err = mgo.Dial(url); err == nil {
session.SetMode(mgo.Monotonic, true)
db := session.DB(dbname)
collection = &CollectionRepo{
Col: db.C(collectionname),
session: session,
}
}
return
}
//FindOne -- finds record with given ID
func (s *CollectionRepo) FindOne(id string, result interface{}) (err error) {
if bson.IsObjectIdHex(id) {
hex := bson.ObjectIdHex(id)
err = s.Col.FindId(hex).One(result)
} else {
err = ErrInvalidID
}
return
}
//FindAndModify -- execute a normal upsert
func (s *CollectionRepo) FindAndModify(selector interface{}, update interface{}, result interface{}) (info *mgo.ChangeInfo, err error) {
change := mgo.Change{
Update: update.(bson.M),
ReturnNew: false,
}
info, err = s.Col.Find(selector.(bson.M)).Apply(change, result)
return
}
//UpsertID -- upserts the given object to the given id
func (s *CollectionRepo) UpsertID(id interface{}, update interface{}) (info *mgo.ChangeInfo, err error) {
info, err = s.Col.UpsertId(id, update)
return
}
//Close -- closes the connection
func (s *CollectionRepo) Close() {
if s.session != nil {
s.session.Close()
}
}
//Count -- counts the collection records
func (s *CollectionRepo) Count() (int, error) {
return s.Col.Count()
}
//Wake - will ping and reconnect if need be
func (s *CollectionRepo) Wake() {
if s.session.Ping() != nil {
s.session = s.session.Clone()
}
}