Default to IMMEDIATE transactions.

This avoid select statements to crash by default when there is a concurrent write.
This commit is contained in:
Gwendal Roué committed 2015-09-13 19:34:13 +02:00
1 parent 329039dabd
commit 85a8819d9c
4 files changed
+49 -28

No files matched your search

@@ -221,4 +221,43 @@ class ConcurrencyTests: XCTestCase {
queue.waitUntilAllOperationsAreFinished()
XCTAssertTrue(concurrencyError == nil)
}
func testReaderDoNotCrashDuringDefaultTransaction() {
databasePath = "/tmp/GRDBTestReaderDuringDefaultTransaction.sqlite"
do { try NSFileManager.defaultManager().removeItemAtPath(databasePath) } catch { }
let dbQueue1 = try! DatabaseQueue(path: databasePath)
let dbQueue2 = try! DatabaseQueue(path: databasePath)
try! dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
}
var rows: [Row] = []
let queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 2
queue.addOperation(NSBlockOperation {
do {
try dbQueue1.inTransaction { db in
try db.execute("INSERT INTO stuffs (id) VALUES (NULL)")
sleep(2) // let other queue try to read.
return .Commit
}
}
catch is DatabaseError {
}
catch {
XCTFail("\(error)")
}
})
queue.addOperation(NSBlockOperation {
dbQueue2.inDatabase { db in
sleep(1) // let other queue write
rows = Row.fetchAll(db, "SELECT * FROM stuffs")
}
})
queue.waitUntilAllOperationsAreFinished()
XCTAssertEqual(rows.count, 0)
}
}
+2 -2
View File
@@ -82,7 +82,7 @@ public struct Configuration {
- parameter readonly: If false (the default), the database will be created
and opened for writing. If true, the database is opened readonly.
- parameter transactionType: An optional transaction type (default
.Exclusive). Unless specified otherwise, transactions opened by
.Immediate). Unless specified otherwise, transactions opened by
DatabaseQueue.inTransaction() will use this transaction type. See
https://www.sqlite.org/lang_transaction.html for more information.
- parameter busyMode: A BusyMode (default .ImmediateError).
@@ -92,7 +92,7 @@ public struct Configuration {
public init(
foreignKeysEnabled: Bool = true,
readonly: Bool = false,
transactionType: Database.TransactionType = .Exclusive,
transactionType: Database.TransactionType = .Immediate,
busyMode: Database.BusyMode = .ImmediateError,
trace: TraceFunction? = nil)
{
+1 -1
View File
@@ -113,7 +113,7 @@ public final class DatabaseQueue {
- parameter type: The transaction type (default nil). If nil, the
transaction type is configuration.transactionType, which itself defaults
to .Exclusive. See https://www.sqlite.org/lang_transaction.html for more
to .Immediate. See https://www.sqlite.org/lang_transaction.html for more
information.
- parameter block: A block that executes SQL statements and return either
.Commit or .Rollback.
+7 -25
View File
@@ -769,33 +769,15 @@ See [SQLite Result Codes](https://www.sqlite.org/rescode.html).
1. **Should a reader be allowed to read while a writer is writing?**
*By default*, GRDB's answer is clear and loud: readers actually *crash* if they read while a writer is writing:
*By default*, the answer is yes.
The writer has acquired a lock on the database which makes all concurrent SELECT queries fail with a SQLITE_BUSY error. Since [GRDB does not recover reading errors](#error-handling), the error turns into a crash.
```swift
// May crash with fatal error:
// SQLite error 5 with statement `SELECT ...`: database is locked
dbQueue.inDatabase { db in
let persons = Person.fetch(db, "SELECT ...")
}
```
Avoid this crash by wrapping the SELECT query inside a transaction (exclusive by default): the SQLITE_BUSY error will be reported to you by the BEGIN statement, before the SELECT has the opportunity to crash:
```swift
// May throw a DatabaseError of code SQLITE_BUSY:
try dbQueue.inTransaction { db in
let persons = Person.fetch(db, "SELECT ...")
return .Commit
}
```
The busy error itself can be avoided, by avoiding the lock, or by waiting until the lock is released: see below.
GRDB transactions are *immediate* by default, and immediate transactions don't lock SELECT queries out.
2. **Should a reader see the changes committed by writers during its reading session? The uncommited changes?**
2. **Should a reader see the changes committed by writers during its reading session? The uncommitted changes?**
*By default*, a reading session wrapped in a single transaction (exclusive by default) can't be affected by any other concurrent writer, since exclusive transactions lock all writers out.
*By default*, the answer is no, to both committed and uncommitted changes.
Yet, between two consecutive SELECT statements, a concurrent writer may have changed the state of the database. Wrap those SELECT statements in a *deferred* transaction so that those changes do not interfere.
3. **How to handle the failure when a connection fails to access the database that is already locked by another connection?**
@@ -824,7 +806,7 @@ For more advanced handling, you should become familiar with the fragmented lands
- WAL journal mode: https://www.sqlite.org/wal.html
- Busy handlers: https://www.sqlite.org/c3ref/busy_handler.html
The interested reader should know that by default, GRDB opens database in the **default journal mode**, uses **EXCLUSIVE transactions**, and registers **no busy handler** of any kind.
The interested reader should know that by default, GRDB opens database in the **default journal mode**, uses **IMMEDIATE transactions**, and registers **no busy handler** of any kind.
See [Configuration](GRDB/Core/Configuration.swift) type and [DatabaseQueue.inTransaction()](GRDB/Core/DatabaseQueue.swift) method for more precise handling of transactions and SQLITE_BUSY errors.