Expose Database.beginTransaction(), commit(), rollback(). New Configuration.allowsUnsafeTransactions flag. New fatal error when a database access block ends with a transaction left opened.

This commit is contained in:
Gwendal Roué committed 2018-02-23 14:14:05 +01:00
1 parent 86bb4a27a4
commit 7dc008db8b
8 files changed
+130 -8

No files matched your search

+34
View File
@@ -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 {
+32
View File
@@ -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
+16 -4
View File
@@ -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")
}
}
+1
View File
@@ -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,
+15 -4
View File
@@ -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)
}
}
+4
View File
@@ -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")
+13
View File
@@ -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()
}
}
}
+15
View File
@@ -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")
}
}
}