Introduce WALSnapshotToken

This commit is contained in:
Gwendal Roué committed 2022-11-13 18:28:54 +01:00
1 parent dffe56f8a9
commit a71eb3d662
11 files changed
+586 -20

No files matched your search

+8
View File
@@ -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 = "<group>"; };
56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = "<group>"; };
568EB71829211E0700E59445 /* WALSnapshotToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotToken.swift; sourceTree = "<group>"; };
568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTokenTests.swift; sourceTree = "<group>"; };
568ECA8925D7013000B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = "<group>"; };
568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOrdering.swift; sourceTree = "<group>"; };
568ECB1725D9161500B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = "<group>"; };
@@ -1356,6 +1360,7 @@
56A238201B9C74A90082EB20 /* Statement */,
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */,
5607EFD11BB8253300605DE3 /* TransactionObserver */,
568EB71D2921234800E59445 /* WALSnapshotTokenTests.swift */,
);
name = Core;
sourceTree = "<group>";
@@ -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 */,
+33 -6
View File
@@ -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 <https://sqlite.org/lang_naming.html>
@@ -79,6 +93,13 @@ extension Database {
// MARK: - Database Schema
/// Returns the current schema version.
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_schema_version>
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:
// <https://sqlite.org/pragma.html#pragma_schema_version>
// <https://sqlite.org/fileformat2.html#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<SchemaObject>
/// - 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)
""")
}
}
+16 -7
View File
@@ -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
+20
View File
@@ -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<TableInfo>? {
tables[table]
}
+5 -2
View File
@@ -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
+3
View File
@@ -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)
}
+327
View File
@@ -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)
/// ```
///
/// - <https://www.sqlite.org/c3ref/snapshot_get.html>
/// - <https://www.sqlite.org/c3ref/snapshot_open.html>
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<T>(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<T>(
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<Database, Error>) -> 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<Output>(
from token: WALSnapshotToken,
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
{
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<T>(from token: WALSnapshotToken, _ value: () throws -> T) throws -> T {
try open(token)
defer {
token.$schemaCache.update { $0.formUnion(schemaCache) }
}
return try value()
}
}
#endif
@@ -62,6 +62,7 @@ But you should prefer wrapping your schema changes in <doc:Migrations> when you
- ``Database/isGRDBInternalTable(_:)``
- ``Database/isSQLiteInternalTable(_:)``
- ``Database/primaryKey(_:)``
- ``Database/schemaVersion()``
- ``Database/table(_:hasUniqueKey:)``
- ``Database/tableExists(_:)``
- ``Database/triggerExists(_:)``
+8
View File
@@ -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 = "<group>"; };
56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
568EB71A2921232200E59445 /* WALSnapshotToken.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotToken.swift; sourceTree = "<group>"; };
568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshotTokenTests.swift; sourceTree = "<group>"; };
568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = "<group>"; };
568ECB3425D91CEE00B71526 /* SQLSubquery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSubquery.swift; sourceTree = "<group>"; };
5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = "<group>"; };
@@ -1352,6 +1356,7 @@
56A238201B9C74A90082EB20 /* Statement */,
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */,
5607EFD11BB8253300605DE3 /* TransactionObserver */,
568EB71F2921235E00E59445 /* WALSnapshotTokenTests.swift */,
);
name = Core;
sourceTree = "<group>";
@@ -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 */,
+2 -5
View File
@@ -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)")
}
+163
View File
@@ -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<Int>(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