mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
WIP : Welcome FetchedRecordsController
This commit is contained in:
1 parent
54d0442fe0
commit
0139618f37
5 files changed
+200
-41
No files matched your search
@@ -1,7 +1,9 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
class MasterViewController: UITableViewController {
|
||||
class MasterViewController: UITableViewController, FetchedRecordsControllerDelegate {
|
||||
var detailViewController: DetailViewController? = nil
|
||||
var fetchedRecordsController: FetchedRecordsController<Person>!
|
||||
var persons = [Person]()
|
||||
|
||||
override func viewDidLoad() {
|
||||
@@ -11,30 +13,26 @@ class MasterViewController: UITableViewController {
|
||||
let controllers = split.viewControllers
|
||||
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
|
||||
}
|
||||
|
||||
fetchedRecordsController = FetchedRecordsController(sql: "SELECT * FROM persons ORDER BY LOWER(firstName), LOWER(lastName)", databaseQueue: dbQueue)
|
||||
fetchedRecordsController.delegate = self
|
||||
fetchedRecordsController.performFetch()
|
||||
tableView.reloadData()
|
||||
}
|
||||
|
||||
override func viewWillAppear(animated: Bool) {
|
||||
// Reload persons, and the tableView
|
||||
reloadPersons()
|
||||
tableView.reloadData()
|
||||
|
||||
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
|
||||
super.viewWillAppear(animated)
|
||||
}
|
||||
|
||||
func reloadPersons() {
|
||||
persons = dbQueue.inDatabase { db in
|
||||
Person.fetchAll(db, "SELECT * FROM persons ORDER BY LOWER(firstName), LOWER(lastName)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Segues
|
||||
|
||||
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
|
||||
if segue.identifier == "showPerson" {
|
||||
let person = fetchedRecordsController.recordAtIndexPath(self.tableView.indexPathForSelectedRow!)
|
||||
let detailViewController = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
|
||||
detailViewController.person = persons[self.tableView.indexPathForSelectedRow!.row]
|
||||
detailViewController.person = person
|
||||
detailViewController.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
|
||||
detailViewController.navigationItem.leftItemsSupplementBackButton = true
|
||||
}
|
||||
@@ -58,39 +56,47 @@ class MasterViewController: UITableViewController {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
|
||||
// Reload persons, and insert a cell.
|
||||
reloadPersons()
|
||||
let index = persons.indexOf { $0.id == person.id }!
|
||||
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Automatic)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Table View
|
||||
|
||||
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return persons.count
|
||||
if let persons = fetchedRecordsController.fetchedRecords {
|
||||
return persons.count
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
|
||||
|
||||
let person = persons[indexPath.row]
|
||||
let person = fetchedRecordsController.recordAtIndexPath(indexPath)!
|
||||
cell.textLabel!.text = person.fullName
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
|
||||
// Delete the person
|
||||
let person = persons[indexPath.row]
|
||||
let person = fetchedRecordsController.recordAtIndexPath(indexPath)!
|
||||
try! dbQueue.inTransaction { db in
|
||||
try person.delete(db)
|
||||
return .Commit
|
||||
}
|
||||
persons.removeAtIndex(indexPath.row)
|
||||
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: - FetchedRecordsControllerDelegate
|
||||
|
||||
func controllerWillChangeContent<Person>(controller: FetchedRecordsController<Person>) {
|
||||
|
||||
}
|
||||
|
||||
func controller<Person>(controller: FetchedRecordsController<Person>, didChangeRecord record: Person, atIndexPath indexPath: NSIndexPath?, forChangeType type: FetchedRecordsChangeType, newIndexPath: NSIndexPath?) {
|
||||
|
||||
}
|
||||
|
||||
func controllerDidChangeContent<Person>(controller: FetchedRecordsController<Person>) {
|
||||
tableView.reloadData()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
31AEFE3F1C185E63003DB703 /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31AEFE3E1C185E63003DB703 /* FetchedRecordsController.swift */; };
|
||||
31AEFE421C185E63003DB703 /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31AEFE3E1C185E63003DB703 /* FetchedRecordsController.swift */; };
|
||||
5606AF911C0ED37000D20487 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; };
|
||||
5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
|
||||
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
|
||||
@@ -299,6 +301,7 @@
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
31AEFE3E1C185E63003DB703 /* FetchedRecordsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsController.swift; sourceTree = "<group>"; };
|
||||
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
|
||||
560C97C61BFD0B8400BF8471 /* FunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FunctionTests.swift; sourceTree = "<group>"; };
|
||||
560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
@@ -714,6 +717,7 @@
|
||||
children = (
|
||||
56A238A01B9C753B0082EB20 /* DatabaseStorable.swift */,
|
||||
56A238A11B9C753B0082EB20 /* Record.swift */,
|
||||
31AEFE3E1C185E63003DB703 /* FetchedRecordsController.swift */,
|
||||
);
|
||||
path = Record;
|
||||
sourceTree = "<group>";
|
||||
@@ -1231,6 +1235,7 @@
|
||||
56A2389C1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */,
|
||||
56A238801B9C75030082EB20 /* DatabaseChanges.swift in Sources */,
|
||||
565D5D691BBC604000DC9BD4 /* Row+Foundation.swift in Sources */,
|
||||
31AEFE421C185E63003DB703 /* FetchedRecordsController.swift in Sources */,
|
||||
56A238AE1B9C90090082EB20 /* NSNull.swift in Sources */,
|
||||
56A2389A1B9C752B0082EB20 /* DatabaseTableMapping.swift in Sources */,
|
||||
56A238881B9C75030082EB20 /* Row.swift in Sources */,
|
||||
@@ -1388,6 +1393,7 @@
|
||||
56A238B31B9C919D0082EB20 /* NSNumber.swift in Sources */,
|
||||
56A238B01B9C90BB0082EB20 /* NSString.swift in Sources */,
|
||||
565D5D681BBC604000DC9BD4 /* Row+Foundation.swift in Sources */,
|
||||
31AEFE3F1C185E63003DB703 /* FetchedRecordsController.swift in Sources */,
|
||||
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
|
||||
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
|
||||
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
|
||||
|
||||
@@ -25,11 +25,6 @@ public struct Configuration {
|
||||
/// Default is `.Immediate`.
|
||||
public var defaultTransactionKind: TransactionKind
|
||||
|
||||
/// The optional transaction observer
|
||||
///
|
||||
/// Default is nil.
|
||||
public var transactionObserver: TransactionObserverType?
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Concurrency
|
||||
@@ -75,7 +70,6 @@ public struct Configuration {
|
||||
self.readonly = false
|
||||
|
||||
self.defaultTransactionKind = .Immediate
|
||||
self.transactionObserver = nil
|
||||
|
||||
self.busyMode = .ImmediateError
|
||||
self.threadingMode = .Default
|
||||
|
||||
+38
-11
@@ -207,6 +207,15 @@ public final class Database {
|
||||
case Regular
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// The transaction observers
|
||||
private var transactionObservers = [TransactionObserverType]()
|
||||
|
||||
public func addTransactionObserver(transactionObserver: TransactionObserverType) {
|
||||
transactionObservers.append(transactionObserver)
|
||||
}
|
||||
|
||||
/// Updated in SQLite callbacks (see setupTransactionHooks())
|
||||
/// Consumed in updateStatementDidFail() and updateStatementDidExecute().
|
||||
private var statementCompletion: StatementCompletion = .Regular
|
||||
@@ -219,7 +228,7 @@ public final class Database {
|
||||
case .TransactionErrorRollback(let error):
|
||||
// The transaction has been rollbacked from
|
||||
// TransactionObserverType.transactionWillCommit().
|
||||
configuration.transactionObserver!.databaseDidRollback(self)
|
||||
propagateDatabaseDidRollback()
|
||||
throw error
|
||||
default:
|
||||
break
|
||||
@@ -232,23 +241,42 @@ public final class Database {
|
||||
|
||||
switch statementCompletion {
|
||||
case .TransactionCommit:
|
||||
configuration.transactionObserver!.databaseDidCommit(self)
|
||||
propagateDatabaseDidCommit()
|
||||
case .TransactionRollback:
|
||||
configuration.transactionObserver!.databaseDidRollback(self)
|
||||
propagateDatabaseDidRollback()
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func setupTransactionHooks() {
|
||||
// No need to setup any hook when there is no transactionObserver:
|
||||
guard configuration.transactionObserver != nil else {
|
||||
return
|
||||
private func propagateDatabaseWillCommit() throws {
|
||||
for observer: TransactionObserverType in transactionObservers {
|
||||
try observer.databaseWillCommit()
|
||||
}
|
||||
}
|
||||
|
||||
private func propagateDatabaseDidChangeWithEvent(event: DatabaseEvent) {
|
||||
for observer: TransactionObserverType in transactionObservers {
|
||||
observer.databaseDidChangeWithEvent(event)
|
||||
}
|
||||
}
|
||||
|
||||
private func propagateDatabaseDidCommit() {
|
||||
for observer: TransactionObserverType in transactionObservers {
|
||||
observer.databaseDidCommit(self)
|
||||
}
|
||||
}
|
||||
|
||||
private func propagateDatabaseDidRollback() {
|
||||
for observer: TransactionObserverType in transactionObservers {
|
||||
observer.databaseDidRollback(self)
|
||||
}
|
||||
}
|
||||
|
||||
private func setupTransactionHooks() {
|
||||
|
||||
let dbPointer = unsafeBitCast(self, UnsafeMutablePointer<Void>.self)
|
||||
|
||||
|
||||
sqlite3_update_hook(sqliteConnection, { (dbPointer, updateKind, databaseName, tableName, rowID) in
|
||||
let db = unsafeBitCast(dbPointer, Database.self)
|
||||
|
||||
@@ -258,15 +286,14 @@ public final class Database {
|
||||
databaseName: String.fromCString(databaseName)!,
|
||||
tableName: String.fromCString(tableName)!,
|
||||
rowID: rowID)
|
||||
db.configuration.transactionObserver!.databaseDidChangeWithEvent(event)
|
||||
db.propagateDatabaseDidChangeWithEvent(event)
|
||||
}, dbPointer)
|
||||
|
||||
|
||||
sqlite3_commit_hook(sqliteConnection, { dbPointer in
|
||||
let db = unsafeBitCast(dbPointer, Database.self)
|
||||
|
||||
do {
|
||||
try db.configuration.transactionObserver!.databaseWillCommit()
|
||||
try db.propagateDatabaseWillCommit()
|
||||
// Next step: updateStatementDidExecute()
|
||||
db.statementCompletion = .TransactionCommit
|
||||
return 0
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//
|
||||
// FetchedRecordsController.swift
|
||||
// GRDB
|
||||
//
|
||||
// Created by Pascal Edmond on 09/12/2015.
|
||||
// Copyright © 2015 Gwendal Roué. All rights reserved.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
|
||||
public class FetchedRecordsController<T: DatabaseTableMapping> {
|
||||
|
||||
// MARK: - Initialization
|
||||
public required init(sql: String, databaseQueue: DatabaseQueue) {
|
||||
self.sql = sql
|
||||
self.databaseQueue = databaseQueue
|
||||
}
|
||||
|
||||
public func performFetch() {
|
||||
|
||||
// Install for observation
|
||||
databaseQueue.inDatabase { db in
|
||||
db.addTransactionObserver(self)
|
||||
}
|
||||
|
||||
fetchedRecords = databaseQueue.inDatabase { db in
|
||||
T.fetchAll(db, self.sql)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The SQL query
|
||||
public let sql: String
|
||||
|
||||
/// The databaseQueue
|
||||
public let databaseQueue: DatabaseQueue
|
||||
|
||||
/// Delegate that is notified when the records set changes.
|
||||
weak public var delegate: FetchedRecordsControllerDelegate?
|
||||
|
||||
|
||||
// MARK: - Accessing records
|
||||
|
||||
/// Returns the results of the query.
|
||||
/// Returns nil if the performQuery: hasn't been called.
|
||||
public private(set) var fetchedRecords: [T]?
|
||||
|
||||
|
||||
/// Returns the fetched object at a given indexPath.
|
||||
public func recordAtIndexPath(indexPath: NSIndexPath) -> T? {
|
||||
if let record = fetchedRecords?[indexPath.row] {
|
||||
return record
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the indexPath of a given object.
|
||||
public func indexPathForRecord(record: T) -> NSIndexPath? {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
func fetchRecords() -> [T] {
|
||||
return databaseQueue.inDatabase { db in
|
||||
T.fetchAll(db, self.sql)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension FetchedRecordsController : TransactionObserverType {
|
||||
|
||||
public func databaseDidChangeWithEvent(event: DatabaseEvent) { }
|
||||
|
||||
public func databaseWillCommit() throws { }
|
||||
|
||||
public func databaseDidCommit(db: Database) {
|
||||
|
||||
let newRecords = T.fetchAll(db, self.sql)
|
||||
print("newRecords => \(newRecords)")
|
||||
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
|
||||
let oldRecords = self.fetchedRecords
|
||||
print("oldRecords => \(oldRecords)")
|
||||
// horrible diff computation
|
||||
|
||||
dispatch_async(dispatch_get_main_queue()) {
|
||||
self.delegate?.controllerWillChangeContent(self)
|
||||
|
||||
// after controllerWillChangeContent
|
||||
self.fetchedRecords = newRecords
|
||||
|
||||
// notify horrible diff computation
|
||||
|
||||
// done
|
||||
self.delegate?.controllerDidChangeContent(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func databaseDidRollback(db: Database) { }
|
||||
}
|
||||
|
||||
public protocol FetchedRecordsControllerDelegate : class {
|
||||
func controllerWillChangeContent<T: DatabaseTableMapping>(controller: FetchedRecordsController<T>)
|
||||
func controller<T: DatabaseTableMapping>(controller: FetchedRecordsController<T>, didChangeRecord record: T, atIndexPath indexPath: NSIndexPath?, forChangeType type: FetchedRecordsChangeType, newIndexPath: NSIndexPath?)
|
||||
func controllerDidChangeContent<T: DatabaseTableMapping>(controller: FetchedRecordsController<T>)
|
||||
}
|
||||
|
||||
public extension FetchedRecordsControllerDelegate {
|
||||
func controllerWillChangeContent<T: DatabaseTableMapping>(controller: FetchedRecordsController<T>) {}
|
||||
func controller<T: DatabaseTableMapping>(controller: FetchedRecordsController<T>, didChangeRecord record: T, atIndexPath indexPath: NSIndexPath?, forChangeType type: FetchedRecordsChangeType, newIndexPath: NSIndexPath?) {}
|
||||
func controllerDidChangeContent<T: DatabaseTableMapping>(controller: FetchedRecordsController<T>) {}
|
||||
}
|
||||
|
||||
public enum FetchedRecordsChangeType : UInt {
|
||||
case Insert
|
||||
case Delete
|
||||
case Move
|
||||
case Update
|
||||
}
|
||||
Reference in new issue
Block a user