mongo-swift-driver

The official MongoDB driver for Swift

APACHE-2.0 License

Stars
339
Committers
28

Bot releases are hidden (Show)

mongo-swift-driver - 1.3.1 Latest Release

Published by kmahar over 2 years ago

This release corrects a minor error that occurred during the 1.3.0 release process, where v1.3.0 was inadvertently tagged before the version string the driver reports in its handshake with the server was updated. As a result, "1.3.0-beta.1" would be incorrectly reported as the driver version in MongoDB server logs.

There are no other changes from the 1.3.0 release.

mongo-swift-driver - 1.3.0

Published by kmahar over 2 years ago

We are pleased to announce the GA of our 1.3.0 release, which contains no changes from our last pre-release, 1.3.0-beta.1.

This release most notably adds the following features:

Async/Await APIs

This release adds a new async/await version of our entire API surface to allow you to start using the driver with Swift concurrency!

For example, to create a collection and insert a document:

let collection = try await db.createCollection("foo")
try await collection.insertOne(["x": 1])

We’ve also made MongoCursor and ChangeStream conform to AsyncSequence. This protocol provides a number of convenience methods for working with sequences, and enables you to consume their values via a for loop, for example:

for try await doc in try await collection.find() {
    print(doc)
}

We’ve written a blog post that discusses this in more detail, and have also updated all of our documentation and our Vapor example project to use Swift concurrency to help you get started using these new APIs.

These APIs are available for Swift 5.5.2+ developers on Linux and macOS 10.15+.

Please feel free to file an issue if you run into any problems or have suggestions for improving the new APIs!

New MongoConnectionString type

This release also adds a new MongoConnectionString type modeling a MongoDB connection string, and moves the driver logic for parsing and validating a connection string, which was previously handled by the C driver, into the Swift layer.

This type conforms to LosslessStringConvertible and so can be initialized via and converted to a String , and has mutable properties to allow setting/changing values. For example:

var connStr = MongoConnectionString("mongodb://localhost:27017")
connStr.readConcern = .local
print(connStr) // prints "mongodb://localhost:27017/?readconcernlevel=local"

You can now use this type to initialize a MongoClient:

var connStr = MongoConnectionString("mongodb://localhost:27017")
connStr.readConcern = .local
let client = try MongoClient(connStr, using: yourEventLoopGroup)

Included Tickets

Below are a selected list of tickets with user-facing implications; for a full list of completed tickets see this Jira query.

New Feature

  • [ SWIFT-1160 ] - Introduce new MongoConnectionString type
  • [ SWIFT-1161 ] - MongoConnectionString authentication options support
  • [ SWIFT-1162 ] - MongoConnectionString TLS options support
  • [ SWIFT-1163 ] - MongoConnectionString non-auth, non-TLS options support
  • [ SWIFT-1165 ] - Initialization of MongoClient via MongoConnectionString
  • [ SWIFT-1174 ] - MongoConnectionString Unix domain socket support
  • [ SWIFT-1384 ] - Support ‘let’ option for multiple CRUD commands
  • [ SWIFT-1389 ] - Implement MongoClient and ClientSession async/await APIs
  • [ SWIFT-1390 ] - Implement MongoDatabase async/await API methods
  • [ SWIFT-1391 ] - Implement MongoCollection async/await API methods
  • [ SWIFT-1392 ] - Make MongoCursor and ChangeStream conform to AsyncSequence
  • [ SWIFT-1405 ] - Implement description for MongoConnectionString
  • [ SWIFT-1407 ] - Support ipv4 address parsing in MongoConnectionString

Improvement

  • [ SWIFT-1451 ] - Use -cross-module-optimization flag in Vapor example

Task

  • [ SWIFT-1493 ] - Update vendored libmongoc to 1.21.0
mongo-swift-driver - 1.3.0-beta.1

Published by kmahar over 2 years ago

We are pleased to announce the first beta for our 1.3.0 driver release, which follows two previous alphas. We have recently gained the capability to test our new async APIs on macOS in CI (previously, we only could on Linux) and are moving toward a stable 1.3.0 GA release in the near future.

Compared to the previous pre-release 1.3.0-alpha.2, this release contains a single bug fix, for SWIFT-1510.

The bug was that, although we document that MongoCursor, ChangeStream and ClientSession will be automatically cleaned up upon deinit on any platform and Swift version where concurrency is available, this automatic cleanup would not actually occur on macOS < 12.

Included Tickets

  • SWIFT-1510: Update #available statements for automatic cleanup logic in deinits to macOS 10.15+
mongo-swift-driver - 1.3.0-alpha.2

Published by kmahar over 2 years ago

We are pleased to announce the second alpha of our 1.3.0 release.

The primary changes in this release from the previous alpha:

  • The minimum Swift version required to use the new async APIs has increased to Swift 5.5.2 from Swift 5.5.0, and the new async APIs are now available on macOS 10.15+, rather than macOS 12+. Thank you to @atultw for contributing these changes!
  • The driver’s vendors copy of libmongoc has been updated from version 1.19.2 to version 1.21.0. Please see the libmongoc release notes for details on the included changes.

Contributors

Thanks to everyone who contributed to this release!

  • @atultw
  • @isabelatkinson
  • @kmahar
mongo-swift-driver - 1.3.0-alpha.1

Published by kmahar over 2 years ago

We are pleased to announce the first alpha of our 1.3.0 release, containing the following new features:

Async/Await APIs

This release adds a new async/await version of our entire API surface to allow you to start using the driver with Swift concurrency!

For example, to create a collection and insert a document:

let collection = try await db.createCollection("foo")
try await collection.insertOne(["x": 1])

We’ve also made MongoCursor and ChangeStream conform to AsyncSequence. This protocol provides a number of convenience methods for working with sequences, and enables you to consume their values via a for loop, for example:

