forked from icza/minquery
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathminquery.go
More file actions
executable file
·341 lines (293 loc) · 8.94 KB
/
Copy pathminquery.go
File metadata and controls
executable file
·341 lines (293 loc) · 8.94 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// This file contains the MinQuery interface and its implementation.
package minquery
import (
"context"
"errors"
"fmt"
"github.com/izinga/mgo"
"github.com/izinga/mgo/bson"
mongoDriverBson "go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
// DefaultCursorCodec is the default CursorCodec value that is used if none
// is specified. The default implementation produces web-safe cursor strings.
var DefaultCursorCodec cursorCodec
var DefaultCursorCodecMongo cursorCodecMongo
var UseMongoDriver = false
// MinQuery is an mgo-like Query that supports cursors to continue listing documents
// where we left off. If a cursor is set, it specifies the last index entry
// that was already returned, and result documents will be listed after this.
type MinQuery interface {
// Sort asks the database to order returned documents according to
// the provided field names.
Sort(fields ...string) MinQuery
// Select enables selecting which fields should be retrieved for
// the results found.
Select(selector interface{}) MinQuery
// Limit restricts the maximum number of documents retrieved to n,
// and also changes the batch size to the same value.
Limit(n int) MinQuery
// Cursor sets the cursor, which specifies the last index entry
// that was already returned, and result documents will be listed after this.
// Parsing a cursor may fail which is not returned. If an invalid cursor
// is specified, All() will fail and return the error.
Cursor(c string) MinQuery
// CursorCoded sets the CursorCodec to be used to parse and to create cursors.
// This gives you the possibility to implement your own logic to create cursors,
// including encryption should you need it.
CursorCodec(cc CursorCodec) MinQuery
// All retrieves all documents from the result set into the provided slice.
// cursorFields lists the fields (in order) to be used to generate
// the returned cursor.
All(result interface{}, cursorFields ...string) (cursor string, err error)
}
// errTestValue is the error value returned for testing purposes.
var errTestValue = errors.New("Intentional testing error")
// minQuery is the MinQuery implementation.
type minQuery struct {
// db is the mgo Database to use
db *mgo.Database
dbMongo *mongo.Database
hint map[string]int
// Name of the collection
coll string
// filter document (query)
filter interface{}
// sort document
sort bson.D
sortMongo mongoDriverBson.D
// projection document (to retrieve only selected fields)
projection interface{}
// limit is the max number of results
limit int
// Cursor, need to store and supply it if query returns no results
cursor string
// cursorCodec to be used to parse and to create cursors
cursorCodec CursorCodec
cursorCodecMongo cursorCodecMongo
// cursorErr contains an error if an invalid cursor is supplied
cursorErr error
// min specifies the last index entry
min bson.D
minMongo mongoDriverBson.D
// testError is a helper field to aid testing errors to reach 100% coverage.
// May only be changed from tests! Zero value means normal operation.
testError bool
}
// New returns a new MinQuery.
func New(db *mgo.Database, coll string, query interface{}, hint map[string]int) MinQuery {
if db.Session.GetDriverDatabase() != nil {
UseMongoDriver = true
// fmt.Println("using mongo driver")
return &minQuery{
db: db,
dbMongo: db.Session.GetDriverDatabase(),
coll: coll,
filter: query,
hint: hint,
cursorCodec: DefaultCursorCodec,
cursorCodecMongo: DefaultCursorCodecMongo,
}
} else {
return &minQuery{
db: db,
coll: coll,
filter: query,
hint: hint,
cursorCodec: DefaultCursorCodec,
}
}
}
// Sort implements MinQuery.Sort().
func (mq *minQuery) Sort(fields ...string) MinQuery {
if UseMongoDriver {
mq.sortMongo = make(mongoDriverBson.D, 0, len(fields))
for _, field := range fields {
if field == "" {
continue
}
n := 1
if field[0] == '+' {
field = field[1:]
} else if field[0] == '-' {
n, field = -1, field[1:]
}
mq.sortMongo = append(mq.sortMongo, mongoDriverBson.E{Key: field, Value: n})
}
} else {
mq.sort = make(bson.D, 0, len(fields))
for _, field := range fields {
if field == "" {
continue
}
n := 1
if field[0] == '+' {
field = field[1:]
} else if field[0] == '-' {
n, field = -1, field[1:]
}
mq.sort = append(mq.sort, bson.DocElem{Name: field, Value: n})
}
}
return mq
}
// Select implements MinQuery.Select().
func (mq *minQuery) Select(selector interface{}) MinQuery {
mq.projection = selector
return mq
}
// Limit implements MinQuery.Limit().
func (mq *minQuery) Limit(n int) MinQuery {
mq.limit = n
return mq
}
// Cursor implements MinQuery.Cursor().
func (mq *minQuery) Cursor(c string) MinQuery {
if UseMongoDriver {
mq.cursor = c
if c != "" {
mq.minMongo, mq.cursorErr = mq.cursorCodecMongo.ParseCursorMongo(c)
} else {
mq.minMongo, mq.cursorErr = nil, nil
}
return mq
} else {
mq.cursor = c
if c != "" {
mq.min, mq.cursorErr = mq.cursorCodec.ParseCursor(c)
} else {
mq.min, mq.cursorErr = nil, nil
}
return mq
}
}
// CursorCodec implements MinQuery.CursorCodec().
func (mq *minQuery) CursorCodec(cc CursorCodec) MinQuery {
mq.cursorCodec = cc
return mq
}
// All implements MinQuery.All().
func (mq *minQuery) All(result interface{}, cursorFields ...string) (cursor string, err error) {
if UseMongoDriver {
db := mq.dbMongo
if mq.cursorErr != nil {
return "", mq.cursorErr
}
cmd := mongoDriverBson.D{
{Key: "find", Value: mq.coll},
{Key: "limit", Value: mq.limit},
{Key: "batchSize", Value: mq.limit},
{Key: "singleBatch", Value: true},
}
if mq.filter != nil {
cmd = append(cmd, mongoDriverBson.E{Key: "filter", Value: mq.filter})
}
if mq.sortMongo != nil {
cmd = append(cmd, mongoDriverBson.E{Key: "sort", Value: mq.sortMongo})
}
if mq.projection != nil {
cmd = append(cmd, mongoDriverBson.E{Key: "projection", Value: mq.projection})
}
if mq.minMongo != nil {
cmd = append(cmd,
mongoDriverBson.E{Key: "skip", Value: 0},
mongoDriverBson.E{Key: "max", Value: mq.minMongo},
mongoDriverBson.E{Key: "hint", Value: mq.hint},
)
}
fmt.Printf("\ncmd %+v\n", cmd)
mcur, merr := db.RunCommandCursor(context.Background(), cmd)
if merr != nil {
return "", merr
}
cursor = mq.cursor
var lastRaw mongoDriverBson.Raw
for mcur.Next(context.TODO()) {
lastRaw = mcur.Current
}
if len(lastRaw) > 0 {
cursorData := make(mongoDriverBson.D, len(cursorFields))
for i, cf := range cursorFields {
cursorData[i] = mongoDriverBson.E{Key: cf, Value: lastRaw.Lookup(cf)}
}
cursor, err = mq.cursorCodecMongo.CreateCursorMongo(cursorData)
if err != nil {
return
}
}
err = mcur.All(context.Background(), result)
} else {
if mq.cursorErr != nil {
return "", mq.cursorErr
}
// Mongodb "find" reference:
// https://docs.mongodb.com/manual/reference/command/find/
cmd := bson.D{
{Name: "find", Value: mq.coll},
{Name: "limit", Value: mq.limit},
{Name: "batchSize", Value: mq.limit},
{Name: "singleBatch", Value: true},
}
if mq.filter != nil {
cmd = append(cmd, bson.DocElem{Name: "filter", Value: mq.filter})
}
if mq.sort != nil {
cmd = append(cmd, bson.DocElem{Name: "sort", Value: mq.sort})
}
if mq.projection != nil {
cmd = append(cmd, bson.DocElem{Name: "projection", Value: mq.projection})
}
if mq.min != nil {
// min is inclusive, skip the first (which is the previous last)
cmd = append(cmd,
bson.DocElem{Name: "skip", Value: 0},
// bson.DocElem{Name: "min", Value: mq.min},
bson.DocElem{Name: "max", Value: mq.min},
bson.DocElem{Name: "hint", Value: mq.hint},
)
}
var res struct {
OK int `bson:"ok"`
WaitedMS int `bson:"waitedMS"`
Cursor struct {
ID interface{} `bson:"id"`
NS string `bson:"ns"`
FirstBatch []bson.Raw `bson:"firstBatch"`
} `bson:"cursor"`
}
fmt.Printf("\ncmd %+v\n", cmd)
if err = mq.db.Run(cmd, &res); err != nil {
return
}
firstBatch := res.Cursor.FirstBatch
if len(firstBatch) > 0 {
if len(cursorFields) > 0 {
// create cursor from the last document
var doc bson.M
err = firstBatch[len(firstBatch)-1].Unmarshal(&doc)
if mq.testError {
err = errTestValue
}
if err != nil {
return
}
cursorData := make(bson.D, len(cursorFields))
for i, cf := range cursorFields {
cursorData[i] = bson.DocElem{Name: cf, Value: doc[cf]}
}
cursor, err = mq.cursorCodec.CreateCursor(cursorData)
if err != nil {
return
}
}
} else {
// No more results. Use the same cursor that was used for the query.
// It's possible that the last doc was returned previously, and there
// are no more.
cursor = mq.cursor
}
// Unmarshal results (FirstBatch) into the user-provided value:
err = mq.db.C(mq.coll).NewIter(nil, firstBatch, 0, nil).All(result)
}
return
}