From 88f206e7f5206dcb07ed2f20f7f33e4cd34e85a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 24 Mar 2017 09:18:24 +0100 Subject: [PATCH] New DatabaseReader.read() guarantee: database modifications are prevented --- GRDB/Core/DatabaseQueue.swift | 25 ++++++++++++++-- GRDB/Core/DatabaseReader.swift | 13 +++++++-- GRDB/Record/FetchedRecordsController.swift | 6 ++-- Tests/GRDBTestCase.swift | 2 +- .../DatabaseReader/DatabaseReaderTests.swift | 29 ++++++++++++++++++- 5 files changed, 65 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index ed7dbbcda..bdffa4d4a 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -216,13 +216,17 @@ extension DatabaseQueue : DatabaseReader { /// Alias for inDatabase /// + /// TODO: writes are prevented + /// /// This method is part of the DatabaseReader protocol adoption. public func read(_ block: (Database) throws -> T) rethrows -> T { - return try inDatabase(block) + return try inDatabase { try readOnly($0, block) } } /// Alias for inDatabase /// + /// TODO: writes are not prevented + /// /// This method is part of the DatabaseReader protocol adoption. public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { return try inDatabase(block) @@ -302,6 +306,23 @@ extension DatabaseQueue : DatabaseWriter { /// This method is part of the DatabaseWriter protocol adoption, and must /// be called from the protected database dispatch queue. public func readFromCurrentState(_ block: @escaping (Database) -> Void) { - serializedDatabase.execute(block) + serializedDatabase.execute { readOnly($0, block) } } } + +// Wraps the block between two `PRAGMA query_only` statements. +// +// This method is unsafe because the two calls to `PRAGMA query_only` are +// not guaranteed to be serialized (some other thread could mess with this). +private func readOnly(_ db: Database, _ block: (Database) throws -> T) rethrows -> T { + if db.configuration.readonly { + return try block(db) + } else { + try! db.execute("PRAGMA query_only = 1") // Assume can't fail + let result = try block(db) + try! db.execute("PRAGMA query_only = 0") // Assume can't fail + return result + } +} + + diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index b0c7874cd..8f89777c4 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -38,8 +38,8 @@ public protocol DatabaseReader : class { /// Synchronously executes a read-only block that takes a database /// connection, and returns its result. /// - /// The block argument is isolated. Eventual concurrent database updates are - /// not visible inside the block: + /// Guarantee 1: the block argument is isolated. Eventual concurrent + /// database updates are not visible inside the block: /// /// try reader.read { db in /// // Those two values are guaranteed to be equal, even if the @@ -53,6 +53,8 @@ public protocol DatabaseReader : class { /// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! /// } /// + /// Guarantee 2: the block argument can't modify the database. + /// /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block, or any DatabaseError that would /// happen while establishing the read access to the database. @@ -61,6 +63,8 @@ public protocol DatabaseReader : class { /// Synchronously executes a read-only block that takes a database /// connection, and returns its result. /// + /// The two guarantees of the safe `read` method are lifted: + /// /// The block argument is not isolated: eventual concurrent database updates /// are visible inside the block: /// @@ -71,7 +75,7 @@ public protocol DatabaseReader : class { /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! /// } /// - /// Cursor iteration is safe, though: + /// Cursor iterations are isolated, though: /// /// try reader.unsafeRead { db in /// // No concurrent update can mess with this iteration: @@ -79,6 +83,9 @@ public protocol DatabaseReader : class { /// while let row = try rows.next() { ... } /// } /// + /// The block argument is not prevented from writing (DatabaseQueue, in + /// particular, will accept database modifications in `unsafeRead`). + /// /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block, or any DatabaseError that would /// happen while establishing the read access to the database. diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 1ec6a958e..6ef514d06 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -70,7 +70,7 @@ public final class FetchedRecordsController { } fileprivate init(_ databaseWriter: DatabaseWriter, request: Request, queue: DispatchQueue, itemsAreIdentical: @escaping ItemComparator) throws where Request: TypedRequest, Request.Fetched == Record { - self.request = try databaseWriter.read { db in try ObservedRequest(db, request: request) } + self.request = try databaseWriter.unsafeRead { db in try ObservedRequest(db, request: request) } self.databaseWriter = databaseWriter self.itemsAreIdentical = itemsAreIdentical self.queue = queue @@ -126,7 +126,7 @@ public final class FetchedRecordsController { /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). public func setRequest(_ request: Request) throws where Request: TypedRequest, Request.Fetched == Record { - self.request = try databaseWriter.read { db in try ObservedRequest(db, request: request) } + self.request = try databaseWriter.unsafeRead { db in try ObservedRequest(db, request: request) } // No observer: don't look for changes guard let observer = observer else { return } @@ -402,7 +402,7 @@ extension FetchedRecordsController where Record: TableMapping { /// notified of changes in this queue. The controller itself must be /// used from this queue. public convenience init(_ databaseWriter: DatabaseWriter, request: Request, queue: DispatchQueue = .main) throws where Request: TypedRequest, Request.Fetched == Record { - let rowComparator = try databaseWriter.read { db in try Record.primaryKeyRowComparator(db) } + let rowComparator = try databaseWriter.unsafeRead { db in try Record.primaryKeyRowComparator(db) } try self.init(databaseWriter, request: request, queue: queue, itemsAreIdentical: { rowComparator($0.row, $1.row) }) } } diff --git a/Tests/GRDBTestCase.swift b/Tests/GRDBTestCase.swift index 9ed5509ac..ad6ebd06f 100644 --- a/Tests/GRDBTestCase.swift +++ b/Tests/GRDBTestCase.swift @@ -124,7 +124,7 @@ class GRDBTestCase: XCTestCase { } func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String { - return try! databaseReader.read { db in + return try! databaseReader.unsafeRead { db in _ = try Row.fetchOne(db, request) return lastSQLQuery } diff --git a/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift b/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift index ecb53d97d..cf9b41f7f 100644 --- a/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift +++ b/Tests/Public/Core/DatabaseReader/DatabaseReaderTests.swift @@ -8,5 +8,32 @@ import XCTest #endif class DatabaseReaderTests : GRDBTestCase { - // TODO + + func testDatabaseQueueReadPreventsDatabaseModification() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + } + do { + try dbQueue.read { try $0.execute("INSERT INTO table1 DEFAULT VALUES") } + XCTFail() + } catch let error as DatabaseError where error.resultCode == .SQLITE_READONLY { + } + } + + func testDatabasePoolReadPreventsDatabaseModification() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + } + do { + try dbPool.read { try $0.execute("INSERT INTO table1 DEFAULT VALUES") } + XCTFail() + } catch let error as DatabaseError where error.resultCode == .SQLITE_READONLY { + } + } }