From d4713c1fa83271da8a88a2239f81ac1293569376 Mon Sep 17 00:00:00 2001
From: Chris Kolbu
Date: Tue, 18 Aug 2026 15:58:30 +1000
Subject: [PATCH 01/27] Failing tests for INTEGER PRIMARY KEY in WITHOUT ROWID
tables
---
.../GRDBTests/Core/PrimaryKeyInfoTests.swift | 30 ++++++++
.../MutablePersistableRecordTests.swift | 75 +++++++++++++++++++
.../PersistableRecordTests.swift | 75 +++++++++++++++++++
3 files changed, 180 insertions(+)
diff --git a/Tests/GRDBTests/Core/PrimaryKeyInfoTests.swift b/Tests/GRDBTests/Core/PrimaryKeyInfoTests.swift
index 7cae11b84..690afa401 100644
--- a/Tests/GRDBTests/Core/PrimaryKeyInfoTests.swift
+++ b/Tests/GRDBTests/Core/PrimaryKeyInfoTests.swift
@@ -105,6 +105,36 @@ class PrimaryKeyInfoTests: GRDBTestCase {
}
}
+ func testIntegerPrimaryKeyWithoutRowID() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.inDatabase { db in
+ try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT) WITHOUT ROWID")
+ let primaryKey = try db.primaryKey("items")
+ XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id"])
+ XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"])
+ XCTAssertEqual(primaryKey.columns, ["id"])
+ // An INTEGER primary key is an alias for the rowid in rowid
+ // tables only: https://www.sqlite.org/lang_createtable.html
+ XCTAssertNil(primaryKey.rowIDColumn)
+ XCTAssertFalse(primaryKey.isRowID)
+ XCTAssertFalse(primaryKey.tableHasRowID)
+ }
+ }
+
+ func testIntegerPrimaryKeyWithoutRowID2() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.inDatabase { db in
+ try db.execute(sql: "CREATE TABLE items (id INTEGER, name TEXT, PRIMARY KEY (id)) WITHOUT ROWID")
+ let primaryKey = try db.primaryKey("items")
+ XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id"])
+ XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"])
+ XCTAssertEqual(primaryKey.columns, ["id"])
+ XCTAssertNil(primaryKey.rowIDColumn)
+ XCTAssertFalse(primaryKey.isRowID)
+ XCTAssertFalse(primaryKey.tableHasRowID)
+ }
+ }
+
func testNonRowIDPrimaryKeyWithoutRowID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
diff --git a/Tests/GRDBTests/Record/PersistableRecord/MutablePersistableRecordTests.swift b/Tests/GRDBTests/Record/PersistableRecord/MutablePersistableRecordTests.swift
index bd08b1524..d6ca5fa88 100644
--- a/Tests/GRDBTests/Record/PersistableRecord/MutablePersistableRecordTests.swift
+++ b/Tests/GRDBTests/Record/PersistableRecord/MutablePersistableRecordTests.swift
@@ -2388,6 +2388,81 @@ extension MutablePersistableRecordTests {
}
}
+ func test_upsert_INTEGER_primary_key_WITHOUT_ROWID() throws {
+#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
+ guard Database.sqliteLibVersionNumber >= 3035000 else {
+ throw XCTSkip("UPSERT is not available")
+ }
+#else
+ guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
+ throw XCTSkip("UPSERT is not available")
+ }
+#endif
+
+ struct MyRecord: Codable, FetchableRecord, MutablePersistableRecord {
+ var id: Int64
+ var name: String
+ }
+
+ try makeDatabaseQueue().write { db in
+ try db.execute(sql: """
+ CREATE TABLE myRecord(
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL
+ ) WITHOUT ROWID;
+ """)
+
+ var record = MyRecord(id: 1, name: "foo")
+ try record.upsert(db)
+
+ XCTAssertEqual(lastSQLQuery, """
+ INSERT INTO "myRecord" ("id", "name") \
+ VALUES (1,'foo') \
+ ON CONFLICT DO UPDATE SET "name" = "excluded"."name"
+ """)
+ }
+ }
+
+ func test_upsertAndFetch_INTEGER_primary_key_WITHOUT_ROWID() throws {
+#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
+ guard Database.sqliteLibVersionNumber >= 3035000 else {
+ throw XCTSkip("UPSERT is not available")
+ }
+#else
+ guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
+ throw XCTSkip("UPSERT is not available")
+ }
+#endif
+
+ struct MyRecord: Codable, FetchableRecord, MutablePersistableRecord {
+ var id: Int64
+ var name: String
+ }
+
+ try makeDatabaseQueue().write { db in
+ try db.execute(sql: """
+ CREATE TABLE myRecord(
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL
+ ) WITHOUT ROWID;
+ """)
+
+ var record = MyRecord(id: 1, name: "foo")
+ let upserted = try record.upsertAndFetch(db)
+
+ // No rowid in the RETURNING clause: the table has none
+ XCTAssertEqual(lastSQLQuery, """
+ INSERT INTO "myRecord" ("id", "name") \
+ VALUES (1,'foo') \
+ ON CONFLICT DO UPDATE SET "name" = "excluded"."name" \
+ RETURNING *
+ """)
+
+ XCTAssertEqual(upserted.id, 1)
+ XCTAssertEqual(upserted.name, "foo")
+ }
+ }
+
func test_upsertAndFetch_do_update_set_where_with_default_strategy() throws {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
guard Database.sqliteLibVersionNumber >= 3035000 else {
diff --git a/Tests/GRDBTests/Record/PersistableRecord/PersistableRecordTests.swift b/Tests/GRDBTests/Record/PersistableRecord/PersistableRecordTests.swift
index faff55346..c5b9009cb 100644
--- a/Tests/GRDBTests/Record/PersistableRecord/PersistableRecordTests.swift
+++ b/Tests/GRDBTests/Record/PersistableRecord/PersistableRecordTests.swift
@@ -2378,6 +2378,81 @@ extension PersistableRecordTests {
}
}
+ func test_upsert_INTEGER_primary_key_WITHOUT_ROWID() throws {
+#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
+ guard Database.sqliteLibVersionNumber >= 3035000 else {
+ throw XCTSkip("UPSERT is not available")
+ }
+#else
+ guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
+ throw XCTSkip("UPSERT is not available")
+ }
+#endif
+
+ struct MyRecord: Codable, FetchableRecord, PersistableRecord {
+ var id: Int64
+ var name: String
+ }
+
+ try makeDatabaseQueue().write { db in
+ try db.execute(sql: """
+ CREATE TABLE myRecord(
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL
+ ) WITHOUT ROWID;
+ """)
+
+ let record = MyRecord(id: 1, name: "foo")
+ try record.upsert(db)
+
+ XCTAssertEqual(lastSQLQuery, """
+ INSERT INTO "myRecord" ("id", "name") \
+ VALUES (1,'foo') \
+ ON CONFLICT DO UPDATE SET "name" = "excluded"."name"
+ """)
+ }
+ }
+
+ func test_upsertAndFetch_INTEGER_primary_key_WITHOUT_ROWID() throws {
+#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
+ guard Database.sqliteLibVersionNumber >= 3035000 else {
+ throw XCTSkip("UPSERT is not available")
+ }
+#else
+ guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
+ throw XCTSkip("UPSERT is not available")
+ }
+#endif
+
+ struct MyRecord: Codable, FetchableRecord, PersistableRecord {
+ var id: Int64
+ var name: String
+ }
+
+ try makeDatabaseQueue().write { db in
+ try db.execute(sql: """
+ CREATE TABLE myRecord(
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL
+ ) WITHOUT ROWID;
+ """)
+
+ let record = MyRecord(id: 1, name: "foo")
+ let upserted = try record.upsertAndFetch(db)
+
+ // No rowid in the RETURNING clause: the table has none
+ XCTAssertEqual(lastSQLQuery, """
+ INSERT INTO "myRecord" ("id", "name") \
+ VALUES (1,'foo') \
+ ON CONFLICT DO UPDATE SET "name" = "excluded"."name" \
+ RETURNING *
+ """)
+
+ XCTAssertEqual(upserted.id, 1)
+ XCTAssertEqual(upserted.name, "foo")
+ }
+ }
+
func test_upsertAndFetch_do_update_set_where_with_default_strategy() throws {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
guard Database.sqliteLibVersionNumber >= 3035000 else {
From 4373b3a49b5bc8043c7aa762f36191388ca43e7e Mon Sep 17 00:00:00 2001
From: Chris Kolbu
Date: Tue, 18 Aug 2026 16:06:50 +1000
Subject: [PATCH 02/27] Fix failing tests for INTEGER PRIMARY KEY in WITHOUT
ROWID tables
---
GRDB/Core/Database+Schema.swift | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift
index d1e17ca49..1525912c3 100644
--- a/GRDB/Core/Database+Schema.swift
+++ b/GRDB/Core/Database+Schema.swift
@@ -511,11 +511,12 @@ extension Database {
// > DESC" clause, it does not become an alias for the rowid [...]
//
// FIXME: We ignore the exception, and consider all INTEGER primary
- // keys as aliases for the rowid:
- if pkColumn.type.uppercased() == "INTEGER" {
+ // keys of rowid tables as aliases for the rowid:
+ let tableHasRowID = try fetchTableHasRowID(table)
+ if pkColumn.type.uppercased() == "INTEGER" && tableHasRowID {
return .rowID(pkColumn)
} else {
- return try .regular([pkColumn], tableHasRowID: fetchTableHasRowID(table))
+ return .regular([pkColumn], tableHasRowID: tableHasRowID)
}
default:
From 8511cfd3994e6a64bc2e9dc1b08fdd90209d1cac Mon Sep 17 00:00:00 2001
From: Chris Kolbu
Date: Tue, 18 Aug 2026 16:59:53 +1000
Subject: [PATCH 03/27] Document INTEGER PRIMARY KEY in WITHOUT ROWID tables
---
GRDB/Core/Database+Schema.swift | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)
diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift
index 1525912c3..68f459a9e 100644
--- a/GRDB/Core/Database+Schema.swift
+++ b/GRDB/Core/Database+Schema.swift
@@ -1606,7 +1606,19 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// pk.columns // ["citizenID", "countryIsoCode"]
/// pk.rowIDColumn // nil
/// pk.isRowID // false
+///
+/// // CREATE TABLE passport (
+/// // id INTEGER PRIMARY KEY,
+/// // name TEXT
+/// // ) WITHOUT ROWID
+/// let pk = try db.primaryKey("passport")
+/// pk.columns // ["id"]
+/// pk.rowIDColumn // nil
+/// pk.isRowID // false
/// ```
+///
+/// An `INTEGER PRIMARY KEY` is an alias for the rowid only in rowid
+/// tables. In a `WITHOUT ROWID` table, it is a regular primary key.
public struct PrimaryKeyInfo: Sendable {
private enum Impl {
/// The hidden rowID.
@@ -1660,7 +1672,9 @@ public struct PrimaryKeyInfo: Sendable {
}
/// When not nil, the name of the column that contains the
- /// `INTEGER PRIMARY KEY`.
+ /// `INTEGER PRIMARY KEY` of a rowid table.
+ ///
+ /// This is nil for `WITHOUT ROWID` tables, which have no rowid.
public var rowIDColumn: String? {
switch impl {
case .hiddenRowID:
From c08767b500388325da9abe264d2fb0907a8b4cf9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Rou=C3=A9?=
Date: Tue, 15 Sep 2026 14:36:27 +0200
Subject: [PATCH 04/27] Fix stale test
The test was checking for the presence of an SQLite bug. This bug is gone in macOS 27.0.
---
Tests/GRDBTests/FTS/Issue1838Tests.swift | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
diff --git a/Tests/GRDBTests/FTS/Issue1838Tests.swift b/Tests/GRDBTests/FTS/Issue1838Tests.swift
index e20fc9c21..66b628ab2 100644
--- a/Tests/GRDBTests/FTS/Issue1838Tests.swift
+++ b/Tests/GRDBTests/FTS/Issue1838Tests.swift
@@ -45,9 +45,8 @@ class Issue1838Tests: GRDBTestCase {
}
// 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")!
+ try dbQueue.read { db in
+ try db.execute(sql: "SELECT COUNT(*) FROM documents")
}
- XCTAssertEqual(documentCount, 0)
}
}
From 9f2e3b7d6b734ae2f4be51da8e31caffa99ed5c7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Rou=C3=A9?=
Date: Wed, 23 Sep 2026 14:00:14 +0200
Subject: [PATCH 05/27] Optimize statement authorizer region accumulation
This commit is inspired by #1873 from @guidedways, who detected an unexpectedly quadratic behavior in the way we build database regions from the statement authorizer
---
GRDB/Core/DatabaseRegion.swift | 42 ++++++++++-
GRDB/Core/StatementAuthorizer.swift | 4 +-
.../Private/DatabaseRegionTests.swift | 58 ++++++++++++++
.../GRDBPerformance.xcodeproj/project.pbxproj | 6 ++
...StatementPreparationPerformanceTests.swift | 75 +++++++++++++++++++
5 files changed, 180 insertions(+), 5 deletions(-)
create mode 100644 Tests/Performance/GRDBPerformance/StatementPreparationPerformanceTests.swift
diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift
index 9c9dd2da6..7db9c0c62 100644
--- a/GRDB/Core/DatabaseRegion.swift
+++ b/GRDB/Core/DatabaseRegion.swift
@@ -41,7 +41,8 @@
/// - ``isModified(byEventsOfKind:)``
/// - ``isModified(by:)``
public struct DatabaseRegion: Sendable {
- private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
+ /// Nil means that the region is the full database.
+ private var tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
self.tableRegions = tableRegions
@@ -77,19 +78,26 @@ public struct DatabaseRegion: Sendable {
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
}
- /// Full columns in a table: (some columns in a table) × (all rows)
+ /// Some columns from all rows in a table.
init(table: String, columns: Set) {
let table = CaseInsensitiveIdentifier(rawValue: table)
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
}
- /// Full rows in a table: (all columns in a table) × (some rows)
+ /// All columns from some rows in a table.
init(table: String, rowIds: Set) {
let table = CaseInsensitiveIdentifier(rawValue: table)
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
}
+ /// Some columns from some rows in a table.
+ init(table: String, columns: Set, rowIds: Set) {
+ let table = CaseInsensitiveIdentifier(rawValue: table)
+ let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
+ self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: rowIds)])
+ }
+
/// Returns the intersection of this region and the given one.
///
/// This method is not public because there is no known public use case for
@@ -162,6 +170,22 @@ public struct DatabaseRegion: Sendable {
self = union(other)
}
+ /// Inserts all columns and rows from the given table.
+ mutating func insert(table: String) {
+ guard tableRegions != nil else { return }
+ let table = CaseInsensitiveIdentifier(rawValue: table)
+ tableRegions![table, default: TableRegion()].insertAllRowsAndColumns()
+ }
+
+ /// Inserts the specified column and all rows from the given table.
+ mutating func insert(table: String, column: String) {
+ assert(!column.isEmpty)
+ guard tableRegions != nil else { return }
+ let table = CaseInsensitiveIdentifier(rawValue: table)
+ let column = CaseInsensitiveIdentifier(rawValue: column)
+ tableRegions![table, default: TableRegion(columns: [column])].insertAllRowsAndColumn(column)
+ }
+
/// Returns a region suitable for database observation
func observableRegion(_ db: Database) throws -> DatabaseRegion {
// SQLite does not expose schema changes to the
@@ -370,6 +394,18 @@ private struct TableRegion: Equatable {
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
}
+ mutating func insertAllRowsAndColumns() {
+ rowIds = nil
+ columns = nil
+ }
+
+ mutating func insertAllRowsAndColumn(_ column: CaseInsensitiveIdentifier) {
+ rowIds = nil
+ if columns != nil {
+ columns!.insert(column)
+ }
+ }
+
func contains(rowID: Int64) -> Bool {
guard let rowIds else {
return true
diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift
index a1e863f3d..384138546 100644
--- a/GRDB/Core/StatementAuthorizer.swift
+++ b/GRDB/Core/StatementAuthorizer.swift
@@ -117,10 +117,10 @@ final class StatementAuthorizer {
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
- selectedRegion.formUnion(DatabaseRegion(table: tableName))
+ selectedRegion.insert(table: tableName)
} else {
// SELECT column FROM table
- selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
+ selectedRegion.insert(table: tableName, column: columnName)
}
return SQLITE_OK
diff --git a/Tests/GRDBTests/Private/DatabaseRegionTests.swift b/Tests/GRDBTests/Private/DatabaseRegionTests.swift
index fc2cf29d4..c844126a8 100644
--- a/Tests/GRDBTests/Private/DatabaseRegionTests.swift
+++ b/Tests/GRDBTests/Private/DatabaseRegionTests.swift
@@ -142,6 +142,64 @@ class DatabaseRegionTests : GRDBTestCase {
XCTAssertEqual(unions.map(\.description), ["foo(a)[1]", "foo(a,b)[1,2]", "foo(a,b)[1,2]", "foo(b)[2]"])
}
+ func testInsertTable() {
+ let regions = [
+ DatabaseRegion.fullDatabase,
+ DatabaseRegion(),
+ DatabaseRegion(table: "foo"),
+ DatabaseRegion(table: "foo", columns: ["a", "b"]),
+ DatabaseRegion(table: "foo", columns: ["b", "c"]),
+ DatabaseRegion(table: "foo", rowIds: [1, 2]),
+ DatabaseRegion(table: "foo", columns: ["b"], rowIds: [2, 3]),
+ DatabaseRegion(table: "bar")]
+
+ var unions: [DatabaseRegion] = []
+ for var region in regions {
+ region.insert(table: "foo")
+ unions.append(region)
+ }
+
+ XCTAssertEqual(unions.map(\.description), [
+ "full database",
+ "foo(*)",
+ "foo(*)",
+ "foo(*)",
+ "foo(*)",
+ "foo(*)",
+ "foo(*)",
+ "bar(*),foo(*)",
+ ])
+ }
+
+ func testInsertTableColumn() {
+ let regions = [
+ DatabaseRegion.fullDatabase,
+ DatabaseRegion(),
+ DatabaseRegion(table: "foo"),
+ DatabaseRegion(table: "foo", columns: ["a", "b"]),
+ DatabaseRegion(table: "foo", columns: ["b", "c"]),
+ DatabaseRegion(table: "foo", rowIds: [1, 2]),
+ DatabaseRegion(table: "foo", columns: ["b"], rowIds: [2, 3]),
+ DatabaseRegion(table: "bar")]
+
+ var unions: [DatabaseRegion] = []
+ for var region in regions {
+ region.insert(table: "foo", column: "a")
+ unions.append(region)
+ }
+
+ XCTAssertEqual(unions.map(\.description), [
+ "full database",
+ "foo(a)",
+ "foo(*)",
+ "foo(a,b)",
+ "foo(a,b,c)",
+ "foo(*)",
+ "foo(a,b)",
+ "bar(*),foo(a)",
+ ])
+ }
+
func testRegionIntersection() {
let regions = [
DatabaseRegion.fullDatabase,
diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj
index 1491ce351..13364ee07 100755
--- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj
+++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj
@@ -35,6 +35,8 @@
56B6D0E62618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; };
56B6D0EA2618C00C003CC455 /* InsertRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E92618C00C003CC455 /* InsertRecordOptimizedTests.swift */; };
56B6D0EB2618C00C003CC455 /* InsertRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E92618C00C003CC455 /* InsertRecordOptimizedTests.swift */; };
+ 56B7DECA3063F1B50018462B /* StatementPreparationPerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7DEC83063F1B30018462B /* StatementPreparationPerformanceTests.swift */; };
+ 56B7DECB3063F1B50018462B /* StatementPreparationPerformanceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7DEC83063F1B30018462B /* StatementPreparationPerformanceTests.swift */; };
56D3BE711F4EB1A00034C6D2 /* FetchRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D3BE701F4EB1900034C6D2 /* FetchRecordStructTests.swift */; };
56D3BE721F4EB1A00034C6D2 /* FetchRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D3BE701F4EB1900034C6D2 /* FetchRecordStructTests.swift */; };
56D507831F6D7B2E00AE1C5B /* InsertRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */; };
@@ -100,6 +102,7 @@
56A6F4AB29BBC8E200E22662 /* ArgumentsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArgumentsTests.swift; sourceTree = ""; };
56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordOptimizedTests.swift; sourceTree = ""; };
56B6D0E92618C00C003CC455 /* InsertRecordOptimizedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordOptimizedTests.swift; sourceTree = ""; };
+ 56B7DEC83063F1B30018462B /* StatementPreparationPerformanceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementPreparationPerformanceTests.swift; sourceTree = ""; };
56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordClassTests.swift; sourceTree = ""; };
56BB862D1BA98933001F9168 /* GRDBPerformanceComparisonTests-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDBPerformanceComparisonTests-Bridging.h"; sourceTree = ""; };
56CA22211BB41565009A04C5 /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceTests.swift; sourceTree = ""; };
@@ -158,6 +161,7 @@
56BB86101BA9886D001F9168 /* Performance */ = {
isa = PBXGroup;
children = (
+ 56B7DEC83063F1B30018462B /* StatementPreparationPerformanceTests.swift */,
56BB862D1BA98933001F9168 /* GRDBPerformanceComparisonTests-Bridging.h */,
56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */,
56A6F4AB29BBC8E200E22662 /* ArgumentsTests.swift */,
@@ -338,6 +342,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ 56B7DECA3063F1B50018462B /* StatementPreparationPerformanceTests.swift in Sources */,
56D3BE711F4EB1A00034C6D2 /* FetchRecordStructTests.swift in Sources */,
565BC5E82517645D00D2B53E /* Generation.swift in Sources */,
560C98231C0E23BB00BF8471 /* InsertRecordClassTests.swift in Sources */,
@@ -365,6 +370,7 @@
565BC5E92517645D00D2B53E /* Generation.swift in Sources */,
56439B361F4CA1DC0066043F /* FetchRecordClassTests.swift in Sources */,
56439B381F4CA1DC0066043F /* FetchNamedValuesTests.swift in Sources */,
+ 56B7DECB3063F1B50018462B /* StatementPreparationPerformanceTests.swift in Sources */,
56439B391F4CA1DC0066043F /* InsertPositionalValuesTests.swift in Sources */,
56D507841F6D7B2F00AE1C5B /* InsertRecordStructTests.swift in Sources */,
5690AFD92120589A001530EA /* InsertRecordEncodableTests.swift in Sources */,
diff --git a/Tests/Performance/GRDBPerformance/StatementPreparationPerformanceTests.swift b/Tests/Performance/GRDBPerformance/StatementPreparationPerformanceTests.swift
new file mode 100644
index 000000000..7e46a5f2d
--- /dev/null
+++ b/Tests/Performance/GRDBPerformance/StatementPreparationPerformanceTests.swift
@@ -0,0 +1,75 @@
+import XCTest
+import GRDB
+
+// Inspired by
+class StatementPreparationPerformanceTests: XCTestCase {
+ let iterationCount = 10_000
+
+ func testStatementPreparationPerformance_wide() throws {
+ let dbQueue = try makeTestDatabase()
+ dbQueue.inDatabase { db in
+ measure {
+ for _ in 0.. DatabaseQueue {
+ let dbQueue = try DatabaseQueue()
+ try dbQueue.write { db in
+ try db.execute(sql: createTableSQL(
+ table: "wide",
+ columns: ["id INTEGER PRIMARY KEY"] + integerColumns(count: 119)))
+ try db.execute(sql: createTableSQL(
+ table: "author",
+ columns: ["id INTEGER PRIMARY KEY"] + integerColumns(count: 39)))
+ try db.execute(sql: createTableSQL(
+ table: "book",
+ columns: ["id INTEGER PRIMARY KEY", "authorId INTEGER"]
+ + integerColumns(count: 38)))
+ try db.execute(sql: createTableSQL(
+ table: "review",
+ columns: ["id INTEGER PRIMARY KEY", "bookId INTEGER"]
+ + integerColumns(count: 38)))
+ }
+
+ return dbQueue
+ }
+
+ private func createTableSQL(table: String, columns: [String]) -> String {
+ "CREATE TABLE \(table) (\(columns.joined(separator: ", ")))"
+ }
+
+ private func integerColumns(count: Int) -> [String] {
+ (1...count).map { "column\($0) INTEGER" }
+ }
+}
From ac1e5e66be3cbcae74ce4558aabc2130bed50b24 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sat, 26 Sep 2026 10:20:32 +0200
Subject: [PATCH 06/27] Remove assertion about SQLite snapshot ordering
Fix #1883
---
.../Observers/ValueConcurrentObserver.swift | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift
index 5c3d6f486..1f87b24cb 100644
--- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift
+++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift
@@ -452,8 +452,15 @@ extension ValueConcurrentObserver {
let isModified: Bool
if let currentWALSnapshot = try? WALSnapshot(writerDB) {
let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot)
- assert(ordering <= 0, "Unexpected snapshot ordering")
- isModified = ordering < 0
+ // We expect `ordering <= 0`, since the current
+ // snapshot is captured after the snapshot of the
+ // initial fetch. The current one is supposed to be
+ // identical (no change), or newer (database was
+ // changed since initial fetch). Yet SQLite has
+ // a quirk, as revealed by
+ // That's why we just check for a difference, and do
+ // not `assert(ordering <= 0)`.
+ isModified = ordering != 0
} else {
// Can't compare: assume the database was modified.
isModified = true
From 5d31cba4a0714c832e2bdb724d179846b7756067 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sat, 26 Sep 2026 11:55:25 +0200
Subject: [PATCH 07/27] Failing tests for database functions returning or
accepting strings with a NUL character
Inspired from #1880 by @nesevis
---
.../Core/DatabaseFunctionTests.swift | 32 +++++++++++++++++--
1 file changed, 30 insertions(+), 2 deletions(-)
diff --git a/Tests/GRDBTests/Core/DatabaseFunctionTests.swift b/Tests/GRDBTests/Core/DatabaseFunctionTests.swift
index 4c670bbd8..3fc841629 100644
--- a/Tests/GRDBTests/Core/DatabaseFunctionTests.swift
+++ b/Tests/GRDBTests/Core/DatabaseFunctionTests.swift
@@ -89,7 +89,20 @@ class DatabaseFunctionTests: GRDBTestCase {
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f()")!, "foo")
}
}
-
+
+ func testFunctionReturningStringWithNULCharacter() throws {
+ let dbQueue = try makeDatabaseQueue()
+ let fn = DatabaseFunction("f", argumentCount: 0) { dbValues in
+ // SQLite supports strings that contain a NUL character:
+ // https://sqlite.org/nulinstr.html
+ return "foo\u{0}bar"
+ }
+ try dbQueue.inDatabase { db in
+ db.add(function: fn)
+ XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f()")!, "foo\u{0}bar")
+ }
+ }
+
func testFunctionReturningData() throws {
let dbQueue = try makeDatabaseQueue()
let fn = DatabaseFunction("f", argumentCount: 0) { dbValues in
@@ -167,7 +180,22 @@ class DatabaseFunctionTests: GRDBTestCase {
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f('foo')")!, "foo")
}
}
-
+
+ func testFunctionArgumentStringWithNULCharacter() throws {
+ let dbQueue = try makeDatabaseQueue()
+ let fn = DatabaseFunction("f", argumentCount: 1) { (dbValues: [DatabaseValue]) in
+ return String.fromDatabaseValue(dbValues[0])
+ }
+ try dbQueue.inDatabase { db in
+ db.add(function: fn)
+ // A NUL character can not be written in an SQL string literal:
+ // the string is passed as a statement argument.
+ XCTAssertEqual(
+ try String.fetchOne(db, sql: "SELECT f(?)", arguments: ["foo\u{0}bar"])!,
+ "foo\u{0}bar")
+ }
+ }
+
func testFunctionArgumentBlob() throws {
let dbQueue = try makeDatabaseQueue()
let fn = DatabaseFunction("f", argumentCount: 1) { (dbValues: [DatabaseValue]) in
From dfa942e9c060eaa6cb9b5985538475276d1f3a4c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sat, 26 Sep 2026 11:55:45 +0200
Subject: [PATCH 08/27] Failing tests for decoding and encoding strings with a
NUL character
Inspired from #1880 by @nesevis
---
.../Core/DatabaseValueConversionTests.swift | 130 ++++++++++++++++++
1 file changed, 130 insertions(+)
diff --git a/Tests/GRDBTests/Core/DatabaseValueConversionTests.swift b/Tests/GRDBTests/Core/DatabaseValueConversionTests.swift
index 7ea09e374..35fc2b476 100644
--- a/Tests/GRDBTests/Core/DatabaseValueConversionTests.swift
+++ b/Tests/GRDBTests/Core/DatabaseValueConversionTests.swift
@@ -28,6 +28,8 @@ private let emojiData = emojiString.data(using: .utf8)
private let nonUTF8Data = Data([0x80])
private let invalidString = "\u{FFFD}" // decoded from nonUTF8Data
private let jpegData = try! Data(contentsOf: testBundle.url(forResource: "Betty", withExtension: "jpeg")!)
+private let nulString = "foo\u{0}bar" // https://sqlite.org/nulinstr.html
+private let nulStringData = nulString.data(using: .utf8)
class DatabaseValueConversionTests : GRDBTestCase {
@@ -253,6 +255,22 @@ class DatabaseValueConversionTests : GRDBTestCase {
return .rollback
}
+ // nulString is turned to Text
+
+ try dbQueue.inTransaction { db in
+ try db.execute(sql: "INSERT INTO `values` (textAffinity) VALUES (?)", arguments: [nulString])
+ let sql = "SELECT textAffinity FROM `values`"
+ XCTAssertEqual(try DatabaseValue.fetchOne(db, sql: sql)!.storageClass, .text)
+ try assertDecoding(db, sql, Bool.self, expectedSQLiteConversion: false, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int.self, expectedSQLiteConversion:0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int32.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int64.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Double.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, String.self, expectedSQLiteConversion: nulString, expectedDatabaseValueConversion: nulString)
+ try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: nulStringData, expectedDatabaseValueConversion: nulStringData)
+ return .rollback
+ }
+
// emojiData is turned to Blob
try dbQueue.inTransaction { db in
@@ -269,6 +287,22 @@ class DatabaseValueConversionTests : GRDBTestCase {
return .rollback
}
+ // nulStringData is turned to Blob
+
+ try dbQueue.inTransaction { db in
+ try db.execute(sql: "INSERT INTO `values` (textAffinity) VALUES (?)", arguments: [nulStringData])
+ let sql = "SELECT textAffinity FROM `values`"
+ XCTAssertEqual(try DatabaseValue.fetchOne(db, sql: sql)!.storageClass, .blob)
+ try assertDecoding(db, sql, Bool.self, expectedSQLiteConversion: false, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int.self, expectedSQLiteConversion:0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int32.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int64.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Double.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, String.self, expectedSQLiteConversion: nulString, expectedDatabaseValueConversion: nulString)
+ try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: nulStringData, expectedDatabaseValueConversion: nulStringData)
+ return .rollback
+ }
+
// nonUTF8Data is turned to Blob
try dbQueue.inTransaction { db in
@@ -512,6 +546,22 @@ class DatabaseValueConversionTests : GRDBTestCase {
return .rollback
}
+ // nulString is turned to Text
+
+ try dbQueue.inTransaction { db in
+ try db.execute(sql: "INSERT INTO `values` (realAffinity) VALUES (?)", arguments: [nulString])
+ let sql = "SELECT realAffinity FROM `values`"
+ XCTAssertEqual(try DatabaseValue.fetchOne(db, sql: sql)!.storageClass, .text)
+ try assertDecoding(db, sql, Bool.self, expectedSQLiteConversion: false, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int.self, expectedSQLiteConversion:0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int32.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int64.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Double.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, String.self, expectedSQLiteConversion: nulString, expectedDatabaseValueConversion: nulString)
+ try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: nulStringData, expectedDatabaseValueConversion: nulStringData)
+ return .rollback
+ }
+
// emojiData is turned to Blob
try dbQueue.inTransaction { db in
@@ -528,6 +578,22 @@ class DatabaseValueConversionTests : GRDBTestCase {
return .rollback
}
+ // nulStringData is turned to Blob
+
+ try dbQueue.inTransaction { db in
+ try db.execute(sql: "INSERT INTO `values` (realAffinity) VALUES (?)", arguments: [nulStringData])
+ let sql = "SELECT realAffinity FROM `values`"
+ XCTAssertEqual(try DatabaseValue.fetchOne(db, sql: sql)!.storageClass, .blob)
+ try assertDecoding(db, sql, Bool.self, expectedSQLiteConversion: false, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int.self, expectedSQLiteConversion:0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int32.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int64.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Double.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, String.self, expectedSQLiteConversion: nulString, expectedDatabaseValueConversion: nulString)
+ try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: nulStringData, expectedDatabaseValueConversion: nulStringData)
+ return .rollback
+ }
+
// nonUTF8Data is turned to Blob
try dbQueue.inTransaction { db in
@@ -699,6 +765,22 @@ class DatabaseValueConversionTests : GRDBTestCase {
return .rollback
}
+ // nulString is turned to Text
+
+ try dbQueue.inTransaction { db in
+ try db.execute(sql: "INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: [nulString])
+ let sql = "SELECT noneAffinity FROM `values`"
+ XCTAssertEqual(try DatabaseValue.fetchOne(db, sql: sql)!.storageClass, .text)
+ try assertDecoding(db, sql, Bool.self, expectedSQLiteConversion: false, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int.self, expectedSQLiteConversion:0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int32.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int64.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Double.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, String.self, expectedSQLiteConversion: nulString, expectedDatabaseValueConversion: nulString)
+ try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: nulStringData, expectedDatabaseValueConversion: nulStringData)
+ return .rollback
+ }
+
// emojiData is turned to Blob
try dbQueue.inTransaction { db in
@@ -715,6 +797,22 @@ class DatabaseValueConversionTests : GRDBTestCase {
return .rollback
}
+ // nullStringData is turned to Blob
+
+ try dbQueue.inTransaction { db in
+ try db.execute(sql: "INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: [nulStringData])
+ let sql = "SELECT noneAffinity FROM `values`"
+ XCTAssertEqual(try DatabaseValue.fetchOne(db, sql: sql)!.storageClass, .blob)
+ try assertDecoding(db, sql, Bool.self, expectedSQLiteConversion: false, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int.self, expectedSQLiteConversion:0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int32.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int64.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Double.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, String.self, expectedSQLiteConversion: nulString, expectedDatabaseValueConversion: nulString)
+ try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: nulStringData, expectedDatabaseValueConversion: nulStringData)
+ return .rollback
+ }
+
// nonUTF8Data is turned to Blob
try dbQueue.inTransaction { db in
@@ -932,6 +1030,22 @@ class DatabaseValueConversionTests : GRDBTestCase {
return .rollback
}
+ // nulString is turned to Text
+
+ try dbQueue.inTransaction { db in
+ try db.execute(sql: "INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: [nulString])
+ let sql = "SELECT \(columnName) FROM `values`"
+ XCTAssertEqual(try DatabaseValue.fetchOne(db, sql: sql)!.storageClass, .text)
+ try assertDecoding(db, sql, Bool.self, expectedSQLiteConversion: false, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int.self, expectedSQLiteConversion:0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int32.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int64.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Double.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, String.self, expectedSQLiteConversion: nulString, expectedDatabaseValueConversion: nulString)
+ try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: nulStringData, expectedDatabaseValueConversion: nulStringData)
+ return .rollback
+ }
+
// emojiData is turned to Blob
try dbQueue.inTransaction { db in
@@ -948,6 +1062,22 @@ class DatabaseValueConversionTests : GRDBTestCase {
return .rollback
}
+ // nulStringData is turned to Blob
+
+ try dbQueue.inTransaction { db in
+ try db.execute(sql: "INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: [nulStringData])
+ let sql = "SELECT \(columnName) FROM `values`"
+ XCTAssertEqual(try DatabaseValue.fetchOne(db, sql: sql)!.storageClass, .blob)
+ try assertDecoding(db, sql, Bool.self, expectedSQLiteConversion: false, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int.self, expectedSQLiteConversion:0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int32.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Int64.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, Double.self, expectedSQLiteConversion: 0, expectedDatabaseValueConversion: nil)
+ try assertDecoding(db, sql, String.self, expectedSQLiteConversion: nulString, expectedDatabaseValueConversion: nulString)
+ try assertDecoding(db, sql, Data.self, expectedSQLiteConversion: nulStringData, expectedDatabaseValueConversion: nulStringData)
+ return .rollback
+ }
+
// nonUTF8Data is turned to Blob
try dbQueue.inTransaction { db in
From 23083c46683bd0b3232467948b1d306ee329b589 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sat, 26 Sep 2026 11:56:06 +0200
Subject: [PATCH 09/27] Failing tests for strings with a NUL character used as
statement argument
Inspired from #1880 by @nesevis
---
Tests/GRDBTests/Core/Statement/UpdateStatementTests.swift | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/Tests/GRDBTests/Core/Statement/UpdateStatementTests.swift b/Tests/GRDBTests/Core/Statement/UpdateStatementTests.swift
index 2f6a90cdc..89b794d50 100644
--- a/Tests/GRDBTests/Core/Statement/UpdateStatementTests.swift
+++ b/Tests/GRDBTests/Core/Statement/UpdateStatementTests.swift
@@ -485,6 +485,7 @@ class UpdateStatementTests : GRDBTestCase {
}
try test(value: "Foo")
+ try test(value: "foo\u{0}bar") // https://sqlite.org/nulinstr.html
try test(value: "")
try test(value: "Hello".data(using: .utf8)!)
try test(value: Data())
@@ -519,6 +520,7 @@ class UpdateStatementTests : GRDBTestCase {
}
try test(value: "Foo")
+ try test(value: "foo\u{0}bar") // https://sqlite.org/nulinstr.html
try test(value: "")
try test(value: "Hello".data(using: .utf8)!)
try test(value: Data())
@@ -560,6 +562,7 @@ class UpdateStatementTests : GRDBTestCase {
}
try test(value: "Foo")
+ try test(value: "foo\u{0}bar") // https://sqlite.org/nulinstr.html
try test(value: "")
try test(value: "Hello".data(using: .utf8)!)
try test(value: Data())
@@ -596,6 +599,7 @@ class UpdateStatementTests : GRDBTestCase {
}
try test(value: "Foo")
+ try test(value: "foo\u{0}bar") // https://sqlite.org/nulinstr.html
try test(value: "")
try test(value: "Hello".data(using: .utf8)!)
try test(value: Data())
From 8957148d4d0ec3aae3c9920f53ecce35b216e591 Mon Sep 17 00:00:00 2001
From: Chris Kolbu
Date: Tue, 18 Aug 2026 21:59:20 +1000
Subject: [PATCH 10/27] Performance tests for string fetching and function
results
---
.../GRDBPerformance/FetchStringTests.swift | 118 ++++++++++++++++++
.../GRDBPerformance/FunctionResultTests.swift | 60 +++++++++
.../GRDBPerformance.xcodeproj/project.pbxproj | 8 ++
3 files changed, 186 insertions(+)
create mode 100644 Tests/Performance/GRDBPerformance/FetchStringTests.swift
create mode 100644 Tests/Performance/GRDBPerformance/FunctionResultTests.swift
diff --git a/Tests/Performance/GRDBPerformance/FetchStringTests.swift b/Tests/Performance/GRDBPerformance/FetchStringTests.swift
new file mode 100644
index 000000000..910461b03
--- /dev/null
+++ b/Tests/Performance/GRDBPerformance/FetchStringTests.swift
@@ -0,0 +1,118 @@
+import XCTest
+import GRDB
+
+/// Here we test the decoding of string columns. The other fetch tests in
+/// this target use an all-INT model, and never decode a string.
+class FetchStringTests: XCTestCase {
+ static let expectedRowCount = 200_000
+ static let personRowCount = 100_000
+ static let recordFetchesPerIteration = 5
+ static let fetchesPerIteration = 10
+
+ private struct Person: Codable, FetchableRecord, PersistableRecord {
+ static let databaseTableName = "person"
+
+ var firstName: String
+ var lastName: String
+ var email: String
+ var address: String
+ var age: Int
+ var height: Double
+ }
+
+ func test_shortString_fetch_performance() throws {
+ try measureFetch(of: String.self, from: "short")
+ }
+
+ func test_longString_fetch_performance() throws {
+ try measureFetch(of: String.self, from: "long")
+ }
+
+ func test_shortString_databaseValue_performance() throws {
+ try measureFetch(of: DatabaseValue.self, from: "short")
+ }
+
+ func test_longString_databaseValue_performance() throws {
+ try measureFetch(of: DatabaseValue.self, from: "long")
+ }
+
+ func test_record_fetch_performance() throws {
+ let dbQueue = try makePersonDatabase()
+ measure {
+ try! dbQueue.read { db in
+ for _ in 0..(
+ of type: Value.Type,
+ from column: String) throws
+ {
+ let dbQueue = try makeDatabaseQueue()
+ measure {
+ try! dbQueue.read { db in
+ for _ in 0.. DatabaseQueue {
+ let url = URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent("GRDBPerformancePeople.sqlite")
+ let dbQueue = try DatabaseQueue(path: url.path)
+ try dbQueue.write { db in
+ if try db.tableExists("person"),
+ try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM person") == Self.personRowCount
+ {
+ return
+ }
+ try db.execute(sql: "DROP TABLE IF EXISTS person")
+ try db.create(table: "person") { table in
+ table.column("firstName", .text)
+ table.column("lastName", .text)
+ table.column("email", .text)
+ table.column("address", .text)
+ table.column("age", .integer)
+ table.column("height", .double)
+ }
+ let statement = try db.makeStatement(sql: """
+ INSERT INTO person (firstName, lastName, email, address, age, height)
+ VALUES (?, ?, ?, ?, ?, ?)
+ """)
+ for index in 0.. DatabaseQueue {
+ let url = URL(fileURLWithPath: NSTemporaryDirectory())
+ .appendingPathComponent("GRDBPerformanceStrings.sqlite")
+ let dbQueue = try DatabaseQueue(path: url.path)
+ try dbQueue.write { db in
+ if try db.tableExists("item"),
+ try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM item") == Self.expectedRowCount
+ {
+ return
+ }
+ try db.execute(sql: "DROP TABLE IF EXISTS item")
+ try db.execute(sql: "CREATE TABLE item (short TEXT, long TEXT)")
+ let statement = try db.makeStatement(sql: "INSERT INTO item (short, long) VALUES (?, ?)")
+ for _ in 0..
Date: Sat, 26 Sep 2026 12:36:33 +0200
Subject: [PATCH 11/27] Test independance
---
Tests/Performance/GRDBPerformance/FetchStringTests.swift | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/Tests/Performance/GRDBPerformance/FetchStringTests.swift b/Tests/Performance/GRDBPerformance/FetchStringTests.swift
index 910461b03..b6de1b013 100644
--- a/Tests/Performance/GRDBPerformance/FetchStringTests.swift
+++ b/Tests/Performance/GRDBPerformance/FetchStringTests.swift
@@ -4,6 +4,9 @@ import GRDB
/// Here we test the decoding of string columns. The other fetch tests in
/// this target use an all-INT model, and never decode a string.
class FetchStringTests: XCTestCase {
+ static let shortString = "foo"
+ static let longString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur felis eget nibh aliquet ullamcorper. Nam sodales, tellus a cursus tincidunt, arcu purus suscipit elit, nec congue erat ipsum a purus."
+
static let expectedRowCount = 200_000
static let personRowCount = 100_000
static let recordFetchesPerIteration = 5
@@ -110,7 +113,7 @@ class FetchStringTests: XCTestCase {
try db.execute(sql: "CREATE TABLE item (short TEXT, long TEXT)")
let statement = try db.makeStatement(sql: "INSERT INTO item (short, long) VALUES (?, ?)")
for _ in 0..
Date: Sat, 26 Sep 2026 12:37:11 +0200
Subject: [PATCH 12/27] Do not measure database access acquisition and Array
building
---
.../GRDBPerformance/FetchStringTests.swift | 24 ++++++++++++-------
1 file changed, 16 insertions(+), 8 deletions(-)
diff --git a/Tests/Performance/GRDBPerformance/FetchStringTests.swift b/Tests/Performance/GRDBPerformance/FetchStringTests.swift
index b6de1b013..e86838374 100644
--- a/Tests/Performance/GRDBPerformance/FetchStringTests.swift
+++ b/Tests/Performance/GRDBPerformance/FetchStringTests.swift
@@ -41,11 +41,15 @@ class FetchStringTests: XCTestCase {
func test_record_fetch_performance() throws {
let dbQueue = try makePersonDatabase()
- measure {
- try! dbQueue.read { db in
+ try dbQueue.read { db in
+ measure {
for _ in 0..
Date: Sat, 26 Sep 2026 12:43:29 +0200
Subject: [PATCH 13/27] Fast path for String performance decoding test
---
.../GRDBPerformance/FetchStringTests.swift | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/Tests/Performance/GRDBPerformance/FetchStringTests.swift b/Tests/Performance/GRDBPerformance/FetchStringTests.swift
index e86838374..411158be0 100644
--- a/Tests/Performance/GRDBPerformance/FetchStringTests.swift
+++ b/Tests/Performance/GRDBPerformance/FetchStringTests.swift
@@ -55,6 +55,25 @@ class FetchStringTests: XCTestCase {
}
}
+ private func measureFetch(
+ of type: Value.Type,
+ from column: String) throws
+ {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.read { db in
+ measure {
+ for _ in 0..(
of type: Value.Type,
from column: String) throws
From fe774b35378faaaf451e3d90794fdfe3b896b953 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sat, 26 Sep 2026 12:58:39 +0200
Subject: [PATCH 14/27] Performance tests for String as a statement argument
---
.../GRDBPerformance/FetchStringTests.swift | 24 +++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/Tests/Performance/GRDBPerformance/FetchStringTests.swift b/Tests/Performance/GRDBPerformance/FetchStringTests.swift
index 411158be0..bf74f25dc 100644
--- a/Tests/Performance/GRDBPerformance/FetchStringTests.swift
+++ b/Tests/Performance/GRDBPerformance/FetchStringTests.swift
@@ -38,6 +38,30 @@ class FetchStringTests: XCTestCase {
func test_longString_databaseValue_performance() throws {
try measureFetch(of: DatabaseValue.self, from: "long")
}
+
+ func test_shortString_as_argument() throws {
+ let dbQueue = try DatabaseQueue()
+ try dbQueue.write { db in
+ let statement = try db.makeStatement(sql: "SELECT ? WHERE 0")
+ measure {
+ for _ in 0..<100_000 {
+ try! statement.execute(arguments: [FetchStringTests.shortString])
+ }
+ }
+ }
+ }
+
+ func test_longString_as_argument() throws {
+ let dbQueue = try DatabaseQueue()
+ try dbQueue.write { db in
+ let statement = try db.makeStatement(sql: "SELECT ? WHERE 0")
+ measure {
+ for _ in 0..<100_000 {
+ try! statement.execute(arguments: [FetchStringTests.longString])
+ }
+ }
+ }
+ }
func test_record_fetch_performance() throws {
let dbQueue = try makePersonDatabase()
From 9858de3249bc2b91b11313c817112b1ab8500dc4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sat, 26 Sep 2026 11:07:35 +0200
Subject: [PATCH 15/27] Decode strings with a NUL character
Inspired from #1880 by @nesevis
---
GRDB/Core/DatabaseValue.swift | 8 ++++++--
GRDB/Core/Support/Foundation/Decimal.swift | 5 ++---
GRDB/Core/Support/Foundation/UUID.swift | 2 +-
GRDB/Core/Support/StandardLibrary/StandardLibrary.swift | 4 +++-
4 files changed, 12 insertions(+), 7 deletions(-)
diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift
index 7a36b3477..9373810cb 100644
--- a/GRDB/Core/DatabaseValue.swift
+++ b/GRDB/Core/DatabaseValue.swift
@@ -147,7 +147,10 @@ public struct DatabaseValue: Hashable {
case SQLITE_FLOAT:
storage = .double(sqlite3_value_double(sqliteValue))
case SQLITE_TEXT:
- storage = .string(String(cString: sqlite3_value_text(sqliteValue)!))
+ let text = sqlite3_value_text(sqliteValue)
+ let byteCount = Int(sqlite3_value_bytes(sqliteValue))
+ let string = String(decoding: UnsafeBufferPointer(start: text, count: byteCount), as: UTF8.self)
+ storage = .string(string)
case SQLITE_BLOB:
if let bytes = sqlite3_value_blob(sqliteValue) {
let count = Int(sqlite3_value_bytes(sqliteValue))
@@ -171,7 +174,8 @@ public struct DatabaseValue: Hashable {
case SQLITE_FLOAT:
storage = .double(sqlite3_column_double(sqliteStatement, index))
case SQLITE_TEXT:
- storage = .string(String(cString: sqlite3_column_text(sqliteStatement, index)))
+ let string = String(sqliteStatement: sqliteStatement, index: index)
+ storage = .string(string)
case SQLITE_BLOB:
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
diff --git a/GRDB/Core/Support/Foundation/Decimal.swift b/GRDB/Core/Support/Foundation/Decimal.swift
index afcb65b74..1a82f32f6 100644
--- a/GRDB/Core/Support/Foundation/Decimal.swift
+++ b/GRDB/Core/Support/Foundation/Decimal.swift
@@ -56,9 +56,8 @@ extension Decimal: StatementColumnConvertible {
case SQLITE_FLOAT:
self.init(sqlite3_column_double(sqliteStatement, index))
case SQLITE_TEXT:
- self.init(
- string: String(cString: sqlite3_column_text(sqliteStatement, index)!),
- locale: _posixLocale)
+ let string = String(sqliteStatement: sqliteStatement, index: index)
+ self.init(string: string, locale: _posixLocale)
default:
return nil
}
diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift
index bb4a34210..8d4055915 100644
--- a/GRDB/Core/Support/Foundation/UUID.swift
+++ b/GRDB/Core/Support/Foundation/UUID.swift
@@ -89,7 +89,7 @@ extension UUID: StatementColumnConvertible {
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_TEXT:
- let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
+ let string = String(sqliteStatement: sqliteStatement, index: index)
guard let uuid = UUID(uuidString: string) else {
return nil
}
diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift
index 0fe494d15..e0f828853 100644
--- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift
+++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift
@@ -592,7 +592,9 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
- self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
+ let text = sqlite3_column_text(sqliteStatement, index)
+ let byteCount = Int(sqlite3_column_bytes(sqliteStatement, index))
+ self = String(decoding: UnsafeBufferPointer(start: text, count: byteCount), as: UTF8.self)
}
/// Returns a TEXT database value.
From de0ce29d73e18b5d6a5d4756ee2ef69d20954ae7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sat, 26 Sep 2026 11:27:14 +0200
Subject: [PATCH 16/27] Encode strings with a NUL character
Inspired from #1880 by @nesevis
---
GRDB/Core/DatabaseFunction.swift | 12 ++++--
GRDB/Core/DatabaseValue.swift | 2 +-
.../StandardLibrary/StandardLibrary.swift | 42 +++++++++++++++++--
3 files changed, 47 insertions(+), 9 deletions(-)
diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift
index 1744ae769..db1ebb4f5 100644
--- a/GRDB/Core/DatabaseFunction.swift
+++ b/GRDB/Core/DatabaseFunction.swift
@@ -105,8 +105,10 @@ public final class DatabaseFunction: Identifiable, Sendable {
sqlite3_result_int64(context, int64)
case .double(let double):
sqlite3_result_double(context, double)
- case .string(let string):
- sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT)
+ case .string(var string):
+ string.withSQLiteText {
+ sqlite3_result_text(context, $0, $1, SQLITE_TRANSIENT)
+ }
case .blob(let data):
data.withUnsafeBytes {
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
@@ -447,8 +449,10 @@ public final class DatabaseFunction: Identifiable, Sendable {
sqlite3_result_int64(sqliteContext, int64)
case .double(let double):
sqlite3_result_double(sqliteContext, double)
- case .string(let string):
- sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
+ case .string(var string):
+ string.withSQLiteText {
+ sqlite3_result_text(sqliteContext, $0, $1, SQLITE_TRANSIENT)
+ }
case .blob(let data):
data.withUnsafeBytes {
sqlite3_result_blob(sqliteContext, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift
index 9373810cb..b335249e9 100644
--- a/GRDB/Core/DatabaseValue.swift
+++ b/GRDB/Core/DatabaseValue.swift
@@ -227,7 +227,7 @@ extension DatabaseValue: StatementBinding {
let code = double.bind(to: sqliteStatement, at: index)
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
return try body()
- case .string(let string):
+ case .string(var string):
return try string.withBinding(to: sqliteStatement, at: index, do: body)
case .blob(let data):
return try data.withBinding(to: sqliteStatement, at: index, do: body)
diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift
index e0f828853..65e8c13b2 100644
--- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift
+++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift
@@ -624,23 +624,57 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
- sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
+ var string = self
+ return string.withSQLiteText {
+ sqlite3_bind_text(sqliteStatement, index, $0, $1, SQLITE_TRANSIENT)
+ }
}
/// Calls the given closure after binding a statement argument.
///
/// The binding is valid only during the execution of this method.
///
+ /// This method is mutating because the string is made contiguous
+ /// if necessary.
+ ///
/// - parameter sqliteStatement: An SQLite statement.
/// - parameter index: 1-based index to statement arguments.
/// - parameter body: The closure to execute when argument is bound.
- func withBinding(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
- try withCString {
- let code = sqlite3_bind_text(sqliteStatement, index, $0, -1, nil /* SQLITE_STATIC */)
+ mutating func withBinding(
+ to sqliteStatement: SQLiteStatement,
+ at index: CInt,
+ do body: () throws -> T
+ ) throws -> T {
+ try withSQLiteText {
+ let code = sqlite3_bind_text(sqliteStatement, index, $0, $1, nil /* SQLITE_STATIC */)
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
return try body()
}
}
+
+ /// Runs body over the content of this string as an UTF8 string. This
+ /// method exists because it deals with the ASCII NUL (\0) characters,
+ /// unlike C strings.
+ ///
+ /// This method is mutating because the string is made contiguous
+ /// if necessary.
+ mutating func withSQLiteText(
+ _ body: (UnsafePointer, CInt) throws -> T
+ ) rethrows -> T {
+ try withUTF8 { utf8 in
+ guard let baseAddress = utf8.baseAddress else {
+ // Empty string: yield a non-nil pointer to the NUL string
+ // terminator, so that functions such as sqlite3_bind_text()
+ // unambiguously interpret it as the empty string.
+ return try withUnsafePointer(to: 0 as CChar) {
+ try body($0, 0)
+ }
+ }
+ return try baseAddress.withMemoryRebound(to: CChar.self, capacity: utf8.count) {
+ try body($0, CInt(utf8.count))
+ }
+ }
+ }
}
From 3f80cfccf487088829e1e1abbf68f3b69edac8c7 Mon Sep 17 00:00:00 2001
From: Sharath Kumar <7642133+builtbysharath@users.noreply.github.com>
Date: Sun, 11 Oct 2026 22:33:07 +0530
Subject: [PATCH 17/27] Keep SQLite's error message when a database fails to
open
---
GRDB/Core/Database.swift | 5 ++++-
.../Core/DatabaseQueue/DatabaseQueueTests.swift | 16 ++++++++++++++++
2 files changed, 20 insertions(+), 1 deletion(-)
diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift
index bcce91c53..822005d40 100644
--- a/GRDB/Core/Database.swift
+++ b/GRDB/Core/Database.swift
@@ -494,8 +494,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// https://www.sqlite.org/c3ref/close.html
// > Calling sqlite3_close() or sqlite3_close_v2() with a NULL
// > pointer argument is a harmless no-op.
+ //
+ // Read the error message before the connection is closed.
+ let message = sqliteConnection.map { String(cString: sqlite3_errmsg($0)) }
_ = sqlite3_close(sqliteConnection) // ignore result code
- throw DatabaseError(resultCode: code)
+ throw DatabaseError(resultCode: code, message: message)
}
guard let sqliteConnection else {
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
diff --git a/Tests/GRDBTests/Core/DatabaseQueue/DatabaseQueueTests.swift b/Tests/GRDBTests/Core/DatabaseQueue/DatabaseQueueTests.swift
index 0372d9777..11dff10ac 100644
--- a/Tests/GRDBTests/Core/DatabaseQueue/DatabaseQueueTests.swift
+++ b/Tests/GRDBTests/Core/DatabaseQueue/DatabaseQueueTests.swift
@@ -52,6 +52,22 @@ class DatabaseQueueTests: GRDBTestCase {
}
}
+ func testOpenErrorMessage() throws {
+ let uriFilenamesEnabled = try DatabaseQueue().read { db in
+ try Bool.fetchOne(db, sql: "SELECT sqlite_compileoption_used('USE_URI')")!
+ }
+ guard uriFilenamesEnabled else {
+ throw XCTSkip("URI filenames are not enabled")
+ }
+ do {
+ _ = try DatabaseQueue(path: "file:test.sqlite?mode=bogus")
+ XCTFail("Expected error")
+ } catch let error as DatabaseError {
+ XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
+ XCTAssertEqual(error.message, "no such access mode: bogus")
+ }
+ }
+
func testAddRemoveFunction() throws {
// Adding a function and then removing it should succeed
let dbQueue = try makeDatabaseQueue()
From e1a0c1afbe77e145c72712c44ede4c09ea1c2d82 Mon Sep 17 00:00:00 2001
From: Sharath Kumar <7642133+builtbysharath@users.noreply.github.com>
Date: Tue, 13 Oct 2026 15:35:38 +0530
Subject: [PATCH 18/27] Skip the open error message test when URI filenames are
off
sqlite_compileoption_used('USE_URI') reports whether the option is
defined, not its value, and is missing when compile-option diagnostics
are omitted. Check the error from the open instead: without URI
filenames, the path is in a missing "file:" directory and fails with
SQLITE_CANTOPEN.
---
.../Core/DatabaseQueue/DatabaseQueueTests.swift | 13 ++++++-------
1 file changed, 6 insertions(+), 7 deletions(-)
diff --git a/Tests/GRDBTests/Core/DatabaseQueue/DatabaseQueueTests.swift b/Tests/GRDBTests/Core/DatabaseQueue/DatabaseQueueTests.swift
index 11dff10ac..fd870adca 100644
--- a/Tests/GRDBTests/Core/DatabaseQueue/DatabaseQueueTests.swift
+++ b/Tests/GRDBTests/Core/DatabaseQueue/DatabaseQueueTests.swift
@@ -53,15 +53,14 @@ class DatabaseQueueTests: GRDBTestCase {
}
func testOpenErrorMessage() throws {
- let uriFilenamesEnabled = try DatabaseQueue().read { db in
- try Bool.fetchOne(db, sql: "SELECT sqlite_compileoption_used('USE_URI')")!
- }
- guard uriFilenamesEnabled else {
- throw XCTSkip("URI filenames are not enabled")
- }
+ // Without URI filenames, this path is a file in a missing "file:"
+ // directory, and opening fails with SQLITE_CANTOPEN.
+ let path = "file:" + NSTemporaryDirectory() + "test.sqlite?mode=bogus"
do {
- _ = try DatabaseQueue(path: "file:test.sqlite?mode=bogus")
+ _ = try DatabaseQueue(path: path)
XCTFail("Expected error")
+ } catch DatabaseError.SQLITE_CANTOPEN {
+ throw XCTSkip("URI filenames are not enabled")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "no such access mode: bogus")
From 94fa864eb73b818fd0b7c7e30cfdb12b3b017f5c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 1 Nov 2026 13:57:06 +0100
Subject: [PATCH 19/27] Failing test for the column cache of a recompiled
statement
---
.../Core/Statement/SelectStatementTests.swift | 22 +++++++++++++++++++
1 file changed, 22 insertions(+)
diff --git a/Tests/GRDBTests/Core/Statement/SelectStatementTests.swift b/Tests/GRDBTests/Core/Statement/SelectStatementTests.swift
index 95d8d39c4..324608dfa 100644
--- a/Tests/GRDBTests/Core/Statement/SelectStatementTests.swift
+++ b/Tests/GRDBTests/Core/Statement/SelectStatementTests.swift
@@ -388,4 +388,26 @@ class SelectStatementTests : GRDBTestCase {
XCTAssertEqual(observers.map(\.triggered), [true, true, true, true])
}
}
+
+ func testColumnsAfterSchemaChange() throws {
+ // SQLite recompiles statements after a schema change, and this can
+ // change the result columns.
+ try makeDatabaseQueue().inDatabase { db in
+ try db.execute(sql: """
+ CREATE TABLE t(a);
+ INSERT INTO t VALUES (1);
+ """)
+ let statement = try db.makeStatement(sql: "SELECT * FROM t")
+ XCTAssertEqual(statement.columnNames, ["a"])
+ XCTAssertEqual(statement.index(ofColumn: "a"), 0)
+ XCTAssertNil(statement.index(ofColumn: "b"))
+
+ try db.execute(sql: "ALTER TABLE t ADD COLUMN b")
+ try statement.execute() // Recompile
+ XCTAssertEqual(statement.columnCount, 2)
+ XCTAssertEqual(statement.columnNames, ["a", "b"])
+ XCTAssertEqual(statement.index(ofColumn: "a"), 0)
+ XCTAssertEqual(statement.index(ofColumn: "b"), 1)
+ }
+ }
}
From b983df96e2360824f1a3c9401ab048d99ad82b78 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 1 Nov 2026 14:10:47 +0100
Subject: [PATCH 20/27] Failing test for SQLRequest on a recompiled statement
---
Tests/GRDBTests/Core/SQLRequestTests.swift | 27 ++++++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/Tests/GRDBTests/Core/SQLRequestTests.swift b/Tests/GRDBTests/Core/SQLRequestTests.swift
index 2c95c8012..ecb3eccd1 100644
--- a/Tests/GRDBTests/Core/SQLRequestTests.swift
+++ b/Tests/GRDBTests/Core/SQLRequestTests.swift
@@ -47,6 +47,33 @@ class SQLRequestTests: GRDBTestCase {
}
}
+ func testCachedSQLRequestAfterSchemaChange() throws {
+ // SQLite recompiles statements after a schema change, and this can
+ // change the result columns.
+ let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
+ try dbQueue.write { db in
+ try db.execute(sql: """
+ CREATE TABLE t(a);
+ INSERT INTO t VALUES (1);
+ """)
+ }
+
+ let request = SQLRequest(sql: "SELECT * FROM t", cached: true)
+ try dbQueue.read { db in
+ XCTAssertEqual(try request.fetchAll(db), [["a": 1]])
+ }
+
+ // Schema change performed by another connection
+ let otherQueue = try makeDatabaseQueue(filename: "test.sqlite")
+ try otherQueue.write { db in
+ try db.execute(sql: "ALTER TABLE t ADD COLUMN b DEFAULT 2")
+ }
+
+ try dbQueue.inDatabase { db in
+ XCTAssertEqual(try request.fetchAll(db), [["a": 1, "b": 2]])
+ }
+ }
+
func testSQLLiteralInitializer() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
From a0f184ec26a132f97e53867392151a7214e37357 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 1 Nov 2026 13:57:10 +0100
Subject: [PATCH 21/27] Invalidate Statement column cache after recompilation
---
GRDB/Core/Statement.swift | 56 +++++++++++++++++++++++++++++++--------
1 file changed, 45 insertions(+), 11 deletions(-)
diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift
index 31a1abd16..28788dddb 100644
--- a/GRDB/Core/Statement.swift
+++ b/GRDB/Core/Statement.swift
@@ -47,6 +47,25 @@ public final class Statement {
case rollbackSavepoint(String)
}
+ /// The column names and indexes of a statement, for a given compilation
+ /// of the statement.
+ private struct ColumnCache {
+ var reprepareCount: CInt
+ var columnNames: [String]
+ /// Indexes of the leftmost columns. Keys are lowercase.
+ var columnIndexes: [String: Int]
+
+ init(sqliteStatement: SQLiteStatement, reprepareCount: CInt) {
+ self.reprepareCount = reprepareCount
+ self.columnNames = (0..), and this can change
+ /// the result columns (think `SELECT *` after a column was added).
+ /// So the cache is rebuilt whenever the statement is recompiled.
+ private var columnCache: ColumnCache {
+ let reprepareCount = sqlite3_stmt_status(sqliteStatement, SQLITE_STMTSTATUS_REPREPARE, 0)
+ if let _columnCache, _columnCache.reprepareCount == reprepareCount {
+ return _columnCache
+ }
+ let columnCache = ColumnCache(sqliteStatement: sqliteStatement, reprepareCount: reprepareCount)
+ _columnCache = columnCache
+ return columnCache
+ }
/// Creates a prepared statement. Returns nil if the compiled string is
/// blank or empty.
From dc101b2847231b30f0b5bc8611d56274364cce70 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 1 Nov 2026 13:57:31 +0100
Subject: [PATCH 22/27] Failing test for the Row column cache of a recompiled
statement
---
.../Core/Row/RowFromStatementTests.swift | 27 +++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/Tests/GRDBTests/Core/Row/RowFromStatementTests.swift b/Tests/GRDBTests/Core/Row/RowFromStatementTests.swift
index 426dca46a..297f521ad 100644
--- a/Tests/GRDBTests/Core/Row/RowFromStatementTests.swift
+++ b/Tests/GRDBTests/Core/Row/RowFromStatementTests.swift
@@ -405,4 +405,31 @@ class RowFromStatementTests : RowTestCase {
])
}
}
+
+ func testRowsAfterSchemaChange() throws {
+ // SQLite recompiles statements after a schema change, and this can
+ // change the result columns.
+ try makeDatabaseQueue().inDatabase { db in
+ try db.execute(sql: """
+ CREATE TABLE t(a);
+ INSERT INTO t VALUES (1);
+ """)
+ let statement = try db.makeStatement(sql: "SELECT * FROM t")
+ XCTAssertEqual(try Row.fetchAll(statement), [["a": 1]])
+
+ try db.execute(sql: "ALTER TABLE t ADD COLUMN b DEFAULT 2")
+
+ // The cursor is created before the statement is recompiled,
+ // on the first step.
+ let rows = try Row.fetchCursor(statement)
+ let row = try XCTUnwrap(rows.next())
+ XCTAssertEqual(row.count, 2)
+ XCTAssertEqual(Array(row.columnNames), ["a", "b"])
+ XCTAssertEqual(row["b"], 2)
+ XCTAssertEqual(row.copy(), ["a": 1, "b": 2])
+ XCTAssertNil(try rows.next())
+
+ XCTAssertEqual(try Row.fetchAll(statement), [["a": 1, "b": 2]])
+ }
+ }
}
From 9601d6ac9b90cdc1d3462adfaf2ec8e2c62ffb64 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 1 Nov 2026 13:57:37 +0100
Subject: [PATCH 23/27] Row fetched from a statement do not cache statement
column in order to support statement recompilation
---
GRDB/Core/Row.swift | 31 ++++++++++++++++++-------------
1 file changed, 18 insertions(+), 13 deletions(-)
diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift
index 8f34f2851..e9589ee63 100644
--- a/GRDB/Core/Row.swift
+++ b/GRDB/Core/Row.swift
@@ -154,7 +154,20 @@ public final class Row {
let sqliteStatement: SQLiteStatement?
/// The number of columns in the row.
- public let count: Int
+ @inlinable
+ public var count: Int {
+ // Rows that map an SQLite statement don't cache the number of
+ // columns, because SQLite may recompile the statement after a
+ // schema change, with a different number of columns.
+ if let sqliteStatement {
+ return Int(sqlite3_column_count(sqliteStatement))
+ }
+ return cachedCount
+ }
+
+ /// The number of columns, when the row does not map an SQLite statement.
+ @usableFromInline
+ let cachedCount: Int
/// A view on the prefetched associated rows.
///
@@ -238,7 +251,7 @@ public final class Row {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
- self.count = Int(sqlite3_column_count(sqliteStatement))
+ self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count`
}
/// Creates a row that maps an SQLite statement. Further calls to
@@ -247,7 +260,7 @@ public final class Row {
self.statement = nil
self.sqliteStatement = sqliteStatement
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
- self.count = Int(sqlite3_column_count(sqliteStatement))
+ self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count`
}
/// Creates a row that contain a copy of the current state of the
@@ -269,7 +282,7 @@ public final class Row {
self.statement = nil
self.sqliteStatement = nil
self.impl = impl
- self.count = impl.count
+ self.cachedCount = impl.count
}
}
@@ -2785,19 +2798,10 @@ private struct StatementCopyRowImpl: RowImpl {
private struct StatementRowImpl: RowImpl {
let statement: Statement
let sqliteStatement: SQLiteStatement
- let lowercaseColumnIndexes: [String: Int]
init(sqliteStatement: SQLiteStatement, statement: Statement) {
self.statement = statement
self.sqliteStatement = sqliteStatement
- // Optimize row[columnName]
- let lowercaseColumnNames = (0.. Int? {
+ let lowercaseColumnIndexes = statement.columnIndexes
if let index = lowercaseColumnIndexes[name] {
return index
}
From a8a5b431bed70a5ffb516adf2a11b2d911284271 Mon Sep 17 00:00:00 2001
From: Dylan Mace
Date: Mon, 28 Sep 2026 14:47:14 -0400
Subject: [PATCH 24/27] Failing tests: SharedValueObservation deadlocks when a
client is cancelled during a notification
---
.../SharedValueObservationTests.swift | 104 ++++++++++++++++++
1 file changed, 104 insertions(+)
diff --git a/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift b/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift
index 4a8d629a5..9104e28ae 100644
--- a/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift
+++ b/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift
@@ -882,6 +882,110 @@ class SharedValueObservationTests: GRDBTestCase {
break
}
}
+
+ // Regression test: a client can be cancelled from another thread while
+ // the shared observation is notifying a fresh value.
+ //
+ // Notifying clients and cancelling clients must not happen under the
+ // same lock. Otherwise, a notification that waits for a resource held by
+ // the cancelling thread deadlocks. This happens in practice when a client
+ // feeds an AsyncThrowingStream: `yield` waits for the consumer task's
+ // status record lock, while `swift_task_cancel` holds that lock and runs
+ // the stream's `onTermination` handler, which cancels the client.
+ func test_cancellation_from_other_thread_during_value_notification() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.create(table: "player") { t in
+ t.autoIncrementedPrimaryKey("id")
+ }
+ }
+
+ let sharedObservation = ValueObservation
+ .tracking(Table("player").fetchCount)
+ .shared(
+ in: dbQueue,
+ scheduling: .async(onQueue: DispatchQueue(label: "SharedValueObservationTests")),
+ extent: .observationLifetime)
+
+ let cancellableMutex: Mutex = Mutex(nil)
+ let cancellationDidCompleteMutex: Mutex = Mutex(nil)
+ let exp = expectation(description: "")
+ let cancellable = sharedObservation.start(
+ onError: { XCTFail("Unexpected error \($0)") },
+ onChange: { value in
+ guard value == 1 else { return }
+ cancellationDidCompleteMutex.store(
+ Self.cancelFromOtherThreadAndWait(cancellableMutex.load()))
+ exp.fulfill()
+ })
+ cancellableMutex.store(cancellable)
+
+ try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES") }
+ wait(for: [exp], timeout: 5)
+ XCTAssertEqual(cancellationDidCompleteMutex.load(), true)
+ }
+
+ // Regression test: a client can be cancelled from another thread while
+ // the shared observation is notifying an error.
+ //
+ // See test_cancellation_from_other_thread_during_value_notification.
+ func test_cancellation_from_other_thread_during_error_notification() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.create(table: "player") { t in
+ t.autoIncrementedPrimaryKey("id")
+ }
+ }
+
+ let fetchErrorMutex: Mutex = Mutex(nil)
+ let sharedObservation = ValueObservation
+ .tracking { db -> Int in
+ try fetchErrorMutex.withLock { error in
+ if let error { throw error }
+ }
+ return try Table("player").fetchCount(db)
+ }
+ .shared(
+ in: dbQueue,
+ scheduling: .async(onQueue: DispatchQueue(label: "SharedValueObservationTests")),
+ extent: .observationLifetime)
+
+ let cancellableMutex: Mutex = Mutex(nil)
+ let cancellationDidCompleteMutex: Mutex = Mutex(nil)
+ let initialValueExp = expectation(description: "initial value")
+ let errorExp = expectation(description: "error")
+ let cancellable = sharedObservation.start(
+ onError: { _ in
+ cancellationDidCompleteMutex.store(
+ Self.cancelFromOtherThreadAndWait(cancellableMutex.load()))
+ errorExp.fulfill()
+ },
+ onChange: { _ in
+ initialValueExp.fulfill()
+ })
+ cancellableMutex.store(cancellable)
+ wait(for: [initialValueExp], timeout: 5)
+
+ fetchErrorMutex.store(TestError())
+ try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES") }
+ wait(for: [errorExp], timeout: 5)
+ XCTAssertEqual(cancellationDidCompleteMutex.load(), true)
+ }
+
+ /// Cancels `cancellable` from another thread, and returns whether the
+ /// cancellation completed before a timeout.
+ ///
+ /// Waiting for the other thread models a notification callback that
+ /// waits for a resource held by a thread that is cancelling the client.
+ /// A timeout reveals a deadlock, without hanging the test suite.
+ private static func cancelFromOtherThreadAndWait(_ cancellable: AnyDatabaseCancellable?) -> Bool {
+ let semaphore = DispatchSemaphore(value: 0)
+ DispatchQueue.global().async {
+ cancellable?.cancel()
+ semaphore.signal()
+ }
+ return semaphore.wait(timeout: .now() + 1) == .success
+ }
}
private class Log: TextOutputStream {
From 5fe300b733cc9cc296b24045665ff033cd23dc25 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 1 Nov 2026 15:44:37 +0100
Subject: [PATCH 25/27] More failing SharedValueObservation tests
---
.../SharedValueObservationTests.swift | 298 ++++++++++++++++++
1 file changed, 298 insertions(+)
diff --git a/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift b/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift
index 9104e28ae..0c21e727f 100644
--- a/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift
+++ b/Tests/GRDBTests/ValueObservation/SharedValueObservationTests.swift
@@ -972,6 +972,266 @@ class SharedValueObservationTests: GRDBTestCase {
XCTAssertEqual(cancellationDidCompleteMutex.load(), true)
}
+ // Regression test: a client cancelled from another thread is not
+ // notified of a value that is being notified to other clients.
+ func test_no_value_notification_after_cancellation_from_other_thread() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.create(table: "player") { t in
+ t.autoIncrementedPrimaryKey("id")
+ }
+ }
+
+ let queue = DispatchQueue(label: "SharedValueObservationTests")
+ let sharedObservation = ValueObservation
+ .tracking(Table("player").fetchCount)
+ .shared(
+ in: dbQueue,
+ scheduling: .async(onQueue: queue),
+ extent: .observationLifetime)
+
+ let initialValuesExp = expectation(description: "initial values")
+ initialValuesExp.expectedFulfillmentCount = 2
+ let notificationDidStartSemaphore = DispatchSemaphore(value: 0)
+ let cancellationDidCompleteSemaphore = DispatchSemaphore(value: 0)
+
+ // Client 1 blocks the notification of the second value until
+ // client 2 is cancelled.
+ let cancellable1 = sharedObservation.start(
+ onError: { XCTFail("Unexpected error \($0)") },
+ onChange: { value in
+ if value == 0 {
+ initialValuesExp.fulfill()
+ } else {
+ notificationDidStartSemaphore.signal()
+ _ = cancellationDidCompleteSemaphore.wait(timeout: .now() + 5)
+ }
+ })
+
+ let values2Mutex: Mutex<[Int]> = Mutex([])
+ let cancellable2 = sharedObservation.start(
+ onError: { XCTFail("Unexpected error \($0)") },
+ onChange: { value in
+ values2Mutex.withLock { $0.append(value) }
+ if value == 0 {
+ initialValuesExp.fulfill()
+ }
+ })
+ wait(for: [initialValuesExp], timeout: 5)
+
+ try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES") }
+ XCTAssertEqual(notificationDidStartSemaphore.wait(timeout: .now() + 5), .success)
+ cancellable2.cancel()
+ cancellationDidCompleteSemaphore.signal()
+ queue.sync { }
+
+ XCTAssertEqual(values2Mutex.load(), [0])
+ withExtendedLifetime(cancellable1) { }
+ }
+
+ // Regression test: a client cancelled from another thread is not
+ // notified of an error that is being notified to other clients.
+ func test_no_error_notification_after_cancellation_from_other_thread() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.create(table: "player") { t in
+ t.autoIncrementedPrimaryKey("id")
+ }
+ }
+
+ let fetchErrorMutex: Mutex = Mutex(nil)
+ let queue = DispatchQueue(label: "SharedValueObservationTests")
+ let sharedObservation = ValueObservation
+ .tracking { db -> Int in
+ try fetchErrorMutex.withLock { error in
+ if let error { throw error }
+ }
+ return try Table("player").fetchCount(db)
+ }
+ .shared(
+ in: dbQueue,
+ scheduling: .async(onQueue: queue),
+ extent: .observationLifetime)
+
+ let initialValuesExp = expectation(description: "initial values")
+ initialValuesExp.expectedFulfillmentCount = 2
+ let notificationDidStartSemaphore = DispatchSemaphore(value: 0)
+ let cancellationDidCompleteSemaphore = DispatchSemaphore(value: 0)
+
+ // Client 1 blocks the notification of the error until
+ // client 2 is cancelled.
+ let cancellable1 = sharedObservation.start(
+ onError: { _ in
+ notificationDidStartSemaphore.signal()
+ _ = cancellationDidCompleteSemaphore.wait(timeout: .now() + 5)
+ },
+ onChange: { _ in
+ initialValuesExp.fulfill()
+ })
+
+ let error2Mutex: Mutex = Mutex(nil)
+ let cancellable2 = sharedObservation.start(
+ onError: { error in
+ error2Mutex.store(error)
+ },
+ onChange: { _ in
+ initialValuesExp.fulfill()
+ })
+ wait(for: [initialValuesExp], timeout: 5)
+
+ fetchErrorMutex.store(TestError())
+ try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES") }
+ XCTAssertEqual(notificationDidStartSemaphore.wait(timeout: .now() + 5), .success)
+ cancellable2.cancel()
+ cancellationDidCompleteSemaphore.signal()
+ queue.sync { }
+
+ XCTAssertNil(error2Mutex.load())
+ withExtendedLifetime(cancellable1) { }
+ }
+
+ // Regression test: a client cancelled before the last value is
+ // notified as its initial value is not notified.
+ func test_no_initial_value_notification_after_cancellation() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.create(table: "player") { t in
+ t.autoIncrementedPrimaryKey("id")
+ }
+ }
+
+ let queue = DispatchQueue(label: "SharedValueObservationTests")
+ let sharedObservation = ValueObservation
+ .tracking(Table("player").fetchCount)
+ .shared(
+ in: dbQueue,
+ scheduling: .async(onQueue: queue),
+ extent: .observationLifetime)
+
+ let initialValueExp = expectation(description: "initial value")
+ let cancellable1 = sharedObservation.start(
+ onError: { XCTFail("Unexpected error \($0)") },
+ onChange: { _ in initialValueExp.fulfill() })
+ wait(for: [initialValueExp], timeout: 5)
+
+ // Block the queue until client 2 is cancelled.
+ let cancellationDidCompleteSemaphore = DispatchSemaphore(value: 0)
+ queue.async {
+ _ = cancellationDidCompleteSemaphore.wait(timeout: .now() + 5)
+ }
+
+ let values2Mutex: Mutex<[Int]> = Mutex([])
+ let cancellable2 = sharedObservation.start(
+ onError: { XCTFail("Unexpected error \($0)") },
+ onChange: { value in
+ values2Mutex.withLock { $0.append(value) }
+ })
+ cancellable2.cancel()
+ cancellationDidCompleteSemaphore.signal()
+ queue.sync { }
+
+ XCTAssertEqual(values2Mutex.load(), [])
+ withExtendedLifetime(cancellable1) { }
+ }
+
+ // Regression test: a shared observation that is restarted while the
+ // failed upstream observation is starting keeps on observing
+ // the database.
+ func test_restart_during_failed_start_whileObserved() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.create(table: "player") { t in
+ t.autoIncrementedPrimaryKey("id")
+ }
+ }
+
+ // The first fetch fails
+ let fetchCountMutex = Mutex(0)
+ let sharedObservation = ValueObservation
+ .tracking { db -> Int in
+ if fetchCountMutex.increment() == 1 {
+ throw TestError()
+ }
+ return try Table("player").fetchCount(db)
+ }
+ .shared(
+ in: dbQueue,
+ scheduling: .immediate,
+ extent: .whileObserved)
+
+ let cancellable2Mutex: Mutex = Mutex(nil)
+ let values2Mutex: Mutex<[Int]> = Mutex([])
+ let value2Exp = expectation(description: "value")
+ let cancellable1 = sharedObservation.start(
+ onError: { _ in
+ // Restart the shared observation from the immediate
+ // error notification, before the failed upstream
+ // observation has returned its cancellable.
+ let cancellable2 = sharedObservation.start(
+ onError: { XCTFail("Unexpected error \($0)") },
+ onChange: { value in
+ values2Mutex.withLock { $0.append(value) }
+ if value == 1 {
+ value2Exp.fulfill()
+ }
+ })
+ cancellable2Mutex.store(cancellable2)
+ },
+ onChange: { _ in XCTFail("Unexpected value") })
+ XCTAssertEqual(values2Mutex.load(), [0])
+
+ try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES") }
+ wait(for: [value2Exp], timeout: 5)
+ XCTAssertEqual(values2Mutex.load(), [0, 1])
+ withExtendedLifetime(cancellable1) { }
+ withExtendedLifetime(cancellable2Mutex) { }
+ }
+
+ // Regression test: the last value, notified as the initial value of a
+ // new client, is not notified after a fresher value.
+ func test_initial_value_is_not_notified_after_fresher_value() throws {
+ let dbQueue = try makeDatabaseQueue()
+ try dbQueue.write { db in
+ try db.create(table: "player") { t in
+ t.autoIncrementedPrimaryKey("id")
+ }
+ }
+
+ let scheduler = ManualScheduler()
+ let sharedObservation = ValueObservation
+ .tracking(Table("player").fetchCount)
+ .shared(
+ in: dbQueue,
+ scheduling: scheduler,
+ extent: .observationLifetime)
+
+ // Client 1 makes 0 the last value.
+ let values1Mutex: Mutex<[Int]> = Mutex([])
+ let cancellable1 = sharedObservation.start(
+ onError: { XCTFail("Unexpected error \($0)") },
+ onChange: { value in values1Mutex.withLock { $0.append(value) } })
+ XCTAssertTrue(scheduler.waitForScheduledActions(count: 1))
+ scheduler.runScheduledActions()
+ XCTAssertEqual(values1Mutex.load(), [0])
+
+ // The fresh value 1 is scheduled, but not notified yet.
+ try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES") }
+ XCTAssertTrue(scheduler.waitForScheduledActions(count: 1))
+
+ // Client 2 starts. The last value 0 is scheduled as its initial
+ // value, after the fresh value 1.
+ let values2Mutex: Mutex<[Int]> = Mutex([])
+ let cancellable2 = sharedObservation.start(
+ onError: { XCTFail("Unexpected error \($0)") },
+ onChange: { value in values2Mutex.withLock { $0.append(value) } })
+ XCTAssertTrue(scheduler.waitForScheduledActions(count: 2))
+ scheduler.runScheduledActions()
+
+ XCTAssertEqual(values1Mutex.load(), [0, 1])
+ XCTAssertEqual(values2Mutex.load(), [1])
+ withExtendedLifetime((cancellable1, cancellable2)) { }
+ }
+
/// Cancels `cancellable` from another thread, and returns whether the
/// cancellation completed before a timeout.
///
@@ -1009,3 +1269,41 @@ private class Log: TextOutputStream {
}
private struct TestError: Error { }
+
+/// A scheduler that runs scheduled actions on demand.
+private final class ManualScheduler: ValueObservationScheduler, @unchecked Sendable {
+ private let condition = NSCondition()
+ private var actions: [@Sendable () -> Void] = [] // protected by condition
+
+ func immediateInitialValue() -> Bool { false }
+
+ func schedule(_ action: @escaping @Sendable () -> Void) {
+ condition.lock()
+ actions.append(action)
+ condition.broadcast()
+ condition.unlock()
+ }
+
+ /// Waits until `count` actions are scheduled, and returns whether
+ /// they were scheduled before a timeout.
+ func waitForScheduledActions(count: Int) -> Bool {
+ let deadline = Date(timeIntervalSinceNow: 5)
+ condition.lock()
+ defer { condition.unlock() }
+ while actions.count < count {
+ if !condition.wait(until: deadline) { return false }
+ }
+ return true
+ }
+
+ /// Runs scheduled actions, in order.
+ func runScheduledActions() {
+ condition.lock()
+ let actions = self.actions
+ self.actions = []
+ condition.unlock()
+ for action in actions {
+ action()
+ }
+ }
+}
From 1d59d1656b2f236fa4f1e9e1955f7d38338b1c9e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 1 Nov 2026 13:20:39 +0100
Subject: [PATCH 26/27] Fix SharedValueObservation
---
.../SharedValueObservation.swift | 235 +++++++++++++-----
1 file changed, 170 insertions(+), 65 deletions(-)
diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift
index 0bc78496c..d5a6efd0d 100644
--- a/GRDB/ValueObservation/SharedValueObservation.swift
+++ b/GRDB/ValueObservation/SharedValueObservation.swift
@@ -169,17 +169,37 @@ public final class SharedValueObservation: @unchecked Sendabl
private let scheduler: any ValueObservationScheduler
private let extent: SharedValueObservationExtent
private let startObservation: ValueObservationStart
- private let lock = NSRecursiveLock() // support synchronous observation events
+ // Clients are notified outside of the lock, so that a client can be
+ // cancelled from any thread during a notification without deadlock.
+ private let lock = NSLock()
// protected by lock
private var clients: [Client]
- private var isObserving = false
- private var cancellable: AnyDatabaseCancellable?
+ private var currentSubscription: ValueObservationSubscription? // nil when not observing
private var lastResult: Result?
+ /// A subscription to the upstream ValueObservation.
+ ///
+ /// Events and cancellables of a subscription that is no longer
+ /// the current one are ignored.
+ private final class ValueObservationSubscription: @unchecked Sendable {
+ // @unchecked Sendable because state is protected by
+ // the lock of SharedValueObservation.
+ var cancellable: AnyDatabaseCancellable?
+ }
+
private final class Client: Sendable {
- let onError: @Sendable (Error) -> Void
- let onChange: @Sendable (Element) -> Void
+ private let onError: @Sendable (Error) -> Void
+ private let onChange: @Sendable (Element) -> Void
+ private let stateMutex = Mutex(State())
+
+ private struct State {
+ var isCancelled = false
+ /// True when a ValueObservation event was notified, and we must
+ /// not notify the last result of the shared observation as the
+ /// initial event.
+ var shouldDiscardInitialResult = false
+ }
init(
onError: @escaping @Sendable (Error) -> Void,
@@ -188,6 +208,54 @@ public final class SharedValueObservation: @unchecked Sendabl
self.onError = onError
self.onChange = onChange
}
+
+ /// Notifies the last result of the shared observation as the initial
+ /// value, unless a ValueObservation event was already notified.
+ func notifyInitial(_ result: Result) {
+ guard shouldNotifyInitialResult() else { return }
+ switch result {
+ case let .failure(error):
+ onError(error)
+ case let .success(value):
+ onChange(value)
+ }
+ }
+
+ /// Notifies a ValueObservation event.
+ func notifyChange(_ value: Element) {
+ guard shouldNotifyValueObservationEvent() else { return }
+ onChange(value)
+ }
+
+ /// Notifies a ValueObservation event.
+ func notifyError(_ error: Error) {
+ guard shouldNotifyValueObservationEvent() else { return }
+ onError(error)
+ }
+
+ /// After this method returns, no new notification starts.
+ func cancel() {
+ stateMutex.withLock { $0.isCancelled = true }
+ }
+
+ /// Returns whether a ValueObservation event event should be notified.
+ private func shouldNotifyValueObservationEvent() -> Bool {
+ stateMutex.withLock { state in
+ if state.isCancelled { return false }
+ // After a ValueObservation event, we must ignore the
+ // initial result.
+ state.shouldDiscardInitialResult = true
+ return true
+ }
+ }
+
+ /// Returns whether the initial result should be notified: the client
+ /// is not cancelled, and the initial result should not be discarded.
+ private func shouldNotifyInitialResult() -> Bool {
+ stateMutex.withLock { state in
+ !state.isCancelled && !state.shouldDiscardInitialResult
+ }
+ }
}
fileprivate init(
@@ -229,49 +297,65 @@ public final class SharedValueObservation: @unchecked Sendabl
onChange: @escaping @Sendable (Element) -> Void)
-> AnyDatabaseCancellable
{
- withLock {
+ let client = Client(onError: onError, onChange: onChange)
+ let (newSubscription, lastResult) = lock.withLock {
+ // State change
+ clients.append(client)
+
// Support for reentrancy: a shared immediate observation is
// started from the first value notification of that same shared
// immediate observation. Yeah, users are nasty.
- // In this case, self.cancellable is still nil, because we are
- // still waiting for the upstream ValueObservation to start.
- // But we must not start another one.
- let needsStart = !isObserving
+ // In this case, self.currentSubscription has no cancellable yet,
+ // because we are still waiting for the upstream ValueObservation
+ // to start. But we must not start another one.
+ if currentSubscription != nil {
+ return (ValueObservationSubscription?.none, self.lastResult)
+ }
+ let newSubscription = ValueObservationSubscription()
+ currentSubscription = newSubscription
+ return (newSubscription, nil)
+ }
+
+ // Side effect
+ if let newSubscription {
+ // Self retains the subscription and its cancellable, so don't have
+ // the cancellable retain self or the subscription.
+ let cancellable = startObservation(
+ // onError
+ { [weak self, weak newSubscription] error in
+ guard let newSubscription else { return }
+ self?.handleError(error, from: newSubscription)
+ },
+ // onChange
+ { [weak self, weak newSubscription] element in
+ guard let newSubscription else { return }
+ self?.handleChange(element, from: newSubscription)
+ })
- // State change
- let client = Client(onError: onError, onChange: onChange)
- clients.append(client)
- isObserving = true
-
- // Side effect
- if needsStart {
- // Self retains the cancellable, so don't have the cancellable retain self.
- cancellable = startObservation(
- // onError
- { [weak self] error in
- self?.handleError(error)
- },
- // onChange
- { [weak self] element in
- self?.handleChange(element)
- })
- } else if let result = lastResult {
- // Notify last result as an initial value
- scheduler.scheduleInitial {
- switch result {
- case let .failure(error):
- onError(error)
- case let .success(value):
- onChange(value)
- }
+ // The upstream observation may have been stopped, and maybe
+ // replaced, while it was starting (for example, if the initial
+ // fetch fails). In this case, discard its cancellable.
+ let discardedCancellable: AnyDatabaseCancellable? = lock.withLock {
+ guard currentSubscription === newSubscription else {
+ return cancellable
}
+ newSubscription.cancellable = cancellable
+ return nil
}
-
- return AnyDatabaseCancellable {
- // Retain shared observation (self) until client cancels
- self.handleCancel(client)
+ discardedCancellable?.cancel()
+ } else if let lastResult {
+ // Notify last result as an initial value. A fresher result may
+ // have been scheduled before, and already notified to the
+ // client: in this case, the last result is not notified.
+ scheduler.scheduleInitial {
+ client.notifyInitial(lastResult)
}
}
+
+ return AnyDatabaseCancellable {
+ // Retain shared observation (self) until client cancels
+ self.handleCancel(client)
+ }
}
#if canImport(Combine)
@@ -299,55 +383,76 @@ public final class SharedValueObservation: @unchecked Sendabl
}
#endif
- private func handleError(_ error: Error) {
- withLock {
- let notifiedClients = clients
+ private func handleError(_ error: Error, from source: ValueObservationSubscription) {
+ let (notifiedClients, stoppedCancellable) = lock.withLock {
+ guard source === currentSubscription else {
+ return ([Client](), AnyDatabaseCancellable?.none)
+ }
// State change
+ let notifiedClients = clients
+ var stoppedCancellable: AnyDatabaseCancellable?
clients = []
if extent == .whileObserved {
- isObserving = false
- cancellable = nil
- lastResult = nil
+ stoppedCancellable = stopObservation()
} else {
lastResult = .failure(error)
}
- // Side effect
- for client in notifiedClients {
- client.onError(error)
- }
+ return (notifiedClients, stoppedCancellable)
+ }
+
+ // Side effects
+ stoppedCancellable?.cancel()
+ for client in notifiedClients {
+ client.notifyError(error)
}
}
- private func handleChange(_ value: Element) {
- withLock {
+ private func handleChange(_ value: Element, from source: ValueObservationSubscription) {
+ let notifiedClients = lock.withLock {
+ guard source === currentSubscription else {
+ return [Client]()
+ }
+
// State change
lastResult = .success(value)
-
- // Side effect
- for client in clients {
- client.onChange(value)
- }
+ return clients
+ }
+
+ // Side effect
+ for client in notifiedClients {
+ client.notifyChange(value)
}
}
private func handleCancel(_ client: Client) {
- withLock {
+ // Prevent the client from being notified, even if a notification
+ // is currently in progress.
+ client.cancel()
+
+ let stoppedCancellable = lock.withLock {
// State change
clients.removeFirst(where: { $0 === client })
if clients.isEmpty && extent == .whileObserved {
- isObserving = false
- cancellable = nil
- lastResult = nil
+ return stopObservation()
}
+ return nil
}
+
+ // Side effect
+ stoppedCancellable?.cancel()
}
- private func withLock(_ execute: () throws -> T) rethrows -> T {
- lock.lock()
- defer { lock.unlock() }
- return try execute()
+ /// Stops the current upstream observation, and returns its cancellable,
+ /// so that it can be cancelled outside of the lock.
+ ///
+ /// Must be called with the lock held.
+ private func stopObservation() -> AnyDatabaseCancellable? {
+ let stoppedCancellable = currentSubscription?.cancellable
+ currentSubscription = nil
+ lastResult = nil
+ return stoppedCancellable
}
}
From 47c8497269ca4443d1bec64bf3c38182efbdf07c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gwendal=20Roue=CC=81?=
Date: Sun, 1 Nov 2026 17:03:56 +0100
Subject: [PATCH 27/27] v7.12.0
---
CHANGELOG.md | 14 ++++++++++++++
GRDB.swift.podspec | 2 +-
README.md | 2 +-
Support/Info.plist | 2 +-
4 files changed, 17 insertions(+), 3 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b7b2b8a6f..0351f4025 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
+- `7.12.x` Releases - [7.12.0](#7120)
- `7.11.x` Releases - [7.11.0](#7110) - [7.11.1](#7111)
- `7.10.x` Releases - [7.10.0](#7100)
- `7.9.x` Releases - [7.9.0](#790)
@@ -143,6 +144,19 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
+## 7.12.0
+
+Released November 1, 2026
+
+- **New**: Add support for Strings that contain the NUL character by [@groue](https://github.com/groue) and [@nesevis](https://github.com/nesevis) in [#1885](https://github.com/groue/GRDB.swift/pull/1885)
+- **New**: Keep SQLite's error message when a database fails to open by [@builtbysharath](https://github.com/builtbysharath) in [#1889](https://github.com/groue/GRDB.swift/pull/1889)
+- **Fixed**: Fix doubled word in doc comment by [@latent-9](https://github.com/latent-9) in [#1876](https://github.com/groue/GRDB.swift/pull/1876)
+- **Fixed**: Fix an accidentally quadratic behavior in SQLite statement compilation by [@groue](https://github.com/groue) and [@guidedways](https://github.com/guidedways) in [#1881](https://github.com/groue/GRDB.swift/pull/1881)
+- **Fixed**: Work around an SQLite bug in WAL snapshot ordering by [@groue](https://github.com/groue) and [@vburojevic](https://github.com/vburojevic) in [#1884](https://github.com/groue/GRDB.swift/pull/1884)
+- **Fixed**: Fix upsert for WITHOUT ROWID tables with an INTEGER primary key by [@nesevis](https://github.com/nesevis) in [#1879](https://github.com/groue/GRDB.swift/pull/1879)
+- **Fixed**: Support for statement recompilation after the columns are modified in the database schema by [@groue](https://github.com/groue) in [#1893](https://github.com/groue/GRDB.swift/pull/1893)
+- **Fixed**: Fix SharedValueObservation deadlock, ordering, and cancellation by [@groue](https://github.com/groue) in [#1894](https://github.com/groue/GRDB.swift/pull/1894)
+
## 7.11.1
Released June 18, 2026
diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec
index 8f09bd13e..fd7d2e77e 100644
--- a/GRDB.swift.podspec
+++ b/GRDB.swift.podspec
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
- s.version = '7.11.1'
+ s.version = '7.12.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
diff --git a/README.md b/README.md
index 77b40ec05..8e0e05217 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@
-**Latest release**: June 18, 2026 • [version 7.11.1](https://github.com/groue/GRDB.swift/tree/v7.11.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
+**Latest release**: November 1, 2026 • [version 7.12.0](https://github.com/groue/GRDB.swift/tree/v7.12.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ • SQLite 3.20.0+ • Swift 6.1+ / Xcode 16.3+
diff --git a/Support/Info.plist b/Support/Info.plist
index 1c52b68a4..e930908d3 100644
--- a/Support/Info.plist
+++ b/Support/Info.plist
@@ -15,7 +15,7 @@
CFBundlePackageType
FMWK
CFBundleShortVersionString
- 7.11.1
+ 7.12.0
CFBundleSignature
????
CFBundleVersion