From 813950f8323960bb892fa1aa7bfad4fe29ade458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 9 Jul 2020 17:45:57 +0200 Subject: [PATCH] Avoid `SQLITE_BUSY` when opening a DatabaseSnapshot. --- CHANGELOG.md | 1 + GRDB/Core/DatabaseSnapshot.swift | 24 +++++++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 172576efd..a10f974f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking Change**: [#803](https://github.com/groue/GRDB.swift/pull/803): Remove FetchedRecordsController - **Breaking Change**: Removed `TableRecord.primaryKey` and `selectPrimaryKey(as:)` introduced in 5.0.0-beta.5 +- **Fixed**: Avoid `SQLITE_BUSY` when opening a DatabaseSnapshot. - The [How do I filter records and only keep those that are NOT associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) FAQ has been updated. ## 5.0.0-beta.6 diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 52158d129..0ba392732 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -21,7 +21,29 @@ public class DatabaseSnapshot: DatabaseReader { var configuration = configuration configuration.readonly = true configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction - + + // https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode + // > But there are some obscure cases where a query against a WAL-mode + // > database can return SQLITE_BUSY, so applications should be prepared + // > for that happenstance. + // > + // > - If another database connection has the database mode open in + // > exclusive locking mode [...] + // > - When the last connection to a particular database is closing, + // > that connection will acquire an exclusive lock for a short time + // > while it cleans up the WAL and shared-memory files [...] + // > - If the last connection to a database crashed, then the first new + // > connection to open the database will start a recovery process. An + // > exclusive lock is held during recovery. [...] + // + // The whole point of WAL readers is to avoid SQLITE_BUSY, so let's + // setup a busy handler for pool readers, in order to workaround those + // "obscure cases" that may happen when the database is shared between + // multiple processes. + if configuration.readonlyBusyMode == nil { + configuration.readonlyBusyMode = .timeout(10) + } + serializedDatabase = try SerializedDatabase( path: path, configuration: configuration,