diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 859882b91..d42bbc0d5 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -222,6 +222,12 @@ extension Database { extension Database { func executeUpdateStatement(_ statement: UpdateStatement) throws { + // In aborted transaction, forbid all statements but statements that + // manage transaction. + if statement.transactionEffect == nil { + try assertNotInsideAbortedTransactionBlock(sql: statement.sql, arguments: statement.arguments) + } + let authorizer = observationBroker.updateStatementWillExecute(statement) let sqliteStatement = statement.sqliteStatement var code: Int32 = SQLITE_OK @@ -289,7 +295,9 @@ extension Database { } @inline(__always) - func selectStatementWillExecute(_ statement: SelectStatement) { + func selectStatementWillExecute(_ statement: SelectStatement) throws { + try assertNotInsideAbortedTransactionBlock(sql: statement.sql, arguments: statement.arguments) + if _isRecordingSelectedRegion { // Don't record schema introspection queries, which may be // run, or not, depending on the state of the schema cache. diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index f27317014..d1458596b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -146,6 +146,38 @@ public final class Database { /// Use recordingSelectedRegion(_:), see `selectStatementWillExecute(_:)` var _isRecordingSelectedRegion: Bool = false var _selectedRegion = DatabaseRegion() + + /// True inside `inTransaction { ... }` and `inSavepoint { ... }` + @usableFromInline var isInsideTransactionBlock = false + + /// When true, a transaction has been aborted (for example, by + /// `sqlite3_interrupt`, or a `ON CONFLICT ROLLBACK` clause. + /// + /// try db.inTransaction { + /// do { + /// // Aborted by sqlite3_interrupt or any other + /// // SQLite error which leaves transaction + /// ... + /// } catch { ... } + /// + /// // <- Here we're inside an aborted transaction. + /// ... + /// + /// return .commit + /// } + /// + /// When a transaction has been aborted, we throw SQLITE_ABORT for all + /// database accesses, because we don't want the user to think they are + /// safely wrapped by a transaction. + /// + /// We only monitor aborted transaction for `inTransaction` and + /// `inSavepoint` methods. When you use explicit methods like + /// `beginTransaction`, `commit`, or raw SQL statements, aborted + /// transactions are not monitored, and you won't get SQLITE_ABORT for + /// database accesses that run after a transaction has been aborted. + @usableFromInline var isInsideAbortedTransactionBlock: Bool { + return isInsideTransactionBlock && !isInsideTransaction + } // MARK: - Private properties @@ -644,6 +676,12 @@ extension Database { extension Database { // MARK: - Transactions & Savepoint + func assertNotInsideAbortedTransactionBlock(sql: String? = nil, arguments: StatementArguments? = nil) throws { + if isInsideAbortedTransactionBlock { + throw DatabaseError(resultCode: SQLITE_ABORT, message: "Transaction was aborted", sql: sql, arguments: arguments) + } + } + /// Executes a block inside a database transaction. /// /// try dbQueue.inDatabase do { @@ -670,6 +708,12 @@ extension Database { // Begin transaction try beginTransaction(kind) + let wasInsideTransactionBlock = isInsideTransactionBlock + isInsideTransactionBlock = true + defer { + isInsideTransactionBlock = wasInsideTransactionBlock + } + // Now that transaction has begun, we'll rollback in case of error. // But we'll throw the first caught error, so that user knows // what happened. @@ -679,6 +723,15 @@ extension Database { let completion = try block() switch completion { case .commit: + // In case of aborted transaction, throw SQLITE_ABORT instead + // of the generic SQLITE_ERROR "cannot commit - no transaction is active" + try assertNotInsideAbortedTransactionBlock() + + // Leave transaction block now, so that transaction observers + // can execute statements without getting errors from + // assertNotInsideAbortedTransactionBlock. + isInsideTransactionBlock = wasInsideTransactionBlock + try commit() needsRollback = false case .rollback: @@ -730,7 +783,8 @@ extension Database { // So when the default GRDB transaction kind is not deferred, we open a // transaction instead if !isInsideTransaction && configuration.defaultTransactionKind != .deferred { - return try inTransaction(configuration.defaultTransactionKind, block) + try inTransaction(configuration.defaultTransactionKind, block) + return } // If the savepoint is top-level, we'll use ROLLBACK TRANSACTION in @@ -746,6 +800,12 @@ extension Database { // the user uses "grdb" as a savepoint name. try execute(sql: "SAVEPOINT grdb") + let wasInsideTransactionBlock = isInsideTransactionBlock + isInsideTransactionBlock = true + defer { + isInsideTransactionBlock = wasInsideTransactionBlock + } + // Now that savepoint has begun, we'll rollback in case of error. // But we'll throw the first caught error, so that user knows // what happened. @@ -755,6 +815,15 @@ extension Database { let completion = try block() switch completion { case .commit: + // In case of aborted transaction, throw SQLITE_ABORT instead + // of the generic SQLITE_ERROR "cannot commit - no transaction is active" + try assertNotInsideAbortedTransactionBlock() + + // Leave transaction block now, so that transaction observers + // can execute statements without getting errors from + // assertNotInsideAbortedTransactionBlock. + isInsideTransactionBlock = wasInsideTransactionBlock + try execute(sql: "RELEASE SAVEPOINT grdb") assert(!topLevelSavepoint || !isInsideTransaction) needsRollback = false @@ -893,7 +962,7 @@ extension Database { // which rollback errors should be ignored, and which rollback errors // should be exposed to the library user. SchedulingWatchdog.preconditionValidQueue(self) // guard sqlite3_get_autocommit - if sqlite3_get_autocommit(sqliteConnection) == 0 { + if isInsideTransaction { try execute(sql: "ROLLBACK TRANSACTION") } assert(!isInsideTransaction) diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 6836906f6..301904d3c 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -67,7 +67,7 @@ public final class DatabaseValueCursor: Cursor _statement.reset(withArguments: arguments) // Assume cursor is created for iteration - statement.database.selectStatementWillExecute(statement) + try statement.database.selectStatementWillExecute(statement) } deinit { @@ -123,7 +123,7 @@ public final class NullableDatabaseValueCursor: _statement.reset(withArguments: arguments) // Assume cursor is created for iteration - statement.database.selectStatementWillExecute(statement) + try statement.database.selectStatementWillExecute(statement) } deinit { diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index e1c4d3ad1..13bfdf89e 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -779,7 +779,7 @@ public final class RowCursor: Cursor { statement.reset(withArguments: arguments) // Assume cursor is created for iteration - statement.database.selectStatementWillExecute(statement) + try statement.database.selectStatementWillExecute(statement) } deinit { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 82346a6fe..d3db3c25f 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -31,6 +31,7 @@ public class Statement { .trimmingCharacters(in: .sqlStatementSeparators) } + @usableFromInline unowned let database: Database /// Creates a prepared statement. Returns nil if the compiled string is @@ -346,8 +347,8 @@ public final class SelectStatement: Statement { /// Creates a cursor over the statement which does not produce any /// value. Each call to the next() cursor method calls the sqlite3_step() /// C function. - func makeCursor(arguments: StatementArguments? = nil) -> StatementCursor { - return StatementCursor(statement: self, arguments: arguments) + func makeCursor(arguments: StatementArguments? = nil) throws -> StatementCursor { + return try StatementCursor(statement: self, arguments: arguments) } /// Utility function for cursors @@ -384,13 +385,13 @@ final class StatementCursor: Cursor { var _done = false // Use SelectStatement.makeCursor() instead - init(statement: SelectStatement, arguments: StatementArguments? = nil) { + init(statement: SelectStatement, arguments: StatementArguments? = nil) throws { _statement = statement _sqliteStatement = statement.sqliteStatement _statement.reset(withArguments: arguments) // Assume cursor is created for iteration - statement.database.selectStatementWillExecute(statement) + try statement.database.selectStatementWillExecute(statement) } deinit { diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index dd0077f59..95aa91a86 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -79,7 +79,7 @@ public final class FastDatabaseValueCursor: Cursor _statement.reset(withArguments: arguments) // Assume cursor is created for iteration - statement.database.selectStatementWillExecute(statement) + try statement.database.selectStatementWillExecute(statement) } deinit { diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 7dbb8b73f..ebf27ca89 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -431,7 +431,7 @@ public final class RecordCursor: Cursor { _statement.reset(withArguments: arguments) // Assume cursor is created for iteration - statement.database.selectStatementWillExecute(statement) + try statement.database.selectStatementWillExecute(statement) } deinit { diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index b2b088478..d5039de87 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -37,7 +37,7 @@ class SelectStatementTests : GRDBTestCase { try dbQueue.inDatabase { db in let sql = "SELECT 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 'Barbara', 'Gourde'" let statement = try db.makeSelectStatement(sql: sql) - let cursor = statement.makeCursor() + let cursor = try statement.makeCursor() // Check that StatementCursor gives access to the raw SQLite API XCTAssertEqual(String(cString: sqlite3_column_name(cursor._statement.sqliteStatement, 0)), "firstName")