From 138cc752a6d50fa4f9c3143d823fd55f7cbbb38f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 29 Jun 2020 18:29:29 +0200 Subject: [PATCH] Remove FetchedRecordsController --- Documentation/FetchedRecordsController.md | 344 +----- GRDB.xcodeproj/project.pbxproj | 18 - GRDB/Record/FetchedRecordsController.swift | 1080 ----------------- GRDBCustom.xcodeproj/project.pbxproj | 12 - README.md | 13 +- .../GRDBTests.xcodeproj/project.pbxproj | 6 - .../GRDBTests.xcodeproj/project.pbxproj | 6 - .../FetchedRecordsControllerTests.swift | 1024 ---------------- .../RecordPrimaryKeyHiddenRowIDTests.swift | 28 - 9 files changed, 10 insertions(+), 2521 deletions(-) delete mode 100644 GRDB/Record/FetchedRecordsController.swift delete mode 100644 Tests/GRDBTests/FetchedRecordsControllerTests.swift diff --git a/Documentation/FetchedRecordsController.md b/Documentation/FetchedRecordsController.md index 6051dc1ff..ee3757ada 100644 --- a/Documentation/FetchedRecordsController.md +++ b/Documentation/FetchedRecordsController.md @@ -1,345 +1,5 @@ # FetchedRecordsController -**FetchedRecordsController is a sunsetted GRDB API.** +FetchedRecordsController has been removed in GRDB 5. -It is not deprecated. But FetchedRecordsController has known limitations which are not planned to be lifted. - -You are advised to use [ValueObservation] instead of FetchedRecordsController. - ---- - -**FetchedRecordsController tracks changes in the results of a request, feeds table views and collection views, and animates cells when the results of the request change.** - -It looks and behaves very much like [Core Data's NSFetchedResultsController](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/). - -Given a fetch request, and a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](../README.md#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record. - -- [Creating the Fetched Records Controller](#creating-the-fetched-records-controller) -- [Responding to Changes](#responding-to-changes) -- [The Changes Notifications](#the-changes-notifications) -- [Modifying the Fetch Request](#modifying-the-fetch-request) -- [Table and Collection Views](#table-and-collection-views) - - [Implementing the Table View Datasource Methods](#implementing-the-table-view-datasource-methods) - - [Implementing Table View Updates](#implementing-table-view-updates) -- [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency) - - -## Creating the Fetched Records Controller - -When you initialize a fetched records controller, you provide the following mandatory information: - -- A [database connection](../README.md#database-connections) -- The type of the fetched records. It must be a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](../README.md#record-class) class -- A fetch request - -```swift -class Player : Record { ... } -let dbQueue = DatabaseQueue(...) // or DatabasePool - -// Using a Request from the Query Interface: -let controller = FetchedRecordsController( - dbQueue, - request: Player.order(Column("name"))) - -// Using SQL, and eventual arguments: -let controller = FetchedRecordsController( - dbQueue, - sql: "SELECT * FROM player ORDER BY name WHERE countryCode = ?", - arguments: ["FR"]) -``` - -The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request. - -```swift -let controller = FetchedRecordsController( - dbQueue, - sql: """ - SELECT author.name, COUNT(book.id) AS bookCount - FROM author - LEFT JOIN book ON book.authorId = author.id - GROUP BY author.id - ORDER BY author.name - """) -``` - - -After creating an instance, you invoke `performFetch()` to actually execute -the fetch. - -```swift -try controller.performFetch() -``` - - -## Responding to Changes - -In general, FetchedRecordsController is designed to respond to changes at *the database layer*, by [notifying](#the-changes-notifications) when *database rows* change location or values. - -Changes are not reflected until they are applied in the database by a successful [transaction](../README.md#transactions-and-savepoints): - -```swift -// One transaction -try dbQueue.write { db in // or dbPool.write - try player1.insert(db) - try player2.insert(db) -} - -// One transaction -try dbQueue.inTransaction { db in // or dbPool.writeInTransaction - try player1.insert(db) - try player2.insert(db) - return .commit -} - -// Two transactions -try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction - try player1.insert(db) - try player2.insert(db) -} -``` - -When you apply several changes to the database, you should group them in a single explicit transaction. The controller will then notify of all changes together. - - -## The Changes Notifications - -An instance of FetchedRecordsController notifies that the controller’s fetched records have been changed by the mean of *callbacks*: - -```swift -let controller = try FetchedRecordsController(...) - -controller.trackChanges( - // controller's records are about to change: - willChange: { controller in ... }, - - // notification of individual record changes: - onChange: { (controller, record, change) in ... }, - - // controller's records have changed: - didChange: { controller in ... }) - -try controller.performFetch() -``` - -See [Implementing Table View Updates](#implementing-table-view-updates) for more detail on table view updates. - -**All callbacks are optional.** When you only need to grab the latest results, you can omit the `didChange` argument name: - -```swift -controller.trackChanges { controller in - let newPlayers = controller.fetchedRecords // [Player] -} -``` - -> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information. - -Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks: - -```swift -// BAD: memory leak -controller.trackChanges { _ in - let newPlayers = controller.fetchedRecords -} - -// GOOD -controller.trackChanges { controller in - let newPlayers = controller.fetchedRecords -} -``` - -**Callbacks are invoked asynchronously.** See [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency) for more information. - -**Values fetched from inside callbacks may be inconsistent with the controller's records.** This is because after database has changed, and before the controller had the opportunity to invoke callbacks in the main thread, other database changes can happen. - -To avoid inconsistencies, provide a `fetchAlongside` argument to the `trackChanges` method, as below: - -```swift -controller.trackChanges( - fetchAlongside: { db in - // Fetch any extra value, for example the number of fetched records: - return try Player.fetchCount(db) - }, - didChange: { (controller, count) in - // The extra value is the second argument. - let recordsCount = controller.fetchedRecords.count - assert(count == recordsCount) // guaranteed - }) -``` - -Whenever the fetched records controller can not look for changes after a transaction has potentially modified the tracked request, an error handler is called. The request observation is not stopped, though: future transactions may successfully be handled, and the notified changes will then be based on the last successful fetch. - -```swift -controller.trackErrors { (controller, error) in - print("Missed a transaction because \(error)") -} -``` - - -## Modifying the Fetch Request - -You can change a fetched records controller's fetch request or SQL query. - -```swift -controller.setRequest(Player.order(Column("name"))) -controller.setRequest(sql: "SELECT ...", arguments: ...) -``` - -The [notification callbacks](#the-changes-notifications) are notified of eventual changes if the new request fetches a different set of records. - -> :point_up: **Note**: This behavior differs from Core Data's NSFetchedResultsController, which does not notify of record changes when the fetch request is replaced. - -**Change callbacks are invoked asynchronously.** This means that modifying the request from the main thread does *not* immediately triggers callbacks. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called: - -```swift -// Change request on the main thread: -controller.setRequest(Player.order(Column("name"))) -// Here callbacks have not been called yet. -// You can cancel them, and refresh records immediately: -try controller.performFetch() -``` - -## Table and Collection Views - -FetchedRecordsController let you feed table and collection views, and keep them up-to-date with the database content. - -For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the [TableRecord] protocol, they are automatically compared according to their primary key: - -```swift -class Player : TableRecord { ... } -let controller = FetchedRecordsController( - dbQueue, - request: Player.all()) -``` - -For other types, the fetched records controller needs you to be more explicit: - -```swift -let controller = FetchedRecordsController( - dbQueue, - request: ..., - isSameRecord: { (player1, player2) in player1.id == player2.id }) -``` - - -### Implementing the Table View Datasource Methods - -The table view data source asks the fetched records controller to provide relevant information: - -```swift -func numberOfSections(in tableView: UITableView) -> Int { - fetchedRecordsController.sections.count -} - -func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - fetchedRecordsController.sections[section].numberOfRecords -} - -func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = ... - let record = fetchedRecordsController.record(at: indexPath) - // Configure the cell - return cell -} -``` - -> :point_up: **Note**: In its current state, FetchedRecordsController does not support grouping table view rows into custom sections: it generates a unique section. - - -### Implementing Table View Updates - -When changes in the fetched records should reload the whole table view, you can simply tell so: - -```swift -controller.trackChanges { [unowned self] _ in - self.tableView.reloadData() -} -``` - -Yet, FetchedRecordsController can notify that the controller’s fetched records have been changed due to some add, remove, move, or update operations, and help applying animated changes to a UITableView. - - -#### Typical Table View Updates - -For animated table view updates, use the `willChange` and `didChange` callbacks to bracket events provided by the fetched records controller, as illustrated in the following example: - -```swift -// Assume self has a tableView property, and a cell configuration -// method named configure(_:at:). - -controller.trackChanges( - // controller's records are about to change: - willChange: { [unowned self] _ in - self.tableView.beginUpdates() - }, - - // notification of individual record changes: - onChange: { [unowned self] (controller, record, change) in - switch change { - case .insertion(let indexPath): - self.tableView.insertRows(at: [indexPath], with: .fade) - - case .deletion(let indexPath): - self.tableView.deleteRows(at: [indexPath], with: .fade) - - case .update(let indexPath, _): - if let cell = self.tableView.cellForRow(at: indexPath) { - self.configure(cell, at: indexPath) - } - - case .move(let indexPath, let newIndexPath, _): - self.tableView.deleteRows(at: [indexPath], with: .fade) - self.tableView.insertRows(at: [newIndexPath], with: .fade) - - // // Alternate technique which actually moves cells around: - // let cell = self.tableView.cellForRow(at: indexPath) - // self.tableView.moveRow(at: indexPath, to: newIndexPath) - // if let cell = cell { - // self.configure(cell, at: newIndexPath) - // } - } - }, - - // controller's records have changed: - didChange: { [unowned self] _ in - self.tableView.endUpdates() - }) -``` - -> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information. -> -> :point_up: **Note**: our sample code above uses `unowned` references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references. - - -## FetchedRecordsController Concurrency - -**A fetched records controller *can not* be used from any thread.** - -When the database itself can be read and modified from [any thread](../README.md#database-connections), fetched records controllers **must** be used from the main thread. Record changes are also [notified](#the-changes-notifications) on the main thread. - -**Change callbacks are invoked asynchronously.** This means that changes made from the main thread are *not* immediately notified. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called: - -```swift -// Change database on the main thread: -try dbQueue.write { db in - try Player(...).insert(db) -} -// Here callbacks have not been called yet. -// You can cancel them, and refresh records immediately: -try controller.performFetch() -``` - -> :point_up: **Note**: when the main thread does not fit your needs, give a serial dispatch queue to the controller initializer: the controller must then be used from this queue, and record changes are notified on this queue as well. -> -> ```swift -> let queue = DispatchQueue() -> queue.async { -> let controller = try FetchedRecordsController(..., queue: queue) -> controller.trackChanges { /* in queue */ } -> try controller.performFetch() -> } -> ``` - - -[ValueObservation]: ../README.md#valueobservation -[FetchableRecord]: ../README.md#fetchablerecord-protocol -[TableRecord]: ../README.md#tablerecord-protocol +The [Database Observation](../README.md#database-changes-observation) chapter describes the other ways to observe the databasee. diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b54da4114..d7484d380 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -7,7 +7,6 @@ objects = { /* Begin PBXBuildFile section */ - 31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A1228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; @@ -37,7 +36,6 @@ 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; 560714E3227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714E2227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift */; }; 560714E4227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714E2227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift */; }; - 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; @@ -89,7 +87,6 @@ 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; - 56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 561CFA7823735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; 561CFA7923735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; 561CFA7A23735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; }; @@ -363,7 +360,6 @@ 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; - 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; 565490E21D5AE252005622CB /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; 565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; @@ -670,7 +666,6 @@ 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B021CD1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; - 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; 56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; @@ -993,7 +988,6 @@ AAA4DCE5230F1E0600C74B15 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */; }; AAA4DCE6230F1E0600C74B15 /* SQLForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* SQLForeignKeyRequest.swift */; }; AAA4DCE7230F1E0600C74B15 /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; - AAA4DCE8230F1E0600C74B15 /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; AAA4DCEA230F1E0600C74B15 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; }; AAA4DCEB230F1E0600C74B15 /* SQLOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */; }; AAA4DCEC230F1E0600C74B15 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; }; @@ -1059,7 +1053,6 @@ AAA4DD3D230F262000C74B15 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */; }; AAA4DD3E230F262000C74B15 /* FTS3RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AC481DA2D48A0056AF8C /* FTS3RecordTests.swift */; }; AAA4DD3F230F262000C74B15 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C612291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */; }; - AAA4DD40230F262000C74B15 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; AAA4DD41230F262000C74B15 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; AAA4DD42230F262000C74B15 /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; }; AAA4DD43230F262000C74B15 /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; }; @@ -1236,7 +1229,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsController.swift; sourceTree = ""; }; 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = ""; }; @@ -1533,7 +1525,6 @@ 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; - 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; @@ -2253,7 +2244,6 @@ isa = PBXGroup; children = ( 5674A7251F30A8EF0095F066 /* FetchableRecord */, - 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73DE203D50B9000C443C /* JoinSupportTests.swift */, 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, @@ -2320,7 +2310,6 @@ 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */, 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */, 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */, - 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, @@ -2956,7 +2945,6 @@ 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 569BBA50229170FA00478429 /* Inflections+English.swift in Sources */, 563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */, - 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */, 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 565490C81D5AE252005622CB /* CGFloat.swift in Sources */, 56F5ABDC1D814330001F60CB /* URL.swift in Sources */, @@ -3123,7 +3111,6 @@ 56781B0C243F86E600650A83 /* Refinable.swift in Sources */, 5653EB0720944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */, 5657AABC1D107001006283EF /* NSData.swift in Sources */, - 31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */, 56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */, 56CEB55D1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 566B91261FA4CF810012D5B0 /* Database+Schema.swift in Sources */, @@ -3201,7 +3188,6 @@ 5698AC4D1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, 56419C6E24A519A3004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */, 56057C632291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, - 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */, 5656A80022946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, 5615B261222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */, @@ -3575,7 +3561,6 @@ 56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */, 56419C7824A51A38004967E1 /* Recorder.swift in Sources */, 56D496911D81316E008276D7 /* RowFromStatementTests.swift in Sources */, - 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, 56176C5B1EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */, 56419C5424A51998004967E1 /* Recording.swift in Sources */, 56D496B91D81346F008276D7 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, @@ -3705,7 +3690,6 @@ 56781B0E243F86E600650A83 /* Refinable.swift in Sources */, AAA4DCE6230F1E0600C74B15 /* SQLForeignKeyRequest.swift in Sources */, AAA4DCE7230F1E0600C74B15 /* NSData.swift in Sources */, - AAA4DCE8230F1E0600C74B15 /* FetchedRecordsController.swift in Sources */, AAA4DCEA230F1E0600C74B15 /* DatabaseValue.swift in Sources */, AAA4DCEB230F1E0600C74B15 /* SQLOrdering.swift in Sources */, AAA4DCEC230F1E0600C74B15 /* Database+Schema.swift in Sources */, @@ -3783,7 +3767,6 @@ AAA4DD3E230F262000C74B15 /* FTS3RecordTests.swift in Sources */, 56419C7324A519A4004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */, AAA4DD3F230F262000C74B15 /* AssociationHasManyThroughRowScopeTests.swift in Sources */, - AAA4DD40230F262000C74B15 /* FetchedRecordsControllerTests.swift in Sources */, AAA4DD41230F262000C74B15 /* RecordInitializersTests.swift in Sources */, AAA4DD42230F262000C74B15 /* ValueObservationQueryInterfaceRequestTests.swift in Sources */, AAA4DD43230F262000C74B15 /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */, @@ -4041,7 +4024,6 @@ 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */, - 56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift deleted file mode 100644 index f4f20cd47..000000000 --- a/GRDB/Record/FetchedRecordsController.swift +++ /dev/null @@ -1,1080 +0,0 @@ -import Foundation - -#if os(iOS) -import UIKit -#endif - -/// You use FetchedRecordsController to track changes in the results of an -/// SQLite request. -/// -/// See https://github.com/groue/GRDB.swift#fetchedrecordscontroller for -/// more information. -public final class FetchedRecordsController { - - // MARK: - Initialization - - /// Creates a fetched records controller initialized from a SQL query and - /// its eventual arguments. - /// - /// let controller = FetchedRecordsController( - /// dbQueue, - /// sql: "SELECT * FROM wine WHERE color = ? ORDER BY name", - /// arguments: [Color.red], - /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) - /// - /// - parameters: - /// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool) - /// - sql: An SQL query. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter - /// - queue: A serial dispatch queue (defaults to the main queue) - /// - /// The fetched records controller tracking callbacks will be - /// notified of changes in this queue. The controller itself must be - /// used from this queue. - /// - /// - isSameRecord: Optional function that compares two records. - /// - /// This function should return true if the two records have the - /// same identity. For example, they have the same id. - public convenience init( - _ databaseWriter: DatabaseWriter, - sql: String, - arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil, - queue: DispatchQueue = .main, - isSameRecord: ((Record, Record) -> Bool)? = nil) throws - { - try self.init( - databaseWriter, - request: SQLRequest(sql: sql, arguments: arguments, adapter: adapter), - queue: queue, - isSameRecord: isSameRecord) - } - - /// Creates a fetched records controller initialized from a fetch request - /// from the [Query Interface](https://github.com/groue/GRDB.swift#the-query-interface). - /// - /// let request = Wine.order(Column("name")) - /// let controller = FetchedRecordsController( - /// dbQueue, - /// request: request, - /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) - /// - /// - parameters: - /// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool) - /// - request: A fetch request. - /// - queue: A serial dispatch queue (defaults to the main queue) - /// - /// The fetched records controller tracking callbacks will be - /// notified of changes in this queue. The controller itself must be - /// used from this queue. - /// - /// - isSameRecord: Optional function that compares two records. - /// - /// This function should return true if the two records have the - /// same identity. For example, they have the same id. - public convenience init( - _ databaseWriter: DatabaseWriter, - request: Request, - queue: DispatchQueue = .main, - isSameRecord: ((Record, Record) -> Bool)? = nil) throws - where Request: FetchRequest, Request.RowDecoder == Record - { - let itemsAreIdenticalFactory: ItemComparatorFactory - if let isSameRecord = isSameRecord { - itemsAreIdenticalFactory = { _ in { isSameRecord($0.record, $1.record) } } - } else { - itemsAreIdenticalFactory = { _ in { _, _ in false } } - } - - try self.init( - databaseWriter, - request: request, - queue: queue, - itemsAreIdenticalFactory: itemsAreIdenticalFactory) - } - - private init( - _ databaseWriter: DatabaseWriter, - request: Request, - queue: DispatchQueue, - itemsAreIdenticalFactory: @escaping ItemComparatorFactory) throws - where Request: FetchRequest, Request.RowDecoder == Record - { - self.itemsAreIdenticalFactory = itemsAreIdenticalFactory - self.request = AnyFetchRequest(request).asRequest(of: Item.self) - (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in - let region = try request.databaseRegion(db) - let itemsAreIdentical = try itemsAreIdenticalFactory(db) - return (region, itemsAreIdentical) - } - self.databaseWriter = databaseWriter - self.queue = queue - } - - /// Executes the controller's fetch request. - /// - /// After executing this method, you can access the the fetched objects with - /// the `fetchedRecords` property. - /// - /// This method must be used from the controller's dispatch queue (the - /// main queue unless stated otherwise in the controller's initializer). - public func performFetch() throws { - // If some changes are currently processed, make sure they are - // discarded. But preserve eventual changes processing for future - // changes. - let fetchAndNotifyChanges = observer?.fetchAndNotifyChanges - observer?.invalidate() - observer = nil - - // Fetch items on the writing dispatch queue, so that the transaction - // observer is added on the same serialized queue as transaction - // callbacks. - try databaseWriter.write { db in - let initialItems = try request.fetchAll(db) - fetchedItems = initialItems - if let fetchAndNotifyChanges = fetchAndNotifyChanges { - let observer = FetchedRecordsObserver(region: self.region, fetchAndNotifyChanges: fetchAndNotifyChanges) - self.observer = observer - observer.items = initialItems - db.add(transactionObserver: observer) - } - } - } - - - // MARK: - Configuration - - /// The database writer used to fetch records. - /// - /// The controller registers as a transaction observer in order to respond - /// to changes. - public let databaseWriter: 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: DispatchQueue - - /// Updates the fetch request, and eventually notifies the tracking - /// callbacks if performFetch() has been called. - /// - /// 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: FetchRequest, Request.RowDecoder == Record - { - self.request = AnyFetchRequest(request).asRequest(of: Item.self) - (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in - let region = try request.databaseRegion(db) - let itemsAreIdentical = try itemsAreIdenticalFactory(db) - return (region, itemsAreIdentical) - } - - // No observer: don't look for changes - guard let observer = observer else { return } - - // If some changes are currently processed, make sure they are - // discarded. But preserve eventual changes processing. - let fetchAndNotifyChanges = observer.fetchAndNotifyChanges - observer.invalidate() - self.observer = nil - - // Replace observer so that it tracks a new set of columns, - // and notify eventual changes - let initialItems = fetchedItems - databaseWriter.writeWithoutTransaction { db in - let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges) - self.observer = observer - observer.items = initialItems - db.add(transactionObserver: observer) - observer.fetchAndNotifyChanges(observer) - } - } - - /// Updates the fetch request, and eventually notifies the tracking - /// callbacks if performFetch() has been called. - /// - /// 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( - sql: String, - arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) - throws - { - try setRequest(SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) - } - - /// Registers changes notification callbacks. - /// - /// This method must be used from the controller's dispatch queue (the - /// main queue unless stated otherwise in the controller's initializer). - /// - /// - parameters: - /// - willChange: Invoked before records are updated. - /// - onChange: Invoked for each record that has been added, - /// removed, moved, or updated. - /// - didChange: Invoked after records have been updated. - public func trackChanges( - willChange: ((FetchedRecordsController) -> Void)? = nil, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)? = nil, - didChange: ((FetchedRecordsController) -> Void)? = nil) - { - // Without SE-0110, we could simply: - // - // trackChanges( - // fetchAlongside: { _ in }, - // willChange: willChange.map { callback in { (controller, _) in callback(controller) } }, - // onChange: onChange, - // didChange: didChange.map { callback in { (controller, _) in callback(controller) } }) - // - // But instead: - let wrappedWillChange: ((FetchedRecordsController, Void) -> Void)? - if let willChange = willChange { - wrappedWillChange = { (controller, _) in willChange(controller) } - } else { - wrappedWillChange = nil - } - - let wrappedDidChange: ((FetchedRecordsController, Void) -> Void)? - if let didChange = didChange { - wrappedDidChange = { (controller, _) in didChange(controller) } - } else { - wrappedDidChange = nil - } - - trackChanges( - fetchAlongside: { _ in }, - willChange: wrappedWillChange, - onChange: onChange, - didChange: wrappedDidChange) - } - - /// Registers changes notification callbacks. - /// - /// This method must be used from the controller's dispatch queue (the - /// main queue unless stated otherwise in the controller's initializer). - /// - /// - parameters: - /// - fetchAlongside: The value returned from this closure is given to - /// willChange and didChange callbacks, as their - /// `fetchedAlongside` argument. The closure is guaranteed to see the - /// database in the state it has just after eventual changes to the - /// fetched records have been performed. Use it in order to fetch - /// values that must be consistent with the fetched records. - /// - willChange: Invoked before records are updated. - /// - onChange: Invoked for each record that has been added, - /// removed, moved, or updated. - /// - didChange: Invoked after records have been updated. - public func trackChanges( - fetchAlongside: @escaping (Database) throws -> T, - willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)? = nil, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)? = nil, - didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)? = nil) - { - // If some changes are currently processed, make sure they are - // discarded because they would trigger previously set callbacks. - observer?.invalidate() - observer = nil - - guard (willChange != nil) || (onChange != nil) || (didChange != nil) else { - // Stop tracking - return - } - - var willProcessTransaction: () -> Void = { } - var didProcessTransaction: () -> Void = { } - #if os(iOS) - if let application = application { - var backgroundTaskID: UIBackgroundTaskIdentifier! = nil - willProcessTransaction = { - backgroundTaskID = application.beginBackgroundTask { - application.endBackgroundTask(backgroundTaskID) - } - } - didProcessTransaction = { - application.endBackgroundTask(backgroundTaskID) - } - } - #endif - - let initialItems = fetchedItems - databaseWriter.writeWithoutTransaction { db in - let fetchAndNotifyChanges = makeFetchAndNotifyChangesFunction( - controller: self, - fetchAlongside: fetchAlongside, - itemsAreIdentical: itemsAreIdentical, - willProcessTransaction: willProcessTransaction, - willChange: willChange, - onChange: onChange, - didChange: didChange, - didProcessTransaction: didProcessTransaction) - let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges) - self.observer = observer - if let initialItems = initialItems { - observer.items = initialItems - db.add(transactionObserver: observer) - observer.fetchAndNotifyChanges(observer) - } - } - } - - /// Registers an error callback. - /// - /// Whenever the controller could not look for changes after a transaction - /// has potentially modified the tracked request, this error handler is - /// called. - /// - /// The request observation is not stopped, though: future transactions may - /// successfully be handled, and the notified changes will then be based on - /// the last successful fetch. - /// - /// This method must be used from the controller's dispatch queue (the - /// main queue unless stated otherwise in the controller's initializer). - public func trackErrors(_ errorHandler: @escaping (FetchedRecordsController, Error) -> Void) { - self.errorHandler = errorHandler - } - - #if os(iOS) - /// Call this method when changes performed while the application is - /// in the background should be processed before the application enters the - /// suspended state. - /// - /// Whenever the tracked request is changed, the fetched records controller - /// sets up a background task using - /// `UIApplication.beginBackgroundTask(expirationHandler:)` which is ended - /// after the `didChange` callback has completed. - public func allowBackgroundChangesTracking(in application: UIApplication) { - self.application = application - } - #endif - - // MARK: - Accessing Records - - /// The fetched records. - /// - /// The value of this property is nil until performFetch() has been called. - /// - /// The records reflect the state of the database after the initial - /// call to performFetch, and after each database transaction that affects - /// the results of the fetch request. - /// - /// This property must be used from the controller's dispatch queue (the - /// main queue unless stated otherwise in the controller's initializer). - public var fetchedRecords: [Record] { - guard let fetchedItems = fetchedItems else { - fatalError("the performFetch() method must be called before accessing fetched records") - } - return fetchedItems.map(\.record) - } - - - // MARK: - Not public - - #if os(iOS) - /// Support for allowBackgroundChangeTracking(in:) - var application: UIApplication? - #endif - - /// The items - fileprivate var fetchedItems: [Item]? - - /// The record comparator - private var itemsAreIdentical: ItemComparator - - /// The record comparator factory (support for request change) - private let itemsAreIdenticalFactory: ItemComparatorFactory - - /// The request - fileprivate var request: AnyFetchRequest> - - /// The observed database region - private var region: DatabaseRegion - - /// The eventual current database observer - private var observer: FetchedRecordsObserver? - - /// The eventual error handler - fileprivate var errorHandler: ((FetchedRecordsController, Error) -> Void)? -} - -extension FetchedRecordsController where Record: TableRecord { - - // MARK: - Initialization - - /// Creates a fetched records controller initialized from a SQL query and - /// its eventual arguments. - /// - /// let controller = FetchedRecordsController( - /// dbQueue, - /// sql: "SELECT * FROM wine WHERE color = ? ORDER BY name", - /// arguments: [Color.red]) - /// - /// The records are compared by primary key (single-column primary key, - /// compound primary key, or implicit rowid). For a database table which - /// has an `id` primary key, this initializer is equivalent to: - /// - /// // Assuming the wine table has an `id` primary key: - /// let controller = FetchedRecordsController( - /// dbQueue, - /// sql: "SELECT * FROM wine WHERE color = ? ORDER BY name", - /// arguments: [Color.red], - /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) - /// - /// - parameters: - /// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool) - /// - sql: An SQL query. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter - /// - queue: A serial dispatch queue (defaults to the main queue) - /// - /// The fetched records controller tracking callbacks will be - /// notified of changes in this queue. The controller itself must be - /// used from this queue. - public convenience init( - _ databaseWriter: DatabaseWriter, - sql: String, - arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil, - queue: DispatchQueue = .main) throws - { - try self.init( - databaseWriter, - request: SQLRequest(sql: sql, arguments: arguments, adapter: adapter), - queue: queue) - } - - /// Creates a fetched records controller initialized from a fetch request - /// from the [Query Interface](https://github.com/groue/GRDB.swift#the-query-interface). - /// - /// let request = Wine.order(Column("name")) - /// let controller = FetchedRecordsController( - /// dbQueue, - /// request: request) - /// - /// The records are compared by primary key (single-column primary key, - /// compound primary key, or implicit rowid). For a database table which - /// has an `id` primary key, this initializer is equivalent to: - /// - /// // Assuming the wine table has an `id` primary key: - /// let controller = FetchedRecordsController( - /// dbQueue, - /// request: request, - /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) - /// - /// - parameters: - /// - databaseWriter: A DatabaseWriter (DatabaseQueue, or DatabasePool) - /// - request: A fetch request. - /// - queue: A serial dispatch queue (defaults to the main queue) - /// - /// The fetched records controller tracking callbacks will be - /// 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: FetchRequest, Request.RowDecoder == Record - { - // Builds a function that returns true if and only if two items - // have the same primary key and primary keys contain at least one - // non-null value. - let itemsAreIdenticalFactory: ItemComparatorFactory = { db in - // Extract primary key columns from database table - let columns = try db.primaryKey(Record.databaseTableName).columns - - // Compare primary keys - assert(!columns.isEmpty) - return { (lItem, rItem) in - var notNullValue = false - for column in columns { - let lValue: DatabaseValue = lItem.row[column] - let rValue: DatabaseValue = rItem.row[column] - if lValue != rValue { - // different primary keys - return false - } - if !lValue.isNull || !rValue.isNull { - notNullValue = true - } - } - // identical primary keys iff at least one value is not null - return notNullValue - } - } - try self.init( - databaseWriter, - request: request, - queue: queue, - itemsAreIdenticalFactory: itemsAreIdenticalFactory) - } -} - - -// MARK: - FetchedRecordsObserver - -/// FetchedRecordsController adopts TransactionObserverType so that it can -/// monitor changes to its fetched records. -private final class FetchedRecordsObserver: TransactionObserver { - var isValid: Bool - var needsComputeChanges: Bool - var items: [Item]! // ought to be not nil when observer has started tracking transactions - let queue: DispatchQueue // protects items - let region: DatabaseRegion - var fetchAndNotifyChanges: (FetchedRecordsObserver) -> Void - - init(region: DatabaseRegion, fetchAndNotifyChanges: @escaping (FetchedRecordsObserver) -> Void) { - self.isValid = true - self.items = nil - self.needsComputeChanges = false - self.queue = DispatchQueue(label: "GRDB.FetchedRecordsObserver") - self.region = region - self.fetchAndNotifyChanges = fetchAndNotifyChanges - } - - func invalidate() { - isValid = false - } - - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - region.isModified(byEventsOfKind: eventKind) - } - - /// Part of the TransactionObserverType protocol - func databaseDidChange(with event: DatabaseEvent) { - if region.isModified(by: event) { - needsComputeChanges = true - stopObservingDatabaseChangesUntilNextTransaction() - } - } - - /// Part of the TransactionObserverType protocol - func databaseDidRollback(_ db: Database) { - needsComputeChanges = false - } - - /// Part of the TransactionObserverType protocol - func databaseDidCommit(_ db: Database) { - // The databaseDidCommit callback is called in the database writer - // dispatch queue, which is serialized: it is guaranteed to process the - // last database transaction. - - // Were observed tables modified? - guard needsComputeChanges else { return } - needsComputeChanges = false - - fetchAndNotifyChanges(self) - } -} - - -// MARK: - Changes - -private typealias FetchCompletionHandler = - (Result<(fetchedItems: [Item], fetchedAlongside: T, observer: FetchedRecordsObserver), Error>) - -> Void - -private func makeFetchFunction( - controller: FetchedRecordsController, - fetchAlongside: @escaping (Database) throws -> T, - willProcessTransaction: @escaping () -> Void, - completion: @escaping FetchCompletionHandler - ) -> (FetchedRecordsObserver) -> Void -{ - // Make sure we keep a weak reference to the fetched records controller, - // so that the user can use unowned references in callbacks: - // - // controller.trackChanges { [unowned self] ... } - // - // Should controller become strong at any point before callbacks are - // called, such unowned reference would have an opportunity to crash. - return { [weak controller] observer in - // Return if observer has been invalidated, or if fetched records - // controller has been deallocated - guard observer.isValid, - let request = controller?.request, - let databaseWriter = controller?.databaseWriter - else { return } - - willProcessTransaction() - - // Perform a concurrent read so that writer dispatch queue is released - // as soon as possible. - let future = databaseWriter.concurrentRead { db in - try (fetchedItems: request.fetchAll(db), - fetchedAlongside: fetchAlongside(db)) - } - - // Dispatch processing immediately on observer.queue in order to - // process fetched values in the same order as transactions: - observer.queue.async { [weak observer] in - // Return if observer has been deallocated or invalidated - guard let observer = observer, - observer.isValid - else { return } - - do { - // Wait for concurrent read to complete - let values = try future.wait() - - completion(.success(( - fetchedItems: values.fetchedItems, - fetchedAlongside: values.fetchedAlongside, - observer: observer))) - } catch { - completion(.failure(error)) - } - } - } -} - -private func makeFetchAndNotifyChangesFunction( - controller: FetchedRecordsController, - fetchAlongside: @escaping (Database) throws -> T, - itemsAreIdentical: @escaping ItemComparator, - willProcessTransaction: @escaping () -> Void, - willChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)?, - onChange: ((FetchedRecordsController, Record, FetchedRecordChange) -> Void)?, - didChange: ((FetchedRecordsController, _ fetchedAlongside: T) -> Void)?, - didProcessTransaction: @escaping () -> Void - ) -> (FetchedRecordsObserver) -> Void -{ - // Make sure we keep a weak reference to the fetched records controller, - // so that the user can use unowned references in callbacks: - // - // controller.trackChanges { [unowned self] ... } - // - // Should controller become strong at any point before callbacks are - // called, such unowned reference would have an opportunity to crash. - return makeFetchFunction( - controller: controller, - fetchAlongside: fetchAlongside, - willProcessTransaction: willProcessTransaction) - { [weak controller] result in - // Return if fetched records controller has been deallocated - guard let callbackQueue = controller?.queue else { return } - - switch result { - case let .failure(error): - callbackQueue.async { - // Now we can retain controller - guard let strongController = controller else { return } - strongController.errorHandler?(strongController, error) - didProcessTransaction() - } - - case let .success((fetchedItems: fetchedItems, fetchedAlongside: fetchedAlongside, observer: observer)): - // Return if there is no change - let changes: [ItemChange] - if onChange != nil { - // Compute table view changes - changes = computeChanges(from: observer.items, to: fetchedItems, itemsAreIdentical: itemsAreIdentical) - if changes.isEmpty { return } - } else { - // Don't compute changes: just look for a row difference: - if identicalItemArrays(fetchedItems, observer.items) { return } - changes = [] - } - - // Ready for next check - observer.items = fetchedItems - - callbackQueue.async { [weak observer] in - // Return if observer has been invalidated - guard let strongObserver = observer else { return } - guard strongObserver.isValid else { return } - - // Now we can retain controller - guard let strongController = controller else { return } - - // Notify changes - willChange?(strongController, fetchedAlongside) - strongController.fetchedItems = fetchedItems - if let onChange = onChange { - for change in changes { - onChange(strongController, change.record, change.fetchedRecordChange) - } - } - didChange?(strongController, fetchedAlongside) - didProcessTransaction() - } - } - } -} - -private func computeChanges( - from s: [Item], - to t: [Item], - itemsAreIdentical: ItemComparator) - -> [ItemChange] -{ - let m = s.count - let n = t.count - - // Fill first row and column of insertions and deletions. - - var d: [[[ItemChange]]] = Array(repeating: Array(repeating: [], count: n + 1), count: m + 1) - - var changes = [ItemChange]() - for (row, item) in s.enumerated() { - let deletion = ItemChange.deletion(item: item, indexPath: IndexPath(indexes: [0, row])) - changes.append(deletion) - d[row + 1][0] = changes - } - - changes.removeAll() - for (col, item) in t.enumerated() { - let insertion = ItemChange.insertion(item: item, indexPath: IndexPath(indexes: [0, col])) - changes.append(insertion) - d[0][col + 1] = changes - } - - if m == 0 || n == 0 { - // Pure deletions or insertions - return d[m][n] - } - - // Fill body of matrix. - for tx in 0..], itemsAreIdentical: ItemComparator) -> [ItemChange] { - - /// Returns a potential .move or .update if *change* has a matching change in *changes*: - /// If *change* is a deletion or an insertion, and there is a matching inverse - /// insertion/deletion with the same value in *changes*, a corresponding .move or .update is returned. - /// As a convenience, the index of the matched change is returned as well. - func merge( - change: ItemChange, - in changes: [ItemChange], - itemsAreIdentical: ItemComparator) - -> (mergedChange: ItemChange, mergedIndex: Int)? - { - /// Returns the changes between two rows: a dictionary [key: oldValue] - /// Precondition: both rows have the same columns - func changedValues(from oldRow: Row, to newRow: Row) -> [String: DatabaseValue] { - var changedValues: [String: DatabaseValue] = [:] - for (column, newValue) in newRow { - let oldValue: DatabaseValue? = oldRow[column] - if newValue != oldValue { - changedValues[column] = oldValue - } - } - return changedValues - } - - switch change { - case let .insertion(newItem, newIndexPath): - // Look for a matching deletion - for (index, otherChange) in changes.enumerated() { - guard case let .deletion(oldItem, oldIndexPath) = otherChange else { continue } - guard itemsAreIdentical(oldItem, newItem) else { continue } - let rowChanges = changedValues(from: oldItem.row, to: newItem.row) - if oldIndexPath == newIndexPath { - return ( - ItemChange.update( - item: newItem, - indexPath: oldIndexPath, - changes: rowChanges), - index) - } else { - return ( - ItemChange.move( - item: newItem, - indexPath: oldIndexPath, - newIndexPath: newIndexPath, - changes: rowChanges), - index) - } - } - return nil - - case let .deletion(oldItem, oldIndexPath): - // Look for a matching insertion - for (index, otherChange) in changes.enumerated() { - guard case let .insertion(newItem, newIndexPath) = otherChange else { continue } - guard itemsAreIdentical(oldItem, newItem) else { continue } - let rowChanges = changedValues(from: oldItem.row, to: newItem.row) - if oldIndexPath == newIndexPath { - return ( - ItemChange.update( - item: newItem, - indexPath: oldIndexPath, - changes: rowChanges), - index) - } else { - return ( - ItemChange.move( - item: newItem, - indexPath: oldIndexPath, - newIndexPath: newIndexPath, - changes: rowChanges), - index) - } - } - return nil - - default: - return nil - } - } - - // Updates must be pushed at the end - var mergedChanges: [ItemChange] = [] - var updateChanges: [ItemChange] = [] - for change in changes { - if let (mergedChange, mergedIndex) - = merge(change: change, in: mergedChanges, itemsAreIdentical: itemsAreIdentical) - { - mergedChanges.remove(at: mergedIndex) - switch mergedChange { - case .update: - updateChanges.append(mergedChange) - default: - mergedChanges.append(mergedChange) - } - } else { - mergedChanges.append(change) - } - } - return mergedChanges + updateChanges - } - - return standardize(changes: d[m][n], itemsAreIdentical: itemsAreIdentical) -} - -private func identicalItemArrays(_ lhs: [Item], _ rhs: [Item]) -> Bool { - guard lhs.count == rhs.count else { - return false - } - for (lhs, rhs) in zip(lhs, rhs) where lhs.row != rhs.row { - return false - } - return true -} - - -// MARK: - UITableView Support - -private typealias ItemComparator = (Item, Item) -> Bool -private typealias ItemComparatorFactory = (Database) throws -> ItemComparator - -extension FetchedRecordsController { - - // MARK: - Accessing Records - - /// Returns the object at the given index path. - /// - /// - parameter indexPath: An index path in the fetched records. - /// - /// If indexPath does not describe a valid index path in the fetched - /// records, a fatal error is raised. - public func record(at indexPath: IndexPath) -> Record { - guard let fetchedItems = fetchedItems else { - // Programmer error - fatalError("performFetch() has not been called.") - } - return fetchedItems[indexPath[1]].record - } - - - // MARK: - Querying Sections Information - - /// The sections for the fetched records. - /// - /// You typically use the sections array when implementing - /// UITableViewDataSource methods, such as `numberOfSectionsInTableView`. - /// - /// The sections array is never empty, even when there are no fetched - /// records. In this case, there is a single empty section. - public var sections: [FetchedRecordsSectionInfo] { - // We only support a single section so far. - // We also return a single section when there are no fetched - // records, just like NSFetchedResultsController. - return [FetchedRecordsSectionInfo(controller: self)] - } -} - -extension FetchedRecordsController where Record: EncodableRecord { - - /// Returns the indexPath of a given record. - /// - /// - returns: The index path of *record* in the fetched records, or nil - /// if record could not be found. - public func indexPath(for record: Record) -> IndexPath? { - let item = Item(row: Row(record)) - guard - let fetchedItems = fetchedItems, - let index = fetchedItems.firstIndex(where: { itemsAreIdentical($0, item) }) - else { - return nil - } - return IndexPath(indexes: [0, index]) - } -} - -private enum ItemChange { - case insertion(item: Item, indexPath: IndexPath) - case deletion(item: Item, indexPath: IndexPath) - case move(item: Item, indexPath: IndexPath, newIndexPath: IndexPath, changes: [String: DatabaseValue]) - case update(item: Item, indexPath: IndexPath, changes: [String: DatabaseValue]) -} - -extension ItemChange { - var record: T { - switch self { - case .insertion(item: let item, indexPath: _): - return item.record - case .deletion(item: let item, indexPath: _): - return item.record - case .move(item: let item, indexPath: _, newIndexPath: _, changes: _): - return item.record - case .update(item: let item, indexPath: _, changes: _): - return item.record - } - } - - var fetchedRecordChange: FetchedRecordChange { - switch self { - case let .insertion(item: _, indexPath: indexPath): - return .insertion(indexPath: indexPath) - case let .deletion(item: _, indexPath: indexPath): - return .deletion(indexPath: indexPath) - case let .move(item: _, indexPath: indexPath, newIndexPath: newIndexPath, changes: changes): - return .move(indexPath: indexPath, newIndexPath: newIndexPath, changes: changes) - case let .update(item: _, indexPath: indexPath, changes: changes): - return .update(indexPath: indexPath, changes: changes) - } - } -} - -extension ItemChange: CustomStringConvertible { - var description: String { - switch self { - case let .insertion(item, indexPath): - return "Insert \(item) at \(indexPath)" - - case let .deletion(item, indexPath): - return "Delete \(item) from \(indexPath)" - - case let .move(item, indexPath, newIndexPath, changes: changes): - return "Move \(item) from \(indexPath) to \(newIndexPath) with changes: \(changes)" - - case let .update(item, indexPath, changes): - return "Update \(item) at \(indexPath) with changes: \(changes)" - } - } -} - -/// A record change, given by a FetchedRecordsController to its change callback. -/// -/// The move and update events hold a *changes* dictionary, whose keys are -/// column names, and values the old values that have been changed. -public enum FetchedRecordChange { - - /// An insertion event, at given indexPath. - case insertion(indexPath: IndexPath) - - /// A deletion event, at given indexPath. - case deletion(indexPath: IndexPath) - - /// A move event, from indexPath to newIndexPath. The *changes* are a - /// dictionary whose keys are column names, and values the old values that - /// have been changed. - case move(indexPath: IndexPath, newIndexPath: IndexPath, changes: [String: DatabaseValue]) - - /// An update event, at given indexPath. The *changes* are a dictionary - /// whose keys are column names, and values the old values that have - /// been changed. - case update(indexPath: IndexPath, changes: [String: DatabaseValue]) -} - -extension FetchedRecordChange: CustomStringConvertible { - public var description: String { - switch self { - case let .insertion(indexPath): - return "Insertion at \(indexPath)" - - case let .deletion(indexPath): - return "Deletion from \(indexPath)" - - case let .move(indexPath, newIndexPath, changes: changes): - return "Move from \(indexPath) to \(newIndexPath) with changes: \(changes)" - - case let .update(indexPath, changes): - return "Update at \(indexPath) with changes: \(changes)" - } - } -} - -/// A section given by a FetchedRecordsController. -public struct FetchedRecordsSectionInfo { - fileprivate let controller: FetchedRecordsController - - /// The number of records (rows) in the section. - public var numberOfRecords: Int { - guard let items = controller.fetchedItems else { - // Programmer error - fatalError("the performFetch() method must be called before accessing section contents") - } - return items.count - } - - /// The array of records in the section. - public var records: [Record] { - guard let items = controller.fetchedItems else { - // Programmer error - fatalError("the performFetch() method must be called before accessing section contents") - } - return items.map(\.record) - } -} - - -// MARK: - Item - -private final class Item: FetchableRecord, Equatable { - let row: Row - - // Records are lazily loaded - lazy var record = T(row: self.row) - - init(row: Row) { - self.row = row.copy() - } - - static func == (lhs: Item, rhs: Item) -> Bool { - lhs.row == rhs.row - } -} diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 101339ce2..1bf355df9 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -17,7 +17,6 @@ 56057C662291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C642291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */; }; 560714ED227DD10F0091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EB227DD10F0091BB10 /* AssociationPrefetchingSQLTests.swift */; }; 560714EE227DD10F0091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EB227DD10F0091BB10 /* AssociationPrefetchingSQLTests.swift */; }; - 56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; }; 5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; }; 561408A0221596A100DAD589 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5614089E221596A100DAD589 /* GRDB-5.0.swift */; }; @@ -547,7 +546,6 @@ F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; - F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; @@ -587,7 +585,6 @@ F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; - F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; @@ -671,7 +668,6 @@ F3BA81001CFB3025003DC1BA /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; F3BA81011CFB3032003DC1BA /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; - F3BA81031CFB303D003DC1BA /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; F3BA810A1CFB3056003DC1BA /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; F3BA810B1CFB3056003DC1BA /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */; }; F3BA810C1CFB3056003DC1BA /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; @@ -754,7 +750,6 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ - 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsController.swift; sourceTree = ""; }; 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 56057C572291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = ""; }; @@ -1048,7 +1043,6 @@ 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; - 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; @@ -1731,7 +1725,6 @@ isa = PBXGroup; children = ( 5674A7251F30A8EF0095F066 /* FetchableRecord */, - 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73E7203DA278000C443C /* JoinSupportTests.swift */, 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, @@ -1798,7 +1791,6 @@ 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */, 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */, 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */, - 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, @@ -2333,7 +2325,6 @@ 56C0539C22ACEECD0029D27D /* Map.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, 5656A8582295BD56001FF3FF /* SQLQueryGenerator.swift in Sources */, - F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */, 5656A8842295BD56001FF3FF /* SQLExpression.swift in Sources */, 5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */, @@ -2496,7 +2487,6 @@ F3BA80F11CFB3019003DC1BA /* DatabaseSavepointTests.swift in Sources */, 56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */, 56419C9324A51D7F004967E1 /* RecordingError.swift in Sources */, - F3BA81031CFB303D003DC1BA /* FetchedRecordsControllerTests.swift in Sources */, 5653EB6920961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */, F3BA80B71CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, 5698ACCC1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */, @@ -2691,7 +2681,6 @@ 56C0539B22ACEECD0029D27D /* Map.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, 5656A8572295BD56001FF3FF /* SQLQueryGenerator.swift in Sources */, - F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */, 5656A8832295BD56001FF3FF /* SQLExpression.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, @@ -2765,7 +2754,6 @@ 56419C8F24A51D7D004967E1 /* Map.swift in Sources */, F3BA80E31CFB300F003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */, - 56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, 563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */, 56BF22882417821F003D86EB /* UtilsTests.swift in Sources */, F3BA80AC1CFB2FA6003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */, diff --git a/README.md b/README.md index 2e4c4f3a5..e8974cdd0 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ GRDB ships with: - [Associations]: Relations and joins between record types. - [WAL Mode Support](#database-pools): Extra performance for multi-threaded applications. - [Migrations]: Transform your database as your application evolves. -- [Database Observation](#database-changes-observation): Observe database changes and transactions. +- [Database Observation]: Observe database changes and transactions. - [Combine Support]: Access and observe the database with Combine publishers. - [Full-Text Search] - [Encryption](#encryption) @@ -251,7 +251,7 @@ observation.start( }) ``` -See [Database Changes Observation](#database-changes-observation) +See [Database Observation]. @@ -290,7 +290,7 @@ Documentation - [Migrations]: Transform your database as your application evolves. - [Full-Text Search]: Perform efficient and customizable full-text searches. - [Joined Queries Support](#joined-queries-support): Consume complex joined queries. -- [Database Changes Observation](#database-changes-observation): Observe database changes and transactions. +- [Database Observation]: Observe database changes and transactions. - [Encryption](#encryption): Encrypt your database with SQLCipher. - [Backup](#backup): Dump the content of a database to another. - [Interrupt a Database](#interrupt-a-database): Abort any pending database operation. @@ -6958,7 +6958,7 @@ Despite the common [guarantees and rules](#guarantees-and-rules) shared by [data See how, with database pools, two reads can see different database states at the same time. -For more information about database pools, grab information about SQLite [WAL mode](https://www.sqlite.org/wal.html) and [snapshot isolation](https://sqlite.org/isolation.html). See [Database Observation](#database-changes-observation) when you look after automatic notifications of database changes. +For more information about database pools, grab information about SQLite [WAL mode](https://www.sqlite.org/wal.html) and [snapshot isolation](https://sqlite.org/isolation.html). See [Database Observation] when you look after automatic notifications of database changes. ### Advanced DatabasePool @@ -7786,7 +7786,9 @@ This chapter has [moved](Documentation/FullTextSearch.md#enabling-fts5-support). #### FetchedRecordsController -This chapter has [moved](Documentation/FetchedRecordsController.md). +FetchedRecordsController has been removed in GRDB 5. + +The [Database Observation] chapter describes the other ways to observe the databasee. #### Full-Text Search @@ -7844,3 +7846,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Demo Applications]: Documentation/DemoApps/README.md [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq +[Database Observation]: #database-changes-observation \ No newline at end of file diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index b1a006018..564ec8423 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -75,8 +75,6 @@ 56419DA824A54062004967E1 /* RecordWithColumnNameManglingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CBC24A54055004967E1 /* RecordWithColumnNameManglingTests.swift */; }; 56419DA924A54062004967E1 /* UpdateStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CBD24A54055004967E1 /* UpdateStatementTests.swift */; }; 56419DAA24A54062004967E1 /* UpdateStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CBD24A54055004967E1 /* UpdateStatementTests.swift */; }; - 56419DAB24A54062004967E1 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CBE24A54055004967E1 /* FetchedRecordsControllerTests.swift */; }; - 56419DAC24A54062004967E1 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CBE24A54055004967E1 /* FetchedRecordsControllerTests.swift */; }; 56419DAD24A54062004967E1 /* AssociationHasManyRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CBF24A54056004967E1 /* AssociationHasManyRowScopeTests.swift */; }; 56419DAE24A54062004967E1 /* AssociationHasManyRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CBF24A54056004967E1 /* AssociationHasManyRowScopeTests.swift */; }; 56419DAF24A54062004967E1 /* DatabaseMigratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CC024A54056004967E1 /* DatabaseMigratorTests.swift */; }; @@ -487,7 +485,6 @@ 56419CBB24A54055004967E1 /* QueryInterfacePromiseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfacePromiseTests.swift; sourceTree = ""; }; 56419CBC24A54055004967E1 /* RecordWithColumnNameManglingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordWithColumnNameManglingTests.swift; sourceTree = ""; }; 56419CBD24A54055004967E1 /* UpdateStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UpdateStatementTests.swift; sourceTree = ""; }; - 56419CBE24A54055004967E1 /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56419CBF24A54056004967E1 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = ""; }; 56419CC024A54056004967E1 /* DatabaseMigratorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigratorTests.swift; sourceTree = ""; }; 56419CC124A54056004967E1 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; @@ -860,7 +857,6 @@ 56419CA624A54054004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56419CAA24A54054004967E1 /* FetchableRecordDecodableTests.swift */, 56419D3824A5405E004967E1 /* FetchableRecordTests.swift */, - 56419CBE24A54055004967E1 /* FetchedRecordsControllerTests.swift */, 56419CB724A54055004967E1 /* FetchRequestTests.swift */, 56419D5B24A54061004967E1 /* FilterCursorTests.swift */, 56419D4B24A54060004967E1 /* FlattenCursorTests.swift */, @@ -1337,7 +1333,6 @@ 56419EBD24A54063004967E1 /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */, 56419E8F24A54063004967E1 /* AssociationHasManySQLTests.swift in Sources */, 5641A1A424A540D6004967E1 /* Support.swift in Sources */, - 56419DAB24A54062004967E1 /* FetchedRecordsControllerTests.swift in Sources */, 5641A1BC24A540D6004967E1 /* PublisherExpectation.swift in Sources */, 56419EE124A54063004967E1 /* FoundationNSUUIDTests.swift in Sources */, 56419D9D24A54062004967E1 /* FetchRequestTests.swift in Sources */, @@ -1561,7 +1556,6 @@ 56419EBE24A54063004967E1 /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */, 56419E9024A54063004967E1 /* AssociationHasManySQLTests.swift in Sources */, 5641A1A524A540D6004967E1 /* Support.swift in Sources */, - 56419DAC24A54062004967E1 /* FetchedRecordsControllerTests.swift in Sources */, 5641A1BD24A540D6004967E1 /* PublisherExpectation.swift in Sources */, 56419EE224A54063004967E1 /* FoundationNSUUIDTests.swift in Sources */, 56419D9E24A54062004967E1 /* FetchRequestTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 14fa34cd2..998a8c2cd 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -109,8 +109,6 @@ 5641A02B24A540A1004967E1 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F2E24A54095004967E1 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5641A02C24A540A1004967E1 /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F2F24A54096004967E1 /* ValueObservationRecorder.swift */; }; 5641A02D24A540A1004967E1 /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F2F24A54096004967E1 /* ValueObservationRecorder.swift */; }; - 5641A02E24A540A1004967E1 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3024A54096004967E1 /* FetchedRecordsControllerTests.swift */; }; - 5641A02F24A540A1004967E1 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3024A54096004967E1 /* FetchedRecordsControllerTests.swift */; }; 5641A03024A540A1004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3124A54096004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 5641A03124A540A1004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3124A54096004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 5641A03224A540A1004967E1 /* DatabaseQueueSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F3224A54096004967E1 /* DatabaseQueueSchemaCacheTests.swift */; }; @@ -506,7 +504,6 @@ 56419F2D24A54095004967E1 /* RecordPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeySingleTests.swift; sourceTree = ""; }; 56419F2E24A54095004967E1 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 56419F2F24A54096004967E1 /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = ""; }; - 56419F3024A54096004967E1 /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56419F3124A54096004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56419F3224A54096004967E1 /* DatabaseQueueSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueSchemaCacheTests.swift; sourceTree = ""; }; 56419F3324A54096004967E1 /* RowFromDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryTests.swift; sourceTree = ""; }; @@ -864,7 +861,6 @@ 56419F4C24A54097004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56419F7C24A5409B004967E1 /* FetchableRecordDecodableTests.swift */, 56419F9624A5409D004967E1 /* FetchableRecordTests.swift */, - 56419F3024A54096004967E1 /* FetchedRecordsControllerTests.swift */, 56419EFD24A54093004967E1 /* FetchRequestTests.swift */, 56419FAD24A5409F004967E1 /* FilterCursorTests.swift */, 56419FAE24A5409F004967E1 /* FlattenCursorTests.swift */, @@ -1322,7 +1318,6 @@ 5641A0E024A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */, 56419FDA24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */, 5641A01024A540A1004967E1 /* RecordEditedTests.swift in Sources */, - 5641A02E24A540A1004967E1 /* FetchedRecordsControllerTests.swift in Sources */, 5641A0A624A540A1004967E1 /* AssociationHasManySQLTests.swift in Sources */, 56419FFC24A540A1004967E1 /* QueryInterfaceRequestTests.swift in Sources */, 5641A0CC24A540A1004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -1546,7 +1541,6 @@ 5641A0E124A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */, 56419FDB24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */, 5641A01124A540A1004967E1 /* RecordEditedTests.swift in Sources */, - 5641A02F24A540A1004967E1 /* FetchedRecordsControllerTests.swift in Sources */, 5641A0A724A540A1004967E1 /* AssociationHasManySQLTests.swift in Sources */, 56419FFD24A540A1004967E1 /* QueryInterfaceRequestTests.swift in Sources */, 5641A0CD24A540A1004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, diff --git a/Tests/GRDBTests/FetchedRecordsControllerTests.swift b/Tests/GRDBTests/FetchedRecordsControllerTests.swift deleted file mode 100644 index 6fcfcf57b..000000000 --- a/Tests/GRDBTests/FetchedRecordsControllerTests.swift +++ /dev/null @@ -1,1024 +0,0 @@ -import XCTest -import GRDB - -private class ChangesRecorder { - var changes: [(record: Record, change: FetchedRecordChange)] = [] - var recordsBeforeChanges: [Record]! - var recordsAfterChanges: [Record]! - var countBeforeChanges: Int? - var countAfterChanges: Int? - var recordsOnFirstEvent: [Record]! - var transactionExpectation: XCTestExpectation? { - didSet { - changes = [] - recordsBeforeChanges = nil - recordsAfterChanges = nil - countBeforeChanges = nil - countAfterChanges = nil - recordsOnFirstEvent = nil - } - } - - func controllerWillChange(_ controller: FetchedRecordsController, count: Int? = nil) { - recordsBeforeChanges = controller.fetchedRecords - countBeforeChanges = count - } - - /// The default implementation does nothing. - func controller(_ controller: FetchedRecordsController, didChangeRecord record: Record, with change: FetchedRecordChange) { - if recordsOnFirstEvent == nil { - recordsOnFirstEvent = controller.fetchedRecords - } - changes.append((record: record, change: change)) - } - - /// The default implementation does nothing. - func controllerDidChange(_ controller: FetchedRecordsController, count: Int? = nil) { - recordsAfterChanges = controller.fetchedRecords - countAfterChanges = count - if let transactionExpectation = transactionExpectation { - transactionExpectation.fulfill() - } - } -} - -private class Person : Record { - var id: Int64? - let name: String - let email: String? - let bookCount: Int? - - init(id: Int64? = nil, name: String, email: String? = nil) { - self.id = id - self.name = name - self.email = email - self.bookCount = nil - super.init() - } - - required init(row: Row) { - id = row["id"] - name = row["name"] - email = row["email"] - bookCount = row["bookCount"] - super.init(row: row) - } - - override class var databaseTableName: String { - "persons" - } - - override func encode(to container: inout PersistenceContainer) { - container["id"] = id - container["name"] = name - container["email"] = email - } - - override func didInsert(with rowID: Int64, for column: String?) { - id = rowID - } -} - -private struct Book : FetchableRecord { - var id: Int64 - var authorID: Int64 - var title: String - - init(row: Row) { - id = row["id"] - authorID = row["authorID"] - title = row["title"] - } -} - -class FetchedRecordsControllerTests: GRDBTestCase { - - override func setup(_ dbWriter: DatabaseWriter) throws { - try dbWriter.write { db in - try db.create(table: "persons") { t in - t.column("id", .integer).primaryKey() - t.column("name", .text) - t.column("email", .text) - } - try db.create(table: "books") { t in - t.column("id", .integer).primaryKey() - t.column("authorId", .integer).notNull().references("persons", onDelete: .cascade, onUpdate: .cascade) - t.column("title", .text) - } - try db.create(table: "flowers") { t in - t.column("id", .integer).primaryKey() - t.column("name", .text) - } - } - } - - func testControllerFromSQL() throws { - let dbQueue = try makeDatabaseQueue() - let authorId: Int64 = try dbQueue.inDatabase { db in - let plato = Person(name: "Plato") - try plato.insert(db) - try db.execute(sql: "INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [plato.id, "Symposium"]) - let cervantes = Person(name: "Cervantes") - try cervantes.insert(db) - try db.execute(sql: "INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [cervantes.id, "Don Quixote"]) - return cervantes.id! - } - - let controller = try FetchedRecordsController(dbQueue, sql: "SELECT * FROM books WHERE authorID = ?", arguments: [authorId]) - try controller.performFetch() - XCTAssertEqual(controller.fetchedRecords.count, 1) - XCTAssertEqual(controller.fetchedRecords[0].title, "Don Quixote") - } - - func testControllerFromSQLWithAdapter() throws { - let dbQueue = try makeDatabaseQueue() - let authorId: Int64 = try dbQueue.inDatabase { db in - let plato = Person(name: "Plato") - try plato.insert(db) - try db.execute(sql: "INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [plato.id, "Symposium"]) - let cervantes = Person(name: "Cervantes") - try cervantes.insert(db) - try db.execute(sql: "INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [cervantes.id, "Don Quixote"]) - return cervantes.id! - } - - let adapter = ColumnMapping(["id": "_id", "authorId": "_authorId", "title": "_title"]) - let controller = try FetchedRecordsController(dbQueue, sql: "SELECT id AS _id, authorId AS _authorId, title AS _title FROM books WHERE authorID = ?", arguments: [authorId], adapter: adapter) - try controller.performFetch() - XCTAssertEqual(controller.fetchedRecords.count, 1) - XCTAssertEqual(controller.fetchedRecords[0].title, "Don Quixote") - } - - func testControllerFromRequest() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try Person(name: "Plato").insert(db) - try Person(name: "Cervantes").insert(db) - } - - let request = Person.order(Column("name")) - let controller = try FetchedRecordsController(dbQueue, request: request) - try controller.performFetch() - XCTAssertEqual(controller.fetchedRecords.count, 2) - XCTAssertEqual(controller.fetchedRecords[0].name, "Cervantes") - XCTAssertEqual(controller.fetchedRecords[1].name, "Plato") - } - - func testSections() throws { - let dbQueue = try makeDatabaseQueue() - let arthur = Person(name: "Arthur") - try dbQueue.inDatabase { db in - try arthur.insert(db) - } - - let request = Person.all() - let controller = try FetchedRecordsController(dbQueue, request: request) - try controller.performFetch() - XCTAssertEqual(controller.sections.count, 1) - XCTAssertEqual(controller.sections[0].numberOfRecords, 1) - XCTAssertEqual(controller.sections[0].records.count, 1) - XCTAssertEqual(controller.sections[0].records[0].name, "Arthur") - XCTAssertEqual(controller.fetchedRecords.count, 1) - XCTAssertEqual(controller.fetchedRecords[0].name, "Arthur") - XCTAssertEqual(controller.record(at: IndexPath(indexes: [0, 0])).name, "Arthur") - XCTAssertEqual(controller.indexPath(for: arthur), IndexPath(indexes: [0, 0])) - } - - func testEmptyRequestGivesOneSection() throws { - let dbQueue = try makeDatabaseQueue() - let request = Person.all() - let controller = try FetchedRecordsController(dbQueue, request: request) - try controller.performFetch() - XCTAssertEqual(controller.fetchedRecords.count, 0) - - // Just like NSFetchedResultsController - XCTAssertEqual(controller.sections.count, 1) - } - - func testDatabaseChangesAreNotReReflectedUntilPerformFetchAndDelegateIsSet() { - // TODO: test that controller.fetchedRecords does not eventually change - // after a database change. The difficulty of this test lies in the - // "eventually" word. - } - - func testSimpleInsert() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id"))) - let recorder = ChangesRecorder() - controller.trackChanges( - willChange: { recorder.controllerWillChange($0) }, - onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, - didChange: { recorder.controllerDidChange($0) }) - try controller.performFetch() - - // First insert - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 0) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1) - XCTAssertEqual(recorder.recordsOnFirstEvent.map(\.name), ["Arthur"]) - XCTAssertEqual(recorder.changes.count, 1) - XCTAssertEqual(recorder.changes[0].record.id, 1) - XCTAssertEqual(recorder.changes[0].record.name, "Arthur") - switch recorder.changes[0].change { - case .insertion(let indexPath): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) - default: - XCTFail() - } - - // Second insert - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur"), - Person(id: 2, name: "Barbara")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 1) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Arthur"]) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2) - XCTAssertEqual(recorder.recordsOnFirstEvent.map(\.name), ["Arthur", "Barbara"]) - XCTAssertEqual(recorder.changes.count, 1) - XCTAssertEqual(recorder.changes[0].record.id, 2) - XCTAssertEqual(recorder.changes[0].record.name, "Barbara") - switch recorder.changes[0].change { - case .insertion(let indexPath): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1])) - default: - XCTFail() - } - } - - func testSimpleUpdate() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id"))) - let recorder = ChangesRecorder() - controller.trackChanges( - willChange: { recorder.controllerWillChange($0) }, - onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, - didChange: { recorder.controllerDidChange($0) }) - try controller.performFetch() - - // Insert - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur"), - Person(id: 2, name: "Barbara")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - // First update - recorder.transactionExpectation = expectation(description: "expectation") - // No change should be recorded - try dbQueue.inTransaction { db in - try db.execute(sql: "UPDATE persons SET name = ? WHERE id = ?", arguments: ["Arthur", 1]) - return .commit - } - // One change should be recorded - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Craig"), - Person(id: 2, name: "Barbara")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Arthur", "Barbara"]) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2) - XCTAssertEqual(recorder.recordsOnFirstEvent.map(\.name), ["Craig", "Barbara"]) - XCTAssertEqual(recorder.changes.count, 1) - XCTAssertEqual(recorder.changes[0].record.id, 1) - XCTAssertEqual(recorder.changes[0].record.name, "Craig") - switch recorder.changes[0].change { - case .update(let indexPath, let changes): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) - XCTAssertEqual(changes, ["name": "Arthur".databaseValue]) - default: - XCTFail() - } - - // Second update - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Craig"), - Person(id: 2, name: "Danielle")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Craig", "Barbara"]) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2) - XCTAssertEqual(recorder.recordsOnFirstEvent.map(\.name), ["Craig", "Danielle"]) - XCTAssertEqual(recorder.changes.count, 1) - XCTAssertEqual(recorder.changes[0].record.id, 2) - XCTAssertEqual(recorder.changes[0].record.name, "Danielle") - switch recorder.changes[0].change { - case .update(let indexPath, let changes): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1])) - XCTAssertEqual(changes, ["name": "Barbara".databaseValue]) - default: - XCTFail() - } - } - - func testSimpleDelete() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id"))) - let recorder = ChangesRecorder() - controller.trackChanges( - willChange: { recorder.controllerWillChange($0) }, - onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, - didChange: { recorder.controllerDidChange($0) }) - try controller.performFetch() - - // Insert - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur"), - Person(id: 2, name: "Barbara")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - // First delete - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 2, name: "Barbara")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Arthur", "Barbara"]) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1) - XCTAssertEqual(recorder.recordsOnFirstEvent.map(\.name), ["Barbara"]) - XCTAssertEqual(recorder.changes.count, 1) - XCTAssertEqual(recorder.changes[0].record.id, 1) - XCTAssertEqual(recorder.changes[0].record.name, "Arthur") - switch recorder.changes[0].change { - case .deletion(let indexPath): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) - default: - XCTFail() - } - - // Second delete - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, []) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 1) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Barbara"]) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 0) - XCTAssertEqual(recorder.changes.count, 1) - XCTAssertEqual(recorder.changes[0].record.id, 2) - XCTAssertEqual(recorder.changes[0].record.name, "Barbara") - switch recorder.changes[0].change { - case .deletion(let indexPath): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) - default: - XCTFail() - } - } - - func testSimpleMove() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name"))) - let recorder = ChangesRecorder() - controller.trackChanges( - willChange: { recorder.controllerWillChange($0) }, - onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, - didChange: { recorder.controllerDidChange($0) }) - try controller.performFetch() - - // Insert - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur"), - Person(id: 2, name: "Barbara")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - // Move - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Craig"), - Person(id: 2, name: "Barbara")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Arthur", "Barbara"]) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2) - XCTAssertEqual(recorder.recordsOnFirstEvent.map(\.name), ["Barbara", "Craig"]) - XCTAssertEqual(recorder.changes.count, 1) - XCTAssertEqual(recorder.changes[0].record.id, 1) - XCTAssertEqual(recorder.changes[0].record.name, "Craig") - switch recorder.changes[0].change { - case .move(let indexPath, let newIndexPath, let changes): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) - XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 1])) - XCTAssertEqual(changes, ["name": "Arthur".databaseValue]) - default: - XCTFail() - } - } - - func testSideTableChange() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController( - dbQueue, - sql: """ - SELECT persons.*, COUNT(books.id) AS bookCount - FROM persons - LEFT JOIN books ON books.authorId = persons.id - GROUP BY persons.id - ORDER BY persons.name - """) - let recorder = ChangesRecorder() - controller.trackChanges( - willChange: { recorder.controllerWillChange($0) }, - onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, - didChange: { recorder.controllerDidChange($0) }) - try controller.performFetch() - - // Insert - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try db.execute(sql: "INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"]) - try db.execute(sql: "INSERT INTO books (authorId, title) VALUES (?, ?)", arguments: [1, "Moby Dick"]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - // Change books - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try db.execute(sql: "DELETE FROM books") - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 1) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Arthur"]) - XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.bookCount! }, [1]) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1) - XCTAssertEqual(recorder.recordsOnFirstEvent.map(\.name), ["Arthur"]) - XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.bookCount! }, [0]) - XCTAssertEqual(recorder.changes.count, 1) - XCTAssertEqual(recorder.changes[0].record.id, 1) - XCTAssertEqual(recorder.changes[0].record.name, "Arthur") - XCTAssertEqual(recorder.changes[0].record.bookCount, 0) - switch recorder.changes[0].change { - case .update(let indexPath, let changes): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) - XCTAssertEqual(changes, ["bookCount": 1.databaseValue]) - default: - XCTFail() - } - } - - func testComplexChanges() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name"))) - let recorder = ChangesRecorder() - controller.trackChanges( - willChange: { recorder.controllerWillChange($0) }, - onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, - didChange: { recorder.controllerDidChange($0) }) - try controller.performFetch() - - enum EventTest { - case I(String, Int) // insert string at index - case M(String, Int, Int, String) // move string from index to index with changed string - case D(String, Int) // delete string at index - case U(String, Int, String) // update string at index with changed string - - func match(name: String, event: FetchedRecordChange) -> Bool { - switch self { - case .I(let s, let i): - switch event { - case .insertion(let indexPath): - return s == name && i == indexPath[1] - default: - return false - } - case .M(let s, let i, let j, let c): - switch event { - case .move(let indexPath, let newIndexPath, let changes): - return s == name && i == indexPath[1] && j == newIndexPath[1] && c == String.fromDatabaseValue(changes["name"]!)! - default: - return false - } - case .D(let s, let i): - switch event { - case .deletion(let indexPath): - return s == name && i == indexPath[1] - default: - return false - } - case .U(let s, let i, let c): - switch event { - case .update(let indexPath, let changes): - return s == name && i == indexPath[1] && c == String.fromDatabaseValue(changes["name"]!)! - default: - return false - } - } - } - } - - // A list of random updates. We hope to cover most cases if not all cases here. - let steps: [(word: String, events: [EventTest])] = [ - (word: "B", events: [.I("B",0)]), - (word: "BA", events: [.I("A",0)]), - (word: "ABF", events: [.M("B",0,1,"A"), .M("A",1,0,"B"), .I("F",2)]), - (word: "AB", events: [.D("F",2)]), - (word: "A", events: [.D("B",1)]), - (word: "C", events: [.U("C",0,"A")]), - (word: "", events: [.D("C",0)]), - (word: "C", events: [.I("C",0)]), - (word: "CD", events: [.I("D",1)]), - (word: "B", events: [.D("D",1), .U("B",0,"C")]), - (word: "BCAEFD", events: [.I("A",0), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]), - (word: "CADBE", events: [.M("A",2,0,"C"), .D("D",3), .M("C",1,2,"B"), .M("B",4,1,"E"), .M("D",0,3,"A"), .M("E",5,4,"F")]), - (word: "EB", events: [.D("B",1), .D("D",3), .D("E",4), .M("E",2,1,"C"), .U("B",0,"A")]), - (word: "BEC", events: [.I("C",1), .M("B",1,0,"E"), .M("E",0,2,"B")]), - (word: "AB", events: [.D("C",1), .M("B",2,1,"E"), .U("A",0,"B")]), - (word: "ADEFCB", events: [.I("B",1), .I("C",2), .I("E",4), .M("D",1,3,"B"), .I("F",5)]), - (word: "DA", events: [.D("B",1), .D("C",2), .D("E",4), .M("A",3,0,"D"), .D("F",5), .M("D",0,1,"A")]), - (word: "BACEF", events: [.I("C",2), .I("E",3), .I("F",4), .U("B",1,"D")]), - (word: "BACD", events: [.D("F",4), .U("D",3,"E")]), - (word: "EABDFC", events: [.M("B",2,1,"C"), .I("C",2), .M("E",1,4,"B"), .I("F",5)]), - (word: "CAB", events: [.D("C",2), .D("D",3), .D("F",5), .M("C",4,2,"E")]), - (word: "CBAD", events: [.M("A",1,0,"B"), .M("B",0,1,"A"), .I("D",3)]), - (word: "BAC", events: [.M("A",1,0,"B"), .M("B",2,1,"C"), .D("D",3), .M("C",0,2,"A")]), - (word: "CBEADF", events: [.I("A",0), .M("B",0,1,"A"), .I("D",3), .M("C",1,2,"B"), .M("E",2,4,"C"), .I("F",5)]), - (word: "CBA", events: [.D("A",0), .D("D",3), .M("A",4,0,"E"), .D("F",5)]), - (word: "CBDAF", events: [.I("A",0), .M("D",0,3,"A"), .I("F",4)]), - (word: "B", events: [.D("A",0), .D("B",1), .D("D",3), .D("F",4), .M("B",2,0,"C")]), - (word: "BDECAF", events: [.I("A",0), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]), - (word: "ABCDEF", events: [.M("A",1,0,"B"), .M("B",3,1,"D"), .M("D",2,3,"C"), .M("C",4,2,"E"), .M("E",0,4,"A")]), - (word: "ADBCF", events: [.M("B",2,1,"C"), .M("C",3,2,"D"), .M("D",1,3,"B"), .D("F",5), .U("F",4,"E")]), - (word: "A", events: [.D("B",1), .D("C",2), .D("D",3), .D("F",4)]), - (word: "AEBDCF", events: [.I("B",1), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]), - (word: "B", events: [.D("B",1), .D("C",2), .D("D",3), .D("E",4), .D("F",5), .U("B",0,"A")]), - (word: "ABCDF", events: [.I("B",1), .I("C",2), .I("D",3), .I("F",4), .U("A",0,"B")]), - (word: "CAB", events: [.M("A",1,0,"B"), .D("D",3), .M("B",2,1,"C"), .D("F",4), .M("C",0,2,"A")]), - (word: "AC", events: [.D("B",1), .M("A",2,0,"C"), .M("C",0,1,"A")]), - (word: "DABC", events: [.I("B",1), .I("C",2), .M("A",1,0,"C"), .M("D",0,3,"A")]), - (word: "BACD", events: [.M("C",1,2,"B"), .M("B",3,1,"D"), .M("D",2,3,"C")]), - (word: "D", events: [.D("A",0), .D("C",2), .D("D",3), .M("D",1,0,"B")]), - (word: "CABDFE", events: [.I("A",0), .I("B",1), .I("D",3), .I("E",4), .M("C",0,2,"D"), .I("F",5)]), - (word: "BACDEF", events: [.M("B",2,1,"C"), .M("C",1,2,"B"), .M("E",5,4,"F"), .M("F",4,5,"E")]), - (word: "AB", events: [.D("C",2), .D("D",3), .D("E",4), .M("A",1,0,"B"), .D("F",5), .M("B",0,1,"A")]), - (word: "BACDE", events: [.I("C",2), .M("B",0,1,"A"), .I("D",3), .M("A",1,0,"B"), .I("E",4)]), - (word: "E", events: [.D("A",0), .D("C",2), .D("D",3), .D("E",4), .M("E",1,0,"B")]), - (word: "A", events: [.U("A",0,"E")]), - (word: "ABCDE", events: [.I("B",1), .I("C",2), .I("D",3), .I("E",4)]), - (word: "BA", events: [.D("C",2), .D("D",3), .M("A",1,0,"B"), .D("E",4), .M("B",0,1,"A")]), - (word: "A", events: [.D("A",0), .M("A",1,0,"B")]), - (word: "CAB", events: [.I("A",0), .I("B",1), .M("C",0,2,"A")]), - (word: "EA", events: [.D("B",1), .M("E",2,1,"C")]), - (word: "B", events: [.D("A",0), .M("B",1,0,"E")]), - ] - - for step in steps { - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, step.word.enumerated().map { Person(id: Int64($0), name: String($1)) }) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.changes.count, step.events.count) - for (change, event) in zip(recorder.changes, step.events) { - XCTAssertTrue(event.match(name: change.record.name, event: change.change)) - } - } - } - - func testExternalTableChange() { - // TODO: test that delegate is not notified after a database change in a - // table not involved in the fetch request. The difficulty of this test - // lies in the "not" word. - } - - func testCustomRecordIdentity() { - // TODO: test record comparison not based on primary key but based on - // custom function - } - - func testRequestChange() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name"))) - let recorder = ChangesRecorder() - controller.trackChanges( - willChange: { recorder.controllerWillChange($0) }, - onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, - didChange: { recorder.controllerDidChange($0) }) - try controller.performFetch() - - // Insert - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur"), - Person(id: 2, name: "Barbara")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - // Change request with Request - recorder.transactionExpectation = expectation(description: "expectation") - try controller.setRequest(Person.order(Column("name").desc)) - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Arthur", "Barbara"]) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2) - XCTAssertEqual(recorder.recordsOnFirstEvent.map(\.name), ["Barbara", "Arthur"]) - XCTAssertEqual(recorder.changes.count, 1) - XCTAssertEqual(recorder.changes[0].record.id, 2) - XCTAssertEqual(recorder.changes[0].record.name, "Barbara") - switch recorder.changes[0].change { - case .move(let indexPath, let newIndexPath, let changes): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1])) - XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 0])) - XCTAssertTrue(changes.isEmpty) - default: - XCTFail() - } - - // Change request with SQL and arguments - recorder.transactionExpectation = expectation(description: "expectation") - try controller.setRequest(sql: "SELECT ? AS id, ? AS name", arguments: [1, "Craig"]) - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Barbara", "Arthur"]) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1) - XCTAssertEqual(recorder.recordsOnFirstEvent.map(\.name), ["Craig"]) - XCTAssertEqual(recorder.changes.count, 2) - XCTAssertEqual(recorder.changes[0].record.id, 2) - XCTAssertEqual(recorder.changes[0].record.name, "Barbara") - XCTAssertEqual(recorder.changes[1].record.id, 1) - XCTAssertEqual(recorder.changes[1].record.name, "Craig") - switch recorder.changes[0].change { - case .deletion(let indexPath): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) - default: - XCTFail() - } - switch recorder.changes[1].change { - case .move(let indexPath, let newIndexPath, let changes): - // TODO: is it really what we should expect? Wouldn't an update fit better? - // What does UITableView think? - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1])) - XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 0])) - XCTAssertEqual(changes, ["name": "Arthur".databaseValue]) - default: - XCTFail() - } - - // Change request with a different set of tracked columns - recorder.transactionExpectation = expectation(description: "expectation") - try controller.setRequest(Person.select(Column("id"), Column("name"), Column("email")).order(Column("name"))) - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 1) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Craig"]) - XCTAssertEqual(recorder.recordsAfterChanges.count, 2) - XCTAssertEqual(recorder.recordsAfterChanges.map(\.name), ["Arthur", "Barbara"]) - - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try db.execute(sql: "UPDATE persons SET email = ? WHERE name = ?", arguments: ["arthur@example.com", "Arthur"]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Arthur", "Barbara"]) - XCTAssertEqual(recorder.recordsAfterChanges.count, 2) - XCTAssertEqual(recorder.recordsAfterChanges.map(\.name), ["Arthur", "Barbara"]) - - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try db.execute(sql: "UPDATE PERSONS SET EMAIL = ? WHERE NAME = ?", arguments: ["barbara@example.com", "Barbara"]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Arthur", "Barbara"]) - XCTAssertEqual(recorder.recordsAfterChanges.count, 2) - XCTAssertEqual(recorder.recordsAfterChanges.map(\.name), ["Arthur", "Barbara"]) - } - - func testSetCallbacksAfterUpdate() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name"))) - let recorder = ChangesRecorder() - try controller.performFetch() - - // Insert - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur")]) - return .commit - } - - // Set callbacks - recorder.transactionExpectation = expectation(description: "expectation") - controller.trackChanges( - willChange: { recorder.controllerWillChange($0) }, - onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, - didChange: { recorder.controllerDidChange($0) }) - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 0) - XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1) - XCTAssertEqual(recorder.recordsOnFirstEvent.map(\.name), ["Arthur"]) - XCTAssertEqual(recorder.changes.count, 1) - XCTAssertEqual(recorder.changes[0].record.id, 1) - XCTAssertEqual(recorder.changes[0].record.name, "Arthur") - switch recorder.changes[0].change { - case .insertion(let indexPath): - XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) - default: - XCTFail() - } - } - - func testTrailingClosureCallback() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name"))) - var persons: [Person] = [] - try controller.performFetch() - - let expectation = self.expectation(description: "expectation") - controller.trackChanges { - persons = $0.fetchedRecords - expectation.fulfill() - } - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(persons.map(\.name), ["Arthur"]) - } - - func testFetchAlongside() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id"))) - let recorder = ChangesRecorder() - controller.trackChanges( - fetchAlongside: { db in try Person.fetchCount(db) }, - willChange: { (controller, count) in recorder.controllerWillChange(controller, count: count) }, - onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, - didChange: { (controller, count) in recorder.controllerDidChange(controller, count: count) }) - try controller.performFetch() - - // First insert - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 0) - XCTAssertEqual(recorder.recordsAfterChanges.count, 1) - XCTAssertEqual(recorder.recordsAfterChanges.map(\.name), ["Arthur"]) - XCTAssertEqual(recorder.countBeforeChanges!, 1) - XCTAssertEqual(recorder.countAfterChanges!, 1) - - // Second insert - recorder.transactionExpectation = expectation(description: "expectation") - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur"), - Person(id: 2, name: "Barbara")]) - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertEqual(recorder.recordsBeforeChanges.count, 1) - XCTAssertEqual(recorder.recordsBeforeChanges.map(\.name), ["Arthur"]) - XCTAssertEqual(recorder.recordsAfterChanges.count, 2) - XCTAssertEqual(recorder.recordsAfterChanges.map(\.name), ["Arthur", "Barbara"]) - XCTAssertEqual(recorder.countBeforeChanges!, 2) - XCTAssertEqual(recorder.countAfterChanges!, 2) - } - - func testFetchErrors() throws { - let dbQueue = try makeDatabaseQueue() - let controller = try FetchedRecordsController(dbQueue, request: Person.all()) - - let expectation = self.expectation(description: "expectation") - var error: Error? - controller.trackErrors { - error = $1 - expectation.fulfill() - } - controller.trackChanges { _ in } - try controller.performFetch() - try dbQueue.inTransaction { db in - try synchronizePersons(db, [ - Person(id: 1, name: "Arthur")]) - try db.drop(table: "persons") - return .commit - } - waitForExpectations(timeout: 1, handler: nil) - if let error = error as? DatabaseError { - XCTAssertEqual(error.resultCode, .SQLITE_ERROR) - XCTAssertEqual(error.message, "no such table: persons") - XCTAssertEqual(error.sql!, "SELECT * FROM \"persons\"") - XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT * FROM \"persons\"`: no such table: persons") - } else { - XCTFail("Expected DatabaseError") - } - } - - func testObservationOfSpecificRowIds() throws { - let dbQueue = try makeDatabaseQueue() - - let generalController = try FetchedRecordsController(dbQueue, request: Person.all()) - let specificController = try FetchedRecordsController(dbQueue, request: Person.filter(key: 1)) - - let generalExpectation = expectation(description: "expectation") - generalExpectation.expectedFulfillmentCount = 6 - var generalChangeCount = 0 - generalController.trackChanges(onChange: { (_, _, _) in - generalChangeCount += 1 - generalExpectation.fulfill() - }) - try generalController.performFetch() - - let specificExpectation = expectation(description: "expectation") - specificExpectation.expectedFulfillmentCount = 3 - var specificChangeCount = 0 - specificController.trackChanges(onChange: { (_, _, _) in - specificChangeCount += 1 - specificExpectation.fulfill() - }) - try specificController.performFetch() - - try dbQueue.writeWithoutTransaction { db in - try db.execute(sql: "INSERT INTO persons (id, name) VALUES (?, ?)", arguments: [1, "Arthur"]) - try db.execute(sql: "INSERT INTO persons (id, name) VALUES (?, ?)", arguments: [2, "Barbara"]) - try db.execute(sql: "UPDATE persons SET name = ? WHERE id = ?", arguments: ["Craig", 1]) - try db.execute(sql: "UPDATE persons SET name = ? WHERE id = ?", arguments: ["David", 2]) - try db.execute(sql: "DELETE FROM persons") - } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(generalChangeCount, 6) - XCTAssertEqual(specificChangeCount, 3) - } -} - - -// Synchronizes the persons table with a JSON payload -private func synchronizePersons(_ db: Database, _ newPersons: [Person]) throws { - // Sort new persons and database persons by id: - let newPersons = newPersons.sorted { $0.id! < $1.id! } - let databasePersons = try Person.fetchAll(db, sql: "SELECT * FROM persons ORDER BY id") - - // Now that both lists are sorted by id, we can compare them with - // the sortedMerge() function. - // - // We'll delete, insert or update persons, depending on their presence - // in either lists. - for mergeStep in sortedMerge( - left: databasePersons, - right: newPersons, - leftKey: { $0.id! }, - rightKey: { $0.id! }) - { - switch mergeStep { - case .left(let databasePerson): - try databasePerson.delete(db) - case .right(let newPerson): - try newPerson.insert(db) - case .common(_, let newPerson): - try newPerson.update(db) - } - } -} - - -/// Given two sorted sequences (left and right), this function emits "merge steps" -/// which tell whether elements are only found on the left, on the right, or on -/// both sides. -/// -/// Both sequences do not have to share the same element type. Yet elements must -/// share a common comparable *key*. -/// -/// Both sequences must be sorted by this key. -/// -/// Keys must be unique in both sequences. -/// -/// The example below compare two sequences sorted by integer representation, -/// and prints: -/// -/// - Left: 1 -/// - Common: 2, 2 -/// - Common: 3, 3 -/// - Right: 4 -/// -/// for mergeStep in sortedMerge( -/// left: [1,2,3], -/// right: ["2", "3", "4"], -/// leftKey: { $0 }, -/// rightKey: { Int($0)! }) -/// { -/// switch mergeStep { -/// case .left(let left): -/// print("- Left: \(left)") -/// case .right(let right): -/// print("- Right: \(right)") -/// case .common(let left, let right): -/// print("- Common: \(left), \(right)") -/// } -/// } -/// -/// - parameters: -/// - left: The left sequence. -/// - right: The right sequence. -/// - leftKey: A function that returns the key of a left element. -/// - rightKey: A function that returns the key of a right element. -/// - returns: A sequence of MergeStep -private func sortedMerge( - left lSeq: LeftSequence, - right rSeq: RightSequence, - leftKey: @escaping (LeftSequence.Element) -> Key, - rightKey: @escaping (RightSequence.Element) -> Key) -> AnySequence> -{ - return AnySequence { () -> AnyIterator> in - var (lGen, rGen) = (lSeq.makeIterator(), rSeq.makeIterator()) - var (lOpt, rOpt) = (lGen.next(), rGen.next()) - return AnyIterator { - switch (lOpt, rOpt) { - case (let lElem?, let rElem?): - let (lKey, rKey) = (leftKey(lElem), rightKey(rElem)) - if lKey > rKey { - rOpt = rGen.next() - return .right(rElem) - } else if lKey == rKey { - (lOpt, rOpt) = (lGen.next(), rGen.next()) - return .common(lElem, rElem) - } else { - lOpt = lGen.next() - return .left(lElem) - } - case (nil, let rElem?): - rOpt = rGen.next() - return .right(rElem) - case (let lElem?, nil): - lOpt = lGen.next() - return .left(lElem) - case (nil, nil): - return nil - } - } - } -} - -/** - Support for sortedMerge() - */ -private enum MergeStep { - /// An element only found in the left sequence: - case left(LeftElement) - /// An element only found in the right sequence: - case right(RightElement) - /// Left and right elements share a common key: - case common(LeftElement, RightElement) -} diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 72e267b1d..606060f6a 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -701,32 +701,4 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(try Person.limit(1).fetchOne(db)!.id != nil) } } - - - // MARK: - FetchedRecordsController - - func testFetchedRecordsController() throws { - let dbQueue = try makeDatabaseQueue() - let person = Person(name: "Arthur") - try dbQueue.inDatabase { db in - try person.insert(db) - } - - let expectation = self.expectation(description: "expectation") - let controller = - try FetchedRecordsController(dbQueue, request: Person.all()) - var update = false - controller.trackChanges( - onChange: { (_, _, change) in if case .update = change { update = true /* identification by hidden rowid primary key has succeeded */ } }, - didChange: { _ in expectation.fulfill() - }) - try controller.performFetch() - try dbQueue.inDatabase { db in - person.name = "Barbara" - try person.update(db) - } - waitForExpectations(timeout: 1, handler: nil) - - XCTAssertTrue(update) - } }