diff --git a/CHANGELOG.md b/CHANGELOG.md index d1f8c92ee..b1984e8b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,6 +62,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: **New** - [#659](https://github.com/groue/GRDB.swift/pull/659): Database interruption +- [#660](https://github.com/groue/GRDB.swift/pull/660): Exclusive Lock Prevention ### Documentation Diff diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index f0dc53069..22222e100 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -494,6 +494,9 @@ 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; + 5682D721239582AA004B58C4 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseLockPreventionTests.swift */; }; + 5682D722239582AA004B58C4 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseLockPreventionTests.swift */; }; + 5682D723239582AA004B58C4 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseLockPreventionTests.swift */; }; 568735A21CEDE16C009B9116 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; }; 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; 568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; @@ -1497,6 +1500,7 @@ 567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; + 5682D71A239582AA004B58C4 /* DatabaseLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLockPreventionTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = ""; }; 5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordCodableTests.swift; sourceTree = ""; }; @@ -2229,6 +2233,7 @@ 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */, 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */, 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */, + 5682D71A239582AA004B58C4 /* DatabaseLockPreventionTests.swift */, 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */, 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, @@ -3486,6 +3491,7 @@ 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */, 5615B288222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, + 5682D722239582AA004B58C4 /* DatabaseLockPreventionTests.swift in Sources */, 5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 563B06C42185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */, @@ -3692,6 +3698,7 @@ 56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, + 5682D721239582AA004B58C4 /* DatabaseLockPreventionTests.swift in Sources */, 56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */, 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 563B06C32185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */, @@ -4031,6 +4038,7 @@ AAA4DD4D230F262000C74B15 /* DatabasePoolReadOnlyTests.swift in Sources */, AAA4DD4E230F262000C74B15 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, AAA4DD4F230F262000C74B15 /* TruncateOptimizationTests.swift in Sources */, + 5682D723239582AA004B58C4 /* DatabaseLockPreventionTests.swift in Sources */, AAA4DD50230F262000C74B15 /* FoundationNSURLTests.swift in Sources */, AAA4DD51230F262000C74B15 /* FoundationURLTests.swift in Sources */, AAA4DD52230F262000C74B15 /* ValueObservationExtentTests.swift in Sources */, diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index d42bbc0d5..0dea32ffc 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -220,13 +220,13 @@ extension Database { } extension Database { - func executeUpdateStatement(_ statement: UpdateStatement) throws { // In aborted transaction, forbid all statements but statements that - // manage transaction. + // manage transactions. if statement.transactionEffect == nil { - try assertNotInsideAbortedTransactionBlock(sql: statement.sql, arguments: statement.arguments) + try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) } + try checkForLockPrevention(from: statement) let authorizer = observationBroker.updateStatementWillExecute(statement) let sqliteStatement = statement.sqliteStatement @@ -296,7 +296,8 @@ extension Database { @inline(__always) func selectStatementWillExecute(_ statement: SelectStatement) throws { - try assertNotInsideAbortedTransactionBlock(sql: statement.sql, arguments: statement.arguments) + try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) + try checkForLockPrevention(from: statement) if _isRecordingSelectedRegion { // Don't record schema introspection queries, which may be diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index c39e6d077..2c937a904 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -147,38 +147,16 @@ public final class Database { var _isRecordingSelectedRegion: Bool = false var _selectedRegion = DatabaseRegion() - /// True inside `inTransaction { ... }` and `inSavepoint { ... }` - @usableFromInline var isInsideTransactionBlock = false + /// Support for checkForAbortedTransaction() + var isInsideTransactionBlock = false + + /// Support for checkForLockPrevention(from:) + var preventsLock = LockedBox(value: false) + + /// Support for checkForLockPrevention(from:) + /// This cache is never cleared: we assume journal mode never changes. + var journalModeCache: String? - /// When true, a transaction has been aborted (for example, by - /// `sqlite3_interrupt`, or a `ON CONFLICT ROLLBACK` clause. - /// - /// try db.inTransaction { - /// do { - /// // Aborted by sqlite3_interrupt or any other - /// // SQLite error which leaves transaction - /// ... - /// } catch { ... } - /// - /// // <- Here we're inside an aborted transaction. - /// ... - /// - /// return .commit - /// } - /// - /// When a transaction has been aborted, we throw SQLITE_ABORT for all - /// database accesses, because we don't want the user to think they are - /// safely wrapped by a transaction. - /// - /// We only monitor aborted transaction for `inTransaction` and - /// `inSavepoint` methods. When you use explicit methods like - /// `beginTransaction`, `commit`, or raw SQL statements, aborted - /// transactions are not monitored, and you won't get SQLITE_ABORT for - /// database accesses that run after a transaction has been aborted. - @usableFromInline var isInsideAbortedTransactionBlock: Bool { - return isInsideTransactionBlock && !isInsideTransaction - } - // MARK: - Private properties private var busyCallback: BusyCallback? @@ -199,9 +177,6 @@ public final class Database { deinit { assert(isClosed) } -} - -extension Database { // MARK: - Database Opening @@ -227,9 +202,6 @@ extension Database { } throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite? } -} - -extension Database { // MARK: - Database Setup @@ -393,7 +365,7 @@ extension Database { }, dbPointer) } - + private func activateExtendedCodes() throws { let code = sqlite3_extended_result_codes(sqliteConnection, 1) @@ -428,9 +400,6 @@ extension Database { // another passphrase. try makeSelectStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next() } -} - -extension Database { // MARK: - Database Closing @@ -504,9 +473,6 @@ extension Database { log(ResultCode(rawValue: code), "could not close database: \(message)") } } -} - -extension Database { // MARK: - Functions @@ -530,9 +496,6 @@ extension Database { functions.remove(function) function.uninstall(in: self) } -} - -extension Database { // MARK: - Collations @@ -570,9 +533,6 @@ extension Database { SQLITE_UTF8, nil, nil, nil) } -} - -extension Database { // MARK: - Read-Only Access @@ -623,9 +583,6 @@ extension Database { return result! } -} - -extension Database { // MARK: - Authorizer @@ -636,9 +593,6 @@ extension Database { defer { self._authorizer = old } return try block() } -} - -extension Database { // MARK: - Recording of the selected region @@ -658,9 +612,9 @@ extension Database { } return try (block(), _selectedRegion) } -} - -extension Database { + + // MARK: - Checkpoints + func checkpoint(_ kind: Database.CheckpointMode) throws { let code = sqlite3_wal_checkpoint_v2(sqliteConnection, nil, kind.rawValue, nil, nil) guard code == SQLITE_OK else { @@ -668,20 +622,160 @@ extension Database { } } + // MARK: - Interrupt + + // See https://www.sqlite.org/c3ref/interrupt.html func interrupt() { sqlite3_interrupt(sqliteConnection) } -} - -extension Database { + + // MARK: - Lock Prevention + + /// Starts preventing database locks. + /// + /// This method can be called from any thread. + /// + /// During lock prevention, any lock is released as soon as possible, and + /// lock acquisition is prevented. + /// + /// All database accesses may throw a DatabaseError of code + /// `SQLITE_INTERRUPT`, or `SQLITE_ABORT`, except reads in WAL mode. + /// + /// Lock prevention ends with stopPreventingLock(). + func startPreventingLock() { + preventsLock.write { preventsLock in + if preventsLock { + return + } + + // Prevent future lock acquisition + preventsLock = true + + // Interrupt the database because this may trigger an + // SQLITE_INTERRUPT error which may itself abort a transaction and + // release a lock. See https://www.sqlite.org/c3ref/interrupt.html + interrupt() + + // What about the eventual remaining lock? + // If the database had been opened with the SQLITE_OPEN_FULLMUTEX + // flag, we could safely execute a rollback statement: + // + // if configuration.SQLiteOpenFlags & SQLITE_OPEN_FULLMUTEX != 0 { + // sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil) + // } + // + // But: + // + // - we currently use SQLITE_OPEN_NOMUTEX instead of SQLITE_OPEN_FULLMUTEX. + // - the rollback may fail, and a lock could remain. + // + // We work around this situation by issuing a rollback on next + // database access which requires a lock, + // in preventExclusiveLock(from:). + } + } + + /// Ends lock prevention. See startPreventingLock(). + /// + /// This method can be called from any thread. + func stopPreventingLock() { + preventsLock.write { preventsLock in + preventsLock = false + } + } + + /// Support for checkForLockPrevention(from:) + private func journalMode() throws -> String { + if let journalMode = journalModeCache { + return journalMode + } + + // Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so + // that we don't create an infinite loop in checkForLockPrevention(from:) + var statement: SQLiteStatement? = nil + let sql = "PRAGMA journal_mode" + sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil) + defer { sqlite3_finalize(statement) } + sqlite3_step(statement) + guard let cString = sqlite3_column_text(statement, 0) else { + throw DatabaseError(resultCode: lastErrorCode, message: lastErrorMessage, sql: sql) + } + let journalMode = String(cString: cString) + journalModeCache = journalMode + return journalMode + } + + /// Throws SQLITE_ABORT during lock prevention, if statement would lock + /// the database. + func checkForLockPrevention(from statement: Statement) throws { + try preventsLock.read { preventsLock in + guard preventsLock else { + return + } + + if try journalMode() == "wal" && statement.isReadonly { + // In WAL mode, accept read-only statements: + // - SELECT ... + // - BEGIN DEFERRED TRANSACTION + // + // Those are not read-only: + // - INSERT ... + // - BEGIN IMMEDIATE TRANSACTION + return + } + + if + let updateStatement = statement as? UpdateStatement, + updateStatement.releasesDatabaseLock + { + // Accept statements that release locks: + // - COMMIT + // - ROLLBACK + // - ROLLBACK TRANSACTION TO SAVEPOINT + // - RELEASE SAVEPOINT + return + } + + // Attempt at releasing an eventual lock with ROLLBACk, + // as explained in Database.startPreventingLock(). + // + // Use sqlite3_exec instead of `try? rollback()` in order to avoid + // an infinite loop in checkForLockPrevention(from:) + _ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil) + + throw DatabaseError( + resultCode: .SQLITE_ABORT, + message: "Aborted due to lock prevention", + sql: statement.sql, + arguments: statement.arguments) + } + } + // MARK: - Transactions & Savepoint - func assertNotInsideAbortedTransactionBlock( + /// Throws SQLITE_ABORT if called from a transaction-wrapping method and + /// transaction has been aborted (for example, by `sqlite3_interrupt`, or a + /// `ON CONFLICT ROLLBACK` clause. + /// + /// try db.inTransaction { + /// do { + /// // Aborted by sqlite3_interrupt or any other + /// // SQLite error which leaves transaction + /// ... + /// } catch { ... } + /// + /// // <- Here we're inside an aborted transaction. + /// try checkForAbortedTransaction(...) // throws + /// ... + /// + /// return .commit + /// } + func checkForAbortedTransaction( sql: @autoclosure () -> String? = nil, arguments: @autoclosure () -> StatementArguments? = nil) throws { - if isInsideAbortedTransactionBlock { + if isInsideTransactionBlock && !isInsideTransaction { throw DatabaseError( resultCode: .SQLITE_ABORT, message: "Transaction was aborted", @@ -733,11 +827,11 @@ extension Database { case .commit: // In case of aborted transaction, throw SQLITE_ABORT instead // of the generic SQLITE_ERROR "cannot commit - no transaction is active" - try assertNotInsideAbortedTransactionBlock() + try checkForAbortedTransaction() // Leave transaction block now, so that transaction observers // can execute statements without getting errors from - // assertNotInsideAbortedTransactionBlock. + // checkForAbortedTransaction(). isInsideTransactionBlock = wasInsideTransactionBlock try commit() @@ -825,11 +919,11 @@ extension Database { case .commit: // In case of aborted transaction, throw SQLITE_ABORT instead // of the generic SQLITE_ERROR "cannot commit - no transaction is active" - try assertNotInsideAbortedTransactionBlock() + try checkForAbortedTransaction() // Leave transaction block now, so that transaction observers // can execute statements without getting errors from - // assertNotInsideAbortedTransactionBlock. + // checkForAbortedTransaction(). isInsideTransactionBlock = wasInsideTransactionBlock try execute(sql: "RELEASE SAVEPOINT grdb") @@ -980,9 +1074,6 @@ extension Database { try execute(sql: "COMMIT TRANSACTION") assert(!isInsideTransaction) } -} - -extension Database { // MARK: - Memory Management @@ -992,9 +1083,6 @@ extension Database { internalStatementCache.clear() publicStatementCache.clear() } -} - -extension Database { // MARK: - Backup diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 57c03ae2e..31a7743a8 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -259,6 +259,24 @@ extension DatabasePool: DatabaseReader { readerPool.forEach { $0.interrupt() } } + // MARK: - Lock Prevention + + public func startPreventingLock() { + if configuration.readonly { + // read-only WAL connections can't acquire locks + return + } + writer.startPreventingLock() + } + + public func stopPreventingLock() { + if configuration.readonly { + // read-only WAL connections can't acquire locks + return + } + writer.stopPreventingLock() + } + // MARK: - Reading from Database /// Synchronously executes a read-only block in a protected dispatch queue, diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index b194d4b7c..933e50773 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -155,6 +155,16 @@ extension DatabaseQueue { writer.interrupt() } + // MARK: - Lock Prevention + + public func startPreventingLock() { + writer.startPreventingLock() + } + + public func stopPreventingLock() { + writer.stopPreventingLock() + } + // MARK: - Reading from Database /// Synchronously executes a read-only block in a protected dispatch queue, diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 5a88f6bea..62cce6195 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -69,8 +69,41 @@ public protocol DatabaseReader: AnyObject { /// try Player(...).insert(db) // throws SQLITE_INTERRUPT /// } catch { } /// } // throws SQLITE_ABORT + /// + /// When an application creates transaction without a transaction-wrapping + /// method, no SQLITE_ABORT error warns of aborted transactions: + /// + /// try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction + /// try db.beginTransaction() + /// do { + /// // interrupted: + /// try Player(...).insert(db) // throws SQLITE_INTERRUPT + /// } catch { } + /// try Player(...).insert(db) // success + /// try db.commit() // throws SQLITE_ERROR "cannot commit - no transaction is active" + /// } func interrupt() + // MARK: - Lock Prevention + + /// Starts preventing database locks. + /// + /// This method can be called from any thread. + /// + /// During lock prevention, any lock is released as soon as possible, and + /// lock acquisition is prevented. + /// + /// All database accesses may throw a DatabaseError of code + /// `SQLITE_INTERRUPT`, or `SQLITE_ABORT`, except reads in WAL mode. + /// + /// Lock prevention ends with stopPreventingLock(). + func startPreventingLock() + + /// Ends lock prevention. See startPreventingLock(). + /// + /// This method can be called from any thread. + func stopPreventingLock() + // MARK: - Read From Database /// Synchronously executes a read-only block that takes a database @@ -302,6 +335,18 @@ public final class AnyDatabaseReader: DatabaseReader { base.interrupt() } + // MARK: - Lock Prevention + + /// :nodoc: + public func startPreventingLock() { + base.startPreventingLock() + } + + /// :nodoc: + public func stopPreventingLock() { + base.stopPreventingLock() + } + // MARK: - Reading from Database /// :nodoc: diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index df92854f9..4972ce11d 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -53,6 +53,16 @@ extension DatabaseSnapshot { serializedDatabase.interrupt() } + // MARK: - Lock Prevention + + public func startPreventingLock() { + // read-only WAL connections can't acquire locks + } + + public func stopPreventingLock() { + // read-only WAL connections can't acquire locks + } + // MARK: - Reading from Database /// Synchronously executes a read-only block that takes a database diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index bc730c406..5834a6e50 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -608,6 +608,18 @@ public final class AnyDatabaseWriter: DatabaseWriter { base.interrupt() } + // MARK: - Lock Prevention + + /// :nodoc: + public func startPreventingLock() { + base.startPreventingLock() + } + + /// :nodoc: + public func stopPreventingLock() { + base.stopPreventingLock() + } + // MARK: - Reading from Database /// :nodoc: 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) } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 0b09b52b4..4e197c639 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -204,6 +204,16 @@ final class SerializedDatabase { db.interrupt() } + func startPreventingLock() { + // Intentionally not scheduled in our serial queue + db.startPreventingLock() + } + + func stopPreventingLock() { + // Intentionally not scheduled in our serial queue + db.stopPreventingLock() + } + /// Fatal error if current dispatch queue is not valid. func preconditionValidQueue( _ message: @autoclosure() -> String = "Database was not used on the correct thread.", diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 05564bb0f..95a95ae43 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -31,7 +31,11 @@ public class Statement { .trimmingCharacters(in: .sqlStatementSeparators) } - @usableFromInline unowned let database: Database + var isReadonly: Bool { + return sqlite3_stmt_readonly(sqliteStatement) != 0 + } + + unowned let database: Database /// Creates a prepared statement. Returns nil if the compiled string is /// blank or empty. @@ -449,6 +453,25 @@ public final class UpdateStatement: Statement { private(set) var transactionEffect: TransactionEffect? private(set) var databaseEventKinds: [DatabaseEventKind] = [] + var releasesDatabaseLock: Bool { + guard let transactionEffect = transactionEffect else { + return false + } + + switch transactionEffect { + case .commitTransaction, .rollbackTransaction, + .releaseSavepoint, .rollbackSavepoint: + // Not technically correct: + // - ROLLBACK TRANSACTION TO SAVEPOINT does not release any lock + // - RELEASE SAVEPOINT does not always release lock + // + // But both move in the direction of releasing locks :-) + return true + default: + return false + } + } + /// Creates a prepared statement. Returns nil if the compiled string is /// blank or empty. /// diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 4e04ba7f9..6002b5311 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -131,6 +131,8 @@ 564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; + 565050E123940CE400A7F660 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050DF23940CE400A7F660 /* DatabaseLockPreventionTests.swift */; }; + 565050E223940CE400A7F660 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050DF23940CE400A7F660 /* DatabaseLockPreventionTests.swift */; }; 5653EB6820961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; }; 5653EB6920961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; }; 5653EB6A20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; @@ -807,6 +809,7 @@ 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; + 565050DF23940CE400A7F660 /* DatabaseLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLockPreventionTests.swift; sourceTree = ""; }; 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; @@ -1558,6 +1561,7 @@ 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */, 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */, 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */, + 565050DF23940CE400A7F660 /* DatabaseLockPreventionTests.swift */, 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */, 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, @@ -2346,6 +2350,7 @@ 6340BF871E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56057C662291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, + 565050E123940CE400A7F660 /* DatabaseLockPreventionTests.swift in Sources */, F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */, 5656A7F722946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, 5615B259222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */, @@ -2685,6 +2690,7 @@ F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, 56057C652291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */, + 565050E223940CE400A7F660 /* DatabaseLockPreventionTests.swift in Sources */, 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 5656A7F622946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, 5615B258222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index bff913351..aa03a319f 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -393,6 +393,8 @@ 5656A803229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */; }; + 5682D725239582C6004B58C4 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D724239582C6004B58C4 /* DatabaseLockPreventionTests.swift */; }; + 5682D726239582C6004B58C4 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D724239582C6004B58C4 /* DatabaseLockPreventionTests.swift */; }; 56915793231C0D6A00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915792231C0D6A00E1D237 /* PoolTests.swift */; }; 56915794231C0D6A00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915792231C0D6A00E1D237 /* PoolTests.swift */; }; 569BBA31228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; @@ -608,6 +610,7 @@ 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = ""; }; 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; + 5682D724239582C6004B58C4 /* DatabaseLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLockPreventionTests.swift; sourceTree = ""; }; 56915792231C0D6A00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; 56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; @@ -712,6 +715,7 @@ 564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */, 564A1F65226B89D5001F64F1 /* DatabaseErrorTests.swift */, 564A1F37226B89CF001F64F1 /* DatabaseFunctionTests.swift */, + 5682D724239582C6004B58C4 /* DatabaseLockPreventionTests.swift */, 564A1F5C226B89D3001F64F1 /* DatabaseLogErrorTests.swift */, 564A1FD4226B89E0001F64F1 /* DatabaseMigratorTests.swift */, 564A1F6A226B89D5001F64F1 /* DatabasePoolBackupTests.swift */, @@ -1247,6 +1251,7 @@ 564A2027226B89E1001F64F1 /* AssociationParallelDecodableRecordTests.swift in Sources */, 564A1FEC226B89E1001F64F1 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 564A208B226B89E1001F64F1 /* DatabaseMigratorTests.swift in Sources */, + 5682D725239582C6004B58C4 /* DatabaseLockPreventionTests.swift in Sources */, 564A206D226B89E1001F64F1 /* ValueObservationCombineTests.swift in Sources */, 564A2022226B89E1001F64F1 /* CursorTests.swift in Sources */, 564A203A226B89E1001F64F1 /* DatabaseDateDecodingStrategyTests.swift in Sources */, @@ -1451,6 +1456,7 @@ 564A2139226B8E18001F64F1 /* AssociationParallelDecodableRecordTests.swift in Sources */, 564A213A226B8E18001F64F1 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 564A213B226B8E18001F64F1 /* DatabaseMigratorTests.swift in Sources */, + 5682D726239582C6004B58C4 /* DatabaseLockPreventionTests.swift in Sources */, 564A213C226B8E18001F64F1 /* ValueObservationCombineTests.swift in Sources */, 564A213D226B8E18001F64F1 /* CursorTests.swift in Sources */, 564A213E226B8E18001F64F1 /* DatabaseDateDecodingStrategyTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 563a277f1..791fa9944 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -395,6 +395,8 @@ 5656A806229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5676FBAD22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */; }; 5676FBAE22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */; }; + 5682D728239582E3004B58C4 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D727239582E2004B58C4 /* DatabaseLockPreventionTests.swift */; }; + 5682D729239582E3004B58C4 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D727239582E2004B58C4 /* DatabaseLockPreventionTests.swift */; }; 56915790231C0D5100E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578F231C0D5100E1D237 /* PoolTests.swift */; }; 56915791231C0D5100E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578F231C0D5100E1D237 /* PoolTests.swift */; }; 569BBA2E228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */; }; @@ -611,6 +613,7 @@ 564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; }; 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = ""; }; 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = ""; }; + 5682D727239582E2004B58C4 /* DatabaseLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLockPreventionTests.swift; sourceTree = ""; }; 5691578F231C0D5100E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; 56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; @@ -715,6 +718,7 @@ 564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */, 564A1F65226B89D5001F64F1 /* DatabaseErrorTests.swift */, 564A1F37226B89CF001F64F1 /* DatabaseFunctionTests.swift */, + 5682D727239582E2004B58C4 /* DatabaseLockPreventionTests.swift */, 564A1F5C226B89D3001F64F1 /* DatabaseLogErrorTests.swift */, 564A1FD4226B89E0001F64F1 /* DatabaseMigratorTests.swift */, 564A1F6A226B89D5001F64F1 /* DatabasePoolBackupTests.swift */, @@ -1220,6 +1224,7 @@ 564A208E226B89E1001F64F1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 564A2029226B89E1001F64F1 /* FTS3TableBuilderTests.swift in Sources */, 561CFAAA2376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */, + 5682D728239582E3004B58C4 /* DatabaseLockPreventionTests.swift in Sources */, 561CFAA82376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */, 564A2001226B89E1001F64F1 /* RecordPrimaryKeyNoneTests.swift in Sources */, 564A2051226B89E1001F64F1 /* RecordWithColumnNameManglingTests.swift in Sources */, @@ -1424,6 +1429,7 @@ 564A211D226B8E18001F64F1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 564A211E226B8E18001F64F1 /* FTS3TableBuilderTests.swift in Sources */, 561CFAAB2376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */, + 5682D729239582E3004B58C4 /* DatabaseLockPreventionTests.swift in Sources */, 561CFAA92376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */, 564A211F226B8E18001F64F1 /* RecordPrimaryKeyNoneTests.swift in Sources */, 564A2120226B8E18001F64F1 /* RecordWithColumnNameManglingTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseLockPreventionTests.swift b/Tests/GRDBTests/DatabaseLockPreventionTests.swift new file mode 100644 index 000000000..a05f0c20c --- /dev/null +++ b/Tests/GRDBTests/DatabaseLockPreventionTests.swift @@ -0,0 +1,447 @@ +import XCTest +#if GRDBCUSTOMSQLITE +import GRDBCustomSQLite +#else +import GRDB +#endif + +class DatabaseLockPreventionTests : GRDBTestCase { + + private func makeDatabaseQueue(journalMode: String) throws -> DatabaseQueue { + let dbQueue = try makeDatabaseQueue() + let actualJournalMode = try dbQueue.inDatabase { try String.fetchOne($0, sql: "PRAGMA journal_mode=\(journalMode)") } + XCTAssertEqual(actualJournalMode, journalMode) + return dbQueue + } + + // MARK: - BEGIN TRANSACTION + + func testLockPreventionPreventsNewTransactionInDeleteJournalMode() throws { + let dbQueue = try makeDatabaseQueue(journalMode: "delete") + dbQueue.startPreventingLock() + + do { + try dbQueue.inDatabase { db in + try db.execute(sql: "BEGIN TRANSACTION") + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "BEGIN TRANSACTION") + } + + do { + try dbQueue.inDatabase { db in + try db.execute(sql: "BEGIN IMMEDIATE TRANSACTION") + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "BEGIN IMMEDIATE TRANSACTION") + } + + do { + try dbQueue.inDatabase { db in + try db.execute(sql: "BEGIN EXCLUSIVE TRANSACTION") + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "BEGIN EXCLUSIVE TRANSACTION") + } + + do { + try dbQueue.inDatabase { db in + try db.execute(sql: "SAVEPOINT test") + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "SAVEPOINT test") + } + } + + func testLockPreventionDoesNotPreventNewDeferredTransactionInWALMode() throws { + let dbQueue = try makeDatabaseQueue(journalMode: "wal") + dbQueue.startPreventingLock() + + try dbQueue.inDatabase { db in + try db.execute(sql: "BEGIN TRANSACTION; ROLLBACK") + try db.execute(sql: "SAVEPOINT test; RELEASE SAVEPOINT test") + } + } + + func testLockPreventionPreventsNewImmediateOrExclusiveTransactionInWALMode() throws { + let dbQueue = try makeDatabaseQueue(journalMode: "wal") + dbQueue.startPreventingLock() + + do { + try dbQueue.inDatabase { db in + try db.execute(sql: "BEGIN IMMEDIATE TRANSACTION") + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "BEGIN IMMEDIATE TRANSACTION") + } + + do { + try dbQueue.inDatabase { db in + try db.execute(sql: "BEGIN EXCLUSIVE TRANSACTION") + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "BEGIN EXCLUSIVE TRANSACTION") + } + } + + // MARK: - COMMIT, ROLLBACK, RELEASE SAVEPOINT, ROLLBACK TRANSACTION TO SAVEPOINT + + func testLockPreventionDoesNotPreventCommit() throws { + func test(_ dbQueue: DatabaseQueue) throws { + try dbQueue.inDatabase { db in + try db.execute(sql: "BEGIN TRANSACTION") + dbQueue.startPreventingLock() + try db.execute(sql: "COMMIT") + } + } + try test(makeDatabaseQueue(journalMode: "delete")) + try test(makeDatabaseQueue(journalMode: "wal")) + } + + func testLockPreventionDoesNotPreventRollback() throws { + func test(_ dbQueue: DatabaseQueue) throws { + try dbQueue.inDatabase { db in + try db.execute(sql: "BEGIN TRANSACTION") + dbQueue.startPreventingLock() + try db.execute(sql: "ROLLBACK") + } + } + try test(makeDatabaseQueue(journalMode: "delete")) + try test(makeDatabaseQueue(journalMode: "wal")) + } + + func testLockPreventionDoesNotPreventReleaseSavePoint() throws { + func test(_ dbQueue: DatabaseQueue) throws { + try dbQueue.inDatabase { db in + try db.execute(sql: "SAVEPOINT test") + dbQueue.startPreventingLock() + try db.execute(sql: "RELEASE SAVEPOINT test") + } + } + try test(makeDatabaseQueue(journalMode: "delete")) + try test(makeDatabaseQueue(journalMode: "wal")) + } + + func testLockPreventionDoesNotPreventRollbackSavePoint() throws { + func test(_ dbQueue: DatabaseQueue) throws { + try dbQueue.inDatabase { db in + try db.execute(sql: "SAVEPOINT test") + dbQueue.startPreventingLock() + try db.execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT test") + try db.execute(sql: "RELEASE SAVEPOINT test") + } + } + try test(makeDatabaseQueue(journalMode: "delete")) + try test(makeDatabaseQueue(journalMode: "wal")) + } + + // MARK: - SELECT + + func testLockPreventionPreventsReadInDeleteJournalMode() throws { + let dbQueue = try makeDatabaseQueue(journalMode: "delete") + do { + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE t(a);") + dbQueue.startPreventingLock() + _ = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "SELECT COUNT(*) FROM t") + } + } + + func testLockPreventionDoesNotPreventReadInWALMode() throws { + let dbQueue = try makeDatabaseQueue(journalMode: "wal") + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE t(a);") + dbQueue.startPreventingLock() + + try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t"), 0) + + try db.inTransaction(.deferred) { + try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t"), 0) + return .commit + } + } + } + + // MARK: - INSERT + + func testLockPreventionPreventsWriteInDeleteJournalMode() throws { + let dbQueue = try makeDatabaseQueue(journalMode: "delete") + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE t(a);") + dbQueue.startPreventingLock() + do { + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") + } + } + } + + func testLockPreventionPreventsWriteInWALMode() throws { + let dbQueue = try makeDatabaseQueue(journalMode: "wal") + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE t(a);") + dbQueue.startPreventingLock() + + do { + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") + } + + do { + try db.inTransaction(.deferred) { + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + return .commit + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") + } + } + } + + // MARK: - Automatic ROLLBACK + + func testLockPreventionRollbacksOnPreventedWrite() throws { + func test(_ dbQueue: DatabaseQueue) throws { + do { + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a);") + XCTAssertTrue(db.isInsideTransaction) + dbQueue.startPreventingLock() + do { + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Aborted due to lock prevention") + XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") + } + // Aborded transaction + XCTAssertFalse(db.isInsideTransaction) + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Transaction was aborted") + } + } + try test(makeDatabaseQueue(journalMode: "delete")) + try test(makeDatabaseQueue(journalMode: "wal")) + } + + // MARK: - Concurrent Lock Prevention + + func testLockPreventionAbortsDatabaseQueueAccess() throws { + func test(_ dbQueue: DatabaseQueue) throws { + let semaphore1 = DispatchSemaphore(value: 0) + let semaphore2 = DispatchSemaphore(value: 0) + dbQueue.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in + semaphore1.signal() + semaphore2.wait() + return nil + }) + + let block1 = { + do { + _ = try dbQueue.inDatabase { + try Row.fetchAll($0, sql: "SELECT wait()") + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_INTERRUPT) + } catch { + XCTFail("Unexpected error: \(error)") + } + } + let block2 = { + semaphore1.wait() + dbQueue.startPreventingLock() + semaphore2.signal() + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + try test(makeDatabaseQueue(journalMode: "delete")) + try test(makeDatabaseQueue(journalMode: "wal")) + } + + func testLockPreventionDoesNotPreventFurtherReadInWALMode() throws { + let dbQueue = try makeDatabaseQueue(journalMode: "wal") + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a);") + } + + let semaphore1 = DispatchSemaphore(value: 0) + let semaphore2 = DispatchSemaphore(value: 0) + + dbQueue.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in + semaphore1.signal() + semaphore2.wait() + return nil + }) + let block1 = { + do { + try dbQueue.inTransaction { db in + do { + _ = try Row.fetchAll(db, sql: "SELECT wait()") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_INTERRUPT) + } + XCTAssertTrue(db.isInsideTransaction) + try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t"), 0) + return .commit + } + } catch { + XCTFail("Unexpected error: \(error)") + } + } + let block2 = { + semaphore1.wait() + dbQueue.startPreventingLock() + semaphore2.signal() + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + + func testWriteTransactionAbortedDuringStatementExecution() throws { + func test(_ dbQueue: DatabaseQueue) throws { + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a);") + } + + let semaphore1 = DispatchSemaphore(value: 0) + let semaphore2 = DispatchSemaphore(value: 0) + + dbQueue.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in + semaphore1.signal() + semaphore2.wait() + return nil + }) + let block1 = { + do { + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO t SELECT wait()") + } + XCTFail("Expected error") + } catch let error as DatabaseError { + // Transactions throw the first uncatched error: SQLITE_INTERRUPT + XCTAssertEqual(error.resultCode, .SQLITE_INTERRUPT) + XCTAssertEqual(error.message, "interrupted") + XCTAssertEqual(error.sql, "INSERT INTO t SELECT wait()") + } catch { + XCTFail("Unexpected error: \(error)") + } + } + let block2 = { + semaphore1.wait() + dbQueue.startPreventingLock() + semaphore2.signal() + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + try test(makeDatabaseQueue(journalMode: "delete")) + try test(makeDatabaseQueue(journalMode: "wal")) + } + + func testWriteTransactionAbortedDuringStatementExecutionPreventsFurtherDatabaseAccess() throws { + func test(_ dbQueue: DatabaseQueue) throws { + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a);") + } + + let semaphore1 = DispatchSemaphore(value: 0) + let semaphore2 = DispatchSemaphore(value: 0) + + dbQueue.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in + semaphore1.signal() + semaphore2.wait() + return nil + }) + let block1 = { + do { + try dbQueue.write { db in + do { + try db.execute(sql: "INSERT INTO t SELECT wait()") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_INTERRUPT) + } + + XCTAssertFalse(db.isInsideTransaction) + + do { + _ = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Transaction was aborted") + XCTAssertEqual(error.sql, "SELECT COUNT(*) FROM t") + } + } + XCTFail("Expected error") + } catch let error as DatabaseError { + // SQLITE_INTERRUPT has been caught. So we get SQLITE_ABORT + // from the last commit. + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Transaction was aborted") + } catch { + XCTFail("Unexpected error: \(error)") + } + } + let block2 = { + semaphore1.wait() + dbQueue.startPreventingLock() + semaphore2.signal() + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + try test(makeDatabaseQueue(journalMode: "delete")) + try test(makeDatabaseQueue(journalMode: "wal")) + } +}