-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathMongoCollection+Write.swift
541 lines (490 loc) · 24 KB
/
MongoCollection+Write.swift
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
import CLibMongoC
import NIO
import SwiftBSON
/// An extension of `MongoCollection` encapsulating write operations.
extension MongoCollection {
/**
* Encodes the provided value to BSON and inserts it. If the value is missing an identifier, one will be
* generated for it.
*
* - Parameters:
* - value: A `CollectionType` value to encode and insert
* - options: Optional `InsertOneOptions` to use when executing the command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns:
* An `EventLoopFuture<InsertOneResult?>`. On success, contains the result of performing the insert, or contains
* `nil` if the write concern is unacknowledged.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.WriteError` if an error occurs while performing the command.
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.InvalidArgumentError` if the options passed in form an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this collection's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the `CollectionType` to BSON.
*/
public func insertOne(
_ value: CollectionType,
options: InsertOneOptions? = nil,
session: ClientSession? = nil
) -> EventLoopFuture<InsertOneResult?> {
self.bulkWrite([.insertOne(value)], options: options?.toBulkWriteOptions(), session: session)
.flatMapThrowing { try InsertOneResult(from: $0) }
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
}
/**
* Encodes the provided values to BSON and inserts them. If any values are
* missing identifiers, the driver will generate them.
*
* - Parameters:
* - values: The `CollectionType` values to insert
* - options: optional `InsertManyOptions` to use while executing the operation
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns:
* An `EventLoopFuture<InsertManyResult?>`. On success, contains the result of performing the inserts, or
* contains `nil` if the write concern is unacknowledged.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.BulkWriteError` if an error occurs while performing any of the writes.
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.InvalidArgumentError` if the options passed in form an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this collection's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the `CollectionType` or options to BSON.
*/
public func insertMany(
_ values: [CollectionType],
options: InsertManyOptions? = nil,
session: ClientSession? = nil
) -> EventLoopFuture<InsertManyResult?> {
self.bulkWrite(values.map { .insertOne($0) }, options: options, session: session)
.flatMapThrowing { InsertManyResult(from: $0) }
}
/**
* Replaces a single document matching the provided filter in this collection.
*
* - Parameters:
* - filter: A `BSONDocument` representing the match criteria
* - replacement: The replacement value, a `CollectionType` value to be encoded and inserted
* - options: Optional `ReplaceOptions` to use when executing the command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns:
* An `EventLoopFuture<UpdateResult?>`. On success, contains the result of performing the replacement, or
* contains `nil` if the write concern is unacknowledged.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.WriteError` if an error occurs while performing the command.
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.InvalidArgumentError` if the options passed in form an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this collection's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the `CollectionType` or options to BSON.
*/
public func replaceOne(
filter: BSONDocument,
replacement: CollectionType,
options: ReplaceOptions? = nil,
session: ClientSession? = nil
) -> EventLoopFuture<UpdateResult?> {
let modelOptions = ReplaceOneModelOptions(
collation: options?.collation,
hint: options?.hint,
upsert: options?.upsert
)
let model = WriteModel.replaceOne(filter: filter, replacement: replacement, options: modelOptions)
return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session)
.flatMapThrowing { try UpdateResult(from: $0) }
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
}
/**
* Updates a single document matching the provided filter in this collection.
*
* - Parameters:
* - filter: A `BSONDocument` representing the match criteria
* - update: A `BSONDocument` representing the update to be applied to a matching document
* - options: Optional `UpdateOptions` to use when executing the command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns:
* An `EventLoopFuture<UpdateResult?>`. On success, contains the result of performing the update, or contains
* `nil` if the write concern is unacknowledged.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.WriteError` if an error occurs while performing the command.
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.InvalidArgumentError` if the options passed in form an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this collection's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*/
public func updateOne(
filter: BSONDocument,
update: BSONDocument,
options: UpdateOptions? = nil,
session: ClientSession? = nil
) -> EventLoopFuture<UpdateResult?> {
let modelOptions = UpdateModelOptions(
arrayFilters: options?.arrayFilters,
collation: options?.collation,
hint: options?.hint,
upsert: options?.upsert
)
let model: WriteModel<CollectionType> = .updateOne(filter: filter, update: update, options: modelOptions)
return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session)
.flatMapThrowing { try UpdateResult(from: $0) }
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
}
/**
* Updates a single document matching the provided filter in this collection.
*
* - Parameters:
* - filter: A `BSONDocument` representing the match criteria
* - pipeline: An array of `BSONDocument` representing the aggregation pipeline to be applied to a matching
* document
* - options: Optional `UpdateOptions` to use when executing the command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns:
* An `EventLoopFuture<UpdateResult?>`. On success, contains the result of performing the update, or contains
* `nil` if the write concern is unacknowledged.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.WriteError` if an error occurs while performing the command.
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.InvalidArgumentError` if the options passed in form an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this collection's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*/
public func updateOne(
filter: BSONDocument,
pipeline: [BSONDocument],
options: UpdateOptions? = nil,
session: ClientSession? = nil
) -> EventLoopFuture<UpdateResult?> {
let update = BSONDocument(pipeline.map { document in BSON.document(document) })
return self.updateOne(filter: filter, update: update, options: options, session: session)
}
/**
* Updates multiple documents matching the provided filter in this collection.
*
* - Parameters:
* - filter: A `BSONDocument` representing the match criteria
* - update: A `BSONDocument` representing the update to be applied to matching documents
* - options: Optional `UpdateOptions` to use when executing the command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns:
* An `EventLoopFuture<UpdateResult?>`. On success, contains the result of performing the update, or contains
* `nil` if the write concern is unacknowledged.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.WriteError` if an error occurs while performing the command.
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.InvalidArgumentError` if the options passed in form an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this collection's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*/
public func updateMany(
filter: BSONDocument,
update: BSONDocument,
options: UpdateOptions? = nil,
session: ClientSession? = nil
) -> EventLoopFuture<UpdateResult?> {
let modelOptions = UpdateModelOptions(
arrayFilters: options?.arrayFilters,
collation: options?.collation,
hint: options?.hint,
upsert: options?.upsert
)
let model: WriteModel<CollectionType> = .updateMany(filter: filter, update: update, options: modelOptions)
return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session)
.flatMapThrowing { try UpdateResult(from: $0) }
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
}
/**
* Updates multiple documents matching the provided filter in this collection.
*
* - Parameters:
* - filter: A `BSONDocument` representing the match criteria
* - pipeline: An array of `BSONDocument` representing the aggregation pipeline to be applied to matching
* documents
* - options: Optional `UpdateOptions` to use when executing the command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns:
* An `EventLoopFuture<UpdateResult?>`. On success, contains the result of performing the update, or contains
* `nil` if the write concern is unacknowledged.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.WriteError` if an error occurs while performing the command.
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.InvalidArgumentError` if the options passed in form an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this collection's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*/
public func updateMany(
filter: BSONDocument,
pipeline: [BSONDocument],
options: UpdateOptions? = nil,
session: ClientSession? = nil
) -> EventLoopFuture<UpdateResult?> {
let update = BSONDocument(pipeline.map { document in BSON.document(document) })
return self.updateMany(filter: filter, update: update, options: options, session: session)
}
/**
* Deletes a single matching document from the collection.
*
* - Parameters:
* - filter: A `BSONDocument` representing the match criteria
* - options: Optional `DeleteOptions` to use when executing the command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns:
* An `EventLoopFuture<DeleteResult?>`. On success, contains the result of performing the deletion, or contains
* `nil` if the write concern is unacknowledged.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.WriteError` if an error occurs while performing the command.
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.InvalidArgumentError` if the options passed in form an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this collection's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*/
public func deleteOne(
_ filter: BSONDocument,
options: DeleteOptions? = nil,
session: ClientSession? = nil
) -> EventLoopFuture<DeleteResult?> {
let modelOptions = DeleteModelOptions(collation: options?.collation, hint: options?.hint)
let model: WriteModel<CollectionType> = .deleteOne(filter, options: modelOptions)
return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session)
.flatMapThrowing { try DeleteResult(from: $0) }
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
}
/**
* Deletes all matching documents from the collection.
*
* - Parameters:
* - filter: Document representing the match criteria
* - options: Optional `DeleteOptions` to use when executing the command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns:
* An `EventLoopFuture<DeleteResult?>`. On success, contains the result of performing the deletions, or contains
* `nil` if the write concern is unacknowledged.
*
* If the future fails, the error is likely one of the following:
* - `MongoError.WriteError` if an error occurs while performing the command.
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
* - `MongoError.InvalidArgumentError` if the options passed in form an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this collection's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*/
public func deleteMany(
_ filter: BSONDocument,
options: DeleteOptions? = nil,
session: ClientSession? = nil
) -> EventLoopFuture<DeleteResult?> {
let modelOptions = DeleteModelOptions(collation: options?.collation, hint: options?.hint)
let model: WriteModel<CollectionType> = .deleteMany(filter, options: modelOptions)
return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session)
.flatMapThrowing { try DeleteResult(from: $0) }
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
}
}
/// Protocol indicating that an options type can be converted to a BulkWriteOptions.
private protocol BulkWriteOptionsConvertible {
var bypassDocumentValidation: Bool? { get }
var writeConcern: WriteConcern? { get }
func toBulkWriteOptions() -> BulkWriteOptions
}
/// Default implementation of the protocol.
private extension BulkWriteOptionsConvertible {
func toBulkWriteOptions() -> BulkWriteOptions {
BulkWriteOptions(
bypassDocumentValidation: self.bypassDocumentValidation,
writeConcern: self.writeConcern
)
}
}
// Write command options structs
/// Options to use when executing an `insertOne` command on a `MongoCollection`.
public struct InsertOneOptions: Codable, BulkWriteOptionsConvertible {
/// If true, allows the write to opt-out of document level validation.
public var bypassDocumentValidation: Bool?
/// An optional WriteConcern to use for the command.
public var writeConcern: WriteConcern?
/// Convenience initializer allowing bypassDocumentValidation to be omitted or optional
public init(bypassDocumentValidation: Bool? = nil, writeConcern: WriteConcern? = nil) {
self.bypassDocumentValidation = bypassDocumentValidation
self.writeConcern = writeConcern
}
}
/// Options to use when executing a multi-document insert operation on a `MongoCollection`.
public typealias InsertManyOptions = BulkWriteOptions
/// Options to use when executing an `update` command on a `MongoCollection`.
public struct UpdateOptions: Codable, BulkWriteOptionsConvertible {
/// A set of filters specifying to which array elements an update should apply.
public var arrayFilters: [BSONDocument]?
/// If true, allows the write to opt-out of document level validation.
public var bypassDocumentValidation: Bool?
/// Specifies a collation.
public var collation: BSONDocument?
/// A document or string that specifies the index to use to support the query. Only supported in server 4.2+.
public var hint: IndexHint?
/// When true, creates a new document if no document matches the query.
public var upsert: Bool?
/// An optional WriteConcern to use for the command.
public var writeConcern: WriteConcern?
/// Convenience initializer allowing any/all parameters to be optional
public init(
arrayFilters: [BSONDocument]? = nil,
bypassDocumentValidation: Bool? = nil,
collation: BSONDocument? = nil,
hint: IndexHint? = nil,
upsert: Bool? = nil,
writeConcern: WriteConcern? = nil
) {
self.arrayFilters = arrayFilters
self.bypassDocumentValidation = bypassDocumentValidation
self.collation = collation
self.hint = hint
self.upsert = upsert
self.writeConcern = writeConcern
}
}
/// Options to use when executing a `replace` command on a `MongoCollection`.
public struct ReplaceOptions: Codable, BulkWriteOptionsConvertible {
/// If true, allows the write to opt-out of document level validation.
public var bypassDocumentValidation: Bool?
/// Specifies a collation.
public var collation: BSONDocument?
/// A document or string that specifies the index to use to support the query. Only supported in server 4.2+.
public var hint: IndexHint?
/// When true, creates a new document if no document matches the query.
public var upsert: Bool?
/// An optional `WriteConcern` to use for the command.
public var writeConcern: WriteConcern?
/// Convenience initializer allowing any/all parameters to be optional
public init(
bypassDocumentValidation: Bool? = nil,
collation: BSONDocument? = nil,
hint: IndexHint? = nil,
upsert: Bool? = nil,
writeConcern: WriteConcern? = nil
) {
self.bypassDocumentValidation = bypassDocumentValidation
self.collation = collation
self.hint = hint
self.upsert = upsert
self.writeConcern = writeConcern
}
}
/// Options to use when executing a `delete` command on a `MongoCollection`.
public struct DeleteOptions: Codable, BulkWriteOptionsConvertible {
/// Specifies a collation.
public var collation: BSONDocument?
/// A document or string that specifies the index to use to support the query. Only supported in server 4.4+.
public var hint: IndexHint?
/// An optional `WriteConcern` to use for the command.
public var writeConcern: WriteConcern?
/// Convenience initializer allowing collation to be omitted or optional
public init(
collation: BSONDocument? = nil,
hint: IndexHint? = nil,
writeConcern: WriteConcern? = nil
) {
self.collation = collation
self.hint = hint
self.writeConcern = writeConcern
}
/// This is a requirement of the BulkWriteOptionsConvertible protocol.
/// Since it does not apply to deletions, we just set it to nil.
internal var bypassDocumentValidation: Bool? { nil }
}
// Write command results structs
/// The result of an `insertOne` command on a `MongoCollection`.
public struct InsertOneResult: Codable {
/// The identifier that was inserted. If the document doesn't have an identifier, this value
/// will be generated and added to the document before insertion.
public let insertedID: BSON
private enum CodingKeys: String, CodingKey {
case insertedID = "insertedId"
}
internal init?(from result: BulkWriteResult?) throws {
guard let result = result else {
return nil
}
guard let id = result.insertedIDs[0] else {
throw MongoError.InternalError(message: "BulkWriteResult missing _id for inserted document")
}
self.insertedID = id
}
}
/// The result of a multi-document insert operation on a `MongoCollection`.
public struct InsertManyResult: Codable {
/// Number of documents inserted.
public let insertedCount: Int
/// Map of the index of the document in `values` to the value of its ID
public let insertedIDs: [Int: BSON]
/// Internal initializer used for converting from a `BulkWriteResult` optional to an `InsertManyResult` optional.
internal init?(from result: BulkWriteResult?) {
guard let result = result else {
return nil
}
self.insertedCount = result.insertedCount
self.insertedIDs = result.insertedIDs
}
private enum CodingKeys: String, CodingKey {
case insertedCount, insertedIDs = "insertedIds"
}
}
/// The result of a `delete` command on a `MongoCollection`.
public struct DeleteResult: Codable {
/// The number of documents that were deleted.
public let deletedCount: Int
internal init?(from result: BulkWriteResult?) throws {
guard let result = result else {
return nil
}
self.deletedCount = result.deletedCount
}
}
/// The result of an `update` operation on a `MongoCollection`.
public struct UpdateResult: Codable {
/// The number of documents that matched the filter.
public let matchedCount: Int
/// The number of documents that were modified.
public let modifiedCount: Int
/// The identifier of the inserted document if an upsert took place.
public let upsertedID: BSON?
/// The number of documents that were upserted.
public let upsertedCount: Int
internal init?(from result: BulkWriteResult?) throws {
guard let result = result else {
return nil
}
self.matchedCount = result.matchedCount
self.modifiedCount = result.modifiedCount
self.upsertedCount = result.upsertedCount
if result.upsertedCount == 1 {
guard let id = result.upsertedIDs[0] else {
throw MongoError.InternalError(message: "BulkWriteResult missing _id for upserted document")
}
self.upsertedID = id
} else {
self.upsertedID = nil
}
}
private enum CodingKeys: String, CodingKey {
case matchedCount, modifiedCount, upsertedID = "upsertedId", upsertedCount
}
}