From 3382280cc361afb031359b6c63d27bc3d6114da8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 10 Mar 2023 20:43:46 +0100 Subject: [PATCH 1/6] Statement.execute(arguments:) uses temporary bindings Inspired by @helje5 in https://hachyderm.io/@helge@mastodon.social/109978514220902036 Thank you!! Now, onto cursors! --- GRDB/Core/DatabaseValue.swift | 28 +++ GRDB/Core/DatabaseValueConvertible.swift | 2 +- GRDB/Core/Row.swift | 2 +- GRDB/Core/Statement.swift | 219 ++++++++++++++++-- GRDB/Core/StatementColumnConvertible.swift | 2 +- GRDB/Core/Support/Foundation/Data.swift | 17 ++ .../StandardLibrary/StandardLibrary.swift | 15 ++ .../Documentation.docc/Extension/Statement.md | 18 ++ GRDB/Record/FetchableRecord.swift | 2 +- Tests/GRDBTests/UpdateStatementTests.swift | 111 +++++++++ 10 files changed, 390 insertions(+), 26 deletions(-) diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 2ab122672..c806a08a3 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -188,6 +188,34 @@ extension DatabaseValue: StatementBinding { return data.bind(to: sqliteStatement, at: index) } } + + /// Calls the given closure after binding a statement argument. + /// + /// The binding is valid only during the execution of this method. + /// + /// - 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 { + switch storage { + case .null: + let code = sqlite3_bind_null(sqliteStatement, index) + try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement) + return try body() + case .int64(let int64): + let code = int64.bind(to: sqliteStatement, at: index) + try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement) + return try body() + case .double(let double): + let code = double.bind(to: sqliteStatement, at: index) + try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement) + return try body() + case .string(let 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) + } + } } extension DatabaseValue: Sendable { } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 64bc7800d..769e5b364 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -156,7 +156,7 @@ public final class DatabaseValueCursor: Databas } // Assume cursor is created for immediate iteration: reset and set arguments - try statement.reset(withArguments: arguments) + try statement.prepareExecution(withArguments: arguments) } deinit { diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 9e4c64a84..8c7c5cb29 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1366,7 +1366,7 @@ public final class RowCursor: DatabaseCursor { self._row = try Row(statement: statement).adapted(with: adapter, layout: statement) // Assume cursor is created for immediate iteration: reset and set arguments - try statement.reset(withArguments: arguments) + try statement.prepareExecution(withArguments: arguments) } deinit { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 531f826b4..f9c56d2fc 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -170,8 +170,55 @@ public final class Statement { // MARK: Arguments - private var argumentsNeedValidation = true + /// Whether arguments are valid and bound inside the SQLite statement. + /// + /// If true, arguments are considered valid, and they are bound in + /// the SQLite statement: + /// + /// - **Valid**: Arguments match the statement expectations, or the user has + /// called ``setUncheckedArguments(_:)``. + /// - **Bound**: The SQLite bindings are set. String and blob arguments + /// are bound with SQLITE_TRANSIENT (copied and managed by SQLite). + /// + /// When false, arguments have not been validated yet, or they are + /// not bound. + /// + /// - Not validated yet: this is the initial default (non-validated + /// empty arguments) + /// + /// ```swift + /// // Default arguments are empty, argumentsAreValidAndBound is + /// // false. The statement needs one argument. + /// let statement = try db.makeStatement(sql: """ + /// INSERT INTO t VALUES (?) + /// """) + /// + /// // Because argumentsAreValidAndBound is false, we validate the + /// // empty arguments, and throw SQLITE_MISUSE: wrong number + /// // of statement arguments. + /// try statement.execute() + /// ``` + /// + /// - Not bound: this is the case after we have performed an optimized + /// execution with temporary bindings that avoid copying strings + /// and blobs: + /// + /// ```swift + /// let statement = try db.makeStatement(sql: """ + /// INSERT INTO t VALUES (?) + /// """) + /// // Arguments are set, and execution is performed with + /// // temporary bindings. + /// try statement.execute(arguments: ["Hello"]) + /// // <- Here statement.arguments is ["Hello"] + /// // <- Here statement.argumentsAreValidAndBound is false + /// ``` + /// + /// See `withArguments(_:do:)`. + private var argumentsAreValidAndBound = false + /// The statement arguments. They may be bound, or not, in the SQLite + /// statement. See `argumentsAreValidAndBound`. private var _arguments = StatementArguments() lazy var sqliteArgumentCount: Int = { @@ -247,10 +294,10 @@ public final class Statement { /// statement.setUncheckedArguments([1]) /// ``` public func setUncheckedArguments(_ arguments: StatementArguments) { - _arguments = arguments - argumentsNeedValidation = false - + // Reset and bind arguments try! reset() + _arguments = arguments + argumentsAreValidAndBound = true clearBindings() var valuesIterator = arguments.values.makeIterator() @@ -288,16 +335,43 @@ public final class Statement { var consumedArguments = arguments let bindings = try consumedArguments.extractBindings(forStatement: self, allowingRemainingValues: false) - // Apply - _arguments = arguments - argumentsNeedValidation = false + // Reset and bind arguments try reset() + _arguments = arguments + argumentsAreValidAndBound = true clearBindings() + for (index, dbValue) in zip(CInt(1)..., bindings) { bind(dbValue, at: index) } } + /// Resets, sets arguments, and calls the given closure after performing + /// temporary bindings that avoid copying strings and blobs. + /// + /// The bindings are valid only during the execution of this method. + /// After it returns, the SQLite statement bindings are cleared (but the + /// statement arguments are set). + func withArguments(_ arguments: StatementArguments, do body: () throws -> T) throws -> T { + // Validate + var consumedArguments = arguments + let bindings = try consumedArguments.extractBindings(forStatement: self, allowingRemainingValues: false) + + // Reset and bind arguments (temporarily) + try reset() + _arguments = arguments + argumentsAreValidAndBound = false + clearBindings() + + defer { + // Don't leave the SQLite statement in an invalid state + // (temporary bindings that point to undefined memory). + clearBindings() + } + + return try withBindings(bindings, to: sqliteStatement, do: body) + } + // 1-based index func bind(_ value: some StatementBinding, at index: CInt) { let code = value.bind(to: sqliteStatement, at: index) @@ -330,16 +404,44 @@ public final class Statement { } } - func reset(withArguments arguments: StatementArguments?) throws { - // Force arguments validity: it is a programmer error to provide - // arguments that do not match the statement. - if let arguments { - try setArguments(arguments) // calls reset() - } else if argumentsNeedValidation { + /// Convenience method that resets, sets arguments if needed, and checks + /// arguments validity. + /// + /// - parameter newArguments: if not nil, this method sets arguments. + func prepareExecution(withArguments newArguments: StatementArguments? = nil) throws { + if let newArguments { + try setArguments(newArguments) // calls reset() + return + } + + if argumentsAreValidAndBound { try reset() - try validateArguments(self.arguments) } else { - try reset() + // Arguments needs to be validated, or bound. + if arguments.isEmpty { + // Only reset and perform validation. + try reset() + try validateArguments(arguments) + } else { + // The `setArguments` method binds and validates, and that's + // exactly what we want to do. + // + // To get there, perform statement.execute() after + // statement.execute(arguments:): + // + // // Step 1 + // // Optimized execution with temporary bindings in order + // // to avoid copying strings and blobs: after execution, + // // arguments are set, but bindings have been cleared, + // // and argumentsAreValidAndBound is false. + // try statement.execute(arguments: StatementArguments(person)!) + // + // // Step 2 (we are here). Stop using temporary + // // bindings because user explicitly opt ins for + // // permanent ones. + // try statement.execute() + try setArguments(arguments) // calls reset() + } } } @@ -360,23 +462,57 @@ public final class Statement { /// try createTableStatement.execute() /// /// // Statement with argument - /// let insertStatement = try db.makeStatement(sql: """ + /// let statement = try db.makeStatement(sql: """ /// INSERT INTO player (name) VALUES (?) /// """) /// /// // Set argument and execute - /// try insertStatement.setArguments(["Arthur"]) - /// try insertStatement.execute() + /// try statement.setArguments(["Arthur"]) + /// try statement.execute() /// /// // Set argument and execute in one shot - /// try insertStatement.execute(arguments: ["Barbara"]) + /// try statement.execute(arguments: ["Barbara"]) /// } /// ``` /// + /// When arguments are set at the moment of execution, with an non-nil + /// `arguments` parameter, it is assumed that the statement won't be + /// reused with the same arguments: execution is performed with + /// temporary SQLite bindings that avoid copying strings and blobs + /// arguments. Compare: + /// + /// ```swift + /// // Set argument and execute in one shot, + /// // without copying the string. + /// try statement.execute(arguments: ["Barbara"]) + /// + /// // Set argument (copy the string), and execute. + /// try statement.setArguments(["Arthur"]) + /// try statement.execute() + /// ``` + /// + /// Both techniques have the same results, but when you care about + /// performances, monitor your application in order to make the + /// best choice. + /// /// - parameter arguments: Optional statement arguments. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func execute(arguments: StatementArguments? = nil) throws { - try reset(withArguments: arguments) + if let arguments { + // Assume that the statement won't be reused with the same + // arguments, and perform an optimized execution with temporary + // bindings in order to avoid copying strings and blobs. + try reset() + try withArguments(arguments) { + try executeAllSteps() + } + } else { + try prepareExecution() + try executeAllSteps() + } + } + + private func executeAllSteps() throws { try database.statementWillExecute(self) // Iterate all rows, since they may execute side effects. @@ -597,7 +733,7 @@ final class StatementCursor: DatabaseCursor { self._statement = statement // Assume cursor is created for immediate iteration: reset and set arguments - try statement.reset(withArguments: arguments) + try statement.prepareExecution(withArguments: arguments) } deinit { @@ -642,11 +778,50 @@ public protocol StatementBinding { /// Binds a statement argument. /// /// - parameter sqliteStatement: An SQLite statement. - /// - parameter index: 1-based index to statement arguments + /// - parameter index: 1-based index to statement arguments. /// - returns: the code returned by the `sqlite3_bind_xxx` function. func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt } +/// Helper function for `withBinding(to:at:do:)` methods. +func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatement) throws { + if code == SQLITE_OK { return } + let message = String(cString: sqlite3_errmsg(sqlite3_db_handle(sqliteStatement))) + let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement + throw DatabaseError(resultCode: code, message: message, sql: sql) +} + +/// Calls the given closure after performing temporary bindings that avoid +/// copying strings and blobs. +/// +/// The bindings are valid only during the execution of this method. +/// +/// - parameter bindings: The bindings +/// - parameter sqliteStatement: The SQLite statement +/// - parameter index: The index of the first binding. +/// - parameter body: The closure to execute when arguments are bound. +@usableFromInline +func withBindings( + _ bindings: C, + to sqliteStatement: SQLiteStatement, + from index: CInt = 1, + do body: () throws -> T) +throws -> T +where C: Collection, C.Element == DatabaseValue +{ + guard let binding = bindings.first else { + return try body() + } + + return try binding.withBinding(to: sqliteStatement, at: index) { + try withBindings( + bindings.dropFirst(), + to: sqliteStatement, + from: index + 1, + do: body) + } +} + // MARK: - StatementArguments /// An instance of `StatementArguments` provides the values for argument diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 87efd16f1..27ee208b6 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -223,7 +223,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible } // Assume cursor is created for immediate iteration: reset and set arguments - try statement.reset(withArguments: arguments) + try statement.prepareExecution(withArguments: arguments) } deinit { diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 21b647ae5..6827b71d9 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -42,6 +42,23 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible { sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT) } } + + /// Calls the given closure after binding a statement argument. + /// + /// The binding is valid only during the execution of this method. + /// + /// - 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 withUnsafeBytes { + let code = sqlite3_bind_blob( + sqliteStatement, index, + $0.baseAddress, CInt($0.count), nil /* SQLITE_STATIC */) + try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement) + return try body() + } + } } // MARK: - Conversions diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index d3528bbca..021beb492 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -610,6 +610,21 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible { public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT) } + + /// Calls the given closure after binding a statement argument. + /// + /// The binding is valid only during the execution of this method. + /// + /// - 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 */) + try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement) + return try body() + } + } } diff --git a/GRDB/Documentation.docc/Extension/Statement.md b/GRDB/Documentation.docc/Extension/Statement.md index 35c039f82..332524aef 100644 --- a/GRDB/Documentation.docc/Extension/Statement.md +++ b/GRDB/Documentation.docc/Extension/Statement.md @@ -68,6 +68,24 @@ let player = try Player.fetchOne(selectStatement, arguments: ["Arthur"]) > Note: A prepared statement that has failed with an error can not be recovered. Create a new instance, or use a cached statement as described below. +> Tip: When you look after the best performance, take care about a difference between setting the arguments before execution, and setting the arguments at the moment of execution: +> +> ```swift +> // First option +> try statement.setArguments(...) +> try statement.execute() +> +> // Second option +> try statement.execute(arguments: ...) +> ``` +> +> Both perform exactly the same action, and most applications should not care about the difference. Yet: +> +> - `setArguments(_:)` performs a copy of string and blob arguments. It uses the low-level [`SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html) option, and fits well the reuse of a given statement with the same arguments. +> - `execute(arguments:)` avoids a temporary allocation for string and blob arguments. It uses the low-level [`SQLITE_STATIC`](https://www.sqlite.org/c3ref/c_static.html) option, and fits well the reuse of a given statement with various arguments. +> +> Don't make a blind choice, and monitor your app performance if it really matters! + ## Caching Prepared Statements When the same query will be used several times in the lifetime of an application, one may feel a natural desire to cache prepared statements. diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 58eb44e14..9c5bfe34a 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -807,7 +807,7 @@ public final class RecordCursor: DatabaseCursor { _row = try Row(statement: statement).adapted(with: adapter, layout: statement) // Assume cursor is created for immediate iteration: reset and set arguments - try statement.reset(withArguments: arguments) + try statement.prepareExecution(withArguments: arguments) } deinit { diff --git a/Tests/GRDBTests/UpdateStatementTests.swift b/Tests/GRDBTests/UpdateStatementTests.swift index 0db27cf65..82f094c6d 100644 --- a/Tests/GRDBTests/UpdateStatementTests.swift +++ b/Tests/GRDBTests/UpdateStatementTests.swift @@ -441,4 +441,115 @@ class UpdateStatementTests : GRDBTestCase { XCTAssertEqual(value, 3) } } + + // To be compared with testTemporaryBindings() and testNonTemporaryBindings() + func testArgumentsReuse() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(literal: """ + CREATE TABLE t(a); + """) + + func test(value: some DatabaseValueConvertible) throws { + defer { try! db.execute(sql: "DELETE FROM t") } + + // Execute with temporary bindings + let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (?)") + try statement.execute(arguments: [value]) + + // Execute with non temporary bindings + try statement.execute() + + // Since bindings are not temporary, they are not cleared, + // so insert the value again. + sqlite3_reset(statement.sqliteStatement) + sqlite3_step(statement.sqliteStatement) + sqlite3_reset(statement.sqliteStatement) + + // Test that we have inserted the value thrice. + try XCTAssertEqual( + DatabaseValue.fetchSet(db, sql: "SELECT a FROM t"), + [value.databaseValue, value.databaseValue, value.databaseValue]) + } + + try test(value: "Foo") + try test(value: "") + try test(value: "Hello".data(using: .utf8)!) + try test(value: Data()) + try test(value: 42) + try test(value: 1.23) + } + } + + // To be compared with testNonTemporaryBindings() and testArgumentsReuse() + func testTemporaryBindings() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(literal: """ + CREATE TABLE t(a); + """) + + func test(value: some DatabaseValueConvertible) throws { + defer { try! db.execute(sql: "DELETE FROM t") } + + // Execute with temporary bindings + let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (?)") + try statement.execute(arguments: [value]) + + // Since bindings were temporary, and cleared, we now insert NULL + sqlite3_reset(statement.sqliteStatement) + sqlite3_step(statement.sqliteStatement) + sqlite3_reset(statement.sqliteStatement) + + // Test that we have inserted the value, and NULL + try XCTAssertEqual( + DatabaseValue.fetchSet(db, sql: "SELECT a FROM t"), + [value.databaseValue, .null]) + } + + try test(value: "Foo") + try test(value: "") + try test(value: "Hello".data(using: .utf8)!) + try test(value: Data()) + try test(value: 42) + try test(value: 1.23) + } + } + + // To be compared with testTemporaryBindings() and testArgumentsReuse() + func testNonTemporaryBindings() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(literal: """ + CREATE TABLE t(a); + """) + + func test(value: some DatabaseValueConvertible) throws { + defer { try! db.execute(sql: "DELETE FROM t") } + + // Execute with non temporary bindings + let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (?)") + try statement.setArguments([value]) + try statement.execute() + + // Since bindings are not temporary, they are not cleared, + // so insert the value again. + sqlite3_reset(statement.sqliteStatement) + sqlite3_step(statement.sqliteStatement) + sqlite3_reset(statement.sqliteStatement) + + // Test that we have inserted the value twice. + try XCTAssertEqual( + DatabaseValue.fetchSet(db, sql: "SELECT a FROM t"), + [value.databaseValue, value.databaseValue]) + } + + try test(value: "Foo") + try test(value: "") + try test(value: "Hello".data(using: .utf8)!) + try test(value: Data()) + try test(value: 42) + try test(value: 1.23) + } + } } From 6a24d835d3a7bb754c39535199f519d58ff04a69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 10 Mar 2023 22:02:22 +0100 Subject: [PATCH 2/6] Performance tests for various statement arguments strategies --- .../GRDBPerformance/ArgumentsTests.swift | 113 ++++++++++++++++++ .../GRDBPerformance.xcodeproj/project.pbxproj | 8 +- 2 files changed, 119 insertions(+), 2 deletions(-) create mode 100644 Tests/Performance/GRDBPerformance/ArgumentsTests.swift diff --git a/Tests/Performance/GRDBPerformance/ArgumentsTests.swift b/Tests/Performance/GRDBPerformance/ArgumentsTests.swift new file mode 100644 index 000000000..ec9ae88df --- /dev/null +++ b/Tests/Performance/GRDBPerformance/ArgumentsTests.swift @@ -0,0 +1,113 @@ +import XCTest +import GRDB + +class ArgumentsTests: 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." + + var dbDirectoryPath: String! + var dbQueue: DatabaseQueue! + + override func setUpWithError() throws { + let dbDirectoryName = "ArgumentsTests-\(ProcessInfo.processInfo.globallyUniqueString)" + dbDirectoryPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(dbDirectoryName) + try FileManager.default.createDirectory(atPath: dbDirectoryPath, withIntermediateDirectories: true) + let dbPath = (dbDirectoryPath as NSString).appendingPathComponent("db.sqlite") + dbQueue = try DatabaseQueue(path: dbPath) + } + + override func tearDownWithError() throws { + dbQueue = nil + try FileManager.default.removeItem(atPath: dbDirectoryPath) + } + + func test_shortString_legacy_performance_() throws { + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a)") + + let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)") + let arguments: StatementArguments = [Self.shortString] + measure { + for _ in 0..<1_000_000 { + // Simulate old implementation of statement.execute(arguments: arguments) + try! statement.setArguments(arguments) + try! statement.execute() + } + } + } + } + + func test_shortString_SQLITE_STATIC_performance() throws { + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a)") + + let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)") + let arguments: StatementArguments = [Self.shortString] + measure { + for _ in 0..<1_000_000 { + try! statement.execute(arguments: arguments) + } + } + } + } + + func test_shortString_SQLITE_TRANSIENT_performance() throws { + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a)") + + let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)") + let arguments: StatementArguments = [Self.shortString] + try statement.setArguments(arguments) + measure { + for _ in 0..<1_000_000 { + try! statement.execute() + } + } + } + } + + func test_longString_legacy_performance_() throws { + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a)") + + let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)") + let arguments: StatementArguments = [Self.longString] + measure { + for _ in 0..<1_000_000 { + // Simulate old implementation of statement.execute(arguments: arguments) + try! statement.setArguments(arguments) + try! statement.execute() + } + } + } + } + + func test_longString_SQLITE_STATIC_performance() throws { + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a)") + + let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)") + let arguments: StatementArguments = [Self.longString] + measure { + for _ in 0..<1_000_000 { + try! statement.execute(arguments: arguments) + } + } + } + } + + func test_longString_SQLITE_TRANSIENT_performance() throws { + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a)") + + let statement = try db.makeStatement(sql: "INSERT INTO t(a) VALUES (?)") + let arguments: StatementArguments = [Self.longString] + try! statement.setArguments(arguments) + measure { + for _ in 0..<1_000_000 { + try! statement.execute() + } + } + } + } +} diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj index d09feca28..d15100f22 100755 --- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj +++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj @@ -31,6 +31,7 @@ 5690AFDC212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */; }; 56A3FEA827A85F4800B0292E /* Realm in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA727A85F4800B0292E /* Realm */; }; 56A3FEAA27A85F4800B0292E /* RealmSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA927A85F4800B0292E /* RealmSwift */; }; + 56A6F4AC29BBC8E200E22662 /* ArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A6F4AB29BBC8E200E22662 /* ArgumentsTests.swift */; }; 56B6D0E52618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; }; 56B6D0E62618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; }; 56B6D0EA2618C00C003CC455 /* InsertRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E92618C00C003CC455 /* InsertRecordOptimizedTests.swift */; }; @@ -97,6 +98,7 @@ 567986AD23A378CD0076902D /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = ""; }; 5690AFD72120589A001530EA /* InsertRecordEncodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordEncodableTests.swift; sourceTree = ""; }; 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordDecodableTests.swift; sourceTree = ""; }; + 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 = ""; }; 56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordClassTests.swift; sourceTree = ""; }; @@ -143,7 +145,7 @@ isa = PBXGroup; children = ( 567986B923A378CD0076902D /* GRDB.framework */, - 567986BB23A378CD0076902D /* GRDBOSXTests.xctest */, + 567986BB23A378CD0076902D /* GRDBTests.xctest */, ); name = Products; sourceTree = ""; @@ -160,6 +162,7 @@ children = ( 56BB862D1BA98933001F9168 /* GRDBPerformanceComparisonTests-Bridging.h */, 56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */, + 56A6F4AB29BBC8E200E22662 /* ArgumentsTests.swift */, 567071FA208A509C006AD95A /* DateParsingTests.swift */, 56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */, 56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */, @@ -307,7 +310,7 @@ remoteRef = 567986B823A378CD0076902D /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 567986BB23A378CD0076902D /* GRDBOSXTests.xctest */ = { + 567986BB23A378CD0076902D /* GRDBTests.xctest */ = { isa = PBXReferenceProxy; fileType = wrapper.cfbundle; path = GRDBTests.xctest; @@ -346,6 +349,7 @@ 56DE7B281C41302500861EB8 /* FetchNamedValuesTests.swift in Sources */, 5690AFD82120589A001530EA /* InsertRecordEncodableTests.swift in Sources */, 56B6D0EA2618C00C003CC455 /* InsertRecordOptimizedTests.swift in Sources */, + 56A6F4AC29BBC8E200E22662 /* ArgumentsTests.swift in Sources */, 5690AFDB212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */, 56D507831F6D7B2E00AE1C5B /* InsertRecordStructTests.swift in Sources */, 56DE7B241C412F7E00861EB8 /* InsertPositionalValuesTests.swift in Sources */, From 0c333b6e22e2c97ef80bf4973be875162945197c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 11 Mar 2023 11:20:55 +0100 Subject: [PATCH 3/6] Performance improvements --- GRDB/Core/Statement.swift | 43 +++++++++++++++++++++----------------- GRDB/Utils/LockedBox.swift | 2 ++ 2 files changed, 26 insertions(+), 19 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index f9c56d2fc..43b782fa3 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -225,13 +225,13 @@ public final class Statement { Int(sqlite3_bind_parameter_count(self.sqliteStatement)) }() - // Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)" + // Returns ["id", nil, "name"] for "INSERT INTO table VALUES (:id, ?, :name)" fileprivate lazy var sqliteArgumentNames: [String?] = { - (0.. [DatabaseValue] { - let initialValuesCount = values.count + var iterator = values.makeIterator() + var consumedValuesCount = 0 let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in if let argumentName { if let dbValue = namedValues[argumentName] { return dbValue - } else if values.isEmpty { + } else if let value = iterator.next() { + consumedValuesCount += 1 + return value + } else { throw DatabaseError( resultCode: .SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql) - } else { - return values.removeFirst() } + } else if let value = iterator.next() { + consumedValuesCount += 1 + return value } else { - if values.isEmpty { - throw DatabaseError( - resultCode: .SQLITE_MISUSE, - message: "wrong number of statement arguments: \(initialValuesCount)", - sql: statement.sql) - } else { - return values.removeFirst() - } + throw DatabaseError( + resultCode: .SQLITE_MISUSE, + message: "wrong number of statement arguments: \(values.count)", + sql: statement.sql) } } - if !allowingRemainingValues && !values.isEmpty { + if !allowingRemainingValues && iterator.next() != nil { throw DatabaseError( resultCode: .SQLITE_MISUSE, - message: "wrong number of statement arguments: \(initialValuesCount)", + message: "wrong number of statement arguments: \(values.count)", sql: statement.sql) } + if consumedValuesCount == values.count { + values.removeAll() + } else { + values = Array(values[consumedValuesCount...]) + } return bindings } } diff --git a/GRDB/Utils/LockedBox.swift b/GRDB/Utils/LockedBox.swift index 79388ae12..aef512604 100644 --- a/GRDB/Utils/LockedBox.swift +++ b/GRDB/Utils/LockedBox.swift @@ -26,6 +26,8 @@ final class LockedBox { /// $count.read { print($0) } /// /// - parameter block: A closure that accepts the value. + @inline(__always) + @usableFromInline func read(_ block: (T) throws -> U) rethrows -> U { lock.lock() defer { lock.unlock() } From 1d5d1aea6887c56aa3fa3086359216cfe8e96957 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 11 Mar 2023 11:38:21 +0100 Subject: [PATCH 4/6] Upgrade performance tests dependencies --- .../xcshareddata/swiftpm/Package.resolved | 14 +++++++------- Tests/generatePerformanceReport.rb | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 871798b7e..f6c6fec34 100644 --- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -12,10 +12,10 @@ { "identity" : "realm-core", "kind" : "remoteSourceControl", - "location" : "https://github.com/realm/realm-core", + "location" : "https://github.com/realm/realm-core.git", "state" : { - "revision" : "3c4b86da569368c4ee5ccca2a112d511cc6fa936", - "version" : "12.11.0" + "revision" : "dd91f5f967c4ae89c37e24ab2a0315c31106648f", + "version" : "13.6.0" } }, { @@ -23,8 +23,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/realm/realm-swift.git", "state" : { - "revision" : "dc1672b3011eb992ce95db4feec83cd897626a16", - "version" : "10.32.1" + "revision" : "8ac6fe1aa5d0fb0100062d80863416a4d70de8ca", + "version" : "10.37.0" } }, { @@ -32,8 +32,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/stephencelis/SQLite.swift.git", "state" : { - "revision" : "4d543d811ee644fa4cc4bfa0be996b4dd6ba0f54", - "version" : "0.13.3" + "revision" : "7a2e3cd27de56f6d396e84f63beefd0267b55ccb", + "version" : "0.14.1" } } ], diff --git a/Tests/generatePerformanceReport.rb b/Tests/generatePerformanceReport.rb index ec8ae5286..6ec3bab05 100755 --- a/Tests/generatePerformanceReport.rb +++ b/Tests/generatePerformanceReport.rb @@ -40,7 +40,7 @@ BUILD_ROOT = $1 # DERIVED_DATA tmp = BUILD_ROOT -while !File.exists?(File.join(tmp, 'SourcePackages')) +while !File.exist?(File.join(tmp, 'SourcePackages')) parent = File.dirname(tmp) exit 1 if tmp == parent tmp = parent From 0169e340dc501a77c6669591bd5e554d0a1a0be4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 11 Mar 2023 16:40:47 +0100 Subject: [PATCH 5/6] CHANGELOG --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bba679f7..16c9b5200 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,8 +108,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release +- **New**: [#1348](https://github.com/groue/GRDB.swift/pull/1348) by [@groue](https://github.com/groue): SQLite argument binding optimization - **New**: `FTS5.api(db)` returns a pointer to the `fts5_api` structure, useful for low-level [FTS5 customization](https://www.sqlite.org/fts5.html#extending_fts5). -- **Documentation Updates**: Moved more README chapters into DocC, or enhanced DocC articles: +- **Documentation Updates**: Moved more README chapters into DocC, enhanced and extended DocC articles: - [Database Connections](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections) - [Prepared Statements](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement) - [DatabaseValueConvertible](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible) From b4e851aa49bc1fc8f825756277d532e2dab1fab9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 12 Mar 2023 10:59:38 +0100 Subject: [PATCH 6/6] More statement arguments documentation --- GRDB/Core/Statement.swift | 76 ++++++++++++++----- .../Documentation.docc/Extension/Statement.md | 4 +- 2 files changed, 59 insertions(+), 21 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 43b782fa3..31c48597a 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -236,6 +236,34 @@ public final class Statement { }() /// The statement arguments. + /// + /// For example: + /// + /// ```swift + /// // This statement expects two arguments + /// let statement = try db.makeUpdateArgument(sql: """ + /// INSERT INTO player (id, name) VALUES (?, ?) + /// """) + /// + /// // Set arguments + /// statement.arguments = [1, "Arthur"] + /// + /// // Prints [1, "Arthur"] + /// print(statement.arguments) + /// ``` + /// + /// If is a programmer error to set arguments that do not provide all + /// values expected by the statement: + /// + /// ```swift + /// // Fatal error + /// statement.arguments = [1] + /// statement.arguments = [1, "Arthur", Date()] + /// ``` + /// + /// Prefer ``setArguments(_:)`` when you are not sure that + /// arguments match, because it throws an error instead of raising a + /// fatal error. public var arguments: StatementArguments { get { _arguments } set { @@ -245,12 +273,13 @@ public final class Statement { } } - /// Throws a ``DatabaseError`` of code `SQLITE_ERROR` if arguments don't - /// fill all statement arguments. + /// Throws a ``DatabaseError`` of code `SQLITE_ERROR` if the provided + /// arguments do not provide all values expected by the statement. /// /// For example: /// /// ```swift + /// // This statement expects two arguments /// let statement = try db.makeUpdateArgument(sql: """ /// INSERT INTO player (id, name) VALUES (?, ?) /// """) @@ -259,7 +288,8 @@ public final class Statement { /// statement.validateArguments([1, "Arthur"]) /// /// // Throws - /// statement.validateArguments([1]) + /// try statement.setArguments([1]) + /// try statement.setArguments([1, "Arthur", Date()]) /// ``` /// /// See also ``setArguments(_:)``. @@ -272,12 +302,13 @@ public final class Statement { /// Set arguments without any validation. Trades safety for performance. /// - /// Only call this method if you are sure input arguments match all expected - /// arguments of the statement. + /// Only call this method if you are sure input arguments provide all + /// values expected by the statement. /// /// For example: /// /// ```swift + /// // This statement expects two arguments /// let statement = try db.makeUpdateArgument(sql: """ /// INSERT INTO player (id, name) VALUES (?, ?) /// """) @@ -286,12 +317,13 @@ public final class Statement { /// statement.setUncheckedArguments([1, "Arthur"]) /// /// // OK - /// let arguments: StatementArguments = ... // some untrusted arguments + /// let arguments = ... // some untrusted arguments /// try statement.validateArguments(arguments) /// statement.setUncheckedArguments(arguments) /// /// // NOT OK /// statement.setUncheckedArguments([1]) + /// statement.setUncheckedArguments([1, "Arthur", Date()]) /// ``` public func setUncheckedArguments(_ arguments: StatementArguments) { // Reset and bind arguments @@ -310,14 +342,16 @@ public final class Statement { } } - /// Sets the statement arguments. + /// Validates and sets the statement arguments. /// /// This method throws a ``DatabaseError`` of code `SQLITE_MISUSE` if - /// arguments don't fill all statement arguments. + /// the provided arguments do not provide all values expected by + /// the statement. /// /// For example: /// /// ```swift + /// // This statement expects two arguments /// let statement = try db.makeUpdateArgument(sql: """ /// INSERT INTO player (id, name) VALUES (?, ?) /// """) @@ -327,6 +361,7 @@ public final class Statement { /// /// // Throws /// try statement.setArguments([1]) + /// try statement.setArguments([1, "Arthur", Date()]) /// ``` /// /// - throws: A ``DatabaseError`` if `arguments` don't fit the expected ones. @@ -450,17 +485,18 @@ public final class Statement { /// For example: /// /// ```swift - /// let dbQueue = try DatabaseQueue() /// try dbQueue.write { db in /// // Statement without argument - /// let createTableStatement = try db.makeStatement(sql: """ + /// let statement = try db.makeStatement(sql: """ /// CREATE TABLE player ( /// id INTEGER PRIMARY KEY AUTOINCREMENT, /// name TEXT NOT NULL /// ) /// """) - /// try createTableStatement.execute() + /// try statement.execute() + /// } /// + /// try dbQueue.write { db in /// // Statement with argument /// let statement = try db.makeStatement(sql: """ /// INSERT INTO player (name) VALUES (?) @@ -477,16 +513,18 @@ public final class Statement { /// /// When arguments are set at the moment of execution, with an non-nil /// `arguments` parameter, it is assumed that the statement won't be - /// reused with the same arguments: execution is performed with + /// reused with the same arguments. Execution is performed with /// temporary SQLite bindings that avoid copying strings and blobs - /// arguments. Compare: + /// arguments. + /// + /// For more information, see [`SQLITE_STATIC` and `SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html). + /// Compare: /// /// ```swift - /// // Set argument and execute in one shot, - /// // without copying the string. + /// // Uses SQLITE_STATIC /// try statement.execute(arguments: ["Barbara"]) /// - /// // Set argument (copy the string), and execute. + /// // Uses SQLITE_TRANSIENT /// try statement.setArguments(["Arthur"]) /// try statement.execute() /// ``` @@ -836,9 +874,9 @@ where C: Collection, C.Element == DatabaseValue /// - `@AAAA` (e.g. `@name`): named argument /// - `$AAAA` (e.g. `$name`): named argument /// -/// GRDB does not allow to distinguish between the `:AAAA`, `@AAAA`, and `$AAAA` -/// syntaxes. You are encouraged to write named arguments with a -/// colon prefix: `:name`. +/// All forms are supported, but GRDB does not allow to distinguish between +/// the `:AAAA`, `@AAAA`, and `$AAAA` syntaxes. You are encouraged to write +/// named arguments with a colon prefix: `:name`. /// /// ## Positional Arguments /// diff --git a/GRDB/Documentation.docc/Extension/Statement.md b/GRDB/Documentation.docc/Extension/Statement.md index 332524aef..0491f43db 100644 --- a/GRDB/Documentation.docc/Extension/Statement.md +++ b/GRDB/Documentation.docc/Extension/Statement.md @@ -81,8 +81,8 @@ let player = try Player.fetchOne(selectStatement, arguments: ["Arthur"]) > > Both perform exactly the same action, and most applications should not care about the difference. Yet: > -> - `setArguments(_:)` performs a copy of string and blob arguments. It uses the low-level [`SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html) option, and fits well the reuse of a given statement with the same arguments. -> - `execute(arguments:)` avoids a temporary allocation for string and blob arguments. It uses the low-level [`SQLITE_STATIC`](https://www.sqlite.org/c3ref/c_static.html) option, and fits well the reuse of a given statement with various arguments. +> - ``setArguments(_:)`` performs a copy of string and blob arguments. It uses the low-level [`SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html) option, and fits well the reuse of a given statement with the same arguments. +> - ``execute(arguments:)`` avoids a temporary allocation for string and blob arguments. It uses the low-level [`SQLITE_STATIC`](https://www.sqlite.org/c3ref/c_static.html) option, and fits well the reuse of a given statement with various arguments. > > Don't make a blind choice, and monitor your app performance if it really matters!