diff --git a/Sources/MongoSwift/APM.swift b/Sources/MongoSwift/APM.swift index 00aee7be4..0c9ff3538 100644 --- a/Sources/MongoSwift/APM.swift +++ b/Sources/MongoSwift/APM.swift @@ -118,7 +118,7 @@ public struct CommandStartedEvent: MongoSwiftEvent, CommandEventProtocol { } /// The command. - public let command: Document + public let command: BSONDocument /// The database name. public let databaseName: String @@ -138,7 +138,7 @@ public struct CommandStartedEvent: MongoSwiftEvent, CommandEventProtocol { fileprivate init(mongocEvent: MongocCommandStartedEvent) { // we have to copy because libmongoc owns the pointer. - self.command = Document(copying: mongoc_apm_command_started_get_command(mongocEvent.ptr)) + self.command = BSONDocument(copying: mongoc_apm_command_started_get_command(mongocEvent.ptr)) self.databaseName = String(cString: mongoc_apm_command_started_get_database_name(mongocEvent.ptr)) self.commandName = String(cString: mongoc_apm_command_started_get_command_name(mongocEvent.ptr)) self.requestID = mongoc_apm_command_started_get_request_id(mongocEvent.ptr) @@ -170,7 +170,7 @@ public struct CommandSucceededEvent: MongoSwiftEvent, CommandEventProtocol { public let duration: Int /// The command reply. - public let reply: Document + public let reply: BSONDocument /// The command name. public let commandName: String @@ -189,7 +189,7 @@ public struct CommandSucceededEvent: MongoSwiftEvent, CommandEventProtocol { // TODO: SWIFT-349 add logging to check and warn of unlikely int size issues self.duration = Int(mongoc_apm_command_succeeded_get_duration(mongocEvent.ptr)) // we have to copy because libmongoc owns the pointer. - self.reply = Document(copying: mongoc_apm_command_succeeded_get_reply(mongocEvent.ptr)) + self.reply = BSONDocument(copying: mongoc_apm_command_succeeded_get_reply(mongocEvent.ptr)) self.commandName = String(cString: mongoc_apm_command_succeeded_get_command_name(mongocEvent.ptr)) self.requestID = mongoc_apm_command_succeeded_get_request_id(mongocEvent.ptr) self.operationID = mongoc_apm_command_succeeded_get_operation_id(mongocEvent.ptr) @@ -240,7 +240,7 @@ public struct CommandFailedEvent: MongoSwiftEvent, CommandEventProtocol { self.commandName = String(cString: mongoc_apm_command_failed_get_command_name(mongocEvent.ptr)) var error = bson_error_t() mongoc_apm_command_failed_get_error(mongocEvent.ptr, &error) - let reply = Document(copying: mongoc_apm_command_failed_get_reply(mongocEvent.ptr)) + let reply = BSONDocument(copying: mongoc_apm_command_failed_get_reply(mongocEvent.ptr)) self.failure = extractMongoError(error: error, reply: reply) // should always return a CommandError self.requestID = mongoc_apm_command_failed_get_request_id(mongocEvent.ptr) self.operationID = mongoc_apm_command_failed_get_operation_id(mongocEvent.ptr) @@ -552,7 +552,7 @@ public struct ServerHeartbeatSucceededEvent: MongoSwiftEvent { public let duration: Int /// The command reply. - public let reply: Document + public let reply: BSONDocument /// The address of the server. public let serverAddress: ServerAddress @@ -560,7 +560,7 @@ public struct ServerHeartbeatSucceededEvent: MongoSwiftEvent { fileprivate init(mongocEvent: MongocServerHeartbeatSucceededEvent) { self.duration = Int(mongoc_apm_server_heartbeat_succeeded_get_duration(mongocEvent.ptr)) // we have to copy because libmongoc owns the pointer. - self.reply = Document(copying: mongoc_apm_server_heartbeat_succeeded_get_reply(mongocEvent.ptr)) + self.reply = BSONDocument(copying: mongoc_apm_server_heartbeat_succeeded_get_reply(mongocEvent.ptr)) self.serverAddress = ServerAddress(mongoc_apm_server_heartbeat_succeeded_get_host(mongocEvent.ptr)) } diff --git a/Sources/MongoSwift/BSON/BSON.swift b/Sources/MongoSwift/BSON/BSON.swift index dedf5a6dd..fbc56e66d 100644 --- a/Sources/MongoSwift/BSON/BSON.swift +++ b/Sources/MongoSwift/BSON/BSON.swift @@ -11,7 +11,7 @@ public enum BSON { case string(String) /// A BSON document. - case document(Document) + case document(BSONDocument) /// A BSON array. indirect case array([BSON]) @@ -40,7 +40,7 @@ public enum BSON { case regex(BSONRegularExpression) /// A BSON dbPointer. - case dbPointer(DBPointer) + case dbPointer(BSONDBPointer) /// A BSON symbol. case symbol(BSONSymbol) @@ -63,7 +63,7 @@ public enum BSON { /// A BSON Decimal128. /// - SeeAlso: https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst - case decimal128(Decimal128) + case decimal128(BSONDecimal128) /// A BSON minKey. case minKey @@ -158,8 +158,8 @@ public enum BSON { return s } - /// If this `BSON` is a `.document`, return it as a `Document`. Otherwise, return nil. - public var documentValue: Document? { + /// If this `BSON` is a `.document`, return it as a `BSONDocument`. Otherwise, return nil. + public var documentValue: BSONDocument? { guard case let .document(d) = self else { return nil } @@ -190,8 +190,8 @@ public enum BSON { return d } - /// If this `BSON` is a `.decimal128`, return it as a `Decimal128`. Otherwise, return nil. - public var decimal128Value: Decimal128? { + /// If this `BSON` is a `.decimal128`, return it as a `BSONDecimal128`. Otherwise, return nil. + public var decimal128Value: BSONDecimal128? { guard case let .decimal128(d) = self else { return nil } @@ -206,8 +206,8 @@ public enum BSON { return s } - /// If this `BSON` is a `.dbPointer`, return it as a `DBPointer`. Otherwise, return nil. - public var dbPointerValue: DBPointer? { + /// If this `BSON` is a `.dbPointer`, return it as a `BSONDBPointer`. Otherwise, return nil. + public var dbPointerValue: BSONDBPointer? { guard case let .dbPointer(d) = self else { return nil } @@ -281,18 +281,18 @@ public enum BSON { } } - /// Return this BSON as a `Decimal128` if possible. - /// This will coerce numeric cases (e.g. `.double`) into a `Decimal128` if such coercion would be lossless. - public func toDecimal128() -> Decimal128? { + /// Return this BSON as a `BSONDecimal128` if possible. + /// This will coerce numeric cases (e.g. `.double`) into a `BSONDecimal128` if such coercion would be lossless. + public func toDecimal128() -> BSONDecimal128? { switch self { case let .decimal128(d): return d case let .int64(i): - return Decimal128(String(i)) + return BSONDecimal128(String(i)) case let .int32(i): - return Decimal128(String(i)) + return BSONDecimal128(String(i)) case let .double(d): - return Decimal128(String(d)) + return BSONDecimal128(String(d)) default: return nil } @@ -305,25 +305,25 @@ extension BSON { internal static var allBSONTypes: [BSONValue.Type] = [ BSONNull.self, BSONUndefined.self, - MinKey.self, + BSONMinKey.self, MaxKey.self, BSONSymbol.self, Double.self, String.self, - Document.self, + BSONDocument.self, BSONBinary.self, BSONObjectID.self, Bool.self, Date.self, BSONRegularExpression.self, - DBPointer.self, + BSONDBPointer.self, BSONCode.self, BSONCodeWithScope.self, Int32.self, BSONTimestamp.self, Int64.self, [BSON].self, - Decimal128.self + BSONDecimal128.self ] /// Get the associated `BSONValue` to this `BSON` case. @@ -334,7 +334,7 @@ extension BSON { case .undefined: return BSONUndefined() case .minKey: - return MinKey() + return BSONMinKey() case .maxKey: return MaxKey() case let .symbol(v): @@ -403,7 +403,7 @@ extension BSON: ExpressibleByIntegerLiteral { extension BSON: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, BSON)...) { - self = .document(Document(keyValuePairs: elements)) + self = .document(BSONDocument(keyValuePairs: elements)) } } diff --git a/Sources/MongoSwift/BSON/BSONDecoder.swift b/Sources/MongoSwift/BSON/BSONDecoder.swift index e7b299036..be479f6d7 100644 --- a/Sources/MongoSwift/BSON/BSONDecoder.swift +++ b/Sources/MongoSwift/BSON/BSONDecoder.swift @@ -136,8 +136,8 @@ public class BSONDecoder { * - Returns: A value of the requested type. * - Throws: `DecodingError` if any value throws an error during decoding. */ - public func decode(_ type: T.Type, from document: Document) throws -> T { - // if the requested type is `Document` we're done + public func decode(_ type: T.Type, from document: BSONDocument) throws -> T { + // if the requested type is `BSONDocument` we're done if let doc = document as? T { return doc } @@ -154,7 +154,7 @@ public class BSONDecoder { * - Throws: `DecodingError` if the BSON data is corrupt or if any value throws an error during decoding. */ public func decode(_ type: T.Type, from data: Data) throws -> T { - try self.decode(type, from: Document(fromBSON: data)) + try self.decode(type, from: BSONDocument(fromBSON: data)) } /** @@ -177,7 +177,7 @@ public class BSONDecoder { // and pay a small performance penalty of decoding a few extra bytes. let wrapped = "{\"value\": \(json)}" - if let doc = try? Document(fromJSON: wrapped) { + if let doc = try? BSONDocument(fromJSON: wrapped) { let s = try self.decode(DecodableWrapper.self, from: doc) return s.value } @@ -240,7 +240,7 @@ internal class _BSONDecoder: Decoder { guard let topContainer = self.storage.topContainer.documentValue else { throw DecodingError._typeMismatch( at: self.codingPath, - expectation: Document.self, + expectation: BSONDocument.self, reality: self.storage.topContainer.bsonValue ) } @@ -489,7 +489,7 @@ extension _BSONDecoder { } } -/// A keyed decoding container, backed by a `Document`. +/// A keyed decoding container, backed by a `BSONDocument`. private struct _BSONKeyedDecodingContainer: KeyedDecodingContainerProtocol { typealias Key = K @@ -497,13 +497,13 @@ private struct _BSONKeyedDecodingContainer: KeyedDecodingContainer private let decoder: _BSONDecoder /// A reference to the container we're reading from. - fileprivate let container: Document + fileprivate let container: BSONDocument /// The path of coding keys taken to get to this point in decoding. public private(set) var codingPath: [CodingKey] /// Initializes `self`, referencing the given decoder and container. - fileprivate init(referencing decoder: _BSONDecoder, wrapping container: Document) { + fileprivate init(referencing decoder: _BSONDecoder, wrapping container: BSONDocument) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath @@ -617,7 +617,7 @@ private struct _BSONKeyedDecodingContainer: KeyedDecodingContainer guard let doc = value.documentValue else { throw DecodingError._typeMismatch( at: self.codingPath, - expectation: Document.self, + expectation: BSONDocument.self, reality: value.bsonValue ) } @@ -789,7 +789,7 @@ private struct _BSONUnkeyedDecodingContainer: UnkeyedDecodingContainer { throws -> KeyedDecodingContainer { try self.decoder.with(pushedKey: _BSONKey(index: self.currentIndex)) { try self.checkAtEnd() - let doc = try self.decodeBSONType(Document.self) + let doc = try self.decodeBSONType(BSONDocument.self) self.currentIndex += 1 let container = _BSONKeyedDecodingContainer(referencing: self.decoder, wrapping: doc) return KeyedDecodingContainer(container) diff --git a/Sources/MongoSwift/BSON/Document+Codable.swift b/Sources/MongoSwift/BSON/BSONDocument+Codable.swift similarity index 72% rename from Sources/MongoSwift/BSON/Document+Codable.swift rename to Sources/MongoSwift/BSON/BSONDocument+Codable.swift index 76b996e11..3d3cf63c3 100644 --- a/Sources/MongoSwift/BSON/Document+Codable.swift +++ b/Sources/MongoSwift/BSON/BSONDocument+Codable.swift @@ -1,13 +1,13 @@ import Foundation -/// An extension of `Document` to implement the `Codable` protocol. -extension Document: Codable { +/// An extension of `BSONDocument` to implement the `Codable` protocol. +extension BSONDocument: Codable { public func encode(to encoder: Encoder) throws { guard let bsonEncoder = encoder as? _BSONEncoder else { throw bsonEncodingUnsupportedError(value: self, at: encoder.codingPath) } - // directly add the `Document` to the encoder's storage. + // directly add the `BSONDocument` to the encoder's storage. bsonEncoder.storage.containers.append(self) } @@ -18,13 +18,13 @@ extension Document: Codable { public init(from decoder: Decoder) throws { // currently we only support decoding to a document using a BSONDecoder. guard let bsonDecoder = decoder as? _BSONDecoder else { - throw getDecodingError(type: Document.self, decoder: decoder) + throw getDecodingError(type: BSONDocument.self, decoder: decoder) } - // we can just return the top container `Document`. + // we can just return the top container `BSONDocument`. let topContainer = bsonDecoder.storage.topContainer guard let doc = topContainer.documentValue else { - throw DecodingError._typeMismatch(at: [], expectation: Document.self, reality: topContainer.bsonValue) + throw DecodingError._typeMismatch(at: [], expectation: BSONDocument.self, reality: topContainer.bsonValue) } self = doc } diff --git a/Sources/MongoSwift/BSON/Document+Collection.swift b/Sources/MongoSwift/BSON/BSONDocument+Collection.swift similarity index 71% rename from Sources/MongoSwift/BSON/Document+Collection.swift rename to Sources/MongoSwift/BSON/BSONDocument+Collection.swift index 1712930d0..723dfb933 100644 --- a/Sources/MongoSwift/BSON/Document+Collection.swift +++ b/Sources/MongoSwift/BSON/BSONDocument+Collection.swift @@ -1,9 +1,9 @@ import Foundation -/// An extension of `Document` to make it conform to the `Collection` protocol. +/// An extension of `BSONDocument` to make it conform to the `Collection` protocol. /// This gives guarantees on non-destructive iteration, and offers an indexed /// ordering to the key-value pairs in the document. -extension Document: Collection { +extension BSONDocument: Collection { /// The index type of a document. public typealias Index = Int @@ -31,14 +31,14 @@ extension Document: Collection { return i + 1 } - /// Allows access to a `KeyValuePair` from the `Document`, given the position of the desired `KeyValuePair` held + /// Allows access to a `KeyValuePair` from the `BSONDocument`, given the position of the desired `KeyValuePair` held /// within. This method does not guarantee constant-time (O(1)) access. public subscript(position: Index) -> KeyValuePair { // TODO: This method _should_ guarantee constant-time O(1) access, and it is possible to make it do so. This // criticism also applies to key-based subscripting via `String`. // See SWIFT-250. self.failIndexCheck(position) - guard let iter = DocumentIterator(over: self) else { + guard let iter = BSONDocumentIterator(over: self) else { fatalError("Failed to initialize an iterator over document \(self)") } @@ -51,10 +51,10 @@ extension Document: Collection { return (iter.currentKey, iter.currentValue) } - /// Allows access to a `KeyValuePair` from the `Document`, given a range of indices of the desired `KeyValuePair`'s - /// held within. This method does not guarantee constant-time (O(1)) access. - public subscript(bounds: Range) -> Document { + /// Allows access to a `KeyValuePair` from the `BSONDocument`, given a range of indices of the desired + /// `KeyValuePair`'s held within. This method does not guarantee constant-time (O(1)) access. + public subscript(bounds: Range) -> BSONDocument { // TODO: SWIFT-252 should provide a more efficient implementation for this. - DocumentIterator.subsequence(of: self, startIndex: bounds.lowerBound, endIndex: bounds.upperBound) + BSONDocumentIterator.subsequence(of: self, startIndex: bounds.lowerBound, endIndex: bounds.upperBound) } } diff --git a/Sources/MongoSwift/BSON/Document+Sequence.swift b/Sources/MongoSwift/BSON/BSONDocument+Sequence.swift similarity index 86% rename from Sources/MongoSwift/BSON/Document+Sequence.swift rename to Sources/MongoSwift/BSON/BSONDocument+Sequence.swift index 3da3c2acb..14a46bdfa 100644 --- a/Sources/MongoSwift/BSON/Document+Sequence.swift +++ b/Sources/MongoSwift/BSON/BSONDocument+Sequence.swift @@ -1,7 +1,7 @@ import CLibMongoC import Foundation -/// An extension of `Document` to make it conform to the `Sequence` protocol. +/// An extension of `BSONDocument` to make it conform to the `Sequence` protocol. /// This allows you to iterate through the (key, value) pairs, for example: /// ``` /// let doc: Document = ["a": 1, "b": 2] @@ -9,21 +9,21 @@ import Foundation /// ... /// } /// ``` -extension Document: Sequence { +extension BSONDocument: Sequence { /// The element type of a document: a tuple containing an individual key-value pair. public typealias KeyValuePair = (key: String, value: BSON) - // Since a `Document` is a recursive structure, we want to enforce the use of it as a subsequence of itself. + // Since a `BSONDocument` is a recursive structure, we want to enforce the use of it as a subsequence of itself. // instead of something like `Slice`. /// The type that is returned from methods such as `dropFirst()` and `split()`. - public typealias SubSequence = Document + public typealias SubSequence = BSONDocument /// Returns a `Bool` indicating whether the document is empty. public var isEmpty: Bool { !self.makeIterator().advance() } - /// Returns a `DocumentIterator` over the values in this `Document`. - public func makeIterator() -> DocumentIterator { - guard let iter = DocumentIterator(over: self) else { + /// Returns a `BSONDocumentIterator` over the values in this `BSONDocument`. + public func makeIterator() -> BSONDocumentIterator { + guard let iter = BSONDocumentIterator(over: self) else { fatalError("Failed to initialize an iterator over document \(self)") } return iter @@ -40,8 +40,8 @@ extension Document: Sequence { * * - Throws: An error if `transform` throws an error. */ - public func mapValues(_ transform: (BSON) throws -> BSON) rethrows -> Document { - var output = Document() + public func mapValues(_ transform: (BSON) throws -> BSON) rethrows -> BSONDocument { + var output = BSONDocument() for (k, v) in self { output[k] = try transform(v) } @@ -56,7 +56,7 @@ extension Document: Sequence { * * - Returns: A document starting after the specified number of key-value pairs. */ - public func dropFirst(_ n: Int) -> Document { + public func dropFirst(_ n: Int) -> BSONDocument { switch n { case ..<0: fatalError("Can't drop a negative number of elements from a document") @@ -66,7 +66,7 @@ extension Document: Sequence { // get all the key-value pairs from nth index on. subsequence will handle the case where n >= length of doc // by creating an iter and calling advance until the end is reached. this is exactly what calling self.count // would do in that situation via bson_count_keys, so no point in special casing self.count <= n here. - return DocumentIterator.subsequence(of: self, startIndex: n) + return BSONDocumentIterator.subsequence(of: self, startIndex: n) } } @@ -78,17 +78,17 @@ extension Document: Sequence { * * - Returns: A document leaving off the specified number of final key-value pairs. */ - public func dropLast(_ n: Int) -> Document { + public func dropLast(_ n: Int) -> BSONDocument { switch n { case ..<0: - fatalError("Can't drop a negative number of elements from a `Document`") + fatalError("Can't drop a negative number of elements from a `BSONDocument`") case 0: return self default: // the subsequence we want is [0, length - n) let end = self.count - n // if we are dropping >= the length, just short circuit and return empty doc - return end <= 0 ? [:] : DocumentIterator.subsequence(of: self, endIndex: end) + return end <= 0 ? [:] : BSONDocumentIterator.subsequence(of: self, endIndex: end) } } @@ -103,7 +103,7 @@ extension Document: Sequence { * * - Throws: An error if `predicate` throws an error. */ - public func drop(while predicate: (KeyValuePair) throws -> Bool) rethrows -> Document { + public func drop(while predicate: (KeyValuePair) throws -> Bool) rethrows -> BSONDocument { // tracks whether we are still in a "dropping" state. once we encounter // an element that doesn't satisfy the predicate, we stop dropping. var drop = true @@ -130,15 +130,15 @@ extension Document: Sequence { * * - Returns: A document starting at the beginning of this document with at most `maxLength` key-value pairs. */ - public func prefix(_ maxLength: Int) -> Document { + public func prefix(_ maxLength: Int) -> BSONDocument { switch maxLength { case ..<0: - fatalError("Can't retrieve a negative length prefix of a `Document`") + fatalError("Can't retrieve a negative length prefix of a `BSONDocument`") case 0: return [:] default: // short circuit if there are fewer elements in the doc than requested - return self.count <= maxLength ? self : DocumentIterator.subsequence(of: self, endIndex: maxLength) + return self.count <= maxLength ? self : BSONDocumentIterator.subsequence(of: self, endIndex: maxLength) } } @@ -153,8 +153,8 @@ extension Document: Sequence { * * - Throws: An error if `predicate` throws an error. */ - public func prefix(while predicate: (KeyValuePair) throws -> Bool) rethrows -> Document { - var output = Document() + public func prefix(while predicate: (KeyValuePair) throws -> Bool) rethrows -> BSONDocument { + var output = BSONDocument() for elt in self { if try !predicate(elt) { break } output[elt.key] = elt.value @@ -170,16 +170,16 @@ extension Document: Sequence { * * - Returns: A document ending at the end of this document with at most `maxLength` key-value pairs. */ - public func suffix(_ maxLength: Int) -> Document { + public func suffix(_ maxLength: Int) -> BSONDocument { switch maxLength { case ..<0: - fatalError("Can't retrieve a negative length suffix of a `Document`") + fatalError("Can't retrieve a negative length suffix of a `BSONDocument`") case 0: return [:] default: let start = self.count - maxLength // short circuit if there are fewer elements in the doc than requested - return start <= 0 ? self : DocumentIterator.subsequence(of: self, startIndex: start) + return start <= 0 ? self : BSONDocumentIterator.subsequence(of: self, startIndex: start) } } @@ -207,7 +207,7 @@ extension Document: Sequence { maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (KeyValuePair) throws -> Bool - ) rethrows -> [Document] { + ) rethrows -> [BSONDocument] { // rather than implementing the complex logic necessary for split, convert to an array and call split on that let asArr = Array(self) // convert to a [[KeyValuePair]] @@ -218,9 +218,9 @@ extension Document: Sequence { ) // convert each nested [KeyValuePair] back to a Document - var output = [Document]() + var output = [BSONDocument]() splitArrs.forEach { array in - var doc = Document() + var doc = BSONDocument() array.forEach { doc[$0.key] = $0.value } output.append(doc) } @@ -229,7 +229,7 @@ extension Document: Sequence { } } -extension Document { +extension BSONDocument { // this is an alternative to the built-in `Document.filter` that returns an `[KeyValuePair]`. // this variant is called by default, but the other is still accessible by explicitly stating // return type: `let newDocPairs: [Document.KeyValuePair] = newDoc.filter { ... }` @@ -244,8 +244,8 @@ extension Document { * * - Throws: An error if `isIncluded` throws an error. */ - public func filter(_ isIncluded: (KeyValuePair) throws -> Bool) rethrows -> Document { - var output = Document() + public func filter(_ isIncluded: (KeyValuePair) throws -> Bool) rethrows -> BSONDocument { + var output = BSONDocument() for elt in self where try isIncluded(elt) { output[elt.key] = elt.value } diff --git a/Sources/MongoSwift/BSON/Document.swift b/Sources/MongoSwift/BSON/BSONDocument.swift similarity index 82% rename from Sources/MongoSwift/BSON/Document.swift rename to Sources/MongoSwift/BSON/BSONDocument.swift index 9ac447d6d..78bd293b8 100644 --- a/Sources/MongoSwift/BSON/Document.swift +++ b/Sources/MongoSwift/BSON/BSONDocument.swift @@ -6,12 +6,12 @@ internal typealias MutableBSONPointer = UnsafeMutablePointer /// A struct representing the BSON document type. @dynamicMemberLookup -public struct Document { +public struct BSONDocument { /// Error thrown when BSON buffer is too small. internal static let BSONBufferTooSmallError = InternalError(message: "BSON buffer is unexpectedly too small (< 5 bytes)") - /// The storage backing a `Document`. + /// The storage backing a `BSONDocument`. private class Storage { fileprivate let _bson: MutableBSONPointer @@ -41,41 +41,41 @@ public struct Document { private var _storage: Storage } -/// An extension of `Document` containing its private/internal functionality. -extension Document { +/// An extension of `BSONDocument` containing its private/internal functionality. +extension BSONDocument { /** - * Initializes a `Document` from a pointer to a `bson_t` by making a copy of the data. The `bson_t`'s owner is + * Initializes a `BSONDocument` from a pointer to a `bson_t` by making a copy of the data. The `bson_t`'s owner is * responsible for freeing the original. * * - Parameters: * - pointer: a BSONPointer * - * - Returns: a new `Document` + * - Returns: a new `BSONDocument` */ internal init(copying pointer: BSONPointer) { self._storage = Storage(copying: pointer) } /** - * Initializes a `Document` from a pointer to a `bson_t`, "stealing" the `bson_t` to use for underlying storage/ + * Initializes a `BSONDocument` from a pointer to a `bson_t`, "stealing" the `bson_t` to use for underlying storage/ * The `bson_t` must not be modified or freed by others after it is used here. * * - Parameters: * - pointer: a MutableBSONPointer * - * - Returns: a new `Document` + * - Returns: a new `BSONDocument` */ internal init(stealing pointer: MutableBSONPointer) { self._storage = Storage(stealing: pointer) } /** - * Initializes a `Document` using an array where the values are KeyValuePairs. + * Initializes a `BSONDocument` using an array where the values are KeyValuePairs. * * - Parameters: * - elements: a `[KeyValuePair]` * - * - Returns: a new `Document` + * - Returns: a new `BSONDocument` */ internal init(_ elements: [KeyValuePair]) { self._storage = Storage() @@ -89,14 +89,14 @@ extension Document { } /** - * Initializes a `Document` using an array where the values are optional + * Initializes a `BSONDocument` using an array where the values are optional * `BSON`s. Values are stored under a string of their index in the * array. * * - Parameters: * - elements: a `[BSON]` * - * - Returns: a new `Document` + * - Returns: a new `BSONDocument` */ internal init(_ elements: [BSON]) { self._storage = Storage() @@ -121,7 +121,7 @@ extension Document { /** * Checks if the document is uniquely referenced. If not, makes a copy of the underlying `bson_t` - * and lets the copy/copies keep the original. This allows us to provide value semantics for `Document`s. + * and lets the copy/copies keep the original. This allows us to provide value semantics for `BSONDocument`s. * This happens if someone copies a document and modifies it. * * For example: @@ -146,7 +146,7 @@ extension Document { * * - Throws: * - `InternalError` if the new value is an `Int` and cannot be written to BSON. - * - `LogicError` if the new value is a `Decimal128` or `BSONObjectID` and is improperly formatted. + * - `LogicError` if the new value is a `BSONDecimal128` or `BSONObjectID` and is improperly formatted. * - `LogicError` if the new value is an `Array` and it contains a non-`BSONValue` element. * - `InternalError` if the underlying `bson_t` would exceed the maximum size by encoding this * key-value pair. @@ -154,8 +154,8 @@ extension Document { internal mutating func setValue(for key: String, to newValue: BSON, checkForKey: Bool = true) throws { let newBSONValue = newValue.bsonValue - // if the key already exists in the `Document`, we need to replace it - if checkForKey, let existingType = DocumentIterator(over: self, advancedTo: key)?.currentType { + // if the key already exists in the `BSONDocument`, we need to replace it + if checkForKey, let existingType = BSONDocumentIterator(over: self, advancedTo: key)?.currentType { let newBSONType = newBSONValue.bsonType let sameTypes = newBSONType == existingType @@ -169,12 +169,12 @@ extension Document { self.copyStorageIfRequired() // key is guaranteed present so initialization will succeed. // swiftlint:disable:next force_unwrapping - try DocumentIterator(over: self, advancedTo: key)!.overwriteCurrentValue(with: ov) + try BSONDocumentIterator(over: self, advancedTo: key)!.overwriteCurrentValue(with: ov) // otherwise, we just create a new document and replace this key } else { - guard let iter = DocumentIterator(over: self) else { - throw Document.BSONBufferTooSmallError + guard let iter = BSONDocumentIterator(over: self) else { + throw BSONDocument.BSONBufferTooSmallError } var keysBefore: [String] = [] // keys to exclude before the key @@ -193,7 +193,7 @@ extension Document { // To preserve order, we construct a Document excluding keys after the key, set the new value for the // key, and then append all keys after the key. - var newSelf = Document() + var newSelf = BSONDocument() try self.copyElements(to: &newSelf, excluding: keysAfter) try newSelf.setValue(for: key, to: newValue, checkForKey: false) try self.copyElements(to: &newSelf, excluding: keysBefore) @@ -208,12 +208,12 @@ extension Document { } /// Retrieves the value associated with `for` as a `BSON?`, which can be nil if the key does not exist in the - /// `Document`. + /// `BSONDocument`. /// /// - Throws: `InternalError` if the BSON buffer is too small (< 5 bytes). internal func getValue(for key: String) throws -> BSON? { - guard let iter = DocumentIterator(over: self) else { - throw Document.BSONBufferTooSmallError + guard let iter = BSONDocumentIterator(over: self) else { + throw BSONDocument.BSONBufferTooSmallError } guard iter.move(to: key) else { @@ -223,9 +223,9 @@ extension Document { return try iter.safeCurrentValue() } - /// Appends the key/value pairs from the provided `doc` to this `Document`. + /// Appends the key/value pairs from the provided `doc` to this `BSONDocument`. /// Note: This function does not check for or clean away duplicate keys. - internal mutating func merge(_ doc: Document) throws { + internal mutating func merge(_ doc: BSONDocument) throws { let success = self.withMutableBSONPointer { selfPtr in doc.withBSONPointer { docPtr in bson_concat(selfPtr, docPtr) @@ -241,19 +241,19 @@ extension Document { /// If the document already has an _id, returns it as-is. Otherwise, returns a new document /// containing all the keys from this document, with an _id prepended. - internal func withID() throws -> Document { + internal func withID() throws -> BSONDocument { if self.hasKey("_id") { return self } - var idDoc: Document = ["_id": .objectID()] + var idDoc: BSONDocument = ["_id": .objectID()] try idDoc.merge(self) return idDoc } /// Helper function for copying elements from some source document to a destination document while /// excluding a non-zero number of keys - internal func copyElements(to otherDoc: inout Document, excluding keys: [String]) throws { + internal func copyElements(to otherDoc: inout BSONDocument, excluding keys: [String]) throws { guard !keys.isEmpty else { throw InternalError(message: "No keys to exclude, use 'bson_copy' instead") } @@ -282,26 +282,26 @@ extension Document { } } -/// An extension of `Document` containing its public API. -extension Document { - /// Returns a `[String]` containing the keys in this `Document`. +/// An extension of `BSONDocument` containing its public API. +extension BSONDocument { + /// Returns a `[String]` containing the keys in this `BSONDocument`. public var keys: [String] { self.makeIterator().keys } - /// Returns a `[BSON]` containing the values stored in this `Document`. + /// Returns a `[BSON]` containing the values stored in this `BSONDocument`. public var values: [BSON] { self.makeIterator().values } - /// Returns the number of (key, value) pairs stored at the top level of this `Document`. + /// Returns the number of (key, value) pairs stored at the top level of this `BSONDocument`. public var count: Int { self.withBSONPointer { ptr in Int(bson_count_keys(ptr)) } } - /// Returns the relaxed extended JSON representation of this `Document`. + /// Returns the relaxed extended JSON representation of this `BSONDocument`. /// On error, an empty string will be returned. public var extendedJSON: String { let result = self.withBSONPointer { ptr in @@ -315,7 +315,7 @@ extension Document { return String(cString: json) } - /// Returns the canonical extended JSON representation of this `Document`. + /// Returns the canonical extended JSON representation of this `BSONDocument`. /// On error, an empty string will be returned. public var canonicalExtendedJSON: String { let result = self.withBSONPointer { ptr in @@ -329,7 +329,7 @@ extension Document { return String(cString: json) } - /// Returns a copy of the raw BSON data for this `Document`, represented as `Data`. + /// Returns a copy of the raw BSON data for this `BSONDocument`, represented as `Data`. public var rawBSON: Data { let data = self.withBSONPointer { ptr in // swiftlint:disable:next force_unwrapping @@ -343,7 +343,7 @@ extension Document { return Data(bytes: data, count: Int(length)) } - /// Initializes a new, empty `Document`. + /// Initializes a new, empty `BSONDocument`. public init() { self._storage = Storage() } @@ -365,12 +365,12 @@ extension Document { } /** - * Constructs a new `Document` from the provided JSON text. + * Constructs a new `BSONDocument` from the provided JSON text. * * - Parameters: - * - fromJSON: a JSON document as `Data` to parse into a `Document` + * - fromJSON: a JSON document as `Data` to parse into a `BSONDocument` * - * - Returns: the parsed `Document` + * - Returns: the parsed `BSONDocument` * * - Throws: * - A `InvalidArgumentError` if the data passed in is invalid JSON. @@ -389,7 +389,7 @@ extension Document { }) } - /// Convenience initializer for constructing a `Document` from a `String`. + /// Convenience initializer for constructing a `BSONDocument` from a `String`. /// - Throws: /// - A `InvalidArgumentError` if the string passed in is invalid JSON. public init(fromJSON json: String) throws { @@ -399,7 +399,7 @@ extension Document { } /** - * Constructs a `Document` from raw BSON `Data`. + * Constructs a `BSONDocument` from raw BSON `Data`. * - Throws: * - A `InvalidArgumentError` if `bson` is too short or too long to be valid BSON. * - A `InvalidArgumentError` if the first four bytes of `bson` do not contain `bson.count`. @@ -415,7 +415,7 @@ extension Document { }) } - /// Returns a `Boolean` indicating whether this `Document` contains the provided key. + /// Returns a `Boolean` indicating whether this `BSONDocument` contains the provided key. public func hasKey(_ key: String) -> Bool { self.withBSONPointer { ptr in bson_has_field(ptr, key) @@ -430,20 +430,20 @@ extension Document { * d["a"] = 1 * print(d["a"]) // prints 1 * ``` - * A nil return value indicates that the subscripted key does not exist in the `Document`. A true BSON null is + * A nil return value indicates that the subscripted key does not exist in the `BSONDocument`. A true BSON null is * returned as `BSON.null`. */ public subscript(key: String) -> BSON? { // TODO: This `get` method _should_ guarantee constant-time O(1) access, and it is possible to make it do so. // This criticism also applies to indexed-based subscripting via `Int`. // See SWIFT-250. - get { DocumentIterator(over: self, advancedTo: key)?.currentValue } + get { BSONDocumentIterator(over: self, advancedTo: key)?.currentValue } set(newValue) { do { if let newValue = newValue { try self.setValue(for: key, to: newValue) } else { - var newSelf = Document() + var newSelf = BSONDocument() try self.copyElements(to: &newSelf, excluding: [key]) self = newSelf } @@ -475,7 +475,7 @@ extension Document { * d.a = 1 * print(d.a) // prints 1 * ``` - * A nil return value indicates that the key does not exist in the `Document`. A true BSON null is returned as + * A nil return value indicates that the key does not exist in the `BSONDocument`. A true BSON null is returned as * `BSON.null`. */ public subscript(dynamicMember member: String) -> BSON? { @@ -488,13 +488,13 @@ extension Document { } } -/// An extension of `Document` to make it a `BSONValue`. -extension Document: BSONValue { +/// An extension of `BSONDocument` to make it a `BSONValue`. +extension BSONDocument: BSONValue { internal static var bsonType: BSONType { .document } internal var bson: BSON { .document(self) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in try self.withBSONPointer { nestedDocPtr in guard bson_append_document(docPtr, key, Int32(key.utf8.count), nestedDocPtr) else { @@ -504,9 +504,9 @@ extension Document: BSONValue { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .document else { - throw wrongIterTypeError(iter, expected: Document.self) + throw wrongIterTypeError(iter, expected: BSONDocument.self) } return .document(try iter.withBSONIterPointer { iterPtr in @@ -528,9 +528,9 @@ extension Document: BSONValue { } } -/// An extension of `Document` to make it `Equatable`. -extension Document: Equatable { - public static func == (lhs: Document, rhs: Document) -> Bool { +/// An extension of `BSONDocument` to make it `Equatable`. +extension BSONDocument: Equatable { + public static func == (lhs: BSONDocument, rhs: BSONDocument) -> Bool { lhs.withBSONPointer { lhsPtr in rhs.withBSONPointer { rhsPtr in bson_compare(lhsPtr, rhsPtr) == 0 @@ -539,26 +539,26 @@ extension Document: Equatable { } } -/// An extension of `Document` to make it convertible to a string. -extension Document: CustomStringConvertible { - /// Returns the relaxed extended JSON representation of this `Document`. +/// An extension of `BSONDocument` to make it convertible to a string. +extension BSONDocument: CustomStringConvertible { + /// Returns the relaxed extended JSON representation of this `BSONDocument`. /// On error, an empty string will be returned. public var description: String { self.extendedJSON } } -/// An extension of `Document` to add the capability to be initialized with a dictionary literal. -extension Document: ExpressibleByDictionaryLiteral { +/// An extension of `BSONDocument` to add the capability to be initialized with a dictionary literal. +extension BSONDocument: ExpressibleByDictionaryLiteral { /** - * Initializes a `Document` using a dictionary literal where the + * Initializes a `BSONDocument` using a dictionary literal where the * keys are `String`s and the values are `BSON`s. For example: * `d: Document = ["a" : 1 ]` * * - Parameters: * - dictionaryLiteral: a [String: BSON] * - * - Returns: a new `Document` + * - Returns: a new `BSONDocument` */ public init(dictionaryLiteral keyValuePairs: (String, BSON)...) { self.init(keyValuePairs: keyValuePairs) @@ -566,7 +566,7 @@ extension Document: ExpressibleByDictionaryLiteral { } internal func withOptionalBSONPointer( - to document: Document?, + to document: BSONDocument?, body: (BSONPointer?) throws -> T ) rethrows -> T { guard let doc = document else { @@ -575,8 +575,8 @@ internal func withOptionalBSONPointer( return try doc.withBSONPointer(body: body) } -// An extension of `Document` to add the capability to be hashed -extension Document: Hashable { +// An extension of `BSONDocument` to add the capability to be hashed +extension BSONDocument: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(self.rawBSON) } diff --git a/Sources/MongoSwift/BSON/DocumentIterator.swift b/Sources/MongoSwift/BSON/BSONDocumentIterator.swift similarity index 86% rename from Sources/MongoSwift/BSON/DocumentIterator.swift rename to Sources/MongoSwift/BSON/BSONDocumentIterator.swift index b632dba90..2a3819d32 100644 --- a/Sources/MongoSwift/BSON/DocumentIterator.swift +++ b/Sources/MongoSwift/BSON/BSONDocumentIterator.swift @@ -4,16 +4,16 @@ import Foundation internal typealias BSONIterPointer = UnsafePointer internal typealias MutableBSONIterPointer = UnsafeMutablePointer -/// An iterator over the values in a `Document`. -public class DocumentIterator: IteratorProtocol { +/// An iterator over the values in a `BSONDocument`. +public class BSONDocumentIterator: IteratorProtocol { /// the libbson iterator. it must be a `var` because we use it as an inout argument. private var _iter: bson_iter_t /// a reference to the document we're iterating over - private let document: Document + private let document: BSONDocument /// Initializes a new iterator over the contents of `doc`. Returns `nil` if the key is not /// found, or if an iterator cannot be created over `doc` due to an error from e.g. corrupt data. - internal init?(over document: Document) { + internal init?(over document: BSONDocument) { self._iter = bson_iter_t() self.document = document @@ -30,7 +30,7 @@ public class DocumentIterator: IteratorProtocol { /// Initializes a new iterator over the contents of `doc`. Returns `nil` if an iterator cannot /// be created over `doc` due to an error from e.g. corrupt data, or if the key is not found. - internal init?(over document: Document, advancedTo key: String) { + internal init?(over document: BSONDocument, advancedTo key: String) { self._iter = bson_iter_t() self.document = document @@ -102,9 +102,9 @@ public class DocumentIterator: IteratorProtocol { /// Returns the current value (equivalent to the `currentValue` property) or throws on error. /// /// - Throws: - /// - `InternalError` if the current value of this `DocumentIterator` cannot be decoded to BSON. + /// - `InternalError` if the current value of this `BSONDocumentIterator` cannot be decoded to BSON. internal func safeCurrentValue() throws -> BSON { - guard let bsonType = DocumentIterator.bsonTypeMap[currentType] else { + guard let bsonType = BSONDocumentIterator.bsonTypeMap[currentType] else { throw InternalError( message: "Unknown BSONType for iterator's current value with type: \(self.currentType)" ) @@ -116,12 +116,16 @@ public class DocumentIterator: IteratorProtocol { // uses an iterator to copy (key, value) pairs of the provided document from range [startIndex, endIndex) into a new // document. starts at the startIndex-th pair and ends at the end of the document or the (endIndex-1)th index, // whichever comes first. - internal static func subsequence(of doc: Document, startIndex: Int = 0, endIndex: Int = Int.max) -> Document { + internal static func subsequence( + of doc: BSONDocument, + startIndex: Int = 0, + endIndex: Int = Int.max + ) -> BSONDocument { guard endIndex >= startIndex else { fatalError("endIndex must be >= startIndex") } - guard let iter = DocumentIterator(over: doc) else { + guard let iter = BSONDocumentIterator(over: doc) else { return [:] } @@ -153,7 +157,7 @@ public class DocumentIterator: IteratorProtocol { return doc } - var newDoc = Document() + var newDoc = BSONDocument() do { try doc.copyElements(to: &newDoc, excluding: excludedKeys) @@ -165,16 +169,16 @@ public class DocumentIterator: IteratorProtocol { } /// Returns the next value in the sequence, or `nil` if the iterator is exhausted. - public func next() -> Document.KeyValuePair? { + public func next() -> BSONDocument.KeyValuePair? { self.advance() ? (self.currentKey, self.currentValue) : nil } /** - * Overwrites the current value of this `DocumentIterator` with the supplied value. + * Overwrites the current value of this `BSONDocumentIterator` with the supplied value. * * - Throws: * - `InternalError` if the new value is an `Int` and cannot be written to BSON. - * - `LogicError` if the new value is a `Decimal128` or `BSONObjectID` and is improperly formatted. + * - `LogicError` if the new value is a `BSONDecimal128` or `BSONObjectID` and is improperly formatted. */ internal func overwriteCurrentValue(with newValue: Overwritable) throws { let newValueType = type(of: newValue).bsonType @@ -199,22 +203,22 @@ public class DocumentIterator: IteratorProtocol { private static let bsonTypeMap: [BSONType: BSONValue.Type] = [ .double: Double.self, .string: String.self, - .document: Document.self, + .document: BSONDocument.self, .array: [BSON].self, .binary: BSONBinary.self, .objectID: BSONObjectID.self, .bool: Bool.self, .datetime: Date.self, .regex: BSONRegularExpression.self, - .dbPointer: DBPointer.self, + .dbPointer: BSONDBPointer.self, .code: BSONCode.self, .symbol: BSONSymbol.self, .codeWithScope: BSONCodeWithScope.self, .int32: Int32.self, .timestamp: BSONTimestamp.self, .int64: Int64.self, - .decimal128: Decimal128.self, - .minKey: MinKey.self, + .decimal128: BSONDecimal128.self, + .minKey: BSONMinKey.self, .maxKey: MaxKey.self, .null: BSONNull.self, .undefined: BSONUndefined.self diff --git a/Sources/MongoSwift/BSON/BSONEncoder.swift b/Sources/MongoSwift/BSON/BSONEncoder.swift index 618abe72b..1dbda516c 100644 --- a/Sources/MongoSwift/BSON/BSONEncoder.swift +++ b/Sources/MongoSwift/BSON/BSONEncoder.swift @@ -136,12 +136,12 @@ public class BSONEncoder { * Encodes the given top-level value and returns its BSON representation. * * - Parameter value: The value to encode. - * - Returns: A new `Document` containing the encoded BSON data. + * - Returns: A new `BSONDocument` containing the encoded BSON data. * - Throws: `EncodingError` if any value throws an error during encoding. */ - public func encode(_ value: T) throws -> Document { - // if the value being encoded is already a `Document` we're done - if let doc = value as? Document { + public func encode(_ value: T) throws -> BSONDocument { + // if the value being encoded is already a `BSONDocument` we're done + if let doc = value as? BSONDocument { return doc } else if let bson = value as? BSON, let doc = bson.documentValue { return doc @@ -177,10 +177,10 @@ public class BSONEncoder { * value is nil or if it contains no data. * * - Parameter value: The value to encode. - * - Returns: A new `Document` containing the encoded BSON data, or nil if there is no data to encode. + * - Returns: A new `BSONDocument` containing the encoded BSON data, or nil if there is no data to encode. * - Throws: `EncodingError` if any value throws an error during encoding. */ - public func encode(_ value: T?) throws -> Document? { + public func encode(_ value: T?) throws -> BSONDocument? { guard let value = value else { return nil } @@ -195,7 +195,7 @@ public class BSONEncoder { * - Returns: A new `[Document]` containing the encoded BSON data. * - Throws: `EncodingError` if any value throws an error during encoding. */ - public func encode(_ values: [T]) throws -> [Document] { + public func encode(_ values: [T]) throws -> [BSONDocument] { try values.map { try self.encode($0) } } @@ -208,7 +208,7 @@ public class BSONEncoder { * contains no data will be mapped to nil. * - Throws: `EncodingError` if any value throws an error during encoding. */ - public func encode(_ values: [T?]) throws -> [Document?] { + public func encode(_ values: [T?]) throws -> [BSONDocument?] { try values.map { try self.encode($0) } } } @@ -369,7 +369,7 @@ private class _BSONReferencingEncoder: _BSONEncoder { deinit { let value: BSONValue switch self.storage.count { - case 0: value = Document() + case 0: value = BSONDocument() case 1: value = self.storage.popContainer() default: fatalError("Referencing encoder deallocated with multiple containers on stack.") } @@ -395,9 +395,9 @@ extension _BSONEncoder { return number } - /// Returns the value as a `BSONValue` if possible. Otherwise, returns an empty `Document`. + /// Returns the value as a `BSONValue` if possible. Otherwise, returns an empty `BSONDocument`. fileprivate func box(_ value: T) throws -> BSONValue { - try self.box_(value) ?? Document() + try self.box_(value) ?? BSONDocument() } fileprivate func handleCustomStrategy( @@ -754,11 +754,11 @@ private class MutableArray: BSONValue { /// methods required by the BSONValue protocol that we don't actually need/use. MutableArray /// is just a BSONValue to simplify usage alongside true BSONValues within the encoder. - fileprivate func encode(to _: inout Document, forKey _: String) throws { - fatalError("`MutableArray` is not meant to be encoded to a `Document`") + fileprivate func encode(to _: inout BSONDocument, forKey _: String) throws { + fatalError("`MutableArray` is not meant to be encoded to a `BSONDocument`") } - internal static func from(iterator _: DocumentIterator) -> BSON { + internal static func from(iterator _: BSONDocumentIterator) -> BSON { fatalError("`MutableArray` is not meant to be initialized from a `DocumentIterator`") } @@ -805,9 +805,9 @@ private class MutableDictionary: BSONValue { } } - /// Converts self to a `Document` with equivalent key-value pairs. - fileprivate func toDocument() -> Document { - var doc = Document() + /// Converts self to a `BSONDocument` with equivalent key-value pairs. + fileprivate func toDocument() -> BSONDocument { + var doc = BSONDocument() for i in 0.. BSON { + internal static func from(iterator _: BSONDocumentIterator) -> BSON { fatalError("`MutableDictionary` is not meant to be initialized from a `DocumentIterator`") } diff --git a/Sources/MongoSwift/BSON/BSONValue.swift b/Sources/MongoSwift/BSON/BSONValue.swift index 01acfc30c..c4163b5b9 100644 --- a/Sources/MongoSwift/BSON/BSONValue.swift +++ b/Sources/MongoSwift/BSON/BSONValue.swift @@ -59,7 +59,7 @@ internal protocol BSONValue: Codable { var bson: BSON { get } /** - * Given the `DocumentStorage` backing a `Document`, appends this `BSONValue` to the end. + * Given the `DocumentStorage` backing a `BSONDocument`, appends this `BSONValue` to the end. * * - Parameters: * - storage: A `DocumentStorage` to write to. @@ -70,16 +70,16 @@ internal protocol BSONValue: Codable { * key-value pair. * - `LogicError` if the value is an `Array` and it contains a non-`BSONValue` element. */ - func encode(to document: inout Document, forKey key: String) throws + func encode(to document: inout BSONDocument, forKey key: String) throws /** - * Given a `DocumentIterator` known to have a next value of this type, + * Given a `BSONDocumentIterator` known to have a next value of this type, * initializes the value. * - * - Throws: `LogicError` if the current type of the `DocumentIterator` does not correspond to the + * - Throws: `LogicError` if the current type of the `BSONDocumentIterator` does not correspond to the * associated type of this `BSONValue`. */ - static func from(iterator iter: DocumentIterator) throws -> BSON + static func from(iterator iter: BSONDocumentIterator) throws -> BSON } extension BSONValue { @@ -96,7 +96,7 @@ extension Array: BSONValue where Element == BSON { .array(self) } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .array else { throw wrongIterTypeError(iter, expected: Array.self) } @@ -116,13 +116,13 @@ extension Array: BSONValue where Element == BSON { throw InternalError(message: "Failed to create an Array from iterator") } - let arrDoc = Document(stealing: arrayData) + let arrDoc = BSONDocument(stealing: arrayData) return arrDoc.values }) } - internal func encode(to document: inout Document, forKey key: String) throws { - var arr = Document() + internal func encode(to document: inout BSONDocument, forKey key: String) throws { + var arr = BSONDocument() for (i, v) in self.enumerated() { try arr.setValue(for: String(i), to: v) } @@ -155,7 +155,7 @@ internal struct BSONNull: BSONValue, Codable, Equatable { internal var bson: BSON { .null } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .null else { throw wrongIterTypeError(iter, expected: BSONNull.self) } @@ -163,17 +163,17 @@ internal struct BSONNull: BSONValue, Codable, Equatable { } /// Initializes a new `BSONNull` instance. - public init() {} + internal init() {} - public init(from decoder: Decoder) throws { + internal init(from decoder: Decoder) throws { throw getDecodingError(type: BSONNull.self, decoder: decoder) } - public func encode(to: Encoder) throws { + internal func encode(to: Encoder) throws { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_null(docPtr, key, Int32(key.utf8.count)) else { throw bsonTooLargeError(value: self, forKey: key) @@ -286,7 +286,7 @@ public struct BSONBinary: BSONValue, Equatable, Codable, Hashable { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { let subtype = bson_subtype_t(UInt32(self.subtype)) let length = self.data.count let byteArray = [UInt8](self.data) @@ -297,7 +297,7 @@ public struct BSONBinary: BSONValue, Equatable, Codable, Hashable { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .binary else { throw wrongIterTypeError(iter, expected: BSONBinary.self) } @@ -350,7 +350,7 @@ extension Bool: BSONValue { internal var bson: BSON { .bool(self) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_bool(docPtr, key, Int32(key.utf8.count), self) else { throw bsonTooLargeError(value: self, forKey: key) @@ -358,7 +358,7 @@ extension Bool: BSONValue { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .bool else { throw wrongIterTypeError(iter, expected: Bool.self) } @@ -384,7 +384,7 @@ extension Date: BSONValue { /// The number of milliseconds after the Unix epoch that this `Date` occurs. internal var msSinceEpoch: Int64 { Int64((self.timeIntervalSince1970 * 1000.0).rounded()) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_date_time(docPtr, key, Int32(key.utf8.count), self.msSinceEpoch) else { throw bsonTooLargeError(value: self, forKey: key) @@ -392,7 +392,7 @@ extension Date: BSONValue { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .datetime else { throw wrongIterTypeError(iter, expected: Date.self) } @@ -405,7 +405,7 @@ extension Date: BSONValue { /// A struct to represent the deprecated DBPointer type. /// DBPointers cannot be instantiated, but they can be read from existing documents that contain them. -public struct DBPointer: BSONValue, Codable, Equatable, Hashable { +public struct BSONDBPointer: BSONValue, Codable, Equatable, Hashable { internal static var bsonType: BSONType { .dbPointer } internal var bson: BSON { .dbPointer(self) } @@ -422,14 +422,14 @@ public struct DBPointer: BSONValue, Codable, Equatable, Hashable { } public init(from decoder: Decoder) throws { - throw getDecodingError(type: DBPointer.self, decoder: decoder) + throw getDecodingError(type: BSONDBPointer.self, decoder: decoder) } public func encode(to: Encoder) throws { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in try withUnsafePointer(to: self.id.oid) { oidPtr in guard bson_append_dbpointer(docPtr, key, Int32(key.utf8.count), self.ref, oidPtr) else { @@ -439,7 +439,7 @@ public struct DBPointer: BSONValue, Codable, Equatable, Hashable { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { try iter.withBSONIterPointer { iterPtr in var length: UInt32 = 0 let collectionPP = UnsafeMutablePointer?>.allocate(capacity: 1) @@ -457,16 +457,16 @@ public struct DBPointer: BSONValue, Codable, Equatable, Hashable { bson_iter_dbpointer(iterPtr, &length, collectionPP, oidPP) guard let oidP = oidPP.pointee, let collectionP = collectionPP.pointee else { - throw wrongIterTypeError(iter, expected: DBPointer.self) + throw wrongIterTypeError(iter, expected: BSONDBPointer.self) } - return .dbPointer(DBPointer(ref: String(cString: collectionP), id: BSONObjectID(bsonOid: oidP.pointee))) + return .dbPointer(BSONDBPointer(ref: String(cString: collectionP), id: BSONObjectID(bsonOid: oidP.pointee))) } } } /// A struct to represent the BSON Decimal128 type. -public struct Decimal128: BSONValue, Equatable, Codable, CustomStringConvertible { +public struct BSONDecimal128: BSONValue, Equatable, Codable, CustomStringConvertible { internal static var bsonType: BSONType { .decimal128 } internal var bson: BSON { .decimal128(self) } @@ -487,12 +487,12 @@ public struct Decimal128: BSONValue, Equatable, Codable, CustomStringConvertible self.decimal128 = bsonDecimal } - /// Initializes a `Decimal128` value from the provided `String`. Returns `nil` if the input is not a valid + /// Initializes a `BSONDecimal128` value from the provided `String`. Returns `nil` if the input is not a valid /// Decimal128 string. /// - SeeAlso: https://github.com/mongodb/specifications/blob/master/source/bson-decimal128/decimal128.rst public init?(_ data: String) { do { - let bsonType = try Decimal128.toLibBSONType(data) + let bsonType = try BSONDecimal128.toLibBSONType(data) self.init(bsonDecimal: bsonType) } catch { return nil @@ -500,14 +500,14 @@ public struct Decimal128: BSONValue, Equatable, Codable, CustomStringConvertible } public init(from decoder: Decoder) throws { - throw getDecodingError(type: Decimal128.self, decoder: decoder) + throw getDecodingError(type: BSONDecimal128.self, decoder: decoder) } public func encode(to: Encoder) throws { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in try withUnsafePointer(to: self.decimal128) { ptr in guard bson_append_decimal128(docPtr, key, Int32(key.utf8.count), ptr) else { @@ -520,7 +520,7 @@ public struct Decimal128: BSONValue, Equatable, Codable, CustomStringConvertible /// Returns the provided string as a `bson_decimal128_t`, or throws an error if initialization fails due an /// invalid string. /// - Throws: - /// - `InvalidArgumentError` if the parameter string does not correspond to a valid `Decimal128`. + /// - `InvalidArgumentError` if the parameter string does not correspond to a valid `BSONDecimal128`. internal static func toLibBSONType(_ str: String) throws -> bson_decimal128_t { var value = bson_decimal128_t() guard bson_decimal128_from_string(str, &value) else { @@ -529,24 +529,24 @@ public struct Decimal128: BSONValue, Equatable, Codable, CustomStringConvertible return value } - public static func == (lhs: Decimal128, rhs: Decimal128) -> Bool { + public static func == (lhs: BSONDecimal128, rhs: BSONDecimal128) -> Bool { lhs.decimal128.low == rhs.decimal128.low && lhs.decimal128.high == rhs.decimal128.high } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { .decimal128(try iter.withBSONIterPointer { iterPtr in var value = bson_decimal128_t() guard bson_iter_decimal128(iterPtr, &value) else { - throw wrongIterTypeError(iter, expected: Decimal128.self) + throw wrongIterTypeError(iter, expected: BSONDecimal128.self) } - return Decimal128(bsonDecimal: value) + return BSONDecimal128(bsonDecimal: value) }) } } -// An extension of `Decimal128` to add capability to be hashed -extension Decimal128: Hashable { +// An extension of `BSONDecimal128` to add capability to be hashed +extension BSONDecimal128: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(self.description) } @@ -558,7 +558,7 @@ extension Double: BSONValue { internal var bson: BSON { .double(self) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_double(docPtr, key, Int32(key.utf8.count), self) else { throw bsonTooLargeError(value: self, forKey: key) @@ -566,7 +566,7 @@ extension Double: BSONValue { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .double else { throw wrongIterTypeError(iter, expected: Double.self) } @@ -583,7 +583,7 @@ extension Int32: BSONValue { internal var bson: BSON { .int32(self) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_int32(docPtr, key, Int32(key.utf8.count), self) else { throw bsonTooLargeError(value: self, forKey: key) @@ -591,7 +591,7 @@ extension Int32: BSONValue { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .int32 else { throw wrongIterTypeError(iter, expected: Int32.self) } @@ -608,7 +608,7 @@ extension Int64: BSONValue { internal var bson: BSON { .int64(self) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_int64(docPtr, key, Int32(key.utf8.count), self) else { throw bsonTooLargeError(value: self, forKey: key) @@ -616,7 +616,7 @@ extension Int64: BSONValue { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .int64 else { throw wrongIterTypeError(iter, expected: Int64.self) } @@ -636,12 +636,12 @@ public struct BSONCodeWithScope: BSONValue, Equatable, Codable, Hashable { /// A string containing Javascript code. public let code: String - /// An optional scope `Document` containing a mapping of identifiers to values, + /// An optional scope `BSONDocument` containing a mapping of identifiers to values, /// representing the context in which `code` should be evaluated. - public let scope: Document + public let scope: BSONDocument /// Initializes a `BSONCodeWithScope` with an optional scope value. - public init(code: String, scope: Document) { + public init(code: String, scope: BSONDocument) { self.code = code self.scope = scope } @@ -654,7 +654,7 @@ public struct BSONCodeWithScope: BSONValue, Equatable, Codable, Hashable { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in try self.scope.withBSONPointer { scopePtr in guard bson_append_code_with_scope(docPtr, key, Int32(key.utf8.count), self.code, scopePtr) else { @@ -664,7 +664,7 @@ public struct BSONCodeWithScope: BSONValue, Equatable, Codable, Hashable { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { .codeWithScope(try iter.withBSONIterPointer { iterPtr in var length: UInt32 = 0 guard iter.currentType == .codeWithScope else { @@ -682,7 +682,7 @@ public struct BSONCodeWithScope: BSONValue, Equatable, Codable, Hashable { guard let scopeData = bson_new_from_data(scopePointer.pointee, Int(scopeLength)) else { throw InternalError(message: "Failed to create a bson_t from scope data") } - let scopeDoc = Document(stealing: scopeData) + let scopeDoc = BSONDocument(stealing: scopeData) return self.init(code: code, scope: scopeDoc) }) @@ -711,7 +711,7 @@ public struct BSONCode: BSONValue, Equatable, Codable, Hashable { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_code(docPtr, key, Int32(key.utf8.count), self.code) else { throw bsonTooLargeError(value: self, forKey: key) @@ -719,7 +719,7 @@ public struct BSONCode: BSONValue, Equatable, Codable, Hashable { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { .code(try iter.withBSONIterPointer { iterPtr in guard iter.currentType == .code else { throw wrongIterTypeError(iter, expected: BSONCode.self) @@ -736,7 +736,7 @@ internal struct MaxKey: BSONValue, Equatable, Codable, Hashable { internal static var bsonType: BSONType { .maxKey } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_maxkey(docPtr, key, Int32(key.utf8.count)) else { throw bsonTooLargeError(value: self, forKey: key) @@ -744,18 +744,18 @@ internal struct MaxKey: BSONValue, Equatable, Codable, Hashable { } } - /// Initializes a new `MaxKey` instance. - public init() {} + /// Initializes a new `BSONMaxKey` instance. + internal init() {} - public init(from decoder: Decoder) throws { + internal init(from decoder: Decoder) throws { throw getDecodingError(type: MaxKey.self, decoder: decoder) } - public func encode(to: Encoder) throws { + internal func encode(to: Encoder) throws { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .maxKey else { throw wrongIterTypeError(iter, expected: MaxKey.self) } @@ -764,12 +764,12 @@ internal struct MaxKey: BSONValue, Equatable, Codable, Hashable { } /// A struct to represent the BSON MinKey type. -internal struct MinKey: BSONValue, Equatable, Codable, Hashable { +internal struct BSONMinKey: BSONValue, Equatable, Codable, Hashable { internal var bson: BSON { .minKey } internal static var bsonType: BSONType { .minKey } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_minkey(docPtr, key, Int32(key.utf8.count)) else { throw bsonTooLargeError(value: self, forKey: key) @@ -777,20 +777,20 @@ internal struct MinKey: BSONValue, Equatable, Codable, Hashable { } } - /// Initializes a new `MinKey` instance. - public init() {} + /// Initializes a new `BSONMinKey` instance. + internal init() {} - public init(from decoder: Decoder) throws { - throw getDecodingError(type: MinKey.self, decoder: decoder) + internal init(from decoder: Decoder) throws { + throw getDecodingError(type: BSONMinKey.self, decoder: decoder) } - public func encode(to: Encoder) throws { + internal func encode(to: Encoder) throws { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .minKey else { - throw wrongIterTypeError(iter, expected: MinKey.self) + throw wrongIterTypeError(iter, expected: BSONMinKey.self) } return .minKey } @@ -869,7 +869,7 @@ public struct BSONObjectID: BSONValue, Equatable, CustomStringConvertible, Codab try container.encode(self.hex) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in try withUnsafePointer(to: self.oid) { oidPtr in guard bson_append_oid(docPtr, key, Int32(key.utf8.count), oidPtr) else { @@ -879,7 +879,7 @@ public struct BSONObjectID: BSONValue, Equatable, CustomStringConvertible, Codab } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { .objectID(try iter.withBSONIterPointer { iterPtr in guard let oid = bson_iter_oid(iterPtr) else { throw wrongIterTypeError(iter, expected: BSONObjectID.self) @@ -972,7 +972,7 @@ public struct BSONRegularExpression: BSONValue, Equatable, Codable, Hashable { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_regex(docPtr, key, Int32(key.utf8.count), self.pattern, self.options) else { throw bsonTooLargeError(value: self, forKey: key) @@ -980,7 +980,7 @@ public struct BSONRegularExpression: BSONValue, Equatable, Codable, Hashable { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { .regex(try iter.withBSONIterPointer { iterPtr in let options = UnsafeMutablePointer?>.allocate(capacity: 1) defer { @@ -1017,7 +1017,7 @@ extension String: BSONValue { internal var bson: BSON { .string(self) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_utf8(docPtr, key, Int32(key.utf8.count), self, Int32(self.utf8.count)) else { throw bsonTooLargeError(value: self, forKey: key) @@ -1031,7 +1031,7 @@ extension String: BSONValue { self.init(data: buffer, encoding: .utf8) } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { .string(try iter.withBSONIterPointer { iterPtr in var length: UInt32 = 0 guard iter.currentType == .string, let strValue = bson_iter_utf8(iterPtr, &length) else { @@ -1079,7 +1079,7 @@ public struct BSONSymbol: BSONValue, CustomStringConvertible, Codable, Equatable throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_symbol( docPtr, @@ -1093,7 +1093,7 @@ public struct BSONSymbol: BSONValue, CustomStringConvertible, Codable, Equatable } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { .symbol(try iter.withBSONIterPointer { iterPtr in var length: UInt32 = 0 guard iter.currentType == .symbol, let cStr = bson_iter_symbol(iterPtr, &length) else { @@ -1141,7 +1141,7 @@ public struct BSONTimestamp: BSONValue, Equatable, Codable, Hashable { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_timestamp(docPtr, key, Int32(key.utf8.count), self.timestamp, self.increment) else { throw bsonTooLargeError(value: self, forKey: key) @@ -1149,7 +1149,7 @@ public struct BSONTimestamp: BSONValue, Equatable, Codable, Hashable { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .timestamp else { throw wrongIterTypeError(iter, expected: BSONTimestamp.self) } @@ -1173,15 +1173,15 @@ internal struct BSONUndefined: BSONValue, Equatable, Codable { internal init() {} - public init(from decoder: Decoder) throws { + internal init(from decoder: Decoder) throws { throw getDecodingError(type: BSONUndefined.self, decoder: decoder) } - public func encode(to: Encoder) throws { + internal func encode(to: Encoder) throws { throw bsonEncodingUnsupportedError(value: self, at: to.codingPath) } - internal func encode(to document: inout Document, forKey key: String) throws { + internal func encode(to document: inout BSONDocument, forKey key: String) throws { try document.withMutableBSONPointer { docPtr in guard bson_append_undefined(docPtr, key, Int32(key.utf8.count)) else { throw bsonTooLargeError(value: self, forKey: key) @@ -1189,7 +1189,7 @@ internal struct BSONUndefined: BSONValue, Equatable, Codable { } } - internal static func from(iterator iter: DocumentIterator) throws -> BSON { + internal static func from(iterator iter: BSONDocumentIterator) throws -> BSON { guard iter.currentType == .undefined else { throw wrongIterTypeError(iter, expected: BSONUndefined.self) } @@ -1246,7 +1246,8 @@ private func bsonDecodingDirectlyError(type _: T.Type, at codingPa * * Some example cases: * - Decoding directly from the BSONDecoder top-level (e.g. BSONDecoder().decode(BSONObjectID.self, from: ...)) - * - Encountering the wrong type of BSONValue (e.g. expected "_id" to be an `BSONObjectID`, got a `Document` instead) + * - Encountering the wrong type of BSONValue (e.g. expected "_id" to be an `BSONObjectID`, got a `BSONDocument` + * instead) * - Attempting to decode a driver-introduced BSONValue with a non-BSONDecoder */ internal func getDecodingError(type _: T.Type, decoder: Decoder) -> DecodingError { diff --git a/Sources/MongoSwift/BSON/CodingStrategies.swift b/Sources/MongoSwift/BSON/CodingStrategies.swift index b41cf47cd..bb090f6bb 100644 --- a/Sources/MongoSwift/BSON/CodingStrategies.swift +++ b/Sources/MongoSwift/BSON/CodingStrategies.swift @@ -3,15 +3,15 @@ import Foundation /// Protocol indicating a set of options can be used to configure `BSONEncoder` and `BSONDecoder`. public protocol CodingStrategyProvider { /// Specifies the strategy to use when converting `Date`s between their BSON representations and their - /// representations in (non `Document`) `Codable` types. + /// representations in (non `BSONDocument`) `Codable` types. var dateCodingStrategy: DateCodingStrategy? { get } /// Specifies the strategy to use when converting `UUID`s between their BSON representations and their - /// representations in (non `Document`) `Codable` types. + /// representations in (non `BSONDocument`) `Codable` types. var uuidCodingStrategy: UUIDCodingStrategy? { get } /// Specifies the strategy to use when converting `Data`s between their BSON representations and their - /// representations in (non `Document`) `Codable` types. + /// representations in (non `BSONDocument`) `Codable` types. var dataCodingStrategy: DataCodingStrategy? { get } } @@ -38,7 +38,8 @@ public struct BSONCoderOptions: CodingStrategyProvider { /** * Enum representing the various encoding/decoding strategy pairs for `Date`s. * Set these on a `MongoClient`, `MongoDatabase`, or `MongoCollection` so that the strategies will be applied when - * converting `Date`s between their BSON representations and their representations in (non `Document`) `Codable` types. + * converting `Date`s between their BSON representations and their representations in (non `BSONDocument`) `Codable` + * types. * * As per the BSON specification, the default strategy is to encode `Date`s as BSON datetime objects. * @@ -123,7 +124,8 @@ public enum DateCodingStrategy: RawRepresentable { /** * Enum representing the various encoding/decoding strategy pairs for `Date`s. * Set these on a `MongoClient`, `MongoDatabase`, or `MongoCollection` so that the strategies will be applied when - * converting `UUID`s between their BSON representations and their representations in (non `Document`) `Codable` types. + * converting `UUID`s between their BSON representations and their representations in (non `BSONDocument`) `Codable` + * types. * * As per the BSON specification, the default strategy is to encode `UUID`s as BSON binary types with the UUID * subtype. @@ -163,7 +165,8 @@ public enum UUIDCodingStrategy: RawRepresentable { /** * Enum representing the various encoding/decoding strategy pairs for `Date`s. * Set these on a `MongoClient`, `MongoDatabase`, or `MongoCollection` so that the strategies will be applied when - * converting `Data`s between their BSON representations and their representations in (non `Document`) `Codable` types. + * converting `Data`s between their BSON representations and their representations in (non `BSONDocument`) `Codable` + * types. * * As per the BSON specification, the default strategy is to encode `Data`s as BSON binary types with the generic * binary subtype. diff --git a/Sources/MongoSwift/BSON/Overwritable.swift b/Sources/MongoSwift/BSON/Overwritable.swift index a5e36f39c..79f94f3a9 100644 --- a/Sources/MongoSwift/BSON/Overwritable.swift +++ b/Sources/MongoSwift/BSON/Overwritable.swift @@ -10,35 +10,35 @@ internal protocol Overwritable: BSONValue { * - `InternalError` if the `BSONValue` is an `Int` and cannot be written to BSON. * - `LogicError` if the `BSONValue` is a `Decimal128` or `BSONObjectID` and is improperly formatted. */ - func writeToCurrentPosition(of iter: DocumentIterator) throws + func writeToCurrentPosition(of iter: BSONDocumentIterator) throws } extension Bool: Overwritable { - internal func writeToCurrentPosition(of iter: DocumentIterator) { + internal func writeToCurrentPosition(of iter: BSONDocumentIterator) { iter.withMutableBSONIterPointer { iterPtr in bson_iter_overwrite_bool(iterPtr, self) } } } extension Int32: Overwritable { - internal func writeToCurrentPosition(of iter: DocumentIterator) { + internal func writeToCurrentPosition(of iter: BSONDocumentIterator) { iter.withMutableBSONIterPointer { iterPtr in bson_iter_overwrite_int32(iterPtr, self) } } } extension Int64: Overwritable { - internal func writeToCurrentPosition(of iter: DocumentIterator) { + internal func writeToCurrentPosition(of iter: BSONDocumentIterator) { iter.withMutableBSONIterPointer { iterPtr in bson_iter_overwrite_int64(iterPtr, self) } } } extension Double: Overwritable { - internal func writeToCurrentPosition(of iter: DocumentIterator) { + internal func writeToCurrentPosition(of iter: BSONDocumentIterator) { iter.withMutableBSONIterPointer { iterPtr in bson_iter_overwrite_double(iterPtr, self) } } } -extension Decimal128: Overwritable { - internal func writeToCurrentPosition(of iter: DocumentIterator) throws { +extension BSONDecimal128: Overwritable { + internal func writeToCurrentPosition(of iter: BSONDocumentIterator) throws { withUnsafePointer(to: self.decimal128) { decPtr in iter.withMutableBSONIterPointer { iterPtr in bson_iter_overwrite_decimal128(iterPtr, decPtr) @@ -48,7 +48,7 @@ extension Decimal128: Overwritable { } extension BSONObjectID: Overwritable { - internal func writeToCurrentPosition(of iter: DocumentIterator) throws { + internal func writeToCurrentPosition(of iter: BSONDocumentIterator) throws { withUnsafePointer(to: self.oid) { oidPtr in iter.withMutableBSONIterPointer { iterPtr in bson_iter_overwrite_oid(iterPtr, oidPtr) } } @@ -56,7 +56,7 @@ extension BSONObjectID: Overwritable { } extension BSONTimestamp: Overwritable { - internal func writeToCurrentPosition(of iter: DocumentIterator) { + internal func writeToCurrentPosition(of iter: BSONDocumentIterator) { iter.withMutableBSONIterPointer { iterPtr in bson_iter_overwrite_timestamp(iterPtr, self.timestamp, self.increment) } @@ -64,7 +64,7 @@ extension BSONTimestamp: Overwritable { } extension Date: Overwritable { - internal func writeToCurrentPosition(of iter: DocumentIterator) { + internal func writeToCurrentPosition(of iter: BSONDocumentIterator) { iter.withMutableBSONIterPointer { iterPtr in bson_iter_overwrite_date_time(iterPtr, self.msSinceEpoch) } diff --git a/Sources/MongoSwift/ChangeStream.swift b/Sources/MongoSwift/ChangeStream.swift index c8d6c87c6..ea2ca5fb7 100644 --- a/Sources/MongoSwift/ChangeStream.swift +++ b/Sources/MongoSwift/ChangeStream.swift @@ -33,9 +33,9 @@ private struct MongocChangeStream: MongocCursorWrapper { /// `ChangeStreamOptions` to resume or start a change stream where a previous one left off. /// - SeeAlso: https://docs.mongodb.com/manual/changeStreams/#resume-a-change-stream public struct ResumeToken: Codable, Equatable { - private let resumeToken: Document + private let resumeToken: BSONDocument - internal init(_ resumeToken: Document) { + internal init(_ resumeToken: BSONDocument) { self.resumeToken = resumeToken } @@ -46,7 +46,7 @@ public struct ResumeToken: Codable, Equatable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() - self.resumeToken = try container.decode(Document.self) + self.resumeToken = try container.decode(BSONDocument.self) } } @@ -66,7 +66,7 @@ public class ChangeStream: CursorProtocol { private let wrappedCursor: Cursor /// Process an event before returning it to the user, or does nothing and returns nil if the provided event is nil. - private func processEvent(_ event: Document?) throws -> T? { + private func processEvent(_ event: BSONDocument?) throws -> T? { guard let event = event else { return nil } @@ -74,7 +74,7 @@ public class ChangeStream: CursorProtocol { } /// Process an event before returning it to the user. - private func processEvent(_ event: Document) throws -> T { + private func processEvent(_ event: BSONDocument) throws -> T { // Update the resumeToken with the `_id` field from the document. guard let resumeToken = event["_id"]?.documentValue else { throw InternalError(message: "_id field is missing from the change stream document.") diff --git a/Sources/MongoSwift/ChangeStreamDocument.swift b/Sources/MongoSwift/ChangeStreamDocument.swift index 3e8313e70..0256e3c61 100644 --- a/Sources/MongoSwift/ChangeStreamDocument.swift +++ b/Sources/MongoSwift/ChangeStreamDocument.swift @@ -3,7 +3,7 @@ public struct UpdateDescription: Codable { /// A document containing key:value pairs of names of the fields that were changed, and the new /// value for those fields. - public let updatedFields: Document + public let updatedFields: BSONDocument /// An array of field names that were removed from the document. public let removedFields: [String] @@ -55,7 +55,7 @@ public struct ChangeStreamEvent: Codable { * will contain all the components of the shard key in order, followed by the _id if the _id isn’t part of the * shard key. */ - public let documentKey: Document? + public let documentKey: BSONDocument? /// An `UpdateDescription` containing updated and removed fields in this operation. Only present for operations of /// type`update`. diff --git a/Sources/MongoSwift/ChangeStreamOptions.swift b/Sources/MongoSwift/ChangeStreamOptions.swift index 29f6a68ec..b0f4f83e1 100644 --- a/Sources/MongoSwift/ChangeStreamOptions.swift +++ b/Sources/MongoSwift/ChangeStreamOptions.swift @@ -34,7 +34,7 @@ public struct ChangeStreamOptions: Codable { /// Specifies a collation. /// - SeeAlso: https://docs.mongodb.com/manual/reference/command/aggregate - public var collation: Document? + public var collation: BSONDocument? /** * Indicates how the `fullDocument` field of a change stream document should be filled out by the server. @@ -76,7 +76,7 @@ public struct ChangeStreamOptions: Codable { /// Initializes a `ChangeStreamOptions`. public init( batchSize: Int? = nil, - collation: Document? = nil, + collation: BSONDocument? = nil, fullDocument: FullDocument? = nil, maxAwaitTimeMS: Int? = nil, resumeAfter: ResumeToken? = nil, diff --git a/Sources/MongoSwift/ClientSession.swift b/Sources/MongoSwift/ClientSession.swift index 51844bbc6..938b5e983 100644 --- a/Sources/MongoSwift/ClientSession.swift +++ b/Sources/MongoSwift/ClientSession.swift @@ -44,7 +44,7 @@ public final class ClientSession { /// Indicates that this session has not been used yet and a corresponding `mongoc_client_session_t` has not /// yet been created. If the user sets operation time or cluster time prior to using the session, those values /// are stored here so they can be set upon starting the session. - case notStarted(opTime: BSONTimestamp?, clusterTime: Document?) + case notStarted(opTime: BSONTimestamp?, clusterTime: BSONDocument?) /// Indicates that the session has been started and a corresponding `mongoc_client_session_t` exists. Stores a /// pointer to the underlying `mongoc_client_session_t` and the source `Connection` for this session. case started(session: OpaquePointer, connection: Connection) @@ -68,7 +68,7 @@ public final class ClientSession { /// The session ID of this session. This is internal for now because we only have a value available after we've /// started the libmongoc session. - internal var id: Document? + internal var id: BSONDocument? /// The server ID of the mongos this session is pinned to. private var serverID: UInt32? { @@ -163,7 +163,7 @@ public final class ClientSession { /// The most recent cluster time seen by this session. This value will be nil if either of the following are true: /// - No operations have been executed using this session and `advanceClusterTime` has not been called. /// - This session has been ended. - public var clusterTime: Document? { + public var clusterTime: BSONDocument? { switch self.state { case let .notStarted(_, clusterTime): return clusterTime @@ -171,7 +171,7 @@ public final class ClientSession { guard let time = mongoc_client_session_get_cluster_time(session) else { return nil } - return Document(copying: time) + return BSONDocument(copying: time) case .ended: return nil } @@ -227,7 +227,7 @@ public final class ClientSession { } // swiftlint:disable:next force_unwrapping - self.id = Document(copying: mongoc_client_session_get_lsid(sessionPtr)!) // always returns a value + self.id = BSONDocument(copying: mongoc_client_session_get_lsid(sessionPtr)!) // never returns nil } case .started: return self.client.operationExecutor.makeSucceededFuture(Void()) @@ -289,9 +289,9 @@ public final class ClientSession { * no effect. * * - Parameters: - * - clusterTime: The session's new cluster time, as a `Document` like `["cluster time": Timestamp(...)]` + * - clusterTime: The session's new cluster time, as a `BSONDocument` like `["cluster time": Timestamp(...)]` */ - public func advanceClusterTime(to clusterTime: Document) { + public func advanceClusterTime(to clusterTime: BSONDocument) { switch self.state { case let .notStarted(opTime, _): self.state = .notStarted(opTime: opTime, clusterTime: clusterTime) @@ -326,7 +326,7 @@ public final class ClientSession { /// Appends this provided session to an options document for libmongoc interoperability. /// - Throws: /// - `LogicError` if this session is inactive - internal func append(to doc: inout Document) throws { + internal func append(to doc: inout BSONDocument) throws { guard case let .started(session, _) = self.state else { throw ClientSession.SessionInactiveError } diff --git a/Sources/MongoSwift/ConnectionString.swift b/Sources/MongoSwift/ConnectionString.swift index d8a2bd5ba..ca9512f1b 100644 --- a/Sources/MongoSwift/ConnectionString.swift +++ b/Sources/MongoSwift/ConnectionString.swift @@ -118,7 +118,7 @@ internal class ConnectionString { } /// Returns a document containing the auth mechanism properties if any were provided, otherwise nil. - internal var authMechanismProperties: Document? { + internal var authMechanismProperties: BSONDocument? { var props = bson_t() return withUnsafeMutablePointer(to: &props) { propsPtr in guard mongoc_uri_get_mechanism_properties(self._uri, propsPtr) else { @@ -127,7 +127,7 @@ internal class ConnectionString { /// This copy should not be returned directly as its only guaranteed valid for as long as the /// `mongoc_uri_t`, as `props` was statically initialized from data stored in the URI and may contain /// pointers that will be invalidated once the URI is. - let copy = Document(copying: propsPtr) + let copy = BSONDocument(copying: propsPtr) return copy.mapValues { value in // mongoc returns boolean options e.g. CANONICALIZE_HOSTNAME as strings, but they are boolean values. @@ -162,11 +162,11 @@ internal class ConnectionString { } /// Returns a document containing all of the options provided after the ? of the URI. - internal var options: Document? { + internal var options: BSONDocument? { guard let optsDoc = mongoc_uri_get_options(self._uri) else { return nil } - return Document(copying: optsDoc) + return BSONDocument(copying: optsDoc) } /// Returns the host/port pairs specified in the connection string, or nil if this connection string's scheme is diff --git a/Sources/MongoSwift/CursorCommon.swift b/Sources/MongoSwift/CursorCommon.swift index a7a80b32e..b972bedb8 100644 --- a/Sources/MongoSwift/CursorCommon.swift +++ b/Sources/MongoSwift/CursorCommon.swift @@ -107,7 +107,7 @@ internal class Cursor { /// Used to store a cached next value to return, if one exists. private enum CachedDocument { /// Indicates that the associated value is the next value to return. This value may be nil. - case cached(Document?) + case cached(BSONDocument?) /// Indicates that there is no value cached. case none @@ -156,7 +156,7 @@ internal class Cursor { // but we will still parse the mongoc error to cover all cases. if let docPtr = replyPtr.pointee { // we have to copy because libmongoc owns the pointer. - let reply = Document(copying: docPtr) + let reply = BSONDocument(copying: docPtr) return extractMongoError(error: error, reply: reply) } @@ -169,7 +169,7 @@ internal class Cursor { /// Will close the cursor if the end of the cursor is reached or if an error occurs. /// /// This method should only be called while the lock is held. - private func getNextDocument() throws -> Document? { + private func getNextDocument() throws -> BSONDocument? { guard case let .open(mongocCursor, _, session) = self.state else { throw ClosedCursorError } @@ -203,7 +203,7 @@ internal class Cursor { } // We have to copy because libmongoc owns the pointer. - return Document(copying: pointee) + return BSONDocument(copying: pointee) } /// Close this cursor @@ -272,7 +272,7 @@ internal class Cursor { /// Block until a result document is received, an error occurs, or the cursor dies. /// This method is blocking and should only be run via the executor. - internal func next() throws -> Document? { + internal func next() throws -> BSONDocument? { try self.lock.withLock { guard self._isAlive else { throw ClosedCursorError @@ -298,7 +298,7 @@ internal class Cursor { /// Attempt to retrieve a single document from the server, returning nil if there are no results. /// This method is blocking and should only be run via the executor. - internal func tryNext() throws -> Document? { + internal func tryNext() throws -> BSONDocument? { try self.lock.withLock { if case let .cached(result) = self.cached.clear() { return result @@ -310,13 +310,13 @@ internal class Cursor { /// Retrieve all the currently available documents in the result set. /// This will not exhaust the cursor. /// This method is blocking and should only be run via the executor. - internal func toArray() throws -> [Document] { + internal func toArray() throws -> [BSONDocument] { try self.lock.withLock { guard self._isAlive else { throw ClosedCursorError } - var results: [Document] = [] + var results: [BSONDocument] = [] if case let .cached(result) = self.cached.clear(), let unwrappedResult = result { results.append(unwrappedResult) } diff --git a/Sources/MongoSwift/Hint.swift b/Sources/MongoSwift/Hint.swift index 903235f3b..11ec56c09 100644 --- a/Sources/MongoSwift/Hint.swift +++ b/Sources/MongoSwift/Hint.swift @@ -4,8 +4,8 @@ import Foundation public enum IndexHint: Codable { /// Specifies an index to use by its name. case indexName(String) - /// Specifies an index to use by a specification `Document` containing the index key(s). - case indexSpec(Document) + /// Specifies an index to use by a specification `BSONDocument` containing the index key(s). + case indexSpec(BSONDocument) public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() @@ -22,7 +22,7 @@ public enum IndexHint: Codable { if let str = try? container.decode(String.self) { self = .indexName(str) } else { - self = .indexSpec(try container.decode(Document.self)) + self = .indexSpec(try container.decode(BSONDocument.self)) } } } diff --git a/Sources/MongoSwift/MongoClient.swift b/Sources/MongoSwift/MongoClient.swift index bb96d7b11..84651e509 100644 --- a/Sources/MongoSwift/MongoClient.swift +++ b/Sources/MongoSwift/MongoClient.swift @@ -363,8 +363,8 @@ public class MongoClient { * Retrieves a list of databases in this client's MongoDB deployment. * * - Parameters: - * - filter: Optional `Document` specifying a filter that the listed databases must pass. This filter can be based - * on the "name", "sizeOnDisk", "empty", or "shards" fields of the output. + * - filter: Optional `BSONDocument` specifying a filter that the listed databases must pass. This filter can be + * based on the "name", "sizeOnDisk", "empty", or "shards" fields of the output. * - options: Optional `ListDatabasesOptions` specifying options for listing databases. * - session: Optional `ClientSession` to use when executing this command. * @@ -381,7 +381,7 @@ public class MongoClient { * - SeeAlso: https://docs.mongodb.com/manual/reference/command/listDatabases/ */ public func listDatabases( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture<[DatabaseSpecification]> { @@ -398,7 +398,7 @@ public class MongoClient { * Get a list of `MongoDatabase`s corresponding to the databases in this client's MongoDB deployment. * * - Parameters: - * - filter: Optional `Document` specifying a filter on the names of the returned databases. + * - filter: Optional `BSONDocument` specifying a filter on the names of the returned databases. * - options: Optional `ListDatabasesOptions` specifying options for listing databases. * - session: Optional `ClientSession` to use when executing this command * @@ -412,7 +412,7 @@ public class MongoClient { * - `CommandError` if options.authorizedDatabases is false and the user does not have listDatabases permissions. */ public func listMongoDatabases( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture<[MongoDatabase]> { @@ -423,7 +423,7 @@ public class MongoClient { * Get the names of databases in this client's MongoDB deployment. * * - Parameters: - * - filter: Optional `Document` specifying a filter on the names of the returned databases. + * - filter: Optional `BSONDocument` specifying a filter on the names of the returned databases. * - options: Optional `ListDatabasesOptions` specifying options for listing databases. * - session: Optional `ClientSession` to use when executing this command * @@ -437,7 +437,7 @@ public class MongoClient { * - `CommandError` if options.authorizedDatabases is false and the user does not have listDatabases permissions. */ public func listDatabaseNames( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture<[String]> { @@ -492,11 +492,11 @@ public class MongoClient { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil - ) -> EventLoopFuture>> { - self.watch(pipeline, options: options, session: session, withFullDocumentType: Document.self) + ) -> EventLoopFuture>> { + self.watch(pipeline, options: options, session: session, withFullDocumentType: BSONDocument.self) } /** @@ -529,7 +529,7 @@ public class MongoClient { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withFullDocumentType _: FullDocType.Type @@ -571,12 +571,12 @@ public class MongoClient { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withEventType _: EventType.Type ) -> EventLoopFuture> { - let operation = WatchOperation( + let operation = WatchOperation( target: .client(self), pipeline: pipeline, options: options diff --git a/Sources/MongoSwift/MongoCollection+BulkWrite.swift b/Sources/MongoSwift/MongoCollection+BulkWrite.swift index 824841e1d..6dabe5b44 100644 --- a/Sources/MongoSwift/MongoCollection+BulkWrite.swift +++ b/Sources/MongoSwift/MongoCollection+BulkWrite.swift @@ -41,36 +41,36 @@ extension MongoCollection { public enum WriteModel { /// A `deleteOne`. /// Parameters: - /// - A `Document` representing the match criteria. + /// - A `BSONDocument` representing the match criteria. /// - `options`: Optional `DeleteModelOptions`. - case deleteOne(Document, options: DeleteModelOptions? = nil) + case deleteOne(BSONDocument, options: DeleteModelOptions? = nil) /// A `deleteMany`. /// Parameters: - /// - A `Document` representing the match criteria. + /// - A `BSONDocument` representing the match criteria. /// - `options`: Optional `DeleteModelOptions`. - case deleteMany(Document, options: DeleteModelOptions? = nil) + case deleteMany(BSONDocument, options: DeleteModelOptions? = nil) /// An `insertOne`. /// Parameters: /// - A `T` to insert. case insertOne(CollectionType) /// A `replaceOne`. /// Parameters: - /// - `filter`: A `Document` representing the match criteria. + /// - `filter`: A `BSONDocument` representing the match criteria. /// - `replacement`: A `T` to use as the replacement value. /// - `options`: Optional `ReplaceOneModelOptions`. - case replaceOne(filter: Document, replacement: CollectionType, options: ReplaceOneModelOptions? = nil) + case replaceOne(filter: BSONDocument, replacement: CollectionType, options: ReplaceOneModelOptions? = nil) /// An `updateOne`. /// Parameters: - /// - `filter`: A `Document` representing the match criteria. - /// - `update`: A `Document` containing update operators. + /// - `filter`: A `BSONDocument` representing the match criteria. + /// - `update`: A `BSONDocument` containing update operators. /// - `options`: Optional `UpdateModelOptions`. - case updateOne(filter: Document, update: Document, options: UpdateModelOptions? = nil) + case updateOne(filter: BSONDocument, update: BSONDocument, options: UpdateModelOptions? = nil) /// An `updateMany`. /// Parameters: - /// - `filter`: A `Document` representing the match criteria. - /// - `update`: A `Document` containing update operators. + /// - `filter`: A `BSONDocument` representing the match criteria. + /// - `update`: A `BSONDocument` containing update operators. /// - `options`: Optional `UpdateModelOptions`. - case updateMany(filter: Document, update: Document, options: UpdateModelOptions? = nil) + case updateMany(filter: BSONDocument, update: BSONDocument, options: UpdateModelOptions? = nil) /// Adds this model to the provided `mongoc_bulk_t`, using the provided encoder for encoding options and /// `CollectionType` values if needed. If this is an `insertOne`, returns the `_id` field of the inserted @@ -151,10 +151,10 @@ public enum WriteModel { /// Options to use with a `WriteModel.deleteOne` or `WriteModel.deleteMany`. public struct DeleteModelOptions: Codable { /// The collation to use. - public var collation: Document? + public var collation: BSONDocument? /// Initializer allowing any/all options to be omitted or optional. - public init(collation: Document? = nil) { + public init(collation: BSONDocument? = nil) { self.collation = collation } } @@ -162,12 +162,12 @@ public struct DeleteModelOptions: Codable { /// Options to use with a `WriteModel.replaceOne`. public struct ReplaceOneModelOptions: Codable { /// The collation to use. - public var collation: Document? + public var collation: BSONDocument? /// When `true`, creates a new document if no document matches the query. public var upsert: Bool? /// Initializer allowing any/all options to be omitted or optional. - public init(collation: Document? = nil, upsert: Bool? = nil) { + public init(collation: BSONDocument? = nil, upsert: Bool? = nil) { self.collation = collation self.upsert = upsert } @@ -176,14 +176,14 @@ public struct ReplaceOneModelOptions: Codable { /// Options to use with a `WriteModel.updateOne` or `WriteModel.updateMany`. public struct UpdateModelOptions: Codable { /// A set of filters specifying to which array elements an update should apply. - public var arrayFilters: [Document]? + public var arrayFilters: [BSONDocument]? /// The collation to use. - public var collation: Document? + public var collation: BSONDocument? /// When `true`, creates a new document if no document matches the query. public var upsert: Bool? /// Initializer allowing any/all options to be omitted or optional. - public init(arrayFilters: [Document]? = nil, collation: Document? = nil, upsert: Bool? = nil) { + public init(arrayFilters: [BSONDocument]? = nil, collation: BSONDocument? = nil, upsert: Bool? = nil) { self.arrayFilters = arrayFilters self.collation = collation self.upsert = upsert @@ -240,9 +240,9 @@ internal struct BulkWriteOperation: Operation { } var error = bson_error_t() - let (serverID, reply) = withStackAllocatedMutableBSONPointer { replyPtr -> (UInt32, Document) in + let (serverID, reply) = withStackAllocatedMutableBSONPointer { replyPtr -> (UInt32, BSONDocument) in let serverID = mongoc_bulk_operation_execute(bulk, replyPtr, &error) - let reply = Document(copying: replyPtr) + let reply = BSONDocument(copying: replyPtr) return (serverID, reply) } @@ -397,13 +397,13 @@ public struct BulkWriteResult: Decodable { * we should expect fields to be missing and handle that gracefully. * * - Parameters: - * - reply: A `Document` result from `mongoc_bulk_operation_execute()` + * - reply: A `BSONDocument` result from `mongoc_bulk_operation_execute()` * - insertedIDs: Map of inserted IDs * * - Throws: * - `InternalError` if an unexpected error occurs reading the reply from the server. */ - fileprivate init?(reply: Document, insertedIDs: [Int: BSON]) throws { + fileprivate init?(reply: BSONDocument, insertedIDs: [Int: BSON]) throws { guard reply.keys.contains(where: { MongocKeys(rawValue: $0) != nil }) else { return nil } @@ -418,7 +418,7 @@ public struct BulkWriteResult: Decodable { var upsertedIDs = [Int: BSON]() if let upserted = try reply.getValue(for: MongocKeys.upserted.rawValue)?.arrayValue { - guard let upserted = upserted.toArrayOf(Document.self) else { + guard let upserted = upserted.toArrayOf(BSONDocument.self) else { throw InternalError(message: "\"upserted\" array did not contain only documents") } diff --git a/Sources/MongoSwift/MongoCollection+ChangeStreams.swift b/Sources/MongoSwift/MongoCollection+ChangeStreams.swift index 99d752e76..3a7f64a5f 100644 --- a/Sources/MongoSwift/MongoCollection+ChangeStreams.swift +++ b/Sources/MongoSwift/MongoCollection+ChangeStreams.swift @@ -27,7 +27,7 @@ extension MongoCollection { * - https://docs.mongodb.com/manual/reference/system-collections/ */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture>> { @@ -61,7 +61,7 @@ extension MongoCollection { * - https://docs.mongodb.com/manual/reference/system-collections/ */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withFullDocumentType _: FullDocType.Type @@ -100,7 +100,7 @@ extension MongoCollection { * - https://docs.mongodb.com/manual/reference/system-collections/ */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withEventType _: EventType.Type diff --git a/Sources/MongoSwift/MongoCollection+FindAndModify.swift b/Sources/MongoSwift/MongoCollection+FindAndModify.swift index e88cbc08a..676efa310 100644 --- a/Sources/MongoSwift/MongoCollection+FindAndModify.swift +++ b/Sources/MongoSwift/MongoCollection+FindAndModify.swift @@ -7,7 +7,7 @@ extension MongoCollection { * Finds a single document and deletes it, returning the original. * * - Parameters: - * - filter: `Document` representing the match criteria + * - filter: `BSONDocument` representing the match criteria * - options: Optional `FindOneAndDeleteOptions` to use when executing the command * - session: Optional `ClientSession` to use when executing this command * @@ -24,7 +24,7 @@ extension MongoCollection { * - `DecodingError` if the deleted document cannot be decoded to a `CollectionType` value. */ public func findOneAndDelete( - _ filter: Document, + _ filter: BSONDocument, options: FindOneAndDeleteOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture { @@ -37,7 +37,7 @@ extension MongoCollection { * Finds a single document and replaces it, returning either the original or the replaced document. * * - Parameters: - * - filter: `Document` representing the match criteria + * - filter: `BSONDocument` representing the match criteria * - replacement: a `CollectionType` to replace the found document * - options: Optional `FindOneAndReplaceOptions` to use when executing the command * - session: Optional `ClientSession` to use when executing this command @@ -54,10 +54,10 @@ extension MongoCollection { * - `CommandError` if an error occurs that prevents the command from executing. * - `WriteError` if an error occurs while executing the command. * - `DecodingError` if the replaced document cannot be decoded to a `CollectionType` value. - * - `EncodingError` if `replacement` cannot be encoded to a `Document`. + * - `EncodingError` if `replacement` cannot be encoded to a `BSONDocument`. */ public func findOneAndReplace( - filter: Document, + filter: BSONDocument, replacement: CollectionType, options: FindOneAndReplaceOptions? = nil, session: ClientSession? = nil @@ -74,8 +74,8 @@ extension MongoCollection { * Finds a single document and updates it, returning either the original or the updated document. * * - Parameters: - * - filter: `Document` representing the match criteria - * - update: a `Document` containing updates to apply + * - filter: `BSONDocument` representing the match criteria + * - update: a `BSONDocument` containing updates to apply * - options: Optional `FindOneAndUpdateOptions` to use when executing the command * - session: Optional `ClientSession` to use when executing this command * @@ -92,8 +92,8 @@ extension MongoCollection { * - `DecodingError` if the updated document cannot be decoded to a `CollectionType` value. */ public func findOneAndUpdate( - filter: Document, - update: Document, + filter: BSONDocument, + update: BSONDocument, options: FindOneAndUpdateOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture { @@ -115,8 +115,8 @@ extension MongoCollection { * - `DecodingError` if the updated document cannot be decoded to a `CollectionType` value. */ private func findAndModify( - filter: Document, - update: Document? = nil, + filter: BSONDocument, + update: BSONDocument? = nil, options: FindAndModifyOptionsConvertible? = nil, session: ClientSession? ) -> EventLoopFuture { @@ -144,16 +144,16 @@ internal protocol FindAndModifyOptionsConvertible { /// Options to use when executing a `findOneAndDelete` command on a `MongoCollection`. public struct FindOneAndDeleteOptions: FindAndModifyOptionsConvertible, Decodable { /// Specifies a collation to use. - public var collation: Document? + public var collation: BSONDocument? /// The maximum amount of time to allow the query to run. public var maxTimeMS: Int? /// Limits the fields to return for the matching document. - public var projection: Document? + public var projection: BSONDocument? /// Determines which document the operation modifies if the query selects multiple documents. - public var sort: Document? + public var sort: BSONDocument? /// An optional `WriteConcern` to use for the command. public var writeConcern: WriteConcern? @@ -171,10 +171,10 @@ public struct FindOneAndDeleteOptions: FindAndModifyOptionsConvertible, Decodabl /// Convenience initializer allowing any/all parameters to be omitted/optional public init( - collation: Document? = nil, + collation: BSONDocument? = nil, maxTimeMS: Int? = nil, - projection: Document? = nil, - sort: Document? = nil, + projection: BSONDocument? = nil, + sort: BSONDocument? = nil, writeConcern: WriteConcern? = nil ) { self.collation = collation @@ -191,19 +191,19 @@ public struct FindOneAndReplaceOptions: FindAndModifyOptionsConvertible, Decodab public var bypassDocumentValidation: Bool? /// Specifies a collation to use. - public var collation: Document? + public var collation: BSONDocument? /// The maximum amount of time to allow the query to run. public var maxTimeMS: Int? /// Limits the fields to return for the matching document. - public var projection: Document? + public var projection: BSONDocument? /// When `ReturnDocument.After`, returns the replaced or inserted document rather than the original. public var returnDocument: ReturnDocument? /// Determines which document the operation modifies if the query selects multiple documents. - public var sort: Document? + public var sort: BSONDocument? /// When `true`, creates a new document if no document matches the query. public var upsert: Bool? @@ -227,11 +227,11 @@ public struct FindOneAndReplaceOptions: FindAndModifyOptionsConvertible, Decodab /// Convenience initializer allowing any/all parameters to be omitted/optional. public init( bypassDocumentValidation: Bool? = nil, - collation: Document? = nil, + collation: BSONDocument? = nil, maxTimeMS: Int? = nil, - projection: Document? = nil, + projection: BSONDocument? = nil, returnDocument: ReturnDocument? = nil, - sort: Document? = nil, + sort: BSONDocument? = nil, upsert: Bool? = nil, writeConcern: WriteConcern? = nil ) { @@ -249,25 +249,25 @@ public struct FindOneAndReplaceOptions: FindAndModifyOptionsConvertible, Decodab /// Options to use when executing a `findOneAndUpdate` command on a `MongoCollection`. public struct FindOneAndUpdateOptions: FindAndModifyOptionsConvertible, Decodable { /// A set of filters specifying to which array elements an update should apply. - public var arrayFilters: [Document]? + public var arrayFilters: [BSONDocument]? /// If `true`, allows the write to opt-out of document level validation. public var bypassDocumentValidation: Bool? /// Specifies a collation to use. - public var collation: Document? + public var collation: BSONDocument? /// The maximum amount of time to allow the query to run. public var maxTimeMS: Int? /// Limits the fields to return for the matching document. - public var projection: Document? + public var projection: BSONDocument? /// When`ReturnDocument.After`, returns the updated or inserted document rather than the original. public var returnDocument: ReturnDocument? /// Determines which document the operation modifies if the query selects multiple documents. - public var sort: Document? + public var sort: BSONDocument? /// When `true`, creates a new document if no document matches the query. public var upsert: Bool? @@ -291,13 +291,13 @@ public struct FindOneAndUpdateOptions: FindAndModifyOptionsConvertible, Decodabl /// Convenience initializer allowing any/all parameters to be omitted/optional. public init( - arrayFilters: [Document]? = nil, + arrayFilters: [BSONDocument]? = nil, bypassDocumentValidation: Bool? = nil, - collation: Document? = nil, + collation: BSONDocument? = nil, maxTimeMS: Int? = nil, - projection: Document? = nil, + projection: BSONDocument? = nil, returnDocument: ReturnDocument? = nil, - sort: Document? = nil, + sort: BSONDocument? = nil, upsert: Bool? = nil, writeConcern: WriteConcern? = nil ) { diff --git a/Sources/MongoSwift/MongoCollection+Indexes.swift b/Sources/MongoSwift/MongoCollection+Indexes.swift index 543a9f4c7..7e59ee2db 100644 --- a/Sources/MongoSwift/MongoCollection+Indexes.swift +++ b/Sources/MongoSwift/MongoCollection+Indexes.swift @@ -4,13 +4,13 @@ import NIO /// A struct representing an index on a `MongoCollection`. public struct IndexModel: Codable { /// Contains the required keys for the index. - public let keys: Document + public let keys: BSONDocument /// Contains the options for the index. public let options: IndexOptions? /// Convenience initializer providing a default `options` value - public init(keys: Document, options: IndexOptions? = nil) { + public init(keys: BSONDocument, options: IndexOptions? = nil) { self.keys = keys self.options = options } @@ -33,7 +33,7 @@ public struct IndexModel: Codable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - self.keys = try values.decode(Document.self, forKey: .key) + self.keys = try values.decode(BSONDocument.self, forKey: .key) self.options = try IndexOptions(from: decoder) } } @@ -51,7 +51,7 @@ public struct IndexOptions: Codable { /// Optionally specifies a collation to use for the index in MongoDB 3.4 and higher. If not specified, no collation /// is sent and the default collation of the collection server-side is used. - public var collation: Document? + public var collation: BSONDocument? /// Optionally specifies the default language for text indexes. Is 'english' if none is provided. public var defaultLanguage: String? @@ -81,7 +81,7 @@ public struct IndexOptions: Codable { /// Optionally specifies a filter for use in a partial index. Only documents that match the filter expression are /// included in the index. New in MongoDB 3.2. - public var partialFilterExpression: Document? + public var partialFilterExpression: BSONDocument? /// Optionally tells the index to only reference documents with the specified field in the index. public var sparse: Bool? @@ -92,7 +92,7 @@ public struct IndexOptions: Codable { /// Optionally used only in MongoDB 3.0.0 and higher. Allows users to configure the storage engine on a per-index /// basis when creating an index. - public var storageEngine: Document? + public var storageEngine: BSONDocument? /// Optionally provides the text index version number. MongoDB 2.4 can only support version 1. MongoDB 2.6 and /// higher may support version 1 or 2. @@ -105,28 +105,28 @@ public struct IndexOptions: Codable { public var version: Int? /// Optionally specifies fields in the index and their corresponding weight values. - public var weights: Document? + public var weights: BSONDocument? /// Convenience initializer allowing any/all parameters to be omitted. public init( background: Bool? = nil, bits: Int? = nil, bucketSize: Int? = nil, - collation: Document? = nil, + collation: BSONDocument? = nil, defaultLanguage: String? = nil, expireAfterSeconds: Int? = nil, languageOverride: String? = nil, max: Double? = nil, min: Double? = nil, name: String? = nil, - partialFilterExpression: Document? = nil, + partialFilterExpression: BSONDocument? = nil, sparse: Bool? = nil, sphereIndexVersion: Int? = nil, - storageEngine: Document? = nil, + storageEngine: BSONDocument? = nil, textIndexVersion: Int? = nil, unique: Bool? = nil, version: Int? = nil, - weights: Document? = nil + weights: BSONDocument? = nil ) { self.background = background self.bits = bits @@ -162,7 +162,7 @@ extension MongoCollection { * Creates an index over the collection for the provided keys with the provided options. * * - Parameters: - * - keys: a `Document` specifing the keys for the index + * - keys: a `BSONDocument` specifing the keys for the index * - indexOptions: Optional `IndexOptions` to use for the index * - options: Optional `CreateIndexOptions` to use for the command * - session: Optional `ClientSession` to use when executing this command @@ -179,7 +179,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the index specification or options. */ public func createIndex( - _ keys: Document, + _ keys: BSONDocument, indexOptions: IndexOptions? = nil, options: CreateIndexOptions? = nil, session: ClientSession? = nil @@ -289,7 +289,7 @@ extension MongoCollection { * Attempts to drop a single index from the collection given the keys describing it. * * - Parameters: - * - keys: a `Document` containing the keys for the index to drop + * - keys: a `BSONDocument` containing the keys for the index to drop * - options: Optional `DropIndexOptions` to use for the command * - session: Optional `ClientSession` to use when executing this command * @@ -305,7 +305,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options. */ public func dropIndex( - _ keys: Document, + _ keys: BSONDocument, options: DropIndexOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture { diff --git a/Sources/MongoSwift/MongoCollection+Read.swift b/Sources/MongoSwift/MongoCollection+Read.swift index cdf947a15..0059bee62 100644 --- a/Sources/MongoSwift/MongoCollection+Read.swift +++ b/Sources/MongoSwift/MongoCollection+Read.swift @@ -7,7 +7,7 @@ extension MongoCollection { * Finds the documents in this collection which match the provided filter. * * - Parameters: - * - filter: A `Document` that should match the query + * - filter: A `BSONDocument` that should match the query * - options: Optional `FindOptions` to use when executing the command * - session: Optional `ClientSession` to use when executing this command * @@ -21,7 +21,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func find( - _ filter: Document = [:], + _ filter: BSONDocument = [:], options: FindOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture> { @@ -33,7 +33,7 @@ extension MongoCollection { * Finds a single document in this collection that matches the provided filter. * * - Parameters: - * - filter: A `Document` that should match the query + * - filter: A `BSONDocument` that should match the query * - options: Optional `FindOneOptions` to use when executing the command * - session: Optional `ClientSession` to use when executing this command * @@ -48,7 +48,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func findOne( - _ filter: Document = [:], + _ filter: BSONDocument = [:], options: FindOneOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture { @@ -76,10 +76,10 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func aggregate( - _ pipeline: [Document], + _ pipeline: [BSONDocument], options: AggregateOptions? = nil, session: ClientSession? = nil - ) -> EventLoopFuture> { + ) -> EventLoopFuture> { let operation = AggregateOperation(collection: self, pipeline: pipeline, options: options) return self._client.operationExecutor.execute(operation, client: self._client, session: session) } @@ -90,7 +90,7 @@ extension MongoCollection { * `estimatedDocumentCount`. * * - Parameters: - * - filter: a `Document`, the filter that documents must match in order to be counted + * - filter: a `BSONDocument`, the filter that documents must match in order to be counted * - options: Optional `CountDocumentsOptions` to use when executing the command * - session: Optional `ClientSession` to use when executing this command * @@ -105,7 +105,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func countDocuments( - _ filter: Document = [:], + _ filter: BSONDocument = [:], options: CountDocumentsOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture { @@ -139,7 +139,8 @@ extension MongoCollection { * * - Parameters: * - fieldName: The field for which the distinct values will be found - * - filter: a `Document` representing the filter documents must match in order to be considered for the operation + * - filter: a `BSONDocument` representing the filter documents must match in order to be considered for the + * operation * - options: Optional `DistinctOptions` to use when executing the command * - session: Optional `ClientSession` to use when executing this command * @@ -155,7 +156,7 @@ extension MongoCollection { */ public func distinct( fieldName: String, - filter: Document = [:], + filter: BSONDocument = [:], options: DistinctOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture<[BSON]> { diff --git a/Sources/MongoSwift/MongoCollection+Write.swift b/Sources/MongoSwift/MongoCollection+Write.swift index 2bad8192f..e8b9ac440 100644 --- a/Sources/MongoSwift/MongoCollection+Write.swift +++ b/Sources/MongoSwift/MongoCollection+Write.swift @@ -68,7 +68,7 @@ extension MongoCollection { * Replaces a single document matching the provided filter in this collection. * * - Parameters: - * - filter: A `Document` representing the match criteria + * - 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 @@ -86,7 +86,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the `CollectionType` or options to BSON. */ public func replaceOne( - filter: Document, + filter: BSONDocument, replacement: CollectionType, options: ReplaceOptions? = nil, session: ClientSession? = nil @@ -102,8 +102,8 @@ extension MongoCollection { * Updates a single document matching the provided filter in this collection. * * - Parameters: - * - filter: A `Document` representing the match criteria - * - update: A `Document` representing the update to be applied to a matching document + * - 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 * @@ -120,8 +120,8 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func updateOne( - filter: Document, - update: Document, + filter: BSONDocument, + update: BSONDocument, options: UpdateOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture { @@ -140,8 +140,8 @@ extension MongoCollection { * Updates multiple documents matching the provided filter in this collection. * * - Parameters: - * - filter: A `Document` representing the match criteria - * - update: A `Document` representing the update to be applied to matching documents + * - 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 * @@ -158,8 +158,8 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func updateMany( - filter: Document, - update: Document, + filter: BSONDocument, + update: BSONDocument, options: UpdateOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture { @@ -178,7 +178,7 @@ extension MongoCollection { * Deletes a single matching document from the collection. * * - Parameters: - * - filter: A `Document` representing the match criteria + * - 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 * @@ -195,7 +195,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func deleteOne( - _ filter: Document, + _ filter: BSONDocument, options: DeleteOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture { @@ -227,7 +227,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func deleteMany( - _ filter: Document, + _ filter: BSONDocument, options: DeleteOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture { @@ -279,13 +279,13 @@ 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: [Document]? + 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: Document? + public var collation: BSONDocument? /// When true, creates a new document if no document matches the query. public var upsert: Bool? @@ -295,9 +295,9 @@ public struct UpdateOptions: Codable, BulkWriteOptionsConvertible { /// Convenience initializer allowing any/all parameters to be optional public init( - arrayFilters: [Document]? = nil, + arrayFilters: [BSONDocument]? = nil, bypassDocumentValidation: Bool? = nil, - collation: Document? = nil, + collation: BSONDocument? = nil, upsert: Bool? = nil, writeConcern: WriteConcern? = nil ) { @@ -315,7 +315,7 @@ public struct ReplaceOptions: Codable, BulkWriteOptionsConvertible { public var bypassDocumentValidation: Bool? /// Specifies a collation. - public var collation: Document? + public var collation: BSONDocument? /// When true, creates a new document if no document matches the query. public var upsert: Bool? @@ -326,7 +326,7 @@ public struct ReplaceOptions: Codable, BulkWriteOptionsConvertible { /// Convenience initializer allowing any/all parameters to be optional public init( bypassDocumentValidation: Bool? = nil, - collation: Document? = nil, + collation: BSONDocument? = nil, upsert: Bool? = nil, writeConcern: WriteConcern? = nil ) { @@ -340,13 +340,13 @@ public struct ReplaceOptions: Codable, BulkWriteOptionsConvertible { /// Options to use when executing a `delete` command on a `MongoCollection`. public struct DeleteOptions: Codable, BulkWriteOptionsConvertible { /// Specifies a collation. - public var collation: Document? + public var collation: BSONDocument? /// An optional `WriteConcern` to use for the command. public var writeConcern: WriteConcern? /// Convenience initializer allowing collation to be omitted or optional - public init(collation: Document? = nil, writeConcern: WriteConcern? = nil) { + public init(collation: BSONDocument? = nil, writeConcern: WriteConcern? = nil) { self.collation = collation self.writeConcern = writeConcern } diff --git a/Sources/MongoSwift/MongoCredential.swift b/Sources/MongoSwift/MongoCredential.swift index 43ac56eda..e39ff7f3b 100644 --- a/Sources/MongoSwift/MongoCredential.swift +++ b/Sources/MongoSwift/MongoCredential.swift @@ -15,7 +15,7 @@ public struct MongoCredential: Decodable, Equatable { public var mechanism: Mechanism? /// A document containing mechanism-specific properties. - public var mechanismProperties: Document? + public var mechanismProperties: BSONDocument? private enum CodingKeys: String, CodingKey { case username, password, source, mechanism, mechanismProperties = "mechanism_properties" @@ -26,7 +26,7 @@ public struct MongoCredential: Decodable, Equatable { password: String? = nil, source: String? = nil, mechanism: Mechanism? = nil, - mechanismProperties: Document? = nil + mechanismProperties: BSONDocument? = nil ) { self.username = username self.password = password diff --git a/Sources/MongoSwift/MongoCursor.swift b/Sources/MongoSwift/MongoCursor.swift index 14b3fd2df..95f364728 100644 --- a/Sources/MongoSwift/MongoCursor.swift +++ b/Sources/MongoSwift/MongoCursor.swift @@ -81,7 +81,7 @@ public class MongoCursor: CursorProtocol { } /// Decodes a result to the generic type or `nil` if no result were returned. - private func decode(result: Document?) throws -> T? { + private func decode(result: BSONDocument?) throws -> T? { guard let doc = result else { return nil } @@ -89,7 +89,7 @@ public class MongoCursor: CursorProtocol { } /// Decodes the given document to the generic type. - private func decode(doc: Document) throws -> T { + private func decode(doc: BSONDocument) throws -> T { try self.decoder.decode(T.self, from: doc) } diff --git a/Sources/MongoSwift/MongoDatabase.swift b/Sources/MongoSwift/MongoDatabase.swift index 92d03f44b..666995eef 100644 --- a/Sources/MongoSwift/MongoDatabase.swift +++ b/Sources/MongoSwift/MongoDatabase.swift @@ -143,8 +143,8 @@ public struct MongoDatabase { * * - Returns: the requested `MongoCollection` */ - public func collection(_ name: String, options: MongoCollectionOptions? = nil) -> MongoCollection { - self.collection(name, withType: Document.self, options: options) + public func collection(_ name: String, options: MongoCollectionOptions? = nil) -> MongoCollection { + self.collection(name, withType: BSONDocument.self, options: options) } /** @@ -191,8 +191,8 @@ public struct MongoDatabase { _ name: String, options: CreateCollectionOptions? = nil, session: ClientSession? = nil - ) -> EventLoopFuture> { - self.createCollection(name, withType: Document.self, options: options, session: session) + ) -> EventLoopFuture> { + self.createCollection(name, withType: BSONDocument.self, options: options, session: session) } /** @@ -230,7 +230,7 @@ public struct MongoDatabase { * Lists all the collections in this database. * * - Parameters: - * - filter: a `Document`, optional criteria to filter results by + * - filter: a `BSONDocument`, optional criteria to filter results by * - options: Optional `ListCollectionsOptions` to use when executing this command * - session: Optional `ClientSession` to use when executing this command * @@ -243,7 +243,7 @@ public struct MongoDatabase { * - `LogicError` if this databases's parent client has already been closed. */ public func listCollections( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListCollectionsOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture> { @@ -262,7 +262,7 @@ public struct MongoDatabase { * Gets a list of `MongoCollection`s corresponding to collections in this database. * * - Parameters: - * - filter: a `Document`, optional criteria to filter results by + * - filter: a `BSONDocument`, optional criteria to filter results by * - options: Optional `ListCollectionsOptions` to use when executing this command * - session: Optional `ClientSession` to use when executing this command * @@ -276,10 +276,10 @@ public struct MongoDatabase { * - `LogicError` if this databases's parent client has already been closed. */ public func listMongoCollections( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListCollectionsOptions? = nil, session: ClientSession? = nil - ) -> EventLoopFuture<[MongoCollection]> { + ) -> EventLoopFuture<[MongoCollection]> { self.listCollectionNames(filter, options: options, session: session).map { collNames in collNames.map { self.collection($0) } } @@ -289,7 +289,7 @@ public struct MongoDatabase { * Gets a list of names of collections in this database. * * - Parameters: - * - filter: a `Document`, optional criteria to filter results by + * - filter: a `BSONDocument`, optional criteria to filter results by * - options: Optional `ListCollectionsOptions` to use when executing this command * - session: Optional `ClientSession` to use when executing this command * @@ -302,7 +302,7 @@ public struct MongoDatabase { * - `LogicError` if this databases's parent client has already been closed. */ public func listCollectionNames( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListCollectionsOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture<[String]> { @@ -320,7 +320,7 @@ public struct MongoDatabase { * Issues a MongoDB command against this database. * * - Parameters: - * - command: a `Document` containing the command to issue against the database + * - command: a `BSONDocument` 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 * @@ -336,10 +336,10 @@ public struct MongoDatabase { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func runCommand( - _ command: Document, + _ command: BSONDocument, options: RunCommandOptions? = nil, session: ClientSession? = nil - ) -> EventLoopFuture { + ) -> EventLoopFuture { let operation = RunCommandOperation(database: self, command: command, options: options) return self._client.operationExecutor.execute(operation, client: self._client, session: session) } @@ -370,11 +370,11 @@ public struct MongoDatabase { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil - ) -> EventLoopFuture>> { - self.watch(pipeline, options: options, session: session, withFullDocumentType: Document.self) + ) -> EventLoopFuture>> { + self.watch(pipeline, options: options, session: session, withFullDocumentType: BSONDocument.self) } /** @@ -407,7 +407,7 @@ public struct MongoDatabase { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withFullDocumentType _: FullDocType.Type @@ -449,12 +449,12 @@ public struct MongoDatabase { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withEventType _: EventType.Type ) -> EventLoopFuture> { - let operation = WatchOperation( + let operation = WatchOperation( target: .database(self), pipeline: pipeline, options: options diff --git a/Sources/MongoSwift/MongoError.swift b/Sources/MongoSwift/MongoError.swift index cb85eb255..2448a3b26 100644 --- a/Sources/MongoSwift/MongoError.swift +++ b/Sources/MongoSwift/MongoError.swift @@ -191,7 +191,7 @@ public struct WriteConcernFailure: Codable { public let codeName: String /// A document identifying the write concern setting related to the error. - public let details: Document? + public let details: BSONDocument? /// A description of the error. public let message: String @@ -213,13 +213,13 @@ public struct WriteConcernFailure: Codable { self.code = try container.decode(ServerErrorCode.self, forKey: .code) self.message = try container.decode(String.self, forKey: .message) self.codeName = try container.decodeIfPresent(String.self, forKey: .codeName) ?? "" - self.details = try container.decodeIfPresent(Document.self, forKey: .details) + self.details = try container.decodeIfPresent(BSONDocument.self, forKey: .details) self.errorLabels = try container.decodeIfPresent([String].self, forKey: .errorLabels) } // TODO: can remove this once SERVER-36755 is resolved internal init( - code: ServerErrorCode, codeName: String, details: Document?, message: String, errorLabels: [String]? = nil + code: ServerErrorCode, codeName: String, details: BSONDocument?, message: String, errorLabels: [String]? = nil ) { self.code = code self.codeName = codeName @@ -272,7 +272,7 @@ public struct BulkWriteFailure: Codable { /// Gets an appropriate error from a libmongoc error. Additional details may be provided in the form of a server reply /// document. -private func parseMongocError(_ error: bson_error_t, reply: Document?) -> MongoError { +private func parseMongocError(_ error: bson_error_t, reply: BSONDocument?) -> MongoError { let domain = mongoc_error_domain_t(rawValue: error.domain) let code = mongoc_error_code_t(rawValue: error.code) let message = toErrorString(error) @@ -323,10 +323,10 @@ private func parseMongocError(_ error: bson_error_t, reply: Document?) -> MongoE // swiftlint:enable cyclomatic_complexity /// Internal function used to get an appropriate error from a libmongoc error and/or a server reply to a command. -internal func extractMongoError(error bsonError: bson_error_t, reply: Document? = nil) -> MongoError { +internal func extractMongoError(error bsonError: bson_error_t, reply: BSONDocument? = nil) -> MongoError { // if the reply is nil or writeErrors or writeConcernErrors aren't present, use the mongoc error to determine // what to throw. - guard let serverReply: Document = reply, + guard let serverReply: BSONDocument = reply, !(serverReply["writeErrors"]?.arrayValue ?? []).isEmpty || !(serverReply["writeConcernError"]?.documentValue?.keys ?? []).isEmpty || !(serverReply["writeConcernErrors"]?.arrayValue ?? []).isEmpty else { @@ -365,7 +365,7 @@ internal func extractMongoError(error bsonError: bson_error_t, reply: Document? internal func extractBulkWriteError( for op: BulkWriteOperation, error: bson_error_t, - reply: Document, + reply: BSONDocument, partialResult: BulkWriteResult? ) -> Error { // If the result is nil, that meains either the write was unacknowledged (so the error is likely coming @@ -447,7 +447,7 @@ internal func extractBulkWriteError( } /// Extracts a `WriteConcernError` from a server reply. -private func extractWriteConcernError(from reply: Document) throws -> WriteConcernFailure? { +private func extractWriteConcernError(from reply: BSONDocument) throws -> WriteConcernFailure? { if let writeConcernErrors = reply["writeConcernErrors"]?.arrayValue?.compactMap({ $0.documentValue }), !writeConcernErrors.isEmpty { return try BSONDecoder().decode(WriteConcernFailure.self, from: writeConcernErrors[0]) @@ -506,7 +506,7 @@ internal func bsonTooLargeError(value: BSONValue, forKey: String) -> MongoError ) } -internal func wrongIterTypeError(_ iter: DocumentIterator, expected type: BSONValue.Type) -> MongoError { +internal func wrongIterTypeError(_ iter: BSONDocumentIterator, expected type: BSONValue.Type) -> MongoError { LogicError( message: "Tried to retreive a \(type) from an iterator whose next type " + "is \(iter.currentType) for key \(iter.currentKey)" diff --git a/Sources/MongoSwift/Operations/AggregateOperation.swift b/Sources/MongoSwift/Operations/AggregateOperation.swift index 118b4ae3f..f2390d7b7 100644 --- a/Sources/MongoSwift/Operations/AggregateOperation.swift +++ b/Sources/MongoSwift/Operations/AggregateOperation.swift @@ -7,7 +7,7 @@ public struct AggregateOptions: Codable { /// can write data to the _tmp subdirectory in the dbPath directory. public var allowDiskUse: Bool? - /// The number of `Document`s to return per batch. + /// The number of `BSONDocument`s to return per batch. public var batchSize: Int? /// If true, allows the write to opt-out of document level validation. This only applies @@ -15,7 +15,7 @@ public struct AggregateOptions: Codable { public var bypassDocumentValidation: Bool? /// Specifies a collation. - public var collation: Document? + public var collation: BSONDocument? /// Enables users to specify an arbitrary string to help trace the operation through /// the database profiler, currentOp and logs. The default is to not send a value. @@ -43,7 +43,7 @@ public struct AggregateOptions: Codable { allowDiskUse: Bool? = nil, batchSize: Int? = nil, bypassDocumentValidation: Bool? = nil, - collation: Document? = nil, + collation: BSONDocument? = nil, comment: String? = nil, hint: IndexHint? = nil, maxTimeMS: Int? = nil, @@ -72,18 +72,18 @@ public struct AggregateOptions: Codable { /// An operation corresponding to an "aggregate" command on a collection. internal struct AggregateOperation: Operation { private let collection: MongoCollection - private let pipeline: [Document] + private let pipeline: [BSONDocument] private let options: AggregateOptions? - internal init(collection: MongoCollection, pipeline: [Document], options: AggregateOptions?) { + internal init(collection: MongoCollection, pipeline: [BSONDocument], options: AggregateOptions?) { self.collection = collection self.pipeline = pipeline self.options = options } - internal func execute(using connection: Connection, session: ClientSession?) throws -> MongoCursor { + internal func execute(using connection: Connection, session: ClientSession?) throws -> MongoCursor { let opts = try encodeOptions(options: self.options, session: session) - let pipeline: Document = ["pipeline": .array(self.pipeline.map { .document($0) })] + let pipeline: BSONDocument = ["pipeline": .array(self.pipeline.map { .document($0) })] let result: OpaquePointer = self.collection.withMongocCollection(from: connection) { collPtr in pipeline.withBSONPointer { pipelinePtr in diff --git a/Sources/MongoSwift/Operations/CommitTransactionOperation.swift b/Sources/MongoSwift/Operations/CommitTransactionOperation.swift index c2f136516..55d56dca4 100644 --- a/Sources/MongoSwift/Operations/CommitTransactionOperation.swift +++ b/Sources/MongoSwift/Operations/CommitTransactionOperation.swift @@ -11,7 +11,7 @@ internal struct CommitTransactionOperation: Operation { try withStackAllocatedMutableBSONPointer { replyPtr in var error = bson_error_t() guard mongoc_client_session_commit_transaction(sessionPtr, replyPtr, &error) else { - throw extractMongoError(error: error, reply: Document(copying: replyPtr)) + throw extractMongoError(error: error, reply: BSONDocument(copying: replyPtr)) } } } diff --git a/Sources/MongoSwift/Operations/CountDocumentsOperation.swift b/Sources/MongoSwift/Operations/CountDocumentsOperation.swift index 02ddb33cf..27b842d74 100644 --- a/Sources/MongoSwift/Operations/CountDocumentsOperation.swift +++ b/Sources/MongoSwift/Operations/CountDocumentsOperation.swift @@ -3,7 +3,7 @@ import CLibMongoC /// Options to use when executing a `countDocuments` command on a `MongoCollection`. public struct CountDocumentsOptions: Codable { /// Specifies a collation. - public var collation: Document? + public var collation: BSONDocument? /// A hint for the index to use. public var hint: IndexHint? @@ -27,7 +27,7 @@ public struct CountDocumentsOptions: Codable { /// Convenience initializer allowing any/all parameters to be optional public init( - collation: Document? = nil, + collation: BSONDocument? = nil, hint: IndexHint? = nil, limit: Int? = nil, maxTimeMS: Int? = nil, @@ -52,10 +52,10 @@ public struct CountDocumentsOptions: Codable { /// An operation corresponding to a "count" command on a collection. internal struct CountDocumentsOperation: Operation { private let collection: MongoCollection - private let filter: Document + private let filter: BSONDocument private let options: CountDocumentsOptions? - internal init(collection: MongoCollection, filter: Document, options: CountDocumentsOptions?) { + internal init(collection: MongoCollection, filter: BSONDocument, options: CountDocumentsOptions?) { self.collection = collection self.filter = filter self.options = options @@ -64,7 +64,7 @@ internal struct CountDocumentsOperation: Operation { internal func execute(using connection: Connection, session: ClientSession?) throws -> Int { let opts = try encodeOptions(options: options, session: session) var error = bson_error_t() - var reply = Document() + var reply = BSONDocument() let count = self.collection.withMongocCollection(from: connection) { collPtr in self.filter.withBSONPointer { filterPtr in withOptionalBSONPointer(to: opts) { optsPtr in diff --git a/Sources/MongoSwift/Operations/CreateCollectionOperation.swift b/Sources/MongoSwift/Operations/CreateCollectionOperation.swift index 33d98a585..8bc91e000 100644 --- a/Sources/MongoSwift/Operations/CreateCollectionOperation.swift +++ b/Sources/MongoSwift/Operations/CreateCollectionOperation.swift @@ -6,7 +6,7 @@ public struct CreateCollectionOptions: Codable, CodingStrategyProvider { public var capped: Bool? /// Specifies the default collation for the collection. - public var collation: Document? + public var collation: BSONDocument? // swiftlint:disable redundant_optional_initialization // to get synthesized decodable conformance for the struct, these strategies need default values. @@ -22,20 +22,20 @@ public struct CreateCollectionOptions: Codable, CodingStrategyProvider { public var dateCodingStrategy: DateCodingStrategy? = nil /// Specify a default configuration for indexes created on this collection. - public var indexOptionDefaults: Document? + public var indexOptionDefaults: BSONDocument? /// Maximum number of documents allowed in the collection (if capped). public var max: Int? /// An array consisting of aggregation pipeline stages. When used with `viewOn`, will create the view by applying /// this pipeline to the source collection or view. - public var pipeline: [Document]? + public var pipeline: [BSONDocument]? /// Maximum size, in bytes, of this collection (if capped). public var size: Int? /// Specifies storage engine configuration for this collection. - public var storageEngine: Document? + public var storageEngine: BSONDocument? /// Specifies the `UUIDCodingStrategy` to use for BSON encoding/decoding operations performed by this collection. /// It is the responsibility of the user to ensure that any `UUID`s already stored in this collection can be @@ -52,7 +52,7 @@ public struct CreateCollectionOptions: Codable, CodingStrategyProvider { public var validationLevel: String? /// What validator should be used for the collection. - public var validator: Document? + public var validator: BSONDocument? /// The name of the source collection or view from which to create the view. public var viewOn: String? @@ -69,18 +69,18 @@ public struct CreateCollectionOptions: Codable, CodingStrategyProvider { /// Convenience initializer allowing any/all parameters to be omitted or optional. public init( capped: Bool? = nil, - collation: Document? = nil, + collation: BSONDocument? = nil, dataCodingStrategy: DataCodingStrategy? = nil, dateCodingStrategy: DateCodingStrategy? = nil, - indexOptionDefaults: Document? = nil, + indexOptionDefaults: BSONDocument? = nil, max: Int? = nil, - pipeline: [Document]? = nil, + pipeline: [BSONDocument]? = nil, size: Int? = nil, - storageEngine: Document? = nil, + storageEngine: BSONDocument? = nil, uuidCodingStrategy: UUIDCodingStrategy? = nil, validationAction: String? = nil, validationLevel: String? = nil, - validator: Document? = nil, + validator: BSONDocument? = nil, viewOn: String? = nil, writeConcern: WriteConcern? = nil ) { diff --git a/Sources/MongoSwift/Operations/CreateIndexesOperation.swift b/Sources/MongoSwift/Operations/CreateIndexesOperation.swift index 290ea09ec..06b997db4 100644 --- a/Sources/MongoSwift/Operations/CreateIndexesOperation.swift +++ b/Sources/MongoSwift/Operations/CreateIndexesOperation.swift @@ -37,7 +37,7 @@ internal struct CreateIndexesOperation: Operation { indexData.append(.document(indexDoc)) } - let command: Document = ["createIndexes": .string(self.collection.name), "indexes": .array(indexData)] + let command: BSONDocument = ["createIndexes": .string(self.collection.name), "indexes": .array(indexData)] let opts = try encodeOptions(options: options, session: session) diff --git a/Sources/MongoSwift/Operations/DistinctOperation.swift b/Sources/MongoSwift/Operations/DistinctOperation.swift index d1b185592..7f4655c57 100644 --- a/Sources/MongoSwift/Operations/DistinctOperation.swift +++ b/Sources/MongoSwift/Operations/DistinctOperation.swift @@ -3,7 +3,7 @@ import CLibMongoC /// Options to use when executing a `distinct` command on a `MongoCollection`. public struct DistinctOptions: Codable { /// Specifies a collation. - public var collation: Document? + public var collation: BSONDocument? /// The maximum amount of time to allow the query to run. public var maxTimeMS: Int? @@ -18,7 +18,7 @@ public struct DistinctOptions: Codable { /// Convenience initializer allowing any/all parameters to be optional public init( - collation: Document? = nil, + collation: BSONDocument? = nil, maxTimeMS: Int? = nil, readConcern: ReadConcern? = nil, readPreference: ReadPreference? = nil @@ -38,10 +38,10 @@ public struct DistinctOptions: Codable { internal struct DistinctOperation: Operation { private let collection: MongoCollection private let fieldName: String - private let filter: Document + private let filter: BSONDocument private let options: DistinctOptions? - internal init(collection: MongoCollection, fieldName: String, filter: Document, options: DistinctOptions?) { + internal init(collection: MongoCollection, fieldName: String, filter: BSONDocument, options: DistinctOptions?) { self.collection = collection self.fieldName = fieldName self.filter = filter @@ -49,7 +49,7 @@ internal struct DistinctOperation: Operation { } internal func execute(using connection: Connection, session: ClientSession?) throws -> [BSON] { - let command: Document = [ + let command: BSONDocument = [ "distinct": .string(self.collection.name), "key": .string(self.fieldName), "query": .document(self.filter) diff --git a/Sources/MongoSwift/Operations/DropCollectionOperation.swift b/Sources/MongoSwift/Operations/DropCollectionOperation.swift index 1a8f80fc8..0fcaff0c1 100644 --- a/Sources/MongoSwift/Operations/DropCollectionOperation.swift +++ b/Sources/MongoSwift/Operations/DropCollectionOperation.swift @@ -11,7 +11,7 @@ internal struct DropCollectionOperation: Operation { } internal func execute(using connection: Connection, session: ClientSession?) throws { - let command: Document = ["drop": .string(self.collection.name)] + let command: BSONDocument = ["drop": .string(self.collection.name)] let opts = try encodeOptions(options: options, session: session) do { diff --git a/Sources/MongoSwift/Operations/DropDatabaseOperation.swift b/Sources/MongoSwift/Operations/DropDatabaseOperation.swift index 24e463480..f2c8302f6 100644 --- a/Sources/MongoSwift/Operations/DropDatabaseOperation.swift +++ b/Sources/MongoSwift/Operations/DropDatabaseOperation.swift @@ -11,7 +11,7 @@ internal struct DropDatabaseOperation: Operation { } internal func execute(using connection: Connection, session: ClientSession?) throws { - let command: Document = ["dropDatabase": 1] + let command: BSONDocument = ["dropDatabase": 1] let opts = try encodeOptions(options: self.options, session: session) try runMongocCommand(command: command, options: opts) { cmdPtr, optsPtr, replyPtr, error in diff --git a/Sources/MongoSwift/Operations/DropIndexesOperation.swift b/Sources/MongoSwift/Operations/DropIndexesOperation.swift index 0a3603131..36dc9a9aa 100644 --- a/Sources/MongoSwift/Operations/DropIndexesOperation.swift +++ b/Sources/MongoSwift/Operations/DropIndexesOperation.swift @@ -28,7 +28,7 @@ internal struct DropIndexesOperation: Operation { } internal func execute(using connection: Connection, session: ClientSession?) throws { - let command: Document = ["dropIndexes": .string(self.collection.name), "index": self.index] + let command: BSONDocument = ["dropIndexes": .string(self.collection.name), "index": self.index] let opts = try encodeOptions(options: self.options, session: session) do { diff --git a/Sources/MongoSwift/Operations/FindAndModifyOperation.swift b/Sources/MongoSwift/Operations/FindAndModifyOperation.swift index 4c1969f71..980b90458 100644 --- a/Sources/MongoSwift/Operations/FindAndModifyOperation.swift +++ b/Sources/MongoSwift/Operations/FindAndModifyOperation.swift @@ -19,14 +19,14 @@ internal class FindAndModifyOptions { /// - Throws: `InvalidArgumentError` if any of the options are invalid. // swiftlint:disable:next cyclomatic_complexity internal init( - arrayFilters: [Document]? = nil, + arrayFilters: [BSONDocument]? = nil, bypassDocumentValidation: Bool? = nil, - collation: Document?, + collation: BSONDocument?, maxTimeMS: Int?, - projection: Document?, + projection: BSONDocument?, remove: Bool? = nil, returnDocument: ReturnDocument? = nil, - sort: Document?, + sort: BSONDocument?, upsert: Bool? = nil, writeConcern: WriteConcern? ) throws { @@ -72,7 +72,7 @@ internal class FindAndModifyOptions { } // build an "extra" document of fields without their own setters - var extra = Document() + var extra = BSONDocument() if let filters = arrayFilters { try extra.setValue(for: "arrayFilters", to: .array(filters.map { .document($0) })) } @@ -107,7 +107,7 @@ internal class FindAndModifyOptions { /// Sets the `update` value on a `mongoc_find_and_modify_opts_t`. We need to have this separate from the /// initializer because its value comes from the API methods rather than their options types. - fileprivate func setUpdate(_ update: Document) throws { + fileprivate func setUpdate(_ update: BSONDocument) throws { try update.withBSONPointer { updatePtr in guard mongoc_find_and_modify_opts_set_update(self._options, updatePtr) else { throw InvalidArgumentError(message: "Error setting update to \(update)") @@ -119,7 +119,7 @@ internal class FindAndModifyOptions { guard let session = session else { return } - var doc = Document() + var doc = BSONDocument() try session.append(to: &doc) try doc.withBSONPointer { docPtr in @@ -138,14 +138,14 @@ internal class FindAndModifyOptions { /// An operation corresponding to a "findAndModify" command. internal struct FindAndModifyOperation: Operation { private let collection: MongoCollection - private let filter: Document - private let update: Document? + private let filter: BSONDocument + private let update: BSONDocument? private let options: FindAndModifyOptionsConvertible? internal init( collection: MongoCollection, - filter: Document, - update: Document?, + filter: BSONDocument, + update: BSONDocument?, options: FindAndModifyOptionsConvertible? ) { self.collection = collection @@ -163,22 +163,23 @@ internal struct FindAndModifyOperation: Operation { var error = bson_error_t() - let (success, reply) = self.collection.withMongocCollection(from: connection) { collPtr -> (Bool, Document) in - self.filter.withBSONPointer { filterPtr in - opts.withMongocOptions { optsPtr in - withStackAllocatedMutableBSONPointer { replyPtr in - let success = mongoc_collection_find_and_modify_with_opts( - collPtr, - filterPtr, - optsPtr, - replyPtr, - &error - ) - return (success, Document(copying: replyPtr)) + let (success, reply) = self.collection + .withMongocCollection(from: connection) { collPtr -> (Bool, BSONDocument) in + self.filter.withBSONPointer { filterPtr in + opts.withMongocOptions { optsPtr in + withStackAllocatedMutableBSONPointer { replyPtr in + let success = mongoc_collection_find_and_modify_with_opts( + collPtr, + filterPtr, + optsPtr, + replyPtr, + &error + ) + return (success, BSONDocument(copying: replyPtr)) + } } } } - } guard success else { throw extractMongoError(error: error, reply: reply) diff --git a/Sources/MongoSwift/Operations/FindOperation.swift b/Sources/MongoSwift/Operations/FindOperation.swift index 941cab613..b1880841c 100644 --- a/Sources/MongoSwift/Operations/FindOperation.swift +++ b/Sources/MongoSwift/Operations/FindOperation.swift @@ -46,7 +46,7 @@ public struct FindOptions: Codable { public var batchSize: Int? /// Specifies a collation. - public var collation: Document? + public var collation: BSONDocument? /// Attaches a comment to the query. public var comment: String? @@ -87,7 +87,7 @@ public struct FindOptions: Codable { public var limit: Int? /// The exclusive upper bound for a specific index. - public var max: Document? + public var max: BSONDocument? /// The maximum amount of time, in milliseconds, for the server to wait on new documents to satisfy a tailable /// cursor query. This only applies when used with `MongoCursorType.tailableAwait`. Otherwise, this option is @@ -98,14 +98,14 @@ public struct FindOptions: Codable { public var maxTimeMS: Int? /// The inclusive lower bound for a specific index. - public var min: Document? + public var min: BSONDocument? /// The server normally times out idle cursors after an inactivity period (10 minutes) /// to prevent excess memory use. Set this option to prevent that. public var noCursorTimeout: Bool? /// Limits the fields to return for all matching documents. - public var projection: Document? + public var projection: BSONDocument? /// A ReadConcern to use for this operation. public var readConcern: ReadConcern? @@ -126,7 +126,7 @@ public struct FindOptions: Codable { public var skip: Int? /// The order in which to return matching documents. - public var sort: Document? + public var sort: BSONDocument? /// If a `MongoCursorType` is provided, indicates whether it is `.tailable` or .`tailableAwait`. private var tailable: Bool? @@ -138,23 +138,23 @@ public struct FindOptions: Codable { allowDiskUse: Bool? = nil, allowPartialResults: Bool? = nil, batchSize: Int? = nil, - collation: Document? = nil, + collation: BSONDocument? = nil, comment: String? = nil, cursorType: MongoCursorType? = nil, hint: IndexHint? = nil, limit: Int? = nil, - max: Document? = nil, + max: BSONDocument? = nil, maxAwaitTimeMS: Int? = nil, maxTimeMS: Int? = nil, - min: Document? = nil, + min: BSONDocument? = nil, noCursorTimeout: Bool? = nil, - projection: Document? = nil, + projection: BSONDocument? = nil, readConcern: ReadConcern? = nil, readPreference: ReadPreference? = nil, returnKey: Bool? = nil, showRecordID: Bool? = nil, skip: Int? = nil, - sort: Document? = nil + sort: BSONDocument? = nil ) { self.allowDiskUse = allowDiskUse self.allowPartialResults = allowPartialResults @@ -210,7 +210,7 @@ public struct FindOneOptions: Codable { public var allowPartialResults: Bool? /// Specifies a collation. - public var collation: Document? + public var collation: BSONDocument? /// Attaches a comment to the query. public var comment: String? @@ -219,16 +219,16 @@ public struct FindOneOptions: Codable { public var hint: IndexHint? /// The exclusive upper bound for a specific index. - public var max: Document? + public var max: BSONDocument? /// The maximum amount of time to allow the query to run. public var maxTimeMS: Int? /// The inclusive lower bound for a specific index. - public var min: Document? + public var min: BSONDocument? /// Limits the fields to return for all matching documents. - public var projection: Document? + public var projection: BSONDocument? /// A ReadConcern to use for this operation. public var readConcern: ReadConcern? @@ -247,24 +247,24 @@ public struct FindOneOptions: Codable { public var skip: Int? /// The order in which to return matching documents. - public var sort: Document? + public var sort: BSONDocument? /// Convenience initializer allowing any/all parameters to be omitted or optional. public init( allowPartialResults: Bool? = nil, - collation: Document? = nil, + collation: BSONDocument? = nil, comment: String? = nil, hint: IndexHint? = nil, - max: Document? = nil, + max: BSONDocument? = nil, maxTimeMS: Int? = nil, - min: Document? = nil, - projection: Document? = nil, + min: BSONDocument? = nil, + projection: BSONDocument? = nil, readConcern: ReadConcern? = nil, readPreference: ReadPreference? = nil, returnKey: Bool? = nil, showRecordID: Bool? = nil, skip: Int? = nil, - sort: Document? = nil + sort: BSONDocument? = nil ) { self.allowPartialResults = allowPartialResults self.collation = collation @@ -292,10 +292,10 @@ public struct FindOneOptions: Codable { /// An operation corresponding to a "find" command on a collection. internal struct FindOperation: Operation { private let collection: MongoCollection - private let filter: Document + private let filter: BSONDocument private let options: FindOptions? - internal init(collection: MongoCollection, filter: Document, options: FindOptions?) { + internal init(collection: MongoCollection, filter: BSONDocument, options: FindOptions?) { self.collection = collection self.filter = filter self.options = options diff --git a/Sources/MongoSwift/Operations/ListCollectionsOperation.swift b/Sources/MongoSwift/Operations/ListCollectionsOperation.swift index ae4199e65..487a8eaa7 100644 --- a/Sources/MongoSwift/Operations/ListCollectionsOperation.swift +++ b/Sources/MongoSwift/Operations/ListCollectionsOperation.swift @@ -95,10 +95,10 @@ internal enum ListCollectionsResults { internal struct ListCollectionsOperation: Operation { private let database: MongoDatabase private let nameOnly: Bool - private let filter: Document? + private let filter: BSONDocument? private let options: ListCollectionsOptions? - internal init(database: MongoDatabase, nameOnly: Bool, filter: Document?, options: ListCollectionsOptions?) { + internal init(database: MongoDatabase, nameOnly: Bool, filter: BSONDocument?, options: ListCollectionsOptions?) { self.database = database self.nameOnly = nameOnly self.filter = filter @@ -106,7 +106,7 @@ internal struct ListCollectionsOperation: Operation { } internal func execute(using connection: Connection, session: ClientSession?) throws -> ListCollectionsResults { - var opts = try encodeOptions(options: self.options, session: session) ?? Document() + var opts = try encodeOptions(options: self.options, session: session) ?? BSONDocument() opts["nameOnly"] = .bool(self.nameOnly) if let filterDoc = self.filter { opts["filter"] = .document(filterDoc) diff --git a/Sources/MongoSwift/Operations/ListDatabasesOperation.swift b/Sources/MongoSwift/Operations/ListDatabasesOperation.swift index ca363d96c..8ce2d7d75 100644 --- a/Sources/MongoSwift/Operations/ListDatabasesOperation.swift +++ b/Sources/MongoSwift/Operations/ListDatabasesOperation.swift @@ -13,7 +13,7 @@ public struct DatabaseSpecification: Codable { /// For sharded clusters, this field includes a document which maps each shard to the size in bytes of the database /// on disk on that shard. For non sharded environments, this field is nil. - public let shards: Document? + public let shards: BSONDocument? } /// Internal intermediate result of a ListDatabases command. @@ -39,13 +39,13 @@ public struct ListDatabasesOptions { /// An operation corresponding to a "listDatabases" command on a collection. internal struct ListDatabasesOperation: Operation { private let client: MongoClient - private let filter: Document? + private let filter: BSONDocument? private let nameOnly: Bool? private let options: ListDatabasesOptions? internal init( client: MongoClient, - filter: Document?, + filter: BSONDocument?, nameOnly: Bool?, options: ListDatabasesOptions? ) { @@ -58,7 +58,7 @@ internal struct ListDatabasesOperation: Operation { internal func execute(using connection: Connection, session: ClientSession?) throws -> ListDatabasesResults { // spec requires that this command be run against the primary. let readPref = ReadPreference.primary - var cmd: Document = ["listDatabases": 1] + var cmd: BSONDocument = ["listDatabases": 1] if let filter = self.filter { cmd["filter"] = .document(filter) } @@ -69,7 +69,7 @@ internal struct ListDatabasesOperation: Operation { cmd["authorizedDatabases"] = .bool(authorizedDatabases) } - let opts = try encodeOptions(options: nil as Document?, session: session) + let opts = try encodeOptions(options: nil as BSONDocument?, session: session) let reply = try connection.withMongocConnection { connPtr in try readPref.withMongocReadPreference { rpPtr in @@ -79,7 +79,7 @@ internal struct ListDatabasesOperation: Operation { } } - guard let databases = reply["databases"]?.arrayValue?.toArrayOf(Document.self) else { + guard let databases = reply["databases"]?.arrayValue?.toArrayOf(BSONDocument.self) else { throw InternalError(message: "Invalid server response: \(reply)") } diff --git a/Sources/MongoSwift/Operations/ListIndexesOperation.swift b/Sources/MongoSwift/Operations/ListIndexesOperation.swift index 9b89ea6a3..a6200e62d 100644 --- a/Sources/MongoSwift/Operations/ListIndexesOperation.swift +++ b/Sources/MongoSwift/Operations/ListIndexesOperation.swift @@ -23,7 +23,7 @@ internal struct ListIndexesOperation: Operation { using connection: Connection, session: ClientSession? ) throws -> ListIndexesResults { - let opts = try encodeOptions(options: nil as Document?, session: session) + let opts = try encodeOptions(options: nil as BSONDocument?, session: session) let indexes: OpaquePointer = self.collection.withMongocCollection(from: connection) { collPtr in withOptionalBSONPointer(to: opts) { optsPtr in diff --git a/Sources/MongoSwift/Operations/MongocCommandHelpers.swift b/Sources/MongoSwift/Operations/MongocCommandHelpers.swift index 9a640bab8..737d83293 100644 --- a/Sources/MongoSwift/Operations/MongocCommandHelpers.swift +++ b/Sources/MongoSwift/Operations/MongocCommandHelpers.swift @@ -23,18 +23,18 @@ internal typealias MongocCommandFunc = /// reply document from the server. If you do not need to use the reply document, `runMongocCommand` is preferable as /// it does not perform a copy of the reply. internal func runMongocCommandWithReply( - command: Document, - options: Document?, + command: BSONDocument, + options: BSONDocument?, body: MongocCommandFunc -) throws -> Document { +) throws -> BSONDocument { try withStackAllocatedMutableBSONPointer { replyPtr in try _runMongocCommand(command: command, options: options, replyPtr: replyPtr, body: body) - return Document(copying: replyPtr) + return BSONDocument(copying: replyPtr) } } /// Calls the provided mongoc command method using pointers to the specified command and options. -internal func runMongocCommand(command: Document, options: Document?, body: MongocCommandFunc) throws { +internal func runMongocCommand(command: BSONDocument, options: BSONDocument?, body: MongocCommandFunc) throws { try withStackAllocatedMutableBSONPointer { replyPtr in try _runMongocCommand(command: command, options: options, replyPtr: replyPtr, body: body) } @@ -42,8 +42,8 @@ internal func runMongocCommand(command: Document, options: Document?, body: Mong /// Private helper to run the provided `MongocCommandFunc` using the specified location for a reply. private func _runMongocCommand( - command: Document, - options: Document?, + command: BSONDocument, + options: BSONDocument?, replyPtr: MutableBSONPointer, body: MongocCommandFunc ) throws { @@ -52,7 +52,7 @@ private func _runMongocCommand( try withOptionalBSONPointer(to: options) { optsPtr in let success = body(cmdPtr, optsPtr, replyPtr, &error) guard success else { - throw extractMongoError(error: error, reply: Document(copying: replyPtr)) + throw extractMongoError(error: error, reply: BSONDocument(copying: replyPtr)) } } } diff --git a/Sources/MongoSwift/Operations/Operation.swift b/Sources/MongoSwift/Operations/Operation.swift index 325f431d5..7b9fec0cc 100644 --- a/Sources/MongoSwift/Operations/Operation.swift +++ b/Sources/MongoSwift/Operations/Operation.swift @@ -111,13 +111,13 @@ internal class OperationExecutor { } } -/// Internal function for generating an options `Document` for passing to libmongoc. -internal func encodeOptions(options: T?, session: ClientSession?) throws -> Document? { +/// Internal function for generating an options `BSONDocument` for passing to libmongoc. +internal func encodeOptions(options: T?, session: ClientSession?) throws -> BSONDocument? { guard options != nil || session != nil else { return nil } - var doc = try BSONEncoder().encode(options) ?? Document() + var doc = try BSONEncoder().encode(options) ?? BSONDocument() try session?.append(to: &doc) return doc } diff --git a/Sources/MongoSwift/Operations/RunCommandOperation.swift b/Sources/MongoSwift/Operations/RunCommandOperation.swift index 79e42a3c9..69222abbe 100644 --- a/Sources/MongoSwift/Operations/RunCommandOperation.swift +++ b/Sources/MongoSwift/Operations/RunCommandOperation.swift @@ -33,16 +33,16 @@ public struct RunCommandOptions: Encodable { /// An operation corresponding to a `runCommand` call. internal struct RunCommandOperation: Operation { private let database: MongoDatabase - private let command: Document + private let command: BSONDocument private let options: RunCommandOptions? - internal init(database: MongoDatabase, command: Document, options: RunCommandOptions?) { + internal init(database: MongoDatabase, command: BSONDocument, options: RunCommandOptions?) { self.database = database self.command = command self.options = options } - internal func execute(using connection: Connection, session: ClientSession?) throws -> Document { + internal func execute(using connection: Connection, session: ClientSession?) throws -> BSONDocument { let opts = try encodeOptions(options: self.options, session: session) return try self.database.withMongocDatabase(from: connection) { dbPtr in try ReadPreference.withOptionalMongocReadPreference(from: self.options?.readPreference) { rpPtr in diff --git a/Sources/MongoSwift/Operations/WatchOperation.swift b/Sources/MongoSwift/Operations/WatchOperation.swift index 62dae9a37..5b23e871a 100644 --- a/Sources/MongoSwift/Operations/WatchOperation.swift +++ b/Sources/MongoSwift/Operations/WatchOperation.swift @@ -20,7 +20,7 @@ internal struct WatchOperation, - pipeline: [Document], + pipeline: [BSONDocument], options: ChangeStreamOptions? ) { self.target = target @@ -32,7 +32,7 @@ internal struct WatchOperation ChangeStream { - let pipeline: Document = ["pipeline": self.pipeline] + let pipeline: BSONDocument = ["pipeline": self.pipeline] let opts = try encodeOptions(options: self.options, session: session) return try pipeline.withBSONPointer { pipelinePtr in diff --git a/Sources/MongoSwift/ReadPreference.swift b/Sources/MongoSwift/ReadPreference.swift index 05431c642..539178c93 100644 --- a/Sources/MongoSwift/ReadPreference.swift +++ b/Sources/MongoSwift/ReadPreference.swift @@ -61,7 +61,7 @@ public struct ReadPreference: Equatable { /// Optionally specified ordered array of tag sets. If provided, a server will only be considered suitable if its /// tags are a superset of at least one of the tag sets. /// - SeeAlso: https://docs.mongodb.com/manual/core/read-preference-tags/#replica-set-read-preference-tag-sets - public var tagSets: [Document]? + public var tagSets: [BSONDocument]? // swiftlint:disable line_length /// An optionally specified value indicating a maximum replication lag, or "staleness", for reads from secondaries. @@ -104,7 +104,7 @@ public struct ReadPreference: Equatable { * - https://docs.mongodb.com/manual/core/read-preference-staleness/#replica-set-read-preference-max-staleness */ public static func primaryPreferred( - tagSets: [Document]? = nil, + tagSets: [BSONDocument]? = nil, maxStalenessSeconds: Int? = nil ) throws -> ReadPreference { try ReadPreference(.primaryPreferred, tagSets: tagSets, maxStalenessSeconds: maxStalenessSeconds) @@ -129,7 +129,7 @@ public struct ReadPreference: Equatable { * - https://docs.mongodb.com/manual/core/read-preference-staleness/#replica-set-read-preference-max-staleness */ public static func secondary( - tagSets: [Document]? = nil, + tagSets: [BSONDocument]? = nil, maxStalenessSeconds: Int? = nil ) throws -> ReadPreference { try ReadPreference(.secondary, tagSets: tagSets, maxStalenessSeconds: maxStalenessSeconds) @@ -155,7 +155,7 @@ public struct ReadPreference: Equatable { * - https://docs.mongodb.com/manual/core/read-preference-staleness/#replica-set-read-preference-max-staleness */ public static func secondaryPreferred( - tagSets: [Document]? = nil, + tagSets: [BSONDocument]? = nil, maxStalenessSeconds: Int? = nil ) throws -> ReadPreference { try ReadPreference(.secondaryPreferred, tagSets: tagSets, maxStalenessSeconds: maxStalenessSeconds) @@ -180,7 +180,7 @@ public struct ReadPreference: Equatable { * - https://docs.mongodb.com/manual/core/read-preference-staleness/#replica-set-read-preference-max-staleness */ public static func nearest( - tagSets: [Document]? = nil, + tagSets: [BSONDocument]? = nil, maxStalenessSeconds: Int? = nil ) throws -> ReadPreference { try ReadPreference(.nearest, tagSets: tagSets, maxStalenessSeconds: maxStalenessSeconds) @@ -193,7 +193,7 @@ public struct ReadPreference: Equatable { self.maxStalenessSeconds = nil } - private init(_ mode: Mode, tagSets: [Document]?, maxStalenessSeconds: Int?) throws { + private init(_ mode: Mode, tagSets: [BSONDocument]?, maxStalenessSeconds: Int?) throws { if let maxStaleness = maxStalenessSeconds { guard maxStaleness >= MONGOC_SMALLEST_MAX_STALENESS_SECONDS else { throw InvalidArgumentError( @@ -215,7 +215,7 @@ public struct ReadPreference: Equatable { fatalError("Failed to retrieve read preference tags") } // we have to copy because libmongoc owns the pointer. - let wrappedTags = Document(copying: tagsPointer) + let wrappedTags = BSONDocument(copying: tagsPointer) if !wrappedTags.isEmpty { // swiftlint:disable:next force_unwrapping self.tagSets = wrappedTags.values.map { $0.documentValue! } // libmongoc will always return array of docs @@ -236,7 +236,7 @@ public struct ReadPreference: Equatable { defer { mongoc_read_prefs_destroy(rp) } if let tagSets = self.tagSets, !tagSets.isEmpty { - let tags = Document(tagSets.map { .document($0) }) + let tags = BSONDocument(tagSets.map { .document($0) }) tags.withBSONPointer { tagsPtr in mongoc_read_prefs_set_tags(rp, tagsPtr) } diff --git a/Sources/MongoSwift/SDAM.swift b/Sources/MongoSwift/SDAM.swift index f075d999b..74515f701 100644 --- a/Sources/MongoSwift/SDAM.swift +++ b/Sources/MongoSwift/SDAM.swift @@ -152,7 +152,7 @@ public struct ServerDescription { // initialize the rest of the values from the isMaster response. // we have to copy because libmongoc owns the pointer. - let isMasterDoc = Document(copying: mongoc_server_description_ismaster(description)) + let isMasterDoc = BSONDocument(copying: mongoc_server_description_ismaster(description)) // TODO: SWIFT-349 log errors encountered here let isMaster = try? BSONDecoder().decode(IsMasterResponse.self, from: isMasterDoc) diff --git a/Sources/MongoSwiftSync/ClientSession.swift b/Sources/MongoSwiftSync/ClientSession.swift index 4064c4cf9..bb682bcad 100644 --- a/Sources/MongoSwiftSync/ClientSession.swift +++ b/Sources/MongoSwiftSync/ClientSession.swift @@ -37,7 +37,7 @@ public final class ClientSession { /// The most recent cluster time seen by this session. This value will be nil if either of the following are true: /// - No operations have been executed using this session and `advanceClusterTime` has not been called. /// - This session has been ended. - public var clusterTime: Document? { self.asyncSession.clusterTime } + public var clusterTime: BSONDocument? { self.asyncSession.clusterTime } /// The operation time of the most recent operation performed using this session. This value will be nil if either /// of the following are true: @@ -81,7 +81,7 @@ public final class ClientSession { * - Parameters: * - clusterTime: The session's new cluster time, as a `Document` like `["cluster time": Timestamp(...)]` */ - public func advanceClusterTime(to clusterTime: Document) { + public func advanceClusterTime(to clusterTime: BSONDocument) { self.asyncSession.advanceClusterTime(to: clusterTime) } diff --git a/Sources/MongoSwiftSync/Exports.swift b/Sources/MongoSwiftSync/Exports.swift index 43e169666..3a92a88d2 100644 --- a/Sources/MongoSwiftSync/Exports.swift +++ b/Sources/MongoSwiftSync/Exports.swift @@ -15,7 +15,11 @@ @_exported import struct MongoSwift.BSONCode @_exported import struct MongoSwift.BSONCodeWithScope @_exported import struct MongoSwift.BSONCoderOptions +@_exported import struct MongoSwift.BSONDBPointer +@_exported import struct MongoSwift.BSONDecimal128 @_exported import class MongoSwift.BSONDecoder +@_exported import struct MongoSwift.BSONDocument +@_exported import class MongoSwift.BSONDocumentIterator @_exported import class MongoSwift.BSONEncoder @_exported import struct MongoSwift.BSONObjectID @_exported import struct MongoSwift.BSONRegularExpression @@ -43,17 +47,13 @@ @_exported import struct MongoSwift.CountDocumentsOptions @_exported import struct MongoSwift.CreateCollectionOptions @_exported import struct MongoSwift.CreateIndexOptions -@_exported import struct MongoSwift.DBPointer @_exported import enum MongoSwift.DataCodingStrategy @_exported import struct MongoSwift.DatabaseSpecification @_exported import enum MongoSwift.DateCodingStrategy -@_exported import struct MongoSwift.Decimal128 @_exported import struct MongoSwift.DeleteModelOptions @_exported import struct MongoSwift.DeleteOptions @_exported import struct MongoSwift.DeleteResult @_exported import struct MongoSwift.DistinctOptions -@_exported import struct MongoSwift.Document -@_exported import class MongoSwift.DocumentIterator @_exported import struct MongoSwift.DropCollectionOptions @_exported import struct MongoSwift.DropDatabaseOptions @_exported import struct MongoSwift.DropIndexOptions diff --git a/Sources/MongoSwiftSync/MongoClient.swift b/Sources/MongoSwiftSync/MongoClient.swift index c49a0305a..080b18954 100644 --- a/Sources/MongoSwiftSync/MongoClient.swift +++ b/Sources/MongoSwiftSync/MongoClient.swift @@ -105,7 +105,7 @@ public class MongoClient { * - SeeAlso: https://docs.mongodb.com/manual/reference/command/listDatabases/ */ public func listDatabases( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) throws -> [DatabaseSpecification] { @@ -127,7 +127,7 @@ public class MongoClient { * - `CommandError` if options.authorizedDatabases is false and the user does not have listDatabases permissions. */ public func listMongoDatabases( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) throws -> [MongoDatabase] { @@ -149,7 +149,7 @@ public class MongoClient { * - `CommandError` if options.authorizedDatabases is false and the user does not have listDatabases permissions. */ public func listDatabaseNames( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListDatabasesOptions? = nil, session: ClientSession? = nil ) throws -> [String] { @@ -197,15 +197,15 @@ public class MongoClient { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil - ) throws -> ChangeStream> { + ) throws -> ChangeStream> { try self.watch( pipeline, options: options, session: session, - withEventType: ChangeStreamEvent.self + withEventType: ChangeStreamEvent.self ) } @@ -238,7 +238,7 @@ public class MongoClient { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withFullDocumentType _: FullDocType.Type @@ -279,7 +279,7 @@ public class MongoClient { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withEventType _: EventType.Type diff --git a/Sources/MongoSwiftSync/MongoCollection+ChangeStreams.swift b/Sources/MongoSwiftSync/MongoCollection+ChangeStreams.swift index 09dcfb3a2..3fd603f06 100644 --- a/Sources/MongoSwiftSync/MongoCollection+ChangeStreams.swift +++ b/Sources/MongoSwiftSync/MongoCollection+ChangeStreams.swift @@ -25,7 +25,7 @@ extension MongoCollection { * - https://docs.mongodb.com/manual/reference/system-collections/ */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil ) throws -> ChangeStream> { @@ -63,7 +63,7 @@ extension MongoCollection { * - https://docs.mongodb.com/manual/reference/system-collections/ */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withFullDocumentType _: FullDocType.Type @@ -101,7 +101,7 @@ extension MongoCollection { * - https://docs.mongodb.com/manual/reference/system-collections/ */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withEventType _: EventType.Type diff --git a/Sources/MongoSwiftSync/MongoCollection+FindAndModify.swift b/Sources/MongoSwiftSync/MongoCollection+FindAndModify.swift index 66fb3065c..5d606a1ca 100644 --- a/Sources/MongoSwiftSync/MongoCollection+FindAndModify.swift +++ b/Sources/MongoSwiftSync/MongoCollection+FindAndModify.swift @@ -21,7 +21,7 @@ extension MongoCollection { */ @discardableResult public func findOneAndDelete( - _ filter: Document, + _ filter: BSONDocument, options: FindOneAndDeleteOptions? = nil, session: ClientSession? = nil ) throws -> CollectionType? { @@ -50,7 +50,7 @@ extension MongoCollection { */ @discardableResult public func findOneAndReplace( - filter: Document, + filter: BSONDocument, replacement: CollectionType, options: FindOneAndReplaceOptions? = nil, session: ClientSession? = nil @@ -85,8 +85,8 @@ extension MongoCollection { */ @discardableResult public func findOneAndUpdate( - filter: Document, - update: Document, + filter: BSONDocument, + update: BSONDocument, options: FindOneAndUpdateOptions? = nil, session: ClientSession? = nil ) throws -> CollectionType? { diff --git a/Sources/MongoSwiftSync/MongoCollection+Indexes.swift b/Sources/MongoSwiftSync/MongoCollection+Indexes.swift index bccbf409c..bed667c71 100644 --- a/Sources/MongoSwiftSync/MongoCollection+Indexes.swift +++ b/Sources/MongoSwiftSync/MongoCollection+Indexes.swift @@ -22,7 +22,7 @@ extension MongoCollection { */ @discardableResult public func createIndex( - _ keys: Document, + _ keys: BSONDocument, indexOptions: IndexOptions? = nil, options: CreateIndexOptions? = nil, session: ClientSession? = nil @@ -126,7 +126,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options. */ public func dropIndex( - _ keys: Document, + _ keys: BSONDocument, options: DropIndexOptions? = nil, session: ClientSession? = nil ) throws { diff --git a/Sources/MongoSwiftSync/MongoCollection+Read.swift b/Sources/MongoSwiftSync/MongoCollection+Read.swift index 854595162..c29774c62 100644 --- a/Sources/MongoSwiftSync/MongoCollection+Read.swift +++ b/Sources/MongoSwiftSync/MongoCollection+Read.swift @@ -17,7 +17,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func find( - _ filter: Document = [:], + _ filter: BSONDocument = [:], options: FindOptions? = nil, session: ClientSession? = nil ) throws -> MongoCursor { @@ -41,7 +41,7 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func findOne( - _ filter: Document = [:], + _ filter: BSONDocument = [:], options: FindOneOptions? = nil, session: ClientSession? = nil ) throws -> T? { @@ -64,10 +64,10 @@ extension MongoCollection { * - `EncodingError` if an error occurs while encoding the options to BSON. */ public func aggregate( - _ pipeline: [Document], + _ pipeline: [BSONDocument], options: AggregateOptions? = nil, session: ClientSession? = nil - ) throws -> MongoCursor { + ) throws -> MongoCursor { let asyncCursor = try self.asyncColl.aggregate(pipeline, options: options, session: session?.asyncSession) .wait() return MongoCursor(wrapping: asyncCursor, client: self.client) @@ -86,7 +86,7 @@ extension MongoCollection { * - Returns: The count of the documents that matched the filter */ public func countDocuments( - _ filter: Document = [:], + _ filter: BSONDocument = [:], options: CountDocumentsOptions? = nil, session: ClientSession? = nil ) throws -> Int { @@ -125,7 +125,7 @@ extension MongoCollection { */ public func distinct( fieldName: String, - filter: Document = [:], + filter: BSONDocument = [:], options: DistinctOptions? = nil, session: ClientSession? = nil ) throws -> [BSON] { diff --git a/Sources/MongoSwiftSync/MongoCollection+Write.swift b/Sources/MongoSwiftSync/MongoCollection+Write.swift index 545f23612..093f15f93 100644 --- a/Sources/MongoSwiftSync/MongoCollection+Write.swift +++ b/Sources/MongoSwiftSync/MongoCollection+Write.swift @@ -78,7 +78,7 @@ extension MongoCollection { */ @discardableResult public func replaceOne( - filter: Document, + filter: BSONDocument, replacement: CollectionType, options: ReplaceOptions? = nil, session: ClientSession? = nil @@ -113,8 +113,8 @@ extension MongoCollection { */ @discardableResult public func updateOne( - filter: Document, - update: Document, + filter: BSONDocument, + update: BSONDocument, options: UpdateOptions? = nil, session: ClientSession? = nil ) throws -> UpdateResult? { @@ -148,8 +148,8 @@ extension MongoCollection { */ @discardableResult public func updateMany( - filter: Document, - update: Document, + filter: BSONDocument, + update: BSONDocument, options: UpdateOptions? = nil, session: ClientSession? = nil ) throws -> UpdateResult? { @@ -182,7 +182,7 @@ extension MongoCollection { */ @discardableResult public func deleteOne( - _ filter: Document, + _ filter: BSONDocument, options: DeleteOptions? = nil, session: ClientSession? = nil ) throws -> DeleteResult? { @@ -209,7 +209,7 @@ extension MongoCollection { */ @discardableResult public func deleteMany( - _ filter: Document, + _ filter: BSONDocument, options: DeleteOptions? = nil, session: ClientSession? = nil ) throws -> DeleteResult? { diff --git a/Sources/MongoSwiftSync/MongoDatabase.swift b/Sources/MongoSwiftSync/MongoDatabase.swift index 693a412ce..47d6afd1a 100644 --- a/Sources/MongoSwiftSync/MongoDatabase.swift +++ b/Sources/MongoSwiftSync/MongoDatabase.swift @@ -59,8 +59,8 @@ public struct MongoDatabase { * * - Returns: the requested `MongoCollection` */ - public func collection(_ name: String, options: MongoCollectionOptions? = nil) -> MongoCollection { - self.collection(name, withType: Document.self, options: options) + public func collection(_ name: String, options: MongoCollectionOptions? = nil) -> MongoCollection { + self.collection(name, withType: BSONDocument.self, options: options) } /** @@ -106,8 +106,8 @@ public struct MongoDatabase { _ name: String, options: CreateCollectionOptions? = nil, session: ClientSession? = nil - ) throws -> MongoCollection { - try self.createCollection(name, withType: Document.self, options: options, session: session) + ) throws -> MongoCollection { + try self.createCollection(name, withType: BSONDocument.self, options: options, session: session) } /** @@ -160,7 +160,7 @@ public struct MongoDatabase { * - `LogicError` if the provided session is inactive. */ public func listCollections( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListCollectionsOptions? = nil, session: ClientSession? = nil ) throws -> MongoCursor { @@ -184,10 +184,10 @@ public struct MongoDatabase { * - `LogicError` if the provided session is inactive. */ public func listMongoCollections( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListCollectionsOptions? = nil, session: ClientSession? = nil - ) throws -> [MongoCollection] { + ) throws -> [MongoCollection] { try self.listCollectionNames(filter, options: options, session: session).map { name in self.collection(name) } @@ -208,7 +208,7 @@ public struct MongoDatabase { * - `LogicError` if the provided session is inactive. */ public func listCollectionNames( - _ filter: Document? = nil, + _ filter: BSONDocument? = nil, options: ListCollectionsOptions? = nil, session: ClientSession? = nil ) throws -> [String] { @@ -234,10 +234,10 @@ public struct MongoDatabase { */ @discardableResult public func runCommand( - _ command: Document, + _ command: BSONDocument, options: RunCommandOptions? = nil, session: ClientSession? = nil - ) throws -> Document { + ) throws -> BSONDocument { try self.asyncDB.runCommand(command, options: options, session: session?.asyncSession).wait() } @@ -265,15 +265,15 @@ public struct MongoDatabase { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil - ) throws -> ChangeStream> { + ) throws -> ChangeStream> { try self.watch( pipeline, options: options, session: session, - withEventType: ChangeStreamEvent.self + withEventType: ChangeStreamEvent.self ) } @@ -305,7 +305,7 @@ public struct MongoDatabase { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withFullDocumentType _: FullDocType.Type @@ -345,7 +345,7 @@ public struct MongoDatabase { * - Note: Supported in MongoDB version 4.0+ only. */ public func watch( - _ pipeline: [Document] = [], + _ pipeline: [BSONDocument] = [], options: ChangeStreamOptions? = nil, session: ClientSession? = nil, withEventType _: EventType.Type diff --git a/Sources/TestsCommon/CommonTestUtils.swift b/Sources/TestsCommon/CommonTestUtils.swift index 741fa6ffc..cda2d3da7 100644 --- a/Sources/TestsCommon/CommonTestUtils.swift +++ b/Sources/TestsCommon/CommonTestUtils.swift @@ -122,8 +122,8 @@ open class MongoSwiftTestCase: XCTestCase { } } -extension Document { - public func sortedEquals(_ other: Document) -> Bool { +extension BSONDocument { + public func sortedEquals(_ other: BSONDocument) -> Bool { let keys = self.keys.sorted() let otherKeys = other.keys.sorted() @@ -166,7 +166,7 @@ private func clean(json: String?) -> String { return "" } do { - let doc = try Document(fromJSON: str.data(using: .utf8)!) + let doc = try BSONDocument(fromJSON: str.data(using: .utf8)!) return doc.extendedJSON } catch { print("Failed to clean string: \(str)") @@ -195,7 +195,7 @@ public func cleanEqual(_ expectedValue: String?) -> Predicate { // Adds a custom "sortedEqual" predicate that compares two `Document`s and returns true if they // have the same key/value pairs in them -public func sortedEqual(_ expectedValue: Document?) -> Predicate { +public func sortedEqual(_ expectedValue: BSONDocument?) -> Predicate { Predicate.define("sortedEqual <\(stringify(expectedValue))>") { actualExpression, msg in let actualValue = try actualExpression.evaluate() diff --git a/Sources/TestsCommon/SpecTestUtils.swift b/Sources/TestsCommon/SpecTestUtils.swift index 0fa047253..12eebf356 100644 --- a/Sources/TestsCommon/SpecTestUtils.swift +++ b/Sources/TestsCommon/SpecTestUtils.swift @@ -19,7 +19,7 @@ extension MongoSwiftTestCase { } } -extension Document { +extension BSONDocument { public init(fromJSONFile file: URL) throws { let jsonString = try String(contentsOf: file, encoding: .utf8) try self.init(fromJSON: jsonString) @@ -42,7 +42,7 @@ public func retrieveSpecTestFiles( .filter { $0.hasSuffix(".json") } .map { filename in let url = URL(fileURLWithPath: "\(path)/\(filename)") - var doc = try Document(fromJSONFile: url) + var doc = try BSONDocument(fromJSONFile: url) doc["name"] = .string(filename) return try (filename, BSONDecoder().decode(T.self, from: doc)) } @@ -51,8 +51,8 @@ public func retrieveSpecTestFiles( /// Given two documents, returns a copy of the input document with all keys that *don't* /// exist in `standard` removed, and with all matching keys put in the same order they /// appear in `standard`. -public func rearrangeDoc(_ input: Document, toLookLike standard: Document) -> Document { - var output = Document() +public func rearrangeDoc(_ input: BSONDocument, toLookLike standard: BSONDocument) -> BSONDocument { + var output = BSONDocument() for (k, v) in standard { switch (v, input[k]) { case let (.document(sDoc), .document(iDoc)?): diff --git a/Tests/BSONTests/BSONCorpusTests.swift b/Tests/BSONTests/BSONCorpusTests.swift index 064ab4750..0c63a8d74 100644 --- a/Tests/BSONTests/BSONCorpusTests.swift +++ b/Tests/BSONTests/BSONCorpusTests.swift @@ -137,7 +137,7 @@ final class BSONCorpusTests: MongoSwiftTestCase { // for cB input: // native_to_bson( bson_to_native(cB) ) = cB - let docFromCB = try Document(fromBSON: cBData) + let docFromCB = try BSONDocument(fromBSON: cBData) expect(docFromCB.rawBSON).to(equal(cBData)) // test round tripping through documents @@ -147,7 +147,7 @@ final class BSONCorpusTests: MongoSwiftTestCase { // -> bson_t. At the end, the new bson_t should be identical to the original one. If not, our bson_t // translation layer is lossy and/or buggy. let nativeFromDoc = docFromCB.toArray() - let docFromNative = Document(fromArray: nativeFromDoc) + let docFromNative = BSONDocument(fromArray: nativeFromDoc) expect(docFromNative.rawBSON).to(equal(cBData)) // native_to_canonical_extended_json( bson_to_native(cB) ) = cEJ @@ -155,16 +155,17 @@ final class BSONCorpusTests: MongoSwiftTestCase { // native_to_relaxed_extended_json( bson_to_native(cB) ) = rEJ (if rEJ exists) if let rEJ = test.relaxedExtJSON { - expect(try Document(fromBSON: cBData).extendedJSON).to(cleanEqual(rEJ)) + expect(try BSONDocument(fromBSON: cBData).extendedJSON).to(cleanEqual(rEJ)) } // for cEJ input: // native_to_canonical_extended_json( json_to_native(cEJ) ) = cEJ - expect(try Document(fromJSON: cEJData).canonicalExtendedJSON).to(cleanEqual(test.canonicalExtJSON)) + expect(try BSONDocument(fromJSON: cEJData).canonicalExtendedJSON) + .to(cleanEqual(test.canonicalExtJSON)) // native_to_bson( json_to_native(cEJ) ) = cB (unless lossy) if !lossy { - expect(try Document(fromJSON: cEJData).rawBSON).to(equal(cBData)) + expect(try BSONDocument(fromJSON: cEJData).rawBSON).to(equal(cBData)) } // for dB input (if it exists): @@ -175,30 +176,31 @@ final class BSONCorpusTests: MongoSwiftTestCase { } // bson_to_canonical_extended_json(dB) = cEJ - expect(try Document(fromBSON: dBData).canonicalExtendedJSON) + expect(try BSONDocument(fromBSON: dBData).canonicalExtendedJSON) .to(cleanEqual(test.canonicalExtJSON)) // bson_to_relaxed_extended_json(dB) = rEJ (if rEJ exists) if let rEJ = test.relaxedExtJSON { - expect(try Document(fromBSON: dBData).extendedJSON).to(cleanEqual(rEJ)) + expect(try BSONDocument(fromBSON: dBData).extendedJSON).to(cleanEqual(rEJ)) } } // for dEJ input (if it exists): if let dEJ = test.degenerateExtJSON { // native_to_canonical_extended_json( json_to_native(dEJ) ) = cEJ - expect(try Document(fromJSON: dEJ).canonicalExtendedJSON).to(cleanEqual(test.canonicalExtJSON)) + expect(try BSONDocument(fromJSON: dEJ).canonicalExtendedJSON) + .to(cleanEqual(test.canonicalExtJSON)) // native_to_bson( json_to_native(dEJ) ) = cB (unless lossy) if !lossy { - expect(try Document(fromJSON: dEJ).rawBSON).to(equal(cBData)) + expect(try BSONDocument(fromJSON: dEJ).rawBSON).to(equal(cBData)) } } // for rEJ input (if it exists): if let rEJ = test.relaxedExtJSON { // native_to_relaxed_extended_json( json_to_native(rEJ) ) = rEJ - expect(try Document(fromJSON: rEJ).extendedJSON).to(cleanEqual(rEJ)) + expect(try BSONDocument(fromJSON: rEJ).extendedJSON).to(cleanEqual(rEJ)) } } } @@ -212,10 +214,10 @@ final class BSONCorpusTests: MongoSwiftTestCase { switch BSONType(rawValue: UInt32(testFile.bsonType.dropFirst(2), radix: 16)!)! { case .invalid: // "top level document" uses 0x00 for the bson type - expect(try Document(fromJSON: test.string)) + expect(try BSONDocument(fromJSON: test.string)) .to(throwError(), description: description) case .decimal128: - expect(Decimal128(test.string)) + expect(BSONDecimal128(test.string)) .to(beNil(), description: description) default: throw TestError( @@ -242,7 +244,7 @@ final class BSONCorpusTests: MongoSwiftTestCase { XCTFail("\(description): Unable to interpret bson as Data") return } - expect(try Document(fromBSON: data)).to(throwError(), description: description) + expect(try BSONDocument(fromBSON: data)).to(throwError(), description: description) } } } diff --git a/Tests/BSONTests/BSONValueTests.swift b/Tests/BSONTests/BSONValueTests.swift index e262f655b..d9ac00742 100644 --- a/Tests/BSONTests/BSONValueTests.swift +++ b/Tests/BSONTests/BSONValueTests.swift @@ -7,9 +7,9 @@ import XCTest final class BSONValueTests: MongoSwiftTestCase { func testInvalidDecimal128() throws { - expect(Decimal128("hi")).to(beNil()) - expect(Decimal128("123.4.5")).to(beNil()) - expect(Decimal128("10")).toNot(beNil()) + expect(BSONDecimal128("hi")).to(beNil()) + expect(BSONDecimal128("123.4.5")).to(beNil()) + expect(BSONDecimal128("10")).toNot(beNil()) } func testUUIDBytes() throws { @@ -39,7 +39,10 @@ final class BSONValueTests: MongoSwiftTestCase { // Double self.checkTrueAndFalse(val: 1.618, alternate: 2.718) // Decimal128 - self.checkTrueAndFalse(val: .decimal128(Decimal128("1.618")!), alternate: .decimal128(Decimal128("2.718")!)) + self.checkTrueAndFalse( + val: .decimal128(BSONDecimal128("1.618")!), + alternate: .decimal128(BSONDecimal128("2.718")!) + ) // Bool self.checkTrueAndFalse(val: true, alternate: false) // String @@ -169,7 +172,7 @@ final class BSONValueTests: MongoSwiftTestCase { let double: Double? let int32: Int32? let int64: Int64? - let decimal: Decimal128? + let decimal: BSONDecimal128? static func compare(computed: T?, expected: T?) { guard computed != nil else { @@ -209,18 +212,24 @@ final class BSONValueTests: MongoSwiftTestCase { } func testBSONNumber() throws { - let decimal128 = Decimal128("5.5")! + let decimal128 = BSONDecimal128("5.5")! let double: BSON = 5.5 expect(double.toDouble()).to(equal(5.5)) expect(double.toDecimal128()).to(equal(decimal128)) let cases = [ - BSONNumberTestCase(int: 5, double: 5.0, int32: Int32(5), int64: Int64(5), decimal: Decimal128("5")!), - BSONNumberTestCase(int: -5, double: -5.0, int32: Int32(-5), int64: Int64(-5), decimal: Decimal128("-5")!), - BSONNumberTestCase(int: 0, double: 0.0, int32: Int32(0), int64: Int64(0), decimal: Decimal128("0")!), - BSONNumberTestCase(int: nil, double: 1.234, int32: nil, int64: nil, decimal: Decimal128("1.234")!), - BSONNumberTestCase(int: nil, double: -31.234, int32: nil, int64: nil, decimal: Decimal128("-31.234")!) + BSONNumberTestCase(int: 5, double: 5.0, int32: Int32(5), int64: Int64(5), decimal: BSONDecimal128("5")!), + BSONNumberTestCase( + int: -5, + double: -5.0, + int32: Int32(-5), + int64: Int64(-5), + decimal: BSONDecimal128("-5")! + ), + BSONNumberTestCase(int: 0, double: 0.0, int32: Int32(0), int64: Int64(0), decimal: BSONDecimal128("0")!), + BSONNumberTestCase(int: nil, double: 1.234, int32: nil, int64: nil, decimal: BSONDecimal128("1.234")!), + BSONNumberTestCase(int: nil, double: -31.234, int32: nil, int64: nil, decimal: BSONDecimal128("-31.234")!) ] cases.forEach { $0.run() } diff --git a/Tests/BSONTests/CodecTests.swift b/Tests/BSONTests/CodecTests.swift index aaef92b53..fc8699227 100644 --- a/Tests/BSONTests/CodecTests.swift +++ b/Tests/BSONTests/CodecTests.swift @@ -48,7 +48,7 @@ final class CodecTests: MongoSwiftTestCase { let encoder = BSONEncoder() let decoder = BSONDecoder() - let expected: Document = [ + let expected: BSONDocument = [ "val1": "a", "val2": 0, "val3": [[1, 2], [3, 4]], @@ -60,28 +60,28 @@ final class CodecTests: MongoSwiftTestCase { // a basic struct let basic1 = BasicStruct(int: 1, string: "hello") - let basic1Doc: Document = ["int": 1, "string": "hello"] + let basic1Doc: BSONDocument = ["int": 1, "string": "hello"] expect(try encoder.encode(basic1)).to(equal(basic1Doc)) expect(try decoder.decode(BasicStruct.self, from: basic1Doc)).to(equal(basic1)) // a struct storing two nested structs as properties let basic2 = BasicStruct(int: 2, string: "hi") - let basic2Doc: Document = ["int": 2, "string": "hi"] + let basic2Doc: BSONDocument = ["int": 2, "string": "hi"] let nestedStruct = NestedStruct(s1: basic1, s2: basic2) - let nestedStructDoc: Document = ["s1": .document(basic1Doc), "s2": .document(basic2Doc)] + let nestedStructDoc: BSONDocument = ["s1": .document(basic1Doc), "s2": .document(basic2Doc)] expect(try encoder.encode(nestedStruct)).to(equal(nestedStructDoc)) expect(try decoder.decode(NestedStruct.self, from: nestedStructDoc)).to(equal(nestedStruct)) // a struct storing two nested structs in an array let nestedArray = NestedArray(array: [basic1, basic2]) - let nestedArrayDoc: Document = ["array": [.document(basic1Doc), .document(basic2Doc)]] + let nestedArrayDoc: BSONDocument = ["array": [.document(basic1Doc), .document(basic2Doc)]] expect(try encoder.encode(nestedArray)).to(equal(nestedArrayDoc)) expect(try decoder.decode(NestedArray.self, from: nestedArrayDoc)).to(equal(nestedArray)) // one more level of nesting let nestedNested = NestedNestedStruct(s: nestedStruct) - let nestedNestedDoc: Document = ["s": .document(nestedStructDoc)] + let nestedNestedDoc: BSONDocument = ["s": .document(nestedStructDoc)] expect(try encoder.encode(nestedNested)).to(equal(nestedNestedDoc)) expect(try decoder.decode(NestedNestedStruct.self, from: nestedNestedDoc)).to(equal(nestedNested)) } @@ -98,17 +98,17 @@ final class CodecTests: MongoSwiftTestCase { let decoder = BSONDecoder() let s1 = OptionalsStruct(int: 1, bool: true, string: "hi") - let s1Doc: Document = ["int": 1, "bool": true, "string": "hi"] + let s1Doc: BSONDocument = ["int": 1, "bool": true, "string": "hi"] expect(try encoder.encode(s1)).to(equal(s1Doc)) expect(try decoder.decode(OptionalsStruct.self, from: s1Doc)).to(equal(s1)) let s2 = OptionalsStruct(int: nil, bool: true, string: "hi") - let s2Doc1: Document = ["bool": true, "string": "hi"] + let s2Doc1: BSONDocument = ["bool": true, "string": "hi"] expect(try encoder.encode(s2)).to(equal(s2Doc1)) expect(try decoder.decode(OptionalsStruct.self, from: s2Doc1)).to(equal(s2)) // test with key in doc explicitly set to BSONNull - let s2Doc2: Document = ["int": .null, "bool": true, "string": "hi"] + let s2Doc2: BSONDocument = ["int": .null, "bool": true, "string": "hi"] expect(try decoder.decode(OptionalsStruct.self, from: s2Doc2)).to(equal(s2)) } @@ -154,7 +154,7 @@ final class CodecTests: MongoSwiftTestCase { let int32 = Int32(42) // all should be stored as Int32s, except the float should be stored as a double - let doc1: Document = [ + let doc1: BSONDocument = [ "int8": .int32(int32), "int16": .int32(int32), "uint8": .int32(int32), "uint16": .int32(int32), "uint32": .int32(int32), "uint64": .int32(int32), "uint": .int32(int32), "float": 42.0 ] @@ -195,7 +195,7 @@ final class CodecTests: MongoSwiftTestCase { let s = Numbers(int8: 42, int16: 42, uint8: 42, uint16: 42, uint32: 42, uint64: 42, uint: 42, float: 42) // store all values as Int32s and decode them to their requested types - var doc1 = Document() + var doc1 = BSONDocument() for k in Numbers.keys { doc1[k] = 42 } @@ -203,7 +203,7 @@ final class CodecTests: MongoSwiftTestCase { expect(res1).to(equal(s)) // store all values as Int64s and decode them to their requested types. - var doc2 = Document() + var doc2 = BSONDocument() for k in Numbers.keys { doc2[k] = .int64(42) } @@ -212,7 +212,7 @@ final class CodecTests: MongoSwiftTestCase { expect(res2).to(equal(s)) // store all values as Doubles and decode them to their requested types - var doc3 = Document() + var doc3 = BSONDocument() for k in Numbers.keys { doc3[k] = .double(42) } @@ -255,22 +255,22 @@ final class CodecTests: MongoSwiftTestCase { ])) // store all values as Int32s and decode them to their requested types - let doc1: Document = ["int": .int32(42), "int32": .int32(42), "int64": .int32(42), "double": .int32(42)] + let doc1: BSONDocument = ["int": .int32(42), "int32": .int32(42), "int64": .int32(42), "double": .int32(42)] expect(try decoder.decode(BSONNumbers.self, from: doc1)).to(equal(s)) // store all values as Int64s and decode them to their requested types - let doc2: Document = ["int": .int64(42), "int32": .int64(42), "int64": .int64(42), "double": .int64(42)] + let doc2: BSONDocument = ["int": .int64(42), "int32": .int64(42), "int64": .int64(42), "double": .int64(42)] expect(try decoder.decode(BSONNumbers.self, from: doc2)).to(equal(s)) // store all values as Doubles and decode them to their requested types - let doc3: Document = ["int": 42.0, "int32": 42.0, "int64": 42.0, "double": 42.0] + let doc3: BSONDocument = ["int": 42.0, "int32": 42.0, "int64": 42.0, "double": 42.0] expect(try decoder.decode(BSONNumbers.self, from: doc3)).to(equal(s)) } struct AllBSONTypes: Codable, Equatable { let double: Double let string: String - let doc: Document + let doc: BSONDocument let arr: [BSON] let binary: BSONBinary let oid: BSONObjectID @@ -281,13 +281,13 @@ final class CodecTests: MongoSwiftTestCase { let ts: BSONTimestamp let int32: Int32 let int64: Int64 - let dec: Decimal128 - let minkey: MinKey + let dec: BSONDecimal128 + let minkey: BSONMinKey let maxkey: MaxKey let regex: BSONRegularExpression let symbol: BSONSymbol let undefined: BSONUndefined - let dbpointer: DBPointer + let dbpointer: BSONDBPointer let null: BSONNull public static func factory() throws -> AllBSONTypes { @@ -305,19 +305,19 @@ final class CodecTests: MongoSwiftTestCase { ts: BSONTimestamp(timestamp: 1, inc: 2), int32: 5, int64: 6, - dec: Decimal128("1.2E+10")!, - minkey: MinKey(), + dec: BSONDecimal128("1.2E+10")!, + minkey: BSONMinKey(), maxkey: MaxKey(), regex: BSONRegularExpression(pattern: "^abc", options: "imx"), symbol: BSONSymbol("i am a symbol"), undefined: BSONUndefined(), - dbpointer: DBPointer(ref: "some.namespace", id: BSONObjectID("507f1f77bcf86cd799439011")!), + dbpointer: BSONDBPointer(ref: "some.namespace", id: BSONObjectID("507f1f77bcf86cd799439011")!), null: BSONNull() ) } // Manually construct a document from this instance for comparision with encoder output. - public func toDocument() -> Document { + public func toDocument() -> BSONDocument { [ "double": .double(self.double), "string": .string(self.string), @@ -410,9 +410,9 @@ final class CodecTests: MongoSwiftTestCase { expect(try decoder.decode(Double.self, from: "{\"$numberDouble\": \"42.42\"}")).to(equal(42.42)) expect(try decoder.decode( - Decimal128.self, + BSONDecimal128.self, from: "{\"$numberDecimal\": \"1.2E+10\"}" - )).to(equal(Decimal128("1.2E+10")!)) + )).to(equal(BSONDecimal128("1.2E+10")!)) let binary = try BSONBinary(base64: "//8=", subtype: .generic) expect( @@ -444,7 +444,7 @@ final class CodecTests: MongoSwiftTestCase { from: "{\"$code\": \"hi\", \"$scope\": {\"x\" : { \"$numberLong\": \"1\" }} }" ) ).to(equal(cws)) - expect(try decoder.decode(Document.self, from: "{\"x\": 1}")).to(equal(["x": .int32(1)])) + expect(try decoder.decode(BSONDocument.self, from: "{\"x\": 1}")).to(equal(["x": .int32(1)])) let ts = BSONTimestamp(timestamp: 1, inc: 2) expect(try decoder.decode(BSONTimestamp.self, from: "{ \"$timestamp\" : { \"t\" : 1, \"i\" : 2 } }")) @@ -458,7 +458,7 @@ final class CodecTests: MongoSwiftTestCase { ) ).to(equal(regex)) - expect(try decoder.decode(MinKey.self, from: "{\"$minKey\": 1}")).to(equal(MinKey())) + expect(try decoder.decode(BSONMinKey.self, from: "{\"$minKey\": 1}")).to(equal(BSONMinKey())) expect(try decoder.decode(MaxKey.self, from: "{\"$maxKey\": 1}")).to(equal(MaxKey())) expect(try decoder.decode(Bool.self, from: "false")).to(beFalse()) @@ -529,14 +529,14 @@ final class CodecTests: MongoSwiftTestCase { let decoder = BSONDecoder() // standalone document - let doc: Document = ["y": 1] + let doc: BSONDocument = ["y": 1] let bsonDoc = BSON.document(doc) expect(try encoder.encode(bsonDoc)).to(equal(doc)) expect(try decoder.decode(BSON.self, from: doc)).to(equal(bsonDoc)) expect(try decoder.decode(BSON.self, from: doc.canonicalExtendedJSON)).to(equal(bsonDoc)) // doc wrapped in a struct - let wrappedDoc: Document = ["x": bsonDoc] + let wrappedDoc: BSONDocument = ["x": bsonDoc] expect(try encoder.encode(AnyBSONStruct(bsonDoc))).to(equal(wrappedDoc)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedDoc).x).to(equal(bsonDoc)) expect(try decoder.decode( @@ -548,7 +548,7 @@ final class CodecTests: MongoSwiftTestCase { let double: BSON = 42.0 expect(try decoder.decode(BSON.self, from: "{\"$numberDouble\": \"42\"}")).to(equal(double)) - let wrappedDouble: Document = ["x": double] + let wrappedDouble: BSONDocument = ["x": double] expect(try encoder.encode(AnyBSONStruct(double))).to(equal(wrappedDouble)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedDouble).x).to(equal(double)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedDouble.canonicalExtendedJSON).x).to(equal(double)) @@ -557,7 +557,7 @@ final class CodecTests: MongoSwiftTestCase { let string: BSON = "hi" expect(try decoder.decode(BSON.self, from: "\"hi\"")).to(equal(string)) - let wrappedString: Document = ["x": string] + let wrappedString: BSONDocument = ["x": string] expect(try encoder.encode(AnyBSONStruct(string))).to(equal(wrappedString)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedString).x).to(equal(string)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedString.canonicalExtendedJSON).x).to(equal(string)) @@ -574,7 +574,7 @@ final class CodecTests: MongoSwiftTestCase { expect(decodedArray?[1]).to(equal(2)) expect(decodedArray?[2]).to(equal("hello")) - let wrappedArray: Document = ["x": array] + let wrappedArray: BSONDocument = ["x": array] expect(try encoder.encode(AnyBSONStruct(array))).to(equal(wrappedArray)) let decodedWrapped = try decoder.decode(AnyBSONStruct.self, from: wrappedArray).x.arrayValue expect(decodedWrapped?[0]).to(equal(1)) @@ -591,7 +591,7 @@ final class CodecTests: MongoSwiftTestCase { ) ).to(equal(binary)) - let wrappedBinary: Document = ["x": binary] + let wrappedBinary: BSONDocument = ["x": binary] expect(try encoder.encode(AnyBSONStruct(binary))).to(equal(wrappedBinary)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedBinary).x).to(equal(binary)) expect(try decoder.decode( @@ -605,7 +605,7 @@ final class CodecTests: MongoSwiftTestCase { expect(try decoder.decode(BSON.self, from: "{\"$oid\": \"\(oid.hex)\"}")).to(equal(bsonOid)) - let wrappedOid: Document = ["x": bsonOid] + let wrappedOid: BSONDocument = ["x": bsonOid] expect(try encoder.encode(AnyBSONStruct(bsonOid))).to(equal(wrappedOid)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedOid).x).to(equal(bsonOid)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedOid.canonicalExtendedJSON).x).to(equal(bsonOid)) @@ -615,7 +615,7 @@ final class CodecTests: MongoSwiftTestCase { expect(try decoder.decode(BSON.self, from: "true")).to(equal(bool)) - let wrappedBool: Document = ["x": bool] + let wrappedBool: BSONDocument = ["x": bool] expect(try encoder.encode(AnyBSONStruct(bool))).to(equal(wrappedBool)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedBool).x).to(equal(bool)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedBool.canonicalExtendedJSON).x).to(equal(bool)) @@ -625,7 +625,7 @@ final class CodecTests: MongoSwiftTestCase { expect(try decoder.decode(BSON.self, from: "{ \"$date\" : { \"$numberLong\" : \"5000000\" } }")).to(equal(date)) - let wrappedDate: Document = ["x": date] + let wrappedDate: BSONDocument = ["x": date] expect(try encoder.encode(AnyBSONStruct(date))).to(equal(wrappedDate)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedDate).x).to(equal(date)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedDate.canonicalExtendedJSON).x).to(equal(date)) @@ -647,7 +647,7 @@ final class CodecTests: MongoSwiftTestCase { ) ).to(equal(regex)) - let wrappedRegex: Document = ["x": regex] + let wrappedRegex: BSONDocument = ["x": regex] expect(try encoder.encode(AnyBSONStruct(regex))).to(equal(wrappedRegex)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedRegex).x).to(equal(regex)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedRegex.canonicalExtendedJSON).x).to(equal(regex)) @@ -663,7 +663,7 @@ final class CodecTests: MongoSwiftTestCase { ) ).to(equal(code)) - let wrappedCode: Document = ["x": code] + let wrappedCode: BSONDocument = ["x": code] expect(try encoder.encode(AnyBSONStruct(code))).to(equal(wrappedCode)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedCode).x).to(equal(code)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedCode.canonicalExtendedJSON).x).to(equal(code)) @@ -673,7 +673,7 @@ final class CodecTests: MongoSwiftTestCase { expect(try decoder.decode(BSON.self, from: "{ \"$numberInt\" : \"5\" }")).to(equal(int32)) - let wrappedInt32: Document = ["x": int32] + let wrappedInt32: BSONDocument = ["x": int32] expect(try encoder.encode(AnyBSONStruct(int32))).to(equal(wrappedInt32)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedInt32).x).to(equal(int32)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedInt32.canonicalExtendedJSON).x).to(equal(int32) @@ -684,7 +684,7 @@ final class CodecTests: MongoSwiftTestCase { expect(try decoder.decode(BSON.self, from: "{ \"$numberLong\" : \"5\" }")).to(equal(int)) - let wrappedInt: Document = ["x": int] + let wrappedInt: BSONDocument = ["x": int] expect(try encoder.encode(AnyBSONStruct(int))).to(equal(wrappedInt)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedInt).x).to(equal(int)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedInt.canonicalExtendedJSON).x).to(equal(int)) @@ -694,17 +694,17 @@ final class CodecTests: MongoSwiftTestCase { expect(try decoder.decode(BSON.self, from: "{\"$numberLong\":\"5\"}")).to(equal(int64)) - let wrappedInt64: Document = ["x": int64] + let wrappedInt64: BSONDocument = ["x": int64] expect(try encoder.encode(AnyBSONStruct(int64))).to(equal(wrappedInt64)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedInt64).x).to(equal(int64)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedInt64.canonicalExtendedJSON).x).to(equal(int64)) // decimal128 - let decimal = BSON.decimal128(Decimal128("1.2E+10")!) + let decimal = BSON.decimal128(BSONDecimal128("1.2E+10")!) expect(try decoder.decode(BSON.self, from: "{ \"$numberDecimal\" : \"1.2E+10\" }")).to(equal(decimal)) - let wrappedDecimal: Document = ["x": decimal] + let wrappedDecimal: BSONDocument = ["x": decimal] expect(try encoder.encode(AnyBSONStruct(decimal))).to(equal(wrappedDecimal)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedDecimal).x).to(equal(decimal)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedDecimal.canonicalExtendedJSON).x).to(equal(decimal)) @@ -714,7 +714,7 @@ final class CodecTests: MongoSwiftTestCase { expect(try decoder.decode(BSON.self, from: "{ \"$maxKey\" : 1 }")).to(equal(maxKey)) - let wrappedMaxKey: Document = ["x": maxKey] + let wrappedMaxKey: BSONDocument = ["x": maxKey] expect(try encoder.encode(AnyBSONStruct(maxKey))).to(equal(wrappedMaxKey)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedMaxKey).x).to(equal(maxKey)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedMaxKey.canonicalExtendedJSON).x).to(equal(maxKey)) @@ -724,7 +724,7 @@ final class CodecTests: MongoSwiftTestCase { expect(try decoder.decode(BSON.self, from: "{ \"$minKey\" : 1 }")).to(equal(minKey)) - let wrappedMinKey: Document = ["x": minKey] + let wrappedMinKey: BSONDocument = ["x": minKey] expect(try encoder.encode(AnyBSONStruct(minKey))).to(equal(wrappedMinKey)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedMinKey).x).to(equal(minKey)) expect(try decoder.decode(AnyBSONStruct.self, from: wrappedMinKey.canonicalExtendedJSON).x).to(equal(minKey)) @@ -784,7 +784,7 @@ final class CodecTests: MongoSwiftTestCase { allowDiskUse: true, batchSize: 5, bypassDocumentValidation: false, - collation: Document(), + collation: BSONDocument(), comment: "hello", hint: .indexName("hint"), maxTimeMS: 12, @@ -806,7 +806,7 @@ final class CodecTests: MongoSwiftTestCase { ])) let count = CountDocumentsOptions( - collation: Document(), + collation: BSONDocument(), hint: .indexName("hint"), limit: 123, maxTimeMS: 12, @@ -824,7 +824,7 @@ final class CodecTests: MongoSwiftTestCase { ])) let distinct = DistinctOptions( - collation: Document(), + collation: BSONDocument(), maxTimeMS: 123, readConcern: rc, readPreference: rp @@ -838,23 +838,23 @@ final class CodecTests: MongoSwiftTestCase { let find = FindOptions( allowPartialResults: false, batchSize: 123, - collation: Document(), + collation: BSONDocument(), comment: "asdf", cursorType: .tailable, hint: .indexName("sdf"), limit: 123, - max: Document(), + max: BSONDocument(), maxAwaitTimeMS: 123, maxTimeMS: 123, - min: Document(), + min: BSONDocument(), noCursorTimeout: true, - projection: Document(), + projection: BSONDocument(), readConcern: rc, readPreference: rp, returnKey: true, showRecordID: false, skip: 45, - sort: Document() + sort: BSONDocument() ) expect(try encoder.encode(find).keys.sorted()).to(equal([ "allowPartialResults", @@ -882,21 +882,21 @@ final class CodecTests: MongoSwiftTestCase { background: false, bits: 32, bucketSize: 333, - collation: Document(), + collation: BSONDocument(), defaultLanguage: "english", expireAfterSeconds: 123, languageOverride: "asdf", max: 5.5, min: 4.4, name: "sadf", - partialFilterExpression: Document(), + partialFilterExpression: BSONDocument(), sparse: false, sphereIndexVersion: 959, storageEngine: ["a": 1], textIndexVersion: 123, unique: true, version: 123, - weights: Document() + weights: BSONDocument() ) expect(try encoder.encode(index).keys.sorted()).to(equal([ "background", diff --git a/Tests/BSONTests/Document+CollectionTests.swift b/Tests/BSONTests/Document+CollectionTests.swift index 839099d26..64c8fdcec 100644 --- a/Tests/BSONTests/Document+CollectionTests.swift +++ b/Tests/BSONTests/Document+CollectionTests.swift @@ -6,12 +6,12 @@ import XCTest final class Document_CollectionTests: MongoSwiftTestCase { func testIndexLogic() { - let emptyDoc: Document = [:] + let emptyDoc: BSONDocument = [:] expect(emptyDoc.startIndex).to(equal(0)) expect(emptyDoc.endIndex).to(equal(emptyDoc.startIndex)) - let doc: Document = ["a": 3, "b": 4] + let doc: BSONDocument = ["a": 3, "b": 4] // doc.startIndex, doc.endIndex, doc.index(after:), etc. expect(doc.startIndex).to(equal(0)) @@ -50,7 +50,7 @@ final class Document_CollectionTests: MongoSwiftTestCase { } func testMutators() throws { - var doc: Document = ["a": 3, "b": 2, "c": 5, "d": 4] + var doc: BSONDocument = ["a": 3, "b": 2, "c": 5, "d": 4] // doc.removeFirst let firstElem = doc.removeFirst() @@ -69,12 +69,12 @@ final class Document_CollectionTests: MongoSwiftTestCase { expect(doc).to(equal([:])) // doc.merge - let newDoc: Document = ["e": 4, "f": 2] + let newDoc: BSONDocument = ["e": 4, "f": 2] try doc.merge(newDoc) } func testPrefixSuffix() { - let doc: Document = ["a": 3, "b": 2, "c": 5, "d": 4, "e": 3] + let doc: BSONDocument = ["a": 3, "b": 2, "c": 5, "d": 4, "e": 3] let upToPrefixDoc = doc.prefix(upTo: 2) let throughPrefixDoc = doc.prefix(through: 1) @@ -91,7 +91,7 @@ final class Document_CollectionTests: MongoSwiftTestCase { } func testIndexSubscript() { - let doc: Document = ["hello": "world", "swift": 4.2, "null": .null] + let doc: BSONDocument = ["hello": "world", "swift": 4.2, "null": .null] // subscript with index position expect(doc[0].value).to(equal("world")) diff --git a/Tests/BSONTests/Document+SequenceTests.swift b/Tests/BSONTests/Document+SequenceTests.swift index 4e2bfe7d0..15dbb0eaf 100644 --- a/Tests/BSONTests/Document+SequenceTests.swift +++ b/Tests/BSONTests/Document+SequenceTests.swift @@ -6,7 +6,7 @@ import XCTest final class Document_SequenceTests: MongoSwiftTestCase { func testIterator() { - let doc: Document = [ + let doc: BSONDocument = [ "string": "test string", "true": true, "false": false, @@ -14,7 +14,7 @@ final class Document_SequenceTests: MongoSwiftTestCase { "int32": .int32(5), "int64": .int64(123), "double": .double(15), - "decimal128": .decimal128(Decimal128("1.2E+10")!), + "decimal128": .decimal128(BSONDecimal128("1.2E+10")!), "minkey": .minKey, "maxkey": .maxKey, "date": .datetime(Date(timeIntervalSince1970: 5000)), @@ -54,7 +54,7 @@ final class Document_SequenceTests: MongoSwiftTestCase { let decimalTup = iter.next()! expect(decimalTup.key).to(equal("decimal128")) - expect(decimalTup.value).to(equal(.decimal128(Decimal128("1.2E+10")!))) + expect(decimalTup.value).to(equal(.decimal128(BSONDecimal128("1.2E+10")!))) let minTup = iter.next()! expect(minTup.key).to(equal("minkey")) @@ -81,7 +81,7 @@ final class Document_SequenceTests: MongoSwiftTestCase { ] var expectedValues: [BSON] = [ "test string", true, false, 25, .int32(5), .int64(123), .double(15), - .decimal128(Decimal128("1.2E+10")!), .minKey, .maxKey, .datetime(Date(timeIntervalSince1970: 5000)), + .decimal128(BSONDecimal128("1.2E+10")!), .minKey, .maxKey, .datetime(Date(timeIntervalSince1970: 5000)), .timestamp(BSONTimestamp(timestamp: 5, inc: 10)) ] for (k, v) in doc { @@ -91,7 +91,7 @@ final class Document_SequenceTests: MongoSwiftTestCase { } func testMapFilter() throws { - let doc1: Document = ["a": 1, "b": .null, "c": 3, "d": 4, "e": .null] + let doc1: BSONDocument = ["a": 1, "b": .null, "c": 3, "d": 4, "e": .null] expect(doc1.mapValues { $0 == .null ? 1 : $0 }).to(equal(["a": 1, "b": 1, "c": 3, "d": 4, "e": 1])) let output1 = doc1.mapValues { val in if let int = val.toInt() { @@ -102,7 +102,7 @@ final class Document_SequenceTests: MongoSwiftTestCase { expect(output1).to(equal(["a": 2, "b": .null, "c": 4, "d": 5, "e": .null])) expect(doc1.filter { !($0.value == .null) }).to(equal(["a": 1, "c": 3, "d": 4])) - let doc2: Document = ["a": 1, "b": "hello", "c": [1, 2]] + let doc2: BSONDocument = ["a": 1, "b": "hello", "c": [1, 2]] expect(doc2.filter { $0.value.stringValue != nil }).to(equal(["b": "hello"])) let output2 = doc2.mapValues { val in switch val { @@ -119,25 +119,25 @@ final class Document_SequenceTests: MongoSwiftTestCase { expect(output2).to(equal(["a": 2, "b": "hello there", "c": 3])) // test that the protocol-supplied version of filter is still available - let _: [Document.KeyValuePair] = doc1.filter { $0.key != "a" } + let _: [BSONDocument.KeyValuePair] = doc1.filter { $0.key != "a" } } // shared docs for subsequence tests - let emptyDoc = Document() - let smallDoc: Document = ["x": 1] - let doc: Document = ["a": 1, "b": "hi", "c": [1, 2], "d": false, "e": .null, "f": .minKey, "g": 10] + let emptyDoc = BSONDocument() + let smallDoc: BSONDocument = ["x": 1] + let doc: BSONDocument = ["a": 1, "b": "hi", "c": [1, 2], "d": false, "e": .null, "f": .minKey, "g": 10] // shared predicates for subsequence tests - func isInt(_ pair: Document.KeyValuePair) -> Bool { pair.value.toInt() != nil } - func isNotNil(_ pair: Document.KeyValuePair) -> Bool { pair.value != .null } - func is10(_ pair: Document.KeyValuePair) -> Bool { + func isInt(_ pair: BSONDocument.KeyValuePair) -> Bool { pair.value.toInt() != nil } + func isNotNil(_ pair: BSONDocument.KeyValuePair) -> Bool { pair.value != .null } + func is10(_ pair: BSONDocument.KeyValuePair) -> Bool { if let int = pair.value.toInt() { return int == 10 } return false } - func isNot10(_ pair: Document.KeyValuePair) -> Bool { !self.is10(pair) } + func isNot10(_ pair: BSONDocument.KeyValuePair) -> Bool { !self.is10(pair) } func testDropFirst() throws { expect(self.emptyDoc.dropFirst(0)).to(equal([:])) diff --git a/Tests/BSONTests/DocumentTests.swift b/Tests/BSONTests/DocumentTests.swift index 4fb440c56..a743135a6 100644 --- a/Tests/BSONTests/DocumentTests.swift +++ b/Tests/BSONTests/DocumentTests.swift @@ -40,14 +40,14 @@ enum SwiftBSON { } /// Extension of Document to allow conversion to and from arrays -extension Document { +extension BSONDocument { internal init(fromArray array: [DocElem]) { self.init() for elem in array { switch elem.value { case let .document(els): - self[elem.key] = .document(Document(fromArray: els)) + self[elem.key] = .document(BSONDocument(fromArray: els)) case let .other(b): self[elem.key] = b } @@ -73,7 +73,7 @@ extension Document { final class DocumentTests: MongoSwiftTestCase { // Set up test document values - static let testDoc: Document = [ + static let testDoc: BSONDocument = [ "string": "test string", "true": true, "false": false, @@ -81,7 +81,7 @@ final class DocumentTests: MongoSwiftTestCase { "int32": .int32(5), "int64": .int64(10), "double": .double(15), - "decimal128": .decimal128(Decimal128("1.2E+10")!), + "decimal128": .decimal128(BSONDecimal128("1.2E+10")!), "minkey": .minKey, "maxkey": .maxKey, "date": .datetime(Date(timeIntervalSince1970: 500.004)), @@ -114,7 +114,7 @@ final class DocumentTests: MongoSwiftTestCase { // splitting this out is necessary because the swift 4.0 compiler // can't handle all the keys being declared together - let binaryData: Document = [ + let binaryData: BSONDocument = [ "binary0": .binary(try BSONBinary(data: testData, subtype: .generic)), "binary1": .binary(try BSONBinary(data: testData, subtype: .function)), "binary2": .binary(try BSONBinary(data: testData, subtype: .binaryDeprecated)), @@ -148,7 +148,7 @@ final class DocumentTests: MongoSwiftTestCase { expect(doc["int32"]).to(equal(.int32(5))) expect(doc["int64"]).to(equal(.int64(10))) expect(doc["double"]).to(equal(15.0)) - expect(doc["decimal128"]).to(equal(.decimal128(Decimal128("1.2E+10")!))) + expect(doc["decimal128"]).to(equal(.decimal128(BSONDecimal128("1.2E+10")!))) expect(doc["minkey"]).to(equal(.minKey)) expect(doc["maxkey"]).to(equal(.maxKey)) expect(doc["date"]).to(equal(.datetime(Date(timeIntervalSince1970: 500.004)))) @@ -198,7 +198,7 @@ final class DocumentTests: MongoSwiftTestCase { expect(DocumentTests.testDoc.int32).to(equal(.int32(5))) expect(DocumentTests.testDoc.int64).to(equal(.int64(10))) expect(DocumentTests.testDoc.double).to(equal(15.0)) - expect(DocumentTests.testDoc.decimal128).to(equal(.decimal128(Decimal128("1.2E+10")!))) + expect(DocumentTests.testDoc.decimal128).to(equal(.decimal128(BSONDecimal128("1.2E+10")!))) expect(DocumentTests.testDoc.minkey).to(equal(.minKey)) expect(DocumentTests.testDoc.maxkey).to(equal(.maxKey)) expect(DocumentTests.testDoc.date).to(equal(.datetime(Date(timeIntervalSince1970: 500.004)))) @@ -233,8 +233,8 @@ final class DocumentTests: MongoSwiftTestCase { expect(DocumentTests.testDoc.nesteddoc?.documentValue?.a).to(equal(1)) // Test assignment - var doc = Document() - let subdoc: Document = ["d": 2.5] + var doc = BSONDocument() + let subdoc: BSONDocument = ["d": 2.5] doc.a = 1 doc.b = "b" @@ -252,18 +252,18 @@ final class DocumentTests: MongoSwiftTestCase { } func testEquatable() { - expect(["hi": true, "hello": "hi", "cat": 2] as Document) - .to(equal(["hi": true, "hello": "hi", "cat": 2] as Document)) + expect(["hi": true, "hello": "hi", "cat": 2] as BSONDocument) + .to(equal(["hi": true, "hello": "hi", "cat": 2] as BSONDocument)) } func testRawBSON() throws { - let doc = try Document(fromJSON: "{\"a\" : [{\"$numberInt\": \"10\"}]}") - let fromRawBSON = try Document(fromBSON: doc.rawBSON) + let doc = try BSONDocument(fromJSON: "{\"a\" : [{\"$numberInt\": \"10\"}]}") + let fromRawBSON = try BSONDocument(fromBSON: doc.rawBSON) expect(doc).to(equal(fromRawBSON)) } func testCopyOnWriteBehavior() { - var doc1: Document? = ["a": 1] + var doc1: BSONDocument? = ["a": 1] let originalAddress = doc1?.pointerAddress var doc2 = doc1! // no mutation has happened, so addresses should be the same @@ -305,7 +305,7 @@ final class DocumentTests: MongoSwiftTestCase { let int32min_sub1 = Int64(Int32.min) - Int64(1) let int32max_add1 = Int64(Int32.max) + Int64(1) - let doc: Document = [ + let doc: BSONDocument = [ "int32min": BSON(Int(Int32.min)), "int32max": BSON(Int(Int32.max)), "int32min-1": BSON(Int(int32min_sub1)), @@ -324,7 +324,7 @@ final class DocumentTests: MongoSwiftTestCase { func testMerge() throws { // test documents are merged correctly - var doc1: Document = ["a": 1] + var doc1: BSONDocument = ["a": 1] try doc1.merge(["b": 2]) expect(doc1).to(equal(["a": 1, "b": 2])) @@ -346,18 +346,18 @@ final class DocumentTests: MongoSwiftTestCase { } // exclude Int64 value on 32-bit platforms - static let overwritables: Document = [ + static let overwritables: BSONDocument = [ "double": 2.5, "int32": .int32(32), "int64": .int64(Int64.max), "bool": false, - "decimal": .decimal128(Decimal128("1.2E+10")!), + "decimal": .decimal128(BSONDecimal128("1.2E+10")!), "oid": .objectID(), "timestamp": .timestamp(BSONTimestamp(timestamp: 1, inc: 2)), "datetime": .datetime(Date(msSinceEpoch: 1000)) ] - static let nonOverwritables: Document = [ + static let nonOverwritables: BSONDocument = [ "string": "hello", "nil": .null, "doc": ["x": 1], @@ -368,7 +368,7 @@ final class DocumentTests: MongoSwiftTestCase { func testOverwritable() throws { // make a deep copy so we start off with uniquely referenced storage var doc = DocumentTests.overwritables.withBSONPointer { ptr in - Document(copying: ptr) + BSONDocument(copying: ptr) } // save a reference to original bson_t so we can verify it doesn't change @@ -387,7 +387,7 @@ final class DocumentTests: MongoSwiftTestCase { doc["double"] = 3.0 expect(doc.pointerAddress).to(equal(pointer)) - doc["decimal"] = .decimal128(Decimal128("100")!) + doc["decimal"] = .decimal128(BSONDecimal128("100")!) expect(doc.pointerAddress).to(equal(pointer)) // overwrite int64 with int64 @@ -409,7 +409,7 @@ final class DocumentTests: MongoSwiftTestCase { "int32": .int32(15), "int64": .int64(Int64.min), "bool": true, - "decimal": .decimal128(Decimal128("100")!), + "decimal": .decimal128(BSONDecimal128("100")!), "oid": .objectID(newOid), "timestamp": .timestamp(BSONTimestamp(timestamp: 5, inc: 10)), "datetime": .datetime(Date(msSinceEpoch: 2000)) @@ -430,7 +430,7 @@ final class DocumentTests: MongoSwiftTestCase { "int32": .int32(15), "int64": BSON(integerLiteral: bigInt), "bool": true, - "decimal": .decimal128(Decimal128("100")!), + "decimal": .decimal128(BSONDecimal128("100")!), "oid": .objectID(newOid), "timestamp": .timestamp(BSONTimestamp(timestamp: 5, inc: 10)), "datetime": .datetime(Date(msSinceEpoch: 2000)) @@ -446,14 +446,14 @@ final class DocumentTests: MongoSwiftTestCase { func testNonOverwritable() throws { // make a deep copy so we start off with uniquely referenced storage var doc = DocumentTests.nonOverwritables.withBSONPointer { ptr in - Document(copying: ptr) + BSONDocument(copying: ptr) } // save a reference to original bson_t so we can verify it changes var pointer = doc.pointerAddress // save these to compare to at the end - let newDoc: Document = ["y": 1] + let newDoc: BSONDocument = ["y": 1] let newPairs: [(String, BSON)] = [("string", "hi"), ("doc", .document(newDoc)), ("arr", [3, 4])] @@ -471,7 +471,7 @@ final class DocumentTests: MongoSwiftTestCase { func testReplaceValueWithNewType() throws { // make a deep copy so we start off with uniquely referenced storage var overwritableDoc = DocumentTests.overwritables.withBSONPointer { ptr in - Document(copying: ptr) + BSONDocument(copying: ptr) } // save a reference to original bson_t so we can verify it changes @@ -481,7 +481,7 @@ final class DocumentTests: MongoSwiftTestCase { let overwritablePairs: [(String, BSON)] = [ ("double", BSON(10)), ("int32", "hi"), - ("int64", .decimal128(Decimal128("1.0")!)), + ("int64", .decimal128(BSONDecimal128("1.0")!)), ("bool", [1, 2, 3]), ("decimal", 100), ("oid", 25.5), @@ -498,7 +498,7 @@ final class DocumentTests: MongoSwiftTestCase { expect(overwritableDoc).to(equal([ "double": BSON(10), "int32": "hi", - "int64": .decimal128(Decimal128("1.0")!), + "int64": .decimal128(BSONDecimal128("1.0")!), "bool": [1, 2, 3], "decimal": 100, "oid": 25.5, @@ -508,7 +508,7 @@ final class DocumentTests: MongoSwiftTestCase { // make a deep copy so we start off with uniquely referenced storage var nonOverwritableDoc = DocumentTests.nonOverwritables.withBSONPointer { ptr in - Document(copying: ptr) + BSONDocument(copying: ptr) } // save a reference to original bson_t so we can verify it changes @@ -528,7 +528,7 @@ final class DocumentTests: MongoSwiftTestCase { // test setting both overwritable and nonoverwritable values to nil func testReplaceValueWithNil() throws { var overwritableDoc = DocumentTests.overwritables.withBSONPointer { ptr in - Document(copying: ptr) + BSONDocument(copying: ptr) } var overwritablePointer = overwritableDoc.pointerAddress @@ -540,7 +540,7 @@ final class DocumentTests: MongoSwiftTestCase { } var nonOverwritableDoc = DocumentTests.nonOverwritables.withBSONPointer { ptr in - Document(copying: ptr) + BSONDocument(copying: ptr) } var nonOverwritablePointer = nonOverwritableDoc.pointerAddress @@ -557,7 +557,7 @@ final class DocumentTests: MongoSwiftTestCase { // Test types where replacing them with an instance of their own type is a no-op func testReplaceValueNoop() throws { - var noops: Document = ["null": .null, "maxkey": .maxKey, "minkey": .minKey] + var noops: BSONDocument = ["null": .null, "maxkey": .maxKey, "minkey": .minKey] var pointer = noops.pointerAddress @@ -587,7 +587,7 @@ final class DocumentTests: MongoSwiftTestCase { } func testDocumentDictionarySimilarity() throws { - var doc: Document = ["hello": "world", "swift": 4.2, "null": .null, "remove_me": "please"] + var doc: BSONDocument = ["hello": "world", "swift": 4.2, "null": .null, "remove_me": "please"] let dict: [String: BSON] = ["hello": "world", "swift": 4.2, "null": .null, "remove_me": "please"] expect(doc["hello"]).to(equal(dict["hello"])) @@ -602,7 +602,7 @@ final class DocumentTests: MongoSwiftTestCase { } func testDefaultSubscript() throws { - let doc: Document = ["hello": "world"] + let doc: BSONDocument = ["hello": "world"] let floatVal = 18.2 let stringVal = "this is a string" expect(doc["DNE", default: .double(floatVal)]).to(equal(.double(floatVal))) @@ -617,10 +617,10 @@ final class DocumentTests: MongoSwiftTestCase { func testMultibyteCharacterStrings() throws { let str = String(repeating: "🇧🇷", count: 10) - var doc: Document = ["first": .string(str)] + var doc: BSONDocument = ["first": .string(str)] expect(doc["first"]).to(equal(.string(str))) - let doc1: Document = [str: "second"] + let doc1: BSONDocument = [str: "second"] expect(doc1[str]).to(equal("second")) let abt = try CodecTests.AllBSONTypes.factory() @@ -662,8 +662,8 @@ final class DocumentTests: MongoSwiftTestCase { // UUID default decoder expects a string decoder.uuidDecodingStrategy = .deferredToUUID - let stringDoc: Document = ["uuid": .string(uuid.description)] - let badString: Document = ["uuid": "hello"] + let stringDoc: BSONDocument = ["uuid": .string(uuid.description)] + let badString: BSONDocument = ["uuid": "hello"] let deferredStruct = try decoder.decode(UUIDWrapper.self, from: stringDoc) expect(deferredStruct.uuid).to(equal(uuid)) expect(try decoder.decode(UUIDWrapper.self, from: badString)).to(throwError(CodecTests.dataCorruptedErr)) @@ -676,11 +676,11 @@ final class DocumentTests: MongoSwiftTestCase { uuidt.8, uuidt.9, uuidt.10, uuidt.11, uuidt.12, uuidt.13, uuidt.14, uuidt.15 ]) - let binaryDoc: Document = ["uuid": .binary(try BSONBinary(data: bytes, subtype: .uuid))] + let binaryDoc: BSONDocument = ["uuid": .binary(try BSONBinary(data: bytes, subtype: .uuid))] let binaryStruct = try decoder.decode(UUIDWrapper.self, from: binaryDoc) expect(binaryStruct.uuid).to(equal(uuid)) - let badBinary: Document = ["uuid": .binary(try BSONBinary(data: bytes, subtype: .generic))] + let badBinary: BSONDocument = ["uuid": .binary(try BSONBinary(data: bytes, subtype: .generic))] expect(try decoder.decode(UUIDWrapper.self, from: badBinary)).to(throwError(CodecTests.dataCorruptedErr)) expect(try decoder.decode(UUIDWrapper.self, from: stringDoc)).to(throwError(CodecTests.typeMismatchErr)) @@ -779,7 +779,7 @@ final class DocumentTests: MongoSwiftTestCase { let date = Date(timeIntervalSince1970: 125.0) // Default is .bsonDateTime - let bsonDate: Document = ["date": .datetime(date)] + let bsonDate: BSONDocument = ["date": .datetime(date)] let defaultStruct = try decoder.decode(DateWrapper.self, from: bsonDate) expect(defaultStruct.date).to(equal(date)) @@ -788,21 +788,21 @@ final class DocumentTests: MongoSwiftTestCase { expect(bsonDateStruct.date).to(equal(date)) decoder.dateDecodingStrategy = .millisecondsSince1970 - let msInt64: Document = ["date": .int64(date.msSinceEpoch)] + let msInt64: BSONDocument = ["date": .int64(date.msSinceEpoch)] let msInt64Struct = try decoder.decode(DateWrapper.self, from: msInt64) expect(msInt64Struct.date).to(equal(date)) expect(try BSONDecoder().decode(DateWrapper.self, from: msInt64)).to(throwError(CodecTests.typeMismatchErr)) - let msDouble: Document = ["date": .double(Double(date.msSinceEpoch))] + let msDouble: BSONDocument = ["date": .double(Double(date.msSinceEpoch))] let msDoubleStruct = try decoder.decode(DateWrapper.self, from: msDouble) expect(msDoubleStruct.date).to(equal(date)) decoder.dateDecodingStrategy = .secondsSince1970 - let sDouble: Document = ["date": .double(date.timeIntervalSince1970)] + let sDouble: BSONDocument = ["date": .double(date.timeIntervalSince1970)] let sDoubleStruct = try decoder.decode(DateWrapper.self, from: sDouble) expect(sDoubleStruct.date).to(equal(date)) - let sInt64: Document = ["date": .double(date.timeIntervalSince1970)] + let sInt64: BSONDocument = ["date": .double(date.timeIntervalSince1970)] let sInt64Struct = try decoder.decode(DateWrapper.self, from: sInt64) expect(sInt64Struct.date).to(equal(date)) @@ -812,8 +812,8 @@ final class DocumentTests: MongoSwiftTestCase { formatter.locale = Locale(identifier: "en_US") decoder.dateDecodingStrategy = .formatted(formatter) - let formatted: Document = ["date": .string(formatter.string(from: date))] - let badlyFormatted: Document = ["date": "this is not a date"] + let formatted: BSONDocument = ["date": .string(formatter.string(from: date))] + let badlyFormatted: BSONDocument = ["date": "this is not a date"] let formattedStruct = try decoder.decode(DateWrapper.self, from: formatted) expect(formattedStruct.date).to(equal(date)) expect(try decoder.decode(DateWrapper.self, from: badlyFormatted)).to(throwError(CodecTests.dataCorruptedErr)) @@ -821,7 +821,7 @@ final class DocumentTests: MongoSwiftTestCase { if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { decoder.dateDecodingStrategy = .iso8601 - let isoDoc: Document = ["date": .string(BSONDecoder.iso8601Formatter.string(from: date))] + let isoDoc: BSONDocument = ["date": .string(BSONDecoder.iso8601Formatter.string(from: date))] let isoStruct = try decoder.decode(DateWrapper.self, from: isoDoc) expect(isoStruct.date).to(equal(date)) expect(try decoder.decode(DateWrapper.self, from: formatted)).to(throwError(CodecTests.dataCorruptedErr)) @@ -830,7 +830,7 @@ final class DocumentTests: MongoSwiftTestCase { } decoder.dateDecodingStrategy = .custom({ decode in try Date(from: decode) }) - let customDoc: Document = ["date": .double(date.timeIntervalSinceReferenceDate)] + let customDoc: BSONDocument = ["date": .double(date.timeIntervalSinceReferenceDate)] let customStruct = try decoder.decode(DateWrapper.self, from: customDoc) expect(customStruct.date).to(equal(date)) expect(try decoder.decode(DateWrapper.self, from: badlyFormatted)).to(throwError(CodecTests.typeMismatchErr)) @@ -883,7 +883,7 @@ final class DocumentTests: MongoSwiftTestCase { expect(try decoder.decode(DataWrapper.self, from: ["data": "this is not base64 encoded~"])) .to(throwError(CodecTests.dataCorruptedErr)) - let customEncodedDoc: Document = [ + let customEncodedDoc: BSONDocument = [ "d": .string(data.base64EncodedString()), "hash": .int64(Int64(data.hashValue)) ] @@ -892,7 +892,7 @@ final class DocumentTests: MongoSwiftTestCase { try container.encode(customEncodedDoc) }) decoder.dataDecodingStrategy = .custom({ decoder in - let doc = try Document(from: decoder) + let doc = try BSONDocument(from: decoder) guard let d = Data(base64Encoded: doc["d"]!.stringValue!) else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "bad base64")) } @@ -909,7 +909,7 @@ final class DocumentTests: MongoSwiftTestCase { } func testIntegerLiteral() { - let doc: Document = ["int": 12] + let doc: BSONDocument = ["int": 12] if MongoSwiftTestCase.is32Bit { expect(doc["int"]).to(equal(.int32(12))) @@ -932,7 +932,7 @@ final class DocumentTests: MongoSwiftTestCase { ] for data in invalidData { - expect(try Document(fromBSON: data)).to(throwError(errorType: InvalidArgumentError.self)) + expect(try BSONDocument(fromBSON: data)).to(throwError(errorType: InvalidArgumentError.self)) } } } diff --git a/Tests/MongoSwiftSyncTests/ClientSessionTests.swift b/Tests/MongoSwiftSyncTests/ClientSessionTests.swift index db96f3083..da6719b05 100644 --- a/Tests/MongoSwiftSyncTests/ClientSessionTests.swift +++ b/Tests/MongoSwiftSyncTests/ClientSessionTests.swift @@ -7,7 +7,7 @@ import TestsCommon /// Describes an operation run on a collection that takes in a session. struct CollectionSessionOp { let name: String - let body: (MongoCollection, MongoSwiftSync.ClientSession?) throws -> Void + let body: (MongoCollection, MongoSwiftSync.ClientSession?) throws -> Void } /// Describes an operation run on a database that takes in a session. @@ -84,7 +84,7 @@ final class SyncClientSessionTests: MongoSwiftTestCase { DatabaseSessionOp(name: "runCommand") { try $0.runCommand(["isMaster": 0], session: $1) }, DatabaseSessionOp(name: "createCollection") { _ = try $0.createCollection("asdf", session: $1) }, DatabaseSessionOp(name: "createCollection1") { - _ = try $0.createCollection("asf", withType: Document.self, session: $1) + _ = try $0.createCollection("asf", withType: BSONDocument.self, session: $1) }, DatabaseSessionOp(name: "drop") { _ = try $0.drop(session: $1) } ] @@ -100,7 +100,7 @@ final class SyncClientSessionTests: MongoSwiftTestCase { func forEachSessionOp( client: MongoClient, database: MongoDatabase, - collection: MongoCollection, + collection: MongoCollection, _ body: (SessionOp) throws -> Void ) rethrows { try (self.collectionSessionReadOps + self.collectionSessionWriteOps).forEach { op in @@ -312,7 +312,7 @@ final class SyncClientSessionTests: MongoSwiftTestCase { client.withSession { session in let date = Date() expect(session.clusterTime).to(beNil()) - let newTime: Document = [ + let newTime: BSONDocument = [ "clusterTime": .timestamp(BSONTimestamp(timestamp: Int(date.timeIntervalSince1970), inc: 100)) ] session.advanceClusterTime(to: newTime) diff --git a/Tests/MongoSwiftSyncTests/CommandMonitoringTests.swift b/Tests/MongoSwiftSyncTests/CommandMonitoringTests.swift index 5584b9f84..a052981bd 100644 --- a/Tests/MongoSwiftSyncTests/CommandMonitoringTests.swift +++ b/Tests/MongoSwiftSyncTests/CommandMonitoringTests.swift @@ -67,7 +67,7 @@ final class CommandMonitoringTests: MongoSwiftTestCase { /// A struct to hold the data for a single file, containing one or more tests. private struct CMTestFile: Decodable { - let data: [Document] + let data: [BSONDocument] let collectionName: String let databaseName: String let tests: [CMTest] @@ -83,7 +83,7 @@ private struct CMTestFile: Decodable { private struct CMTest: Decodable { struct Operation: Decodable { let name: String - let args: Document + let args: BSONDocument let readPreference: ReadPreference? enum CodingKeys: String, CodingKey { @@ -93,7 +93,7 @@ private struct CMTest: Decodable { let op: Operation let description: String - let expectationDocs: [Document] + let expectationDocs: [BSONDocument] let minServerVersion: String? let maxServerVersion: String? @@ -115,8 +115,8 @@ private struct CMTest: Decodable { // If something fails/succeeds incorrectly, we'll know because the generated // events won't match up. // swiftlint:disable cyclomatic_complexity - func doOperation(withCollection collection: MongoCollection) throws { - let filter: Document = self.op.args["filter"]?.documentValue ?? [:] + func doOperation(withCollection collection: MongoCollection) throws { + let filter: BSONDocument = self.op.args["filter"]?.documentValue ?? [:] switch self.op.name { case "count": @@ -159,15 +159,15 @@ private struct CMTest: Decodable { _ = try? collection.insertMany(documents, options: options) case "insertOne": - let document: Document = try self.op.args.get("document") + let document: BSONDocument = try self.op.args.get("document") _ = try? collection.insertOne(document) case "updateMany": - let update: Document = try self.op.args.get("update") + let update: BSONDocument = try self.op.args.get("update") _ = try? collection.updateMany(filter: filter, update: update) case "updateOne": - let update: Document = try self.op.args.get("update") + let update: BSONDocument = try self.op.args.get("update") let options = UpdateOptions(upsert: self.op.args["upsert"]?.boolValue) _ = try? collection.updateOne(filter: filter, update: update, options: options) @@ -188,7 +188,7 @@ private protocol ExpectationType { /// Based on the name of the expectation, generate a corresponding /// `ExpectationType` to be compared to incoming events -private func makeExpectation(_ document: Document) throws -> ExpectationType { +private func makeExpectation(_ document: BSONDocument) throws -> ExpectationType { let decoder = BSONDecoder() if let doc = document["command_started_event"]?.documentValue { @@ -208,7 +208,7 @@ private func makeExpectation(_ document: Document) throws -> ExpectationType { /// An expectation for a `CommandStartedEvent` private struct CommandStartedExpectation: ExpectationType, Decodable { - var command: Document + var command: BSONDocument let commandName: String let databaseName: String @@ -244,8 +244,8 @@ private struct CommandStartedExpectation: ExpectationType, Decodable { } } -private func normalizeCommand(_ input: Document) -> Document { - var output = Document() +private func normalizeCommand(_ input: BSONDocument) -> BSONDocument { + var output = BSONDocument() for (k, v) in input { // temporary fix pending resolution of SPEC-1049. removes the field // from the expected command unless if it is set to true, because none of the @@ -302,12 +302,12 @@ private struct CommandFailedExpectation: ExpectationType, Decodable { } private struct CommandSucceededExpectation: ExpectationType, Decodable { - let originalReply: Document + let originalReply: BSONDocument let commandName: String - var reply: Document { normalizeExpectedReply(originalReply) } - var writeErrors: [Document]? { originalReply["writeErrors"]?.arrayValue?.compactMap { $0.documentValue } } - var cursor: Document? { originalReply["cursor"]?.documentValue } + var reply: BSONDocument { normalizeExpectedReply(originalReply) } + var writeErrors: [BSONDocument]? { originalReply["writeErrors"]?.arrayValue?.compactMap { $0.documentValue } } + var cursor: BSONDocument? { originalReply["cursor"]?.documentValue } enum CodingKeys: String, CodingKey { case commandName = "command_name", originalReply = "reply" @@ -353,7 +353,7 @@ private struct CommandSucceededExpectation: ExpectationType, Decodable { } /// Compare expected vs actual write errors. - func checkWriteErrors(expected: [Document], actual: [Document]) { + func checkWriteErrors(expected: [BSONDocument], actual: [BSONDocument]) { // The expected writeErrors has placeholder values, // so just make sure the count is the same expect(expected.count).to(equal(actual.count)) @@ -367,7 +367,7 @@ private struct CommandSucceededExpectation: ExpectationType, Decodable { /// Compare expected vs actual cursor data, excluding the cursor ID /// (handled in `compare` because we need the test context). - func compareCursors(expected: Document, actual: Document) { + func compareCursors(expected: BSONDocument, actual: BSONDocument) { let ordered = rearrangeDoc(actual, toLookLike: expected) expect(ordered["ns"]).to(equal(expected["ns"])) if let firstBatch = expected["firstBatch"] { @@ -379,8 +379,8 @@ private struct CommandSucceededExpectation: ExpectationType, Decodable { } /// Clean up expected replies for easier comparison to received replies -private func normalizeExpectedReply(_ input: Document) -> Document { - var output = Document() +private func normalizeExpectedReply(_ input: BSONDocument) -> BSONDocument { + var output = BSONDocument() for (k, v) in input { // These fields both have placeholder values in them, // so we can't directly compare. Remove them from the expected diff --git a/Tests/MongoSwiftSyncTests/CrudTests.swift b/Tests/MongoSwiftSyncTests/CrudTests.swift index c41cd72df..c1ba70090 100644 --- a/Tests/MongoSwiftSyncTests/CrudTests.swift +++ b/Tests/MongoSwiftSyncTests/CrudTests.swift @@ -69,8 +69,8 @@ final class CrudTests: MongoSwiftTestCase { /// A container for the data from a single .json file. private struct CrudTestFile: Decodable { - let data: [Document] - let testDocs: [Document] + let data: [BSONDocument] + let testDocs: [BSONDocument] func makeTests() throws -> [CrudTest] { try self.testDocs.map { try makeCrudTest($0) } @@ -85,8 +85,8 @@ private struct CrudTestFile: Decodable { } /// Initializes a new `CrudTest` of the appropriate subclass from a `Document` -private func makeCrudTest(_ doc: Document) throws -> CrudTest { - let operation: Document = try doc.get("operation") +private func makeCrudTest(_ doc: BSONDocument) throws -> CrudTest { + let operation: BSONDocument = try doc.get("operation") let opName: String = try operation.get("name") guard let type = testTypeMap[opName] else { throw TestError(message: "Unknown operation name \(opName)") @@ -120,18 +120,18 @@ private var testTypeMap: [String: CrudTest.Type] = [ private class CrudTest { let description: String let operationName: String - let args: Document + let args: BSONDocument let error: Bool? let result: BSON? - let collection: Document? + let collection: BSONDocument? - var arrayFilters: [Document]? { self.args["arrayFilters"]?.arrayValue?.compactMap { $0.documentValue } } + var arrayFilters: [BSONDocument]? { self.args["arrayFilters"]?.arrayValue?.compactMap { $0.documentValue } } var batchSize: Int? { self.args["batchSize"]?.toInt() } - var collation: Document? { self.args["collation"]?.documentValue } - var sort: Document? { self.args["sort"]?.documentValue } + var collation: BSONDocument? { self.args["collation"]?.documentValue } + var sort: BSONDocument? { self.args["sort"]?.documentValue } var skip: Int? { self.args["skip"]?.toInt() } var limit: Int? { self.args["limit"]?.toInt() } - var projection: Document? { self.args["projection"]?.documentValue } + var projection: BSONDocument? { self.args["projection"]?.documentValue } var returnDoc: ReturnDocument? { if let ret = self.args["returnDocument"]?.stringValue { return ret == "After" ? .after : .before @@ -142,23 +142,23 @@ private class CrudTest { var upsert: Bool? { self.args["upsert"]?.boolValue } /// Initializes a new `CrudTest` from a `Document`. - required init(_ test: Document) throws { + required init(_ test: BSONDocument) throws { self.description = try test.get("description") - let operation: Document = try test.get("operation") + let operation: BSONDocument = try test.get("operation") self.operationName = try operation.get("name") self.args = try operation.get("arguments") - let outcome: Document = try test.get("outcome") + let outcome: BSONDocument = try test.get("outcome") self.error = outcome["error"]?.boolValue self.result = outcome["result"] self.collection = outcome["collection"]?.documentValue } // Subclasses should implement `execute` according to the particular operation(s) they are for. - func execute(usingCollection _: MongoCollection) throws { XCTFail("Unimplemented") } + func execute(usingCollection _: MongoCollection) throws { XCTFail("Unimplemented") } // If the test has a `collection` field in its `outcome`, verify that the expected // data is present. If there is no `collection` field, do nothing. - func verifyData(testCollection coll: MongoCollection, db: MongoDatabase) throws { + func verifyData(testCollection coll: MongoCollection, db: MongoDatabase) throws { // only some tests have data to verify guard let collection = self.collection else { return @@ -189,7 +189,7 @@ private class CrudTest { /// Given the response to a findAndModify command, verify that it matches the expected /// results for this `CrudTest`. Meant for use by findAndModify subclasses, i.e. findOneAndX. - func verifyFindAndModifyResult(_ result: Document?) { + func verifyFindAndModifyResult(_ result: BSONDocument?) { guard self.result != nil else { return } @@ -203,7 +203,7 @@ private class CrudTest { /// A class for executing `aggregate` tests private class AggregateTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { + override func execute(usingCollection coll: MongoCollection) throws { let pipeline = self.args["pipeline"]!.arrayValue!.compactMap { $0.documentValue } let options = AggregateOptions(batchSize: self.batchSize, collation: self.collation) let cursor = try coll.aggregate(pipeline, options: options) @@ -221,9 +221,9 @@ private class AggregateTest: CrudTest { } private class BulkWriteTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { - let requestDocuments: [Document] = self.args["requests"]!.arrayValue!.compactMap { $0.documentValue } - let requests = try requestDocuments.map { try BSONDecoder().decode(WriteModel.self, from: $0) } + override func execute(usingCollection coll: MongoCollection) throws { + let requestDocuments: [BSONDocument] = self.args["requests"]!.arrayValue!.compactMap { $0.documentValue } + let requests = try requestDocuments.map { try BSONDecoder().decode(WriteModel.self, from: $0) } let options = try BSONDecoder().decode(BulkWriteOptions.self, from: self.args["options"]?.documentValue ?? [:]) let expectError = self.error ?? false @@ -240,8 +240,8 @@ private class BulkWriteTest: CrudTest { } } - private static func prepareIds(_ ids: [Int: BSON]) -> Document { - var document = Document() + private static func prepareIds(_ ids: [Int: BSON]) -> BSONDocument { + var document = BSONDocument() // Dictionaries are unsorted. Sort before comparing with expected map for (index, id) in ids.sorted(by: { $0.key < $1.key }) { @@ -282,13 +282,13 @@ private class BulkWriteTest: CrudTest { /// A class for executing `count` tests private class CountTest: CrudTest { - override func execute(usingCollection _: MongoCollection) throws {} + override func execute(usingCollection _: MongoCollection) throws {} } /// A class for executing `countDocuments` tests private class CountDocumentsTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { - let filter: Document = try self.args.get("filter") + override func execute(usingCollection coll: MongoCollection) throws { + let filter: BSONDocument = try self.args.get("filter") let options = CountDocumentsOptions(collation: self.collation, limit: self.limit, skip: self.skip) let result = try coll.countDocuments(filter, options: options) expect(result).to(equal(self.result?.toInt())) @@ -297,7 +297,7 @@ private class CountDocumentsTest: CrudTest { /// A class for executing `estimatedDocumentCount` tests private class EstimatedDocumentCountTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { + override func execute(usingCollection coll: MongoCollection) throws { let options = EstimatedDocumentCountOptions() let result = try coll.estimatedDocumentCount(options: options) expect(result).to(equal(self.result?.toInt())) @@ -306,8 +306,8 @@ private class EstimatedDocumentCountTest: CrudTest { /// A class for executing `deleteOne` and `deleteMany` tests private class DeleteTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { - let filter: Document = try self.args.get("filter") + override func execute(usingCollection coll: MongoCollection) throws { + let filter: BSONDocument = try self.args.get("filter") let options = DeleteOptions(collation: self.collation) let result: DeleteResult? if self.operationName == "deleteOne" { @@ -323,16 +323,16 @@ private class DeleteTest: CrudTest { /// A class for executing `distinct` tests private class DistinctTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { + override func execute(usingCollection coll: MongoCollection) throws { let filter = self.args["filter"]?.documentValue let fieldName: String = try self.args.get("fieldName") let options = DistinctOptions(collation: self.collation) // rather than casting to all the possible BSON types, just wrap the arrays in documents to compare them - let resultDoc: Document = [ + let resultDoc: BSONDocument = [ "result": .array(try coll.distinct(fieldName: fieldName, filter: filter ?? [:], options: options)) ] if let result = self.result { - let expectedDoc: Document = ["result": result] + let expectedDoc: BSONDocument = ["result": result] expect(resultDoc).to(equal(expectedDoc)) } } @@ -340,8 +340,8 @@ private class DistinctTest: CrudTest { /// A class for executing `find` tests private class FindTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { - let filter: Document = try self.args.get("filter") + override func execute(usingCollection coll: MongoCollection) throws { + let filter: BSONDocument = try self.args.get("filter") let options = FindOptions( batchSize: self.batchSize, collation: self.collation, @@ -356,8 +356,8 @@ private class FindTest: CrudTest { /// A class for executing `findOneAndDelete` tests private class FindOneAndDeleteTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { - let filter: Document = try self.args.get("filter") + override func execute(usingCollection coll: MongoCollection) throws { + let filter: BSONDocument = try self.args.get("filter") let opts = FindOneAndDeleteOptions(collation: self.collation, projection: self.projection, sort: self.sort) let result = try coll.findOneAndDelete(filter, options: opts) @@ -367,9 +367,9 @@ private class FindOneAndDeleteTest: CrudTest { /// A class for executing `findOneAndUpdate` tests private class FindOneAndReplaceTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { - let filter: Document = try self.args.get("filter") - let replacement: Document = try self.args.get("replacement") + override func execute(usingCollection coll: MongoCollection) throws { + let filter: BSONDocument = try self.args.get("filter") + let replacement: BSONDocument = try self.args.get("replacement") let opts = FindOneAndReplaceOptions( collation: self.collation, @@ -386,9 +386,9 @@ private class FindOneAndReplaceTest: CrudTest { /// A class for executing `findOneAndReplace` tests private class FindOneAndUpdateTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { - let filter: Document = try self.args.get("filter") - let update: Document = try self.args.get("update") + override func execute(usingCollection coll: MongoCollection) throws { + let filter: BSONDocument = try self.args.get("filter") + let update: BSONDocument = try self.args.get("update") let opts = FindOneAndUpdateOptions( arrayFilters: self.arrayFilters, @@ -406,7 +406,7 @@ private class FindOneAndUpdateTest: CrudTest { /// A class for executing `insertMany` tests private class InsertManyTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { + override func execute(usingCollection coll: MongoCollection) throws { let documents = self.args["documents"]!.arrayValue!.compactMap { $0.documentValue } let options = InsertManyTest.parseInsertManyOptions(self.args["options"]?.documentValue) let expectError = self.error ?? false @@ -424,7 +424,7 @@ private class InsertManyTest: CrudTest { } } - private static func parseInsertManyOptions(_ options: Document?) -> InsertManyOptions? { + private static func parseInsertManyOptions(_ options: BSONDocument?) -> InsertManyOptions? { guard let options = options else { return nil } @@ -434,8 +434,8 @@ private class InsertManyTest: CrudTest { return InsertManyOptions(ordered: ordered) } - private static func prepareIds(_ ids: [Int: BSON]) -> Document { - var document = Document() + private static func prepareIds(_ ids: [Int: BSON]) -> BSONDocument { + var document = BSONDocument() // Dictionaries are unsorted. Sort before comparing with expected map for (index, id) in ids.sorted(by: { $0.key < $1.key }) { @@ -461,8 +461,8 @@ private class InsertManyTest: CrudTest { /// A Class for executing `insertOne` tests private class InsertOneTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { - let doc: Document = try self.args.get("document") + override func execute(usingCollection coll: MongoCollection) throws { + let doc: BSONDocument = try self.args.get("document") let result = try coll.insertOne(doc) expect(doc["_id"]).to(equal(result?.insertedID)) } @@ -470,9 +470,9 @@ private class InsertOneTest: CrudTest { /// A class for executing `replaceOne` tests private class ReplaceOneTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { - let filter: Document = try self.args.get("filter") - let replacement: Document = try self.args.get("replacement") + override func execute(usingCollection coll: MongoCollection) throws { + let filter: BSONDocument = try self.args.get("filter") + let replacement: BSONDocument = try self.args.get("replacement") let options = ReplaceOptions(collation: self.collation, upsert: self.upsert) let result = try coll.replaceOne(filter: filter, replacement: replacement, options: options) try self.verifyUpdateResult(result) @@ -481,9 +481,9 @@ private class ReplaceOneTest: CrudTest { /// A class for executing `updateOne` and `updateMany` tests private class UpdateTest: CrudTest { - override func execute(usingCollection coll: MongoCollection) throws { - let filter: Document = try self.args.get("filter") - let update: Document = try self.args.get("update") + override func execute(usingCollection coll: MongoCollection) throws { + let filter: BSONDocument = try self.args.get("filter") + let update: BSONDocument = try self.args.get("update") let options = UpdateOptions(arrayFilters: self.arrayFilters, collation: self.collation, upsert: self.upsert) let result: UpdateResult? if self.operationName == "updateOne" { diff --git a/Tests/MongoSwiftSyncTests/MongoCollection+BulkWriteTests.swift b/Tests/MongoSwiftSyncTests/MongoCollection+BulkWriteTests.swift index 93d90f1b0..4b716d668 100644 --- a/Tests/MongoSwiftSyncTests/MongoCollection+BulkWriteTests.swift +++ b/Tests/MongoSwiftSyncTests/MongoCollection+BulkWriteTests.swift @@ -5,7 +5,7 @@ import XCTest final class MongoCollection_BulkWriteTests: MongoSwiftTestCase { static var client: MongoClient? - var coll: MongoCollection! + var coll: MongoCollection! /// Set up the entire suite - run once before all tests override class func setUp() { @@ -51,7 +51,7 @@ final class MongoCollection_BulkWriteTests: MongoSwiftTestCase { } func testInserts() throws { - let requests: [WriteModel] = [ + let requests: [WriteModel] = [ .insertOne(["_id": 1, "x": 11]), .insertOne(["x": 22]) ] @@ -79,11 +79,11 @@ final class MongoCollection_BulkWriteTests: MongoSwiftTestCase { let id2 = BSON.objectID() let id3 = BSON.objectID() - let doc = ["_id": id] as Document + let doc = ["_id": id] as BSONDocument try self.coll.insertOne(doc) - let requests: [WriteModel] = [ + let requests: [WriteModel] = [ .insertOne(["_id": id2]), .insertOne(doc), .updateOne( @@ -120,7 +120,7 @@ final class MongoCollection_BulkWriteTests: MongoSwiftTestCase { func testUpdates() throws { try self.createFixtures(4) - let requests: [WriteModel] = [ + let requests: [WriteModel] = [ .updateOne(filter: ["_id": 2], update: ["$inc": ["x": 1]]), .updateMany(filter: ["_id": ["$gt": 2]], update: ["$inc": ["x": -1]]), .updateOne( @@ -157,7 +157,7 @@ final class MongoCollection_BulkWriteTests: MongoSwiftTestCase { func testDeletes() throws { try self.createFixtures(4) - let requests: [WriteModel] = [ + let requests: [WriteModel] = [ .deleteOne(["_id": 1]), .deleteMany(["_id": ["$gt": 2]]) ] @@ -174,7 +174,7 @@ final class MongoCollection_BulkWriteTests: MongoSwiftTestCase { func testMixedOrderedOperations() throws { try self.createFixtures(3) - let requests: [WriteModel] = [ + let requests: [WriteModel] = [ .updateOne( filter: ["_id": ["$gt": 1]], update: ["$inc": ["x": 1]], @@ -209,14 +209,14 @@ final class MongoCollection_BulkWriteTests: MongoSwiftTestCase { } func testUnacknowledgedWriteConcern() throws { - let requests: [WriteModel] = [.insertOne(["_id": 1])] + let requests: [WriteModel] = [.insertOne(["_id": 1])] let options = BulkWriteOptions(writeConcern: try WriteConcern(w: .number(0))) let result = try self.coll.bulkWrite(requests, options: options) expect(result).to(beNil()) } private func createFixtures(_ n: Int) throws { - var documents: [Document] = [] + var documents: [BSONDocument] = [] for i in 1...n { documents.append(["_id": BSON(i), "x": BSON(Int("\(i)\(i)")!)]) diff --git a/Tests/MongoSwiftSyncTests/MongoCollection+IndexTests.swift b/Tests/MongoSwiftSyncTests/MongoCollection+IndexTests.swift index c8f10122e..2dd17d2f2 100644 --- a/Tests/MongoSwiftSyncTests/MongoCollection+IndexTests.swift +++ b/Tests/MongoSwiftSyncTests/MongoCollection+IndexTests.swift @@ -7,9 +7,9 @@ private var _client: MongoClient? final class MongoCollection_IndexTests: MongoSwiftTestCase { var collName: String = "" - var coll: MongoCollection! - let doc1: Document = ["_id": 1, "cat": "dog"] - let doc2: Document = ["_id": 2, "cat": "cat"] + var coll: MongoCollection! + let doc1: BSONDocument = ["_id": 1, "cat": "dog"] + let doc2: BSONDocument = ["_id": 2, "cat": "cat"] /// Set up the entire suite - run once before all tests override class func setUp() { diff --git a/Tests/MongoSwiftSyncTests/MongoCollectionTests.swift b/Tests/MongoSwiftSyncTests/MongoCollectionTests.swift index 83bf38c94..219c1e8fc 100644 --- a/Tests/MongoSwiftSyncTests/MongoCollectionTests.swift +++ b/Tests/MongoSwiftSyncTests/MongoCollectionTests.swift @@ -7,9 +7,9 @@ private var _client: MongoSwiftSync.MongoClient? final class MongoCollectionTests: MongoSwiftTestCase { var collName: String = "" - var coll: MongoSwiftSync.MongoCollection! - let doc1: Document = ["_id": 1, "cat": "dog"] - let doc2: Document = ["_id": 2, "cat": "cat"] + var coll: MongoSwiftSync.MongoCollection! + let doc1: BSONDocument = ["_id": 1, "cat": "dog"] + let doc2: BSONDocument = ["_id": 2, "cat": "cat"] /// Set up the entire suite - run once before all tests override class func setUp() { @@ -76,7 +76,7 @@ final class MongoCollectionTests: MongoSwiftTestCase { expect(try self.coll.countDocuments()).to(equal(2)) // try inserting a document without an ID - let docNoID: Document = ["x": 1] + let docNoID: BSONDocument = ["x": 1] // verify that an _id is returned in the InsertOneResult expect(try self.coll.insertOne(docNoID)?.insertedID).toNot(beNil()) // verify that the original document was not modified @@ -101,7 +101,7 @@ final class MongoCollectionTests: MongoSwiftTestCase { func testAggregate() throws { expect(try self.coll.aggregate([["$project": ["_id": 0, "cat": 1]]]).all()) - .to(equal([["cat": "dog"], ["cat": "cat"]] as [Document])) + .to(equal([["cat": "dog"], ["cat": "cat"]] as [BSONDocument])) } func testDrop() throws { @@ -132,10 +132,10 @@ final class MongoCollectionTests: MongoSwiftTestCase { func testInsertMany() throws { expect(try self.coll.countDocuments()).to(equal(2)) // try inserting a mix of documents with and without IDs to verify they are generated - let docNoId1: Document = ["x": 1] - let docNoId2: Document = ["x": 2] - let docId1: Document = ["_id": 10, "x": 8] - let docId2: Document = ["_id": 11, "x": 9] + let docNoId1: BSONDocument = ["x": 1] + let docNoId2: BSONDocument = ["x": 2] + let docId1: BSONDocument = ["_id": 10, "x": 8] + let docId2: BSONDocument = ["_id": 11, "x": 9] let res = try coll.insertMany([docNoId1, docNoId2, docId1, docId2]) @@ -153,10 +153,10 @@ final class MongoCollectionTests: MongoSwiftTestCase { expect(docNoId1).to(equal(["x": 1])) expect(docNoId2).to(equal(["x": 2])) - let newDoc1: Document = ["_id": .objectID()] - let newDoc2: Document = ["_id": .objectID()] - let newDoc3: Document = ["_id": .objectID()] - let newDoc4: Document = ["_id": .objectID()] + let newDoc1: BSONDocument = ["_id": .objectID()] + let newDoc2: BSONDocument = ["_id": .objectID()] + let newDoc3: BSONDocument = ["_id": .objectID()] + let newDoc4: BSONDocument = ["_id": .objectID()] let expectedResultOrdered = BulkWriteResult.new(insertedCount: 1, insertedIDs: [0: newDoc1["_id"]!]) let expectedErrorsOrdered = [ diff --git a/Tests/MongoSwiftSyncTests/MongoCursorTests.swift b/Tests/MongoSwiftSyncTests/MongoCursorTests.swift index e9c645114..a11a48074 100644 --- a/Tests/MongoSwiftSyncTests/MongoCursorTests.swift +++ b/Tests/MongoSwiftSyncTests/MongoCursorTests.swift @@ -3,9 +3,9 @@ import MongoSwift import Nimble import TestsCommon -private let doc1: Document = ["_id": 1, "x": 1] -private let doc2: Document = ["_id": 2, "x": 2] -private let doc3: Document = ["_id": 3, "x": 3] +private let doc1: BSONDocument = ["_id": 1, "x": 1] +private let doc2: BSONDocument = ["_id": 2, "x": 2] +private let doc3: BSONDocument = ["_id": 3, "x": 3] final class MongoCursorTests: MongoSwiftTestCase { func testNonTailableCursor() throws { @@ -74,7 +74,7 @@ final class MongoCursorTests: MongoSwiftTestCase { // for each doc we insert, check that it arrives in the cursor next, // and that the cursor is still alive afterward - let checkNextResult: (Document) throws -> Void = { doc in + let checkNextResult: (BSONDocument) throws -> Void = { doc in let result = cursor.tryNext() expect(result).toNot(beNil()) expect(try result?.get()).to(equal(doc)) @@ -152,7 +152,7 @@ final class MongoCursorTests: MongoSwiftTestCase { func testKillTailable() throws { let options = CreateCollectionOptions(capped: true, max: 3, size: 1000) try self.withTestNamespace(ns: self.getNamespace(suffix: "tail"), collectionOptions: options) { _, _, coll in - let docs: [Document] = [["_id": 1], ["_id": 2], ["_id": 3]] + let docs: [BSONDocument] = [["_id": 1], ["_id": 2], ["_id": 3]] _ = try coll.insertMany(docs) let cursor = try coll.find(options: FindOptions(cursorType: .tailable)) expect(cursor.isAlive()).to(beTrue()) @@ -160,7 +160,7 @@ final class MongoCursorTests: MongoSwiftTestCase { let queue = DispatchQueue(label: "tailable close") let allDocsLock = DispatchSemaphore(value: 0) - var allDocs: [Document] = [] + var allDocs: [BSONDocument] = [] var allError: Error? queue.async { defer { allDocsLock.signal() } diff --git a/Tests/MongoSwiftSyncTests/MongoDatabaseTests.swift b/Tests/MongoSwiftSyncTests/MongoDatabaseTests.swift index 50521f5dc..8fc1dd9a9 100644 --- a/Tests/MongoSwiftSyncTests/MongoDatabaseTests.swift +++ b/Tests/MongoSwiftSyncTests/MongoDatabaseTests.swift @@ -19,7 +19,7 @@ final class MongoDatabaseTests: MongoSwiftTestCase { let client = try MongoClient.makeTestClient() let db = client.db(Self.testDatabase) - let command: Document = ["create": .string(self.getCollectionName(suffix: "1"))] + let command: BSONDocument = ["create": .string(self.getCollectionName(suffix: "1"))] let res = try db.runCommand(command) expect(res["ok"]?.toDouble()).to(equal(1.0)) expect(try (Array(db.listCollections())).count).to(equal(1)) @@ -80,7 +80,7 @@ final class MongoDatabaseTests: MongoSwiftTestCase { let client = try MongoClient.makeTestClient() let db = client.db(Self.testDatabase) - let indexOpts: Document = + let indexOpts: BSONDocument = ["storageEngine": ["wiredTiger": ["configString": "access_pattern_hint=random"]]] // test non-view options @@ -110,7 +110,7 @@ final class MongoDatabaseTests: MongoSwiftTestCase { expect(collectionInfo).to(haveCount(3)) let fooInfo = CollectionSpecificationInfo.new(readOnly: false, uuid: UUID()) - let fooIndex = IndexModel(keys: ["_id": 1] as Document, options: IndexOptions(name: "_id_")) + let fooIndex = IndexModel(keys: ["_id": 1] as BSONDocument, options: IndexOptions(name: "_id_")) let expectedFoo = CollectionSpecification.new( name: "foo", type: .collection, diff --git a/Tests/MongoSwiftSyncTests/ReadPreferenceOperationTests.swift b/Tests/MongoSwiftSyncTests/ReadPreferenceOperationTests.swift index 4bfa34a27..95bcb4c47 100644 --- a/Tests/MongoSwiftSyncTests/ReadPreferenceOperationTests.swift +++ b/Tests/MongoSwiftSyncTests/ReadPreferenceOperationTests.swift @@ -15,7 +15,7 @@ final class ReadPreferenceOperationTests: MongoSwiftTestCase { defer { try? db.drop() } let coll = try db.createCollection(self.getCollectionName(suffix: "1")) - let command: Document = ["count": .string(coll.name)] + let command: BSONDocument = ["count": .string(coll.name)] // expect runCommand to return a success response when passing in a valid read preference let opts = RunCommandOptions(readPreference: .secondaryPreferred) diff --git a/Tests/MongoSwiftSyncTests/ReadWriteConcernOperationTests.swift b/Tests/MongoSwiftSyncTests/ReadWriteConcernOperationTests.swift index e7e9071d5..10d617b44 100644 --- a/Tests/MongoSwiftSyncTests/ReadWriteConcernOperationTests.swift +++ b/Tests/MongoSwiftSyncTests/ReadWriteConcernOperationTests.swift @@ -15,7 +15,7 @@ final class ReadWriteConcernOperationTests: MongoSwiftTestCase { defer { try? db.drop() } let coll = try db.createCollection(self.getCollectionName()) - let command: Document = ["count": .string(coll.name)] + let command: BSONDocument = ["count": .string(coll.name)] // run command with a valid readConcern let options1 = RunCommandOptions(readConcern: .local) @@ -102,7 +102,7 @@ final class ReadWriteConcernOperationTests: MongoSwiftTestCase { defer { try? db.drop() } var counter = 0 - func nextDoc() -> Document { + func nextDoc() -> BSONDocument { defer { counter += 1 } return ["x": BSON(integerLiteral: counter)] } @@ -112,7 +112,7 @@ final class ReadWriteConcernOperationTests: MongoSwiftTestCase { let wc2 = WriteConcern.serverDefault let wc3 = try WriteConcern(journal: true) - let command: Document = ["insert": .string(coll.name), "documents": [.document(nextDoc())]] + let command: BSONDocument = ["insert": .string(coll.name), "documents": [.document(nextDoc())]] // run command with a valid writeConcern let options1 = RunCommandOptions(writeConcern: wc1) @@ -161,7 +161,7 @@ final class ReadWriteConcernOperationTests: MongoSwiftTestCase { let coll2 = try db.createCollection(self.getCollectionName(suffix: "2")) defer { try? coll2.drop() } - let pipeline: [Document] = [["$out": .string("\(db.name).\(coll2.name)")]] + let pipeline: [BSONDocument] = [["$out": .string("\(db.name).\(coll2.name)")]] expect(try coll.aggregate(pipeline, options: AggregateOptions(writeConcern: wc1))).toNot(throwError()) expect(try coll.replaceOne( diff --git a/Tests/MongoSwiftSyncTests/RetryableWritesTests.swift b/Tests/MongoSwiftSyncTests/RetryableWritesTests.swift index c23703914..42094fc80 100644 --- a/Tests/MongoSwiftSyncTests/RetryableWritesTests.swift +++ b/Tests/MongoSwiftSyncTests/RetryableWritesTests.swift @@ -39,7 +39,7 @@ private struct RetryableWritesTestFile: Decodable { let runOn: [TestRequirement]? /// Data that should exist in the collection before running any of the tests. - let data: [Document] + let data: [BSONDocument] /// List of tests to run in this file. let tests: [RetryableWritesTest] diff --git a/Tests/MongoSwiftSyncTests/SpecTestRunner/FailPoint.swift b/Tests/MongoSwiftSyncTests/SpecTestRunner/FailPoint.swift index 296321133..2395e30cf 100644 --- a/Tests/MongoSwiftSyncTests/SpecTestRunner/FailPoint.swift +++ b/Tests/MongoSwiftSyncTests/SpecTestRunner/FailPoint.swift @@ -29,23 +29,23 @@ extension FailPointConfigured { /// - Note: if a fail point results in a connection being closed / interrupted, libmongoc built in debug mode will print /// a warning. internal struct FailPoint: Decodable { - private var failPoint: Document + private var failPoint: BSONDocument /// The fail point being configured. internal var name: String { self.failPoint["configureFailPoint"]?.stringValue ?? "" } - private init(_ document: Document) { + private init(_ document: BSONDocument) { self.failPoint = document } public init(from decoder: Decoder) throws { - self.failPoint = try Document(from: decoder) + self.failPoint = try BSONDocument(from: decoder) } internal func enable(on serverAddress: ServerAddress? = nil) throws { - var commandDoc = ["configureFailPoint": self.failPoint["configureFailPoint"]!] as Document + var commandDoc = ["configureFailPoint": self.failPoint["configureFailPoint"]!] as BSONDocument for (k, v) in self.failPoint { guard k != "configureFailPoint" else { continue @@ -111,9 +111,9 @@ internal struct FailPoint: Decodable { closeConnection: Bool? = nil, errorCode: Int? = nil, errorLabels: [String]? = nil, - writeConcernError: Document? = nil + writeConcernError: BSONDocument? = nil ) -> FailPoint { - var data: Document = [ + var data: BSONDocument = [ "failCommands": .array(failCommands.map { .string($0) }) ] if let close = closeConnection { @@ -129,7 +129,7 @@ internal struct FailPoint: Decodable { data["writeConcernError"] = .document(writeConcernError) } - let command: Document = [ + let command: BSONDocument = [ "configureFailPoint": "failCommand", "mode": mode.toBSON(), "data": .document(data) diff --git a/Tests/MongoSwiftSyncTests/SpecTestRunner/Match.swift b/Tests/MongoSwiftSyncTests/SpecTestRunner/Match.swift index 6960fb2e9..4f1a29aec 100644 --- a/Tests/MongoSwiftSyncTests/SpecTestRunner/Match.swift +++ b/Tests/MongoSwiftSyncTests/SpecTestRunner/Match.swift @@ -66,8 +66,8 @@ extension Array: Matchable where Element: Matchable { } /// Extension that adds MATCHES functionality to `Document`. -extension Document: Matchable { - internal func contentMatches(expected: Document) -> Bool { +extension BSONDocument: Matchable { + internal func contentMatches(expected: BSONDocument) -> Bool { for (eK, eV) in expected { // If the expected document has "key": null then the actual document must either have "key": null // or no reference to "key". diff --git a/Tests/MongoSwiftSyncTests/SpecTestRunner/SpecTest.swift b/Tests/MongoSwiftSyncTests/SpecTestRunner/SpecTest.swift index eb84a5ded..d7daf0d9d 100644 --- a/Tests/MongoSwiftSyncTests/SpecTestRunner/SpecTest.swift +++ b/Tests/MongoSwiftSyncTests/SpecTestRunner/SpecTest.swift @@ -7,7 +7,7 @@ import XCTest /// A struct containing the portions of a `CommandStartedEvent` the spec tests use for testing. internal struct TestCommandStartedEvent: Decodable, Matchable { - let command: Document + let command: BSONDocument let commandName: String @@ -21,7 +21,7 @@ internal struct TestCommandStartedEvent: Decodable, Matchable { case type = "command_started_event" } - internal init(from event: CommandStartedEvent, sessionIds: [Document: String]? = nil) { + internal init(from event: CommandStartedEvent, sessionIds: [BSONDocument: String]? = nil) { var command = event.command // If command started event has "lsid": Document(...), change the value to correpond to "session0", @@ -45,7 +45,7 @@ internal struct TestCommandStartedEvent: Decodable, Matchable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: TopLevelCodingKeys.self) let eventContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .type) - self.command = try eventContainer.decode(Document.self, forKey: .command) + self.command = try eventContainer.decode(BSONDocument.self, forKey: .command) if let commandName = try eventContainer.decodeIfPresent(String.self, forKey: .commandName) { self.commandName = commandName } else if let firstKey = self.command.keys.first { @@ -100,20 +100,20 @@ internal struct TestRequirement: Decodable { /// Enum representing the contents of deployment before a spec test has been run. internal enum TestData: Decodable { /// Data for multiple collections, with the name of the collection mapping to its contents. - case multiple([String: [Document]]) + case multiple([String: [BSONDocument]]) /// The contents of a single collection. - case single([Document]) + case single([BSONDocument]) public init(from decoder: Decoder) throws { - if let array = try? [Document](from: decoder) { + if let array = try? [BSONDocument](from: decoder) { self = .single(array) - } else if let document = try? Document(from: decoder) { - var mapping: [String: [Document]] = [:] + } else if let document = try? BSONDocument(from: decoder) { + var mapping: [String: [BSONDocument]] = [:] for (k, v) in document { guard let documentArray = v.arrayValue?.compactMap({ $0.documentValue }) else { throw DecodingError.typeMismatch( - [Document].self, + [BSONDocument].self, DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Expected array of documents, got \(v) instead" @@ -139,7 +139,7 @@ internal struct CollectionTestInfo: Decodable { let name: String? /// The documents found in the collection. - let data: [Document] + let data: [BSONDocument] } /// Struct representing an "outcome" defined in a spec test. @@ -192,7 +192,7 @@ extension SpecTestFile { ) try? database.drop() - func populateCollection(name: String, docs: [Document]) throws { + func populateCollection(name: String, docs: [BSONDocument]) throws { let collection = try database.createCollection(name) guard !docs.isEmpty else { @@ -336,7 +336,7 @@ extension SpecTest { sessions[session] = client.startSession(options: self.sessionOptions?[session]) } - var sessionIds = [Document: String]() + var sessionIds = [BSONDocument: String]() try monitor.captureEvents { for operation in self.operations { diff --git a/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/ChangeStreamOperations.swift b/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/ChangeStreamOperations.swift index 1dcbed052..5290f3f4d 100644 --- a/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/ChangeStreamOperations.swift +++ b/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/ChangeStreamOperations.swift @@ -12,7 +12,7 @@ struct Watch: TestOperation { } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions _: [String: ClientSession] ) throws -> TestOperationResult? { _ = try collection.watch() diff --git a/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/CollectionOperations.swift b/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/CollectionOperations.swift index 03186181f..dd8e93d6f 100644 --- a/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/CollectionOperations.swift +++ b/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/CollectionOperations.swift @@ -6,7 +6,7 @@ import TestsCommon struct Aggregate: TestOperation { let session: String? - let pipeline: [Document] + let pipeline: [BSONDocument] let options: AggregateOptions private enum CodingKeys: String, CodingKey { case session, pipeline } @@ -15,11 +15,11 @@ struct Aggregate: TestOperation { self.options = try AggregateOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.pipeline = try container.decode([Document].self, forKey: .pipeline) + self.pipeline = try container.decode([BSONDocument].self, forKey: .pipeline) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let cursor = @@ -30,7 +30,7 @@ struct Aggregate: TestOperation { struct CountDocuments: TestOperation { let session: String? - let filter: Document + let filter: BSONDocument let options: CountDocumentsOptions private enum CodingKeys: String, CodingKey { case session, filter } @@ -39,11 +39,11 @@ struct CountDocuments: TestOperation { self.options = try CountDocumentsOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = try container.decode(Document.self, forKey: .filter) + self.filter = try container.decode(BSONDocument.self, forKey: .filter) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { .int(try collection.countDocuments(self.filter, options: self.options, session: sessions[self.session ?? ""])) @@ -53,7 +53,7 @@ struct CountDocuments: TestOperation { struct Distinct: TestOperation { let session: String? let fieldName: String - let filter: Document? + let filter: BSONDocument? let options: DistinctOptions private enum CodingKeys: String, CodingKey { case session, fieldName, filter } @@ -63,11 +63,11 @@ struct Distinct: TestOperation { let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) self.fieldName = try container.decode(String.self, forKey: .fieldName) - self.filter = try container.decodeIfPresent(Document.self, forKey: .filter) + self.filter = try container.decodeIfPresent(BSONDocument.self, forKey: .filter) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = try collection.distinct( @@ -82,7 +82,7 @@ struct Distinct: TestOperation { struct Find: TestOperation { let session: String? - let filter: Document + let filter: BSONDocument let options: FindOptions private enum CodingKeys: String, CodingKey { case session, filter } @@ -91,11 +91,11 @@ struct Find: TestOperation { self.options = try FindOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = (try container.decodeIfPresent(Document.self, forKey: .filter)) ?? Document() + self.filter = (try container.decodeIfPresent(BSONDocument.self, forKey: .filter)) ?? BSONDocument() } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { try TestOperationResult( @@ -106,7 +106,7 @@ struct Find: TestOperation { struct FindOne: TestOperation { let session: String? - let filter: Document + let filter: BSONDocument let options: FindOneOptions private enum CodingKeys: String, CodingKey { case session, filter } @@ -115,11 +115,11 @@ struct FindOne: TestOperation { self.options = try FindOneOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = try container.decode(Document.self, forKey: .filter) + self.filter = try container.decode(BSONDocument.self, forKey: .filter) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let doc = try collection.findOne(self.filter, options: self.options, session: sessions[self.session ?? ""]) @@ -129,8 +129,8 @@ struct FindOne: TestOperation { struct UpdateOne: TestOperation { let session: String? - let filter: Document - let update: Document + let filter: BSONDocument + let update: BSONDocument let options: UpdateOptions private enum CodingKeys: String, CodingKey { case session, filter, update } @@ -139,12 +139,12 @@ struct UpdateOne: TestOperation { self.options = try UpdateOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = try container.decode(Document.self, forKey: .filter) - self.update = try container.decode(Document.self, forKey: .update) + self.filter = try container.decode(BSONDocument.self, forKey: .filter) + self.update = try container.decode(BSONDocument.self, forKey: .update) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = try collection.updateOne( @@ -159,8 +159,8 @@ struct UpdateOne: TestOperation { struct UpdateMany: TestOperation { let session: String? - let filter: Document - let update: Document + let filter: BSONDocument + let update: BSONDocument let options: UpdateOptions private enum CodingKeys: String, CodingKey { case session, filter, update } @@ -169,12 +169,12 @@ struct UpdateMany: TestOperation { self.options = try UpdateOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = try container.decode(Document.self, forKey: .filter) - self.update = try container.decode(Document.self, forKey: .update) + self.filter = try container.decode(BSONDocument.self, forKey: .filter) + self.update = try container.decode(BSONDocument.self, forKey: .update) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = try collection.updateMany( @@ -189,7 +189,7 @@ struct UpdateMany: TestOperation { struct DeleteMany: TestOperation { let session: String? - let filter: Document + let filter: BSONDocument let options: DeleteOptions private enum CodingKeys: String, CodingKey { case session, filter } @@ -198,11 +198,11 @@ struct DeleteMany: TestOperation { self.options = try DeleteOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = try container.decode(Document.self, forKey: .filter) + self.filter = try container.decode(BSONDocument.self, forKey: .filter) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = @@ -213,7 +213,7 @@ struct DeleteMany: TestOperation { struct DeleteOne: TestOperation { let session: String? - let filter: Document + let filter: BSONDocument let options: DeleteOptions private enum CodingKeys: String, CodingKey { case session, filter } @@ -222,11 +222,11 @@ struct DeleteOne: TestOperation { self.options = try DeleteOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = try container.decode(Document.self, forKey: .filter) + self.filter = try container.decode(BSONDocument.self, forKey: .filter) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = try collection.deleteOne(self.filter, options: self.options, session: sessions[self.session ?? ""]) @@ -236,10 +236,10 @@ struct DeleteOne: TestOperation { struct InsertOne: TestOperation { let session: String? - let document: Document + let document: BSONDocument func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = try collection.insertOne(self.document, session: sessions[self.session ?? ""]) @@ -249,11 +249,11 @@ struct InsertOne: TestOperation { struct InsertMany: TestOperation { let session: String? - let documents: [Document] + let documents: [BSONDocument] let options: InsertManyOptions? func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = try collection.insertMany( @@ -299,19 +299,19 @@ extension WriteModel: Decodable { case "deleteOne", "deleteMany": let options = try container.decode(DeleteModelOptions.self, forKey: .arguments) let args = try container.nestedContainer(keyedBy: DeleteKeys.self, forKey: .arguments) - let filter = try args.decode(Document.self, forKey: .filter) + let filter = try args.decode(BSONDocument.self, forKey: .filter) self = name == "deleteOne" ? .deleteOne(filter, options: options) : .deleteMany(filter, options: options) case "replaceOne": let options = try container.decode(ReplaceOneModelOptions.self, forKey: .arguments) let args = try container.nestedContainer(keyedBy: ReplaceOneKeys.self, forKey: .arguments) - let filter = try args.decode(Document.self, forKey: .filter) + let filter = try args.decode(BSONDocument.self, forKey: .filter) let replacement = try args.decode(CollectionType.self, forKey: .replacement) self = .replaceOne(filter: filter, replacement: replacement, options: options) case "updateOne", "updateMany": let options = try container.decode(UpdateModelOptions.self, forKey: .arguments) let args = try container.nestedContainer(keyedBy: UpdateKeys.self, forKey: .arguments) - let filter = try args.decode(Document.self, forKey: .filter) - let update = try args.decode(Document.self, forKey: .update) + let filter = try args.decode(BSONDocument.self, forKey: .filter) + let update = try args.decode(BSONDocument.self, forKey: .update) self = name == "updateOne" ? .updateOne(filter: filter, update: update, options: options) : .updateMany(filter: filter, update: update, options: options) @@ -329,11 +329,11 @@ extension WriteModel: Decodable { struct BulkWrite: TestOperation { let session: String? - let requests: [WriteModel] + let requests: [WriteModel] let options: BulkWriteOptions? func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = @@ -344,8 +344,8 @@ struct BulkWrite: TestOperation { struct FindOneAndUpdate: TestOperation { let session: String? - let filter: Document - let update: Document + let filter: BSONDocument + let update: BSONDocument let options: FindOneAndUpdateOptions private enum CodingKeys: String, CodingKey { case session, filter, update } @@ -354,12 +354,12 @@ struct FindOneAndUpdate: TestOperation { self.options = try FindOneAndUpdateOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = try container.decode(Document.self, forKey: .filter) - self.update = try container.decode(Document.self, forKey: .update) + self.filter = try container.decode(BSONDocument.self, forKey: .filter) + self.update = try container.decode(BSONDocument.self, forKey: .update) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let doc = try collection.findOneAndUpdate( @@ -374,7 +374,7 @@ struct FindOneAndUpdate: TestOperation { struct FindOneAndDelete: TestOperation { let session: String? - let filter: Document + let filter: BSONDocument let options: FindOneAndDeleteOptions private enum CodingKeys: String, CodingKey { case session, filter } @@ -383,11 +383,11 @@ struct FindOneAndDelete: TestOperation { self.options = try FindOneAndDeleteOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = try container.decode(Document.self, forKey: .filter) + self.filter = try container.decode(BSONDocument.self, forKey: .filter) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = try collection.findOneAndDelete( @@ -401,8 +401,8 @@ struct FindOneAndDelete: TestOperation { struct FindOneAndReplace: TestOperation { let session: String? - let filter: Document - let replacement: Document + let filter: BSONDocument + let replacement: BSONDocument let options: FindOneAndReplaceOptions private enum CodingKeys: String, CodingKey { case session, filter, replacement } @@ -411,12 +411,12 @@ struct FindOneAndReplace: TestOperation { self.options = try FindOneAndReplaceOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = try container.decode(Document.self, forKey: .filter) - self.replacement = try container.decode(Document.self, forKey: .replacement) + self.filter = try container.decode(BSONDocument.self, forKey: .filter) + self.replacement = try container.decode(BSONDocument.self, forKey: .replacement) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = try collection.findOneAndReplace( @@ -431,8 +431,8 @@ struct FindOneAndReplace: TestOperation { struct ReplaceOne: TestOperation { let session: String? - let filter: Document - let replacement: Document + let filter: BSONDocument + let replacement: BSONDocument let options: ReplaceOptions private enum CodingKeys: String, CodingKey { case session, filter, replacement } @@ -441,12 +441,12 @@ struct ReplaceOne: TestOperation { self.options = try ReplaceOptions(from: decoder) let container = try decoder.container(keyedBy: CodingKeys.self) self.session = try container.decodeIfPresent(String.self, forKey: .session) - self.filter = try container.decode(Document.self, forKey: .filter) - self.replacement = try container.decode(Document.self, forKey: .replacement) + self.filter = try container.decode(BSONDocument.self, forKey: .filter) + self.replacement = try container.decode(BSONDocument.self, forKey: .replacement) } func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let result = try collection.replaceOne( @@ -464,11 +464,11 @@ struct RenameCollection: TestOperation { let to: String func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let databaseName = collection.namespace.db - let cmd: Document = [ + let cmd: BSONDocument = [ "renameCollection": .string(databaseName + "." + collection.name), "to": .string(databaseName + "." + self.to) ] @@ -479,7 +479,7 @@ struct RenameCollection: TestOperation { struct Drop: TestOperation { func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions _: [String: ClientSession] ) throws -> TestOperationResult? { try collection.drop() @@ -489,7 +489,7 @@ struct Drop: TestOperation { struct ListIndexes: TestOperation { func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions _: [String: ClientSession] ) throws -> TestOperationResult? { try TestOperationResult(from: collection.listIndexes()) @@ -498,7 +498,7 @@ struct ListIndexes: TestOperation { struct ListIndexNames: TestOperation { func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions _: [String: ClientSession] ) throws -> TestOperationResult? { try .array(collection.listIndexNames().map(BSON.string)) @@ -507,7 +507,7 @@ struct ListIndexNames: TestOperation { struct EstimatedDocumentCount: TestOperation { func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions _: [String: ClientSession] ) throws -> TestOperationResult? { try .int(collection.estimatedDocumentCount()) @@ -517,10 +517,10 @@ struct EstimatedDocumentCount: TestOperation { struct CreateIndex: TestOperation { let session: String? let name: String - let keys: Document + let keys: BSONDocument func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? { let indexOptions = IndexOptions(name: self.name) diff --git a/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/DatabaseOperations.swift b/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/DatabaseOperations.swift index 859184125..4b5422565 100644 --- a/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/DatabaseOperations.swift +++ b/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/DatabaseOperations.swift @@ -41,7 +41,7 @@ struct ListCollectionNames: TestOperation { struct RunCommand: TestOperation { let session: String? - let command: Document + let command: BSONDocument let readPreference: ReadPreference? func execute(on database: MongoDatabase, sessions: [String: ClientSession]) throws -> TestOperationResult? { diff --git a/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/TestOperation.swift b/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/TestOperation.swift index 2a55c336d..8db2867bc 100644 --- a/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/TestOperation.swift +++ b/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/TestOperation.swift @@ -9,7 +9,7 @@ protocol TestOperation: Decodable { func execute(on database: MongoDatabase, sessions: [String: ClientSession]) throws -> TestOperationResult? func execute( - on collection: MongoCollection, + on collection: MongoCollection, sessions: [String: ClientSession] ) throws -> TestOperationResult? @@ -28,7 +28,7 @@ extension TestOperation { } func execute( - on _: MongoCollection, + on _: MongoCollection, sessions _: [String: ClientSession] ) throws -> TestOperationResult? { throw TestError(message: "\(type(of: self)) cannot execute on a collection") @@ -125,7 +125,7 @@ struct TestOperationDescription: Decodable { sessions: [String: ClientSession] ) throws { let database = client.db(dbName, options: self.databaseOptions) - var collection: MongoCollection? + var collection: MongoCollection? if let collName = collName { collection = database.collection(collName, options: self.collectionOptions) diff --git a/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/TestOperationResult.swift b/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/TestOperationResult.swift index 834af82e0..d7f9a87de 100644 --- a/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/TestOperationResult.swift +++ b/Tests/MongoSwiftSyncTests/SpecTestRunner/TestOperations/TestOperationResult.swift @@ -12,7 +12,7 @@ enum TestOperationResult: Decodable, Equatable, Matchable { case array([BSON]) /// Result of CRUD operations that return a single `Document` (e.g. `findOneAndDelete`). - case document(Document) + case document(BSONDocument) /// Result of CRUD operations whose result can be represented by a `BulkWriteResult` (e.g. `InsertOne`). case bulkWrite(BulkWriteResult) @@ -20,7 +20,7 @@ enum TestOperationResult: Decodable, Equatable, Matchable { /// Result of test operations that are expected to return an error (e.g. `CommandError`, `WriteError`). case error(ErrorResult) - public init?(from doc: Document?) { + public init?(from doc: BSONDocument?) { guard let doc = doc else { return nil } @@ -56,7 +56,7 @@ enum TestOperationResult: Decodable, Equatable, Matchable { self = .array(array) } else if let error = try? ErrorResult(from: decoder) { self = .error(error) - } else if let doc = try? Document(from: decoder) { + } else if let doc = try? BSONDocument(from: decoder) { self = .document(doc) } else { throw DecodingError.valueNotFound( diff --git a/Tests/MongoSwiftSyncTests/SyncAuthTests.swift b/Tests/MongoSwiftSyncTests/SyncAuthTests.swift index 1a54766ac..28156b94a 100644 --- a/Tests/MongoSwiftSyncTests/SyncAuthTests.swift +++ b/Tests/MongoSwiftSyncTests/SyncAuthTests.swift @@ -11,7 +11,7 @@ struct TestUser { let mechanisms: [MongoSwift.MongoCredential.Mechanism] /// A command to create this user. - var createCmd: Document { + var createCmd: BSONDocument { [ "createUser": .string(self.username), "pwd": .string(self.password), @@ -23,7 +23,7 @@ struct TestUser { func createCredential( authSource: String = "admin", mechanism: MongoCredential.Mechanism? = nil, - mechanismProperties: Document? = nil + mechanismProperties: BSONDocument? = nil ) -> MongoCredential { MongoCredential( username: self.username, diff --git a/Tests/MongoSwiftSyncTests/SyncChangeStreamTests.swift b/Tests/MongoSwiftSyncTests/SyncChangeStreamTests.swift index c98b9bad4..1afe7706a 100644 --- a/Tests/MongoSwiftSyncTests/SyncChangeStreamTests.swift +++ b/Tests/MongoSwiftSyncTests/SyncChangeStreamTests.swift @@ -20,24 +20,24 @@ internal enum ChangeStreamTarget: String, Decodable { _ client: MongoClient, _ database: String?, _ collection: String?, - _ pipeline: [Document], + _ pipeline: [BSONDocument], _ options: ChangeStreamOptions - ) throws -> ChangeStream { + ) throws -> ChangeStream { switch self { case .client: - return try client.watch(pipeline, options: options, withEventType: Document.self) + return try client.watch(pipeline, options: options, withEventType: BSONDocument.self) case .database: guard let database = database else { throw TestError(message: "missing db in watch") } - return try client.db(database).watch(pipeline, options: options, withEventType: Document.self) + return try client.db(database).watch(pipeline, options: options, withEventType: BSONDocument.self) case .collection: guard let collection = collection, let database = database else { throw TestError(message: "missing db or collection in watch") } return try client.db(database) .collection(collection) - .watch(pipeline, options: options, withEventType: Document.self) + .watch(pipeline, options: options, withEventType: BSONDocument.self) } } } @@ -79,7 +79,7 @@ internal enum ChangeStreamTestResult: Decodable { case error(code: Int, labels: [String]?) /// An array of event documents expected to be received from the change stream without error during the test. - case success([Document]) + case success([BSONDocument]) /// Top-level coding keys. Used for determining whether this result is a success or failure. internal enum CodingKeys: CodingKey { @@ -114,7 +114,7 @@ internal enum ChangeStreamTestResult: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.success) { - self = .success(try container.decode([Document].self, forKey: .success)) + self = .success(try container.decode([BSONDocument].self, forKey: .success)) } else { let nested = try container.nestedContainer(keyedBy: ErrorCodingKeys.self, forKey: .error) let code = try nested.decode(Int.self, forKey: .code) @@ -143,7 +143,7 @@ internal struct ChangeStreamTest: Decodable, FailPointConfigured { /// An array of additional aggregation pipeline stages to pass to the `watch` used to create the change stream for /// this test. - let changeStreamPipeline: [Document] + let changeStreamPipeline: [BSONDocument] /// Additional options to pass to the `watch` used to create the change stream for this test. let changeStreamOptions: ChangeStreamOptions @@ -187,7 +187,7 @@ internal struct ChangeStreamTest: Decodable, FailPointConfigured { _ = try changeStream.nextWithTimeout() fail("\(self.description) failed: expected error but got none while iterating") case let .success(events): - var seenEvents: [Document] = [] + var seenEvents: [BSONDocument] = [] for _ in 0.. Document in + let filteredStreamStage = { (pipeline: [BSONDocument]) -> BSONDocument in let stage = pipeline[0] let streamDoc = stage["$changeStream"]?.documentValue expect(streamDoc).toNot(beNil()) @@ -548,7 +548,7 @@ final class SyncChangeStreamTests: MongoSwiftTestCase { } // need to keep the stream alive so its deinit doesn't kill the cursor. - var changeStream: ChangeStream>? + var changeStream: ChangeStream>? let events = try captureCommandEvents(commandNames: ["killCursors"]) { client in try withTestNamespace(client: client) { _, coll in changeStream = @@ -581,7 +581,7 @@ final class SyncChangeStreamTests: MongoSwiftTestCase { } let monitor = client.addCommandMonitor() - var changeStream: ChangeStream>? + var changeStream: ChangeStream>? let options = ChangeStreamOptions(batchSize: 1) try monitor.captureEvents { @@ -710,8 +710,8 @@ final class SyncChangeStreamTests: MongoSwiftTestCase { let coll1 = db1.collection("coll1") let coll2 = db1.collection("coll2") - let doc1: Document = ["_id": 1, "a": 1] - let doc2: Document = ["_id": 2, "x": 123] + let doc1: BSONDocument = ["_id": 1, "a": 1] + let doc2: BSONDocument = ["_id": 2, "x": 123] try coll1.insertOne(doc1) try coll2.insertOne(doc2) @@ -735,7 +735,7 @@ final class SyncChangeStreamTests: MongoSwiftTestCase { defer { try? db2.drop() } let coll = db2.collection("coll3") - let doc3: Document = ["_id": 3, "y": 321] + let doc3: BSONDocument = ["_id": 3, "y": 321] try coll.insertOne(doc3) let change3 = try changeStream.nextWithTimeout() @@ -766,7 +766,7 @@ final class SyncChangeStreamTests: MongoSwiftTestCase { expect(try changeStream.tryNext()?.get()).to(beNil()) let coll = db.collection(self.getCollectionName(suffix: "1")) - let doc1: Document = ["_id": 1, "a": 1] + let doc1: BSONDocument = ["_id": 1, "a": 1] try coll.insertOne(doc1) // test that the change stream contains a change document for the `insert` operation @@ -801,7 +801,7 @@ final class SyncChangeStreamTests: MongoSwiftTestCase { let options = ChangeStreamOptions(fullDocument: .updateLookup) let changeStream = try coll.watch(options: options) - let doc: Document = ["_id": 1, "x": 1] + let doc: BSONDocument = ["_id": 1, "x": 1] try coll.insertOne(doc) // expect the change stream to contain a change document for the `insert` operation @@ -846,10 +846,10 @@ final class SyncChangeStreamTests: MongoSwiftTestCase { let coll = try db.createCollection(self.getCollectionName(suffix: "1")) let options = ChangeStreamOptions(fullDocument: .updateLookup) - let pipeline: [Document] = [["$match": ["fullDocument.a": 1]]] + let pipeline: [BSONDocument] = [["$match": ["fullDocument.a": 1]]] let changeStream = try coll.watch(pipeline, options: options) - let doc1: Document = ["_id": 1, "a": 1] + let doc1: BSONDocument = ["_id": 1, "a": 1] try coll.insertOne(doc1) let change1 = try changeStream.nextWithTimeout() @@ -903,11 +903,11 @@ final class SyncChangeStreamTests: MongoSwiftTestCase { } struct MyEventType: Codable, Equatable { - let id: Document + let id: BSONDocument let operation: String let fullDocument: MyFullDocumentType - let nameSpace: Document - let updateDescription: Document? + let nameSpace: BSONDocument + let updateDescription: BSONDocument? enum CodingKeys: String, CodingKey { case id = "_id", operation = "operationType", fullDocument, nameSpace = "ns", updateDescription @@ -928,7 +928,7 @@ final class SyncChangeStreamTests: MongoSwiftTestCase { // test that the change stream works on a collection when using withEventType let collChangeStream = try coll.watch(withEventType: MyEventType.self) - let doc: Document = ["_id": 1, "x": 1, "y": 2] + let doc: BSONDocument = ["_id": 1, "x": 1, "y": 2] try coll.insertOne(doc) let collChange = try collChangeStream.nextWithTimeout() diff --git a/Tests/MongoSwiftSyncTests/SyncMongoClientTests.swift b/Tests/MongoSwiftSyncTests/SyncMongoClientTests.swift index 2de4fd569..242e5ec4a 100644 --- a/Tests/MongoSwiftSyncTests/SyncMongoClientTests.swift +++ b/Tests/MongoSwiftSyncTests/SyncMongoClientTests.swift @@ -254,7 +254,7 @@ final class SyncMongoClientTests: MongoSwiftTestCase { db = nil expect(weakClientRef).to(beNil()) - var coll: MongoCollection? + var coll: MongoCollection? do { let client = try MongoClient.makeTestClient() weakClientRef = client diff --git a/Tests/MongoSwiftSyncTests/SyncTestUtils.swift b/Tests/MongoSwiftSyncTests/SyncTestUtils.swift index 9b98c4d1a..9d607bc9d 100644 --- a/Tests/MongoSwiftSyncTests/SyncTestUtils.swift +++ b/Tests/MongoSwiftSyncTests/SyncTestUtils.swift @@ -12,7 +12,7 @@ extension MongoSwiftTestCase { ns: MongoNamespace? = nil, MongoClientOptions: MongoClientOptions? = nil, collectionOptions: CreateCollectionOptions? = nil, - f: (MongoClient, MongoDatabase, MongoCollection) + f: (MongoClient, MongoDatabase, MongoCollection) throws -> T ) throws -> T { let client = try MongoClient.makeTestClient(options: MongoClientOptions) @@ -30,7 +30,7 @@ extension MongoSwiftTestCase { client: MongoClient, ns: MongoNamespace? = nil, options: CreateCollectionOptions? = nil, - _ f: (MongoDatabase, MongoCollection) throws -> T + _ f: (MongoDatabase, MongoCollection) throws -> T ) throws -> T { let ns = ns ?? self.getNamespace() @@ -39,7 +39,7 @@ extension MongoSwiftTestCase { } let database = client.db(ns.db) - let collection: MongoCollection + let collection: MongoCollection do { collection = try database.createCollection(collName, options: options) } catch let error as CommandError where error.code == 48 { @@ -195,7 +195,7 @@ extension ChangeStream { extension MongoSwiftSync.ClientSession { internal var active: Bool { self.asyncSession.active } - internal var id: Document? { self.asyncSession.id } + internal var id: BSONDocument? { self.asyncSession.id } internal var pinnedServerAddress: ServerAddress? { self.asyncSession.pinnedServerAddress } diff --git a/Tests/MongoSwiftTests/AsyncTestUtils.swift b/Tests/MongoSwiftTests/AsyncTestUtils.swift index 25f42209e..aeb4b08cb 100644 --- a/Tests/MongoSwiftTests/AsyncTestUtils.swift +++ b/Tests/MongoSwiftTests/AsyncTestUtils.swift @@ -81,7 +81,7 @@ extension MongoSwiftTestCase { client: MongoClient, ns: MongoNamespace? = nil, options: CreateCollectionOptions? = nil, - _ f: (MongoDatabase, MongoCollection) throws -> T + _ f: (MongoDatabase, MongoCollection) throws -> T ) throws -> T { let ns = ns ?? self.getNamespace() @@ -90,7 +90,7 @@ extension MongoSwiftTestCase { } let database = client.db(ns.db) - let collection: MongoCollection + let collection: MongoCollection do { collection = try database.createCollection(collName, options: options).wait() } catch let error as CommandError where error.code == 48 { @@ -108,7 +108,7 @@ extension MongoSwiftTestCase { internal func withTestNamespace( ns: MongoNamespace? = nil, collectionOptions: CreateCollectionOptions? = nil, - _ f: (MongoClient, MongoDatabase, MongoCollection) throws -> T + _ f: (MongoClient, MongoDatabase, MongoCollection) throws -> T ) throws -> T { try self.withTestClient { client in try self.withTestNamespace(client: client, ns: ns, options: collectionOptions) { db, coll in diff --git a/Tests/MongoSwiftTests/ChangeStreamTests.swift b/Tests/MongoSwiftTests/ChangeStreamTests.swift index 7042b14f2..52a980ed4 100644 --- a/Tests/MongoSwiftTests/ChangeStreamTests.swift +++ b/Tests/MongoSwiftTests/ChangeStreamTests.swift @@ -137,7 +137,7 @@ final class ChangeStreamTests: MongoSwiftTestCase { } var count = 0 - let increment: (ChangeStreamEvent) -> Void = { _ in count += 1 } + let increment: (ChangeStreamEvent) -> Void = { _ in count += 1 } try self.withTestClient { client in let db = client.db(Self.testDatabase) diff --git a/Tests/MongoSwiftTests/ClientSessionTests.swift b/Tests/MongoSwiftTests/ClientSessionTests.swift index df4bc2e41..77681976c 100644 --- a/Tests/MongoSwiftTests/ClientSessionTests.swift +++ b/Tests/MongoSwiftTests/ClientSessionTests.swift @@ -31,7 +31,7 @@ final class ClientSessionTests: MongoSwiftTestCase { // test session is closed when withSession is completed var escapedSession: ClientSession? - let res2: EventLoopFuture = client.withSession { session in + let res2: EventLoopFuture = client.withSession { session in escapedSession = session return db.runCommand(["isMaster": 1], session: session) } diff --git a/Tests/MongoSwiftTests/DNSSeedlistTests.swift b/Tests/MongoSwiftTests/DNSSeedlistTests.swift index b1a81e722..f9ccdc030 100644 --- a/Tests/MongoSwiftTests/DNSSeedlistTests.swift +++ b/Tests/MongoSwiftTests/DNSSeedlistTests.swift @@ -13,10 +13,10 @@ struct DNSSeedlistTestCase: Decodable { /// The discovered topology's list of hosts once SDAM completes a scan. let hosts: [ServerAddress] /// The parsed connection string options as discovered from URI and TXT records. - let options: Document? + let options: BSONDocument? /// Additional options present in the connection string URI such as Userinfo (as user and password), and Auth /// database (as auth_database). - let parsedOptions: Document? + let parsedOptions: BSONDocument? /// Indicates that the parsing of the URI, or the resolving or contents of the SRV or TXT records included errors. let error: Bool? /// A comment to indicate why a test would fail. diff --git a/Tests/MongoSwiftTests/MongoClientTests.swift b/Tests/MongoSwiftTests/MongoClientTests.swift index 4ffaa6752..328622b07 100644 --- a/Tests/MongoSwiftTests/MongoClientTests.swift +++ b/Tests/MongoSwiftTests/MongoClientTests.swift @@ -84,7 +84,7 @@ final class MongoClientTests: MongoSwiftTestCase { // tests that when no connections are available operations won't block the thread pool. func testResubmittingToThreadPool() throws { try self.withTestNamespace { _, _, coll in - let docs: [Document] = (1...10).map { ["x": .int32($0)] } + let docs: [BSONDocument] = (1...10).map { ["x": .int32($0)] } _ = try coll.insertMany(docs).wait() let cursors = try (1...100).map { _ in try coll.find().wait() } diff --git a/Tests/MongoSwiftTests/MongoCursorTests.swift b/Tests/MongoSwiftTests/MongoCursorTests.swift index 757e00248..9f25c0d80 100644 --- a/Tests/MongoSwiftTests/MongoCursorTests.swift +++ b/Tests/MongoSwiftTests/MongoCursorTests.swift @@ -5,9 +5,9 @@ import NIO import NIOConcurrencyHelpers import TestsCommon -private let doc1: Document = ["_id": 1, "x": 1] -private let doc2: Document = ["_id": 2, "x": 2] -private let doc3: Document = ["_id": 3, "x": 3] +private let doc1: BSONDocument = ["_id": 1, "x": 1] +private let doc2: BSONDocument = ["_id": 2, "x": 2] +private let doc3: BSONDocument = ["_id": 3, "x": 3] final class AsyncMongoCursorTests: MongoSwiftTestCase { override func setUp() { @@ -57,14 +57,14 @@ final class AsyncMongoCursorTests: MongoSwiftTestCase { let collOptions = CreateCollectionOptions(capped: true, max: 3, size: 1000) try self.withTestNamespace(collectionOptions: collOptions) { _, _, coll in let cursorOpts = FindOptions(batchSize: 1, cursorType: .tailableAwait, maxAwaitTimeMS: 10) - _ = try coll.insertMany([Document()]).wait() + _ = try coll.insertMany([BSONDocument()]).wait() let cursor = try coll.find(options: cursorOpts).wait() let doc = try cursor.next().wait() expect(doc).toNot(beNil()) let future = cursor.next() - _ = try coll.insertMany([Document()]).wait() + _ = try coll.insertMany([BSONDocument()]).wait() expect(try future.wait()).toNot(beNil()) expect(try cursor.tryNext().wait()).to(beNil()) @@ -97,7 +97,7 @@ final class AsyncMongoCursorTests: MongoSwiftTestCase { // for each doc we insert, check that it arrives in the cursor next, // and that the cursor is still alive afterward - let checkNextResult: (Document) throws -> Void = { doc in + let checkNextResult: (BSONDocument) throws -> Void = { doc in let results = try cursor.toArray().wait() expect(results).to(haveCount(1)) expect(results[0]).to(equal(doc)) @@ -212,7 +212,7 @@ final class AsyncMongoCursorTests: MongoSwiftTestCase { func testForEach() throws { let count = NIOAtomic.makeAtomic(value: 0) - let increment: (Document) -> Void = { _ in + let increment: (BSONDocument) -> Void = { _ in _ = count.add(1) } diff --git a/Tests/MongoSwiftTests/ReadWriteConcernSpecTests.swift b/Tests/MongoSwiftTests/ReadWriteConcernSpecTests.swift index 815445945..a96e50e1f 100644 --- a/Tests/MongoSwiftTests/ReadWriteConcernSpecTests.swift +++ b/Tests/MongoSwiftTests/ReadWriteConcernSpecTests.swift @@ -7,7 +7,7 @@ extension WriteConcern { /// Initialize a new `WriteConcern` from a `Document`. We can't /// use `decode` because the format is different in spec tests /// ("journal" instead of "j", etc.) - fileprivate init(_ doc: Document) throws { + fileprivate init(_ doc: BSONDocument) throws { let j = doc["journal"]?.boolValue var w: W? @@ -32,10 +32,10 @@ class ReadWriteConcernSpecTests: MongoSwiftTestCase { let testFiles = try retrieveSpecTestFiles( specName: "read-write-concern", subdirectory: "connection-string", - asType: Document.self + asType: BSONDocument.self ) for (_, asDocument) in testFiles { - let tests: [Document] = asDocument["tests"]!.arrayValue!.compactMap { $0.documentValue } + let tests: [BSONDocument] = asDocument["tests"]!.arrayValue!.compactMap { $0.documentValue } for test in tests { let description: String = try test.get("description") // skipping because C driver does not comply with these; see CDRIVER-2621 @@ -73,7 +73,7 @@ class ReadWriteConcernSpecTests: MongoSwiftTestCase { let testFiles = try retrieveSpecTestFiles( specName: "read-write-concern", subdirectory: "document", - asType: Document.self + asType: BSONDocument.self ) for (_, asDocument) in testFiles { @@ -86,7 +86,7 @@ class ReadWriteConcernSpecTests: MongoSwiftTestCase { let isDefault: Bool = try test.get("isServerDefault") expect(rc.isDefault).to(equal(isDefault)) - let expected: Document = try test.get("readConcernDocument") + let expected: BSONDocument = try test.get("readConcernDocument") if expected == [:] { expect(try encoder.encode(rc)).to(beNil()) } else { @@ -102,7 +102,7 @@ class ReadWriteConcernSpecTests: MongoSwiftTestCase { let isDefault: Bool = try test.get("isServerDefault") expect(wc.isDefault).to(equal(isDefault)) - var expected: Document = try test.get("writeConcernDocument") + var expected: BSONDocument = try test.get("writeConcernDocument") if expected == [:] { expect(try encoder.encode(wc)).to(beNil()) } else {