for try await doc in try await collection.find() {
    print(doc)
}

We’ve written a blog post that discusses this in more detail, and have also updated all of our documentation and our Vapor example project to use Swift concurrency to help you get started using these new APIs.

Currently, these APIs are available for Swift 5.5.0+ developers on Linux and macOS 12. For future alpha releases we are exploring making these APIs available on older macOS versions as well where concurrency has recently become available.

Please feel free to file an issue if you run into any problems or have suggestions for improving the new APIs!

New MongoConnectionString type

This release also adds a new MongoConnectionString type modeling a MongoDB connection string, and moves the driver logic for parsing and validating a connection string, which was previously handled by the C driver, into the Swift layer.

This type conforms to LosslessStringConvertible and so can be initialized via and converted to a String , and has mutable properties to allow setting/changing values. For example:

var connStr = MongoConnectionString("mongodb://localhost:27017")
connStr.readConcern = .local
print(connStr) // prints "mongodb://localhost:27017/?readconcernlevel=local"

You can now use this type to initialize a MongoClient:

var connStr = MongoConnectionString("mongodb://localhost:27017")
connStr.readConcern = .local
let client = try MongoClient(connStr, using: yourEventLoopGroup)

Included Tickets

Below are a selected list of tickets with user-facing implications; for a full list of completed tickets see this Jira query.

New Feature

  • [ SWIFT-1160 ] - Introduce new MongoConnectionString type
  • [ SWIFT-1161 ] - MongoConnectionString authentication options support
  • [ SWIFT-1162 ] - MongoConnectionString TLS options support
  • [ SWIFT-1163 ] - MongoConnectionString non-auth, non-TLS options support
  • [ SWIFT-1165 ] - Initialization of MongoClient via MongoConnectionString
  • [ SWIFT-1174 ] - MongoConnectionString Unix domain socket support
  • [ SWIFT-1384 ] - Support ‘let’ option for multiple CRUD commands
  • [ SWIFT-1389 ] - Implement MongoClient and ClientSession async/await APIs
  • [ SWIFT-1390 ] - Implement MongoDatabase async/await API methods
  • [ SWIFT-1391 ] - Implement MongoCollection async/await API methods
  • [ SWIFT-1392 ] - Make MongoCursor and ChangeStream conform to AsyncSequence
  • [ SWIFT-1405 ] - Implement description for MongoConnectionString
  • [ SWIFT-1407 ] - Support ipv4 address parsing in MongoConnectionString

Improvement

  • [ SWIFT-1451 ] - Use -cross-module-optimization flag in Vapor example
mongo-swift-driver - v1.2.0

Published by kmahar almost 3 years ago

We are pleased to announce the 1.2.0 release of the Swift driver.

This release most notably adds support for the following features:

MongoDB Versioned API

MongoDB 5.0 introduced supported for the versioned API, which will make it much easier for users to upgrade their server versions without experiencing backward-breaking changes.

To specify an API version for your application, provide a version via MongoClientOptions (currently, the only supported API version is 1):

let opts = MongoClientOptions(
    serverAPI: MongoServerAPI(version: .v1)
)

// Create an async client
let client = try MongoClient("mongodb://localhost:27017", using: myEventLoopGroup, options: opts)

// Or, create a sync client
let client = try MongoClient("mongodb://localhost:27017", options: opts)

Serverless MongoDB Support / Load Balancer Support

This release adds support for using the driver with Serverless MongoDB, which is currently in preview.

This is enabled via new support for connecting to a MongoDB cluster behind a TCP load balancer, which is supported via the loadBalanced connection string option or by setting the loadBalanced property on MongoClientOptions.

MongoDB 5.0 Support

This release adds full support for using new MongoDB 5.0 features, including creating and working with time series collections as well as extended support for the “snapshot” read concern; see the MongoDB 5.0 release notes for more details.

OCSP Support

The driver previously had implicit support for the Online Certificate Status Protocol (OCSP) via the underlying C driver, however as part of this release we have added explicit testing for this from Swift along with support for configuring it programmatically via MongoClientOptions, using the tlsDisableCertificateRevocationCheck and tlsDisableOCSPEndpointCheck options.

Please see our TLS Guide for more information.

Below are a selected list of tickets with user-facing implications; for a full list of completed tickets see this Jira query.

Included Tickets

Bug

  • SWIFT-1322 - listCollections does not respect batchSize option
  • SWIFT-1347 - ClientSession.pinnedServerAddress leaks memory (in tests only)

New Feature

  • SWIFT-787 - OCSP Support
  • SWIFT-1025 - Versioned MongoDB API for Drivers
  • SWIFT-1094 - Load Balancer Support
  • SWIFT-797 - Allow hinting the delete command
  • SWIFT-801 - support ability to pass hint to update
  • SWIFT-788 - Allow passing hint to findAndModify update and replace operations
  • SWIFT-904 - Add connectTimeoutMS option to MongoClientOptions
  • SWIFT-1157 - Implement ExpressibleByXLiteral for IndexHint
  • SWIFT-1102 - Snapshot reads on Secondaries
  • SWIFT-560 - Add the ability to specify a pipeline to an update command
  • SWIFT-1108 - Time-series Collections
  • SWIFT-1225 - Support ‘let’ option for aggregate command
  • SWIFT-1100 - Support truncatedArrays field in ChangeStream update descriptions
  • SWIFT-1307 - Expose serviceId in command monitoring events

Improvement

  • SWIFT-910 - Lift restriction on authSource without credentials
  • SWIFT-1099 - Change estimatedDocumentCount() to use the $collStats Agg Stage Instead of Count Command
  • SWIFT-1107 - Mitigate pain of using field names with dots and dollars
  • SWIFT-1211 - Use “hello” command for monitoring if supported
  • SWIFT-1173 - Use “hello” command when API version is declared

