Simplify SerializedDatabase

This commit is contained in:
Gwendal Roué committed 2016-03-29 08:26:07 +02:00
1 parent c04c8ef815
commit ab3ec443d2
4 files changed
+80 -82

No files matched your search

+20 -18
View File
@@ -41,7 +41,9 @@ public final class DatabasePool {
// Activate WAL Mode unless readonly
if !configuration.readonly {
let journalMode = String.fetchOne(writer, "PRAGMA journal_mode=WAL")
let journalMode = writer.performSync { db in
String.fetchOne(db, "PRAGMA journal_mode=WAL")
}
guard journalMode == "wal" else {
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
}
@@ -59,7 +61,7 @@ public final class DatabasePool {
configuration: readerConfig,
schemaCache: databaseSchemaCache)
serializedDatabase.inDatabase { db in
serializedDatabase.performSync { db in
for function in self.functions {
db.addFunction(function)
}
@@ -83,7 +85,7 @@ public final class DatabasePool {
///
/// - parameter kind: The checkpoint mode (default passive)
public func checkpoint(kind: CheckpointMode = .Passive) throws {
try writer.inDatabase { db in
try writer.performSync { db in
// TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and
// check whether we need a busy handler on writer and/or readers
// when kind is not .Passive.
@@ -102,12 +104,12 @@ public final class DatabasePool {
/// This method blocks the current thread until all database accesses are completed.
public func releaseMemory() {
// TODO: test that this method blocks the current thread until all database accesses are completed.
writer.inDatabase { db in
writer.performSync { db in
db.releaseMemory()
}
readerPool.forEach { reader in
reader.inDatabase { db in
reader.performSync { db in
db.releaseMemory()
}
}
@@ -172,7 +174,7 @@ extension DatabasePool : DatabaseReader {
// The block isolation comes from the DEFERRED transaction.
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
return try readerPool.get { reader in
try reader.inDatabase { db in
try reader.performSync { db in
var result: T? = nil
try db.inTransaction(.Deferred) {
result = try block(db: db)
@@ -205,7 +207,7 @@ extension DatabasePool : DatabaseReader {
/// - throws: The error thrown by the block.
public func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T {
return try readerPool.get { reader in
try reader.inDatabase { db in
try reader.performSync { db in
try block(db: db)
}
}
@@ -230,15 +232,15 @@ extension DatabasePool : DatabaseReader {
public func addFunction(function: DatabaseFunction) {
functions.remove(function)
functions.insert(function)
writer.addFunction(function)
readerPool.forEach { $0.addFunction(function) }
writer.performSync { db in db.addFunction(function) }
readerPool.forEach { $0.performSync { db in db.addFunction(function) } }
}
/// Remove an SQL function.
public func removeFunction(function: DatabaseFunction) {
functions.remove(function)
writer.removeFunction(function)
readerPool.forEach { $0.removeFunction(function) }
writer.performSync { db in db.removeFunction(function) }
readerPool.forEach { $0.performSync { db in db.removeFunction(function) } }
}
@@ -256,15 +258,15 @@ extension DatabasePool : DatabaseReader {
public func addCollation(collation: DatabaseCollation) {
collations.remove(collation)
collations.insert(collation)
writer.addCollation(collation)
readerPool.forEach { $0.addCollation(collation) }
writer.performSync { db in db.addCollation(collation) }
readerPool.forEach { $0.performSync { db in db.addCollation(collation) } }
}
/// Remove a collation.
public func removeCollation(collation: DatabaseCollation) {
collations.remove(collation)
writer.removeCollation(collation)
readerPool.forEach { $0.removeCollation(collation) }
writer.performSync { db in db.removeCollation(collation) }
readerPool.forEach { $0.performSync { db in db.removeCollation(collation) } }
}
}
@@ -288,7 +290,7 @@ extension DatabasePool : DatabaseWriter {
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func write<T>(block: (db: Database) throws -> T) rethrows -> T {
return try writer.inDatabase(block)
return try writer.performSync(block)
}
/// Synchronously executes a block in a protected dispatch queue, wrapped
@@ -313,7 +315,7 @@ extension DatabasePool : DatabaseWriter {
/// .Commit or .Rollback.
/// - throws: The error thrown by the block.
public func writeInTransaction(kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) throws {
try writer.inDatabase { db in
try writer.performSync { db in
try db.inTransaction(kind) {
try block(db: db)
}
@@ -348,7 +350,7 @@ extension DatabasePool : DatabaseWriter {
let s = dispatch_semaphore_create(0)
self.readerPool.get { reader in
reader.asyncInDatabase { db in
reader.performAsync { db in
db.read { db in
// Now we're isolated: release the writing queue
dispatch_semaphore_signal(s)
+19 -11
View File
@@ -61,7 +61,7 @@ public final class DatabaseQueue {
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func inDatabase<T>(block: (db: Database) throws -> T) rethrows -> T {
return try serializedDatabase.inDatabase(block)
return try serializedDatabase.performSync(block)
}
/// Synchronously executes a block in a protected dispatch queue, wrapped
@@ -86,7 +86,7 @@ public final class DatabaseQueue {
/// .Commit or .Rollback.
/// - throws: The error thrown by the block.
public func inTransaction(kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) throws {
try serializedDatabase.inDatabase { db in
try serializedDatabase.performSync { db in
try db.inTransaction(kind) {
try block(db: db)
}
@@ -100,7 +100,7 @@ public final class DatabaseQueue {
///
/// This method blocks the current thread until all database accesses are completed.
public func releaseMemory() {
serializedDatabase.inDatabase { db in
serializedDatabase.performSync { db in
db.releaseMemory()
}
}
@@ -147,14 +147,14 @@ extension DatabaseQueue : DatabaseReader {
///
/// This method is part of the DatabaseReader protocol adoption.
public func read<T>(block: (db: Database) throws -> T) rethrows -> T {
return try serializedDatabase.inDatabase(block)
return try serializedDatabase.performSync(block)
}
/// Alias for inDatabase
///
/// This method is part of the DatabaseReader protocol adoption.
public func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T {
return try serializedDatabase.inDatabase(block)
return try serializedDatabase.performSync(block)
}
@@ -174,12 +174,16 @@ extension DatabaseQueue : DatabaseReader {
/// Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func addFunction(function: DatabaseFunction) {
serializedDatabase.addFunction(function)
serializedDatabase.performSync { db in
db.addFunction(function)
}
}
/// Remove an SQL function.
public func removeFunction(function: DatabaseFunction) {
serializedDatabase.removeFunction(function)
serializedDatabase.performSync { db in
db.removeFunction(function)
}
}
@@ -195,12 +199,16 @@ extension DatabaseQueue : DatabaseReader {
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func addCollation(collation: DatabaseCollation) {
serializedDatabase.addCollation(collation)
serializedDatabase.performSync { db in
db.addCollation(collation)
}
}
/// Remove a collation.
public func removeCollation(collation: DatabaseCollation) {
serializedDatabase.removeCollation(collation)
serializedDatabase.performSync { db in
db.removeCollation(collation)
}
}
}
@@ -216,7 +224,7 @@ extension DatabaseQueue : DatabaseWriter {
///
/// This method is part of the DatabaseWriter protocol adoption.
public func write<T>(block: (db: Database) throws -> T) rethrows -> T {
return try serializedDatabase.inDatabase(block)
return try serializedDatabase.performSync(block)
}
/// Executes *block*.
@@ -224,6 +232,6 @@ extension DatabaseQueue : DatabaseWriter {
/// This method is part of the DatabaseWriter protocol adoption, and must
/// be called from the protected database dispatch queue.
public func readFromWrite(block: (db: Database) -> Void) {
serializedDatabase.readFromWrite(block)
serializedDatabase.perform(block)
}
}
+13 -43
View File
@@ -43,14 +43,11 @@ final class SerializedDatabase {
db.dispatchQueueID = dispatchQueueID
}
/// Synchronously executes a block a serialized dispatch queue, and returns
/// Synchronously executes a block the serialized dispatch queue, and returns
/// its result.
///
/// This method is *not* reentrant.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
func inDatabase<T>(block: (db: Database) throws -> T) rethrows -> T {
func performSync<T>(block: (db: Database) throws -> T) rethrows -> T {
// This method is NOT reentrant.
//
// Avoiding dispatch_sync and calling block() right away if the specific
@@ -81,50 +78,23 @@ final class SerializedDatabase {
}
}
func asyncInDatabase(block: (db: Database) -> Void) {
/// Asynchronously executes a block in the serialized dispatch queue.
func performAsync(block: (db: Database) -> Void) {
dispatch_async(queue) {
block(db: self.db)
}
}
/// Executes the block in the current queue.
///
/// - precondition: the current dispatch queue is valid.
func perform<T>(block: (db: Database) throws -> T) rethrows -> T {
db.preconditionValidQueue()
return try block(db: db)
}
/// Fatal error if current dispatch queue is not valid.
func preconditionValidQueue() {
db.preconditionValidQueue()
}
}
extension SerializedDatabase : DatabaseReader {
func read<T>(block: (db: Database) throws -> T) rethrows -> T {
return try inDatabase { try $0.read(block) }
}
func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T {
return try inDatabase { try $0.nonIsolatedRead(block) }
}
func addFunction(function: DatabaseFunction) {
inDatabase { $0.addFunction(function) }
}
func removeFunction(function: DatabaseFunction) {
inDatabase { $0.removeFunction(function) }
}
func addCollation(collation: DatabaseCollation) {
inDatabase { $0.addCollation(collation) }
}
func removeCollation(collation: DatabaseCollation) {
inDatabase { $0.removeCollation(collation) }
}
}
extension SerializedDatabase : DatabaseWriter {
func write<T>(block: (db: Database) throws -> T) rethrows -> T {
return try inDatabase { try $0.write(block) }
}
func readFromWrite(block: (db: Database) -> Void) {
db.preconditionValidQueue()
block(db: db)
}
}
+28 -10
View File
@@ -237,7 +237,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
private init(db: DatabaseWriter, source: DatabaseSource<Record>, queue: dispatch_queue_t, isSameRecordBuilder: (Database) -> (Record, Record) -> Bool) {
self.source = source
self.db = db
self.writer = db
self.isSameRecord = { _ in return false }
self.isSameRecordBuilder = isSameRecordBuilder
self.queue = queue
@@ -251,17 +251,17 @@ public final class FetchedRecordsController<Record: RowConvertible> {
// If some changes are currently processed, make sure they are discarded.
observer?.invalidate()
// Fetch items
db.write { db in
// Fetch items on the writing dispatch queue, so that the transaction
// observer is added on the same serialized queue as transaction
// callbacks.
writer.write { db in
let statement = try! self.source.selectStatement(db)
let items = Item<Record>.fetchAll(statement)
self.fetchedItems = items
self.isSameRecord = self.isSameRecordBuilder(db)
if self.delegate != nil {
// Setup a new transaction observer. Use db.write, so that
// the transaction observer is added on the same serialized
// queue as transaction callbacks.
// Setup a new transaction observer.
let observer = FetchedRecordsObserver(
controller: self,
initialItems: items,
@@ -292,7 +292,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
// Setup a new transaction observer. Use
// database.write, so that the transaction observer is added on the
// same serialized queue as transaction callbacks.
db.write { db in
writer.write { db in
let statement = try! self.source.selectStatement(db)
let observer = FetchedRecordsObserver(
controller: self,
@@ -313,13 +313,31 @@ public final class FetchedRecordsController<Record: RowConvertible> {
///
/// The controller registers as a transaction observer in order to respond
/// to changes.
public let db: DatabaseWriter
public let writer: DatabaseWriter
/// The dispatch queue on which the controller must be used.
///
/// Unless specified otherwise at initialization time, it is the main queue.
public let queue: dispatch_queue_t
/// The fetch request. Nil if controller uses a raw SQL query (see
/// sqlAndArguments property).
public var request: FetchRequest<Record>? {
guard case .FetchRequest(let request) = source else {
return nil
}
return request
}
/// The SQL query, and eventual arguments. Nil if controller uses a
/// fetch request (see request property).
public var sqlAndArguments: (sql: String, arguments: StatementArguments?)? {
guard case .SQL(let sql, let arguments) = source else {
return nil
}
return (sql: sql, arguments: arguments)
}
/// Updates the fetch request, and notifies the delegate of changes in the
/// fetched records.
public func setRequest<T>(request: FetchRequest<T>) {
@@ -407,7 +425,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
private var source: DatabaseSource<Record> {
didSet {
guard let observer = observer else { return }
db.write { db in
writer.write { db in
observer.checkForChangesInDatabase(db)
}
}
@@ -566,7 +584,7 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
// of the fetch. We just need to block the writer queue until we can
// perform a fetch in isolation. This is the role of the readFromWrite
// method:
controller.db.readFromWrite { db in
controller.writer.readFromWrite { db in
// Invalidated?
guard let controller = self.controller else { return }