-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathMongoDatabase.swift
432 lines (409 loc) · 19.4 KB
/
MongoDatabase.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
import MongoSwift
/// A MongoDB Database.
public struct MongoDatabase {
/// Encoder used by this database for BSON conversions. This encoder's options are inherited by collections derived
/// from this database.
public var encoder: BSONEncoder { self.asyncDB.encoder }
/// Decoder whose options are inherited by collections derived from this database.
public var decoder: BSONDecoder { self.asyncDB.decoder }
/// The name of this database.
public var name: String { self.asyncDB.name }
/// The `ReadConcern` set on this database, or `nil` if one is not set.
public var readConcern: ReadConcern? { self.asyncDB.readConcern }
/// The `ReadPreference` set on this database
public var readPreference: ReadPreference { self.asyncDB.readPreference }
/// The `WriteConcern` set on this database, or `nil` if one is not set.
public var writeConcern: WriteConcern? { self.asyncDB.writeConcern }
/// The underlying asynchronous database.
internal let asyncDB: MongoSwift.MongoDatabase
/// The client this database was derived from. We store this to ensure it remains open for as long as this object
/// is in scope.
private let client: MongoClient
/// Initializes a new `MongoDatabase` instance wrapping the provided async database.
internal init(client: MongoClient, asyncDB: MongoSwift.MongoDatabase) {
self.client = client
self.asyncDB = asyncDB
}
/**
* Drops this database.
* - Parameters:
* - options: An optional `DropDatabaseOptions` to use when executing this command
* - session: An optional `ClientSession` to use for this command
*
* - Throws:
* - `MongoError.CommandError` if an error occurs that prevents the command from executing.
*/
public func drop(options: DropDatabaseOptions? = nil, session: ClientSession? = nil) throws {
try self.asyncDB.drop(options: options, session: session?.asyncSession).wait()
}
/**
* Access a collection within this database. If an option is not specified in the `MongoCollectionOptions` param,
* the collection will inherit the value from the parent database or the default if the db's option is not set.
* To override an option inherited from the db (e.g. a read concern) with the default value, it must be explicitly
* specified in the options param (e.g. ReadConcern.serverDefault, not nil).
*
* - Parameters:
* - name: the name of the collection to get
* - options: options to set on the returned collection
*
* - Returns: the requested `MongoCollection<Document>`
*/
public func collection(_ name: String, options: MongoCollectionOptions? = nil) -> MongoCollection<BSONDocument> {
self.collection(name, withType: BSONDocument.self, options: options)
}
/**
* Access a collection within this database, and associates the specified `Codable` type `T` with the
* returned `MongoCollection`. This association only exists in the context of this particular
* `MongoCollection` instance. If an option is not specified in the `MongoCollectionOptions` param, the
* collection will inherit the value from the parent database or the default if the db's option is not set.
* To override an option inherited from the db (e.g. a read concern) with the default value, it must be explicitly
* specified in the options param (e.g. ReadConcern.serverDefault, not nil).
*
* - Parameters:
* - name: the name of the collection to get
* - options: options to set on the returned collection
*
* - Returns: the requested `MongoCollection<T>`
*/
public func collection<T: Codable>(
_ name: String,
withType _: T.Type,
options: MongoCollectionOptions? = nil
) -> MongoCollection<T> {
let asyncColl = self.asyncDB.collection(name, withType: T.self, options: options)
return MongoCollection(client: self.client, asyncCollection: asyncColl)
}
/**
* Creates a collection in this database with the specified options.
*
* - Parameters:
* - name: a `String`, the name of the collection to create
* - options: Optional `CreateCollectionOptions` to use for the collection
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns: the newly created `MongoCollection<Document>`
*
* - Throws:
* - `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.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*/
public func createCollection(
_ name: String,
options: CreateCollectionOptions? = nil,
session: ClientSession? = nil
) throws -> MongoCollection<BSONDocument> {
try self.createCollection(name, withType: BSONDocument.self, options: options, session: session)
}
/**
* Creates a collection in this database with the specified options, and associates the
* specified `Codable` type `T` with the returned `MongoCollection`. This association only
* exists in the context of this particular `MongoCollection` instance.
*
*
* - Parameters:
* - name: a `String`, the name of the collection to create
* - options: Optional `CreateCollectionOptions` to use for the collection
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns: the newly created `MongoCollection<T>`
*
* - Throws:
* - `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.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*/
public func createCollection<T: Codable>(
_ name: String,
withType type: T.Type,
options: CreateCollectionOptions? = nil,
session: ClientSession? = nil
) throws -> MongoCollection<T> {
let asyncColl = try self.asyncDB.createCollection(
name,
withType: type,
options: options,
session: session?.asyncSession
)
.wait()
return MongoCollection(client: self.client, asyncCollection: asyncColl)
}
/**
* Lists all the collections in this database.
*
* - Parameters:
* - filter: a `Document`, optional criteria to filter results by
* - options: Optional `ListCollectionsOptions` to use when executing this command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns: a `MongoCursor` over an array of `CollectionSpecification`s
*
* - Throws:
* - `MongoError.InvalidArgumentError` if the options passed are an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
*/
public func listCollections(
_ filter: BSONDocument? = nil,
options: ListCollectionsOptions? = nil,
session: ClientSession? = nil
) throws -> MongoCursor<CollectionSpecification> {
let asyncCursor =
try self.asyncDB.listCollections(filter, options: options, session: session?.asyncSession).wait()
return MongoCursor(wrapping: asyncCursor, client: self.client)
}
/**
* Gets a list of `MongoCollection`s in this database.
*
* - Parameters:
* - filter: a `Document`, optional criteria to filter results by
* - options: Optional `ListCollectionsOptions` to use when executing this command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns: An array of `MongoCollection`s that match the provided filter.
*
* - Throws:
* - `MongoError.InvalidArgumentError` if the options passed are an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
*/
public func listMongoCollections(
_ filter: BSONDocument? = nil,
options: ListCollectionsOptions? = nil,
session: ClientSession? = nil
) throws -> [MongoCollection<BSONDocument>] {
try self.listCollectionNames(filter, options: options, session: session).map { name in
self.collection(name)
}
}
/**
* Gets a list of names of collections in this database.
*
* - Parameters:
* - filter: a `Document`, optional criteria to filter results by
* - options: Optional `ListCollectionsOptions` to use when executing this command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns: A `[String]` containing names of collections that match the provided filter.
*
* - Throws:
* - `MongoError.InvalidArgumentError` if the options passed are an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
*/
public func listCollectionNames(
_ filter: BSONDocument? = nil,
options: ListCollectionsOptions? = nil,
session: ClientSession? = nil
) throws -> [String] {
try self.asyncDB.listCollectionNames(filter, options: options, session: session?.asyncSession).wait()
}
/**
* Issues a MongoDB command against this database.
*
* - Parameters:
* - command: a `Document` containing the command to issue against the database
* - options: Optional `RunCommandOptions` to use when executing this command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns: a `Document` containing the server response for the command
*
* - Throws:
* - `MongoError.InvalidArgumentError` if `requests` is empty.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.WriteError` if any error occurs while the command was performing a write.
* - `MongoError.CommandError` if an error occurs that prevents the command from being performed.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*
* - Note: Attempting to specify an API version in this command is considered undefined behavior. API version may
* only be configured at the `MongoClient` level.
*/
@discardableResult
public func runCommand(
_ command: BSONDocument,
options: RunCommandOptions? = nil,
session: ClientSession? = nil
) throws -> BSONDocument {
try self.asyncDB.runCommand(command, options: options, session: session?.asyncSession).wait()
}
/**
* Starts a `ChangeStream` on a database. Excludes system collections.
*
* - Parameters:
* - pipeline: An array of aggregation pipeline stages to apply to the events returned by the change stream.
* - options: An optional `ChangeStreamOptions` to use when constructing the change stream.
* - session: An optional `ClientSession` to use with this change stream.
*
* - Returns: A `ChangeStream` on all collections in a database.
*
* - Throws:
* - `MongoError.CommandError` if an error occurs on the server while creating the change stream.
* - `MongoError.InvalidArgumentError` if the options passed formed an invalid combination.
* - `MongoError.InvalidArgumentError` if the `_id` field is projected out of the change stream documents by the
* pipeline.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/changeStreams/
* - https://docs.mongodb.com/manual/meta/aggregation-quick-reference/
* - https://docs.mongodb.com/manual/reference/system-collections/
*
* - Note: Supported in MongoDB version 4.0+ only.
*/
public func watch(
_ pipeline: [BSONDocument] = [],
options: ChangeStreamOptions? = nil,
session: ClientSession? = nil
) throws -> ChangeStream<ChangeStreamEvent<BSONDocument>> {
try self.watch(
pipeline,
options: options,
session: session,
withEventType: ChangeStreamEvent<BSONDocument>.self
)
}
/**
* Starts a `ChangeStream` on a database. Excludes system collections.
* Associates the specified `Codable` type `T` with the `fullDocument` field in the `ChangeStreamEvent`s emitted
* by the returned `ChangeStream`.
*
* - Parameters:
* - pipeline: An array of aggregation pipeline stages to apply to the events returned by the change stream.
* - options: An optional `ChangeStreamOptions` to use when constructing the change stream.
* - session: An optional `ClientSession` to use with this change stream.
* - withFullDocumentType: The type that the `fullDocument` field of the emitted `ChangeStreamEvent`s will be
* decoded to.
*
* - Returns: A `ChangeStream` on all collections in a database.
*
* - Throws:
* - `MongoError.CommandError` if an error occurs on the server while creating the change stream.
* - `MongoError.InvalidArgumentError` if the options passed formed an invalid combination.
* - `MongoError.InvalidArgumentError` if the `_id` field is projected out of the change stream documents by the
* pipeline.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/changeStreams/
* - https://docs.mongodb.com/manual/meta/aggregation-quick-reference/
* - https://docs.mongodb.com/manual/reference/system-collections/
*
* - Note: Supported in MongoDB version 4.0+ only.
*/
public func watch<FullDocType: Codable>(
_ pipeline: [BSONDocument] = [],
options: ChangeStreamOptions? = nil,
session: ClientSession? = nil,
withFullDocumentType _: FullDocType.Type
) throws -> ChangeStream<ChangeStreamEvent<FullDocType>> {
try self.watch(
pipeline,
options: options,
session: session,
withEventType: ChangeStreamEvent<FullDocType>.self
)
}
/**
* Starts a `ChangeStream` on a database. Excludes system collections.
* Associates the specified `Codable` type `T` with the returned `ChangeStream`.
*
* - Parameters:
* - pipeline: An array of aggregation pipeline stages to apply to the events returned by the change stream.
* - options: An optional `ChangeStreamOptions` to use when constructing the `ChangeStream`.
* - session: An optional `ClientSession` to use with this change stream.
* - withEventType: The type that the entire change stream response will be decoded to and that will be returned
* when iterating through the change stream.
*
* - Returns: A `ChangeStream` on all collections in a database.
*
* - Throws:
* - `MongoError.CommandError` if an error occurs on the server while creating the change stream.
* - `MongoError.InvalidArgumentError` if the options passed formed an invalid combination.
* - `MongoError.InvalidArgumentError` if the `_id` field is projected out of the change stream documents by the
* pipeline.
*
* - SeeAlso:
* - https://docs.mongodb.com/manual/changeStreams/
* - https://docs.mongodb.com/manual/meta/aggregation-quick-reference/
* - https://docs.mongodb.com/manual/reference/system-collections/
*
* - Note: Supported in MongoDB version 4.0+ only.
*/
public func watch<EventType: Codable>(
_ pipeline: [BSONDocument] = [],
options: ChangeStreamOptions? = nil,
session: ClientSession? = nil,
withEventType _: EventType.Type
) throws -> ChangeStream<EventType> {
let asyncStream = try self.asyncDB.watch(
pipeline,
options: options,
session: session?.asyncSession,
withEventType: EventType.self
).wait()
return ChangeStream(wrapping: asyncStream, client: self.client)
}
/**
* Runs an aggregation framework pipeline against this database for pipeline stages that do not require an
* underlying collection, such as `$currentOp` and `$listLocalSessions`.
*
* - Parameters:
* - pipeline: an `[BSONDocument]` containing the pipeline of aggregation operations to perform
* - options: Optional `AggregateOptions` to use when executing the command
* - session: Optional `ClientSession` to use when executing this command
*
* - Returns:
* A `MongoCursor` over the resulting documents.
*
* Throws:
* - `MongoError.CommandError` if an error occurs on the server while executing the aggregation
* - `MongoError.InvalidArgumentError` if the options passed are an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this database's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*
* - SeeAlso: https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/#db-aggregate-stages
*/
public func aggregate(
_ pipeline: [BSONDocument],
options: AggregateOptions? = nil,
session: ClientSession? = nil
) throws -> MongoCursor<BSONDocument> {
try self.aggregate(pipeline, options: options, session: session, withOutputType: BSONDocument.self)
}
/**
* Runs an aggregation framework pipeline against this database for pipeline stages that do not require an
* underlying collection, such as `$currentOp` and `$listLocalSessions`.
* Associates the specified `Codable` type `OutputType` with the returned `MongoCursor`
*
* - Parameters:
* - pipeline: an `[BSONDocument]` containing the pipeline of aggregation operations to perform
* - options: Optional `AggregateOptions` to use when executing the command
* - session: Optional `ClientSession` to use when executing this command
* - withOutputType: the type that each resulting document of the output
* of the aggregation operation will be decoded to
*
* - Returns:
* A `MongoCursor` over the resulting `OutputType`s
*
* Throws:
* - `MongoError.CommandError` if an error occurs on the server while executing the aggregation
* - `MongoError.InvalidArgumentError` if the options passed are an invalid combination.
* - `MongoError.LogicError` if the provided session is inactive.
* - `MongoError.LogicError` if this database's parent client has already been closed.
* - `EncodingError` if an error occurs while encoding the options to BSON.
*
* - SeeAlso: https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/#db-aggregate-stages
*/
public func aggregate<OutputType: Codable>(
_ pipeline: [BSONDocument],
options: AggregateOptions? = nil,
session: ClientSession? = nil,
withOutputType: OutputType.Type
) throws -> MongoCursor<OutputType> {
let asyncCursor = try self.asyncDB.aggregate(
pipeline,
options: options,
session: session?.asyncSession,
withOutputType: withOutputType
).wait()
return MongoCursor(wrapping: asyncCursor, client: self.client)
}
}