Let SQLite check if DatabaseSnapshotPool can be created

This commit is contained in:
Gwendal Roué committed 2022-11-17 20:01:17 +01:00
1 parent 0bc49460d7
commit 12d656d3a1
5 files changed
+224 -98

No files matched your search

+3
View File
@@ -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.
+11 -53
View File
@@ -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
}
+1 -1
View File
@@ -52,7 +52,7 @@ import Dispatch
/// return .commit
/// }
///
/// return dbPool.makeSnapshot()
/// return try dbPool.makeSnapshot()
/// }
///
/// // <- Other threads may have created some players here
+112 -7
View File
@@ -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 @@
///
/// - <https://www.sqlite.org/c3ref/snapshot_get.html>
/// - <https://www.sqlite.org/c3ref/snapshot_open.html>
///
/// ## 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<SerializedDatabase>?
/// 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: <https://www.sqlite.org/c3ref/snapshot_get.html>
///
/// - 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: <https://www.sqlite.org/c3ref/snapshot_get.html>
///
/// - 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(
+97 -37
View File
@@ -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)
}
}