diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index d4256b4d8..bfc216250 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -569,30 +569,14 @@ public final class Database { /// Grants read-only access, starting SQLite 3.8.0 func readOnly(_ block: () throws -> T) throws -> T { - try beginReadOnly() - - var result: T? - var thrownError: Error? - - do { - result = try block() - } catch { - thrownError = error - } - - do { - try endReadOnly() - } catch { - if thrownError == nil { - thrownError = error - } - } - - if let error = thrownError { - throw error - } - - return result! + return try throwingFirstError( + execute: { + try beginReadOnly() + return try block() + }, + finally: { + try endReadOnly() + }) } // MARK: - Authorizer diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index bc730c406..1501dfe46 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -285,35 +285,32 @@ extension DatabaseWriter { // https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 // So we'll drop all database objects one after the other. try writeWithoutTransaction { db in - // Prevent foreign keys from messing with drop table statements let foreignKeysEnabled = try Bool.fetchOne(db, sql: "PRAGMA foreign_keys")! - if foreignKeysEnabled { - try db.execute(sql: "PRAGMA foreign_keys = OFF") - } - // Remove all database objects, one after the other - do { - try db.inTransaction { - let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'" - while let row = try Row.fetchOne(db, sql: sql) { - let type: String = row["type"] - let name: String = row["name"] - try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)") + try throwingFirstError( + execute: { + // Prevent foreign keys from messing with drop table statements + if foreignKeysEnabled { + try db.execute(sql: "PRAGMA foreign_keys = OFF") } - return .commit - } - - // Restore foreign keys if needed - if foreignKeysEnabled { - try db.execute(sql: "PRAGMA foreign_keys = ON") - } - } catch { - // Restore foreign keys if needed - if foreignKeysEnabled { - try? db.execute(sql: "PRAGMA foreign_keys = ON") - } - throw error - } + + // Remove all database objects, one after the other + try db.inTransaction { + let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'" + while let row = try Row.fetchOne(db, sql: sql) { + let type: String = row["type"] + let name: String = row["name"] + try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)") + } + return .commit + } + }, + finally: { + // Restore foreign keys if needed + if foreignKeysEnabled { + try db.execute(sql: "PRAGMA foreign_keys = ON") + } + }) } #else try DatabaseQueue().backup(to: self) diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 098667d76..a969721c9 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -46,39 +46,42 @@ struct Migration { } private func runWithDisabledForeignKeys(_ db: Database) throws { - // Support for database alterations described at - // https://www.sqlite.org/lang_altertable.html#otheralter - // - // > 1. If foreign key constraints are enabled, disable them using - // > PRAGMA foreign_keys=OFF. - try db.execute(sql: "PRAGMA foreign_keys = OFF") - - // > 2. Start a transaction. - try db.inTransaction(.immediate) { - try migrate(db) - try insertAppliedIdentifier(db) - - // > 10. If foreign key constraints were originally enabled then run PRAGMA - // > foreign_key_check to verify that the schema change did not break any foreign key - // > constraints. - if try Row.fetchOne(db, sql: "PRAGMA foreign_key_check") != nil { - // https://www.sqlite.org/pragma.html#pragma_foreign_key_check + try throwingFirstError( + execute: { + // Support for database alterations described at + // https://www.sqlite.org/lang_altertable.html#otheralter // - // PRAGMA foreign_key_check does not return an error, - // but the list of violated foreign key constraints. - // - // Let's turn any violation into an SQLITE_CONSTRAINT - // error, and rollback the transaction. - throw DatabaseError(resultCode: .SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed") - } - - // > 11. Commit the transaction started in step 2. - return .commit - } - - // TODO: we should restore foreign_keys in case of error as well - // > 12. If foreign keys constraints were originally enabled, reenable them now. - try db.execute(sql: "PRAGMA foreign_keys = ON") + // > 1. If foreign key constraints are enabled, disable them using + // > PRAGMA foreign_keys=OFF. + try db.execute(sql: "PRAGMA foreign_keys = OFF") + + // > 2. Start a transaction. + try db.inTransaction(.immediate) { + try migrate(db) + try insertAppliedIdentifier(db) + + // > 10. If foreign key constraints were originally enabled then run PRAGMA + // > foreign_key_check to verify that the schema change did not break any foreign key + // > constraints. + if try Row.fetchOne(db, sql: "PRAGMA foreign_key_check") != nil { + // https://www.sqlite.org/pragma.html#pragma_foreign_key_check + // + // PRAGMA foreign_key_check does not return an error, + // but the list of violated foreign key constraints. + // + // Let's turn any violation into an SQLITE_CONSTRAINT + // error, and rollback the transaction. + throw DatabaseError(resultCode: .SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed") + } + + // > 11. Commit the transaction started in step 2. + return .commit + } + }, + finally: { + // > 12. If foreign keys constraints were originally enabled, reenable them now. + try db.execute(sql: "PRAGMA foreign_keys = ON") + }) } private func insertAppliedIdentifier(_ db: Database) throws { diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index a29d65202..ecf9f3abf 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -122,3 +122,38 @@ extension Character { } } #endif + +/// Makes sure the `finally` function is executed even if `execute` throws, and +/// rethrows the eventual first thrown error. +/// +/// For example: +/// +/// // Does not throw +/// try throwingFirstError( +/// execute: { }, +/// finally: { }) +/// +/// // throws A +/// try throwingFirstError( +/// execute: { throw A }, +/// finally: { }) +/// +/// // throws B +/// try throwingFirstError( +/// execute: { }, +/// finally: { throw B }) +/// +/// // throws A +/// try throwingFirstError( +/// execute: { throw A }, +/// finally: { throw B }) +func throwingFirstError(execute: () throws -> T, finally: () throws -> Void) throws -> T { + do { + let result = try execute() + try finally() + return result + } catch { + try? finally() + throw error + } +}