Task

  • SWIFT-1256 - Vendor libmongoc 1.19.0
  • SWIFT-1363 - Vendor libmongoc 1.19.1
  • SWIFT-1409 - Vendor libmongoc 1.19.2
  • SWIFT-1224 - Increase maxWireVersion for MongoDB 5.0

Contributors

Thanks to everyone who contributed to this release!

  • @agolin95
  • @bynn
  • @isabelatkinson
  • @kmahar
  • @patrickfreed
mongo-swift-driver - 1.2.0-beta.1

Published by kmahar about 3 years ago

We are pleased to announce our first beta release for the upcoming 1.2.0 release of the Swift driver. We would love for you to try it out!

This release most notably adds support for the following features:

MongoDB Versioned API

MongoDB 5.0 introduced supported for the versioned API, which will make it much easier for users to upgrade their server versions without experiencing backward-breaking changes.

To specify an API version for your application, provide a version via MongoClientOptions (currently, the only supported API version is 1):

let opts = MongoClientOptions(
    serverAPI: MongoServerAPI(version: .v1)
)

// Create an async client
let client = try MongoClient("mongodb://localhost:27017", using: myEventLoopGroup, options: opts)

// Or, create a sync client
let client = try MongoClient("mongodb://localhost:27017", options: opts)

Serverless MongoDB Support / Load Balancer Support

This release adds support for using the driver with Serverless MongoDB, which is currently in preview.

This is enabled via new support for connecting to a MongoDB cluster behind a TCP load balancer, which is supported via the loadBalanced connection string option or by setting the loadBalanced property on MongoClientOptions.

OCSP Support

The driver previously had implicit support for the Online Certificate Status Protocol (OCSP) via the underlying C driver, however as part of this release we have added explicit testing for this from Swift along with support for configuring it programmatically via MongoClientOptions, using the tlsDisableCertificateRevocationCheck and tlsDisableOCSPEndpointCheck options.

Please see our TLS Guide for more information.

Below are a selected list of tickets with user-facing implications; for a full list of completed tickets see this Jira query.

Included Tickets

Bug

  • SWIFT-1322 - listCollections does not respect batchSize option
  • SWIFT-1347 - ClientSession.pinnedServerAddress leaks memory (in tests only)

New Feature

  • SWIFT-787 - OCSP Support
  • SWIFT-1025 - Versioned MongoDB API for Drivers
  • SWIFT-1094 - Load Balancer Support
  • SWIFT-797 - Allow hinting the delete command
  • SWIFT-801 - support ability to pass hint to update
  • SWIFT-904 - Add connectTimeoutMS option to MongoClientOptions
  • SWIFT-1157 - Implement ExpressibleByXLiteral for IndexHint
  • SWIFT-788 - Allow passing hint to findAndModify update and replace operations

Improvement

  • SWIFT-910 - Lift restriction on authSource without credentials
  • SWIFT-1099 - Change estimatedDocumentCount() to use the $collStats Agg Stage Instead of Count Command
  • SWIFT-1100 - Implement change stream oplog parsing code for delta oplog entries
  • SWIFT-1107 - Mitigate pain of using field names with dots and dollars
  • SWIFT-1224 - Bump maxWireVersion for MongoDB 5.0
  • SWIFT-1307 - Expose serviceId in command monitoring events

Task

  • SWIFT-1256 - Vendor libmongoc 1.19.0
mongo-swift-driver - 1.1.1

Published by kmahar over 3 years ago

The MongoDB Swift driver team is pleased to announce our 1.1.1 release.

This patch release is a recommended upgrade which updates the vendored MongoDB C driver code from version 1.17.4 to 1.17.7 and thus pulls in a number of bug fixes. You can find the details of the fixes included in the following C driver release notes: 1.17.7, 1.17.6, 1.17.5.

mongo-swift-driver - 1.1.0

Published by kmahar over 3 years ago

The MongoDB Swift driver team is pleased to announce our 1.1.0 release.

Highlights

New BSON Library

Last week, we released version 3.0.0 of SwiftBSON. This is a brand new, pure Swift BSON library. While the internals are all-new, the API is identical to the one that previously lived in the driver with a few additions as described in the release notes, and we've now switched the driver to depend on this library.
For convenience, we re-export all symbols from SwiftBSON from MongoSwift and MongoSwiftSync, so you can continue to use BSON types as if they were defined directly in the driver with no breaking changes.

Event Loop "Binding" for Core Async Driver Types

Previously, there was no way to specify at the API level a particular EventLoop that a core driver type (client, database, or collection) should return EventLoopFutures on. We've now introduced a special EventLoopBoundClient type to support this for clients, and added support directly to MongoDatabase and MongoCollection for it as well. Please see our Multithreaded Usage Guide for more details.

Aggregation Improvements

We've added a new helper method to MongoDatabase via SWIFT-577 to support performing database-level aggregations.

We've also added support via SWIFT-506 to both MongoDatabase.aggregate and MongoCollection.aggregate for specifying a Codable type that the returned MongoCursor should decode resulting documents into. Previously, these methods could only return MongoCursor<BSONDocument>s. For example:

/// Collection type.
struct Person: Codable {
    let _id: BSONObjectID
    let name: String
    let age: Int
    let favoriteColor: String
}

let coll = db.collection("people", withType: Person.self)
try coll.insertMany([
    Person(_id: BSONObjectID(),  name: "Kaitlin", age: 26, favoriteColor: "blue")
    Person(_id: BSONObjectID(),  name: "Buffalo", age: 27, favoriteColor: "green")
]).wait()


/// Transformed aggregation output type.
struct PersonOutput: Codable {
    let name: String
    let age: Int
}

let resultsFuture = coll.aggregate([
    ["$project": ["age": 1, "name": 1, "_id": 0]] // only keep the age and name fields
], withOutputType: PersonOutput.self).flatMap { cursor in
    cursor.toArray()
}

