diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 824de443f..d0a4e0bac 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -1,3 +1,5 @@ +# https://github.com/actions/runner-images/blob/main/images/macos/macos-12-Readme.md + name: "GRDB CI" on: @@ -9,12 +11,14 @@ on: - 'GRDB/**' - 'Tests/**' - '.github/workflows/**' + - 'Makefile' - 'Package.swift' pull_request: paths: - 'GRDB/**' - 'Tests/**' - '.github/workflows/**' + - 'Makefile' - 'Package.swift' concurrency: @@ -24,50 +28,56 @@ permissions: contents: read jobs: - macOS: - name: macOS + Framework: + name: Framework runs-on: ${{ matrix.runsOn }} + env: + DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer" timeout-minutes: 60 strategy: fail-fast: false matrix: include: + - xcode: "Xcode_14.1.app" + runsOn: macOS-12 + destination: "platform=macOS" + name: "macOS" + - xcode: "Xcode_14.1.app" + runsOn: macOS-12 + destination: "OS=16.1,name=iPhone 14" + name: "iOS" + - xcode: "Xcode_14.1.app" + runsOn: macOS-12 + destination: "OS=16.1,name=Apple TV" + name: "tvOS" - xcode: "Xcode_14.0.1.app" runsOn: macOS-12 - name: "macOS 12, Xcode 14.0.1, Swift 5.7" - shell: "/bin/zsh {0}" + destination: "platform=macOS" + name: "macOS" + - xcode: "Xcode_14.0.1.app" + runsOn: macOS-12 + destination: "OS=16.0,name=iPhone 14" + name: "iOS" steps: - uses: actions/checkout@v3 - name: ${{ matrix.name }} - run: make test_framework_GRDBOSX_maxSwift - iOS: - name: iOS - runs-on: ${{ matrix.runsOn }} - timeout-minutes: 60 - strategy: - fail-fast: false - matrix: - include: - - xcode: "Xcode_14.0.1.app" - runsOn: macOS-12 - name: "macOS 12, Xcode 14.0.1, Swift 5.7" - shell: "/bin/zsh {0}" - steps: - - uses: actions/checkout@v3 - - name: ${{ matrix.name }} - run: make test_framework_GRDBiOS_maxTarget_maxSwift + run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test SPM: name: SPM runs-on: ${{ matrix.runsOn }} + env: + DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer" timeout-minutes: 60 strategy: fail-fast: false matrix: include: + - xcode: "Xcode_14.1.app" + runsOn: macOS-12 + name: "Xcode 14.1" - xcode: "Xcode_14.0.1.app" runsOn: macOS-12 - name: "macOS 12, Xcode 14.0.1, Swift 5.7" - shell: "/bin/zsh {0}" + name: "Xcode 14.0.1" steps: - uses: actions/checkout@v3 - name: ${{ matrix.name }} @@ -75,15 +85,16 @@ jobs: SQLCipher3: name: SQLCipher3 runs-on: ${{ matrix.runsOn }} + env: + DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer" timeout-minutes: 60 strategy: fail-fast: false matrix: include: - - xcode: "Xcode_14.0.1.app" + - xcode: "Xcode_14.1.app" runsOn: macOS-12 - name: "macOS 12, Xcode 14.0.1, Swift 5.7" - shell: "/bin/zsh {0}" + name: "Xcode 14.1" steps: - uses: actions/checkout@v3 - name: ${{ matrix.name }} @@ -91,15 +102,16 @@ jobs: SQLCipher4: name: SQLCipher4 runs-on: ${{ matrix.runsOn }} + env: + DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer" timeout-minutes: 60 strategy: fail-fast: false matrix: include: - - xcode: "Xcode_14.0.1.app" + - xcode: "Xcode_14.1.app" runsOn: macOS-12 - name: "macOS 12, Xcode 14.0.1, Swift 5.7" - shell: "/bin/zsh {0}" + name: "Xcode 14.1" steps: - uses: actions/checkout@v3 - name: ${{ matrix.name }} @@ -107,15 +119,16 @@ jobs: CustomSQLite: name: CustomSQLite runs-on: ${{ matrix.runsOn }} + env: + DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer" timeout-minutes: 60 strategy: fail-fast: false matrix: include: - - xcode: "Xcode_14.0.1.app" + - xcode: "Xcode_14.1.app" runsOn: macOS-12 - name: "macOS 12, Xcode 14.0.1, Swift 5.7" - shell: "/bin/zsh {0}" + name: "Xcode 14.1" steps: - uses: actions/checkout@v3 - name: ${{ matrix.name }} @@ -123,15 +136,16 @@ jobs: XCFramework: name: XCFramework runs-on: ${{ matrix.runsOn }} + env: + DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer" timeout-minutes: 60 strategy: fail-fast: false matrix: include: - - xcode: "Xcode_14.0.1.app" + - xcode: "Xcode_14.1.app" runsOn: macOS-12 - name: "macOS 12, Xcode 14.0.1, Swift 5.7" - shell: "/bin/zsh {0}" + name: "Xcode 14.1" steps: - uses: actions/checkout@v3 - name: ${{ matrix.name }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b7f73d3b..46603ad42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 6.x Releases +- `6.6.x` Releases - [6.6.0](#660) - `6.5.x` Releases - [6.5.0](#650) - `6.4.x` Releases - [6.4.0](#640) - `6.3.x` Releases - [6.3.0](#630) - [6.3.1](#631) @@ -103,6 +104,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 6.6.0 + +Released December 29, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.5.0...v6.6.0) + +- **New**: [#1304](https://github.com/groue/GRDB.swift/pull/1304) by [@groue](https://github.com/groue): Expose generated columns with availability checks + ## 6.5.0 Released December 5, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.4.0...v6.5.0) diff --git a/Documentation/Combine.md b/Documentation/Combine.md index a9004214a..d4e114cc8 100644 --- a/Documentation/Combine.md +++ b/Documentation/Combine.md @@ -398,7 +398,7 @@ let cancellable = hallOfFamePublisher.sink( [`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread [`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:) [configured]: ../README.md#databasepool-configuration -[database pool]: ../README.md#database-pools -[database queue]: ../README.md#database-queues +[database pool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool +[database queue]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue [database snapshot]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot [scheduler]: https://developer.apple.com/documentation/combine/scheduler diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index 5df56ab8f..7b1dc090b 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -21,7 +21,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal 2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`. - It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) when you use a [Database Pool](../README.md#database-pools). + It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool). 3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory. diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 866604db6..d42d199bf 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,16 +1,14 @@ { - "object": { - "pins": [ - { - "package": "GRDBQuery", - "repositoryURL": "https://github.com/groue/GRDBQuery", - "state": { - "branch": null, - "revision": "4301166cd2aee9ce37b4057c9a58f5cc3bbeae06", - "version": "0.1.0" - } + "pins" : [ + { + "identity" : "grdbquery", + "kind" : "remoteSourceControl", + "location" : "https://github.com/groue/GRDBQuery", + "state" : { + "revision" : "df514f2bd74548f94e082f3233022190e594fce4", + "version" : "0.5.1" } - ] - }, - "version": 1 + } + ], + "version" : 2 } diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift index 0d4b2227c..e1c893464 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift @@ -17,7 +17,7 @@ struct AppDatabase { /// Application can use a `DatabasePool`, while SwiftUI previews and tests /// can use a fast in-memory `DatabaseQueue`. /// - /// See + /// See private let dbWriter: any DatabaseWriter /// The DatabaseMigrator that defines the database schema. @@ -162,7 +162,7 @@ extension AppDatabase { // reading methods. extension AppDatabase { /// Provides a read-only access to the database - var databaseReader: DatabaseReader { + var reader: DatabaseReader { dbWriter } } diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift index b9a2cc1f7..7670af424 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift @@ -24,7 +24,7 @@ extension AppDatabase { try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true) // Connect to a database on disk - // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections + // See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections let dbURL = folderURL.appendingPathComponent("db.sqlite") let dbPool = try DatabasePool(path: dbURL.path) @@ -58,7 +58,7 @@ extension AppDatabase { /// Creates an empty database for SwiftUI previews static func empty() -> AppDatabase { // Connect to an in-memory database - // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections + // See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections let dbQueue = try! DatabaseQueue() return try! AppDatabase(dbQueue) } diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift index fff68d1ca..8c70aab8d 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift @@ -29,12 +29,12 @@ struct PlayerRequest: Queryable { func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> { // Build the publisher from the general-purpose read-only access - // granted by `appDatabase.databaseReader`. + // granted by `appDatabase.reader`. // Some apps will prefer to call a dedicated method of `appDatabase`. ValueObservation .tracking(fetchValue(_:)) .publisher( - in: appDatabase.databaseReader, + in: appDatabase.reader, // The `.immediate` scheduling feeds the view right on // subscription, and avoids an undesired animation when the // application starts. diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 866604db6..d42d199bf 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,16 +1,14 @@ { - "object": { - "pins": [ - { - "package": "GRDBQuery", - "repositoryURL": "https://github.com/groue/GRDBQuery", - "state": { - "branch": null, - "revision": "4301166cd2aee9ce37b4057c9a58f5cc3bbeae06", - "version": "0.1.0" - } + "pins" : [ + { + "identity" : "grdbquery", + "kind" : "remoteSourceControl", + "location" : "https://github.com/groue/GRDBQuery", + "state" : { + "revision" : "df514f2bd74548f94e082f3233022190e594fce4", + "version" : "0.5.1" } - ] - }, - "version": 1 + } + ], + "version" : 2 } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift index b9516f3d0..3f9cbd0f5 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift @@ -18,7 +18,7 @@ struct AppDatabase { /// Application can use a `DatabasePool`, while SwiftUI previews and tests /// can use a fast in-memory `DatabaseQueue`. /// - /// See + /// See private let dbWriter: any DatabaseWriter /// The DatabaseMigrator that defines the database schema. @@ -163,7 +163,7 @@ extension AppDatabase { // reading methods. extension AppDatabase { /// Provides a read-only access to the database - var databaseReader: DatabaseReader { + var reader: DatabaseReader { dbWriter } } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift index b9a2cc1f7..7670af424 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift @@ -24,7 +24,7 @@ extension AppDatabase { try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true) // Connect to a database on disk - // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections + // See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections let dbURL = folderURL.appendingPathComponent("db.sqlite") let dbPool = try DatabasePool(path: dbURL.path) @@ -58,7 +58,7 @@ extension AppDatabase { /// Creates an empty database for SwiftUI previews static func empty() -> AppDatabase { // Connect to an in-memory database - // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections + // See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections let dbQueue = try! DatabaseQueue() return try! AppDatabase(dbQueue) } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift index fff68d1ca..8c70aab8d 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift @@ -29,12 +29,12 @@ struct PlayerRequest: Queryable { func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> { // Build the publisher from the general-purpose read-only access - // granted by `appDatabase.databaseReader`. + // granted by `appDatabase.reader`. // Some apps will prefer to call a dedicated method of `appDatabase`. ValueObservation .tracking(fetchValue(_:)) .publisher( - in: appDatabase.databaseReader, + in: appDatabase.reader, // The `.immediate` scheduling feeds the view right on // subscription, and avoids an undesired animation when the // application starts. diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index ff56eec1f..9d811be25 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -16,7 +16,7 @@ final class AppDatabase { /// Application can use a `DatabasePool`, and tests can use a fast /// in-memory `DatabaseQueue`. /// - /// See + /// See private let dbWriter: any DatabaseWriter /// The DatabaseMigrator that defines the database schema. @@ -127,7 +127,7 @@ extension AppDatabase { // reading methods. extension AppDatabase { /// Provides a read-only access to the database - var databaseReader: DatabaseReader { + var reader: DatabaseReader { dbWriter } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift index 7887f9773..0b0c44c33 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift @@ -17,7 +17,7 @@ extension AppDatabase { try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true) // Connect to a database on disk - // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections + // See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections let dbURL = folderURL.appendingPathComponent("db.sqlite") let dbPool = try DatabasePool(path: dbURL.path) diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift index 92a9a28e6..0ef0c52d4 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift @@ -138,7 +138,7 @@ class PlayerListViewController: UITableViewController { playersCancellable = ValueObservation .tracking(request.fetchAll(_:)) .start( - in: AppDatabase.shared.databaseReader, + in: AppDatabase.shared.reader, // Immediate scheduling feeds the data source right on subscription, // and avoids an undesired animation when the application starts. scheduling: .immediate, diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 24cd883b3..86fd94b1c 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -154,11 +154,11 @@ See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/docume ### Non-blocking database reads -GRDB ships with two ways to access databases, [database queues](../README.md#database-queues) and [pools](../README.md#database-pools). +GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool). Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen. -[Database pools](../README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured). +[Database pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured). ### Strong and clear multi-threading guarantees @@ -287,7 +287,7 @@ Happy GRDB! :gift: [Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency [Core Data]: https://developer.apple.com/documentation/coredata -[DatabasePool]: ../README.md#database-pools +[DatabasePool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool [Diesel]: http://diesel.rs [FCModel]: https://github.com/marcoarment/FCModel [ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 5dbb3f2bb..452b046af 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '6.5.0' + s.version = '6.6.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 174e96965..2316c2cb1 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -1,55 +1,6 @@ import Dispatch import Foundation -/// The configuration of a database connection. -/// -/// You create a `Configuration` before opening a database connection: -/// -/// ```swift -/// var config = Configuration() -/// config.readonly = true -/// config.maximumReaderCount = 2 // (DatabasePool only) The default is 5 -/// config.prepareDatabase { db in // A function to run on connection -/// db.trace { print("SQL >", $0) } -/// } -/// -/// let dbQueue = try DatabaseQueue( // or DatabasePool -/// path: "/path/to/database.sqlite", -/// configuration: config) -/// ``` -/// -/// See . -/// -/// ## Topics -/// -/// ### Creating a Configuration -/// -/// - ``init()`` -/// -/// ### Configuring SQLite Connections -/// -/// - ``acceptsDoubleQuotedStringLiterals`` -/// - ``busyMode`` -/// - ``foreignKeysEnabled`` -/// - ``readonly`` -/// -/// ### Configuring GRDB Connections -/// -/// - ``allowsUnsafeTransactions`` -/// - ``defaultTransactionKind`` -/// - ``label`` -/// - ``maximumReaderCount`` -/// - ``observesSuspensionNotifications`` -/// - ``prepareDatabase(_:)`` -/// - ``publicStatementArguments`` -/// -/// ### Configuring the Quality of Service -/// -/// - ``qos`` -/// - ``readQoS`` -/// - ``writeQoS`` -/// - ``targetQueue`` -/// - ``writeTargetQueue`` public struct Configuration { // MARK: - Misc options @@ -64,6 +15,15 @@ public struct Configuration { /// A boolean value indicating whether an SQLite connection is read-only. /// /// The default is false. + /// + /// ```swift + /// var config = Configuration() + /// config.readonly = true + /// + /// let dbQueue = try DatabaseQueue( // or DatabasePool + /// path: "/path/to/database.sqlite", + /// configuration: config) + /// ``` public var readonly = false /// A label that describes a database connection. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5c5afa1d1..3f146ceb3 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -4,66 +4,6 @@ import Foundation import UIKit #endif -/// A database connection that allows concurrent accesses to an SQLite database. -/// -/// ## Overview -/// -/// Unless ``Configuration/readonly``, a `DatabasePool` opens an SQLite database -/// in the [WAL mode](https://sqlite.org/wal.html). -/// -/// It creates one writer SQLite connection, and a pool of up to -/// ``Configuration/maximumReaderCount`` read-only SQLite connections. All -/// write accesses are executed in a serial **writer dispatch queue**. All -/// read accesses are executed in **reader dispatch queues** (one per read-only -/// SQLite connection). SQLite connections are closed when the `DatabasePool` -/// is deallocated. -/// -/// See for more information about concurrent -/// database accesses. -/// -/// ## Usage -/// -/// ```swift -/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") -/// -/// let playerCount = try dbPool.read { db in -/// try Player.fetchCount(db) -/// } -/// -/// let newPlayerCount = try dbPool.write { db -> Int in -/// try Player(name: "Arthur").insert(db) -/// return try Player.fetchCount(db) -/// } -/// ``` -/// -/// `DatabasePool` inherits most of its database access methods from the -/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few -/// specific database access methods as well. -/// -/// ## Topics -/// -/// ### Creating a DatabasePool -/// -/// - ``init(path:configuration:)`` -/// -/// ### Accessing the Database -/// -/// See ``DatabaseReader`` and ``DatabaseWriter`` for more database -/// access methods. -/// -/// - ``asyncConcurrentRead(_:)`` -/// - ``writeInTransaction(_:_:)`` -/// -/// ### Creating Database Snapshots -/// -/// - ``makeSnapshot()`` -/// - ``makeSnapshotPool()`` -/// -/// ### Managing SQLite Connections -/// -/// - ``invalidateReadOnlyConnections()`` -/// - ``releaseMemory()`` -/// - ``releaseMemoryEventually()`` public final class DatabasePool { private let writer: SerializedDatabase @@ -704,7 +644,7 @@ extension DatabasePool: DatabaseReader { public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable { @@ -735,7 +675,7 @@ extension DatabasePool: DatabaseReader { /// the writer. private func _addConcurrent( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 1e8268467..ddb3bf494 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -4,51 +4,6 @@ import Foundation import UIKit #endif -/// A database connection that serializes accesses to an SQLite database. -/// -/// ## Overview -/// -/// A `DatabaseQueue` creates one single SQLite connection. All database -/// accesses are executed in a serial **writer dispatch queue**. The SQLite -/// connection is closed when the `DatabaseQueue` is deallocated. -/// -/// ```swift -/// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") -/// -/// let playerCount = try dbQueue.read { db in -/// try Player.fetchCount(db) -/// } -/// -/// let newPlayerCount = try dbQueue.write { db -> Int in -/// try Player(name: "Arthur").insert(db) -/// return try Player.fetchCount(db) -/// } -/// ``` -/// -/// ## Usage -/// -/// `DatabaseQueue` inherits most of its database access methods from the -/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few -/// specific database access methods as well. -/// -/// ## Topics -/// -/// ### Creating a DatabaseQueue -/// -/// - ``init(named:configuration:)`` -/// - ``init(path:configuration:)`` -/// -/// ### Accessing the Database -/// -/// See ``DatabaseReader`` and ``DatabaseWriter`` for more database -/// access methods. -/// -/// - ``inDatabase(_:)`` -/// - ``inTransaction(_:_:)`` -/// -/// ### Managing the SQLite Connection -/// -/// - ``releaseMemory()`` public final class DatabaseQueue { private let writer: SerializedDatabase @@ -339,7 +294,7 @@ extension DatabaseQueue: DatabaseReader { public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable { diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index aa1851cd4..6bea5c1bb 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -325,7 +325,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - returns: A DatabaseCancellable that can stop the observation. func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable } @@ -584,7 +584,7 @@ extension DatabaseReader { /// initial value. func _addReadOnly( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable { @@ -676,7 +676,7 @@ extension AnyDatabaseReader: DatabaseReader { public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 9ab92e592..984ab5c63 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -170,7 +170,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable { diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 8f635c244..dcfbd4cb8 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -329,7 +329,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable where Reducer: ValueReducer { diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index fb264a6b3..a1ada352c 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -531,7 +531,7 @@ extension DatabaseWriter { /// was modified. func _addWriteOnly( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable { @@ -993,7 +993,7 @@ extension AnyDatabaseWriter: DatabaseReader { public func _add( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 97c2c834d..39e98827f 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -507,37 +507,47 @@ extension Statement { /// A cursor that lazily iterates the results of a prepared ``Statement``. /// -/// To get a `DatabaseCursor` instance, use a fetching method of -/// ``Row``, ``DatabaseValueConvertible``, ``FetchableRecord``, -/// or ``FetchRequest``. For example: +/// ## Overview /// -/// ```swift -/// try dbQueue.read { db in -/// // A cursor of database rows, -/// // built from a prepared statement -/// let statement = try db.makeStatement(sql: "SELECT * FROM player") -/// let rows = try Row.fetchCursor(statement) -/// while let row = try rows.next() { -/// let id: Int64 = row["id"] -/// let name: String = row["name"] -/// } +/// To get a `DatabaseCursor` instance, use one of the `fetchCursor` methods. +/// For example: /// -/// // A cursor of values, -/// // built from an SQL string -/// let scores = try Int.fetchCursor(db, sql: "SELECT score FROM player") -/// while let score = try scores.next() { -/// print(score) -/// } +/// - A cursor of ``Row`` built from a prepared ``Statement``: /// -/// // A cursor of players, -/// // built from a QueryInterfaceRequest: -/// let request = Player.all() -/// let players = try request.fetchCursor(db) -/// while let player = try players.next() { -/// print(player.name, player.score) +/// ```swift +/// try dbQueue.read { db in +/// let statement = try db.makeStatement(sql: "SELECT * FROM player") +/// let rows = try Row.fetchCursor(statement) +/// while let row = try rows.next() { +/// let id: Int64 = row["id"] +/// let name: String = row["name"] +/// } /// } -/// } -/// ``` +/// ``` +/// +/// - A cursor of `Int` built from an SQL string (see ``DatabaseValueConvertible``): +/// +/// ```swift +/// try dbQueue.read { db in +/// let sql = "SELECT score FROM player" +/// let scores = try Int.fetchCursor(db, sql: sql) +/// while let score = try scores.next() { +/// print(score) +/// } +/// } +/// ``` +/// +/// - A cursor of `Player` records built from a request (see ``FetchableRecord`` and ``FetchRequest``): +/// +/// ```swift +/// try dbQueue.read { db in +/// let request = Player.all() +/// let players = try request.fetchCursor(db) +/// while let player = try players.next() { +/// print(player.name, player.score) +/// } +/// } +/// ``` /// /// A database cursor is valid only during the current database access (read or /// write). Do not store or escape a cursor for later use. diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index 4f6efbe02..24a69c248 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -45,7 +45,7 @@ try dbQueue.read { db } ``` -Alternatively, you can open an explicit transaction or savepoint with ``Database/inTransaction(_:_:)`` and ``Database/inSavepoint(_:)``. +Alternatively, you can open an explicit transaction or savepoint: see . - *Why does this rule exist?* - Because GRDB and SQLite can not guess where to insert the transaction boundaries that protect the invariants of your database. This is your task. Transactions also avoid concurrency problems, as described in the section below. diff --git a/GRDB/Documentation.docc/DatabaseConnections.md b/GRDB/Documentation.docc/DatabaseConnections.md index db6321bd9..d530d8c56 100644 --- a/GRDB/Documentation.docc/DatabaseConnections.md +++ b/GRDB/Documentation.docc/DatabaseConnections.md @@ -17,25 +17,28 @@ let dbPool = try DatabasePool(path: "/path/to/database.sqlite") The differences are: - `DatabasePool` allows concurrent database accesses (this can improve the performance of multithreaded applications). -- `DatabasePool` opens your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) (unless read-only). -- `DatabaseQueue` supports [in-memory databases](https://www.sqlite.org/inmemorydb.html). +- `DatabasePool` opens your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html). +- `DatabaseQueue` supports . **If you are not sure, choose `DatabaseQueue`.** You will always be able to switch to `DatabasePool` later. ## Topics -### Configuring Database Connections +### Configuring database connections - ``Configuration`` -### Database Connections +### Connections for read and write accesses - ``DatabaseQueue`` - ``DatabasePool`` + +### Read-only connections on an unchanging database content + - ``DatabaseSnapshot`` - ``DatabaseSnapshotPool`` -### Using Database Connections +### Using database connections - ``Database`` - ``DatabaseError`` diff --git a/GRDB/Documentation.docc/Documentation.md b/GRDB/Documentation.docc/Documentation.md index e6531907b..eead88397 100644 --- a/GRDB/Documentation.docc/Documentation.md +++ b/GRDB/Documentation.docc/Documentation.md @@ -21,6 +21,7 @@ Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMD - - - +- ### Migrations and The Database Schema diff --git a/GRDB/Documentation.docc/Extension/Configuration.md b/GRDB/Documentation.docc/Extension/Configuration.md new file mode 100644 index 000000000..3954ae64a --- /dev/null +++ b/GRDB/Documentation.docc/Extension/Configuration.md @@ -0,0 +1,104 @@ +# ``GRDB/Configuration`` + +The configuration of a database connection. + +## Overview + +You create a `Configuration` before opening a database connection: + +```swift +var config = Configuration() +config.readonly = true +config.maximumReaderCount = 2 // (DatabasePool only) The default is 5 + +let dbQueue = try DatabaseQueue( // or DatabasePool + path: "/path/to/database.sqlite", + configuration: config) +``` + +See . + +## Frequent Use Cases + +#### Tracing SQL Statements + +You can setup a tracing function that prints out all executed SQL requests with ``prepareDatabase(_:)`` and ``Database/trace(options:_:)``: + +```swift +var config = Configuration() +config.prepareDatabase { db in + db.trace { print("SQL> \($0)") } +} + +let dbQueue = try DatabaseQueue( + path: "/path/to/database.sqlite", + configuration: config) + +// Prints "SQL> SELECT COUNT(*) FROM player" +let playerCount = dbQueue.read { db in + try Player.fetchCount(db) +} +``` + +#### Public Statement Arguments + +Debugging is easier when database errors and tracing functions expose the values sent to the database. Since those values may contain sensitive information, verbose logging is disabled by default. You turn it on with ``publicStatementArguments``: + +```swift +var config = Configuration() +#if DEBUG +// Protect sensitive information by enabling +// verbose debugging in DEBUG builds only. +config.publicStatementArguments = true +#endif + +let dbQueue = try DatabaseQueue( + path: "/path/to/database.sqlite", + configuration: config) + +do { + try dbQueue.write { db in + user.name = ... + user.location = ... + user.address = ... + user.phoneNumber = ... + try user.save(db) + } +} catch { + // Prints sensitive information in debug builds only + print(error) +} +``` + +> Warning: It is your responsibility to prevent sensitive information from leaking in unexpected locations, so you should not set the `publicStatementArguments` flag in release builds (think about GDPR and other privacy-related rules). + +## Topics + +### Creating a Configuration + +- ``init()`` + +### Configuring SQLite Connections + +- ``acceptsDoubleQuotedStringLiterals`` +- ``busyMode`` +- ``foreignKeysEnabled`` +- ``readonly`` + +### Configuring GRDB Connections + +- ``allowsUnsafeTransactions`` +- ``defaultTransactionKind`` +- ``label`` +- ``maximumReaderCount`` +- ``observesSuspensionNotifications`` +- ``prepareDatabase(_:)`` +- ``publicStatementArguments`` + +### Configuring the Quality of Service + +- ``qos`` +- ``readQoS`` +- ``writeQoS`` +- ``targetQueue`` +- ``writeTargetQueue`` diff --git a/GRDB/Documentation.docc/Extension/DatabasePool.md b/GRDB/Documentation.docc/Extension/DatabasePool.md new file mode 100644 index 000000000..43c64f85e --- /dev/null +++ b/GRDB/Documentation.docc/Extension/DatabasePool.md @@ -0,0 +1,96 @@ +# ``GRDB/DatabasePool`` + +A database connection that allows concurrent accesses to an SQLite database. + +## Usage + +Open a `DatabasePool` with the path to a database file: + +```swift +import GRDB + +let dbPool = try DatabasePool(path: "/path/to/database.sqlite") +``` + +SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated. + +**A `DatabasePool` can be used from any thread.** The ``DatabaseWriter/write(_:)-76inz`` and ``DatabaseReader/read(_:)-3806d`` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: + +```swift +// Modify the database: +try dbPool.write { db in + try Player(name: "Arthur").insert(db) +} + +// Read values: +try dbPool.read { db in + let players = try Player.fetchAll(db) + let playerCount = try Player.fetchCount(db) +} +``` + +Database access methods can return values: + +```swift +let playerCount = try dbPool.read { db in + try Place.fetchCount(db) +} + +let newPlayerCount = try dbPool.write { db -> Int in + try Player(name: "Arthur").insert(db) + return try Player.fetchCount(db) +} +``` + +The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown. + +When you don't need to modify the database, prefer the ``DatabaseReader/read(_:)-3806d`` method, because several threads can perform reads in parallel. + +When precise transaction handling is required, see . + +Asynchronous database accesses are described in . + +`DatabasePool` can take snapshots of the database: see ``DatabaseSnapshot`` and ``DatabaseSnapshotPool``. + +`DatabasePool` can be configured with ``Configuration``. + +## Concurrency + +A `DatabasePool` creates one writer SQLite connection, and a pool of read-only SQLite connections. + +Unless ``Configuration/readonly``, the database is set to the [WAL mode](https://sqlite.org/wal.html). The WAL mode makes it possible for reads and writes to proceed concurrently. + +All write accesses are executed in a serial **writer dispatch queue**, which means that there is never more than one thread that writes in the database. + +All read accesses are executed in **reader dispatch queues** (one per read-only SQLite connection). Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be configured with ``Configuration/maximumReaderCount``. + +SQLite connections are closed when the `DatabasePool` is deallocated. + +`DatabasePool` inherits most of its database access methods from the ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few specific database access methods as well, listed below. + +A `DatabasePool` needs your application to follow rules in order to deliver its safety guarantees. See for more information. + +## Topics + +### Creating a DatabasePool + +- ``init(path:configuration:)`` + +### Accessing the Database + +See ``DatabaseReader`` and ``DatabaseWriter`` for more database +access methods. + +- ``asyncConcurrentRead(_:)`` +- ``writeInTransaction(_:_:)`` + +### Creating Database Snapshots + +- ``makeSnapshot()`` +- ``makeSnapshotPool()`` + +### Managing SQLite Connections + +- ``invalidateReadOnlyConnections()`` +- ``releaseMemory()`` +- ``releaseMemoryEventually()`` diff --git a/GRDB/Documentation.docc/Extension/DatabaseQueue.md b/GRDB/Documentation.docc/Extension/DatabaseQueue.md new file mode 100644 index 000000000..856bcc655 --- /dev/null +++ b/GRDB/Documentation.docc/Extension/DatabaseQueue.md @@ -0,0 +1,102 @@ +# ``GRDB/DatabaseQueue`` + +A database connection that serializes accesses to an SQLite database. + +## Usage + +Open a `DatabaseQueue` with the path to a database file: + +```swift +import GRDB + +let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") +``` + +SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated. + +**A `DatabaseQueue` can be used from any thread.** The ``DatabaseWriter/write(_:)-76inz`` and ``DatabaseReader/read(_:)-3806d`` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: + +```swift +// Modify the database: +try dbQueue.write { db in + try Player(name: "Arthur").insert(db) +} + +// Read values: +try dbQueue.read { db in + let players = try Player.fetchAll(db) + let playerCount = try Player.fetchCount(db) +} +``` + +Database access methods can return values: + +```swift +let playerCount = try dbQueue.read { db in + try Place.fetchCount(db) +} + +let newPlayerCount = try dbQueue.write { db -> Int in + try Player(name: "Arthur").insert(db) + return try Player.fetchCount(db) +} +``` + +The ``DatabaseWriter/write(_:)-76inz`` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown. + +When you don't need to modify the database, prefer the ``DatabaseReader/read(_:)-3806d`` method: it prevents any modification to the database. + +When precise transaction handling is required, see . + +Asynchronous database accesses are described in . + +`DatabaseQueue` can be configured with ``Configuration``. + +## In-Memory Databases + +`DatabaseQueue` can open a connection to an [in-memory SQLite database](https://www.sqlite.org/inmemorydb.html). + +Such connections are quite handy for tests and SwiftUI previews, since you do not have to perform any cleanup of the file system. + +```swift +let dbQueue = try DatabaseQueue() +``` + +In order to create several connections to the same in-memory database, give this database a name: + +```swift +// A shared in-memory database +let dbQueue1 = try DatabaseQueue(named: "myDatabase") + +// Another connection to the same database +let dbQueue2 = try DatabaseQueue(named: "myDatabase") +``` + +See ``init(named:configuration:)``. + +## Concurrency + +A `DatabaseQueue` creates one single SQLite connection. All database accesses are executed in a serial **writer dispatch queue**, which means that there is never more than one thread that uses the database. The SQLite connection is closed when the `DatabaseQueue` is deallocated. + +`DatabaseQueue` inherits most of its database access methods from the ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few specific database access methods as well, listed below. + +A `DatabaseQueue` needs your application to follow rules in order to deliver its safety guarantees. See for more information. + +## Topics + +### Creating a DatabaseQueue + +- ``init(named:configuration:)`` +- ``init(path:configuration:)`` + +### Accessing the Database + +See ``DatabaseReader`` and ``DatabaseWriter`` for more database +access methods. + +- ``inDatabase(_:)`` +- ``inTransaction(_:_:)`` + +### Managing the SQLite Connection + +- ``releaseMemory()`` diff --git a/GRDB/Documentation.docc/SQLSupport.md b/GRDB/Documentation.docc/SQLSupport.md index f857f08ef..7fbdb7cd0 100644 --- a/GRDB/Documentation.docc/SQLSupport.md +++ b/GRDB/Documentation.docc/SQLSupport.md @@ -23,7 +23,7 @@ try dbQueue.write { db in } ``` -Build prepared ``Statement`` and lazily iterate fetched rows with an efficient and fast ``DatabaseCursor``: +Build a prepared ``Statement`` and lazily iterate a ``DatabaseCursor`` of ``Row``: ```swift try dbQueue.read { db in diff --git a/GRDB/Documentation.docc/Transactions.md b/GRDB/Documentation.docc/Transactions.md new file mode 100644 index 000000000..b12c3f32f --- /dev/null +++ b/GRDB/Documentation.docc/Transactions.md @@ -0,0 +1,239 @@ +# Transactions and Savepoints + +## Transactions and Safety + +**A transaction is a fundamental tool of SQLite** that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. It is at the core of GRDB guarantees. + +To profit from database transactions, all you have to do is group related database statements in a single database access method such as ``DatabaseWriter/write(_:)-76inz`` or ``DatabaseReader/read(_:)-3806d``: + +```swift +// BEGIN TRANSACTION +// INSERT INTO credit ... +// INSERT INTO debit ... +// COMMIT +try dbQueue.write { db in + try Credit(destinationAccount, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) +} + +// BEGIN TRANSACTION +// SELECT * FROM credit +// SELECT * FROM debit +// COMMIT +let (credits, debits) = try dbQueue.read { db in + let credits = try Credit.fetchAll(db) + let debits = try Debit.fetchAll(db) + return (credits, debits) +} +``` + +In the following sections we'll explore how you can avoid transactions, and how to perform explicit transactions and savepoints. + +## Database Accesses without Transactions + +When needed, you can write outside of any transaction with ``DatabaseWriter/writeWithoutTransaction(_:)-4qh1w`` (also named `inDatabase(_:)`, for `DatabaseQueue`): + +```swift +// INSERT INTO credit ... +// INSERT INTO debit ... +try dbQueue.writeWithoutTransaction { db in + try Credit(destinationAccount, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) +} +``` + +For reads, use ``DatabaseReader/unsafeRead(_:)-5i7tf``: + +```swift +// SELECT * FROM credit +// SELECT * FROM debit +let (credits, debits) = try dbPool.unsafeRead { db in + let credits = try Credit.fetchAll(db) + let debits = try Debit.fetchAll(db) + return (credits, debits) +} +``` + +Those method names, `writeWithoutTransaction` and `unsafeRead`, are longer and "scarier" than the regular `write` and `read` in order to draw your attention to the dangers of those unisolated accesses. + +In our credit/debit example, a credit may be successfully inserted, but the debit insertion may fail, ending up with unbalanced accounts (oops). + +```swift +// UNSAFE DATABASE INTEGRITY +try dbQueue.writeWithoutTransaction { db in // or dbPool.writeWithoutTransaction + try Credit(destinationAccount, amount).insert(db) + // 😬 May fail after credit was successfully written to disk: + try Debit(sourceAccount, amount).insert(db) +} +``` + +Transactions avoid this kind of bug. + +``DatabasePool`` concurrent reads can see an inconsistent state of the database: + +```swift +// UNSAFE CONCURRENCY +try dbPool.writeWithoutTransaction { db in + try Credit(destinationAccount, amount).insert(db) + // <- 😬 Here a concurrent read sees a partial db update (unbalanced accounts) + try Debit(sourceAccount, amount).insert(db) +} +``` + +Transactions avoid this kind of bug, too. + +Finally, reads performed outside of any transaction are not isolated from concurrent writes. It is possible to see unbalanced accounts, even though the invariant is never broken on disk: + +```swift +// UNSAFE CONCURRENCY +let (credits, debits) = try dbPool.unsafeRead { db in + let credits = try Credit.fetchAll(db) + // <- 😬 Here a concurrent write can modify the balance before debits are fetched + let debits = try Debit.fetchAll(db) + return (credits, debits) +} +``` + +Yes, transactions also avoid this kind of bug. + +## Explicit Transactions + +To open explicit transactions, use `inTransaction()` or `writeInTransaction()`: + +```swift +// BEGIN TRANSACTION +// INSERT INTO credit ... +// INSERT INTO debit ... +// COMMIT +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction + try Credit(destinationAccount, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return .commit +} + +// BEGIN TRANSACTION +// INSERT INTO credit ... +// INSERT INTO debit ... +// COMMIT +try dbQueue.writeWithoutTransaction { db in + try db.inTransaction { + try Credit(destinationAccount, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return .commit + } +} +``` + +If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the transaction method. If the transaction closure returns `.rollback` instead of `.commit`, the transaction is also rollbacked, but no error is thrown. + +Full manual transaction management is also possible: + +```swift +try dbQueue.writeWithoutTransaction { db + try db.beginTransaction() + ... + try db.commit() + + try db.execute(sql: "BEGIN TRANSACTION") + ... + try db.execute(sql: "ROLLBACK") +} +``` + +Transactions can't be left opened unless the ``Configuration/allowsUnsafeTransactions`` configuration flag is set: + +```swift +// fatal error: A transaction has been left opened at the end of a database access +try dbQueue.writeWithoutTransaction { db in + try db.execute(sql: "BEGIN TRANSACTION") + // <- no commit or rollback +} +``` + +It is possible to ask if a transaction is currently opened: + +```swift +func myCriticalMethod(_ db: Database) throws { + precondition(db.isInsideTransaction, "This method requires a transaction") + try ... +} +``` + +Yet, there is a better option than checking for transactions. Critical database sections should use savepoints, described below: + +```swift +func myCriticalMethod(_ db: Database) throws { + try db.inSavepoint { + // Here the database is guaranteed to be inside a transaction. + try ... + } +} +``` + +## Savepoints + +**Statements grouped in a savepoint can be rollbacked without invalidating a whole transaction:** + +```swift +try dbQueue.write { db in + // Makes sure both inserts succeed, or none: + try db.inSavepoint { + try Credit(destinationAccount, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return .commit + } + + // Other savepoints, etc... +} +``` + +If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the `inSavepoint` method. If the savepoint closure returns `.rollback` instead of `.commit`, the savepoint is also rollbacked, but no error is thrown. + +**Unlike transactions, savepoints can be nested.** They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only written to disk when the outermost transaction is committed: + +```swift +try dbQueue.writeWithoutTransaction { db in + try db.inSavepoint { + ... + try db.inSavepoint { + ... + return .commit + } + ... + return .commit // Writes changes to disk + } +} +``` + +SQLite savepoints are more than nested transactions, though. For advanced uses, use [SQLite savepoint documentation](https://www.sqlite.org/lang_savepoint.html). + + +## Transaction Kinds + +SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive. + +The transaction kind can be chosen for individual transaction: + +```swift +let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") + +// BEGIN EXCLUSIVE TRANSACTION ... +try dbQueue.inTransaction(.exclusive) { db in ... } +``` + +It is also possible to configure the ``Configuration/defaultTransactionKind``: + +```swift +var config = Configuration() +config.defaultTransactionKind = .immediate + +let dbQueue = try DatabaseQueue( + path: "/path/to/database.sqlite", + configuration: config) + +// BEGIN IMMEDIATE TRANSACTION ... +try dbQueue.write { db in ... } + +// BEGIN IMMEDIATE TRANSACTION ... +try dbQueue.inTransaction { db in ... } +``` diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index e755deea2..9beba1c2c 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -206,6 +206,16 @@ extension Database { /// /// For extra index options, see ``create(index:on:columns:options:condition:)``. /// + /// ### Generated columns + /// + /// See [Generated columns](https://sqlite.org/gencol.html) for + /// more information: + /// + /// ```swift + /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") + /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) + /// ``` + /// /// ### Integrity checks /// /// SQLite will only let conforming rows in: @@ -224,16 +234,6 @@ extension Database { /// t.check(sql: "a + b < 10") /// ``` /// - /// ### Generated columns - /// - /// [Generated columns](https://sqlite.org/gencol.html) are available with a - /// [custom SQLite build](https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md): - /// - /// ```swift - /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") - /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) - /// ``` - /// /// ### Raw SQL columns and constraints /// /// Columns and constraints can be defined with raw sql: @@ -1396,6 +1396,12 @@ public final class TableAlteration { /// - ``collate(_:)-4dljx`` /// - ``collate(_:)-9ywza`` /// +/// ### Generated Columns +/// +/// - ``generatedAs(_:_:)`` +/// - ``generatedAs(sql:_:)`` +/// - ``GeneratedColumnQualification`` +/// /// ### Other Constraints /// /// - ``check(_:)`` @@ -1423,12 +1429,13 @@ public final class ColumnDefinition { var deferred: Bool } - /// The `GeneratedColumnQualification` enum defines whether a generated - /// column sis virtual or stored. + /// The kind of a generated column. /// /// Related SQLite documentation: public enum GeneratedColumnQualification { + /// A `VIRTUAL` generated column. case virtual + /// A `STORED` generated column. case stored } @@ -1699,7 +1706,7 @@ public final class ColumnDefinition { return self } - #if GRDBCUSTOMSQLITE +#if GRDBCUSTOMSQLITE || GRDBCIPHER /// Defines the column as a generated column. /// /// For example: @@ -1709,13 +1716,13 @@ public final class ColumnDefinition { /// // id INTEGER PRIMARY KEY AUTOINCREMENT, /// // score INTEGER NOT NULL, /// // bonus INTEGER NOT NULL, - /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) STORED + /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL /// // ) /// try db.create(table: "player") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("score", .integer).notNull() /// t.column("bonus", .integer).notNull() - /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus", .stored) + /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") /// } /// ``` /// @@ -1748,13 +1755,13 @@ public final class ColumnDefinition { /// // id INTEGER PRIMARY KEY AUTOINCREMENT, /// // score INTEGER NOT NULL, /// // bonus INTEGER NOT NULL, - /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) STORED + /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL /// // ) /// try db.create(table: "player") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("score", .integer).notNull() /// t.column("bonus", .integer).notNull() - /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"), .stored) + /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) /// } /// ``` /// @@ -1776,6 +1783,85 @@ public final class ColumnDefinition { qualification: qualification) return self } + #else + /// Defines the column as a generated column. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // score INTEGER NOT NULL, + /// // bonus INTEGER NOT NULL, + /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("score", .integer).notNull() + /// t.column("bonus", .integer).notNull() + /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - sql: An SQL expression. + /// - qualification: The generated column's qualification, which + /// defaults to ``GeneratedColumnQualification/virtual``. + /// - returns: `self` so that you can further refine the column definition. + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ (3.31 actually) + @discardableResult + public func generatedAs( + sql: String, + _ qualification: GeneratedColumnQualification = .virtual) + -> Self + { + let expression = SQL(sql: sql).sqlExpression + generatedColumnConstraint = GeneratedColumnConstraint( + expression: expression, + qualification: qualification) + return self + } + + /// Defines the column as a generated column. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // score INTEGER NOT NULL, + /// // bonus INTEGER NOT NULL, + /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("score", .integer).notNull() + /// t.column("bonus", .integer).notNull() + /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - expression: The generated expression. + /// - qualification: The generated column's qualification, which + /// defaults to ``GeneratedColumnQualification/virtual``. + /// - returns: `self` so that you can further refine the column definition. + @available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+ (3.31 actually) + @discardableResult + public func generatedAs( + _ expression: some SQLExpressible, + _ qualification: GeneratedColumnQualification = .virtual) + -> Self + { + generatedColumnConstraint = GeneratedColumnConstraint( + expression: expression.sqlExpression, + qualification: qualification) + return self + } #endif /// Adds a foreign key constraint. diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index 63c2f4df1..b4e94fc3a 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -18,13 +18,13 @@ import Foundation /// reducing stage. /// /// **Notify** is calling user callbacks, in case of database change or error. -final class ValueConcurrentObserver { +final class ValueConcurrentObserver { // MARK: - Configuration // // Configuration is not mutable. /// How to schedule observed values and errors. - private let scheduler: ValueObservationScheduler + private let scheduler: Scheduler /// Configures the tracked database region. private let trackingMode: ValueObservationTrackingMode @@ -141,7 +141,7 @@ final class ValueConcurrentObserver { init( dbPool: DatabasePool, - scheduler: ValueObservationScheduler, + scheduler: Scheduler, trackingMode: ValueObservationTrackingMode, reducer: Reducer, events: ValueObservationEvents, diff --git a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift index ba49a7449..404e73de5 100644 --- a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift @@ -18,13 +18,13 @@ import Foundation /// reducing stage. /// /// **Notify** is calling user callbacks, in case of database change or error. -final class ValueWriteOnlyObserver { +final class ValueWriteOnlyObserver { // MARK: - Configuration // // Configuration is not mutable. /// How to schedule observed values and errors. - private let scheduler: ValueObservationScheduler + private let scheduler: Scheduler /// Configures the tracked database region. private let trackingMode: ValueObservationTrackingMode @@ -141,7 +141,7 @@ final class ValueWriteOnlyObserver SharedValueObservation where Reducer: ValueReducer @@ -168,7 +168,7 @@ extension ValueObservation { /// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) /// ``` public final class SharedValueObservation { - private let scheduler: ValueObservationScheduler + private let scheduler: any ValueObservationScheduler private let extent: SharedValueObservationExtent private let startObservation: ValueObservationStart private let lock = NSRecursiveLock() // support synchronous observation events @@ -190,7 +190,7 @@ public final class SharedValueObservation { } fileprivate init( - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, extent: SharedValueObservationExtent, startObservation: @escaping ValueObservationStart) { diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 9db7ef096..d3f1bb2cb 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -475,7 +475,7 @@ extension ValueObservation: Refinable { /// - returns: A DatabaseCancellable that can stop the observation. public func start( in reader: some DatabaseReader, - scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), + scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main), onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> AnyDatabaseCancellable @@ -637,7 +637,7 @@ extension ValueObservation { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func values( in reader: some DatabaseReader, - scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), + scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main), bufferingPolicy: AsyncValueObservation.BufferingPolicy = .unbounded) -> AsyncValueObservation where Reducer: ValueReducer @@ -774,7 +774,7 @@ extension ValueObservation { @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func publisher( in reader: some DatabaseReader, - scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main)) + scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main)) -> DatabasePublishers.Value where Reducer: ValueReducer { diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index 488d7fac0..6ca3447cf 100644 --- a/GRDB/ValueObservation/ValueObservationScheduler.swift +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -1,68 +1,26 @@ import Dispatch import Foundation -/// ValueObservationScheduler determines how `ValueObservation` notifies its -/// fresh values. -public class ValueObservationScheduler { - private let impl: any ValueObservationSchedulerImpl - - private init(impl: any ValueObservationSchedulerImpl) { - self.impl = impl - } - - func schedule(_ action: @escaping () -> Void) { - impl.schedule(action) - } - +/// A type that determines when `ValueObservation` notifies its fresh values. +/// +/// ## Topics +/// +/// ### Built-In Schedulers +/// +/// - ``async(onQueue:)`` +/// - ``immediate`` +/// - ``AsyncValueObservationScheduler`` +/// - ``ImmediateValueObservationScheduler`` +public protocol ValueObservationScheduler { /// Returns whether the initial value should be immediately notified. /// - /// If true, then this method was called on the main thread. - func immediateInitialValue() -> Bool { - impl.immediateInitialValue() - } - - /// A scheduler which asynchronously notifies fresh value of the - /// given DispatchQueue. - /// - /// For example: - /// - /// let observation = ValueObservation.tracking { db in - /// try Player.fetchAll(db) - /// } - /// - /// let cancellable = try observation.start( - /// in: dbQueue, - /// scheduling: .async(onQueue: .main), - /// onError: { error in ... }, - /// onChange: { (players: [Player]) in - /// print("fresh players: \(players)") - /// }) - public static func async(onQueue queue: DispatchQueue) -> ValueObservationScheduler { - ValueObservationScheduler(impl: queue) - } - - /// A scheduler which notifies all values on the main queue. The first one - /// is immediately notified when the start() method is called. - /// - /// For example: - /// - /// let observation = ValueObservation.tracking { db in - /// try Player.fetchAll(db) - /// } - /// - /// let cancellable = try observation.start( - /// in: dbQueue, - /// scheduling: .immediate, - /// onError: { error in ... }, - /// onChange: { (players: [Player]) in - /// print("fresh players: \(players)") - /// }) - /// // <- here "fresh players" is already printed. - /// - /// - important: this scheduler requires that the observation is started - /// from the main queue. A fatal error is raised otherwise. - public static let immediate = ValueObservationScheduler(impl: ImmediateImpl()) + /// If the result is true, then this method was called on the main thread. + func immediateInitialValue() -> Bool + func schedule(_ action: @escaping () -> Void) +} + +extension ValueObservationScheduler { func scheduleInitial(_ action: @escaping () -> Void) { if immediateInitialValue() { action() @@ -72,34 +30,92 @@ public class ValueObservationScheduler { } } -private protocol ValueObservationSchedulerImpl { - func schedule(_ action: @escaping () -> Void) - - /// Returns whether the initial value should be immediately notified. - /// - /// If true, then this method was called on the main thread. - func immediateInitialValue() -> Bool -} +// MARK: - AsyncValueObservationScheduler -private struct ImmediateImpl: ValueObservationSchedulerImpl { - func schedule(_ action: @escaping () -> Void) { - DispatchQueue.main.async(execute: action) +/// A scheduler that asynchronously notifies fresh value of a `DispatchQueue`. +public struct AsyncValueObservationScheduler: ValueObservationScheduler { + var queue: DispatchQueue + + public init(queue: DispatchQueue) { + self.queue = queue } - func immediateInitialValue() -> Bool { + public func immediateInitialValue() -> Bool { false } + + public func schedule(_ action: @escaping () -> Void) { + queue.async(execute: action) + } +} + +extension ValueObservationScheduler where Self == AsyncValueObservationScheduler { + /// A scheduler that asynchronously notifies fresh value of the + /// given `DispatchQueue`. + /// + /// For example: + /// + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let cancellable = try observation.start( + /// in: dbQueue, + /// scheduling: .async(onQueue: .main), + /// onError: { error in ... }, + /// onChange: { (players: [Player]) in + /// print("fresh players: \(players)") + /// }) + /// ``` + public static func async(onQueue queue: DispatchQueue) -> AsyncValueObservationScheduler { + AsyncValueObservationScheduler(queue: queue) + } +} + +// MARK: - ImmediateValueObservationScheduler + +/// A scheduler that notifies all values on the main `DispatchQueue`. The +/// first value is immediately notified when the `ValueObservation` +/// is started. +public struct ImmediateValueObservationScheduler: ValueObservationScheduler { + public init() { } + + public func immediateInitialValue() -> Bool { GRDBPrecondition( Thread.isMainThread, "ValueObservation must be started from the main thread.") return true } + + public func schedule(_ action: @escaping () -> Void) { + DispatchQueue.main.async(execute: action) + } } -extension DispatchQueue: ValueObservationSchedulerImpl { - func schedule(_ action: @escaping () -> Void) { - async(execute: action) - } - - func immediateInitialValue() -> Bool { - false +extension ValueObservationScheduler where Self == ImmediateValueObservationScheduler { + /// A scheduler that notifies all values on the main `DispatchQueue`. The + /// first value is immediately notified when the `ValueObservation` + /// is started. + /// + /// For example: + /// + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let cancellable = try observation.start( + /// in: dbQueue, + /// scheduling: .immediate, + /// onError: { error in ... }, + /// onChange: { (players: [Player]) in + /// print("fresh players: \(players)") + /// }) + /// // <- here "fresh players" is already printed. + /// ``` + /// + /// - important: this scheduler requires that the observation is started + /// from the main queue. A fatal error is raised otherwise. + public static var immediate: ImmediateValueObservationScheduler { + ImmediateValueObservationScheduler() } } diff --git a/Makefile b/Makefile index 942233b73..0dc02d847 100644 --- a/Makefile +++ b/Makefile @@ -10,78 +10,14 @@ default: test smokeTest: test_framework_GRDBiOS_maxTarget test_framework_GRDBiOS_minTarget test_framework_SQLCipher3 test_framework_SQLCipher4Encrypted test_framework_GRDBCustomSQLiteiOS_maxTarget test_SPM -# Requirements -# ============ -# -# Xcode -# CocoaPods - https://cocoapods.org +# ===== +# Tools GIT := $(shell command -v git) POD := $(shell command -v pod) XCRUN := $(shell command -v xcrun) XCODEBUILD := set -o pipefail && $(shell command -v xcodebuild) -# Xcode Version Information -XCODEVERSION_FULL := $(word 2, $(shell xcodebuild -version)) -XCODEVERSION_MAJOR := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f1) -XCODEVERSION_MINOR := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f2) -XCODEVERSION_PATCH := $(shell xcodebuild -version 2>&1 | grep Xcode | cut -d' ' -f2 | cut -d'.' -f3) - -# The Xcode Version, containing only the "MAJOR.MINOR" (ex. "8.3" for Xcode 8.3, 8.3.1, etc.) -XCODEVERSION := $(XCODEVERSION_MAJOR).$(XCODEVERSION_MINOR) - -# Used to determine if xcpretty is available -XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null) - -# Avoid the "No output has been received in the last 10m0s" error on Travis: -COCOAPODS_EXTRA_TIME = -ifeq ($(TRAVIS),true) - COCOAPODS_EXTRA_TIME = --verbose -endif - -DOCS_PATH = Documentation/Reference - -# Tests -# ===== - -# xcodebuild actions to run test targets -TEST_ACTIONS = clean build build-for-testing test-without-building - -# When adding support for an Xcode version, look for available devices with -# `xcrun xctrace list devices` (or the deprecated `instruments -s devices`). -ifeq ($(XCODEVERSION),14.1) - MAX_SWIFT_VERSION = 5.7 - MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 14,OS=16.1" - #MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=12.4" TODO: restore - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=16.1" - #MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' # -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else ifeq ($(XCODEVERSION),14.0) - MAX_SWIFT_VERSION = 5.7 - MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 13,OS=16.0" - MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=12.4" - MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=16.0" - #MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4" TODO: restore - OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' # -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks' - GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' -else - # Swift 5.3 required: Xcode < 12.0 is not supported -endif - -# If xcpretty is available, use it for xcodebuild output -XCPRETTY = -ifdef XCPRETTY_PATH - XCPRETTY = | xcpretty -c - - # On Travis-CI, use xcpretty-travis-formatter - ifeq ($(TRAVIS),true) - XCPRETTY += -f `xcpretty-travis-formatter` - endif -endif - ifdef TOOLCHAIN # If TOOLCHAIN is specified, add xcodebuild parameter XCODEBUILD += -toolchain $(TOOLCHAIN) @@ -100,12 +36,37 @@ else SWIFT = $(shell $(XCRUN) --find swift 2> /dev/null) endif -# We test framework test suites, and if GRBD can be installed in an application: +# ===== +# Configuration + +DOCS_PATH = Documentation/Reference + +TEST_ACTIONS = clean build build-for-testing test-without-building + +OTHER_SWIFT_FLAGS = '$$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' # -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks' +GCC_PREPROCESSOR_DEFINITIONS = '$$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' + +# Extract min and max destinations from the available devices +MIN_IOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/destination.rb | grep iPhone | grep -v ^13\.7 | sort -n | head -1 | cut -wf 3 | sed 's/\(.*\)/"platform=iOS Simulator,id=\1"/') +MAX_IOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/destination.rb | grep iPhone | grep -v ^13\.7 | sort -rn | head -1 | cut -wf 3 | sed 's/\(.*\)/"platform=iOS Simulator,id=\1"/') +MIN_TVOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/destination.rb | grep tvOS | sort -n | head -1 | cut -wf 3 | sed 's/\(.*\)/"platform=tvOS Simulator,id=\1"/') +MAX_TVOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/destination.rb | grep tvOS | sort -rn | head -1 | cut -wf 3 | sed 's/\(.*\)/"platform=tvOS Simulator,id=\1"/') + +# If xcpretty is available, use it for xcodebuild output +XCPRETTY = +XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null) +ifdef XCPRETTY_PATH + XCPRETTY = | xcpretty -c +endif + +# ===== +# Tests + test: test_framework test_archive test_install test_demo_apps test_framework: test_framework_darwin test_framework_darwin: test_framework_GRDB test_framework_GRDBCustom test_framework_SQLCipher test_SPM -test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBWatchOS test_framework_GRDBiOS test_framework_GRDBtvOS +test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBiOS test_framework_GRDBtvOS test_framework_GRDBCustom: test_framework_GRDBCustomSQLiteOSX test_framework_GRDBCustomSQLiteiOS test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher3Encrypted test_framework_SQLCipher4 test_framework_SQLCipher4Encrypted test_archive: test_archive_GRDBOSX_xcframework @@ -113,144 +74,80 @@ test_install: test_install_manual test_install_SPM test_install_customSQLite tes test_CocoaPodsLint: test_CocoaPodsLint_GRDB test_demo_apps: test_GRDBDemoiOS test_GRDBCombineDemo test_GRDBAsyncDemo -test_framework_GRDBOSX: test_framework_GRDBOSX_maxSwift test_framework_GRDBOSX_minSwift - -test_framework_GRDBOSX_maxSwift: +test_framework_GRDBOSX: $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDB \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ + -destination "platform=macOS" \ OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ - $(TEST_ACTIONS) - -test_framework_GRDBOSX_minSwift: -ifdef MIN_SWIFT_VERSION - $(XCODEBUILD) \ - -project GRDB.xcodeproj \ - -scheme GRDB \ - SWIFT_VERSION=$(MIN_SWIFT_VERSION) \ - OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ - GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ - $(TEST_ACTIONS) -endif - -test_framework_GRDBWatchOS: - # XCTest is not supported for watchOS: we only make sure that the framework builds. - $(XCODEBUILD) \ - -project GRDB.xcodeproj \ - -scheme GRDB \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - clean build \ + $(TEST_ACTIONS) \ $(XCPRETTY) test_framework_GRDBiOS: test_framework_GRDBiOS_maxTarget test_framework_GRDBiOS_minTarget -test_framework_GRDBiOS_maxTarget: test_framework_GRDBiOS_maxTarget_maxSwift test_framework_GRDBiOS_maxTarget_minSwift -test_framework_GRDBiOS_maxTarget_maxSwift: +test_framework_GRDBiOS_maxTarget: $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDB \ -destination $(MAX_IOS_DESTINATION) \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ - $(TEST_ACTIONS) - -test_framework_GRDBiOS_maxTarget_minSwift: -ifdef MIN_SWIFT_VERSION - $(XCODEBUILD) \ - -project GRDB.xcodeproj \ - -scheme GRDB \ - -destination $(MAX_IOS_DESTINATION) \ - SWIFT_VERSION=$(MIN_SWIFT_VERSION) \ - OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ - GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ - $(TEST_ACTIONS) -endif + $(TEST_ACTIONS) \ + $(XCPRETTY) test_framework_GRDBiOS_minTarget: -ifdef MIN_IOS_DESTINATION $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDB \ -destination $(MIN_IOS_DESTINATION) \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - $(TEST_ACTIONS) -endif + $(TEST_ACTIONS) \ + $(XCPRETTY) test_framework_GRDBtvOS: test_framework_GRDBtvOS_maxTarget test_framework_GRDBtvOS_minTarget -test_framework_GRDBtvOS_maxTarget: test_framework_GRDBtvOS_maxTarget_maxSwift test_framework_GRDBtvOS_maxTarget_minSwift -test_framework_GRDBtvOS_maxTarget_maxSwift: +test_framework_GRDBtvOS_maxTarget: $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDB \ -destination $(MAX_TVOS_DESTINATION) \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ - $(TEST_ACTIONS) - -test_framework_GRDBtvOS_maxTarget_minSwift: -ifdef MIN_SWIFT_VERSION - $(XCODEBUILD) \ - -project GRDB.xcodeproj \ - -scheme GRDB \ - -destination $(MAX_TVOS_DESTINATION) \ - SWIFT_VERSION=$(MIN_SWIFT_VERSION) \ - OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ - GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ - $(TEST_ACTIONS) -endif + $(TEST_ACTIONS) \ + $(XCPRETTY) test_framework_GRDBtvOS_minTarget: -ifdef MIN_TVOS_DESTINATION $(XCODEBUILD) \ -project GRDB.xcodeproj \ -scheme GRDB \ -destination $(MIN_TVOS_DESTINATION) \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - $(TEST_ACTIONS) -endif + $(TEST_ACTIONS) \ + $(XCPRETTY) test_framework_GRDBCustomSQLiteOSX: SQLiteCustom $(XCODEBUILD) \ -project GRDBCustom.xcodeproj \ -scheme GRDBCustom \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - $(TEST_ACTIONS) + $(TEST_ACTIONS) \ + $(XCPRETTY) test_framework_GRDBCustomSQLiteiOS: test_framework_GRDBCustomSQLiteiOS_maxTarget test_framework_GRDBCustomSQLiteiOS_minTarget -test_framework_GRDBCustomSQLiteiOS_maxTarget: test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift -test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift: SQLiteCustom +test_framework_GRDBCustomSQLiteiOS_maxTarget: SQLiteCustom $(XCODEBUILD) \ -project GRDBCustom.xcodeproj \ -scheme GRDBCustom \ -destination $(MAX_IOS_DESTINATION) \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - $(TEST_ACTIONS) - -test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift: SQLiteCustom -ifdef MIN_SWIFT_VERSION - $(XCODEBUILD) \ - -project GRDBCustom.xcodeproj \ - -scheme GRDBCustom \ - -destination $(MAX_IOS_DESTINATION) \ - SWIFT_VERSION=$(MIN_SWIFT_VERSION) \ - $(TEST_ACTIONS) -endif + $(TEST_ACTIONS) \ + $(XCPRETTY) test_framework_GRDBCustomSQLiteiOS_minTarget: SQLiteCustom -ifdef MIN_IOS_DESTINATION $(XCODEBUILD) \ -project GRDBCustom.xcodeproj \ -scheme GRDBCustom \ -destination $(MIN_IOS_DESTINATION) \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - $(TEST_ACTIONS) -endif + $(TEST_ACTIONS) \ + $(XCPRETTY) test_framework_SQLCipher3: ifdef POD @@ -259,8 +156,8 @@ ifdef POD $(XCODEBUILD) \ -workspace GRDBTests.xcworkspace \ -scheme GRDBTests \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - build-for-testing test-without-building + build-for-testing test-without-building \ + $(XCPRETTY) else @echo CocoaPods must be installed for test_framework_SQLCipher3 @exit 1 @@ -273,8 +170,8 @@ ifdef POD $(XCODEBUILD) \ -workspace GRDBTests.xcworkspace \ -scheme GRDBEncryptedTests \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - build-for-testing test-without-building + build-for-testing test-without-building \ + $(XCPRETTY) else @echo CocoaPods must be installed for test_framework_SQLCipher3Encrypted @exit 1 @@ -287,8 +184,8 @@ ifdef POD $(XCODEBUILD) \ -workspace GRDBTests.xcworkspace \ -scheme GRDBTests \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - build-for-testing test-without-building + build-for-testing test-without-building \ + $(XCPRETTY) else @echo CocoaPods must be installed for test_framework_SQLCipher4 @exit 1 @@ -301,8 +198,8 @@ ifdef POD $(XCODEBUILD) \ -workspace GRDBTests.xcworkspace \ -scheme GRDBEncryptedTests \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - build-for-testing test-without-building + build-for-testing test-without-building \ + $(XCPRETTY) else @echo CocoaPods must be installed for test_framework_SQLCipher4Encrypted @exit 1 @@ -323,7 +220,6 @@ test_archive_GRDBOSX_xcframework: -scheme GRDB \ -configuration Release \ -destination "generic/platform=macOS" \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ -archivePath "$(PWD)/Tests/products/GRDB.xcarchive" \ @@ -427,7 +323,7 @@ endif test_CocoaPodsLint_GRDB: ifdef POD - $(POD) lib lint GRDB.swift.podspec --allow-warnings $(COCOAPODS_EXTRA_TIME) + $(POD) lib lint GRDB.swift.podspec --allow-warnings else @echo CocoaPods must be installed for test_CocoaPodsLint_GRDB @exit 1 @@ -438,24 +334,24 @@ test_GRDBDemoiOS: -project Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj \ -scheme GRDBDemoiOS \ -destination $(MAX_IOS_DESTINATION) \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - $(TEST_ACTIONS) + $(TEST_ACTIONS) \ + $(XCPRETTY) test_GRDBCombineDemo: $(XCODEBUILD) \ -project Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj \ -scheme GRDBCombineDemo \ -destination $(MAX_IOS_DESTINATION) \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - $(TEST_ACTIONS) + $(TEST_ACTIONS) \ + $(XCPRETTY) test_GRDBAsyncDemo: $(XCODEBUILD) \ -project Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj \ -scheme GRDBAsyncDemo \ -destination $(MAX_IOS_DESTINATION) \ - SWIFT_VERSION=$(MAX_SWIFT_VERSION) \ - $(TEST_ACTIONS) + $(TEST_ACTIONS) \ + $(XCPRETTY) test_performance: $(XCODEBUILD) \ diff --git a/README.md b/README.md index 1606288bf..6d687feed 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: December 5, 2022 • [version 6.5.0](https://github.com/groue/GRDB.swift/tree/v6.5.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: December 29, 2022 • [version 6.6.0](https://github.com/groue/GRDB.swift/tree/v6.6.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.7+** | **v6.5.0** | +| **Swift 5.7+** | **v6.6.0** | | Swift 5.3 | [v5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) | | Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -70,7 +70,7 @@ Programming tools for both database beginners and SQLite experts: - [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies. - [Query Interface](#the-query-interface): A swift way to avoid the SQL language. - [Associations]: Relations and joins between record types. -- [WAL Mode Support](#database-pools): Extra performance for multi-threaded applications. +- [WAL Mode Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool): Extra performance for multi-threaded applications. - [Migrations]: Transform your database as your application evolves. - [Database Observation]: Observe database changes and transactions. - [Full-Text Search] @@ -428,7 +428,7 @@ GRDB offers two libraries, `GRDB` and `GRDB-dynamic`. Pick only one. When in dou Database Connections ==================== -GRDB provides two classes for accessing SQLite databases: `DatabaseQueue` and `DatabasePool`: +GRDB provides two classes for accessing SQLite databases: [`DatabaseQueue`] and [`DatabasePool`]: ```swift import GRDB @@ -444,179 +444,7 @@ The differences are: - Database pools open your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) (unless read-only). - Database queues support [in-memory databases](https://www.sqlite.org/inmemorydb.html). -**If you are not sure, choose DatabaseQueue.** You will always be able to switch to DatabasePool later. - -- [Database Queues](#database-queues) -- [Database Pools](#database-pools) - - -## Database Queues - -**Open a database queue** with the path to a database file: - -```swift -import GRDB - -let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") -let inMemoryDBQueue = try DatabaseQueue() -``` - -SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deinitialized. - -**A database queue can be used from any thread.** The `write` and `read` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: - -```swift -// Modify the database: -try dbQueue.write { db in - try db.create(table: "place") { ... } - try Place(...).insert(db) -} - -// Read values: -try dbQueue.read { db in - let places = try Place.fetchAll(db) - let placeCount = try Place.fetchCount(db) -} -``` - -Database access methods can return values: - -```swift -let placeCount = try dbQueue.read { db in - try Place.fetchCount(db) -} - -let newPlaceCount = try dbQueue.write { db -> Int in - try Place(...).insert(db) - return try Place.fetchCount(db) -} -``` - -See the [Concurrency] guide for asynchronous database accesses. - -**A database queue serializes accesses to the database**, which means that there is never more than one thread that uses the database. - -- When you don't need to modify the database, prefer the `read` method. It prevents any modification to the database. - -- The `write` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown. - - When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints). - -**A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency] guide. - -See [Database Configuration] for DatabaseQueue options. - -> :bulb: **Tip**: see the [Demo Applications] for sample code. - - -## Database Pools - -**A database pool allows concurrent database accesses.** - -```swift -import GRDB -let dbPool = try DatabasePool(path: "/path/to/database.sqlite") -``` - -SQLite creates the database file if it does not already exist. The connection is closed when the database pool gets deinitialized. - -> **Note**: unless read-only, a database pool opens your database in the SQLite "WAL mode". The WAL mode does not fit all situations. Please have a look at https://www.sqlite.org/wal.html. - -**A database pool can be used from any thread.** The `write` and `read` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: - -```swift -// Modify the database: -try dbPool.write { db in - try db.create(table: "place") { ... } - try Place(...).insert(db) -} - -// Read values: -try dbPool.read { db in - let places = try Place.fetchAll(db) - let placeCount = try Place.fetchCount(db) -} -``` - -Database access methods can return values: - -```swift -let placeCount = try dbPool.read { db in - try Place.fetchCount(db) -} - -let newPlaceCount = try dbPool.write { db -> Int in - try Place(...).insert(db) - return try Place.fetchCount(db) -} -``` - -See the [Concurrency] guide for asynchronous database accesses. - -**Database pools allow several threads to access the database at the same time:** - -- When you don't need to modify the database, prefer the `read` method, because several threads can perform reads in parallel. - - Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#database-configuration). - -- Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called [snapshot isolation](https://sqlite.org/isolation.html). - -- Unlike reads, writes are serialized. There is never more than a single thread that is writing into the database. - -- The `write` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, all changes are reverted, the whole transaction is rollbacked, and the error is rethrown. - - When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints). - -- Database pools can take [snapshots](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot) of the database. - -**A database pool needs your application to follow rules in order to deliver its safety guarantees.** See the [Concurrency] guide for more details about database pools, how they differ from database queues, and advanced use cases. - -See [Database Configuration] for DatabasePool options. - -> :bulb: **Tip**: see the [Demo Applications] for sample code. - - -## Database Configuration - -```swift -var config = Configuration() -config.readonly = true -config.foreignKeysEnabled = true // Default is already true -config.label = "MyDatabase" // Useful when your app opens multiple databases -config.maximumReaderCount = 10 // (DatabasePool only) The default is 5 - -let dbQueue = try DatabaseQueue( // or DatabasePool - path: "/path/to/database.sqlite", - configuration: config) -``` - -In debug builds, you can increase the verbosity of [error descriptions](#databaseerror) and [trace events](#how-do-i-print-a-request-as-sql) if you opt in for public statement arguments: - -```swift -#if DEBUG -// Protect sensitive information by enabling verbose debugging in DEBUG builds only -config.publicStatementArguments = true -#endif - -let dbQueue = try DatabaseQueue(path: ..., configuration: config) - -do { - try dbQueue.write { db in - user.name = ... - user.location = ... - user.address = ... - user.phoneNumber = ... - try user.save(db) - } -} catch { - // Prints sensitive information in debug builds only - print(error) -} -``` - -> **Warning**: It is your responsibility to prevent sensitive information from leaking in unexpected locations, so you should not set the `publicStatementArguments` flag in release builds (think about GDPR and other privacy-related rules). - -See [Configuration](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration) for more details and configuration options. +**If you are not sure, choose `DatabaseQueue`.** You will always be able to switch to `DatabasePool` later. SQLite API @@ -635,7 +463,7 @@ SQLite API - [NSNumber, NSDecimalNumber, and Decimal](#nsnumber-nsdecimalnumber-and-decimal) - [Swift enums](#swift-enums) - [Custom Value Types](#custom-value-types) -- [Transactions and Savepoints](#transactions-and-savepoints) +- [Transactions and Savepoints] - [SQL Interpolation] Advanced topics: @@ -1665,230 +1493,6 @@ In order to customize the JSON format, provide a custom implementation of the `D > **Note**: standard sequences such as `Array`, `Set`, or `Dictionary` do not conform to `DatabaseValueConvertible`, even conditionally. You won't be able to directly fetch or store arrays, sets, or dictionaries as JSON database values. You can get free JSON support from these standard types when they are embedded as properties of [Codable Records], though. -## Transactions and Savepoints - -- [Transactions and Safety](#transactions-and-safety) -- [Explicit Transactions](#explicit-transactions) -- [Savepoints](#savepoints) -- [Transaction Kinds](#transaction-kinds) - - -### Transactions and Safety - -**A transaction** is a fundamental tool of SQLite that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. - -GRDB generally opens transactions for you, as a way to enforce its [concurrency guarantees](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency), and provide maximal security for both your application data and application logic: - -```swift -// BEGIN TRANSACTION -// INSERT INTO credit ... -// INSERT INTO debit ... -// COMMIT -try dbQueue.write { db in - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) -} - -// BEGIN TRANSACTION -// INSERT INTO credit ... -// INSERT INTO debit ... -// COMMIT -try dbPool.write { db in - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) -} -``` - -Yet you may need to exactly control when transactions take place: - - -### Explicit Transactions - -`DatabaseQueue.inDatabase()` and `DatabasePool.writeWithoutTransaction()` execute your database statements outside of any transaction: - -```swift -// INSERT INTO credit ... -// INSERT INTO debit ... -try dbQueue.inDatabase { db in - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) -} - -// INSERT INTO credit ... -// INSERT INTO debit ... -try dbPool.writeWithoutTransaction { db in - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) -} -``` - -**Writing outside of any transaction is dangerous,** for two reasons: - -- In our credit/debit example, you may successfully insert a credit, but fail inserting the debit, and end up with unbalanced accounts (oops). - - ```swift - // UNSAFE DATABASE INTEGRITY - try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction - try Credit(destinationAccount, amount).insert(db) // may succeed - try Debit(sourceAccount, amount).insert(db) // may fail - } - ``` - - Transactions avoid this kind of bug. - -- [Database pool](#database-pools) concurrent reads can see an inconsistent state of the database: - - ```swift - // UNSAFE CONCURRENCY - try dbPool.writeWithoutTransaction { db in - try Credit(destinationAccount, amount).insert(db) - // <- Concurrent dbPool.read sees a partial db update here - try Debit(sourceAccount, amount).insert(db) - } - ``` - - Transactions avoid this kind of bug, too. - -To open explicit transactions, use one of the `Database.inTransaction`, `DatabaseQueue.inTransaction`, or `DatabasePool.writeInTransaction` methods: - -```swift -// BEGIN TRANSACTION -// INSERT INTO credit ... -// INSERT INTO debit ... -// COMMIT -try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction - try db.inTransaction { - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) - return .commit - } -} - -// BEGIN TRANSACTION -// INSERT INTO credit ... -// INSERT INTO debit ... -// COMMIT -try dbQueue.inTransaction { db in // or dbPool.writeInTransaction - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) - return .commit -} -``` - -If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the `inTransaction` method. If you return `.rollback` instead of `.commit`, the transaction is also rollbacked, but no error is thrown. - -You can also perform manual transaction management: - -```swift -try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction - try db.beginTransaction() - ... - try db.commit() - - try db.execute(sql: "BEGIN TRANSACTION") - ... - try db.execute(sql: "ROLLBACK") -} -``` - -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/allowsunsafetransactions) configuration flag: - -```swift -// fatal error: A transaction has been left opened at the end of a database access -try dbQueue.inDatabase { db in - try db.execute(sql: "BEGIN TRANSACTION") - // <- no commit or rollback -} -``` - -You can ask if a transaction is currently opened: - -```swift -func myCriticalMethod(_ db: Database) throws { - precondition(db.isInsideTransaction, "This method requires a transaction") - try ... -} -``` - -Yet, you have a better option than checking for transactions: critical database sections should use savepoints, described below: - -```swift -func myCriticalMethod(_ db: Database) throws { - try db.inSavepoint { - // Here the database is guaranteed to be inside a transaction. - try ... - } -} -``` - - -### Savepoints - -**Statements grouped in a savepoint can be rollbacked without invalidating a whole transaction:** - -```swift -try dbQueue.write { db in - // Makes sure both inserts succeed, or none: - try db.inSavepoint { - try Credit(destinationAccount, amount).insert(db) - try Debit(sourceAccount, amount).insert(db) - return .commit - } - - // Other savepoints, etc... -} -``` - -If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the `inSavepoint` method. If you return `.rollback` instead of `.commit`, the savepoint is also rollbacked, but no error is thrown. - -**Unlike transactions, savepoints can be nested.** They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only written to disk when the outermost transaction is committed: - -```swift -try dbQueue.inDatabase { db in - try db.inSavepoint { - ... - try db.inSavepoint { - ... - return .commit - } - ... - return .commit // writes changes to disk - } -} -``` - -SQLite savepoints are more than nested transactions, though. For advanced uses, use [SQLite savepoint documentation](https://www.sqlite.org/lang_savepoint.html). - - -### Transaction Kinds - -SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive. - -The transaction kind can be changed in the database configuration, or for each transaction: - -```swift -// 1) Default configuration: -let dbQueue = try DatabaseQueue(path: "...") - -// BEGIN DEFERRED TRANSACTION ... -dbQueue.write { db in ... } - -// BEGIN EXCLUSIVE TRANSACTION ... -dbQueue.inTransaction(.exclusive) { db in ... } - -// 2) Customized default transaction kind: -var config = Configuration() -config.defaultTransactionKind = .immediate -let dbQueue = try DatabaseQueue(path: "...", configuration: config) - -// BEGIN IMMEDIATE TRANSACTION ... -dbQueue.write { db in ... } - -// BEGIN EXCLUSIVE TRANSACTION ... -dbQueue.inTransaction(.exclusive) { db in ... } -``` - - ## Prepared Statements **Prepared Statements** let you prepare an SQL query and execute it later, several times if you need, with different arguments. @@ -1995,7 +1599,7 @@ When the same query will be used several times in the lifetime of your applicati **Don't cache statements yourself.** -> **Note**: This is because you don't have the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which you don't manage yourself, especially when you use [database pools](#database-pools). A change in the database schema [may, or may not](https://www.sqlite.org/compile.html#max_schema_retry) invalidate a statement. +> **Note**: This is because you don't have the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which you don't manage yourself, especially when you use [database pools]. A change in the database schema [may, or may not](https://www.sqlite.org/compile.html#max_schema_retry) invalidate a statement. Instead, use the `cachedStatement` method. GRDB does all the hard caching and [memory management](#memory-management) stuff for you: @@ -5975,7 +5579,7 @@ See [SQLCipher 4.0.0 Release](https://www.zetetic.net/blog/2018/11/30/sqlcipher- **You can change the passphrase** of an already encrypted database. -When you use a [database queue](#database-queues), open the database with the old passphrase, and then apply the new passphrase: +When you use a [database queue](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue), open the database with the old passphrase, and then apply the new passphrase: ```swift try dbQueue.write { db in @@ -5983,7 +5587,7 @@ try dbQueue.write { db in } ``` -When you use a [database pool](#database-pools), make sure that no concurrent read can happen by changing the passphrase within the `barrierWriteWithoutTransaction` block. You must also ensure all future reads open a new database connection by calling the `invalidateReadOnlyConnections` method: +When you use a [database pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool), make sure that no concurrent read can happen by changing the passphrase within the `barrierWriteWithoutTransaction` block. You must also ensure all future reads open a new database connection by calling the `invalidateReadOnlyConnections` method: ```swift try dbPool.barrierWriteWithoutTransaction { db in @@ -6131,7 +5735,7 @@ config.prepareDatabase { db in let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) ``` -For the same reason, [database pools](#database-pools), which open SQLite connections on demand, may fail at any time as soon as the passphrase becomes unavailable: +For the same reason, [database pools], which open SQLite connections on demand, may fail at any time as soon as the passphrase becomes unavailable: ```swift // Success if and only if the passphrase is available @@ -6165,7 +5769,7 @@ try source.backup(to: destination) The `backup` method blocks the current thread until the destination database contains the same contents as the source database. -When the source is a [database pool](#database-pools), concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won't trigger any error. +When the source is a [database pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool), concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won't trigger any error. `Database` has an analogous `backup` method. @@ -6357,7 +5961,7 @@ do { } ``` -If you want to see statement arguments in the error description, [make statement arguments public](#database-configuration). +If you want to see statement arguments in the error description, [make statement arguments public](https://swiftpackageindex.com/groue/grdb.swift/configuration/publicstatementarguments). **SQLite uses [results codes](https://www.sqlite.org/rescode.html) to distinguish between various errors**. @@ -6678,7 +6282,7 @@ dbPool.releaseMemoryEventually() **The iOS operating system likes applications that do not consume much memory.** -[Database queues](#database-queues) and [pools](#database-pools) automatically free non-essential memory when the application receives a memory warning, and when the application enters background. +[Database queues] and [pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool) automatically free non-essential memory when the application receives a memory warning, and when the application enters background. You can opt out of this automatic memory management: @@ -6695,7 +6299,7 @@ let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) // or Datab Data protection can be enabled [globally](https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/AddingCapabilities/AddingCapabilities.html#//apple_ref/doc/uid/TP40012582-CH26-SW30) for all files created by an application. -You can also explicitly protect a database, by configuring its enclosing *directory*. This will not only protect the database file, but also all [temporary files](https://www.sqlite.org/tempfiles.html) created by SQLite (including the persistent `.shm` and `.wal` files created by [database pools](#database-pools)). +You can also explicitly protect a database, by configuring its enclosing *directory*. This will not only protect the database file, but also all [temporary files](https://www.sqlite.org/tempfiles.html) created by SQLite (including the persistent `.shm` and `.wal` files created by [database pools]). For example, to explicitly use [complete](https://developer.apple.com/reference/foundation/fileprotectiontype/1616200-complete) protection: @@ -6861,7 +6465,7 @@ try dbQueue.read { db in } ``` -If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration). +If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](https://swiftpackageindex.com/groue/grdb.swift/configuration/publicstatementarguments). > **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output. @@ -6898,7 +6502,7 @@ try dbQueue.read { db in } ``` -If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](#database-configuration). +If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](https://swiftpackageindex.com/groue/grdb.swift/configuration/publicstatementarguments). ### What Are Experimental Features? @@ -7308,6 +6912,18 @@ This chapter was replaced with [Persistence Callbacks]. This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation). +#### Database Configuration + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration). + +#### Database Queues + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue). + +#### Database Pools + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool). + #### Database Snapshots This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency). @@ -7366,6 +6982,10 @@ This protocol has been renamed [FetchableRecord] in GRDB 3.0. This protocol has been renamed [TableRecord] in GRDB 3.0. +#### Transactions and Savepoints + +This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions). + #### Transaction Hook This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)). @@ -7427,7 +7047,12 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [SQL literal]: Documentation/SQLInterpolation.md#sql-literal [Identifiable]: https://developer.apple.com/documentation/swift/identifiable [Query Interface Organization]: Documentation/QueryInterfaceOrganization.md -[Database Configuration]: #database-configuration +[Database Configuration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration [Persistence Methods]: #persistence-methods [persistence methods]: #persistence-methods [RecordError]: #recorderror +[Transactions and Savepoints]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions +[`DatabaseQueue`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue +[Database queues]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue +[`DatabasePool`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool +[database pools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool diff --git a/Scripts/destination.rb b/Scripts/destination.rb new file mode 100755 index 000000000..331ee990c --- /dev/null +++ b/Scripts/destination.rb @@ -0,0 +1,15 @@ +#!/usr/bin/env ruby +gem 'json' +require 'json' +require 'optparse' + +samples = JSON.parse(STDIN.read) + +samples['devices'].each do |key, devices| + next unless key =~ /^com\.apple\.CoreSimulator\.SimRuntime\.([^-]*)-(.*)$/ + platform = $1 + version = $2.gsub('-', '.') + devices.each do |device| + puts "#{version} #{platform} #{device["udid"]} #{device["name"]}" + end +end diff --git a/Support/Info.plist b/Support/Info.plist index 9d328f817..71d587967 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.5.0 + 6.6.0 CFBundleSignature ???? CFBundleVersion diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index eebe2d597..ffefeb44a 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -357,9 +357,15 @@ class TableDefinitionTests: GRDBTestCase { } func testColumnGeneratedAs() throws { - #if !GRDBCUSTOMSQLITE - throw XCTSkip("Generated columns are not available") - #else +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3031000 else { + throw XCTSkip("Generated columns are not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("Generated columns are not available") + } +#endif let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in try db.create(table: "test") { t in @@ -387,7 +393,6 @@ class TableDefinitionTests: GRDBTestCase { """) return .rollback } - #endif } func testTablePrimaryKey() throws { @@ -767,9 +772,15 @@ class TableDefinitionTests: GRDBTestCase { } func testAlterTableAddGeneratedVirtualColumn() throws { - #if !GRDBCUSTOMSQLITE - throw XCTSkip("Generated columns are not available") - #else +#if GRDBCUSTOMSQLITE || GRDBCIPHER + guard sqlite3_libversion_number() >= 3031000 else { + throw XCTSkip("Generated columns are not available") + } +#else + guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else { + throw XCTSkip("Generated columns are not available") + } +#endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in @@ -794,7 +805,6 @@ class TableDefinitionTests: GRDBTestCase { assertEqualSQL(latestQueries[3], "ALTER TABLE \"test\" ADD COLUMN \"g\" GENERATED ALWAYS AS (\"a\" * 2) VIRTUAL") assertEqualSQL(latestQueries[4], "ALTER TABLE \"test\" ADD COLUMN \"h\" GENERATED ALWAYS AS ('O''Brien') VIRTUAL") } - #endif } func testAlterTableDropColumn() throws { diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 644c18073..2b585a740 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -219,7 +219,7 @@ extension ValueObservationRecorder { extension ValueObservation { public func record( in reader: some DatabaseReader, - scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), + scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main), onError: ((Error) -> Void)? = nil, onChange: ((Reducer.Value) -> Void)? = nil) -> ValueObservationRecorder @@ -365,7 +365,7 @@ extension GRDBTestCase { { func test( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, testValueDispatching: @escaping () -> Void) throws { func testRecordingEqualWhenWriteAfterStart(writer: some DatabaseWriter) throws { @@ -575,7 +575,7 @@ extension GRDBTestCase { { func test( observation: ValueObservation, - scheduling scheduler: ValueObservationScheduler, + scheduling scheduler: some ValueObservationScheduler, testErrorDispatching: @escaping () -> Void) throws { func test(writer: some DatabaseWriter) throws {