mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-29 04:24:21 +00:00
Database only exposes its current authorizer with the withAuthorizer(_:_:) wrapper method.
This commit is contained in:
1 parent
a59f4ef096
commit
e351b79526
4 files changed
+109
-89
No files matched your search
@@ -180,16 +180,15 @@ extension Database {
|
||||
|
||||
// Compile
|
||||
do {
|
||||
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
|
||||
authorizer = statementCompilationAuthorizer
|
||||
defer { authorizer = nil }
|
||||
|
||||
nextStatement = try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: statementCompilationAuthorizer)
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
nextStatement = try withAuthorizer(authorizer) {
|
||||
try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: authorizer)
|
||||
}
|
||||
}
|
||||
|
||||
guard let statement = nextStatement else {
|
||||
@@ -222,11 +221,54 @@ extension Database {
|
||||
|
||||
extension Database {
|
||||
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) {
|
||||
observationBroker.updateStatementWillExecute(statement)
|
||||
func executeUpdateStatement(_ statement: UpdateStatement) throws {
|
||||
let authorizer = observationBroker.updateStatementWillExecute(statement)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
var code: Int32 = SQLITE_OK
|
||||
withAuthorizer(authorizer) {
|
||||
while true {
|
||||
code = sqlite3_step(sqliteStatement)
|
||||
if code == SQLITE_ROW {
|
||||
// Statement returns a row, but the user ignores the
|
||||
// content of this row:
|
||||
//
|
||||
// try db.execute(sql: "SELECT ...")
|
||||
//
|
||||
// That's OK: maybe the selected rows perform side effects.
|
||||
// For example:
|
||||
//
|
||||
// try db.execute(sql: "SELECT sqlcipher_export(...)")
|
||||
//
|
||||
// Or maybe the user doesn't know that the executed statement
|
||||
// return rows (https://github.com/groue/GRDB.swift/issues/15);
|
||||
//
|
||||
// try db.execute(sql: "PRAGMA journal_mode=WAL")
|
||||
//
|
||||
// It is thus important that we consume *all* rows.
|
||||
continue
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Statement has been fully executed, and authorizer has been reset.
|
||||
// We can now move on further tasks.
|
||||
|
||||
if code == SQLITE_DONE {
|
||||
try updateStatementDidExecute(statement)
|
||||
} else {
|
||||
assert(code != SQLITE_ROW)
|
||||
try updateStatementDidFail(statement)
|
||||
throw DatabaseError(
|
||||
resultCode: code,
|
||||
message: lastErrorMessage,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
private func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
@@ -234,7 +276,7 @@ extension Database {
|
||||
try observationBroker.updateStatementDidExecute(statement)
|
||||
}
|
||||
|
||||
func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
private func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
|
||||
@@ -129,8 +129,8 @@ public final class Database {
|
||||
var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
|
||||
var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
|
||||
|
||||
// Statement authorizer
|
||||
var authorizer: StatementAuthorizer?
|
||||
// Statement authorizer. Use withAuthorizer(_:_:).
|
||||
fileprivate var _authorizer: StatementAuthorizer? //
|
||||
|
||||
// Transaction observers management
|
||||
lazy var observationBroker = DatabaseObservationBroker(self)
|
||||
@@ -341,7 +341,7 @@ extension Database {
|
||||
{ (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
|
||||
guard let dbPointer = dbPointer else { return SQLITE_OK }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer).takeUnretainedValue()
|
||||
guard let authorizer = db.authorizer else { return SQLITE_OK }
|
||||
guard let authorizer = db._authorizer else { return SQLITE_OK }
|
||||
return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
},
|
||||
dbPointer)
|
||||
@@ -594,6 +594,19 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Authorizer
|
||||
|
||||
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
let old = self._authorizer
|
||||
self._authorizer = authorizer
|
||||
defer { self._authorizer = old }
|
||||
return try block()
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Transactions & Savepoint
|
||||
|
||||
+31
-67
@@ -224,46 +224,41 @@ public class Statement {
|
||||
|
||||
// MARK: - Statement Preparation
|
||||
|
||||
/// A common protocol for UpdateStatement and SelectStatement, only used as
|
||||
/// support for SelectStatement.prepare(...) and UpdateStatement.prepare(...).
|
||||
protocol StatementProtocol { }
|
||||
extension Statement: StatementProtocol { }
|
||||
extension StatementProtocol where Self: Statement {
|
||||
extension Statement {
|
||||
// Static method instead of an initializer because initializer can't run
|
||||
// inside `sqlCodeUnits.withUnsafeBufferPointer`.
|
||||
static func prepare(sql: String, prepFlags: Int32, in database: Database) throws -> Self {
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
database.authorizer = authorizer
|
||||
defer { database.authorizer = nil }
|
||||
|
||||
return try sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
let statementStart = buffer.baseAddress!
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
guard let statement = try self.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer) else
|
||||
{
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ERROR,
|
||||
message: "empty statement",
|
||||
sql: sql)
|
||||
}
|
||||
|
||||
let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators)
|
||||
guard remainingSQL.isEmpty else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: """
|
||||
return try database.withAuthorizer(authorizer) {
|
||||
try sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
let statementStart = buffer.baseAddress!
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
guard let statement = try self.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer) else
|
||||
{
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ERROR,
|
||||
message: "empty statement",
|
||||
sql: sql)
|
||||
}
|
||||
|
||||
let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators)
|
||||
guard remainingSQL.isEmpty else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: """
|
||||
Multiple statements found. To execute multiple statements, \
|
||||
use Database.execute(sql:) instead.
|
||||
""",
|
||||
sql: sql)
|
||||
sql: sql)
|
||||
}
|
||||
|
||||
return statement
|
||||
}
|
||||
|
||||
return statement
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -484,42 +479,11 @@ public final class UpdateStatement: Statement {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
prepare(withArguments: arguments)
|
||||
try reset()
|
||||
database.updateStatementWillExecute(self)
|
||||
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_ROW:
|
||||
// The statement did return a row, and the user ignores the
|
||||
// content of this row:
|
||||
//
|
||||
// try db.execute(sql: "SELECT ...")
|
||||
//
|
||||
// That's OK: maybe the selected rows perform side effects.
|
||||
// For example:
|
||||
//
|
||||
// try db.execute(sql: "SELECT sqlcipher_export(...)")
|
||||
//
|
||||
// Or maybe the user doesn't know that the executed statement
|
||||
// return rows (https://github.com/groue/GRDB.swift/issues/15);
|
||||
//
|
||||
// try db.execute(sql: "PRAGMA journal_mode=WAL")
|
||||
//
|
||||
// It is thus important that we consume *all* rows.
|
||||
continue
|
||||
|
||||
case SQLITE_DONE:
|
||||
try database.updateStatementDidExecute(self)
|
||||
return
|
||||
|
||||
case let code:
|
||||
try database.updateStatementDidFail(self)
|
||||
throw DatabaseError(
|
||||
resultCode: code,
|
||||
message: database.lastErrorMessage,
|
||||
sql: sql,
|
||||
arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
|
||||
}
|
||||
}
|
||||
// Statement does not know how to execute itself, because it does not
|
||||
// know how to handle its errors, or if truncate optimisation should be
|
||||
// prevented or not. Database knows.
|
||||
try database.executeUpdateStatement(self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -206,7 +206,10 @@ class DatabaseObservationBroker {
|
||||
|
||||
// MARK: - Statement execution
|
||||
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) {
|
||||
/// Setups observation of changes that are about to be performed by the
|
||||
/// statement, and returns the authorizer that should be used during
|
||||
/// statement execution.
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) -> StatementAuthorizer? {
|
||||
// As statement executes, it may trigger database changes that will
|
||||
// be notified to transaction observers. As a consequence, observers
|
||||
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
|
||||
@@ -285,16 +288,15 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
|
||||
if observesRowDeletion {
|
||||
database.authorizer = TruncateOptimizationBlocker()
|
||||
return TruncateOptimizationBlocker()
|
||||
} else {
|
||||
database.authorizer = nil
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Undo updateStatementWillExecute
|
||||
statementObservations = []
|
||||
database.authorizer = nil
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
|
||||
// Reset transactionState before databaseDidRollback eventually
|
||||
@@ -319,7 +321,6 @@ class DatabaseObservationBroker {
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
// Undo updateStatementWillExecute
|
||||
statementObservations = []
|
||||
database.authorizer = nil
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
|
||||
// Has statement any effect on transaction/savepoints?
|
||||
|
||||
Reference in new issue
Block a user