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 01/10] 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 02/10] 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 03/10] 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 04/10] 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 05/10] 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 06/10] 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 07/10] 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 08/10] 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 09/10] 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 10/10] 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)) + } + } + } }