-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdb.go
113 lines (92 loc) · 2.17 KB
/
db.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
package lili
import (
"errors"
"log"
"os"
"time"
. "github.com/bearyinnovative/lili/model"
. "github.com/bearyinnovative/lili/util"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
var dbContext DatabaseType
type DatabaseType interface {
// return created, key_changed, error
UpsertItem(*Item) (bool, bool, error)
MarkNotified(*Item, bool) error
}
type Database struct {
itemColl *mgo.Collection
}
func init() {
mongoServer := os.Getenv("MONGO_SERVER")
if mongoServer == "" {
mongoServer = "localhost"
}
log.Println("db before dial:", mongoServer)
session, err := mgo.Dial(mongoServer)
if LogIfErr(err) {
panic(err)
}
// defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
dbContext = &Database{
itemColl: session.DB("lili").C("items"),
}
log.Println("mongo setup success")
}
func (db *Database) UpsertItem(h *Item) (bool, bool, error) {
keyChanged := false
if !h.IsValid() {
return false, keyChanged, errors.New("item invalid")
}
query := bson.M{
"identifier": h.Identifier,
}
count, err := db.itemColl.Find(query).Count()
if LogIfErr(err) {
return false, keyChanged, err
}
if count > 1 {
return false, keyChanged, errors.New("more than one item with same identifier")
}
h.Updated = time.Now()
if count == 0 {
err = db.itemColl.Insert(h)
if LogIfErr(err) {
return false, keyChanged, err
}
keyChanged = len(h.KeyHistory) > 0
return true, keyChanged, nil
}
var old *Item
err = db.itemColl.Find(query).One(&old)
if LogIfErr(err) {
return false, keyChanged, err
}
if old.Key != h.Key {
// log.Println("key updated")
keyChanged = true
h.KeyHistory = append(old.KeyHistory, old.Key)
} else {
h.KeyHistory = old.KeyHistory
}
err = db.itemColl.Update(query, h)
if LogIfErr(err) {
return false, keyChanged, err
}
return false, keyChanged, nil
}
func (db *Database) MarkNotified(item *Item, notified bool) error {
query := bson.M{
"identifier": item.Identifier,
}
var t time.Time
if notified {
t = time.Now()
} else {
t = time.Time{} // empty time means haven't notified
}
return db.itemColl.Update(query, bson.M{"$set": bson.M{"notified_at": t}})
}