-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathCreateIndexesOperation.swift
59 lines (47 loc) · 2.15 KB
/
CreateIndexesOperation.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
import CLibMongoC
/// Options to use when creating a new index on a `MongoCollection`.
public struct CreateIndexOptions: Encodable {
/// The maximum amount of time to allow the query to run - enforced server-side.
public var maxTimeMS: Int?
/// An optional `WriteConcern` to use for the command.
public var writeConcern: WriteConcern?
/// Initializer allowing any/all parameters to be omitted.
public init(maxTimeMS: Int? = nil, writeConcern: WriteConcern? = nil) {
self.maxTimeMS = maxTimeMS
self.writeConcern = writeConcern
}
}
/// An operation corresponding to a "createIndexes" command.
internal struct CreateIndexesOperation<T: Codable>: Operation {
private let collection: MongoCollection<T>
private let models: [IndexModel]
private let options: CreateIndexOptions?
internal init(collection: MongoCollection<T>, models: [IndexModel], options: CreateIndexOptions?) {
self.collection = collection
self.models = models
self.options = options
}
internal func execute(using connection: Connection, session: ClientSession?) throws -> [String] {
var indexData = [BSON]()
var indexNames = [String]()
for index in self.models {
var indexDoc = try self.collection.encoder.encode(index)
if let indexName = index.options?.name {
indexNames.append(indexName)
} else {
let indexName = try index.getDefaultName()
indexDoc["name"] = .string(indexName)
indexNames.append(indexName)
}
indexData.append(.document(indexDoc))
}
let command: BSONDocument = ["createIndexes": .string(self.collection.name), "indexes": .array(indexData)]
let opts = try encodeOptions(options: options, session: session)
try self.collection.withMongocCollection(from: connection) { collPtr in
try runMongocCommand(command: command, options: opts) { cmdPtr, optsPtr, replyPtr, error in
mongoc_collection_write_command_with_opts(collPtr, cmdPtr, optsPtr, replyPtr, &error)
}
}
return indexNames
}
}