Merge pull request #801 from groue/dev/Combine

Combine support
This commit is contained in:
Gwendal Roué authored and GitHub committed 2020-06-29 08:04:47 +02:00
commit a9b02a2d2e
127 files changed
+9261 -3063

No files matched your search

-1
View File
@@ -25,7 +25,6 @@ disabled_rules:
opt_in_rules:
- anyobject_protocol
- array_init
- attributes
- closure_spacing
- collection_alignment
- contains_over_filter_count
+6 -1
View File
@@ -72,11 +72,16 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- **New**: [#798](https://github.com/groue/GRDB.swift/pull/798): Debugging operators for ValueObservation
- **New**: [#800](https://github.com/groue/GRDB.swift/pull/800): Xcode 12 support
- **New**: [#801](https://github.com/groue/GRDB.swift/pull/801): Combine support
- **New**: 2x faster decoding of Date and DateComponents
### Documentation Diff
[ValueObservation Operators](README.md#valueobservation-operators) was extended with the documentation for the two new operators `handleEvents` and `print`.
- The [ValueObservation Operators](README.md#valueobservation-operators) chapter was extended with a description of the two new debugging operators `handleEvents` and `print`.
- A new [GRDB ❤️ Combine](Documentation/Combine.md) guide describes the various Combine publishers that read, write, and observe the database.
- [GRDBCombineDemo](Documentation/DemoApps/GRDBCombineDemo/README.md) is a new Combine + SwiftUI demo application.
## 5.0.0-beta.5
-11
View File
@@ -82,7 +82,6 @@ The ideas, in alphabetical order:
- [JSON]
- [Linux]
- [More SQL Generation]
- [Reactive Database Observation]
- [SQL Console in the Debugger]
- [SQLCipher in a Shared App Container]
- [Typed Expressions]
@@ -247,15 +246,6 @@ There are several SQLite features that GRDB could natively support:
See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more information and guidance about the implementation of extra table alterations.
### Reactive Database Observation
:baby: Starter Task
We already have the [GRDBCombine](http://github.com/groue/GRDBCombine) and [RxGRDB] companion libraries.
More choices of reactive engines would help more developers enjoy GRDB.
### SQL Console in the Debugger
:question: Unknown Difficulty :hammer: Tooling
@@ -319,7 +309,6 @@ Features that blur this focus are non-goals:
[JSON]: #json
[Linux]: #linux
[More SQL Generation]: #more-sql-generation
[Reactive Database Observation]: #reactive-database-observation
[Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database
[Non-Goals]: #non-goals
[Report Bugs]: #report-bugs
+316
View File
@@ -0,0 +1,316 @@
GRDB ❤️ Combine
===============
**On systems supporting the Combine framework, GRDB offers the ability to publish database values and events using Combine's publishers.**
- [Usage]
- [Demo Application]
- [Asynchronous Database Access]
- [Database Observation]
## Usage
To connect to the database, please refer to [Database Connections].
<details>
<summary><strong>Asynchronously read from the database</strong></summary>
This publisher reads a single value and delivers it.
```swift
// DatabasePublishers.Read<[Player]>
let players = dbQueue.readPublisher { db in
try Player.fetchAll(db)
}
```
</details>
<details>
<summary><strong>Asynchronously write in the database</strong></summary>
This publisher updates the database and delivers a single value.
```swift
// DatabasePublishers.Write<Void>
let write = dbQueue.writePublisher { db in
try Player(...).insert(db)
}
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher { db -> Int in
try Player(...).insert(db)
return try Player.fetchCount(db)
}
```
</details>
<details>
<summary><strong>Observe changes in database values</strong></summary>
This publisher delivers fresh values whenever the database changes:
```swift
// A publisher with output [Player] and failure Error
let publisher = ValueObservation
.tracking { db in try Player.fetchAll(db) }
.publisher(in: dbQueue)
// A publisher with output Int? and failure Error
let publisher = ValueObservation
.tracking { db in try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player") }
.publisher(in: dbQueue)
```
</details>
<details>
<summary><strong>Observe database transactions</strong></summary>
This publisher delivers database connections whenever a database transaction has impacted an observed region:
```swift
// A publisher with output Database and failure Error
let publisher = DatabaseRegionObservation
.tracking(Player.all())
.publisher(in: dbQueue)
let cancellable = publisher.sink(
receiveCompletion: { completion in ... },
receiveValue: { (db: Database) in
print("Exclusive write access to the database after players have been impacted")
})
// A publisher with output Database and failure Error
let publisher = DatabaseRegionObservation
.tracking(SQLRequest<Int>(sql: "SELECT MAX(score) FROM player"))
.publisher(in: dbQueue)
let cancellable = publisher.sink(
receiveCompletion: { completion in ... },
receiveValue: { (db: Database) in
print("Exclusive write access to the database after maximum score has been impacted")
})
```
</details>
# Asynchronous Database Access
GRDB provide publishers that perform asynchronous database accesses.
- [`readPublisher(receiveOn:value:)`]
- [`writePublisher(receiveOn:updates:)`]
- [`writePublisher(receiveOn:updates:thenRead:)`]
#### `DatabaseReader.readPublisher(receiveOn:value:)`
This methods returns a publisher that completes after database values have been asynchronously fetched.
```swift
// DatabasePublishers.Read<[Player]>
let players = dbQueue.readPublisher { db in
try Player.fetchAll(db)
}
```
Any attempt at modifying the database completes subscriptions with an error.
When you use a [database queue] or a [database snapshot], the read has to wait for any eventual concurrent database access performed by this queue or snapshot to complete.
When you use a [database pool], reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured].
This publisher can be subscribed from any thread. A new database access starts on every subscription.
The fetched value is published on the main queue, unless you provide a specific scheduler to the `receiveOn` argument.
#### `DatabaseWriter.writePublisher(receiveOn:updates:)`
This method returns a publisher that completes after database updates have been successfully executed inside a database transaction.
```swift
// DatabasePublishers.Write<Void>
let write = dbQueue.writePublisher { db in
try Player(...).insert(db)
}
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher { db -> Int in
try Player(...).insert(db)
return try Player.fetchCount(db)
}
```
This publisher can be subscribed from any thread. A new database access starts on every subscription.
It completes on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
When you use a [database pool], and your app executes some database updates followed by some slow fetches, you may profit from optimized scheduling with [`writePublisher(receiveOn:updates:thenRead:)`]. See below.
#### `DatabaseWriter.writePublisher(receiveOn:updates:thenRead:)`
This method returns a publisher that completes after database updates have been successfully executed inside a database transaction, and values have been subsequently fetched:
```swift
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher(
updates: { db in try Player(...).insert(db) }
thenRead: { db, _ in try Player.fetchCount(db) })
}
```
It publishes exactly the same values as [`writePublisher(receiveOn:updates:)`]:
```swift
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher { db -> Int in
try Player(...).insert(db)
return try Player.fetchCount(db)
}
```
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from a function to the other (it is ignored in the sample code above).
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention. See [Advanced DatabasePool](../README.md#advanced-databasepool) for more information.
When you use a [database queue], the results are guaranteed to be identical, but no scheduling optimization is applied.
This publisher can be subscribed from any thread. A new database access starts on every subscription.
It completes on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
# Database Observation
Database Observation publishers are based on [ValueObservation] and [DatabaseRegionObservation]. Please refer to their documentation for more information. If your application needs change notifications that are not built as Combine publishers, check the general [Database Changes Observation] chapter.
- [`ValueObservation.publisher(in:scheduling:)`]
- [`DatabaseRegionObservation.publisher(in:)`]
#### `ValueObservation.publisher(in:scheduling:)`
[ValueObservation] tracks changes in database values. You can turn it into a Combine publisher:
```swift
let observation = ValueObservation.tracking { db in
try Player.fetchAll(db)
}
// A publisher with output [Player] and failure Error
let publisher = observation.publisher(in: dbQueue)
```
This publisher has the same behavior as ValueObservation:
- It notifies an initial value before the eventual changes.
- It may coalesce subsequent changes into a single notification.
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](../README.md#valueobservationremoveduplicates) GRDB operator also.
- It stops emitting any value after the database connection is closed. But it never completes.
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservation scheduler](../README.md#valueobservation-scheduling).
For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications:
```swift
// Immediate notification of the initial value
let cancellable = observation
.publisher(
in: dbQueue,
scheduling: .immediate) // <-
.sink(
receiveCompletion: { completion in ... },
receiveValue: { (players: [Player]) in print("Fresh players: \(players)") })
// <- here "fresh players" is already printed.
```
Note that the `.immediate` scheduler requires that the publisher is subscribed from the main thread. It raises a fatal error otherwise.
See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information.
:warning: **ValueObservation and Data Consistency**
When you compose ValueObservation publishers together with the [combineLatest](https://developer.apple.com/documentation/combine/publisher/3333677-combinelatest) operator, you lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
Instead, compose requests together into **one single** ValueObservation, as below (this is the technique used in the [Demo Application]):
```swift
// DATA CONSISTENCY GUARANTEED
let hallOfFamePublisher = ValueObservation
.tracking { db -> HallOfFame in
let playerCount = try Player.fetchCount(db)
let bestPlayers = try Player.limit(10).orderedByScore().fetchAll(db)
return HallOfFame(playerCount:playerCount, bestPlayers:bestPlayers)
}
.publisher(in: dbQueue)
```
See [ValueObservation] for more information.
#### `DatabaseRegionObservation.publisher(in:)`
[DatabaseRegionObservation] notifies all transactions that impact a tracked database region. You can turn it into a Combine publisher:
```swift
let request = Player.all()
let observation = DatabaseRegionObservation.tracking(request)
// A publisher with output Database and failure Error
let publisher = observation.publisher(in: dbQueue)
```
This publisher can be created and subscribed from any thread. It delivers database connections in a "protected dispatch queue", serialized with all database updates. It only completes when a database error happens.
```swift
let request = Player.all()
let cancellable = DatabaseRegionObservation
.tracking(request)
.publisher(in: dbQueue)
.sink(
receiveCompletion: { completion in ... },
receiveValue: { (db: Database) in
print("Players have changed.")
})
try dbQueue.write { db in
try Player(name: "Arthur").insert(db)
try Player(name: "Barbara").insert(db)
}
// Prints "Players have changed."
try dbQueue.write { db in
try Player.deleteAll(db)
}
// Prints "Players have changed."
```
See [DatabaseRegionObservation] for more information.
[Database Connections]: ../README.md#database-connections
[Usage]: #usage
[Asynchronous Database Access]: #asynchronous-database-access
[Combine]: https://developer.apple.com/documentation/combine
[Database Changes Observation]: ../README.md#database-changes-observation
[Database Observation]: #database-observation
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
[SQLite]: http://sqlite.org
[ValueObservation]: ../README.md#valueobservation
[`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin
[`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
[configured]: ../README.md#databasepool-configuration
[database pool]: ../README.md#database-pools
[database queue]: ../README.md#database-queues
[database snapshot]: ../README.md#database-snapshots
[scheduler]: https://developer.apple.com/documentation/combine/scheduler
@@ -0,0 +1,590 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 50;
objects = {
/* Begin PBXBuildFile section */
563F3E7124A78BD400982CF8 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F3E7024A78BD400982CF8 /* AppDelegate.swift */; };
563F3E7324A78BD400982CF8 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F3E7224A78BD400982CF8 /* SceneDelegate.swift */; };
563F3E7724A78BD700982CF8 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 563F3E7624A78BD700982CF8 /* Assets.xcassets */; };
563F3E7A24A78BD700982CF8 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 563F3E7924A78BD700982CF8 /* Preview Assets.xcassets */; };
563F3E7D24A78BD700982CF8 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 563F3E7B24A78BD700982CF8 /* LaunchScreen.storyboard */; };
5651F47D24A8837800727C9D /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5651F47124A8835B00727C9D /* GRDB.framework */; };
5651F47F24A884B200727C9D /* World.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F47E24A884B200727C9D /* World.swift */; };
5651F48124A8856300727C9D /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48024A8856300727C9D /* PlayerList.swift */; };
5651F48324A885AF00727C9D /* PlayerListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48224A885AF00727C9D /* PlayerListViewModel.swift */; };
5651F48524A8905100727C9D /* PlayerEditor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48424A8905100727C9D /* PlayerEditor.swift */; };
5651F48724A8909F00727C9D /* PlayerFormViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5651F48624A8909F00727C9D /* PlayerFormViewModel.swift */; };
5678066124A8A4E400606BC6 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 5678066324A8A4E400606BC6 /* Localizable.stringsdict */; };
5678066524A8B7DD00606BC6 /* PlayerCreationSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5678066424A8B7DD00606BC6 /* PlayerCreationSheet.swift */; };
56AAFD4724A78F9A0077EADB /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AAFD4524A78F9A0077EADB /* AppDatabase.swift */; };
56AAFD4824A78F9A0077EADB /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AAFD4624A78F9A0077EADB /* Player.swift */; };
56B1B13024A8E9A700D7FB31 /* PlayerForm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1B12F24A8E9A700D7FB31 /* PlayerForm.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
5651F46A24A8835B00727C9D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = DC3773F319C8CBB3004FCF85;
remoteInfo = GRDBOSX;
};
5651F46C24A8835B00727C9D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
remoteInfo = GRDBOSXTests;
};
5651F46E24A8835B00727C9D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56553C181C3E906C00522B5C;
remoteInfo = GRDBOSXCrashTests;
};
5651F47024A8835B00727C9D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
remoteInfo = GRDBiOS;
};
5651F47224A8835B00727C9D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
remoteInfo = GRDBiOSTests;
};
5651F47424A8835B00727C9D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 565490A01D5A4798005622CB;
remoteInfo = GRDBWatchOS;
};
5651F47624A8835B00727C9D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AAA4DCFE230F1E0600C74B15;
remoteInfo = GRDBtvOS;
};
5651F47824A8835B00727C9D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = AAA4DDD4230F262000C74B15;
remoteInfo = GRDBtvOSTests;
};
5651F47A24A8836B00727C9D /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
remoteInfo = GRDBiOS;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
563F3E6D24A78BD400982CF8 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
563F3E7024A78BD400982CF8 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
563F3E7224A78BD400982CF8 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
563F3E7624A78BD700982CF8 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
563F3E7924A78BD700982CF8 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = "<group>"; };
563F3E7C24A78BD700982CF8 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
563F3E7E24A78BD700982CF8 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
5651F45F24A8835B00727C9D /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
5651F47E24A884B200727C9D /* World.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = World.swift; sourceTree = "<group>"; };
5651F48024A8856300727C9D /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
5651F48224A885AF00727C9D /* PlayerListViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerListViewModel.swift; sourceTree = "<group>"; };
5651F48424A8905100727C9D /* PlayerEditor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerEditor.swift; sourceTree = "<group>"; };
5651F48624A8909F00727C9D /* PlayerFormViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerFormViewModel.swift; sourceTree = "<group>"; };
5678066224A8A4E400606BC6 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = "<group>"; };
5678066424A8B7DD00606BC6 /* PlayerCreationSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerCreationSheet.swift; sourceTree = "<group>"; };
56AAFD4524A78F9A0077EADB /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
56AAFD4624A78F9A0077EADB /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
56B1B12F24A8E9A700D7FB31 /* PlayerForm.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerForm.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
563F3E6A24A78BD400982CF8 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
5651F47D24A8837800727C9D /* GRDB.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
56248FEF24A8F3DD009C144A /* ViewModels */ = {
isa = PBXGroup;
children = (
5651F48624A8909F00727C9D /* PlayerFormViewModel.swift */,
5651F48224A885AF00727C9D /* PlayerListViewModel.swift */,
);
path = ViewModels;
sourceTree = "<group>";
};
563F3E6424A78BD400982CF8 = {
isa = PBXGroup;
children = (
5651F45F24A8835B00727C9D /* GRDB.xcodeproj */,
563F3E6F24A78BD400982CF8 /* GRDBCombineDemo */,
563F3E6E24A78BD400982CF8 /* Products */,
5651F47C24A8837800727C9D /* Frameworks */,
);
sourceTree = "<group>";
};
563F3E6E24A78BD400982CF8 /* Products */ = {
isa = PBXGroup;
children = (
563F3E6D24A78BD400982CF8 /* GRDBCombineDemo.app */,
);
name = Products;
sourceTree = "<group>";
};
563F3E6F24A78BD400982CF8 /* GRDBCombineDemo */ = {
isa = PBXGroup;
children = (
563F3E7024A78BD400982CF8 /* AppDelegate.swift */,
563F3E7224A78BD400982CF8 /* SceneDelegate.swift */,
56AAFD4524A78F9A0077EADB /* AppDatabase.swift */,
56AAFD4624A78F9A0077EADB /* Player.swift */,
5651F47E24A884B200727C9D /* World.swift */,
56248FEF24A8F3DD009C144A /* ViewModels */,
56B1B12524A8DA1000D7FB31 /* Views */,
563F3E7824A78BD700982CF8 /* Preview Content */,
56B1B12D24A8DA3300D7FB31 /* Resources */,
56B1B12E24A8DA4F00D7FB31 /* Support */,
);
path = GRDBCombineDemo;
sourceTree = "<group>";
};
563F3E7824A78BD700982CF8 /* Preview Content */ = {
isa = PBXGroup;
children = (
563F3E7924A78BD700982CF8 /* Preview Assets.xcassets */,
);
path = "Preview Content";
sourceTree = "<group>";
};
5651F46024A8835B00727C9D /* Products */ = {
isa = PBXGroup;
children = (
5651F46B24A8835B00727C9D /* GRDB.framework */,
5651F46D24A8835B00727C9D /* GRDBOSXTests.xctest */,
5651F46F24A8835B00727C9D /* GRDBOSXCrashTests.xctest */,
5651F47124A8835B00727C9D /* GRDB.framework */,
5651F47324A8835B00727C9D /* GRDBiOSTests.xctest */,
5651F47524A8835B00727C9D /* GRDB.framework */,
5651F47724A8835B00727C9D /* GRDB.framework */,
5651F47924A8835B00727C9D /* GRDBtvOSTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
5651F47C24A8837800727C9D /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
56B1B12524A8DA1000D7FB31 /* Views */ = {
isa = PBXGroup;
children = (
5678066424A8B7DD00606BC6 /* PlayerCreationSheet.swift */,
5651F48424A8905100727C9D /* PlayerEditor.swift */,
56B1B12F24A8E9A700D7FB31 /* PlayerForm.swift */,
5651F48024A8856300727C9D /* PlayerList.swift */,
);
path = Views;
sourceTree = "<group>";
};
56B1B12D24A8DA3300D7FB31 /* Resources */ = {
isa = PBXGroup;
children = (
563F3E7624A78BD700982CF8 /* Assets.xcassets */,
563F3E7B24A78BD700982CF8 /* LaunchScreen.storyboard */,
5678066324A8A4E400606BC6 /* Localizable.stringsdict */,
);
name = Resources;
sourceTree = "<group>";
};
56B1B12E24A8DA4F00D7FB31 /* Support */ = {
isa = PBXGroup;
children = (
563F3E7E24A78BD700982CF8 /* Info.plist */,
);
name = Support;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
563F3E6C24A78BD400982CF8 /* GRDBCombineDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = 563F3E8124A78BD700982CF8 /* Build configuration list for PBXNativeTarget "GRDBCombineDemo" */;
buildPhases = (
563F3E6924A78BD400982CF8 /* Sources */,
563F3E6A24A78BD400982CF8 /* Frameworks */,
563F3E6B24A78BD400982CF8 /* Resources */,
);
buildRules = (
);
dependencies = (
5651F47B24A8836B00727C9D /* PBXTargetDependency */,
);
name = GRDBCombineDemo;
productName = GRDBCombineDemo;
productReference = 563F3E6D24A78BD400982CF8 /* GRDBCombineDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
563F3E6524A78BD400982CF8 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1150;
LastUpgradeCheck = 1150;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
563F3E6C24A78BD400982CF8 = {
CreatedOnToolsVersion = 11.5;
};
};
};
buildConfigurationList = 563F3E6824A78BD400982CF8 /* Build configuration list for PBXProject "GRDBCombineDemo" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 563F3E6424A78BD400982CF8;
productRefGroup = 563F3E6E24A78BD400982CF8 /* Products */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = 5651F46024A8835B00727C9D /* Products */;
ProjectRef = 5651F45F24A8835B00727C9D /* GRDB.xcodeproj */;
},
);
projectRoot = "";
targets = (
563F3E6C24A78BD400982CF8 /* GRDBCombineDemo */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
5651F46B24A8835B00727C9D /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 5651F46A24A8835B00727C9D /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F46D24A8835B00727C9D /* GRDBOSXTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXTests.xctest;
remoteRef = 5651F46C24A8835B00727C9D /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F46F24A8835B00727C9D /* GRDBOSXCrashTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXCrashTests.xctest;
remoteRef = 5651F46E24A8835B00727C9D /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F47124A8835B00727C9D /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 5651F47024A8835B00727C9D /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F47324A8835B00727C9D /* GRDBiOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBiOSTests.xctest;
remoteRef = 5651F47224A8835B00727C9D /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F47524A8835B00727C9D /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 5651F47424A8835B00727C9D /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F47724A8835B00727C9D /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = GRDB.framework;
remoteRef = 5651F47624A8835B00727C9D /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
5651F47924A8835B00727C9D /* GRDBtvOSTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBtvOSTests.xctest;
remoteRef = 5651F47824A8835B00727C9D /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
563F3E6B24A78BD400982CF8 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
563F3E7D24A78BD700982CF8 /* LaunchScreen.storyboard in Resources */,
5678066124A8A4E400606BC6 /* Localizable.stringsdict in Resources */,
563F3E7A24A78BD700982CF8 /* Preview Assets.xcassets in Resources */,
563F3E7724A78BD700982CF8 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
563F3E6924A78BD400982CF8 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
5651F47F24A884B200727C9D /* World.swift in Sources */,
5651F48324A885AF00727C9D /* PlayerListViewModel.swift in Sources */,
56B1B13024A8E9A700D7FB31 /* PlayerForm.swift in Sources */,
5678066524A8B7DD00606BC6 /* PlayerCreationSheet.swift in Sources */,
563F3E7124A78BD400982CF8 /* AppDelegate.swift in Sources */,
563F3E7324A78BD400982CF8 /* SceneDelegate.swift in Sources */,
5651F48724A8909F00727C9D /* PlayerFormViewModel.swift in Sources */,
5651F48124A8856300727C9D /* PlayerList.swift in Sources */,
56AAFD4724A78F9A0077EADB /* AppDatabase.swift in Sources */,
5651F48524A8905100727C9D /* PlayerEditor.swift in Sources */,
56AAFD4824A78F9A0077EADB /* Player.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
5651F47B24A8836B00727C9D /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = GRDBiOS;
targetProxy = 5651F47A24A8836B00727C9D /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
563F3E7B24A78BD700982CF8 /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
563F3E7C24A78BD700982CF8 /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
5678066324A8A4E400606BC6 /* Localizable.stringsdict */ = {
isa = PBXVariantGroup;
children = (
5678066224A8A4E400606BC6 /* en */,
);
name = Localizable.stringsdict;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
563F3E7F24A78BD700982CF8 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.5;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
563F3E8024A78BD700982CF8 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 13.5;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
563F3E8224A78BD700982CF8 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
DEVELOPMENT_TEAM = AMD8W895CT;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
};
name = Debug;
};
563F3E8324A78BD700982CF8 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
DEVELOPMENT_TEAM = AMD8W895CT;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = 1;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
563F3E6824A78BD400982CF8 /* Build configuration list for PBXProject "GRDBCombineDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
563F3E7F24A78BD700982CF8 /* Debug */,
563F3E8024A78BD700982CF8 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
563F3E8124A78BD700982CF8 /* Build configuration list for PBXNativeTarget "GRDBCombineDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
563F3E8224A78BD700982CF8 /* Debug */,
563F3E8324A78BD700982CF8 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 563F3E6524A78BD400982CF8 /* Project object */;
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,163 @@
import Combine
import GRDB
/// AppDatabase lets the application access the database.
///
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
final class AppDatabase {
private let dbQueue: DatabaseQueue
/// Creates an AppDatabase and make sure the database schema is ready.
init(_ dbQueue: DatabaseQueue) throws {
self.dbQueue = dbQueue
try migrator.migrate(dbQueue)
}
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
migrator.eraseDatabaseOnSchemaChange = true
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// Sort player names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
.collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
}
}
// Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
return migrator
}
}
// MARK: - Database Access
//
// This extension defines methods that fulfill application needs, both in terms
// of writes and reads.
extension AppDatabase {
// MARK: Writes
/// Save (insert or update) a player.
func savePlayer(_ player: inout Player) throws {
try dbQueue.write { db in
try player.save(db)
}
}
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbQueue.write { db in
_ = try Player.deleteAll(db, keys: ids)
}
}
/// Delete all players
func deleteAllPlayers() throws {
try dbQueue.write { db in
_ = try Player.deleteAll(db)
}
}
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() throws {
try dbQueue.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
try createRandomPlayers(db)
} else {
// Insert a player
if Bool.random() {
var player = Player.newRandom()
try player.insert(db)
}
// Delete a random player
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where Bool.random() {
try player.updateChanges(db) {
$0.score = Player.randomScore()
}
}
}
}
}
/// Create random players if the database is empty.
func createRandomPlayersIfEmpty() throws {
try dbQueue.write { db in
if try Player.fetchCount(db) == 0 {
try createRandomPlayers(db)
}
}
}
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: Database) throws {
for _ in 0..<8 {
var player = Player.newRandom()
try player.insert(db)
}
}
// MARK: Reads
/// Returns a publisher that tracks changes in players ordered by name
func playersOrderedByNamePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByName().fetchAll)
// Use the .immediate scheduling so that views do not have to wait
// until the players are loaded.
.publisher(in: dbQueue, scheduling: .immediate)
.eraseToAnyPublisher()
}
/// Returns a publisher that tracks changes in players ordered by score
func playersOrderedByScorePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
// Use the .immediate scheduling so that views do not have to wait
// until the players are loaded.
.publisher(in: dbQueue, scheduling: .immediate)
.eraseToAnyPublisher()
}
}
// MARK: - Support for Tests and Previews
#if DEBUG
extension AppDatabase {
/// Returns an empty, in-memory database, suitable for testing and previews.
static func empty() throws -> AppDatabase {
try AppDatabase(DatabaseQueue())
}
/// Returns an in-memory database populated with a few random
/// players, suitable for previews.
static func random() throws -> AppDatabase {
let database = try AppDatabase.empty()
try database.createRandomPlayersIfEmpty()
return database
}
}
#endif
@@ -0,0 +1,45 @@
import UIKit
import GRDB
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Setup database. Error handling left as an exercise for the reader.
try! setupDatabase()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Database Setup
private func setupDatabase() throws {
// AppDelegate chooses the location of the database file.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
let dbQueue = try DatabaseQueue(path: databaseURL.path)
// Create the shared application database
let database = try AppDatabase(dbQueue)
// Populate the database if it is empty, for better demo purpose.
try database.createRandomPlayersIfEmpty()
// Expose it to the rest of the application
Current.database = { database }
}
}
File renamed without changes.

