diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/GRDBDemoApp.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/GRDBDemoApp.swift index f52b183f4..a08232a76 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo/GRDBDemoApp.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/GRDBDemoApp.swift @@ -4,7 +4,7 @@ import SwiftUI struct GRDBDemoApp: App { var body: some Scene { WindowGroup { - PlayerNavigationView().appDatabase(.shared) + PlayersNavigationView().appDatabase(.shared) } } } diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon-Dark-1024×1024.png b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon-Dark-1024×1024.png index a3aca30da..d20dbec5c 100644 Binary files a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon-Dark-1024×1024.png and b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon-Dark-1024×1024.png differ diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerCreationSheet.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerCreationSheet.swift index 95508c221..c52634804 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerCreationSheet.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerCreationSheet.swift @@ -1,5 +1,6 @@ import SwiftUI +/// A view that creates a `Player`. Display it as a sheet. struct PlayerCreationSheet: View { @Environment(\.appDatabase) var appDatabase @Environment(\.dismiss) var dismiss diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerEditionView.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerEditionView.swift index a8ffabf40..0bbe76aa7 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerEditionView.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerEditionView.swift @@ -1,7 +1,6 @@ import SwiftUI struct PlayerEditionView: View { - @Environment(\.dismiss) var dismiss @Environment(\.isPresented) var isPresented @Environment(\.appDatabase) var appDatabase @State var form: PlayerForm diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerFormView.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerFormView.swift index d3b64687a..32172b020 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerFormView.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerFormView.swift @@ -1,5 +1,6 @@ import SwiftUI +/// A view that edits a `PlayerForm`. struct PlayerFormView: View { @Binding var form: PlayerForm @@ -38,6 +39,7 @@ struct PlayerFormView: View { } } +/// The model edited by `PlayerFormView`. struct PlayerForm { var name: String var score: Int? diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift index a380c0557..74dc501ec 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift @@ -2,6 +2,12 @@ import Foundation import Observation import GRDB +/// The observable model that drives the main navigation view. +/// +/// It observes the database in order to always display an up-to-date list +/// of players. +/// +/// This class is testable. See `PlayerListModelTests.swift`. @Observable @MainActor final class PlayerListModel { /// A player ordering enum Ordering { @@ -22,6 +28,8 @@ import GRDB private let appDatabase: AppDatabase @ObservationIgnored private var cancellable: AnyDatabaseCancellable? + // MARK: - Initialization + /// Creates a `PlayerListModel`. init(appDatabase: AppDatabase) { self.appDatabase = appDatabase @@ -29,6 +37,7 @@ import GRDB /// Start observing the database. func observePlayers() { + // We observe all players, sorted according to `ordering`. let observation = ValueObservation.tracking { [ordering] db in switch ordering { case .byName: @@ -38,6 +47,8 @@ import GRDB } } + // Start observing the database. + // Previous observation, if any, is cancelled. cancellable = observation.start(in: appDatabase.reader) { error in // Handle error } onChange: { [unowned self] players in @@ -45,21 +56,26 @@ import GRDB } } + // MARK: - Actions + + /// Delete players at specified indexes in `self.players`. func deletePlayers(at offsets: IndexSet) throws { let playerIds = offsets.compactMap { players[$0].id } try appDatabase.deletePlayers(ids: playerIds) } + /// Delete all players. func deleteAllPlayers() throws { try appDatabase.deleteAllPlayers() } + /// Refresh all players (by performing some random changes, for demo purpose). func refreshPlayers() async throws { try await appDatabase.refreshPlayers() } + /// Perform 50 refreshes in parallel, for demo purpose. func refreshPlayersManyTimes() async throws { - // Perform 50 refreshes in parallel try await withThrowingTaskGroup(of: Void.self) { group in for _ in 0..<50 { group.addTask { diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListView.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListView.swift index 1d4df467f..0f3316512 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListView.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListView.swift @@ -1,5 +1,6 @@ import SwiftUI +/// A view that displays a list of players. struct PlayerListView: View { @Bindable var model: PlayerListModel @@ -50,6 +51,8 @@ struct PlayerRow: View { @Environment(\.appDatabase) var appDatabase var body: some View { + // This technique makes it possible to create an observable object + // (PlayerListModel) from the SwiftUI environment. ContentView(appDatabase: appDatabase) } } @@ -64,8 +67,8 @@ struct PlayerRow: View { var body: some View { NavigationStack { PlayerListView(model: model) - .onAppear { model.observePlayers() } } + .onAppear { model.observePlayers() } } } diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerNavigationView.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayersNavigationView.swift similarity index 92% rename from Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerNavigationView.swift rename to Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayersNavigationView.swift index 8b4ce9bf8..b6e96ac2d 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerNavigationView.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayersNavigationView.swift @@ -1,9 +1,12 @@ import SwiftUI -struct PlayerNavigationView: View { +/// The main navigation view. +struct PlayersNavigationView: View { @Environment(\.appDatabase) var appDatabase var body: some View { + // This technique makes it possible to create an observable object + // (PlayerListModel) from the SwiftUI environment. ContentView(appDatabase: appDatabase) } } @@ -12,7 +15,7 @@ private struct ContentView: View { /// The model for the player list. @State var model: PlayerListModel - /// We'll need to leave edit mode in several occasions. + /// Tracks the edit mode of the player list. @State var editMode = EditMode.inactive /// Tracks the presentation of the player creation sheet. @@ -36,7 +39,7 @@ private struct ContentView: View { stopEditing() } .onChange(of: model.players.isEmpty) { - // Stop editing when last player is deleted. + // Stop editing when the last player is deleted. if model.players.isEmpty { stopEditing() } @@ -168,11 +171,11 @@ private struct ToggleOrderingButton: View { // MARK: - Previews #Preview("Populated") { - PlayerNavigationView() + PlayersNavigationView() .appDatabase(.random()) } #Preview("Empty") { - PlayerNavigationView() + PlayersNavigationView() .appDatabase(.empty()) } diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemoTests/PlayerListModelTests.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemoTests/PlayerListModelTests.swift new file mode 100644 index 000000000..ccba9208b --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemoTests/PlayerListModelTests.swift @@ -0,0 +1,85 @@ +import Testing +import GRDB +@testable import GRDBDemo + +struct PlayerListModelTests { + // MARK: - PlayerListModel.observePlayers tests + + @Test(.timeLimit(.minutes(1))) + @MainActor func observation_started_after_player_creation() async throws { + // Given a PlayerListModel on a database that contains a player + let (appDatabase, _) = try makeEmptyTestDatabase() + var player = Player(name: "Arthur", score: 1000) + try appDatabase.savePlayer(&player) + let model = PlayerListModel(appDatabase: appDatabase) + + // When we start observing the database + model.observePlayers() + + // Then the model eventually fetches the player. + // We poll because we do not know when the model will update its players. + await pollUntil { + model.players.isEmpty == false + } + #expect(model.players == [player]) + } + + @Test(.timeLimit(.minutes(1))) + @MainActor func observation_started_before_player_creation() async throws { + // Given a PlayerListModel that observes a empty database + let (appDatabase, _) = try makeEmptyTestDatabase() + let model = PlayerListModel(appDatabase: appDatabase) + model.observePlayers() + + // When we insert a player + var player = Player(name: "Arthur", score: 1000) + try appDatabase.savePlayer(&player) + + // Then the model eventually fetches the player. + // We poll because we do not know when the model will update its players. + await pollUntil { + model.players.isEmpty == false + } + #expect(model.players == [player]) + } + + @Test + @MainActor func test_deleteAllPlayers_deletes_players_in_the_database() async throws { + // Given a PlayerListModel on a database that contains a player + let (appDatabase, dbQueue) = try makeEmptyTestDatabase() + var player = Player(name: "Arthur", score: 1000) + try appDatabase.savePlayer(&player) + let model = PlayerListModel(appDatabase: appDatabase) + + // When we delete all players + try model.deleteAllPlayers() + + // Then the database is empty. + let playerCount = try await dbQueue.read { db in + try Player.fetchCount(db) + } + #expect(playerCount == 0) + } + + /// Returns an `AppDatabase`, and its underlying database connection. + private func makeEmptyTestDatabase() throws -> (AppDatabase, DatabaseQueue) { + let config = AppDatabase.makeConfiguration() + let dbQueue = try DatabaseQueue(configuration: config) + let appDatabase = try AppDatabase(dbQueue) + return (appDatabase, dbQueue) + } + + /// Convenience method that loops until a condition is met. + private func pollUntil(condition: @escaping @MainActor () async -> Bool) async { + await confirmation { confirmation in + while true { + if await condition() { + confirmation() + return + } else { + await Task.yield() + } + } + } + } +}