// prints [PersonOutput(name: "Kaitlin", age: 26), PersonOutput(name: "Buffalo", age: 27)]
print(try resultsFuture.wait())

MongoClientOptions Improvements

Previously, a number of driver options were only specifiable via connection string, and not supported via MongoClientOptions. We've now added support for specifying a number of options via the options struct as well, such as replicaSet and serverSelectionTimeoutMS.

Included Tickets

Bug

  • [SWIFT-957] - DecodingError when encountering dropDatabase event in change stream
  • [SWIFT-958] - Ensure nil is returned from cursor before returning LogicError
  • [SWIFT-969] - Manually clean up mongoc_uri_t when ConnectionString options validation fails
  • [SWIFT-974] - Cursor gets leaked in findOne after DecodingError
  • [SWIFT-1045] - MongoClient initializer performs blocking DNS lookup

New Feature

  • [SWIFT-481] - Support index all paths
  • [SWIFT-828] - Hidden Indexes
  • [SWIFT-577] - Add database aggregation helper
  • [SWIFT-1028] - Create EventLoopBoundMongoClient type
  • [SWIFT-1029] - Implement EventLoop binding support for database and collection objects
  • [SWIFT-1030] - Implement EventLoop binding support for change streams and cursors
  • [SWIFT-1031] - Implement EventLoop binding support for sessions
  • [SWIFT-459] - Add a renameCollection helper
  • [SWIFT-519] - Support startAfter option for change streams
  • [SWIFT-506] - Allow users to specify the output type of an aggregation

Task

  • [SWIFT-734] - Maintain multiple versions of the documentation
  • [SWIFT-791] - Support shorter SCRAM conversation
  • [SWIFT-854] - Organize API documentation in a more useful way
  • [SWIFT-936] - Update the driver to use the new BSON library
  • [SWIFT-1010] - Test against Swift 5.3 + Linux on Evergreen
  • [SWIFT-1034] - Update readme with how to sort all records after running collection.find()
  • [SWIFT-1092] - Vendor libmongoc 1.17.4
  • [SWIFT-763] - Deprecate geoHaystack and geoSearch

Improvement

  • [SWIFT-805] - Make ExceededTimeLimit retryable writes error
  • [SWIFT-872] - Reduce default keepalive time to align with Azure defaults
  • [SWIFT-903] - Add compressors option to MongoClientOptions
  • [SWIFT-905] - Add heartbeatFrequencyMS option to MongoClientOptions
  • [SWIFT-906] - Add localThresholdMS option to MongoClientOptions
  • [SWIFT-907] - Add serverSelectionTimeoutMS option to MongoClientOptions
  • [SWIFT-909] - Add zLibCompressionLevel option to MongoClientOptions
  • [SWIFT-897] - Add appname option to MongoClientOptions
  • [SWIFT-898] - Add replicaSet option to MongoClientOptions
  • [SWIFT-901] - Add tlsInsecure option to MongoClientOptions
  • [SWIFT-912] - Error if minPoolSize option is provided in connection string
  • [SWIFT-929] - Validate options provided via MongoClientOptions
  • [SWIFT-1015] - Only create monitoring events if the user is actually subscribing to them
  • [SWIFT-1072] - Improve performance of insertion
mongo-swift-driver - 1.0.2

Published by kmahar almost 4 years ago

I'm pleased to announce our 1.0.2 release.

This contains a fix (14afd20d3b2f75a373b990fa5ffcc5219ed2266e) for a memory leak on Linux: SWIFT-1051 / #571. Thank you to @NikolayJuly for bringing this to our attention.

This leak was due to our usage of String.cString(using:), a Foundation method whose Linux implementation has apparently had a longstanding, known memory leak (see SR-4036, and the source code).

mongo-swift-driver - 1.0.1

Published by kmahar about 4 years ago

I'm pleased to announce our 1.0.1 release.

This release contains a single bug fix for the issue raised in #387. Due to a bug in Xcode, cSettings defined in our Package.swift file were not being correctly applied to the driver when attempting to build it via Xcode's SwiftPM integration. We have now removed the need for the driver to use cSettings at all via #513. (See also: SWIFT-952) and the driver should build with Xcode + SwiftPM as expected.

mongo-swift-driver - 1.0.0

Published by kmahar over 4 years ago

Today I'm very pleased to announce our 1.0 release.

Our API is now stable, and from this point forward we'll follow semantic versioning.

We'd like to thank the following people for helping us get to this release out:

  • @valeriomazzeo for raising #458, which led to the fix introduced in SWIFT-824 - as well as for opening various other issues over time!
  • @weissi and @lukasa for advice on fixing the issue encountered in SWIFT-779
  • The Swift Server Work Group for their thoughtful feedback and help moving through the SSWG pitch and proposal process (@tanner0101, @loganwright, @weissi, @tomerd)
  • Numerous others who have contributed code, feedback, and bug reports to the driver over the last 2 years!

This release was preceded by 2 release candidates (rc0, rc1); if you are upgrading from an earlier version of the driver, please see their respective release notes for details on what has changed since v0.3.0.

Below are some changes of note we've made, as well as a list of all tickets we've closed since 1.0.0-rc1.

Notable Changes

macOS Version Support

The minimum macOS version the driver now supports is 10.14.

Errors

To improve the discoverability of driver error types, their definitions have now all been nested in an enumeration MongoError. The old protocol MongoError has been renamed MongoErrorProtocol. Additionally, a separate namespace and set of errors have been introduced for use within the BSON library. Please see our error handling guide for more details.

BSON API

We've made some naming changes to the BSON library to prevent collisions with other libraries as well as to provide more consistency within the library as a whole. Please see the migration guide section of our BSON guide for details on upgrading from 1.0.0-rc1's API.

