Disable SQLITE_STATIC optimization when there are too many arguments

This commit is contained in:
Gwendal Roué committed 2023-03-13 19:33:52 +01:00
1 parent c22fc202a9
commit d5a41bd11b
4 files changed
+74 -22

No files matched your search

+4
View File
@@ -107,6 +107,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## Next Release
- **Fixed**: Avoid the risk for pathologically deep stack trace, or stack overflow, introduced by [#1348](https://github.com/groue/GRDB.swift/pull/1348).
## 6.9.1
Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.8.0...v6.9.1)
+21 -9
View File
@@ -513,18 +513,19 @@ 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
/// temporary SQLite bindings that avoid copying strings and blobs
/// arguments.
/// reused with the same arguments. When the number of arguments is
/// small, execution is performed with temporary SQLite bindings that
/// avoid copying strings and blobs arguments.
///
/// For more information, see [`SQLITE_STATIC` and `SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html).
/// Compare:
///
/// ```swift
/// // Uses SQLITE_STATIC
/// // Uses SQLITE_STATIC if there are few arguments,
/// // SQLITE_TRANSIENT otherwise.
/// try statement.execute(arguments: ["Barbara"])
///
/// // Uses SQLITE_TRANSIENT
/// // Always uses SQLITE_TRANSIENT
/// try statement.setArguments(["Arthur"])
/// try statement.execute()
/// ```
@@ -537,10 +538,21 @@ public final class Statement {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func execute(arguments: StatementArguments? = nil) throws {
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 withArguments(arguments) {
// Assume that the statement won't be reused with the same arguments.
//
// Avoid a stack overflow, and don't perform an unbounded nesting
// of `withBinding(to:at:do:)` methods: only use temporary bindings
// for less than 20 arguments. This number 20 is completely
// arbitrary!
// See <https://forums.swift.org/t/avoiding-stack-overflow-when-nesting-string-withcstring-how-to-handle-an-arbitrary-number-of-temp-values-in-general/63663>
if sqliteArgumentCount <= 20 {
// Perform an optimized execution with temporary bindings
// in order to avoid copying strings and blobs.
try withArguments(arguments) {
try executeAllSteps()
}
} else {
try setArguments(arguments)
try executeAllSteps()
}
} else {
@@ -82,7 +82,7 @@ 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.
> - ``execute(arguments:)`` avoids a temporary allocation for string and blob arguments if the number of arguments is small. Instead of `SQLITE_TRANSIENT`, it uses the low-level [`SQLITE_STATIC`](https://www.sqlite.org/c3ref/c_static.html) option. This 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!
+48 -12
View File
@@ -442,8 +442,9 @@ class UpdateStatementTests : GRDBTestCase {
}
}
// To be compared with testTemporaryBindings() and testNonTemporaryBindings()
func testArgumentsReuse() throws {
// MARK: - SQLITE_STATIC vs SQLITE_TRANSIENT
func test_SQLITE_STATIC_then_SQLITE_TRANSIENT() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(literal: """
@@ -453,11 +454,11 @@ class UpdateStatementTests : GRDBTestCase {
func test(value: some DatabaseValueConvertible) throws {
defer { try! db.execute(sql: "DELETE FROM t") }
// Execute with temporary bindings
// Execute with temporary bindings (SQLITE_STATIC)
let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (?)")
try statement.execute(arguments: [value])
// Execute with non temporary bindings
// Execute with non temporary bindings (SQLITE_TRANSIENT)
try statement.execute()
// Since bindings are not temporary, they are not cleared,
@@ -469,7 +470,7 @@ class UpdateStatementTests : GRDBTestCase {
// Test that we have inserted the value thrice.
try XCTAssertEqual(
DatabaseValue.fetchSet(db, sql: "SELECT a FROM t"),
[value.databaseValue, value.databaseValue, value.databaseValue])
[value.databaseValue])
}
try test(value: "Foo")
@@ -481,8 +482,7 @@ class UpdateStatementTests : GRDBTestCase {
}
}
// To be compared with testNonTemporaryBindings() and testArgumentsReuse()
func testTemporaryBindings() throws {
func test_SQLITE_STATIC() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(literal: """
@@ -492,7 +492,7 @@ class UpdateStatementTests : GRDBTestCase {
func test(value: some DatabaseValueConvertible) throws {
defer { try! db.execute(sql: "DELETE FROM t") }
// Execute with temporary bindings
// Execute with temporary bindings (SQLITE_STATIC)
let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (?)")
try statement.execute(arguments: [value])
@@ -516,8 +516,44 @@ class UpdateStatementTests : GRDBTestCase {
}
}
// To be compared with testTemporaryBindings() and testArgumentsReuse()
func testNonTemporaryBindings() throws {
func test_SQLITE_TRANSIENT_due_to_high_number_of_arguments() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(literal: """
-- 21 columns
CREATE TABLE t(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u);
""")
func test(value: some DatabaseValueConvertible) throws {
defer { try! db.execute(sql: "DELETE FROM t") }
// Execute with non temporary bindings (SQLITE_TRANSIENT),
// because there are more than 20 arguments
let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (\(databaseQuestionMarks(count: 21)))")
try statement.execute(arguments: StatementArguments(Array(repeating: value, count: 21)))
// 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])
}
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)
}
}
func test_SQLITE_TRANSIENT() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(literal: """
@@ -527,7 +563,7 @@ class UpdateStatementTests : GRDBTestCase {
func test(value: some DatabaseValueConvertible) throws {
defer { try! db.execute(sql: "DELETE FROM t") }
// Execute with non temporary bindings
// Execute with non temporary bindings (SQLITE_TRANSIENT)
let statement = try db.makeStatement(sql: "INSERT INTO t VALUES (?)")
try statement.setArguments([value])
try statement.execute()
@@ -541,7 +577,7 @@ class UpdateStatementTests : GRDBTestCase {
// Test that we have inserted the value twice.
try XCTAssertEqual(
DatabaseValue.fetchSet(db, sql: "SELECT a FROM t"),
[value.databaseValue, value.databaseValue])
[value.databaseValue])
}
try test(value: "Foo")