Cleanup and harmonize demo apps

This commit is contained in:
Gwendal Roué committed 2021-01-20 07:48:05 +01:00
1 parent 9628eaffb9
commit 8fe3d41d18
33 files changed
+127 -109

No files matched your search

@@ -137,6 +137,24 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
56185BC125B8047D00B9C30F /* Resources */ = {
isa = PBXGroup;
children = (
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */,
567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */,
567C3E752520BB650011F6E9 /* Localizable.stringsdict */,
);
path = Resources;
sourceTree = "<group>";
};
56185BC225B8048B00B9C30F /* Support */ = {
isa = PBXGroup;
children = (
567C3E222520B6DF0011F6E9 /* Info.plist */,
);
name = Support;
sourceTree = "<group>";
};
567C3E0D2520B6DE0011F6E9 = {
isa = PBXGroup;
children = (
@@ -158,17 +176,15 @@
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */ = {
isa = PBXGroup;
children = (
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */,
567C3E652520B7880011F6E9 /* AppDatabase.swift */,
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */,
567C3E542520B75C0011F6E9 /* Persistence.swift */,
567C3E532520B75C0011F6E9 /* Player.swift */,
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
56185BC125B8047D00B9C30F /* Resources */,
56185BC225B8048B00B9C30F /* Support */,
567C3E552520B75C0011F6E9 /* ViewModels */,
567C3E582520B75C0011F6E9 /* Views */,
567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */,
567C3E752520BB650011F6E9 /* Localizable.stringsdict */,
567C3E222520B6DF0011F6E9 /* Info.plist */,
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */,
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
);
path = GRDBCombineDemo;
sourceTree = "<group>";
@@ -6,14 +6,16 @@ import GRDB
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
struct AppDatabase {
private let dbWriter: DatabaseWriter
/// Creates an AppDatabase and make sure the database schema is ready.
/// Creates an `AppDatabase` from a database connection,
/// and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
}
/// The database connection
private let dbWriter: DatabaseWriter
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
@@ -48,14 +50,11 @@ struct AppDatabase {
}
}
// MARK: - Database Access
//
// This extension defines methods that fulfill application needs, both in terms
// of writes and reads.
// MARK: - Database Access: Writes
extension AppDatabase {
// MARK: Writes
/// Save (insert or update) a player.
/// Saves (inserts or updates) a player. When the method returns, the
/// player id is not nil.
func savePlayer(_ player: inout Player) throws {
try dbWriter.write { db in
try player.save(db)
@@ -88,10 +87,12 @@ extension AppDatabase {
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) {
@@ -118,14 +119,16 @@ extension AppDatabase {
try player.insert(db)
}
}
// MARK: Reads
}
// MARK: - Database Access: Reads
extension AppDatabase {
/// Returns a publisher that tracks changes in players ordered by name
func playersOrderedByNamePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByName().fetchAll)
.publisher(in: dbWriter)
.publisher(in: dbWriter, scheduling: .immediate)
.eraseToAnyPublisher()
}
@@ -133,7 +136,7 @@ extension AppDatabase {
func playersOrderedByScorePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
.publisher(in: dbWriter)
.publisher(in: dbWriter, scheduling: .immediate)
.eraseToAnyPublisher()
}
}
@@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
56185BBF25B8036100B9C30F /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BBE25B8036100B9C30F /* Persistence.swift */; };
56606D202355938A00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; };
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
56606D24235593AB00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; };
@@ -164,6 +165,7 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
56185BBE25B8036100B9C30F /* Persistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoWatchOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
568E5FC21E926430002582E0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = "<group>"; };
568E5FC41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
@@ -275,13 +277,14 @@
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
isa = PBXGroup;
children = (
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */,
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56185BBE25B8036100B9C30F /* Persistence.swift */,
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
56FE6F4F24A9114200711EDF /* ViewControllers */,
56FE6F2524A90CE400711EDF /* SceneDelegate.swift */,
56FE6F4E24A9112900711EDF /* Resources */,
56FE6F5124A9118000711EDF /* Support */,
56FE6F4F24A9114200711EDF /* ViewControllers */,
);
path = GRDBDemoiOS;
sourceTree = "<group>";
@@ -534,6 +537,7 @@
56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */,
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */,
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
56185BBF25B8036100B9C30F /* Persistence.swift in Sources */,
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */,
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */,
@@ -68,10 +68,8 @@
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<RemoteRunnable
runnableDebuggingMode = "2"
BundleIdentifier = "com.apple.Carousel"
RemotePath = "/GRDBDemoiOS">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
@@ -79,7 +77,7 @@
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</RemoteRunnable>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -87,10 +85,8 @@
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<RemoteRunnable
runnableDebuggingMode = "2"
BundleIdentifier = "com.apple.Carousel"
RemotePath = "/GRDBDemoiOS">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
@@ -98,16 +94,7 @@
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</RemoteRunnable>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
@@ -5,17 +5,16 @@ import GRDB
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
final class AppDatabase {
/// The shared AppDatabase
static var shared: 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)
/// Creates an `AppDatabase` from a database connection,
/// and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
}
/// The database connection
private let dbWriter: DatabaseWriter
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
@@ -50,37 +49,34 @@ final class AppDatabase {
}
}
// MARK: - Database Access
//
// This extension defines methods that fulfill application needs, both in terms
// of writes and reads.
// MARK: - Database Access: Writes
extension AppDatabase {
// MARK: Writes
/// Save (insert or update) a player.
/// Saves (inserts or updates) a player. When the method returns, the
/// player id is not nil.
func savePlayer(_ player: inout Player) throws {
try dbQueue.write { db in
try dbWriter.write { db in
try player.save(db)
}
}
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbQueue.write { db in
try dbWriter.write { db in
_ = try Player.deleteAll(db, keys: ids)
}
}
/// Delete all players
func deleteAllPlayers() throws {
try dbQueue.write { db in
try dbWriter.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
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
try createRandomPlayers(db)
@@ -90,10 +86,12 @@ extension AppDatabase {
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) {
@@ -106,7 +104,7 @@ extension AppDatabase {
/// Create random players if the database is empty.
func createRandomPlayersIfEmpty() throws {
try dbQueue.write { db in
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
try createRandomPlayers(db)
}
@@ -120,9 +118,11 @@ extension AppDatabase {
try player.insert(db)
}
}
// MARK: Reads
}
// MARK: - Database Access: Reads
extension AppDatabase {
/// Tracks changes in the number of players
func observePlayerCount(
onError: @escaping (Error) -> Void,
@@ -132,7 +132,7 @@ extension AppDatabase {
ValueObservation
.tracking(Player.fetchCount)
.start(
in: dbQueue,
in: dbWriter,
onError: onError,
onChange: onChange)
}
@@ -146,7 +146,7 @@ extension AppDatabase {
ValueObservation
.tracking(Player.all().orderedByName().fetchAll)
.start(
in: dbQueue,
in: dbWriter,
onError: onError,
onChange: onChange)
}
@@ -160,19 +160,8 @@ extension AppDatabase {
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
.start(
in: dbQueue,
in: dbWriter,
onError: onError,
onChange: onChange)
}
}
// 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,11 +1,8 @@
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
}
@@ -22,24 +19,4 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// 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
AppDatabase.shared = database
}
}
@@ -0,0 +1,42 @@
import GRDB
extension AppDatabase {
/// The shared `PlayerDatabase`
static let shared = makeShared()
private static func makeShared() -> AppDatabase {
do {
// Connect to a database on disk
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let url: URL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: url.path)
let appDatabase = try AppDatabase(dbPool)
// Populate the database if it is empty, for better demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
return appDatabase
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate.
//
// Typical reasons for an error here include:
// * The parent directory cannot be created, or disallows writing.
// * The database is not accessible, due to permissions or data protection when the device is locked.
// * The device is out of space.
// * The database could not be migrated to its latest schema version.
// Check the error message to determine what the actual problem was.
fatalError("Unresolved error \(error)")
}
}
/// Creates an empty in-memory database for test
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let dbQueue = DatabaseQueue()
return try! AppDatabase(dbQueue)
}
}
+5 -5
View File
@@ -16,13 +16,13 @@ The topics covered in this demo are:
**Files of interest:**
- [AppDelegate.swift](GRDBDemoiOS/AppDelegate.swift)
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../../README.md#database-queues) available for the whole application.
- [AppDatabase.swift](GRDBDemoiOS/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.
`AppDatabase` is the type that grants database access. 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.
- [Persistence.swift](GRDBDemoiOS/Persistence.swift)
This file instantiates various `AppDatabase` for the various projects needs: one database on disk for the application, and in-memory databases for tests.
- [Player.swift](GRDBDemoiOS/Player.swift)