diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 6509a765c..2488e9284 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -717,15 +717,24 @@ extension Database { } func assertExclusiveLockPrevention(from statement: Statement) throws { - if preventsExclusiveLock.value { - // Attempt at releasing eventual exclusive lock. - // See Database.startPreventingExclusiveLock() - try? rollback() - throw DatabaseError( - resultCode: .SQLITE_ABORT, - message: "Can't acquire exclusive lock", - sql: statement.sql, - arguments: statement.arguments) + SchedulingWatchdog.assertValidQueue(self) + + try preventsExclusiveLock.read { preventsExclusiveLock in + if preventsExclusiveLock { + // Attempt at releasing eventual exclusive lock with ROLLBACk, + // as explained in Database.startPreventingExclusiveLock(). + // + // We don't use `try? rollback()` because we're not in the + // protected dispatch queue here due to + // `preventsExclusiveLock.read`. + _ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil) + + throw DatabaseError( + resultCode: .SQLITE_ABORT, + message: "Can't acquire exclusive lock", + sql: statement.sql, + arguments: statement.arguments) + } } } } diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 087926c45..5f1887db0 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -52,6 +52,15 @@ final class SchedulingWatchdog { GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line) } + static func assertValidQueue( + _ db: Database, + _ message: @autoclosure() -> String = "Database was not used on the correct thread.", + file: StaticString = #file, + line: UInt = #line) + { + assert(current?.allows(db) ?? false, message(), file: file, line: line) + } + static var current: SchedulingWatchdog? { return DispatchQueue.getSpecific(key: watchDogKey) }