Rename "lock prevention" to "suspension"

This commit is contained in:
Gwendal Roué committed 2019-12-12 08:47:49 +01:00
1 parent dfb013bf78
commit 6656f72782
21 files changed
+644 -205

No files matched your search

+31 -1
View File
@@ -80,7 +80,37 @@ let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
### Documentation Diff
A new [Interrupt a Database](README.md#interrupt-a-database) chapter documents the new `interrupt()` method.
The new [Interrupt a Database](README.md#interrupt-a-database) chapter documents the new `interrupt()` method.
### API Diff
```diff
struct Configuration {
+ var observesSuspensionNotifications: Bool // Experimental
+ var acceptsDoubleQuotedStringLiterals: Bool
}
class Database {
+ static let suspendNotification: Notification.Name
+ static let resumeNotification: Notification.Name
}
extension DatabaseError {
+ var isInterruptionError: Bool { get }
}
protocol DatabaseReader {
+ func interrupt()
}
extension SQLSpecificExpressible {
+ #if GRDBCUSTOMSQLITE
+ var ascNullsLast: SQLOrderingTerm { get }
+ var descNullsFirst: SQLOrderingTerm { get }
+ #endif
}
```
## 4.6.2
+8 -8
View File
@@ -494,9 +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 */; };
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
5682D722239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.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 */; };
@@ -1500,7 +1500,7 @@
567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5682D71A239582AA004B58C4 /* DatabaseLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLockPreventionTests.swift; sourceTree = "<group>"; };
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = "<group>"; };
5690AFD72120589A001530EA /* InsertRecordCodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InsertRecordCodableTests.swift; sourceTree = "<group>"; };
@@ -2233,7 +2233,6 @@
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */,
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */,
560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */,
5682D71A239582AA004B58C4 /* DatabaseLockPreventionTests.swift */,
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */,
560A37A91C90084600949E71 /* DatabasePool */,
563363BB1C93FD32000BE133 /* DatabaseQueue */,
@@ -2241,6 +2240,7 @@
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
@@ -3491,7 +3491,7 @@
56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */,
5615B288222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5682D722239582AA004B58C4 /* DatabaseLockPreventionTests.swift in Sources */,
5682D722239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */,
563B06C42185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */,
@@ -3698,7 +3698,7 @@
56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
5682D721239582AA004B58C4 /* DatabaseLockPreventionTests.swift in Sources */,
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
563B06C32185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */,
@@ -4038,7 +4038,7 @@
AAA4DD4D230F262000C74B15 /* DatabasePoolReadOnlyTests.swift in Sources */,
AAA4DD4E230F262000C74B15 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
AAA4DD4F230F262000C74B15 /* TruncateOptimizationTests.swift in Sources */,
5682D723239582AA004B58C4 /* DatabaseLockPreventionTests.swift in Sources */,
5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
AAA4DD50230F262000C74B15 /* FoundationNSURLTests.swift in Sources */,
AAA4DD51230F262000C74B15 /* FoundationURLTests.swift in Sources */,
AAA4DD52230F262000C74B15 /* ValueObservationExtentTests.swift in Sources */,
+13
View File
@@ -98,6 +98,19 @@ public struct Configuration {
/// - Default value: false
public var acceptsDoubleQuotedStringLiterals = false
/// When true, the `Database.suspendNotification` and
/// `Database.resumeNotification` suspend and resume the database. Database
/// suspension helps avoiding the [`0xdead10cc`
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
///
/// During suspension, all database accesses but reads in WAL mode may throw
/// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can
/// check for those error codes with the
/// `DatabaseError.isInterruptionError` property.
///
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
public var observesSuspensionNotifications = false
// MARK: - Encryption
#if SQLITE_HAS_CODEC
+6 -2
View File
@@ -221,8 +221,10 @@ extension Database {
extension Database {
func executeUpdateStatement(_ statement: UpdateStatement) throws {
// Two things must prevent the statement from executing: aborted
// transactions, and database suspension.
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
try checkForLockPrevention(from: statement)
try checkForSuspensionViolation(from: statement)
let authorizer = observationBroker.updateStatementWillExecute(statement)
let sqliteStatement = statement.sqliteStatement
@@ -292,8 +294,10 @@ extension Database {
@inline(__always)
func selectStatementWillExecute(_ statement: SelectStatement) throws {
// Two things must prevent the statement from executing: aborted
// transactions, and database suspension.
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
try checkForLockPrevention(from: statement)
try checkForSuspensionViolation(from: statement)
if _isRecordingSelectedRegion {
// Don't record schema introspection queries, which may be
+55 -42
View File
@@ -150,10 +150,10 @@ public final class Database {
/// Support for checkForAbortedTransaction()
var isInsideTransactionBlock = false
/// Support for checkForLockPrevention(from:)
var preventsLock = LockedBox<Bool>(value: false)
/// Support for checkForSuspensionViolation(from:)
var isSuspended = LockedBox<Bool>(value: false)
/// Support for checkForLockPrevention(from:)
/// Support for checkForSuspensionViolation(from:)
/// This cache is never cleared: we assume journal mode never changes.
var journalModeCache: String?
@@ -640,27 +640,39 @@ public final class Database {
sqlite3_interrupt(sqliteConnection)
}
// MARK: - Lock Prevention
// MARK: - Database Suspension
/// Starts preventing database locks.
/// When this notification is posted, databases which were opened with the
/// `Configuration.observesSuspensionNotifications` flag are suspended.
public static let suspendNotification = Notification.Name("GRDB.Database.Suspend")
/// When this notification is posted, databases which were opened with the
/// `Configuration.observesSuspensionNotifications` flag are resumed.
public static let resumeNotification = Notification.Name("GRDB.Database.Resume")
/// Suspends the database. A suspended database prevents database locks in
/// order to avoid the [`0xdead10cc`
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.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.
/// During suspension, 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.
///
/// All database accesses may throw a DatabaseError of code
/// `SQLITE_INTERRUPT`, or `SQLITE_ABORT`, except reads in WAL mode.
/// If database configuration has the `observesSuspensionNotifications`
/// flag set, this methods performs an immediate rollback.
///
/// Lock prevention ends with stopPreventingLock().
func startPreventingLock() {
preventsLock.write { preventsLock in
if preventsLock {
/// Suspension ends with resume().
func suspend() {
isSuspended.write { isSuspended in
if isSuspended {
return
}
// Prevent future lock acquisition
preventsLock = true
isSuspended = true
// Interrupt the database because this may trigger an
// SQLITE_INTERRUPT error which may itself abort a transaction and
@@ -669,40 +681,40 @@ public final class Database {
// What about the eventual remaining lock?
// If the database had been opened with the SQLITE_OPEN_FULLMUTEX
// flag, we could safely execute a rollback statement:
//
// if configuration.SQLiteOpenFlags & SQLITE_OPEN_FULLMUTEX != 0 {
// sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil)
// }
//
// But:
//
// - we currently use SQLITE_OPEN_NOMUTEX instead of SQLITE_OPEN_FULLMUTEX.
// - the rollback may fail, and a lock could remain.
//
// We work around this situation by issuing a rollback on next
// database access which requires a lock,
// in preventExclusiveLock(from:).
// flag, execute a rollback statement:
if configuration.threadingMode == .serialized {
assert(configuration.SQLiteOpenFlags & SQLITE_OPEN_FULLMUTEX != 0)
_ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil)
}
// If threadingMode is not .serialized, or if the rollback has
// failed, a lock could remain. We'll issue a rollback on next
// database access which requires a lock, in
// checkForSuspensionViolation(from:).
}
}
/// Ends lock prevention. See startPreventingLock().
/// Resumes the database. A resumed database stops preventing database locks
/// in order to avoid the [`0xdead10cc`
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
///
/// This method can be called from any thread.
func stopPreventingLock() {
preventsLock.write { preventsLock in
preventsLock = false
///
/// See suspend().
func resume() {
isSuspended.write { isSuspended in
isSuspended = false
}
}
/// Support for checkForLockPrevention(from:)
/// Support for checkForSuspensionViolation(from:)
private func journalMode() throws -> String {
if let journalMode = journalModeCache {
return journalMode
}
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
// that we don't create an infinite loop in checkForLockPrevention(from:)
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
var statement: SQLiteStatement? = nil
let sql = "PRAGMA journal_mode"
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
@@ -716,11 +728,12 @@ public final class Database {
return journalMode
}
/// Throws SQLITE_ABORT during lock prevention, if statement would lock
/// the database.
func checkForLockPrevention(from statement: Statement) throws {
try preventsLock.read { preventsLock in
guard preventsLock else {
/// Throws SQLITE_ABORT for suspended databases, if statement would lock
/// the database, in order to avoid the [`0xdead10cc`
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
func checkForSuspensionViolation(from statement: Statement) throws {
try isSuspended.read { isSuspended in
guard isSuspended else {
return
}
@@ -748,15 +761,15 @@ public final class Database {
}
// Attempt at releasing an eventual lock with ROLLBACk,
// as explained in Database.startPreventingLock().
// as explained in Database.suspend().
//
// Use sqlite3_exec instead of `try? rollback()` in order to avoid
// an infinite loop in checkForLockPrevention(from:)
// an infinite loop in checkForSuspensionViolation(from:)
_ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil)
throw DatabaseError(
resultCode: .SQLITE_ABORT,
message: "Aborted due to lock prevention",
message: "Database is suspended",
sql: statement.sql,
arguments: statement.arguments)
}
+19
View File
@@ -250,6 +250,25 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
let arguments: StatementArguments?
}
extension DatabaseError {
// TODO: test
/// Returns true if the error has code `SQLITE_ABORT` or `SQLITE_INTERRUPT`.
///
/// Such an error can be thrown when a database has been interrupted, or
/// when the database is suspended.
///
/// See `DatabaseReader.interrupt()` and `DatabaseReader.suspend()` for
/// more information.
public var isInterruptionError: Bool {
switch resultCode {
case .SQLITE_ABORT, .SQLITE_INTERRUPT:
return true
default:
return false
}
}
}
// CustomStringConvertible
extension DatabaseError {
/// :nodoc:
+62 -10
View File
@@ -15,7 +15,8 @@ import UIKit
public final class DatabasePool: DatabaseWriter {
private let writer: SerializedDatabase
private var readerPool: Pool<SerializedDatabase>!
var readerConfiguration: Configuration
// TODO: remove when the deprecated change(passphrase:) method turns unavailable.
private var readerConfiguration: Configuration
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
@@ -64,13 +65,36 @@ public final class DatabasePool: DatabaseWriter {
// Readers
readerConfiguration = configuration
readerConfiguration.readonly = true
// Readers use deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
readerConfiguration.defaultTransactionKind = .deferred
// Readers can't allow dangling transactions because there's no
// guarantee that one can get the same reader later in order to close
// an opened transaction.
readerConfiguration.allowsUnsafeTransactions = false
// https://www.sqlite.org/wal.html#sometimes_queries_return_sqlite_busy_in_wal_mode
// > But there are some obscure cases where a query against a WAL-mode
// > database can return SQLITE_BUSY, so applications should be prepared
// > for that happenstance.
// >
// > - If another database connection has the database mode open in
// > exclusive locking mode [...]
// > - When the last connection to a particular database is closing,
// > that connection will acquire an exclusive lock for a short time
// > while it cleans up the WAL and shared-memory files [...]
// > - If the last connection to a database crashed, then the first new
// > connection to open the database will start a recovery process. An
// > exclusive lock is held during recovery. [...]
//
// The whole point of WAL readers is to avoid SQLITE_BUSY, so let's
// setup a busy handler for pool readers, in order to workaround those
// "obscure cases" that may happen when the database is shared between
// multiple processes.
readerConfiguration.busyMode = .timeout(10)
var readerCount = 0
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
readerCount += 1 // protected by pool (TODO: documented this protection behavior)
@@ -112,9 +136,10 @@ public final class DatabasePool: DatabaseWriter {
}
}
}
setupSuspension()
}
#if os(iOS)
deinit {
// Undo job done in setupMemoryManagement()
//
@@ -122,7 +147,6 @@ public final class DatabasePool: DatabaseWriter {
// Explicit unregistration is required before iOS 9 and OS X 10.11.
NotificationCenter.default.removeObserver(self)
}
#endif
private func setupDatabase(_ db: Database) {
for function in functions {
@@ -259,22 +283,50 @@ extension DatabasePool: DatabaseReader {
readerPool.forEach { $0.interrupt() }
}
// MARK: - Lock Prevention
// MARK: - Database Suspension
public func startPreventingLock() {
func suspend() {
if configuration.readonly {
// read-only WAL connections can't acquire locks
// read-only WAL connections can't acquire locks and do not need to
// be suspended.
return
}
writer.startPreventingLock()
writer.suspend()
}
public func stopPreventingLock() {
func resume() {
if configuration.readonly {
// read-only WAL connections can't acquire locks
// read-only WAL connections can't acquire locks and do not need to
// be suspended.
return
}
writer.stopPreventingLock()
writer.resume()
}
private func setupSuspension() {
if configuration.observesSuspensionNotifications {
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(DatabasePool.suspend(_:)),
name: Database.suspendNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabasePool.resume(_:)),
name: Database.resumeNotification,
object: nil)
}
}
@objc
private func suspend(_ notification: Notification) {
suspend()
}
@objc
private func resume(_ notification: Notification) {
resume()
}
// MARK: - Reading from Database
+33 -7
View File
@@ -41,6 +41,8 @@ public final class DatabaseQueue: DatabaseWriter {
configuration: configuration,
schemaCache: SimpleDatabaseSchemaCache(),
defaultLabel: "GRDB.DatabaseQueue")
setupSuspension()
}
/// Opens an in-memory SQLite database.
@@ -59,7 +61,6 @@ public final class DatabaseQueue: DatabaseWriter {
defaultLabel: "GRDB.DatabaseQueue")
}
#if os(iOS)
deinit {
// Undo job done in setupMemoryManagement()
//
@@ -67,7 +68,6 @@ public final class DatabaseQueue: DatabaseWriter {
// Explicit unregistration is required before iOS 9 and OS X 10.11.
NotificationCenter.default.removeObserver(self)
}
#endif
}
extension DatabaseQueue {
@@ -155,14 +155,40 @@ extension DatabaseQueue {
writer.interrupt()
}
// MARK: - Lock Prevention
// MARK: - Database Suspension
public func startPreventingLock() {
writer.startPreventingLock()
func suspend() {
writer.suspend()
}
public func stopPreventingLock() {
writer.stopPreventingLock()
func resume() {
writer.resume()
}
private func setupSuspension() {
if configuration.observesSuspensionNotifications {
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(DatabaseQueue.suspend(_:)),
name: Database.suspendNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabaseQueue.resume(_:)),
name: Database.resumeNotification,
object: nil)
}
}
@objc
private func suspend(_ notification: Notification) {
suspend()
}
@objc
private func resume(_ notification: Notification) {
resume()
}
// MARK: - Reading from Database
+3 -32
View File
@@ -82,28 +82,11 @@ public protocol DatabaseReader: AnyObject {
/// try Player(...).insert(db) // success
/// try db.commit() // throws SQLITE_ERROR "cannot commit - no transaction is active"
/// }
///
/// Both SQLITE_ABORT and SQLITE_INTERRUPT errors can be checked with the
/// `DatabaseError.isInterruptionError` property.
func interrupt()
// MARK: - Lock Prevention
/// Starts preventing database locks.
///
/// This method can be called from any thread.
///
/// During lock prevention, any lock is released as soon as possible, and
/// lock acquisition is prevented.
///
/// All database accesses may throw a DatabaseError of code
/// `SQLITE_INTERRUPT`, or `SQLITE_ABORT`, except reads in WAL mode.
///
/// Lock prevention ends with stopPreventingLock().
func startPreventingLock()
/// Ends lock prevention. See startPreventingLock().
///
/// This method can be called from any thread.
func stopPreventingLock()
// MARK: - Read From Database
/// Synchronously executes a read-only block that takes a database
@@ -335,18 +318,6 @@ 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:
-10
View File
@@ -53,16 +53,6 @@ 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
-12
View File
@@ -608,18 +608,6 @@ public final class AnyDatabaseWriter: DatabaseWriter {
base.interrupt()
}
// MARK: - Lock Prevention
/// :nodoc:
public func startPreventingLock() {
base.startPreventingLock()
}
/// :nodoc:
public func stopPreventingLock() {
base.stopPreventingLock()
}
// MARK: - Reading from Database
/// :nodoc:
+12 -5
View File
@@ -41,8 +41,15 @@ final class SerializedDatabase {
//
// Since our database connection is only used via our serial dispatch
// queue, there is no purpose using the default serialized mode.
//
// But we make an exception in order to prevent the `0xdead10cc`
// exception. We need the serialized mode just so that we can perform
// an emergency rollback when database gets suspended. This extra
// behavior is triggered by `observesSuspensionNotifications`:
var config = configuration
config.threadingMode = .multiThread
config.threadingMode = config.observesSuspensionNotifications
? .serialized
: .multiThread
self.path = path
self.db = try Database(path: path, configuration: config, schemaCache: schemaCache)
@@ -204,14 +211,14 @@ final class SerializedDatabase {
db.interrupt()
}
func startPreventingLock() {
func suspend() {
// Intentionally not scheduled in our serial queue
db.startPreventingLock()
db.suspend()
}
func stopPreventingLock() {
func resume() {
// Intentionally not scheduled in our serial queue
db.stopPreventingLock()
db.resume()
}
/// Fatal error if current dispatch queue is not valid.
+6 -6
View File
@@ -113,6 +113,8 @@
5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */; };
5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
564B3D73239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
564CE4E021B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */; };
@@ -131,8 +133,6 @@
564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
565050E123940CE400A7F660 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050DF23940CE400A7F660 /* DatabaseLockPreventionTests.swift */; };
565050E223940CE400A7F660 /* DatabaseLockPreventionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565050DF23940CE400A7F660 /* DatabaseLockPreventionTests.swift */; };
5653EB6820961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; };
5653EB6920961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; };
5653EB6A20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */; };
@@ -800,6 +800,7 @@
5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = "<group>"; };
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = "<group>"; };
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
@@ -809,7 +810,6 @@
564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
565050DF23940CE400A7F660 /* DatabaseLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLockPreventionTests.swift; sourceTree = "<group>"; };
5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = "<group>"; };
5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = "<group>"; };
5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = "<group>"; };
@@ -1561,7 +1561,6 @@
563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */,
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */,
560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */,
565050DF23940CE400A7F660 /* DatabaseLockPreventionTests.swift */,
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */,
560A37A91C90084600949E71 /* DatabasePool */,
563363BB1C93FD32000BE133 /* DatabaseQueue */,
@@ -1569,6 +1568,7 @@
564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */,
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
@@ -2350,7 +2350,6 @@
6340BF871E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
56057C662291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */,
56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
565050E123940CE400A7F660 /* DatabaseLockPreventionTests.swift in Sources */,
F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */,
5656A7F722946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */,
5615B259222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */,
@@ -2359,6 +2358,7 @@
F3BA80FD1CFB3024003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */,
F3BA811F1CFB3063003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
5657AB451D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
564B3D73239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */,
56CC9255201E094600CB597E /* PrefixCursorTests.swift in Sources */,
F3BA80EA1CFB3016003DC1BA /* RowFromStatementTests.swift in Sources */,
F3BA80AF1CFB2FB1003DC1BA /* DatabaseCollationTests.swift in Sources */,
@@ -2690,7 +2690,6 @@
F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */,
56057C652291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */,
F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */,
565050E223940CE400A7F660 /* DatabaseLockPreventionTests.swift in Sources */,
6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
5656A7F622946B1B001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */,
5615B258222AE19100061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */,
@@ -2699,6 +2698,7 @@
5698AC4C1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */,
F3BA80EF1CFB3017003DC1BA /* RowFromStatementTests.swift in Sources */,
5657AB511D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */,
56CC9254201E094600CB597E /* PrefixCursorTests.swift in Sources */,
562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */,
+2
View File
@@ -19,6 +19,7 @@
## Features
- [ ] Measure the duration of transactions
- [ ] Make deleteAll and updateAll work even for complex queries, with `DELETE FROM xxx WHERE rowid IN (SELECT rowid ...)`
- [ ] Improve SQL generation for `Player.....fetchCount(db)`, especially with distinct. Try to avoid `SELECT COUNT(*) FROM (SELECT DISTINCT player.* ...)`
- [ ] Alternative technique for custom SQLite builds: see the Podfile at https://github.com/CocoaPods/CocoaPods/issues/9104, and https://github.com/clemensg/sqlite3pod
@@ -98,3 +99,4 @@
- File protection: https://github.com/ccgus/fmdb/issues/262
- File protection: https://lists.apple.com/archives/cocoa-dev/2012/Aug/msg00527.html
- [iOS apps are terminated every time they enter the background if they share an encrypted database with an app extension](https://github.com/sqlcipher/sqlcipher/issues/255)
- [Cross-Process notifications with CFNotificationCenterGetDarwinNotifyCenter](https://www.avanderlee.com/swift/core-data-app-extension-data-sharing/)
@@ -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 */; };
564B3D78239BDC00007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D77239BDC00007BF308 /* DatabaseSuspensionTests.swift */; };
564B3D79239BDC00007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D77239BDC00007BF308 /* DatabaseSuspensionTests.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 = "<group>"; };
564A1FDD226B89E1001F64F1 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
564B3D77239BDC00007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
5656A801229474DC001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
5676FBAF22F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
5682D724239582C6004B58C4 /* DatabaseLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLockPreventionTests.swift; sourceTree = "<group>"; };
56915792231C0D6A00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
569BBA30228DF91000478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = "<group>"; };
56DF0025228DE00900D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = "<group>"; };
@@ -715,7 +715,6 @@
564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */,
564A1F65226B89D5001F64F1 /* DatabaseErrorTests.swift */,
564A1F37226B89CF001F64F1 /* DatabaseFunctionTests.swift */,
5682D724239582C6004B58C4 /* DatabaseLockPreventionTests.swift */,
564A1F5C226B89D3001F64F1 /* DatabaseLogErrorTests.swift */,
564A1FD4226B89E0001F64F1 /* DatabaseMigratorTests.swift */,
564A1F6A226B89D5001F64F1 /* DatabasePoolBackupTests.swift */,
@@ -737,6 +736,7 @@
564A1F69226B89D5001F64F1 /* DatabaseRegionTests.swift */,
564A1F79226B89D7001F64F1 /* DatabaseSavepointTests.swift */,
564A1F3F226B89D0001F64F1 /* DatabaseSnapshotTests.swift */,
564B3D77239BDC00007BF308 /* DatabaseSuspensionTests.swift */,
564A1FC7226B89DF001F64F1 /* DatabaseTests.swift */,
564A1FAF226B89DC001F64F1 /* DatabaseTimestampTests.swift */,
564A1FD6226B89E0001F64F1 /* DatabaseUUIDEncodingStrategyTests.swift */,
@@ -1137,6 +1137,7 @@
564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
564A208F226B89E1001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */,
564B3D78239BDC00007BF308 /* DatabaseSuspensionTests.swift in Sources */,
564A2047226B89E1001F64F1 /* AnyCursorTests.swift in Sources */,
564A1FFC226B89E1001F64F1 /* DatabaseValueTests.swift in Sources */,
564A200E226B89E1001F64F1 /* RowFromStatementTests.swift in Sources */,
@@ -1251,7 +1252,6 @@
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 */,
@@ -1342,6 +1342,7 @@
564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
564A20D1226B8E18001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */,
564B3D79239BDC00007BF308 /* DatabaseSuspensionTests.swift in Sources */,
564A20D2226B8E18001F64F1 /* AnyCursorTests.swift in Sources */,
564A20D3226B8E18001F64F1 /* DatabaseValueTests.swift in Sources */,
564A20D4226B8E18001F64F1 /* RowFromStatementTests.swift in Sources */,
@@ -1456,7 +1457,6 @@
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 */,
@@ -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 */; };
564B3D75239BDBED007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D74239BDBEC007BF308 /* DatabaseSuspensionTests.swift */; };
564B3D76239BDBED007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D74239BDBEC007BF308 /* DatabaseSuspensionTests.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 = "<group>"; };
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; };
564B3D74239BDBEC007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
5656A804229474F4001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationQueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
5676FBAC22F5CEF5004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
5682D727239582E2004B58C4 /* DatabaseLockPreventionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLockPreventionTests.swift; sourceTree = "<group>"; };
5691578F231C0D5100E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
569BBA2D228DF90200478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = "<group>"; };
56DF001F228DDFF000D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = "<group>"; };
@@ -718,7 +718,6 @@
564A1F54226B89D2001F64F1 /* DatabaseDateEncodingStrategyTests.swift */,
564A1F65226B89D5001F64F1 /* DatabaseErrorTests.swift */,
564A1F37226B89CF001F64F1 /* DatabaseFunctionTests.swift */,
5682D727239582E2004B58C4 /* DatabaseLockPreventionTests.swift */,
564A1F5C226B89D3001F64F1 /* DatabaseLogErrorTests.swift */,
564A1FD4226B89E0001F64F1 /* DatabaseMigratorTests.swift */,
564A1F6A226B89D5001F64F1 /* DatabasePoolBackupTests.swift */,
@@ -740,6 +739,7 @@
564A1F69226B89D5001F64F1 /* DatabaseRegionTests.swift */,
564A1F79226B89D7001F64F1 /* DatabaseSavepointTests.swift */,
564A1F3F226B89D0001F64F1 /* DatabaseSnapshotTests.swift */,
564B3D74239BDBEC007BF308 /* DatabaseSuspensionTests.swift */,
564A1FC7226B89DF001F64F1 /* DatabaseTests.swift */,
564A1FAF226B89DC001F64F1 /* DatabaseTimestampTests.swift */,
564A1FD6226B89E0001F64F1 /* DatabaseUUIDEncodingStrategyTests.swift */,
@@ -1143,6 +1143,7 @@
564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5676FBAD22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
564A208F226B89E1001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */,
564B3D75239BDBED007BF308 /* DatabaseSuspensionTests.swift in Sources */,
564A2047226B89E1001F64F1 /* AnyCursorTests.swift in Sources */,
564A1FFC226B89E1001F64F1 /* DatabaseValueTests.swift in Sources */,
564A200E226B89E1001F64F1 /* RowFromStatementTests.swift in Sources */,
@@ -1224,7 +1225,6 @@
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 */,
@@ -1348,6 +1348,7 @@
564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5676FBAE22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
564A20D1226B8E18001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */,
564B3D76239BDBED007BF308 /* DatabaseSuspensionTests.swift in Sources */,
564A20D2226B8E18001F64F1 /* AnyCursorTests.swift in Sources */,
564A20D3226B8E18001F64F1 /* DatabaseValueTests.swift in Sources */,
564A20D4226B8E18001F64F1 /* RowFromStatementTests.swift in Sources */,
@@ -1429,7 +1430,6 @@
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 */,
@@ -11,6 +11,8 @@ import XCTest
#endif
class DatabaseConfigurationTests: GRDBTestCase {
// MARK: - prepareDatabase
func testPrepareDatabase() throws {
// prepareDatabase is called when connection opens
var connectionCount = 0
@@ -78,6 +80,8 @@ class DatabaseConfigurationTests: GRDBTestCase {
}
}
// MARK: - acceptsDoubleQuotedStringLiterals
func testAcceptsDoubleQuotedStringLiteralsDefault() throws {
let configuration = Configuration()
XCTAssertFalse(configuration.acceptsDoubleQuotedStringLiterals)
@@ -152,4 +156,151 @@ class DatabaseConfigurationTests: GRDBTestCase {
XCTAssertEqual(error.sql, "CREATE INDEX i ON player(\"foo\")")
}
}
// MARK: - busyMode
func testBusyModeImmediate() throws {
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
// running this test
try dbQueue1.inDatabase { db in
try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
var configuration2 = Configuration()
configuration2.busyMode = .immediateError
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2)
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let queue = DispatchQueue(label: "GRDB", attributes: [.concurrent])
let group = DispatchGroup()
queue.async(group: group) {
do {
try dbQueue1.inTransaction(.exclusive) { db in
s2.signal()
queue.asyncAfter(deadline: .now() + 1) {
s1.signal()
}
_ = s1.wait(timeout: .distantFuture)
return .commit
}
} catch {
XCTFail("\(error)")
}
}
queue.async(group: group) {
do {
_ = s2.wait(timeout: .distantFuture)
try dbQueue2.inTransaction(.exclusive) { db in return .commit }
XCTFail("Expected error")
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
} catch {
XCTFail("\(error)")
}
}
_ = group.wait(timeout: .distantFuture)
}
func testBusyModeTimeoutTooShort() throws {
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
// running this test
try dbQueue1.inDatabase { db in
try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
var configuration2 = Configuration()
configuration2.busyMode = .timeout(0.5)
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2)
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let queue = DispatchQueue(label: "GRDB", attributes: [.concurrent])
let group = DispatchGroup()
queue.async(group: group) {
do {
try dbQueue1.inTransaction(.exclusive) { db in
s2.signal()
queue.asyncAfter(deadline: .now() + 1) {
s1.signal()
}
_ = s1.wait(timeout: .distantFuture)
return .commit
}
} catch {
XCTFail("\(error)")
}
}
queue.async(group: group) {
do {
_ = s2.wait(timeout: .distantFuture)
try dbQueue2.inTransaction(.exclusive) { db in return .commit }
XCTFail("Expected error")
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
} catch {
XCTFail("\(error)")
}
}
_ = group.wait(timeout: .distantFuture)
}
func testBusyModeTimeoutTooLong() throws {
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
#if GRDBCIPHER_USE_ENCRYPTION
// Work around SQLCipher bug when two connections are open to the
// same empty database: make sure the database is not empty before
// running this test
try dbQueue1.inDatabase { db in
try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
var configuration2 = Configuration()
configuration2.busyMode = .timeout(2)
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite", configuration: configuration2)
let s1 = DispatchSemaphore(value: 0)
let s2 = DispatchSemaphore(value: 0)
let queue = DispatchQueue(label: "GRDB", attributes: [.concurrent])
let group = DispatchGroup()
queue.async(group: group) {
do {
try dbQueue1.inTransaction(.exclusive) { db in
s2.signal()
queue.asyncAfter(deadline: .now() + 1) {
s1.signal()
}
_ = s1.wait(timeout: .distantFuture)
return .commit
}
} catch {
XCTFail("\(error)")
}
}
queue.async(group: group) {
do {
_ = s2.wait(timeout: .distantFuture)
try dbQueue2.inTransaction(.exclusive) { db in return .commit }
} catch {
XCTFail("\(error)")
}
}
_ = group.wait(timeout: .distantFuture)
}
}
@@ -1,5 +1,6 @@
import XCTest
import Dispatch
import Foundation
#if GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
@@ -1276,4 +1277,101 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
s4.wait()
}
}
// MARK: - Concurrent opening
func testConcurrentOpening() throws {
for _ in 0..<50 {
let dbDirectoryName = "DatabasePoolConcurrencyTests-\(ProcessInfo.processInfo.globallyUniqueString)"
let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent(dbDirectoryName, isDirectory: true)
let dbURL = directoryURL.appendingPathComponent("db.sqlite")
try FileManager.default.createDirectory(atPath: directoryURL.path, withIntermediateDirectories: true, attributes: nil)
defer { try! FileManager.default.removeItem(at: directoryURL) }
DispatchQueue.concurrentPerform(iterations: 10) { n in
// WTF I could never Google for the proper correct error handling
// of NSFileCoordinator. What a weird API.
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var poolError: Error?
coordinator.coordinate(writingItemAt: dbURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
do {
_ = try DatabasePool(path: url.path)
} catch {
poolError = error
}
})
XCTAssert(poolError ?? coordinatorError == nil)
}
}
}
// MARK: - NSFileCoordinator sample code tests
// Test for sample code in Documentation/AppGroupContainers.md.
// This test passes if this method compiles
private func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool!
}
// Test for sample code in Documentation/AppGroupContainers.md.
// This test passes if this method compiles
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
let dbPool = try DatabasePool(path: databaseURL.path)
// Perform here other database setups, such as defining
// the database schema with a DatabaseMigrator.
return dbPool
}
// Test for sample code in Documentation/AppGroupContainers.md.
// This test passes if this method compiles
private func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openReadOnlyDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool
}
// Test for sample code in Documentation/AppGroupContainers.md.
// This test passes if this method compiles
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
do {
var configuration = Configuration()
configuration.readonly = true
return try DatabasePool(path: databaseURL.path, configuration: configuration)
} catch {
if FileManager.default.fileExists(atPath: databaseURL.path) {
// Something went wrong
throw error
} else {
// Database file does not exist
return nil
}
}
}
}
@@ -7,6 +7,15 @@ import XCTest
class DatabasePoolReadOnlyTests: GRDBTestCase {
func testOpenReadOnlyMissingDatabase() throws {
dbConfiguration.readonly = true
do {
_ = try makeDatabasePool()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_CANTOPEN)
}
}
func testConcurrentRead() throws {
let databaseFileName = "db.sqlite"
@@ -7,6 +7,15 @@ import XCTest
class DatabaseQueueReadOnlyTests : GRDBTestCase {
func testOpenReadOnlyMissingDatabase() throws {
dbConfiguration.readonly = true
do {
_ = try makeDatabaseQueue()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_CANTOPEN)
}
}
func testReadOnlyDatabaseCanNotBeModified() throws {
// Create database
do {
@@ -1,11 +1,11 @@
import XCTest
#if GRDBCUSTOMSQLITE
import GRDBCustomSQLite
@testable import GRDBCustomSQLite
#else
import GRDB
@testable import GRDB
#endif
class DatabaseLockPreventionTests : GRDBTestCase {
class DatabaseSuspensionTests : GRDBTestCase {
private func makeDatabaseQueue(journalMode: String) throws -> DatabaseQueue {
let dbQueue = try makeDatabaseQueue()
@@ -16,9 +16,9 @@ class DatabaseLockPreventionTests : GRDBTestCase {
// MARK: - BEGIN TRANSACTION
func testLockPreventionPreventsNewTransactionInDeleteJournalMode() throws {
func testSuspensionPreventsNewTransactionInDeleteJournalMode() throws {
let dbQueue = try makeDatabaseQueue(journalMode: "delete")
dbQueue.startPreventingLock()
dbQueue.suspend()
do {
try dbQueue.inDatabase { db in
@@ -27,7 +27,7 @@ class DatabaseLockPreventionTests : GRDBTestCase {
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ABORT)
XCTAssertEqual(error.message, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
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, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
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, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
XCTAssertEqual(error.sql, "BEGIN EXCLUSIVE TRANSACTION")
}
@@ -60,14 +60,14 @@ class DatabaseLockPreventionTests : GRDBTestCase {
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ABORT)
XCTAssertEqual(error.message, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
XCTAssertEqual(error.sql, "SAVEPOINT test")
}
}
func testLockPreventionDoesNotPreventNewDeferredTransactionInWALMode() throws {
func testSuspensionDoesNotPreventNewDeferredTransactionInWALMode() throws {
let dbQueue = try makeDatabaseQueue(journalMode: "wal")
dbQueue.startPreventingLock()
dbQueue.suspend()
try dbQueue.inDatabase { db in
try db.execute(sql: "BEGIN TRANSACTION; ROLLBACK")
@@ -75,9 +75,9 @@ class DatabaseLockPreventionTests : GRDBTestCase {
}
}
func testLockPreventionPreventsNewImmediateOrExclusiveTransactionInWALMode() throws {
func testSuspensionPreventsNewImmediateOrExclusiveTransactionInWALMode() throws {
let dbQueue = try makeDatabaseQueue(journalMode: "wal")
dbQueue.startPreventingLock()
dbQueue.suspend()
do {
try dbQueue.inDatabase { db in
@@ -86,7 +86,7 @@ class DatabaseLockPreventionTests : GRDBTestCase {
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ABORT)
XCTAssertEqual(error.message, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
XCTAssertEqual(error.sql, "BEGIN IMMEDIATE TRANSACTION")
}
@@ -97,18 +97,18 @@ class DatabaseLockPreventionTests : GRDBTestCase {
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ABORT)
XCTAssertEqual(error.message, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
XCTAssertEqual(error.sql, "BEGIN EXCLUSIVE TRANSACTION")
}
}
// MARK: - COMMIT, ROLLBACK, RELEASE SAVEPOINT, ROLLBACK TRANSACTION TO SAVEPOINT
func testLockPreventionDoesNotPreventCommit() throws {
func testSuspensionDoesNotPreventCommit() throws {
func test(_ dbQueue: DatabaseQueue) throws {
try dbQueue.inDatabase { db in
try db.execute(sql: "BEGIN TRANSACTION")
dbQueue.startPreventingLock()
dbQueue.suspend()
try db.execute(sql: "COMMIT")
}
}
@@ -116,11 +116,11 @@ class DatabaseLockPreventionTests : GRDBTestCase {
try test(makeDatabaseQueue(journalMode: "wal"))
}
func testLockPreventionDoesNotPreventRollback() throws {
func testSuspensionDoesNotPreventRollback() throws {
func test(_ dbQueue: DatabaseQueue) throws {
try dbQueue.inDatabase { db in
try db.execute(sql: "BEGIN TRANSACTION")
dbQueue.startPreventingLock()
dbQueue.suspend()
try db.execute(sql: "ROLLBACK")
}
}
@@ -128,11 +128,11 @@ class DatabaseLockPreventionTests : GRDBTestCase {
try test(makeDatabaseQueue(journalMode: "wal"))
}
func testLockPreventionDoesNotPreventReleaseSavePoint() throws {
func testSuspensionDoesNotPreventReleaseSavePoint() throws {
func test(_ dbQueue: DatabaseQueue) throws {
try dbQueue.inDatabase { db in
try db.execute(sql: "SAVEPOINT test")
dbQueue.startPreventingLock()
dbQueue.suspend()
try db.execute(sql: "RELEASE SAVEPOINT test")
}
}
@@ -140,11 +140,11 @@ class DatabaseLockPreventionTests : GRDBTestCase {
try test(makeDatabaseQueue(journalMode: "wal"))
}
func testLockPreventionDoesNotPreventRollbackSavePoint() throws {
func testSuspensionDoesNotPreventRollbackSavePoint() throws {
func test(_ dbQueue: DatabaseQueue) throws {
try dbQueue.inDatabase { db in
try db.execute(sql: "SAVEPOINT test")
dbQueue.startPreventingLock()
dbQueue.suspend()
try db.execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT test")
try db.execute(sql: "RELEASE SAVEPOINT test")
}
@@ -155,27 +155,27 @@ class DatabaseLockPreventionTests : GRDBTestCase {
// MARK: - SELECT
func testLockPreventionPreventsReadInDeleteJournalMode() throws {
func testSuspensionPreventsReadInDeleteJournalMode() throws {
let dbQueue = try makeDatabaseQueue(journalMode: "delete")
do {
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE t(a);")
dbQueue.startPreventingLock()
try db.execute(sql: "CREATE TABLE t(a)")
dbQueue.suspend()
_ = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")
}
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ABORT)
XCTAssertEqual(error.message, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
XCTAssertEqual(error.sql, "SELECT COUNT(*) FROM t")
}
}
func testLockPreventionDoesNotPreventReadInWALMode() throws {
func testSuspensionDoesNotPreventReadInWALMode() throws {
let dbQueue = try makeDatabaseQueue(journalMode: "wal")
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE t(a);")
dbQueue.startPreventingLock()
try db.execute(sql: "CREATE TABLE t(a)")
dbQueue.suspend()
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t"), 0)
@@ -188,34 +188,34 @@ class DatabaseLockPreventionTests : GRDBTestCase {
// MARK: - INSERT
func testLockPreventionPreventsWriteInDeleteJournalMode() throws {
func testSuspensionPreventsWriteInDeleteJournalMode() throws {
let dbQueue = try makeDatabaseQueue(journalMode: "delete")
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE t(a);")
dbQueue.startPreventingLock()
try db.execute(sql: "CREATE TABLE t(a)")
dbQueue.suspend()
do {
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ABORT)
XCTAssertEqual(error.message, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES")
}
}
}
func testLockPreventionPreventsWriteInWALMode() throws {
func testSuspensionPreventsWriteInWALMode() throws {
let dbQueue = try makeDatabaseQueue(journalMode: "wal")
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE t(a);")
dbQueue.startPreventingLock()
try db.execute(sql: "CREATE TABLE t(a)")
dbQueue.suspend()
do {
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ABORT)
XCTAssertEqual(error.message, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
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, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES")
}
}
@@ -235,19 +235,19 @@ class DatabaseLockPreventionTests : GRDBTestCase {
// MARK: - Automatic ROLLBACK
func testLockPreventionRollbacksOnPreventedWrite() throws {
func testSuspensionRollbacksOnPreventedWrite() throws {
func test(_ dbQueue: DatabaseQueue) throws {
do {
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE t(a);")
try db.execute(sql: "CREATE TABLE t(a)")
XCTAssertTrue(db.isInsideTransaction)
dbQueue.startPreventingLock()
dbQueue.suspend()
do {
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ABORT)
XCTAssertEqual(error.message, "Aborted due to lock prevention")
XCTAssertEqual(error.message, "Database is suspended")
XCTAssertEqual(error.sql, "INSERT INTO t DEFAULT VALUES")
}
// Aborded transaction
@@ -265,7 +265,7 @@ class DatabaseLockPreventionTests : GRDBTestCase {
// MARK: - Concurrent Lock Prevention
func testLockPreventionAbortsDatabaseQueueAccess() throws {
func testSuspensionAbortsDatabaseQueueAccess() throws {
func test(_ dbQueue: DatabaseQueue) throws {
let semaphore1 = DispatchSemaphore(value: 0)
let semaphore2 = DispatchSemaphore(value: 0)
@@ -289,7 +289,7 @@ class DatabaseLockPreventionTests : GRDBTestCase {
}
let block2 = {
semaphore1.wait()
dbQueue.startPreventingLock()
dbQueue.suspend()
semaphore2.signal()
}
let blocks = [block1, block2]
@@ -301,10 +301,10 @@ class DatabaseLockPreventionTests : GRDBTestCase {
try test(makeDatabaseQueue(journalMode: "wal"))
}
func testLockPreventionDoesNotPreventFurtherReadInWALMode() throws {
func testSuspensionDoesNotPreventFurtherReadInWALMode() throws {
let dbQueue = try makeDatabaseQueue(journalMode: "wal")
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE t(a);")
try db.execute(sql: "CREATE TABLE t(a)")
}
let semaphore1 = DispatchSemaphore(value: 0)
@@ -334,7 +334,7 @@ class DatabaseLockPreventionTests : GRDBTestCase {
}
let block2 = {
semaphore1.wait()
dbQueue.startPreventingLock()
dbQueue.suspend()
semaphore2.signal()
}
let blocks = [block1, block2]
@@ -346,7 +346,7 @@ class DatabaseLockPreventionTests : GRDBTestCase {
func testWriteTransactionAbortedDuringStatementExecution() throws {
func test(_ dbQueue: DatabaseQueue) throws {
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE t(a);")
try db.execute(sql: "CREATE TABLE t(a)")
}
let semaphore1 = DispatchSemaphore(value: 0)
@@ -374,7 +374,7 @@ class DatabaseLockPreventionTests : GRDBTestCase {
}
let block2 = {
semaphore1.wait()
dbQueue.startPreventingLock()
dbQueue.suspend()
semaphore2.signal()
}
let blocks = [block1, block2]
@@ -389,7 +389,7 @@ class DatabaseLockPreventionTests : GRDBTestCase {
func testWriteTransactionAbortedDuringStatementExecutionPreventsFurtherDatabaseAccess() throws {
func test(_ dbQueue: DatabaseQueue) throws {
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE t(a);")
try db.execute(sql: "CREATE TABLE t(a)")
}
let semaphore1 = DispatchSemaphore(value: 0)
@@ -433,7 +433,7 @@ class DatabaseLockPreventionTests : GRDBTestCase {
}
let block2 = {
semaphore1.wait()
dbQueue.startPreventingLock()
dbQueue.suspend()
semaphore2.signal()
}
let blocks = [block1, block2]
@@ -445,15 +445,72 @@ class DatabaseLockPreventionTests : GRDBTestCase {
try test(makeDatabaseQueue(journalMode: "wal"))
}
// MARK: - stopPreventingLock
// MARK: - resume
func testStopPreventingLock() throws {
func testResume() throws {
let dbQueue = try makeDatabaseQueue(journalMode: "delete")
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE t(a);")
dbQueue.startPreventingLock()
dbQueue.stopPreventingLock()
try db.execute(sql: "CREATE TABLE t(a)")
dbQueue.suspend()
dbQueue.resume()
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!, 0)
}
}
// MARK: - journalModeCache
// Test for internals. Make sure the journalModeCache is not set too early,
// especially not before user can choose the journal mode
func testJournalModeCache() throws {
do {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
XCTAssertNil(db.journalModeCache)
try db.execute(sql: "PRAGMA journal_mode=truncate")
try db.execute(sql: "CREATE TABLE t(a)")
XCTAssertNil(db.journalModeCache)
}
dbQueue.suspend()
dbQueue.inDatabase { db in
XCTAssertNil(db.journalModeCache)
try? db.execute(sql: "SELECT * FROM sqlite_master")
XCTAssertEqual(db.journalModeCache, "truncate")
}
}
do {
var configuration = Configuration()
configuration.prepareDatabase = { db in
try db.execute(sql: "PRAGMA journal_mode=truncate")
}
let dbQueue = try makeDatabaseQueue(configuration: configuration)
dbQueue.suspend()
dbQueue.inDatabase { db in
XCTAssertNil(db.journalModeCache)
try? db.execute(sql: "SELECT * FROM sqlite_master")
XCTAssertEqual(db.journalModeCache, "truncate")
}
}
do {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
XCTAssertNil(db.journalModeCache)
try db.execute(sql: "CREATE TABLE t(a)")
XCTAssertNil(db.journalModeCache)
}
dbPool.suspend()
try dbPool.writeWithoutTransaction { db in
XCTAssertNil(db.journalModeCache)
try db.execute(sql: "SELECT * FROM sqlite_master")
XCTAssertEqual(db.journalModeCache, "wal")
}
try dbPool.write { db in
XCTAssertEqual(db.journalModeCache, "wal")
}
try dbPool.read { db in
XCTAssertNil(db.journalModeCache)
try db.execute(sql: "SELECT * FROM sqlite_master")
XCTAssertNil(db.journalModeCache)
}
}
}
}