forked from xiaonanln/goworld
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongodb.go
114 lines (97 loc) · 2.51 KB
/
mongodb.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
package entitystoragemongodb
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"io"
"github.com/xiaonanln/goworld/engine/common"
"github.com/xiaonanln/goworld/engine/gwlog"
"github.com/xiaonanln/goworld/engine/storage/storage_common"
)
const (
_DEFAULT_DB_NAME = "goworld"
)
var (
db *mgo.Database
)
type mongoDBEntityStorge struct {
db *mgo.Database
}
// OpenMongoDB opens mongodb as entity storage
func OpenMongoDB(url string, dbname string) (storagecommon.EntityStorage, error) {
gwlog.Debugf("Connecting MongoDB ...")
session, err := mgo.Dial(url)
if err != nil {
return nil, err
}
session.SetMode(mgo.Monotonic, true)
if dbname == "" {
// if db is not specified, use default
dbname = _DEFAULT_DB_NAME
}
db = session.DB(dbname)
return &mongoDBEntityStorge{
db: db,
}, nil
}
func (es *mongoDBEntityStorge) Write(typeName string, entityID common.EntityID, data interface{}) error {
col := es.getCollection(typeName)
_, err := col.UpsertId(entityID, bson.M{
"data": data,
})
return err
}
func (es *mongoDBEntityStorge) Read(typeName string, entityID common.EntityID) (interface{}, error) {
col := es.getCollection(typeName)
q := col.FindId(entityID)
var doc bson.M
err := q.One(&doc)
if err != nil {
return nil, err
}
return es.convertM2Map(doc["data"].(bson.M)), nil
}
func (es *mongoDBEntityStorge) convertM2Map(m bson.M) map[string]interface{} {
ma := map[string]interface{}(m)
for k, v := range ma {
if m, ok := v.(bson.M); ok {
ma[k] = es.convertM2Map(m)
}
}
return ma
}
func (es *mongoDBEntityStorge) getCollection(typeName string) *mgo.Collection {
return es.db.C(typeName)
}
func (es *mongoDBEntityStorge) List(typeName string) ([]common.EntityID, error) {
col := es.getCollection(typeName)
var docs []bson.M
err := col.Find(nil).Select(bson.M{"_id": 1}).All(&docs)
if err != nil {
return nil, err
}
entityIDs := make([]common.EntityID, len(docs))
for i, doc := range docs {
entityIDs[i] = common.EntityID(doc["_id"].(string))
}
return entityIDs, nil
}
func (es *mongoDBEntityStorge) Exists(typeName string, entityID common.EntityID) (bool, error) {
col := es.getCollection(typeName)
query := col.FindId(entityID)
var doc bson.M
err := query.One(&doc)
if err == nil {
// doc found
return true, nil
} else if err == mgo.ErrNotFound {
return false, nil
} else {
return false, err
}
}
func (es *mongoDBEntityStorge) Close() {
es.db.Session.Close()
}
func (es *mongoDBEntityStorge) IsEOF(err error) bool {
return err == io.EOF || err == io.ErrUnexpectedEOF
}