Before

Width:  |  Height:  |  Size: 329 KiB

After

Width:  |  Height:  |  Size: 329 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 1.8 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 6.5 KiB

After

Width:  |  Height:  |  Size: 6.5 KiB

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,12 @@
{
"images" : [
{
"filename" : "LaunchIcon.pdf",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16097" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="LaunchIcon" translatesAutoresizingMaskIntoConstraints="NO" id="Sgi-te-PKu">
<rect key="frame" x="123.5" y="334.5" width="167" height="237"/>
</imageView>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="Sgi-te-PKu" firstAttribute="centerY" secondItem="6Tk-OE-BBY" secondAttribute="centerY" id="KT7-xd-gV4"/>
<constraint firstItem="Sgi-te-PKu" firstAttribute="centerX" secondItem="6Tk-OE-BBY" secondAttribute="centerX" id="feL-Vs-SeN"/>
</constraints>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="LaunchIcon" width="167" height="237"/>
</resources>
</document>
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
</dict>
</array>
</dict>
</dict>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
@@ -0,0 +1,94 @@
import GRDB
/// The Player struct.
///
/// Identifiable conformance supports SwiftUI list animations
struct Player: Identifiable {
/// The player id.
///
/// Int64 is the recommended type for auto-incremented database ids.
/// Use nil for players that are not inserted yet in the database.
var id: Int64?
var name: String
var score: Int
}
extension Player {
private static let names = [
"Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David",
"Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette",
"Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl",
"Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole",
"Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul",
"Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain",
"Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann",
"Zazie", "Zoé"]
/// Creates a new player with empty name and zero score
static func new() -> Player {
Player(id: nil, name: "", score: 0)
}
/// Creates a new player with random name and random score
static func newRandom() -> Player {
Player(id: nil, name: randomName(), score: randomScore())
}
/// Returns a random name
static func randomName() -> String {
names.randomElement()!
}
/// Returns a random score
static func randomScore() -> Int {
10 * Int.random(in: 0...100)
}
}
// MARK: - Persistence
/// Make Player a Codable Record.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
fileprivate enum Columns {
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
// MARK: - Player Database Requests
/// Define some player requests used by the application.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
order(Player.Columns.name)
}
/// A request of players ordered by score
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
func orderedByScore() -> Self {
order(Player.Columns.score.desc, Player.Columns.name)
}
}
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,52 @@
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let viewModel = PlayerListViewModel(database: Current.database())
let rootView = PlayerList(viewModel: viewModel)
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: rootView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
@@ -0,0 +1,67 @@
import Combine
import Foundation
/// The view model that validates and saves an edited player into the database.
///
/// It feeds `PlayerForm`, `PlayerCreationSheet` and `PlayerEditor`.
final class PlayerFormViewModel: ObservableObject {
/// A validation error that prevents the player from being saved into
/// the database.
enum ValidationError: LocalizedError {
case missingName
var errorDescription: String? {
switch self {
case .missingName:
return "Please give a name to this player."
}
}
}
@Published var name: String = ""
@Published var score: String = ""
private let database: AppDatabase
private var player: Player
init(database: AppDatabase, player: Player) {
self.database = database
self.player = player
updateViewFromPlayer()
}
// MARK: - Manage the Player Form
/// Validates and saves the player into the database.
func savePlayer() throws {
if name.isEmpty {
throw ValidationError.missingName
}
player.name = name
player.score = Int(score) ?? 0
try database.savePlayer(&player)
}
/// Resets form values to the original player values.
func reset() {
updateViewFromPlayer()
}
/// Edits a new player
func editNewPlayer() {
player = .new()
updateViewFromPlayer()
}
// MARK: - Private
private func updateViewFromPlayer() {
self.name = player.name
if player.score == 0 && player.id == nil {
// Avoid displaying "0" for a new player: it does not look good.
self.score = ""
} else {
self.score = "\(player.score)"
}
}
}
@@ -0,0 +1,103 @@
import Combine
import Foundation
/// The view model that feeds `PlayerList`, and performs list modifications
/// in the database.
final class PlayerListViewModel: ObservableObject {
enum Ordering {
case byScore
case byName
}
/// The list ordering
@Published var ordering: Ordering = .byScore
/// The players in the list
@Published var players: [Player] = []
/// The view model that edits a new player
let newPlayerViewModel: PlayerFormViewModel
private let database: AppDatabase
private var playersCancellable: AnyCancellable?
init(database: AppDatabase) {
self.database = database
newPlayerViewModel = PlayerFormViewModel(database: database, player: .new())
playersCancellable = playersPublisher(in: database).sink { [weak self] players in
self?.players = players
}
}
// MARK: - Players List Management
/// Deletes all players
func deleteAllPlayers() {
// Eventual error presentation is left as an exercise for the reader.
try! database.deleteAllPlayers()
}
func deletePlayers(atOffsets offsets: IndexSet) {
// Eventual error presentation is left as an exercise for the reader.
let playerIDs = offsets.compactMap { players[$0].id }
try! database.deletePlayers(ids: playerIDs)
}
/// Refreshes the list of players
func refreshPlayers() {
// Eventual error presentation is left as an exercise for the reader.
try! database.refreshPlayers()
}
/// Spawns many concurrent database updates, for demo purpose
func stressTest() {
for _ in 0..<50 {
DispatchQueue.global().async {
self.refreshPlayers()
}
}
}
// MARK: - Change Player Ordering
/// Toggles between the available orderings
func toggleOrdering() {
switch ordering {
case .byName:
ordering = .byScore
case .byScore:
ordering = .byName
}
}
// MARK: - Player Edition
/// Returns a view model suitable for editing a player.
func editionViewModel(for player: Player) -> PlayerFormViewModel {
PlayerFormViewModel(database: database, player: player)
}
// MARK: - Private
/// Returns a publisher of the players in the list
private func playersPublisher(in database: AppDatabase) -> AnyPublisher<[Player], Never> {
// Players depend on the current ordering
$ordering.map { ordering -> AnyPublisher<[Player], Error> in
switch ordering {
case .byScore:
return database.playersOrderedByScorePublisher()
case .byName:
return database.playersOrderedByNamePublisher()
}
}
.map { playersPublisher in
// Turn database errors into an empty players list.
// Eventual error presentation is left as an exercise for the reader.
playersPublisher.catch { error in
Just<[Player]>([])
}
}
.switchToLatest()
.eraseToAnyPublisher()
}
}
@@ -0,0 +1,55 @@
import SwiftUI
/// The Player creation sheet
struct PlayerCreationSheet: View {
/// Manages edition of the new player
let viewModel: PlayerFormViewModel
/// Executed when user cancels or saves the new user.
let dismissAction: () -> Void
@State private var errorAlertIsPresented = false
@State private var errorAlertTitle = ""
var body: some View {
NavigationView {
PlayerForm(viewModel: viewModel)
.alert(
isPresented: $errorAlertIsPresented,
content: { Alert(title: Text(errorAlertTitle)) })
.navigationBarTitle("New Player")
.navigationBarItems(
leading: Button(
action: self.dismissAction,
label: { Text("Cancel") }),
trailing: Button(
action: self.save,
label: { Text("Save") }))
}
}
private func save() {
do {
try viewModel.savePlayer()
dismissAction()
} catch {
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
errorAlertIsPresented = true
}
}
}
#if DEBUG
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
let viewModel = try! PlayerFormViewModel(
database: .empty(),
player: .new())
return PlayerCreationSheet(
viewModel: viewModel,
dismissAction: { })
}
}
#endif
@@ -0,0 +1,31 @@
import SwiftUI
/// The Player edition view, designed to be the destination of
/// a NavigationLink.
struct PlayerEditor: View {
/// Manages edition of the player
let viewModel: PlayerFormViewModel
var body: some View {
PlayerForm(viewModel: viewModel)
.onDisappear(perform: {
// Ignore validation errors
try? self.viewModel.savePlayer()
})
}
}
#if DEBUG
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = try! PlayerFormViewModel(
database: .empty(),
player: .newRandom())
return NavigationView {
PlayerEditor(viewModel: viewModel)
.navigationBarTitle("Player Edition")
}
}
}
#endif
@@ -0,0 +1,41 @@
import SwiftUI
/// The Player edition form, embedded in both
/// `PlayerCreationSheet` and `PlayerEditor`.
struct PlayerForm: View {
/// Manages the player form
@ObservedObject var viewModel: PlayerFormViewModel
var body: some View {
List {
TextField("Name", text: $viewModel.name)
TextField("Score", text: $viewModel.score)
.keyboardType(.numberPad)
}
.listStyle(GroupedListStyle())
// Make sure the form is reset, in case a previous edition ended
// with a validation error.
//
// The bug we want to prevent is the following:
//
// 1. Launch the app
// 2. Tap a player
// 3. Erase the name so that validation fails
// 4. Hit the back button
// 5. Tap the same player
// 6. Bug: the form displays an empty name.
.onAppear(perform: viewModel.reset)
}
}
#if DEBUG
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = try! PlayerFormViewModel(
database: .empty(),
player: .newRandom())
return PlayerForm(viewModel: viewModel)
}
}
#endif
@@ -0,0 +1,131 @@
import SwiftUI
/// The list of players
struct PlayerList: View {
/// Manages the list of players
@ObservedObject var viewModel: PlayerListViewModel
/// Controls the presentation of the player creation sheet.
@State private var newPlayerIsPresented = false
var body: some View {
NavigationView {
VStack {
playerList
toolbar
}
.navigationBarTitle(Text("\(viewModel.players.count) Players"))
.navigationBarItems(
leading: HStack {
EditButton()
newPlayerButton
},
trailing: toggleOrderingButton)
}
}
private var playerList: some View {
List {
ForEach(viewModel.players) { player in
NavigationLink(destination: self.editionView(for: player)) {
PlayerRow(player: player)
}
}
.onDelete(perform: { offsets in
self.viewModel.deletePlayers(atOffsets: offsets)
})
}
.listStyle(PlainListStyle())
}
private var toolbar: some View {
HStack {
Button(
action: viewModel.deleteAllPlayers,
label: { Image(systemName: "trash").imageScale(.large) })
Spacer()
Button(
action: viewModel.refreshPlayers,
label: { Image(systemName: "arrow.clockwise").imageScale(.large) })
Spacer()
Button(
action: viewModel.stressTest,
label: { Image(systemName: "tornado").imageScale(.large) })
}
.padding()
}
/// The button that toggles between name/score ordering.
private var toggleOrderingButton: some View {
switch viewModel.ordering {
case .byName:
return Button(action: viewModel.toggleOrdering, label: {
HStack {
Text("Name")
Image(systemName: "arrowtriangle.up.fill")
.imageScale(.small)
}
})
case .byScore:
return Button(action: viewModel.toggleOrdering, label: {
HStack {
Text("Score")
Image(systemName: "arrowtriangle.down.fill")
.imageScale(.small)
}
})
}
}
/// The view that edits a player in the list.
private func editionView(for player: Player) -> some View {
PlayerEditor(
viewModel: viewModel.editionViewModel(for: player))
.navigationBarTitle(player.name)
}
/// The button that presents the player creation sheet.
private var newPlayerButton: some View {
Button(
action: {
// Make sure we do not edit a previously created player.
self.viewModel.newPlayerViewModel.editNewPlayer()
self.newPlayerIsPresented = true
},
label: { Image(systemName: "plus").imageScale(.large) })
.sheet(
isPresented: $newPlayerIsPresented,
content: { self.newPlayerCreationSheet })
}
/// The player creation sheet.
private var newPlayerCreationSheet: some View {
PlayerCreationSheet(
viewModel: self.viewModel.newPlayerViewModel,
dismissAction: {
self.newPlayerIsPresented = false
})
}
}
struct PlayerRow: View {
var player: Player
var body: some View {
HStack {
Text(player.name)
Spacer()
Text("\(player.score) points").foregroundColor(.gray)
}
}
}
#if DEBUG
struct PlayerListView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = try! PlayerListViewModel(database: .random())
return PlayerList(viewModel: viewModel)
}
}
#endif
@@ -0,0 +1,11 @@
/// Dependency Injection based on the "How to Control the World" article:
/// https://www.pointfree.co/blog/posts/21-how-to-control-the-world
struct World {
/// The application database
var database: () -> AppDatabase
}
/// The current world.
///
/// Its setup is done by `AppDelegate`, or tests.
var Current = World(database: { fatalError("Database is uninitialized") })
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>%lld Players</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@VARIABLE@</string>
<key>VARIABLE</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>lld</string>
<key>zero</key>
<string>No Player</string>
<key>one</key>
<string>1 Player</string>
<key>other</key>
<string>%lld Players</string>
</dict>
</dict>
<key>%lld points</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@VARIABLE@</string>
<key>VARIABLE</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>lld</string>
<key>zero</key>
<string>0 point</string>
<key>one</key>
<string>1 point</string>
<key>other</key>
<string>%lld points</string>
</dict>
</dict>
</dict>
</plist>
@@ -0,0 +1,36 @@
Combine + SwiftUI Demo Application
==================================
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png" width="50%">
**This demo application is a Combine + SwiftUI application, based on the MVVM design pattern.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a SwiftUI List with [ValueObservation](../../../README.md#valueobservation) Combine publishers.
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
- [AppDelegate.swift](GRDBCombineDemo/AppDelegate.swift)
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../../README.md#database-queues) available for the whole application.
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
`AppDatabase` grants database access for the whole application. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
- [Player.swift](GRDBCombineDemo/Player.swift)
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application.
- [PlayerList.swift](GRDBCombineDemo/Views/PlayerList.swift) and [PlayerListViewModel.swift](GRDBCombineDemo/ViewModels/PlayerListViewModel.swift)
`PlayerList` is the SwiftUI view that displays the list of players, fed by `PlayerListViewModel`.
- [PlayerForm.swift](GRDBCombineDemo/Views/PlayerForm.swift), [PlayerEditor.swift](GRDBCombineDemo/Views/PlayerEditor.swift), [PlayerCreationSheet.swift](GRDBCombineDemo/Views/PlayerCreationSheet.swift) and [PlayerFormViewModel.swift](GRDBCombineDemo/ViewModels/PlayerFormViewModel.swift).
`PlayerForm` is the SwiftUI view that displays a Player edition form. It is embedded in `PlayerEditor` and `PlayerCreationSheet`, two SwiftUI views that edit or create a player. All those views are fed by `PlayerFormViewModel`.
Binary file not shown.

After

Width:  |  Height:  |  Size: 799 KiB

@@ -26,6 +26,8 @@
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; };
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; };
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */; };
56FE6F1E24A90CC500711EDF /* World.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FE6F1D24A90CC500711EDF /* World.swift */; };
56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FE6F2524A90CE400711EDF /* SceneDelegate.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -183,6 +185,8 @@
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewController.swift; sourceTree = "<group>"; };
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
56FE6F1D24A90CC500711EDF /* World.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = World.swift; sourceTree = "<group>"; };
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -273,17 +277,43 @@
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
isa = PBXGroup;
children = (
56B036121E8D9EBE003B6DA4 /* Info.plist */,
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */,
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */,
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */,
56FE6F1D24A90CC500711EDF /* World.swift */,
56FE6F4F24A9114200711EDF /* ViewControllers */,
56FE6F4E24A9112900711EDF /* Resources */,
56FE6F5124A9118000711EDF /* Support */,
);
path = GRDBDemoiOS;
sourceTree = "<group>";
};
56FE6F4E24A9112900711EDF /* Resources */ = {
isa = PBXGroup;
children = (
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */,
56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */,
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
);
path = GRDBDemoiOS;
path = Resources;
sourceTree = "<group>";
};
56FE6F4F24A9114200711EDF /* ViewControllers */ = {
isa = PBXGroup;
children = (
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */,
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */,
);
path = ViewControllers;
sourceTree = "<group>";
};
56FE6F5124A9118000711EDF /* Support */ = {
isa = PBXGroup;
children = (
56B036121E8D9EBE003B6DA4 /* Info.plist */,
);
name = Support;
sourceTree = "<group>";
};
/* End PBXGroup section */
@@ -504,6 +534,8 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
56FE6F1E24A90CC500711EDF /* World.swift in Sources */,
56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */,
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */,
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
@@ -7,7 +7,7 @@ import GRDB
final class AppDatabase {
private let dbQueue: DatabaseQueue
/// Creates an AppDatabase and updates its schema if necessary.
/// Creates an AppDatabase and make sure the database schema is ready.
init(_ dbQueue: DatabaseQueue) throws {
self.dbQueue = dbQueue
try migrator.migrate(dbQueue)
@@ -19,32 +19,29 @@ final class AppDatabase {
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
migrator.eraseDatabaseOnSchemaChange = true
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
// Sort player names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
t.column("name", .text).notNull()
// Sort player names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode
.collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
}
}
migrator.registerMigration("fixtures") { db in
// Populate the players table with random data
for _ in 0..<8 {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
}
// // Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
// Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
return migrator
}
@@ -54,9 +51,7 @@ final class AppDatabase {
//
// This extension defines methods that fulfill application needs, both in terms
// of writes and reads.
extension AppDatabase {
// MARK: Writes
/// Save (insert or update) a player.
@@ -66,10 +61,10 @@ extension AppDatabase {
}
}
/// Delete one player
func deletePlayer(_ player: Player) throws {
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbQueue.write { db in
_ = try player.delete(db)
_ = try Player.deleteAll(db, keys: ids)
}
}
@@ -85,14 +80,11 @@ extension AppDatabase {
try dbQueue.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
for _ in 0..<8 {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
try createRandomPlayers(db)
} else {
// Insert a player
if Bool.random() {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
var player = Player.newRandom()
try player.insert(db)
}
// Delete a random player
@@ -109,6 +101,23 @@ extension AppDatabase {
}
}
/// Create random players if the database is empty.
func createRandomPlayersIfEmpty() throws {
try dbQueue.write { db in
if try Player.fetchCount(db) == 0 {
try createRandomPlayers(db)
}
}
}
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: Database) throws {
for _ in 0..<8 {
var player = Player.newRandom()
try player.insert(db)
}
}
// MARK: Reads
/// Tracks changes in the number of players
@@ -154,3 +163,13 @@ extension AppDatabase {
}
}
// MARK: - Support for Tests
#if DEBUG
extension AppDatabase {
/// Returns an empty, in-memory database, suitable for testing.
static func empty() throws -> AppDatabase {
try AppDatabase(DatabaseQueue())
}
}
#endif
@@ -1,20 +1,32 @@
import UIKit
import GRDB
// The shared application database
var appDatabase: AppDatabase!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
try! setupDatabase(application)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Setup database. Error handling left as an exercise for the reader.
try! setupDatabase()
return true
}
private func setupDatabase(_ application: UIApplication) throws {
// AppDelegate is responsible for choosing the location of the database file.
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Database Setup
private func setupDatabase() throws {
// AppDelegate chooses the location of the database file.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
@@ -22,6 +34,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
let dbQueue = try DatabaseQueue(path: databaseURL.path)
// Create the shared application database
appDatabase = try AppDatabase(dbQueue)
let database = try AppDatabase(dbQueue)
// Populate the database if it is empty, for better demo purpose.
try database.createRandomPlayersIfEmpty()
// Expose it to the rest of the application
Current.database = { database }
}
}
@@ -1,27 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="8150" systemVersion="15A204g" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8122"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<animations/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
@@ -3,7 +3,7 @@
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
@@ -13,15 +13,32 @@
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
</dict>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
@@ -33,6 +50,11 @@
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
@@ -1,14 +1,49 @@
import GRDB
/// The Player struct
struct Player {
var id: Int64? // Use Int64 for auto-incremented database ids
/// The Player struct.
///
/// Hashable conformance supports table view updates
struct Player: Hashable {
/// The player id.
///
/// Int64 is the recommended type for auto-incremented database ids.
/// Use nil for players that are not inserted yet in the database.
var id: Int64?
var name: String
var score: Int
}
/// Hashable conformance supports tableView diffing
extension Player: Hashable { }
extension Player {
private static let names = [
"Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David",
"Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette",
"Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl",
"Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole",
"Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul",
"Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain",
"Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann",
"Zazie", "Zoé"]
/// Creates a new player with empty name and zero score
static func new() -> Player {
Player(id: nil, name: "", score: 0)
}
/// Creates a new player with random name and random score
static func newRandom() -> Player {
Player(id: nil, name: randomName(), score: randomScore())
}
/// Returns a random name
static func randomName() -> String {
names.randomElement()!
}
/// Returns a random score
static func randomScore() -> Int {
10 * Int.random(in: 0...100)
}
}
// MARK: - Persistence
@@ -18,18 +53,17 @@ extension Player: Hashable { }
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
fileprivate enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
// Update a player id after it has been inserted in the database.
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
// MARK: - Player Requests
// MARK: - Player Database Requests
/// Define some player requests used by the application.
///
@@ -58,25 +92,3 @@ extension DerivableRequest where RowDecoder == Player {
order(Player.Columns.score.desc, Player.Columns.name)
}
}
// MARK: - Player Randomization
extension Player {
private static let names = [
"Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David",
"Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette",
"Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl",
"Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole",
"Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul",
"Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain",
"Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann",
"Zazie", "Zoé"]
static func randomName() -> String {
names.randomElement()!
}
static func randomScore() -> Int {
10 * Int.random(in: 0...100)
}
}
@@ -1,225 +0,0 @@
import UIKit
import GRDB
/// PlayerListViewController displays the list of players.
class PlayerListViewController: UITableViewController {
private enum PlayerOrdering {
case byName
case byScore
}
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
private var players: [Player] = []
private var playersCancellable: DatabaseCancellable?
private var playerCountCancellable: DatabaseCancellable?
private var playerOrdering: PlayerOrdering = .byScore {
didSet {
configureOrderingBarButtonItem()
configureTableView()
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureToolbar()
configureNavigationItem()
configureTableView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isToolbarHidden = false
}
private func configureToolbar() {
toolbarItems = [
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
]
}
private func configureNavigationItem() {
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
configureOrderingBarButtonItem()
configureTitle()
}
private func configureOrderingBarButtonItem() {
switch playerOrdering {
case .byScore:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Score ▼",
style: .plain,
target: self, action: #selector(sortByName))
case .byName:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Name ▲",
style: .plain,
target: self, action: #selector(sortByScore))
}
}
private func configureTitle() {
playerCountCancellable = appDatabase.observePlayerCount(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] count in
guard let self = self else { return }
switch count {
case 0: self.navigationItem.title = "No Player"
case 1: self.navigationItem.title = "1 Player"
default: self.navigationItem.title = "\(count) Players"
}
})
}
private func configureTableView() {
switch playerOrdering {
case .byName:
playersCancellable = appDatabase.observePlayersOrderedByName(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(players)
})
case .byScore:
playersCancellable = appDatabase.observePlayersOrderedByScore(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(players)
})
}
}
private func updateTableView(_ players: [Player]) {
// Compute difference between current and new list of players
let difference = players
.difference(from: self.players)
.inferringMoves()
// Apply those changes to the table view
tableView.performBatchUpdates({
self.players = players
for change in difference {
switch change {
case let .remove(offset, _, associatedWith):
if let associatedWith = associatedWith {
self.tableView.moveRow(
at: IndexPath(row: offset, section: 0),
to: IndexPath(row: associatedWith, section: 0))
} else {
self.tableView.deleteRows(
at: [IndexPath(row: offset, section: 0)],
with: .fade)
}
case let .insert(offset, _, associatedWith):
if associatedWith == nil {
self.tableView.insertRows(
at: [IndexPath(row: offset, section: 0)],
with: .fade)
}
}
}
}, completion: nil)
}
}
// MARK: - Navigation
extension PlayerListViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
let player = players[tableView.indexPathForSelectedRow!.row]
let controller = segue.destination as! PlayerEditionViewController
controller.title = player.name
controller.player = player
controller.presentation = .push
}
else if segue.identifier == "New" {
setEditing(false, animated: true)
let navigationController = segue.destination as! UINavigationController
let controller = navigationController.viewControllers.first as! PlayerEditionViewController
controller.title = "New Player"
controller.player = Player(id: nil, name: "", score: 0)
controller.presentation = .modal
}
}
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation cancelled
}
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation committed
}
}
// MARK: - UITableViewDataSource
extension PlayerListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
players.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
configure(cell, at: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Delete the player
let player = players[indexPath.row]
try! appDatabase.deletePlayer(player)
}
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
let player = players[indexPath.row]
if player.name.isEmpty {
cell.textLabel?.text = "-"
} else {
cell.textLabel?.text = player.name
}
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
}
}
// MARK: - Actions
extension PlayerListViewController {
@IBAction func sortByName() {
setEditing(false, animated: true)
playerOrdering = .byName
}
@IBAction func sortByScore() {
setEditing(false, animated: true)
playerOrdering = .byScore
}
@IBAction func deletePlayers() {
setEditing(false, animated: true)
try! appDatabase.deleteAllPlayers()
}
@IBAction func refresh() {
setEditing(false, animated: true)
try! appDatabase.refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
try! appDatabase.refreshPlayers()
}
}
}
}
@@ -0,0 +1,116 @@
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "icon_20pt@2x.png",
"scale" : "2x"
},
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "icon_20pt@3x.png",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "icon_29pt@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "icon_29pt@3x.png",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "icon_40pt@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "icon_40pt@3x.png",
"scale" : "3x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "icon_60pt@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "icon_60pt@3x.png",
"scale" : "3x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "icon_20pt.png",
"scale" : "1x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "icon_20pt@2x-1.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "icon_29pt.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "icon_29pt@2x-1.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "icon_40pt.png",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "icon_40pt@2x-1.png",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "icon_76pt.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "icon_76pt@2x.png",
"scale" : "2x"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "icon_83.5@2x.png",
"scale" : "2x"
},
{
"size" : "1024x1024",
"idiom" : "ios-marketing",
"filename" : "Icon.png",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,12 @@
{
"images" : [
{
"filename" : "LaunchIcon.pdf",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16097" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="LaunchIcon" translatesAutoresizingMaskIntoConstraints="NO" id="10v-qH-Qer">
<rect key="frame" x="123.5" y="334.5" width="167" height="237"/>
</imageView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="10v-qH-Qer" firstAttribute="centerX" secondItem="5Q0-b7-anu" secondAttribute="centerX" id="CgU-Ob-iCK"/>
<constraint firstItem="10v-qH-Qer" firstAttribute="centerY" secondItem="5Q0-b7-anu" secondAttribute="centerY" id="l2h-yP-koC"/>
</constraints>
<viewLayoutGuide key="safeArea" id="5Q0-b7-anu"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="LaunchIcon" width="167" height="237"/>
</resources>
</document>
@@ -0,0 +1,40 @@
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
@@ -127,7 +127,7 @@ extension PlayerEditionViewController: UITextFieldDelegate {
}
player.name = nameTextField.text ?? ""
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
try! appDatabase.savePlayer(&player)
try! Current.database().savePlayer(&player)
self.player = player
}
}
@@ -38,7 +38,7 @@ class PlayerListViewController: UITableViewController {
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
UIBarButtonItem(image: UIImage(systemName: "tornado"), style: .plain, target: self, action: #selector(stressTest)),
]
}
@@ -67,7 +67,7 @@ class PlayerListViewController: UITableViewController {
}
private func configureTitle() {
playerCountCancellable = appDatabase.observePlayerCount(
playerCountCancellable = Current.database().observePlayerCount(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] count in
guard let self = self else { return }
@@ -82,14 +82,14 @@ class PlayerListViewController: UITableViewController {
private func configureTableView() {
switch playerOrdering {
case .byName:
playersCancellable = appDatabase.observePlayersOrderedByName(
playersCancellable = Current.database().observePlayersOrderedByName(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(with: players)
})
case .byScore:
playersCancellable = appDatabase.observePlayersOrderedByScore(
playersCancellable = Current.database().observePlayersOrderedByScore(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
@@ -193,8 +193,9 @@ extension PlayerListViewController {
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Delete the player
let player = players[indexPath.row]
try! appDatabase.deletePlayer(player)
if let id = players[indexPath.row].id {
try! Current.database().deletePlayers(ids: [id])
}
}
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
@@ -224,19 +225,19 @@ extension PlayerListViewController {
@IBAction func deletePlayers() {
setEditing(false, animated: true)
try! appDatabase.deleteAllPlayers()
try! Current.database().deleteAllPlayers()
}
@IBAction func refresh() {
setEditing(false, animated: true)
try! appDatabase.refreshPlayers()
try! Current.database().refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
try! appDatabase.refreshPlayers()
try! Current.database().refreshPlayers()
}
}
}
@@ -0,0 +1,11 @@
/// Dependency Injection based on the "How to Control the World" article:
/// https://www.pointfree.co/blog/posts/21-how-to-control-the-world
struct World {
/// The application database
var database: () -> AppDatabase
}
/// The current world.
///
/// Its setup is done by `AppDelegate`, or tests.
var Current = World(database: { fatalError("Database is uninitialized") })
+8 -6
View File
@@ -1,9 +1,11 @@
Demo Application
================
UIKit Demo Application
======================
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/Images/GRDBDemoScreenshot.png" width="50%">
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png" width="50%">
**This demo application shows you:**
**This demo application is a storyboard-based UIKit application, based on the MVC design pattern.** For a demo application that uses Combine and SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
@@ -24,10 +26,10 @@ Demo Application
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application.
- [PlayerListViewController.swift](GRDBDemoiOS/PlayerListViewController.swift)
- [PlayerListViewController.swift](GRDBDemoiOS/ViewControllers/PlayerListViewController.swift)
`PlayerListViewController` displays the list of players.
- [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift)
- [PlayerEditionViewController.swift](GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift)
`PlayerEditionViewController` can create or edit a player, and save it in the database.
Binary file not shown.

After

Width:  |  Height:  |  Size: 887 KiB

+6
View File
@@ -0,0 +1,6 @@
Demo Applications
=================
- [UIKit Demo Application](GRDBDemoiOS/README.md): a storyboard-based UIKit application, based on the MVC design pattern.
- [Combine + SwiftUI Demo Application](GRDBCombineDemo/README.md): a Combine + SwiftUI application, based on the MVVM design pattern.
@@ -341,7 +341,5 @@ try controller.performFetch()
[ValueObservation]: ../README.md#valueobservation
[GRDBCombine]: http://github.com/groue/GRDBCombine
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[FetchableRecord]: ../README.md#fetchablerecord-protocol
[TableRecord]: ../README.md#tablerecord-protocol
+25 -4
View File
@@ -6,6 +6,7 @@ Migrating From GRDB 4 to GRDB 5
- [Preparing the Migration to GRDB 5](#preparing-the-migration-to-grdb-5)
- [New requirements](#new-requirements)
- [ValueObservation](#valueobservation)
- [Combine Integration](#combine-integration)
- [Other Changes](#other-changes)
@@ -34,7 +35,7 @@ GRDB requirements have been bumped:
[ValueObservation] is the database observation tool that tracks changes in database values. It has quite changed in GRDB 5.
Those changes have the vanilla GRDB, [GRDBCombine], and [RxGRDB], offer a common API, and a common behavior. This greatly helps choosing or switching your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
Those changes have the vanilla GRDB, its [Combine publishers], and [RxGRDB] offer a common API, and a common behavior. This greatly helps choosing or switching your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
In the end, this migration step might require some work. But it's for the benefit of all!
@@ -188,7 +189,7 @@ The changes can quite impact your application. We'll describe them below, as wel
Note that the `.immediate` scheduling requires that the observation starts from the main thread. A fatal error is raised otherwise.
<details>
<summary>GRDBCombine impact</summary>
<summary>Combine impact</summary>
```swift
let observation = ValueObservation.tracking(Player.fetchAll)
@@ -262,7 +263,7 @@ The changes can quite impact your application. We'll describe them below, as wel
1. ValueObservation used to have a `compactMap` method. This method has been removed without any replacement.
If your application uses GRDBCombine or RxGRDB, then use the `compactMap` method from Combine or RxSwift instead.
If your application uses Combine publishers or RxGRDB, then use the `compactMap` method from Combine or RxSwift instead.
2. ValueObservation used to have a `combine` method. This method has been removed without any replacement.
@@ -293,6 +294,26 @@ The changes can quite impact your application. We'll describe them below, as wel
As is previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
## Combine Integration
GRDB 4 had a companion library named GRDBCombine. Combine support is now embedded right into GRDB, and you have to remove any dependency on GRDBCombine.
GRDBCombine used to define a `fetchOnSubscription()` method of the ValueObservation subscriber. It has been removed. Replace it with `scheduling: .immediate` for the same effect (an initial value is notified immediately, synchronously, when the publisher is subscribed):
```swift
// BEFORE: GRDB 4 + GRDBCombine
let observation = ValueObservation.tracking { db in ... }
let publisher = observation
.publisher(in: dbQueue)
.fetchOnSubscription()
// NEW: GRDB 5
let observation = ValueObservation.tracking { db in ... }
let publisher = observation
.publisher(in: dbQueue, scheduling: .immediate)
```
## Other Changes
1. The `Configuration.trace` property has been removed. You know use the `Database.trace(options:_:)` method instead:
@@ -429,7 +450,6 @@ The changes can quite impact your application. We'll describe them below, as wel
[ValueObservation]: ../README.md#valueobservation
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[GRDBCombine]: http://github.com/groue/GRDBCombine
[Observing a Varying Database Region]: ../README.md#observing-a-varying-database-region
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
[Custom SQL functions]: ../README.md#custom-sql-functions
@@ -438,3 +458,4 @@ The changes can quite impact your application. We'll describe them below, as wel
[SQLLiteral]: SQLInterpolation.md#sqlliteral
[SQLRequest]: ../README.md#custom-requests
[QueryInterfaceRequest]: ../README.md#requests
[Combine publishers]: Combine.md
@@ -679,7 +679,7 @@ Instead, have a look at [Database Observation]:
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
>
> :bulb: **Tip**: [GRDBCombine] performs automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
> :bulb: **Tip**: [Combine Support] allows automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
>
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
>
@@ -710,7 +710,6 @@ Instead, have a look at [Database Observation]:
[Database Observation]: ../README.md#database-changes-observation
[ValueObservation]: ../README.md#valueobservation
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[GRDBCombine]: http://github.com/groue/GRDBCombine
[TransactionObserver]: ../README.md#transactionobserver-protocol
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
@@ -727,3 +726,4 @@ Instead, have a look at [Database Observation]:
[Association Aggregates]: AssociationsBasics.md#association-aggregates
[Codable Record]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Combine Support]: Combine.md
Binary file not shown.

Before

Width:  |  Height:  |  Size: 285 KiB

+2 -2
View File
@@ -254,7 +254,7 @@ See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for
## How to perform cross-process database observation
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify database changes performed by other processes.
GRDB [Database Observation] features, as well as its [Combine publishers] and [RxGRDB], are not able to notify database changes performed by other processes.
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
@@ -280,10 +280,10 @@ let observer = try observation.start(in: dbPool) { (db: Database) in
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
[Database Pool]: ../README.md#database-pools
[Database Observation]: ../README.md#database-changes-observation
[GRDBCombine]: http://github.com/groue/GRDBCombine
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[WAL mode]: https://www.sqlite.org/wal.html
[How do I monitor the duration of database statements execution?]: ../README.md#how-do-i-monitor-the-duration-of-database-statements-execution
[Combine publishers]: Combine.md
+4 -8
View File
@@ -117,7 +117,7 @@ let players = try Player.fetchAll(db)
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, or by observing database changes and react accordingly.
In order to keep your views synchronized with the database content, you can use [ValueObservation]. It notifies fresh values after each database change. The [GRDBCombine] and [RxGRDB] companion libraries provide support for [Combine] and [RxSwift].
In order to keep your views synchronized with the database content, you can use [ValueObservation]. It notifies fresh values after each database change, with convenient support for [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB).
```swift
/// An observation of [Player]
@@ -130,7 +130,7 @@ let cancellable = observation.start(in: dbQueue,
onError: { error in ... },
onChange: { (players: [Player]) in print("Fresh players") })
// GRDBCombine
// GRDB + Combine
let cancellable = observation.publisher(in: dbQueue).sink(
receiveCompletion: { completion in ... },
receiveValue: { (players: [Player]) in print("Fresh players") })
@@ -254,14 +254,14 @@ extension Player {
let player = try Player.filter(name: "Arthur O'Brien").fetchOne(db)
```
Custom SQL requests as the one above are welcome in database observation tools like the built-in [ValueObservation], or the companion libraries [GRDBCombine] and [RxGRDB]:
Custom SQL requests as the one above are welcome in database observation tools like the built-in [ValueObservation] and its [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB) flavors:
```swift
let playerObservation = ValueObservation.tracking { db in
try Player.filter(name: "Arthur O'Brien").fetchOne(db)
}
// Observe the SQL request with GRDBCombine
// Observe the SQL request with Combine
let cancellable = playerObservation.publisher(in: dbQueue).sink(
receiveCompletion: { completion in ... },
receiveValue: { (player: Player?) in print("Player has changed") })
@@ -300,10 +300,6 @@ Happy GRDB! :gift:
[PersistableRecord]: ../README.md#records
[Realm]: http://realm.io
[FetchableRecord]: ../README.md#records
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[RxSwift]: https://github.com/ReactiveX/RxSwift
[GRDBCombine]: http://github.com/groue/GRDBCombine
[Combine]: https://developer.apple.com/documentation/combine
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
[StORM]: https://www.perfect.org/docs/StORM.html
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
+184 -10
View File
@@ -173,6 +173,18 @@
563B8FA1249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; };
563B8FA2249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; };
563B8FA3249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; };
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */; };
563B8FAD24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */; };
563B8FAE24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */; };
563B8FAF24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */; };
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
563B8FB624A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
563B8FB824A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
563B8FC624A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
563B8FC824A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563C67B424628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563C67B524628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
@@ -192,6 +204,51 @@
563EF45321631E21007DAACD /* QueryInterfacePromiseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */; };
563EF45421631E21007DAACD /* QueryInterfacePromiseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */; };
563EF45D2163309F007DAACD /* Inflections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF4492161F179007DAACD /* Inflections.swift */; };
56419C5124A51998004967E1 /* Finished.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6124A51601004967E1 /* Finished.swift */; };
56419C5224A51998004967E1 /* NextOne.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6224A51601004967E1 /* NextOne.swift */; };
56419C5324A51998004967E1 /* Next.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6324A51601004967E1 /* Next.swift */; };
56419C5424A51998004967E1 /* Recording.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6424A51601004967E1 /* Recording.swift */; };
56419C5524A51998004967E1 /* Prefix.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6524A51601004967E1 /* Prefix.swift */; };
56419C5624A51998004967E1 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6624A51601004967E1 /* Map.swift */; };
56419C5724A51998004967E1 /* Inverted.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6724A51601004967E1 /* Inverted.swift */; };
56419C5824A51998004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6824A51601004967E1 /* PublisherExpectation.swift */; };
56419C5924A51999004967E1 /* Finished.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6124A51601004967E1 /* Finished.swift */; };
56419C5A24A51999004967E1 /* NextOne.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6224A51601004967E1 /* NextOne.swift */; };
56419C5B24A51999004967E1 /* Next.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6324A51601004967E1 /* Next.swift */; };
56419C5C24A51999004967E1 /* Recording.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6424A51601004967E1 /* Recording.swift */; };
56419C5D24A51999004967E1 /* Prefix.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6524A51601004967E1 /* Prefix.swift */; };
56419C5E24A51999004967E1 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6624A51601004967E1 /* Map.swift */; };
56419C5F24A51999004967E1 /* Inverted.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6724A51601004967E1 /* Inverted.swift */; };
56419C6024A51999004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6824A51601004967E1 /* PublisherExpectation.swift */; };
56419C6124A5199B004967E1 /* Finished.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6124A51601004967E1 /* Finished.swift */; };
56419C6224A5199B004967E1 /* NextOne.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6224A51601004967E1 /* NextOne.swift */; };
56419C6324A5199B004967E1 /* Next.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6324A51601004967E1 /* Next.swift */; };
56419C6424A5199B004967E1 /* Recording.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6424A51601004967E1 /* Recording.swift */; };
56419C6524A5199B004967E1 /* Prefix.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6524A51601004967E1 /* Prefix.swift */; };
56419C6624A5199B004967E1 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6624A51601004967E1 /* Map.swift */; };
56419C6724A5199B004967E1 /* Inverted.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6724A51601004967E1 /* Inverted.swift */; };
56419C6824A5199B004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6824A51601004967E1 /* PublisherExpectation.swift */; };
56419C6924A519A2004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6A24A51601004967E1 /* DatabaseWriterWritePublisherTests.swift */; };
56419C6A24A519A2004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6B24A51601004967E1 /* DatabaseReaderReadPublisherTests.swift */; };
56419C6B24A519A2004967E1 /* Support.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6C24A51601004967E1 /* Support.swift */; };
56419C6C24A519A2004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */; };
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */; };
56419C6E24A519A3004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6A24A51601004967E1 /* DatabaseWriterWritePublisherTests.swift */; };
56419C6F24A519A3004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6B24A51601004967E1 /* DatabaseReaderReadPublisherTests.swift */; };
56419C7024A519A3004967E1 /* Support.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6C24A51601004967E1 /* Support.swift */; };
56419C7124A519A3004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */; };
56419C7224A519A3004967E1 /* ValueObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */; };
56419C7324A519A4004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6A24A51601004967E1 /* DatabaseWriterWritePublisherTests.swift */; };
56419C7424A519A4004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6B24A51601004967E1 /* DatabaseReaderReadPublisherTests.swift */; };
56419C7524A519A4004967E1 /* Support.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6C24A51601004967E1 /* Support.swift */; };
56419C7624A519A4004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */; };
56419C7724A519A4004967E1 /* ValueObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */; };
56419C7824A51A38004967E1 /* Recorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5E24A51601004967E1 /* Recorder.swift */; };
56419C7924A51A38004967E1 /* RecordingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5F24A51601004967E1 /* RecordingError.swift */; };
56419C7A24A51A39004967E1 /* Recorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5E24A51601004967E1 /* Recorder.swift */; };
56419C7B24A51A39004967E1 /* RecordingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5F24A51601004967E1 /* RecordingError.swift */; };
56419C7C24A51A3A004967E1 /* Recorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5E24A51601004967E1 /* Recorder.swift */; };
56419C7D24A51A3A004967E1 /* RecordingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5F24A51601004967E1 /* RecordingError.swift */; };
564390D52414FC2C00BA61E6 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AAA4DCFE230F1E0600C74B15 /* GRDB.framework */; };
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
@@ -371,9 +428,9 @@
56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */; };
56677C0E241CD0D00050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */; };
56677C0F241CD0D00050755D /* ValueObservationRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */; };
56677C15241D14450050755D /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailableTestCase.swift */; };
56677C16241D14450050755D /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailableTestCase.swift */; };
56677C17241D14450050755D /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailableTestCase.swift */; };
56677C15241D14450050755D /* FailureTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailureTestCase.swift */; };
56677C16241D14450050755D /* FailureTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailureTestCase.swift */; };
56677C17241D14450050755D /* FailureTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C14241D14450050755D /* FailureTestCase.swift */; };
56677C19241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */; };
56677C1A241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */; };
56677C1B241D217F0050755D /* ValueObservationRecorderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */; };
@@ -1254,6 +1311,9 @@
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
563B8F91249E6171007A48C9 /* Trace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = "<group>"; };
563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = "<group>"; };
563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabasePublishers.swift; sourceTree = "<group>"; };
563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReceiveValuesOn.swift; sourceTree = "<group>"; };
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnDemandFuture.swift; sourceTree = "<group>"; };
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
@@ -1261,6 +1321,21 @@
563EF43E216131D1007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = "<group>"; };
563EF4492161F179007DAACD /* Inflections.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inflections.swift; sourceTree = "<group>"; };
563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfacePromiseTests.swift; sourceTree = "<group>"; };
56419A5E24A51601004967E1 /* Recorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Recorder.swift; sourceTree = "<group>"; };
56419A5F24A51601004967E1 /* RecordingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordingError.swift; sourceTree = "<group>"; };
56419A6124A51601004967E1 /* Finished.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Finished.swift; sourceTree = "<group>"; };
56419A6224A51601004967E1 /* NextOne.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NextOne.swift; sourceTree = "<group>"; };
56419A6324A51601004967E1 /* Next.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Next.swift; sourceTree = "<group>"; };
56419A6424A51601004967E1 /* Recording.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Recording.swift; sourceTree = "<group>"; };
56419A6524A51601004967E1 /* Prefix.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Prefix.swift; sourceTree = "<group>"; };
56419A6624A51601004967E1 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
56419A6724A51601004967E1 /* Inverted.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inverted.swift; sourceTree = "<group>"; };
56419A6824A51601004967E1 /* PublisherExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublisherExpectation.swift; sourceTree = "<group>"; };
56419A6A24A51601004967E1 /* DatabaseWriterWritePublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseWriterWritePublisherTests.swift; sourceTree = "<group>"; };
56419A6B24A51601004967E1 /* DatabaseReaderReadPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseReaderReadPublisherTests.swift; sourceTree = "<group>"; };
56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = "<group>"; };
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = "<group>"; };
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = "<group>"; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
@@ -1326,7 +1401,7 @@
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateDecodingStrategyTests.swift; sourceTree = "<group>"; };
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseDateEncodingStrategyTests.swift; sourceTree = "<group>"; };
56677C0C241CD0D00050755D /* ValueObservationRecorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorder.swift; sourceTree = "<group>"; };
56677C14241D14450050755D /* FailableTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = "<group>"; };
56677C14241D14450050755D /* FailureTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailureTestCase.swift; sourceTree = "<group>"; };
56677C18241D217F0050755D /* ValueObservationRecorderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationRecorderTests.swift; sourceTree = "<group>"; };
566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = "<group>"; };
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = "<group>"; };
@@ -1700,7 +1775,7 @@
children = (
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
56677C14241D14450050755D /* FailableTestCase.swift */,
56677C14241D14450050755D /* FailureTestCase.swift */,
5698AC3E1DA2BEBB0056AF8C /* FTS */,
56176CA01EACEE2A000F3F2B /* GRDBCipher */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
@@ -1837,6 +1912,43 @@
name = ValueObservation;
sourceTree = "<group>";
};
56419A5D24A51601004967E1 /* CombineExpectations */ = {
isa = PBXGroup;
children = (
56419A5E24A51601004967E1 /* Recorder.swift */,
56419A5F24A51601004967E1 /* RecordingError.swift */,
56419A6024A51601004967E1 /* PublisherExpectations */,
56419A6824A51601004967E1 /* PublisherExpectation.swift */,
);
path = CombineExpectations;
sourceTree = "<group>";
};
56419A6024A51601004967E1 /* PublisherExpectations */ = {
isa = PBXGroup;
children = (
56419A6124A51601004967E1 /* Finished.swift */,
56419A6224A51601004967E1 /* NextOne.swift */,
56419A6324A51601004967E1 /* Next.swift */,
56419A6424A51601004967E1 /* Recording.swift */,
56419A6524A51601004967E1 /* Prefix.swift */,
56419A6624A51601004967E1 /* Map.swift */,
56419A6724A51601004967E1 /* Inverted.swift */,
);
path = PublisherExpectations;
sourceTree = "<group>";
};
56419A6924A51601004967E1 /* GRDBCombineTests */ = {
isa = PBXGroup;
children = (
56419A6A24A51601004967E1 /* DatabaseWriterWritePublisherTests.swift */,
56419A6B24A51601004967E1 /* DatabaseReaderReadPublisherTests.swift */,
56419A6C24A51601004967E1 /* Support.swift */,
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */,
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */,
);
path = GRDBCombineTests;
sourceTree = "<group>";
};
564390D42414FC2C00BA61E6 /* Frameworks */ = {
isa = PBXGroup;
children = (
@@ -1955,9 +2067,11 @@
563EF4492161F179007DAACD /* Inflections.swift */,
569BBA482291707D00478429 /* Inflections+English.swift */,
566BE7172342542F00A8254B /* LockedBox.swift */,
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */,
563EF414215F87EB007DAACD /* OrderedDictionary.swift */,
5659F4971EA8D989004A4992 /* Pool.swift */,
5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */,
563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */,
56781B0A243F86E600650A83 /* Refinable.swift */,
5659F4871EA8D94E004A4992 /* Utils.swift */,
);
@@ -2160,6 +2274,7 @@
56A238731B9C75030082EB20 /* DatabaseError.swift */,
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */,
560A37A31C8F625000949E71 /* DatabasePool.swift */,
563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
@@ -2182,8 +2297,8 @@
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
5605F1471C672E4000235C62 /* Support */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
sourceTree = "<group>";
@@ -2276,8 +2391,10 @@
DC10500F19C904DD00D8CA30 /* Tests */ = {
isa = PBXGroup;
children = (
56176C581EACC2D8000F3F2B /* GRDBTests */,
56419A5D24A51601004967E1 /* CombineExpectations */,
569530FA1C9067CC00CF1A2B /* Crash */,
56419A6924A51601004967E1 /* GRDBCombineTests */,
56176C581EACC2D8000F3F2B /* GRDBTests */,
DC37740319C8CBB3004FCF85 /* Supporting Files */,
);
path = Tests;
@@ -2766,6 +2883,7 @@
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */,
56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
565490B91D5AE236005622CB /* DatabasePool.swift in Sources */,
563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
@@ -2804,6 +2922,7 @@
5659F49E1EA8D989004A4992 /* Pool.swift in Sources */,
5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */,
563B8FAE24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */,
565490D01D5AE252005622CB /* NSString.swift in Sources */,
565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */,
@@ -2836,6 +2955,7 @@
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
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 */,
@@ -2890,6 +3010,7 @@
5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */,
563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */,
56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
563B8FC624A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
5656A8B12295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
@@ -2923,6 +3044,7 @@
5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */,
5653EB0420944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
56B964B41DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
563B8FB624A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
@@ -2942,6 +3064,7 @@
569BBA4F229170F900478429 /* Inflections+English.swift in Sources */,
5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
5617294F223533F40006E219 /* EncodableRecord.swift in Sources */,
563B8FAD24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */,
5657AB121D10899D006283EF /* URL.swift in Sources */,
5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
@@ -3020,6 +3143,7 @@
files = (
563B06C82185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */,
6340BF841E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
56419C5E24A51999004967E1 /* Map.swift in Sources */,
56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */,
56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */,
56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
@@ -3047,6 +3171,7 @@
5657AB4A1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */,
56A2385A1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift in Sources */,
56419C7224A519A3004967E1 /* ValueObservationPublisherTests.swift in Sources */,
562756471E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */,
563B06F821861D8400B38F35 /* ValueObservationCountTests.swift in Sources */,
@@ -3074,6 +3199,7 @@
56E4F7EF2392E2D000A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */,
561CFA992376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */,
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 */,
@@ -3088,18 +3214,21 @@
5653EADD20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */,
56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
56300B621C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
56419C5D24A51999004967E1 /* Prefix.swift in Sources */,
56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */,
56677C16241D14450050755D /* FailableTestCase.swift in Sources */,
56677C16241D14450050755D /* FailureTestCase.swift in Sources */,
5615B288222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5682D722239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */,
56419C5A24A51999004967E1 /* NextOne.swift in Sources */,
564FCE5F20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */,
5653EADF20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */,
5695961D222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */,
56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */,
56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */,
56419C5B24A51999004967E1 /* Next.swift in Sources */,
56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */,
563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */,
56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */,
@@ -3108,6 +3237,7 @@
56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */,
56B86E7A220FF4E000524C16 /* SQLLiteralTests.swift in Sources */,
56176C6C1EACCCC9000F3F2B /* FTS5PatternTests.swift in Sources */,
56419C7024A519A3004967E1 /* Support.swift in Sources */,
563363B21C933FF8000BE133 /* PersistableRecordTests.swift in Sources */,
5615B26B222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
561CFA9D2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */,
@@ -3118,6 +3248,7 @@
563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */,
5665F85E203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */,
56A238441B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
56419C7B24A51A39004967E1 /* RecordingError.swift in Sources */,
560A37AC1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */,
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */,
5690C33B1D23E7D200E59934 /* FoundationDateTests.swift in Sources */,
@@ -3128,12 +3259,14 @@
563B06CB2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */,
5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
56419C5F24A51999004967E1 /* Inverted.swift in Sources */,
560432A4228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */,
566A84412041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */,
56057C562291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */,
56419C5924A51999004967E1 /* Finished.swift in Sources */,
56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */,
56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */,
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */,
@@ -3150,6 +3283,7 @@
56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
56915783231BF28B00E1D237 /* PoolTests.swift in Sources */,
56419C7124A519A3004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */,
56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */,
5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
563B8FA2249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */,
@@ -3161,8 +3295,10 @@
56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */,
5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
5653EAE720944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */,
56419C6F24A519A3004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */,
563EF440216131D1007DAACD /* AssociationAggregateTests.swift in Sources */,
5695312A1C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift in Sources */,
56419C6024A51999004967E1 /* PublisherExpectation.swift in Sources */,
5653EADB20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
56677C0E241CD0D00050755D /* ValueObservationRecorder.swift in Sources */,
5698ACA21DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
@@ -3213,9 +3349,11 @@
5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */,
563B06BE2185CCD300B38F35 /* ValueObservationTests.swift in Sources */,
56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
56419C7A24A51A39004967E1 /* Recorder.swift in Sources */,
56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */,
5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */,
56176C6D1EACCCC9000F3F2B /* FTS5RecordTests.swift in Sources */,
56419C5C24A51999004967E1 /* Recording.swift in Sources */,
569178491CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */,
562393761DEE104400A6B01F /* MapCursorTests.swift in Sources */,
566A8426204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */,
@@ -3229,6 +3367,7 @@
files = (
563B06C72185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */,
6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */,
56419C5624A51998004967E1 /* Map.swift in Sources */,
56D496771D81309E008276D7 /* RecordInitializersTests.swift in Sources */,
56D496651D813076008276D7 /* DatabaseMigratorTests.swift in Sources */,
56D496591D81304E008276D7 /* FoundationNSDateTests.swift in Sources */,
@@ -3256,6 +3395,7 @@
56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */,
56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */,
56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */,
56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */,
56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */,
563B06F721861D8400B38F35 /* ValueObservationCountTests.swift in Sources */,
@@ -3283,6 +3423,7 @@
56E4F7EE2392E2D000A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */,
561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */,
56D496881D81316E008276D7 /* DatabaseValueConversionTests.swift in Sources */,
56419C6924A519A2004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */,
56057C622291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */,
56D496BA1D813482008276D7 /* DatabaseQueueSchemaCacheTests.swift in Sources */,
56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */,
@@ -3297,18 +3438,21 @@
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */,
5653EADC20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */,
56D5075E1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
56419C5524A51998004967E1 /* Prefix.swift in Sources */,
56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
56677C15241D14450050755D /* FailableTestCase.swift in Sources */,
56677C15241D14450050755D /* FailureTestCase.swift in Sources */,
5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
56419C5224A51998004967E1 /* NextOne.swift in Sources */,
56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */,
564FCE5E20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */,
5695961C222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */,
5653EADE20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */,
56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */,
56419C5324A51998004967E1 /* Next.swift in Sources */,
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */,
563B071521862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */,
56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */,
@@ -3317,6 +3461,7 @@
56741EA81E66A8B3003E422D /* FetchRequestTests.swift in Sources */,
56B86E79220FF4E000524C16 /* SQLLiteralTests.swift in Sources */,
56D496831D813147008276D7 /* DatabaseSavepointTests.swift in Sources */,
56419C6B24A519A2004967E1 /* Support.swift in Sources */,
56D496871D81316E008276D7 /* DatabaseTimestampTests.swift in Sources */,
5615B26A222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */,
@@ -3327,6 +3472,7 @@
563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */,
5674A70F1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
56D496711D81309E008276D7 /* RecordPrimaryKeySingleTests.swift in Sources */,
56419C7924A51A38004967E1 /* RecordingError.swift in Sources */,
5665F85D203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */,
5698AC031D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */,
56D496611D81304E008276D7 /* Row+FoundationTests.swift in Sources */,
@@ -3337,12 +3483,14 @@
563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */,
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */,
56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */,
56419C5724A51998004967E1 /* Inverted.swift in Sources */,
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */,
5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
566A84402041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */,
56419C5124A51998004967E1 /* Finished.swift in Sources */,
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */,
56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */,
@@ -3359,6 +3507,7 @@
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */,
56419C6C24A519A2004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */,
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
563B8FA1249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */,
@@ -3370,8 +3519,10 @@
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */,
5653EAE020944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
56419C6A24A519A2004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */,
563EF43F216131D1007DAACD /* AssociationAggregateTests.swift in Sources */,
5653EAE620944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */,
56419C5824A51998004967E1 /* PublisherExpectation.swift in Sources */,
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */,
56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */,
5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
@@ -3422,9 +3573,11 @@
5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */,
563B06BD2185CCD300B38F35 /* ValueObservationTests.swift in Sources */,
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 */,
56D496901D81316E008276D7 /* RowAdapterTests.swift in Sources */,
566A8425204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */,
@@ -3439,6 +3592,7 @@
AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */,
AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */,
AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */,
563B8FC824A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
AAA4DC7A230F1E0600C74B15 /* QueryInterfaceRequest.swift in Sources */,
AAA4DC7B230F1E0600C74B15 /* TableRecord+QueryInterfaceRequest.swift in Sources */,
AAA4DC7C230F1E0600C74B15 /* SQLExpression.swift in Sources */,
@@ -3472,6 +3626,7 @@
AAA4DC98230F1E0600C74B15 /* FTS5Tokenizer.swift in Sources */,
AAA4DC99230F1E0600C74B15 /* BelongsToAssociation.swift in Sources */,
AAA4DC9A230F1E0600C74B15 /* FTS5TokenizerDescriptor.swift in Sources */,
563B8FB824A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
AAA4DC9B230F1E0600C74B15 /* SerializedDatabase.swift in Sources */,
AAA4DC9C230F1E0600C74B15 /* DatabaseSnapshot.swift in Sources */,
AAA4DC9D230F1E0600C74B15 /* SQLExpressible.swift in Sources */,
@@ -3491,6 +3646,7 @@
AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */,
AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */,
AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */,
563B8FAF24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
AAA4DCAC230F1E0600C74B15 /* SQLGenerationContext.swift in Sources */,
AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */,
AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */,
@@ -3569,6 +3725,7 @@
files = (
AAA4DD0B230F262000C74B15 /* ValueObservationReadonlyTests.swift in Sources */,
AAA4DD0C230F262000C74B15 /* RecordPersistenceConflictPolicy.swift in Sources */,
56419C6624A5199B004967E1 /* Map.swift in Sources */,
AAA4DD0D230F262000C74B15 /* Record+QueryInterfaceRequestTests.swift in Sources */,
AAA4DD0E230F262000C74B15 /* RowAdapterTests.swift in Sources */,
AAA4DD0F230F262000C74B15 /* DatabaseCursorTests.swift in Sources */,
@@ -3596,6 +3753,7 @@
AAA4DD23230F262000C74B15 /* FoundationNSNullTests.swift in Sources */,
AAA4DD24230F262000C74B15 /* DatabasePoolCollationTests.swift in Sources */,
AAA4DD25230F262000C74B15 /* RecordPrimaryKeySingleTests.swift in Sources */,
56419C7724A519A4004967E1 /* ValueObservationPublisherTests.swift in Sources */,
AAA4DD26230F262000C74B15 /* DatabaseWriterTests.swift in Sources */,
AAA4DD27230F262000C74B15 /* DatabasePoolFunctionTests.swift in Sources */,
AAA4DD28230F262000C74B15 /* ValueObservationCountTests.swift in Sources */,
@@ -3623,6 +3781,7 @@
56E4F7F02392E2D000A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */,
561CFA9A2376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */,
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 */,
@@ -3637,18 +3796,21 @@
AAA4DD4A230F262000C74B15 /* AssociationBelongsToSQLTests.swift in Sources */,
AAA4DD4B230F262000C74B15 /* FTS5CustomTokenizerTests.swift in Sources */,
AAA4DD4C230F262000C74B15 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
56419C6524A5199B004967E1 /* Prefix.swift in Sources */,
AAA4DD4D230F262000C74B15 /* DatabasePoolReadOnlyTests.swift in Sources */,
56677C17241D14450050755D /* FailableTestCase.swift in Sources */,
56677C17241D14450050755D /* FailureTestCase.swift in Sources */,
AAA4DD4E230F262000C74B15 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
AAA4DD4F230F262000C74B15 /* TruncateOptimizationTests.swift in Sources */,
5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
AAA4DD50230F262000C74B15 /* FoundationNSURLTests.swift in Sources */,
AAA4DD51230F262000C74B15 /* FoundationURLTests.swift in Sources */,
56419C6224A5199B004967E1 /* NextOne.swift in Sources */,
AAA4DD53230F262000C74B15 /* DatabaseValueConversionErrorTests.swift in Sources */,
AAA4DD54230F262000C74B15 /* AssociationHasOneSQLDerivationTests.swift in Sources */,
AAA4DD55230F262000C74B15 /* AssociationHasManyThroughSQLTests.swift in Sources */,
AAA4DD56230F262000C74B15 /* ResultCodeTests.swift in Sources */,
AAA4DD57230F262000C74B15 /* DataMemoryTests.swift in Sources */,
56419C6324A5199B004967E1 /* Next.swift in Sources */,
AAA4DD58230F262000C74B15 /* ColumnExpressionTests.swift in Sources */,
AAA4DD59230F262000C74B15 /* ValueObservationRecordTests.swift in Sources */,
AAA4DD5A230F262000C74B15 /* EncryptionTests.swift in Sources */,
@@ -3657,6 +3819,7 @@
AAA4DD5D230F262000C74B15 /* RecordCopyTests.swift in Sources */,
AAA4DD5E230F262000C74B15 /* SQLLiteralTests.swift in Sources */,
AAA4DD5F230F262000C74B15 /* FTS5PatternTests.swift in Sources */,
56419C7524A519A4004967E1 /* Support.swift in Sources */,
AAA4DD60230F262000C74B15 /* PersistableRecordTests.swift in Sources */,
AAA4DD61230F262000C74B15 /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
561CFA9E2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */,
@@ -3667,6 +3830,7 @@
AAA4DD66230F262000C74B15 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */,
AAA4DD67230F262000C74B15 /* ColumnInfoTests.swift in Sources */,
AAA4DD68230F262000C74B15 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
56419C7D24A51A3A004967E1 /* RecordingError.swift in Sources */,
AAA4DD69230F262000C74B15 /* DatabasePoolConcurrencyTests.swift in Sources */,
AAA4DD6A230F262000C74B15 /* TransactionObserverTests.swift in Sources */,
AAA4DD6B230F262000C74B15 /* FoundationDateTests.swift in Sources */,
@@ -3677,12 +3841,14 @@
AAA4DD70230F262000C74B15 /* ValueObservationFetchTests.swift in Sources */,
AAA4DD71230F262000C74B15 /* FilterCursorTests.swift in Sources */,
AAA4DD73230F262000C74B15 /* FetchableRecordDecodableTests.swift in Sources */,
56419C6724A5199B004967E1 /* Inverted.swift in Sources */,
AAA4DD74230F262000C74B15 /* AssociationPrefetchingObservationTests.swift in Sources */,
AAA4DD75230F262000C74B15 /* MutablePersistableRecordChangesTests.swift in Sources */,
AAA4DD76230F262000C74B15 /* FTS5WrapperTokenizerTests.swift in Sources */,
AAA4DD77230F262000C74B15 /* TableRecordTests.swift in Sources */,
AAA4DD78230F262000C74B15 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */,
56419C6124A5199B004967E1 /* Finished.swift in Sources */,
AAA4DD79230F262000C74B15 /* RecordSubClassTests.swift in Sources */,
AAA4DD7A230F262000C74B15 /* DatabaseValueTests.swift in Sources */,
AAA4DD7B230F262000C74B15 /* DatabaseQueueReadOnlyTests.swift in Sources */,
@@ -3699,6 +3865,7 @@
AAA4DD86230F262000C74B15 /* SQLExpressionLiteralTests.swift in Sources */,
AAA4DD87230F262000C74B15 /* DropFirstCursorTests.swift in Sources */,
56915784231BF28B00E1D237 /* PoolTests.swift in Sources */,
56419C7624A519A4004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */,
AAA4DD88230F262000C74B15 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
AAA4DD89230F262000C74B15 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
563B8FA3249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */,
@@ -3710,8 +3877,10 @@
AAA4DD8E230F262000C74B15 /* RecordEditedTests.swift in Sources */,
AAA4DD8F230F262000C74B15 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
AAA4DD90230F262000C74B15 /* AssociationBelongsToFetchableRecordTests.swift in Sources */,
56419C7424A519A4004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */,
AAA4DD91230F262000C74B15 /* AssociationAggregateTests.swift in Sources */,
AAA4DD92230F262000C74B15 /* DatabasePoolSchemaCacheTests.swift in Sources */,
56419C6824A5199B004967E1 /* PublisherExpectation.swift in Sources */,
AAA4DD93230F262000C74B15 /* AssociationRowScopeSearchTests.swift in Sources */,
56677C0F241CD0D00050755D /* ValueObservationRecorder.swift in Sources */,
AAA4DD94230F262000C74B15 /* FTS4TableBuilderTests.swift in Sources */,
@@ -3762,9 +3931,11 @@
AAA4DDC2230F262000C74B15 /* AssociationParallelSQLTests.swift in Sources */,
AAA4DDC3230F262000C74B15 /* ValueObservationTests.swift in Sources */,
AAA4DDC4230F262000C74B15 /* RecordUniqueIndexTests.swift in Sources */,
56419C7C24A51A3A004967E1 /* Recorder.swift in Sources */,
AAA4DDC5230F262000C74B15 /* CGFloatTests.swift in Sources */,
AAA4DDC6230F262000C74B15 /* DatabaseRegionTests.swift in Sources */,
AAA4DDC7230F262000C74B15 /* FTS5RecordTests.swift in Sources */,
56419C6424A5199B004967E1 /* Recording.swift in Sources */,
AAA4DDC8230F262000C74B15 /* DatabaseQueueTests.swift in Sources */,
AAA4DDC9230F262000C74B15 /* MapCursorTests.swift in Sources */,
AAA4DDCA230F262000C74B15 /* DatabaseSnapshotTests.swift in Sources */,
@@ -3779,6 +3950,7 @@
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */,
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */,
@@ -3812,6 +3984,7 @@
566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
@@ -3831,6 +4004,7 @@
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */,
+3
View File
@@ -53,4 +53,7 @@
<FileRef
location = "group:Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj">
</FileRef>
<FileRef
location = "group:Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj">
</FileRef>
</Workspace>
+5
View File
@@ -0,0 +1,5 @@
#if canImport(Combine)
/// A namespace for database Combine publishers.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public enum DatabasePublishers { }
#endif
+84
View File
@@ -1,3 +1,6 @@
#if canImport(Combine)
import Combine
#endif
import Dispatch
/// The protocol for all types that can fetch values from a database.
@@ -289,6 +292,87 @@ extension DatabaseReader {
}
}
#if canImport(Combine)
extension DatabaseReader {
// MARK: - Publishing Database Values
/// Returns a Publisher that asynchronously completes with a fetched value.
///
/// // DatabasePublishers.Read<[Player]>
/// let players = dbQueue.readPublisher { db in
/// try Player.fetchAll(db)
/// }
///
/// Its value and completion are emitted on the main dispatch queue.
///
/// - parameter value: A closure which accesses the database.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func readPublisher<Output>(
value: @escaping (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
{
readPublisher(receiveOn: DispatchQueue.main, value: value)
}
/// Returns a Publisher that asynchronously completes with a fetched value.
///
/// // DatabasePublishers.Read<[Player]>
/// let players = dbQueue.readPublisher(
/// receiveOn: DispatchQueue.global(),
/// value: { db in try Player.fetchAll(db) })
///
/// Its value and completion are emitted on `scheduler`.
///
/// - parameter scheduler: A Combine Scheduler.
/// - parameter value: A closure which accesses the database.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func readPublisher<S, Output>(
receiveOn scheduler: S,
value: @escaping (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
where S: Scheduler
{
Deferred {
Future { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
}
}
.receiveValues(on: scheduler)
.eraseToReadPublisher()
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
/// A publisher that reads a value from the database. It publishes exactly
/// one element, or an error.
///
/// See:
///
/// - `DatabaseReader.readPublisher(receiveOn:value:)`.
/// - `DatabaseReader.readPublisher(value:)`.
public struct Read<Output>: Publisher {
public typealias Output = Output
public typealias Failure = Error
fileprivate let upstream: AnyPublisher<Output, Error>
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
upstream.receive(subscriber: subscriber)
}
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension Publisher where Failure == Error {
fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read<Output> {
.init(upstream: eraseToAnyPublisher())
}
}
#endif
extension DatabaseReader {
// MARK: - Value Observation Support
+149
View File
@@ -1,3 +1,8 @@
#if canImport(Combine)
import Combine
#endif
import Foundation
/// DatabaseRegionObservation tracks changes in the results of database
/// requests, and notifies each database transaction whenever the
/// database changes.
@@ -94,6 +99,24 @@ extension DatabaseRegionObservation {
}
}
#if canImport(Combine)
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension DatabaseRegionObservation {
// MARK: - Publishing Impactful Transactions
/// Returns a publisher that tracks changes in a database region.
///
/// It emits database connections on a protected dispatch queue.
///
/// Error completion, if any, is only emitted, synchronously,
/// on subscription.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func publisher(in writer: DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
return DatabasePublishers.DatabaseRegion(self, in: writer)
}
}
#endif
private class DatabaseRegionObserver: TransactionObserver {
let region: DatabaseRegion
let onChange: (Database) -> Void
@@ -126,3 +149,129 @@ private class DatabaseRegionObserver: TransactionObserver {
isChanged = false
}
}
#if canImport(Combine)
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
/// A publisher that tracks changes in a database region.
///
/// See `DatabaseRegionObservation.publisher(in:)`.
public struct DatabaseRegion: Publisher {
public typealias Output = Database
public typealias Failure = Error
let writer: DatabaseWriter
let observation: DatabaseRegionObservation
init(_ observation: DatabaseRegionObservation, in writer: DatabaseWriter) {
self.writer = writer
self.observation = observation
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
let subscription = DatabaseRegionSubscription(
writer: writer,
observation: observation,
downstream: subscriber)
subscriber.receive(subscription: subscription)
}
}
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription
where Downstream.Failure == Error, Downstream.Input == Database
{
private struct WaitingForDemand {
let downstream: Downstream
let writer: DatabaseWriter
let observation: DatabaseRegionObservation
}
private struct Observing {
let downstream: Downstream
let writer: DatabaseWriter // Retain writer until subscription is finished
var remainingDemand: Subscribers.Demand
}
private enum State {
// Waiting for demand, not observing the database.
case waitingForDemand(WaitingForDemand)
// Observing the database.
case observing(Observing)
// Completed or cancelled, not observing the database.
case finished
}
// Observer is not stored in self.state because we must enter the
// .observing state *before* the observation starts.
private var observer: TransactionObserver?
private var state: State
private var lock = NSRecursiveLock() // Allow re-entrancy
init(
writer: DatabaseWriter,
observation: DatabaseRegionObservation,
downstream: Downstream)
{
state = .waitingForDemand(WaitingForDemand(
downstream: downstream,
writer: writer,
observation: observation))
}
func request(_ demand: Subscribers.Demand) {
lock.synchronized {
switch state {
case let .waitingForDemand(info):
guard demand > 0 else {
return
}
do {
state = .observing(Observing(
downstream: info.downstream,
writer: info.writer,
remainingDemand: demand))
observer = try info.observation.start(
in: info.writer,
onChange: { [weak self] in self?.receive($0) })
} catch {
state = .finished
info.downstream.receive(completion: .failure(error))
}
case var .observing(info):
info.remainingDemand += demand
state = .observing(info)
case .finished:
break
}
}
}
func cancel() {
lock.synchronized {
observer = nil
state = .finished
}
}
private func receive(_ value: Database) {
lock.synchronized {
if case let .observing(info) = state,
info.remainingDemand > .none
{
let additionalDemand = info.downstream.receive(value)
if case var .observing(info) = state {
info.remainingDemand += additionalDemand
info.remainingDemand -= 1
state = .observing(info)
}
}
}
}
}
}
#endif
+155
View File
@@ -1,3 +1,6 @@
#if canImport(Combine)
import Combine
#endif
import Dispatch
/// The protocol for all types that can update a database.
@@ -357,6 +360,158 @@ extension DatabaseWriter {
}
}
#if canImport(Combine)
extension DatabaseWriter {
// MARK: - Publishing Database Updates
/// Returns a Publisher that asynchronously writes into the database.
///
/// // DatabasePublishers.Write<Int>
/// let newPlayerCount = dbQueue.writePublisher { db -> Int in
/// try Player(...).insert(db)
/// return try Player.fetchCount(db)
/// }
///
/// Its value and completion are emitted on the main dispatch queue.
///
/// - parameter updates: A closure which writes in the database.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func writePublisher<Output>(
updates: @escaping (Database) throws -> Output)
-> DatabasePublishers.Write<Output>
{
writePublisher(receiveOn: DispatchQueue.main, updates: updates)
}
/// Returns a Publisher that asynchronously writes into the database.
///
/// // DatabasePublishers.Write<Int>
/// let newPlayerCount = dbQueue.writePublisher(
/// receiveOn: DispatchQueue.global(),
/// updates: { db -> Int in
/// try Player(...).insert(db)
/// return try Player.fetchCount(db)
/// })
///
/// Its value and completion are emitted on `scheduler`.
///
/// - parameter scheduler: A Combine Scheduler.
/// - parameter updates: A closure which writes in the database.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func writePublisher<S, Output>(
receiveOn scheduler: S,
updates: @escaping (Database) throws -> Output)
-> DatabasePublishers.Write<Output>
where S: Scheduler
{
OnDemandFuture({ fulfill in
self.asyncWrite(updates, completion: { _, result in
fulfill(result)
})
})
// We don't want users to process emitted values on a
// database dispatch queue.
.receiveValues(on: scheduler)
.eraseToWritePublisher()
}
/// Returns a Publisher that asynchronously writes into the database.
///
/// // DatabasePublishers.Write<Int>
/// let newPlayerCount = dbQueue.writePublisher(
/// updates: { db in try Player(...).insert(db) }
/// thenRead: { db, _ in try Player.fetchCount(db) })
///
/// Its value and completion are emitted on the main dispatch queue.
///
/// - parameter updates: A closure which writes in the database.
/// - parameter value: A closure which reads from the database.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func writePublisher<T, Output>(
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
-> DatabasePublishers.Write<Output>
{
writePublisher(receiveOn: DispatchQueue.main, updates: updates, thenRead: value)
}
/// Returns a Publisher that asynchronously writes into the database.
///
/// // DatabasePublishers.Write<Int>
/// let newPlayerCount = dbQueue.writePublisher(
/// receiveOn: DispatchQueue.global(),
/// updates: { db in try Player(...).insert(db) }
/// thenRead: { db, _ in try Player.fetchCount(db) })
///
/// Its value and completion are emitted on `scheduler`.
///
/// - parameter scheduler: A Combine Scheduler.
/// - parameter updates: A closure which writes in the database.
/// - parameter value: A closure which reads from the database.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func writePublisher<S, T, Output>(
receiveOn scheduler: S,
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
-> DatabasePublishers.Write<Output>
where S: Scheduler
{
OnDemandFuture({ fulfill in
self.asyncWriteWithoutTransaction { db in
var updatesValue: T?
do {
try db.inTransaction {
updatesValue = try updates(db)
return .commit
}
} catch {
fulfill(.failure(error))
return
}
self.spawnConcurrentRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
}
}
})
// We don't want users to process emitted values on a
// database dispatch queue.
.receiveValues(on: scheduler)
.eraseToWritePublisher()
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
/// A publisher that writes into the database. It publishes exactly
/// one element, or an error.
///
/// See:
///
/// - `DatabaseReader.writePublisher(updates:)`.
/// - `DatabaseReader.writePublisher(updates:thenRead:)`.
/// - `DatabaseReader.writePublisher(receiveOn:updates:)`.
/// - `DatabaseReader.writePublisher(receiveOn:updates:thenRead:)`.
public struct Write<Output>: Publisher {
public typealias Output = Output
public typealias Failure = Error
fileprivate let upstream: AnyPublisher<Output, Error>
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
upstream.receive(subscriber: subscriber)
}
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension Publisher where Failure == Error {
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
.init(upstream: eraseToAnyPublisher())
}
}
#endif
/// A future database value, returned by the DatabaseWriter.concurrentRead(_:)
/// method.
///
+117
View File
@@ -0,0 +1,117 @@
#if canImport(Combine)
import Combine
import Foundation
/// A publisher that eventually produces one value and then finishes or fails.
///
/// Like a Combine.Future wrapped in Combine.Deferred, OnDemandFuture starts
/// producing its value on demand.
///
/// Unlike Combine.Future wrapped in Combine.Deferred, OnDemandFuture guarantees
/// that it starts producing its value on demand, **synchronously**, and that
/// it produces its value on promise completion, **synchronously**.
///
/// Both two extra scheduling guarantees are used by GRDB in order to be
/// able to spawn concurrent database reads right from the database writer
/// queue, and fulfill GRDB preconditions.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
struct OnDemandFuture<Output, Failure: Error>: Publisher {
typealias Promise = (Result<Output, Failure>) -> Void
typealias Output = Output
typealias Failure = Failure
fileprivate let attemptToFulfill: (@escaping Promise) -> Void
init(_ attemptToFulfill: @escaping (@escaping Promise) -> Void) {
self.attemptToFulfill = attemptToFulfill
}
/// :nodoc:
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
let subscription = OnDemandFutureSubscription(
attemptToFulfill: attemptToFulfill,
downstream: subscriber)
subscriber.receive(subscription: subscription)
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription {
typealias Promise = (Result<Downstream.Input, Downstream.Failure>) -> Void
private enum State {
case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void)
case waitingForFulfillment(downstream: Downstream)
case finished
}
private var state: State
private let lock = NSRecursiveLock() // Allow re-entrancy
init(
attemptToFulfill: @escaping (@escaping Promise) -> Void,
downstream: Downstream)
{
self.state = .waitingForDemand(downstream: downstream, attemptToFulfill: attemptToFulfill)
}
func request(_ demand: Subscribers.Demand) {
lock.synchronized {
switch state {
case let .waitingForDemand(downstream: downstream, attemptToFulfill: attemptToFulfill):
guard demand > 0 else {
return
}
state = .waitingForFulfillment(downstream: downstream)
attemptToFulfill { result in
switch result {
case let .success(value):
self.receive(value)
case let .failure(error):
self.receive(completion: .failure(error))
}
}
case .waitingForFulfillment, .finished:
break
}
}
}
func cancel() {
lock.synchronized {
state = .finished
}
}
private func receive(_ value: Downstream.Input) {
lock.synchronized { sideEffect in
switch state {
case let .waitingForFulfillment(downstream: downstream):
state = .finished
sideEffect = {
_ = downstream.receive(value)
downstream.receive(completion: .finished)
}
case .waitingForDemand, .finished:
break
}
}
}
private func receive(completion: Subscribers.Completion<Downstream.Failure>) {
lock.synchronized { sideEffect in
switch state {
case let .waitingForFulfillment(downstream: downstream):
state = .finished
sideEffect = {
downstream.receive(completion: completion)
}
case .waitingForDemand, .finished:
break
}
}
}
}
#endif
+210
View File
@@ -0,0 +1,210 @@
#if canImport(Combine)
import Combine
import Foundation
/// A publisher that delivers values to its downstream subscriber on a
/// specific scheduler.
///
/// Unlike Combine's Publishers.ReceiveOn, ReceiveValuesOn only re-schedule
/// values and completion. It does not re-schedule subscription.
///
/// This scheduling guarantee is used by GRDB in order to be able
/// to make promises on the scheduling of database values without surprising
/// the users as in https://forums.swift.org/t/28631.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
struct ReceiveValuesOn<Upstream: Publisher, Context: Scheduler>: Publisher {
typealias Output = Upstream.Output
typealias Failure = Upstream.Failure
fileprivate let upstream: Upstream
fileprivate let context: Context
fileprivate let options: Context.SchedulerOptions?
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
let subscription = ReceiveValuesOnSubscription(
upstream: upstream,
context: context,
options: options,
downstream: subscriber)
subscriber.receive(subscription: subscription)
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
private class ReceiveValuesOnSubscription<Upstream, Context, Downstream>: Subscription, Subscriber
where
Upstream: Publisher,
Context: Scheduler,
Downstream: Subscriber,
Upstream.Failure == Downstream.Failure,
Upstream.Output == Downstream.Input
{
private struct Target {
let context: Context
let options: Context.SchedulerOptions?
let downstream: Downstream
}
private enum State {
case waitingForRequest(Upstream, Target)
case waitingForSubscription(Target, Subscribers.Demand)
case subscribed(Target, Subscription)
case finished
}
private var state: State
private let lock = NSRecursiveLock()
init(
upstream: Upstream,
context: Context,
options: Context.SchedulerOptions?,
downstream: Downstream)
{
let target = Target(context: context, options: options, downstream: downstream)
self.state = .waitingForRequest(upstream, target)
}
// MARK: Subscription
func request(_ demand: Subscribers.Demand) {
lock.synchronized { sideEffect in
switch state {
case let .waitingForRequest(upstream, target):
state = .waitingForSubscription(target, demand)
sideEffect = {
upstream.receive(subscriber: self)
}
case let .waitingForSubscription(target, currentDemand):
state = .waitingForSubscription(target, demand + currentDemand)
case let .subscribed(_, subcription):
sideEffect = {
subcription.request(demand)
}
case .finished:
break
}
}
}
func cancel() {
lock.synchronized { sideEffect in
switch state {
case .waitingForRequest, .waitingForSubscription:
state = .finished
case let .subscribed(_, subcription):
state = .finished
sideEffect = {
subcription.cancel()
}
case .finished:
break
}
}
}
// MARK: Subscriber
func receive(subscription: Subscription) {
lock.synchronized { sideEffect in
switch state {
case let .waitingForSubscription(target, currentDemand):
state = .subscribed(target, subscription)
sideEffect = {
subscription.request(currentDemand)
}
case .waitingForRequest, .subscribed, .finished:
preconditionFailure()
}
}
}
func receive(_ input: Upstream.Output) -> Subscribers.Demand {
lock.synchronized { sideEffect in
switch state {
case let .subscribed(target, _):
sideEffect = {
target.context.schedule(options: target.options) {
self._receive(input)
}
}
case .waitingForRequest, .waitingForSubscription, .finished:
break
}
}
// TODO: what problem are we creating by returning .unlimited and
// ignoring downstream's result?
//
// `Publisher.receive(on:options:)` does not document its behavior
// regarding backpressure.
return .unlimited
}
func receive(completion: Subscribers.Completion<Upstream.Failure>) {
lock.synchronized { sideEffect in
switch state {
case .waitingForRequest, .waitingForSubscription:
break
case let .subscribed(target, _):
sideEffect = {
target.context.schedule(options: target.options) {
self._receive(completion: completion)
}
}
case .finished:
break
}
}
}
private func _receive(_ input: Upstream.Output) {
lock.synchronized { sideEffect in
switch state {
case .waitingForRequest, .waitingForSubscription:
break
case let .subscribed(target, _):
// TODO: don't ignore demand
sideEffect = {
_ = target.downstream.receive(input)
}
case .finished:
break
}
}
}
private func _receive(completion: Subscribers.Completion<Upstream.Failure>) {
lock.synchronized { sideEffect in
switch state {
case .waitingForRequest, .waitingForSubscription:
break
case let .subscribed(target, _):
state = .finished
sideEffect = {
target.downstream.receive(completion: completion)
}
case .finished:
break
}
}
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension Publisher {
/// Specifies the scheduler on which to receive values from the publisher
///
/// The difference with the stock `receive(on:options:)` Combine method is
/// that only values and completion are re-scheduled. Subscriptions are not.
func receiveValues<S: Scheduler>(on scheduler: S, options: S.SchedulerOptions? = nil) -> ReceiveValuesOn<Self, S> {
return ReceiveValuesOn(upstream: self, context: scheduler, options: options)
}
}
#endif
+41
View File
@@ -170,3 +170,44 @@ func concat<T>(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? {
}
}
}
extension NSRecursiveLock {
@inlinable
@inline(__always)
func synchronized<T>(
_ message: @autoclosure () -> String = #function,
_ block: () throws -> T)
rethrows -> T
{
lock()
defer { unlock() }
return try block()
}
// // Verbose version which helps understanding locking bugs
// func synchronized<T>(_ message: @autoclosure () -> String = "", _ block: () throws -> T) rethrows -> T {
// let queueName = String(validatingUTF8: __dispatch_queue_get_label(nil))
// print("\(queueName ?? "n/d"): \(message()) acquiring \(self)")
// lock()
// print("\(queueName ?? "n/d"): \(message()) acquired \(self)")
// defer {
// print("\(queueName ?? "n/d"): \(message()) releasing \(self)")
// unlock()
// print("\(queueName ?? "n/d"): \(message()) released \(self)")
// }
// return try block()
// }
/// Performs the side effect outside of the synchronized block. This allows
/// avoiding deadlocks, when the side effect feedbacks.
@inlinable
@inline(__always)
func synchronized(
_ message: @autoclosure () -> String = #function,
_ block: (inout (() -> Void)?) -> Void)
{
var sideEffect: (() -> Void)?
synchronized(message()) { block(&sideEffect) }
sideEffect?()
}
}
@@ -1,4 +1,8 @@
#if canImport(Combine)
import Combine
#endif
import Dispatch
import Foundation
/// ValueObservation tracks changes in the results of database requests, and
/// notifies fresh values whenever the database changes.
@@ -193,6 +197,214 @@ extension ValueObservation: Refinable {
}
}
#if canImport(Combine)
extension ValueObservation {
// MARK: - Publishing Observed Values
/// Creates a publisher which tracks changes in database values.
///
/// For example:
///
/// let observation = ValueObservation.tracking { db in
/// try Player.fetchAll(db)
/// }
/// let cancellable = observation
/// .publisher(in: dbQueue)
/// .sink(
/// receiveCompletion: { completion in ... },
/// receiveValue: { players: [Player] in
/// print("fresh players: \(players)")
/// })
///
/// By default, fresh values are dispatched asynchronously on the
/// main queue. You can change this behavior by by providing a scheduler.
///
/// For example, `.immediate` notifies all values on the main queue as well,
/// and the first one is immediately notified when the publisher
/// is subscribed:
///
/// let cancellable = observation
/// .publisher(
/// in: dbQueue,
/// scheduling: .immediate) // <-
/// .sink(
/// receiveCompletion: { completion in ... },
/// receiveValue: { players: [Player] in
/// print("fresh players: \(players)")
/// })
/// // <- here "fresh players" is already printed.
///
/// Note that the `.immediate` scheduler requires that the publisher is
/// subscribed from the main thread. It raises a fatal error otherwise.
///
/// - parameter reader: A DatabaseReader.
/// - parameter scheduler: A Scheduler. By default, fresh values are
/// dispatched asynchronously on the main queue.
/// - returns: A Combine publisher
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public func publisher(
in reader: DatabaseReader,
scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main))
-> DatabasePublishers.Value<Reducer.Value>
{
return DatabasePublishers.Value(self, in: reader, scheduling: scheduler)
}
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension DatabasePublishers {
fileprivate typealias Start<T> = (
_ onError: @escaping (Error) -> Void,
_ onChange: @escaping (T) -> Void) -> DatabaseCancellable
/// A publisher that tracks changes in the database.
///
/// See `ValueObservation.publisher(in:scheduling:)`.
public struct Value<Output>: Publisher {
public typealias Failure = Error
private let start: Start<Output>
init<Reducer>(
_ observation: ValueObservation<Reducer>,
in reader: DatabaseReader,
scheduling scheduler: ValueObservationScheduler)
where Reducer.Value == Output
{
start = { [weak reader] (onError, onChange) in
guard let reader = reader else {
return AnyDatabaseCancellable(cancel: { })
}
return observation.start(
in: reader,
scheduling: scheduler,
onError: onError,
onChange: onChange)
}
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
let subscription = ValueSubscription(
start: start,
downstream: subscriber)
subscriber.receive(subscription: subscription)
}
}
private class ValueSubscription<Downstream: Subscriber>: Subscription
where Downstream.Failure == Error
{
private struct WaitingForDemand {
let downstream: Downstream
let start: Start<Downstream.Input>
}
private struct Observing {
let downstream: Downstream
var remainingDemand: Subscribers.Demand
}
private enum State {
/// Waiting for demand, not observing the database.
case waitingForDemand(WaitingForDemand)
/// Observing the database. Self.observer is not nil.
case observing(Observing)
/// Completed or cancelled, not observing the database.
case finished
}
// Cancellable is not stored in self.state because we must enter the
// .observing state *before* the observation starts, so that the user
// can change the state even before the cancellable is known.
private var cancellable: DatabaseCancellable?
private var state: State
private var lock = NSRecursiveLock() // Allow re-entrancy
init(
start: @escaping Start<Downstream.Input>,
downstream: Downstream)
{
state = .waitingForDemand(WaitingForDemand(
downstream: downstream,
start: start))
}
func request(_ demand: Subscribers.Demand) {
lock.synchronized {
switch state {
case let .waitingForDemand(info):
guard demand > 0 else {
return
}
state = .observing(Observing(
downstream: info.downstream,
remainingDemand: demand))
let cancellable = info.start(
{ [weak self] error in self?.receiveCompletion(.failure(error)) },
{ [weak self] value in self?.receive(value) })
// State may have been altered (error or cancellation)
switch state {
case .waitingForDemand:
preconditionFailure()
case .observing:
self.cancellable = cancellable
case .finished:
cancellable.cancel()
}
case var .observing(info):
info.remainingDemand += demand
state = .observing(info)
case .finished:
break
}
}
}
func cancel() {
lock.synchronized { sideEffect in
let cancellable = self.cancellable
self.cancellable = nil
self.state = .finished
sideEffect = {
cancellable?.cancel()
}
}
}
private func receive(_ value: Downstream.Input) {
lock.synchronized {
if case let .observing(info) = state,
info.remainingDemand > .none
{
let additionalDemand = info.downstream.receive(value)
if case var .observing(info) = state {
info.remainingDemand += additionalDemand
info.remainingDemand -= 1
state = .observing(info)
}
}
}
}
private func receiveCompletion(_ completion: Subscribers.Completion<Error>) {
lock.synchronized { sideEffect in
if case let .observing(info) = state {
cancellable = nil
state = .finished
sideEffect = {
info.downstream.receive(completion: completion)
}
}
}
}
}
}
#endif
extension ValueObservation where Reducer == ValueReducers.Auto {
// MARK: - Creating ValueObservation
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff. Show more