From 7dc008db8b89ee712e6610cd453e14eec40e9255 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 23 Feb 2018 14:14:05 +0100 Subject: [PATCH] Expose Database.beginTransaction(), commit(), rollback(). New Configuration.allowsUnsafeTransactions flag. New fatal error when a database access block ends with a transaction left opened. --- CHANGELOG.md | 34 ++++++++++++++++++++++++ GRDB/Core/Configuration.swift | 32 ++++++++++++++++++++++ GRDB/Core/Database.swift | 20 +++++++++++--- GRDB/Core/DatabasePool.swift | 1 + GRDB/Core/SerializedDatabase.swift | 19 ++++++++++--- README.md | 4 +++ Tests/GRDBTests/DatabaseQueueTests.swift | 13 +++++++++ Tests/GRDBTests/DatabaseTests.swift | 15 +++++++++++ 8 files changed, 130 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f3d9450c..28f39fe70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,12 +3,39 @@ Release Notes ## Next Version +### Fixed + +- It is now a programmer error to leave a transaction opened at the end of a database access block: + + ```swift + // Fatal error: + // A transaction has been left opened at the end of a database access + try dbQueue.inDatabase { db in + try db.beginTransaction() + } + ``` + + One can still opt-in for the unsafe behavior by setting the new `allowsUnsafeTransactions` configuration flag: + + ```swift + var config = Configuration() + config.allowsUnsafeTransactions = true + let dbQueue = DatabaseQueue(configuration: config) + + // OK + try dbQueue.inDatabase { db in + try db.beginTransaction() + } + ``` + + ### New - `Record.updateChanges(_:)` now returns whether the record had unsaved changes, or not. - `Database.columns(in:)` returns information about the columns of a table. - Improved support for joined queries: check the new [Joined Queries Support](https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support) documentation chapter. - `Request.adapted(_:)` is no longer experimental. +- Support for explicit transaction management, via the new `Database.beginTransaction`, `commit`, and `rollback` methods. ### Deprecated @@ -36,11 +63,18 @@ Release Notes + let defaultValueSQL: String? + let primaryKeyIndex: Int +} + + struct Configuration { ++ var allowsUnsafeTransactions: Bool + } class Database { + @available(*, deprecated, message: "Use db.columns(in: tableName).count instead") func columnCount(in tableName: String) throws -> Int + func columns(in tableName: String) throws -> [ColumnInfo] ++ func beginTransaction(_ kind: TransactionKind? = nil) throws ++ func rollback() throws ++ func commit() throws } class Record { diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index cc789ad40..7ca4f9b7b 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -43,6 +43,38 @@ public struct Configuration { /// Default: deferred public var defaultTransactionKind: Database.TransactionKind = .deferred + /// If false, it is a programmer error to leave a transaction opened at the + /// end of a database access block. + /// + /// For example: + /// + /// let dbQueue = DatabaseQueue() + /// + /// // fatal error: A transaction has been left opened at the end of a database access + /// try dbQueue.inDatabase { db in + /// try db.beginTransaction() + /// } + /// + /// If true, one can leave opened transaction at the end of database access + /// blocks: + /// + /// var config = Configuration() + /// config.allowsUnsafeTransactions = true + /// let dbQueue = DatabaseQueue(configuration: config) + /// + /// try dbQueue.inDatabase { db in + /// try db.beginTransaction() + /// } + /// + /// try dbQueue.inDatabase { db in + /// try db.commit() + /// } + /// + /// This configuration flag has no effect on DatabasePool readers: those + /// never allow leaving a transaction opened at the end of a read access. + /// + /// Default: false + public var allowsUnsafeTransactions: Bool = false // MARK: - Concurrency diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index cc82f0d96..9a8f4c8eb 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -98,6 +98,8 @@ public final class Database { /// True if the database connection is currently in a transaction. public var isInsideTransaction: Bool { + if isClosed { return false } + // https://sqlite.org/c3ref/get_autocommit.html // // > The sqlite3_get_autocommit() interface returns non-zero or zero if @@ -549,7 +551,7 @@ extension Database { /// - throws: The error thrown by the block. public func inTransaction(_ kind: TransactionKind? = nil, _ block: () throws -> TransactionCompletion) throws { // Begin transaction - try beginTransaction(kind ?? configuration.defaultTransactionKind) + try beginTransaction(kind) // Now that transaction has begun, we'll rollback in case of error. // But we'll throw the first caught error, so that user knows @@ -669,11 +671,20 @@ extension Database { } } - func beginTransaction(_ kind: TransactionKind) throws { + /// Begins a database transaction. + /// + /// - parameter kind: The transaction type (default nil). If nil, the + /// transaction type is configuration.defaultTransactionKind, which itself + /// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html + /// for more information. + /// - throws: The error thrown by the block. + public func beginTransaction(_ kind: TransactionKind? = nil) throws { + let kind = kind ?? configuration.defaultTransactionKind try execute("BEGIN \(kind.rawValue) TRANSACTION") } - private func rollback() throws { + /// Rollbacks a database transaction. + public func rollback() throws { // The SQLite documentation contains two related but distinct techniques // to handle rollbacks and errors: // @@ -718,7 +729,8 @@ extension Database { } } - func commit() throws { + /// Commits a database transaction. + public func commit() throws { try execute("COMMIT TRANSACTION") } } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index ce66da6bc..12a771fe3 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -77,6 +77,7 @@ public final class DatabasePool { readerConfig = configuration readerConfig.readonly = true readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections. + readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction. readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in let reader = try SerializedDatabase( path: path, diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 50b5ed508..129870a83 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -81,7 +81,8 @@ final class SerializedDatabase { guard let watchdog = SchedulingWatchdog.current else { // Case 1 return try queue.sync { - try block(db) + defer { preconditionNoTransactionLeft(db) } + return try block(db) } } @@ -91,7 +92,8 @@ final class SerializedDatabase { // Case 3 return try queue.sync { try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) { - try block(db) + defer { preconditionNoTransactionLeft(db) } + return try block(db) } } } @@ -125,19 +127,22 @@ final class SerializedDatabase { guard let watchdog = SchedulingWatchdog.current else { // Case 1 return try queue.sync { - try block(db) + defer { preconditionNoTransactionLeft(db) } + return try block(db) } } // Case 2 if watchdog.allows(db) { + defer { preconditionNoTransactionLeft(db) } return try block(db) } // Case 3 return try queue.sync { try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) { - try block(db) + defer { preconditionNoTransactionLeft(db) } + return try block(db) } } } @@ -146,6 +151,7 @@ final class SerializedDatabase { func async(_ block: @escaping (Database) -> Void) { queue.async { block(self.db) + self.preconditionNoTransactionLeft(self.db) } } @@ -166,4 +172,9 @@ final class SerializedDatabase { func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) { SchedulingWatchdog.preconditionValidQueue(db, message, file: file, line: line) } + + /// Fatal error if a transaction has been left opened. + func preconditionNoTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) { + GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message, file: file, line: line) + } } diff --git a/README.md b/README.md index d3ce5b7c1..b8c920ca7 100644 --- a/README.md +++ b/README.md @@ -1279,6 +1279,10 @@ try dbQueue.inDatabase { db in // or dbPool.write { db in return .commit } ... + try db.beginTransaction() + ... + try db.commit() + ... try db.execute("BEGIN TRANSACTION") ... try db.execute("COMMIT") diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 940a23a1c..23fe4f7dc 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -90,4 +90,17 @@ class DatabaseQueueTests: GRDBTestCase { XCTAssertEqual(error.description.lowercased(), "sqlite error 1 with statement `create table files_fail (name text collate test_collation_foo)`: no such collation sequence: test_collation_foo") } } + + func testAllowsUnsafeTransactions() throws { + dbConfiguration.allowsUnsafeTransactions = true + let dbQueue = try makeDatabaseQueue() + + try dbQueue.inDatabase { db in + try db.beginTransaction() + } + + try dbQueue.inDatabase { db in + try db.commit() + } + } } diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index 40776c72d..28e47ebf9 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -298,4 +298,19 @@ class DatabaseTests : GRDBTestCase { // Make sure we can open another transaction try dbQueue.inTransaction { db in .commit } } + + func testExplicitTransactionManagement() throws { + let dbQueue = try makeDatabaseQueue() + + try dbQueue.inDatabase { db in + try db.beginTransaction() + XCTAssertEqual(lastSQLQuery, "BEGIN DEFERRED TRANSACTION") + try db.rollback() + XCTAssertEqual(lastSQLQuery, "ROLLBACK TRANSACTION") + try db.beginTransaction(.immediate) + XCTAssertEqual(lastSQLQuery, "BEGIN IMMEDIATE TRANSACTION") + try db.commit() + XCTAssertEqual(lastSQLQuery, "COMMIT TRANSACTION") + } + } }