-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollection.go
More file actions
121 lines (92 loc) · 2.25 KB
/
collection.go
File metadata and controls
121 lines (92 loc) · 2.25 KB
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
115
116
117
118
119
120
121
package mgoStreamingCollection
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
func CollectionExists(db *mgo.Database, name string) (bool, error) {
result, err := db.CollectionNames()
if err != nil {
return false, err
}
for _, v := range result {
if v == name {
return true, nil
}
}
return false, nil
}
func ConvertToCapped(c *mgo.Collection, size int) error {
return c.Database.Run(bson.D{{"convertToCapped", c.Name}, {"size", size}}, nil)
}
func createCappedCollection(db *mgo.Database, name string, size int) error {
return db.C(name).Create(&mgo.CollectionInfo{
Capped: true,
MaxBytes: size,
})
}
// Creates a capped collection called `collectionName`.
// if `collectionName` exists but is not capped, it is converted to a capped collection
//
func CreateOrConvertCollection(database *mgo.Database, collectionName string, size int) (*mgo.Collection, error) {
exists, err := CollectionExists(database, collectionName)
if err != nil {
return nil, err
}
if !exists {
err := createCappedCollection(database, collectionName, size)
if err != nil {
return nil, err
}
}
collection := database.C(collectionName)
collectionStats, err := Stats(collection)
if err != nil {
return nil, err
}
if !collectionStats.Capped || collectionStats.MaxBytes != size {
err = ConvertToCapped(collection, size)
if err != nil {
return nil, err
}
}
return collection, nil
}
func Stats(c *mgo.Collection) (*mgo.CollectionInfo, error) {
stats := struct {
Capped bool
Maxsize int `bson:"maxSize"`
}{}
err := c.Database.Run(bson.D{{"collStats", c.Name}}, &stats)
if err != nil {
return nil, err
}
result := mgo.CollectionInfo{
Capped: stats.Capped,
MaxBytes: stats.Maxsize,
}
return &result, nil
}
// Tails a query on a capped collection
// streams the returned documents over the channel passed in
// This method should be run in a goroutine
// closing the channel ends the goroutine
func TailQuery(query *mgo.Query, ch chan interface{}) {
defer func() {
recover()
}()
iter := query.Tail(-1)
defer iter.Close()
for {
var result interface{}
for iter.Next(&result) {
ch <- result
}
if err := iter.Err(); err != nil {
iter.Close()
}
if iter.Timeout() {
continue
}
iter = query.Tail(-1)
}
}