mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-28 04:24:20 +00:00
Refactor Statement initializers
This commit is contained in:
1 parent
9c6879bd97
commit
2cdcdb9cd6
2 files changed
+136
-91
No files matched your search
+78
-43
@@ -712,7 +712,38 @@ extension Database {
|
||||
/// - returns: A SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
|
||||
return try SelectStatement(database: self, sql: sql, prepFlags: prepFlags)
|
||||
let observer = StatementCompilationObserver(self)
|
||||
observer.start()
|
||||
defer { observer.stop() }
|
||||
|
||||
var statement: SelectStatement? = nil
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
var remainingSQL = ""
|
||||
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
do {
|
||||
statement = try SelectStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
observer: observer)
|
||||
} catch is EmptyStatementError {
|
||||
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "empty statement", sql: sql, arguments: nil)
|
||||
}
|
||||
let remainingData = Data(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
|
||||
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
|
||||
deallocator: .none)
|
||||
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
guard remainingSQL.isEmpty else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
|
||||
}
|
||||
|
||||
return statement!
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
@@ -764,7 +795,38 @@ extension Database {
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
|
||||
return try UpdateStatement(database: self, sql: sql, prepFlags: prepFlags)
|
||||
let observer = StatementCompilationObserver(self)
|
||||
observer.start()
|
||||
defer { observer.stop() }
|
||||
|
||||
var statement: UpdateStatement? = nil
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
var remainingSQL = ""
|
||||
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
do {
|
||||
statement = try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
observer: observer)
|
||||
} catch is EmptyStatementError {
|
||||
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "empty statement", sql: sql, arguments: nil)
|
||||
}
|
||||
let remainingData = Data(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
|
||||
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
|
||||
deallocator: .none)
|
||||
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
guard remainingSQL.isEmpty else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
|
||||
}
|
||||
|
||||
return statement!
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
@@ -811,11 +873,8 @@ extension Database {
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws {
|
||||
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
|
||||
// It adds support for arguments.
|
||||
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
// The tricky part is to consume arguments as statements are executed.
|
||||
// It adds support for arguments, and the tricky part is to consume
|
||||
// arguments as statements are executed.
|
||||
//
|
||||
// Here we build two functions:
|
||||
// - consumeArguments returns arguments for a statement
|
||||
@@ -835,63 +894,39 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Execute statements
|
||||
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
var error: Error?
|
||||
|
||||
// During the execution of sqlite3_prepare_v2, the observer listens to
|
||||
// authorization callbacks in order to recognize "interesting"
|
||||
// statements. See updateStatementDidExecute().
|
||||
let observer = StatementCompilationObserver(self)
|
||||
observer.start()
|
||||
defer { observer.stop() }
|
||||
|
||||
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
let sqlEnd = sqlStart + sqlCodeUnits.count
|
||||
var statementStart = sqlStart
|
||||
while statementStart < sqlEnd - 1 {
|
||||
observer.reset()
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
let code = sqlite3_prepare_v2(sqliteConnection, statementStart, -1, &sqliteStatement, &statementEnd)
|
||||
guard code == SQLITE_OK else {
|
||||
error = DatabaseError(resultCode: code, message: lastErrorMessage, sql: sql)
|
||||
break
|
||||
}
|
||||
|
||||
guard sqliteStatement != nil else {
|
||||
// The remaining string contains only whitespace
|
||||
assert(String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: statementStart), count: statementEnd! - statementStart, deallocator: .none), encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
break
|
||||
}
|
||||
|
||||
do {
|
||||
let statement = UpdateStatement(
|
||||
let statement = try UpdateStatement(
|
||||
database: self,
|
||||
sqliteStatement: sqliteStatement!,
|
||||
invalidatesDatabaseSchemaCache: observer.invalidatesDatabaseSchemaCache,
|
||||
transactionStatementInfo: observer.transactionStatementInfo,
|
||||
databaseEventKinds: observer.databaseEventKinds)
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
observer: observer)
|
||||
|
||||
let arguments = try consumeArguments(statement)
|
||||
statement.unsafeSetArguments(arguments)
|
||||
try statement.execute()
|
||||
} catch let statementError {
|
||||
error = statementError
|
||||
|
||||
statementStart = statementEnd!
|
||||
} catch is EmptyStatementError {
|
||||
break
|
||||
}
|
||||
|
||||
statementStart = statementEnd!
|
||||
}
|
||||
}
|
||||
|
||||
observer.stop()
|
||||
|
||||
if let error = error {
|
||||
throw error
|
||||
}
|
||||
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
try! validateRemainingArguments() // throws if there are remaining arguments.
|
||||
|
||||
+58
-48
@@ -8,6 +8,10 @@ import Foundation
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
public typealias SQLiteStatement = OpaquePointer
|
||||
|
||||
/// An error emitted when one tries to compile an empty statement.
|
||||
struct EmptyStatementError : Error {
|
||||
}
|
||||
|
||||
/// A statement represents an SQL query.
|
||||
///
|
||||
/// It is the base class of UpdateStatement that executes *update statements*,
|
||||
@@ -27,53 +31,47 @@ public class Statement {
|
||||
/// The database
|
||||
unowned let database: Database
|
||||
|
||||
init(database: Database, sqliteStatement: SQLiteStatement) {
|
||||
self.database = database
|
||||
self.sqliteStatement = sqliteStatement
|
||||
}
|
||||
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
/// - parameter database: A database connection.
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
|
||||
/// containing SQL.
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - parameter observer: A StatementCompilationObserver
|
||||
fileprivate init(database: Database, sql: String, prepFlags: Int32, observer: StatementCompilationObserver) throws {
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32) throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
observer.start()
|
||||
defer { observer.stop() }
|
||||
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
var code: Int32 = 0
|
||||
var remainingSQL = ""
|
||||
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
var sqlEnd: UnsafePointer<Int8>? = nil
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE
|
||||
code = sqlite3_prepare_v3(database.sqliteConnection, sqlStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, &sqlEnd)
|
||||
#else
|
||||
code = sqlite3_prepare_v2(database.sqliteConnection, sqlStart, -1, &sqliteStatement, &sqlEnd)
|
||||
#endif
|
||||
let remainingData = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: sqlEnd!), count: sqlStart + sqlCodeUnits.count - sqlEnd! - 1, deallocator: .none)
|
||||
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE
|
||||
let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
|
||||
#else
|
||||
let code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, &statementEnd)
|
||||
#endif
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: String(cString: statementStart))
|
||||
}
|
||||
|
||||
guard remainingSQL.isEmpty else {
|
||||
sqlite3_finalize(sqliteStatement)
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
|
||||
guard let statement = sqliteStatement else {
|
||||
// Sanity check: verify that the string contains only whitespace
|
||||
assert(String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: statementStart), count: statementEnd.pointee! - statementStart, deallocator: .none), encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
|
||||
// I wish we could simply return nil, and make this initializer failable.
|
||||
//
|
||||
// Unfortunately, there is a Swift bug with failable+throwing initializers:
|
||||
// https://bugs.swift.org/browse/SR-6067
|
||||
//
|
||||
// We thus use sentinel error for empty statements.
|
||||
throw EmptyStatementError()
|
||||
}
|
||||
|
||||
self.database = database
|
||||
self.sqliteStatement = sqliteStatement!
|
||||
|
||||
self.sqliteStatement = statement
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -236,13 +234,23 @@ public final class SelectStatement : Statement {
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
/// - parameter database: A database connection.
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
|
||||
/// containing SQL.
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
init(database: Database, sql: String, prepFlags: Int32) throws {
|
||||
/// - observer: A StatementCompilationObserver
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32, observer: StatementCompilationObserver) throws {
|
||||
observer.reset()
|
||||
self.selectionInfo = SelectionInfo()
|
||||
let observer = StatementCompilationObserver(database)
|
||||
try super.init(database: database, sql: sql, prepFlags: prepFlags, observer: observer)
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
Database.preconditionValidSelectStatement(sql: sql, observer: observer)
|
||||
self.selectionInfo = observer.selectionInfo
|
||||
}
|
||||
@@ -411,25 +419,27 @@ public final class UpdateStatement : Statement {
|
||||
private(set) var transactionStatementInfo: TransactionStatementInfo?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind]
|
||||
|
||||
init(database: Database, sqliteStatement: SQLiteStatement, invalidatesDatabaseSchemaCache: Bool, transactionStatementInfo: TransactionStatementInfo?, databaseEventKinds: [DatabaseEventKind]) {
|
||||
self.invalidatesDatabaseSchemaCache = invalidatesDatabaseSchemaCache
|
||||
self.transactionStatementInfo = transactionStatementInfo
|
||||
self.databaseEventKinds = databaseEventKinds
|
||||
super.init(database: database, sqliteStatement: sqliteStatement)
|
||||
}
|
||||
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
/// - parameter database: A database connection.
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
|
||||
/// containing SQL.
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
init(database: Database, sql: String, prepFlags: Int32) throws {
|
||||
/// - observer: A StatementCompilationObserver
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32, observer: StatementCompilationObserver) throws {
|
||||
observer.reset()
|
||||
self.invalidatesDatabaseSchemaCache = false
|
||||
self.databaseEventKinds = []
|
||||
|
||||
let observer = StatementCompilationObserver(database)
|
||||
try super.init(database: database, sql: sql, prepFlags: prepFlags, observer: observer)
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
self.invalidatesDatabaseSchemaCache = observer.invalidatesDatabaseSchemaCache
|
||||
self.transactionStatementInfo = observer.transactionStatementInfo
|
||||
self.databaseEventKinds = observer.databaseEventKinds
|
||||
|
||||
Reference in new issue
Block a user