From b54a8f7fe8b070329f71df5321673068b3f6ce7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Dec 2019 17:25:46 +0100 Subject: [PATCH 01/17] DatabaseWriter.startPreventingExclusiveLock() --- GRDB.xcodeproj/project.pbxproj | 8 + GRDB/Core/Database+Statements.swift | 20 +- GRDB/Core/Database.swift | 51 ++- GRDB/Core/DatabaseError.swift | 8 + GRDB/Core/DatabasePool.swift | 16 + GRDB/Core/DatabaseQueue.swift | 16 + GRDB/Core/DatabaseWriter.swift | 20 + GRDB/Core/SerializedDatabase.swift | 10 + GRDB/Core/Statement.swift | 19 +- GRDBCustom.xcodeproj/project.pbxproj | 6 + .../GRDBTests.xcodeproj/project.pbxproj | 6 + .../GRDBTests.xcodeproj/project.pbxproj | 6 + ...DatabaseExclusiveLockPreventionTests.swift | 413 ++++++++++++++++++ 13 files changed, 594 insertions(+), 5 deletions(-) create mode 100644 Tests/GRDBTests/DatabaseExclusiveLockPreventionTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index f0dc53069..268f25ba4 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -262,6 +262,9 @@ 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564FCE5E20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */; }; 564FCE5F20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */; }; + 565050C82393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050C12393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; + 565050C92393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050C12393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; + 565050CA2393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050C12393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; 5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */; }; @@ -1407,6 +1410,7 @@ 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 = ""; }; 564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; + 565050C12393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseExclusiveLockPreventionTests.swift; sourceTree = ""; }; 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; @@ -2228,6 +2232,7 @@ 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */, 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */, 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */, + 565050C12393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */, 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */, 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */, 560A37A91C90084600949E71 /* DatabasePool */, @@ -3580,6 +3585,7 @@ 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, 56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 565050C92393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 5676FBA722F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, @@ -3786,6 +3792,7 @@ 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 565050C82393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, @@ -4125,6 +4132,7 @@ AAA4DDA8230F262000C74B15 /* SQLRequestTests.swift in Sources */, AAA4DDA9230F262000C74B15 /* StatementArguments+FoundationTests.swift in Sources */, AAA4DDAA230F262000C74B15 /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 565050CA2393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, AAA4DDAB230F262000C74B15 /* ValueObservationRegionRecordingTests.swift in Sources */, AAA4DDAC230F262000C74B15 /* RowFetchTests.swift in Sources */, AAA4DDAD230F262000C74B15 /* AssociationChainRowScopesTests.swift in Sources */, diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index d42bbc0d5..845e8cd5c 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -222,8 +222,17 @@ extension Database { extension Database { func executeUpdateStatement(_ statement: UpdateStatement) throws { + if preventsExclusiveLock.value && statement.createsExclusiveLock { + try? rollback() + throw DatabaseError( + resultCode: .SQLITE_ABORT_EXCLUSIVE, + message: "Can't acquire exclusive lock", + sql: statement.sql, + arguments: statement.arguments) + } + // 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) } @@ -296,6 +305,15 @@ extension Database { @inline(__always) func selectStatementWillExecute(_ statement: SelectStatement) throws { + if preventsExclusiveLock.value && !statement.isReadonly { + try? rollback() + throw DatabaseError( + resultCode: .SQLITE_ABORT_EXCLUSIVE, + message: "Can't acquire exclusive lock", + sql: statement.sql, + arguments: statement.arguments) + } + try assertNotInsideAbortedTransactionBlock(sql: statement.sql, arguments: statement.arguments) if _isRecordingSelectedRegion { diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index c39e6d077..1d956b021 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -148,7 +148,7 @@ public final class Database { var _selectedRegion = DatabaseRegion() /// True inside `inTransaction { ... }` and `inSavepoint { ... }` - @usableFromInline var isInsideTransactionBlock = false + var isInsideTransactionBlock = false /// When true, a transaction has been aborted (for example, by /// `sqlite3_interrupt`, or a `ON CONFLICT ROLLBACK` clause. @@ -175,10 +175,13 @@ public final class Database { /// `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 { + var isInsideAbortedTransactionBlock: Bool { return isInsideTransactionBlock && !isInsideTransaction } - + + // See startPreventingExclusiveLock + var preventsExclusiveLock = ReadWriteBox(value: false) + // MARK: - Private properties private var busyCallback: BusyCallback? @@ -668,9 +671,51 @@ extension Database { } } + // See https://www.sqlite.org/c3ref/interrupt.html func interrupt() { sqlite3_interrupt(sqliteConnection) } + + /// Aborts any exclusive lock, as soon as possible, at any cost. + /// + /// See https://www.sqlite.org/lockingv3.html + func startPreventingExclusiveLock() { + preventsExclusiveLock.write { preventsExclusiveLock in + if preventsExclusiveLock { + return + } + + // Prevent future lock acquisition + preventsExclusiveLock = true + + // Interrupt the database because this may trigger an + // SQLITE_INTERRUPT error which may itself abort a transaction and + // release an exclusive lock. See https://www.sqlite.org/c3ref/interrupt.html + interrupt() + + // What about the eventual remaining exclusive 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 an exclusive lock. + // See Database.executeUpdateStatement(_:) and + // Database.selectStatementWillExecute(_:). + } + } + + func stopPreventingExclusiveLock() { + preventsExclusiveLock.value = false + } } extension Database { diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index c9140cd4f..f0e888f15 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -153,6 +153,14 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8))) public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8))) public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8))) + + // GRDB-specific + /// SQLITE_ABORT_EXCLUSIVE (32772) is thrown when an SQL statement attempts + /// at acquiring an exclusive lock on a database which prevents exclusive + /// lock acquisition. + /// + /// See DatabaseWriter.prevents + public static let SQLITE_ABORT_EXCLUSIVE = ResultCode(rawValue: (SQLITE_ABORT.rawValue | (128<<8))) // swiftlint:enable operator_usage_whitespace line_length } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 57c03ae2e..fbb59acab 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -259,6 +259,22 @@ extension DatabasePool: DatabaseReader { readerPool.forEach { $0.interrupt() } } + public func startPreventingExclusiveLock() { + if configuration.readonly { + // read-only connections can't acquire exclusive locks + return + } + writer.startPreventingExclusiveLock() + } + + public func stopPreventingExclusiveLock() { + if configuration.readonly { + // read-only connections can't acquire exclusive locks + return + } + writer.stopPreventingExclusiveLock() + } + // 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..c67bc77fc 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -155,6 +155,22 @@ extension DatabaseQueue { writer.interrupt() } + public func startPreventingExclusiveLock() { + if configuration.readonly { + // read-only connections can't acquire exclusive locks + return + } + writer.startPreventingExclusiveLock() + } + + public func stopPreventingExclusiveLock() { + if configuration.readonly { + // read-only connections can't acquire exclusive locks + return + } + writer.stopPreventingExclusiveLock() + } + // MARK: - Reading from Database /// Synchronously executes a read-only block in a protected dispatch queue, diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index bc730c406..7dbfed815 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -174,6 +174,14 @@ public protocol DatabaseWriter: DatabaseReader { /// :nodoc: func spawnConcurrentRead(_ block: @escaping (Result) -> Void) #endif + + // MARK: - Exclusive Lock Prevention + + // TODO: doc + func startPreventingExclusiveLock() + + // TODO: doc + func stopPreventingExclusiveLock() } extension DatabaseWriter { @@ -608,6 +616,18 @@ public final class AnyDatabaseWriter: DatabaseWriter { base.interrupt() } + // MARK: - Exclusive Lock Prevention + + /// :nodoc: + public func startPreventingExclusiveLock() { + base.startPreventingExclusiveLock() + } + + /// :nodoc: + public func stopPreventingExclusiveLock() { + base.stopPreventingExclusiveLock() + } + // MARK: - Reading from Database /// :nodoc: diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 0b09b52b4..a542323ec 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -204,6 +204,16 @@ final class SerializedDatabase { db.interrupt() } + func startPreventingExclusiveLock() { + // Intentionally not scheduled in our serial queue + db.startPreventingExclusiveLock() + } + + func stopPreventingExclusiveLock() { + // Intentionally not scheduled in our serial queue + db.stopPreventingExclusiveLock() + } + /// 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..5927f377a 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,19 @@ public final class UpdateStatement: Statement { private(set) var transactionEffect: TransactionEffect? private(set) var databaseEventKinds: [DatabaseEventKind] = [] + var createsExclusiveLock: Bool { + switch transactionEffect { + case .beginTransaction: + // Not technically correct, because only immediate transactions + // acquire an exclusive lock. But SQLite authorizer does not allow + // us to distinguish BEGIN DEFERRED TRANSACTION from + // BEGIN IMMEDIATE TRANSACTION. + return true + default: + return sqlite3_stmt_readonly(sqliteStatement) == 0 + } + } + /// 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..d91ca5467 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 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050DF23940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; + 565050E223940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050DF23940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.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 /* DatabaseExclusiveLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseExclusiveLockPreventionTests.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 = ""; }; @@ -1557,6 +1560,7 @@ 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */, 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */, 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */, + 565050DF23940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */, 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */, 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */, 560A37A91C90084600949E71 /* DatabasePool */, @@ -2346,6 +2350,7 @@ 6340BF871E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56057C662291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, + 565050E123940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.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 /* DatabaseExclusiveLockPreventionTests.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..aef89299c 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -389,6 +389,8 @@ 564A214C226B8E18001F64F1 /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F2E226B89CF001F64F1 /* NumericOverflowTests.swift */; }; 564A214D226B8E18001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FAB226B89DC001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; + 565050E723940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050E623940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; + 565050E823940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050E623940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; 5656A802229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5656A803229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */; }; @@ -606,6 +608,7 @@ 564A1FDC226B89E1001F64F1 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; 564A1FDD226B89E1001F64F1 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 565050E623940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseExclusiveLockPreventionTests.swift; sourceTree = ""; }; 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 = ""; }; 56915792231C0D6A00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; @@ -711,6 +714,7 @@ 564A1F83226B89D8001F64F1 /* DatabaseDateDecodingStrategyTests.swift */, 564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */, 564A1F65226B89D5001F64F1 /* DatabaseErrorTests.swift */, + 565050E623940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */, 564A1F37226B89CF001F64F1 /* DatabaseFunctionTests.swift */, 564A1F5C226B89D3001F64F1 /* DatabaseLogErrorTests.swift */, 564A1FD4226B89E0001F64F1 /* DatabaseMigratorTests.swift */, @@ -1166,6 +1170,7 @@ 564A2045226B89E1001F64F1 /* FetchableRecordDecodableTests.swift in Sources */, 564A1FF4226B89E1001F64F1 /* DatabasePoolCollationTests.swift in Sources */, 564A2025226B89E1001F64F1 /* QueryInterfaceExtensibilityTests.swift in Sources */, + 565050E723940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 564A2038226B89E1001F64F1 /* RowFromDictionaryTests.swift in Sources */, 564A200B226B89E1001F64F1 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 564A2070226B89E1001F64F1 /* ValueObservationCompactMapTests.swift in Sources */, @@ -1370,6 +1375,7 @@ 564A20EE226B8E18001F64F1 /* FetchableRecordDecodableTests.swift in Sources */, 564A20EF226B8E18001F64F1 /* DatabasePoolCollationTests.swift in Sources */, 564A20F0226B8E18001F64F1 /* QueryInterfaceExtensibilityTests.swift in Sources */, + 565050E823940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 564A20F1226B8E18001F64F1 /* RowFromDictionaryTests.swift in Sources */, 564A20F2226B8E18001F64F1 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 564A20F3226B8E18001F64F1 /* ValueObservationCompactMapTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 563a277f1..27a765a47 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -391,6 +391,8 @@ 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; 564A2159226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; 564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; + 565050E423940DD500A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050E323940DD400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; + 565050E523940DD500A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050E323940DD400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; 5656A805229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5656A806229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 5676FBAD22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */; }; @@ -609,6 +611,7 @@ 564A1FDD226B89E1001F64F1 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; }; + 565050E323940DD400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseExclusiveLockPreventionTests.swift; sourceTree = ""; }; 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 = ""; }; 5691578F231C0D5100E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; @@ -714,6 +717,7 @@ 564A1F83226B89D8001F64F1 /* DatabaseDateDecodingStrategyTests.swift */, 564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */, 564A1F65226B89D5001F64F1 /* DatabaseErrorTests.swift */, + 565050E323940DD400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */, 564A1F37226B89CF001F64F1 /* DatabaseFunctionTests.swift */, 564A1F5C226B89D3001F64F1 /* DatabaseLogErrorTests.swift */, 564A1FD4226B89E0001F64F1 /* DatabaseMigratorTests.swift */, @@ -1172,6 +1176,7 @@ 564A2045226B89E1001F64F1 /* FetchableRecordDecodableTests.swift in Sources */, 564A1FF4226B89E1001F64F1 /* DatabasePoolCollationTests.swift in Sources */, 564A2025226B89E1001F64F1 /* QueryInterfaceExtensibilityTests.swift in Sources */, + 565050E423940DD500A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 564A2038226B89E1001F64F1 /* RowFromDictionaryTests.swift in Sources */, 564A200B226B89E1001F64F1 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 564A2070226B89E1001F64F1 /* ValueObservationCompactMapTests.swift in Sources */, @@ -1376,6 +1381,7 @@ 564A20EE226B8E18001F64F1 /* FetchableRecordDecodableTests.swift in Sources */, 564A20EF226B8E18001F64F1 /* DatabasePoolCollationTests.swift in Sources */, 564A20F0226B8E18001F64F1 /* QueryInterfaceExtensibilityTests.swift in Sources */, + 565050E523940DD500A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 564A20F1226B8E18001F64F1 /* RowFromDictionaryTests.swift in Sources */, 564A20F2226B8E18001F64F1 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 564A20F3226B8E18001F64F1 /* ValueObservationCompactMapTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseExclusiveLockPreventionTests.swift b/Tests/GRDBTests/DatabaseExclusiveLockPreventionTests.swift new file mode 100644 index 000000000..7ff9bea7a --- /dev/null +++ b/Tests/GRDBTests/DatabaseExclusiveLockPreventionTests.swift @@ -0,0 +1,413 @@ +import XCTest +#if GRDBCUSTOMSQLITE +import GRDBCustomSQLite +#else +import GRDB +#endif + +class DatabaseExclusiveLockPreventionTests : GRDBTestCase { + + func testExclusiveLockPreventionPreventsNewTransaction() throws { + let dbQueue = try makeDatabaseQueue() + dbQueue.startPreventingExclusiveLock() + 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, "Can't acquire exclusive lock") + XCTAssertEqual(error.sql, "BEGIN TRANSACTION") + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + func testExclusiveLockPreventionDoesNotPreventCommit() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "BEGIN TRANSACTION") + dbQueue.startPreventingExclusiveLock() + try db.execute(sql: "COMMIT") + } + } + + func testExclusiveLockPreventionDoesNotPreventRollback() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "BEGIN TRANSACTION") + dbQueue.startPreventingExclusiveLock() + try db.execute(sql: "ROLLBACK") + } + } + + func testExclusiveLockPreventionDoesNotPreventRead() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE t(a);") + dbQueue.startPreventingExclusiveLock() + try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t"), 0) + } + } + + func testExclusiveLockPreventionDoesNotPreventSavepoint() throws { + // This is because savepoints do not acquire exclusive locks. + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE t(a);") + dbQueue.startPreventingExclusiveLock() + try db.execute(sql: "SAVEPOINT test") + try db.execute(sql: "RELEASE SAVEPOINT test") + } + } + + func testExclusiveLockPreventionPreventsWrite() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE t(a);") + dbQueue.startPreventingExclusiveLock() + 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, "Can't acquire exclusive lock") + XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") + } catch { + XCTFail("Unexpected error: \(error)") + } + } + } + + func testExclusiveLockPreventionRollbacksOnPreventedWrite() throws { + do { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: "CREATE TABLE t(a);") + XCTAssertTrue(db.isInsideTransaction) + dbQueue.startPreventingExclusiveLock() + 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, "Can't acquire exclusive lock") + XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") + } catch { + XCTFail("Unexpected error: \(error)") + } + // Aborded transaction + XCTAssertFalse(db.isInsideTransaction) + } + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Transaction was aborted") + } catch { + XCTFail("Unexpected error: \(error)") + } + + + do { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE t(a);") + dbQueue.startPreventingExclusiveLock() + try db.execute(sql: "SAVEPOINT test") + 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, "Can't acquire exclusive lock") + XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") + } catch { + XCTFail("Unexpected error: \(error)") + } + // Aborded transaction + XCTAssertFalse(db.isInsideTransaction) + } + } + } + + func testExclusiveLockPreventionAbortsDatabaseQueueAccess() throws { + let dbQueue = try makeDatabaseQueue() + + 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.startPreventingExclusiveLock() + semaphore2.signal() + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + + func testExclusiveLockPreventionDoesNotAbortDatabasePoolReadTransaction() throws { + let dbPool = try makeDatabasePool() + + let semaphore1 = DispatchSemaphore(value: 0) + let semaphore2 = DispatchSemaphore(value: 0) + + dbPool.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in + semaphore1.signal() + semaphore2.wait() + return nil + }) + let block1 = { + do { + _ = try dbPool.read { + try Row.fetchAll($0, sql: "SELECT wait()") + } + } catch { + XCTFail("Unexpected error: \(error)") + } + } + let block2 = { + semaphore1.wait() + dbPool.startPreventingExclusiveLock() + semaphore2.signal() + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + + func testExclusiveLockPreventionDoesNotPreventFurtherDatabaseQueueRead() throws { + let dbQueue = try makeDatabaseQueue() + + 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 = { + try! dbQueue.inDatabase { db in + let wasInTransaction = db.isInsideTransaction + do { + _ = try Row.fetchAll(db, sql: "SELECT wait()") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_INTERRUPT) + } catch { + XCTFail("Unexpected error: \(error)") + } + XCTAssertEqual(db.isInsideTransaction, wasInTransaction) + try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t"), 0) + } + } + let block2 = { + semaphore1.wait() + dbQueue.startPreventingExclusiveLock() + semaphore2.signal() + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + + func testWriteTransactionAbortedDuringStatementExecution() throws { + func setup(_ dbWriter: T) throws -> T { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE t(a);") + } + return dbWriter + } + func test(_ dbWriter: DatabaseWriter) throws { + let semaphore1 = DispatchSemaphore(value: 0) + let semaphore2 = DispatchSemaphore(value: 0) + + dbWriter.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in + semaphore1.signal() + semaphore2.wait() + return nil + }) + let block1 = { + do { + try dbWriter.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() + dbWriter.startPreventingExclusiveLock() + semaphore2.signal() + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + + try test(setup(DatabaseQueue())) + try test(setup(makeDatabaseQueue())) + try test(setup(makeDatabasePool())) + } + + func testWriteTransactionAbortedDuringStatementExecutionPreventsFurtherDatabaseAccess() throws { + func setup(_ dbWriter: T) throws -> T { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE t(a);") + } + return dbWriter + } + func test(_ dbWriter: DatabaseWriter) throws { + let semaphore1 = DispatchSemaphore(value: 0) + let semaphore2 = DispatchSemaphore(value: 0) + + dbWriter.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in + semaphore1.signal() + semaphore2.wait() + return nil + }) + let block1 = { + do { + try dbWriter.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) + } catch { + XCTFail("Unexpected error: \(error)") + } + + 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") + } catch { + XCTFail("Unexpected error: \(error)") + } + + do { + try db.execute(sql: "INSERT INTO t (a) VALUES (0)") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ABORT) + XCTAssertEqual(error.message, "Can't acquire exclusive lock") + XCTAssertEqual(error.sql, "INSERT INTO t (a) VALUES (0)") + } catch { + XCTFail("Unexpected error: \(error)") + } + } + 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() + dbWriter.startPreventingExclusiveLock() + semaphore2.signal() + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + + try test(setup(DatabaseQueue())) + try test(setup(makeDatabaseQueue())) + try test(setup(makeDatabasePool())) + } + + func testWriteTransactionAbortedDuringStatementExecutionDoesNotPreventRollback() throws { + func setup(_ dbWriter: T) throws -> T { + try dbWriter.write { db in + try db.execute(sql: "CREATE TABLE t(a);") + } + return dbWriter + } + func test(_ dbWriter: DatabaseWriter) throws { + let semaphore1 = DispatchSemaphore(value: 0) + let semaphore2 = DispatchSemaphore(value: 0) + + dbWriter.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in + semaphore1.signal() + semaphore2.wait() + return nil + }) + let block1 = { + try! dbWriter.writeWithoutTransaction { db in + try db.inTransaction { + do { + try db.execute(sql: "INSERT INTO t SELECT wait()") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_INTERRUPT) + } catch { + XCTFail("Unexpected error: \(error)") + } + + XCTAssertFalse(db.isInsideTransaction) + return .rollback + } + } + } + let block2 = { + semaphore1.wait() + dbWriter.startPreventingExclusiveLock() + semaphore2.signal() + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + + try test(setup(DatabaseQueue())) + try test(setup(makeDatabaseQueue())) + try test(setup(makeDatabasePool())) + } +} From d1db8406f4a94ebc15b3a7d4f2112b270c90ba6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Dec 2019 18:26:52 +0100 Subject: [PATCH 02/17] SQLITE_ABORT_EXCLUSIVE had no real purpose. --- GRDB/Core/Database+Statements.swift | 4 ++-- GRDB/Core/DatabaseError.swift | 8 -------- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 845e8cd5c..c82e223cc 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -225,7 +225,7 @@ extension Database { if preventsExclusiveLock.value && statement.createsExclusiveLock { try? rollback() throw DatabaseError( - resultCode: .SQLITE_ABORT_EXCLUSIVE, + resultCode: .SQLITE_ABORT, message: "Can't acquire exclusive lock", sql: statement.sql, arguments: statement.arguments) @@ -308,7 +308,7 @@ extension Database { if preventsExclusiveLock.value && !statement.isReadonly { try? rollback() throw DatabaseError( - resultCode: .SQLITE_ABORT_EXCLUSIVE, + resultCode: .SQLITE_ABORT, message: "Can't acquire exclusive lock", sql: statement.sql, arguments: statement.arguments) diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index f0e888f15..c9140cd4f 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -153,14 +153,6 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8))) public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8))) public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8))) - - // GRDB-specific - /// SQLITE_ABORT_EXCLUSIVE (32772) is thrown when an SQL statement attempts - /// at acquiring an exclusive lock on a database which prevents exclusive - /// lock acquisition. - /// - /// See DatabaseWriter.prevents - public static let SQLITE_ABORT_EXCLUSIVE = ResultCode(rawValue: (SQLITE_ABORT.rawValue | (128<<8))) // swiftlint:enable operator_usage_whitespace line_length } From d85a7883bb8415456d2f380c826ee3257235f1eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Dec 2019 18:34:51 +0100 Subject: [PATCH 03/17] Database.assertExclusiveLockPrevention mirrors assertNotInsideAbortedTransactionBlock --- GRDB/Core/Database+Statements.swift | 18 ++++-------------- GRDB/Core/Database.swift | 18 +++++++++++++++--- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index c82e223cc..53b0c0d13 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -222,13 +222,8 @@ extension Database { extension Database { func executeUpdateStatement(_ statement: UpdateStatement) throws { - if preventsExclusiveLock.value && statement.createsExclusiveLock { - try? rollback() - throw DatabaseError( - resultCode: .SQLITE_ABORT, - message: "Can't acquire exclusive lock", - sql: statement.sql, - arguments: statement.arguments) + if statement.createsExclusiveLock { + try assertExclusiveLockPrevention(from: statement) } // In aborted transaction, forbid all statements but statements that @@ -305,13 +300,8 @@ extension Database { @inline(__always) func selectStatementWillExecute(_ statement: SelectStatement) throws { - if preventsExclusiveLock.value && !statement.isReadonly { - try? rollback() - throw DatabaseError( - resultCode: .SQLITE_ABORT, - message: "Can't acquire exclusive lock", - sql: statement.sql, - arguments: statement.arguments) + if !statement.isReadonly { + try assertExclusiveLockPrevention(from: statement) } try assertNotInsideAbortedTransactionBlock(sql: statement.sql, arguments: statement.arguments) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 1d956b021..6509a765c 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -707,15 +707,27 @@ extension Database { // - the rollback may fail, and a lock could remain. // // We work around this situation by issuing a rollback on next - // database access which requires an exclusive lock. - // See Database.executeUpdateStatement(_:) and - // Database.selectStatementWillExecute(_:). + // database access which requires an exclusive lock, + // in preventExclusiveLock(from:). } } func stopPreventingExclusiveLock() { preventsExclusiveLock.value = false } + + 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) + } + } } extension Database { From 98dc5df039b521efa1ed88c9b5dfd52e25dfafb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Dec 2019 18:44:23 +0100 Subject: [PATCH 04/17] Avoid race condition in assertExclusiveLockPrevention --- GRDB/Core/Database.swift | 27 ++++++++++++++++++--------- GRDB/Core/SchedulingWatchdog.swift | 9 +++++++++ 2 files changed, 27 insertions(+), 9 deletions(-) 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) } From 74bb9c11d7bfd1d1f39b4bf65e2ad7bc66b0c4ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Dec 2019 18:52:51 +0100 Subject: [PATCH 05/17] Documentatioon --- GRDB/Core/DatabaseWriter.swift | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 7dbfed815..ab3471e93 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -177,10 +177,21 @@ public protocol DatabaseWriter: DatabaseReader { // MARK: - Exclusive Lock Prevention - // TODO: doc + /// Starts exclusive lock prevention. + /// + /// During exclusive lock prevention, any exclusive lock is released as soon + /// as possible, and acquisition of exclusive lock is prevented. + /// + /// All database accesses may throw a DatabaseError of code + /// `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. + /// + /// Read-only connections are not affected. Such errors will never happen to + /// `DatabasePool.read(_:)`, for example. + /// + /// Exclusive lock prevention ends with stopPreventingExclusiveLock(). func startPreventingExclusiveLock() - // TODO: doc + /// Ends exclusive lock prevention. See startPreventingExclusiveLock(). func stopPreventingExclusiveLock() } From 559aae02631ccea5ba769e92c31d42e693eeefbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Dec 2019 18:54:01 +0100 Subject: [PATCH 06/17] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d1f8c92ee..d961d18af 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/659): Exclusive Lock Prevention ### Documentation Diff From f66cf92bba56f77a29a8168262c0d0d22bdb5964 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Dec 2019 18:54:21 +0100 Subject: [PATCH 07/17] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d961d18af..b1984e8b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,7 +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/659): Exclusive Lock Prevention +- [#660](https://github.com/groue/GRDB.swift/pull/660): Exclusive Lock Prevention ### Documentation Diff From 1c318892c9f1e0ad50b416fbc6af36893f3824fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Dec 2019 18:56:06 +0100 Subject: [PATCH 08/17] Documentation --- GRDB/Core/DatabaseWriter.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index ab3471e93..6af0c1cb0 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -179,6 +179,8 @@ public protocol DatabaseWriter: DatabaseReader { /// Starts exclusive lock prevention. /// + /// This method can be called from any thread. + /// /// During exclusive lock prevention, any exclusive lock is released as soon /// as possible, and acquisition of exclusive lock is prevented. /// @@ -192,6 +194,8 @@ public protocol DatabaseWriter: DatabaseReader { func startPreventingExclusiveLock() /// Ends exclusive lock prevention. See startPreventingExclusiveLock(). + /// + /// This method can be called from any thread. func stopPreventingExclusiveLock() } From f604005b4ce1535ea73bdb873cbe4c552c0dcab5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 1 Dec 2019 19:03:47 +0100 Subject: [PATCH 09/17] Improve interrupt() documentation --- GRDB/Core/DatabaseReader.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 5a88f6bea..e5eb5def3 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -69,6 +69,19 @@ 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: - Read From Database From 16025356bfb3c76d14fb56a8aecd70e1d127b591 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Dec 2019 20:27:39 +0100 Subject: [PATCH 10/17] Adapt lock prevention to the journal mode --- GRDB.xcodeproj/project.pbxproj | 16 +- GRDB/Core/Database+Statements.swift | 67 ++- GRDB/Core/Database.swift | 46 +- GRDB/Core/DatabasePool.swift | 14 +- GRDB/Core/DatabaseQueue.swift | 18 +- GRDB/Core/DatabaseReader.swift | 32 ++ GRDB/Core/DatabaseSnapshot.swift | 10 + GRDB/Core/DatabaseWriter.swift | 33 +- GRDB/Core/SerializedDatabase.swift | 8 +- GRDB/Core/Statement.swift | 13 +- GRDBCustom.xcodeproj/project.pbxproj | 12 +- .../GRDBTests.xcodeproj/project.pbxproj | 12 +- .../GRDBTests.xcodeproj/project.pbxproj | 12 +- ...DatabaseExclusiveLockPreventionTests.swift | 413 ---------------- .../DatabaseLockPreventionTests.swift | 455 ++++++++++++++++++ 15 files changed, 625 insertions(+), 536 deletions(-) delete mode 100644 Tests/GRDBTests/DatabaseExclusiveLockPreventionTests.swift create mode 100644 Tests/GRDBTests/DatabaseLockPreventionTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 268f25ba4..22222e100 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -262,9 +262,6 @@ 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564FCE5E20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */; }; 564FCE5F20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */; }; - 565050C82393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050C12393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; - 565050C92393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050C12393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; - 565050CA2393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050C12393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; 5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */; }; @@ -497,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 */; }; @@ -1410,7 +1410,6 @@ 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 = ""; }; 564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; - 565050C12393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseExclusiveLockPreventionTests.swift; sourceTree = ""; }; 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; @@ -1501,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 = ""; }; @@ -2232,8 +2232,8 @@ 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */, 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */, 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */, - 565050C12393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */, 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */, + 5682D71A239582AA004B58C4 /* DatabaseLockPreventionTests.swift */, 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */, 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, @@ -3491,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 */, @@ -3585,7 +3586,6 @@ 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, 56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, - 565050C92393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 5676FBA722F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, @@ -3698,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 */, @@ -3792,7 +3793,6 @@ 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, - 565050C82393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, @@ -4038,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 */, @@ -4132,7 +4133,6 @@ AAA4DDA8230F262000C74B15 /* SQLRequestTests.swift in Sources */, AAA4DDA9230F262000C74B15 /* StatementArguments+FoundationTests.swift in Sources */, AAA4DDAA230F262000C74B15 /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, - 565050CA2393D3AF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, AAA4DDAB230F262000C74B15 /* ValueObservationRegionRecordingTests.swift in Sources */, AAA4DDAC230F262000C74B15 /* RowFetchTests.swift in Sources */, AAA4DDAD230F262000C74B15 /* AssociationChainRowScopesTests.swift in Sources */, diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 53b0c0d13..753a32ff0 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -220,11 +220,68 @@ extension Database { } extension Database { + // TODO: cache + private func journalMode() throws -> String? { + // Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so + // that we don't create an infinite loop of assertLockPrevention(from:) + let journalModeStatement = try internalStatementCache.selectStatement("PRAGMA journal_mode") + try journalModeStatement.reset() + defer { + try? journalModeStatement.reset() + } + let code = sqlite3_step(journalModeStatement.sqliteStatement) + guard code == SQLITE_ROW else { + try journalModeStatement.didFail(withResultCode: code) + } + return String(cString: sqlite3_column_text(journalModeStatement.sqliteStatement, 0)!) + } + + private func assertLockPrevention(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.leavesTransaction + { + // Accept statements that remove 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 of assertLockPrevention(from:) + _ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil) + + throw DatabaseError( + resultCode: .SQLITE_ABORT, + message: "Can't acquire lock", + sql: statement.sql, + arguments: statement.arguments) + } + } func executeUpdateStatement(_ statement: UpdateStatement) throws { - if statement.createsExclusiveLock { - try assertExclusiveLockPrevention(from: statement) - } + try assertLockPrevention(from: statement) // In aborted transaction, forbid all statements but statements that // manage transactions. @@ -300,9 +357,7 @@ extension Database { @inline(__always) func selectStatementWillExecute(_ statement: SelectStatement) throws { - if !statement.isReadonly { - try assertExclusiveLockPrevention(from: statement) - } + try assertLockPrevention(from: statement) try assertNotInsideAbortedTransactionBlock(sql: statement.sql, arguments: statement.arguments) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 2488e9284..55a564032 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -179,8 +179,8 @@ public final class Database { return isInsideTransactionBlock && !isInsideTransaction } - // See startPreventingExclusiveLock - var preventsExclusiveLock = ReadWriteBox(value: false) + // See startPreventingLock + var preventsLock = LockedBox(value: false) // MARK: - Private properties @@ -676,24 +676,24 @@ extension Database { sqlite3_interrupt(sqliteConnection) } - /// Aborts any exclusive lock, as soon as possible, at any cost. + /// Release any database lock, as soon as possible, at any cost. /// /// See https://www.sqlite.org/lockingv3.html - func startPreventingExclusiveLock() { - preventsExclusiveLock.write { preventsExclusiveLock in - if preventsExclusiveLock { + func startPreventingLock() { + preventsLock.write { preventsLock in + if preventsLock { return } // Prevent future lock acquisition - preventsExclusiveLock = true + preventsLock = true // Interrupt the database because this may trigger an // SQLITE_INTERRUPT error which may itself abort a transaction and - // release an exclusive lock. See https://www.sqlite.org/c3ref/interrupt.html + // release a lock. See https://www.sqlite.org/c3ref/interrupt.html interrupt() - // What about the eventual remaining exclusive lock? + // 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: // @@ -707,35 +707,13 @@ extension Database { // - the rollback may fail, and a lock could remain. // // We work around this situation by issuing a rollback on next - // database access which requires an exclusive lock, + // database access which requires a lock, // in preventExclusiveLock(from:). } } - func stopPreventingExclusiveLock() { - preventsExclusiveLock.value = false - } - - func assertExclusiveLockPrevention(from statement: Statement) throws { - 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) - } - } + func stopPreventingLock() { + preventsLock.value = false } } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index fbb59acab..31a7743a8 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -259,20 +259,22 @@ extension DatabasePool: DatabaseReader { readerPool.forEach { $0.interrupt() } } - public func startPreventingExclusiveLock() { + // MARK: - Lock Prevention + + public func startPreventingLock() { if configuration.readonly { - // read-only connections can't acquire exclusive locks + // read-only WAL connections can't acquire locks return } - writer.startPreventingExclusiveLock() + writer.startPreventingLock() } - public func stopPreventingExclusiveLock() { + public func stopPreventingLock() { if configuration.readonly { - // read-only connections can't acquire exclusive locks + // read-only WAL connections can't acquire locks return } - writer.stopPreventingExclusiveLock() + writer.stopPreventingLock() } // MARK: - Reading from Database diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index c67bc77fc..933e50773 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -155,20 +155,14 @@ extension DatabaseQueue { writer.interrupt() } - public func startPreventingExclusiveLock() { - if configuration.readonly { - // read-only connections can't acquire exclusive locks - return - } - writer.startPreventingExclusiveLock() + // MARK: - Lock Prevention + + public func startPreventingLock() { + writer.startPreventingLock() } - public func stopPreventingExclusiveLock() { - if configuration.readonly { - // read-only connections can't acquire exclusive locks - return - } - writer.stopPreventingExclusiveLock() + public func stopPreventingLock() { + writer.stopPreventingLock() } // MARK: - Reading from Database diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index e5eb5def3..e6cdc49f3 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -84,6 +84,26 @@ public protocol DatabaseReader: AnyObject { /// } 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`. + /// + /// 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 @@ -315,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 6af0c1cb0..5834a6e50 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -174,29 +174,6 @@ public protocol DatabaseWriter: DatabaseReader { /// :nodoc: func spawnConcurrentRead(_ block: @escaping (Result) -> Void) #endif - - // MARK: - Exclusive Lock Prevention - - /// Starts exclusive lock prevention. - /// - /// This method can be called from any thread. - /// - /// During exclusive lock prevention, any exclusive lock is released as soon - /// as possible, and acquisition of exclusive lock is prevented. - /// - /// All database accesses may throw a DatabaseError of code - /// `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. - /// - /// Read-only connections are not affected. Such errors will never happen to - /// `DatabasePool.read(_:)`, for example. - /// - /// Exclusive lock prevention ends with stopPreventingExclusiveLock(). - func startPreventingExclusiveLock() - - /// Ends exclusive lock prevention. See startPreventingExclusiveLock(). - /// - /// This method can be called from any thread. - func stopPreventingExclusiveLock() } extension DatabaseWriter { @@ -631,16 +608,16 @@ public final class AnyDatabaseWriter: DatabaseWriter { base.interrupt() } - // MARK: - Exclusive Lock Prevention + // MARK: - Lock Prevention /// :nodoc: - public func startPreventingExclusiveLock() { - base.startPreventingExclusiveLock() + public func startPreventingLock() { + base.startPreventingLock() } /// :nodoc: - public func stopPreventingExclusiveLock() { - base.stopPreventingExclusiveLock() + public func stopPreventingLock() { + base.stopPreventingLock() } // MARK: - Reading from Database diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index a542323ec..4e197c639 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -204,14 +204,14 @@ final class SerializedDatabase { db.interrupt() } - func startPreventingExclusiveLock() { + func startPreventingLock() { // Intentionally not scheduled in our serial queue - db.startPreventingExclusiveLock() + db.startPreventingLock() } - func stopPreventingExclusiveLock() { + func stopPreventingLock() { // Intentionally not scheduled in our serial queue - db.stopPreventingExclusiveLock() + db.stopPreventingLock() } /// Fatal error if current dispatch queue is not valid. diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 5927f377a..bb1af4457 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -453,16 +453,15 @@ public final class UpdateStatement: Statement { private(set) var transactionEffect: TransactionEffect? private(set) var databaseEventKinds: [DatabaseEventKind] = [] - var createsExclusiveLock: Bool { + var leavesTransaction: Bool { switch transactionEffect { - case .beginTransaction: - // Not technically correct, because only immediate transactions - // acquire an exclusive lock. But SQLite authorizer does not allow - // us to distinguish BEGIN DEFERRED TRANSACTION from - // BEGIN IMMEDIATE TRANSACTION. + case .commitTransaction, .rollbackTransaction, + .releaseSavepoint, .rollbackSavepoint: + // Not technically correct: ROLLBACK TRANSACTION TO SAVEPOINT and + // RELEASE SAVEPOINT do not leave transactions. return true default: - return sqlite3_stmt_readonly(sqliteStatement) == 0 + return false } } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index d91ca5467..6002b5311 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -131,8 +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 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050DF23940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; - 565050E223940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050DF23940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.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 */; }; @@ -809,7 +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 /* DatabaseExclusiveLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseExclusiveLockPreventionTests.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 = ""; }; @@ -1560,8 +1560,8 @@ 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */, 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */, 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */, - 565050DF23940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */, 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */, + 565050DF23940CE400A7F660 /* DatabaseLockPreventionTests.swift */, 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */, 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, @@ -2350,7 +2350,7 @@ 6340BF871E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56057C662291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, - 565050E123940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, + 565050E123940CE400A7F660 /* DatabaseLockPreventionTests.swift in Sources */, F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */, 5656A7F722946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, 5615B259222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */, @@ -2690,7 +2690,7 @@ F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, 56057C652291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */, - 565050E223940CE400A7F660 /* DatabaseExclusiveLockPreventionTests.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 aef89299c..aa03a319f 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -389,12 +389,12 @@ 564A214C226B8E18001F64F1 /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F2E226B89CF001F64F1 /* NumericOverflowTests.swift */; }; 564A214D226B8E18001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1FAB226B89DC001F64F1 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; - 565050E723940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050E623940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; - 565050E823940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050E623940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; 5656A802229474DD001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 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,9 +608,9 @@ 564A1FDC226B89E1001F64F1 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; 564A1FDD226B89E1001F64F1 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 565050E623940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseExclusiveLockPreventionTests.swift; sourceTree = ""; }; 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 = ""; }; @@ -714,8 +714,8 @@ 564A1F83226B89D8001F64F1 /* DatabaseDateDecodingStrategyTests.swift */, 564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */, 564A1F65226B89D5001F64F1 /* DatabaseErrorTests.swift */, - 565050E623940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift */, 564A1F37226B89CF001F64F1 /* DatabaseFunctionTests.swift */, + 5682D724239582C6004B58C4 /* DatabaseLockPreventionTests.swift */, 564A1F5C226B89D3001F64F1 /* DatabaseLogErrorTests.swift */, 564A1FD4226B89E0001F64F1 /* DatabaseMigratorTests.swift */, 564A1F6A226B89D5001F64F1 /* DatabasePoolBackupTests.swift */, @@ -1170,7 +1170,6 @@ 564A2045226B89E1001F64F1 /* FetchableRecordDecodableTests.swift in Sources */, 564A1FF4226B89E1001F64F1 /* DatabasePoolCollationTests.swift in Sources */, 564A2025226B89E1001F64F1 /* QueryInterfaceExtensibilityTests.swift in Sources */, - 565050E723940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 564A2038226B89E1001F64F1 /* RowFromDictionaryTests.swift in Sources */, 564A200B226B89E1001F64F1 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 564A2070226B89E1001F64F1 /* ValueObservationCompactMapTests.swift in Sources */, @@ -1252,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 */, @@ -1375,7 +1375,6 @@ 564A20EE226B8E18001F64F1 /* FetchableRecordDecodableTests.swift in Sources */, 564A20EF226B8E18001F64F1 /* DatabasePoolCollationTests.swift in Sources */, 564A20F0226B8E18001F64F1 /* QueryInterfaceExtensibilityTests.swift in Sources */, - 565050E823940DEF00A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 564A20F1226B8E18001F64F1 /* RowFromDictionaryTests.swift in Sources */, 564A20F2226B8E18001F64F1 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 564A20F3226B8E18001F64F1 /* ValueObservationCompactMapTests.swift in Sources */, @@ -1457,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 27a765a47..791fa9944 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -391,12 +391,12 @@ 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; 564A2159226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; 564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; - 565050E423940DD500A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050E323940DD400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; - 565050E523940DD500A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050E323940DD400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */; }; 5656A805229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; 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,9 +611,9 @@ 564A1FDD226B89E1001F64F1 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; }; - 565050E323940DD400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseExclusiveLockPreventionTests.swift; sourceTree = ""; }; 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 = ""; }; @@ -717,8 +717,8 @@ 564A1F83226B89D8001F64F1 /* DatabaseDateDecodingStrategyTests.swift */, 564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */, 564A1F65226B89D5001F64F1 /* DatabaseErrorTests.swift */, - 565050E323940DD400A7F660 /* DatabaseExclusiveLockPreventionTests.swift */, 564A1F37226B89CF001F64F1 /* DatabaseFunctionTests.swift */, + 5682D727239582E2004B58C4 /* DatabaseLockPreventionTests.swift */, 564A1F5C226B89D3001F64F1 /* DatabaseLogErrorTests.swift */, 564A1FD4226B89E0001F64F1 /* DatabaseMigratorTests.swift */, 564A1F6A226B89D5001F64F1 /* DatabasePoolBackupTests.swift */, @@ -1176,7 +1176,6 @@ 564A2045226B89E1001F64F1 /* FetchableRecordDecodableTests.swift in Sources */, 564A1FF4226B89E1001F64F1 /* DatabasePoolCollationTests.swift in Sources */, 564A2025226B89E1001F64F1 /* QueryInterfaceExtensibilityTests.swift in Sources */, - 565050E423940DD500A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 564A2038226B89E1001F64F1 /* RowFromDictionaryTests.swift in Sources */, 564A200B226B89E1001F64F1 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 564A2070226B89E1001F64F1 /* ValueObservationCompactMapTests.swift in Sources */, @@ -1225,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 */, @@ -1381,7 +1381,6 @@ 564A20EE226B8E18001F64F1 /* FetchableRecordDecodableTests.swift in Sources */, 564A20EF226B8E18001F64F1 /* DatabasePoolCollationTests.swift in Sources */, 564A20F0226B8E18001F64F1 /* QueryInterfaceExtensibilityTests.swift in Sources */, - 565050E523940DD500A7F660 /* DatabaseExclusiveLockPreventionTests.swift in Sources */, 564A20F1226B8E18001F64F1 /* RowFromDictionaryTests.swift in Sources */, 564A20F2226B8E18001F64F1 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 564A20F3226B8E18001F64F1 /* ValueObservationCompactMapTests.swift in Sources */, @@ -1430,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/DatabaseExclusiveLockPreventionTests.swift b/Tests/GRDBTests/DatabaseExclusiveLockPreventionTests.swift deleted file mode 100644 index 7ff9bea7a..000000000 --- a/Tests/GRDBTests/DatabaseExclusiveLockPreventionTests.swift +++ /dev/null @@ -1,413 +0,0 @@ -import XCTest -#if GRDBCUSTOMSQLITE -import GRDBCustomSQLite -#else -import GRDB -#endif - -class DatabaseExclusiveLockPreventionTests : GRDBTestCase { - - func testExclusiveLockPreventionPreventsNewTransaction() throws { - let dbQueue = try makeDatabaseQueue() - dbQueue.startPreventingExclusiveLock() - 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, "Can't acquire exclusive lock") - XCTAssertEqual(error.sql, "BEGIN TRANSACTION") - } catch { - XCTFail("Unexpected error: \(error)") - } - } - - func testExclusiveLockPreventionDoesNotPreventCommit() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.execute(sql: "BEGIN TRANSACTION") - dbQueue.startPreventingExclusiveLock() - try db.execute(sql: "COMMIT") - } - } - - func testExclusiveLockPreventionDoesNotPreventRollback() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.execute(sql: "BEGIN TRANSACTION") - dbQueue.startPreventingExclusiveLock() - try db.execute(sql: "ROLLBACK") - } - } - - func testExclusiveLockPreventionDoesNotPreventRead() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE TABLE t(a);") - dbQueue.startPreventingExclusiveLock() - try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t"), 0) - } - } - - func testExclusiveLockPreventionDoesNotPreventSavepoint() throws { - // This is because savepoints do not acquire exclusive locks. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE TABLE t(a);") - dbQueue.startPreventingExclusiveLock() - try db.execute(sql: "SAVEPOINT test") - try db.execute(sql: "RELEASE SAVEPOINT test") - } - } - - func testExclusiveLockPreventionPreventsWrite() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE TABLE t(a);") - dbQueue.startPreventingExclusiveLock() - 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, "Can't acquire exclusive lock") - XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") - } catch { - XCTFail("Unexpected error: \(error)") - } - } - } - - func testExclusiveLockPreventionRollbacksOnPreventedWrite() throws { - do { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { db in - try db.execute(sql: "CREATE TABLE t(a);") - XCTAssertTrue(db.isInsideTransaction) - dbQueue.startPreventingExclusiveLock() - 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, "Can't acquire exclusive lock") - XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") - } catch { - XCTFail("Unexpected error: \(error)") - } - // Aborded transaction - XCTAssertFalse(db.isInsideTransaction) - } - XCTFail("Expected error") - } catch let error as DatabaseError { - XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Transaction was aborted") - } catch { - XCTFail("Unexpected error: \(error)") - } - - - do { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.execute(sql: "CREATE TABLE t(a);") - dbQueue.startPreventingExclusiveLock() - try db.execute(sql: "SAVEPOINT test") - 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, "Can't acquire exclusive lock") - XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") - } catch { - XCTFail("Unexpected error: \(error)") - } - // Aborded transaction - XCTAssertFalse(db.isInsideTransaction) - } - } - } - - func testExclusiveLockPreventionAbortsDatabaseQueueAccess() throws { - let dbQueue = try makeDatabaseQueue() - - 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.startPreventingExclusiveLock() - semaphore2.signal() - } - let blocks = [block1, block2] - DispatchQueue.concurrentPerform(iterations: blocks.count) { index in - blocks[index]() - } - } - - func testExclusiveLockPreventionDoesNotAbortDatabasePoolReadTransaction() throws { - let dbPool = try makeDatabasePool() - - let semaphore1 = DispatchSemaphore(value: 0) - let semaphore2 = DispatchSemaphore(value: 0) - - dbPool.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in - semaphore1.signal() - semaphore2.wait() - return nil - }) - let block1 = { - do { - _ = try dbPool.read { - try Row.fetchAll($0, sql: "SELECT wait()") - } - } catch { - XCTFail("Unexpected error: \(error)") - } - } - let block2 = { - semaphore1.wait() - dbPool.startPreventingExclusiveLock() - semaphore2.signal() - } - let blocks = [block1, block2] - DispatchQueue.concurrentPerform(iterations: blocks.count) { index in - blocks[index]() - } - } - - func testExclusiveLockPreventionDoesNotPreventFurtherDatabaseQueueRead() throws { - let dbQueue = try makeDatabaseQueue() - - 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 = { - try! dbQueue.inDatabase { db in - let wasInTransaction = db.isInsideTransaction - do { - _ = try Row.fetchAll(db, sql: "SELECT wait()") - XCTFail("Expected error") - } catch let error as DatabaseError { - XCTAssertEqual(error.resultCode, .SQLITE_INTERRUPT) - } catch { - XCTFail("Unexpected error: \(error)") - } - XCTAssertEqual(db.isInsideTransaction, wasInTransaction) - try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t"), 0) - } - } - let block2 = { - semaphore1.wait() - dbQueue.startPreventingExclusiveLock() - semaphore2.signal() - } - let blocks = [block1, block2] - DispatchQueue.concurrentPerform(iterations: blocks.count) { index in - blocks[index]() - } - } - - func testWriteTransactionAbortedDuringStatementExecution() throws { - func setup(_ dbWriter: T) throws -> T { - try dbWriter.write { db in - try db.execute(sql: "CREATE TABLE t(a);") - } - return dbWriter - } - func test(_ dbWriter: DatabaseWriter) throws { - let semaphore1 = DispatchSemaphore(value: 0) - let semaphore2 = DispatchSemaphore(value: 0) - - dbWriter.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in - semaphore1.signal() - semaphore2.wait() - return nil - }) - let block1 = { - do { - try dbWriter.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() - dbWriter.startPreventingExclusiveLock() - semaphore2.signal() - } - let blocks = [block1, block2] - DispatchQueue.concurrentPerform(iterations: blocks.count) { index in - blocks[index]() - } - } - - try test(setup(DatabaseQueue())) - try test(setup(makeDatabaseQueue())) - try test(setup(makeDatabasePool())) - } - - func testWriteTransactionAbortedDuringStatementExecutionPreventsFurtherDatabaseAccess() throws { - func setup(_ dbWriter: T) throws -> T { - try dbWriter.write { db in - try db.execute(sql: "CREATE TABLE t(a);") - } - return dbWriter - } - func test(_ dbWriter: DatabaseWriter) throws { - let semaphore1 = DispatchSemaphore(value: 0) - let semaphore2 = DispatchSemaphore(value: 0) - - dbWriter.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in - semaphore1.signal() - semaphore2.wait() - return nil - }) - let block1 = { - do { - try dbWriter.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) - } catch { - XCTFail("Unexpected error: \(error)") - } - - 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") - } catch { - XCTFail("Unexpected error: \(error)") - } - - do { - try db.execute(sql: "INSERT INTO t (a) VALUES (0)") - XCTFail("Expected error") - } catch let error as DatabaseError { - XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire exclusive lock") - XCTAssertEqual(error.sql, "INSERT INTO t (a) VALUES (0)") - } catch { - XCTFail("Unexpected error: \(error)") - } - } - 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() - dbWriter.startPreventingExclusiveLock() - semaphore2.signal() - } - let blocks = [block1, block2] - DispatchQueue.concurrentPerform(iterations: blocks.count) { index in - blocks[index]() - } - } - - try test(setup(DatabaseQueue())) - try test(setup(makeDatabaseQueue())) - try test(setup(makeDatabasePool())) - } - - func testWriteTransactionAbortedDuringStatementExecutionDoesNotPreventRollback() throws { - func setup(_ dbWriter: T) throws -> T { - try dbWriter.write { db in - try db.execute(sql: "CREATE TABLE t(a);") - } - return dbWriter - } - func test(_ dbWriter: DatabaseWriter) throws { - let semaphore1 = DispatchSemaphore(value: 0) - let semaphore2 = DispatchSemaphore(value: 0) - - dbWriter.add(function: DatabaseFunction("wait", argumentCount: 0, pure: true) { _ in - semaphore1.signal() - semaphore2.wait() - return nil - }) - let block1 = { - try! dbWriter.writeWithoutTransaction { db in - try db.inTransaction { - do { - try db.execute(sql: "INSERT INTO t SELECT wait()") - XCTFail("Expected error") - } catch let error as DatabaseError { - XCTAssertEqual(error.resultCode, .SQLITE_INTERRUPT) - } catch { - XCTFail("Unexpected error: \(error)") - } - - XCTAssertFalse(db.isInsideTransaction) - return .rollback - } - } - } - let block2 = { - semaphore1.wait() - dbWriter.startPreventingExclusiveLock() - semaphore2.signal() - } - let blocks = [block1, block2] - DispatchQueue.concurrentPerform(iterations: blocks.count) { index in - blocks[index]() - } - } - - try test(setup(DatabaseQueue())) - try test(setup(makeDatabaseQueue())) - try test(setup(makeDatabasePool())) - } -} diff --git a/Tests/GRDBTests/DatabaseLockPreventionTests.swift b/Tests/GRDBTests/DatabaseLockPreventionTests.swift new file mode 100644 index 000000000..844933dc5 --- /dev/null +++ b/Tests/GRDBTests/DatabaseLockPreventionTests.swift @@ -0,0 +1,455 @@ +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, "Can't acquire lock") + 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, "Can't acquire lock") + 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, "Can't acquire lock") + 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, "Can't acquire lock") + 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, "Can't acquire lock") + 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, "Can't acquire lock") + 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, "Can't acquire lock") + 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, "Can't acquire lock") + 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, "Can't acquire lock") + 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, "Can't acquire lock") + 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, "Can't acquire lock") + 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(journalMode: String) throws { + let dbQueue = try makeDatabaseQueue(journalMode: journalMode) + 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) + switch journalMode { + case "delete": + XCTAssertEqual(error.message, "Can't acquire lock") + case "wal": + XCTAssertEqual(error.message, "Transaction was aborted") + default: + XCTFail() + } + 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(journalMode: "delete") + try test(journalMode: "wal") + } +} From 2b4a9207323895539e0357d1f5b529331285c731 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Dec 2019 20:39:55 +0100 Subject: [PATCH 11/17] Cleanup --- GRDB/Core/Database+Statements.swift | 4 ++-- GRDB/Core/Statement.swift | 13 ++++++++++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 753a32ff0..c36895ae1 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -255,9 +255,9 @@ extension Database { if let updateStatement = statement as? UpdateStatement, - updateStatement.leavesTransaction + updateStatement.releasesDatabaseLock { - // Accept statements that remove locks: + // Accept statements that release locks: // - COMMIT // - ROLLBACK // - ROLLBACK TRANSACTION TO SAVEPOINT diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index bb1af4457..95a95ae43 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -453,12 +453,19 @@ public final class UpdateStatement: Statement { private(set) var transactionEffect: TransactionEffect? private(set) var databaseEventKinds: [DatabaseEventKind] = [] - var leavesTransaction: Bool { + var releasesDatabaseLock: Bool { + guard let transactionEffect = transactionEffect else { + return false + } + switch transactionEffect { case .commitTransaction, .rollbackTransaction, .releaseSavepoint, .rollbackSavepoint: - // Not technically correct: ROLLBACK TRANSACTION TO SAVEPOINT and - // RELEASE SAVEPOINT do not leave transactions. + // 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 From 9efd5965eac92398802bd08a1aadb973beaef82a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 2 Dec 2019 20:56:06 +0100 Subject: [PATCH 12/17] Cleanup --- GRDB/Core/Database+Statements.swift | 60 -------------- GRDB/Core/Database.swift | 123 +++++++++++++++++++--------- 2 files changed, 84 insertions(+), 99 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index c36895ae1..4319b09bc 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -220,66 +220,6 @@ extension Database { } extension Database { - // TODO: cache - private func journalMode() throws -> String? { - // Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so - // that we don't create an infinite loop of assertLockPrevention(from:) - let journalModeStatement = try internalStatementCache.selectStatement("PRAGMA journal_mode") - try journalModeStatement.reset() - defer { - try? journalModeStatement.reset() - } - let code = sqlite3_step(journalModeStatement.sqliteStatement) - guard code == SQLITE_ROW else { - try journalModeStatement.didFail(withResultCode: code) - } - return String(cString: sqlite3_column_text(journalModeStatement.sqliteStatement, 0)!) - } - - private func assertLockPrevention(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 of assertLockPrevention(from:) - _ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil) - - throw DatabaseError( - resultCode: .SQLITE_ABORT, - message: "Can't acquire lock", - sql: statement.sql, - arguments: statement.arguments) - } - } - func executeUpdateStatement(_ statement: UpdateStatement) throws { try assertLockPrevention(from: statement) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 55a564032..089d3e0bf 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -179,9 +179,12 @@ public final class Database { return isInsideTransactionBlock && !isInsideTransaction } - // See startPreventingLock + /// See startPreventingLock var preventsLock = LockedBox(value: false) + /// Support for assertLockPrevention(from:) + var journalModeCache: String? + // MARK: - Private properties private var busyCallback: BusyCallback? @@ -202,9 +205,6 @@ public final class Database { deinit { assert(isClosed) } -} - -extension Database { // MARK: - Database Opening @@ -230,9 +230,6 @@ extension Database { } throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite? } -} - -extension Database { // MARK: - Database Setup @@ -396,7 +393,7 @@ extension Database { }, dbPointer) } - + private func activateExtendedCodes() throws { let code = sqlite3_extended_result_codes(sqliteConnection, 1) @@ -431,9 +428,6 @@ extension Database { // another passphrase. try makeSelectStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next() } -} - -extension Database { // MARK: - Database Closing @@ -507,9 +501,6 @@ extension Database { log(ResultCode(rawValue: code), "could not close database: \(message)") } } -} - -extension Database { // MARK: - Functions @@ -533,9 +524,6 @@ extension Database { functions.remove(function) function.uninstall(in: self) } -} - -extension Database { // MARK: - Collations @@ -573,9 +561,6 @@ extension Database { SQLITE_UTF8, nil, nil, nil) } -} - -extension Database { // MARK: - Read-Only Access @@ -626,9 +611,6 @@ extension Database { return result! } -} - -extension Database { // MARK: - Authorizer @@ -639,9 +621,6 @@ extension Database { defer { self._authorizer = old } return try block() } -} - -extension Database { // MARK: - Recording of the selected region @@ -661,9 +640,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 { @@ -671,11 +650,15 @@ extension Database { } } + // MARK: - Interrupt + // See https://www.sqlite.org/c3ref/interrupt.html func interrupt() { sqlite3_interrupt(sqliteConnection) } + // MARK: - Lock Prevention + /// Release any database lock, as soon as possible, at any cost. /// /// See https://www.sqlite.org/lockingv3.html @@ -713,11 +696,79 @@ extension Database { } func stopPreventingLock() { - preventsLock.value = false + preventsLock.write { preventsLock in + preventsLock = false + // Reset journalMode cache until next need for it + journalModeCache = nil + } } -} - -extension Database { + + /// Support for assertLockPrevention(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 of assertLockPrevention(from:) + let journalModeStatement = try internalStatementCache.selectStatement("PRAGMA journal_mode") + try journalModeStatement.reset() + defer { + try? journalModeStatement.reset() + } + let code = sqlite3_step(journalModeStatement.sqliteStatement) + guard code == SQLITE_ROW else { + try journalModeStatement.didFail(withResultCode: code) + } + let journalMode = String(cString: sqlite3_column_text(journalModeStatement.sqliteStatement, 0)!) + journalModeCache = journalMode + return journalMode + } + + func assertLockPrevention(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 of assertLockPrevention(from:) + _ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil) + + throw DatabaseError( + resultCode: .SQLITE_ABORT, + message: "Can't acquire lock", + sql: statement.sql, + arguments: statement.arguments) + } + } + // MARK: - Transactions & Savepoint func assertNotInsideAbortedTransactionBlock( @@ -1024,9 +1075,6 @@ extension Database { try execute(sql: "COMMIT TRANSACTION") assert(!isInsideTransaction) } -} - -extension Database { // MARK: - Memory Management @@ -1036,9 +1084,6 @@ extension Database { internalStatementCache.clear() publicStatementCache.clear() } -} - -extension Database { // MARK: - Backup From 7f66c85e679101e0f400b7ae069b660c64396510 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Dec 2019 08:11:14 +0100 Subject: [PATCH 13/17] Cleanup --- GRDB/Core/Database+Statements.swift | 8 +-- GRDB/Core/Database.swift | 94 +++++++++++++---------------- 2 files changed, 45 insertions(+), 57 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 4319b09bc..d9e91de98 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -221,12 +221,12 @@ extension Database { extension Database { func executeUpdateStatement(_ statement: UpdateStatement) throws { - try assertLockPrevention(from: statement) + try checkLockPrevention(from: statement) // In aborted transaction, forbid all statements but statements that // manage transactions. if statement.transactionEffect == nil { - try assertNotInsideAbortedTransactionBlock(sql: statement.sql, arguments: statement.arguments) + try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) } let authorizer = observationBroker.updateStatementWillExecute(statement) @@ -297,9 +297,9 @@ extension Database { @inline(__always) func selectStatementWillExecute(_ statement: SelectStatement) throws { - try assertLockPrevention(from: statement) + try checkLockPrevention(from: statement) - try assertNotInsideAbortedTransactionBlock(sql: statement.sql, arguments: statement.arguments) + try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) if _isRecordingSelectedRegion { // Don't record schema introspection queries, which may be diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 089d3e0bf..18aad7f2e 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -147,42 +147,14 @@ public final class Database { var _isRecordingSelectedRegion: Bool = false var _selectedRegion = DatabaseRegion() - /// True inside `inTransaction { ... }` and `inSavepoint { ... }` + /// Support for checkForAbortedTransaction() var isInsideTransactionBlock = false - /// 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. - var isInsideAbortedTransactionBlock: Bool { - return isInsideTransactionBlock && !isInsideTransaction - } - - /// See startPreventingLock + /// Support for checkLockPrevention(from:) var preventsLock = LockedBox(value: false) - /// Support for assertLockPrevention(from:) + /// Support for checkLockPrevention(from:) + /// This cache is never cleared: we assume journal mode never changes. var journalModeCache: String? // MARK: - Private properties @@ -698,34 +670,33 @@ public final class Database { func stopPreventingLock() { preventsLock.write { preventsLock in preventsLock = false - // Reset journalMode cache until next need for it - journalModeCache = nil } } - /// Support for assertLockPrevention(from:) + /// Support for checkLockPrevention(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 of assertLockPrevention(from:) - let journalModeStatement = try internalStatementCache.selectStatement("PRAGMA journal_mode") - try journalModeStatement.reset() - defer { - try? journalModeStatement.reset() + // that we don't create an infinite loop in checkLockPrevention(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 code = sqlite3_step(journalModeStatement.sqliteStatement) - guard code == SQLITE_ROW else { - try journalModeStatement.didFail(withResultCode: code) - } - let journalMode = String(cString: sqlite3_column_text(journalModeStatement.sqliteStatement, 0)!) + let journalMode = String(cString: cString) journalModeCache = journalMode return journalMode } - func assertLockPrevention(from statement: Statement) throws { + /// Throws SQLITE_ABORT during lock prevention, if statement would lock + /// the database. + func checkLockPrevention(from statement: Statement) throws { try preventsLock.read { preventsLock in guard preventsLock else { return @@ -758,7 +729,7 @@ public final class Database { // as explained in Database.startPreventingLock(). // // Use sqlite3_exec instead of `try? rollback()` in order to avoid - // an infinite loop of assertLockPrevention(from:) + // an infinite loop in checkLockPrevention(from:) _ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil) throw DatabaseError( @@ -771,12 +742,29 @@ public final class Database { // 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", @@ -828,11 +816,11 @@ public final class 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() @@ -920,11 +908,11 @@ public final class 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") From 4e26e8e7448f39b9f35bf3125b6719ebaa785c88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Dec 2019 08:13:19 +0100 Subject: [PATCH 14/17] Lock prevention: better error message --- GRDB/Core/Database.swift | 2 +- .../DatabaseLockPreventionTests.swift | 24 +++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 18aad7f2e..7fb064346 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -734,7 +734,7 @@ public final class Database { throw DatabaseError( resultCode: .SQLITE_ABORT, - message: "Can't acquire lock", + message: "Aborted due to lock prevention", sql: statement.sql, arguments: statement.arguments) } diff --git a/Tests/GRDBTests/DatabaseLockPreventionTests.swift b/Tests/GRDBTests/DatabaseLockPreventionTests.swift index 844933dc5..9b2a1acc1 100644 --- a/Tests/GRDBTests/DatabaseLockPreventionTests.swift +++ b/Tests/GRDBTests/DatabaseLockPreventionTests.swift @@ -27,7 +27,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "BEGIN TRANSACTION") } @@ -38,7 +38,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "BEGIN IMMEDIATE TRANSACTION") } @@ -49,7 +49,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "BEGIN EXCLUSIVE TRANSACTION") } @@ -60,7 +60,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "SAVEPOINT test") } } @@ -86,7 +86,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "BEGIN IMMEDIATE TRANSACTION") } @@ -97,7 +97,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "BEGIN EXCLUSIVE TRANSACTION") } } @@ -166,7 +166,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "SELECT COUNT(*) FROM t") } } @@ -198,7 +198,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") } } @@ -215,7 +215,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") } @@ -227,7 +227,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") } } @@ -247,7 +247,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES") } // Aborded transaction @@ -420,7 +420,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) switch journalMode { case "delete": - XCTAssertEqual(error.message, "Can't acquire lock") + XCTAssertEqual(error.message, "Aborted due to lock prevention") case "wal": XCTAssertEqual(error.message, "Transaction was aborted") default: From 17864d3dccf8986cc5a54d1d3b911558e4d7e6fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Dec 2019 08:15:57 +0100 Subject: [PATCH 15/17] Documentation --- GRDB/Core/Database.swift | 15 +++++++++++++-- GRDB/Core/DatabaseReader.swift | 2 +- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 7fb064346..12c8bf5d9 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -631,9 +631,17 @@ public final class Database { // MARK: - Lock Prevention - /// Release any database lock, as soon as possible, at any cost. + /// Starts preventing database locks. /// - /// See https://www.sqlite.org/lockingv3.html + /// 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 { @@ -667,6 +675,9 @@ public final class Database { } } + /// Ends lock prevention. See startPreventingLock(). + /// + /// This method can be called from any thread. func stopPreventingLock() { preventsLock.write { preventsLock in preventsLock = false diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index e6cdc49f3..62cce6195 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -94,7 +94,7 @@ public protocol DatabaseReader: AnyObject { /// lock acquisition is prevented. /// /// All database accesses may throw a DatabaseError of code - /// `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. + /// `SQLITE_INTERRUPT`, or `SQLITE_ABORT`, except reads in WAL mode. /// /// Lock prevention ends with stopPreventingLock(). func startPreventingLock() From 12106387d146607d34978385967e5fd48036b5dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Dec 2019 08:51:10 +0100 Subject: [PATCH 16/17] Cleanup --- GRDB/Core/Database+Statements.swift | 4 ++-- GRDB/Core/Database.swift | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index d9e91de98..73d4e7408 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -221,7 +221,7 @@ extension Database { extension Database { func executeUpdateStatement(_ statement: UpdateStatement) throws { - try checkLockPrevention(from: statement) + try checkForLockPrevention(from: statement) // In aborted transaction, forbid all statements but statements that // manage transactions. @@ -297,7 +297,7 @@ extension Database { @inline(__always) func selectStatementWillExecute(_ statement: SelectStatement) throws { - try checkLockPrevention(from: statement) + try checkForLockPrevention(from: statement) try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 12c8bf5d9..2c937a904 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -150,10 +150,10 @@ public final class Database { /// Support for checkForAbortedTransaction() var isInsideTransactionBlock = false - /// Support for checkLockPrevention(from:) + /// Support for checkForLockPrevention(from:) var preventsLock = LockedBox(value: false) - /// Support for checkLockPrevention(from:) + /// Support for checkForLockPrevention(from:) /// This cache is never cleared: we assume journal mode never changes. var journalModeCache: String? @@ -684,14 +684,14 @@ public final class Database { } } - /// Support for checkLockPrevention(from:) + /// 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 checkLockPrevention(from:) + // 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) @@ -707,7 +707,7 @@ public final class Database { /// Throws SQLITE_ABORT during lock prevention, if statement would lock /// the database. - func checkLockPrevention(from statement: Statement) throws { + func checkForLockPrevention(from statement: Statement) throws { try preventsLock.read { preventsLock in guard preventsLock else { return @@ -740,7 +740,7 @@ public final class Database { // as explained in Database.startPreventingLock(). // // Use sqlite3_exec instead of `try? rollback()` in order to avoid - // an infinite loop in checkLockPrevention(from:) + // an infinite loop in checkForLockPrevention(from:) _ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil) throw DatabaseError( From 41cd4c214000d7c52bf7949910c51730b4d533d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 3 Dec 2019 09:01:03 +0100 Subject: [PATCH 17/17] Check for aborted transactions before checking for lock prevention --- GRDB/Core/Database+Statements.swift | 6 ++---- .../GRDBTests/DatabaseLockPreventionTests.swift | 16 ++++------------ 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 73d4e7408..0dea32ffc 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -221,13 +221,12 @@ extension Database { extension Database { func executeUpdateStatement(_ statement: UpdateStatement) throws { - try checkForLockPrevention(from: statement) - // In aborted transaction, forbid all statements but statements that // manage transactions. if statement.transactionEffect == nil { try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) } + try checkForLockPrevention(from: statement) let authorizer = observationBroker.updateStatementWillExecute(statement) let sqliteStatement = statement.sqliteStatement @@ -297,9 +296,8 @@ extension Database { @inline(__always) func selectStatementWillExecute(_ statement: SelectStatement) throws { - try checkForLockPrevention(from: statement) - 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/Tests/GRDBTests/DatabaseLockPreventionTests.swift b/Tests/GRDBTests/DatabaseLockPreventionTests.swift index 9b2a1acc1..a05f0c20c 100644 --- a/Tests/GRDBTests/DatabaseLockPreventionTests.swift +++ b/Tests/GRDBTests/DatabaseLockPreventionTests.swift @@ -387,8 +387,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { } func testWriteTransactionAbortedDuringStatementExecutionPreventsFurtherDatabaseAccess() throws { - func test(journalMode: String) throws { - let dbQueue = try makeDatabaseQueue(journalMode: journalMode) + func test(_ dbQueue: DatabaseQueue) throws { try dbQueue.write { db in try db.execute(sql: "CREATE TABLE t(a);") } @@ -418,14 +417,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { XCTFail("Expected error") } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ABORT) - switch journalMode { - case "delete": - XCTAssertEqual(error.message, "Aborted due to lock prevention") - case "wal": - XCTAssertEqual(error.message, "Transaction was aborted") - default: - XCTFail() - } + XCTAssertEqual(error.message, "Transaction was aborted") XCTAssertEqual(error.sql, "SELECT COUNT(*) FROM t") } } @@ -449,7 +441,7 @@ class DatabaseLockPreventionTests : GRDBTestCase { blocks[index]() } } - try test(journalMode: "delete") - try test(journalMode: "wal") + try test(makeDatabaseQueue(journalMode: "delete")) + try test(makeDatabaseQueue(journalMode: "wal")) } }