From a71eb3d662c6edd0610222db807d01333ed0fcd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 13 Nov 2022 17:58:01 +0100 Subject: [PATCH] Introduce WALSnapshotToken --- GRDB.xcodeproj/project.pbxproj | 8 + GRDB/Core/Database+Schema.swift | 39 ++- GRDB/Core/DatabasePool.swift | 23 +- GRDB/Core/DatabaseSchemaCache.swift | 20 ++ GRDB/Core/DatabaseSnapshot.swift | 7 +- GRDB/Core/WALSnapshot.swift | 3 + GRDB/Core/WALSnapshotToken.swift | 327 ++++++++++++++++++++ GRDB/Documentation.docc/DatabaseSchema.md | 1 + GRDBCustom.xcodeproj/project.pbxproj | 8 + Tests/GRDBTests/DatabaseSnapshotTests.swift | 7 +- Tests/GRDBTests/WALSnapshotTokenTests.swift | 163 ++++++++++ 11 files changed, 586 insertions(+), 20 deletions(-) create mode 100644 GRDB/Core/WALSnapshotToken.swift create mode 100644 Tests/GRDBTests/WALSnapshotTokenTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 06012b132..a6e0c8ea8 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -202,6 +202,8 @@ 56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; }; 56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; }; 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; + 568EB71929211E0800E59445 /* WALSnapshotToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71829211E0700E59445 /* WALSnapshotToken.swift */; }; + 568EB71E2921234800E59445 /* WALSnapshotTokenTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */; }; 568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA8925D7013000B71526 /* SQLSelection.swift */; }; 568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */; }; 568ECB1825D9161600B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB1725D9161500B71526 /* SQLSubquery.swift */; }; @@ -616,6 +618,8 @@ 56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; 56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; 568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = ""; }; + 568EB71829211E0700E59445 /* WALSnapshotToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotToken.swift; sourceTree = ""; }; + 568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTokenTests.swift; sourceTree = ""; }; 568ECA8925D7013000B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; 568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = ""; }; 568ECB1725D9161500B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = ""; }; @@ -1356,6 +1360,7 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, + 568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */, ); name = Core; sourceTree = ""; @@ -1455,6 +1460,7 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56B7EE822863781300C0525F /* WALSnapshot.swift */, + 568EB71829211E0700E59445 /* WALSnapshotToken.swift */, 5605F1471C672E4000235C62 /* Support */, ); path = Core; @@ -1785,6 +1791,7 @@ 56D496B01D813385008276D7 /* DatabaseErrorTests.swift in Sources */, 56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */, 562206061E420EA4005860AC /* DatabasePoolBackupTests.swift in Sources */, + 568EB71E2921234800E59445 /* WALSnapshotTokenTests.swift in Sources */, 56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */, 563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */, 56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */, @@ -2035,6 +2042,7 @@ 566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, + 568EB71929211E0800E59445 /* WALSnapshotToken.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 8a66e2585..63ccaf628 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -22,6 +22,20 @@ extension Database { schemaIdentifiers = nil schemas.removeAll() } + + mutating func formUnion(_ other: SchemaCache) { + let schemaIdentifiers = Set(schemas.keys).union(other.schemas.keys) + for schemaIdentifier in schemaIdentifiers { + switch (schemas[schemaIdentifier], other.schemas[schemaIdentifier]) { + case let (nil, schema): + schemas[schemaIdentifier] = schema + case let (lhs?, rhs?): + schemas[schemaIdentifier] = lhs.union(rhs) + default: + break + } + } + } } /// An SQLite schema. See @@ -79,6 +93,13 @@ extension Database { // MARK: - Database Schema + /// Returns the current schema version. + /// + /// Related SQLite documentation: + public func schemaVersion() throws -> Int32 { + try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))! + } + /// Clears the database schema cache. /// /// If the database schema is modified by another SQLite connection to the @@ -106,7 +127,7 @@ extension Database { // at offset 40 of the database header: // // - let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version")) + let schemaVersion = try self.schemaVersion() if lastSchemaVersion != schemaVersion { lastSchemaVersion = schemaVersion clearSchemaCache() @@ -1317,11 +1338,8 @@ enum SchemaObjectType: String { struct SchemaInfo: Equatable { private var objects: Set - /// - parameter masterTable: "sqlite_master" or "sqlite_temp_master" - init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language - objects = try SchemaObject.fetchSet(db, sql: """ - SELECT type, name, tbl_name, sql FROM \(masterTableName) - """) + func union(_ other: SchemaInfo) -> SchemaInfo { + SchemaInfo(objects: objects.union(other.objects)) } /// Returns whether there exists a object of given type with this name @@ -1352,3 +1370,12 @@ struct SchemaInfo: Equatable { var sql: String? } } + +extension SchemaInfo { + /// - parameter masterTable: "sqlite_master" or "sqlite_temp_master" + init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language + objects = try SchemaObject.fetchSet(db, sql: """ + SELECT type, name, tbl_name, sql FROM \(masterTableName) + """) + } +} diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index e40ebf400..b2ccad1a0 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -46,10 +46,6 @@ import UIKit /// /// - ``init(path:configuration:)`` /// -/// ### Creating a DatabaseSnapshot -/// -/// - ``makeSnapshot()`` -/// /// ### Accessing the Database /// /// See ``DatabaseReader`` and ``DatabaseWriter`` for more database @@ -58,6 +54,16 @@ import UIKit /// - ``asyncConcurrentRead(_:)`` /// - ``writeInTransaction(_:_:)`` /// +/// ### Creating and Reading WAL Snapshots +/// +/// - ``makeSnapshot()`` +/// - ``currentSnapshotToken()`` +/// - ``read(from:_:)-7wtr2`` +/// - ``read(from:_:)-8bwfe`` +/// - ``readPublisher(from:receiveOn:value:)`` +/// - ``asyncRead(from:_:)`` +/// - ``WALSnapshotToken`` +/// /// ### Managing SQLite Connections /// /// - ``invalidateReadOnlyConnections()`` @@ -851,9 +857,10 @@ extension DatabasePool { /// the transaction: /// /// ```swift + /// let snapshot = try dbPool.makeSnapshot() // OK + /// /// try dbPool.writeWithoutTransaction { db in - /// // OK - /// let snapshot = try dbPool.makeSnapshot() + /// let snapshot = try dbPool.makeSnapshot() // OK /// /// try db.inTransaction { /// try Player.deleteAll() @@ -861,8 +868,10 @@ extension DatabasePool { /// } /// /// // OK - /// let snapshot = try dbPool.makeSnapshot() + /// let snapshot = try dbPool.makeSnapshot() // OK /// } + /// + /// let snapshot = try dbPool.makeSnapshot() // OK /// ``` public func makeSnapshot() throws -> DatabaseSnapshot { // Sanity check diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 9acaae267..eed828e97 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -36,6 +36,26 @@ struct DatabaseSchemaCache { schemaInfo = nil } + func union(_ other: DatabaseSchemaCache) -> DatabaseSchemaCache { + let mergedSchemaInfo: SchemaInfo? + switch (schemaInfo, other.schemaInfo) { + case (nil, nil): + mergedSchemaInfo = nil + case let (nil, info?), let (info?, nil): + mergedSchemaInfo = info + case let (lhs?, rhs?): + mergedSchemaInfo = lhs.union(rhs) + } + + return DatabaseSchemaCache( + schemaInfo: mergedSchemaInfo, + tables: tables.merging(other.tables) { (current, _) in current }, + primaryKeys: primaryKeys.merging(other.primaryKeys) { (current, _) in current }, + columns: columns.merging(other.columns) { (current, _) in current }, + indexes: indexes.merging(other.indexes) { (current, _) in current }, + foreignKeys: foreignKeys.merging(other.foreignKeys) { (current, _) in current }) + } + func table(_ table: String) -> Presence? { tables[table] } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 3a9e66efa..9dfb2250c 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -33,8 +33,8 @@ import Dispatch /// } /// ``` /// -/// When you want to control the database state seen by a snapshot, -/// create the snapshot from within a write access, outside of any transaction. +/// When you want to control the database state seen by a snapshot, create the +/// snapshot from within a write access, outside of any transaction. /// /// For example, compare the two snapshots below. The first one is guaranteed to /// see an empty table of players, because is is created after all players have @@ -65,6 +65,9 @@ import Dispatch /// /// `DatabaseSnapshot` inherits its database access methods from the /// ``DatabaseReader`` protocols. +/// +/// `DatabaseSnapshot` serializes database accesses and can't perform concurrent +/// reads. For concurrent reads, see ``WALSnapshotToken``. public final class DatabaseSnapshot { private let reader: SerializedDatabase diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 6ee1ddaf6..c3a7b1dcc 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -26,6 +26,7 @@ final class WALSnapshot { // // We can't provide snapshots api for SQLCipher, since we'd have linker // errors if they are not enabled. + // swiftlint:disable:next line_length #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) static let available = false @@ -69,5 +70,7 @@ final class WALSnapshot { func compare(_ other: WALSnapshot) -> CInt { return sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot) } + + // swiftlint:disable:next line_length #endif // (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) } diff --git a/GRDB/Core/WALSnapshotToken.swift b/GRDB/Core/WALSnapshotToken.swift new file mode 100644 index 000000000..f72782125 --- /dev/null +++ b/GRDB/Core/WALSnapshotToken.swift @@ -0,0 +1,327 @@ +// swiftlint:disable:next line_length +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else + +#if canImport(Combine) +import Combine +import Dispatch +#endif + +/// A token that indicates which WAL snapshot is being accessed. +/// +/// ## Overview +/// +/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +/// +/// All database accesses performed from a `WALSnapshotToken` see the database +/// content as it existed at the moment the token was created. +/// +/// ## Usage +/// +/// You create a `WALSnapshotToken` from a ``DatabasePool``, +/// with ``DatabasePool/currentSnapshotToken()``: +/// +/// ```swift +/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") +/// let token = try dbPool.currentSnapshotToken() +/// let playerCount = try dbPool.read(from: token) { db in +/// try Player.fetchCount(db) +/// } +/// ``` +/// +/// When you want to control the database state seen by a token, create the +/// token from within a write access, outside of any transaction. +/// +/// For example, compare the two tokens below. The first one is guaranteed to +/// see an empty table of players, because is is created after all players have +/// been deleted, and from the serialized writer dispatch queue which prevents +/// any concurrent write. The second is created without this concurrency +/// protection, which means that some other threads may already have created +/// some players: +/// +/// ```swift +/// let token1 = try dbPool.writeWithoutTransaction { db -> WALSnapshotToken in +/// try db.inTransaction { +/// try Player.deleteAll() +/// return .commit +/// } +/// +/// return dbPool.currentSnapshotToken() +/// } +/// +/// // <- Other threads may have created some players here +/// let token2 = try dbPool.currentSnapshotToken() +/// +/// // Guaranteed to be zero +/// let count1 = try dbPool.read(from: token1, Player.fetchCount) +/// +/// // Could be anything +/// let count2 = try dbPool.read(from: token2, Player.fetchCount) +/// ``` +/// +/// - +/// - +public struct WALSnapshotToken { + let walSnapshot: WALSnapshot + + /// The connection that holds a transaction and prevents checkpointing in + /// order to keep `walSnapshot` valid. + let snapshot: DatabaseSnapshot + + let schemaVersion: Int32 + + // Protected by a lock because a token can be used in multiple + // database connections. + @LockedBox var schemaCache: Database.SchemaCache +} + +extension DatabaseSnapshot { + func currentSnapshotToken() throws -> WALSnapshotToken { + try unsafeReentrantRead { db in + let walSnapshot = try WALSnapshot(db) + let schemaVersion = try db.schemaVersion() + return WALSnapshotToken( + walSnapshot: walSnapshot, + snapshot: self, + schemaVersion: schemaVersion, + schemaCache: db.schemaCache) + } + } +} + +extension DatabasePool { + /// Returns a token associated with the WAL snapshot of the current state of + /// the database. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// The returned token makes it possible to see the database content as it + /// existed at the moment the token was created. + /// + /// It is a programmer error to get a WAL snapshot token from the writer + /// dispatch queue when a transaction is opened: + /// + /// ```swift + /// try dbPool.write { db in + /// try Player.deleteAll() + /// + /// // fatal error: currentSnapshotToken() must not be called from inside a transaction + /// let token = try dbPool.currentSnapshotToken() + /// } + /// ``` + /// + /// To avoid this fatal error, create the token *before* or *after* + /// the transaction: + /// + /// ```swift + /// let token = try dbPool.currentSnapshotToken() // OK + /// + /// try dbPool.writeWithoutTransaction { db in + /// let token = try dbPool.currentSnapshotToken() // OK + /// + /// try db.inTransaction { + /// try Player.deleteAll() + /// return .commit + /// } + /// + /// let token = try dbPool.currentSnapshotToken() // OK + /// } + /// + /// let token = try dbPool.currentSnapshotToken() // OK + /// ``` + public func currentSnapshotToken() throws -> WALSnapshotToken { + try makeSnapshot().currentSnapshotToken() + } + + /// Executes read-only database operations from the given WAL snapshot, and + /// returns their result after they have finished executing. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// let token = try dbPool.currentSnapshotToken() + /// let count = try reader.read(from: token) { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations see the database content as it existed at the moment + /// the token was created. + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// It is a programmer error to call this method from another database + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. + /// + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails + public func read(from token: WALSnapshotToken, _ value: (Database) throws -> T) throws -> T { + try read { db in + try db.read(from: token) { + try value(db) + } + } + } + + /// Executes read-only database operations from the given WAL snapshot, and + /// returns their result after they have finished executing. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// let token = try dbPool.currentSnapshotToken() + /// let count = try await reader.read(from: token) { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations see the database content as it existed at the moment + /// the token was created. + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - parameter value: A closure which accesses the database. + /// - throws: The error thrown by `value`, or any ``DatabaseError`` that + /// would happen while establishing the database access. + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func read( + from token: WALSnapshotToken, + _ value: @Sendable @escaping (Database) throws -> T) + async throws -> T + { + try await read { db in + try db.read(from: token) { + try value(db) + } + } + } + + /// Schedules read-only database operations for execution, from the given + /// WAL snapshot, and returns immediately. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// For example: + /// + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// let token = try dbPool.currentSnapshotToken() + /// try reader.asyncRead(from: token) { dbResult in + /// do { + /// let db = try dbResult.get() + /// let count = try Player.fetchCount(db) + /// } catch { + /// // Handle error + /// } + /// } + /// ``` + /// + /// Database operations see the database content as it existed at the moment + /// the token was created. + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// - parameter value: A closure which accesses the database. Its argument + /// is a `Result` that provides the database connection, or the failure + /// that would prevent establishing the read access to the database. + public func asyncRead(from token: WALSnapshotToken, _ value: @escaping (Result) -> Void) { + asyncRead { dbResult in + do { + let db = try dbResult.get() + try db.read(from: token) { + value(.success(db)) + } + } catch { + value(.failure(error)) + } + } + } + +#if canImport(Combine) + /// Returns a publisher that publishes one value fetched from the given WAL + /// snapshot, and completes. + /// + /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) + /// + /// The database is not accessed until subscription. Value and completion + /// are published on `scheduler` (the main dispatch queue by default). + /// + /// For example: + /// + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// let token = try dbPool.currentSnapshotToken() + /// let countPublisher = reader.readPublisher(from: token) { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations are isolated in a transaction: they do not see + /// changes performed by eventual concurrent writes (even writes performed + /// by other processes). + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - parameter scheduler: A Combine Scheduler. + /// - parameter value: A closure which accesses the database. + @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func readPublisher( + from token: WALSnapshotToken, + receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, + value: @escaping (Database) throws -> Output) + -> DatabasePublishers.Read + { + readPublisher(receiveOn: scheduler) { db in + try db.read(from: token) { + try value(db) + } + } + } +#endif +} + +extension Database { + fileprivate func open(_ token: WALSnapshotToken) throws { + let code = sqlite3_snapshot_open(sqliteConnection, "main", token.walSnapshot.sqliteSnapshot) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code) + } + lastSchemaVersion = token.schemaVersion + schemaCache = token.schemaCache + } + + fileprivate func read(from token: WALSnapshotToken, _ value: () throws -> T) throws -> T { + try open(token) + defer { + token.$schemaCache.update { $0.formUnion(schemaCache) } + } + + return try value() + } +} +#endif diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index c187cff9d..de824bb0e 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -62,6 +62,7 @@ But you should prefer wrapping your schema changes in when you - ``Database/isGRDBInternalTable(_:)`` - ``Database/isSQLiteInternalTable(_:)`` - ``Database/primaryKey(_:)`` +- ``Database/schemaVersion()`` - ``Database/table(_:hasUniqueKey:)`` - ``Database/tableExists(_:)`` - ``Database/triggerExists(_:)`` diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ffef388ad..b1f4dd214 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -199,6 +199,8 @@ 56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; }; 56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; }; 56894FF2260658E600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */; }; + 568EB71C2921232200E59445 /* WALSnapshotToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71A2921232200E59445 /* WALSnapshotToken.swift */; }; + 568EB7202921235E00E59445 /* WALSnapshotTokenTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */; }; 568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB0C25D904CA00B71526 /* SQLSelection.swift */; }; 568ECB3525D91CEF00B71526 /* SQLSubquery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */; }; 5690C3291D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; }; @@ -639,6 +641,8 @@ 56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; 56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; + 568EB71A2921232200E59445 /* WALSnapshotToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotToken.swift; sourceTree = ""; }; + 568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTokenTests.swift; sourceTree = ""; }; 568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; 568ECB3425D91CEE00B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1352,6 +1356,7 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, + 568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */, ); name = Core; sourceTree = ""; @@ -1451,6 +1456,7 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 56564F3828637C9900A19E9F /* WALSnapshot.swift */, + 568EB71A2921232200E59445 /* WALSnapshotToken.swift */, 5605F1471C672E4000235C62 /* Support */, ); path = Core; @@ -1861,6 +1867,7 @@ F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */, 56C0539322ACEECD0029D27D /* Fetch.swift in Sources */, 56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */, + 568EB71C2921232200E59445 /* WALSnapshotToken.swift in Sources */, 563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */, F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */, 569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */, @@ -2080,6 +2087,7 @@ F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 5691D96F27256C490021D540 /* AvailableElements.swift in Sources */, 56419C7F24A51D6E004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */, + 568EB7202921235E00E59445 /* WALSnapshotTokenTests.swift in Sources */, 56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */, F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index 874c57a6d..6730a8984 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -2,12 +2,9 @@ import XCTest @testable import GRDB class DatabaseSnapshotTests: GRDBTestCase { - - /// A helper class - private class Counter { - let dbPool: DatabasePool + /// A helper type + private struct Counter { init(dbPool: DatabasePool) throws { - self.dbPool = dbPool try dbPool.write { db in try db.execute(sql: "CREATE TABLE counter(id INTEGER PRIMARY KEY)") } diff --git a/Tests/GRDBTests/WALSnapshotTokenTests.swift b/Tests/GRDBTests/WALSnapshotTokenTests.swift new file mode 100644 index 000000000..0fd0dcbd4 --- /dev/null +++ b/Tests/GRDBTests/WALSnapshotTokenTests.swift @@ -0,0 +1,163 @@ +#if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) +#else +import XCTest +import GRDB + +// test create from non-wal (read-only) snapshot +final class WALSnapshotTokenTests: GRDBTestCase { + /// A helper type + private struct Counter { + init(dbPool: DatabasePool) throws { + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE counter(id INTEGER PRIMARY KEY)") + } + } + + func increment(_ db: Database) throws { + try db.execute(sql: "INSERT INTO counter DEFAULT VALUES") + } + + func value(_ db: Database) throws -> Int { + try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM counter")! + } + } + + func testWALSnapshotTokenCreationFromNewDatabase() throws { + _ = try makeDatabasePool().currentSnapshotToken() + } + + func testWALSnapshotTokenCreationFromNonWALDatabase() throws { + let dbQueue = try makeDatabaseQueue() + + var config = Configuration() + config.readonly = true + let dbPool = try DatabasePool(path: dbQueue.path, configuration: config) + + do { + _ = try dbPool.currentSnapshotToken() + XCTFail("Expected error") + } catch DatabaseError.SQLITE_ERROR { } + } + + func testWALSnapshotToken() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + + try dbPool.write(counter.increment) + let token = try dbPool.currentSnapshotToken() + try dbPool.write(counter.increment) + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + + func testPassiveCheckpointDoesNotInvalidateWALSnapshotToken() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let token = try dbPool.currentSnapshotToken() + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.passive) } // ignore if error or not, that's not the point + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + } + + func testFullCheckpointDoesNotInvalidateWALSnapshotToken() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let token = try dbPool.currentSnapshotToken() + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.full) } // ignore if error or not, that's not the point + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + } + + func testRestartCheckpointDoesNotInvalidateWALSnapshotToken() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let token = try dbPool.currentSnapshotToken() + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.restart) } // ignore if error or not, that's not the point + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + } + + func testTruncateCheckpointDoesNotInvalidateWALSnapshotToken() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) + try dbPool.write(counter.increment) + let token = try dbPool.currentSnapshotToken() + try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } // ignore if error or not, that's not the point + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + try dbPool.write(counter.increment) + try XCTAssertEqual(dbPool.read(from: token, counter.value), 1) + } + + func testWALSnapshotTokenAndSchemaCache() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: """ + CREATE TABLE player(id INTEGER PRIMARY KEY, name, score); + """) + } + + let token = try dbPool.currentSnapshotToken() + + try dbPool.write { db in + try db.execute(sql: """ + CREATE TABLE team(id INTEGER PRIMARY KEY, name, color); + """) + } + + do { + let exists = try dbPool.read { try $0.tableExists("team") } + XCTAssertTrue(exists) + } + + do { + let exists = try dbPool.read(from: token) { try $0.tableExists("team") } + XCTAssertFalse(exists) + } + + do { + let exists = try dbPool.read { try $0.tableExists("team") } + XCTAssertTrue(exists) + } + } + + func testWALSnapshotTokenAndStatementCache() throws { + let dbPool = try makeDatabasePool() + let request = SQLRequest(sql: "SELECT COUNT(*) FROM player", cached: true) + try dbPool.write { db in + try db.execute(sql: """ + CREATE TABLE player(id INTEGER PRIMARY KEY, name, score); + """) + } + + let token = try dbPool.currentSnapshotToken() + + try dbPool.write { db in + try db.execute(sql: "DROP TABLE player") + } + + do { + let count = try dbPool.read(from: token) { try request.fetchOne($0) } + XCTAssertEqual(count, 0) + } + + do { + _ = try dbPool.read { try request.fetchOne($0) } + XCTFail("Expected error") + } catch DatabaseError.SQLITE_ERROR { } + + do { + let count = try dbPool.read(from: token) { try request.fetchOne($0) } + XCTAssertEqual(count, 0) + } + } +} +#endif