From 86b9616dd7fa6ae99713b92cb23fcfc40e561e85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 24 Jul 2020 18:32:24 +0200 Subject: [PATCH] DatabasePool readers don't invalidate their database schema cache until schema is actually changed. --- CHANGELOG.md | 5 +- GRDB/Core/Database+Schema.swift | 10 +++ GRDB/Core/Database.swift | 50 +------------ GRDB/Core/DatabasePool.swift | 72 ++++++++++++++----- GRDB/Core/DatabaseSnapshot.swift | 9 ++- .../DatabasePoolConcurrencyTests.swift | 7 +- .../DatabasePoolSchemaCacheTests.swift | 24 +++++-- Tests/GRDBTests/DatabaseSnapshotTests.swift | 55 ++++++++++++++ 8 files changed, 154 insertions(+), 78 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce64bf565..0799e3e53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,7 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. - #### 5.x Releases @@ -70,10 +68,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... - +- **New**: DatabasePool readers don't invalidate their database schema cache until schema is actually changed. ## 5.0.0-beta.9 diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 175610bec..25de4e0eb 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -18,6 +18,16 @@ extension Database { publicStatementCache.clear() } + /// Clears the database schema cache if the database schema has changed + /// since this method was last called. + func clearSchemaCacheIfNeeded() throws { + let schemaVersion = try Int32.fetchOne(internalCachedSelectStatement(sql: "PRAGMA schema_version")) + if _lastSchemaVersion != schemaVersion { + _lastSchemaVersion = schemaVersion + clearSchemaCache() + } + } + /// Returns whether a table exists. public func tableExists(_ name: String) throws -> Bool { try exists(type: .table, name: name) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 8f9d57a38..1f1b4736b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -125,6 +125,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Internal properties // Caches + var _lastSchemaVersion: Int32? // Support for clearSchemaCacheIfNeeded() var schemaCache: DatabaseSchemaCache // internal so that it can be tested lazy var internalStatementCache = StatementCache(database: self) lazy var publicStatementCache = StatementCache(database: self) @@ -1072,55 +1073,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib assert(isInsideTransaction) } - /// Begins a database transaction and take a snapshot of the last committed - /// database state. - func beginSnapshotTransaction() throws { - // https://www.sqlite.org/isolation.html - // - // > In WAL mode, SQLite exhibits "snapshot isolation". When a read - // > transaction starts, that reader continues to see an unchanging - // > "snapshot" of the database file as it existed at the moment in time - // > when the read transaction started. Any write transactions that - // > commit while the read transaction is active are still invisible to - // > the read transaction, because the reader is seeing a snapshot of - // > database file from a prior moment in time. - // - // That's exactly what we need. But what does "when read transaction - // starts" mean? - // - // http://www.sqlite.org/lang_transaction.html - // - // > Deferred [transaction] means that no locks are acquired on the - // > database until the database is first accessed. [...] Locks are not - // > acquired until the first read or write operation. [...] Because the - // > acquisition of locks is deferred until they are needed, it is - // > possible that another thread or process could create a separate - // > transaction and write to the database after the BEGIN on the - // > current thread has executed. - // - // Now that's precise enough: SQLite defers "snapshot isolation" until - // the first SELECT: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // UPDATE ... (1) - // Here the change (1) is visible - // SELECT ... - // UPDATE ... (2) - // Here the change (2) is not visible - // - // We thus have to perform a select that establishes the - // snapshot isolation before we release the writer queue: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // SELECT anything - // UPDATE ... - // Here the change is not visible by GRDB user - try beginTransaction(.deferred) - try internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() - } - /// Rollbacks a database transaction. public func rollback() throws { // The SQLite documentation contains two related but distinct techniques diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 022ffc985..fc88caf81 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -322,8 +322,7 @@ extension DatabasePool: DatabaseReader { // The block isolation comes from the DEFERRED transaction. // See DatabasePoolTests.testReadMethodIsolationOfBlock(). try db.inTransaction(.deferred) { - // Reset the schema cache before running user code in snapshot isolation - db.clearSchemaCache() + try db.clearSchemaCacheIfNeeded() result = try block(db) return .commit } @@ -369,9 +368,7 @@ extension DatabasePool: DatabaseReader { do { // The block isolation comes from the DEFERRED transaction. try db.beginTransaction(.deferred) - - // Reset the schema cache before running user code in snapshot isolation - db.clearSchemaCache() + try db.clearSchemaCacheIfNeeded() block(.success(db)) } catch { block(.failure(error)) @@ -416,9 +413,7 @@ extension DatabasePool: DatabaseReader { do { // The block isolation comes from the DEFERRED transaction. try db.beginTransaction(.deferred) - - // Reset the schema cache before running user code in snapshot isolation - db.clearSchemaCache() + try db.clearSchemaCacheIfNeeded() block(.success(db)) } catch { block(.failure(error)) @@ -460,8 +455,7 @@ extension DatabasePool: DatabaseReader { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") return try readerPool.get { reader in try reader.sync { db in - // Reset the schema cache - db.clearSchemaCache() + try db.clearSchemaCacheIfNeeded() return try block(db) } } @@ -500,8 +494,7 @@ extension DatabasePool: DatabaseReader { } else { return try readerPool.get { reader in try reader.sync { db in - // Reset the schema cache - db.clearSchemaCache() + try db.clearSchemaCacheIfNeeded() return try block(db) } } @@ -592,19 +585,64 @@ extension DatabasePool: DatabaseReader { releaseReader() } do { - try db.beginSnapshotTransaction() + // https://www.sqlite.org/isolation.html + // + // > In WAL mode, SQLite exhibits "snapshot isolation". When + // > a read transaction starts, that reader continues to see + // > an unchanging "snapshot" of the database file as it + // > existed at the moment in time when the read transaction + // > started. Any write transactions that commit while the + // > read transaction is active are still invisible to the + // > read transaction, because the reader is seeing a + // > snapshot of database file from a prior moment in time. + // + // That's exactly what we need. But what does "when read + // transaction starts" mean? + // + // http://www.sqlite.org/lang_transaction.html + // + // > Deferred [transaction] means that no locks are acquired + // > on the database until the database is first accessed. + // > [...] Locks are not acquired until the first read or + // > write operation. [...] Because the acquisition of locks + // > is deferred until they are needed, it is possible that + // > another thread or process could create a separate + // > transaction and write to the database after the BEGIN + // > on the current thread has executed. + // + // Now that's precise enough: SQLite defers snapshot + // isolation until the first SELECT: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // UPDATE ... (1) + // Here the change (1) is visible from the reader + // SELECT ... + // UPDATE ... (2) + // Here the change (2) is not visible from the reader + // + // We thus have to perform a select that establishes the + // snapshot isolation before we release the writer queue: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // SELECT anything + // UPDATE ... (1) + // Here the change (1) is not visible from the reader + // + // Since any select goes, use `PRAGMA schema_version`. + try db.beginTransaction(.deferred) + try db.clearSchemaCacheIfNeeded() } catch { isolationSemaphore.signal() block(.failure(error)) return } - // Release the writer queue + // Now that we have an isolated snapshot of the last commit, we + // can release the writer queue. isolationSemaphore.signal() - // Reset the schema cache before running user code in snapshot isolation - db.clearSchemaCache() - block(.success(db)) } } catch { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index edd3edbeb..a865fdeb1 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -57,7 +57,14 @@ public class DatabaseSnapshot: DatabaseReader { guard journalMode == "wal" else { throw DatabaseError(message: "WAL mode is not activated at path: \(path)") } - try db.beginSnapshotTransaction() + + // Open transaction + try db.beginTransaction(.deferred) + + // Acquire snapshot isolation + try db.internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() + + // Support for ValueObservation in DatabasePool version = try? db.takeVersionSnapshot() } } diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 73a26c40a..ccf171093 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -480,10 +480,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try! dbPool.read { db in s1.signal() _ = s2.wait(timeout: .distantFuture) - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) // Not a bug. The writer did not start a transaction. + // We read 0 due to snaphot isolation: the reader has checked + // the schema version before `s1` could let the writer insert + // an item. + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0) s3.signal() _ = s4.wait(timeout: .distantFuture) - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0) } } let block2 = { () in diff --git a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift index cfe20e1ca..850404c98 100644 --- a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift @@ -31,7 +31,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { _ = try db.columns(in: "items") _ = try db.indexes(on: "items") - // Assert that reader cache is warmed + // Assert that reader cache is warm + XCTAssertTrue(db.schemaCache.primaryKey("items") != nil) + XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) + XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) + } + + try dbPool.read { db in + // Assert that reader cache is still warm XCTAssertTrue(db.schemaCache.primaryKey("items") != nil) XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) @@ -43,24 +50,31 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { _ = try db.columns(in: "items") _ = try db.indexes(on: "items") - // Assert that writer cache is warmed + // Assert that writer cache is warm XCTAssertTrue(db.schemaCache.primaryKey("items") != nil) XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) } try dbPool.write { db in - // Empty cache after schema change + // Assert that writer cache is still warm + XCTAssertTrue(db.schemaCache.primaryKey("items") != nil) + XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) + XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil) + } + + try dbPool.write { db in + // Change schema try db.execute(sql: "DROP TABLE items") - // Assert that the writer cache is empty + // Assert that the writer cache is cleared XCTAssertTrue(db.schemaCache.primaryKey("items") == nil) XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) } try dbPool.read { db in - // Assert that a reader cache is empty + // Assert that reader cache is cleared XCTAssertTrue(db.schemaCache.primaryKey("items") == nil) XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) XCTAssertTrue(db.schemaCache.indexes(on: "items") == nil) diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index df3c8cb4a..432099d0a 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -195,6 +195,61 @@ class DatabaseSnapshotTests: GRDBTestCase { // MARK: - Concurrency + func testReadBlockIsolationStartingWithRead() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + } + + // Block 1 Block 2 + // dbSnapshot.read { + // > + let s1 = DispatchSemaphore(value: 0) + // INSERT INTO items (id) VALUES (NULL) + // < + let s2 = DispatchSemaphore(value: 0) + // SELECT COUNT(*) FROM items -> 0 + // > + let s3 = DispatchSemaphore(value: 0) + // INSERT INTO items (id) VALUES (NULL) + // < + let s4 = DispatchSemaphore(value: 0) + // SELECT COUNT(*) FROM items -> 0 + // } + + let block1 = { () in + let snapshot = try! dbPool.makeSnapshot() + try! snapshot.read { db in + s1.signal() + _ = s2.wait(timeout: .distantFuture) + // We read 0 due to snaphot isolation which was acquired before + // `s1` could let the writer insert an item. + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0) + s3.signal() + _ = s4.wait(timeout: .distantFuture) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0) + } + } + let block2 = { () in + do { + _ = s1.wait(timeout: .distantFuture) + try dbPool.writeWithoutTransaction { db in + try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") + s2.signal() + _ = s3.wait(timeout: .distantFuture) + try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") + s4.signal() + } + } catch { + XCTFail("error: \(error)") + } + } + let blocks = [block1, block2] + DispatchQueue.concurrentPerform(iterations: blocks.count) { index in + blocks[index]() + } + } + func testDefaultLabel() throws { let dbPool = try makeDatabasePool()