diff --git a/.travis.yml b/.travis.yml index b1c9a2116..8380e54ec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -230,13 +230,11 @@ jobs: script: make test_install_SPM ## Carthage Build - ## Commented out until `make test_CarthageBuild` performs *reliably*. - ## See https://github.com/groue/GRDB.swift/pull/262 - # - stage: Test Installation - # osx_image: xcode10 - # before_install: - # - brew update - # - brew outdated carthage || brew upgrade carthage - # env: - # - TID=Carthages - # script: make test_CarthageBuild + - stage: Test Installation + osx_image: xcode10 + before_install: + - brew update + - brew outdated carthage || brew upgrade carthage + env: + - TID=Carthages + script: make test_CarthageBuild diff --git a/CHANGELOG.md b/CHANGELOG.md index fe1383b1f..de22c0fc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,39 @@ Release Notes ============= +## 3.3.0 + +Released September 16, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v3.3.0-beta1...v3.3.0) + +### New + +- [#409](https://github.com/groue/GRDB.swift/pull/409): DatabaseWriter.concurrentRead + + +### Documentation Diff + +- [Advanced DatabasePool](README.md#advanced-databasepool): the chapter has been updated for the new DatabasePool.concurrentRead method. + + +### API diff + +```diff + protocol DatabaseWriter : DatabaseReader { ++ func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future ++ @available(*, deprecated) + func readFromCurrentState(_ block: @escaping (Database) -> Void) throws + } + ++class Future { ++ func wait() throws -> Value ++} + + extension Cursor { ++ func isEmpty() throws -> Bool + } +``` + + ## 3.3.0-beta1 Released September 5, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v3.2.0...v3.3.0-beta1) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 38110ecfd..719804c45 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -233,6 +233,8 @@ Starting points: - [RxSwiftCommunity/RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources) - [ra1028/DifferenceKit](https://github.com/ra1028/DifferenceKit) - [tonyarnold/Differ](https://github.com/tonyarnold/Differ) +- [onmyway133/DeepDiff](https://github.com/onmyway133/DeepDiff) +- [mcudich/HeckelDiff](https://github.com/mcudich/HeckelDiff) ### FetchedRecordsController Support for Any Request diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index bcc314012..440e2419d 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal ```sh cd [GRDB directory] - git checkout v3.3.0-beta1 + git checkout v3.3.0 git submodule update --init SQLiteCustom/src ```` diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index c26e0d6d5..c98251973 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '3.3.0-beta1' + s.version = '3.3.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 0062157d4..cf26885f8 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -85,6 +85,12 @@ public protocol Cursor : class { } extension Cursor { + /// Returns a Boolean value indicating whether the cursor contains + /// an element. + public func isEmpty() throws -> Bool { + return try next() == nil + } + /// Returns a Boolean value indicating whether the cursor contains an /// element that satisfies the given predicate. /// diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 9bbf8a63f..1257be73b 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -25,9 +25,8 @@ extension Database { } /// Returns whether a table exists. - public func tableExists(_ tableName: String) throws -> Bool { - // SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html) - return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()]) != nil + public func tableExists(_ name: String) throws -> Bool { + return try exists(type: "table", name: name) } /// Returns whether a table is an internal SQLite table. @@ -53,15 +52,31 @@ extension Database { } /// Returns whether a view exists. - public func viewExists(_ viewName: String) throws -> Bool { - // SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html) - return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'view' AND LOWER(name) = ?", arguments: [viewName.lowercased()]) != nil + public func viewExists(_ name: String) throws -> Bool { + return try exists(type: "view", name: name) } /// Returns whether a trigger exists. - public func triggerExists(_ triggerName: String) throws -> Bool { - // SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html) - return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'trigger' AND LOWER(name) = ?", arguments: [triggerName.lowercased()]) != nil + public func triggerExists(_ name: String) throws -> Bool { + return try exists(type: "trigger", name: name) + } + + private func exists(type: String, name: String) throws -> Bool { + // SQlite identifiers are case-insensitive, case-preserving: + // http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html + let name = name.lowercased() + + if try makeSelectStatement("SELECT 1 FROM sqlite_master WHERE type = ? AND LOWER(name) = ?") + .makeCursor(arguments: [type, name]) + .isEmpty() == false + { return true } + + if try makeSelectStatement("SELECT 1 FROM sqlite_temp_master WHERE type = ? AND LOWER(name) = ?") + .makeCursor(arguments: [type, name]) + .isEmpty() == false + { return true } + + return false } /// The primary key for table named `tableName`. @@ -164,14 +179,21 @@ extension Database { return indexes } - let indexes = try Row.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in - let indexName: String = row[1] - let unique: Bool = row[2] - let columns = try Row.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))") - .map { ($0[0] as Int, $0[2] as String) } - .sorted { $0.0 < $1.0 } - .map { $0.1 } - return IndexInfo(name: indexName, columns: columns, unique: unique) + let indexes = try Row + .fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))") + .map { row -> IndexInfo in + // [seq:0 name:"index" unique:0 origin:"c" partial:0] + let indexName: String = row[1] + let unique: Bool = row[2] + let columns = try Row + .fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))") + .map { row -> (Int, String) in + // [seqno:0 cid:2 name:"column"] + (row[0] as Int, row[2] as String) + } + .sorted { $0.0 < $1.0 } + .map { $0.1 } + return IndexInfo(name: indexName, columns: columns, unique: unique) } if indexes.isEmpty { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index bb604e734..6a5df7bb8 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -1,4 +1,5 @@ import Foundation +import Dispatch #if SWIFT_PACKAGE import CSQLite #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER @@ -349,6 +350,8 @@ extension DatabasePool : DatabaseReader { } } + /// This method is deprecated. Use concurrentRead instead. + /// /// Asynchronously executes a read-only block in a protected dispatch queue, /// wrapped in a deferred transaction. /// @@ -374,6 +377,7 @@ extension DatabasePool : DatabaseReader { /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block, or any DatabaseError that would /// happen while establishing the read access to the database. + @available(*, deprecated, message: "Use concurrentRead instead") public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { // https://www.sqlite.org/isolation.html // @@ -422,7 +426,12 @@ extension DatabasePool : DatabaseReader { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. - GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction. If this error is raised from a DatabasePool.write block, use DatabasePool.writeWithoutTransaction instead (and use transactions when needed).") + GRDBPrecondition(!db.isInsideTransaction, """ + readFromCurrentState must not be called from inside a transaction. \ + If this error is raised from a DatabasePool.write block, use \ + DatabasePool.writeWithoutTransaction instead (and use \ + transactions when needed). + """) } // The semaphore that blocks the writing dispatch queue until snapshot @@ -456,7 +465,119 @@ extension DatabasePool : DatabaseReader { throw readError } } - + + public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { + // https://www.sqlite.org/isolation.html + // + // > In WAL mode, SQLite exhibits "snapshot isolation". When a read + // > transaction starts, that reader continues to see an unchanging + // > "snapshot" of the database file as it existed at the moment in time + // > when the read transaction started. Any write transactions that + // > commit while the read transaction is active are still invisible to + // > the read transaction, because the reader is seeing a snapshot of + // > database file from a prior moment in time. + // + // That's exactly what we need. But what does "when read transaction + // starts" mean? + // + // http://www.sqlite.org/lang_transaction.html + // + // > Deferred [transaction] means that no locks are acquired on the + // > database until the database is first accessed. [...] Locks are not + // > acquired until the first read or write operation. [...] Because the + // > acquisition of locks is deferred until they are needed, it is + // > possible that another thread or process could create a separate + // > transaction and write to the database after the BEGIN on the + // > current thread has executed. + // + // Now that's precise enough: SQLite defers "snapshot isolation" until + // the first SELECT: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // UPDATE ... (1) + // Here the change (1) is visible + // SELECT ... + // UPDATE ... (2) + // Here the change (2) is not visible + // + // The readFromCurrentState method says that no change should be visible + // at all. We thus have to perform a select that establishes the + // snapshot isolation before we release the writer queue: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // SELECT anything + // UPDATE ... + // Here the change is not visible by GRDB user + + // Check that we're on the writer queue... + writer.execute { db in + // ... and that no transaction is opened. + GRDBPrecondition(!db.isInsideTransaction, """ + concurrentRead must not be called from inside a transaction. \ + If this error is raised from a DatabasePool.write block, use \ + DatabasePool.writeWithoutTransaction instead (and use \ + transactions when needed). + """) + } + + // The semaphore that blocks the writing dispatch queue until snapshot + // isolation has been established: + let isolationSemaphore = DispatchSemaphore(value: 0) + + // The semaphore that blocks until futureResult is defined: + let futureSemaphore = DispatchSemaphore(value: 0) + var futureResult: Result? = nil + + do { + try readerPool.get { reader in + reader.async { db in + // Open a deferred transaction and access the database in + // order to establish snapshot isolation. + defer { _ = try? db.commit() } + do { + try db.beginTransaction(.deferred) + try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() + } catch { + // Snapshot isolation failure + futureResult = .failure(error) + isolationSemaphore.signal() + futureSemaphore.signal() + return + } + + // Release the writer queue + isolationSemaphore.signal() + + // Reset the schema cache before running user code in snapshot isolation + db.schemaCache = SimpleDatabaseSchemaCache() + + // Fetch and release the future + futureResult = Result { try block(db) } + futureSemaphore.signal() + } + } + } catch { + return Future { throw error } + } + + // Block the writer queue until snapshot isolation success or error + _ = isolationSemaphore.wait(timeout: .distantFuture) + + return Future { + // Block the future until results are fetched + _ = futureSemaphore.wait(timeout: .distantFuture) + + switch futureResult! { + case .failure(let error): + throw error + case .success(let result): + return result + } + } + } + /// Returns a reader that can be used from the current dispatch queue, /// if any. private var currentReader: SerializedDatabase? { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 5ddaa7ed0..06148a0ba 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -203,6 +203,8 @@ extension DatabaseQueue { return try writer.reentrantSync(block) } + /// This method is deprecated. Use concurrentRead instead. + /// /// Synchronously executes *block*. /// /// This method must be called from the protected database dispatch queue, @@ -211,10 +213,7 @@ extension DatabaseQueue { /// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and /// SQLCipher), attempts to write in the database from this meethod throw a /// DatabaseError of resultCode `SQLITE_READONLY`. - /// - /// See `DatabaseWriter.readFromCurrentState`. - /// - /// :nodoc: + @available(*, deprecated, message: "Use concurrentRead instead") public func readFromCurrentState(_ block: @escaping (Database) -> Void) { // Check that we're on the correct queue... writer.execute { db in @@ -224,6 +223,23 @@ extension DatabaseQueue { } } + public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { + // DatabaseQueue can't perform parallel reads. + let result = Result { + // Check that we're on the writer queue... + try writer.execute { db in + // ... and that no transaction is opened. + GRDBPrecondition(!db.isInsideTransaction, "concurrentRead must not be called from inside a transaction.") + return try db.readOnly { + try block(db) + } + } + } + return Future { + try result.unwrap() + } + } + // MARK: - Writing in Database /// Synchronously executes a block in a protected dispatch queue, wrapped diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 6beb4d5ed..423822fcf 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -34,7 +34,7 @@ public class DatabaseSnapshot : DatabaseReader { try db.beginTransaction(.deferred) // Take snapshot - // See DatabasePool.readFromCurrentState for a complete discussion + // See DatabasePool.concurrentRead for a complete discussion try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 3f5b11060..c1b77e010 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -1,3 +1,5 @@ +import Dispatch + /// The protocol for all types that can update a database. /// /// It is adopted by DatabaseQueue and DatabasePool. @@ -60,6 +62,8 @@ public protocol DatabaseWriter : DatabaseReader { // MARK: - Reading from Database + /// This method is deprecated. Use concurrentRead instead. + /// /// Synchronously or asynchronously executes a read-only block that takes a /// database connection. /// @@ -80,7 +84,42 @@ public protocol DatabaseWriter : DatabaseReader { /// } /// try db.execute("INSERT INTO player ...") /// } + @available(*, deprecated, message: "Use concurrentRead instead") func readFromCurrentState(_ block: @escaping (Database) -> Void) throws + + /// Concurrently executes a read-only block that takes a + /// database connection. + /// + /// This method must be called from a writing dispatch queue, outside of any + /// transaction. You'll get a fatal error otherwise. + /// + /// The *block* argument is guaranteed to see the database in the last + /// committed state at the moment this method is called. Eventual concurrent + /// database updates are *not visible* inside the block. + /// + /// This method returns as soon as the isolation guarantees described above + /// are established. To access the fetched results, you call the wait() + /// method of the returned future, on any dispatch queue. + /// + /// In the example below, the number of players is fetched concurrently with + /// the player insertion. Yet the future is guaranteed to return zero: + /// + /// try writer.writeWithoutTransaction { db in + /// // Delete all players + /// try Player.deleteAll() + /// + /// // Count players concurrently + /// let future = writer.concurrentRead { db in + /// return try Player.fetchCount() + /// } + /// + /// // Insert a player + /// try Player(...).insert(db) + /// + /// // Guaranteed to be zero + /// let count = try future.wait() + /// } + func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future } extension DatabaseWriter { @@ -148,6 +187,37 @@ extension DatabaseWriter { #endif } + // MARK: - Reading from Database + + /// Default implementation, based on the deprecated readFromCurrentState. + /// + /// :nodoc: + public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { + let semaphore = DispatchSemaphore(value: 0) + var result: Result? = nil + + do { + try readFromCurrentState { db in + result = Result { try block(db) } + semaphore.signal() + } + } catch { + result = .failure(error) + semaphore.signal() + } + + return Future { + _ = semaphore.wait(timeout: .distantFuture) + + switch result! { + case .failure(let error): + throw error + case .success(let result): + return result + } + } + } + // MARK: - Claiming Disk Space /// Rebuilds the database file, repacking it into a minimal amount of @@ -159,6 +229,29 @@ extension DatabaseWriter { } } +/// A future value. +public class Future { + private var consumed = false + private let _wait: () throws -> Value + + init(_ wait: @escaping () throws -> Value) { + _wait = wait + } + + /// Blocks the current thread until the value is available, and returns it. + /// + /// It is a programmer error to call this method several times. + /// + /// - throws: Any error that prevented the value from becoming available. + public func wait() throws -> Value { + // Not thread-safe and quick and dirty. + // Goal is that users learn not to call this method twice. + GRDBPrecondition(consumed == false, "Future.wait() must be called only once") + consumed = true + return try _wait() + } +} + /// A type-erased DatabaseWriter /// /// Instances of AnyDatabaseWriter forward their methods to an arbitrary @@ -189,9 +282,15 @@ public final class AnyDatabaseWriter : DatabaseWriter { } /// :nodoc: + @available(*, deprecated, message: "Use concurrentRead instead") public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { try base.readFromCurrentState(block) } + + /// :nodoc: + public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { + return base.concurrentRead(block) + } // MARK: - Writing in Database diff --git a/GRDB/QueryInterface/Support/SQLOperators.swift b/GRDB/QueryInterface/Support/SQLOperators.swift index 0dd16b0f2..8ff7c996f 100644 --- a/GRDB/QueryInterface/Support/SQLOperators.swift +++ b/GRDB/QueryInterface/Support/SQLOperators.swift @@ -789,6 +789,7 @@ extension SQLBinaryOperator { static let like = SQLBinaryOperator("LIKE") } +/// :nodoc: extension SQLSpecificExpressible { /// An SQL expression with the `LIKE` SQL operator. diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 48dce6b61..f4e3ca161 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -580,62 +580,41 @@ private func makeFetchFunction( // Should controller become strong at any point before callbacks are // called, such unowned reference would have an opportunity to crash. return { [weak controller] observer in - // Return if observer has been invalidated - guard observer.isValid else { return } - - // Return if fetched records controller has been deallocated - guard let request = controller?.request, let databaseWriter = controller?.databaseWriter else { return } + // Return if observer has been invalidated, or if fetched records + // controller has been deallocated + guard observer.isValid, + let request = controller?.request, + let databaseWriter = controller?.databaseWriter + else { return } willProcessTransaction() - // Fetch items. - // - // This method is called from the database writer's serialized - // queue, so that we can fetch items before other writes have the - // opportunity to modify the database. - // - // However, we don't have to block the writer queue for all the - // duration of the fetch. We just need to block the writer queue - // until we can perform a fetch in isolation. This is the role of - // the readFromCurrentState method (see below). - // - // However, our fetch will last for an unknown duration. And since - // we release the writer queue early, the next database modification - // will triggers this callback while our fetch is, maybe, still - // running. This next callback will also perform its own fetch, that - // will maybe end before our own fetch. - // - // We have to make sure that our fetch is processed *before* the - // next fetch: let's immediately dispatch the processing task in our - // serialized FIFO queue, but have it wait for our fetch to - // complete, with a semaphore: - let semaphore = DispatchSemaphore(value: 0) - var result: Result<(fetchedItems: [Item], fetchedAlongside: T)>? = nil - do { - try databaseWriter.readFromCurrentState { db in - result = Result { try ( - fetchedItems: request.fetchAll(db), - fetchedAlongside: fetchAlongside(db)) } - semaphore.signal() - } - } catch { - result = .failure(error) - semaphore.signal() + // Perform a concurrent read so that writer dispatch queue is released + // as soon as possible. + let future = databaseWriter.concurrentRead { db in + try (fetchedItems: request.fetchAll(db), + fetchedAlongside: fetchAlongside(db)) } - // Process the fetched items - + // Dispatch processing immediately on observer.queue in order to + // process fetched values in the same order as transactions: observer.queue.async { [weak observer] in - // Wait for the fetch to complete: - _ = semaphore.wait(timeout: .distantFuture) + // Return if observer has been deallocated or invalidated + guard let observer = observer, + observer.isValid + else { return } - // Return if observer has been invalidated - guard let strongObserver = observer else { return } - guard strongObserver.isValid else { return } - - completion(result!.map { (fetchedItems, fetchedAlongside) in - (fetchedItems: fetchedItems, fetchedAlongside: fetchedAlongside, observer: strongObserver) - }) + do { + // Wait for concurrent read to complete + let values = try future.wait() + + completion(.success(( + fetchedItems: values.fetchedItems, + fetchedAlongside: values.fetchedAlongside, + observer: observer))) + } catch { + completion(.failure(error)) + } } } } diff --git a/GRDB/Utils/Result.swift b/GRDB/Utils/Result.swift index b388fe1a2..ee5bbfdfc 100644 --- a/GRDB/Utils/Result.swift +++ b/GRDB/Utils/Result.swift @@ -37,4 +37,13 @@ enum Result { return .failure(error) } } + + func unwrap() throws -> Value { + switch self { + case .success(let value): + return value + case .failure(let error): + throw error + } + } } diff --git a/GRDBCipher.podspec b/GRDBCipher.podspec index 784efd481..232a283e6 100644 --- a/GRDBCipher.podspec +++ b/GRDBCipher.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDBCipher' - s.version = '3.3.0-beta1' + s.version = '3.3.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDBPlus.podspec b/GRDBPlus.podspec index d30faf46f..ef47112a8 100644 --- a/GRDBPlus.podspec +++ b/GRDBPlus.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDBPlus' - s.version = '3.3.0-beta1' + s.version = '3.3.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/Makefile b/Makefile index 42800245a..8fbd3d2f3 100644 --- a/Makefile +++ b/Makefile @@ -430,12 +430,12 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v3.3.0-beta1 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v3.3.0 \ --module-version 3.3 \ --module GRDB \ --root-url http://groue.github.io/GRDB.swift/docs/3.3/ \ --output Documentation/Reference \ - --podspec GRDB.swift.podspec + --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else @echo Jazzy must be installed for doc @exit 1 diff --git a/README.md b/README.md index a144077a7..06b06fe14 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,13 @@ GRDB 3 [![Swift](https://img.shields.io/badge/swift-4.1-orange.svg?style=flat)]( ### A toolkit for SQLite databases, with a focus on application development -**Latest release**: September 5, 2018 • version 3.3.0-beta1 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 2 to GRDB 3](Documentation/GRDB2MigrationGuide.md) +**Latest release**: September 16, 2018 • version 3.3.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 2 to GRDB 3](Documentation/GRDB2MigrationGuide.md) **Requirements**: iOS 8.0+ / macOS 10.9+ / watchOS 2.0+ • Swift 4.1+ / Xcode 9.3+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 4.2** | **v3.3.0-beta1** | +| **Swift 4.2** | **v3.3.0** | | Swift 4.1 | [v3.2.0](https://github.com/groue/GRDB.swift/tree/v3.2.0) | | Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) | | Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | @@ -219,20 +219,21 @@ See the [Query Interface](#the-query-interface) Be notified of database changes ```swift -// Track query interface requests -Place.filter(key: 1) - .rx - .fetchOne(in: dbQueue) - .subscribe(onNext: { place: Place? in - print("Place 1 has changed") - }) +let request = Place.order(Column("title")) -// Track SQL requests -SQLRequest("SELECT * FROM place WHERE favorite ORDER BY title") - .rx +// Track request changes with FetchedRecordsController +let controller = FetchedRecordsController(dbQueue, request: request) +controller.trackChanges { controller in + print("Places have changed.") + let places = controller.fetchedRecords // [Place] +} +try controller.performFetch() + +// Track request changes with RxSwift and RxGRDB +request.rx .fetchAll(in: dbQueue) .subscribe(onNext: { places: [Place] in - print("Favorite places have changed") + print("Places have changed.") }) ``` @@ -330,7 +331,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di ```swift let package = Package( dependencies: [ - .package(url: "https://github.com/groue/GRDB.swift.git", from: "3.3.0-beta1") + .package(url: "https://github.com/groue/GRDB.swift.git", from: "3.3.0") ] ) ``` @@ -347,7 +348,7 @@ If you decide to use Carthage despite this warning, and get any Carthage-related ## Manually -1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v3.3.0-beta1) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v3.3.0-beta1` command. +1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v3.3.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v3.3.0` command. 2. Embed the `GRDB.xcodeproj` project in your own project. @@ -6517,7 +6518,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher: ```sh cd [GRDB directory] - git checkout v3.3.0-beta1 + git checkout v3.3.0 git submodule update --init SQLCipher/src ``` @@ -7197,50 +7198,54 @@ try dbPool.write { db in // Increment the number of players try Player(...).insert(db) } +// <- other threads can write in the database here try dbPool.read { db in // Read some random value :-( let count = try Player.fetchCount(db) } ``` -The correct solution is the `readFromCurrentState` method, which must be called from within a write block, outside of any transaction: +The correct solution is the `concurrentRead` method, which must be called from within a write block, outside of any transaction. + +`concurrentRead` returns a **future value** which you consume on any dispatch queue, with the `wait()` method: ```swift // CORRECT -try dbPool.writeWithoutTransaction { db in - try db.inTransaction { - // increment the number of players - try Player(...).insert(db) - return .commit - } +let futureCount: Future = try dbPool.writeWithoutTransaction { db in + // increment the number of players + try Player(...).insert(db) // <- not in a transaction here - try dbPool.readFromCurrentState { db - // Read the number of players. The writer queue has been unlocked :-) - let count = try Player.fetchCount(db) + let futureCount = dbPool.concurrentRead { db + return try Player.fetchCount(db) } + return futureCount } +// <- The writer queue has been unlocked :-) + +// Wait for the player count +let count: Int = try futureCount.wait() ``` -`readFromCurrentState` blocks until it can guarantee its closure argument an isolated access to the last committed state of the database. It then asynchronously executes the closure. If the isolated access can't be established, `readFromCurrentState` throws an error, and the closure is not executed. +`concurrentRead` blocks until it can guarantee its closure argument an isolated access to the last committed state of the database. It then asynchronously executes the closure. -The closure can run concurrently with eventual updates performed after `readFromCurrentState`: those updates won't be visible from within the closure. In the example below, the number of players is guaranteed to be non-zero, even though it is fetched concurrently with the player deletion: +The closure can run concurrently with eventual updates performed after `concurrentRead`: those updates won't be visible from within the closure. In the example below, the number of players is guaranteed to be non-zero, even though it is fetched concurrently with the player deletion: ```swift try dbPool.writeWithoutTransaction { db in // Increment the number of players try Player(...).insert(db) - try dbPool.readFromCurrentState { db + let futureCount = dbPool.concurrentRead { db // Guaranteed to be non-zero - let count = try Player.fetchCount(db) + return try Player.fetchCount(db) } try Player.deleteAll(db) } ``` -[Transaction Observers](#transactionobserver-protocol) can also use `readFromCurrentState` in their `databaseDidCommit` method in order to process database changes without blocking other threads that want to write into the database. +[Transaction Observers](#transactionobserver-protocol) can also use `concurrentRead` in their `databaseDidCommit` method in order to process database changes without blocking other threads that want to write into the database. ### Database Snapshots @@ -7306,21 +7311,14 @@ try snapshot2.read { db in Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/3.3/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/3.3/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. -These protocols provide a unified API that lets you write safe concurrent code that targets all three concurrency modes. - -However, queues are not pools which are different from snapshots, and DatabaseReader and DatabaseWriter provide the *smallest* common guarantees. They require more discipline: - -- Pools are less forgiving than queues when one overlooks a transaction (see [concurrency rule 3](#guarantees-and-rules)). -- DatabaseWriter.readFromCurrentState is synchronous, or asynchronous, depending on whether it is run by a queue or a pool (see [advanced DatabasePool](#advanced-databasepool)). It thus requires higher libDispatch skills, and more complex synchronization code. - -DatabaseReader and DatabaseWriter are not a tool for applications that hesitate between DatabaseQueue and DatabasePool, and look for a common API. As seen above, the protocols actually make applications harder to write correctly. Instead, they target generic code that has *both* queues and pools in mind. The built-in AnyDatabaseReader and AnyDatabaseWriter type erasers serve the same purpose. - -DatabaseWriter and DatabaseReader fuel, for example: +These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example: - [Migrations](#migrations) - [FetchedRecordsController](#fetchedrecordscontroller) - [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) +Caution: DatabaseQueue and DatabasePool only provide the *smallest* common guarantees. They don't erase the differences between queues, pools, and snapshots. See for example [Differences between Database Queues and Pools](#differences-between-database-queues-and-pools). + ### Unsafe Concurrency APIs @@ -7807,7 +7805,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@Chiliec](https://github.com/Chiliec), [@darrenclark](https://github.com/darrenclark), [@fpillet](http://github.com/fpillet), [@gusrota](https://github.com/gusrota), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@Marus](https://github.com/Marus), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. +- [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@Chiliec](https://github.com/Chiliec), [@darrenclark](https://github.com/darrenclark), [@fpillet](http://github.com/fpillet), [@gusrota](https://github.com/gusrota), [@hartbit](https://github.com/hartbit), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@Marus](https://github.com/Marus), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@swiftlyfalling](https://github.com/swiftlyfalling), [@valexa](https://github.com/valexa), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. diff --git a/SQLCipher/src b/SQLCipher/src index aa6e995ee..e8720c0d0 160000 --- a/SQLCipher/src +++ b/SQLCipher/src @@ -1 +1 @@ -Subproject commit aa6e995ee414056911c468dde3bd0e7d3cbea00e +Subproject commit e8720c0d00e82017469e11dd9b25fc8ca15c7236 diff --git a/TODO.md b/TODO.md index f4452b765..73e38da04 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,8 @@ - [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0075-import-test.md - [ ] Avoid code duplication: https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 - [ ] Allow joining methods on DerivableRequest +- [ ] DatabaseWriter.assertWriteAccess() +- [ ] Configuration.crashOnError = true - [ ] Support for "INSERT INTO ... SELECT ...". For example: ```swift diff --git a/Tests/Carthage/GRDBiOS/iOS.xcodeproj/project.pbxproj b/Tests/Carthage/GRDBiOS/iOS.xcodeproj/project.pbxproj index dfa0962ab..6649a87c8 100644 --- a/Tests/Carthage/GRDBiOS/iOS.xcodeproj/project.pbxproj +++ b/Tests/Carthage/GRDBiOS/iOS.xcodeproj/project.pbxproj @@ -7,18 +7,16 @@ objects = { /* Begin PBXBuildFile section */ + 277479482141D92B00FCD661 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 277479452141D92B00FCD661 /* PlayerEditionViewController.swift */; }; + 277479492141D92B00FCD661 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 277479462141D92B00FCD661 /* PlayersViewController.swift */; }; + 2774794A2141D92B00FCD661 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 277479472141D92B00FCD661 /* Player.swift */; }; 5644E4041C1072A30090716E /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5644E4031C1072A30090716E /* GRDB.framework */; }; 5644E4061C1072CA0090716E /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 5644E4031C1072A30090716E /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 567374431B4D46600089DE44 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374411B4D46600089DE44 /* Main.storyboard */; }; 567374451B4D46600089DE44 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567374441B4D46600089DE44 /* Assets.xcassets */; }; 567374481B4D46600089DE44 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567374461B4D46600089DE44 /* LaunchScreen.storyboard */; }; - 568E2B991CACE4ED00426E7B /* SimplePersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E2B981CACE4ED00426E7B /* SimplePersonsViewController.swift */; }; 56AEC9D91CAA985700452D96 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D21CAA985700452D96 /* AppDelegate.swift */; }; 56AEC9DA1CAA985700452D96 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D31CAA985700452D96 /* AppDatabase.swift */; }; - 56AEC9DB1CAA985700452D96 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D41CAA985700452D96 /* DemoViewController.swift */; }; - 56AEC9DD1CAA985700452D96 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D61CAA985700452D96 /* Person.swift */; }; - 56AEC9DE1CAA985700452D96 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D71CAA985700452D96 /* PersonEditionViewController.swift */; }; - 56AEC9DF1CAA985700452D96 /* PersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AEC9D81CAA985700452D96 /* PersonsViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -36,19 +34,17 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 277479452141D92B00FCD661 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; + 277479462141D92B00FCD661 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = ""; }; + 277479472141D92B00FCD661 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; 5644E4031C1072A30090716E /* GRDB.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GRDB.framework; path = ../../../Carthage/Build/iOS/GRDB.framework; sourceTree = ""; }; 567374381B4D46600089DE44 /* iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = iOS.app; sourceTree = BUILT_PRODUCTS_DIR; }; 567374421B4D46600089DE44 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 567374441B4D46600089DE44 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 567374471B4D46600089DE44 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 567374491B4D46600089DE44 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 568E2B981CACE4ED00426E7B /* SimplePersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePersonsViewController.swift; sourceTree = ""; }; 56AEC9D21CAA985700452D96 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 56AEC9D31CAA985700452D96 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; - 56AEC9D41CAA985700452D96 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = ""; }; - 56AEC9D61CAA985700452D96 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = ""; }; - 56AEC9D71CAA985700452D96 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = ""; }; - 56AEC9D81CAA985700452D96 /* PersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonsViewController.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -84,16 +80,14 @@ isa = PBXGroup; children = ( 56AEC9D21CAA985700452D96 /* AppDelegate.swift */, - 567374441B4D46600089DE44 /* Assets.xcassets */, 56AEC9D31CAA985700452D96 /* AppDatabase.swift */, - 56AEC9D41CAA985700452D96 /* DemoViewController.swift */, + 277479472141D92B00FCD661 /* Player.swift */, + 277479452141D92B00FCD661 /* PlayerEditionViewController.swift */, + 277479462141D92B00FCD661 /* PlayersViewController.swift */, + 567374441B4D46600089DE44 /* Assets.xcassets */, 567374491B4D46600089DE44 /* Info.plist */, 567374461B4D46600089DE44 /* LaunchScreen.storyboard */, 567374411B4D46600089DE44 /* Main.storyboard */, - 56AEC9D61CAA985700452D96 /* Person.swift */, - 56AEC9D71CAA985700452D96 /* PersonEditionViewController.swift */, - 56AEC9D81CAA985700452D96 /* PersonsViewController.swift */, - 568E2B981CACE4ED00426E7B /* SimplePersonsViewController.swift */, ); name = GRDBDemoiOS; path = ../../../DemoApps/GRDBDemoiOS/GRDBDemoiOS; @@ -190,12 +184,10 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 56AEC9DD1CAA985700452D96 /* Person.swift in Sources */, - 56AEC9DF1CAA985700452D96 /* PersonsViewController.swift in Sources */, - 56AEC9DB1CAA985700452D96 /* DemoViewController.swift in Sources */, + 277479482141D92B00FCD661 /* PlayerEditionViewController.swift in Sources */, 56AEC9DA1CAA985700452D96 /* AppDatabase.swift in Sources */, - 568E2B991CACE4ED00426E7B /* SimplePersonsViewController.swift in Sources */, - 56AEC9DE1CAA985700452D96 /* PersonEditionViewController.swift in Sources */, + 277479492141D92B00FCD661 /* PlayersViewController.swift in Sources */, + 2774794A2141D92B00FCD661 /* Player.swift in Sources */, 56AEC9D91CAA985700452D96 /* AppDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -263,7 +255,7 @@ ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; }; name = Debug; }; @@ -300,7 +292,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_VERSION = 4.0; + SWIFT_VERSION = 4.2; VALIDATE_PRODUCT = YES; }; name = Release; diff --git a/Tests/Carthage/GRDBiOS/iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Tests/Carthage/GRDBiOS/iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/Tests/Carthage/GRDBiOS/iOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 1d999c64f..109d65759 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -80,6 +80,7 @@ private class UserDatabaseWriter : DatabaseWriter { func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() } + func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { preconditionFailure() } } // MARK: - FTS5Tokenizer diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 280b43b9d..a56830c49 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -836,6 +836,21 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { _ = s.wait(timeout: .distantFuture) } + func testConcurrentReadOpensATransaction() throws { + let dbPool = try makeDatabasePool() + let future = dbPool.writeWithoutTransaction { db in + dbPool.concurrentRead { db in + XCTAssertTrue(db.isInsideTransaction) + do { + try db.execute("BEGIN DEFERRED TRANSACTION") + XCTFail("Expected error") + } catch { + } + } + } + try future.wait() + } + func testReadFromCurrentStateOutsideOfTransaction() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in @@ -871,6 +886,38 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { XCTAssertEqual(i, 0) } + func testConcurrentReadOutsideOfTransaction() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.create(table: "persons") { t in + t.column("id", .integer).primaryKey() + } + } + + // Writer Reader + // dbPool.writeWithoutTransaction { + // > + // dbPool.concurrentRead { + // < + // INSERT INTO items (id) VALUES (NULL) + // > + let s1 = DispatchSemaphore(value: 0) + // } SELECT COUNT(*) FROM persons -> 0 + // < + // } + + let future: Future = try dbPool.writeWithoutTransaction { db in + let future: Future = dbPool.concurrentRead { db in + _ = s1.wait(timeout: .distantFuture) + return try! Int.fetchOne(db, "SELECT COUNT(*) FROM persons")! + } + try db.execute("INSERT INTO persons DEFAULT VALUES") + s1.signal() + return future + } + XCTAssertEqual(try future.wait(), 0) + } + func testReadFromCurrentStateError() throws { let dbPool = try makeDatabasePool() try dbPool.writeWithoutTransaction { db in @@ -890,6 +937,26 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } } + func testConcurrentReadError() throws { + let dbPool = try makeDatabasePool() + try dbPool.writeWithoutTransaction { db in + try db.execute("PRAGMA locking_mode=EXCLUSIVE") + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + let future = dbPool.concurrentRead { db in + fatalError("Should not run") + } + do { + try future.wait() + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_BUSY) + XCTAssertEqual(error.message!, "database is locked") + XCTAssertTrue(error.sql == nil) + XCTAssertEqual(error.description, "SQLite error 5: database is locked") + } + } + } + func testLongRunningReadTransaction() throws { // A test for a "user-defined" DatabaseSnapshot based on DatabaseQueue let dbName = "test.sqlite"