From 12d656d3a19232596e88b99a2b5769a1d1cfd390 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 17 Nov 2022 20:01:17 +0100 Subject: [PATCH] Let SQLite check if DatabaseSnapshotPool can be created --- GRDB/Core/Database.swift | 3 + GRDB/Core/DatabasePool.swift | 64 ++------- GRDB/Core/DatabaseSnapshot.swift | 2 +- GRDB/Core/DatabaseSnapshotPool.swift | 119 +++++++++++++++- .../GRDBTests/DatabaseSnapshotPoolTests.swift | 134 +++++++++++++----- 5 files changed, 224 insertions(+), 98 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 30081aeb9..eddd8d380 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -217,6 +217,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Internal properties + let path: String + /// Support for schema changes performed with ``DatabasePool``: each read /// access needs to clear the schema cache if the schema has been modified /// by the writer connection since the previous read. This property is reset @@ -306,6 +308,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags) self.description = description self.configuration = configuration + self.path = path // We do not report read-only transactions to transaction observers, so // don't bother installing the observation broker for read-only connections. diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 3836c7b55..11aaeb2d2 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -832,10 +832,8 @@ extension DatabasePool { // MARK: - Snapshots - /// Creates an independent database snapshot. - /// - /// The returned snapshot sees an unchanging database content, as it existed - /// at the moment it was created. + /// Creates a database snapshot that serializes accesses to an unchanging + /// database content, as it exists at the moment the snapshot is created. /// /// It is a programmer error to create a snapshot from the writer dispatch /// queue when a transaction is opened: @@ -889,60 +887,20 @@ extension DatabasePool { // swiftlint:disable:next line_length #if (compiler(<5.7.1) && (os(macOS) || targetEnvironment(macCatalyst))) || GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) #else - /// Creates a database snapshot that uses the reader connections of - /// the pool. + /// Creates a database snapshot that allows concurrent accesses to an + /// unchanging database content, as it exists at the moment the snapshot + /// is created. /// /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) /// - /// The returned snapshot sees an unchanging database content, as it existed - /// at the moment it was created. - /// - /// An error is thrown unless the SQLite database is in the - /// [WAL mode](https://www.sqlite.org/wal.html). - /// - /// It is a programmer error to create a snapshot from the writer dispatch - /// queue when a transaction is opened: - /// - /// ```swift - /// try dbPool.write { db in - /// try Player.deleteAll() - /// - /// // fatal error: makeSnapshot() must not be called from inside a transaction - /// let snapshot = try dbPool.makeSnapshot() - /// } - /// ``` - /// - /// To avoid this fatal error, create the snapshot *before* or *after* - /// the transaction: - /// - /// ```swift - /// let snapshot = try dbPool.makeSnapshot() // OK - /// - /// try dbPool.writeWithoutTransaction { db in - /// let snapshot = try dbPool.makeSnapshot() // OK - /// - /// try db.inTransaction { - /// try Player.deleteAll() - /// return .commit - /// } - /// - /// // OK - /// let snapshot = try dbPool.makeSnapshot() // OK - /// } - /// - /// let snapshot = try dbPool.makeSnapshot() // OK - /// ``` + /// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite + /// database is not in the [WAL mode](https://www.sqlite.org/wal.html), or + /// if this method is called from a database access where a write + /// transaction is open. public func makeSnapshotPool() throws -> DatabaseSnapshotPool { - // Sanity check - if writer.onValidQueue { - writer.execute { db in - GRDBPrecondition( - !db.isInsideTransaction, - "makeSnapshotPool() must not be called from inside a transaction.") - } + try unsafeReentrantRead { db in + try DatabaseSnapshotPool(db) } - - return try DatabaseSnapshotPool(path: path, configuration: configuration) } #endif } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index ea02271ad..84fddf8f5 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -52,7 +52,7 @@ import Dispatch /// return .commit /// } /// -/// return dbPool.makeSnapshot() +/// return try dbPool.makeSnapshot() /// } /// /// // <- Other threads may have created some players here diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index be01adae8..33b98dd7d 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -26,8 +26,9 @@ /// /// ## Usage /// -/// You create a `DatabaseSnapshotPool` from a ``DatabasePool``, -/// with ``DatabasePool/makeSnapshotPool()``: +/// You create a `DatabaseSnapshotPool` from a +/// [WAL mode](https://www.sqlite.org/wal.html) database, such as databases +/// created from a ``DatabasePool``: /// /// ```swift /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") @@ -48,13 +49,15 @@ /// some players: /// /// ```swift -/// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in +/// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshotPool in /// try db.inTransaction { /// try Player.deleteAll() /// return .commit /// } /// -/// return dbPool.makeSnapshotPool() +/// return try dbPool.makeSnapshotPool() +/// // OR (this is equivalent) +/// return try DatabaseSnapshotPool(db) /// } /// /// // <- Other threads may have created some players here @@ -74,19 +77,120 @@ /// /// - /// - +/// +/// ## Topics +/// +/// ### Creating a DatabaseSnapshotPool +/// +/// See also ``DatabasePool/makeSnapshotPool()``. +/// +/// - ``init(_:)`` +/// - ``init(path:configuration:)`` public final class DatabaseSnapshotPool { public let configuration: Configuration + /// The path to the database file. + public let path: String + /// The pool of reader connections. /// It is constant, until close() sets it to nil. private var readerPool: Pool? + /// Creates a snapshot of the database. + /// + /// For example: + /// + /// ```swift + /// let dbPool = try DatabasePool(path: "/path/to/database.sqlite") + /// let snapshot = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshotPool in + /// try db.inTransaction { + /// try Player.deleteAll() + /// return .commit + /// } + /// + /// return DatabaseSnapshotPool(db) + /// } + /// ``` + /// + /// If any of the following statements are false when the snapshot is + /// created, a ``DatabaseError`` of code `SQLITE_ERROR` is thrown: + /// + /// - The database connection must be in the + /// [WAL mode](https://www.sqlite.org/wal.html). + /// - There must not be a write transaction open. + /// + /// Related SQLite documentation: + /// + /// - parameter db: A database connection. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public init(_ db: Database) throws { + // Snapshot keeps a long-lived transaction + var configuration = DatabasePool.readerConfiguration(db.configuration) + configuration.allowsUnsafeTransactions = true + + GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") + + var walSnapshot: WALSnapshot? + configuration.prepareDatabase { db in + // Open transaction + try db.beginTransaction(.deferred) + + // Acquire snapshot isolation + try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") + + // Open snapshot + let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot!.sqliteSnapshot) + guard code == SQLITE_OK else { + throw DatabaseError(resultCode: code) + } + } + + self.configuration = configuration + self.path = db.path + + var readerCount = 0 + readerPool = Pool( + maximumCount: configuration.maximumReaderCount, + qos: configuration.readQoS, + makeElement: { + readerCount += 1 // protected by Pool (TODO: document this protection behavior) + return try SerializedDatabase( + path: db.path, + configuration: configuration, + defaultLabel: "GRDB.DatabaseSnapshotPool", + purpose: "snapshot.\(readerCount)") + }) + + // Get WAL snapshot + walSnapshot = try db.isolated(readOnly: true) { try WALSnapshot(db) } + + // Create first connection that will keep the WALSnapshot alive. + try readerPool!.get { _ in } + } + + /// Creates a snapshot of the database. + /// + /// For example: + /// + /// ```swift + /// let snapshot = try DatabaseSnapshotPool(path: "/path/to/database.sqlite") + /// ``` + /// + /// If the database at `path` is not in the + /// [WAL mode](https://www.sqlite.org/wal.html), a ``DatabaseError`` of code + /// `SQLITE_ERROR` is thrown. + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - path: The path to the database file. + /// - configuration: A configuration. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1") - var configuration = DatabasePool.readerConfiguration(configuration) - // Snapshot keeps a long-lived transaction + var configuration = DatabasePool.readerConfiguration(configuration) configuration.allowsUnsafeTransactions = true var walSnapshot: WALSnapshot? @@ -98,7 +202,7 @@ public final class DatabaseSnapshotPool { try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") // Open snapshot - if let walSnapshot { + if let walSnapshot { // nil on first connection created below let code = sqlite3_snapshot_open(db.sqliteConnection, "main", walSnapshot.sqliteSnapshot) guard code == SQLITE_OK else { throw DatabaseError(resultCode: code) @@ -107,6 +211,7 @@ public final class DatabaseSnapshotPool { } self.configuration = configuration + self.path = path var readerCount = 0 readerPool = Pool( diff --git a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift index 7d0b65703..8716e2a8f 100644 --- a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift @@ -22,11 +22,11 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { } } - func test_creation_from_new_database() throws { + func test_creation_from_new_DatabasePool() throws { _ = try makeDatabasePool().makeSnapshotPool() } - func test_creation_from_non_WAL_database() throws { + func test_creation_from_non_WAL_DatabasePool() throws { let dbQueue = try makeDatabaseQueue() var config = Configuration() @@ -39,12 +39,75 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { } catch DatabaseError.SQLITE_ERROR { } } + func test_creation_from_DatabasePool_write_and_read() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.write { db in try DatabaseSnapshotPool(db) } // locked at 1 + try dbPool.write(counter.increment) // 2 + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.read(counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + + func test_creation_from_DatabasePool_writeWithoutTransaction_and_read() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.writeWithoutTransaction { db in try DatabaseSnapshotPool(db) } // locked at 1 + try dbPool.write(counter.increment) // 2 + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.read(counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + + func test_creation_from_DatabasePool_uncommitted_write() throws { + let dbPool = try makeDatabasePool() + do { + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE t(a)") + _ = try DatabaseSnapshotPool(db) + } + XCTFail("Expected error") + } catch DatabaseError.SQLITE_ERROR { } + } + + func test_creation_from_DatabasePool_read_and_read() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.read { db in try DatabaseSnapshotPool(db) } // locked at 1 + try dbPool.write(counter.increment) // 2 + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.read(counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + + func test_creation_from_DatabasePool_unsafeRead_and_read() throws { + let dbPool = try makeDatabasePool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.unsafeRead { db in try DatabaseSnapshotPool(db) } // locked at 1 + try dbPool.write(counter.increment) // 2 + + try XCTAssertEqual(dbPool.read(counter.value), 2) + try XCTAssertEqual(snapshot.read(counter.value), 1) + // Reuse the last connection + try XCTAssertEqual(dbPool.read(counter.value), 2) + } + func test_read() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() - try dbPool.write(counter.increment) + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(dbPool.read(counter.value), 2) try XCTAssertEqual(snapshot.read(counter.value), 1) @@ -93,11 +156,10 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { func test_unsafeRead() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() - try dbPool.write(counter.increment) + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(dbPool.read(counter.value), 2) try XCTAssertEqual(snapshot.unsafeRead(counter.value), 1) @@ -107,11 +169,10 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { func test_unsafeReentrantRead() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() - try dbPool.write(counter.increment) + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(dbPool.read(counter.value), 2) try XCTAssertEqual(snapshot.unsafeReentrantRead { _ in try snapshot.unsafeReentrantRead(counter.value) }, 1) @@ -122,11 +183,10 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func test_read_async() async throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - - try await dbPool.write { try counter.increment($0) } - let snapshot = try dbPool.makeSnapshotPool() - try await dbPool.write { try counter.increment($0) } + let counter = try Counter(dbPool: dbPool) // 0 + try await dbPool.write { try counter.increment($0) } // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 + try await dbPool.write { try counter.increment($0) } // 2 do { let count = try await dbPool.read { try counter.value($0) } @@ -145,45 +205,45 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { func testPassiveCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.passive) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) - try dbPool.write(counter.increment) + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(snapshot.read(counter.value), 1) } func testFullCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.full) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) - try dbPool.write(counter.increment) + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(snapshot.read(counter.value), 1) } func testRestartCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.restart) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) - try dbPool.write(counter.increment) + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(snapshot.read(counter.value), 1) } func testTruncateCheckpointDoesNotInvalidateSnapshotPool() throws { let dbPool = try makeDatabasePool() - let counter = try Counter(dbPool: dbPool) - try dbPool.write(counter.increment) - let snapshot = try dbPool.makeSnapshotPool() + let counter = try Counter(dbPool: dbPool) // 0 + try dbPool.write(counter.increment) // 1 + let snapshot = try dbPool.makeSnapshotPool() // locked at 1 try? dbPool.writeWithoutTransaction { _ = try $0.checkpoint(.truncate) } // ignore if error or not, that's not the point try XCTAssertEqual(snapshot.read(counter.value), 1) - try dbPool.write(counter.increment) + try dbPool.write(counter.increment) // 2 try XCTAssertEqual(snapshot.read(counter.value), 1) } }