From 2212a179504c0be529b400553023b7395702bb6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 8 Dec 2025 15:13:28 +0100 Subject: [PATCH 1/8] Failing test for #1838 --- Tests/GRDBTests/Issue1838Tests.swift | 142 +++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 Tests/GRDBTests/Issue1838Tests.swift diff --git a/Tests/GRDBTests/Issue1838Tests.swift b/Tests/GRDBTests/Issue1838Tests.swift new file mode 100644 index 000000000..4c29cae60 --- /dev/null +++ b/Tests/GRDBTests/Issue1838Tests.swift @@ -0,0 +1,142 @@ +import Foundation +import GRDB +import os +import Testing + +private struct Person: Codable, TableRecord, FetchableRecord, PersistableRecord { + static let databaseTableName = "person" + + var id: Int + var name: String + + enum Column: String, CodingKey, ColumnExpression { + case id + case name + } + typealias CodingKeys = Column +} + +// MARK: - + +private struct PersonText: Codable, TableRecord, FetchableRecord, PersistableRecord { + static let databaseTableName = "person_text" + + let id: Int + let content: String + + enum Column: String, CodingKey, ColumnExpression { + case id + case content + } + typealias CodingKeys = Column +} + +// MARK: - + +private final class SQLiteStore: Sendable { + private let queue: DatabaseQueue + + init(queue: DatabaseQueue) { + self.queue = queue + } + + convenience init() throws { + var configuration = Configuration() + configuration.prepareDatabase { db in + db.trace { print("SQL", $0) } + } + let queue = try DatabaseQueue(configuration: configuration) + self.init(queue: queue) + + var migrator = DatabaseMigrator() + migrator.registerMigration("Person/v1") { db in + try db.create(table: Person.databaseTableName) { t in + t.column(Person.Column.id.name, .integer).notNull().primaryKey() + t.column(Person.Column.name.name, .text).notNull() + } + try db.create(virtualTable: PersonText.databaseTableName, using: FTS5()) { t in + t.tokenizer = .porter(wrapping: .unicode61()) + t.column(PersonText.Column.id.name).notIndexed() + t.column(PersonText.Column.content.name) + } + } + try migrator.migrate(queue) + } + + // MARK: - + + class Reader { + let database: Database + + init(database: Database) { + self.database = database + } + func fetchPersons() throws -> [Person] { + return try Person + .fetchAll(database) + } + func personExists(id: Int) throws -> Bool { + return try Person + .filter(Person.Column.id == id) + .fetchCount(database) > 0 + } + } + + // MARK: - + + final class Writer: Reader { + func insert(_ person: Person) throws { + try person + .insert(database) + try PersonText(id: person.id, content: person.name) + .insert(database) + } + func ensure(_ id: Int, inserting person: @autoclosure () -> Person) throws { + if try !personExists(id: id) { + try insert(person()) + } + } + } + + // MARK: - + + func read(_ body: @Sendable @escaping (Reader) throws -> T) async throws -> T where T: Sendable { + return try await queue.read { + try body(Reader(database: $0)) + } + } + + func write(_ body: @Sendable @escaping (Writer) throws -> T) async throws -> T where T: Sendable { + return try await queue.write { + try body(Writer(database: $0)) + } + } +} + +// MARK: - + +struct Issue1838Tests { + @Test func cancelWrite() async throws { + let store = try SQLiteStore() + + let task = Task { + do { + try await store.write { + for i in 1... { + try $0.ensure(i, inserting: Person(id: i, name: "person \(i)")) + Thread.sleep(forTimeInterval: 0.1) + try Task.checkCancellation() + } + } + } catch { + print("caught \(error)") + throw error + } + } + + try await Task.sleep(for: .seconds(1)) + + task.cancel() + let _ = await task.result + } +} From 5dba64d5457edc5bf8f74e79883e686d6badd2e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Dec 2025 20:34:02 +0100 Subject: [PATCH 2/8] Retry a rollback in case of SQLITE_INTERRUPT error This should fix a race condition about cancellation that happens during a rollback --- GRDB/Core/Database.swift | 18 ++++++++++- Tests/GRDBTests/DatabaseWriterTests.swift | 37 +++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 2614602dd..513903a16 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1764,7 +1764,23 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // which rollback errors should be ignored, and which rollback errors // should be exposed to the library user. if isInsideTransaction { - try execute(sql: "ROLLBACK TRANSACTION") + do { + try execute(sql: "ROLLBACK TRANSACTION") + } catch is CancellationError, DatabaseError.SQLITE_INTERRUPT { + // Maybe we were unlucky, and user has interrupted the database + // during the rollback. CancellationError is thrown when + // the rollback is interrupted during execution. SQLITE_INTERRUPT + // is thrown when the rollback is interrupted during compilation. + // + // Let's rollback again. This is a correct behavior, because: + // 1. Since the interrupt was concurrent, we can reorder it + // and pretend it occurred before or after the rollback. + // 2. If we do not rollback, we might leave a database + // transaction open, with no other opportunity to close it. + // This might trigger a fatal error in + // `SerializedDatabase.preconditionNoUnsafeTransactionLeft`. + try execute(sql: "ROLLBACK TRANSACTION") + } } assert(!isInsideTransaction) } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 9a8cf4062..2e527cdab 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -896,4 +896,41 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabasePool()) try await test(AnyDatabaseWriter(makeDatabaseQueue())) } + + // Regression test for https://github.com/groue/GRDB.swift/pull/1838 + func test_cancellation_does_not_prevent_rollback() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + // Numbers that have the test fail more or less reliably + // (on my machine) unless the #1838 patch is applied. + // When the test fails, we have a fatal error: A transaction has been left opened at the end of a database access. + let repeatCount = 400 + let taskCount = 50 + for _ in 0.. Date: Mon, 8 Dec 2025 21:22:43 +0100 Subject: [PATCH 3/8] Protect PRAGMA query_only = 0 against SQLITE_INTERRUPT This should fix a race condition about cancellation that happens during a read-only access. --- GRDB/Core/Database.swift | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 513903a16..b50ee05a2 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -863,7 +863,25 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib readOnlyDepth -= 1 assert(readOnlyDepth >= 0, "unbalanced endReadOnly()") if readOnlyDepth == 0 { - try internalCachedStatement(sql: "PRAGMA query_only = 0").execute() + do { + try internalCachedStatement(sql: "PRAGMA query_only = 0").execute() + } catch is CancellationError, DatabaseError.SQLITE_INTERRUPT { + // Note: no test could take this path. Maybe `PRAGMA query_only` is + // not sensitive to SQLite interrupt. But if it is, this code is necessary. + // + // Maybe we were unlucky, and user has interrupted the database + // during the PRAGMA. CancellationError is thrown when + // the PRAGMA is interrupted during execution. SQLITE_INTERRUPT + // is thrown when the PRAGMA is interrupted during compilation. + // + // Let's run it again. This is a correct behavior, because: + // 1. Since the interrupt was concurrent, we can reorder it + // and pretend it occurred before or after the PRAGMA. + // 2. If we do not PRAGMA, we might leave a database + // transaction in the read-only state, with no other + // opportunity to quit it. + try internalCachedStatement(sql: "PRAGMA query_only = 0").execute() + } } } From 64a024097d0a5a754d3a2941b0b0411f1016a9d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 8 Dec 2025 21:34:17 +0100 Subject: [PATCH 4/8] Fix failing test for #1838 by reseting all prepared statements before retrying --- GRDB/Core/Database.swift | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index b50ee05a2..ae012951b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -880,6 +880,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // 2. If we do not PRAGMA, we might leave a database // transaction in the read-only state, with no other // opportunity to quit it. + // + // As a workaround for an FTS5 bug (https://sqlite.org/forum/forumpost/137c7662b3), + // we must make sure we leave the interrupted state first: + resetAllPreparedStatements() try internalCachedStatement(sql: "PRAGMA query_only = 0").execute() } } @@ -1797,6 +1801,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // transaction open, with no other opportunity to close it. // This might trigger a fatal error in // `SerializedDatabase.preconditionNoUnsafeTransactionLeft`. + // + // As a workaround for an FTS5 bug (https://sqlite.org/forum/forumpost/137c7662b3), + // we must make sure we leave the interrupted state first: + resetAllPreparedStatements() try execute(sql: "ROLLBACK TRANSACTION") } } @@ -1813,6 +1821,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib assert(sqlite3_get_autocommit(sqliteConnection) != 0) } + /// Resets all prepared statements. + /// + /// This method helps clearing the interrupted state, as a workaround + /// for https://sqlite.org/forum/forumpost/137c7662b3, discovered + /// in https://github.com/groue/GRDB.swift/issues/1838. + func resetAllPreparedStatements() { + var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil) + while stmt != nil { + sqlite3_reset(stmt) + stmt = sqlite3_next_stmt(sqliteConnection, stmt) + } + } + // MARK: - Memory Management /// Frees as much memory as possible. From 361599aacde2f4c8b283e2078943219822c2fa16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Dec 2025 21:38:15 +0100 Subject: [PATCH 5/8] Task cancellation should turn all SQLITE_INTERRUPT errors into CancellationError, including errors thrown by statement compilation I did not know statement compilation could fail when database is interrupted until #1838. A ROLLBACK statement would not even compile due to the FTS5 statement leak reported in https://sqlite.org/forum/forumpost/137c7662b389fa18 --- GRDB/Core/Database+Statements.swift | 21 +++++++++++++++++++++ GRDB/Core/Statement.swift | 5 +---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 34a362b9d..02229266c 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -513,6 +513,27 @@ extension Database { publicStatementArguments: configuration.publicStatementArguments) } + /// Always throws an error + func statementCompilationDidFail( + at statementStart: UnsafePointer, + withResultCode resultCode: CInt + ) throws -> Never { + switch ResultCode(rawValue: resultCode) { + case .SQLITE_INTERRUPT, .SQLITE_ABORT: + // The only error that a user sees when a Task is cancelled + // is CancellationError. + try suspensionMutex.load().checkCancellation() + default: + break + } + + // Throw compilation failure + throw DatabaseError( + resultCode: resultCode, + message: lastErrorMessage, + sql: String(cString: statementStart)) + } + private func checkForAutocommitTransition() { if sqlite3_get_autocommit(sqliteConnection) == 0 { if autocommitState == .on { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 6bf3a89ad..e47907d97 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -150,10 +150,7 @@ public final class Statement { &sqliteStatement, statementEnd) guard code == SQLITE_OK else { - throw DatabaseError( - resultCode: code, - message: database.lastErrorMessage, - sql: String(cString: statementStart)) + try database.statementCompilationDidFail(at: statementStart, withResultCode: code) } guard let sqliteStatement else { From 3ee256e7e871542ad547d98f6c7675e14d70e723 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 9 Dec 2025 21:39:20 +0100 Subject: [PATCH 6/8] Common API for statements that must ignore interruption errors --- GRDB/Core/Database.swift | 81 ++++++++++++++++++++-------------------- 1 file changed, 41 insertions(+), 40 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ae012951b..d280aa7f1 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -863,27 +863,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib readOnlyDepth -= 1 assert(readOnlyDepth >= 0, "unbalanced endReadOnly()") if readOnlyDepth == 0 { - do { - try internalCachedStatement(sql: "PRAGMA query_only = 0").execute() - } catch is CancellationError, DatabaseError.SQLITE_INTERRUPT { - // Note: no test could take this path. Maybe `PRAGMA query_only` is - // not sensitive to SQLite interrupt. But if it is, this code is necessary. - // - // Maybe we were unlucky, and user has interrupted the database - // during the PRAGMA. CancellationError is thrown when - // the PRAGMA is interrupted during execution. SQLITE_INTERRUPT - // is thrown when the PRAGMA is interrupted during compilation. - // - // Let's run it again. This is a correct behavior, because: - // 1. Since the interrupt was concurrent, we can reorder it - // and pretend it occurred before or after the PRAGMA. - // 2. If we do not PRAGMA, we might leave a database - // transaction in the read-only state, with no other - // opportunity to quit it. - // - // As a workaround for an FTS5 bug (https://sqlite.org/forum/forumpost/137c7662b3), - // we must make sure we leave the interrupted state first: - resetAllPreparedStatements() + // We MUST ignore interruptions when we leave the read-only mode, + // otherwise user could not write with this database + // connection again. + // + // It's OK to ignore interruption, since interruption is + // concurrent and we can pretend it occurred before or after + // the PRAGMA. + try ignoringInterruption { try internalCachedStatement(sql: "PRAGMA query_only = 0").execute() } } @@ -1322,6 +1309,31 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib return try value() } + /// Returns the result of `value`. If `value` throws an interruption + /// error, it is retried a second time. + func ignoringInterruption(_ value: () throws -> T) rethrows -> T { + do { + return try value() + } + catch is CancellationError, + DatabaseError.SQLITE_INTERRUPT, + DatabaseError.SQLITE_ABORT + { + // Maybe we were unlucky, and user has interrupted the database + // during `value` execution. + // + // Another possible cause for this error is the FTS5 bug + // described at , + // which leaves the database in a sticky interrupted state. + // To workaround this bug, we must leave the interrupted state + // before retrying: + resetAllPreparedStatements() + + // Retry + return try value() + } + } + /// Support for `checkForSuspensionViolation(from:)` private func journalMode() throws -> String { if let journalMode = journalModeCache { @@ -1786,25 +1798,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // which rollback errors should be ignored, and which rollback errors // should be exposed to the library user. if isInsideTransaction { - do { - try execute(sql: "ROLLBACK TRANSACTION") - } catch is CancellationError, DatabaseError.SQLITE_INTERRUPT { - // Maybe we were unlucky, and user has interrupted the database - // during the rollback. CancellationError is thrown when - // the rollback is interrupted during execution. SQLITE_INTERRUPT - // is thrown when the rollback is interrupted during compilation. - // - // Let's rollback again. This is a correct behavior, because: - // 1. Since the interrupt was concurrent, we can reorder it - // and pretend it occurred before or after the rollback. - // 2. If we do not rollback, we might leave a database - // transaction open, with no other opportunity to close it. - // This might trigger a fatal error in - // `SerializedDatabase.preconditionNoUnsafeTransactionLeft`. - // - // As a workaround for an FTS5 bug (https://sqlite.org/forum/forumpost/137c7662b3), - // we must make sure we leave the interrupted state first: - resetAllPreparedStatements() + // We MUST ignore interruptions during the rollback, otherwise + // we could leave a transaction open, and trigger a fatal error in + // `SerializedDatabase.preconditionNoUnsafeTransactionLeft`. + // + // It's OK to ignore interruption, since interruption is + // concurrent and we can pretend it occurred before or after + // the rollback. + try ignoringInterruption { try execute(sql: "ROLLBACK TRANSACTION") } } From e281149a2d8d81e39cb3497953b3301608d774af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 10 Dec 2025 13:28:04 +0100 Subject: [PATCH 7/8] Simplify Issue1838Tests ... and add it to test targets --- GRDB.xcodeproj/project.pbxproj | 4 + GRDBCustom.xcodeproj/project.pbxproj | 4 + Tests/GRDBTests/Issue1838Tests.swift | 153 ++++----------------------- 3 files changed, 27 insertions(+), 134 deletions(-) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index c0d3f02a7..f9888c454 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -292,6 +292,7 @@ 56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; }; 56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */; }; 56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; }; + 56C7979B2EE99BD000AA265D /* Issue1838Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C7979A2EE99BD000AA265D /* Issue1838Tests.swift */; }; 56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; }; 56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; }; 56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; }; @@ -802,6 +803,7 @@ 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = ""; }; 56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = ""; }; 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = ""; }; + 56C7979A2EE99BD000AA265D /* Issue1838Tests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Issue1838Tests.swift; sourceTree = ""; }; 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = ""; }; 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; @@ -1448,6 +1450,7 @@ 56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */, 5698ACCA1DA62A2D0056AF8C /* FTS5TokenizerTests.swift */, 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */, + 56C7979A2EE99BD000AA265D /* Issue1838Tests.swift */, ); name = FTS; sourceTree = ""; @@ -2130,6 +2133,7 @@ 56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */, 562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */, 56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */, + 56C7979B2EE99BD000AA265D /* Issue1838Tests.swift in Sources */, 568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 5ae342ef8..f7c29af3a 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -287,6 +287,7 @@ 56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538C22ACEECD0029D27D /* ValueReducer.swift */; }; 56C0539B22ACEECD0029D27D /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538E22ACEECD0029D27D /* Map.swift */; }; 56C0539D22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; }; + 56C7979D2EE99BE900AA265D /* Issue1838Tests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C7979C2EE99BE900AA265D /* Issue1838Tests.swift */; }; 56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; 56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; }; @@ -814,6 +815,7 @@ 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = ""; }; 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = ""; }; 56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLiteCustom/GRDBDeploymentTarget.xcconfig; sourceTree = ""; }; + 56C7979C2EE99BE900AA265D /* Issue1838Tests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Issue1838Tests.swift; sourceTree = ""; }; 56C9EB9A2495324700FE5D55 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = grdb_config.h; path = SQLiteCustom/grdb_config.h; sourceTree = ""; }; 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = ""; }; 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; @@ -1441,6 +1443,7 @@ 5698AC3E1DA2BEBB0056AF8C /* FTS */ = { isa = PBXGroup; children = ( + 56C7979C2EE99BE900AA265D /* Issue1838Tests.swift */, 5698AC3F1DA2BED90056AF8C /* FTS3PatternTests.swift */, 5698AC481DA2D48A0056AF8C /* FTS3RecordTests.swift */, 5698AC881DA389380056AF8C /* FTS3TableBuilderTests.swift */, @@ -2374,6 +2377,7 @@ 562205FE1E420EA2005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 56DF0017228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */, + 56C7979D2EE99BE900AA265D /* Issue1838Tests.swift in Sources */, F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */, F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */, 5676FBAA22F5CEB9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, diff --git a/Tests/GRDBTests/Issue1838Tests.swift b/Tests/GRDBTests/Issue1838Tests.swift index 4c29cae60..0d51010ae 100644 --- a/Tests/GRDBTests/Issue1838Tests.swift +++ b/Tests/GRDBTests/Issue1838Tests.swift @@ -1,142 +1,27 @@ -import Foundation import GRDB -import os -import Testing +import XCTest -private struct Person: Codable, TableRecord, FetchableRecord, PersistableRecord { - static let databaseTableName = "person" - - var id: Int - var name: String - - enum Column: String, CodingKey, ColumnExpression { - case id - case name - } - typealias CodingKeys = Column -} - -// MARK: - - -private struct PersonText: Codable, TableRecord, FetchableRecord, PersistableRecord { - static let databaseTableName = "person_text" - - let id: Int - let content: String - - enum Column: String, CodingKey, ColumnExpression { - case id - case content - } - typealias CodingKeys = Column -} - -// MARK: - - -private final class SQLiteStore: Sendable { - private let queue: DatabaseQueue - - init(queue: DatabaseQueue) { - self.queue = queue - } - - convenience init() throws { - var configuration = Configuration() - configuration.prepareDatabase { db in - db.trace { print("SQL", $0) } - } - let queue = try DatabaseQueue(configuration: configuration) - self.init(queue: queue) +class Issue1838Tests: GRDBTestCase { + /// Regression test for . + /// + /// This test passes since + /// which workarounds the SQLite bug described at + /// . + func test_interrupted_rollback() throws { + let dbQueue = try makeDatabaseQueue() - var migrator = DatabaseMigrator() - migrator.registerMigration("Person/v1") { db in - try db.create(table: Person.databaseTableName) { t in - t.column(Person.Column.id.name, .integer).notNull().primaryKey() - t.column(Person.Column.name.name, .text).notNull() - } - try db.create(virtualTable: PersonText.databaseTableName, using: FTS5()) { t in - t.tokenizer = .porter(wrapping: .unicode61()) - t.column(PersonText.Column.id.name).notIndexed() - t.column(PersonText.Column.content.name) - } - } - try migrator.migrate(queue) - } - - // MARK: - - - class Reader { - let database: Database - - init(database: Database) { - self.database = database - } - func fetchPersons() throws -> [Person] { - return try Person - .fetchAll(database) - } - func personExists(id: Int) throws -> Bool { - return try Person - .filter(Person.Column.id == id) - .fetchCount(database) > 0 - } - } - - // MARK: - - - final class Writer: Reader { - func insert(_ person: Person) throws { - try person - .insert(database) - try PersonText(id: person.id, content: person.name) - .insert(database) - } - func ensure(_ id: Int, inserting person: @autoclosure () -> Person) throws { - if try !personExists(id: id) { - try insert(person()) - } - } - } - - // MARK: - - - func read(_ body: @Sendable @escaping (Reader) throws -> T) async throws -> T where T: Sendable { - return try await queue.read { - try body(Reader(database: $0)) - } - } - - func write(_ body: @Sendable @escaping (Writer) throws -> T) async throws -> T where T: Sendable { - return try await queue.write { - try body(Writer(database: $0)) - } - } -} - -// MARK: - - -struct Issue1838Tests { - @Test func cancelWrite() async throws { - let store = try SQLiteStore() - - let task = Task { - do { - try await store.write { - for i in 1... { - try $0.ensure(i, inserting: Person(id: i, name: "person \(i)")) - Thread.sleep(forTimeInterval: 0.1) - try Task.checkCancellation() - } - } - } catch { - print("caught \(error)") - throw error + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE VIRTUAL TABLE documents USING FTS5(content)") + try db.inTransaction { + try db.execute(sql: "INSERT INTO documents(content) VALUES ('Document')") + dbQueue.interrupt() + return .rollback } } - try await Task.sleep(for: .seconds(1)) - - task.cancel() - let _ = await task.result + let documentCount = try dbQueue.read { db in + try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents")! + } + XCTAssertEqual(documentCount, 0) } } From ac2f2e8643ed2752fa73fcdef28a361b5d32afea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Wed, 10 Dec 2025 13:38:25 +0100 Subject: [PATCH 8/8] Test that we recover from the FTS5 bug --- Tests/GRDBTests/Issue1838Tests.swift | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Tests/GRDBTests/Issue1838Tests.swift b/Tests/GRDBTests/Issue1838Tests.swift index 0d51010ae..e20fc9c21 100644 --- a/Tests/GRDBTests/Issue1838Tests.swift +++ b/Tests/GRDBTests/Issue1838Tests.swift @@ -24,4 +24,30 @@ class Issue1838Tests: GRDBTestCase { } XCTAssertEqual(documentCount, 0) } + + /// Tests about how we handle the FTS5 bug + func test_interrupted_commit() throws { + let dbQueue = try makeDatabaseQueue() + + try dbQueue.write { db in + try db.execute(sql: "CREATE VIRTUAL TABLE documents USING FTS5(content)") + } + + do { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO documents(content) VALUES ('Document')") + dbQueue.interrupt() + } + // Do not assert that the above code throws, because the + // FTS5 bug might be fixed in the tested SQLite version. + } catch DatabaseError.SQLITE_INTERRUPT { + // Fine: That's the FTS5 bug. + } + + // Make sure the interrupted state created by the FTS5 bug is no longer active. + let documentCount = try dbQueue.read { db in + try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents")! + } + XCTAssertEqual(documentCount, 0) + } }