Merge pull request #1348 from groue/dev/argument-optimization

SQLite argument binding optimization
This commit is contained in:
Gwendal Roué authored and GitHub committed 2023-03-12 11:56:57 +01:00
commit db165581ea
16 files changed
+596 -69

No files matched your search

+2 -1
View File
@@ -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)
+28
View File
@@ -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<T>(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 { }
+1 -1
View File
@@ -156,7 +156,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
}
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.reset(withArguments: arguments)
try statement.prepareExecution(withArguments: arguments)
}
deinit {
+1 -1
View File
@@ -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 {
+272 -54
View File
@@ -170,25 +170,100 @@ 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 = {
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..<CInt(self.sqliteArgumentCount)).map {
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, $0 + 1) else {
(1..<CInt(sqliteArgumentCount + 1)).map {
guard let cString = sqlite3_bind_parameter_name(sqliteStatement, $0) else {
return nil
}
return String(String(cString: cString).dropFirst()) // Drop initial ":", "@", "$"
return String(cString: cString + 1) // Drop initial ":", "@", "$"
}
}()
/// 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 {
@@ -198,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 (?, ?)
/// """)
@@ -212,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(_:)``.
@@ -225,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 (?, ?)
/// """)
@@ -239,18 +317,19 @@ 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) {
_arguments = arguments
argumentsNeedValidation = false
// Reset and bind arguments
try! reset()
_arguments = arguments
argumentsAreValidAndBound = true
clearBindings()
var valuesIterator = arguments.values.makeIterator()
@@ -263,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 (?, ?)
/// """)
@@ -280,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.
@@ -288,16 +370,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<T>(_ 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 +439,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()
}
}
}
@@ -348,35 +485,71 @@ 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 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.
///
/// For more information, see [`SQLITE_STATIC` and `SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html).
/// Compare:
///
/// ```swift
/// // Uses SQLITE_STATIC
/// try statement.execute(arguments: ["Barbara"])
///
/// // Uses SQLITE_TRANSIENT
/// 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 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 +770,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 +815,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<C, T>(
_ 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
@@ -662,9 +874,9 @@ public protocol StatementBinding {
/// - `@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
///
@@ -1083,36 +1295,42 @@ public struct StatementArguments: Hashable {
allowingRemainingValues: Bool)
throws -> [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
}
}
+1 -1
View File
@@ -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 {
+17
View File
@@ -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<T>(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
@@ -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<T>(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()
}
}
}
@@ -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.
+1 -1
View File
@@ -807,7 +807,7 @@ public final class RecordCursor<Record: FetchableRecord>: 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 {
+2
View File
@@ -26,6 +26,8 @@ final class LockedBox<T> {
/// $count.read { print($0) }
///
/// - parameter block: A closure that accepts the value.
@inline(__always)
@usableFromInline
func read<U>(_ block: (T) throws -> U) rethrows -> U {
lock.lock()
defer { lock.unlock() }
+111
View File
@@ -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)
}
}
}
@@ -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()
}
}
}
}
}
@@ -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 = "<group>"; };
5690AFD72120589A001530EA /* InsertRecordEncodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordEncodableTests.swift; sourceTree = "<group>"; };
5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordDecodableTests.swift; sourceTree = "<group>"; };
56A6F4AB29BBC8E200E22662 /* ArgumentsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArgumentsTests.swift; sourceTree = "<group>"; };
56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRecordOptimizedTests.swift; sourceTree = "<group>"; };
56B6D0E92618C00C003CC455 /* InsertRecordOptimizedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordOptimizedTests.swift; sourceTree = "<group>"; };
56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordClassTests.swift; sourceTree = "<group>"; };
@@ -143,7 +145,7 @@
isa = PBXGroup;
children = (
567986B923A378CD0076902D /* GRDB.framework */,
567986BB23A378CD0076902D /* GRDBOSXTests.xctest */,
567986BB23A378CD0076902D /* GRDBTests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -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 */,
@@ -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"
}
}
],
+1 -1
View File
@@ -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