forked from go-mgo/mgo
-
Notifications
You must be signed in to change notification settings - Fork 17
/
bulk.go
351 lines (322 loc) · 9.76 KB
/
bulk.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
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
342
343
344
345
346
347
348
349
350
351
package mgo
import (
"bytes"
"sort"
"gopkg.in/mgo.v2/bson"
)
// Bulk represents an operation that can be prepared with several
// orthogonal changes before being delivered to the server.
//
// MongoDB servers older than version 2.6 do not have proper support for bulk
// operations, so the driver attempts to map its API as much as possible into
// the functionality that works. In particular, in those releases updates and
// removals are sent individually, and inserts are sent in bulk but have
// suboptimal error reporting compared to more recent versions of the server.
// See the documentation of BulkErrorCase for details on that.
//
// Relevant documentation:
//
// http://blog.mongodb.org/post/84922794768/mongodbs-new-bulk-api
//
type Bulk struct {
c *Collection
opcount int
actions []bulkAction
ordered bool
}
type bulkOp int
const (
bulkInsert bulkOp = iota + 1
bulkUpdate
bulkUpdateAll
bulkRemove
)
type bulkAction struct {
op bulkOp
docs []interface{}
idxs []int
}
type bulkUpdateOp []interface{}
type bulkDeleteOp []interface{}
// BulkResult holds the results for a bulk operation.
type BulkResult struct {
Matched int
Modified int // Available only for MongoDB 2.6+
// Be conservative while we understand exactly how to report these
// results in a useful and convenient way, and also how to emulate
// them with prior servers.
private bool
}
// BulkError holds an error returned from running a Bulk operation.
// Individual errors may be obtained and inspected via the Cases method.
type BulkError struct {
ecases []BulkErrorCase
}
func (e *BulkError) Error() string {
if len(e.ecases) == 0 {
return "invalid BulkError instance: no errors"
}
if len(e.ecases) == 1 {
return e.ecases[0].Err.Error()
}
msgs := make([]string, 0, len(e.ecases))
seen := make(map[string]bool)
for _, ecase := range e.ecases {
msg := ecase.Err.Error()
if !seen[msg] {
seen[msg] = true
msgs = append(msgs, msg)
}
}
if len(msgs) == 1 {
return msgs[0]
}
var buf bytes.Buffer
buf.WriteString("multiple errors in bulk operation:\n")
for _, msg := range msgs {
buf.WriteString(" - ")
buf.WriteString(msg)
buf.WriteByte('\n')
}
return buf.String()
}
type bulkErrorCases []BulkErrorCase
func (slice bulkErrorCases) Len() int { return len(slice) }
func (slice bulkErrorCases) Less(i, j int) bool { return slice[i].Index < slice[j].Index }
func (slice bulkErrorCases) Swap(i, j int) { slice[i], slice[j] = slice[j], slice[i] }
// BulkErrorCase holds an individual error found while attempting a single change
// within a bulk operation, and the position in which it was enqueued.
//
// MongoDB servers older than version 2.6 do not have proper support for bulk
// operations, so the driver attempts to map its API as much as possible into
// the functionality that works. In particular, only the last error is reported
// for bulk inserts and without any positional information, so the Index
// field is set to -1 in these cases.
type BulkErrorCase struct {
Index int // Position of operation that failed, or -1 if unknown.
Err error
}
// Cases returns all individual errors found while attempting the requested changes.
//
// See the documentation of BulkErrorCase for limitations in older MongoDB releases.
func (e *BulkError) Cases() []BulkErrorCase {
return e.ecases
}
// Bulk returns a value to prepare the execution of a bulk operation.
func (c *Collection) Bulk() *Bulk {
return &Bulk{c: c, ordered: true}
}
// Unordered puts the bulk operation in unordered mode.
//
// In unordered mode the indvidual operations may be sent
// out of order, which means latter operations may proceed
// even if prior ones have failed.
func (b *Bulk) Unordered() {
b.ordered = false
}
func (b *Bulk) action(op bulkOp, opcount int) *bulkAction {
var action *bulkAction
if len(b.actions) > 0 && b.actions[len(b.actions)-1].op == op {
action = &b.actions[len(b.actions)-1]
} else if !b.ordered {
for i := range b.actions {
if b.actions[i].op == op {
action = &b.actions[i]
break
}
}
}
if action == nil {
b.actions = append(b.actions, bulkAction{op: op})
action = &b.actions[len(b.actions)-1]
}
for i := 0; i < opcount; i++ {
action.idxs = append(action.idxs, b.opcount)
b.opcount++
}
return action
}
// Insert queues up the provided documents for insertion.
func (b *Bulk) Insert(docs ...interface{}) {
action := b.action(bulkInsert, len(docs))
action.docs = append(action.docs, docs...)
}
// Remove queues up the provided selectors for removing matching documents.
// Each selector will remove only a single matching document.
func (b *Bulk) Remove(selectors ...interface{}) {
action := b.action(bulkRemove, len(selectors))
for _, selector := range selectors {
if selector == nil {
selector = bson.D{}
}
action.docs = append(action.docs, &deleteOp{
Collection: b.c.FullName,
Selector: selector,
Flags: 1,
Limit: 1,
})
}
}
// RemoveAll queues up the provided selectors for removing all matching documents.
// Each selector will remove all matching documents.
func (b *Bulk) RemoveAll(selectors ...interface{}) {
action := b.action(bulkRemove, len(selectors))
for _, selector := range selectors {
if selector == nil {
selector = bson.D{}
}
action.docs = append(action.docs, &deleteOp{
Collection: b.c.FullName,
Selector: selector,
Flags: 0,
Limit: 0,
})
}
}
// Update queues up the provided pairs of updating instructions.
// The first element of each pair selects which documents must be
// updated, and the second element defines how to update it.
// Each pair matches exactly one document for updating at most.
func (b *Bulk) Update(pairs ...interface{}) {
if len(pairs)%2 != 0 {
panic("Bulk.Update requires an even number of parameters")
}
action := b.action(bulkUpdate, len(pairs)/2)
for i := 0; i < len(pairs); i += 2 {
selector := pairs[i]
if selector == nil {
selector = bson.D{}
}
action.docs = append(action.docs, &updateOp{
Collection: b.c.FullName,
Selector: selector,
Update: pairs[i+1],
})
}
}
// UpdateAll queues up the provided pairs of updating instructions.
// The first element of each pair selects which documents must be
// updated, and the second element defines how to update it.
// Each pair updates all documents matching the selector.
func (b *Bulk) UpdateAll(pairs ...interface{}) {
if len(pairs)%2 != 0 {
panic("Bulk.UpdateAll requires an even number of parameters")
}
action := b.action(bulkUpdate, len(pairs)/2)
for i := 0; i < len(pairs); i += 2 {
selector := pairs[i]
if selector == nil {
selector = bson.D{}
}
action.docs = append(action.docs, &updateOp{
Collection: b.c.FullName,
Selector: selector,
Update: pairs[i+1],
Flags: 2,
Multi: true,
})
}
}
// Upsert queues up the provided pairs of upserting instructions.
// The first element of each pair selects which documents must be
// updated, and the second element defines how to update it.
// Each pair matches exactly one document for updating at most.
func (b *Bulk) Upsert(pairs ...interface{}) {
if len(pairs)%2 != 0 {
panic("Bulk.Update requires an even number of parameters")
}
action := b.action(bulkUpdate, len(pairs)/2)
for i := 0; i < len(pairs); i += 2 {
selector := pairs[i]
if selector == nil {
selector = bson.D{}
}
action.docs = append(action.docs, &updateOp{
Collection: b.c.FullName,
Selector: selector,
Update: pairs[i+1],
Flags: 1,
Upsert: true,
})
}
}
// Run runs all the operations queued up.
//
// If an error is reported on an unordered bulk operation, the error value may
// be an aggregation of all issues observed. As an exception to that, Insert
// operations running on MongoDB versions prior to 2.6 will report the last
// error only due to a limitation in the wire protocol.
func (b *Bulk) Run() (*BulkResult, error) {
var result BulkResult
var berr BulkError
var failed bool
for i := range b.actions {
action := &b.actions[i]
var ok bool
switch action.op {
case bulkInsert:
ok = b.runInsert(action, &result, &berr)
case bulkUpdate:
ok = b.runUpdate(action, &result, &berr)
case bulkRemove:
ok = b.runRemove(action, &result, &berr)
default:
panic("unknown bulk operation")
}
if !ok {
failed = true
if b.ordered {
break
}
}
}
if failed {
sort.Sort(bulkErrorCases(berr.ecases))
return nil, &berr
}
return &result, nil
}
func (b *Bulk) runInsert(action *bulkAction, result *BulkResult, berr *BulkError) bool {
op := &insertOp{b.c.FullName, action.docs, 0}
if !b.ordered {
op.flags = 1 // ContinueOnError
}
lerr, err := b.c.writeOp(op, b.ordered)
return b.checkSuccess(action, berr, lerr, err)
}
func (b *Bulk) runUpdate(action *bulkAction, result *BulkResult, berr *BulkError) bool {
lerr, err := b.c.writeOp(bulkUpdateOp(action.docs), b.ordered)
if lerr != nil {
result.Matched += lerr.N
result.Modified += lerr.modified
}
return b.checkSuccess(action, berr, lerr, err)
}
func (b *Bulk) runRemove(action *bulkAction, result *BulkResult, berr *BulkError) bool {
lerr, err := b.c.writeOp(bulkDeleteOp(action.docs), b.ordered)
if lerr != nil {
result.Matched += lerr.N
result.Modified += lerr.modified
}
return b.checkSuccess(action, berr, lerr, err)
}
func (b *Bulk) checkSuccess(action *bulkAction, berr *BulkError, lerr *LastError, err error) bool {
if lerr != nil && len(lerr.ecases) > 0 {
for i := 0; i < len(lerr.ecases); i++ {
// Map back from the local error index into the visible one.
ecase := lerr.ecases[i]
idx := ecase.Index
if idx >= 0 {
idx = action.idxs[idx]
}
berr.ecases = append(berr.ecases, BulkErrorCase{idx, ecase.Err})
}
return false
} else if err != nil {
for i := 0; i < len(action.idxs); i++ {
berr.ecases = append(berr.ecases, BulkErrorCase{action.idxs[i], err})
}
return false
}
return true
}