Renamed Types

In addition to prefixing some types in the BSON library, we've also made the following renames in the driver:

  • ClientOptions is now MongoClientOptions
  • DatabaseOptions is now MongoDatabaseOptions
  • CollectionOptions is now MongoCollectionOptions
  • Hint is now IndexHint
  • Address is now ServerAddress
  • CursorType is now MongoCursorType
  • The enum case WriteConcern.W.tag is now WriteConcern.W.custom

Initial Replica Set Discovery Behavior

The driver's behavior around initial discovery of replica set members has changed as of SWIFT-742.

Consider the following scenario: you have a three-node replica set with hosts running at localhost:27017, localhost:27018, and localhost:27019.
Previously, given a connection string containing a single one of those hosts (e.g. mongodb://localhost:27017) the driver would make a direct connection to that host only, and would not attempt to discover or monitor other members of the replica set.

The driver's default behavior is now to automatically attempt discovery of the entire replica set when given a single host.

If you need to establish a direction connection, you can use the new connection string option directConnection=true, or set MongoClientOptions.directConnection to true. Omitting the option is equivalent to setting it to false.

More Complex Vapor Example Application

We've added a new Vapor example, demonstrating how to use the driver within the context of a CRUD application. If you have any suggestions for improvement or other example code you'd like to see added, please let us know!

Included Tickets

Bug

  • [SWIFT-779] - Investigate issue with 5.2 release mode C interop
  • [SWIFT-824] - Use stack allocated bson_ts for all reply documents
  • [SWIFT-761] - Fix thread sanitizer warnings

Task

  • [SWIFT-826] - Make Date(msSinceEpoch:) internal
  • [SWIFT-850] - Rename Id -> ID
  • [SWIFT-851] - Namespace all error types within an enum
  • [SWIFT-855] - Drop support for macOS versions < 10.14
  • [SWIFT-870] - Add default value for BSON.objectID case
  • [SWIFT-878] - Define BSON specific error types

Improvement

  • [SWIFT-742] - Unify behavior around configuration for replica set discovery
  • [SWIFT-204] - Suppress "ns not found" errors in MongoCollection.drop()
  • [SWIFT-769] - localizedDescription of errors should contain error message
  • [SWIFT-815] - More convenient API for ReadConcern/WriteConcern creation
  • [SWIFT-822] - Add prefixes to public type names where needed
  • [SWIFT-827] - Rewrite enums with .other case as structs
  • [SWIFT-835] - Standardize on conversion method names
  • [SWIFT-863] - Rename WriteConcern.W tag case to custom
  • [SWIFT-882] - Rewrite extJSON properties as functions
  • [SWIFT-640] - Add authentication options to MongoClientOptions
mongo-swift-driver - 0.3.0

Published by kmahar over 4 years ago

We are pleased to announce our 0.3.0 release.

This release is identical to the 0.2.0 release except for a single ticket, SWIFT-823, which drops support for Swift 5.0 and updates the way we link to system installations of the MongoDB C driver to be compatible with Swift 5.2.

This release is intended to provide an upgrade path to our 1.0 release for users, allowing you to first upgrade to Swift 5.2 and then to separately upgrade to a newer driver version.
At this time we do not plan on tagging further 0.3.x releases. For new users, we strongly suggest pinning to the latest 1.0 release candidate:

.package(url: "https://github.com/mongodb/mongo-swift-driver", .exact("1.0.0-rc1"))
mongo-swift-driver - 1.0.0-rc1

Published by kmahar over 4 years ago

We are pleased to announce the second release candidate for our 1.0.0 release.

Please note that this release drops support for Swift 5.0. The driver officially supports Swift 5.1 and 5.2 on macOS, Ubuntu 16.04, and Ubuntu 18.04.

A full list of included tickets is available below, but here are some highlights:

New Feature: Transactions Support

The driver now provides an API for transactions! Note that MongoDB supports transactions in replica sets as of v4.0, and in sharded clusters as of v4.2.

Please see the Transactions Guide in our documentation for details and examples.

Work on the convenient API for transactions (i.e. a withTransaction helper that includes helpful logic to automatically retry transactions on certain errors) is currently in progress.

Notable API Changes

  • MongoClient.shutdown() and MongoClient.syncShutdown() have been renamed MongoClient.close() and MongoClient.syncClose(), respectively, for consistency with other MongoDB drivers. (SWIFT-749)
  • ReadPreference is now a struct rather than a class. It no longer has any public initializers, but is instead initializable via static properties and methods available on the type. This makes usages more succinct, particularly in the context of e.g. an options struct where the compiler can infer the type. (SWIFT-738)
    Example:
    let rp = ReadPreference(.primary) // old
    let rp = ReadPreference.primary // new
    
    let rp = try ReadPreference(.secondary, maxStalenessSeconds: 100) // old
    let rp = try ReadPreference.secondary(maxStalenessSeconds: 100) // new
    
    let options = FindOptions(readPreference: ReadPreference(.primary)) // old
    let options = FindOptions(readPreference: .primary) // new
    
  • All of the TLS options previously specifiable via the TLSOptions struct have been moved directly into ClientOptions, and have been renamed for consistency with the names used when they are specified via a MongoDB connection string. (SWIFT-753)
  • The maxScan option which has been deprecated since MongoDB v4.0 has been removed from FindOptions and FindOneOptions. (SWIFT-439)
  • Several previous usages of other integer types in the API have been updated to use Int instead (SWIFT-754). Please see 940d90d9e8879fd09a8cb5f7a17aa4ca29bb6617 for a complete list.

Included Tickets

Bug

  • [SWIFT-750] - fix potential for deadlock when all connections are in use

New Feature

  • [SWIFT-746] - Implement startTransaction, commitTransaction, and abortTransaction in the asynchronous API
  • [SWIFT-747] - Implement startTransaction, commitTransaction, and abortTransaction in the synchronous API

Task

  • [SWIFT-434] - Add a TLS guide
  • [SWIFT-743] - Implement TransactionOptions struct
  • [SWIFT-752] - Implement Transactions Spec Test Runner
  • [SWIFT-347] - Update error handling guide to include errorLabels information
  • [SWIFT-439] - Remove maxScan query option
  • [SWIFT-499] - Update benchmark suite to include multithreaded scenarios
  • [SWIFT-595] - Bump libmongoc version to 1.16
  • [SWIFT-618] - Bump minimum Swift version to 5.1, and start testing against Swift 5.2
  • [SWIFT-636] - Stop filtering out SERVICE_NAME = mongodb from mechanism properties in GSSAPI auth tests
    ( [SWIFT-705] - Tune default NIOThreadPool size
  • [SWIFT-731] - Update guides to focus on async API
  • [SWIFT-735] - Make ObjectId work with JSONEncoder/JSONDecoder
  • [SWIFT-744] - Update ClientSessionOptions to support transactions
  • [SWIFT-745] - Implement StartTransactionOperation, CommitTransactionOperation, and AbortTransactionOperation
  • [SWIFT-784] - Disable BSON_EXTRA_ALIGN in vendored libbson
  • [SWIFT-423] - Provide Transactions example for Docs

Improvement

  • [SWIFT-224] - Avoid roundtripping values through Swift when copying values from one document to another
  • [SWIFT-621] - Provide default values for enum associated values where appropriate
  • [SWIFT-623] - Use Self rather than type(of: self)
  • [SWIFT-677] - listIndexNames should extract names from Documents rather than decoding entire IndexModels
  • [SWIFT-753] - Condense TLSOptions into ClientOptions struct, and make property names consistent with URI options spec
  • [SWIFT-754] - Use Int in public API as much as possible
  • [SWIFT-757] - Add RetryableWriteError error labels to retryable transaction tests
  • [SWIFT-772] - Add allowDiskUse option to find command
  • [SWIFT-751] - Add maxPoolSize option for connection pool
  • [SWIFT-773] - Support for authorizedDatabases option
  • [SWIFT-749] - Improve MongoClient shutdown logic
  • [SWIFT-738] - Make ReadPreference a struct
mongo-swift-driver -

Published by kmahar over 4 years ago

mongo-swift-driver - MongoSwift 1.0.0-rc0

Published by kmahar over 4 years ago

MongoSwift 1.0.0-rc0

We are very excited to announce the first release candidate for our upcoming 1.0.0 release.

This release contains a number of major changes to the driver, as detailed in the following sections.

Asynchronous, SwiftNIO-based API

The driver now contains both asynchronous and synchronous APIs for working with MongoDB from Swift.
These APIs are contained in two modules, named MongoSwift (async) and MongoSwiftSync (sync). Depending on which API you would like to use, you can depend on either one of those modules.

The asynchronous API is implemented by running all blocking code off the calling thread in a SwiftNIO NIOThreadPool. The size of this thread pool is configurable via the threadPoolSize property on ClientOptions.

Vapor developers: please note that since we depend on SwiftNIO 2, as of this reelase the driver will not be compatible with Vapor versions < 4, as Vapor 3 depends on SwiftNIO 1.0.

All of the web framework examples in the Examples/ directory of this repository have now been updated to use the asynchronous API.

The synchronous API has been reimplemented as a wrapper of the asynchronous API. You may also configure the size of the thread pool when constructing a synchronous MongoClient as well.

If you are upgrading from a previous version of the driver and would like to continue using the synchronous API, you should update your Package.swift to make your target depend on MongoSwiftSync, and replace every occurrence of import MongoSwift with import MongoSwiftSync.

The MongoDB C driver is now vendored and built via SwiftPM

Previously, the driver would link to a system installation of the MongoDB C driver, libmongoc. We have now vendored the source of libmongoc into the driver, and it is built using SwiftPM.

libmongoc does link to some system libraries itself for e.g. SSL support, so depending on your operating system and system configuration you may still need to install some libraries. Please see the updated installation instructions for more details.

Note: Unfortunately, due to an issue with the Xcode SwiftPM integration where Xcode ignores cSettings (necessary for building libmongoc), as of Xcode 11.3 the driver currently cannot be added to your project as a dependency in that matter. Please see #387 and SR-12009 for more information. In the meantime, you can work around this by:

  1. Add the driver to your Package.swift file
  2. Run swift package generate-xcodeproj from the command line
  3. Open the resulting .xcodeproj in Xcode

Alternatively, as described in #387 you can clone the driver, run make project from its root directory to generate a corresponding .xcodeproj, and add that to an Xcode workspace.

Driver Error Types are now structs

Like many Swift libraries, the driver previously used enums to represent a number of different error types. However, over time we realized that enums were a poor fit for modeling MongoDB errors.
Anytime we wished to add an additional associated value to one of the error cases in an enum, or to add a new case to one of the enums, it would be a breaking change.
Over time the MongoDB server has added more and more information to the errors it returns, and has added various new categories of errors. Enums made it difficult for our errors to evolve gracefully along with the server.

Now, each type of error that was previously an enum case is represented as a struct, and similar errors are grouped together by protocols rather than by being cases in the same enum.

Please see the updated error handling guide for more information on the types of errors and best practices for working with them.

Synchronous Cursor and Change Stream API Updates

Use of Result

The synchronous variants of MongoCursor and ChangeStream (defined in MongoSwiftSync) now return a Result<T>? from their next() methods rather than a T?.
You can read more about the Swift Standard Library's Result type here.
This change enables to propagate errors encountered while iterating, for example a network error, via a failed Result. Previously, users had to inspect the error property of a cursor/change stream, which was unintuitive and easy to forget.

Iterating over a cursor would now look like this:

for result in cursor {
    switch result {
    case let .success(doc):
        // do something with doc
    case let .failure(error):
        // handle error    
    }
}

Alternatively, you may use the get method on Result:

for result in cursor {
    let doc = try result.get()
    // do something with doc
}

Since errors are now propagated in this way, the error property has been removed from both types and inspecting it is no longer necessary.

next() now blocks while waiting for more results

This change only affects ChangeStreams and tailable MongoCursors. (See: change streams, tailable cursors.) (By default, cursors are not tailable.)
These types will stay alive even after their initial results have been exhausted, and will continue to receive new matching documents (or events in the case of change streams) if and when they become available.

In the past, next() would simply return nil immediately if a next result was not available. This would require a user who wants to wait for the next result to continuously loop and check for a non-nil result.
Now, next() will internally poll until a new result is obtained or the cursor is killed (you can trigger this yourself by calling kill).

If you wish to use the old behavior where the method would not continuously poll and look for more results, you can use the newly introduced tryNext() which preserves that behavior.

For non-tailable MongoCursors, the cursor is automatically killed as soon as all currently available results are retrieved, so next() will behave exactly the same as tryNext().

Note that a consequence of this change is that working with a tailable MongoCursor or a ChangeStream via Sequence methods or a for loop can block while waiting for new results, since many Sequence methods are implemented via next().

Conformance to LazySequenceProtocol

MongoCursor and ChangeStream now conform to LazySequenceProtocol, which inherits from Sequence (which these types conformed to previously).

This allows the standard library to defer applying operations such as map and filter until the elements of the resulting Sequence are actually accessed. This is beneficial for cursors and change streams as you can transform their elements without having to load the entire result set into memory at once. For example, consider the following snippet. The map call will be lazily applied as each element is read from the cursor in step 3:

// 1. Create a cursor
let cursor = try myCollection.find()

// 2. Add a call to `map` that transforms each result in the cursor by adding a new key
let transformed = cursor.map { result in
    // try to get the result, and if we succeed add a key "a" to it. if we fail, return
    // a failed result containing the error
    Result { () throws -> Document  in
        var doc = try result.get()
        doc["a"] = 1
        return doc
    }
}

// 3. Iterate the transformed cursor
for result in transformed {
    // ...
}

Note: If you wish to take advantage of LazySequenceProtocol, you cannot throw from the closure passed to map / filter / etc. Those variants only exist on Sequence, and calling them will result in the sequence being eagerly loaded into memory before the closure is applied.

Improved Monitoring API

More Flexible Event Handling

Prior to this release, MongoClient posted all monitoring events to a NotificationCenter, either one provided to it via ClientOptions or the application's default center. This was overly restrictive, as it required you to interface with NotificationCenter in order to receive monitoring events, even if NotificationCenter wasn't used anywhere else in your application.

Starting in this release, you can attach your own handler types that conform to the new CommandEventHandler and SDAMEventHandler protocols to via MongoClient.addCommandEventHandler and MongoClient.addSDAMEventHandler respectively. The appropriate monitoring events will then be passed to them directly via the protocol requirement methods. From there, you can do whatever processing of the events you want, including, but not limited to, posting to a NotificationCenter.

Also, there are ergonomic overloads for both of the handler adding methods that take in callbacks if you don't want to define your own handler type:

client.addCommandEventHandler { event in
    print(event)
    // be sure not to strongly capture client in here!
}

Restructured Event Types

Prior to this release, all monitoring events were defined as their own structs, and extracting the right event type required lots of downcasting. Starting in this release, common event types are grouped into enums, namely into the SDAMEvent and CommandEvent enums, whose cases' associated values are the existing event structs. This models events in a way that makes better use of the Swift type system by removing the need for downcasting, allowing like events to be grouped together, and enabling relevant event types to be switched over exhaustively.

Included Tickets

Bug

  • [SWIFT-663] - Stop parsing write concern errors when extracting bulk write errors

New Features

  • [SWIFT-410] - Async API
  • [SWIFT-643] - Add a findOne method
  • [SWIFT-718] - Implement toArray method for async cursors and change streams
  • [SWIFT-719] - Implement forEach method for async cursors and change streams
  • [SWIFT-360] - More flexible monitoring API

Improvement

  • [SWIFT-500] - Vendor libmongoc and build it with SwiftPM
  • [SWIFT-675] - Iterate over Result<T> in MongoCursor
  • [SWIFT-688] - Iterate over Result<T> in ChangeStream
  • [SWIFT-661] - Make find and aggregate do immediate I/O
  • [SWIFT-314] - Gracefully handle errors parsing isMaster responses for SDAM monitoring
  • [SWIFT-502] - Reimplement errors as structs
  • [SWIFT-601] - Introduce protocol(s) for SDAM monitoring events

Task

  • [SWIFT-288] - Make use of new libmongoc function for getting a server's lastUpdateTime
  • [SWIFT-427] - Remove autoIndexId option for collection creation
mongo-swift-driver - MongoSwift 0.2.0

Published by kmahar almost 5 years ago

We are pleased to announce the 0.2.0 release of the MongoDB Swift driver.

This release includes a number of major improvements, detailed in the following sections.

Please note that as of this release we now require using Swift version 5.0 or greater, and version 1.15.3 or greater of the MongoDB C driver.

Thank you to everyone who contributed to this release!

Improvements for use in multithreaded applications

MongoClients now automatically pool connections to the server. We recommend sharing clients across threads in your application when possible in order to decrease the total number of connections to the server your application has open at a time.

MongoClient, MongoDatabase, and MongoCollection are now all safe to share across threads.

Please see our new multithreading guide for more information.

New BSON API

We've significantly changed the API for the driver's BSON library to make using BSON types and constructing Documents much easier.

Please see our guide describing how to use the BSON library, including a migration guide for updating from the old API.

Other new features of note

A number of other new features have been added since our last release, including:

  • Change streams support (please see our guide on using change streams here)
  • API for specifying TLS options for use with a MongoClient

Included tickets

mongo-swift-driver -

Published by kmahar over 5 years ago

This release includes a couple of small fixes to correct inadvertent backwards-breaking changes introduced in 0.1.1.

mongo-swift-driver - MongoSwift 0.1.1

Published by kmahar over 5 years ago

We are pleased to announce the 0.1.1 release of the MongoDB Swift driver.

Release Highlights

Sessions support

This release adds support for MongoDB client sessions. This allows the driver to make certain causal consistency guarantees for operations that are executed using the same session, depending on the write/read concern configuration. See the official MongoDB documentation for more information on these guarantees, and the documentation on ClientSession for example usage.

Simpler Initialization and Cleanup

Previously, we required that users call MongoSwift.initialize() before using the driver to set up some global state and resources. We've now deprecated this method, and made it so that initialization happens automatically the first time you create a MongoClient.

Additionally, note that MongoSwift.cleanup() (which should be called exactly once when your application is done using the driver) has been deprecated and renamed cleanupMongoSwift(). Please see SWIFT-402 for context on the name change.

Mutable options structs

All of the properties stored in options structs are now vars, allowing you to do things like:

var options = FindOptions()
options.batchSize =  10
options.skip = 5

Included tickets

Bug

  • [SWIFT-404] - expireAfter index option is not correctly encoded
  • [SWIFT-405] - Document.count should not be publicly settable

New Feature

Improvement

  • [SWIFT-311] - MongoClient/MongoDatabase/MongoCollection ReadPreference getters should not return Optionals
  • [SWIFT-355] - Make options properties mutable to allow changing them after creation
  • [SWIFT-402] - Handle MongoSwift name conflicts
  • [SWIFT-413] - Make properties of WriteModel implementations public
mongo-swift-driver - MongoSwift 0.1.0

Published by kmahar over 5 years ago

We are pleased to announce the 0.1.0 release of the MongoDB Swift driver.

Release Highlights

Swift 5 Support

This release adds support for using the driver in Swift 5.0. It also drops support for Swift versions < 4.2.

Improved Error Reporting

This release re-organizes the errors thrown by the driver to more accurately represent their sources. In particular, we now throw four classes of errors: ServerError, UserError, RuntimeError, and EncodingError/DecodingError. Each type is described in detail in the error handling guide.

BSON Improvements

This release includes a number of improvements to the BSON library. In particular:

Improved Int Handling consistency in Document

We've improved the consistency of how Ints are read from and written to Documents. Previously, Int was encoded to BSON as an int32 if it could fit, or an int64 otherwise. This could lead to situations where Ints were not round tripped properly through Documents. Now, Int behaves as the type of integer it represents on a given architecture, which means it is always round-tripped correctly. (See here for details on Swift Int's variable bitwidth.)

On 64-bit systems:

  • Int is encoded as a BSON int64
  • BSON int32s are read out of documents as Int32s
  • BSON int64s are read out of documents as Ints
  • e.g. doc["a"] = 5 sets the "a" key of a document to the BSON int64 5, and doc["a"] returns Int(5)

On 32-bit systems:

  • Int is encoded as a BSON int32
  • BSON int32s are read out of documents as Ints
  • BSON int64s are read out of documents as Int64s

On both systems, Int32 and Int64 are encoded to BSON int32 and BSON int64, respectively.

BSONNumber

To facilitate writing architecture-independent code (which is rare, since Swift support for 32-bit is extremely limited), we introduced the BSONNumber protocol, which all the numeric BSONValue types (Int32, Int64, Int, Double, and Decimal128) conform to. Conformance to this protocol allows conversion to any of the number types that BSON natively supports. However, the conversions will only return a value if the conversion is exact, and will return nil otherwise.

let a: BSONNumber = 5.2
a.int32Value // nil
a.doubleValue // Double(5.2)
       
let b: BSONNumber = 5.0
b.int32Value // int32(5)
b.doubleValue // Double(5.0)
   
let c: BSONNumber = Int32.max + 1
c.int32Value // nil
c.int64Value // Int64(2147483648)

// Example usage for when you know it's a number, but not what type of number it is and/or you don't care
let doc: Document = ["a": 5.0]
(doc["a"] as! BSONNumber).intValue // 5

New Types for Deprecated BSON Types

We've added new types for deprecated BSON types: Undefined, DBPointer, and Symbol. Previously, when extracted from a Document, values encoded as those types would be automatically converted to similar non-deprecated ones. Their types are now preserved.

bsonEquals added to BSONValue protocol

bsonEquals is now part of the BSONValue protocol. Statements that were previously written as bsonEquals(a, b) can now be written as a.bsonEquals(b). The old syntax is deprecated and will be removed in a future release.

Coding Strategies Introduced

We've introduced the concept of a Coding Strategy in this release, which allows the user to specify how certain values get encoded to and decoded from BSON using BSONEncoder / BSONDecoder. The provided strategies are heavily based on the encoding and decoding strategies used in Foundation's JSONEncoder/JSONDecoder, and are implemented to behave similarly. See the driver documentation (and Foundations docs) for information on how they can be used. An in-depth guide is forthcoming for usage in the driver.

let date = Date(timeIntervalSince1970: 1.5)
let codingOptions = BSONCoderOptions(dateCodingStrategy: .millisecondsSince1970)
let doc = try BSONEncoder(options: codingOptions).encode(["a": date]) // ["a": Int64(1500)]
try BSONDecoder(options: codingOptions).decode(DateWrapperA.self, from: doc).a.timeIntervalSince1970 // 1.5

Release Notes