From ad74526f6a816f9ad7649b865fc5830b892cf7d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Aug 2024 14:50:42 +0200 Subject: [PATCH 01/30] BusyCallback and BusyMode are Sendable --- GRDB/Core/Database.swift | 4 ++-- TODO.md | 4 ++-- Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift | 12 ++++++------ 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 68956eaa1..8f3eeaffe 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1831,7 +1831,7 @@ extension Database { // MARK: - Database-Related Types /// See BusyMode and - public typealias BusyCallback = (_ numberOfTries: Int) -> Bool + public typealias BusyCallback = @Sendable (_ numberOfTries: Int) -> Bool /// When there are several connections to a database, a connection may try /// to access the database while it is locked by another connection. @@ -1859,7 +1859,7 @@ extension Database { /// - /// - /// - - public enum BusyMode { + public enum BusyMode: Sendable { /// The `SQLITE_BUSY` error is immediately returned to the connection /// that tries to access the locked database. case immediateError diff --git a/TODO.md b/TODO.md index 06c27e3f0..96f71aa68 100644 --- a/TODO.md +++ b/TODO.md @@ -92,8 +92,8 @@ - [X] GRDB7/BREAKING: Stop exporting SQLite (679d6463) - [X] GRDB7/BREAKING: Remove Configuration.defaultTransactionKind (2661ff46) - [X] GRDB7: Replace LockedBox with Mutex (00ccab06) -- [ ] GRDB7: Sendable: BusyCallback (e0d8e20b) -- [ ] GRDB7: Sendable: BusyMode (e0d8e20b) +- [X] GRDB7: Sendable: BusyCallback (e0d8e20b) +- [X] GRDB7: Sendable: BusyMode (e0d8e20b) - [ ] GRDB7: Sendable: TransactionClock (f7dc72a5) - [ ] GRDB7: Sendable: Configuration (54ffb21f) - [ ] GRDB7: Sendable: DatabaseDataEncodingStrategy (264d7fb5) diff --git a/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift b/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift index a05115288..c525f9ef7 100644 --- a/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift @@ -244,9 +244,9 @@ class ConcurrencyTests: GRDBTestCase { // BEGIN EXCLUSIVE TRANSACTION // COMMIT - var busyCallbackCalled = false + let busyCallbackCalledMutex = Mutex(false) self.busyCallback = { n in - busyCallbackCalled = true + busyCallbackCalledMutex.store(true) s2.signal() return true } @@ -283,7 +283,7 @@ class ConcurrencyTests: GRDBTestCase { _ = group.wait(timeout: .distantFuture) - XCTAssertTrue(busyCallbackCalled) + XCTAssertTrue(busyCallbackCalledMutex.load()) } func testReaderDuringDefaultTransaction() throws { @@ -384,9 +384,9 @@ class ConcurrencyTests: GRDBTestCase { // COMMIT // COMMIT - var busyCallbackCalled = false + let busyCallbackCalledMutex = Mutex(false) self.busyCallback = { n in - busyCallbackCalled = true + busyCallbackCalledMutex.store(true) s3.signal() return true } @@ -431,6 +431,6 @@ class ConcurrencyTests: GRDBTestCase { _ = group.wait(timeout: .distantFuture) - XCTAssertTrue(busyCallbackCalled) + XCTAssertTrue(busyCallbackCalledMutex.load()) } } From 0457a6262e1e64d91c7297bf41e8afb40c7922c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Mar 2024 16:26:20 +0100 Subject: [PATCH 02/30] TransactionClock is Sendable --- GRDB/Core/TransactionClock.swift | 8 ++-- TODO.md | 2 +- Tests/GRDBTests/TransactionDateTests.swift | 48 +++++++++------------- 3 files changed, 25 insertions(+), 33 deletions(-) diff --git a/GRDB/Core/TransactionClock.swift b/GRDB/Core/TransactionClock.swift index d878cd450..b467ce724 100644 --- a/GRDB/Core/TransactionClock.swift +++ b/GRDB/Core/TransactionClock.swift @@ -10,7 +10,7 @@ import Foundation /// /// - ``DefaultTransactionClock`` /// - ``CustomTransactionClock`` -public protocol TransactionClock { +public protocol TransactionClock: Sendable { /// Returns the date of the current transaction. /// /// This function is called whenever a transaction starts - precisely @@ -36,7 +36,7 @@ extension TransactionClock where Self == CustomTransactionClock { /// /// It is also called when the ``Database/transactionDate`` property is /// called, and the database connection is not in a transaction. - public static func custom(_ now: @escaping (Database) throws -> Date) -> Self { + public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self { CustomTransactionClock(now) } } @@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock { /// A custom transaction clock. public struct CustomTransactionClock: TransactionClock { - let _now: (Database) throws -> Date + let _now: @Sendable (Database) throws -> Date - public init(_ now: @escaping (Database) throws -> Date) { + public init(_ now: @escaping @Sendable (Database) throws -> Date) { self._now = now } diff --git a/TODO.md b/TODO.md index 96f71aa68..ebe34c75b 100644 --- a/TODO.md +++ b/TODO.md @@ -94,7 +94,7 @@ - [X] GRDB7: Replace LockedBox with Mutex (00ccab06) - [X] GRDB7: Sendable: BusyCallback (e0d8e20b) - [X] GRDB7: Sendable: BusyMode (e0d8e20b) -- [ ] GRDB7: Sendable: TransactionClock (f7dc72a5) +- [X] GRDB7: Sendable: TransactionClock (f7dc72a5) - [ ] GRDB7: Sendable: Configuration (54ffb21f) - [ ] GRDB7: Sendable: DatabaseDataEncodingStrategy (264d7fb5) - [ ] GRDB7: Sendable: DatabaseDateEncodingStrategy (264d7fb5) diff --git a/Tests/GRDBTests/TransactionDateTests.swift b/Tests/GRDBTests/TransactionDateTests.swift index 5f2707223..59bec6641 100644 --- a/Tests/GRDBTests/TransactionDateTests.swift +++ b/Tests/GRDBTests/TransactionDateTests.swift @@ -8,9 +8,9 @@ class TransactionDateTests: GRDBTestCase { Date(), Date.distantFuture, ] - var dateIterator = dates.makeIterator() + let dateIteratorMutex = Mutex(dates.makeIterator()) dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + dateIteratorMutex.withLock { $0.next()! } } var collectedDates: [Date] = [] @@ -28,9 +28,9 @@ class TransactionDateTests: GRDBTestCase { Date(), Date.distantFuture, ] - var dateIterator = dates.makeIterator() + let dateIteratorMutex = Mutex(dates.makeIterator()) dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + dateIteratorMutex.withLock { $0.next()! } } var collectedDates: [Date] = [] @@ -51,9 +51,9 @@ class TransactionDateTests: GRDBTestCase { Date(), Date.distantFuture, ] - var dateIterator = dates.makeIterator() + let dateIteratorMutex = Mutex(dates.makeIterator()) dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + dateIteratorMutex.withLock { $0.next()! } } var collectedDates: [Date] = [] @@ -74,9 +74,9 @@ class TransactionDateTests: GRDBTestCase { Date(), Date.distantFuture, ] - var dateIterator = dates.makeIterator() + let dateIteratorMutex = Mutex(dates.makeIterator()) dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + dateIteratorMutex.withLock { $0.next()! } } var collectedDates: [Date] = [] @@ -107,8 +107,7 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + dbConfiguration.transactionClock = .custom { _ in .distantPast } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -119,7 +118,6 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast try dbQueue.write { db in do { var player = Player(name: "Arthur") @@ -152,8 +150,8 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + let currentDate = Mutex(Date.distantPast) + dbConfiguration.transactionClock = .custom { _ in currentDate.load() } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -164,14 +162,13 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast try dbQueue.write { db in var player = Player(name: "Arthur") try player.insert(db) } let newTransactionDate = Date() - currentDate = newTransactionDate + currentDate.store(newTransactionDate) try dbQueue.write { db in var player = try Player.find(db, key: 1) @@ -198,8 +195,8 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + let currentDate = Mutex(Date.distantPast) + dbConfiguration.transactionClock = .custom { _ in currentDate.load() } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -210,14 +207,13 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast try dbQueue.write { db in var player = Player(name: "Arthur") try player.insert(db) } let newTransactionDate = Date() - currentDate = newTransactionDate + currentDate.store(newTransactionDate) try dbQueue.write { db in var player = try Player.find(db, key: 1) @@ -251,8 +247,8 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + let currentDate = Mutex(Date.distantPast) + dbConfiguration.transactionClock = .custom { _ in currentDate.load() } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -267,7 +263,7 @@ class TransactionDateTests: GRDBTestCase { } let newTransactionDate = Date() - currentDate = newTransactionDate + currentDate.store(newTransactionDate) try dbQueue.write { db in var player = try Player.find(db, key: 1) try player.touch(db) @@ -303,8 +299,7 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + dbConfiguration.transactionClock = .custom { _ in .distantPast } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -315,7 +310,6 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast try dbQueue.write { db in var player = Player(name: "Arthur", isInserted: false) try player.insert(db) @@ -354,8 +348,7 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + dbConfiguration.transactionClock = .custom { _ in .distantPast } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -366,7 +359,6 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast try dbQueue.write { db in let player = Player(name: "Arthur") try player.insert(db) From 8e860e671ba06613cc3b9085219731096506a5b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Mar 2024 16:39:51 +0100 Subject: [PATCH 03/30] Configuration is Sendable --- GRDB/Core/Configuration.swift | 28 ++++- TODO.md | 2 +- .../DatabaseConfigurationTests.swift | 32 ++--- .../DatabasePoolReleaseMemoryTests.swift | 115 ++++++++---------- .../DatabaseQueueReleaseMemoryTests.swift | 48 +++----- Tests/GRDBTests/DatabaseQueueTests.swift | 2 +- Tests/GRDBTests/DatabaseTraceTests.swift | 12 +- Tests/GRDBTests/FTS4TableBuilderTests.swift | 12 +- Tests/GRDBTests/GRDBTestCase.swift | 2 +- 9 files changed, 122 insertions(+), 131 deletions(-) diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 17a50eff8..059bbb86f 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -10,7 +10,7 @@ import SQLite3 import Dispatch import Foundation -public struct Configuration { +public struct Configuration: Sendable { // MARK: - Misc options @@ -195,7 +195,7 @@ public struct Configuration { // MARK: - Managing SQLite Connections - private var setups: [(Database) throws -> Void] = [] + private var setups: [@Sendable (Database) throws -> Void] = [] /// Defines a function to run whenever an SQLite connection is opened. /// @@ -232,7 +232,7 @@ public struct Configuration { /// /// On newly created databases files, ``DatabasePool`` activates the WAL /// mode after the preparation functions have run. - public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) { + public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) { setups.append(setup) } @@ -432,9 +432,25 @@ public struct Configuration { /// through a `SerializedDatabase`. var threadingMode = Database.ThreadingMode.default - var SQLiteConnectionDidOpen: (() -> Void)? - var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)? - var SQLiteConnectionDidClose: (() -> Void)? + private(set) var SQLiteConnectionDidOpen: (@Sendable () -> Void)? + private(set) var SQLiteConnectionWillClose: (@Sendable (SQLiteConnection) -> Void)? + private(set) var SQLiteConnectionDidClose: (@Sendable () -> Void)? + + // Workaround https://github.com/apple/swift/issues/72727 + mutating func onConnectionDidOpen(_ callback: @escaping @Sendable () -> Void) { + SQLiteConnectionDidOpen = callback + } + + // Workaround https://github.com/apple/swift/issues/72727 + mutating func onConnectionWillClose(_ callback: @escaping @Sendable (SQLiteConnection) -> Void) { + SQLiteConnectionWillClose = callback + } + + // Workaround https://github.com/apple/swift/issues/72727 + mutating func onConnectionDidClose(_ callback: @escaping @Sendable () -> Void) { + SQLiteConnectionDidClose = callback + } + var SQLiteOpenFlags: CInt { var flags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE) if sqlite3_libversion_number() >= 3037000 { diff --git a/TODO.md b/TODO.md index ebe34c75b..42d463d3e 100644 --- a/TODO.md +++ b/TODO.md @@ -95,7 +95,7 @@ - [X] GRDB7: Sendable: BusyCallback (e0d8e20b) - [X] GRDB7: Sendable: BusyMode (e0d8e20b) - [X] GRDB7: Sendable: TransactionClock (f7dc72a5) -- [ ] GRDB7: Sendable: Configuration (54ffb21f) +- [X] GRDB7: Sendable: Configuration (54ffb21f) - [ ] GRDB7: Sendable: DatabaseDataEncodingStrategy (264d7fb5) - [ ] GRDB7: Sendable: DatabaseDateEncodingStrategy (264d7fb5) - [ ] GRDB7: Sendable: DatabaseColumnEncodingStrategy (264d7fb5) diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index fccf86e9d..7c64c91e5 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -15,40 +15,40 @@ class DatabaseConfigurationTests: GRDBTestCase { func testPrepareDatabase() throws { // prepareDatabase is called when connection opens - var connectionCount = 0 + let connectionCountMutex = Mutex(0) var configuration = Configuration() configuration.prepareDatabase { db in - connectionCount += 1 + connectionCountMutex.increment() } _ = try DatabaseQueue(configuration: configuration) - XCTAssertEqual(connectionCount, 1) + XCTAssertEqual(connectionCountMutex.load(), 1) _ = try makeDatabaseQueue(configuration: configuration) - XCTAssertEqual(connectionCount, 2) + XCTAssertEqual(connectionCountMutex.load(), 2) let pool = try makeDatabasePool(configuration: configuration) - XCTAssertEqual(connectionCount, 3) + XCTAssertEqual(connectionCountMutex.load(), 3) try pool.read { _ in } - XCTAssertEqual(connectionCount, 4) + XCTAssertEqual(connectionCountMutex.load(), 4) try pool.makeSnapshot().read { _ in } - XCTAssertEqual(connectionCount, 5) + XCTAssertEqual(connectionCountMutex.load(), 5) #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try pool.makeSnapshotPool().read { _ in } - XCTAssertEqual(connectionCount, 6) + XCTAssertEqual(connectionCountMutex.load(), 6) #endif } func testPrepareDatabaseError() throws { struct TestError: Error { } - var error: TestError? + let errorMutex: Mutex = Mutex(nil) var configuration = Configuration() configuration.prepareDatabase { db in - if let error { + if let error = errorMutex.load() { throw error } } @@ -56,36 +56,36 @@ class DatabaseConfigurationTests: GRDBTestCase { // TODO: what about in-memory DatabaseQueue??? do { - error = TestError() + errorMutex.store(TestError()) _ = try makeDatabaseQueue(configuration: configuration) XCTFail("Expected TestError") } catch is TestError { } do { - error = TestError() + errorMutex.store(TestError()) _ = try makeDatabasePool(configuration: configuration) XCTFail("Expected TestError") } catch is TestError { } do { - error = nil + errorMutex.store(nil) let pool = try makeDatabasePool(configuration: configuration) do { - error = TestError() + errorMutex.store(TestError()) try pool.read { _ in } XCTFail("Expected TestError") } catch is TestError { } do { - error = TestError() + errorMutex.store(TestError()) _ = try pool.makeSnapshot() XCTFail("Expected TestError") } catch is TestError { } #if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) do { - error = TestError() + errorMutex.store(TestError()) _ = try pool.makeSnapshotPool() XCTFail("Expected TestError") } catch is TestError { } diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index 09dfde405..afa8bd32a 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -13,21 +13,16 @@ import XCTest class DatabasePoolReleaseMemoryTests: GRDBTestCase { func testDatabasePoolDeinitClosesAllConnections() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 + let openConnectionCountMutex = Mutex(0) + let totalOpenConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } + dbConfiguration.onConnectionDidOpen { + totalOpenConnectionCountMutex.increment() + openConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } + dbConfiguration.onConnectionDidClose { + openConnectionCountMutex.decrement() } // write & read @@ -44,19 +39,19 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { } // One reader, one writer - XCTAssertEqual(totalOpenConnectionCount, 2) + XCTAssertEqual(totalOpenConnectionCountMutex.load(), 2) // All connections are closed - XCTAssertEqual(openConnectionCount, 0) + XCTAssertEqual(openConnectionCountMutex.load(), 0) } - + #if os(iOS) func testDatabasePoolReleasesMemoryOnPressureEvent() throws { // Create a database pool, and expect a reader connection to be closed let expectation = self.expectation(description: "Reader connection closed") var configuration = Configuration() - configuration.SQLiteConnectionWillClose = { conn in + configuration.onConnectionWillClose { conn in if sqlite3_db_readonly(conn, nil) != 0 { expectation.fulfill() } @@ -76,7 +71,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { waitForExpectations(timeout: 0.5) } } - + func testDatabasePoolDoesNotReleaseMemoryOnPressureEventIfDisabled() throws { // Create a database pool, and do not expect any reader connection to be closed let expectation = self.expectation(description: "Reader connection closed") @@ -84,7 +79,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { var configuration = Configuration() configuration.automaticMemoryManagement = false - configuration.SQLiteConnectionWillClose = { conn in + configuration.onConnectionWillClose { conn in if sqlite3_db_readonly(conn, nil) != 0 { expectation.fulfill() } @@ -126,26 +121,21 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { // Cleanup semaphore.signal() } - + #endif - + func test_DatabasePool_releaseMemory_closes_reader_connections() throws { // A complicated test setup that opens multiple reader connections. - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 + let openConnectionCountMutex = Mutex(0) + let totalOpenConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } + dbConfiguration.onConnectionDidOpen { + totalOpenConnectionCountMutex.increment() + openConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } + dbConfiguration.onConnectionDidClose { + openConnectionCountMutex.decrement() } let dbPool = try makeDatabasePool() @@ -201,74 +191,69 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { } // Two readers, one writer - XCTAssertEqual(totalOpenConnectionCount, 3) + XCTAssertEqual(totalOpenConnectionCountMutex.load(), 3) // Writer is still open - XCTAssertEqual(openConnectionCount, 1) + XCTAssertEqual(openConnectionCountMutex.load(), 1) } func test_DatabasePool_releaseMemory_closes_reader_connections_when_persistentReadOnlyConnections_is_false() throws { - var persistentConnectionCount = 0 + let persistentConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - persistentConnectionCount += 1 + dbConfiguration.onConnectionDidOpen { + persistentConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - persistentConnectionCount -= 1 + dbConfiguration.onConnectionDidClose { + persistentConnectionCountMutex.decrement() } dbConfiguration.persistentReadOnlyConnections = false let dbPool = try makeDatabasePool() - XCTAssertEqual(persistentConnectionCount, 1) // writer + XCTAssertEqual(persistentConnectionCountMutex.load(), 1) // writer try dbPool.read { _ in } - XCTAssertEqual(persistentConnectionCount, 2) // writer + reader + XCTAssertEqual(persistentConnectionCountMutex.load(), 2) // writer + reader dbPool.releaseMemory() - XCTAssertEqual(persistentConnectionCount, 1) // writer + XCTAssertEqual(persistentConnectionCountMutex.load(), 1) // writer } func test_DatabasePool_releaseMemory_does_not_close_reader_connections_when_persistentReadOnlyConnections_is_true() throws { - var persistentConnectionCount = 0 + let persistentConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - persistentConnectionCount += 1 + dbConfiguration.onConnectionDidOpen { + persistentConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - persistentConnectionCount -= 1 + dbConfiguration.onConnectionDidClose { + persistentConnectionCountMutex.decrement() } dbConfiguration.persistentReadOnlyConnections = true let dbPool = try makeDatabasePool() - XCTAssertEqual(persistentConnectionCount, 1) // writer + XCTAssertEqual(persistentConnectionCountMutex.load(), 1) // writer try dbPool.read { _ in } - XCTAssertEqual(persistentConnectionCount, 2) // writer + reader + XCTAssertEqual(persistentConnectionCountMutex.load(), 2) // writer + reader dbPool.releaseMemory() - XCTAssertEqual(persistentConnectionCount, 2) // writer + reader + XCTAssertEqual(persistentConnectionCountMutex.load(), 2) // writer + reader } - + func testBlocksRetainConnection() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 + let openConnectionCountMutex = Mutex(0) + let totalOpenConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } + dbConfiguration.onConnectionDidOpen { + totalOpenConnectionCountMutex.increment() + openConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } + dbConfiguration.onConnectionDidClose { + openConnectionCountMutex.decrement() } // Block 1 Block 2 @@ -311,10 +296,10 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { } // one writer, one reader - XCTAssertEqual(totalOpenConnectionCount, 2) + XCTAssertEqual(totalOpenConnectionCountMutex.load(), 2) // All connections are closed - XCTAssertEqual(openConnectionCount, 0) + XCTAssertEqual(openConnectionCountMutex.load(), 0) } func testStatementDoNotRetainDatabaseConnection() throws { diff --git a/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift b/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift index 7c5b9428e..5a828b9e8 100644 --- a/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift @@ -4,21 +4,16 @@ import XCTest class DatabaseQueueReleaseMemoryTests: GRDBTestCase { func testDatabaseQueueDeinitClosesConnection() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 + let openConnectionCountMutex = Mutex(0) + let totalOpenConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } + dbConfiguration.onConnectionDidOpen { + totalOpenConnectionCountMutex.increment() + openConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } + dbConfiguration.onConnectionDidClose { + openConnectionCountMutex.decrement() } do { @@ -27,28 +22,23 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase { } // One reader, one writer - XCTAssertEqual(totalOpenConnectionCount, 1) + XCTAssertEqual(totalOpenConnectionCountMutex.load(), 1) // All connections are closed - XCTAssertEqual(openConnectionCount, 0) + XCTAssertEqual(openConnectionCountMutex.load(), 0) } - + func testBlocksRetainConnection() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 + let openConnectionCountMutex = Mutex(0) + let totalOpenConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } + dbConfiguration.onConnectionDidOpen { + totalOpenConnectionCountMutex.increment() + openConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } + dbConfiguration.onConnectionDidClose { + openConnectionCountMutex.decrement() } // Block 1 Block 2 @@ -91,10 +81,10 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase { } // one writer - XCTAssertEqual(totalOpenConnectionCount, 1) + XCTAssertEqual(totalOpenConnectionCountMutex.load(), 1) // All connections are closed - XCTAssertEqual(openConnectionCount, 0) + XCTAssertEqual(openConnectionCountMutex.load(), 0) } func testStatementDoNotRetainDatabaseConnection() throws { diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 66f4cd555..bf0bb5371 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -378,7 +378,7 @@ class DatabaseQueueTests: GRDBTestCase { } let parallelWritesCount = 50 - DispatchQueue.concurrentPerform(iterations: parallelWritesCount) { index in + DispatchQueue.concurrentPerform(iterations: parallelWritesCount) { [configuration] index in let dbQueue = try! makeDatabaseQueue(filename: "test", configuration: configuration) try! dbQueue.write { db in _ = try Table("test").fetchCount(db) diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index df9d73119..8ad6eedc7 100644 --- a/Tests/GRDBTests/DatabaseTraceTests.swift +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -114,11 +114,11 @@ class DatabaseTraceTests : GRDBTestCase { } func testTraceFromConfigurationWithDefaultOptions() throws { - var events: [String] = [] + let eventsMutex: Mutex<[String]> = Mutex([]) var configuration = Configuration() configuration.prepareDatabase { db in db.trace { event in - events.append("SQL: \(event)") + eventsMutex.withLock { $0.append("SQL: \(event)") } } } let dbQueue = try makeDatabaseQueue(configuration: configuration) @@ -127,19 +127,19 @@ class DatabaseTraceTests : GRDBTestCase { CREATE table t(a); INSERT INTO t (a) VALUES (?) """, arguments: [1]) - XCTAssertEqual(events.suffix(2), [ + XCTAssertEqual(eventsMutex.load().suffix(2), [ "SQL: CREATE table t(a)", "SQL: INSERT INTO t (a) VALUES (?)"]) } } func testTraceFromConfigurationWithPublicStatementArguments() throws { - var events: [String] = [] + let eventsMutex: Mutex<[String]> = Mutex([]) var configuration = Configuration() configuration.publicStatementArguments = true configuration.prepareDatabase { db in db.trace { event in - events.append("SQL: \(event)") + eventsMutex.withLock { $0.append("SQL: \(event)") } } } let dbQueue = try makeDatabaseQueue(configuration: configuration) @@ -148,7 +148,7 @@ class DatabaseTraceTests : GRDBTestCase { CREATE table t(a); INSERT INTO t (a) VALUES (?) """, arguments: [1]) - XCTAssertEqual(events.suffix(2), [ + XCTAssertEqual(eventsMutex.load().suffix(2), [ "SQL: CREATE table t(a)", "SQL: INSERT INTO t (a) VALUES (1)"]) } diff --git a/Tests/GRDBTests/FTS4TableBuilderTests.swift b/Tests/GRDBTests/FTS4TableBuilderTests.swift index ad7287b4d..20b19384c 100644 --- a/Tests/GRDBTests/FTS4TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS4TableBuilderTests.swift @@ -272,16 +272,16 @@ class FTS4TableBuilderTests: GRDBTestCase { func testFTS4Compression() throws { // Based on https://github.com/groue/GRDB.swift/issues/369 - var compressCalled = false - var uncompressCalled = false + let compressCalledMutex = Mutex(false) + let uncompressCalledMutex = Mutex(false) dbConfiguration.prepareDatabase { db in db.add(function: DatabaseFunction("zipit", argumentCount: 1, pure: true, function: { dbValues in - compressCalled = true + compressCalledMutex.store(true) return dbValues[0] })) db.add(function: DatabaseFunction("unzipit", argumentCount: 1, pure: true, function: { dbValues in - uncompressCalled = true + uncompressCalledMutex.store(true) return dbValues[0] })) } @@ -296,12 +296,12 @@ class FTS4TableBuilderTests: GRDBTestCase { assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(content, compress=\"zipit\", uncompress=\"unzipit\")") try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["abc"]) - XCTAssertTrue(compressCalled) + XCTAssertTrue(compressCalledMutex.load()) } try dbPool.read { db in _ = try Row.fetchOne(db, sql: "SELECT * FROM documents") - XCTAssertTrue(uncompressCalled) + XCTAssertTrue(uncompressCalledMutex.load()) } } } diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index d1f52ac49..7fe7ac6b3 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -84,7 +84,7 @@ class GRDBTestCase: XCTestCase { dbConfiguration = Configuration() // Test that database are deallocated in a clean state - dbConfiguration.SQLiteConnectionWillClose = { sqliteConnection in + dbConfiguration.onConnectionWillClose { sqliteConnection in // https://www.sqlite.org/capi3ref.html#sqlite3_close: // > If sqlite3_close_v2() is called on a database connection that still // > has outstanding prepared statements, BLOB handles, and/or From 876a0870ee62ff22da06f8a3391e1ce2b387a4a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Mar 2024 16:44:14 +0100 Subject: [PATCH 04/30] Coding strategies are Sendable --- GRDB/Record/EncodableRecord.swift | 12 ++++++------ GRDB/Record/FetchableRecord.swift | 12 ++++++------ TODO.md | 12 ++++++------ 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index fb71cce64..9e8e80e2c 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -474,7 +474,7 @@ extension Row { /// var jsonData: Data /// } /// ``` -public enum DatabaseDataEncodingStrategy { +public enum DatabaseDataEncodingStrategy: Sendable { /// Encodes `Data` columns as SQL blob. case deferredToData @@ -482,7 +482,7 @@ public enum DatabaseDataEncodingStrategy { case text /// Encodes `Data` column as the result of the user-provided function. - case custom((Data) -> (any DatabaseValueConvertible)?) + case custom(@Sendable (Data) -> (any DatabaseValueConvertible)?) func encode(_ data: Data) -> DatabaseValue { switch self { @@ -518,7 +518,7 @@ public enum DatabaseDataEncodingStrategy { /// var creationDate: Date /// } /// ``` -public enum DatabaseDateEncodingStrategy { +public enum DatabaseDateEncodingStrategy: Sendable { /// The strategy that uses formatting from the Date structure. /// /// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the @@ -548,7 +548,7 @@ public enum DatabaseDateEncodingStrategy { case formatted(DateFormatter) /// Encodes the result of the user-provided function - case custom((Date) -> (any DatabaseValueConvertible)?) + case custom(@Sendable (Date) -> (any DatabaseValueConvertible)?) private static let iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() @@ -638,7 +638,7 @@ public enum DatabaseUUIDEncodingStrategy: Sendable { /// var playerID: String /// } /// ``` -public enum DatabaseColumnEncodingStrategy { +public enum DatabaseColumnEncodingStrategy: Sendable { /// A key encoding strategy that doesn’t change key names during encoding. case useDefaultKeys @@ -646,7 +646,7 @@ public enum DatabaseColumnEncodingStrategy { case convertToSnakeCase /// A key encoding strategy defined by the closure you supply. - case custom((any CodingKey) -> String) + case custom(@Sendable (any CodingKey) -> String) func column(forKey key: some CodingKey) -> String { switch self { diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index bf1c92fbd..cde368dce 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -882,7 +882,7 @@ extension RecordCursor: Sendable { } /// var myData: Data /// } /// ``` -public enum DatabaseDataDecodingStrategy { +public enum DatabaseDataDecodingStrategy: Sendable { /// Decodes `Data` columns from SQL blobs and UTF8 text. case deferredToData @@ -891,7 +891,7 @@ public enum DatabaseDataDecodingStrategy { /// If the database value does not contain a suitable value, the function /// must return nil (GRDB will interpret this nil result as a conversion /// error, and react accordingly). - case custom((DatabaseValue) -> Data?) + case custom(@Sendable (DatabaseValue) -> Data?) } // MARK: - DatabaseDateDecodingStrategy @@ -910,7 +910,7 @@ public enum DatabaseDataDecodingStrategy { /// var name: String /// var registrationDate: Date // decoded from epoch timestamp /// } -public enum DatabaseDateDecodingStrategy { +public enum DatabaseDateDecodingStrategy: Sendable { /// The strategy that uses formatting from the Date structure. /// /// It decodes numeric values as a number of seconds since Epoch @@ -951,7 +951,7 @@ public enum DatabaseDateDecodingStrategy { /// If the database value does not contain a suitable value, the function /// must return nil (GRDB will interpret this nil result as a conversion /// error, and react accordingly). - case custom((DatabaseValue) -> Date?) + case custom(@Sendable (DatabaseValue) -> Date?) } // MARK: - DatabaseColumnDecodingStrategy @@ -968,7 +968,7 @@ public enum DatabaseDateDecodingStrategy { /// // Decoded from the player_id column /// var playerID: Int /// } -public enum DatabaseColumnDecodingStrategy { +public enum DatabaseColumnDecodingStrategy: Sendable { /// A key decoding strategy that doesn’t change key names during decoding. case useDefaultKeys @@ -976,7 +976,7 @@ public enum DatabaseColumnDecodingStrategy { case convertFromSnakeCase /// A key decoding strategy defined by the closure you supply. - case custom((String) -> CodingKey) + case custom(@Sendable (String) -> CodingKey) func key(forColumn column: String) -> K? { switch self { diff --git a/TODO.md b/TODO.md index 42d463d3e..4886d1411 100644 --- a/TODO.md +++ b/TODO.md @@ -96,12 +96,12 @@ - [X] GRDB7: Sendable: BusyMode (e0d8e20b) - [X] GRDB7: Sendable: TransactionClock (f7dc72a5) - [X] GRDB7: Sendable: Configuration (54ffb21f) -- [ ] GRDB7: Sendable: DatabaseDataEncodingStrategy (264d7fb5) -- [ ] GRDB7: Sendable: DatabaseDateEncodingStrategy (264d7fb5) -- [ ] GRDB7: Sendable: DatabaseColumnEncodingStrategy (264d7fb5) -- [ ] GRDB7: Sendable: DatabaseDataDecodingStrategy (264d7fb5) -- [ ] GRDB7: Sendable: DatabaseDateDecodingStrategy (264d7fb5) -- [ ] GRDB7: Sendable: DatabaseColumnDecodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseDataEncodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseDateEncodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseColumnEncodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseDataDecodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseDateDecodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseColumnDecodingStrategy (264d7fb5) - [X] GRDB7/BREAKING: Remove DatabaseFuture and concurrentRead (05f7d3c8) - [ ] GRDB7: Sendable: DatabaseFunction (6e691fe7) - [ ] GRDB7: Sendable: DatabaseMigrator (22114ad4) From b752229c375d7b651b6b8d6fc9f49bd68df357b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 10 Feb 2024 19:48:21 +0100 Subject: [PATCH 05/30] DatabaseFunction is Sendable --- GRDB/Core/DatabaseFunction.swift | 12 ++++++------ TODO.md | 2 +- Tests/GRDBTests/DatabaseFunctionTests.swift | 6 +++--- Tests/GRDBTests/SelectStatementTests.swift | 10 +++++----- Tests/GRDBTests/UpdateStatementTests.swift | 7 +++---- 5 files changed, 18 insertions(+), 19 deletions(-) diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 2fb1301f5..d7f835401 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -29,7 +29,7 @@ import SQLite3 /// - ``localizedUppercase`` /// - ``lowercase`` /// - ``uppercase`` -public final class DatabaseFunction: Hashable { +public final class DatabaseFunction: Hashable, Sendable { // SQLite identifies functions by (name + argument count) private struct Identity: Hashable { let name: String @@ -82,11 +82,11 @@ public final class DatabaseFunction: Hashable { _ name: String, argumentCount: Int? = nil, pure: Bool = false, - function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?) + function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?) { self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1) self.isPure = pure - self.kind = .function{ (argc, argv) in + self.kind = .function { (argc, argv) in let arguments = (0.. - private enum Kind { + private enum Kind: Sendable { /// A regular function: SELECT f(1) - case function((CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)?) + case function(@Sendable (CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)?) /// An aggregate: SELECT f(foo) FROM bar GROUP BY baz - case aggregate(() -> any DatabaseAggregate) + case aggregate(@Sendable () -> any DatabaseAggregate) /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// diff --git a/TODO.md b/TODO.md index 4886d1411..ef373f309 100644 --- a/TODO.md +++ b/TODO.md @@ -103,7 +103,7 @@ - [X] GRDB7: Sendable: DatabaseDateDecodingStrategy (264d7fb5) - [X] GRDB7: Sendable: DatabaseColumnDecodingStrategy (264d7fb5) - [X] GRDB7/BREAKING: Remove DatabaseFuture and concurrentRead (05f7d3c8) -- [ ] GRDB7: Sendable: DatabaseFunction (6e691fe7) +- [X] GRDB7: Sendable: DatabaseFunction (6e691fe7) - [ ] GRDB7: Sendable: DatabaseMigrator (22114ad4) - [ ] GRDB7: Not Sendable: FilterCursor (b26e9709) - [ ] GRDB7: Sendable: RowAdapter (d138af26) diff --git a/Tests/GRDBTests/DatabaseFunctionTests.swift b/Tests/GRDBTests/DatabaseFunctionTests.swift index 8d252c6a8..4c670bbd8 100644 --- a/Tests/GRDBTests/DatabaseFunctionTests.swift +++ b/Tests/GRDBTests/DatabaseFunctionTests.swift @@ -347,13 +347,13 @@ class DatabaseFunctionTests: GRDBTestCase { func testFunctionsAreClosures() throws { let dbQueue = try makeDatabaseQueue() - var x = 123 + let mutex = Mutex(123) let fn = DatabaseFunction("f", argumentCount: 0) { dbValues in - return x + return mutex.load() } try dbQueue.inDatabase { db in db.add(function: fn) - x = 321 + mutex.store(321) XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f()")!, 321) } } diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index b3263d651..95d8d39c4 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -139,20 +139,20 @@ class SelectStatementTests : GRDBTestCase { func testCachedSelectStatementStepFailure() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var needsThrow = false + let needsThrowMutex = Mutex(false) db.add(function: DatabaseFunction("bomb", argumentCount: 0, pure: false) { _ in - if needsThrow { + if needsThrowMutex.load() { throw DatabaseError(message: "boom") } return "success" }) let sql = "SELECT bomb()" - needsThrow = false + needsThrowMutex.store(false) XCTAssertEqual(try String.fetchAll(db.cachedStatement(sql: sql)), ["success"]) do { - needsThrow = true + needsThrowMutex.store(true) _ = try String.fetchAll(db.cachedStatement(sql: sql)) XCTFail() } catch let error as DatabaseError { @@ -162,7 +162,7 @@ class SelectStatementTests : GRDBTestCase { XCTAssertEqual(error.description, "SQLite error 1: boom - while executing `\(sql)`") } - needsThrow = false + needsThrowMutex.store(false) XCTAssertEqual(try String.fetchAll(db.cachedStatement(sql: sql)), ["success"]) } } diff --git a/Tests/GRDBTests/UpdateStatementTests.swift b/Tests/GRDBTests/UpdateStatementTests.swift index 64b9c23c3..6a3233fdc 100644 --- a/Tests/GRDBTests/UpdateStatementTests.swift +++ b/Tests/GRDBTests/UpdateStatementTests.swift @@ -178,17 +178,16 @@ class UpdateStatementTests : GRDBTestCase { func testUpdateStatementAcceptsSelectQueriesAndConsumeAllRows() throws { let dbQueue = try makeDatabaseQueue() - var index = 0 + let indexMutex = Mutex(0) try dbQueue.inDatabase { db in db.add(function: DatabaseFunction("seq", argumentCount: 0, pure: false) { _ in - defer { index += 1 } - return index + indexMutex.increment() }) try db.execute(sql: "SELECT seq() UNION ALL SELECT seq() UNION ALL SELECT seq()") let statement = try db.makeStatement(sql: "SELECT seq() UNION ALL SELECT seq() UNION ALL SELECT seq()") try statement.execute() } - XCTAssertEqual(index, 3 + 3) + XCTAssertEqual(indexMutex.load(), 3 + 3) } func testExecuteNothing() throws { From 300e5fec6b0364dbe660d27c54a235bb696209b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Aug 2024 15:39:57 +0200 Subject: [PATCH 06/30] DatabaseFunction is Identifiable --- GRDB/Core/DatabaseFunction.swift | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index d7f835401..3731db9b4 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -29,16 +29,20 @@ import SQLite3 /// - ``localizedUppercase`` /// - ``lowercase`` /// - ``uppercase`` -public final class DatabaseFunction: Hashable, Sendable { - // SQLite identifies functions by (name + argument count) - private struct Identity: Hashable { +public final class DatabaseFunction: Hashable, Identifiable, Sendable { + /// The identifier of an SQLite function. + /// + /// SQLite identifies functions by their name and argument count. + public struct ID: Hashable, Sendable { let name: String let nArg: CInt // -1 for variadic functions } - /// The name of the SQL function - public var name: String { identity.name } - private let identity: Identity + /// The name of the SQL function. + public var name: String { id.name } + + /// The identifier of the SQL function. + public let id: ID let isPure: Bool private let kind: Kind private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) } @@ -84,7 +88,7 @@ public final class DatabaseFunction: Hashable, Sendable { pure: Bool = false, function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?) { - self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1) + self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1) self.isPure = pure self.kind = .function { (argc, argv) in let arguments = (0.. Bool { - lhs.identity == rhs.identity + lhs.id == rhs.id } } From a5806a002045dbb39e8596d426e6295df8f11780 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Aug 2024 15:28:17 +0200 Subject: [PATCH 07/30] [BREAKING] DatabaseFunction is no longer Hashable --- GRDB/Core/Database.swift | 6 +++--- GRDB/Core/DatabaseFunction.swift | 13 +------------ 2 files changed, 4 insertions(+), 15 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 8f3eeaffe..1a18d265a 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -361,7 +361,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib private var trace: ((TraceEvent) -> Void)? /// The registered custom SQL functions. - private var functions = Set() + private var functions: [DatabaseFunction.ID: DatabaseFunction] = [:] /// The registered custom SQL collations. private var collations = Set() @@ -707,13 +707,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// let dbPool = try DatabasePool(path: ..., configuration: config) /// ``` public func add(function: DatabaseFunction) { - functions.update(with: function) + functions[function.id] = function function.install(in: self) } /// Removes a custom SQL function. public func remove(function: DatabaseFunction) { - functions.remove(function) + functions.removeValue(forKey: function.id) function.uninstall(in: self) } diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 3731db9b4..9e2c03ed2 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -29,7 +29,7 @@ import SQLite3 /// - ``localizedUppercase`` /// - ``lowercase`` /// - ``uppercase`` -public final class DatabaseFunction: Hashable, Identifiable, Sendable { +public final class DatabaseFunction: Identifiable, Sendable { /// The identifier of an SQLite function. /// /// SQLite identifies functions by their name and argument count. @@ -428,17 +428,6 @@ public final class DatabaseFunction: Hashable, Identifiable, Sendable { } } -extension DatabaseFunction { - public func hash(into hasher: inout Hasher) { - hasher.combine(id) - } - - /// Two functions are equal if they share the same name and arity. - public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool { - lhs.id == rhs.id - } -} - /// The protocol for custom SQLite aggregates. /// /// For example: From 405312f52e3bbb6ba0f7c5a604309fa840162b07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 10 Feb 2024 19:49:07 +0100 Subject: [PATCH 08/30] DatabaseCollation is Sendable --- GRDB/Core/DatabaseCollation.swift | 6 +++--- TODO.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index 38c0dba68..19ae4baed 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -29,10 +29,10 @@ import Foundation /// - ``localizedCompare`` /// - ``localizedStandardCompare`` /// - ``unicodeCompare`` -public final class DatabaseCollation { +public final class DatabaseCollation: Sendable { /// The name of the collation. public let name: String - let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult + let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult /// Creates a collation. /// @@ -49,7 +49,7 @@ public final class DatabaseCollation { /// - parameters: /// - name: The collation name. /// - function: A function that compares two strings. - public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) { + public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) { self.name = name self.function = { (length1, buffer1, length2, buffer2) in // Buffers are not C strings: they do not end with \0. diff --git a/TODO.md b/TODO.md index ef373f309..31cae197e 100644 --- a/TODO.md +++ b/TODO.md @@ -108,7 +108,7 @@ - [ ] GRDB7: Not Sendable: FilterCursor (b26e9709) - [ ] GRDB7: Sendable: RowAdapter (d138af26) - [ ] GRDB7: Sendable: ValueObservationScheduler (8429eb68) -- [ ] GRDB7: Sendable: DatabaseCollation (4d9d67dd) +- [X] GRDB7: Sendable: DatabaseCollation (4d9d67dd) - [ ] GRDB7: Sendable: LogErrorFunction (f362518d) - [ ] GRDB7: Sendable: ReadWriteBox (57a86a0e) - [ ] GRDB7: Sendable: Pool (f13b2d2e) From eedd165e5ba57c87345f0f349703ec7cfe5a4e7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Aug 2024 15:34:35 +0200 Subject: [PATCH 09/30] DatabaseCollation is Identifiable --- GRDB/Core/DatabaseCollation.swift | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index 19ae4baed..792531da9 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -29,7 +29,33 @@ import Foundation /// - ``localizedCompare`` /// - ``localizedStandardCompare`` /// - ``unicodeCompare`` -public final class DatabaseCollation: Sendable { +public final class DatabaseCollation: Identifiable, Sendable { + /// The identifier of an SQLite collation. + /// + /// SQLite identifies collations by their name (case insensitive). + public struct ID: Hashable { + var name: String + + // Collation equality is based on the sqlite3_strnicmp SQLite function. + // (see https://www.sqlite.org/c3ref/create_collation.html). Computing + // a hash value that honors the Swift Hashable contract (value equality + // implies hash equality) is thus non trivial. But it's not that + // important, since this hashValue is only used when one adds + // or removes a collation from a database connection. + public func hash(into hasher: inout Hasher) { + hasher.combine(0) + } + + /// Two collations are equal if they share the same name (case insensitive) + public static func == (lhs: Self, rhs: Self) -> Bool { + // See + return sqlite3_stricmp(lhs.name, rhs.name) == 0 + } + } + + /// The identifier of the collation. + public var id: ID { ID(name: name) } + /// The name of the collation. public let name: String let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult From c1f59dfa2a5ad995a3b43fa6e232a0b9c93fe38e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Aug 2024 15:36:09 +0200 Subject: [PATCH 10/30] [BREAKING] DatabaseCollation is no longer Hashable --- GRDB/Core/Database.swift | 6 +++--- GRDB/Core/DatabaseCollation.swift | 18 ------------------ 2 files changed, 3 insertions(+), 21 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 1a18d265a..dec9d1273 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -364,7 +364,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib private var functions: [DatabaseFunction.ID: DatabaseFunction] = [:] /// The registered custom SQL collations. - private var collations = Set() + private var collations: [DatabaseCollation.ID: DatabaseCollation] = [:] /// Support for `beginReadOnly()` and `endReadOnly()`. private var readOnlyDepth = 0 @@ -734,7 +734,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// let dbPool = try DatabasePool(path: ..., configuration: config) /// ``` public func add(collation: DatabaseCollation) { - collations.update(with: collation) + collations[collation.id] = collation let collationPointer = Unmanaged.passUnretained(collation).toOpaque() let code = sqlite3_create_collation_v2( sqliteConnection, @@ -753,7 +753,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Removes a collation. public func remove(collation: DatabaseCollation) { - collations.remove(collation) + collations.removeValue(forKey: collation.id) sqlite3_create_collation_v2( sqliteConnection, collation.name, diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index 792531da9..6748874c8 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -93,21 +93,3 @@ public final class DatabaseCollation: Identifiable, Sendable { } } } - -extension DatabaseCollation: Hashable { - // Collation equality is based on the sqlite3_strnicmp SQLite function. - // (see https://www.sqlite.org/c3ref/create_collation.html). Computing - // a hash value that honors the Swift Hashable contract (value equality - // implies hash equality) is thus non trivial. But it's not that - // important, since this hashValue is only used when one adds - // or removes a collation from a database connection. - public func hash(into hasher: inout Hasher) { - hasher.combine(0) - } - - /// Two collations are equal if they share the same name (case insensitive) - public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool { - // See - return sqlite3_stricmp(lhs.name, rhs.name) == 0 - } -} From 55cdb4e9a975f603e2542a155e1d7864228de662 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 11 Feb 2024 14:01:57 +0100 Subject: [PATCH 11/30] DatabaseMigrator is Sendable --- GRDB/Migration/DatabaseMigrator.swift | 4 ++-- GRDB/Migration/Migration.swift | 4 ++-- TODO.md | 2 +- Tests/GRDBTests/DatabaseMigratorTests.swift | 8 ++++---- Tests/GRDBTests/RecordEditedTests.swift | 6 ++++-- .../RecordMinimalNonOptionalPrimaryKeySingleTests.swift | 6 ++++-- Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift | 6 ++++-- Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift | 6 ++++-- Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift | 6 ++++-- Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift | 6 ++++-- Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift | 6 ++++-- Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift | 6 ++++-- Tests/GRDBTests/RecordPrimaryKeySingleTests.swift | 6 ++++-- ...imaryKeySingleWithReplaceConflictResolutionTests.swift | 6 ++++-- Tests/GRDBTests/RecordSubClassTests.swift | 6 ++++-- Tests/GRDBTests/RecordWithColumnNameManglingTests.swift | 6 ++++-- Tests/GRDBTests/TransactionObserverTests.swift | 2 +- 17 files changed, 58 insertions(+), 34 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 2bb9d8517..00c759c22 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -40,7 +40,7 @@ import Foundation /// - ``completedMigrations(_:)`` /// - ``hasBeenSuperseded(_:)`` /// - ``hasCompletedMigrations(_:)`` -public struct DatabaseMigrator { +public struct DatabaseMigrator: Sendable { /// Controls how a migration handle foreign keys constraints. public enum ForeignKeyChecks: Sendable { /// The migration runs with disabled foreign keys. @@ -207,7 +207,7 @@ public struct DatabaseMigrator { public mutating func registerMigration( _ identifier: String, foreignKeyChecks: ForeignKeyChecks = .deferred, - migrate: @escaping (Database) throws -> Void) + migrate: @escaping @Sendable (Database) throws -> Void) { let migrationChecks: Migration.ForeignKeyChecks switch foreignKeyChecks { diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 36676d017..5a100bdec 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -1,5 +1,5 @@ /// An internal struct that defines a migration. -struct Migration { +struct Migration: Sendable { enum ForeignKeyChecks { case deferred case immediate @@ -8,7 +8,7 @@ struct Migration { let identifier: String var foreignKeyChecks: ForeignKeyChecks - let migrate: (Database) throws -> Void + let migrate: @Sendable (Database) throws -> Void func run(_ db: Database) throws { if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false { diff --git a/TODO.md b/TODO.md index 31cae197e..ba700e44f 100644 --- a/TODO.md +++ b/TODO.md @@ -104,7 +104,7 @@ - [X] GRDB7: Sendable: DatabaseColumnDecodingStrategy (264d7fb5) - [X] GRDB7/BREAKING: Remove DatabaseFuture and concurrentRead (05f7d3c8) - [X] GRDB7: Sendable: DatabaseFunction (6e691fe7) -- [ ] GRDB7: Sendable: DatabaseMigrator (22114ad4) +- [X] GRDB7: Sendable: DatabaseMigrator (22114ad4) - [ ] GRDB7: Not Sendable: FilterCursor (b26e9709) - [ ] GRDB7: Sendable: RowAdapter (d138af26) - [ ] GRDB7: Sendable: ValueObservationScheduler (8429eb68) diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index c117b5729..a9efa088d 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -128,7 +128,7 @@ class DatabaseMigratorTests : GRDBTestCase { } let expectation = self.expectation(description: "") - migrator.asyncMigrate(writer, completion: { dbResult in + migrator.asyncMigrate(writer, completion: { [migrator2] dbResult in // No migration error let db = try! dbResult.get() @@ -795,13 +795,13 @@ class DatabaseMigratorTests : GRDBTestCase { var migrator = DatabaseMigrator() migrator.eraseDatabaseOnSchemaChange = true - var witness = 1 + let mutex = Mutex(0) migrator.registerMigration("1") { db in + let value = mutex.increment() try db.execute(sql: """ CREATE TABLE t1(id INTEGER PRIMARY KEY); INSERT INTO t1(id) VALUES (?) - """, arguments: [witness]) - witness += 1 + """, arguments: [value]) } let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 31316f5c0..64573f4c4 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -15,7 +15,7 @@ private class Person : Record { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, @@ -131,7 +131,9 @@ class RecordEditedTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createPerson", migrate: Person.setup) + migrator.registerMigration("createPerson") { + try Person.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 21896ae5b..a77404913 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -13,7 +13,7 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: "CREATE TABLE minimalSingles (id TEXT NOT NULL PRIMARY KEY)") } @@ -48,7 +48,9 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createMinimalNonOptionalPrimaryKeySingle", migrate: MinimalNonOptionalPrimaryKeySingle.setup) + migrator.registerMigration("createMinimalNonOptionalPrimaryKeySingle") { + try MinimalNonOptionalPrimaryKeySingle.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 37a577b21..ff462cb6a 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -12,7 +12,7 @@ class MinimalRowID : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: "CREATE TABLE minimalRowIDs (id INTEGER PRIMARY KEY)") } @@ -52,7 +52,9 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createMinimalRowID", migrate: MinimalRowID.setup) + migrator.registerMigration("createMinimalRowID") { + try MinimalRowID.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 028d6ea6d..9139d0cfc 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -11,7 +11,7 @@ class MinimalSingle: Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: "CREATE TABLE minimalSingles (UUID TEXT NOT NULL PRIMARY KEY)") } @@ -49,7 +49,9 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createMinimalSingle", migrate: MinimalSingle.setup) + migrator.registerMigration("createMinimalSingle") { + try MinimalSingle.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index d2388e1d9..cc4de060e 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -16,7 +16,7 @@ private class Person : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( creationDate TEXT NOT NULL, @@ -84,7 +84,9 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createPerson", migrate: Person.setup) + migrator.registerMigration("createPerson") { + try Person.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index f8b8c8e10..cf792c686 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -14,7 +14,7 @@ private class Citizenship : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE citizenships ( personName TEXT NOT NULL, @@ -61,7 +61,9 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createCitizenship", migrate: Citizenship.setup) + migrator.registerMigration("createCitizenship") { + try Citizenship.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 8582a5e48..a96bd496e 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -14,7 +14,7 @@ private class Item : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE items ( name TEXT, @@ -58,7 +58,9 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createItem", migrate: Item.setup) + migrator.registerMigration("createItem") { + try Item.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index eb9023cf2..dabb5c908 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -16,7 +16,7 @@ private class Person : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, @@ -78,7 +78,9 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createPerson", migrate: Person.setup) + migrator.registerMigration("createPerson") { + try Person.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 69664f729..ca70ff5b4 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -12,7 +12,7 @@ class Pet : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE pets ( UUID TEXT NOT NULL PRIMARY KEY, @@ -51,7 +51,9 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createPet", migrate: Pet.setup) + migrator.registerMigration("createPet") { + try Pet.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index e1444cdf3..8451feeab 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -11,7 +11,7 @@ class Email : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE emails ( email TEXT NOT NULL PRIMARY KEY ON CONFLICT REPLACE, @@ -50,7 +50,9 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createEmail", migrate: Email.setup) + migrator.registerMigration("createEmail") { + try Email.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index fc3d8dc3f..ce82183f5 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -15,7 +15,7 @@ private class Person : Record { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, @@ -105,7 +105,9 @@ class RecordSubClassTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createPerson", migrate: Person.setup) + migrator.registerMigration("createPerson") { + try Person.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index 0ce7021e0..e9dba8383 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -13,7 +13,7 @@ class BadlyMangledStuff : Record { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY, name TEXT)") } @@ -48,7 +48,9 @@ class RecordWithColumnNameManglingTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createBadlyMangledStuff", migrate: BadlyMangledStuff.setup) + migrator.registerMigration("createBadlyMangledStuff") { + try BadlyMangledStuff.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index 0730f42f2..cedbb2302 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -1384,7 +1384,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer) try dbQueue.writeWithoutTransaction { db in - try MinimalRowID.setup(inDatabase: db) + try MinimalRowID.setup(db) let record = MinimalRowID() try record.save(db) From 961f6c41760e69abb2d57c492463329f5082782a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Mar 2024 18:45:22 +0100 Subject: [PATCH 12/30] FilterCursor can't be made Sendable --- GRDB/Core/Cursor.swift | 4 ++++ TODO.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 5ce6dc7c0..f2bed7800 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -909,6 +909,10 @@ public final class FilterCursor { } } +// Explicit non-conformance to Sendable. +@available(*, unavailable) +extension FilterCursor: Sendable { } + extension FilterCursor: Cursor { public func next() throws -> Base.Element? { while let element = try base.next() { diff --git a/TODO.md b/TODO.md index ba700e44f..4302cc33d 100644 --- a/TODO.md +++ b/TODO.md @@ -105,7 +105,7 @@ - [X] GRDB7/BREAKING: Remove DatabaseFuture and concurrentRead (05f7d3c8) - [X] GRDB7: Sendable: DatabaseFunction (6e691fe7) - [X] GRDB7: Sendable: DatabaseMigrator (22114ad4) -- [ ] GRDB7: Not Sendable: FilterCursor (b26e9709) +- [X] GRDB7: Not Sendable: FilterCursor (b26e9709) - [ ] GRDB7: Sendable: RowAdapter (d138af26) - [ ] GRDB7: Sendable: ValueObservationScheduler (8429eb68) - [X] GRDB7: Sendable: DatabaseCollation (4d9d67dd) From 7aff0b97c7890495844a05c334c8a14ddb82e4ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Mar 2024 18:59:20 +0100 Subject: [PATCH 13/30] RowAdapter is Sendable --- GRDB/Core/RowAdapter.swift | 6 +++--- TODO.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index a077e5815..86c42a38d 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -318,7 +318,7 @@ extension Statement: _RowLayout { /// - ``RenameColumnAdapter`` /// - ``ScopeAdapter`` /// - ``SuffixRowAdapter`` -public protocol RowAdapter { +public protocol RowAdapter: Sendable { /// You never call this method directly. It is called for you whenever an /// adapter has to be applied. /// @@ -656,11 +656,11 @@ struct ChainedAdapter: RowAdapter { /// print(Array(adaptedRow.columnNames)) /// ``` public struct RenameColumnAdapter: RowAdapter { - let transform: (String) -> String + let transform: @Sendable (String) -> String /// Creates a `RenameColumnAdapter` adapter that renames columns according to the /// provided transform function. - public init(_ transform: @escaping (String) -> String) { + public init(_ transform: @escaping @Sendable (String) -> String) { self.transform = transform } diff --git a/TODO.md b/TODO.md index 4302cc33d..132ca83bc 100644 --- a/TODO.md +++ b/TODO.md @@ -106,7 +106,7 @@ - [X] GRDB7: Sendable: DatabaseFunction (6e691fe7) - [X] GRDB7: Sendable: DatabaseMigrator (22114ad4) - [X] GRDB7: Not Sendable: FilterCursor (b26e9709) -- [ ] GRDB7: Sendable: RowAdapter (d138af26) +- [X] GRDB7: Sendable: RowAdapter (d138af26) - [ ] GRDB7: Sendable: ValueObservationScheduler (8429eb68) - [X] GRDB7: Sendable: DatabaseCollation (4d9d67dd) - [ ] GRDB7: Sendable: LogErrorFunction (f362518d) From 5333dbeff1a094509acd430983abef74cf606b5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Mar 2024 19:36:05 +0100 Subject: [PATCH 14/30] LogErrorFunction is Sendable --- GRDB/Core/Database.swift | 30 ++++++++++++++++++--- TODO.md | 2 +- Tests/GRDBTests/DatabasePoolTests.swift | 4 +-- Tests/GRDBTests/DatabaseQueueTests.swift | 2 +- Tests/GRDBTests/DatabaseSnapshotTests.swift | 2 +- Tests/GRDBTests/GRDBTestCase.swift | 14 +++++----- 6 files changed, 39 insertions(+), 15 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index dec9d1273..fb0715e4e 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -122,8 +122,14 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``logError`` /// - ``releaseMemory()`` /// - ``trace(options:_:)`` +/// +/// ### Supporting Types +/// +/// - ``BusyCallback`` +/// - ``BusyMode`` /// - ``CheckpointMode`` /// - ``DatabaseBackupProgress`` +/// - ``LogErrorFunction`` /// - ``StorageClass`` /// - ``TraceEvent`` /// - ``TracingOptions`` @@ -143,8 +149,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The error logging function. /// + /// SQLite can be configured to invoke a callback function containing + /// an error code and a terse error message whenever anomalies occur. + /// + /// This global error callback must be configured early in the lifetime + /// of your application: + /// + /// ```swift + /// Database.logError = { (resultCode, message) in + /// NSLog("%@", "SQLite error \(resultCode): \(message)") + /// } + /// ``` + /// + /// - warning: Database.logError must be set before any database + /// connection is opened. This includes the connections that your + /// application opens with GRDB, but also connections opened by + /// other tools, such as third-party libraries. Setting it after a + /// connection has been opened is an SQLite misuse, and has no effect. + /// /// Related SQLite documentation: - public static var logError: LogErrorFunction? = nil { + nonisolated(unsafe) public static var logError: LogErrorFunction? = nil { didSet { if logError != nil { _registerErrorLogCallback { (_, code, message) in @@ -1830,7 +1854,7 @@ extension Database { // MARK: - Database-Related Types - /// See BusyMode and + /// See ``BusyMode`` and public typealias BusyCallback = @Sendable (_ numberOfTries: Int) -> Bool /// When there are several connections to a database, a connection may try @@ -2019,7 +2043,7 @@ extension Database { } /// An error log function that takes an error code and message. - public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void + public typealias LogErrorFunction = @Sendable (_ resultCode: ResultCode, _ message: String) -> Void /// An SQLite storage class. /// diff --git a/TODO.md b/TODO.md index 132ca83bc..c9ed6dceb 100644 --- a/TODO.md +++ b/TODO.md @@ -109,7 +109,7 @@ - [X] GRDB7: Sendable: RowAdapter (d138af26) - [ ] GRDB7: Sendable: ValueObservationScheduler (8429eb68) - [X] GRDB7: Sendable: DatabaseCollation (4d9d67dd) -- [ ] GRDB7: Sendable: LogErrorFunction (f362518d) +- [X] GRDB7: Sendable: LogErrorFunction (f362518d) - [ ] GRDB7: Sendable: ReadWriteBox (57a86a0e) - [ ] GRDB7: Sendable: Pool (f13b2d2e) - [ ] GRDB7: Sendable: OnDemandFuture fulfill (2aabc4c1) diff --git a/Tests/GRDBTests/DatabasePoolTests.swift b/Tests/GRDBTests/DatabasePoolTests.swift index 2e42bb5cc..21b76f64e 100644 --- a/Tests/GRDBTests/DatabasePoolTests.swift +++ b/Tests/GRDBTests/DatabasePoolTests.swift @@ -397,7 +397,7 @@ class DatabasePoolTests: GRDBTestCase { XCTFail("Expected Error") } catch DatabaseError.SQLITE_BUSY { } } - XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master")) + XCTAssert(lastSQLiteDiagnostic!.message.contains("unfinalized statement: SELECT * FROM sqlite_master")) // Database is not closed: no error try dbPool.write { db in @@ -427,7 +427,7 @@ class DatabasePoolTests: GRDBTestCase { // // The first comes from GRDB, and the second, depending on the SQLite // version, from `sqlite3_close_v2()`. Write the test so that it always pass: - XCTAssert(lastMessage!.contains("unfinalized statement")) + XCTAssert(lastSQLiteDiagnostic!.message.contains("unfinalized statement")) // Database is in a zombie state. // In the zombie state, access throws SQLITE_MISUSE diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index bf0bb5371..3f748f06e 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -458,7 +458,7 @@ class DatabaseQueueTests: GRDBTestCase { XCTFail("Expected Error") } catch DatabaseError.SQLITE_BUSY { } } - XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master")) + XCTAssert(lastSQLiteDiagnostic!.message.contains("unfinalized statement: SELECT * FROM sqlite_master")) // Database is not closed: no error try dbQueue.inDatabase { db in diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index 6730a8984..1cb422ecd 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -424,7 +424,7 @@ class DatabaseSnapshotTests: GRDBTestCase { XCTFail("Expected Error") } catch DatabaseError.SQLITE_BUSY { } } - XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master")) + XCTAssert(lastSQLiteDiagnostic!.message.contains("unfinalized statement: SELECT * FROM sqlite_master")) // Database is not closed: no error try snapshot.read { db in diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 7fe7ac6b3..a4151604e 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -12,15 +12,15 @@ import XCTest @testable import GRDB // Support for Database.logError -var lastResultCode: ResultCode? = nil -var lastMessage: String? = nil +struct SQLiteDiagnostic { + var resultCode: ResultCode + var message: String +} +private let lastSQLiteDiagnosticMutex = Mutex(nil) +var lastSQLiteDiagnostic: SQLiteDiagnostic? { lastSQLiteDiagnosticMutex.load() } let logErrorSetup: Void = { - let lock = NSLock() Database.logError = { (resultCode, message) in - lock.lock() - defer { lock.unlock() } - lastResultCode = resultCode - lastMessage = message + lastSQLiteDiagnosticMutex.store(SQLiteDiagnostic(resultCode: resultCode, message: message)) } }() From e93e4c5a31335d3334ed9acec0c911bd45e51182 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 11 Feb 2024 11:52:26 +0100 Subject: [PATCH 15/30] ReadWriteBox is Sendable --- GRDB/Utils/ReadWriteBox.swift | 3 ++- TODO.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/GRDB/Utils/ReadWriteBox.swift b/GRDB/Utils/ReadWriteBox.swift index 1037ef8b3..2c0cd88f8 100644 --- a/GRDB/Utils/ReadWriteBox.swift +++ b/GRDB/Utils/ReadWriteBox.swift @@ -3,7 +3,8 @@ import Dispatch /// A ReadWriteBox grants multiple readers and single-writer guarantees on a /// value. It is backed by a concurrent DispatchQueue. @propertyWrapper -final class ReadWriteBox { +final class ReadWriteBox: @unchecked Sendable { + // @unchecked because `_wrappedValue` is protected by `queue` private var _wrappedValue: T private var queue: DispatchQueue diff --git a/TODO.md b/TODO.md index c9ed6dceb..84ccdb2ec 100644 --- a/TODO.md +++ b/TODO.md @@ -110,7 +110,7 @@ - [ ] GRDB7: Sendable: ValueObservationScheduler (8429eb68) - [X] GRDB7: Sendable: DatabaseCollation (4d9d67dd) - [X] GRDB7: Sendable: LogErrorFunction (f362518d) -- [ ] GRDB7: Sendable: ReadWriteBox (57a86a0e) +- [X] GRDB7: Sendable: ReadWriteBox (57a86a0e) - [ ] GRDB7: Sendable: Pool (f13b2d2e) - [ ] GRDB7: Sendable: OnDemandFuture fulfill (2aabc4c1) - [ ] GRDB7: Sendable: WALSnapshotTransaction (7fd34012) From b587afba0e65d726e8996ba3c5bd03b505fd5994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 11 Feb 2024 11:52:45 +0100 Subject: [PATCH 16/30] Pool is Sendable --- GRDB/Core/DatabasePool.swift | 6 ++-- GRDB/Core/DatabaseSnapshotPool.swift | 19 +++++------ GRDB/Utils/Pool.swift | 50 ++++++++++++++++++---------- TODO.md | 2 +- Tests/GRDBTests/PoolTests.swift | 4 ++- 5 files changed, 46 insertions(+), 35 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index e7e4ff609..e6019cd72 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -62,17 +62,15 @@ public final class DatabasePool { // an opened transaction. readerConfiguration.allowsUnsafeTransactions = false - var readerCount = 0 readerPool = Pool( maximumCount: configuration.maximumReaderCount, qos: configuration.readQoS, - makeElement: { - readerCount += 1 // protected by Pool (TODO: document this protection behavior) + makeElement: { [readerConfiguration] index in return try SerializedDatabase( path: path, configuration: readerConfiguration, defaultLabel: "GRDB.DatabasePool", - purpose: "reader.\(readerCount)") + purpose: "reader.\(index)") }) // Set up journal mode unless readonly diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 525fa1c74..935f3ccf4 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -130,6 +130,7 @@ public final class DatabaseSnapshotPool { /// `db` is used. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(_ db: Database, configuration: Configuration? = nil) throws { + let path = db.path var configuration = Self.configure(configuration ?? db.configuration) // Acquire and hold WAL snapshot @@ -138,7 +139,7 @@ public final class DatabaseSnapshotPool { } var holderConfig = Configuration() holderConfig.allowsUnsafeTransactions = true - snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig) + snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig) try snapshotHolder.inDatabase { db in try db.beginTransaction(.deferred) try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") @@ -158,20 +159,18 @@ public final class DatabaseSnapshotPool { } self.configuration = configuration - self.path = db.path + self.path = path self.walSnapshot = walSnapshot - var readerCount = 0 readerPool = Pool( maximumCount: configuration.maximumReaderCount, qos: configuration.readQoS, - makeElement: { - readerCount += 1 // protected by Pool (TODO: document this protection behavior) + makeElement: { [configuration] index in return try SerializedDatabase( - path: db.path, + path: path, configuration: configuration, defaultLabel: "GRDB.DatabaseSnapshotPool", - purpose: "snapshot.\(readerCount)") + purpose: "snapshot.\(index)") }) } @@ -219,17 +218,15 @@ public final class DatabaseSnapshotPool { self.path = path self.walSnapshot = walSnapshot - var readerCount = 0 readerPool = Pool( maximumCount: configuration.maximumReaderCount, qos: configuration.readQoS, - makeElement: { - readerCount += 1 // protected by Pool (TODO: document this protection behavior) + makeElement: { [configuration] index in return try SerializedDatabase( path: path, configuration: configuration, defaultLabel: "GRDB.DatabaseSnapshotPool", - purpose: "snapshot.\(readerCount)") + purpose: "snapshot.\(index)") }) } diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 6e1014c75..0a8be5338 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -35,8 +35,9 @@ import Dispatch /// got 2 /// got 1 /// got 3 -final class Pool { - private class Item { +final class Pool: Sendable { + private class Item: @unchecked Sendable { + // @unchecked because `isAvailable` is protected by `Pool.content`. let element: T var isAvailable: Bool @@ -46,8 +47,19 @@ final class Pool { } } - private let makeElement: () throws -> T - @ReadWriteBox private var items: [Item] = [] + private struct Content { + var items: [Item] + + /// The number of created items. May become greater than the number + /// of elements in items, as some items are destroyed and other + /// are created. + var createdCount = 0 + } + + typealias ElementAndRelease = (element: T, release: @Sendable (PoolCompletion) -> Void) + + private let makeElement: @Sendable (Int) throws -> T + private let content = ReadWriteBox(wrappedValue: Content(items: [], createdCount: 0)) private let itemsSemaphore: DispatchSemaphore // limits the number of elements private let itemsGroup: DispatchGroup // knows when no element is used private let barrierQueue: DispatchQueue @@ -59,11 +71,12 @@ final class Pool { /// - maximumCount: The maximum number of elements. /// - qos: The quality of service of asynchronous accesses. /// - makeElement: A function that creates an element. It is called - /// on demand. + /// on demand. Its argument is the index of the created elements + /// (1, then 2, etc). init( maximumCount: Int, qos: DispatchQoS = .unspecified, - makeElement: @escaping () throws -> T) + makeElement: @escaping @Sendable (_ index: Int) throws -> T) { GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1") self.makeElement = makeElement @@ -75,19 +88,20 @@ final class Pool { /// Returns a tuple (element, release) /// Client must call release(), only once, after the element has been used. - func get() throws -> (element: T, release: (PoolCompletion) -> Void) { + func get() throws -> ElementAndRelease { try barrierQueue.sync { itemsSemaphore.wait() itemsGroup.enter() do { - let item = try $items.update { items -> Item in - if let item = items.first(where: \.isAvailable) { + let item = try content.update { content -> Item in + if let item = content.items.first(where: \.isAvailable) { item.isAvailable = false return item } else { - let element = try makeElement() + content.createdCount += 1 + let element = try makeElement(content.createdCount) let item = Item(element: element, isAvailable: false) - items.append(item) + content.items.append(item) return item } } @@ -107,7 +121,7 @@ final class Pool { /// /// - important: The `execute` argument is executed in a serial dispatch /// queue, so make sure you use the element asynchronously. - func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) { + func asyncGet(_ execute: @escaping (Result) -> Void) { // Inspired by https://khanlou.com/2016/04/the-GCD-handbook/ // > We wait on the semaphore in the serial queue, which means that // > we’ll have at most one blocked thread when we reach maximum @@ -128,7 +142,7 @@ final class Pool { } private func release(_ item: Item, completion: PoolCompletion) { - $items.update { items in + content.update { content in switch completion { case .reuse: // This is why Item is a class, not a struct: so that we can @@ -136,8 +150,8 @@ final class Pool { item.isAvailable = true case .discard: // Discard should be rare: perform lookup. - if let index = items.firstIndex(where: { $0 === item }) { - items.remove(at: index) + if let index = content.items.firstIndex(where: { $0 === item }) { + content.items.remove(at: index) } } } @@ -148,8 +162,8 @@ final class Pool { /// Performs a block on each pool element, available or not. /// The block is run is some arbitrary dispatch queue. func forEach(_ body: (T) throws -> Void) rethrows { - try $items.read { items in - for item in items { + try content.read { content in + for item in content.items { try body(item.element) } } @@ -158,7 +172,7 @@ final class Pool { /// Removes all elements from the pool. /// Currently used elements won't be reused. func removeAll() { - items = [] + content.update { $0.items.removeAll() } } /// Blocks until no element is used, and runs the `barrier` function before diff --git a/TODO.md b/TODO.md index 84ccdb2ec..a0d7dd972 100644 --- a/TODO.md +++ b/TODO.md @@ -111,7 +111,7 @@ - [X] GRDB7: Sendable: DatabaseCollation (4d9d67dd) - [X] GRDB7: Sendable: LogErrorFunction (f362518d) - [X] GRDB7: Sendable: ReadWriteBox (57a86a0e) -- [ ] GRDB7: Sendable: Pool (f13b2d2e) +- [X] GRDB7: Sendable: Pool (f13b2d2e) - [ ] GRDB7: Sendable: OnDemandFuture fulfill (2aabc4c1) - [ ] GRDB7: Sendable: WALSnapshotTransaction (7fd34012) - [ ] GRDB7: sending closures for SerializedDatabase diff --git a/Tests/GRDBTests/PoolTests.swift b/Tests/GRDBTests/PoolTests.swift index 29c8fcaf7..dbce4868b 100644 --- a/Tests/GRDBTests/PoolTests.swift +++ b/Tests/GRDBTests/PoolTests.swift @@ -5,7 +5,9 @@ class PoolTests: XCTestCase { /// Returns a Pool whose elements are incremented integers: 1, 2, 3... private func makeCounterPool(maximumCount: Int) -> Pool { let count = ReadWriteBox(wrappedValue: 0) - return Pool(maximumCount: maximumCount, makeElement: count.increment) + return Pool(maximumCount: maximumCount, makeElement: { _ in + count.increment() + }) } func testElementsAreReused() throws { From b0c572507504b2d311e97c4780c048756cb361ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Mar 2024 07:54:07 +0200 Subject: [PATCH 17/30] OnDemandFuture fulfill is Sendable --- GRDB/Core/DatabaseReader.swift | 8 +++----- GRDB/Utils/OnDemandFuture.swift | 10 +++++++--- TODO.md | 2 +- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index ca694be0d..37d63fc66 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -555,11 +555,9 @@ extension DatabaseReader { value: @escaping (Database) throws -> Output) -> DatabasePublishers.Read { - Deferred { - Future { fulfill in - self.asyncRead { dbResult in - fulfill(dbResult.flatMap { db in Result { try value(db) } }) - } + OnDemandFuture { fulfill in + self.asyncRead { dbResult in + fulfill(dbResult.flatMap { db in Result { try value(db) } }) } } .receiveValues(on: scheduler) diff --git a/GRDB/Utils/OnDemandFuture.swift b/GRDB/Utils/OnDemandFuture.swift index e1d8dff6c..645da8d19 100644 --- a/GRDB/Utils/OnDemandFuture.swift +++ b/GRDB/Utils/OnDemandFuture.swift @@ -14,9 +14,12 @@ import Foundation /// Both two extra scheduling guarantees are used by GRDB in order to be /// able to spawn concurrent database reads right from the database writer /// queue, and fulfill GRDB preconditions. +/// +/// OnDemandFuture also adds Sendable requirements that avoid +/// compiler warnings. @available(iOS 13, macOS 10.15, tvOS 13, *) struct OnDemandFuture: Publisher { - typealias Promise = (Result) -> Void + typealias Promise = @Sendable (Result) -> Void typealias Output = Output typealias Failure = Failure fileprivate let attemptToFulfill: (@escaping Promise) -> Void @@ -34,8 +37,9 @@ struct OnDemandFuture: Publisher { } @available(iOS 13, macOS 10.15, tvOS 13, *) -private class OnDemandFutureSubscription: Subscription { - typealias Promise = (Result) -> Void +private class OnDemandFutureSubscription: Subscription, @unchecked Sendable { + // @unchecked because `state` is protected with `lock`. + typealias Promise = @Sendable (Result) -> Void private enum State { case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void) diff --git a/TODO.md b/TODO.md index a0d7dd972..82fb1a5b0 100644 --- a/TODO.md +++ b/TODO.md @@ -112,7 +112,7 @@ - [X] GRDB7: Sendable: LogErrorFunction (f362518d) - [X] GRDB7: Sendable: ReadWriteBox (57a86a0e) - [X] GRDB7: Sendable: Pool (f13b2d2e) -- [ ] GRDB7: Sendable: OnDemandFuture fulfill (2aabc4c1) +- [X] GRDB7: Sendable: OnDemandFuture fulfill (2aabc4c1) - [ ] GRDB7: Sendable: WALSnapshotTransaction (7fd34012) - [ ] GRDB7: sending closures for SerializedDatabase - [ ] GRDB7: sending closures for ValueObservationScheduler From 1036371dff933deade0cadbd0d61d46f35faaa7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 25 Aug 2024 17:42:39 +0200 Subject: [PATCH 18/30] DatabasePromise is Sendable --- .../Request/Association/Association.swift | 24 ++++++++++++++----- .../Request/QueryInterfaceRequest.swift | 12 +++++----- .../Request/RequestProtocols.swift | 24 ++++++++++++++----- GRDB/QueryInterface/SQL/DatabasePromise.swift | 8 +++---- GRDB/QueryInterface/SQL/SQLRelation.swift | 16 ++++++------- TODO.md | 2 +- 6 files changed, 55 insertions(+), 31 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index debe9590a..b52aa3122 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -173,7 +173,9 @@ extension Association { // SelectionRequest conformance extension Association { - public func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { + public func selectWhenConnected( + _ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] + ) -> Self { withDestinationRelation { relation in relation = relation.selectWhenConnected { db in try selection(db).map(\.sqlSelection) @@ -181,7 +183,9 @@ extension Association { } } - public func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { + public func annotatedWhenConnected( + with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] + ) -> Self { withDestinationRelation { relation in relation = relation.annotatedWhenConnected { db in try selection(db).map(\.sqlSelection) @@ -192,7 +196,9 @@ extension Association { // FilteredRequest conformance extension Association { - public func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { + public func filterWhenConnected( + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible + ) -> Self { withDestinationRelation { relation in relation = relation.filterWhenConnected { db in try predicate(db).sqlExpression @@ -203,7 +209,9 @@ extension Association { // OrderedRequest conformance extension Association { - public func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self { + public func orderWhenConnected( + _ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm] + ) -> Self { withDestinationRelation { relation in relation = relation.orderWhenConnected { db in try orderings(db).map(\.sqlOrdering) @@ -239,7 +247,9 @@ extension Association { // AggregatingRequest conformance extension Association { - public func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self { + public func groupWhenConnected( + _ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible] + ) -> Self { withDestinationRelation { relation in relation = relation.groupWhenConnected { db in try expressions(db).map(\.sqlExpression) @@ -247,7 +257,9 @@ extension Association { } } - public func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { + public func havingWhenConnected( + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible + ) -> Self { withDestinationRelation { relation in relation = relation.havingWhenConnected { db in try predicate(db).sqlExpression diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 54826e148..e4dccaaa6 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -118,7 +118,7 @@ extension QueryInterfaceRequest: FetchRequest { extension QueryInterfaceRequest: SelectionRequest { public func selectWhenConnected( - _ selection: @escaping (Database) throws -> [any SQLSelectable]) + _ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self { with { @@ -282,7 +282,7 @@ extension QueryInterfaceRequest: SelectionRequest { } public func annotatedWhenConnected( - with selection: @escaping (Database) throws -> [any SQLSelectable]) + with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self { with { @@ -295,7 +295,7 @@ extension QueryInterfaceRequest: SelectionRequest { extension QueryInterfaceRequest: FilteredRequest { public func filterWhenConnected( - _ predicate: @escaping (Database) throws -> any SQLExpressible) + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self { with { @@ -308,7 +308,7 @@ extension QueryInterfaceRequest: FilteredRequest { extension QueryInterfaceRequest: OrderedRequest { public func orderWhenConnected( - _ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) + _ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]) -> Self { with { @@ -355,7 +355,7 @@ extension QueryInterfaceRequest: OrderedRequest { extension QueryInterfaceRequest: AggregatingRequest { public func groupWhenConnected( - _ expressions: @escaping (Database) throws -> [any SQLExpressible]) + _ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]) -> Self { with { @@ -366,7 +366,7 @@ extension QueryInterfaceRequest: AggregatingRequest { } public func havingWhenConnected( - _ predicate: @escaping (Database) throws -> any SQLExpressible) + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self { with { diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 1803a4cfb..030ad91ee 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -58,7 +58,9 @@ public protocol SelectionRequest { /// /// - parameter selection: A closure that accepts a database connection and /// returns an array of result columns. - func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self + func selectWhenConnected( + _ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] + ) -> Self /// Appends result columns to the selected columns. /// @@ -78,7 +80,9 @@ public protocol SelectionRequest { /// /// - parameter selection: A closure that accepts a database connection and /// returns an array of result columns. - func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self + func annotatedWhenConnected( + with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] + ) -> Self } extension SelectionRequest { @@ -240,7 +244,9 @@ public protocol FilteredRequest { /// /// - parameter predicate: A closure that accepts a database connection and /// returns a boolean SQL expression. - func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self + func filterWhenConnected( + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible + ) -> Self } extension FilteredRequest { @@ -764,7 +770,9 @@ public protocol AggregatingRequest { /// /// - parameter expressions: A closure that accepts a database connection /// and returns an array of SQL expressions. - func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self + func groupWhenConnected( + _ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible] + ) -> Self /// Filters the aggregated groups with a boolean SQL expression. /// @@ -788,7 +796,9 @@ public protocol AggregatingRequest { /// /// - parameter predicate: A closure that accepts a database connection and /// returns a boolean SQL expression. - func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self + func havingWhenConnected( + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible + ) -> Self } extension AggregatingRequest { @@ -969,7 +979,9 @@ public protocol OrderedRequest { /// /// - parameter orderings: A closure that accepts a database connection and /// returns an array of SQL ordering terms. - func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self + func orderWhenConnected( + _ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm] + ) -> Self /// Returns a request with reversed ordering. /// diff --git a/GRDB/QueryInterface/SQL/DatabasePromise.swift b/GRDB/QueryInterface/SQL/DatabasePromise.swift index 9d497b584..7fb7c3ede 100644 --- a/GRDB/QueryInterface/SQL/DatabasePromise.swift +++ b/GRDB/QueryInterface/SQL/DatabasePromise.swift @@ -23,20 +23,20 @@ /// see SQLRelation.filterPromise. struct DatabasePromise { /// Returns the resolved value. - let resolve: (Database) throws -> T + let resolve: @Sendable (Database) throws -> T /// Creates a promise that resolves to a value. - init(value: T) { + init(value: T) where T: Sendable { self.resolve = { _ in value } } /// Creates a promise from a closure. - init(_ resolve: @escaping (Database) throws -> T) { + init(_ resolve: @escaping @Sendable (Database) throws -> T) { self.resolve = resolve } /// Returns a promise whose value is transformed by the given closure. - func map(_ transform: @escaping (T) throws -> U) -> DatabasePromise { + func map(_ transform: @escaping @Sendable (T) throws -> U) -> DatabasePromise { DatabasePromise { db in try transform(resolve(db)) } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 4488cc96f..d9b1b0a29 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -187,7 +187,7 @@ extension SQLRelation { /// Convenience factory methods which selects all rows from a table. static func all( fromTable tableName: String, - selection: @escaping (Database) -> [SQLSelection] = { _ in [.allColumns] }) + selection: @escaping @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] }) -> Self { SQLRelation( @@ -197,7 +197,7 @@ extension SQLRelation { } extension SQLRelation: Refinable { - func selectWhenConnected(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self { + func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self { with { $0.selectionPromise = DatabasePromise(selection) } @@ -228,7 +228,7 @@ extension SQLRelation: Refinable { } } - func annotatedWhenConnected(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self { + func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self { with { let old = $0.selectionPromise $0.selectionPromise = DatabasePromise { db in @@ -242,7 +242,7 @@ extension SQLRelation: Refinable { annotatedWhenConnected(with: { _ in selection }) } - func filterWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { + func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self { with { if let old = $0.filterPromise { $0.filterPromise = DatabasePromise { db in @@ -259,7 +259,7 @@ extension SQLRelation: Refinable { filterWhenConnected { _ in predicate } } - func orderWhenConnected(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self { + func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self { with { $0.ordering = SQLRelation.Ordering(orderings: orderings) } @@ -313,13 +313,13 @@ extension SQLRelation: Refinable { } } - func groupWhenConnected(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self { + func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self { with { $0.groupPromise = DatabasePromise(expressions) } } - func havingWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { + func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self { with { if let old = $0.havingExpressionPromise { $0.havingExpressionPromise = DatabasePromise { db in @@ -740,7 +740,7 @@ extension SQLRelation { isReversed: false) } - init(orderings: @escaping (Database) throws -> [SQLOrdering]) { + init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) { self.init( elements: [.terms(DatabasePromise(orderings))], isReversed: false) diff --git a/TODO.md b/TODO.md index 82fb1a5b0..cfa2d0b4c 100644 --- a/TODO.md +++ b/TODO.md @@ -122,7 +122,7 @@ - [ ] GRDB7: Sendable closures for writePublisher - [ ] GRDB7: Sendable closures for readPublisher - [ ] GRDB7: Not Sendable: fts5customtokenizer, fts5tokenizer, fts5wrappertokenizer -- [ ] GRDB7: Sendable: DatabasePromise (05899228, 5a2c15b8) +- [X] GRDB7: Sendable: DatabasePromise (05899228, 5a2c15b8) - [ ] GRDB7: Sendable: TableAlias (f2b0b186) - [ ] GRDB7: Sendable: SQLRelation (9545bf70) - [ ] GRDB7: Sendable: SQL (ac33856f) From 0fdd910b0847dcc008f0814c0319c35ada56b769 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Mar 2024 11:31:36 +0200 Subject: [PATCH 19/30] =?UTF-8?q?=E2=9A=A0=EF=B8=8F=20Make=20TableAlias=20?= =?UTF-8?q?Sendable=20even=20if=20it=20is=20not=20yet.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift | 4 +++- TODO.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index d364a6bbb..8715e0af9 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -213,7 +213,9 @@ class StatementArgumentsSink { /// See ``TableRequest/aliased(_:)`` for more information and examples. /// /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) -public class TableAlias { +public class TableAlias: @unchecked Sendable { + // This Sendable conformance is transient. TableAlias IS NOT really Sendable. + // TODO: GRDB7 Make TableAlias really Sendable private enum Impl { /// A TableAlias is undefined when it is created by the GRDB user: /// diff --git a/TODO.md b/TODO.md index cfa2d0b4c..cced7f267 100644 --- a/TODO.md +++ b/TODO.md @@ -123,7 +123,7 @@ - [ ] GRDB7: Sendable closures for readPublisher - [ ] GRDB7: Not Sendable: fts5customtokenizer, fts5tokenizer, fts5wrappertokenizer - [X] GRDB7: Sendable: DatabasePromise (05899228, 5a2c15b8) -- [ ] GRDB7: Sendable: TableAlias (f2b0b186) +- [X] GRDB7: Sendable: TableAlias (f2b0b186) - [ ] GRDB7: Sendable: SQLRelation (9545bf70) - [ ] GRDB7: Sendable: SQL (ac33856f) - [ ] GRDB7: Split Row.swift (2ce8a619) From 56e2ab85b7ce42a8b3567c38cc9b55ab6f8b083c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 24 Apr 2024 07:57:30 +0200 Subject: [PATCH 20/30] SQLAssociationCondition is Sendable --- GRDB/QueryInterface/Request/CommonTableExpression.swift | 6 +++--- GRDB/QueryInterface/SQL/SQLRelation.swift | 4 ++-- GRDB/QueryInterface/SQL/Table.swift | 2 +- GRDB/QueryInterface/TableRecord+Association.swift | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 8e1e5d2c6..9cbd4d2bb 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -385,7 +385,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( @@ -421,7 +421,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to destination: Destination.Type, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation where Destination: TableRecord { @@ -458,7 +458,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to destination: Table, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index d9b1b0a29..5633f3051 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -796,7 +796,7 @@ extension SQLRelation { /// // SELECT * FROM book WHERE author.id = 1 /// // ~~~~~~~~~~~~~ /// author.request(for: Author.books) -enum SQLAssociationCondition { +enum SQLAssociationCondition: Sendable { /// A condition based on a foreign key. case foreignKey(SQLForeignKeyCondition) @@ -814,7 +814,7 @@ enum SQLAssociationCondition { /// player[Column("id")] == bonus[Column("playerID")] /// }) /// Player.with(bonus).joining(required: association) - case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression?) + case expression(@Sendable (_ left: TableAlias, _ right: TableAlias) -> SQLExpression?) /// The condition that does not constrain the two associated tables /// in any way. diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 6b85f3e51..2cc7690e5 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -1297,7 +1297,7 @@ extension Table { /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 67249d4d1..6ba8dacfe 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -339,7 +339,7 @@ extension TableRecord { /// - returns: An association to the common table expression. public static func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( From 30569aba27856a077ab6b44aa2d043c1e39634bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 23 Apr 2024 08:11:20 +0200 Subject: [PATCH 21/30] OrderedDictionary is conditionally Sendable --- GRDB/Utils/OrderedDictionary.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index 4f7d5242b..228f84dfc 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -207,6 +207,8 @@ extension OrderedDictionary: CustomStringConvertible { } } +extension OrderedDictionary: Sendable where Key: Sendable, Value: Sendable { } + extension Dictionary { init(_ orderedDictionary: OrderedDictionary) { self = orderedDictionary.dictionary From aff662c101001802ce160f64da479f39225aef44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Mar 2024 11:44:38 +0200 Subject: [PATCH 22/30] SQL is Sendable --- GRDB/Core/SQL.swift | 2 +- GRDB/QueryInterface/SQL/SQLExpression.swift | 2 +- GRDB/QueryInterface/SQL/SQLOrdering.swift | 2 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 6 +++--- GRDB/QueryInterface/SQL/SQLSelection.swift | 2 +- GRDB/QueryInterface/SQL/SQLSubquery.swift | 2 +- TODO.md | 4 ++-- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index 4246cf202..a6d2c439f 100644 --- a/GRDB/Core/SQL.swift +++ b/GRDB/Core/SQL.swift @@ -39,7 +39,7 @@ /// /// - ``append(literal:)`` /// - ``append(sql:arguments:)`` -public struct SQL { +public struct SQL: Sendable { /// `SQL.Element` is a component of an `SQL` literal. /// /// Elements can be qualified with table aliases, and this is how `SQL` diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index eb4d58ceb..6203aaef5 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -34,7 +34,7 @@ /// ``` /// /// Related SQLite documentation: -public struct SQLExpression { +public struct SQLExpression: Sendable { private var impl: Impl /// The preferred interpretation of the expression in JSON diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index e7b18f974..0badbcca2 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -12,7 +12,7 @@ /// function arguments, prefer the ``SQLOrderingTerm`` protocol. /// /// Related SQLite documentation: -public struct SQLOrdering { +public struct SQLOrdering: Sendable { private var impl: Impl private enum Impl { diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 5633f3051..2077537b2 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -90,7 +90,7 @@ /// // JOIN passport ON passport.citizenId = citizens.id /// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...); /// Country.including(all: Country.citizens) -struct SQLRelation { +struct SQLRelation: Sendable { struct Child: Refinable { enum Kind { // Record.including(optional: association) @@ -672,7 +672,7 @@ struct SQLLimit { // MARK: - SQLSource -struct SQLSource { +struct SQLSource: Sendable { var tableName: String var alias: TableAlias? @@ -691,7 +691,7 @@ struct SQLSource { extension SQLRelation { /// SQLRelation.Ordering provides the order clause to SQLRelation. - struct Ordering { + struct Ordering: Sendable { private enum Element { case terms(DatabasePromise<[SQLOrdering]>) case ordering(SQLRelation.Ordering) diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index c4ff88045..a0f29120d 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -15,7 +15,7 @@ /// function arguments, prefer the ``SQLSelectable`` protocol. /// /// Related SQLite documentation: -public struct SQLSelection { +public struct SQLSelection: Sendable { private var impl: Impl /// The private implementation of the public `SQLSelection`. diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index fb3d59584..fdc9c3a3a 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -1,7 +1,7 @@ /// An SQL subquery. /// /// `SQLSubquery` is an opaque representation of an SQL subquery. -public struct SQLSubquery { +public struct SQLSubquery: Sendable { private var impl: Impl private enum Impl { diff --git a/TODO.md b/TODO.md index cced7f267..1fd95c8d9 100644 --- a/TODO.md +++ b/TODO.md @@ -124,8 +124,8 @@ - [ ] GRDB7: Not Sendable: fts5customtokenizer, fts5tokenizer, fts5wrappertokenizer - [X] GRDB7: Sendable: DatabasePromise (05899228, 5a2c15b8) - [X] GRDB7: Sendable: TableAlias (f2b0b186) -- [ ] GRDB7: Sendable: SQLRelation (9545bf70) -- [ ] GRDB7: Sendable: SQL (ac33856f) +- [X] GRDB7: Sendable: SQLRelation (9545bf70) +- [X] GRDB7: Sendable: SQL (ac33856f) - [ ] GRDB7: Split Row.swift (2ce8a619) - [ ] GRDB7: Cleanup ValueReducer (6c73b1c5) - [X] GRDB7: DatabaseCursor has a primary associated type (b11c5dd2) From cc5798cf1ed54c010b231d99def28d8482ba1ddc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 Mar 2024 08:51:57 +0200 Subject: [PATCH 23/30] WALSnapshotTransaction is Sendable --- GRDB/Core/DatabaseError.swift | 4 + GRDB/Core/DatabaseSnapshotPool.swift | 2 +- GRDB/Core/WALSnapshotTransaction.swift | 80 +++++++++++++------ .../Observers/ValueConcurrentObserver.swift | 15 ++-- TODO.md | 4 +- 5 files changed, 70 insertions(+), 35 deletions(-) diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 524c18d63..bf808dbaa 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -415,6 +415,10 @@ extension DatabaseError { static func connectionIsClosed() -> Self { DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed") } + + static func snapshotIsLost() -> Self { + DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.") + } } // Support for `catch DatabaseError.SQLITE_XXX` diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 935f3ccf4..715dabf72 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -318,7 +318,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { return try reader.reentrantSync { db in let result = try value(db) if snapshotIsLost(db) { - throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.") + throw DatabaseError.snapshotIsLost() } return result } diff --git a/GRDB/Core/WALSnapshotTransaction.swift b/GRDB/Core/WALSnapshotTransaction.swift index 4340b67e4..eb6597fe1 100644 --- a/GRDB/Core/WALSnapshotTransaction.swift +++ b/GRDB/Core/WALSnapshotTransaction.swift @@ -3,9 +3,28 @@ /// /// `WALSnapshotTransaction` **takes ownership** of its reader /// `SerializedDatabase` (TODO: make it a move-only type eventually). -class WALSnapshotTransaction { - private let reader: SerializedDatabase - private let release: (_ isInsideTransaction: Bool) -> Void +final class WALSnapshotTransaction: @unchecked Sendable { + // @unchecked because `databaseAccess` is protected by a mutex. + + private struct DatabaseAccess { + let reader: SerializedDatabase + let release: @Sendable (_ isInsideTransaction: Bool) -> Void + + // MUST be called only once + func commitAndRelease() { + // WALSnapshotTransaction may be deinitialized in the dispatch + // queue of its reader: allow reentrancy. + let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in + try? db.commit() + return db.isInsideTransaction + } + release(isInsideTransaction) + } + } + + // TODO: consider using the serialized DispatchQueue of reader instead of a lock. + /// nil when closed + private let databaseAccessMutex: Mutex /// The state of the database at the beginning of the transaction. let walSnapshot: WALSnapshot @@ -36,10 +55,11 @@ class WALSnapshotTransaction { /// is no longer used. init( onReader reader: SerializedDatabase, - release: @escaping (_ isInsideTransaction: Bool) -> Void) + release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void) throws { assert(reader.configuration.readonly) + let databaseAccess = DatabaseAccess(reader: reader, release: release) do { // Open a long-lived transaction, and enter snapshot isolation @@ -50,44 +70,56 @@ class WALSnapshotTransaction { try db.clearSchemaCacheIfNeeded() return try WALSnapshot(db) } - self.reader = reader - self.release = release + self.databaseAccessMutex = Mutex(databaseAccess) } catch { // self is not initialized, so deinit will not run. - Self.commitAndRelease(reader: reader, release: release) + databaseAccess.commitAndRelease() throw error } } deinit { - Self.commitAndRelease(reader: reader, release: release) + close() } /// Executes database operations in the snapshot transaction, and /// returns their result after they have finished executing. - func read(_ value: (Database) throws -> T) rethrows -> T { - // We should check the validity of the snapshot, as DatabaseSnapshotPool does. - try reader.sync(value) + func read(_ value: (Database) throws -> T) throws -> T { + try databaseAccessMutex.withLock { databaseAccess in + guard let databaseAccess else { + throw DatabaseError.snapshotIsLost() + } + + // We should check the validity of the snapshot, as DatabaseSnapshotPool does. + return try databaseAccess.reader.sync(value) + } } /// Schedules database operations for execution, and /// returns immediately. - func asyncRead(_ value: @escaping (Database) -> Void) { - // We should check the validity of the snapshot, as DatabaseSnapshotPool does. - reader.async(value) + func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { + databaseAccessMutex.withLock { databaseAccess in + guard let databaseAccess else { + value(.failure(DatabaseError.snapshotIsLost())) + return + } + + databaseAccess.reader.async { db in + // We should check the validity of the snapshot, as DatabaseSnapshotPool does. + // At least check if self was closed: + if self.databaseAccessMutex.load() == nil { + value(.failure(DatabaseError.snapshotIsLost())) + } + value(.success(db)) + } + } } - private static func commitAndRelease( - reader: SerializedDatabase, - release: (_ isInsideTransaction: Bool) -> Void) - { - // WALSnapshotTransaction may be deinitialized in the dispatch - // queue of its reader: allow reentrancy. - let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in - try? db.commit() - return db.isInsideTransaction + func close() { + databaseAccessMutex.withLock { databaseAccess in + databaseAccess?.commitAndRelease() + databaseAccess = nil } - release(isInsideTransaction) } } #endif diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index e57aef098..d4cc4b030 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -352,10 +352,11 @@ extension ValueConcurrentObserver { let initialFetchTransaction = try result.get() // Second async jump because that's how // `DatabasePool.asyncWALSnapshotTransaction` has to be used. - initialFetchTransaction.asyncRead { db in + initialFetchTransaction.asyncRead { dbResult in do { let fetchedValue: Reducer.Fetched let initialRegion: DatabaseRegion + let db = try dbResult.get() switch self.trackingMode { case let .constantRegion(regions): @@ -429,11 +430,9 @@ extension ValueConcurrentObserver { // checkpointed. That's why we'll keep `initialFetchTransaction` // alive until the comparison is done. // - // However, we want to release `initialFetchTransaction` as soon as + // However, we want to close `initialFetchTransaction` as soon as // possible, so that the reader connection it holds becomes - // available for other reads. It will be released when this optional - // is set to nil: - var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction + // available for other reads. databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in let events = self.lock.synchronized { self.notificationCallbacks?.events } @@ -446,7 +445,7 @@ extension ValueConcurrentObserver { // Was the database modified since the initial fetch? let isModified: Bool if let currentWALSnapshot = try? WALSnapshot(writerDB) { - let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot) + let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot) assert(ordering <= 0, "Unexpected snapshot ordering") isModified = ordering < 0 } else { @@ -454,9 +453,9 @@ extension ValueConcurrentObserver { isModified = true } - // Comparison done: end the WAL snapshot transaction + // Comparison done: close the WAL snapshot transaction // and release its reader connection. - initialFetchTransaction = nil + initialFetchTransaction.close() if isModified { events.databaseDidChange?() diff --git a/TODO.md b/TODO.md index 1fd95c8d9..c19164891 100644 --- a/TODO.md +++ b/TODO.md @@ -113,7 +113,7 @@ - [X] GRDB7: Sendable: ReadWriteBox (57a86a0e) - [X] GRDB7: Sendable: Pool (f13b2d2e) - [X] GRDB7: Sendable: OnDemandFuture fulfill (2aabc4c1) -- [ ] GRDB7: Sendable: WALSnapshotTransaction (7fd34012) +- [X] GRDB7: Sendable: WALSnapshotTransaction (7fd34012) - [ ] GRDB7: sending closures for SerializedDatabase - [ ] GRDB7: sending closures for ValueObservationScheduler - [ ] GRDB7: Sendable closures for ValueObservation.handleEvents @@ -130,7 +130,7 @@ - [ ] GRDB7: Cleanup ValueReducer (6c73b1c5) - [X] GRDB7: DatabaseCursor has a primary associated type (b11c5dd2) - [ ] GRDB7: Enable Strict Concurrency Checks (6aa43ded) -- [ ] GRDB7: Sendable: OrderedDictionary (e022c35b) +- [X] GRDB7: Sendable: OrderedDictionary (e022c35b) - [ ] GRDB7: Rename ReadWriteBox to ReadWriteLock (7f5205ef) - [ ] GRDB7: Sendable: DatabaseRegionConvertible (b4677ded) - [ ] GRDB7: Sendable: ValueConcurrentObserver (87b9db65, 5465d056) From 47aa1f58a7ec479e0f7f003448cf62ae9f488120 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 26 Aug 2024 08:36:46 +0200 Subject: [PATCH 24/30] TODO --- TODO.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/TODO.md b/TODO.md index c19164891..00feb18f0 100644 --- a/TODO.md +++ b/TODO.md @@ -144,6 +144,20 @@ - [ ] GRDB7: doc (c0838cf9) - [ ] GRDB7/BREAKING: PersistenceContainer is Sendable (50eefa8c) - [ ] GRDB7: TableRecord.databaseSelection must be declared as a computed property (24d232aa) +- [ ] GRDB7: Sendable: Association (b06aaee4) +- [ ] GRDB7/Tests: Sendable: ValueObservationRecorder (2947b3d7) +- [ ] GRDB7: ValueObservation.print cautiously uses its stream argument (5f8b39b7) +- [ ] GRDB7/Tests: use a single and Sendable test TextOutputStream (bbb1a736) +- [ ] GRDB7: ValueObservation needs a ValueReducer, not a `_ValueReducer` (08733108) +- [ ] GRDB7: Database support for cancellation (4ddf4bca) +- [ ] GRDB7: SerializedDatabase support for async db access with support for Task cancellation (737cb149) +- [ ] GRDB7: DatabaseWriter async methods support Task cancellation (a5226501) +- [ ] GRDB7: DatabaseReader async methods support Task cancellation (10c9d311) +- [ ] GRDB7: Document that async methods can throw CancellationError (8df18fb8) +- [ ] GRDB7: Sendable: AssociationAggregate (48ad10ae) +- [?] GRDB7: Sendable: AsyncValueObservation (ce63cdfa) +- [ ] GRDB7: Sendable: DatabaseRegionObservation (b4ff52fb) +- [ ] GRDB7: DispatchQueue.asyncSending (7b075e6b) - [?] GRDB7: Change ValueObservation callback argument so that it could expose snapshots? https://github.com/groue/GRDB.swift/discussions/1523#discussioncomment-9092500 From 4222854f8b576e38aeb648277b7b91d244de3397 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Aug 2024 07:46:52 +0200 Subject: [PATCH 25/30] DatabaseRegionConvertible is Sendable --- GRDB/Core/DatabaseRegion.swift | 8 ++++---- GRDB/Core/FetchRequest.swift | 12 +++++++----- TODO.md | 2 +- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index fddeb77d3..06b887947 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -416,7 +416,7 @@ private struct TableRegion: Equatable { /// ### Supporting Types /// /// - ``AnyDatabaseRegionConvertible`` -public protocol DatabaseRegionConvertible { +public protocol DatabaseRegionConvertible: Sendable { /// Returns a database region. /// /// - parameter db: A database connection. @@ -437,14 +437,14 @@ extension DatabaseRegion: DatabaseRegionConvertible { /// A type-erased DatabaseRegionConvertible public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { - let _region: (Database) throws -> DatabaseRegion + let _region: @Sendable (Database) throws -> DatabaseRegion - public init(_ region: @escaping (Database) throws -> DatabaseRegion) { + public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) { _region = region } public init(_ region: some DatabaseRegionConvertible) { - _region = region.databaseRegion + _region = { try region.databaseRegion($0) } } public func databaseRegion(_ db: Database) throws -> DatabaseRegion { diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 43115cab7..c3e24d8ba 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -171,7 +171,9 @@ extension FetchRequest { /// /// - parameter adapter: A closure that accepts a database connection and /// returns a row adapter. - public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest { + public func adapted( + _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter + ) -> AdaptedFetchRequest { AdaptedFetchRequest(self, adapter) } } @@ -181,11 +183,11 @@ extension FetchRequest { /// See ``FetchRequest/adapted(_:)``. public struct AdaptedFetchRequest { let base: Base - let adapter: (Database) throws -> any RowAdapter + let adapter: @Sendable (Database) throws -> any RowAdapter /// Creates an adapted request from a base request and a closure that builds /// a row adapter from a database connection. - init(_ base: Base, _ adapter: @escaping (Database) throws -> any RowAdapter) { + init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) { self.base = base self.adapter = adapter } @@ -274,7 +276,7 @@ extension AnyFetchRequest: FetchRequest { } // Class-based type erasure, so that we preserve full type information. -private class FetchRequestEraser: FetchRequest { +private class FetchRequestEraser: FetchRequest, @unchecked Sendable { typealias RowDecoder = Void var sqlSubquery: SQLSubquery { @@ -290,7 +292,7 @@ private class FetchRequestEraser: FetchRequest { } } -private final class ConcreteFetchRequestEraser: FetchRequestEraser { +private final class ConcreteFetchRequestEraser: FetchRequestEraser, @unchecked Sendable { let request: Request init(request: Request) { diff --git a/TODO.md b/TODO.md index 00feb18f0..0eb3932d9 100644 --- a/TODO.md +++ b/TODO.md @@ -132,7 +132,7 @@ - [ ] GRDB7: Enable Strict Concurrency Checks (6aa43ded) - [X] GRDB7: Sendable: OrderedDictionary (e022c35b) - [ ] GRDB7: Rename ReadWriteBox to ReadWriteLock (7f5205ef) -- [ ] GRDB7: Sendable: DatabaseRegionConvertible (b4677ded) +- [X] GRDB7: Sendable: DatabaseRegionConvertible (b4677ded) - [ ] GRDB7: Sendable: ValueConcurrentObserver (87b9db65, 5465d056) - [ ] GRDB7: Sendable: ValueWriteOnlyObserver (ff2a7548) - [ ] GRDB7: Sendable: ValueConcurrentObserver (87b9db65) From c56b52980afd9ae6ac5b19b19fa7f3f614aafc56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Aug 2024 07:55:46 +0200 Subject: [PATCH 26/30] DatabaseCancellable is Sendable --- GRDB/Core/DatabaseReader.swift | 8 ++--- .../DatabaseCancellable.swift | 34 ++++++++++++------- TODO.md | 2 +- 3 files changed, 26 insertions(+), 18 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 37d63fc66..2295f6f03 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -618,16 +618,16 @@ extension DatabaseReader { } return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ }) } else { - var isCancelled = false + let cancellable = AnyDatabaseCancellable() asyncRead { dbResult in - guard !isCancelled else { return } + if cancellable.isCancelled { return } let result = dbResult.flatMap { db in Result { try observation.fetchInitialValue(db) } } scheduler.schedule { - guard !isCancelled else { return } + if cancellable.isCancelled { return } do { try onChange(result.get()) } catch { @@ -635,7 +635,7 @@ extension DatabaseReader { } } } - return AnyDatabaseCancellable(cancel: { isCancelled = true }) + return cancellable } } } diff --git a/GRDB/ValueObservation/DatabaseCancellable.swift b/GRDB/ValueObservation/DatabaseCancellable.swift index de6298791..fc904892f 100644 --- a/GRDB/ValueObservation/DatabaseCancellable.swift +++ b/GRDB/ValueObservation/DatabaseCancellable.swift @@ -5,7 +5,7 @@ /// ### Supporting Types /// /// - ``AnyDatabaseCancellable`` -public protocol DatabaseCancellable { +public protocol DatabaseCancellable: Sendable { /// Cancel the activity. func cancel() } @@ -15,31 +15,39 @@ public protocol DatabaseCancellable { /// /// An `AnyDatabaseCancellable` instance automatically calls ``cancel()`` /// when deinitialized. -public class AnyDatabaseCancellable: DatabaseCancellable { - private var _cancel: (() -> Void)? +public final class AnyDatabaseCancellable: DatabaseCancellable { + private let cancelMutex: Mutex<(@Sendable () -> Void)?> + + var isCancelled: Bool { + cancelMutex.withLock { $0 == nil } + } + + convenience init() { + self.init(cancel: { }) + } /// Initializes the cancellable object with the given cancel-time closure. - public init(cancel: @escaping () -> Void) { - _cancel = cancel + public init(cancel: @escaping @Sendable () -> Void) { + cancelMutex = Mutex(cancel) } /// Creates a cancellable object that forwards cancellation to `base`. public convenience init(_ base: some DatabaseCancellable) { - var cancellable = Optional.some(base) self.init { - cancellable?.cancel() - cancellable = nil // Release memory + base.cancel() } } deinit { - _cancel?() + cancel() } public func cancel() { - // Don't prevent multiple concurrent calls to _cancel, because it is - // pointless. But release memory! - _cancel?() - _cancel = nil + let cancel = cancelMutex.withLock { + let cancel = $0 + $0 = nil + return cancel + } + cancel?() } } diff --git a/TODO.md b/TODO.md index 0eb3932d9..ac4245ad9 100644 --- a/TODO.md +++ b/TODO.md @@ -136,7 +136,7 @@ - [ ] GRDB7: Sendable: ValueConcurrentObserver (87b9db65, 5465d056) - [ ] GRDB7: Sendable: ValueWriteOnlyObserver (ff2a7548) - [ ] GRDB7: Sendable: ValueConcurrentObserver (87b9db65) -- [ ] GRDB7: Sendable: DatabaseCancellable (2f93f00b, 8f486a5e) +- [X] GRDB7: Sendable: DatabaseCancellable (2f93f00b, 8f486a5e) - [ ] GRDB7: ValueObservation closures - [?] GRDB7: DatabasePublishers.ValueSubscription - [ ] GRDB7: Sendable: ValueObservation (93f6f982) From aac8720bc75199806780c4290d030e96a616050b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Aug 2024 07:59:26 +0200 Subject: [PATCH 27/30] DatabaseRegionObservation is Sendable --- GRDB/Core/DatabaseRegion.swift | 2 +- GRDB/Core/DatabaseRegionObservation.swift | 4 ++-- TODO.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 06b887947..271b53f60 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -461,7 +461,7 @@ extension DatabaseRegion { } } - static func union(_ regions: [any DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { + static func union(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (Database) throws -> DatabaseRegion { return { db in try regions.reduce(into: DatabaseRegion()) { union, region in try union.formUnion(region.databaseRegion(db)) diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 3579586f8..877e14fea 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -3,10 +3,10 @@ import Combine #endif import Foundation -public struct DatabaseRegionObservation { +public struct DatabaseRegionObservation: Sendable { /// A closure that is evaluated when the observation starts, and returns /// the observed database region. - var observedRegion: (Database) throws -> DatabaseRegion + var observedRegion: @Sendable (Database) throws -> DatabaseRegion } extension DatabaseRegionObservation { diff --git a/TODO.md b/TODO.md index ac4245ad9..004238c8d 100644 --- a/TODO.md +++ b/TODO.md @@ -156,7 +156,7 @@ - [ ] GRDB7: Document that async methods can throw CancellationError (8df18fb8) - [ ] GRDB7: Sendable: AssociationAggregate (48ad10ae) - [?] GRDB7: Sendable: AsyncValueObservation (ce63cdfa) -- [ ] GRDB7: Sendable: DatabaseRegionObservation (b4ff52fb) +- [X] GRDB7: Sendable: DatabaseRegionObservation (b4ff52fb) - [ ] GRDB7: DispatchQueue.asyncSending (7b075e6b) - [?] GRDB7: Change ValueObservation callback argument so that it could expose snapshots? https://github.com/groue/GRDB.swift/discussions/1523#discussioncomment-9092500 From 849bba28207d2304cea6bad0e92ec8ee456f6c9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Aug 2024 08:23:04 +0200 Subject: [PATCH 28/30] Refactor ValueReducer for Swift concurrency The fetching facet of a ValueReducer is Sendable. --- .../Extension/ValueObservation.md | 2 +- .../Observers/ValueConcurrentObserver.swift | 38 +++++++++-------- .../Observers/ValueWriteOnlyObserver.swift | 24 +++++------ GRDB/ValueObservation/Reducers/Fetch.swift | 24 +++++++---- GRDB/ValueObservation/Reducers/Map.swift | 16 ++++--- .../Reducers/RemoveDuplicates.swift | 14 +++---- GRDB/ValueObservation/Reducers/Trace.swift | 27 +++++++----- .../Reducers/ValueReducer.swift | 42 ++++++++++++++----- GRDB/ValueObservation/ValueObservation.swift | 16 +++---- TODO.md | 2 +- Tests/GRDBTests/GRDBTestCase.swift | 27 ++++++++---- 11 files changed, 142 insertions(+), 90 deletions(-) diff --git a/GRDB/Documentation.docc/Extension/ValueObservation.md b/GRDB/Documentation.docc/Extension/ValueObservation.md index 2fbf4f9e1..5c4664e1f 100644 --- a/GRDB/Documentation.docc/Extension/ValueObservation.md +++ b/GRDB/Documentation.docc/Extension/ValueObservation.md @@ -313,6 +313,6 @@ When needed, you can help GRDB optimize observations and reduce database content - ``handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)`` - ``print(_:to:)`` -### Support +### Supporting Types - ``ValueReducer`` diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index d4cc4b030..2671b6b09 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -76,25 +76,25 @@ final class ValueConcurrentObserver Reducer.Fetched { + func fetch(_ db: Database) throws -> Reducer.Fetcher.Value { try db.isolated(readOnly: true) { - try reducer._fetch(db) + try fetcher.fetch(db) } } - func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetched, DatabaseRegion) { + func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetcher.Value, DatabaseRegion) { var region = DatabaseRegion() let fetchedValue = try db.isolated(readOnly: true) { try db.recordingSelection(®ion) { - try reducer._fetch(db) + try fetcher.fetch(db) } } return try (fetchedValue, region.observableRegion(db)) @@ -170,9 +170,9 @@ final class ValueConcurrentObserver (Reducer.Fetched, DatabaseRegion) in + let fetchedValue: Reducer.Fetcher.Value + let initialRegion: DatabaseRegion + (fetchedValue, initialRegion) = try databaseAccess.dbPool.read { db in switch trackingMode { case let .constantRegion(regions): let fetchedValue = try databaseAccess.fetch(db) @@ -583,7 +587,7 @@ extension ValueConcurrentObserver { do { // Fetch - let fetchedValue: Reducer.Fetched + let fetchedValue: Reducer.Fetcher.Value let initialRegion: DatabaseRegion let db = try dbResult.get() switch self.trackingMode { @@ -643,7 +647,7 @@ extension ValueConcurrentObserver { do { try writerDB.isolated(readOnly: true) { // Fetch - let fetchedValue: Reducer.Fetched + let fetchedValue: Reducer.Fetcher.Value let observedRegion: DatabaseRegion switch self.trackingMode { case .constantRegion: @@ -822,7 +826,7 @@ extension ValueConcurrentObserver: TransactionObserver { } } - private func reduce(_ fetchResult: Result) { + private func reduce(_ fetchResult: Result) { reduceQueue.async { do { let fetchedValue = try fetchResult.get() diff --git a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift index e7dc67bda..3f5a1c50f 100644 --- a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift @@ -83,26 +83,26 @@ final class ValueWriteOnlyObserver< /// If true, database values are fetched from a read-only access. private let readOnly: Bool - /// A reducer that fetches database values. - private let reducer: Reducer + /// The fetcher that fetches database values. + private let fetcher: Reducer.Fetcher - init(writer: Writer, readOnly: Bool, reducer: Reducer) { + init(writer: Writer, readOnly: Bool, fetcher: Reducer.Fetcher) { self.writer = writer self.readOnly = readOnly - self.reducer = reducer + self.fetcher = fetcher } - func fetch(_ db: Database) throws -> Reducer.Fetched { + func fetch(_ db: Database) throws -> Reducer.Fetcher.Value { try db.isolated(readOnly: readOnly) { - try reducer._fetch(db) + try fetcher.fetch(db) } } - func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetched, DatabaseRegion) { + func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetcher.Value, DatabaseRegion) { var region = DatabaseRegion() let fetchedValue = try db.isolated(readOnly: readOnly) { try db.recordingSelection(®ion) { - try reducer._fetch(db) + try fetcher.fetch(db) } } return try (fetchedValue, region.observableRegion(db)) @@ -160,9 +160,9 @@ final class ValueWriteOnlyObserver< self.databaseAccess = DatabaseAccess( writer: writer, readOnly: readOnly, - // ValueReducer semantics guarantees that reducer._fetch + // ValueReducer semantics guarantees that the fetcher // is independent from the reducer state - reducer: reducer) + fetcher: reducer._makeFetcher()) self.notificationCallbacks = NotificationCallbacks(events: events, onChange: onChange) self.reducer = reducer self.reduceQueue = DispatchQueue( @@ -301,7 +301,7 @@ extension ValueWriteOnlyObserver { /// By grouping the initial fetch and the beginning of observation in a /// single database access, we are sure that no concurrent write can happen /// during the initial fetch, and that we won't miss any future change. - private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetched? { + private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetcher.Value? { let (events, databaseAccess) = lock.synchronized { (notificationCallbacks?.events, self.databaseAccess) } @@ -380,7 +380,7 @@ extension ValueWriteOnlyObserver: TransactionObserver { do { // Fetch - let fetchedValue: Reducer.Fetched + let fetchedValue: Reducer.Fetcher.Value switch trackingMode { case .constantRegion, .constantRegionRecordedFromSelection: diff --git a/GRDB/ValueObservation/Reducers/Fetch.swift b/GRDB/ValueObservation/Reducers/Fetch.swift index 4f9b16c88..6ab2f1583 100644 --- a/GRDB/ValueObservation/Reducers/Fetch.swift +++ b/GRDB/ValueObservation/Reducers/Fetch.swift @@ -1,16 +1,24 @@ extension ValueReducers { /// A `ValueReducer` that perform database fetches. public struct Fetch: ValueReducer { - private let __fetch: (Database) throws -> Value - - /// Creates a reducer which passes raw fetched values through. - init(fetch: @escaping (Database) throws -> Value) { - self.__fetch = fetch + public struct _Fetcher: _ValueReducerFetcher { + let _fetch: @Sendable (Database) throws -> Value + + public func fetch(_ db: Database) throws -> Value { + assert(db.isInsideTransaction, "Fetching in a non-isolated way is illegal") + return try _fetch(db) + } } - public func _fetch(_ db: Database) throws -> Value { - assert(db.isInsideTransaction, "Fetching in a non-isolated way is illegal") - return try __fetch(db) + private let _fetch: @Sendable (Database) throws -> Value + + /// Creates a reducer which passes raw fetched values through. + init(fetch: @escaping @Sendable (Database) throws -> Value) { + self._fetch = fetch + } + + public func _makeFetcher() -> _Fetcher { + _Fetcher(_fetch: _fetch) } public func _value(_ fetched: Value) -> Value? { diff --git a/GRDB/ValueObservation/Reducers/Map.swift b/GRDB/ValueObservation/Reducers/Map.swift index b69984b24..0b90fda7f 100644 --- a/GRDB/ValueObservation/Reducers/Map.swift +++ b/GRDB/ValueObservation/Reducers/Map.swift @@ -26,11 +26,11 @@ extension ValueObservation { } extension ValueReducers { - /// A `ValueReducer` whose values consist of those in a `Base` reduced + /// A `ValueReducer` whose values consist of those in a `Base` reducer /// passed through a transform function. /// /// See ``ValueObservation/map(_:)``. - public struct Map: _ValueReducer { + public struct Map: ValueReducer { private var base: Base private let transform: (Base.Value) throws -> Value @@ -39,15 +39,13 @@ extension ValueReducers { self.transform = transform } - public mutating func _value(_ fetched: Base.Fetched) throws -> Value? { + public func _makeFetcher() -> Base.Fetcher { + base._makeFetcher() + } + + public mutating func _value(_ fetched: Base.Fetcher.Value) throws -> Value? { guard let value = try base._value(fetched) else { return nil } return try transform(value) } } } - -extension ValueReducers.Map: ValueReducer where Base: ValueReducer { - public func _fetch(_ db: Database) throws -> Base.Fetched { - try base._fetch(db) - } -} diff --git a/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift index 6d2e64e53..632066408 100644 --- a/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift @@ -67,7 +67,7 @@ extension ValueReducers { /// previously observed value. /// /// See ``ValueObservation/removeDuplicates()``. - public struct RemoveDuplicates: _ValueReducer { + public struct RemoveDuplicates: ValueReducer { private var base: Base private var previousValue: Base.Value? private var predicate: (Base.Value, Base.Value) -> Bool @@ -77,7 +77,11 @@ extension ValueReducers { self.predicate = predicate } - public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? { + public func _makeFetcher() -> Base.Fetcher { + base._makeFetcher() + } + + public mutating func _value(_ fetched: Base.Fetcher.Value) throws -> Base.Value? { guard let value = try base._value(fetched) else { return nil } @@ -90,9 +94,3 @@ extension ValueReducers { } } } - -extension ValueReducers.RemoveDuplicates: ValueReducer where Base: ValueReducer { - public func _fetch(_ db: Database) throws -> Base.Fetched { - try base._fetch(db) - } -} diff --git a/GRDB/ValueObservation/Reducers/Trace.swift b/GRDB/ValueObservation/Reducers/Trace.swift index bb2db4f62..107d80de7 100644 --- a/GRDB/ValueObservation/Reducers/Trace.swift +++ b/GRDB/ValueObservation/Reducers/Trace.swift @@ -4,12 +4,26 @@ extension ValueReducers { /// /// See ``ValueObservation/handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)`` /// and ``ValueObservation/print(_:to:)``. - public struct Trace: _ValueReducer { + public struct Trace: ValueReducer { + public struct _Fetcher: _ValueReducerFetcher { + let base: Base.Fetcher + let willFetch: @Sendable () -> Void + + public func fetch(_ db: Database) throws -> Base.Fetcher.Value { + willFetch() + return try base.fetch(db) + } + } + var base: Base - let willFetch: () -> Void + let willFetch: @Sendable () -> Void let didReceiveValue: (Base.Value) -> Void - public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? { + public func _makeFetcher() -> _Fetcher { + _Fetcher(base: base._makeFetcher(), willFetch: willFetch) + } + + public mutating func _value(_ fetched: Base.Fetcher.Value) throws -> Base.Value? { guard let value = try base._value(fetched) else { return nil } @@ -19,10 +33,3 @@ extension ValueReducers { } // swiftlint:enable line_length } - -extension ValueReducers.Trace: ValueReducer where Base: ValueReducer { - public func _fetch(_ db: Database) throws -> Base.Fetched { - willFetch() - return try base._fetch(db) - } -} diff --git a/GRDB/ValueObservation/Reducers/ValueReducer.swift b/GRDB/ValueObservation/Reducers/ValueReducer.swift index 0a4706057..52cf4e848 100644 --- a/GRDB/ValueObservation/Reducers/ValueReducer.swift +++ b/GRDB/ValueObservation/Reducers/ValueReducer.swift @@ -1,11 +1,28 @@ +// A `ValueReducer` fetches and transforms the database values +// observed by a ``ValueObservation``. +// +// It is NOT Sendable, because we need `ValueReducers.RemoveDuplicates` to +// be able to call `Equatable.==`, which IS not a Sendable function. +// Thread-safety will be assured by `ValueObservation`, which will make sure +// it does not invoke the reducer concurrently. +// +// However, we need to be able to fetch from any database dispatch queue, +// and maybe concurrently. That's why a `ValueReducer` has a Sendable facet, +// which is its `Fetcher`. + /// Implementation details of `ValueReducer`. public protocol _ValueReducer { - /// The type of fetched database values - associatedtype Fetched + /// The Sendable type that fetches database values + associatedtype Fetcher: _ValueReducerFetcher /// The type of observed values associatedtype Value + /// Returns a value that fetches database values upon changes in an + /// observed database region. The returned value method must not depend + /// on the state of the reducer. + func _makeFetcher() -> Fetcher + /// Transforms a fetched value into an eventual observed value. Returns nil /// when observer should not be notified. /// @@ -18,7 +35,14 @@ public protocol _ValueReducer { /// reducer._value(...) // MUST NOT be nil /// reducer._value(...) // MAY be nil /// reducer._value(...) // MAY be nil - mutating func _value(_ fetched: Fetched) throws -> Value? + mutating func _value(_ fetched: Fetcher.Value) throws -> Value? +} + +public protocol _ValueReducerFetcher: Sendable { + /// The type of fetched database values + associatedtype Value + + func fetch(_ db: Database) throws -> Value } /// `ValueReducer` supports ``ValueObservation``. @@ -26,17 +50,15 @@ public protocol _ValueReducer { /// A `ValueReducer` fetches and transforms the database values /// observed by a ``ValueObservation``. /// +/// Do not declare new conformances to `ValueReducer`. Only the built-in +/// conforming types are valid. +/// /// ## Topics /// -/// ### Support +/// ### Supporting Types /// /// - ``ValueReducers`` -public protocol ValueReducer: _ValueReducer { - /// Fetches database values upon changes in an observed database region. - /// - /// This method must does not depend on the state of the reducer. - func _fetch(_ db: Database) throws -> Fetched -} +public protocol ValueReducer: _ValueReducer { } /// A namespace for concrete types that adopt the ``ValueReducer`` protocol. public enum ValueReducers { } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index ae8ca3cc7..aa8a59f6d 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -4,7 +4,7 @@ import Combine import Dispatch import Foundation -public struct ValueObservation { +public struct ValueObservation { var events = ValueObservationEvents() /// A boolean value indicating whether the observation requires write access @@ -176,7 +176,7 @@ extension ValueObservation: Refinable { /// when ValueObservation events occur. public func handleEvents( willStart: (() -> Void)? = nil, - willFetch: (() -> Void)? = nil, + willFetch: (@Sendable () -> Void)? = nil, willTrackRegion: ((DatabaseRegion) -> Void)? = nil, databaseDidChange: (() -> Void)? = nil, didReceiveValue: ((Reducer.Value) -> Void)? = nil, @@ -267,7 +267,9 @@ extension ValueObservation: Refinable { where Reducer: ValueReducer { var reducer = makeReducer() - guard let value = try reducer._value(reducer._fetch(db)) else { + let fetcher = reducer._makeFetcher() + let fetchedValue = try fetcher.fetch(db) + guard let value = try reducer._value(fetchedValue) else { fatalError("Broken contract: reducer has no initial value") } return value @@ -731,7 +733,7 @@ extension ValueObservation { /// /// - parameter fetch: The closure that fetches the observed value. public static func trackingConstantRegion( - _ fetch: @escaping (Database) throws -> Value) + _ fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { @@ -805,7 +807,7 @@ extension ValueObservation { public static func tracking( region: any DatabaseRegionConvertible, _ otherRegions: any DatabaseRegionConvertible..., - fetch: @escaping (Database) throws -> Value) + fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { @@ -874,7 +876,7 @@ extension ValueObservation { /// - parameter fetch: The closure that fetches the observed value. public static func tracking( regions: [any DatabaseRegionConvertible], - fetch: @escaping (Database) throws -> Value) + fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { @@ -931,7 +933,7 @@ extension ValueObservation { /// /// - parameter fetch: The closure that fetches the observed value. public static func tracking( - _ fetch: @escaping (Database) throws -> Value) + _ fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { diff --git a/TODO.md b/TODO.md index 004238c8d..dd8551bb9 100644 --- a/TODO.md +++ b/TODO.md @@ -139,7 +139,7 @@ - [X] GRDB7: Sendable: DatabaseCancellable (2f93f00b, 8f486a5e) - [ ] GRDB7: ValueObservation closures - [?] GRDB7: DatabasePublishers.ValueSubscription -- [ ] GRDB7: Sendable: ValueObservation (93f6f982) +- [X] GRDB7: Sendable: ValueObservation (93f6f982) - [?] GRDB7: Not Sendable: SharedValueObservation - [ ] GRDB7: doc (c0838cf9) - [ ] GRDB7/BREAKING: PersistenceContainer is Sendable (50eefa8c) diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index a4151604e..ffb1f1a0b 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -235,26 +235,39 @@ extension FetchRequest { } /// A type-erased ValueReducer. -public struct AnyValueReducer: ValueReducer { - private var __fetch: (Database) throws -> Fetched +struct AnyValueReducer: ValueReducer { + private var __fetch: @Sendable (Database) throws -> Fetched private var __value: (Fetched) -> Value? - public init( - fetch: @escaping (Database) throws -> Fetched, + init( + fetch: @escaping @Sendable (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) { self.__fetch = fetch self.__value = value } - public func _fetch(_ db: Database) throws -> Fetched { - try __fetch(db) + func _makeFetcher() -> AnyValueReducerFetcher { + AnyValueReducerFetcher(fetch: __fetch) } - public func _value(_ fetched: Fetched) -> Value? { + func _value(_ fetched: Fetched) -> Value? { __value(fetched) } } +/// A type-erased _ValueReducerFetcher. +struct AnyValueReducerFetcher: _ValueReducerFetcher { + private var _fetch: @Sendable (Database) throws -> Fetched + + init(fetch: @escaping @Sendable (Database) throws -> Fetched) { + self._fetch = fetch + } + + func fetch(_ db: Database) throws -> Fetched { + try _fetch(db) + } +} + // Assume this is correct :-/ extension XCTestExpectation: @unchecked Sendable { } From c08b1fa7d5816d324c202d693c9781ed2622ca0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Aug 2024 09:58:15 +0200 Subject: [PATCH 29/30] ValueObservationScheduler is Sendable --- GRDB/ValueObservation/ValueObservationScheduler.swift | 2 +- TODO.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index d43cad7dc..df109cfee 100644 --- a/GRDB/ValueObservation/ValueObservationScheduler.swift +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -11,7 +11,7 @@ import Foundation /// - ``immediate`` /// - ``AsyncValueObservationScheduler`` /// - ``ImmediateValueObservationScheduler`` -public protocol ValueObservationScheduler { +public protocol ValueObservationScheduler: Sendable { /// Returns whether the initial value should be immediately notified. /// /// If the result is true, then this method was called on the main thread. diff --git a/TODO.md b/TODO.md index dd8551bb9..632aa72fe 100644 --- a/TODO.md +++ b/TODO.md @@ -107,7 +107,7 @@ - [X] GRDB7: Sendable: DatabaseMigrator (22114ad4) - [X] GRDB7: Not Sendable: FilterCursor (b26e9709) - [X] GRDB7: Sendable: RowAdapter (d138af26) -- [ ] GRDB7: Sendable: ValueObservationScheduler (8429eb68) +- [X] GRDB7: Sendable: ValueObservationScheduler (8429eb68) - [X] GRDB7: Sendable: DatabaseCollation (4d9d67dd) - [X] GRDB7: Sendable: LogErrorFunction (f362518d) - [X] GRDB7: Sendable: ReadWriteBox (57a86a0e) From b1424d16d5a81b4b388e9022d7256624f85cfc15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Aug 2024 10:08:03 +0200 Subject: [PATCH 30/30] [BREAKING] PersistenceContainer is Sendable --- GRDB/QueryInterface/SQL/SQLRelation.swift | 3 - GRDB/Record/EncodableRecord.swift | 97 ++++++++----------- .../Record/MutablePersistableRecord+DAO.swift | 10 +- .../MutablePersistableRecord+Insert.swift | 2 +- .../MutablePersistableRecord+Save.swift | 2 +- .../MutablePersistableRecord+Upsert.swift | 2 +- GRDB/Record/Record.swift | 3 +- GRDB/Record/TableRecord.swift | 2 +- TODO.md | 2 +- 9 files changed, 51 insertions(+), 72 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 2077537b2..569fb5d8a 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -1027,9 +1027,6 @@ extension Row: ColumnAddressable { /// PersistenceContainer has columns extension PersistenceContainer: ColumnAddressable { func index(forColumn column: String) -> String? { column } - func databaseValue(at column: String) -> DatabaseValue { - self[caseInsensitive: column]?.databaseValue ?? .null - } } // MARK: - Merging diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 9e8e80e2c..dd91c7586 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -258,7 +258,7 @@ extension EncodableRecord { /// database representation. public var databaseDictionary: [String: DatabaseValue] { get throws { - try Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null } + try Dictionary(uniqueKeysWithValues: PersistenceContainer(self)) } } } @@ -336,19 +336,30 @@ extension EncodableRecord { /// /// `PersistenceContainer` is the argument of the /// ``EncodableRecord/encode(to:)-k9pf`` method. -public struct PersistenceContainer { - // fileprivate for Row(_:PersistenceContainer) +public struct PersistenceContainer: Sendable { // The ordering of the OrderedDictionary helps generating always the same // SQL queries, and hit the statement cache. - fileprivate var storage: OrderedDictionary + private var storage: OrderedDictionary /// The value associated with the given column. + /// + /// The setter accepts any ``DatabaseValueConvertible`` type, but the + /// getter always returns a ``DatabaseValue``. public subscript(_ column: String) -> (any DatabaseValueConvertible)? { - get { self[caseInsensitive: column] } - set { storage.updateValue(newValue, forKey: column) } + get { + storage[CaseInsensitiveIdentifier(rawValue: column)] + } + set { + storage.updateValue( + newValue?.databaseValue ?? .null, + forKey: CaseInsensitiveIdentifier(rawValue: column)) + } } /// The value associated with the given column. + /// + /// The setter accepts any ``DatabaseValueConvertible`` type, but the + /// getter always returns a ``DatabaseValue``. public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { get { self[column.name] } set { self[column.name] = newValue } @@ -378,66 +389,25 @@ public struct PersistenceContainer { } /// Columns stored in the container, ordered like values. - var columns: [String] { Array(storage.keys) } + var columns: [String] { storage.keys.map(\.rawValue) } /// Values stored in the container, ordered like columns. - var values: [(any DatabaseValueConvertible)?] { Array(storage.values) } + var values: [DatabaseValue] { storage.values } - /// Accesses the value associated with the given column, in a - /// case-insensitive fashion. - subscript(caseInsensitive column: String) -> (any DatabaseValueConvertible)? { - get { - if let value = storage[column] { - return value - } - let lowercaseColumn = column.lowercased() - for (key, value) in storage where key.lowercased() == lowercaseColumn { - return value - } - return nil - } - set { - if storage[column] != nil { - storage[column] = newValue - return - } - let lowercaseColumn = column.lowercased() - for key in storage.keys where key.lowercased() == lowercaseColumn { - storage[key] = newValue - return - } - - storage[column] = newValue - } - } - - // Returns nil if column is not defined - func value(forCaseInsensitiveColumn column: String) -> DatabaseValue? { - let lowercaseColumn = column.lowercased() - for (key, value) in storage where key.lowercased() == lowercaseColumn { - return value?.databaseValue ?? .null - } - return nil - } - - var isEmpty: Bool { storage.isEmpty } - - /// An iterator over the (column, value) pairs - func makeIterator() -> IndexingIterator> { - storage.makeIterator() + /// Returns ``DatabaseValue/null`` if column is not defined + func databaseValue(at column: String) -> DatabaseValue { + storage[CaseInsensitiveIdentifier(rawValue: column)] ?? .null } @usableFromInline func changesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { - var newValueIterator = makeIterator() + var newValueIterator = storage.makeIterator() return AnyIterator { // Loop until we find a change, or exhaust columns: - while let (column, newValue) = newValueIterator.next() { - let oldValue = container[caseInsensitive: column] - let oldDbValue = oldValue?.databaseValue ?? .null - let newDbValue = newValue?.databaseValue ?? .null + while let (column, newDbValue) = newValueIterator.next() { + let oldDbValue = container.storage[column] ?? .null if newDbValue != oldDbValue { - return (column, oldDbValue) + return (column.rawValue, oldDbValue) } } return nil @@ -445,13 +415,26 @@ public struct PersistenceContainer { } } +extension PersistenceContainer: RandomAccessCollection { + public typealias Index = Int + + public var startIndex: Int { storage.startIndex } + public var endIndex: Int { storage.endIndex } + + /// Returns the (column, value) pair at given index. + public subscript(position: Int) -> (String, DatabaseValue) { + let element = storage[position] + return (element.key.rawValue, element.value) + } +} + extension Row { convenience init(_ record: Record) throws { try self.init(PersistenceContainer(record)) } convenience init(_ container: PersistenceContainer) { - self.init(Dictionary(container.storage)) + self.init(impl: ArrayRowImpl(columns: container.lazy.map { ($0, $1) })) } } diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift index 48b9025c8..b63c1ab3a 100644 --- a/GRDB/Record/MutablePersistableRecord+DAO.swift +++ b/GRDB/Record/MutablePersistableRecord+DAO.swift @@ -142,7 +142,7 @@ final class DAO { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + persistenceContainer.databaseValue(at: $0) } if primaryKeyValues.allSatisfy({ $0.isNull }) { return nil @@ -173,7 +173,7 @@ final class DAO { } let updatedValues = updatedColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + persistenceContainer.databaseValue(at: $0) } let query = UpdateQuery( @@ -193,7 +193,7 @@ final class DAO { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + persistenceContainer.databaseValue(at: $0) } if primaryKeyValues.allSatisfy({ $0.isNull }) { return nil @@ -212,7 +212,7 @@ final class DAO { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + persistenceContainer.databaseValue(at: $0) } if primaryKeyValues.allSatisfy({ $0.isNull }) { return nil @@ -229,7 +229,7 @@ final class DAO { /// Throws a RecordError.recordNotFound error func recordNotFound() throws -> Never { let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map { - ($0, persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null) + ($0, persistenceContainer.databaseValue(at: $0)) }) throw RecordError.recordNotFound( databaseTableName: databaseTableName, diff --git a/GRDB/Record/MutablePersistableRecord+Insert.swift b/GRDB/Record/MutablePersistableRecord+Insert.swift index e089cb23c..f63d9f938 100644 --- a/GRDB/Record/MutablePersistableRecord+Insert.swift +++ b/GRDB/Record/MutablePersistableRecord+Insert.swift @@ -525,7 +525,7 @@ extension MutablePersistableRecord { // to false in its `aroundInsert` callback. var persistenceContainer = dao.persistenceContainer if let rowIDColumn { - persistenceContainer[caseInsensitive: rowIDColumn] = rowid + persistenceContainer[rowIDColumn] = rowid } let inserted = InsertionSuccess( diff --git a/GRDB/Record/MutablePersistableRecord+Save.swift b/GRDB/Record/MutablePersistableRecord+Save.swift index 6a238ac2f..a57988433 100644 --- a/GRDB/Record/MutablePersistableRecord+Save.swift +++ b/GRDB/Record/MutablePersistableRecord+Save.swift @@ -409,7 +409,7 @@ extension MutablePersistableRecord { let primaryKeyInfo = try db.primaryKey(databaseTableName) let container = try PersistenceContainer(db, self) let primaryKey = Dictionary(uniqueKeysWithValues: primaryKeyInfo.columns.map { - ($0, container[caseInsensitive: $0]?.databaseValue ?? .null) + ($0, container.databaseValue(at: $0)) }) if primaryKey.allSatisfy({ $0.value.isNull }) { return nil diff --git a/GRDB/Record/MutablePersistableRecord+Upsert.swift b/GRDB/Record/MutablePersistableRecord+Upsert.swift index 4374c1960..567feee50 100644 --- a/GRDB/Record/MutablePersistableRecord+Upsert.swift +++ b/GRDB/Record/MutablePersistableRecord+Upsert.swift @@ -452,7 +452,7 @@ extension MutablePersistableRecord { var persistenceContainer = dao.persistenceContainer let rowIDColumn = dao.primaryKey.rowIDColumn if let rowIDColumn { - persistenceContainer[caseInsensitive: rowIDColumn] = rowid + persistenceContainer[rowIDColumn] = rowid } let inserted = InsertionSuccess( diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index cb7394fe1..67fbf6c0d 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -201,8 +201,7 @@ open class Record { var newValueIterator = try PersistenceContainer(self).makeIterator() return AnyIterator { // Loop until we find a change, or exhaust columns: - while let (column, newValue) = newValueIterator.next() { - let newDbValue = newValue?.databaseValue ?? .null + while let (column, newDbValue) = newValueIterator.next() { guard let oldRow, let oldDbValue: DatabaseValue = oldRow[column] else { return (column, nil) } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index db6edc45e..4e9cd4485 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -763,7 +763,7 @@ extension TableRecord where Self: EncodableRecord { let container = try PersistenceContainer(db, self) let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map { - ($0, container[caseInsensitive: $0]?.databaseValue ?? .null) + ($0, container.databaseValue(at: $0)) }) return RecordError.recordNotFound( databaseTableName: databaseTableName, diff --git a/TODO.md b/TODO.md index 632aa72fe..9bb275b6d 100644 --- a/TODO.md +++ b/TODO.md @@ -142,7 +142,7 @@ - [X] GRDB7: Sendable: ValueObservation (93f6f982) - [?] GRDB7: Not Sendable: SharedValueObservation - [ ] GRDB7: doc (c0838cf9) -- [ ] GRDB7/BREAKING: PersistenceContainer is Sendable (50eefa8c) +- [X] GRDB7/BREAKING: PersistenceContainer is Sendable (50eefa8c) - [ ] GRDB7: TableRecord.databaseSelection must be declared as a computed property (24d232aa) - [ ] GRDB7: Sendable: Association (b06aaee4) - [ ] GRDB7/Tests: Sendable: ValueObservationRecorder (2947b3d7)