From 3ce33e9e325d75a7909c66787e22c8ab72275324 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 21:40:52 +0700 Subject: [PATCH 1/3] fix(macos): keep each tab's edits and undo history, tell statements and app work of a lost session once each, and keep connections.json readable record by record --- .claude/rules/data-sync-storage.md | 3 + .../ChangeTracking/DataChangeManager.swift | 69 +++-- .../Core/ChangeTracking/PendingChanges.swift | 32 --- .../QueryExecutionCoordinator+Batches.swift | 5 +- .../QueryExecutionCoordinator+Helpers.swift | 43 ++- ...yExecutionCoordinator+MultiStatement.swift | 7 +- ...QueryExecutionCoordinator+Parameters.swift | 8 +- .../RowEditingCoordinator+Discard.swift | 4 - .../RowEditingCoordinator+SaveChanges.swift | 47 ++-- .../Coordinators/RowEditingCoordinator.swift | 44 +-- .../Core/DataWrite/CascadeDeletePreview.swift | 2 +- .../Access/DatabaseAccessBridge.swift | 11 +- .../Database/DatabaseManager+Metadata.swift | 4 +- .../DatabaseManager+OpenTransactions.swift | 4 +- .../DatabaseManager+ScopedDriver.swift | 61 +++-- .../TablePro/Core/Database/SessionLanes.swift | 38 ++- .../Core/Database/SessionStateLedger.swift | 9 + .../DatabaseSearch/DatabaseSearchReader.swift | 2 +- .../Core/Scripting/ScriptingSnapshot.swift | 5 +- .../MainSplitViewController.swift | 1 - .../Infrastructure/SessionStateFactory.swift | 5 - .../Infrastructure/WindowManager.swift | 2 +- .../Storage/ConnectionStoreIntegrity.swift | 5 + .../Storage/IntegrityStampedFileStore.swift | 251 ++++++++++++++++-- apple/TablePro/Models/Query/QueryTab.swift | 3 - .../Models/Query/QueryTabManager.swift | 1 - .../TablePro/Models/Query/QueryTabState.swift | 30 --- .../TablePro/Resources/Localizable.xcstrings | 6 + .../ViewModels/ServerDashboardViewModel.swift | 2 +- .../Views/Main/Child/DataTabGridAdapter.swift | 13 +- .../Views/Main/Child/DataTabSQLExporter.swift | 2 +- .../Main/Child/MainEditorContentView.swift | 3 +- .../MainContentCoordinator+ChangeGuard.swift | 3 - .../MainContentCoordinator+Explain.swift | 4 +- .../MainContentCoordinator+Favorites.swift | 2 +- .../MainContentCoordinator+GridModels.swift | 17 +- .../MainContentCoordinator+Protection.swift | 7 +- .../MainContentCoordinator+QueryHelpers.swift | 8 +- ...ainContentCoordinator+RenameAdoption.swift | 13 +- ...MainContentCoordinator+RowOperations.swift | 4 +- .../MainContentCoordinator+Share.swift | 2 +- .../MainContentCoordinator+TabClosing.swift | 5 +- .../MainContentCoordinator+TabEdits.swift | 173 ++++++++++++ .../MainContentCoordinator+TabSwitch.swift | 85 +----- ...ContentCoordinator+TableRowsMutation.swift | 3 +- ...nContentCoordinator+TableRowsRefresh.swift | 15 +- ...ainContentCoordinator+UnloadedValues.swift | 6 +- .../MainContentView+EventHandlers.swift | 2 +- .../MainContentView+Modifiers.swift | 1 - .../MainContentCommandActions+UndoState.swift | 33 ++- .../Views/Main/MainContentCoordinator.swift | 38 +-- .../TablePro/Views/Main/MainContentView.swift | 9 +- .../Core/AI/AIConnectionAccessGateTests.swift | 1 - .../DataChangeManagerExtendedTests.swift | 209 +++++---------- .../DataChangeModelsTests.swift | 49 ---- .../EditedRowChangeTrackingTests.swift | 19 +- .../FieldAbsenceTrackingTests.swift | 9 +- .../ChangeTracking/PendingChangesTests.swift | 23 -- .../UnloadedValueWriteTests.swift | 9 - .../FilterCommitRefusalTests.swift | 2 - .../Core/Coordinators/FilterRerunTests.swift | 1 - .../Coordinators/RunResultPlanTests.swift | 1 - ...angeStatementFactoryServerOwnedTests.swift | 9 +- .../CredentialLeaseRoutingTests.swift | 12 +- .../Core/Database/MultiConnectionTests.swift | 6 - .../PreConnectScriptConsentTests.swift | 1 - .../Core/Database/SessionLanesTests.swift | 73 +++-- .../Database/SessionRecoveryLoopTests.swift | 77 ++++-- .../SessionTransactionTrackerTests.swift | 4 +- .../CancelledExecutionOwnershipTests.swift | 1 - .../Tools/FocusQueryTabToolTests.swift | 1 - .../Scripting/ScriptingTabResultTests.swift | 43 +++ .../EditorTabConnectionMovePolicyTests.swift | 9 +- .../ConnectionWindowChromeTests.swift | 1 - .../Query/UnloadedValueReaderTests.swift | 27 ++ .../Services/RowPasteForeignTextTests.swift | 5 +- .../ConnectionStoreTagRemovalTests.swift | 203 ++++++++++++++ .../MCPWritePolicyMatrixTests.swift | 1 - .../Helpers/CoordinatorFixture.swift | 3 +- .../Models/QueryTabConnectionMoveTests.swift | 2 - ...MainWindowToolbarNativeContractTests.swift | 2 - .../ERDiagramSchemaEditsTests.swift | 2 - .../Views/DataGrid/RowVisualIndexTests.swift | 2 +- .../Views/Editor/FoldTabOwnershipTests.swift | 1 - .../Views/Main/AIChatInsertQueryTests.swift | 1 - .../Views/Main/CatalogChangeWindowTests.swift | 21 +- .../Views/Main/CellFilterApplyTests.swift | 12 +- .../Views/Main/ClearQueryResultsTests.swift | 1 - .../Main/CommandActionsBulkCloseTests.swift | 8 +- .../CoordinatorColumnVisibilityTests.swift | 1 - .../Main/CoordinatorEditorLoadTests.swift | 2 - .../Main/CoordinatorQueryRoutingTests.swift | 1 - .../Main/CoordinatorRowImportTests.swift | 1 - .../Main/CoordinatorTableListingTests.swift | 1 - .../Main/DataTabGridEditCommitTests.swift | 14 +- .../DatabaseSearchResultOpeningTests.swift | 1 - .../Main/ExplainAuthorizationTests.swift | 1 - .../Views/Main/ExtractTableNameTests.swift | 2 - .../Views/Main/FKNavigationTests.swift | 36 --- .../Views/Main/FetchAllQueryTaskTests.swift | 3 - .../FilterTypingBeforeFirstLoadTests.swift | 1 - .../Views/Main/GridReloadViewportTests.swift | 1 - .../Main/InspectorFieldEditStagingTests.swift | 1 - .../Views/Main/JoinBuilderOpeningTests.swift | 1 - ...inContentCoordinatorAutoRefreshTests.swift | 1 - ...nContentCoordinatorDisplayStateTests.swift | 7 +- .../MainContentCoordinatorLazyLoadTests.swift | 8 +- .../MainContentCoordinatorSortTests.swift | 4 - ...MainContentCoordinatorTabSwitchTests.swift | 132 +++------ ...ContentCoordinatorTableMetadataTests.swift | 2 - .../Main/MatchAnyUnsupportedFilterTests.swift | 1 - .../Main/MaterializedViewRowWriteTests.swift | 1 - .../Main/MultiConnectionNavigationTests.swift | 2 - .../Views/Main/OpenTableTabTests.swift | 20 -- .../Views/Main/ParkedEditSnapshotTests.swift | 199 -------------- ...luginBrowsedQueryTabEditabilityTests.swift | 1 - .../Main/QueryFailureReportingTests.swift | 5 +- .../Main/QueryParameterDetectionTests.swift | 1 - .../RedisDatabaseSelectionGateTests.swift | 1 - .../Views/Main/ResultPinningTests.swift | 1 - .../Main/ResultReplacementEditsTests.swift | 135 ++++++++++ .../Main/RowCountTaskLifecycleTests.swift | 1 - .../Views/Main/RowWriterWiringTests.swift | 8 +- .../Views/Main/SaveAttributionTests.swift | 65 ++++- .../Views/Main/SaveCompletionTests.swift | 30 ++- .../Main/SaveInFlightEditGateTests.swift | 1 - .../Views/Main/ScriptErrorResultTests.swift | 1 - .../Main/SeedBufferFromErrorResultTests.swift | 1 - .../Views/Main/TabCloseProtectionTests.swift | 32 +-- .../Views/Main/TabEditHistoryTests.swift | 165 ++++++++++++ .../Views/Main/TabQueryIsolationTests.swift | 1 - .../Main/TableLoadConfirmationTests.swift | 1 - .../TableLoadForeignKeyPrefetchTests.swift | 1 - .../Main/TableTabSchemaResolutionTests.swift | 2 - .../Main/UnloadedValueFirstLoadTests.swift | 1 - .../Main/UpdatableViewRowWriteTests.swift | 1 - .../Main/ValueFilterEditedRowTests.swift | 1 - .../Views/Main/ValueFilterReloadTests.swift | 1 - .../WindowCloseSaveEveryConnectionTests.swift | 14 +- .../Views/QuickSwitcherObjectKindTests.swift | 2 - .../FailedContainerSwitchCommandTests.swift | 1 - .../Structure/StructureSavePlanTests.swift | 1 - .../Views/SwitchContainerTests.swift | 1 - .../Views/SwitchDatabaseTests.swift | 3 - .../Views/SwitchSchemaTests.swift | 3 - .../VisibleContainerFollowingTests.swift | 7 +- 146 files changed, 1662 insertions(+), 1274 deletions(-) create mode 100644 apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabEdits.swift create mode 100644 apple/TableProTests/Core/Scripting/ScriptingTabResultTests.swift delete mode 100644 apple/TableProTests/Views/Main/ParkedEditSnapshotTests.swift create mode 100644 apple/TableProTests/Views/Main/ResultReplacementEditsTests.swift create mode 100644 apple/TableProTests/Views/Main/TabEditHistoryTests.swift diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index d6809a939f..76e7269ff1 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -181,6 +181,9 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | Approved sign-ins with this Mac's own credentials (Entra, AWS profile or SSO, Google ADC or OAuth, Kerberos, `~/.pgpass`), per connection, field values and destination digest | UserDefaults `com.TablePro.localCredentialApprovals`, plus `com.TablePro.localCredentialApprovalsMigrated` for the one-time approval of this Mac's rows; device-local, never synced | `ConnectionApprovalStore.localCredentials` | | Snowflake SSO and MFA tokens, per host and user. A bare account's `NAME.USER` item stays for 0.83.1, which reads only that key | Keychain, device-local | `SnowflakeTokenCache` | | Whether `connections.json` was ever given an integrity tag, so a deleted tag reads as modified | Keychain `com.TablePro.connectionStoreStamped.`, device-local | `ConnectionStoreIntegrity` | +| The last copy of `connections.json` and `credentialProfiles.json` that parsed, taken before each save with its tag, restored when the file no longer parses | `.backup` and `.backup.hmac` beside the file, device-local, never synced | `IntegrityStampedFileStore` | +| A `connections.json` or `credentialProfiles.json` that no longer parsed, set aside when its backup was restored; the next one replaces it | `.unreadable` beside the file, device-local, never synced | `IntegrityStampedFileStore` | +| Records this build cannot read from a file changed outside TablePro, which a save would otherwise sign; added to, never replaced | `.unreadable-records` beside the file, device-local, never synced | `IntegrityStampedFileStore` | | Whether Local only connections' secrets were copied to device-only items | UserDefaults `com.TablePro.localOnlySecretsKeptOnDevice`, device-local, never synced | `ConnectionStorage` | | iCloud Keychain copies of Local only secrets the keychain refused to remove, retried at launch | UserDefaults `com.TablePro.localOnlySyncedCopiesPendingRemoval`, device-local, never synced | `ConnectionStorage` | | Whether plugin secure fields moved out of `connections.json` into the Keychain, set only when every field moved and the save succeeded | UserDefaults `com.TablePro.pluginSecureFieldsMovedToKeychain`, device-local, never synced | `ConnectionStorage` | diff --git a/apple/TablePro/Core/ChangeTracking/DataChangeManager.swift b/apple/TablePro/Core/ChangeTracking/DataChangeManager.swift index 51793a5616..a42c579fe1 100644 --- a/apple/TablePro/Core/ChangeTracking/DataChangeManager.swift +++ b/apple/TablePro/Core/ChangeTracking/DataChangeManager.swift @@ -143,6 +143,7 @@ final class DataChangeManager: ObservableObject, ChangeManaging { // MARK: - Undo/Redo Properties + var undoManager: UndoManager? { undoManagerProvider?() } var canUndo: Bool { undoManagerProvider?()?.canUndo ?? false } var canRedo: Bool { undoManagerProvider?()?.canRedo ?? false } @@ -188,14 +189,16 @@ final class DataChangeManager: ObservableObject, ChangeManaging { columnTypeNames: [String: String] = [:], triggerReload: Bool = true ) { - self.tableName = tableName - self.schemaName = schemaName - self.columns = columns - self.primaryKeyColumns = primaryKeyColumns - self.databaseType = databaseType - self.generatedColumns = generatedColumns - self.rowMatchPolicy = rowMatchPolicy - self.columnTypeNames = columnTypeNames + describeTable( + tableName: tableName, + schemaName: schemaName, + columns: columns, + primaryKeyColumns: primaryKeyColumns, + databaseType: databaseType, + generatedColumns: generatedColumns, + rowMatchPolicy: rowMatchPolicy, + columnTypeNames: columnTypeNames + ) discardUndoHistory() objectWillChange.send() @@ -207,6 +210,27 @@ final class DataChangeManager: ObservableObject, ChangeManaging { } } + // What the staged edits are written against, set without touching them or the undo history. + func describeTable( + tableName: String, + schemaName: String?, + columns: [String], + primaryKeyColumns: [String], + databaseType: DatabaseType, + generatedColumns: Set, + rowMatchPolicy: RowMatchPolicy, + columnTypeNames: [String: String] + ) { + if self.tableName != tableName { self.tableName = tableName } + if self.schemaName != schemaName { self.schemaName = schemaName } + if self.columns != columns { self.columns = columns } + if self.primaryKeyColumns != primaryKeyColumns { self.primaryKeyColumns = primaryKeyColumns } + if self.databaseType != databaseType { self.databaseType = databaseType } + if self.generatedColumns != generatedColumns { self.generatedColumns = generatedColumns } + if self.rowMatchPolicy != rowMatchPolicy { self.rowMatchPolicy = rowMatchPolicy } + self.columnTypeNames = columnTypeNames + } + func setPrimaryKeyColumns(_ primaryKeyColumns: [String]) { self.primaryKeyColumns = primaryKeyColumns } @@ -979,35 +1003,6 @@ final class DataChangeManager: ObservableObject, ChangeManaging { reloadVersion += 1 } - // MARK: - Per-Tab State Management - - func saveState() -> TabChangeSnapshot { - pending.snapshot(primaryKeyColumns: primaryKeyColumns, columns: columns) - } - - func restoreState( - from state: TabChangeSnapshot, - tableName: String, - schemaName: String? = nil, - databaseType: DatabaseType, - generatedColumns: Set, - rowMatchPolicy: RowMatchPolicy = .none, - columnTypeNames: [String: String] = [:] - ) { - self.tableName = tableName - self.schemaName = schemaName - self.columns = state.columns - self.primaryKeyColumns = state.primaryKeyColumns - self.databaseType = databaseType - self.generatedColumns = generatedColumns - self.rowMatchPolicy = rowMatchPolicy - self.columnTypeNames = columnTypeNames - discardUndoHistory() - objectWillChange.send() - pending.restore(from: state) - self.hasChanges = !pending.isEmpty - } - // MARK: - O(1) Lookups func isRowDeleted(_ rowID: RowID) -> Bool { diff --git a/apple/TablePro/Core/ChangeTracking/PendingChanges.swift b/apple/TablePro/Core/ChangeTracking/PendingChanges.swift index e9d21fe2bc..9ad004a308 100644 --- a/apple/TablePro/Core/ChangeTracking/PendingChanges.swift +++ b/apple/TablePro/Core/ChangeTracking/PendingChanges.swift @@ -402,31 +402,6 @@ struct PendingChanges: Equatable { supersededUpdates.removeAll() } - mutating func restore(from snapshot: TabChangeSnapshot) { - changes = snapshot.changes - deletedRowIDs = snapshot.deletedRowIDs - insertedRowIDs = snapshot.insertedRowIDs - modifiedCells = snapshot.modifiedCells - insertedRowData = snapshot.insertedRowData - supersededUpdates = snapshot.supersededUpdates - let sequences = (changes + supersededUpdates.values).flatMap { [$0.sequence] + $0.runs.map(\.sequence) } - nextSequence = (sequences.max() ?? -1) + 1 - rebuildChangeIndex() - } - - func snapshot(primaryKeyColumns: [String], columns: [String]) -> TabChangeSnapshot { - var snap = TabChangeSnapshot() - snap.changes = changes - snap.deletedRowIDs = deletedRowIDs - snap.insertedRowIDs = insertedRowIDs - snap.modifiedCells = modifiedCells - snap.insertedRowData = insertedRowData - snap.supersededUpdates = supersededUpdates - snap.primaryKeyColumns = primaryKeyColumns - snap.columns = columns - return snap - } - // MARK: - Internals private mutating func appendChange(_ change: RowChange) { @@ -481,13 +456,6 @@ struct PendingChanges: Equatable { changes.removeLast() } - private mutating func rebuildChangeIndex() { - changeIndex.removeAll(keepingCapacity: true) - for (index, change) in changes.enumerated() { - changeIndex[RowChangeKey(rowID: change.rowID, type: change.type)] = index - } - } - private mutating func removeModifiedCell(rowID: RowID, columnIndex: Int) { modifiedCells[rowID]?.remove(columnIndex) if modifiedCells[rowID]?.isEmpty == true { diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift index 46fd174885..06ca9d36e6 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift @@ -274,7 +274,8 @@ extension QueryExecutionCoordinator { var run = try await DatabaseManager.shared.withScopedDriver( scope: scope, route: DatabaseManager.shared.executionRoute(for: scope), - cancellation: .cancellableRead(lease) + cancellation: .cancellableRead(lease), + sessionWork: .statements ) { driver in let startState = await driver.heldSessionTransactionState() let manual = ManualCommit.decision( @@ -538,7 +539,7 @@ extension QueryExecutionCoordinator { } } parent.seedBufferFromActiveResult(tabId: tabId) - parent.dropParkedEdits(ofBackgroundTab: tabId) + parent.dropEdits(ofReplacedResultIn: tabId) if parent.tabManager.selectedTabId == tabId { parent.toolbarState.isResultsCollapsed = false parent.toolbarState.recordQueryTiming(timing, for: tabId) diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift index ecad7c5c02..1c988b5ece 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift @@ -369,20 +369,17 @@ extension QueryExecutionCoordinator { isEditable: isEditable ) - if parent.tabManager.selectedTabId == tabId { - parent.changeManager.configureForTable( - tableName: tableName ?? "", - schemaName: parent.tabManager.tabs[idx].tableContext.schemaName, - columns: columns, - primaryKeyColumns: resolvedPKs, - databaseType: conn.type, - generatedColumns: generatedColumns, - rowMatchPolicy: resolved.rowMatchPolicy, - columnTypeNames: newTableRows.columnTypeNames - ) - parent.changeManagerMatchesSelectedResult() - } - parent.dropParkedEdits(ofBackgroundTab: tabId) + // The tab's own edits named rows of the result this replaces. + parent.changeManager(forTab: tabId).configureForTable( + tableName: tableName ?? "", + schemaName: parent.tabManager.tabs[idx].tableContext.schemaName, + columns: columns, + primaryKeyColumns: resolvedPKs, + databaseType: conn.type, + generatedColumns: generatedColumns, + rowMatchPolicy: resolved.rowMatchPolicy, + columnTypeNames: newTableRows.columnTypeNames + ) if trigger.recordsHistory { recordSuccessfulRun( @@ -390,10 +387,6 @@ extension QueryExecutionCoordinator { executionTime: executionTime, rowCount: rows.count, timing: timing ) } - - if parent.tabManager.selectedTabId == tabId, isEditable, !parent.changeManager.hasChanges { - parent.changeManager.clearChangesAndUndoHistory() - } } private func applyExplainResult( @@ -451,7 +444,7 @@ extension QueryExecutionCoordinator { } } parent.seedBufferFromActiveResult(tabId: tabId) - parent.dropParkedEdits(ofBackgroundTab: tabId) + parent.dropEdits(ofReplacedResultIn: tabId) parent.toolbarState.isResultsCollapsed = false recordHistory( @@ -688,14 +681,12 @@ extension QueryExecutionCoordinator { tab.metadataVersion += 1 } - if parent.tabManager.selectedTabId == tabId, !parsed.primaryKeyColumns.isEmpty { - parent.changeManager.setPrimaryKeyColumns(parsed.primaryKeyColumns) - } - - if parent.tabManager.selectedTabId == tabId { - parent.changeManager.setGeneratedColumns(parsed.generatedColumns) - parent.changeManager.setRowMatchPolicy(parsed.rowMatchPolicy) + let changeManager = parent.changeManager(forTab: tabId) + if !parsed.primaryKeyColumns.isEmpty { + changeManager.setPrimaryKeyColumns(parsed.primaryKeyColumns) } + changeManager.setGeneratedColumns(parsed.generatedColumns) + changeManager.setRowMatchPolicy(parsed.rowMatchPolicy) // The metadata delta rebuilt the model's columns; the foreign key arrows need the rows redrawn. let refreshed = isActiveTab(tabId) diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift index e9d278d3dc..6a06da7ab5 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift @@ -361,11 +361,6 @@ extension QueryExecutionCoordinator { } parent.toolbarState.isResultsCollapsed = false - if parent.tabManager.selectedTabId == tabId { - parent.changeManager.clearChangesAndUndoHistory() - parent.changeManagerMatchesSelectedResult() - } else { - parent.dropParkedEdits(ofBackgroundTab: tabId) - } + parent.dropEdits(ofReplacedResultIn: tabId) } } diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift index b6dcf300b5..78a08b097b 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift @@ -247,7 +247,8 @@ extension QueryExecutionCoordinator { let (fetchResult, tableEdits) = try await DatabaseManager.shared.withScopedDriver( scope: scope, route: DatabaseManager.shared.executionRoute(for: scope), - cancellation: .cancellableRead(lease) + cancellation: .cancellableRead(lease), + sessionWork: .statements ) { [queryExecutor = parent.queryExecutor, boundValues] driver in let fetched = try await held.running([statement.sql], on: driver) { // Before it runs, so a statement that fails or a connection lost under it is still noted. @@ -593,7 +594,8 @@ extension QueryExecutionCoordinator { var run = try await DatabaseManager.shared.withScopedDriver( scope: scope, route: DatabaseManager.shared.executionRoute(for: scope), - cancellation: .cancellableRead(lease) + cancellation: .cancellableRead(lease), + sessionWork: .statements ) { driver in let context = driver.readOnlyRunContext(safeModeIsReadOnly: safeModeIsReadOnly) let startState = await driver.heldSessionTransactionState() @@ -975,7 +977,7 @@ extension QueryExecutionCoordinator { } } parent.seedBufferFromActiveResult(tabId: tabId) - parent.dropParkedEdits(ofBackgroundTab: tabId) + parent.dropEdits(ofReplacedResultIn: tabId) if parent.tabManager.selectedTabId == tabId { parent.toolbarState.isResultsCollapsed = false parent.toolbarState.recordQueryTiming(timing, for: tabId) diff --git a/apple/TablePro/Core/Coordinators/RowEditingCoordinator+Discard.swift b/apple/TablePro/Core/Coordinators/RowEditingCoordinator+Discard.swift index 408ed53bfa..a1c92171de 100644 --- a/apple/TablePro/Core/Coordinators/RowEditingCoordinator+Discard.swift +++ b/apple/TablePro/Core/Coordinators/RowEditingCoordinator+Discard.swift @@ -63,10 +63,6 @@ extension RowEditingCoordinator { pendingTruncates.removeAll() pendingDeletes.removeAll() parent.changeManager.clearChangesAndUndoHistory() - - if let (_, index) = parent.tabManager.selectedTabAndIndex { - parent.tabManager.mutate(at: index) { $0.pendingChanges = TabChangeSnapshot() } - } parent.resumeDeferredTableRefresh() } diff --git a/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift b/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift index 805110f096..348ac4c2c9 100644 --- a/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift +++ b/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift @@ -44,7 +44,9 @@ extension RowEditingCoordinator { endInspectorEditRun() // Taken now: the slot is a handoff, and a save still in flight keeps its own waiter when a second one starts. let waiter = parent.takeSaveCompletion() - let hasEditedCells = parent.changeManager.hasChanges + // The tab's own edits: they stay its own while another tab is shown, so the save follows them, not the selection. + let savingManager = parent.changeManager + let hasEditedCells = savingManager.hasChanges let hasPendingTableOps = !pendingTruncates.isEmpty || !pendingDeletes.isEmpty guard hasEditedCells || hasPendingTableOps else { @@ -53,9 +55,8 @@ extension RowEditingCoordinator { } let savingTabId = parent.tabManager.selectedTabId - /// One change manager serves the whole window, so a second save cannot start while one is - /// in flight. Say so: over the slow link this guard exists for, a Save that silently does - /// nothing is indistinguishable from a Save that is broken. + // A second save in the window waits for the first. Say so: over a slow link a Save that silently + // does nothing is indistinguishable from a broken one. guard beginSaveInFlight(tabId: savingTabId) else { saveChangesLogger.debug("Save already in flight, refusing the repeat") if let index = parent.tabManager.selectedTabIndex { @@ -110,10 +111,10 @@ extension RowEditingCoordinator { let connId = parent.connection.id let kind: OperationKind = hasPendingTableOps ? .destructiveQuery : .writeQuery let deleteConfirmation = BulkDeleteConfirmation( - deletedRowCount: parent.changeManager.deletedRowIDs.count, + deletedRowCount: savingManager.deletedRowIDs.count, tableName: plan.rowOperations.first(where: { $0.kind == .delete })?.target.table ) - let confirmingChanges = PlannedEdits(parent.changeManager.pending) + let confirmingChanges = PlannedEdits(savingManager.pending) Task { [weak self, parent] in guard let self else { waiter?.resume(returning: false) @@ -122,10 +123,8 @@ extension RowEditingCoordinator { if deleteConfirmation.isRequired { let preview = await previewCascade(of: plan) - // The window stays live while counting. A tab switched to holds the change manager this - // save would clear, and an edit made meanwhile is not in the plan, so either ends the save. - let planIsCurrent = parent.tabManager.selectedTabId == savingTabId - && PlannedEdits(parent.changeManager.pending) == confirmingChanges + // The window stays live while counting, and an edit made meanwhile is not in the plan. + let planIsCurrent = PlannedEdits(savingManager.pending) == confirmingChanges var choice = BulkDeleteAlert.Choice.cancel if planIsCurrent { choice = await BulkDeleteAlert.present(deleteConfirmation.with(preview), window: parent.contentWindow) @@ -171,11 +170,8 @@ extension RowEditingCoordinator { ) switch decision { case .authorized: - // The approval prompt is not window-modal. A tab switched to holds the change manager this save - // would clear, and an edit made meanwhile is not in the plan, so either ends the save. - let editsAreCurrent = !hasEditedCells - || (parent.tabManager.selectedTabId == savingTabId - && PlannedEdits(parent.changeManager.pending) == confirmingChanges) + // The approval prompt is not window-modal, and an edit made meanwhile is not in the plan. + let editsAreCurrent = !hasEditedCells || PlannedEdits(savingManager.pending) == confirmingChanges guard editsAreCurrent else { if hasPendingTableOps { restorePendingTableOperations( @@ -187,7 +183,7 @@ extension RowEditingCoordinator { } failSave( message: String( - localized: "The tab or its edits changed while the save waited for approval. Nothing was saved." + localized: "The edits changed while the save waited for approval. Nothing was saved." ), tabId: savingTabId, waiter: waiter @@ -262,7 +258,7 @@ extension RowEditingCoordinator { let route = DatabaseManager.shared.executionRoute(for: scope) let commitMode = DatabaseManager.shared.commitMode(for: conn.id) let serverOwned = serverOwnedColumns(of: savingTabId) - let columnTypeNames = parent.changeManager.columnTypeNames + let columnTypeNames = savingTabId.flatMap(parent.existingChangeManager(forTab:))?.columnTypeNames ?? [:] Task { [weak self, parent] in guard let self else { @@ -379,11 +375,7 @@ extension RowEditingCoordinator { } } - /// The tab that started the save owns the outcome of it. - /// - /// One `changeManager` serves the whole window and swaps contents on every tab switch, so - /// writing the completion into whichever tab is selected when the write lands clears the edits - /// of a tab that had nothing to do with it, and re-runs that tab's query. + // The tab that started the save owns its outcome, whichever tab is selected when the write lands. private func finishSuccessfulSave( plan: DataWritePlan, savingTabId: UUID?, @@ -392,14 +384,11 @@ extension RowEditingCoordinator { truncatedTables: Set ) { let savingTabIsSelected = savingTabId != nil && parent.tabManager.selectedTabId == savingTabId - if savingTabIsSelected { - parent.changeManager.clearChangesAndUndoHistory() + if let savingTabId { + parent.existingChangeManager(forTab: savingTabId)?.clearChangesAndUndoHistory() } if let savingTabId, let index = parent.tabManager.tabs.firstIndex(where: { $0.id == savingTabId }) { - parent.tabManager.mutate(at: index) { - $0.pendingChanges = TabChangeSnapshot() - $0.execution.errorMessage = nil - } + parent.tabManager.mutate(at: index) { $0.execution.errorMessage = nil } } if clearTableOps, !deletedTables.isEmpty { @@ -611,7 +600,7 @@ extension RowEditingCoordinator { /// Read before the save is sent, because by the time it commits the user may be on another tab, and the record /// has to describe the table the save wrote. private func serverOwnedColumns(of tabId: UUID?) -> (generated: [String], identity: [String]) { - let generated = Array(parent.changeManager.generatedColumns) + let generated = Array(tabId.flatMap(parent.existingChangeManager(forTab:))?.generatedColumns ?? []) guard let tabId else { return (generated, []) } let identity = parent.tabSessionRegistry.tableRows(for: tabId).columnIdentity .filter { $0.value == .always } diff --git a/apple/TablePro/Core/Coordinators/RowEditingCoordinator.swift b/apple/TablePro/Core/Coordinators/RowEditingCoordinator.swift index fa81cadf9a..5f623b932c 100644 --- a/apple/TablePro/Core/Coordinators/RowEditingCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/RowEditingCoordinator.swift @@ -60,7 +60,7 @@ final class RowEditingCoordinator: ObservableObject { let uuidKeys = uuidKeyForms(in: tableRows, tab: tab) var addResult: RowOperationsManager.AddNewRowResult? parent.mutateActiveTableRows(for: tabId) { rows in - let result = parent.rowOperationsManager.addNewRow(tableRows: &rows, uuidKeyForms: uuidKeys) + let result = parent.rowOperations(forTab: tabId).addNewRow(tableRows: &rows, uuidKeyForms: uuidKeys) addResult = result return result?.delta ?? .none } @@ -87,7 +87,7 @@ final class RowEditingCoordinator: ObservableObject { delta: .none ) parent.mutateActiveTableRows(for: tabId) { rows in - let result = parent.rowOperationsManager.deleteRows( + let result = parent.rowOperations(forTab: tabId).deleteRows( rowIDs, selectedDisplayIndices: displayIndices, displayCount: displayCount, @@ -112,9 +112,10 @@ final class RowEditingCoordinator: ObservableObject { func undoRowDeletions(_ rowIDs: [RowID]) { guard parent.canEditActiveResult(.delete), let tabId = parent.tabManager.selectedTabId else { return } - let deleted = rowIDs.filter { parent.changeManager.isRowDeleted($0) } + let changeManager = parent.changeManager(forTab: tabId) + let deleted = rowIDs.filter { changeManager.isRowDeleted($0) } guard !deleted.isEmpty else { return } - parent.changeManager.restoreDeletedRows(deleted) + changeManager.restoreDeletedRows(deleted) parent.existingGridModel(forTab: tabId)?.repaintRows(deleted) } @@ -140,7 +141,7 @@ final class RowEditingCoordinator: ObservableObject { let uuidKeys = uuidKeyForms(in: tableRows, tab: tab) var duplicated: [RowOperationsManager.AddNewRowResult] = [] parent.mutateActiveTableRows(for: tabId) { rows in - let result = parent.rowOperationsManager.duplicateRows( + let result = parent.rowOperations(forTab: tabId).duplicateRows( sourceRowIndices: storageIndices, tableRows: &rows, uuidKeyForms: uuidKeys @@ -189,7 +190,7 @@ final class RowEditingCoordinator: ObservableObject { } private func uuidKeyForms(in tableRows: TableRows, tab: QueryTab) -> [Int: UUIDCellForm] { - let changeManager = parent.changeManager + let changeManager = parent.changeManager(forTab: tab.id) return Self.uuidKeyForms( in: tableRows, primaryKeyColumns: changeManager.primaryKeyColumns, @@ -308,31 +309,32 @@ final class RowEditingCoordinator: ObservableObject { guard !parent.isSavingSelectedTab, let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex, !valuesByRow.isEmpty else { return } let tabId = tab.id + let changeManager = parent.changeManager(forTab: tabId) let tableRows = parent.tabSessionRegistry.tableRows(for: tabId) guard tableRows.columns.indices.contains(columnIndex) else { return } let columnName = tableRows.columns[columnIndex] // Checked before touching rows: a server-owned column is refused later, so the grid would show a value nothing writes. - guard parent.changeManager.isColumnWritable(columnName) else { return } + guard changeManager.isColumnWritable(columnName) else { return } var edits: [(row: Int, column: Int, value: PluginCellValue)] = [] var removedCells: Set = [] - parent.changeManager.recordAsOneAction { + changeManager.recordAsOneAction { for (rowID, value) in valuesByRow { guard let storageRow = tableRows.index(of: rowID) else { continue } let row = tableRows.rows[storageRow] guard row.unloadedByteCount(columnIndex) == nil else { continue } let values = Array(row.values) - let removesField = removedRowIDs.contains(rowID) && parent.changeManager.supportsFieldRemoval + let removesField = removedRowIDs.contains(rowID) && changeManager.supportsFieldRemoval let absence = FieldAbsence( wasAbsent: row.isAbsent(columnIndex), isAbsent: removesField, originalRow: row.absentColumns ) let isExpression = expressionRowIDs.contains(rowID) && !removesField - let wasExpression = parent.changeManager.isExpression(rowID: rowID, columnIndex: columnIndex) + let wasExpression = changeManager.isExpression(rowID: rowID, columnIndex: columnIndex) guard values.indices.contains(columnIndex), values[columnIndex] != value || absence.wasAbsent != absence.isAbsent || wasExpression != isExpression else { continue } if continuity == .typing { - parent.changeManager.recordTypedCellChange( + changeManager.recordTypedCellChange( rowID: rowID, columnIndex: columnIndex, columnName: columnName, @@ -343,7 +345,7 @@ final class RowEditingCoordinator: ObservableObject { isExpression: isExpression ) } else { - parent.changeManager.recordCellChange( + changeManager.recordCellChange( rowID: rowID, columnIndex: columnIndex, columnName: columnName, @@ -369,7 +371,7 @@ final class RowEditingCoordinator: ObservableObject { // One user command, one undo step named for it; the buffer write reaches the grid as one delta. func commitGridEdits(_ resolved: [DataGridResolvedEdit], actionName: String, tabId: UUID) -> Bool { - let changeManager = parent.changeManager + let changeManager = parent.changeManager(forTab: tabId) let tableRows = parent.tabSessionRegistry.tableRows(for: tabId) var edits: [(row: Int, column: Int, value: PluginCellValue)] = [] var removedCells: Set = [] @@ -399,14 +401,12 @@ final class RowEditingCoordinator: ObservableObject { return true } - func handleUndoResult(_ result: UndoResult) { - guard let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex else { return } - - let tabId = tab.id + func handleUndoResult(_ result: UndoResult, tabId: UUID) { + guard let tabIndex = parent.tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } var application = RowOperationsManager.UndoApplicationResult(clearsSelection: false, delta: .none) parent.mutateActiveTableRows(for: tabId) { rows in - let applied = parent.rowOperationsManager.applyUndoResult(result, tableRows: &rows) + let applied = parent.rowOperations(forTab: tabId).applyUndoResult(result, tableRows: &rows) application = applied return applied.delta } @@ -440,7 +440,7 @@ final class RowEditingCoordinator: ObservableObject { guard parent.unloadedValuesAreLoaded(rowIDs: rowIDs, retry: { [weak self] in self?.copyRowsToClipboard(rowIDs, includeHeaders: includeHeaders) }) else { return } - parent.rowOperationsManager.copyRowsToClipboard( + parent.rowOperations(forTab: tab.id).copyRowsToClipboard( rowIDs, tableRows: parent.tabSessionRegistry.tableRows(for: tab.id), includeHeaders: includeHeaders, @@ -459,7 +459,7 @@ final class RowEditingCoordinator: ObservableObject { tableRows: tableRows, displayIDs: model.displayedRowIDs, selectedDisplayIndices: Set(rowIDs.compactMap { model.displayIndex(of: $0) }), - defaultedCells: parent.changeManager.defaultedCells(in: tableRows), + defaultedCells: parent.changeManager(forTab: tab.id).defaultedCells(in: tableRows), columns: VisibleColumnProjection(indices: presentedColumnIndices(tabId: tab.id)) ) guard output.rowCount > 0 else { return } @@ -485,9 +485,9 @@ final class RowEditingCoordinator: ObservableObject { var pasteResult = RowOperationsManager.PasteRowsResult(pastedRows: [], delta: .none) parent.mutateActiveTableRows(for: tabId) { rows in - let result = parent.rowOperationsManager.pasteRowsFromClipboard( + let result = parent.rowOperations(forTab: tabId).pasteRowsFromClipboard( columns: columns, - primaryKeyColumns: parent.changeManager.primaryKeyColumns, + primaryKeyColumns: parent.changeManager(forTab: tabId).primaryKeyColumns, tableRows: &rows, uuidKeyForms: uuidKeys ) diff --git a/apple/TablePro/Core/DataWrite/CascadeDeletePreview.swift b/apple/TablePro/Core/DataWrite/CascadeDeletePreview.swift index f69de6844a..7be54ac023 100644 --- a/apple/TablePro/Core/DataWrite/CascadeDeletePreview.swift +++ b/apple/TablePro/Core/DataWrite/CascadeDeletePreview.swift @@ -239,7 +239,7 @@ extension CascadeDeletePreviewer.Environment { @MainActor func scalar(_ query: String, on route: ScopedDriverRoute) async throws -> String? { try await manager.withCancellableRead( - scope: scope, route: route, ownsSessionState: route != countRoute + scope: scope, route: route, sessionWork: route != countRoute ? .app : .independent ) { driver in try await driver.execute(query: query).rows.first?.first?.asText } diff --git a/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift b/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift index 6e390bec4c..9d62071348 100644 --- a/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift +++ b/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift @@ -597,7 +597,8 @@ internal actor DatabaseAccessBridge { return try await manager.withScopedDriver( scope: scope, route: route, - cancellation: .protectedWrite + cancellation: .protectedWrite, + sessionWork: .statements ) { driver -> (affected: Int, notice: String?) in reach.mark() // The hold and savepoint execute_query gets, so a Manual Commit insert waits for Commit too. @@ -691,7 +692,8 @@ internal actor DatabaseAccessBridge { try await manager.withScopedDriver( scope: scope, route: .sessionDriver, - cancellation: .protectedWrite + cancellation: .protectedWrite, + sessionWork: .statements ) { driver in reach.mark() switch action { @@ -829,7 +831,9 @@ internal actor DatabaseAccessBridge { timeoutSeconds: timeoutSeconds, onLateCompletion: onLateCompletion ) { enterDriver in - try await manager.withScopedDriver(scope: scope, route: route, cancellation: policy) { driver in + try await manager.withScopedDriver( + scope: scope, route: route, cancellation: policy, sessionWork: .statements + ) { driver in try enterDriver() return try await body(driver) } @@ -841,6 +845,7 @@ internal actor DatabaseAccessBridge { scope: scope, route: route, cancellation: policy, + sessionWork: .statements, body ) } diff --git a/apple/TablePro/Core/Database/DatabaseManager+Metadata.swift b/apple/TablePro/Core/Database/DatabaseManager+Metadata.swift index 643ff155dc..adf3ed4582 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+Metadata.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+Metadata.swift @@ -70,7 +70,7 @@ extension DatabaseManager { route: metadataRoute(for: scope), workload: workload, cancellation: .untracked, - ownsSessionState: false, + sessionWork: .independent, body ) } @@ -86,7 +86,7 @@ extension DatabaseManager { route: metadataRoute(for: scope), workload: workload, cancellation: .untracked, - ownsSessionState: false, + sessionWork: .independent, readsOnly: true, body ) diff --git a/apple/TablePro/Core/Database/DatabaseManager+OpenTransactions.swift b/apple/TablePro/Core/Database/DatabaseManager+OpenTransactions.swift index e922e93eb5..31b7a4588a 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+OpenTransactions.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+OpenTransactions.swift @@ -119,7 +119,9 @@ extension DatabaseManager { } let heldId = ObjectIdentifier(held) let scope = DatabaseScope(connectionId: hold.connectionId, database: hold.key.lane ?? "", schema: nil) - try await withScopedDriver(scope: scope, route: .sessionDriver, cancellation: .protectedWrite) { driver in + try await withScopedDriver( + scope: scope, route: .sessionDriver, cancellation: .protectedWrite, sessionWork: .statements + ) { driver in let unchanged = await MainActor.run { DatabaseManager.shared.sessionTransactions.isCurrent(hold) } diff --git a/apple/TablePro/Core/Database/DatabaseManager+ScopedDriver.swift b/apple/TablePro/Core/Database/DatabaseManager+ScopedDriver.swift index fc16b57818..904f0e3fdf 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+ScopedDriver.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+ScopedDriver.swift @@ -23,6 +23,13 @@ enum ScopedDriverRoute: Equatable { } } +// Who hears of a lost session: `.statements`, text someone wrote, and `.app`, work the app builds, each once; never `.independent`. +enum SessionWork: Sendable { + case independent + case app + case statements +} + /// What a table read's turn on the session driver came to. private enum TableReadTurn: Sendable { case ran(any Sendable) @@ -79,7 +86,7 @@ extension DatabaseManager { } // A database the user has browsed keeps its own session connection, so its tabs carry on in the transaction, // temp tables and settings they left there. A database whose connection ended holding a transaction or session - // state takes the session path once more, where that loss is reported before anything runs on a replacement. + // state takes the session path once more, where the next statements hear of that loss before they run. if usesDatabaseLanes(session) { if sessionLanes.parkedDriver(for: scope.connectionId, database: scope.database) != nil { return .sessionDriver @@ -114,7 +121,7 @@ extension DatabaseManager { route: ScopedDriverRoute, workload: MetadataConnectionPool.Workload = .interactive, cancellation: DriverCancellationPolicy, - ownsSessionState: Bool = true, + sessionWork: SessionWork = .app, readsOnly: Bool = false, _ body: @Sendable @escaping (DatabaseDriver) async throws -> T ) async throws -> T { @@ -124,7 +131,7 @@ extension DatabaseManager { route: route, workload: workload, cancellation: cancellation, - ownsSessionState: ownsSessionState, + sessionWork: sessionWork, readsOnly: readsOnly ) { driver in try await body(driver) @@ -138,7 +145,7 @@ extension DatabaseManager { route: ScopedDriverRoute, workload: MetadataConnectionPool.Workload, cancellation: DriverCancellationPolicy, - ownsSessionState: Bool, + sessionWork: SessionWork, readsOnly: Bool, _ body: @Sendable @escaping (DatabaseDriver) async throws -> any Sendable ) async throws -> any Sendable { @@ -152,7 +159,7 @@ extension DatabaseManager { ) case .sessionDriver: return try await withPinnedSessionDriver( - scope: scope, ownsSessionState: ownsSessionState, readsOnly: readsOnly, leased + scope: scope, sessionWork: sessionWork, readsOnly: readsOnly, leased ) } } @@ -170,7 +177,7 @@ extension DatabaseManager { scope: DatabaseScope, route: ScopedDriverRoute, workload: MetadataConnectionPool.Workload = .interactive, - ownsSessionState: Bool = true, + sessionWork: SessionWork = .app, readsOnly: Bool = false, _ body: @Sendable @escaping (DatabaseDriver) async throws -> T ) async throws -> T { @@ -179,7 +186,7 @@ extension DatabaseManager { scope: scope, route: route, workload: workload, - ownsSessionState: ownsSessionState, + sessionWork: sessionWork, readsOnly: readsOnly ) { driver in try await body(driver) @@ -191,7 +198,7 @@ extension DatabaseManager { scope: DatabaseScope, route: ScopedDriverRoute, workload: MetadataConnectionPool.Workload, - ownsSessionState: Bool, + sessionWork: SessionWork, readsOnly: Bool, _ body: @Sendable @escaping (DatabaseDriver) async throws -> any Sendable ) async throws -> any Sendable { @@ -203,7 +210,7 @@ extension DatabaseManager { route: route, workload: workload, cancellation: .cancellableRead(owner), - ownsSessionState: ownsSessionState, + sessionWork: sessionWork, readsOnly: readsOnly, body ) @@ -439,11 +446,11 @@ extension DatabaseManager { private func withPinnedSessionDriver( scope: DatabaseScope, - ownsSessionState: Bool, + sessionWork: SessionWork, readsOnly: Bool, _ body: @Sendable @escaping (DatabaseDriver) async throws -> T ) async throws -> T { - try await withSessionDriverTurn(scope: scope, ownsSessionState: ownsSessionState, readsOnly: readsOnly) { driver in + try await withSessionDriverTurn(scope: scope, sessionWork: sessionWork, readsOnly: readsOnly) { driver in try await pin(driver, to: scope) return try await body(driver) } @@ -456,7 +463,7 @@ extension DatabaseManager { scope: DatabaseScope, _ body: @Sendable @escaping (DatabaseDriver) async throws -> any Sendable ) async throws -> TableReadTurn { - try await withSessionDriverTurn(scope: scope, ownsSessionState: false, readsOnly: true) { driver in + try await withSessionDriverTurn(scope: scope, sessionWork: .independent, readsOnly: true) { driver in let route = tableReadRoute(for: scope) guard route == .sessionDriver else { return .moved(route) } try await pin(driver, to: scope) @@ -464,12 +471,10 @@ extension DatabaseManager { } } - // `ownsSessionState` is false for a table read or a metadata read, which depend on nothing the session holds. Such - // a turn neither opens a session connection nor takes the report of a lost session, which is kept for the next - // turn that owns session state. That turn is refused once with the whole loss, whatever work it is. + // Statements and the app's own work each take a lost session's report once; work on a temporary table it took is refused. private func withSessionDriverTurn( scope: DatabaseScope, - ownsSessionState: Bool, + sessionWork: SessionWork, readsOnly: Bool = false, _ turn: (DatabaseDriver) async throws -> R ) async throws -> R { @@ -509,7 +514,13 @@ extension DatabaseManager { guard let lane else { // A driver replaced while it held a transaction or session state, by a reconnect or a Vault lease // rotation. - if ownsSessionState, let lost = sessionLanes.takeAnyLoss(for: connectionId) { + if sessionWork == .statements, let lost = sessionLanes.takeAnyLoss(for: connectionId) { + throw DatabaseError.connectionFailed(Self.sessionLostMessage(database: lost.database, loss: lost.loss)) + } + if scope.isSessionBound, sessionLanes.anyLossIncludes(.temporaryObjects, for: connectionId) { + throw DatabaseError.connectionFailed(Self.temporaryTableLostMessage(database: scope.database)) + } + if sessionWork == .app, let lost = sessionLanes.takeAnyAppLoss(for: connectionId) { throw DatabaseError.connectionFailed(Self.sessionLostMessage(database: lost.database, loss: lost.loss)) } return try await recordingTransaction( @@ -521,9 +532,9 @@ extension DatabaseManager { let driver: DatabaseDriver if let held = sessionDriver(for: connectionId, laneDatabase: lane) { driver = held - } else if ownsSessionState, !scope.isSessionBound, + } else if sessionWork != .independent, !scope.isSessionBound, startsWithoutLane || sessionLanes.wasClosedIdle(database: lane, for: connectionId), - !sessionLanes.hasLoss(database: lane, for: connectionId) { + sessionWork == .app || !sessionLanes.hasLoss(database: lane, for: connectionId) { driver = try await openedLaneDriver(database: lane, for: connectionId) } else { driver = browsedDriver @@ -531,7 +542,13 @@ extension DatabaseManager { let laneDriver = sessionLanes.isParked(driver, for: connectionId) ? try await verifiedParkedDriver(driver, database: lane, for: connectionId) : driver - if ownsSessionState, let loss = sessionLanes.takeLoss(database: lane, for: connectionId) { + if sessionWork == .statements, let loss = sessionLanes.takeLoss(database: lane, for: connectionId) { + throw DatabaseError.connectionFailed(Self.sessionLostMessage(database: lane, loss: loss)) + } + if scope.isSessionBound, sessionLanes.lossIncludes(.temporaryObjects, database: lane, for: connectionId) { + throw DatabaseError.connectionFailed(Self.temporaryTableLostMessage(database: lane)) + } + if sessionWork == .app, let loss = sessionLanes.takeAppLoss(database: lane, for: connectionId) { throw DatabaseError.connectionFailed(Self.sessionLostMessage(database: lane, loss: loss)) } sessionLanes.noteOpenedUse(database: lane, for: connectionId) @@ -612,8 +629,8 @@ extension DatabaseManager { } // A parked connection nobody watched may have died while it sat idle. One that no longer answers is replaced - // before the work runs, and if it held a transaction or session state the work is refused once, because running it - // on the new connection would carry on as if the server had not just dropped them. + // before the work runs, and if it held a transaction or session state the next statements are refused once, because + // running them on the new connection would carry on as if the server had not just dropped them. private func verifiedParkedDriver( _ driver: DatabaseDriver, database: String, diff --git a/apple/TablePro/Core/Database/SessionLanes.swift b/apple/TablePro/Core/Database/SessionLanes.swift index b1c291d62b..f6cc4f96af 100644 --- a/apple/TablePro/Core/Database/SessionLanes.swift +++ b/apple/TablePro/Core/Database/SessionLanes.swift @@ -45,9 +45,10 @@ internal final class SessionLanes { /// Drivers being checked before use. A turn held on one of these is not a query proving the /// driver answers, so a switch back waits for the check instead of promoting it on trust. private var verifying: [ObjectIdentifier: [CheckedContinuation]] = [:] - // Databases whose connection died holding a transaction or session state and was replaced. The next turn there is - // refused once, so work meant for that session does not carry on without it. + // Databases whose connection died holding a transaction or session state and was replaced. The next statements + // someone wrote and the app's own next work are each told once, so neither hears it at the other's expense. private var losses: [UUID: [String: SessionLoss]] = [:] + private var appLosses: [UUID: [String: SessionLoss]] = [:] private struct Opened { weak var driver: AnyObject? @@ -144,6 +145,7 @@ internal final class SessionLanes { closedIdle.removeValue(forKey: connectionId) if !keepingLosses { losses.removeValue(forKey: connectionId) + appLosses.removeValue(forKey: connectionId) } for driver in drivers.values { verifiedAt.removeValue(forKey: ObjectIdentifier(driver)) @@ -220,6 +222,7 @@ internal final class SessionLanes { guard transaction || !state.isEmpty else { return } let loss = SessionLoss(transaction: transaction, state: state) losses[connectionId, default: [:]][database] = losses[connectionId]?[database]?.merging(loss) ?? loss + appLosses[connectionId, default: [:]][database] = appLosses[connectionId]?[database]?.merging(loss) ?? loss Self.logger.info( "noted a lost session connId=\(connectionId, privacy: .public) transaction=\(transaction) kinds=\(state.rawValue)" ) @@ -229,8 +232,16 @@ internal final class SessionLanes { losses[connectionId]?[database] != nil } + internal func lossIncludes(_ kind: SQLSessionStateKinds, database: String, for connectionId: UUID) -> Bool { + losses[connectionId]?[database]?.state.contains(kind) ?? false + } + + internal func anyLossIncludes(_ kind: SQLSessionStateKinds, for connectionId: UUID) -> Bool { + losses[connectionId]?.values.contains { $0.state.contains(kind) } ?? false + } + // Closes every parked connection when the transport under them is rebuilt, first noting each one that held a - // transaction or session state, so the next work on that database is told what the server dropped instead of + // transaction or session state, so the next statements on that database are told what the server dropped instead of // quietly starting over on a new connection. internal func closeAllNotingLosses(for connectionId: UUID) async { for (database, driver) in parked[connectionId] ?? [:] { @@ -245,7 +256,7 @@ internal final class SessionLanes { closeAll(for: connectionId, keepingLosses: true) } - // Reported once, whole, to the first turn that owns session state, as a lost transaction always was. + // Reported once, whole, to the next turn running statements someone wrote; the app's own work leaves it standing. internal func takeLoss(database: String, for connectionId: UUID) -> SessionLoss? { let loss = losses[connectionId]?.removeValue(forKey: database) if losses[connectionId]?.isEmpty == true { @@ -254,9 +265,26 @@ internal final class SessionLanes { return loss } + // The app's own copy: its next work on the session, which would have joined the lost transaction, is told once too. + internal func takeAppLoss(database: String, for connectionId: UUID) -> SessionLoss? { + let loss = appLosses[connectionId]?.removeValue(forKey: database) + if appLosses[connectionId]?.isEmpty == true { + appLosses.removeValue(forKey: connectionId) + } + return loss + } + + internal func takeAnyAppLoss(for connectionId: UUID) -> (database: String, loss: SessionLoss)? { + Self.merged(appLosses.removeValue(forKey: connectionId)) + } + // A connection with one driver for every database lost the session whichever name it was noted under. internal func takeAnyLoss(for connectionId: UUID) -> (database: String, loss: SessionLoss)? { - guard let noted = losses.removeValue(forKey: connectionId), let database = noted.keys.min() else { return nil } + Self.merged(losses.removeValue(forKey: connectionId)) + } + + private static func merged(_ noted: [String: SessionLoss]?) -> (database: String, loss: SessionLoss)? { + guard let noted, let database = noted.keys.min() else { return nil } let loss = noted.values.reduce(SessionLoss(transaction: false, state: [])) { $0.merging($1) } return (database: database, loss: loss) } diff --git a/apple/TablePro/Core/Database/SessionStateLedger.swift b/apple/TablePro/Core/Database/SessionStateLedger.swift index 8ed93187c8..d4b90e174b 100644 --- a/apple/TablePro/Core/Database/SessionStateLedger.swift +++ b/apple/TablePro/Core/Database/SessionStateLedger.swift @@ -117,6 +117,15 @@ extension DatabaseManager { database, kinds ) } + + static func temporaryTableLostMessage(database: String) -> String { + String( + format: String( + localized: "The connection to %@ was lost while it waited and has been reconnected. This temporary table went with the old session. Create it again in a query tab." + ), + database + ) + } } extension SQLSessionDialect { diff --git a/apple/TablePro/Core/DatabaseSearch/DatabaseSearchReader.swift b/apple/TablePro/Core/DatabaseSearch/DatabaseSearchReader.swift index 4e23754acf..5669ab5c42 100644 --- a/apple/TablePro/Core/DatabaseSearch/DatabaseSearchReader.swift +++ b/apple/TablePro/Core/DatabaseSearch/DatabaseSearchReader.swift @@ -60,7 +60,7 @@ internal final class DatabaseSearchLiveReader: DatabaseSearchReading { let rowCap = Self.rowCap let scope = DatabaseScope(connectionId: connection.id, database: database, schema: target.schema) return try await manager.withCancellableRead( - scope: scope, route: manager.metadataRoute(for: scope), ownsSessionState: false + scope: scope, route: manager.metadataRoute(for: scope), sessionWork: .independent ) { driver in let classifier = ColumnTypeClassifier(family: family) let columns = try await driver.fetchColumns(table: target.name, schema: target.schema).map { info in diff --git a/apple/TablePro/Core/Scripting/ScriptingSnapshot.swift b/apple/TablePro/Core/Scripting/ScriptingSnapshot.swift index 48ab2df429..c42c433b3a 100644 --- a/apple/TablePro/Core/Scripting/ScriptingSnapshot.swift +++ b/apple/TablePro/Core/Scripting/ScriptingSnapshot.swift @@ -141,7 +141,6 @@ internal enum ScriptingSnapshot { } // Each data tab's model keeps its own selection, mounted or not, so every tab answers for itself. - let isSelectedTab = coordinator.tabManager.selectedTabId == tabId let selection = coordinator.existingGridModel(forTab: tabId)?.selection.affectedRows ?? IndexSet() let selected = selectedOnly ? Set(selection) : [] if selectedOnly, selected.isEmpty { @@ -149,9 +148,7 @@ internal enum ScriptingSnapshot { } // A row marked for deletion stays in the buffer but not in the grid's result, so a script doesn't read it either. - let deleted = isSelectedTab - ? coordinator.changeManager.deletedRowIDs - : tab.pendingChanges.deletedRowIDs + let deleted = coordinator.existingChangeManager(forTab: tabId)?.deletedRowIDs ?? [] let tableRows = coordinator.externallyMaskedRows(forTab: tabId) let read = DisplayedResultReader.read( diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift index c5d66aba1d..b383be2402 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift @@ -1000,7 +1000,6 @@ internal final class MainSplitViewController: NSSplitViewController { tableOperationOptions: sessionBinding(for: workspace, get: { $0.tableOperationOptions }, set: { $0.tableOperationOptions = $1 }, defaultValue: [:]), trailingPaneState: trailingPaneState, tabManager: sessionState.tabManager, - changeManager: sessionState.changeManager, toolbarState: sessionState.toolbarState, coordinator: sessionState.coordinator ) diff --git a/apple/TablePro/Core/Services/Infrastructure/SessionStateFactory.swift b/apple/TablePro/Core/Services/Infrastructure/SessionStateFactory.swift index 6b202b7b79..ed8a27bc01 100644 --- a/apple/TablePro/Core/Services/Infrastructure/SessionStateFactory.swift +++ b/apple/TablePro/Core/Services/Infrastructure/SessionStateFactory.swift @@ -12,7 +12,6 @@ private let sessionStateLogger = Logger(subsystem: "com.TablePro", category: "Se enum SessionStateFactory { struct SessionState { let tabManager: QueryTabManager - let changeManager: DataChangeManager let toolbarState: ConnectionToolbarState let coordinator: MainContentCoordinator } @@ -85,8 +84,6 @@ enum SessionStateFactory { database: databaseName, name: tableName, to: schemaName ) } - let changeMgr = DataChangeManager() - changeMgr.databaseType = connection.type let toolbarSt = ConnectionToolbarState(connection: connection) let session = DatabaseManager.shared.session(for: connection.id) @@ -107,7 +104,6 @@ enum SessionStateFactory { let coord = MainContentCoordinator( connection: connection, tabManager: tabMgr, - changeManager: changeMgr, toolbarState: toolbarSt, tabSessionRegistry: tabSessionRegistry, queryExecutor: queryExecutor @@ -122,7 +118,6 @@ enum SessionStateFactory { return SessionState( tabManager: tabMgr, - changeManager: changeMgr, toolbarState: toolbarSt, coordinator: coord ) diff --git a/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift b/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift index ed071c40e3..d8db9f0d62 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WindowManager.swift @@ -270,7 +270,7 @@ internal final class WindowManager { /// The destination has to be told a tab arrived. Its coordinator was built with no payload /// and `selectedTabId` is set before anything observes the manager, so the switch that /// normally prepares an incoming tab never runs: `toolbarState.isTableTab` stayed false and - /// `changeManager` kept empty table, column and primary-key metadata, which leaves Find and + /// the tab's edits kept empty table, column and primary-key metadata, which leaves Find and /// Filter disabled and a later edit unable to name the row it is saving. This is that same /// preparation, with no outgoing tab to put away. state.coordinator.handleTabChange(from: nil, to: moved.id, tabs: [moved]) diff --git a/apple/TablePro/Core/Storage/ConnectionStoreIntegrity.swift b/apple/TablePro/Core/Storage/ConnectionStoreIntegrity.swift index 69356f97dd..7aeefc52de 100644 --- a/apple/TablePro/Core/Storage/ConnectionStoreIntegrity.swift +++ b/apple/TablePro/Core/Storage/ConnectionStoreIntegrity.swift @@ -79,6 +79,11 @@ struct ConnectionStoreIntegrity: Sendable { return .trusted } + // A tag removed on purpose still counts as one this device wrote, so its absence reads as modified. + func recordTagged(fileURL: URL) -> Bool { + keySource.hasStamped(Self.storeId(for: fileURL)) || keySource.recordStamped(Self.storeId(for: fileURL)) + } + @discardableResult func stamp(_ data: Data, fileURL: URL) -> Bool { guard let key = keySource.key() else { return false } diff --git a/apple/TablePro/Core/Storage/IntegrityStampedFileStore.swift b/apple/TablePro/Core/Storage/IntegrityStampedFileStore.swift index 51969fa7b5..278231142b 100644 --- a/apple/TablePro/Core/Storage/IntegrityStampedFileStore.swift +++ b/apple/TablePro/Core/Storage/IntegrityStampedFileStore.swift @@ -32,6 +32,14 @@ final class IntegrityStampedFileStore { private let userSaveEstablishesTrust: Bool private let encoder = JSONEncoder() private let decoder = JSONDecoder() + // Records the last load could not decode; every save writes them back after the decoded ones. + private var preserved: [PreservedJSON] = [] + // Unreadable records of an untrusted file that could not be set aside: kept, so a save writes but never signs them. + private var holdsUnverifiedRecords = false + + var backupURL: URL { fileURL.appendingPathExtension("backup") } + var unreadableURL: URL { fileURL.appendingPathExtension("unreadable") } + var unreadableRecordsURL: URL { fileURL.appendingPathExtension("unreadable-records") } /// `userSaveEstablishesTrust` says whether writing this file is itself the user's consent to /// trust what is in it. @@ -56,9 +64,11 @@ final class IntegrityStampedFileStore { self.integrity = integrity } - // Only an absent file is an empty list, a fresh install; one that cannot be read or decoded is nil, never saved over. + // Only an absent file is an empty list, a fresh install; one that cannot be read, or parsed with no backup, is nil, never saved over. func load() -> [Element]? { - let data: Data + preserved = [] + holdsUnverifiedRecords = false + var data: Data do { data = try Data(contentsOf: fileURL) } catch let error as CocoaError where error.code == .fileReadNoSuchFile { @@ -70,18 +80,88 @@ final class IntegrityStampedFileStore { return nil } - switch integrity.verify(data, fileURL: fileURL) { + var entries: [StoredEntry]? + var restoredWithoutTag = false + do { + entries = try decoder.decode([StoredEntry].self, from: data) + } catch { + logger.error("Failed to decode \(self.label, privacy: .public): \(error.publicLogShape, privacy: .public)") + if let restored = restoreBackup(over: data) { + data = restored.data + restoredWithoutTag = !restored.hasTag + entries = try? decoder.decode([StoredEntry].self, from: data) + } + } + + adoptVerdict(for: data, restoredWithoutTag: restoredWithoutTag) + + guard let entries else { return nil } + var elements: [Element] = [] + for entry in entries { + switch entry { + case .decoded(let element): + elements.append(element) + case .preserved(let json): + preserved.append(json) + } + } + if !preserved.isEmpty { + logger.error( + "\(self.label, privacy: .public) holds \(self.preserved.count, privacy: .public) records this build cannot read; they are kept as they are" + ) + } + // A save signs the whole file, and the user never saw these records, so an untrusted file's go beside it instead. + if !isTrusted, !preserved.isEmpty { + if setAside(preserved) { + preserved = [] + } else { + holdsUnverifiedRecords = true + } + } + return elements + } + + /// False when nothing reached disk. A caller that also writes keychain items or sync tombstones + /// has to abort on that rather than strand them against a record that was never persisted. + /// `byUser` false is a write nobody asked for, such as a sync pull, which is not consent either. + @discardableResult + func save(_ elements: [Element], byUser: Bool = true) -> Bool { + do { + let entries = elements.map(StoredEntry.decoded) + preserved.map(StoredEntry.preserved) + let data = try encoder.encode(entries) + keepBackup() + try data.write(to: fileURL, options: .atomic) + // A store that does not take a save as consent keeps the verdict its last load reached. + guard (userSaveEstablishesTrust && byUser) || isTrusted, !holdsUnverifiedRecords else { + logger.warning("Saved \(self.label, privacy: .public) without a trust tag; it stays untrusted") + return true + } + // With no tag written, later edits are undetectable, so the file is not trusted. + isTrusted = integrity.stamp(data, fileURL: fileURL) + return true + } catch { + logger.error("Failed to save \(self.label, privacy: .public): \(error.publicLogShape, privacy: .public)") + return false + } + } + + private func adoptVerdict(for data: Data, restoredWithoutTag: Bool) { + var verdict = integrity.verify(data, fileURL: fileURL) + // A restored backup that carried no tag is not a store from before the tag existed. + if restoredWithoutTag, verdict == .unstamped { + verdict = .modified + } + + switch verdict { case .trusted: isTrusted = true case .unstamped: guard userSaveEstablishesTrust else { logger.warning("\(self.label, privacy: .public) has no integrity tag; anything it declares will not run") isTrusted = false - break + return } - /// An install that predates the tag: this device never tagged the store. Adopt the file as it - /// stands, which is the only option without a prior baseline, and stamp it so later edits are - /// detectable. A tag that went missing afterwards reads as modified instead. + // Never tagged on this device: adopt the file as it stands, the only baseline there is. integrity.stamp(data, fileURL: fileURL) isTrusted = true case .modified: @@ -91,37 +171,156 @@ final class IntegrityStampedFileStore { logger.warning("No integrity key for \(self.label, privacy: .public); anything it declares will not run") isTrusted = false } + } + // Each step leaves either the damaged file in place, so the next load retries, or the backup with its own tag. + private func restoreBackup(over damaged: Data) -> (data: Data, hasTag: Bool)? { + guard let backup = try? Data(contentsOf: backupURL), parsesAsArray(backup) else { return nil } + let backupTag = try? Data(contentsOf: ConnectionStoreIntegrity.tagURL(for: backupURL)) + let hasTag = backupTag?.isEmpty == false + let tagURL = ConnectionStoreIntegrity.tagURL(for: fileURL) do { - return try decoder.decode([Element].self, from: data) + try damaged.write(to: unreadableURL, options: .atomic) + if let backupTag, hasTag { + try backupTag.write(to: tagURL, options: .atomic) + } else { + try removeIfPresent(tagURL) + // Remembered as tagged, so the next load reads the missing tag as modified and never adopts these bytes. + guard integrity.recordTagged(fileURL: fileURL) else { + throw CocoaError(.fileWriteUnknown) + } + } + try backup.write(to: fileURL, options: .atomic) } catch { - logger.error("Failed to decode \(self.label, privacy: .public): \(error.publicLogShape, privacy: .public)") + logger.error( + "Could not restore \(self.label, privacy: .public) from its backup: \(error.publicLogShape, privacy: .public)" + ) return nil } + logger.warning( + "Restored \(self.label, privacy: .public) from its backup; the damaged file is kept as \(self.label, privacy: .public).unreadable" + ) + return (backup, hasTag) } - /// False when nothing reached disk. A caller that also writes keychain items or sync tombstones - /// has to abort on that rather than strand them against a record that was never persisted. - /// `byUser` false is a write nobody asked for, such as a sync pull, which is not consent either. - @discardableResult - func save(_ elements: [Element], byUser: Bool = true) -> Bool { + // A file that no longer parses never replaces the last good copy. + private func keepBackup() { + guard let current = try? Data(contentsOf: fileURL), parsesAsArray(current) else { return } + let tag = try? Data(contentsOf: ConnectionStoreIntegrity.tagURL(for: fileURL)) + let backupTagURL = ConnectionStoreIntegrity.tagURL(for: backupURL) do { - let data = try encoder.encode(elements) - try data.write(to: fileURL, options: .atomic) - /// A store that does not take a save as consent keeps the verdict its last load - /// reached: the write lands, so the user's edit is not lost, but nothing in the file - /// becomes trusted because of it. - guard (userSaveEstablishesTrust && byUser) || isTrusted else { - logger.warning("Saved \(self.label, privacy: .public) without a trust tag; it stays untrusted") - return true + try current.write(to: backupURL, options: .atomic) + if let tag { + try tag.write(to: backupTagURL, options: .atomic) + } else { + try removeIfPresent(backupTagURL) } - /// Trust follows the tag. If no tag could be written, later edits are undetectable, so - /// the file is not treated as trusted. - isTrusted = integrity.stamp(data, fileURL: fileURL) + } catch { + logger.error( + "Could not keep a backup of \(self.label, privacy: .public): \(error.publicLogShape, privacy: .public)" + ) + } + } + + // Added to what an earlier load set aside, so a file loaded again before its next save adds nothing twice. + private func setAside(_ records: [PreservedJSON]) -> Bool { + var kept = (try? Data(contentsOf: unreadableRecordsURL)).flatMap { try? decoder.decode([PreservedJSON].self, from: $0) } ?? [] + for record in records where !kept.contains(record) { + kept.append(record) + } + do { + try encoder.encode(kept).write(to: unreadableRecordsURL, options: .atomic) return true } catch { - logger.error("Failed to save \(self.label, privacy: .public): \(error.publicLogShape, privacy: .public)") + logger.error( + "Could not set aside unreadable records of \(self.label, privacy: .public): \(error.publicLogShape, privacy: .public)" + ) return false } } + + // The same check load makes, so a restored backup always loads. + private func parsesAsArray(_ data: Data) -> Bool { + (try? decoder.decode([PreservedJSON].self, from: data)) != nil + } + + private func removeIfPresent(_ url: URL) throws { + do { + try FileManager.default.removeItem(at: url) + } catch let error as CocoaError where error.code == .fileNoSuchFile { + return + } + } +} + +private enum StoredEntry: Codable { + case decoded(Element) + case preserved(PreservedJSON) + + init(from decoder: any Decoder) throws { + if let element = try? Element(from: decoder) { + self = .decoded(element) + } else { + self = .preserved(try PreservedJSON(from: decoder)) + } + } + + func encode(to encoder: any Encoder) throws { + switch self { + case .decoded(let element): + try element.encode(to: encoder) + case .preserved(let json): + try json.encode(to: encoder) + } + } +} + +// Integers decode before doubles so ids and ports keep their precision. +private enum PreservedJSON: Codable, Equatable { + case null + case bool(Bool) + case integer(Int64) + case double(Double) + case string(String) + case array([PreservedJSON]) + case object([String: PreservedJSON]) + + init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + if container.decodeNil() { + self = .null + } else if let value = try? container.decode(Bool.self) { + self = .bool(value) + } else if let value = try? container.decode(Int64.self) { + self = .integer(value) + } else if let value = try? container.decode(Double.self) { + self = .double(value) + } else if let value = try? container.decode(String.self) { + self = .string(value) + } else if let value = try? container.decode([PreservedJSON].self) { + self = .array(value) + } else { + self = .object(try container.decode([String: PreservedJSON].self)) + } + } + + func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .null: + try container.encodeNil() + case .bool(let value): + try container.encode(value) + case .integer(let value): + try container.encode(value) + case .double(let value): + try container.encode(value) + case .string(let value): + try container.encode(value) + case .array(let value): + try container.encode(value) + case .object(let value): + try container.encode(value) + } + } } diff --git a/apple/TablePro/Models/Query/QueryTab.swift b/apple/TablePro/Models/Query/QueryTab.swift index 314d4336f9..f2b397aa23 100644 --- a/apple/TablePro/Models/Query/QueryTab.swift +++ b/apple/TablePro/Models/Query/QueryTab.swift @@ -54,7 +54,6 @@ struct QueryTab: Identifiable, Equatable { var tableContext: TabTableContext var display: TabDisplayState - var pendingChanges: TabChangeSnapshot // The grid's selection by row and column identity, carried when the tab moves to another window. var selectionSnapshot: GridSelectionSnapshot @@ -146,7 +145,6 @@ struct QueryTab: Identifiable, Equatable { self.execution = TabExecutionState() self.tableContext = TabTableContext(tableName: tableName, isEditable: tabType == .table) self.display = TabDisplayState() - self.pendingChanges = TabChangeSnapshot() self.selectionSnapshot = .empty self.sortState = SortState() self.filterState = TabFilterState() @@ -194,7 +192,6 @@ struct QueryTab: Identifiable, Equatable { objectRef: persisted.objectRef, versionHistorySubject: persisted.versionHistorySubject ) - self.pendingChanges = TabChangeSnapshot() self.selectionSnapshot = .empty // Seeding the source carries a saved empty sort (the user's Don't Sort) past wantsDefaultSort on the first load. self.sortState = (persisted.sortColumns?.isEmpty ?? true) && persisted.sortSource == .user diff --git a/apple/TablePro/Models/Query/QueryTabManager.swift b/apple/TablePro/Models/Query/QueryTabManager.swift index 02dd5453ad..d8aa4523cb 100644 --- a/apple/TablePro/Models/Query/QueryTabManager.swift +++ b/apple/TablePro/Models/Query/QueryTabManager.swift @@ -699,7 +699,6 @@ final class QueryTabManager: ObservableObject { tab.sortState = SortState() tab.restoredSortSource = .unset tab.selectionSnapshot = .empty - tab.pendingChanges = TabChangeSnapshot() tab.autoRefreshInterval = .off tab.autoRefreshPause = nil tab.hasUserInteraction = false diff --git a/apple/TablePro/Models/Query/QueryTabState.swift b/apple/TablePro/Models/Query/QueryTabState.swift index 48b832dd2e..c1ed11dee6 100644 --- a/apple/TablePro/Models/Query/QueryTabState.swift +++ b/apple/TablePro/Models/Query/QueryTabState.swift @@ -168,36 +168,6 @@ struct PersistedTab: Codable { } } -struct TabChangeSnapshot: Equatable { - var changes: [RowChange] - var deletedRowIDs: Set - var insertedRowIDs: Set - var modifiedCells: [RowID: Set] - var insertedRowData: [RowID: [PluginCellValue]] - var supersededUpdates: [RowID: RowChange] = [:] - // The result these edits were made on. They name its rows, so they are void on any other. - var resultSetId: UUID? - var primaryKeyColumns: [String] - var columns: [String] - - init() { - self.changes = [] - self.deletedRowIDs = [] - self.insertedRowIDs = [] - self.modifiedCells = [:] - self.insertedRowData = [:] - self.primaryKeyColumns = [] - self.columns = [] - } - - var hasChanges: Bool { - !changes.isEmpty || !insertedRowIDs.isEmpty || !deletedRowIDs.isEmpty - } - - mutating func adoptLoadedValues(_ values: [RowID: [Int: PluginCellValue]]) { - RowChange.adoptLoadedValues(values, into: &changes) - } -} enum SortDirection: String, Equatable, Codable, CaseIterable, Identifiable { case ascending diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 72db702fbd..51b62f8333 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -191509,6 +191509,9 @@ } } } + }, + "The connection to %@ was lost while it waited and has been reconnected. This temporary table went with the old session. Create it again in a query tab." : { + }, "The connection to %@ was lost while it waited, and the server rolled back its open transaction. It has been reconnected; run the statements again." : { "localizations" : { @@ -192864,6 +192867,9 @@ } } } + }, + "The edits changed while the save waited for approval. Nothing was saved." : { + }, "The emulator endpoint must be a local address, such as http://127.0.0.1:9020." : { "extractionState" : "manual", diff --git a/apple/TablePro/ViewModels/ServerDashboardViewModel.swift b/apple/TablePro/ViewModels/ServerDashboardViewModel.swift index 5bdb0e1791..69867dc073 100644 --- a/apple/TablePro/ViewModels/ServerDashboardViewModel.swift +++ b/apple/TablePro/ViewModels/ServerDashboardViewModel.swift @@ -208,7 +208,7 @@ final class ServerDashboardViewModel: ObservableObject { return try await manager.withCancellableRead( scope: scope, route: manager.executionRoute(for: scope), - ownsSessionState: false, + sessionWork: .independent, readsOnly: true ) { driver in if let context = driver.readOnlyRunContext(safeModeIsReadOnly: isReadOnly) { diff --git a/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift b/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift index a463a7077b..7a43968b12 100644 --- a/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift +++ b/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift @@ -38,9 +38,9 @@ final class DataTabGridAdapter: DataGridDataSource, DataGridActions { coordinator?.tabManager.tabs.first { $0.id == tabId } } - // The change manager and the window's row commands belong to the selected tab only. + // The window's row commands act on the selected tab only. private var ownsWindowState: Bool { - coordinator?.changeManagerTabId == tabId + coordinator?.tabManager.selectedTabId == tabId } // MARK: - DataGridDataSource @@ -50,7 +50,7 @@ final class DataTabGridAdapter: DataGridDataSource, DataGridActions { } var gridChangeState: AnyChangeManager { - coordinator?.gridChangeState ?? Self.detachedChangeState + coordinator?.gridChangeState(forTab: tabId) ?? Self.detachedChangeState } var gridRowNumberOffset: Int { @@ -69,9 +69,9 @@ final class DataTabGridAdapter: DataGridDataSource, DataGridActions { // MARK: - Edits - // A commit against a tab the shared change manager no longer holds would land in another table (H2). + // Lands in this tab's own edits, also when a switch has already moved the selection (H2). func gridCommit(_ edits: [DataGridResolvedEdit], actionName: String) -> Bool { - guard let coordinator, ownsWindowState else { return false } + guard let coordinator, !coordinator.rowEditingCoordinator.isSaving(tabId: tabId) else { return false } let committed = coordinator.rowEditingCoordinator.commitGridEdits(edits, actionName: actionName, tabId: tabId) if committed { coordinator.gridCellsEdited.send() @@ -252,7 +252,8 @@ final class DataTabGridAdapter: DataGridDataSource, DataGridActions { ) -> NSMenuItem? { guard coordinator.canFilterRows, !row.id.isInserted, - !coordinator.changeManager.isCellModified(rowID: row.id, columnIndex: column.dataIndex) else { return nil } + !coordinator.changeManager(forTab: tabId).isCellModified(rowID: row.id, columnIndex: column.dataIndex) + else { return nil } let tabId = tabId return CellFilterMenuBuilder.menuItem( columnName: column.name, diff --git a/apple/TablePro/Views/Main/Child/DataTabSQLExporter.swift b/apple/TablePro/Views/Main/Child/DataTabSQLExporter.swift index 7e2c92da6f..c0088c00a6 100644 --- a/apple/TablePro/Views/Main/Child/DataTabSQLExporter.swift +++ b/apple/TablePro/Views/Main/Child/DataTabSQLExporter.swift @@ -43,7 +43,7 @@ final class DataTabSQLExporter: DataGridSQLExporting { primaryKeyColumns: tab.tableContext.primaryKeyColumns, databaseType: coordinator.connection.type, connectionId: coordinator.connectionId, - changeManager: coordinator.changeManager, + changeManager: coordinator.changeManager(forTab: tabId), driver: coordinator.services.databaseManager.driver(for: coordinator.connectionId) ) } diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index b8f6b3b0bf..9e6568bc13 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -36,7 +36,8 @@ struct MainEditorContentView: View { // Handed in, not resolved in `body` where nothing would observe it: the drawer state is a per-connection singleton. @ObservedObject var historyState: HistoryPanelState - @ObservedObject var changeManager: DataChangeManager + @ObservedObject var selectedEdits: SelectedTabEdits + private var changeManager: DataChangeManager { selectedEdits.manager } let connection: DatabaseConnection let windowId: UUID let connectionId: UUID diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift index b730595993..6f4dbaecda 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift @@ -52,9 +52,6 @@ extension MainContentCoordinator { if confirmed { rowEditingCoordinator.restoreRowBufferToOriginals() changeManager.clearChangesAndUndoHistory() - if let (_, index) = tabManager.selectedTabAndIndex { - tabManager.mutate(at: index) { $0.pendingChanges = TabChangeSnapshot() } - } } completion(confirmed) } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift index 6ee104d4ba..1712b38a27 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift @@ -131,7 +131,7 @@ extension MainContentCoordinator { let fetchResult = try await services.databaseManager.withScopedDriver( scope: scope, route: services.databaseManager.executionRoute(for: scope), - cancellation: .cancellableRead(lease) + cancellation: .cancellableRead(lease), sessionWork: .statements ) { [queryExecutor, held = manualCommitRun(skipped: !ranWrite)] driver in try await held.running([request.gatedSQL(databaseType: conn.type)], on: driver) { try await ServerOutputCapture.running(on: driver, failureOutput: failureOutput) { () async throws -> QueryFetchResult in @@ -214,7 +214,7 @@ extension MainContentCoordinator { } } seedBufferFromActiveResult(tabId: tabId) - dropParkedEdits(ofBackgroundTab: tabId) + dropEdits(ofReplacedResultIn: tabId) toolbarState.isResultsCollapsed = false recordHistory( diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Favorites.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Favorites.swift index f2876bd7a1..6fc2253541 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Favorites.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Favorites.swift @@ -65,7 +65,7 @@ extension MainContentCoordinator { tab.tabType == .query, tab.content.sourceFileURL == nil, tab.content.query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, - !tab.pendingChanges.hasChanges { + !hasStagedRowEdits(inTab: tab.id) { tabManager.mutate(at: tabIndex) { tab in tab.content.sourceFileURL = favorite.fileURL FileTabBaseline.adopt(loaded, into: &tab.content) diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift index e257f4de58..0cc9b2cef1 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift @@ -132,11 +132,6 @@ extension MainContentCoordinator { // MARK: - Editing - // The tab whose edits the shared change manager holds. A switch repoints it after it starts. - var changeManagerTabId: UUID? { - tabSwitchOutgoingTabId ?? tabManager.selectedTabId - } - @discardableResult func commitActiveGridEdit() -> Bool { guard let selectedTabId = tabManager.selectedTabId else { return true } @@ -158,14 +153,6 @@ extension MainContentCoordinator { || activeGridModelProvider(for: tab)?.activeGridModel?.isEditing == true } - func observeChangeManagerForGridRepaint() -> AnyCancellable { - changeManager.$reloadVersion - .removeDuplicates() - .dropFirst() - .receive(on: RunLoop.main) - .sink { [weak self] _ in self?.selectedTabGridModel?.repaintAllRows() } - } - // MARK: - Sort func requestSort(_ sort: SortState, forTab tabId: UUID) { @@ -192,8 +179,8 @@ extension MainContentCoordinator { immutableColumns: Set(services.pluginManager.immutableColumns(for: connection.type)), usesTrueFalseBooleans: services.pluginManager.usesTrueFalseBooleans(for: connection.type), stringLiteralPrefix: SQLStringLiteralPrefix.forDatabaseType(connection.type), - cellWriterSupport: changeManager.cellWriterSupport, - supportsFieldRemoval: changeManager.supportsFieldRemoval, + cellWriterSupport: changeManager(forTab: tab.id).cellWriterSupport, + supportsFieldRemoval: changeManager(forTab: tab.id).supportsFieldRemoval, connectionScope: scope(for: tab) ) configuration.commands = gridCommands(for: tab, isSelected: isSelected, isEditable: isEditable) diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Protection.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Protection.swift index f7b85bde40..219797d44a 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Protection.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Protection.swift @@ -48,7 +48,7 @@ extension MainContentCoordinator { case .createTable: guard !hasTableDraftWork(in: tab) else { return .mountedOnly } default: - guard !tab.pendingChanges.hasChanges else { return .mountedOnly } + guard !hasStagedRowEdits(inTab: tab.id) else { return .mountedOnly } if hasStagedStructureEdits(in: tab) || hasStagedTypeChanges(in: tab) { return .saveable } } return fileSavability(of: tab) @@ -68,7 +68,7 @@ extension MainContentCoordinator { case .createTable: return toolbarState.hasCreateTablePending || hasTableDraftWork(in: tab) default: - return changeManager.hasChanges + return hasStagedRowEdits(inTab: tab.id) || hasStagedStructureEdits(in: tab) || hasStagedTypeChanges(in: tab) } @@ -108,8 +108,7 @@ extension MainContentCoordinator { } func hasAnyUnsavedWork() -> Bool { - changeManager.hasChanges - || hasPendingDestructiveTableOps + hasPendingDestructiveTableOps || hasSidebarEdits || toolbarState.hasCreateTablePending || tabManager.tabs.contains { hasUnsavedWork(in: $0) } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift index d3946eabbe..a2347a5a70 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift @@ -42,6 +42,7 @@ extension MainContentCoordinator { scope: scope, route: services.databaseManager.executionRoute(for: scope), cancellation: .cancellableRead(lease), + sessionWork: .statements, body ) } @@ -94,13 +95,10 @@ extension MainContentCoordinator { ) } - /// The change manager is one per window and holds whichever tab is selected, so a result that - /// still owns its own tab may not own the edits on screen. Clearing without the selection check - /// throws away another tab's uncommitted cells and its undo history. + // Only a result that still owns its tab replaces it, and only that tab's edits go. func clearChangesIfCurrent(claim: TabExecutionClaim) { guard tabExecution.ownsContent(claim), !Task.isCancelled else { return } - guard tabManager.selectedTabId == claim.tabId else { return } - changeManager.clearChangesAndUndoHistory() + dropEdits(ofReplacedResultIn: claim.tabId) } func resolveRowCap(sql: String, tabType: TabType, bypassLimit: Bool = false) -> Int? { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+RenameAdoption.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+RenameAdoption.swift index 41e3314c15..223fd3afe1 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+RenameAdoption.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+RenameAdoption.swift @@ -14,9 +14,9 @@ import Foundation extension MainContentCoordinator { func retitleTabs(ids: Set, to newName: String) { guard !ids.isEmpty else { return } - var renamedSelectedTab = false for index in tabManager.tabs.indices where ids.contains(tabManager.tabs[index].id) { - if tabManager.tabs[index].id == tabManager.selectedTabId { renamedSelectedTab = true } + // Staged edits name the table their statements target, so a save after the rename writes to the new name. + existingChangeManager(forTab: tabManager.tabs[index].id)?.tableName = newName tabManager.mutate(at: index) { tab in tab.tableContext.tableName = newName tab.title = newName @@ -27,11 +27,6 @@ extension MainContentCoordinator { // run against a name the server no longer has. rebuildTableQuery(at: index) } - // One change manager serves the whole window and holds the name its statements target, so - // a save started after the rename would still write to the old one. It moves only when the - // tab it is serving is one of the tabs that was renamed. - guard renamedSelectedTab else { return } - changeManager.tableName = newName } // A container's new name has to reach every tab keyed by its old one, or the next page or save @@ -46,6 +41,10 @@ extension MainContentCoordinator { tab.tableContext.databaseName = toDatabase if schema != nil { tab.tableContext.schemaName = toSchema } } + // Staged edits keep their undo history across the rename, so their schema moves without clearing them. + if let schema, let manager = existingChangeManager(forTab: tabManager.tabs[index].id), manager.schemaName == schema { + manager.schemaName = toSchema + } followRename(ofTableMetadataFor: tabManager.tabs[index]) rebuildTableQuery(at: index) // The history's change notice can land while the tab still names the old database. diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+RowOperations.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+RowOperations.swift index 1a236f244f..a7bcffbbd6 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+RowOperations.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+RowOperations.swift @@ -37,8 +37,8 @@ extension MainContentCoordinator { rowEditingCoordinator.duplicateRows(rowIDs) } - func handleUndoResult(_ result: UndoResult) { - rowEditingCoordinator.handleUndoResult(result) + func handleUndoResult(_ result: UndoResult, forTab tabId: UUID) { + rowEditingCoordinator.handleUndoResult(result, tabId: tabId) } func stageInspectorFieldEdit( diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Share.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Share.swift index 85089f30da..191a3d2229 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Share.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Share.swift @@ -194,7 +194,7 @@ extension MainContentCoordinator { HeldShareRows( tableRows: tableRows, displayIDs: displayIDs(forTab: tab.id), - deletedRowIDs: changeManager.deletedRowIDs, + deletedRowIDs: changeManager(forTab: tab.id).deletedRowIDs, overlay: externalOverlay(forTab: tab.id), projection: projection, untracedColumns: projection.positions(of: Set(untraced)), diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift index c8cdf4bfd3..52bdce90c4 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift @@ -78,6 +78,7 @@ extension MainContentCoordinator { prune(&navigationHistories, keeping: openTabIds) // The editor stores the outgoing tab's history on its next update, after the close forgot it. editorUndoHistories.forgetAll(except: openTabIds) + releaseEdits(exceptTabs: openTabIds) toolbarState.forgetQueryTimings(keeping: openTabIds) for (tabId, session) in structureSessions where !openTabIds.contains(tabId) { session.releaseViewWiring() @@ -100,6 +101,8 @@ extension MainContentCoordinator { erDiagramModels.removeValue(forKey: tabId) discardTableHealthModels([tabId]) tabsWithStagedPrincipals.remove(tabId) + // Rows read from the old target must not stay editable under the new one. + dropEdits(ofReplacedResultIn: tabId) toolbarState.hasCreateTablePending = false toolbarState.hasPrincipalChanges = false toolbarState.hasTypeChanges = false @@ -117,8 +120,8 @@ extension MainContentCoordinator { editorUndoHistories.forget(tab.id) releaseGridModel(forTab: tab.id) tableMetadataCache.removeValue(forKey: tab.id) + releaseEdits(ofTab: tab.id) guard isSelectedTab(tab) else { return } - changeManager.clearChangesAndUndoHistory() toolbarState.hasCreateTablePending = false toolbarState.hasPrincipalChanges = false toolbarState.hasTypeChanges = false diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabEdits.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabEdits.swift new file mode 100644 index 0000000000..84d86e50b6 --- /dev/null +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabEdits.swift @@ -0,0 +1,173 @@ +// +// MainContentCoordinator+TabEdits.swift +// TablePro +// + +import AppKit +import Combine +import Foundation +import TableProPluginKit + +// A tab's staged row edits and their undo history. They stay with the tab while another one is shown. +struct TabEdits { + let changes: DataChangeManager + let gridState: AnyChangeManager + let undoManager: UndoManager + let observers: [AnyCancellable] +} + +// The selected tab's edits for the views that draw them: they follow the selection instead of holding one tab. +@MainActor +final class SelectedTabEdits: ObservableObject { + private(set) var manager: DataChangeManager + private var forwarding: AnyCancellable? + + init(_ manager: DataChangeManager) { + self.manager = manager + forwarding = forward(manager) + } + + func follow(_ manager: DataChangeManager) { + guard manager !== self.manager else { return } + objectWillChange.send() + self.manager = manager + forwarding = forward(manager) + } + + private func forward(_ manager: DataChangeManager) -> AnyCancellable { + manager.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() } + } +} + +extension MainContentCoordinator { + // The selected tab's edits, which the window's commands act on. + var changeManager: DataChangeManager { + guard let tabId = tabManager.selectedTabId else { return idleChangeManager } + return changeManager(forTab: tabId) + } + + func changeManager(forTab tabId: UUID) -> DataChangeManager { + edits(forTab: tabId).changes + } + + func existingChangeManager(forTab tabId: UUID) -> DataChangeManager? { + tabEdits[tabId]?.changes + } + + func hasStagedRowEdits(inTab tabId: UUID) -> Bool { + tabEdits[tabId]?.changes.hasChanges ?? false + } + + func gridChangeState(forTab tabId: UUID) -> AnyChangeManager { + edits(forTab: tabId).gridState + } + + func rowOperations(forTab tabId: UUID) -> RowOperationsManager { + RowOperationsManager(changeManager: changeManager(forTab: tabId)) + } + + // Edits made on a result name its rows, so a result that replaces it leaves them nothing to write to. + func dropEdits(ofReplacedResultIn tabId: UUID) { + existingChangeManager(forTab: tabId)?.clearChangesAndUndoHistory() + } + + func releaseEdits(ofTab tabId: UUID) { + guard let edits = tabEdits.removeValue(forKey: tabId) else { return } + edits.changes.clearChangesAndUndoHistory() + edits.changes.pluginDriver = nil + guard selectedTabEdits.manager === edits.changes else { return } + selectedTabEdits.follow(tabManager.selectedTabId == tabId ? idleChangeManager : changeManager) + } + + func releaseEdits(exceptTabs openTabIds: Set) { + for tabId in tabEdits.keys where !openTabIds.contains(tabId) { + releaseEdits(ofTab: tabId) + } + } + + func releaseAllTabEdits() { + for tabId in Array(tabEdits.keys) { + releaseEdits(ofTab: tabId) + } + selectedTabEdits.follow(idleChangeManager) + idleChangeManager.clearChanges() + idleChangeManager.pluginDriver = nil + rowWriter = nil + } + + func adoptRowWriter(_ writer: (any PluginDatabaseDriver)?) { + rowWriter = writer + for manager in [idleChangeManager] + tabEdits.values.map(\.changes) where manager.pluginDriver !== writer { + manager.pluginDriver = writer + } + } + + // `$selectedTabId` publishes before the property changes, so the new id is the one it hands over. + func followSelectedTabEdits() -> AnyCancellable { + tabManager.$selectedTabId + .removeDuplicates() + .sink { [weak self] tabId in + guard let self else { return } + selectedTabEdits.follow(tabId.map { self.changeManager(forTab: $0) } ?? idleChangeManager) + } + } + + // Asked on every switch: a manager with nothing staged takes the tab's current result without losing its redo. + func describeCurrentResult(ofTab tabId: UUID) { + guard let manager = existingChangeManager(forTab: tabId), !manager.hasChanges, + let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return } + describe(tab, in: manager) + } + + private func describe(_ tab: QueryTab, in manager: DataChangeManager) { + let rows = tabSessionRegistry.tableRows(for: tab.id) + manager.describeTable( + tableName: tab.tableContext.tableName ?? "", + schemaName: tab.tableContext.schemaName, + columns: rows.columns, + primaryKeyColumns: tab.tableContext.primaryKeyColumns, + databaseType: connection.type, + generatedColumns: rows.generatedColumns, + rowMatchPolicy: rows.rowMatchPolicy, + columnTypeNames: rows.columnTypeNames + ) + } + + private func edits(forTab tabId: UUID) -> TabEdits { + if let existing = tabEdits[tabId] { return existing } + let manager = DataChangeManager() + let undoManager = UndoManager() + manager.undoManagerProvider = { undoManager } + manager.onUndoApplied = { [weak self] result in self?.handleUndoResult(result, forTab: tabId) } + manager.databaseType = connection.type + manager.pluginDriver = rowWriter + if let tab = tabManager.tabs.first(where: { $0.id == tabId }) { + describe(tab, in: manager) + } + let observers = [ + manager.$reloadVersion + .removeDuplicates() + .dropFirst() + .receive(on: RunLoop.main) + .sink { [weak self] _ in self?.existingGridModel(forTab: tabId)?.repaintAllRows() }, + // Heard a turn later: the manager publishes before it stores, and by then a save has started the load. + manager.$hasChanges + .removeDuplicates() + .dropFirst() + .filter { !$0 } + .receive(on: RunLoop.main) + .sink { [weak self] _ in + guard let self, tabManager.selectedTabId == tabId else { return } + resumeDeferredTableRefresh() + }, + ] + let edits = TabEdits( + changes: manager, + gridState: AnyChangeManager(manager), + undoManager: undoManager, + observers: observers + ) + tabEdits[tabId] = edits + return edits + } +} diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabSwitch.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabSwitch.swift index 40e812529e..99820c7d94 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabSwitch.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabSwitch.swift @@ -25,32 +25,21 @@ extension MainContentCoordinator { "[switch] handleTabChange start from=\(oldTabId?.uuidString ?? "nil", privacy: .public) to=\(newTabId?.uuidString ?? "nil", privacy: .public) connId=\(self.connectionId, privacy: .public) tabsCount=\(self.tabManager.tabs.count)" ) isHandlingTabSwitch = true - // The change manager holds the outgoing tab's edits until the restore below, so an open cell editor commits there (H2). - tabSwitchOutgoingTabId = oldTabId if let oldTabId { commitGridEdit(ofTab: oldTabId) + // A typed run left open would swallow the tab's next step when it comes back. + existingChangeManager(forTab: oldTabId)?.endCoalescedUndoRun() } defer { - tabSwitchOutgoingTabId = nil isHandlingTabSwitch = false Self.lifecycleLogger.debug( "[switch] handleTabChange done to=\(newTabId?.uuidString ?? "nil", privacy: .public) elapsedMs=\(Int(Date().timeIntervalSince(start) * 1_000))" ) } - let saveStart = Date() if let oldId = oldTabId, let oldIndex = tabManager.tabs.firstIndex(where: { $0.id == oldId }) { - // Also checks the tab's snapshot: on `hasChanges` alone an undo kept a stale snapshot that restored the undone edit on return. - // Only on the switch the result landed in: a mark left by a reselect this handler never saw is dropped. - if let selectedAtLanding = tabsGivenResultOffScreen.removeValue(forKey: oldId), selectedAtLanding == newTabId { - tabManager.mutate(at: oldIndex) { $0.pendingChanges = TabChangeSnapshot() } - } else if changeManager.hasChanges || tabManager.tabs[oldIndex].pendingChanges.hasChanges { - var savedState = changeManager.saveState() - savedState.resultSetId = tabManager.tabs[oldIndex].display.activeResultSetId - tabManager.mutate(at: oldIndex) { $0.pendingChanges = savedState } - } // One editor serves every query tab with no `.id(tab.id)`, so write only once this tab's restored caret has been consumed. let outgoing = tabManager.tabs[oldIndex] if outgoing.tabType == .query, @@ -64,7 +53,6 @@ extension MainContentCoordinator { } filterCoordinator.saveLastFilters(of: tabManager.tabs[oldIndex]) } - let saveMs = Int(Date().timeIntervalSince(saveStart) * 1_000) // Deferred a tick: releasing a large formatted cache is not work the switch should wait on. Task { @MainActor [weak self] in @@ -75,52 +63,19 @@ extension MainContentCoordinator { if let newId = newTabId, let newIndex = tabManager.tabs.firstIndex(where: { $0.id == newId }) { let newTab = tabManager.tabs[newIndex] - let newRows = tabSessionRegistry.tableRows(for: newId) - tabsGivenResultOffScreen.removeValue(forKey: newId) toolbarState.isTableTab = newTab.tabType == .table toolbarState.isResultsCollapsed = newTab.display.isResultsCollapsed syncQueryToolbarState(for: newTab) - // Consumed once restored: a copy left on the tab went stale with the first undo and kept reporting undone edits. - var pendingState = newTab.pendingChanges - if pendingState.hasChanges, pendingState.resultSetId != newTab.display.activeResultSetId { - pendingState = TabChangeSnapshot() - tabManager.mutate(at: newIndex) { $0.pendingChanges = pendingState } - } - if pendingState.hasChanges { - changeManager.restoreState( - from: pendingState, - tableName: newTab.tableContext.tableName ?? "", - schemaName: newTab.tableContext.schemaName, - databaseType: connection.type, - generatedColumns: newRows.generatedColumns, - rowMatchPolicy: newRows.rowMatchPolicy, - columnTypeNames: newRows.columnTypeNames - ) - tabManager.mutate(at: newIndex) { $0.pendingChanges = TabChangeSnapshot() } - tabSwitchOutgoingTabId = nil - } else { - changeManager.configureForTable( - tableName: newTab.tableContext.tableName ?? "", - schemaName: newTab.tableContext.schemaName, - columns: newRows.columns, - primaryKeyColumns: newTab.tableContext.primaryKeyColumns, - databaseType: connection.type, - generatedColumns: newRows.generatedColumns, - rowMatchPolicy: newRows.rowMatchPolicy, - columnTypeNames: newRows.columnTypeNames, - triggerReload: false - ) - tabSwitchOutgoingTabId = nil - } - - let restoreMs = Int(Date().timeIntervalSince(restoreStart) * 1_000) + // Each tab keeps its own edits and undo history, so arriving only points the window at them. + describeCurrentResult(ofTab: newId) + selectedTabEdits.follow(changeManager(forTab: newId)) Self.lifecycleLogger.debug( - "[switch] handleTabChange phases: saveOutgoing=\(saveMs)ms restoreIncoming=\(restoreMs)ms" + "[switch] handleTabChange restoreIncoming=\(Int(Date().timeIntervalSince(restoreStart) * 1_000))ms" ) - // No `reloadVersion` bump: it is window-wide, and bumping it on a switch re-formatted the incoming grid's whole result (#2424). + // No `reloadVersion` bump: bumping it on a switch re-formatted the incoming grid's whole result (#2424). let isStale = tabSessionRegistry.isStale(newId) lazyLoadCurrentTabIfNeeded() TabSwitchTracer.shared.selectionApplied( @@ -130,15 +85,7 @@ extension MainContentCoordinator { isShowing: { [weak manager = tabManager] in manager?.isShowing(newId) ?? false } ) } else { - // No tab selected: drop the live copy, or a Save would write the outgoing tab's rows against the database now on screen. - changeManager.configureForTable( - tableName: "", - columns: [], - primaryKeyColumns: [], - databaseType: connection.type, - generatedColumns: [], - triggerReload: false - ) + selectedTabEdits.follow(idleChangeManager) toolbarState.isTableTab = false toolbarState.isResultsCollapsed = false toolbarState.isQueryTab = false @@ -146,22 +93,6 @@ extension MainContentCoordinator { } } - // Edits parked on a background tab name rows of the result it held; a result installed meanwhile makes them - // another table's on return. - func dropParkedEdits(ofBackgroundTab tabId: UUID) { - guard tabManager.selectedTabId != tabId else { return } - tabsGivenResultOffScreen[tabId] = .some(tabManager.selectedTabId) - tabManager.mutate(tabId: tabId) { tab in - if tab.pendingChanges.hasChanges { tab.pendingChanges = TabChangeSnapshot() } - } - } - - // The selected tab's change manager now describes the result on screen. - func changeManagerMatchesSelectedResult() { - guard let selected = tabManager.selectedTabId else { return } - tabsGivenResultOffScreen.removeValue(forKey: selected) - } - private func commitGridEdit(ofTab tabId: UUID) { existingGridModel(forTab: tabId)?.commitEditing() guard let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift index 27fc922ce3..b47d74f496 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift @@ -169,9 +169,8 @@ extension MainContentCoordinator { tab.schemaVersion += 1 } let tab = tabManager.tabs[tabIdx] - guard tab.id == tabManager.selectedTabId else { return } let rows = tabSessionRegistry.tableRows(for: tab.id) - changeManager.configureForTable( + changeManager(forTab: tab.id).configureForTable( tableName: tab.tableContext.tableName ?? "", schemaName: tab.tableContext.schemaName, columns: resultSet.resultColumns, diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsRefresh.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsRefresh.swift index b87f556999..9518e36e50 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsRefresh.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsRefresh.swift @@ -51,16 +51,6 @@ extension MainContentCoordinator { ) } - // Heard a turn later: the manager publishes before it stores, and by then a cleaning switch or save has started the load. - func resumeWhenEditsClear() -> AnyCancellable { - changeManager.$hasChanges - .removeDuplicates() - .dropFirst() - .filter { !$0 } - .receive(on: RunLoop.main) - .sink { [weak self] _ in self?.resumeDeferredTableRefresh() } - } - // A scope-wide change can alter columns of tables no tab shows, so every cached column list goes. func applyDataRefresh(_ request: DataRefreshRequest) { guard request.connectionId == connectionId else { return } @@ -128,9 +118,8 @@ extension MainContentCoordinator { // The one answer for every reload path, the lazy load included: an open cell counts, or a reload drops what is typed in it. func holdsUnsavedWork(_ tab: QueryTab) -> Bool { - if tab.pendingChanges.hasChanges { return true } - guard tab.id == changeManagerTabId else { return false } - return changeManager.hasChanges || isEditingActiveGrid + if hasStagedRowEdits(inTab: tab.id) { return true } + return tab.id == tabManager.selectedTabId && isEditingActiveGrid } private func selectedTabLoad(_ tabId: UUID) -> TableRowsRefreshPlan.SelectedTabLoad { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+UnloadedValues.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+UnloadedValues.swift index 1448717a5a..ca4f2557a9 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+UnloadedValues.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+UnloadedValues.swift @@ -147,11 +147,7 @@ extension MainContentCoordinator { return false } mutateActiveTableRows(for: tabId) { $0.fillUnloaded(read.values) } - if tabManager.selectedTabId == tabId { - changeManager.adoptLoadedValues(read.values) - } else { - tabManager.mutate(tabId: tabId) { $0.pendingChanges.adoptLoadedValues(read.values) } - } + changeManager(forTab: tabId).adoptLoadedValues(read.values) inspectorRowSourceRevision &+= 1 return read.isComplete } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentView+EventHandlers.swift b/apple/TablePro/Views/Main/Extensions/MainContentView+EventHandlers.swift index 668b73a88c..fc6a9ce656 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentView+EventHandlers.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentView+EventHandlers.swift @@ -67,7 +67,7 @@ extension MainContentView { } func handleColumnsChange(newColumns: [String]?) { - // Skip during tab switch: handleTabChange already configures the change manager + // Skip during tab switch: handleTabChange already describes the incoming tab's result to its edits guard !coordinator.isHandlingTabSwitch else { return } if let newColumns = newColumns { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentView+Modifiers.swift b/apple/TablePro/Views/Main/Extensions/MainContentView+Modifiers.swift index 148cceb37f..3881dcad65 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentView+Modifiers.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentView+Modifiers.swift @@ -26,7 +26,6 @@ import SwiftUI tableOperationOptions: .constant([:]), trailingPaneState: TrailingPaneState(), tabManager: state.tabManager, - changeManager: state.changeManager, toolbarState: state.toolbarState, coordinator: state.coordinator ) diff --git a/apple/TablePro/Views/Main/MainContentCommandActions+UndoState.swift b/apple/TablePro/Views/Main/MainContentCommandActions+UndoState.swift index c74704fad4..1fed2819e1 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions+UndoState.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions+UndoState.swift @@ -20,12 +20,31 @@ extension StructureEditingSession: StructureUndoHistory {} extension CreateTableDraft: StructureUndoHistory {} -// Users & Roles, the diagram and the structure editor keep their own histories; everything else uses the browse one. +// Users & Roles, the diagram, the structure editor and each data tab keep their own histories. extension MainContentCommandActions { private var windowUndoManager: UndoManager? { coordinator?.browseUndoManager } + // Typing in a field and the sidebar's folder edits register on the window's history, which they undo first. + private var focusRegistersOnWindow: Bool { + guard let windowHistory = windowUndoManager, + let responder = coordinator?.contentWindow?.firstResponder, + responder is NSText || responder is NSOutlineView else { return false } + return responder.undoManager === windowHistory + } + + private func history(using canAct: (UndoManager) -> Bool) -> UndoManager? { + if focusRegistersOnWindow, let windowHistory = windowUndoManager, canAct(windowHistory) { + return windowHistory + } + return coordinator?.changeManager.undoManager + } + + private var undoHistory: UndoManager? { history { $0.canUndo } } + + private var redoHistory: UndoManager? { history { $0.canRedo } } + // A Create Table tab keeps its view mode at Data, so it is asked for by tab type. private var showsStructureEditor: Bool { guard let tab = coordinator?.tabManager.selectedTab else { return false } @@ -56,7 +75,7 @@ extension MainContentCommandActions { if showsStructureEditor { return structureHistory?.canUndo ?? false } if coordinator?.isSavingSelectedTab == true { return false } if coordinator?.changeManager.hasCoalescedUndoRun == true { return true } - return windowUndoManager?.canUndo ?? false + return undoHistory?.canUndo ?? false } var canRedo: Bool { @@ -64,7 +83,7 @@ extension MainContentCommandActions { if isDiagramTab { return selectedDiagram?.canRedoStagedEdit ?? false } if showsStructureEditor { return structureHistory?.canRedo ?? false } if coordinator?.isSavingSelectedTab == true { return false } - return windowUndoManager?.canRedo ?? false + return redoHistory?.canRedo ?? false } var resolvedUndoTitle: String { @@ -77,7 +96,7 @@ extension MainContentCommandActions { if coordinator?.changeManager.hasCoalescedUndoRun == true { return String(localized: "Undo Edit Cell") } - guard let manager = windowUndoManager, manager.canUndo else { return String(localized: "Undo") } + guard let manager = undoHistory, manager.canUndo else { return String(localized: "Undo") } return manager.undoMenuItemTitle } @@ -88,7 +107,7 @@ extension MainContentCommandActions { guard let history = structureHistory, history.canRedo else { return String(localized: "Redo") } return history.redoMenuItemTitle } - guard let manager = windowUndoManager, manager.canRedo else { return String(localized: "Redo") } + guard let manager = redoHistory, manager.canRedo else { return String(localized: "Redo") } return manager.redoMenuItemTitle } @@ -109,7 +128,7 @@ extension MainContentCommandActions { return } guard coordinator?.isSavingSelectedTab != true else { return } - windowUndoManager?.undo() + undoHistory?.undo() } func redoChange() { @@ -127,6 +146,6 @@ extension MainContentCommandActions { return } guard coordinator?.isSavingSelectedTab != true else { return } - windowUndoManager?.redo() + redoHistory?.redo() } } diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index c0edc94f0a..40992d76a5 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -171,7 +171,12 @@ final class MainContentCoordinator: ObservableObject { } let selectionSummary = SelectionSummaryState() let tabManager: QueryTabManager - let changeManager: DataChangeManager + // Each tab stages its edits in its own manager; this one answers while no tab is selected. + let idleChangeManager = DataChangeManager() + var tabEdits: [UUID: TabEdits] = [:] + let selectedTabEdits: SelectedTabEdits + // The driver a tab's edits are written through, kept for the managers tabs create later. + var rowWriter: (any PluginDatabaseDriver)? let toolbarState: ConnectionToolbarState let tabSessionRegistry: TabSessionRegistry let queryExecutor: QueryExecutor @@ -182,10 +187,6 @@ final class MainContentCoordinator: ObservableObject { @Published internal var queryBuilder: TableQueryBuilder let persistence: TabPersistenceCoordinator - internal lazy var rowOperationsManager: RowOperationsManager = { - RowOperationsManager(changeManager: changeManager) - }() - private(set) var filterCoordinator: FilterCoordinator! private(set) var findCoordinator: FindCoordinator! private(set) var queryExecutionCoordinator: QueryExecutionCoordinator! @@ -234,13 +235,6 @@ final class MainContentCoordinator: ObservableObject { // One grid model per data tab, outliving every mount of its grid. var dataGridEntries: [UUID: DataTabGridEntry] = [:] - // Set while a tab switch still has the outgoing tab's edits in the change manager. - var tabSwitchOutgoingTabId: UUID? - // Tabs given a result while off screen, with the tab selected at that moment. One still listed when the switch - // handler parks its edits on the way to that same tab got the result before the handler ran, so the edits in - // the change manager are the old result's. - var tabsGivenResultOffScreen: [UUID: UUID?] = [:] - private(set) lazy var gridChangeState = AnyChangeManager(changeManager) let gridCellsEdited = PassthroughSubject() // One-shot: set on an explicit open (Return, double-click), consumed by the grid to take focus. Never set on selection. @@ -358,8 +352,7 @@ final class MainContentCoordinator: ObservableObject { private var externalFileModCancellable: AnyCancellable? internal lazy var sourceFileDiskChangeMonitor = SourceFileDiskChangeMonitor(tabManager: tabManager) private var schemaSwitchCancellable: AnyCancellable? - private var clearedEditsCancellable: AnyCancellable? - private var gridRepaintCancellable: AnyCancellable? + private var selectedTabEditsCancellable: AnyCancellable? var maskingRulesCancellable: AnyCancellable? // Sent once a saved rule has masked the rows on screen, so an open Share sheet reads them again. let maskingRulesApplied = PassthroughSubject() @@ -595,7 +588,6 @@ final class MainContentCoordinator: ObservableObject { init( connection: DatabaseConnection, tabManager: QueryTabManager, - changeManager: DataChangeManager, toolbarState: ConnectionToolbarState, tabSessionRegistry: TabSessionRegistry? = nil, queryExecutor: QueryExecutor? = nil, @@ -606,7 +598,8 @@ final class MainContentCoordinator: ObservableObject { self.connection = connection self.windowSidebarState = WindowSidebarState(connectionId: connection.id) self.tabManager = tabManager - self.changeManager = changeManager + idleChangeManager.databaseType = connection.type + self.selectedTabEdits = SelectedTabEdits(idleChangeManager) self.toolbarState = toolbarState let resolvedRegistry = tabSessionRegistry ?? TabSessionRegistry() self.tabSessionRegistry = resolvedRegistry @@ -622,8 +615,6 @@ final class MainContentCoordinator: ObservableObject { self.persistence = TabPersistenceCoordinator.forConnection(connection.id) ConnectionDataCache.shared(for: connection.id).ensureLoaded() - changeManager.undoManagerProvider = { [weak self] in self?.browseUndoManager } - changeManager.onUndoApplied = { [weak self] result in self?.handleUndoResult(result) } tabManager.onVisibleContainerReconciled = { [weak self] in self?.browseCursorCoordinator.followVisibleContainer() } @@ -679,8 +670,7 @@ final class MainContentCoordinator: ObservableObject { self.queryExecutionCoordinator = QueryExecutionCoordinator(parent: self) self.paginationCoordinator = PaginationCoordinator(parent: self) self.rowEditingCoordinator = RowEditingCoordinator(parent: self) - clearedEditsCancellable = resumeWhenEditsClear() - gridRepaintCancellable = observeChangeManagerForGridRepaint() + selectedTabEditsCancellable = followSelectedTabEdits() maskingRulesCancellable = observeMaskingRuleChanges() observeSelectionForAutoRefresh() @@ -756,10 +746,7 @@ final class MainContentCoordinator: ObservableObject { if !queryBuilder.usesSessionDriver(driver) { queryBuilder.setSessionDriver(driver) } - let rowWriter = driver.rowWritingPluginDriver - if rowWriter !== changeManager.pluginDriver { - changeManager.pluginDriver = rowWriter - } + adoptRowWriter(driver.rowWritingPluginDriver) } func markTeardownScheduled() { @@ -909,8 +896,7 @@ final class MainContentCoordinator: ObservableObject { tabManager.selectedTabId = nil // pluginDriver strongly holds the whole database driver, which blocks deallocation. - changeManager.clearChanges() - changeManager.pluginDriver = nil + releaseAllTabEdits() services.schemaProviderRegistry.release(for: connection.id) services.schemaProviderRegistry.purgeUnused() diff --git a/apple/TablePro/Views/Main/MainContentView.swift b/apple/TablePro/Views/Main/MainContentView.swift index f31aeb43ac..ee2e011fd1 100644 --- a/apple/TablePro/Views/Main/MainContentView.swift +++ b/apple/TablePro/Views/Main/MainContentView.swift @@ -34,7 +34,9 @@ struct MainContentView: View { // MARK: - State Objects @ObservedObject var tabManager: QueryTabManager - @ObservedObject var changeManager: DataChangeManager + // The selected tab's edits; each tab keeps its own, and this follows the selection. + @ObservedObject var selectedEdits: SelectedTabEdits + var changeManager: DataChangeManager { selectedEdits.manager } @ObservedObject var toolbarState: ConnectionToolbarState @ObservedObject var coordinator: MainContentCoordinator @@ -63,7 +65,6 @@ struct MainContentView: View { tableOperationOptions: Binding<[DatabaseTreeTableRef: TableOperationOptions]>, trailingPaneState: TrailingPaneState, tabManager: QueryTabManager, - changeManager: DataChangeManager, toolbarState: ConnectionToolbarState, coordinator: MainContentCoordinator ) { @@ -77,7 +78,7 @@ struct MainContentView: View { self._tableOperationOptions = tableOperationOptions self.trailingPaneState = trailingPaneState self.tabManager = tabManager - self.changeManager = changeManager + self.selectedEdits = coordinator.selectedTabEdits self.toolbarState = toolbarState self.coordinator = coordinator } @@ -530,7 +531,7 @@ struct MainContentView: View { tabManager: tabManager, coordinator: coordinator, historyState: HistoryPanelState.forConnection(connection.id), - changeManager: changeManager, + selectedEdits: selectedEdits, connection: connection, windowId: windowId, connectionId: connection.id, diff --git a/apple/TableProTests/Core/AI/AIConnectionAccessGateTests.swift b/apple/TableProTests/Core/AI/AIConnectionAccessGateTests.swift index 0eadf3f2cc..d1e41b97d1 100644 --- a/apple/TableProTests/Core/AI/AIConnectionAccessGateTests.swift +++ b/apple/TableProTests/Core/AI/AIConnectionAccessGateTests.swift @@ -287,7 +287,6 @@ internal struct AIConnectionAccessGateSavedPolicyTests { let coordinator = MainContentCoordinator( connection: makeConnection(id: id, policy: held), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState(), services: services(manager: DatabaseManager(connectionStorage: storage)) ) diff --git a/apple/TableProTests/Core/ChangeTracking/DataChangeManagerExtendedTests.swift b/apple/TableProTests/Core/ChangeTracking/DataChangeManagerExtendedTests.swift index 1e6da3421e..e59ad35035 100644 --- a/apple/TableProTests/Core/ChangeTracking/DataChangeManagerExtendedTests.swift +++ b/apple/TableProTests/Core/ChangeTracking/DataChangeManagerExtendedTests.swift @@ -44,8 +44,7 @@ struct DataChangeManagerExtendedTests { func recordRowInsertionStoresInInsertedRowData() { let manager = makeManager() manager.recordRowInsertion(rowID: insertedID(5), values: ["a", "b", "c"]) - let state = manager.saveState() - #expect(state.insertedRowData[insertedID(5)] == ["a", "b", "c"]) + #expect(manager.pending.insertedRowData[insertedID(5)] == ["a", "b", "c"]) } @Test("Record row insertion adds insert-type change with empty cellChanges") @@ -182,173 +181,95 @@ struct DataChangeManagerExtendedTests { #expect(manager.getModifiedColumnsForRow(.existing(0)).isEmpty) } - // MARK: - State Save/Restore + // MARK: - Describing the Table - @Test("saveState captures changes") - func saveStateCapturesChanges() { + @Test("Describing the table keeps the staged edits and their undo steps") + func describeTableKeepsTheUndoSteps() { let manager = makeManager() manager.recordCellChange( rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "Alice", newValue: "Bob" + oldValue: "Alice", newValue: "Bob", originalRow: ["1", "Alice", "a@test.com"] ) - let state = manager.saveState() - #expect(state.changes.count == 1) - #expect(state.changes[0].type == .update) - } - - @Test("saveState captures deleted row indices") - func saveStateCapturesDeletedRowIndices() { - let manager = makeManager() manager.recordRowDeletion(rowID: .existing(2), originalRow: ["3", "Charlie", "c@test.com"]) - let state = manager.saveState() - #expect(state.deletedRowIDs.contains(.existing(2))) - } - - @Test("saveState captures inserted row indices") - func saveStateCapturesInsertedRowIndices() { - let manager = makeManager() - manager.recordRowInsertion(rowID: insertedID(0), values: ["a", "b", "c"]) - let state = manager.saveState() - #expect(state.insertedRowIDs.contains(insertedID(0))) - } - - @Test("saveState captures modified cells") - func saveStateCapturesModifiedCells() { - let manager = makeManager() - manager.recordCellChange( - rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "Alice", newValue: "Bob" - ) - let state = manager.saveState() - #expect(state.modifiedCells[.existing(0)]?.contains(1) == true) - } - @Test("saveState captures inserted row data") - func saveStateCapturesInsertedRowData() { - let manager = makeManager() - manager.recordRowInsertion(rowID: insertedID(0), values: ["x", "y", "z"]) - let state = manager.saveState() - #expect(state.insertedRowData[insertedID(0)] == ["x", "y", "z"]) - } + describeTestTable(on: manager) - @Test("saveState captures columns and primary key") - func saveStateCapturesColumnsAndPrimaryKey() { - let manager = makeManager(columns: ["a", "b", "c"], pk: "a") - let state = manager.saveState() - #expect(state.columns == ["a", "b", "c"]) - #expect(state.primaryKeyColumns == ["a"]) - } - - @Test("Round-trip save/restore preserves hasChanges") - func roundTripPreservesHasChanges() { - let manager = makeManager() - manager.recordCellChange( - rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "Alice", newValue: "Bob" - ) - let state = manager.saveState() - manager.clearChanges() - #expect(!manager.hasChanges) - manager.restoreState(from: state, tableName: "test_table", databaseType: .mysql, generatedColumns: []) #expect(manager.hasChanges) + #expect(manager.canUndo) + manager.undoManagerProvider?()?.undo() + manager.undoManagerProvider?()?.undo() + #expect(!manager.isCellModified(rowID: .existing(0), columnIndex: 1)) + #expect(!manager.isRowDeleted(.existing(2))) + #expect(manager.changes.isEmpty) } - @Test("Round-trip save/restore preserves isRowDeleted") - func roundTripPreservesIsRowDeleted() { + @Test("Describing the table keeps the redo steps") + func describeTableKeepsTheRedoSteps() { let manager = makeManager() manager.recordRowDeletion(rowID: .existing(2), originalRow: ["3", "Charlie", "c@test.com"]) - let state = manager.saveState() - manager.clearChanges() - manager.restoreState(from: state, tableName: "test_table", databaseType: .mysql, generatedColumns: []) - #expect(manager.isRowDeleted(.existing(2))) - } - - @Test("Round-trip save/restore preserves isCellModified") - func roundTripPreservesIsCellModified() { - let manager = makeManager() - manager.recordCellChange( - rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "Alice", newValue: "Bob" - ) - let state = manager.saveState() - manager.clearChanges() - manager.restoreState(from: state, tableName: "test_table", databaseType: .mysql, generatedColumns: []) - #expect(manager.isCellModified(rowID: .existing(0), columnIndex: 1)) - } + manager.undoManagerProvider?()?.undo() + #expect(manager.canRedo) - @Test("Round-trip save/restore allows continued editing") - func roundTripCanContinueEditing() { - let manager = makeManager() - manager.recordCellChange( - rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "Alice", newValue: "Bob" - ) - let state = manager.saveState() - manager.clearChanges() - manager.restoreState(from: state, tableName: "test_table", databaseType: .mysql, generatedColumns: []) - manager.recordCellChange( - rowID: .existing(0), columnIndex: 2, columnName: "email", - oldValue: "a@test.com", newValue: "b@test.com" - ) - #expect(manager.changes.count == 1) - #expect(manager.changes[0].cellChanges.count == 2) - } + describeTestTable(on: manager) - @Test("Empty state round-trip preserves empty state") - func emptyStateRoundTrip() { - let manager = makeManager() - let state = manager.saveState() - manager.restoreState(from: state, tableName: "test_table", databaseType: .mysql, generatedColumns: []) - #expect(!manager.hasChanges) - #expect(manager.changes.isEmpty) + #expect(manager.canRedo) + manager.undoManagerProvider?()?.redo() + #expect(manager.isRowDeleted(.existing(2))) } - @Test("Restoring another tab's changes drops the undo steps recorded before it") - func restoreStateDropsTheOutgoingTabsUndoSteps() { + @Test("Describing the table updates what the edits are written against") + func describeTableUpdatesTheTableContext() { let manager = makeManager() - manager.recordCellChange( - rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "Alice", newValue: "Bob", originalRow: ["1", "Alice", "a@test.com"] - ) - manager.recordRowDeletion(rowID: .existing(2), originalRow: ["3", "Charlie", "c@test.com"]) - #expect(manager.canUndo) - manager.restoreState( - from: makeProductsTabState(), tableName: "products", databaseType: .mysql, generatedColumns: [] + manager.describeTable( + tableName: "products", + schemaName: "sales", + columns: ["sku", "title"], + primaryKeyColumns: ["sku"], + databaseType: .postgresql, + generatedColumns: ["title"], + rowMatchPolicy: .none, + columnTypeNames: ["sku": "text"] ) - #expect(!manager.canUndo) - manager.undoManagerProvider?()?.undo() - manager.undoManagerProvider?()?.undo() - #expect(!manager.isCellModified(rowID: .existing(0), columnIndex: 1)) - #expect(!manager.isRowDeleted(.existing(2))) - #expect(manager.changes.map(\.rowID) == [.existing(5)]) + #expect(manager.tableName == "products") + #expect(manager.schemaName == "sales") + #expect(manager.columns == ["sku", "title"]) + #expect(manager.primaryKeyColumns == ["sku"]) + #expect(manager.databaseType == .postgresql) + #expect(manager.generatedColumns == ["title"]) + #expect(manager.columnTypeNames == ["sku": "text"]) } - @Test("Restoring another tab's changes drops the redo steps recorded before it") - func restoreStateDropsTheOutgoingTabsRedoSteps() { + @Test("Configuring for a table drops the staged edits' undo steps") + func configureForTableDropsTheUndoSteps() { let manager = makeManager() manager.recordRowDeletion(rowID: .existing(2), originalRow: ["3", "Charlie", "c@test.com"]) - manager.undoManagerProvider?()?.undo() - #expect(manager.canRedo) + #expect(manager.canUndo) - manager.restoreState( - from: makeProductsTabState(), tableName: "products", databaseType: .mysql, generatedColumns: [] + manager.configureForTable( + tableName: "products", + columns: ["sku", "title"], + primaryKeyColumns: ["sku"], + databaseType: .mysql, + generatedColumns: [] ) - #expect(!manager.canRedo) - manager.undoManagerProvider?()?.redo() - #expect(!manager.isRowDeleted(.existing(2))) - #expect(manager.changes.map(\.rowID) == [.existing(5)]) + #expect(!manager.canUndo) + #expect(!manager.hasChanges) } - private func makeProductsTabState() -> TabChangeSnapshot { - let productsTab = makeManager(columns: ["sku", "title"], pk: "sku") - productsTab.recordCellChange( - rowID: .existing(5), columnIndex: 1, columnName: "title", - oldValue: "Lamp", newValue: "Desk Lamp", originalRow: ["P-5", "Lamp"] + private func describeTestTable(on manager: DataChangeManager) { + manager.describeTable( + tableName: "test_table", + schemaName: nil, + columns: ["id", "name", "email"], + primaryKeyColumns: ["id"], + databaseType: .mysql, + generatedColumns: [], + rowMatchPolicy: .none, + columnTypeNames: ["id": "INT"] ) - return productsTab.saveState() } // MARK: - discardChanges @@ -621,8 +542,7 @@ struct DataChangeManagerExtendedTests { ) #expect(manager.changes.count == 1) #expect(manager.changes[0].type == .insert) - let state = manager.saveState() - #expect(state.insertedRowData[insertedID(0)]?[1] == "hello") + #expect(manager.pending.insertedRowData[insertedID(0)]?[1] == "hello") } @Test("Insert then edit then undo reverts inserted row cell data") @@ -634,10 +554,8 @@ struct DataChangeManagerExtendedTests { oldValue: nil, newValue: "hello" ) manager.undoManagerProvider?()?.undo() - let state = manager.saveState() - /// `.null`, not a Swift nil. An inserted row holds an explicit SQL NULL for a cell with no - /// value, so undoing an edit restores `.null` rather than removing the entry. - #expect(state.insertedRowData[insertedID(0)]?[1] == .null) + // `.null`, not a Swift nil: an inserted row holds an explicit SQL NULL for a cell with no value. + #expect(manager.pending.insertedRowData[insertedID(0)]?[1] == .null) } @Test("Edit multiple cells in same row all tracked") @@ -877,8 +795,7 @@ struct DataChangeManagerExtendedTests { ) let cellChange = manager.changes[0].cellChanges.first { $0.columnIndex == 1 } #expect(cellChange?.newValue == "hello") - let state = manager.saveState() - #expect(state.insertedRowData[insertedID(0)]?[1] == "hello") + #expect(manager.pending.insertedRowData[insertedID(0)]?[1] == "hello") } } diff --git a/apple/TableProTests/Core/ChangeTracking/DataChangeModelsTests.swift b/apple/TableProTests/Core/ChangeTracking/DataChangeModelsTests.swift index 4640a24a54..07708a62d8 100644 --- a/apple/TableProTests/Core/ChangeTracking/DataChangeModelsTests.swift +++ b/apple/TableProTests/Core/ChangeTracking/DataChangeModelsTests.swift @@ -110,55 +110,6 @@ struct DataChangeModelsTests { #expect(rowChange.type == .insert) } - @Test("TabChangeSnapshot initializes as empty") - func tabPendingChangesInit() { - let pending = TabChangeSnapshot() - - #expect(pending.changes.isEmpty) - #expect(pending.deletedRowIDs.isEmpty) - #expect(pending.insertedRowIDs.isEmpty) - #expect(pending.modifiedCells.isEmpty) - #expect(pending.insertedRowData.isEmpty) - #expect(pending.primaryKeyColumns.isEmpty) - #expect(pending.columns.isEmpty) - } - - @Test("TabChangeSnapshot hasChanges is false when empty") - func tabPendingChangesHasChangesEmpty() { - let pending = TabChangeSnapshot() - - #expect(!pending.hasChanges) - } - - @Test("TabChangeSnapshot hasChanges is true with changes") - func tabPendingChangesHasChangesWithChanges() { - let rowChange = RowChange( - rowID: .existing(0), - type: .update - ) - - var pending = TabChangeSnapshot() - pending.changes = [rowChange] - - #expect(pending.hasChanges) - } - - @Test("TabChangeSnapshot hasChanges is true with deletedRowIDs") - func tabPendingChangesHasChangesWithDeleted() { - var pending = TabChangeSnapshot() - pending.deletedRowIDs = [.existing(1), .existing(2), .existing(3)] - - #expect(pending.hasChanges) - } - - @Test("TabChangeSnapshot hasChanges is true with insertedRowIDs") - func tabPendingChangesHasChangesWithInserted() { - var pending = TabChangeSnapshot() - pending.insertedRowIDs = [.inserted(UUID()), .inserted(UUID())] - - #expect(pending.hasChanges) - } - @Test("Array safe subscript with valid index") func arraySafeSubscriptValid() { let array = ["a", "b", "c"] diff --git a/apple/TableProTests/Core/ChangeTracking/EditedRowChangeTrackingTests.swift b/apple/TableProTests/Core/ChangeTracking/EditedRowChangeTrackingTests.swift index fff4ca6e57..5b7356e9c2 100644 --- a/apple/TableProTests/Core/ChangeTracking/EditedRowChangeTrackingTests.swift +++ b/apple/TableProTests/Core/ChangeTracking/EditedRowChangeTrackingTests.swift @@ -106,19 +106,16 @@ struct EditedRowDeletionTests { #expect(originals.first?.value == "US") } - @Test("A deleted row's parked edit survives a tab switch") - func parkedEditSurvivesSaveAndRestore() { + @Test("Restoring a deleted row brings back the edit parked under it") + func restoringADeletedRowBringsBackItsEdit() { let (manager, _) = makeManager() editCode(manager) manager.recordRowDeletion(rowID: .existing(0), originalRow: ["UK", "United States"]) - let state = manager.saveState() - let (restored, _) = makeManager() - restored.restoreState(from: state, tableName: "countries", databaseType: .mysql, generatedColumns: []) - restored.undoRowDeletion(rowID: .existing(0)) + manager.undoRowDeletion(rowID: .existing(0)) - #expect(restored.isCellModified(rowID: .existing(0), columnIndex: 0)) - #expect(restored.changes.first?.type == .update) + #expect(manager.isCellModified(rowID: .existing(0), columnIndex: 0)) + #expect(manager.changes.first?.type == .update) } @Test("Deleting an edited row from the grid deletes the row the server holds") @@ -308,13 +305,11 @@ struct UpdateSaveOrderTests { #expect(bound == [["6", "3"], ["2"], ["Cyd", "6"]]) } - @Test("A tab switch keeps the place of every edit of a row, so a later change sorts after them") - func aTabSwitchKeepsEveryRunsPlace() throws { + @Test("A change recorded after a row edited around a delete sorts after every edit of that row") + func aLaterChangeSortsAfterEveryRun() throws { let (manager, _) = EditAroundADelete.manager() EditAroundADelete.record(on: manager) - let state = manager.saveState() - manager.restoreState(from: state, tableName: "users", databaseType: .mysql, generatedColumns: []) manager.recordRowInsertion(rowID: .inserted(UUID()), values: ["9", "Di", "d@test.com"]) let verbs = try EditAroundADelete.verbs(manager.generateSQL()) diff --git a/apple/TableProTests/Core/ChangeTracking/FieldAbsenceTrackingTests.swift b/apple/TableProTests/Core/ChangeTracking/FieldAbsenceTrackingTests.swift index 5d96a38241..5f22fc6f44 100644 --- a/apple/TableProTests/Core/ChangeTracking/FieldAbsenceTrackingTests.swift +++ b/apple/TableProTests/Core/ChangeTracking/FieldAbsenceTrackingTests.swift @@ -105,15 +105,12 @@ struct FieldAbsencePendingChangesTests { #expect(pending.insertedRowData[inserted] == ["__DEFAULT__", "Ada", .null]) } - @Test("A snapshot carries the fields a deleted row did not have") - func snapshotKeepsDeletedRowAbsence() { + @Test("A deleted row's change carries the fields it did not have") + func deletedRowKeepsItsAbsence() { var pending = PendingChanges() pending.recordRowDeletion(rowID: row, originalRow: ["1", .null], absentColumns: [1]) - var restored = PendingChanges() - restored.restore(from: pending.snapshot(primaryKeyColumns: ["_id"], columns: ["_id", "nick"])) - - #expect(restored.change(forRow: row, type: .delete)?.absentColumns == [1]) + #expect(pending.change(forRow: row, type: .delete)?.absentColumns == [1]) } } diff --git a/apple/TableProTests/Core/ChangeTracking/PendingChangesTests.swift b/apple/TableProTests/Core/ChangeTracking/PendingChangesTests.swift index 73caf20ea5..4e9aff8596 100644 --- a/apple/TableProTests/Core/ChangeTracking/PendingChangesTests.swift +++ b/apple/TableProTests/Core/ChangeTracking/PendingChangesTests.swift @@ -201,29 +201,6 @@ struct PendingChangesReplayTests { } } -struct PendingChangesSnapshotTests { - @Test("Snapshot round-trip preserves state") - func snapshotRoundTrip() { - var pending = PendingChanges() - pending.recordCellChange( - rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "a", newValue: "b" - ) - pending.recordRowDeletion(rowID: .existing(5), originalRow: ["x"]) - pending.recordRowInsertion(rowID: insertedID(7), values: ["new"]) - - let snapshot = pending.snapshot(primaryKeyColumns: ["id"], columns: ["id", "name"]) - - var restored = PendingChanges() - restored.restore(from: snapshot) - - #expect(restored.changes.count == pending.changes.count) - #expect(restored.isRowDeleted(.existing(5))) - #expect(restored.isRowInserted(insertedID(7))) - #expect(restored.isCellModified(rowID: .existing(0), columnIndex: 1)) - } -} - struct PendingChangesLifecycleTests { @Test("Clear empties all internal state") func clearResets() { diff --git a/apple/TableProTests/Core/ChangeTracking/UnloadedValueWriteTests.swift b/apple/TableProTests/Core/ChangeTracking/UnloadedValueWriteTests.swift index e54e988caf..57d158297e 100644 --- a/apple/TableProTests/Core/ChangeTracking/UnloadedValueWriteTests.swift +++ b/apple/TableProTests/Core/ChangeTracking/UnloadedValueWriteTests.swift @@ -95,13 +95,4 @@ struct UnloadedValueWriteTests { let build = try manager.buildRowWrites(database: "d", schema: nil, containsTableOperation: false) #expect(build.operations.first?.preImage?[2] == .bytes(Data([5]))) } - - @Test("A value loaded for a tab in the background completes that tab's saved deletion") - func backgroundTabSnapshotTakesLoadedValue() { - let row = Self.page().rows[0] - var snapshot = TabChangeSnapshot() - snapshot.changes = [RowChange(rowID: row.id, type: .delete, originalRow: Array(row.values))] - snapshot.adoptLoadedValues([row.id: [2: .bytes(Data([5]))]]) - #expect(snapshot.changes.first?.originalRow?[2] == .bytes(Data([5]))) - } } diff --git a/apple/TableProTests/Core/Coordinators/FilterCommitRefusalTests.swift b/apple/TableProTests/Core/Coordinators/FilterCommitRefusalTests.swift index 0c6b4d163e..d515c5603d 100644 --- a/apple/TableProTests/Core/Coordinators/FilterCommitRefusalTests.swift +++ b/apple/TableProTests/Core/Coordinators/FilterCommitRefusalTests.swift @@ -16,7 +16,6 @@ struct FilterCommitRefusalTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(type: .etcd), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "(root)", query: "page three", tabType: .table, tableName: "(root)") @@ -44,7 +43,6 @@ struct FilterCommitRefusalTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(type: .mysql), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "users", query: "unfiltered", tabType: .table, tableName: "users") diff --git a/apple/TableProTests/Core/Coordinators/FilterRerunTests.swift b/apple/TableProTests/Core/Coordinators/FilterRerunTests.swift index 54025a8080..912495da00 100644 --- a/apple/TableProTests/Core/Coordinators/FilterRerunTests.swift +++ b/apple/TableProTests/Core/Coordinators/FilterRerunTests.swift @@ -22,7 +22,6 @@ struct FilterRerunTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(type: type), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "users", query: "SELECT * FROM users", tabType: .table) diff --git a/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift b/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift index 435a31ba59..27914afa19 100644 --- a/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift +++ b/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift @@ -88,7 +88,6 @@ struct RunAllSummaryResultTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { diff --git a/apple/TableProTests/Core/DataWrite/RowChangeStatementFactoryServerOwnedTests.swift b/apple/TableProTests/Core/DataWrite/RowChangeStatementFactoryServerOwnedTests.swift index 7f37204287..153d13ab84 100644 --- a/apple/TableProTests/Core/DataWrite/RowChangeStatementFactoryServerOwnedTests.swift +++ b/apple/TableProTests/Core/DataWrite/RowChangeStatementFactoryServerOwnedTests.swift @@ -165,13 +165,16 @@ struct RowChangeStatementFactoryServerOwnedTests { } @Test - func aRestoredTabKeepsItsColumnTypes() { + func aDescribedTabKeepsItsColumnTypes() { let manager = DataChangeManager() - manager.restoreState( - from: TabChangeSnapshot(), + manager.describeTable( tableName: "Ord", + schemaName: nil, + columns: ["ID"], + primaryKeyColumns: ["ID"], databaseType: .oracle, generatedColumns: [], + rowMatchPolicy: .none, columnTypeNames: ["ID": "number"] ) #expect(manager.columnTypeNames == ["ID": "number"]) diff --git a/apple/TableProTests/Core/Database/CredentialLeaseRoutingTests.swift b/apple/TableProTests/Core/Database/CredentialLeaseRoutingTests.swift index 6eb56754f3..98f477c2f6 100644 --- a/apple/TableProTests/Core/Database/CredentialLeaseRoutingTests.swift +++ b/apple/TableProTests/Core/Database/CredentialLeaseRoutingTests.swift @@ -104,10 +104,14 @@ struct CredentialLeaseRoutingTests { let scope = DatabaseScope(connectionId: connection.id, database: "app", schema: nil) let error = await #expect(throws: DatabaseError.self) { - try await manager.withScopedDriver(scope: scope, route: .sessionDriver, cancellation: .protectedWrite) { _ in } + try await manager.withScopedDriver( + scope: scope, route: .sessionDriver, cancellation: .protectedWrite, sessionWork: .statements + ) { _ in } } #expect(error?.localizedDescription.contains(DatabaseManager.parkedTransactionLostMessage(database: "app")) == true) - try await manager.withScopedDriver(scope: scope, route: .sessionDriver, cancellation: .protectedWrite) { _ in } + try await manager.withScopedDriver( + scope: scope, route: .sessionDriver, cancellation: .protectedWrite, sessionWork: .statements + ) { _ in } } @Test("A metadata read on the session driver leaves the lost transaction's report for the user's statement") @@ -126,7 +130,9 @@ struct CredentialLeaseRoutingTests { #expect(manager.sessionLanes.hasLoss(database: "", for: connection.id)) await #expect(throws: DatabaseError.self) { - try await manager.withScopedDriver(scope: scope, route: .sessionDriver, cancellation: .protectedWrite) { _ in } + try await manager.withScopedDriver( + scope: scope, route: .sessionDriver, cancellation: .protectedWrite, sessionWork: .statements + ) { _ in } } #expect(!manager.sessionLanes.hasLoss(database: "", for: connection.id)) } diff --git a/apple/TableProTests/Core/Database/MultiConnectionTests.swift b/apple/TableProTests/Core/Database/MultiConnectionTests.swift index 5b8c3ae98a..b89685c9bd 100644 --- a/apple/TableProTests/Core/Database/MultiConnectionTests.swift +++ b/apple/TableProTests/Core/Database/MultiConnectionTests.swift @@ -177,13 +177,11 @@ struct CoordinatorConnectionIsolationTests { let connId = UUID() let connection = TestFixtures.makeConnection(id: connId, name: "MySQL", database: "db_a", type: .mysql) let tabManager = QueryTabManager() - let changeManager = DataChangeManager() let toolbarState = ConnectionToolbarState() let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: changeManager, toolbarState: toolbarState ) defer { coordinator.teardown() } @@ -201,7 +199,6 @@ struct CoordinatorConnectionIsolationTests { let coordinator1 = MainContentCoordinator( connection: conn1, tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator1.teardown() } @@ -209,7 +206,6 @@ struct CoordinatorConnectionIsolationTests { let coordinator2 = MainContentCoordinator( connection: conn2, tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator2.teardown() } @@ -242,13 +238,11 @@ struct CoordinatorConnectionIsolationTests { let connId = UUID() let connection = TestFixtures.makeConnection(id: connId, name: "MySQL", database: "db_a", type: .mysql) let tabManager = QueryTabManager() - let changeManager = DataChangeManager() let toolbarState = ConnectionToolbarState() let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: changeManager, toolbarState: toolbarState ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/Core/Database/PreConnectScriptConsentTests.swift b/apple/TableProTests/Core/Database/PreConnectScriptConsentTests.swift index 5a858dc16a..90efdb030f 100644 --- a/apple/TableProTests/Core/Database/PreConnectScriptConsentTests.swift +++ b/apple/TableProTests/Core/Database/PreConnectScriptConsentTests.swift @@ -442,7 +442,6 @@ struct PreConnectScriptEntryPointTests { let coordinator = MainContentCoordinator( connection: fixture.connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState(), services: Self.services(databaseManager: fixture.manager) ) diff --git a/apple/TableProTests/Core/Database/SessionLanesTests.swift b/apple/TableProTests/Core/Database/SessionLanesTests.swift index ad7404e4b5..51c928f6b2 100644 --- a/apple/TableProTests/Core/Database/SessionLanesTests.swift +++ b/apple/TableProTests/Core/Database/SessionLanesTests.swift @@ -498,7 +498,7 @@ struct SessionLanesTests { await #expect(throws: (any Error).self) { try await DatabaseManager.shared.withScopedDriver( - scope: scope, route: .sessionDriver, cancellation: .untracked + scope: scope, route: .sessionDriver, cancellation: .untracked, sessionWork: .statements ) { _ in () } } @@ -506,7 +506,7 @@ struct SessionLanesTests { #expect(harness.home.disconnectCallCount == 1) #expect(DatabaseManager.shared.sessionLanes.parkedDriver(for: harness.connection.id, database: "app") === replacement) let ranOn = try await DatabaseManager.shared.withScopedDriver( - scope: scope, route: .sessionDriver, cancellation: .untracked + scope: scope, route: .sessionDriver, cancellation: .untracked, sessionWork: .statements ) { driver in ObjectIdentifier(driver) } #expect(ranOn == ObjectIdentifier(replacement)) } @@ -547,11 +547,11 @@ struct SessionLanesTests { let scope = DatabaseScope(connectionId: harness.connection.id, database: "app", schema: nil) await #expect(throws: (any Error).self) { try await DatabaseManager.shared.withScopedDriver( - scope: scope, route: .sessionDriver, cancellation: .untracked + scope: scope, route: .sessionDriver, cancellation: .untracked, sessionWork: .statements ) { _ in () } } let ranOn = try await DatabaseManager.shared.withScopedDriver( - scope: scope, route: .sessionDriver, cancellation: .untracked + scope: scope, route: .sessionDriver, cancellation: .untracked, sessionWork: .statements ) { driver in ObjectIdentifier(driver) } #expect(ranOn == ObjectIdentifier(replacement)) } @@ -661,7 +661,8 @@ struct SessionLanesTests { try await DatabaseManager.shared.withScopedDriver( scope: scope, route: DatabaseManager.shared.executionRoute(for: scope), - cancellation: .untracked + cancellation: .untracked, + sessionWork: .statements ) { _ in () } } #expect(!DatabaseManager.shared.sessionLanes.hasLoss(database: "app", for: harness.connection.id)) @@ -685,7 +686,7 @@ struct SessionLanesTests { #expect(manager.executionRoute(for: scope) == .sessionDriver) let error = await #expect(throws: DatabaseError.self) { try await manager.withScopedDriver( - scope: scope, route: manager.executionRoute(for: scope), cancellation: .untracked + scope: scope, route: manager.executionRoute(for: scope), cancellation: .untracked, sessionWork: .statements ) { _ in () } } let expected = DatabaseManager.sessionLostMessage( @@ -710,7 +711,7 @@ struct SessionLanesTests { let error = await #expect(throws: DatabaseError.self) { try await manager.withScopedDriver( - scope: scope, route: .sessionDriver, cancellation: .untracked + scope: scope, route: .sessionDriver, cancellation: .untracked, sessionWork: .statements ) { _ in () } } @@ -721,13 +722,13 @@ struct SessionLanesTests { let replacement = try #require(harness.opener.opened["app"]) #expect(harness.home.disconnectCallCount == 1) let ranOn = try await manager.withScopedDriver( - scope: scope, route: .sessionDriver, cancellation: .untracked + scope: scope, route: .sessionDriver, cancellation: .untracked, sessionWork: .statements ) { driver in ObjectIdentifier(driver) } #expect(ranOn == ObjectIdentifier(replacement)) } - @Test("A grid save on a database whose lane died with session state is refused once, and the next one runs") - func firstOwningTurnOnALostLaneTakesTheReport() async throws { + @Test("A grid save on a database whose lane died with session state reopens it, is told once, and leaves a statement's report") + func gridSaveOnALostLaneLeavesTheReport() async throws { let harness = makeHarness() defer { cleanUp(harness) } let manager = DatabaseManager.shared @@ -738,24 +739,56 @@ struct SessionLanesTests { manager.sessionStateLedger.record(SQLSessionStateEffect(creates: .temporaryObjects), on: harness.home, for: lane) await manager.closeTransportLanes(for: connectionId) { true } let scope = DatabaseScope(connectionId: connectionId, database: "app", schema: nil) + let expected = DatabaseManager.sessionLostMessage( + database: "app", loss: SessionLoss(transaction: false, state: .temporaryObjects) + ) - let error = await #expect(throws: DatabaseError.self) { + let saveError = await #expect(throws: DatabaseError.self) { try await manager.withScopedDriver( scope: scope, route: manager.executionRoute(for: scope), cancellation: .protectedWrite ) { _ in () } } - - let expected = DatabaseManager.sessionLostMessage( - database: "app", loss: SessionLoss(transaction: false, state: .temporaryObjects) - ) - #expect(error?.localizedDescription.contains(expected) == true) - #expect(harness.opener.opened["app"] == nil) - #expect(!manager.sessionLanes.hasLoss(database: "app", for: connectionId)) + #expect(saveError?.localizedDescription.contains(expected) == true) let savedOn = try await manager.withScopedDriver( scope: scope, route: manager.executionRoute(for: scope), cancellation: .protectedWrite ) { driver in ObjectIdentifier(driver) } + let reopened = try #require(harness.opener.opened["app"]) #expect(savedOn == ObjectIdentifier(reopened)) + #expect(manager.sessionLanes.hasLoss(database: "app", for: connectionId)) + let error = await #expect(throws: DatabaseError.self) { + try await manager.withScopedDriver( + scope: scope, route: manager.executionRoute(for: scope), cancellation: .untracked, sessionWork: .statements + ) { _ in () } + } + #expect(error?.localizedDescription.contains(expected) == true) + #expect(!manager.sessionLanes.hasLoss(database: "app", for: connectionId)) + let ranOn = try await manager.withScopedDriver( + scope: scope, route: manager.executionRoute(for: scope), cancellation: .untracked, sessionWork: .statements + ) { driver in ObjectIdentifier(driver) } + #expect(ranOn == ObjectIdentifier(reopened)) + #expect(harness.opener.openCount == 2) + } + + @Test("A lost session's kinds are asked without taking the report") + func lossKindsAreAskedWithoutTakingTheReport() { + let lanes = SessionLanes(opener: { _ in MockDatabaseDriver() }) + let connectionId = UUID() + lanes.markLost(database: "app", state: [.temporaryObjects, .sessionSettings], for: connectionId) + + #expect(lanes.lossIncludes(.temporaryObjects, database: "app", for: connectionId)) + #expect(!lanes.lossIncludes(.userVariables, database: "app", for: connectionId)) + #expect(!lanes.lossIncludes(.temporaryObjects, database: "logs", for: connectionId)) + #expect(lanes.anyLossIncludes(.temporaryObjects, for: connectionId)) + #expect(!lanes.anyLossIncludes(.listeners, for: connectionId)) + #expect(lanes.hasLoss(database: "app", for: connectionId)) + + // The app's copy and the statements' copy are taken apart. + #expect(lanes.takeAppLoss(database: "app", for: connectionId) != nil) + #expect(lanes.takeAppLoss(database: "app", for: connectionId) == nil) + #expect(lanes.hasLoss(database: "app", for: connectionId)) + #expect(lanes.takeLoss(database: "app", for: connectionId) != nil) + #expect(!lanes.hasLoss(database: "app", for: connectionId)) } @Test("A run notes what ran: every statement, through the one that failed, or only those a Stop let run") @@ -785,7 +818,9 @@ struct SessionLanesTests { #expect(ranOn == ObjectIdentifier(harness.home)) #expect(manager.sessionLanes.hasLoss(database: "app", for: harness.connection.id)) await #expect(throws: DatabaseError.self) { - try await manager.withScopedDriver(scope: scope, route: .sessionDriver, cancellation: .untracked) { _ in () } + try await manager.withScopedDriver( + scope: scope, route: .sessionDriver, cancellation: .untracked, sessionWork: .statements + ) { _ in () } } } diff --git a/apple/TableProTests/Core/Database/SessionRecoveryLoopTests.swift b/apple/TableProTests/Core/Database/SessionRecoveryLoopTests.swift index 8600b2c143..9f200a8a92 100644 --- a/apple/TableProTests/Core/Database/SessionRecoveryLoopTests.swift +++ b/apple/TableProTests/Core/Database/SessionRecoveryLoopTests.swift @@ -317,7 +317,9 @@ struct SessionRecoveryLoopTests { #expect(!manager.sessionTransactions.holdsTransaction(connectionId: fixture.id, container: "app")) #expect(manager.sessionLanes.hasLoss(database: "app", for: fixture.id)) let error = await #expect(throws: DatabaseError.self) { - try await manager.withScopedDriver(scope: scope, route: .sessionDriver, cancellation: .untracked) { _ in () } + try await manager.withScopedDriver( + scope: scope, route: .sessionDriver, cancellation: .untracked, sessionWork: .statements + ) { _ in () } } #expect(error?.localizedDescription.contains(DatabaseManager.parkedTransactionLostMessage(database: "app")) == true) #expect(!manager.sessionLanes.hasLoss(database: "app", for: fixture.id)) @@ -358,16 +360,27 @@ struct SessionRecoveryLoopTests { await loop.value } - private func runNextStatement(_ fixture: Fixture, ownsSessionState: Bool = true) async throws { - let scope = DatabaseScope(connectionId: fixture.id, database: "app", schema: nil) + private func runNextStatement( + _ fixture: Fixture, + sessionWork: SessionWork = .statements, + onTemporaryTable: Bool = false + ) async throws { + let table = DatabaseScope(connectionId: fixture.id, database: "app", schema: nil) try await fixture.manager.withScopedDriver( - scope: scope, route: .sessionDriver, cancellation: .untracked, ownsSessionState: ownsSessionState + scope: onTemporaryTable ? table.sessionBound : table, + route: .sessionDriver, + cancellation: .untracked, + sessionWork: sessionWork ) { _ in () } } - private func nextStatementRefusal(_ fixture: Fixture) async -> DatabaseError? { + private func nextStatementRefusal( + _ fixture: Fixture, + sessionWork: SessionWork = .statements, + onTemporaryTable: Bool = false + ) async -> DatabaseError? { do { - try await runNextStatement(fixture) + try await runNextStatement(fixture, sessionWork: sessionWork, onTemporaryTable: onTemporaryTable) return nil } catch { return error as? DatabaseError @@ -413,10 +426,34 @@ struct SessionRecoveryLoopTests { await cleanUp(fixture) } - // A grid save, an Explain or an MCP statement takes the report as the user's statement would, as a lost - // transaction's report always went. - @Test("The first turn that owns the session after the loss is refused once, whatever work it is, and the next runs") - func firstOwningTurnTakesTheStateReport() async throws { + @Test("The app's own work and the next statement are each refused once with the whole loss; reads never are") + func appWorkAndStatementsAreEachToldOnce() async throws { + let fixture = makeFixture() + let manager = fixture.manager + fixture.driver.sessionTransactionStateToReturn = .inTransaction + try await runUserStatements(["SET XACT_ABORT ON"], on: fixture) + + try await recover(fixture) + + let expected = DatabaseManager.sessionLostMessage( + database: "app", loss: SessionLoss(transaction: true, state: .sessionSettings) + ) + // A grid save would have joined the lost transaction, so it is not let to commit on its own unannounced. + let appRefusal = await nextStatementRefusal(fixture, sessionWork: .app) + #expect(appRefusal?.localizedDescription.contains(expected) == true) + try await runNextStatement(fixture, sessionWork: .app) + try await runNextStatement(fixture, sessionWork: .independent) + #expect(manager.sessionLanes.hasLoss(database: "app", for: fixture.id)) + + let refusal = await nextStatementRefusal(fixture) + #expect(refusal?.localizedDescription.contains(expected) == true) + #expect(!manager.sessionLanes.hasLoss(database: "app", for: fixture.id)) + try await runNextStatement(fixture) + await cleanUp(fixture) + } + + @Test("Work on a temporary table the lost session took is refused without taking the report, until a statement takes it") + func temporaryTableWorkIsRefusedWhileTheLossStands() async throws { let fixture = makeFixture() let manager = fixture.manager fixture.driver.sessionTransactionStateToReturn = .idle @@ -424,16 +461,22 @@ struct SessionRecoveryLoopTests { try await recover(fixture) - let scope = DatabaseScope(connectionId: fixture.id, database: "app", schema: nil) - let error = await #expect(throws: DatabaseError.self) { - try await manager.withScopedDriver(scope: scope, route: .sessionDriver, cancellation: .protectedWrite) { _ in () } - } + let gone = DatabaseManager.temporaryTableLostMessage(database: "app") + let appRefusal = await nextStatementRefusal(fixture, sessionWork: .app, onTemporaryTable: true) + #expect(appRefusal?.localizedDescription.contains(gone) == true) + let readRefusal = await nextStatementRefusal(fixture, sessionWork: .independent, onTemporaryTable: true) + #expect(readRefusal?.localizedDescription.contains(gone) == true) + #expect(await nextStatementRefusal(fixture, sessionWork: .app) != nil) + try await runNextStatement(fixture, sessionWork: .app) + #expect(manager.sessionLanes.hasLoss(database: "app", for: fixture.id)) + + let statementRefusal = await nextStatementRefusal(fixture, onTemporaryTable: true) let expected = DatabaseManager.sessionLostMessage( database: "app", loss: SessionLoss(transaction: false, state: .temporaryObjects) ) - #expect(error?.localizedDescription.contains(expected) == true) + #expect(statementRefusal?.localizedDescription.contains(expected) == true) #expect(!manager.sessionLanes.hasLoss(database: "app", for: fixture.id)) - try await runNextStatement(fixture) + try await runNextStatement(fixture, sessionWork: .app, onTemporaryTable: true) await cleanUp(fixture) } @@ -504,7 +547,7 @@ struct SessionRecoveryLoopTests { try await runUserStatements(["DECLARE c CURSOR FOR SELECT 1"], on: fixture) try await recover(fixture) - try await runNextStatement(fixture, ownsSessionState: false) + try await runNextStatement(fixture, sessionWork: .independent) #expect(manager.sessionLanes.hasLoss(database: "app", for: fixture.id)) let refusal = await nextStatementRefusal(fixture) diff --git a/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift b/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift index 7f5b437b5d..7bec8cb96f 100644 --- a/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift +++ b/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift @@ -344,14 +344,14 @@ struct SessionTransactionTrackerTests { } _ = try await DatabaseManager.shared.withScopedDriver( scope: Self.scope(connection.id), route: .sessionDriver, cancellation: .untracked, - ownsSessionState: false, readsOnly: true + sessionWork: .independent, readsOnly: true ) { driver in try await driver.execute(query: "SELECT 1") } #expect(Self.tracker.isCurrent(hold)) _ = try await DatabaseManager.shared.withScopedDriver( - scope: Self.scope(connection.id), route: .sessionDriver, cancellation: .untracked, ownsSessionState: false + scope: Self.scope(connection.id), route: .sessionDriver, cancellation: .untracked, sessionWork: .independent ) { driver in try await driver.execute(query: "INSERT INTO t VALUES (1)") } diff --git a/apple/TableProTests/Core/Execution/CancelledExecutionOwnershipTests.swift b/apple/TableProTests/Core/Execution/CancelledExecutionOwnershipTests.swift index dcc112ceca..d21d999177 100644 --- a/apple/TableProTests/Core/Execution/CancelledExecutionOwnershipTests.swift +++ b/apple/TableProTests/Core/Execution/CancelledExecutionOwnershipTests.swift @@ -23,7 +23,6 @@ struct CancelledExecutionOwnershipTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) return (coordinator, tabManager) diff --git a/apple/TableProTests/Core/MCP/Protocol/Tools/FocusQueryTabToolTests.swift b/apple/TableProTests/Core/MCP/Protocol/Tools/FocusQueryTabToolTests.swift index c33d65a2de..1d443ba25b 100644 --- a/apple/TableProTests/Core/MCP/Protocol/Tools/FocusQueryTabToolTests.swift +++ b/apple/TableProTests/Core/MCP/Protocol/Tools/FocusQueryTabToolTests.swift @@ -95,7 +95,6 @@ struct FocusQueryTabSelectionTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) return (coordinator, tabs.map(\.id)) diff --git a/apple/TableProTests/Core/Scripting/ScriptingTabResultTests.swift b/apple/TableProTests/Core/Scripting/ScriptingTabResultTests.swift new file mode 100644 index 0000000000..ff7c73001d --- /dev/null +++ b/apple/TableProTests/Core/Scripting/ScriptingTabResultTests.swift @@ -0,0 +1,43 @@ +// +// ScriptingTabResultTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +extension GlobalStateSuites { + @MainActor + struct ScriptingTabResultTests { + @Test("A script reading a background tab's result leaves out the rows that tab marked for deletion") + func backgroundTabSkipsItsDeletedRows() throws { + let connection = TestFixtures.makeConnection(database: "db_a") + let saved = ConnectionStorage.shared.loadConnections() + ConnectionStorage.shared.saveConnections(saved + [connection]) + defer { ConnectionStorage.shared.saveConnections(saved) } + let coordinator = SessionStateFactory.create(connection: connection, payload: nil).coordinator + defer { coordinator.teardown() } + let background = QueryTab(title: "users", query: "SELECT * FROM users", tabType: .table, tableName: "users") + coordinator.tabManager.tabs.append(background) + coordinator.setActiveTableRows( + TableRows.from( + queryRows: [[.text("1")], [.text("2")], [.text("3")]], + columns: ["id"], + columnTypes: [.text(rawType: nil)] + ), + for: background.id + ) + coordinator.changeManager(forTab: background.id).recordRowDeletion(rowID: .existing(1), originalRow: [.text("2")]) + let selected = QueryTab(title: "Query 1", query: "SELECT 1", tabType: .query) + coordinator.tabManager.tabs.append(selected) + coordinator.tabManager.selectedTabId = selected.id + + let record = ScriptingSnapshot.result(ofTab: background.id, connectionId: connection.id, selectedOnly: false) + + let rows = try #require(record[ScriptingKeys.QueryResult.rows] as? [[String: Any]]) + #expect(rows.compactMap { $0[ScriptingKeys.ResultRow.values] as? [String] } == [["1"], ["3"]]) + } + } +} diff --git a/apple/TableProTests/Core/Services/EditorTabConnectionMovePolicyTests.swift b/apple/TableProTests/Core/Services/EditorTabConnectionMovePolicyTests.swift index 5346e27113..738afcd1dd 100644 --- a/apple/TableProTests/Core/Services/EditorTabConnectionMovePolicyTests.swift +++ b/apple/TableProTests/Core/Services/EditorTabConnectionMovePolicyTests.swift @@ -5,6 +5,7 @@ import Foundation @testable import TablePro +import TableProPluginKit import Testing @MainActor @@ -38,7 +39,6 @@ struct EditorTabConnectionMovePolicyTests { MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } @@ -75,14 +75,13 @@ struct EditorTabConnectionMovePolicyTests { #expect(coordinator.canMoveTabToConnection(tabId)) } - @Test("Grid edits snapshotted on a background tab hold it back") + @Test("Grid edits staged on a background tab hold it back") func backgroundGridEditsStay() { let coordinator = makeCoordinator() defer { coordinator.teardown() } let selected = addQueryTab(to: coordinator) - let edited = addQueryTab(to: coordinator) { tab in - tab.pendingChanges.deletedRowIDs = [.existing(0)] - } + let edited = addQueryTab(to: coordinator) + coordinator.changeManager(forTab: edited).recordRowDeletion(rowID: .existing(0), originalRow: ["1"]) coordinator.tabManager.selectedTabId = selected #expect(!coordinator.canMoveTabToConnection(edited)) diff --git a/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowChromeTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowChromeTests.swift index 2c600f982e..a6f6ca61be 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowChromeTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ConnectionWindowChromeTests.swift @@ -187,7 +187,6 @@ struct ConnectionWindowChromeTests { let coordinator = MainContentCoordinator( connection: record, tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState(connection: record) ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/Core/Services/Query/UnloadedValueReaderTests.swift b/apple/TableProTests/Core/Services/Query/UnloadedValueReaderTests.swift index ce41c48541..5036556d81 100644 --- a/apple/TableProTests/Core/Services/Query/UnloadedValueReaderTests.swift +++ b/apple/TableProTests/Core/Services/Query/UnloadedValueReaderTests.swift @@ -173,6 +173,33 @@ struct UnloadedValueLoadTests { #expect(rows.unloadedByteCount(row: 0, column: 1) == 10) } + @Test("A value loaded for a tab in the background completes that tab's staged deletion") + func backgroundTabDeletionTakesTheLoadedValue() async { + let connection = TestFixtures.makeConnection(type: .mysql) + let driver = BlobAnsweringDriver(connection: connection, rows: [["2", .bytes(Data([7, 7]))]]) + let fixture = CoordinatorFixture(connection: connection, driver: driver) + var tab = QueryTab(title: "files", query: "", tabType: .table, tableName: "files") + tab.tableContext.primaryKeyColumns = ["id"] + fixture.addTab(tab, rows: TableRows.from( + queryRows: [["1", .null], ["2", .null]], + columns: ["id", "data"], + columnTypes: [.integer(rawType: "INT"), .blob(rawType: "LONGBLOB")], + unloadedCells: [0: [1: 10], 1: [1: 20]] + )) + let edits = fixture.coordinator.changeManager(forTab: tab.id) + edits.recordRowDeletion(rowID: .existing(1), originalRow: ["2", .null]) + let other = fixture.addTab(QueryTab(title: "Query 1", query: "SELECT 1", tabType: .query)) + + let loaded = await fixture.coordinator.loadUnloadedValues( + tabId: tab.id, rowIDs: [.existing(1)], columns: IndexSet(integer: 1) + ) + + #expect(loaded) + #expect(fixture.tabManager.selectedTabId == other.id) + #expect(edits.changes.first?.originalRow == ["2", .bytes(Data([7, 7]))]) + #expect(fixture.coordinator.existingChangeManager(forTab: other.id)?.hasChanges != true) + } + @Test("A row the table no longer holds leaves its cell unloaded and reports it") func missingRowStaysUnloaded() async { let connection = TestFixtures.makeConnection(type: .mysql) diff --git a/apple/TableProTests/Core/Services/RowPasteForeignTextTests.swift b/apple/TableProTests/Core/Services/RowPasteForeignTextTests.swift index d74fe0ddb7..7289e114ce 100644 --- a/apple/TableProTests/Core/Services/RowPasteForeignTextTests.swift +++ b/apple/TableProTests/Core/Services/RowPasteForeignTextTests.swift @@ -234,9 +234,8 @@ struct RowPasteBatchRecordingTests { ) ]) - let state = changeManager.saveState() - #expect(state.insertedRowData[first] == ["1", "now()"]) - #expect(state.insertedRowData[second] == ["2", nil]) + #expect(changeManager.pending.insertedRowData[first] == ["1", "now()"]) + #expect(changeManager.pending.insertedRowData[second] == ["2", nil]) #expect(changeManager.expressionColumns(forRow: first) == [1]) let secondChange = changeManager.changes.first { $0.rowID == second } #expect(secondChange?.absentColumns == [1]) diff --git a/apple/TableProTests/Core/Storage/ConnectionStoreTagRemovalTests.swift b/apple/TableProTests/Core/Storage/ConnectionStoreTagRemovalTests.swift index 0a2672d69d..64ad4ffb3f 100644 --- a/apple/TableProTests/Core/Storage/ConnectionStoreTagRemovalTests.swift +++ b/apple/TableProTests/Core/Storage/ConnectionStoreTagRemovalTests.swift @@ -1,5 +1,6 @@ import CryptoKit import Foundation +import os @testable import TablePro import TableProSyncTransport import Testing @@ -11,6 +12,11 @@ private struct KeyOnlySource: IntegrityKeySource { func key() -> SymmetricKey? { source.key() } } +private struct StampedRow: Codable, Equatable { + let id: Int + let name: String +} + @MainActor struct ConnectionStoreTagRemovalTests { private let keychain = InMemoryKeychain() @@ -119,4 +125,201 @@ struct ConnectionStoreTagRemovalTests { #expect(storage.loadConnections().count == 1) #expect(storage.storeIsTrusted) } + + private func makeStore(at fileURL: URL) -> IntegrityStampedFileStore { + IntegrityStampedFileStore( + fileURL: fileURL, + label: "rows.json", + logger: Logger(subsystem: "com.TablePro", category: "ConnectionStoreTagRemovalTests"), + userSaveEstablishesTrust: true, + integrity: integrity + ) + } + + private func saveTwice(_ store: IntegrityStampedFileStore) { + #expect(store.load()?.isEmpty == true) + #expect(store.save([StampedRow(id: 1, name: "One")])) + #expect(store.save([StampedRow(id: 1, name: "One"), StampedRow(id: 2, name: "Two")])) + } + + @Test("A record that does not decode is skipped and written back unchanged by the next save") + func undecodableRecordSurvivesASave() throws { + let fileURL = try makeFileURL() + let unreadable = #"{"id":"seven","port":5432,"ratio":0.25,"flags":[true,null],"nested":{"big":9007199254740993}}"# + try Data(#"[{"id":1,"name":"One"},\#(unreadable),{"id":2,"name":"Two"}]"#.utf8).write(to: fileURL) + let store = makeStore(at: fileURL) + + #expect(store.load() == [StampedRow(id: 1, name: "One"), StampedRow(id: 2, name: "Two")]) + #expect(store.save([StampedRow(id: 1, name: "One")])) + + let written = try Data(contentsOf: fileURL) + let rows = try #require(try JSONSerialization.jsonObject(with: written) as? [NSDictionary]) + let original = try #require(try JSONSerialization.jsonObject(with: Data(unreadable.utf8)) as? NSDictionary) + #expect(rows.count == 2) + #expect(rows.last == original) + let text = try #require(String(bytes: written, encoding: .utf8)) + #expect(text.contains("9007199254740993")) + #expect(makeStore(at: fileURL).load() == [StampedRow(id: 1, name: "One")]) + } + + @Test("One connection that does not decode keeps the rest of connections.json") + func undecodableConnectionKeepsTheLibrary() throws { + let fileURL = try makeFileURL() + let suite = try EphemeralDefaults() + let connection = TestFixtures.makeConnection(name: "Kept") + let stored = try #require(String(bytes: JSONEncoder().encode(StoredConnection(from: connection)), encoding: .utf8)) + let unreadable = #"{"id":"not-a-uuid","name":"From a newer build"}"# + try Data("[\(stored),\(unreadable)]".utf8).write(to: fileURL) + let storage = ConnectionStorage( + fileURL: fileURL, + userDefaults: suite.defaults, + syncTracker: SyncChangeTracker(metadataStorage: SyncMetadataStorage(userDefaults: suite.defaults)), + keychain: keychain, + integrity: integrity + ) + + #expect(storage.loadConnections().map { $0.name } == ["Kept"]) + #expect(!storage.lastLoadFailed) + + var renamed = connection + renamed.name = "Renamed" + #expect(storage.saveConnections([renamed])) + + let rows = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: fileURL)) as? [NSDictionary]) + #expect(rows.count == 2) + #expect(rows.last?["name"] as? String == "From a newer build") + } + + @Test("A save keeps the file it replaces, with its tag, as the backup") + func saveKeepsThePreviousFileAsBackup() throws { + let fileURL = try makeFileURL() + let store = makeStore(at: fileURL) + #expect(store.load()?.isEmpty == true) + #expect(store.save([StampedRow(id: 1, name: "One")])) + #expect(!FileManager.default.fileExists(atPath: store.backupURL.path)) + let first = try Data(contentsOf: fileURL) + let firstTag = try Data(contentsOf: ConnectionStoreIntegrity.tagURL(for: fileURL)) + + #expect(store.save([StampedRow(id: 2, name: "Two")])) + + #expect(try Data(contentsOf: store.backupURL) == first) + #expect(try Data(contentsOf: ConnectionStoreIntegrity.tagURL(for: store.backupURL)) == firstTag) + } + + @Test("A file that no longer parses is restored from the backup, which keeps its own trust") + func damagedFileIsRestoredFromBackup() throws { + let fileURL = try makeFileURL() + saveTwice(makeStore(at: fileURL)) + let damaged = Data(#"[{"id":1,"name":"One"},{"id":2"#.utf8) + try damaged.write(to: fileURL) + + let store = makeStore(at: fileURL) + + #expect(store.load() == [StampedRow(id: 1, name: "One")]) + #expect(store.isTrusted) + let backup = try Data(contentsOf: store.backupURL) + #expect(try Data(contentsOf: store.unreadableURL) == damaged) + #expect(try Data(contentsOf: fileURL) == backup) + } + + @Test("A file that no longer parses never replaces the backup") + func damagedFileNeverBecomesTheBackup() throws { + let fileURL = try makeFileURL() + let store = makeStore(at: fileURL) + saveTwice(store) + let backup = try Data(contentsOf: store.backupURL) + let backupTag = try Data(contentsOf: ConnectionStoreIntegrity.tagURL(for: store.backupURL)) + try Data("not json".utf8).write(to: fileURL) + + #expect(store.save([StampedRow(id: 3, name: "Three")])) + + #expect(try Data(contentsOf: store.backupURL) == backup) + #expect(try Data(contentsOf: ConnectionStoreIntegrity.tagURL(for: store.backupURL)) == backupTag) + } + + @Test("A backup with no tag is restored untrusted, even on a store never tagged") + func untaggedBackupIsRestoredUntrusted() throws { + let stampedURL = try makeFileURL() + let stamped = makeStore(at: stampedURL) + saveTwice(stamped) + try FileManager.default.removeItem(at: ConnectionStoreIntegrity.tagURL(for: stamped.backupURL)) + try Data().write(to: stampedURL) + + let reloaded = makeStore(at: stampedURL) + #expect(reloaded.load() == [StampedRow(id: 1, name: "One")]) + #expect(!reloaded.isTrusted) + + let neverTaggedURL = try makeFileURL() + let neverTagged = makeStore(at: neverTaggedURL) + try JSONEncoder().encode([StampedRow(id: 1, name: "Planted")]).write(to: neverTagged.backupURL) + try Data("not json".utf8).write(to: neverTaggedURL) + + #expect(neverTagged.load() == [StampedRow(id: 1, name: "Planted")]) + #expect(!neverTagged.isTrusted) + #expect(!FileManager.default.fileExists(atPath: ConnectionStoreIntegrity.tagURL(for: neverTaggedURL).path)) + + let loadedAgain = makeStore(at: neverTaggedURL) + #expect(loadedAgain.load() == [StampedRow(id: 1, name: "Planted")]) + #expect(!loadedAgain.isTrusted) + } + + @Test("A store changed outside TablePro sets its unreadable records aside, so a save never signs them") + func untrustedStoreSetsUnreadableRecordsAside() throws { + let fileURL = try makeFileURL() + let store = makeStore(at: fileURL) + #expect(store.load()?.isEmpty == true) + #expect(store.save([StampedRow(id: 1, name: "One")])) + let unreadable = #"{"id":"planted","command":"curl"}"# + try Data(#"[{"id":1,"name":"One"},\#(unreadable)]"#.utf8).write(to: fileURL) + + let reloaded = makeStore(at: fileURL) + #expect(reloaded.load() == [StampedRow(id: 1, name: "One")]) + #expect(!reloaded.isTrusted) + #expect(reloaded.save([StampedRow(id: 1, name: "One")])) + + let rows = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: fileURL)) as? [NSDictionary]) + #expect(rows.count == 1) + let setAside = try #require( + try JSONSerialization.jsonObject(with: Data(contentsOf: reloaded.unreadableRecordsURL)) as? [NSDictionary] + ) + #expect(setAside.first?["id"] as? String == "planted") + } + + @Test("Loading the same changed file again sets its unreadable records aside once") + func settingAsideTwiceKeepsOneCopy() throws { + let fileURL = try makeFileURL() + let store = makeStore(at: fileURL) + #expect(store.load()?.isEmpty == true) + #expect(store.save([StampedRow(id: 1, name: "One")])) + try Data(#"[{"id":1,"name":"One"},{"id":"planted"}]"#.utf8).write(to: fileURL) + + _ = makeStore(at: fileURL).load() + _ = makeStore(at: fileURL).load() + + let setAside = try #require( + try JSONSerialization.jsonObject(with: Data(contentsOf: store.unreadableRecordsURL)) as? [NSDictionary] + ) + #expect(setAside.count == 1) + } + + @Test("Unreadable records that cannot be set aside are written back and never signed") + func recordsThatCannotBeSetAsideStayUnsigned() throws { + let fileURL = try makeFileURL() + let store = makeStore(at: fileURL) + #expect(store.load()?.isEmpty == true) + #expect(store.save([StampedRow(id: 1, name: "One")])) + try Data(#"[{"id":1,"name":"One"},{"id":"planted"}]"#.utf8).write(to: fileURL) + try FileManager.default.createDirectory(at: store.unreadableRecordsURL, withIntermediateDirectories: true) + + let reloaded = makeStore(at: fileURL) + #expect(reloaded.load() == [StampedRow(id: 1, name: "One")]) + #expect(reloaded.save([StampedRow(id: 1, name: "One")])) + + #expect(!reloaded.isTrusted) + let rows = try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: fileURL)) as? [NSDictionary]) + #expect(rows.count == 2) + let again = makeStore(at: fileURL) + _ = again.load() + #expect(!again.isTrusted) + } } diff --git a/apple/TableProTests/Core/WritePolicy/MCPWritePolicyMatrixTests.swift b/apple/TableProTests/Core/WritePolicy/MCPWritePolicyMatrixTests.swift index ed0947f0fa..ed2e01829d 100644 --- a/apple/TableProTests/Core/WritePolicy/MCPWritePolicyMatrixTests.swift +++ b/apple/TableProTests/Core/WritePolicy/MCPWritePolicyMatrixTests.swift @@ -192,7 +192,6 @@ extension GlobalStateSuites { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) coordinator.registerEagerly() diff --git a/apple/TableProTests/Helpers/CoordinatorFixture.swift b/apple/TableProTests/Helpers/CoordinatorFixture.swift index 5edcff795b..a2d7b5ccf9 100644 --- a/apple/TableProTests/Helpers/CoordinatorFixture.swift +++ b/apple/TableProTests/Helpers/CoordinatorFixture.swift @@ -6,7 +6,7 @@ final class CoordinatorFixture { let connection: DatabaseConnection let tabManager = QueryTabManager() - let changeManager = DataChangeManager() + var changeManager: DataChangeManager { coordinator.changeManager } let coordinator: MainContentCoordinator private let injectedSession: Bool @@ -25,7 +25,6 @@ final class CoordinatorFixture { coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: changeManager, toolbarState: ConnectionToolbarState(), services: services ) diff --git a/apple/TableProTests/Models/QueryTabConnectionMoveTests.swift b/apple/TableProTests/Models/QueryTabConnectionMoveTests.swift index 2b85de1b65..608cba117d 100644 --- a/apple/TableProTests/Models/QueryTabConnectionMoveTests.swift +++ b/apple/TableProTests/Models/QueryTabConnectionMoveTests.swift @@ -79,7 +79,6 @@ struct QueryTabConnectionMoveTests { source: .user ) tab.selectionSnapshot = GridSelectionSnapshot(rowIDs: [.existing(2)], rectangles: [], activeCell: nil, anchor: nil) - tab.pendingChanges.deletedRowIDs = [.existing(0)] let moved = move(tab) @@ -90,7 +89,6 @@ struct QueryTabConnectionMoveTests { #expect(moved.pendingRestoredSort == nil) #expect(moved.restoredSortSource == .unset) #expect(moved.selectionSnapshot.isEmpty) - #expect(!moved.pendingChanges.hasChanges) #expect(moved.display.resultSets.isEmpty) } diff --git a/apple/TableProTests/Services/MainWindowToolbarNativeContractTests.swift b/apple/TableProTests/Services/MainWindowToolbarNativeContractTests.swift index ddfefcf26d..23bd1d6387 100644 --- a/apple/TableProTests/Services/MainWindowToolbarNativeContractTests.swift +++ b/apple/TableProTests/Services/MainWindowToolbarNativeContractTests.swift @@ -261,7 +261,6 @@ struct MainWindowToolbarNativeContractTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(database: "db_a"), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -366,7 +365,6 @@ struct MainWindowToolbarNativeContractTests { let coordinator = MainContentCoordinator( connection: record, tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState(connection: record) ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/ViewModels/ERDiagramSchemaEditsTests.swift b/apple/TableProTests/ViewModels/ERDiagramSchemaEditsTests.swift index b52fb16d24..5889183d97 100644 --- a/apple/TableProTests/ViewModels/ERDiagramSchemaEditsTests.swift +++ b/apple/TableProTests/ViewModels/ERDiagramSchemaEditsTests.swift @@ -393,7 +393,6 @@ struct ERDiagramSchemaEditsTests { let coordinator = MainContentCoordinator( connection: fixture.connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) tabManager.addERDiagramTab(schemaKey: "shop.public", databaseName: "shop", schemaName: "public") @@ -426,7 +425,6 @@ struct ERDiagramSchemaEditsTests { let coordinator = MainContentCoordinator( connection: fixture.connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) tabManager.addERDiagramTab(schemaKey: "shop.public", databaseName: "shop", schemaName: "public") diff --git a/apple/TableProTests/Views/DataGrid/RowVisualIndexTests.swift b/apple/TableProTests/Views/DataGrid/RowVisualIndexTests.swift index 5d8ba4999e..8c6650f901 100644 --- a/apple/TableProTests/Views/DataGrid/RowVisualIndexTests.swift +++ b/apple/TableProTests/Views/DataGrid/RowVisualIndexTests.swift @@ -96,7 +96,7 @@ struct UndoStepRepaintTests { needsRowRemoval: false, needsRowRestore: false, restoreRow: nil - )) + ), forTab: tab.id) var repainted = IndexSet() var marksRepainted = false diff --git a/apple/TableProTests/Views/Editor/FoldTabOwnershipTests.swift b/apple/TableProTests/Views/Editor/FoldTabOwnershipTests.swift index f77a91d17b..3fca9a21c6 100644 --- a/apple/TableProTests/Views/Editor/FoldTabOwnershipTests.swift +++ b/apple/TableProTests/Views/Editor/FoldTabOwnershipTests.swift @@ -23,7 +23,6 @@ struct FoldTabOwnershipTests { type: .mysql ), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } diff --git a/apple/TableProTests/Views/Main/AIChatInsertQueryTests.swift b/apple/TableProTests/Views/Main/AIChatInsertQueryTests.swift index 5fe1ffc01f..a5d8730f73 100644 --- a/apple/TableProTests/Views/Main/AIChatInsertQueryTests.swift +++ b/apple/TableProTests/Views/Main/AIChatInsertQueryTests.swift @@ -72,7 +72,6 @@ struct AIChatInsertQueryTests { MainContentCoordinator( connection: TestFixtures.makeConnection(database: "db"), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } diff --git a/apple/TableProTests/Views/Main/CatalogChangeWindowTests.swift b/apple/TableProTests/Views/Main/CatalogChangeWindowTests.swift index fbeb76328f..fa6ccae5b1 100644 --- a/apple/TableProTests/Views/Main/CatalogChangeWindowTests.swift +++ b/apple/TableProTests/Views/Main/CatalogChangeWindowTests.swift @@ -204,10 +204,10 @@ struct CatalogChangeWindowTests { let connection = TestFixtures.makeConnection(database: "shop") defer { DatabaseManager.shared.removeSession(for: connection.id) } let (coordinator, tabManager) = makeCoordinator(connection: connection) - var selected = Self.loadedTab("users", rowCount: 3, totalRowCount: 42, in: coordinator) - selected.pendingChanges.deletedRowIDs = [.existing(0)] + let selected = Self.loadedTab("users", rowCount: 3, totalRowCount: 42, in: coordinator) tabManager.tabs = [selected] tabManager.selectedTabId = selected.id + coordinator.changeManager(forTab: selected.id).recordRowDeletion(rowID: .existing(0), originalRow: [.text("0")]) coordinator.applyObjectChange(Self.change(connection, name: "users", database: "shop", schema: nil, kind: .rows)) @@ -355,10 +355,10 @@ struct CatalogChangeWindowTests { let (coordinator, tabManager) = makeCoordinator(connection: connection) let background = Self.tabWithCachedMetadata("users", in: coordinator) let unrelated = Self.tabWithCachedMetadata("orders", in: coordinator) - var editing = Self.tabWithCachedMetadata("users", in: coordinator) - editing.pendingChanges.deletedRowIDs = [.existing(0)] + let editing = Self.tabWithCachedMetadata("users", in: coordinator) tabManager.tabs = [background, unrelated, editing] tabManager.selectedTabId = editing.id + coordinator.changeManager(forTab: editing.id).recordRowDeletion(rowID: .existing(0), originalRow: [.text("0")]) #expect(coordinator.isMetadataCached(tabId: background.id, tableName: "users")) coordinator.applyObjectChange(Self.change(connection, name: "users", database: "shop", schema: nil, kind: .rows)) @@ -497,10 +497,10 @@ struct CatalogChangeWindowTests { let connection = TestFixtures.makeConnection(database: "shop") defer { DatabaseManager.shared.removeSession(for: connection.id) } let (coordinator, tabManager) = makeCoordinator(connection: connection) - var selected = Self.loadedTab("users", rowCount: 3, totalRowCount: 42, in: coordinator) - selected.pendingChanges.deletedRowIDs = [.existing(0)] + let selected = Self.loadedTab("users", rowCount: 3, totalRowCount: 42, in: coordinator) tabManager.tabs = [selected] tabManager.selectedTabId = selected.id + coordinator.changeManager(forTab: selected.id).recordRowDeletion(rowID: .existing(0), originalRow: [.text("0")]) coordinator.applyObjectChange(Self.change(connection, name: "users", database: "shop", schema: nil, kind: .rows)) coordinator.resumeDeferredTableRefresh() @@ -577,10 +577,8 @@ struct CatalogChangeWindowTests { #expect(Self.totalRowCount(of: selected.id, in: tabManager) == nil) } - /// Switching back to a tab restores its edits into the change manager, and the copy left on the - /// tab went on reporting them after the reader undid them all, so it vetoed the reload they had - /// put off for as long as the tab stayed in front. - @Test("a tab switched back to holds its edits in the change manager only, so undoing them reloads it") + // A copy of the edits left on the tab once vetoed the reload after the reader undid them all. + @Test("a tab switched back to holds its edits in its own change manager only, so undoing them reloads it") func aTabShownAgainDropsItsSavedEditsOnceRestored() async throws { let connection = TestFixtures.makeConnection(database: "shop") defer { DatabaseManager.shared.removeSession(for: connection.id) } @@ -596,8 +594,9 @@ struct CatalogChangeWindowTests { coordinator.handleTabChange(from: edited.id, to: other.id, tabs: tabManager.tabs) tabManager.selectedTabId = edited.id coordinator.handleTabChange(from: other.id, to: edited.id, tabs: tabManager.tabs) + #expect(coordinator.changeManager === coordinator.changeManager(forTab: edited.id)) #expect(coordinator.changeManager.hasChanges) - #expect(tabManager.tabs.first { $0.id == edited.id }?.pendingChanges.hasChanges == false) + #expect(coordinator.existingChangeManager(forTab: other.id)?.hasChanges != true) coordinator.applyObjectChange(Self.change(connection, name: "users", database: "shop", schema: nil, kind: .rows)) await Self.afterQueuedMainWork() diff --git a/apple/TableProTests/Views/Main/CellFilterApplyTests.swift b/apple/TableProTests/Views/Main/CellFilterApplyTests.swift index b36520ba59..4b5b281ebc 100644 --- a/apple/TableProTests/Views/Main/CellFilterApplyTests.swift +++ b/apple/TableProTests/Views/Main/CellFilterApplyTests.swift @@ -38,12 +38,11 @@ struct CellFilterApplyTests { } } - private func makeHarness(tabType: TabType = .table, changeManager: DataChangeManager = DataChangeManager()) -> Harness { + private func makeHarness(tabType: TabType = .table, editsFirstRowStatus: Bool = false) -> Harness { let tabManager = QueryTabManager() let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: changeManager, toolbarState: ConnectionToolbarState() ) var tab = QueryTab( @@ -57,11 +56,11 @@ struct CellFilterApplyTests { tabManager.tabs.append(tab) tabManager.selectedTabId = tab.id coordinator.setActiveTableRows(rows, for: tab.id) + if editsFirstRowStatus { editStatusOfFirstRow(coordinator.changeManager(forTab: tab.id)) } return Harness(coordinator: coordinator, tabManager: tabManager, tabId: tab.id) } - private func editedStatusOfFirstRow() -> DataChangeManager { - let changes = DataChangeManager() + private func editStatusOfFirstRow(_ changes: DataChangeManager) { changes.configureForTable( tableName: "orders", columns: ["id", "status"], @@ -78,7 +77,6 @@ struct CellFilterApplyTests { newValue: .text("void"), originalRow: [.text("1"), .text("paid")] ) - return changes } private func clearSavedFilters(_ harness: Harness) { @@ -142,7 +140,7 @@ struct CellFilterApplyTests { // Pretends an alert is already up, which `confirmDiscardChangesIfNeeded` answers false to once there are edits. @Test("Nothing changes while the discard alert is unanswered") func declinedDiscardChangesNothing() throws { - let harness = makeHarness(changeManager: editedStatusOfFirstRow()) + let harness = makeHarness(editsFirstRowStatus: true) defer { harness.coordinator.teardown() } #expect(harness.coordinator.changeManager.hasChanges) let item = try #require(harness.filterMenuItem(row: 1, dataColumn: 1)) @@ -166,7 +164,7 @@ struct CellFilterApplyTests { @Test("An edited cell has no Filter item, because the server does not hold its value") func editedCellHasNoItem() { - let harness = makeHarness(changeManager: editedStatusOfFirstRow()) + let harness = makeHarness(editsFirstRowStatus: true) defer { harness.coordinator.teardown() } #expect(harness.filterMenuItem(row: 0, dataColumn: 1) == nil) diff --git a/apple/TableProTests/Views/Main/ClearQueryResultsTests.swift b/apple/TableProTests/Views/Main/ClearQueryResultsTests.swift index ba240b549d..14224d79be 100644 --- a/apple/TableProTests/Views/Main/ClearQueryResultsTests.swift +++ b/apple/TableProTests/Views/Main/ClearQueryResultsTests.swift @@ -133,7 +133,6 @@ struct ClearQueryResultsTests { MainContentCoordinator( connection: TestFixtures.makeConnection(database: "db"), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } diff --git a/apple/TableProTests/Views/Main/CommandActionsBulkCloseTests.swift b/apple/TableProTests/Views/Main/CommandActionsBulkCloseTests.swift index 762910ee39..914a0ce6fb 100644 --- a/apple/TableProTests/Views/Main/CommandActionsBulkCloseTests.swift +++ b/apple/TableProTests/Views/Main/CommandActionsBulkCloseTests.swift @@ -269,8 +269,9 @@ struct CommandActionsBulkCloseTests { tab.content.sourceFileURL = URL(fileURLWithPath: "/tmp/tablepro-mixed.sql") tab.content.savedFileContent = "SELECT 1" tab.content.query = "SELECT 2" - tab.pendingChanges.deletedRowIDs = [.existing(0)] } + current.coordinator.changeManager(forTab: background.id) + .recordRowDeletion(rowID: .existing(0), originalRow: ["1"]) let mixed = try #require(current.coordinator.tabManager.tabs.first) #expect(current.coordinator.savability(of: mixed) == .mountedOnly) @@ -299,9 +300,8 @@ struct CommandActionsBulkCloseTests { current.coordinator.tabManager.addTab(initialQuery: "SELECT 1", databaseName: "db_a") current.coordinator.tabManager.addTab(initialQuery: "SELECT 2", databaseName: "db_a") let background = try #require(current.coordinator.tabManager.tabs.first) - current.coordinator.tabManager.mutate(tabId: background.id) { tab in - tab.pendingChanges.deletedRowIDs = [.existing(0)] - } + current.coordinator.changeManager(forTab: background.id) + .recordRowDeletion(rowID: .existing(0), originalRow: ["1"]) #expect(current.actions.holdsWorkOnlyItsTabCanSave(among: current.coordinator.tabManager.tabs)) #expect(await current.actions.saveEveryTabsWork() == false) diff --git a/apple/TableProTests/Views/Main/CoordinatorColumnVisibilityTests.swift b/apple/TableProTests/Views/Main/CoordinatorColumnVisibilityTests.swift index a8cc2d0b5c..47e536fd40 100644 --- a/apple/TableProTests/Views/Main/CoordinatorColumnVisibilityTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorColumnVisibilityTests.swift @@ -17,7 +17,6 @@ struct CoordinatorColumnVisibilityTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) return (coordinator, tabManager) diff --git a/apple/TableProTests/Views/Main/CoordinatorEditorLoadTests.swift b/apple/TableProTests/Views/Main/CoordinatorEditorLoadTests.swift index 8c6fba3bb1..0fe6909c04 100644 --- a/apple/TableProTests/Views/Main/CoordinatorEditorLoadTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorEditorLoadTests.swift @@ -19,13 +19,11 @@ struct CoordinatorEditorLoadTests { private func makeCoordinator() -> (MainContentCoordinator, QueryTabManager) { let connection = TestFixtures.makeConnection(database: "testdb") let tabManager = QueryTabManager() - let changeManager = DataChangeManager() let toolbarState = ConnectionToolbarState() let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: changeManager, toolbarState: toolbarState ) coordinator.openTabInNewWindow = { _ in } diff --git a/apple/TableProTests/Views/Main/CoordinatorQueryRoutingTests.swift b/apple/TableProTests/Views/Main/CoordinatorQueryRoutingTests.swift index 0cfbebea14..a60283d0d4 100644 --- a/apple/TableProTests/Views/Main/CoordinatorQueryRoutingTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorQueryRoutingTests.swift @@ -11,7 +11,6 @@ struct CoordinatorQueryRoutingTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) coordinator.openTabInNewWindow = { _ in } diff --git a/apple/TableProTests/Views/Main/CoordinatorRowImportTests.swift b/apple/TableProTests/Views/Main/CoordinatorRowImportTests.swift index ec0651b861..83d5f65ae7 100644 --- a/apple/TableProTests/Views/Main/CoordinatorRowImportTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorRowImportTests.swift @@ -25,7 +25,6 @@ struct CoordinatorRowImportTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(name: "Warehouse", type: type), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: toolbarState ) coordinator.importFormatLookup = lookup diff --git a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift index 71fdeb5abb..6ed69522aa 100644 --- a/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift +++ b/apple/TableProTests/Views/Main/CoordinatorTableListingTests.swift @@ -18,7 +18,6 @@ struct CoordinatorTableListingTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) let log = PayloadLog() diff --git a/apple/TableProTests/Views/Main/DataTabGridEditCommitTests.swift b/apple/TableProTests/Views/Main/DataTabGridEditCommitTests.swift index f37e88ffb6..9107c7653e 100644 --- a/apple/TableProTests/Views/Main/DataTabGridEditCommitTests.swift +++ b/apple/TableProTests/Views/Main/DataTabGridEditCommitTests.swift @@ -35,11 +35,10 @@ struct DataTabGridEditCommitTests { return tab.id } - // The change manager holds the selected tab's edits. private func select(_ tabId: UUID, in coordinator: MainContentCoordinator) { coordinator.tabManager.selectedTabId = tabId let name = coordinator.tabManager.tabs.first { $0.id == tabId }?.tableContext.tableName ?? "" - coordinator.changeManager.configureForTable( + coordinator.changeManager(forTab: tabId).configureForTable( tableName: name, columns: ["id", "name"], primaryKeyColumns: ["id"], @@ -106,7 +105,7 @@ struct DataTabGridEditCommitTests { coordinator.handleTabChange(from: outgoing, to: incoming, tabs: coordinator.tabManager.tabs) #expect(mount.commitCount == 1) - #expect(coordinator.tabManager.tabs.first { $0.id == outgoing }?.pendingChanges.hasChanges == true) + #expect(coordinator.changeManager(forTab: outgoing).isCellModified(rowID: .existing(1), columnIndex: 1)) #expect(name(coordinator, tabId: outgoing) == .text("Zed")) #expect(name(coordinator, tabId: incoming) == .text("Bob")) #expect(!coordinator.changeManager.hasChanges) @@ -127,8 +126,8 @@ struct DataTabGridEditCommitTests { #expect(name(coordinator, tabId: tabId) == .text("Zed")) } - @Test("the adapter refuses a commit for a tab that no longer holds the change manager") - func commitForAnotherTabIsRefused() throws { + @Test("a commit from a tab the selection has left lands in that tab's own edits") + func commitForAnotherTabLandsInItsOwnEdits() throws { let coordinator = fixtures.make().coordinator let outgoing = addTableTab(coordinator, name: "users") let incoming = addTableTab(coordinator, name: "orders") @@ -140,9 +139,10 @@ struct DataTabGridEditCommitTests { let committed = model.commit([try nameEdit(model, "Zed")], actionName: "Edit") - #expect(!committed) + #expect(committed) + #expect(coordinator.changeManager(forTab: outgoing).isCellModified(rowID: .existing(1), columnIndex: 1)) #expect(!coordinator.changeManager.hasChanges) - #expect(name(coordinator, tabId: outgoing) == .text("Bob")) + #expect(name(coordinator, tabId: outgoing) == .text("Zed")) #expect(name(coordinator, tabId: incoming) == .text("Bob")) } diff --git a/apple/TableProTests/Views/Main/DatabaseSearchResultOpeningTests.swift b/apple/TableProTests/Views/Main/DatabaseSearchResultOpeningTests.swift index fee2eb9e5f..454411d01f 100644 --- a/apple/TableProTests/Views/Main/DatabaseSearchResultOpeningTests.swift +++ b/apple/TableProTests/Views/Main/DatabaseSearchResultOpeningTests.swift @@ -22,7 +22,6 @@ struct DatabaseSearchResultOpeningTests { MainContentCoordinator( connection: TestFixtures.makeConnection(database: "shop"), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } diff --git a/apple/TableProTests/Views/Main/ExplainAuthorizationTests.swift b/apple/TableProTests/Views/Main/ExplainAuthorizationTests.swift index 39b0d1f84e..528352be8e 100644 --- a/apple/TableProTests/Views/Main/ExplainAuthorizationTests.swift +++ b/apple/TableProTests/Views/Main/ExplainAuthorizationTests.swift @@ -198,7 +198,6 @@ struct ExplainAuthorizationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: toolbarState ) let authenticating = StubAuthenticating(answer: true) diff --git a/apple/TableProTests/Views/Main/ExtractTableNameTests.swift b/apple/TableProTests/Views/Main/ExtractTableNameTests.swift index 1f4fe74e28..e3b37e1a29 100644 --- a/apple/TableProTests/Views/Main/ExtractTableNameTests.swift +++ b/apple/TableProTests/Views/Main/ExtractTableNameTests.swift @@ -11,13 +11,11 @@ struct ExtractTableNameTests { private func makeCoordinator(type: DatabaseType = .mysql) -> MainContentCoordinator { let connection = TestFixtures.makeConnection(database: "db_a", type: type) let tabManager = QueryTabManager() - let changeManager = DataChangeManager() let toolbarState = ConnectionToolbarState() return MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: changeManager, toolbarState: toolbarState ) } diff --git a/apple/TableProTests/Views/Main/FKNavigationTests.swift b/apple/TableProTests/Views/Main/FKNavigationTests.swift index 0a72e68235..8ea4b7b378 100644 --- a/apple/TableProTests/Views/Main/FKNavigationTests.swift +++ b/apple/TableProTests/Views/Main/FKNavigationTests.swift @@ -12,7 +12,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -43,7 +42,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -79,7 +77,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -111,7 +108,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -153,7 +149,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -182,7 +177,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -215,7 +209,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -244,7 +237,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -276,7 +268,6 @@ struct FKNavigationTests { let originCoordinator = MainContentCoordinator( connection: connection, tabManager: originTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) originCoordinator.registerEagerly() @@ -285,7 +276,6 @@ struct FKNavigationTests { let targetCoordinator = MainContentCoordinator( connection: connection, tabManager: targetTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) targetCoordinator.registerEagerly() @@ -345,7 +335,6 @@ struct FKNavigationTests { let originCoordinator = MainContentCoordinator( connection: connection, tabManager: originTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) originCoordinator.registerEagerly() @@ -354,7 +343,6 @@ struct FKNavigationTests { let targetCoordinator = MainContentCoordinator( connection: connection, tabManager: targetTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) targetCoordinator.registerEagerly() @@ -407,7 +395,6 @@ struct FKNavigationTests { let originCoordinator = MainContentCoordinator( connection: connection, tabManager: originTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) originCoordinator.registerEagerly() @@ -416,7 +403,6 @@ struct FKNavigationTests { let targetCoordinator = MainContentCoordinator( connection: connection, tabManager: targetTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) targetCoordinator.registerEagerly() @@ -474,7 +460,6 @@ struct FKNavigationTests { let originCoordinator = MainContentCoordinator( connection: connection, tabManager: originTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) originCoordinator.registerEagerly() @@ -483,7 +468,6 @@ struct FKNavigationTests { let targetCoordinator = MainContentCoordinator( connection: connection, tabManager: targetTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) targetCoordinator.registerEagerly() @@ -542,7 +526,6 @@ struct FKNavigationTests { let originCoordinator = MainContentCoordinator( connection: connection, tabManager: originTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) originCoordinator.registerEagerly() @@ -551,7 +534,6 @@ struct FKNavigationTests { let targetCoordinator = MainContentCoordinator( connection: connection, tabManager: targetTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) targetCoordinator.registerEagerly() @@ -601,7 +583,6 @@ struct FKNavigationTests { let originCoordinator = MainContentCoordinator( connection: connection, tabManager: originTabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) originCoordinator.registerEagerly() @@ -645,7 +626,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -690,7 +670,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -722,7 +701,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -753,7 +731,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -782,7 +759,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -818,7 +794,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -849,7 +824,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -883,7 +857,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -911,7 +884,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -942,7 +914,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -973,7 +944,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -1005,7 +975,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -1046,7 +1015,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -1088,7 +1056,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -1121,7 +1088,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -1154,7 +1120,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -1191,7 +1156,6 @@ struct FKNavigationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/Views/Main/FetchAllQueryTaskTests.swift b/apple/TableProTests/Views/Main/FetchAllQueryTaskTests.swift index 5409b0869d..a5fa0cc89c 100644 --- a/apple/TableProTests/Views/Main/FetchAllQueryTaskTests.swift +++ b/apple/TableProTests/Views/Main/FetchAllQueryTaskTests.swift @@ -27,7 +27,6 @@ struct FetchAllQueryTaskTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) let tab = QueryTab(title: "Query", query: "SELECT 1", tabType: .query) @@ -68,7 +67,6 @@ struct FetchAllQueryTaskTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) coordinator.executionGate = AlwaysDenyGate() @@ -109,7 +107,6 @@ struct FetchAllQueryTaskTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "Query", query: "SELECT noisy()", tabType: .query) diff --git a/apple/TableProTests/Views/Main/FilterTypingBeforeFirstLoadTests.swift b/apple/TableProTests/Views/Main/FilterTypingBeforeFirstLoadTests.swift index 220d9879bc..51779b1a02 100644 --- a/apple/TableProTests/Views/Main/FilterTypingBeforeFirstLoadTests.swift +++ b/apple/TableProTests/Views/Main/FilterTypingBeforeFirstLoadTests.swift @@ -21,7 +21,6 @@ extension GlobalStateSuites { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(type: type), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "items", query: "SELECT * FROM `items` LIMIT 200", tabType: .table) diff --git a/apple/TableProTests/Views/Main/GridReloadViewportTests.swift b/apple/TableProTests/Views/Main/GridReloadViewportTests.swift index c85b15082f..2eb1d66215 100644 --- a/apple/TableProTests/Views/Main/GridReloadViewportTests.swift +++ b/apple/TableProTests/Views/Main/GridReloadViewportTests.swift @@ -37,7 +37,6 @@ struct GridReloadViewportTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "users", query: "SELECT * FROM users", tabType: tabType, tableName: "users") diff --git a/apple/TableProTests/Views/Main/InspectorFieldEditStagingTests.swift b/apple/TableProTests/Views/Main/InspectorFieldEditStagingTests.swift index fe2cf2db52..a25df817ab 100644 --- a/apple/TableProTests/Views/Main/InspectorFieldEditStagingTests.swift +++ b/apple/TableProTests/Views/Main/InspectorFieldEditStagingTests.swift @@ -71,7 +71,6 @@ struct InspectorFieldEditStagingTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "users", query: "SELECT * FROM users", tabType: .table, tableName: "users") diff --git a/apple/TableProTests/Views/Main/JoinBuilderOpeningTests.swift b/apple/TableProTests/Views/Main/JoinBuilderOpeningTests.swift index b815faa15a..b135f51493 100644 --- a/apple/TableProTests/Views/Main/JoinBuilderOpeningTests.swift +++ b/apple/TableProTests/Views/Main/JoinBuilderOpeningTests.swift @@ -10,7 +10,6 @@ struct JoinBuilderOpeningTests { MainContentCoordinator( connection: TestFixtures.makeConnection(database: "shop", type: type), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } diff --git a/apple/TableProTests/Views/Main/MainContentCoordinatorAutoRefreshTests.swift b/apple/TableProTests/Views/Main/MainContentCoordinatorAutoRefreshTests.swift index e314bd5c04..69c5ad667e 100644 --- a/apple/TableProTests/Views/Main/MainContentCoordinatorAutoRefreshTests.swift +++ b/apple/TableProTests/Views/Main/MainContentCoordinatorAutoRefreshTests.swift @@ -218,7 +218,6 @@ private final class AutoRefreshHarness { coordinator = MainContentCoordinator( connection: connection, tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState(), services: AppServices.live.replacingQueryHistory(history) ) diff --git a/apple/TableProTests/Views/Main/MainContentCoordinatorDisplayStateTests.swift b/apple/TableProTests/Views/Main/MainContentCoordinatorDisplayStateTests.swift index ecec0f0675..9829e8653a 100644 --- a/apple/TableProTests/Views/Main/MainContentCoordinatorDisplayStateTests.swift +++ b/apple/TableProTests/Views/Main/MainContentCoordinatorDisplayStateTests.swift @@ -159,9 +159,12 @@ struct MainContentCoordinatorDisplayStateTests { seedRows(coordinator, for: first.id) seedRows(coordinator, for: second.id) - let before = coordinator.changeManager.reloadVersion + let incoming = coordinator.changeManager(forTab: first.id) + let outgoing = coordinator.changeManager(forTab: second.id) + let before = (incoming: incoming.reloadVersion, outgoing: outgoing.reloadVersion) tabManager.selectedTabId = first.id coordinator.handleTabChange(from: second.id, to: first.id, tabs: tabManager.tabs) - #expect(coordinator.changeManager.reloadVersion == before) + #expect(incoming.reloadVersion == before.incoming) + #expect(outgoing.reloadVersion == before.outgoing) } } diff --git a/apple/TableProTests/Views/Main/MainContentCoordinatorLazyLoadTests.swift b/apple/TableProTests/Views/Main/MainContentCoordinatorLazyLoadTests.swift index 3251e31267..bc76c87ef1 100644 --- a/apple/TableProTests/Views/Main/MainContentCoordinatorLazyLoadTests.swift +++ b/apple/TableProTests/Views/Main/MainContentCoordinatorLazyLoadTests.swift @@ -148,7 +148,7 @@ struct MainContentCoordinatorLazyLoadTests { return } tabManager.tabs[idx].execution.lastExecutedAt = Date() - tabManager.tabs[idx].pendingChanges.deletedRowIDs = [.existing(0)] + coordinator.changeManager(forTab: tabId).recordRowDeletion(rowID: .existing(0), originalRow: ["1"]) coordinator.tabSessionRegistry.recordChange(TableFreshness.Change(extent: .rows, at: .now), for: tabId) coordinator.lazyLoadCurrentTabIfNeeded() @@ -161,11 +161,7 @@ struct MainContentCoordinatorLazyLoadTests { let (coordinator, tabManager) = makeCoordinator() let tabId = addTableTab(to: tabManager) seedRows(coordinator, for: tabId, rowCount: 1) - guard let idx = tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { - Issue.record("expected tab to exist") - return - } - tabManager.tabs[idx].pendingChanges.deletedRowIDs = [.existing(0)] + coordinator.changeManager(forTab: tabId).recordRowDeletion(rowID: .existing(0), originalRow: ["1"]) coordinator.lazyLoadCurrentTabIfNeeded() #expect(coordinator.parkedTableLoad == nil) diff --git a/apple/TableProTests/Views/Main/MainContentCoordinatorSortTests.swift b/apple/TableProTests/Views/Main/MainContentCoordinatorSortTests.swift index 14cee2efb9..940dd8eae0 100644 --- a/apple/TableProTests/Views/Main/MainContentCoordinatorSortTests.swift +++ b/apple/TableProTests/Views/Main/MainContentCoordinatorSortTests.swift @@ -13,7 +13,6 @@ struct MainContentCoordinatorSortTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(type: type), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "Q1", query: "SELECT id, name, email FROM users", tabType: .query) @@ -565,7 +564,6 @@ struct MainContentCoordinatorSortTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(type: type), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: tableName, query: "SELECT * FROM \(tableName)", tabType: .table) @@ -637,7 +635,6 @@ struct MainContentCoordinatorSortTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { @@ -780,7 +777,6 @@ private struct ParameterizedRunHarness { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "Query", query: query, tabType: .query) diff --git a/apple/TableProTests/Views/Main/MainContentCoordinatorTabSwitchTests.swift b/apple/TableProTests/Views/Main/MainContentCoordinatorTabSwitchTests.swift index f7692219d0..166a3d7406 100644 --- a/apple/TableProTests/Views/Main/MainContentCoordinatorTabSwitchTests.swift +++ b/apple/TableProTests/Views/Main/MainContentCoordinatorTabSwitchTests.swift @@ -21,7 +21,6 @@ struct MainContentCoordinatorTabSwitchTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) return (coordinator, tabManager) @@ -235,15 +234,8 @@ struct MainContentCoordinatorTabSwitchTests { #expect(saved.isVisible == true) } - @Test("Switching saves outgoing pending changes into the tab") - func savesOutgoingPendingChanges() { - let (coordinator, tabManager) = makeCoordinator() - let oldId = addQueryTab(to: tabManager, title: "Old") - let newId = addQueryTab(to: tabManager, title: "New") - seedRows(coordinator, for: oldId) - seedRows(coordinator, for: newId) - - coordinator.changeManager.configureForTable( + private func stageNameEdit(on edits: DataChangeManager) { + edits.configureForTable( tableName: "users", columns: ["id", "name"], primaryKeyColumns: ["id"], @@ -251,7 +243,7 @@ struct MainContentCoordinatorTabSwitchTests { generatedColumns: [], triggerReload: false ) - coordinator.changeManager.recordCellChange( + edits.recordCellChange( rowID: .existing(0), columnIndex: 1, columnName: "name", @@ -259,45 +251,38 @@ struct MainContentCoordinatorTabSwitchTests { newValue: "Bob", originalRow: ["1", "Alice"] ) - #expect(coordinator.changeManager.hasChanges == true) + } + + @Test("Switching keeps the outgoing tab's edits in its own change manager") + func keepsOutgoingEditsInTheirTab() { + let (coordinator, tabManager) = makeCoordinator() + let oldId = addQueryTab(to: tabManager, title: "Old") + let newId = addQueryTab(to: tabManager, title: "New") + seedRows(coordinator, for: oldId) + seedRows(coordinator, for: newId) + let edits = coordinator.changeManager(forTab: oldId) + stageNameEdit(on: edits) + #expect(edits.hasChanges == true) coordinator.handleTabChange(from: oldId, to: newId, tabs: tabManager.tabs) - guard let oldIndex = tabManager.tabs.firstIndex(where: { $0.id == oldId }) else { - Issue.record("Expected old tab to exist after switch") - return - } - #expect(tabManager.tabs[oldIndex].pendingChanges.hasChanges == true) + #expect(edits.hasChanges == true) + #expect(coordinator.hasStagedRowEdits(inTab: oldId)) + #expect(coordinator.changeManager === coordinator.changeManager(forTab: newId)) + #expect(coordinator.changeManager.hasChanges == false) } - // Gated on `hasChanges`, an undo left an older snapshot on the tab, and switching back restored the undone edit. - @Test("Switching clears a snapshot the reader has undone") - func undoneChangesClearTheOutgoingSnapshot() throws { + // A copy of the edits left on the tab once restored an edit the reader had undone. + @Test("An edit the reader takes back stays taken back across switches") + func undoneChangesStayUndoneAcrossSwitches() { let (coordinator, tabManager) = makeCoordinator() let oldId = addQueryTab(to: tabManager, title: "Old") let newId = addQueryTab(to: tabManager, title: "New") seedRows(coordinator, for: oldId) seedRows(coordinator, for: newId) - - coordinator.changeManager.configureForTable( - tableName: "users", - columns: ["id", "name"], - primaryKeyColumns: ["id"], - databaseType: .mysql, - generatedColumns: [], - triggerReload: false - ) - coordinator.changeManager.recordCellChange( - rowID: .existing(0), - columnIndex: 1, - columnName: "name", - oldValue: "Alice", - newValue: "Bob", - originalRow: ["1", "Alice"] - ) + stageNameEdit(on: coordinator.changeManager(forTab: oldId)) coordinator.handleTabChange(from: oldId, to: newId, tabs: tabManager.tabs) - let afterFirstSwitch = try #require(tabManager.tabs.first { $0.id == oldId }) - #expect(afterFirstSwitch.pendingChanges.hasChanges == true) + #expect(coordinator.hasStagedRowEdits(inTab: oldId)) tabManager.selectedTabId = oldId coordinator.handleTabChange(from: newId, to: oldId, tabs: tabManager.tabs) @@ -306,9 +291,11 @@ struct MainContentCoordinatorTabSwitchTests { tabManager.selectedTabId = newId coordinator.handleTabChange(from: oldId, to: newId, tabs: tabManager.tabs) + #expect(!coordinator.hasStagedRowEdits(inTab: oldId)) - let afterUndo = try #require(tabManager.tabs.first { $0.id == oldId }) - #expect(afterUndo.pendingChanges.hasChanges == false) + tabManager.selectedTabId = oldId + coordinator.handleTabChange(from: newId, to: oldId, tabs: tabManager.tabs) + #expect(coordinator.changeManager.hasChanges == false) } @Test("Hiding a column persists into the active tab's column layout") @@ -450,17 +437,17 @@ struct MainContentCoordinatorTabSwitchTests { #expect(coordinator.toolbarState.isResultsCollapsed == true) } - // MARK: - Pending changes restore + // MARK: - The incoming tab's edits - @Test("Switching restores pending changes when the incoming tab has them") - func restoresIncomingPendingChanges() { + @Test("Switching to a tab shows the edits it holds") + func showsTheIncomingTabsEdits() { let (coordinator, tabManager) = makeCoordinator() let oldId = addTableTab(to: tabManager, tableName: "users") let newId = addTableTab(to: tabManager, tableName: "orders") seedRows(coordinator, for: oldId) seedRows(coordinator, for: newId, columns: ["id", "total"]) - - coordinator.changeManager.configureForTable( + let edits = coordinator.changeManager(forTab: newId) + edits.configureForTable( tableName: "orders", columns: ["id", "total"], primaryKeyColumns: ["id"], @@ -468,7 +455,7 @@ struct MainContentCoordinatorTabSwitchTests { generatedColumns: [], triggerReload: false ) - coordinator.changeManager.recordCellChange( + edits.recordCellChange( rowID: .existing(0), columnIndex: 1, columnName: "total", @@ -476,25 +463,17 @@ struct MainContentCoordinatorTabSwitchTests { newValue: "99", originalRow: ["1", "10"] ) - let snapshot = coordinator.changeManager.saveState() - - guard let newIndex = tabManager.tabs.firstIndex(where: { $0.id == newId }) else { - Issue.record("Expected new tab to exist before switch") - return - } - tabManager.tabs[newIndex].pendingChanges = snapshot - - coordinator.changeManager.clearChanges() - #expect(coordinator.changeManager.hasChanges == false) coordinator.handleTabChange(from: oldId, to: newId, tabs: tabManager.tabs) + #expect(coordinator.changeManager === edits) + #expect(coordinator.selectedTabEdits.manager === edits) #expect(coordinator.changeManager.hasChanges == true) #expect(coordinator.changeManager.tableName == "orders") } - @Test("Switching configures the change manager when the incoming tab has no pending state") - func configuresChangeManagerWhenNoPendingState() { + @Test("Switching describes the incoming tab's result to its change manager when it holds no edits") + func describesIncomingResultWhenNoEdits() { let (coordinator, tabManager) = makeCoordinator() let oldId = addQueryTab(to: tabManager, title: "Old") let newId = addTableTab(to: tabManager, tableName: "products") @@ -506,12 +485,12 @@ struct MainContentCoordinatorTabSwitchTests { return } tabManager.tabs[newIndex].tableContext.primaryKeyColumns = ["id"] - tabManager.tabs[newIndex].pendingChanges = TabChangeSnapshot() coordinator.handleTabChange(from: oldId, to: newId, tabs: tabManager.tabs) #expect(coordinator.changeManager.tableName == "products") #expect(coordinator.changeManager.primaryKeyColumns == ["id"]) + #expect(coordinator.changeManager.columns == ["id", "name", "price"]) #expect(coordinator.changeManager.hasChanges == false) } @@ -947,39 +926,6 @@ struct MainContentCoordinatorTabSwitchTests { #expect(!saved.isApplied) } - @Test("DataChangeManager restoreState rehydrates table context and changes") - func dataChangeManagerRestoresFromSnapshot() { - let manager = DataChangeManager() - manager.configureForTable( - tableName: "users", - columns: ["id", "name"], - primaryKeyColumns: ["id"], - databaseType: .mysql, - generatedColumns: [], - triggerReload: false - ) - manager.recordCellChange( - rowID: .existing(0), - columnIndex: 1, - columnName: "name", - oldValue: "Alice", - newValue: "Bob", - originalRow: ["1", "Alice"] - ) - let snapshot = manager.saveState() - - let fresh = DataChangeManager() - #expect(fresh.hasChanges == false) - - fresh.restoreState(from: snapshot, tableName: "users", databaseType: .postgresql, generatedColumns: []) - - #expect(fresh.hasChanges == true) - #expect(fresh.tableName == "users") - #expect(fresh.primaryKeyColumns == ["id"]) - #expect(fresh.databaseType == .postgresql) - #expect(fresh.columns == ["id", "name"]) - } - @Test("Coordinator helpers round-trip hidden columns through the active tab's layout") func columnVisibilityHelpersRoundTrip() { let (coordinator, tabManager) = makeCoordinator() diff --git a/apple/TableProTests/Views/Main/MainContentCoordinatorTableMetadataTests.swift b/apple/TableProTests/Views/Main/MainContentCoordinatorTableMetadataTests.swift index 5c9680ba30..1be8dcec62 100644 --- a/apple/TableProTests/Views/Main/MainContentCoordinatorTableMetadataTests.swift +++ b/apple/TableProTests/Views/Main/MainContentCoordinatorTableMetadataTests.swift @@ -21,7 +21,6 @@ struct MainContentCoordinatorTableMetadataTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) return (coordinator, tabManager) @@ -469,7 +468,6 @@ private struct LiveSession { coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) coordinator.trailingPaneState = paneState diff --git a/apple/TableProTests/Views/Main/MatchAnyUnsupportedFilterTests.swift b/apple/TableProTests/Views/Main/MatchAnyUnsupportedFilterTests.swift index 35a1501ac2..b2f52f3857 100644 --- a/apple/TableProTests/Views/Main/MatchAnyUnsupportedFilterTests.swift +++ b/apple/TableProTests/Views/Main/MatchAnyUnsupportedFilterTests.swift @@ -19,7 +19,6 @@ struct MatchAnyUnsupportedFilterTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(type: type), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "events", query: "SELECT * FROM events", tabType: .table) diff --git a/apple/TableProTests/Views/Main/MaterializedViewRowWriteTests.swift b/apple/TableProTests/Views/Main/MaterializedViewRowWriteTests.swift index 6b5f3a8701..9fa57f8ffb 100644 --- a/apple/TableProTests/Views/Main/MaterializedViewRowWriteTests.swift +++ b/apple/TableProTests/Views/Main/MaterializedViewRowWriteTests.swift @@ -15,7 +15,6 @@ extension GlobalStateSuites { MainContentCoordinator( connection: TestFixtures.makeConnection(database: "shop", type: .postgresql), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } diff --git a/apple/TableProTests/Views/Main/MultiConnectionNavigationTests.swift b/apple/TableProTests/Views/Main/MultiConnectionNavigationTests.swift index 4ca61ab10e..a2ce41e9f3 100644 --- a/apple/TableProTests/Views/Main/MultiConnectionNavigationTests.swift +++ b/apple/TableProTests/Views/Main/MultiConnectionNavigationTests.swift @@ -19,12 +19,10 @@ struct MultiConnectionNavigationTests { ) -> (coordinator: MainContentCoordinator, tabManager: QueryTabManager) { let connection = TestFixtures.makeConnection(id: id, name: name, database: database, type: type) let tabManager = QueryTabManager() - let changeManager = DataChangeManager() let toolbarState = ConnectionToolbarState() let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: changeManager, toolbarState: toolbarState ) return (coordinator, tabManager) diff --git a/apple/TableProTests/Views/Main/OpenTableTabTests.swift b/apple/TableProTests/Views/Main/OpenTableTabTests.swift index 1737328943..e598fd8295 100644 --- a/apple/TableProTests/Views/Main/OpenTableTabTests.swift +++ b/apple/TableProTests/Views/Main/OpenTableTabTests.swift @@ -12,13 +12,11 @@ struct OpenTableTabTests { func addsTabDirectlyWhenTabsEmptyNotSwitching() { let connection = TestFixtures.makeConnection(database: "db_a") let tabManager = QueryTabManager() - let changeManager = DataChangeManager() let toolbarState = ConnectionToolbarState() let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: changeManager, toolbarState: toolbarState ) defer { coordinator.teardown() } @@ -42,7 +40,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -64,7 +61,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -89,7 +85,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -113,7 +108,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -143,7 +137,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -167,7 +160,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -185,7 +177,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -261,7 +252,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(database: "0", type: .redis), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -347,7 +337,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -372,7 +361,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -399,7 +387,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -423,7 +410,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -451,7 +437,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -626,7 +611,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -654,7 +638,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -682,7 +665,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -707,7 +689,6 @@ struct OpenTableTabTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -731,7 +712,6 @@ struct OpenTableTabTests { MainContentCoordinator( connection: TestFixtures.makeConnection(database: "db"), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } diff --git a/apple/TableProTests/Views/Main/ParkedEditSnapshotTests.swift b/apple/TableProTests/Views/Main/ParkedEditSnapshotTests.swift deleted file mode 100644 index b25fe57889..0000000000 --- a/apple/TableProTests/Views/Main/ParkedEditSnapshotTests.swift +++ /dev/null @@ -1,199 +0,0 @@ -import Foundation -import TableProPluginKit -import Testing - -@testable import TablePro - -@MainActor -struct ParkedEditSnapshotTests { - private func parkedEdits() -> TabChangeSnapshot { - var snapshot = TabChangeSnapshot() - snapshot.insertedRowIDs = [.inserted(UUID())] - snapshot.columns = ["id", "name"] - snapshot.primaryKeyColumns = ["id"] - return snapshot - } - - @Test("A result installed on a background tab drops the edits parked for its old result") - func backgroundResultDropsParkedEdits() throws { - let fixture = CoordinatorFixture() - let background = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM orders", tabType: .query)) - fixture.tabManager.mutate(tabId: background.id) { $0.pendingChanges = self.parkedEdits() } - fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query)) - - fixture.coordinator.queryExecutionCoordinator.presentMultiStatementResults( - tabId: background.id, - timing: PluginQueryTiming(total: 0), - totalRowsAffected: 0, - newResultSets: [ResultSet(label: "Result 1", tableRows: TableRows())], - sessionNotice: nil - ) - - let tab = try #require(fixture.tabManager.tabs.first { $0.id == background.id }) - #expect(!tab.pendingChanges.hasChanges) - } - - @Test("Edits parked on one result are not restored onto the result that replaced it") - func switchingBackDropsEditsOfAReplacedResult() throws { - let fixture = CoordinatorFixture() - let edited = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM users", tabType: .query)) - let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) - let users = ResultSet(label: "users", tableRows: TableRows()) - fixture.tabManager.mutate(tabId: edited.id) { $0.display.replaceUnpinnedResults(with: [users]) } - fixture.changeManager.configureForTable( - tableName: "users", - columns: ["id", "name"], - primaryKeyColumns: ["id"], - databaseType: .mysql, - generatedColumns: [], - triggerReload: false - ) - fixture.changeManager.recordCellChange( - rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "a", newValue: "z", originalRow: ["1", "a"] - ) - - fixture.tabManager.selectedTabId = other.id - fixture.coordinator.handleTabChange(from: edited.id, to: other.id, tabs: fixture.tabManager.tabs) - let parked = try #require(fixture.tabManager.tabs.first { $0.id == edited.id }).pendingChanges - #expect(parked.hasChanges) - #expect(parked.resultSetId == users.id) - - // Written straight to the tab, as a result landing in the turn before the switch handler ran would be. - let orders = ResultSet(label: "orders", tableRows: TableRows()) - fixture.tabManager.mutate(tabId: edited.id) { $0.display.replaceUnpinnedResults(with: [orders]) } - fixture.tabManager.selectedTabId = edited.id - fixture.coordinator.handleTabChange(from: other.id, to: edited.id, tabs: fixture.tabManager.tabs) - - #expect(!fixture.changeManager.hasChanges) - #expect(!(try #require(fixture.tabManager.tabs.first { $0.id == edited.id })).pendingChanges.hasChanges) - } - - @Test("A result that lands before the switch handler runs voids the edits still in the change manager") - func resultLandingBeforeTheSwitchHandlerVoidsTheEdits() throws { - let fixture = CoordinatorFixture() - let edited = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM users", tabType: .query)) - let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) - let users = ResultSet(label: "users", tableRows: TableRows()) - fixture.tabManager.mutate(tabId: edited.id) { $0.display.replaceUnpinnedResults(with: [users]) } - fixture.changeManager.configureForTable( - tableName: "users", - columns: ["id", "name"], - primaryKeyColumns: ["id"], - databaseType: .mysql, - generatedColumns: [], - triggerReload: false - ) - fixture.changeManager.recordCellChange( - rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "a", newValue: "z", originalRow: ["1", "a"] - ) - - // The selection moved, the handler has not run yet, and the run finishes in between. - fixture.tabManager.selectedTabId = other.id - fixture.coordinator.queryExecutionCoordinator.presentMultiStatementResults( - tabId: edited.id, - timing: PluginQueryTiming(total: 0), - totalRowsAffected: 0, - newResultSets: [ResultSet(label: "orders", tableRows: TableRows())], - sessionNotice: nil - ) - fixture.coordinator.handleTabChange(from: edited.id, to: other.id, tabs: fixture.tabManager.tabs) - #expect(!(try #require(fixture.tabManager.tabs.first { $0.id == edited.id })).pendingChanges.hasChanges) - - fixture.tabManager.selectedTabId = edited.id - fixture.coordinator.handleTabChange(from: other.id, to: edited.id, tabs: fixture.tabManager.tabs) - #expect(!fixture.changeManager.hasChanges) - } - - @Test("A tab reselected without the switch handler keeps the edits it stages afterwards") - func reselectWithoutTheHandlerKeepsLaterEdits() throws { - let fixture = CoordinatorFixture() - let edited = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM users", tabType: .query)) - let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) - let third = fixture.addTab(QueryTab(title: "C", query: "SELECT 2", tabType: .query), select: false) - - // A to B and back inside one update: a result lands on A in between, and no handler runs. - fixture.tabManager.selectedTabId = other.id - fixture.coordinator.dropParkedEdits(ofBackgroundTab: edited.id) - fixture.tabManager.selectedTabId = edited.id - fixture.changeManager.configureForTable( - tableName: "users", - columns: ["id", "name"], - primaryKeyColumns: ["id"], - databaseType: .mysql, - generatedColumns: [], - triggerReload: false - ) - fixture.changeManager.recordCellChange( - rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "a", newValue: "z", originalRow: ["1", "a"] - ) - - fixture.tabManager.selectedTabId = third.id - fixture.coordinator.handleTabChange(from: edited.id, to: third.id, tabs: fixture.tabManager.tabs) - - #expect((try #require(fixture.tabManager.tabs.first { $0.id == edited.id })).pendingChanges.hasChanges) - } - - @Test("A result installed on the selected tab clears its off-screen mark") - func resultOnTheSelectedTabClearsTheMark() throws { - let fixture = CoordinatorFixture() - let edited = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM users", tabType: .query)) - let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) - fixture.tabManager.selectedTabId = other.id - fixture.coordinator.dropParkedEdits(ofBackgroundTab: edited.id) - fixture.tabManager.selectedTabId = edited.id - - fixture.coordinator.queryExecutionCoordinator.presentMultiStatementResults( - tabId: edited.id, - timing: PluginQueryTiming(total: 0), - totalRowsAffected: 0, - newResultSets: [ResultSet(label: "users", tableRows: TableRows())], - sessionNotice: nil - ) - - #expect(fixture.coordinator.tabsGivenResultOffScreen.keys.contains(edited.id) == false) - } - - @Test("Edits come back when the tab still shows the result they were made on") - func switchingBackRestoresEditsOfTheSameResult() throws { - let fixture = CoordinatorFixture() - let edited = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM users", tabType: .query)) - let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) - let users = ResultSet(label: "users", tableRows: TableRows()) - fixture.tabManager.mutate(tabId: edited.id) { $0.display.replaceUnpinnedResults(with: [users]) } - fixture.changeManager.configureForTable( - tableName: "users", - columns: ["id", "name"], - primaryKeyColumns: ["id"], - databaseType: .mysql, - generatedColumns: [], - triggerReload: false - ) - fixture.changeManager.recordCellChange( - rowID: .existing(0), columnIndex: 1, columnName: "name", - oldValue: "a", newValue: "z", originalRow: ["1", "a"] - ) - - fixture.tabManager.selectedTabId = other.id - fixture.coordinator.handleTabChange(from: edited.id, to: other.id, tabs: fixture.tabManager.tabs) - #expect(!fixture.changeManager.hasChanges) - fixture.tabManager.selectedTabId = edited.id - fixture.coordinator.handleTabChange(from: other.id, to: edited.id, tabs: fixture.tabManager.tabs) - - #expect(fixture.changeManager.hasChanges) - } - - @Test("Only a background tab's parked edits are dropped") - func selectedTabKeepsItsSnapshot() throws { - let fixture = CoordinatorFixture() - let selected = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM orders", tabType: .query)) - fixture.tabManager.mutate(tabId: selected.id) { $0.pendingChanges = self.parkedEdits() } - - fixture.coordinator.dropParkedEdits(ofBackgroundTab: selected.id) - - let tab = try #require(fixture.tabManager.tabs.first { $0.id == selected.id }) - #expect(tab.pendingChanges.hasChanges) - } -} diff --git a/apple/TableProTests/Views/Main/PluginBrowsedQueryTabEditabilityTests.swift b/apple/TableProTests/Views/Main/PluginBrowsedQueryTabEditabilityTests.swift index cf4e33a455..b668f230ba 100644 --- a/apple/TableProTests/Views/Main/PluginBrowsedQueryTabEditabilityTests.swift +++ b/apple/TableProTests/Views/Main/PluginBrowsedQueryTabEditabilityTests.swift @@ -68,7 +68,6 @@ struct PluginBrowsedQueryTabEditabilityTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/Views/Main/QueryFailureReportingTests.swift b/apple/TableProTests/Views/Main/QueryFailureReportingTests.swift index 0a501c2aa0..b8b4465497 100644 --- a/apple/TableProTests/Views/Main/QueryFailureReportingTests.swift +++ b/apple/TableProTests/Views/Main/QueryFailureReportingTests.swift @@ -186,8 +186,7 @@ struct QueryFailureReportingTests { #expect(coordinator.queryTasks.hasTask(for: tabId) == false) } - /// The change manager is one per window and holds whichever tab is selected. Clearing it from a - /// completion on a different tab throws away edits and undo history the user can never get back. + // A completion for one tab once cleared the edits and undo history of the tab the user had switched to. @Test("Clearing pending changes never reaches a tab the user has switched to") func pendingChangesOfAnotherTabSurvive() { let (coordinator, tabManager) = makeCoordinator() @@ -206,10 +205,12 @@ struct QueryFailureReportingTests { newValue: "edited" ) #expect(coordinator.changeManager.hasChanges) + coordinator.changeManager(forTab: backgroundTabId).recordRowDeletion(rowID: .existing(0), originalRow: ["1"]) coordinator.clearChangesIfCurrent(claim: claim) #expect(coordinator.changeManager.hasChanges) + #expect(!coordinator.hasStagedRowEdits(inTab: backgroundTabId)) } private static func finishFailure( diff --git a/apple/TableProTests/Views/Main/QueryParameterDetectionTests.swift b/apple/TableProTests/Views/Main/QueryParameterDetectionTests.swift index ddb9c261d9..1934076d2e 100644 --- a/apple/TableProTests/Views/Main/QueryParameterDetectionTests.swift +++ b/apple/TableProTests/Views/Main/QueryParameterDetectionTests.swift @@ -62,7 +62,6 @@ private struct QueryTabHarness { coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(type: type), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) let tab = QueryTab(title: "Query", query: query, tabType: .query) diff --git a/apple/TableProTests/Views/Main/RedisDatabaseSelectionGateTests.swift b/apple/TableProTests/Views/Main/RedisDatabaseSelectionGateTests.swift index 62ea39434b..ef37b495b4 100644 --- a/apple/TableProTests/Views/Main/RedisDatabaseSelectionGateTests.swift +++ b/apple/TableProTests/Views/Main/RedisDatabaseSelectionGateTests.swift @@ -28,7 +28,6 @@ struct RedisDatabaseSelectionGateTests { MainContentCoordinator( connection: connection, tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } diff --git a/apple/TableProTests/Views/Main/ResultPinningTests.swift b/apple/TableProTests/Views/Main/ResultPinningTests.swift index 2d0552c968..08ba677235 100644 --- a/apple/TableProTests/Views/Main/ResultPinningTests.swift +++ b/apple/TableProTests/Views/Main/ResultPinningTests.swift @@ -489,7 +489,6 @@ struct ResultPinningTests { MainContentCoordinator( connection: TestFixtures.makeConnection(database: "db"), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } diff --git a/apple/TableProTests/Views/Main/ResultReplacementEditsTests.swift b/apple/TableProTests/Views/Main/ResultReplacementEditsTests.swift new file mode 100644 index 0000000000..72a19f9d6b --- /dev/null +++ b/apple/TableProTests/Views/Main/ResultReplacementEditsTests.swift @@ -0,0 +1,135 @@ +// +// ResultReplacementEditsTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +@MainActor +struct ResultReplacementEditsTests { + private func stageEdit(in tabId: UUID, of fixture: CoordinatorFixture) { + let edits = fixture.coordinator.changeManager(forTab: tabId) + edits.configureForTable( + tableName: "users", + columns: ["id", "name"], + primaryKeyColumns: ["id"], + databaseType: .mysql, + generatedColumns: [], + triggerReload: false + ) + edits.recordCellChange( + rowID: .existing(0), columnIndex: 1, columnName: "name", + oldValue: "a", newValue: "z", originalRow: ["1", "a"] + ) + } + + private func presentResult(in tabId: UUID, of fixture: CoordinatorFixture) { + fixture.coordinator.queryExecutionCoordinator.presentMultiStatementResults( + tabId: tabId, + timing: PluginQueryTiming(total: 0), + totalRowsAffected: 0, + newResultSets: [ResultSet(label: "orders", tableRows: TableRows())], + sessionNotice: nil + ) + } + + private func select(_ tabId: UUID, from outgoing: UUID?, in fixture: CoordinatorFixture) { + fixture.tabManager.selectedTabId = tabId + fixture.coordinator.handleTabChange(from: outgoing, to: tabId, tabs: fixture.tabManager.tabs) + } + + @Test("A result installed on a background tab drops only that tab's edits") + func backgroundResultDropsItsTabsEdits() { + let fixture = CoordinatorFixture() + let background = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM users", tabType: .query)) + stageEdit(in: background.id, of: fixture) + let selected = fixture.addTab(QueryTab(title: "B", query: "SELECT * FROM users", tabType: .query)) + stageEdit(in: selected.id, of: fixture) + + presentResult(in: background.id, of: fixture) + + #expect(!fixture.coordinator.hasStagedRowEdits(inTab: background.id)) + #expect(fixture.coordinator.hasStagedRowEdits(inTab: selected.id)) + #expect(fixture.changeManager.hasChanges) + } + + @Test("A result installed on the selected tab drops its edits") + func selectedResultDropsItsEdits() { + let fixture = CoordinatorFixture() + let selected = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM users", tabType: .query)) + stageEdit(in: selected.id, of: fixture) + + presentResult(in: selected.id, of: fixture) + + #expect(!fixture.changeManager.hasChanges) + } + + @Test("A result that lands while the selection moves drops the edits of the tab it replaced") + func resultLandingDuringASwitchDropsItsTabsEdits() { + let fixture = CoordinatorFixture() + let edited = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM users", tabType: .query)) + let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) + stageEdit(in: edited.id, of: fixture) + + // The selection moved, the handler has not run yet, and the run finishes in between. + fixture.tabManager.selectedTabId = other.id + presentResult(in: edited.id, of: fixture) + fixture.coordinator.handleTabChange(from: edited.id, to: other.id, tabs: fixture.tabManager.tabs) + #expect(!fixture.coordinator.hasStagedRowEdits(inTab: edited.id)) + + select(edited.id, from: other.id, in: fixture) + #expect(!fixture.changeManager.hasChanges) + } + + @Test("Switching away and back keeps the tab's edits in its own manager") + func switchingBackKeepsTheEdits() { + let fixture = CoordinatorFixture() + let edited = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM users", tabType: .query)) + let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) + stageEdit(in: edited.id, of: fixture) + let edits = fixture.coordinator.changeManager(forTab: edited.id) + + select(other.id, from: edited.id, in: fixture) + #expect(!fixture.changeManager.hasChanges) + #expect(edits.hasChanges) + + select(edited.id, from: other.id, in: fixture) + #expect(fixture.changeManager === edits) + #expect(edits.isCellModified(rowID: .existing(0), columnIndex: 1)) + } + + @Test("Renaming a table moves a background tab's staged edits to the new name") + func renameRetargetsABackgroundTabsEdits() { + let fixture = CoordinatorFixture() + let edited = fixture.addTab(QueryTab(title: "users", query: "SELECT * FROM users", tabType: .table, tableName: "users")) + stageEdit(in: edited.id, of: fixture) + fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query)) + + fixture.coordinator.retitleTabs(ids: [edited.id], to: "people") + + #expect(fixture.coordinator.changeManager(forTab: edited.id).tableName == "people") + #expect(fixture.coordinator.hasStagedRowEdits(inTab: edited.id)) + } + + @Test("Edits staged after a reselect the switch handler never saw stay with their tab") + func reselectWithoutTheHandlerKeepsLaterEdits() { + let fixture = CoordinatorFixture() + let edited = fixture.addTab(QueryTab(title: "A", query: "SELECT * FROM users", tabType: .query)) + let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) + let third = fixture.addTab(QueryTab(title: "C", query: "SELECT 2", tabType: .query), select: false) + + // A to B and back inside one update, and no handler runs. + fixture.tabManager.selectedTabId = other.id + fixture.tabManager.selectedTabId = edited.id + stageEdit(in: edited.id, of: fixture) + + select(third.id, from: edited.id, in: fixture) + + #expect(fixture.coordinator.hasStagedRowEdits(inTab: edited.id)) + #expect(!fixture.changeManager.hasChanges) + } +} diff --git a/apple/TableProTests/Views/Main/RowCountTaskLifecycleTests.swift b/apple/TableProTests/Views/Main/RowCountTaskLifecycleTests.swift index f0aea875b0..814180bbc6 100644 --- a/apple/TableProTests/Views/Main/RowCountTaskLifecycleTests.swift +++ b/apple/TableProTests/Views/Main/RowCountTaskLifecycleTests.swift @@ -155,7 +155,6 @@ struct RowCountTaskLifecycleTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) return (coordinator, tabManager) diff --git a/apple/TableProTests/Views/Main/RowWriterWiringTests.swift b/apple/TableProTests/Views/Main/RowWriterWiringTests.swift index 303226b88f..dbb80377db 100644 --- a/apple/TableProTests/Views/Main/RowWriterWiringTests.swift +++ b/apple/TableProTests/Views/Main/RowWriterWiringTests.swift @@ -73,14 +73,18 @@ struct RowWriterWiringTests { for: connection.id ) state.coordinator.setupPluginDriver() - state.changeManager.configureForTable( + let tab = QueryTab(title: "events", query: "SELECT * FROM events", tabType: .table, tableName: "events") + state.tabManager.tabs.append(tab) + state.tabManager.selectedTabId = tab.id + let changeManager = state.coordinator.changeManager(forTab: tab.id) + changeManager.configureForTable( tableName: "events", columns: ["d", "id", "v"], primaryKeyColumns: ["d"], databaseType: .clickhouse, generatedColumns: [] ) - return (state.coordinator, state.changeManager) + return (state.coordinator, changeManager) } // The bug in #3776: the host keyed this on the sorting key `d`, and its DELETE removed every row sharing `d`. diff --git a/apple/TableProTests/Views/Main/SaveAttributionTests.swift b/apple/TableProTests/Views/Main/SaveAttributionTests.swift index c46cdf7b6f..2f561b83eb 100644 --- a/apple/TableProTests/Views/Main/SaveAttributionTests.swift +++ b/apple/TableProTests/Views/Main/SaveAttributionTests.swift @@ -1,3 +1,4 @@ +import AppKit import Foundation import TableProPluginKit import TableProTestSupport @@ -11,11 +12,34 @@ private final class SaveAnswers { var second: Bool? } +// Writes every statement as one row affected, so a keyed save lands. +private final class RowWritingDriver: PluginDriverStub, @unchecked Sendable { + private let lock = NSLock() + private var received: [String] = [] + private var database: String? + + var queries: [String] { lock.withLock { received } } + var supportsSchemas: Bool { false } + var supportsTransactions: Bool { false } + var currentSchema: String? { nil } + var currentDatabase: String? { lock.withLock { database } } + var serverVersion: String? { nil } + + func ping() async throws {} + func switchDatabase(to database: String) async throws { + lock.withLock { self.database = database } + } + func execute(query: String) async throws -> PluginQueryResult { + lock.withLock { received.append(query) } + return PluginQueryResult(columns: [], columnTypeNames: [], rows: [], rowsAffected: 1, executionTime: 0) + } +} + @MainActor struct SaveAttributionTests { // A table tab with one edited cell, and a gate that holds the save until the test answers. - private func makeEditedTable() -> (CoordinatorFixture, HeldExecutionGate, UUID) { - let fixture = CoordinatorFixture() + private func makeEditedTable(connection: DatabaseConnection = TestFixtures.makeConnection()) -> (CoordinatorFixture, HeldExecutionGate, UUID) { + let fixture = CoordinatorFixture(connection: connection) let gate = HeldExecutionGate() fixture.coordinator.executionGate = gate var tab = QueryTab(title: "users", query: "SELECT * FROM users", tabType: .table, tableName: "users") @@ -52,24 +76,47 @@ struct SaveAttributionTests { ) } - @Test("A save approved after a tab switch writes nothing and keeps the edits") - func saveApprovedAfterATabSwitchIsDropped() async throws { - let (fixture, gate, savingTabId) = makeEditedTable() - let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) + @Test("A save approved after a tab switch writes the saving tab's edits and clears only them") + func saveApprovedAfterATabSwitchClearsTheSavingTab() async throws { + let connection = TestFixtures.makeConnection() + let writer = RowWritingDriver() + var session = ConnectionSession( + connection: connection, + driver: PluginDriverAdapter(connection: connection, pluginDriver: writer) + ) + session.status = .connected + session.browseDatabase = connection.database + DatabaseManager.shared.injectSession(session, for: connection.id) + defer { DatabaseManager.shared.removeSession(for: connection.id) } + // A failed save reports in a sheet on this window rather than in a modal alert nothing answers. + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: true) + window.isReleasedWhenClosed = false + defer { window.orderOut(nil) } + let (fixture, gate, savingTabId) = makeEditedTable(connection: connection) + fixture.coordinator.contentWindow = window + let other = fixture.addTab(QueryTab(title: "B", query: "SELECT * FROM orders", tabType: .query), select: false) + let otherEdits = fixture.coordinator.changeManager(forTab: other.id) + otherEdits.recordRowDeletion(rowID: .existing(0), originalRow: ["1"]) save(fixture.coordinator) try await waitUntil { gate.askedCount == 1 } fixture.tabManager.selectedTabId = other.id + fixture.coordinator.handleTabChange(from: savingTabId, to: other.id, tabs: fixture.tabManager.tabs) await gate.answer(allowing: true) + let savingTab = { fixture.tabManager.tabs.first { $0.id == savingTabId } } try await waitUntil { - fixture.tabManager.tabs.first { $0.id == savingTabId }?.execution.errorMessage != nil + !fixture.coordinator.hasStagedRowEdits(inTab: savingTabId) || savingTab()?.execution.errorMessage != nil } - #expect(fixture.changeManager.hasChanges) - #expect(fixture.tabManager.tabs.first { $0.id == other.id }?.execution.errorMessage == nil) + #expect(savingTab()?.execution.errorMessage == nil) + #expect(!fixture.coordinator.hasStagedRowEdits(inTab: savingTabId)) + #expect(writer.queries.contains { $0.hasPrefix("UPDATE") }) + #expect(fixture.changeManager === otherEdits) + #expect(otherEdits.hasChanges) // The save is over: a second one is not refused as already running. #expect(fixture.coordinator.rowEditingCoordinator.beginSaveInFlight(tabId: nil)) fixture.coordinator.rowEditingCoordinator.endSaveInFlight() + withExtendedLifetime(window) {} } @Test("A value loaded during the approval prompt is not an edit, a new cell change is") diff --git a/apple/TableProTests/Views/Main/SaveCompletionTests.swift b/apple/TableProTests/Views/Main/SaveCompletionTests.swift index c984992ae9..a9c1b062cc 100644 --- a/apple/TableProTests/Views/Main/SaveCompletionTests.swift +++ b/apple/TableProTests/Views/Main/SaveCompletionTests.swift @@ -34,7 +34,7 @@ struct SaveCompletionTests { safeModeLevel: SafeModeLevel = .silent, type: DatabaseType = .mysql, pluginDriver: any PluginDatabaseDriver = StubSaveDriver() - ) -> (MainContentCoordinator, QueryTabManager, DataChangeManager) { + ) -> (MainContentCoordinator, QueryTabManager) { var conn = TestFixtures.makeConnection(type: type) conn.safeModeLevel = safeModeLevel let state = SessionStateFactory.create(connection: conn, payload: nil) @@ -46,14 +46,14 @@ struct SaveCompletionTests { ), for: conn.id ) - return (state.coordinator, state.tabManager, state.changeManager) + return (state.coordinator, state.tabManager) } // MARK: - No Changes @Test("saveChanges with no changes returns immediately without error") func noChanges_returnsWithoutError() { - let (coordinator, tabManager, _) = makeCoordinator() + let (coordinator, tabManager) = makeCoordinator() tabManager.addTab(databaseName: "testdb") var truncates: Set = [] @@ -73,7 +73,9 @@ struct SaveCompletionTests { @Test("saveChanges on read-only connection does not clear changes") func readOnly_doesNotClearChanges() { - let (coordinator, _, changeManager) = makeCoordinator(safeModeLevel: .readOnly) + let (coordinator, tabManager) = makeCoordinator(safeModeLevel: .readOnly) + tabManager.addTab(databaseName: "testdb") + let changeManager = coordinator.changeManager changeManager.hasChanges = true @@ -94,8 +96,9 @@ struct SaveCompletionTests { @Test("saveChanges with hasChanges true but no generated SQL sets error") func hasChangesButNoSQL_setsError() { - let (coordinator, tabManager, changeManager) = makeCoordinator() + let (coordinator, tabManager) = makeCoordinator() tabManager.addTab(databaseName: "testdb") + let changeManager = coordinator.changeManager changeManager.hasChanges = true @@ -122,8 +125,9 @@ struct SaveCompletionTests { PluginRowWrite(statement: "UPDATE items SET name = 'z' WHERE id = \($0.rowIndex)", rowIndices: [$0.rowIndex]) } } - let (coordinator, tabManager, changeManager) = makeCoordinator(pluginDriver: driver) + let (coordinator, tabManager) = makeCoordinator(pluginDriver: driver) tabManager.addTab(databaseName: "testdb") + let changeManager = coordinator.changeManager changeManager.configureForTable( tableName: "items", columns: ["_id", "name"], @@ -159,7 +163,7 @@ struct SaveCompletionTests { @Test("saveChanges with no changes and no pending ops does nothing") func noChangesNoPendingOps_noop() { - let (coordinator, tabManager, _) = makeCoordinator() + let (coordinator, tabManager) = makeCoordinator() tabManager.addTab(databaseName: "testdb") var truncates: Set = [] @@ -181,7 +185,7 @@ struct SaveCompletionTests { @Test("saveChanges with alert level and pending truncates clears inout params immediately") func alertLevel_pendingTruncates_clearsParams() { - let (coordinator, tabManager, _) = makeCoordinator(safeModeLevel: .alert) + let (coordinator, tabManager) = makeCoordinator(safeModeLevel: .alert) tabManager.addTab(databaseName: "testdb") var truncates: Set = [TestFixtures.makeTableRef(name: "users")] @@ -200,7 +204,7 @@ struct SaveCompletionTests { @Test("saveChanges with safeMode level and pending deletes clears inout params") func safeModeLevel_pendingDeletes_clearsParams() { - let (coordinator, tabManager, _) = makeCoordinator(safeModeLevel: .safeMode) + let (coordinator, tabManager) = makeCoordinator(safeModeLevel: .safeMode) tabManager.addTab(databaseName: "testdb") var truncates: Set = [] @@ -218,7 +222,7 @@ struct SaveCompletionTests { @Test("saveChanges with alert level and no changes does nothing") func alertLevel_noChanges_noop() { - let (coordinator, tabManager, _) = makeCoordinator(safeModeLevel: .alert) + let (coordinator, tabManager) = makeCoordinator(safeModeLevel: .alert) tabManager.addTab(databaseName: "testdb") var truncates: Set = [] @@ -238,7 +242,7 @@ struct SaveCompletionTests { @Test("saveChanges with silent level and pending truncates clears via normal path") func silentLevel_pendingTruncates_clearsViaNormalPath() { - let (coordinator, tabManager, _) = makeCoordinator(safeModeLevel: .silent) + let (coordinator, tabManager) = makeCoordinator(safeModeLevel: .silent) tabManager.addTab(databaseName: "testdb") var truncates: Set = [TestFixtures.makeTableRef(name: "users")] @@ -259,7 +263,7 @@ struct SaveCompletionTests { @Test("row operations blocked by readOnly level") func rowOperations_blockedByReadOnly() { - let (coordinator, tabManager, _) = makeCoordinator(safeModeLevel: .readOnly) + let (coordinator, tabManager) = makeCoordinator(safeModeLevel: .readOnly) tabManager.addTab(databaseName: "testdb") if let index = tabManager.selectedTabIndex { tabManager.tabs[index].tableContext.isEditable = true @@ -298,7 +302,7 @@ struct SaveCompletionTests { @Test("row operations allowed by alert level") func rowOperations_allowedByAlertLevel() { - let (coordinator, tabManager, _) = makeCoordinator(safeModeLevel: .alert) + let (coordinator, tabManager) = makeCoordinator(safeModeLevel: .alert) tabManager.addTab(databaseName: "testdb") if let index = tabManager.selectedTabIndex { tabManager.tabs[index].tableContext.isEditable = true diff --git a/apple/TableProTests/Views/Main/SaveInFlightEditGateTests.swift b/apple/TableProTests/Views/Main/SaveInFlightEditGateTests.swift index 107cce1726..5edaee9cf8 100644 --- a/apple/TableProTests/Views/Main/SaveInFlightEditGateTests.swift +++ b/apple/TableProTests/Views/Main/SaveInFlightEditGateTests.swift @@ -15,7 +15,6 @@ struct SaveInFlightEditGateTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(database: "shop", type: .postgresql), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) coordinator.openTableTab(TableInfo(name: "orders", type: .table, rowCount: nil, schema: "public")) diff --git a/apple/TableProTests/Views/Main/ScriptErrorResultTests.swift b/apple/TableProTests/Views/Main/ScriptErrorResultTests.swift index 9479a92e54..bf13db0680 100644 --- a/apple/TableProTests/Views/Main/ScriptErrorResultTests.swift +++ b/apple/TableProTests/Views/Main/ScriptErrorResultTests.swift @@ -23,7 +23,6 @@ struct ScriptErrorResultTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { diff --git a/apple/TableProTests/Views/Main/SeedBufferFromErrorResultTests.swift b/apple/TableProTests/Views/Main/SeedBufferFromErrorResultTests.swift index 4003c7f62d..5741987744 100644 --- a/apple/TableProTests/Views/Main/SeedBufferFromErrorResultTests.swift +++ b/apple/TableProTests/Views/Main/SeedBufferFromErrorResultTests.swift @@ -18,7 +18,6 @@ private final class SeedFixture { coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) let tab = QueryTab(title: "Query 1", query: "SELECT 3 AS third_col;", tabType: .query) diff --git a/apple/TableProTests/Views/Main/TabCloseProtectionTests.swift b/apple/TableProTests/Views/Main/TabCloseProtectionTests.swift index 5a6d165dc8..e12fa8b2d7 100644 --- a/apple/TableProTests/Views/Main/TabCloseProtectionTests.swift +++ b/apple/TableProTests/Views/Main/TabCloseProtectionTests.swift @@ -23,8 +23,7 @@ struct TabCloseProtectionTests { return SessionStateFactory.create(connection: connection, payload: nil).coordinator } - /// Puts a real pending change in the coordinator's change manager, the same way an inline cell - /// edit does, so the predicate is exercised against live state rather than a hand-built stub. + // Stages a real change in the selected tab's manager, as an inline cell edit does. private func stageCellEdit(on coordinator: MainContentCoordinator, table: String = "users") { coordinator.changeManager.configureForTable( tableName: table, @@ -38,10 +37,7 @@ struct TabCloseProtectionTests { // MARK: - The reported bug - /// The case the user reported, and the reason the old predicate could not answer it. Live grid - /// edits sit in the coordinator's change manager until a tab switch snapshots them into - /// `pendingChanges`, so a table tab edited and closed without ever leaving it had an empty - /// snapshot and reported itself clean. + // A table tab edited and closed without ever leaving it once reported itself clean. @Test("The selected tab reports its live cell edits with no tab switch") func selectedTabSeesLiveGridEdits() { let coordinator = makeCoordinator() @@ -56,16 +52,11 @@ struct TabCloseProtectionTests { stageCellEdit(on: coordinator) - #expect(!tab.pendingChanges.hasChanges) #expect(coordinator.hasUnsavedWork(in: tab)) } - /// The other half of the same rule: a tab the user is not looking at has no live state on the - /// coordinator, so its own snapshot is the only honest answer. Reading the live manager here - /// would report the selected tab's edits against a tab that does not own them, and would ask - /// about work the user cannot see on the tab they are closing. - @Test("A background tab reports its own snapshot, not the selected tab's live edits") - func backgroundTabReadsItsOwnSnapshot() { + @Test("A background tab reports its own edits, not the selected tab's") + func backgroundTabReadsItsOwnEdits() { let coordinator = makeCoordinator() defer { coordinator.teardown() } @@ -81,10 +72,8 @@ struct TabCloseProtectionTests { #expect(coordinator.changeManager.hasChanges) #expect(!coordinator.hasUnsavedWork(in: background)) - var carriesSnapshot = background - carriesSnapshot.pendingChanges = coordinator.changeManager.saveState() - #expect(carriesSnapshot.pendingChanges.hasChanges) - #expect(coordinator.hasUnsavedWork(in: carriesSnapshot)) + coordinator.changeManager(forTab: background.id).recordRowDeletion(rowID: .existing(0), originalRow: Self.originalRow) + #expect(coordinator.hasUnsavedWork(in: background)) } /// Work the connection holds must not gate an unrelated tab. Neither Save nor Don't Save could @@ -311,9 +300,7 @@ struct TabCloseProtectionTests { // MARK: - A closed tab takes its state with it - /// Nothing else can clear the change manager on this path: `handleTabChange` snapshots a tab by - /// looking it up in `tabManager.tabs`, and by the time it runs the tab is gone. Left behind, the - /// edits outlive their tab and the next Save runs them under whatever scope the sidebar moved to. + // Edits left behind would outlive their tab, and the next Save would run them under whatever scope the sidebar moved to. @Test("Closing the selected tab clears the change manager it was using") func closingClearsTheOrphanedChangeManager() { let coordinator = makeCoordinator() @@ -325,11 +312,14 @@ struct TabCloseProtectionTests { return } stageCellEdit(on: coordinator) - #expect(coordinator.changeManager.hasChanges) + let edits = coordinator.changeManager + #expect(edits.hasChanges) coordinator.closeTabsByUser(ids: [id]) #expect(coordinator.tabManager.tabs.isEmpty) + #expect(!edits.hasChanges) + #expect(coordinator.existingChangeManager(forTab: id) == nil) #expect(!coordinator.changeManager.hasChanges) #expect(!coordinator.hasAnyUnsavedWork()) } diff --git a/apple/TableProTests/Views/Main/TabEditHistoryTests.swift b/apple/TableProTests/Views/Main/TabEditHistoryTests.swift new file mode 100644 index 0000000000..5919ca1576 --- /dev/null +++ b/apple/TableProTests/Views/Main/TabEditHistoryTests.swift @@ -0,0 +1,165 @@ +// +// TabEditHistoryTests.swift +// TableProTests +// + +import AppKit +import Foundation +import SwiftUI +@testable import TablePro +import TableProPluginKit +import Testing + +@MainActor +struct TabEditHistoryTests { + private func makeSUT() -> (MainContentCommandActions, MainContentCoordinator) { + let connection = TestFixtures.makeConnection() + let coordinator = SessionStateFactory.create(connection: connection, payload: nil).coordinator + var selectedTables: Set = [] + var pendingTruncates: Set = [] + var pendingDeletes: Set = [] + var tableOperationOptions: [DatabaseTreeTableRef: TableOperationOptions] = [:] + let actions = MainContentCommandActions( + coordinator: coordinator, + connection: connection, + selectedTables: Binding(get: { selectedTables }, set: { selectedTables = $0 }), + pendingTruncates: Binding(get: { pendingTruncates }, set: { pendingTruncates = $0 }), + pendingDeletes: Binding(get: { pendingDeletes }, set: { pendingDeletes = $0 }), + tableOperationOptions: Binding(get: { tableOperationOptions }, set: { tableOperationOptions = $0 }), + trailingPaneState: TrailingPaneState() + ) + return (actions, coordinator) + } + + private func openTable(_ name: String, in coordinator: MainContentCoordinator) -> UUID { + var tab = QueryTab(title: name, query: "SELECT * FROM \(name)", tabType: .table, tableName: name) + tab.tableContext.isEditable = true + tab.tableContext.primaryKeyColumns = ["id"] + coordinator.tabManager.tabs.append(tab) + coordinator.setActiveTableRows( + TableRows.from( + queryRows: [[.text("1"), .text("ada")], [.text("2"), .text("grace")]], + columns: ["id", "name"], + columnTypes: [.integer(rawType: "INT"), .text(rawType: "TEXT")] + ), + for: tab.id + ) + select(tab.id, in: coordinator) + return tab.id + } + + private func select(_ tabId: UUID, in coordinator: MainContentCoordinator) { + let outgoing = coordinator.tabManager.selectedTabId + coordinator.tabManager.selectedTabId = tabId + coordinator.handleTabChange(from: outgoing, to: tabId, tabs: coordinator.tabManager.tabs) + } + + private func rename(row: Int, to name: String, in tabId: UUID, of coordinator: MainContentCoordinator) { + let old: PluginCellValue = row == 0 ? .text("ada") : .text("grace") + coordinator.changeManager(forTab: tabId).recordCellChange( + rowID: .existing(row), + columnIndex: 1, + columnName: "name", + oldValue: old, + newValue: .text(name), + originalRow: [.text("\(row + 1)"), old] + ) + } + + @Test("Switching tabs and back keeps the data undo history with the edits") + func switchingKeepsTheUndoHistory() { + let (actions, coordinator) = makeSUT() + let users = openTable("users", in: coordinator) + rename(row: 0, to: "lovelace", in: users, of: coordinator) + let orders = openTable("orders", in: coordinator) + + select(users, in: coordinator) + + #expect(coordinator.changeManager === coordinator.changeManager(forTab: users)) + #expect(coordinator.changeManager.hasChanges) + #expect(actions.canUndo) + + actions.undoChange() + + #expect(!coordinator.changeManager(forTab: users).hasChanges) + #expect(actions.canRedo) + #expect(coordinator.existingChangeManager(forTab: orders)?.hasChanges != true) + } + + @Test("Undo in one tab never reaches another tab's edits") + func undoStaysInItsTab() { + let (actions, coordinator) = makeSUT() + let users = openTable("users", in: coordinator) + rename(row: 0, to: "lovelace", in: users, of: coordinator) + let orders = openTable("orders", in: coordinator) + rename(row: 1, to: "hopper", in: orders, of: coordinator) + + actions.undoChange() + + #expect(!coordinator.changeManager(forTab: orders).hasChanges) + #expect(coordinator.changeManager(forTab: users).hasChanges) + #expect(!actions.canUndo) + } + + @Test("Each tab's edits keep their own table while another tab is shown") + func editsStayWithTheirTab() { + let (_, coordinator) = makeSUT() + let users = openTable("users", in: coordinator) + rename(row: 0, to: "lovelace", in: users, of: coordinator) + let orders = openTable("orders", in: coordinator) + + #expect(coordinator.changeManager(forTab: users).tableName == "users") + #expect(coordinator.changeManager(forTab: orders).tableName == "orders") + #expect(coordinator.changeManager(forTab: users).hasChanges) + #expect(!coordinator.changeManager.hasChanges) + #expect(coordinator.hasUnsavedWork(forTab: users)) + #expect(coordinator.selectedTabEdits.manager === coordinator.changeManager(forTab: orders)) + } + + @Test("A result that replaces a background tab's rows drops only that tab's edits") + func replacedResultDropsOnlyItsTabsEdits() { + let (_, coordinator) = makeSUT() + let users = openTable("users", in: coordinator) + rename(row: 0, to: "lovelace", in: users, of: coordinator) + let orders = openTable("orders", in: coordinator) + rename(row: 1, to: "hopper", in: orders, of: coordinator) + + coordinator.dropEdits(ofReplacedResultIn: users) + + #expect(!coordinator.changeManager(forTab: users).hasChanges) + #expect(coordinator.changeManager(forTab: orders).hasChanges) + } + + @Test("Closing a tab releases its edits and history") + func closingReleasesTheTabsEdits() { + let (_, coordinator) = makeSUT() + let users = openTable("users", in: coordinator) + rename(row: 0, to: "lovelace", in: users, of: coordinator) + let orders = openTable("orders", in: coordinator) + + coordinator.releaseEdits(ofTab: users) + + #expect(coordinator.existingChangeManager(forTab: users) == nil) + #expect(coordinator.existingChangeManager(forTab: orders) != nil) + } + + @Test("A schema rename moves a background tab's staged edits without clearing them") + func schemaRenameMovesStagedEdits() { + let (actions, coordinator) = makeSUT() + let users = openTable("users", in: coordinator) + coordinator.tabManager.mutate(tabId: users) { tab in + tab.tableContext.databaseName = "app" + tab.tableContext.schemaName = "sales" + } + coordinator.changeManager(forTab: users).schemaName = "sales" + rename(row: 0, to: "lovelace", in: users, of: coordinator) + _ = openTable("orders", in: coordinator) + + coordinator.retargetTabs(database: "app", schema: "sales", toDatabase: "app", toSchema: "crm") + select(users, in: coordinator) + + #expect(coordinator.changeManager.schemaName == "crm") + #expect(coordinator.changeManager.hasChanges) + #expect(actions.canUndo) + } +} diff --git a/apple/TableProTests/Views/Main/TabQueryIsolationTests.swift b/apple/TableProTests/Views/Main/TabQueryIsolationTests.swift index 8207e09cc8..3ac5d6f381 100644 --- a/apple/TableProTests/Views/Main/TabQueryIsolationTests.swift +++ b/apple/TableProTests/Views/Main/TabQueryIsolationTests.swift @@ -247,7 +247,6 @@ struct TabQueryIsolationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) diff --git a/apple/TableProTests/Views/Main/TableLoadConfirmationTests.swift b/apple/TableProTests/Views/Main/TableLoadConfirmationTests.swift index f5f2205af5..649b394295 100644 --- a/apple/TableProTests/Views/Main/TableLoadConfirmationTests.swift +++ b/apple/TableProTests/Views/Main/TableLoadConfirmationTests.swift @@ -108,7 +108,6 @@ struct TableLoadConfirmationTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: toolbarState ) coordinator.executionGate = gate diff --git a/apple/TableProTests/Views/Main/TableLoadForeignKeyPrefetchTests.swift b/apple/TableProTests/Views/Main/TableLoadForeignKeyPrefetchTests.swift index 9a6b18e4c9..997eef8b29 100644 --- a/apple/TableProTests/Views/Main/TableLoadForeignKeyPrefetchTests.swift +++ b/apple/TableProTests/Views/Main/TableLoadForeignKeyPrefetchTests.swift @@ -22,7 +22,6 @@ struct TableLoadForeignKeyPrefetchTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { diff --git a/apple/TableProTests/Views/Main/TableTabSchemaResolutionTests.swift b/apple/TableProTests/Views/Main/TableTabSchemaResolutionTests.swift index 94088a9d45..eb14311bab 100644 --- a/apple/TableProTests/Views/Main/TableTabSchemaResolutionTests.swift +++ b/apple/TableProTests/Views/Main/TableTabSchemaResolutionTests.swift @@ -22,7 +22,6 @@ struct TableTabSchemaResolutionTests { MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) } @@ -234,7 +233,6 @@ struct TableTabListingSchemaTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/Views/Main/UnloadedValueFirstLoadTests.swift b/apple/TableProTests/Views/Main/UnloadedValueFirstLoadTests.swift index 4021cd9f13..a3eddc910a 100644 --- a/apple/TableProTests/Views/Main/UnloadedValueFirstLoadTests.swift +++ b/apple/TableProTests/Views/Main/UnloadedValueFirstLoadTests.swift @@ -20,7 +20,6 @@ extension GlobalStateSuites { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(type: type), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "files", query: "SELECT * FROM `files` LIMIT 200", tabType: .table) diff --git a/apple/TableProTests/Views/Main/UpdatableViewRowWriteTests.swift b/apple/TableProTests/Views/Main/UpdatableViewRowWriteTests.swift index fd2e3f5568..8ea81ebed9 100644 --- a/apple/TableProTests/Views/Main/UpdatableViewRowWriteTests.swift +++ b/apple/TableProTests/Views/Main/UpdatableViewRowWriteTests.swift @@ -12,7 +12,6 @@ extension GlobalStateSuites { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(database: "shop", type: .postgresql), tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) coordinator.openTableTab(TableInfo(name: "v_orders", type: .view, rowCount: nil, schema: "public")) diff --git a/apple/TableProTests/Views/Main/ValueFilterEditedRowTests.swift b/apple/TableProTests/Views/Main/ValueFilterEditedRowTests.swift index c47bc60459..616ed7ef4a 100644 --- a/apple/TableProTests/Views/Main/ValueFilterEditedRowTests.swift +++ b/apple/TableProTests/Views/Main/ValueFilterEditedRowTests.swift @@ -31,7 +31,6 @@ struct ValueFilterEditedRowTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) var tab = QueryTab(title: "users", query: "SELECT * FROM users", tabType: .table, tableName: "users") diff --git a/apple/TableProTests/Views/Main/ValueFilterReloadTests.swift b/apple/TableProTests/Views/Main/ValueFilterReloadTests.swift index a94f41c9c5..b2fb083f69 100644 --- a/apple/TableProTests/Views/Main/ValueFilterReloadTests.swift +++ b/apple/TableProTests/Views/Main/ValueFilterReloadTests.swift @@ -24,7 +24,6 @@ struct ValueFilterReloadTests { let coordinator = MainContentCoordinator( connection: TestFixtures.makeConnection(), tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) let tab = QueryTab(title: "users", query: "SELECT id, name FROM users", tabType: tabType, tableName: "users") diff --git a/apple/TableProTests/Views/Main/WindowCloseSaveEveryConnectionTests.swift b/apple/TableProTests/Views/Main/WindowCloseSaveEveryConnectionTests.swift index bb0a30c859..8166c7082d 100644 --- a/apple/TableProTests/Views/Main/WindowCloseSaveEveryConnectionTests.swift +++ b/apple/TableProTests/Views/Main/WindowCloseSaveEveryConnectionTests.swift @@ -45,11 +45,17 @@ struct WindowCloseSaveEveryConnectionTests { try harness.addSelectedTab(to: harness.foreground) try harness.addSelectedTab(to: harness.background) - var edited = QueryTab(title: "users", query: "SELECT * FROM users", tabType: .table, tableName: "users") - edited.pendingChanges.insertedRowIDs = [.inserted(UUID())] - edited.pendingChanges.columns = ["id", "name"] - edited.pendingChanges.primaryKeyColumns = ["id"] + let edited = QueryTab(title: "users", query: "SELECT * FROM users", tabType: .table, tableName: "users") back.tabManager.tabs.append(edited) + let edits = back.changeManager(forTab: edited.id) + edits.configureForTable( + tableName: "users", + columns: ["id", "name"], + primaryKeyColumns: ["id"], + databaseType: back.connection.type, + generatedColumns: [] + ) + edits.recordRowInsertion(rowID: .inserted(UUID()), values: [.null, .null]) frontActions.confirmSaveChanges = { _, _ in .save } let outcome = await frontActions.closeWindowAwaiting() diff --git a/apple/TableProTests/Views/QuickSwitcherObjectKindTests.swift b/apple/TableProTests/Views/QuickSwitcherObjectKindTests.swift index 1a424d54dc..6df877dba6 100644 --- a/apple/TableProTests/Views/QuickSwitcherObjectKindTests.swift +++ b/apple/TableProTests/Views/QuickSwitcherObjectKindTests.swift @@ -40,7 +40,6 @@ struct QuickSwitcherObjectKindTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -73,7 +72,6 @@ struct QuickSwitcherObjectKindTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/Views/Sidebar/FailedContainerSwitchCommandTests.swift b/apple/TableProTests/Views/Sidebar/FailedContainerSwitchCommandTests.swift index 39c0195b2d..700c0b8af8 100644 --- a/apple/TableProTests/Views/Sidebar/FailedContainerSwitchCommandTests.swift +++ b/apple/TableProTests/Views/Sidebar/FailedContainerSwitchCommandTests.swift @@ -33,7 +33,6 @@ struct FailedContainerSwitchCommandTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: QueryTabManager(containerTarget: .database, visibleContainer: "db_a"), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/Views/Structure/StructureSavePlanTests.swift b/apple/TableProTests/Views/Structure/StructureSavePlanTests.swift index 277e783354..768dfe3478 100644 --- a/apple/TableProTests/Views/Structure/StructureSavePlanTests.swift +++ b/apple/TableProTests/Views/Structure/StructureSavePlanTests.swift @@ -163,7 +163,6 @@ struct StructureSavePlanTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) let tab = QueryTab( diff --git a/apple/TableProTests/Views/SwitchContainerTests.swift b/apple/TableProTests/Views/SwitchContainerTests.swift index a6c7530103..3a78bb8cb4 100644 --- a/apple/TableProTests/Views/SwitchContainerTests.swift +++ b/apple/TableProTests/Views/SwitchContainerTests.swift @@ -26,7 +26,6 @@ struct SwitchContainerTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/Views/SwitchDatabaseTests.swift b/apple/TableProTests/Views/SwitchDatabaseTests.swift index 893497c7f1..79fca697ff 100644 --- a/apple/TableProTests/Views/SwitchDatabaseTests.swift +++ b/apple/TableProTests/Views/SwitchDatabaseTests.swift @@ -31,7 +31,6 @@ struct SwitchDatabaseTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -43,13 +42,11 @@ struct SwitchDatabaseTests { func openTableTabSkipsForSameTableSameDatabase() throws { let connection = TestFixtures.makeConnection(database: "db_a") let tabManager = QueryTabManager() - let changeManager = DataChangeManager() let toolbarState = ConnectionToolbarState() let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: changeManager, toolbarState: toolbarState ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/Views/SwitchSchemaTests.swift b/apple/TableProTests/Views/SwitchSchemaTests.swift index e951c60034..8f220787e5 100644 --- a/apple/TableProTests/Views/SwitchSchemaTests.swift +++ b/apple/TableProTests/Views/SwitchSchemaTests.swift @@ -24,7 +24,6 @@ struct SwitchSchemaTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: QueryTabManager(), - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -87,7 +86,6 @@ struct SwitchSchemaTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -118,7 +116,6 @@ struct SwitchSchemaTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } diff --git a/apple/TableProTests/Views/VisibleContainerFollowingTests.swift b/apple/TableProTests/Views/VisibleContainerFollowingTests.swift index 15ee6ca493..a187230909 100644 --- a/apple/TableProTests/Views/VisibleContainerFollowingTests.swift +++ b/apple/TableProTests/Views/VisibleContainerFollowingTests.swift @@ -30,7 +30,6 @@ struct VisibleContainerFollowingTests { let coordinator = MainContentCoordinator( connection: connection, tabManager: tabManager, - changeManager: DataChangeManager(), toolbarState: ConnectionToolbarState() ) defer { coordinator.teardown() } @@ -108,8 +107,7 @@ struct VisibleContainerFollowingTests { } } - /// The edits are the outgoing tab's and go with it. Left in the change manager with no tab - /// selected, a Save would write them against the database on screen. + // A Save with no tab selected must not write the outgoing tab's edits against the database on screen. @Test("Landing on an entry with no tabs keeps the outgoing edits on their tab") func emptyEntryTakesNoLiveEdits() async throws { try await withConnectedCoordinator { coordinator, tabManager, _ in @@ -137,7 +135,8 @@ struct VisibleContainerFollowingTests { coordinator.handleTabChange(from: orders.id, to: nil, tabs: tabManager.tabs) #expect(!coordinator.changeManager.hasChanges) - #expect(tabManager.tabs.first?.pendingChanges.hasChanges == true) + #expect(coordinator.selectedTabEdits.manager === coordinator.idleChangeManager) + #expect(coordinator.hasStagedRowEdits(inTab: orders.id)) } } From b5c03b62092b15187b4a38e7c0fac07904ce4040 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 21:41:35 +0700 Subject: [PATCH 2/3] docs(changelog): note the edit, connection file and lost session fixes --- apple/changelog.d/4283.fixed.1.md | 1 + apple/changelog.d/4283.fixed.2.md | 1 + apple/changelog.d/4283.fixed.md | 1 + 3 files changed, 3 insertions(+) create mode 100644 apple/changelog.d/4283.fixed.1.md create mode 100644 apple/changelog.d/4283.fixed.2.md create mode 100644 apple/changelog.d/4283.fixed.md diff --git a/apple/changelog.d/4283.fixed.1.md b/apple/changelog.d/4283.fixed.1.md new file mode 100644 index 0000000000..670e225e26 --- /dev/null +++ b/apple/changelog.d/4283.fixed.1.md @@ -0,0 +1 @@ +One connection TablePro could not read emptied the whole connection list and blocked saving. diff --git a/apple/changelog.d/4283.fixed.2.md b/apple/changelog.d/4283.fixed.2.md new file mode 100644 index 0000000000..8824e3ccb7 --- /dev/null +++ b/apple/changelog.d/4283.fixed.2.md @@ -0,0 +1 @@ +After a reconnect lost a transaction, a grid save used up the warning meant for your next statement. diff --git a/apple/changelog.d/4283.fixed.md b/apple/changelog.d/4283.fixed.md new file mode 100644 index 0000000000..64200a86ab --- /dev/null +++ b/apple/changelog.d/4283.fixed.md @@ -0,0 +1 @@ +Switching tabs cleared the undo history of grid edits still waiting to be saved. From cb2eaaaec7e6a80fd98dbd9f14a048dadd6d9363 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sat, 14 Nov 2026 21:43:12 +0700 Subject: [PATCH 3/3] fix(windows): bring pending row edits and a held transaction back after Windows ends the app by force --- windows/docs/decisions/0004-app-shell.md | 8 +- .../docs/decisions/0006-editing-table-rows.md | 1 + .../src/TablePro.App.Model/ConnectionLife.cs | 5 +- .../src/TablePro.App.Model/DefinitionTab.cs | 3 + windows/src/TablePro.App.Model/QueryTab.cs | 7 + windows/src/TablePro.App.Model/SavedEdits.cs | 431 +++++++++++++++++ .../src/TablePro.App.Model/SessionState.cs | 71 +++ windows/src/TablePro.App.Model/TabSession.cs | 45 ++ windows/src/TablePro.App.Model/TableTab.cs | 108 ++++- .../src/TablePro.App.Model/WorkspaceTabs.cs | 3 + windows/src/TablePro.App/MainWindow.xaml.cs | 54 ++- windows/src/TablePro.App/Program.cs | 3 + .../src/TablePro.App/Services/AppRestart.cs | 23 + .../TablePro.App/Strings/en-US/Resources.resw | 27 ++ .../Views/DefinitionTabView.xaml.cs | 2 + .../src/TablePro.App/Views/IWorkspaceHost.cs | 3 + .../src/TablePro.App/Views/OpenConnection.cs | 5 +- .../src/TablePro.App/Views/QueryTabView.xaml | 51 +- .../TablePro.App/Views/QueryTabView.xaml.cs | 15 +- .../src/TablePro.App/Views/TableTabView.xaml | 23 +- .../TablePro.App/Views/TableTabView.xaml.cs | 70 +++ .../TablePro.App/Views/WorkspaceView.xaml.cs | 27 +- .../TablePro.DataGrid/DataGridView.Editing.cs | 17 + .../ConnectionFakes.cs | 2 +- .../SessionRecoveryTests.cs | 443 ++++++++++++++++++ .../TablePro.App.Model.Tests/TabFakes.cs | 26 + .../TabRecoveryTests.cs | 429 +++++++++++++++++ .../WorkspaceTabsTests.cs | 2 + .../CloseAndSessionTests.cs | 40 ++ .../TablePro.DataGrid.Tests/EditingTests.cs | 25 + 30 files changed, 1913 insertions(+), 56 deletions(-) create mode 100644 windows/src/TablePro.App.Model/SavedEdits.cs create mode 100644 windows/src/TablePro.App/Services/AppRestart.cs create mode 100644 windows/tests/TablePro.App.Model.Tests/SessionRecoveryTests.cs create mode 100644 windows/tests/TablePro.App.Model.Tests/TabRecoveryTests.cs diff --git a/windows/docs/decisions/0004-app-shell.md b/windows/docs/decisions/0004-app-shell.md index 43b7250c11..77528d429b 100644 --- a/windows/docs/decisions/0004-app-shell.md +++ b/windows/docs/decisions/0004-app-shell.md @@ -122,7 +122,7 @@ On 2026-11-05 the maintainer had the app show what the server prints, PostgreSQL - Table tabs page as macOS pages a table: a page is the default page size long (Settings, Pagination: 100, 500, 1,000, 5,000 or 10,000 rows, 1,000 unless changed, as macOS); First, Previous, Next and Last sit in the tab's `CommandBar`, and its one status words the page as the macOS status bar does, with the run's time: "1,001-2,000 of 3,503 rows · 15 ms", or "Rows 1,001-2,000 · 15 ms" until the count lands. A table that fits one page keeps "Rows: 347 · 12 ms". The core writes each page (`table_query` takes an offset, over `build_page`'s `PagePosition::Offset`) and counts the table (`table_row_count`, `build_count` as the Linux pager counts), in the background after the first full page; until the count lands, Next stays while pages come back full. Before it counts, it reads the engine's estimate (`table_row_estimate`, over `Connection::table_estimate`, as the Linux pager does), and decides as macOS does: an exact count the engine keeps is the total; under the threshold (Settings, Pagination, Count rows if estimate less than: 1,000, 10,000, 100,000, 1,000,000 or Always count, 100,000 unless changed, as macOS), or with no estimate, the server counts; from the threshold on nothing is counted, the status says "1-1,000 of about 2,000,000 rows" (no total under a filter), and Count rows in the command bar counts on request. Last page, Go to page and All rows wait for an exact count. A sort or a refresh goes back to the first page, and a refresh counts again. An engine that pages on the server (Cassandra) cannot seek by offset, so it has only its first page, as on macOS, and the core refuses another (`ffi.page_unsupported`). - Rows per page: a "1,000 rows" button before First page opens the macOS sizes, 5, 10, 20, 100, 500 and 1,000, as `RadioMenuFlyoutItem`s, then All rows..., which asks first and needs the count, and Custom..., up to 1,000,000. A new size keeps the page that holds the first row shown, as macOS does. The size belongs to the tab: `session.json` keeps it with the tab's page, and Reopen closed tab brings both back. - Go to page: between Previous and Next, "Page 3 of 36" opens a flyout with a `NumberBox` from 1 to the page count, as macOS asks in a popover. It is offered once the table is counted, as on macOS, and the box keeps a typed number inside that range (`InvalidInputOverwritten`). -- An open transaction: each run's `Finished` event carries the transaction the editor's connection is left in (the core's `RunSummary.transaction_state`). The tab that holds one shows a Warning `InfoBar` above its results, "Transaction open", with Roll back, which asks first, and Commit, hidden on a read-only connection; a failed one is an Error bar with Roll back only. Both send COMMIT or ROLLBACK as typed SQL, EXEC or DISCARD for a key-value engine, as the Linux app does. Over the tabs, a bar names another tab that holds one, with Show; macOS shows its bar above every tab of the connection, and here the owning tab carries the actions, since the transaction lives on that tab's own connection. Closing a tab that holds one asks first, since closing rolls it back. Window close and Exit confirm every affected held transaction before closing any tabs; cancelling keeps them open. Then one dialog lists every query tab still running, as macOS asks before it quits, and says closing rolls back a transaction a run has open; a table tab loading a page is not asked about. Exit then hides the windows and closes every connection, each tab stopping its run, for up to 5 seconds before the process ends. While any tab holds a transaction or unsaved changes, the primary window registers a reason with `ShutdownBlockReasonCreate` ("Table changes are not saved.", "A transaction is open.") and answers `WM_QUERYENDSESSION` with FALSE once it has written the session file: a sign-out or a restart then lists TablePro with its reason and the user can cancel and save, and a Restart Manager request, as from an installer, is cancelled ([Application Shutdown Changes in Windows Vista](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms700677(v=vs.85)); Restart Manager, [Guidelines for Applications](https://learn.microsoft.com/en-us/windows/win32/rstmgr/guidelines-for-applications)). A running query does not hold it, since stopping it is the default. A forced end cannot be held: "Sign out anyway" (`ENDSESSION_CRITICAL`) goes on to `WM_ENDSESSION`, which writes the session file again, and a forced Restart Manager close, as an update that closes the app by force, ends the process with no `WM_ENDSESSION`. Either way the unsaved changes and the transaction are lost. Disconnect, Reconnect and connecting an edited connection ask about held transactions the same way first, in the primary and in a tab window, but not about a running query, which they stop, and Reconnect and an edited connection bring the tabs back with their text on the new session. Cancelling that connect keeps the connection with Retry, so the tabs still come back. A window with a dialog already open waits for it to be dismissed before accepting a close request. WinUI opens one `ContentDialog` per thread, even across windows, so a question asked while another window shows one is declined, as Cancel would decline it (`WindowDialogs`). +- An open transaction: each run's `Finished` event carries the transaction the editor's connection is left in (the core's `RunSummary.transaction_state`). The tab that holds one shows a Warning `InfoBar` above its results, "Transaction open", with Roll back, which asks first, and Commit, hidden on a read-only connection; a failed one is an Error bar with Roll back only. Both send COMMIT or ROLLBACK as typed SQL, EXEC or DISCARD for a key-value engine, as the Linux app does. Over the tabs, a bar names another tab that holds one, with Show; macOS shows its bar above every tab of the connection, and here the owning tab carries the actions, since the transaction lives on that tab's own connection. Closing a tab that holds one asks first, since closing rolls it back. Window close and Exit confirm every affected held transaction before closing any tabs; cancelling keeps them open. Then one dialog lists every query tab still running, as macOS asks before it quits, and says closing rolls back a transaction a run has open; a table tab loading a page is not asked about. Exit then hides the windows and closes every connection, each tab stopping its run, for up to 5 seconds before the process ends. While any tab holds a transaction or unsaved changes, the primary window registers a reason with `ShutdownBlockReasonCreate` ("Table changes are not saved.", "A transaction is open.") and answers `WM_QUERYENDSESSION` with FALSE once it has written the session file: a sign-out or a restart then lists TablePro with its reason and the user can cancel and save, and a Restart Manager request, as from an installer, is cancelled ([Application Shutdown Changes in Windows Vista](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms700677(v=vs.85)); Restart Manager, [Guidelines for Applications](https://learn.microsoft.com/en-us/windows/win32/rstmgr/guidelines-for-applications)). A running query does not hold it, since stopping it is the default. A forced end cannot be held: "Sign out anyway" (`ENDSESSION_CRITICAL`) goes on to `WM_ENDSESSION`, which writes the session file again, and a forced Restart Manager close, as an update that closes the app by force, ends the process with no `WM_ENDSESSION`. Either way the server rolls the transaction back, and the session file already holds the work, as Restart Manager's guidelines ask: each table tab's pending changes, with the open cell editor's text as if it were kept (each change of that text starts the 2-second write too), a data row named by its primary key's values, each with the kind the core read it as so a BLOB and a text that read alike stay apart, and a cell by its column's name (a table with no primary key keeps none, since nothing finds its rows again), and each tab that held a transaction (`SavedEdits`, `SessionTab`). The app registers with `RegisterApplicationRestart` at startup (`RESTART_NO_CRASH | RESTART_NO_HANG`, no arguments), so Restart Manager starts it again after an update or a restart, and the new process claims the data folder as any launch does. A launch whose session holds such work reopens those connections and tabs even with Reopen at startup off (`SessionState.Recovered`). A table tab puts its changes back as pending once a page is read, each on the row its key finds there; a key two rows of the page share finds neither. What the page cannot take (a row not on it, a column gone, a value refused, every change while the table is locked) waits on the tab, and each later page read tries it again, so going to the row's page brings it back; a new row goes back whole or waits whole, since each try adds it again. An InfoBar over the rows says how many wait, with Discard, which drops only those and asks nothing more, and closes once none are left. Before a save sends its first statement, the session file is written at once with that tab's changes marked uncertain (`SavedRowEdit.Uncertain`), a write the file refuses being logged and the save going on; the change-triggered write that follows the save's answer clears the mark. Changes from a save whose outcome was unknown keep it too. The server may hold changes so marked already, so once any goes back, the tab is in the state an unknown outcome leaves it in, Save refused with "The last save may have been written" until a reload or Discard changes, and the bar says so. A query tab that held a transaction shows an InfoBar that it was open when TablePro last closed and the server rolled it back; the words name no cause, since a crash or a kill keeps the same work from the write before it. Only the session's own writes carry the work: the last write of a close or Exit leaves out what its questions covered, and a reconnect, a tab window's close and Reopen closed tab never carry it, so an answered change does not come back. Changes still waiting on a tab, and a connection not opened since, keep theirs in every write, Exit's last one too, since nothing has asked about them. Disconnect, Reconnect and connecting an edited connection ask about held transactions the same way first, in the primary and in a tab window, but not about a running query, which they stop, and Reconnect and an edited connection bring the tabs back with their text on the new session. Cancelling that connect keeps the connection with Retry, so the tabs still come back. A window with a dialog already open waits for it to be dismissed before accepting a close request. WinUI opens one `ContentDialog` per thread, even across windows, so a question asked while another window shows one is declined, as Cancel would decline it (`WindowDialogs`). - Safe Mode: before a typed run the core judges each statement at the connection's level (`DatabaseSession.gate_run`, over `SafeModeLevel::gate`, as the Linux editor judges its batches). Confirm writes asks before any write, and Off before a DROP, a TRUNCATE, or a DELETE or UPDATE with no WHERE. The question is a `ContentDialog` that lists each statement in full, with Cancel as the default. Read only keeps the whole run back, since the editor sends the text it runs whole: the selection, the whole text, or with Run statement the one statement. The driver splits that text with the session's own settings, so when the whole text reads stricter than every statement, the question shows the whole text. A MySQL script with DELIMITER lines is judged statement by statement, since the driver sends its statements apart. A level saved while the connection is open applies at once to its sessions in every window (`set_safe_mode`), as on Linux, and a connect still under way starts over when the save changed a field it reads or a secret, since the core read the saved connection as it began; a change to or from Read only takes a new connection, so those sessions reconnect once their held transactions are confirmed. A session that keeps its connection shows "Changes apply the next time you connect", as Linux says it, and one that cannot take Read only asks before every write until then. Statements are judged by the connection's own engine, also while its link is down and a tab's own connection still runs (`Session::grammar`). Commit, Roll back and a sort's rerun are not asked about. Closing a tab stops its run and waits for it to end before its connection closes. - Lifecycle: running, closing, paging, sorting, a lost editor, the session share and connecting are plain types in `src/TablePro.App.Model` (`QueryTab`, `TableTab`, `WorkspaceTabs`, `ConnectionLife`, `SessionShare`) over `ITabSession`, `ITabEditor` and `ITabRun`, with the core's adapters beside them. The views draw and ask through small view interfaces (`IQueryTabView`, `ITableTabView`, `IResultsView`, `IWorkspaceTabsView`, `IConnectionView`), so the model tests run them with fakes. - A table tab edits its page's rows, keeps the changes pending until Save, and asks before a reload or a close would lose them ([0006](0006-editing-table-rows.md)). @@ -139,9 +139,9 @@ A page in the window, built from `SettingsCard` and `SettingsExpander`: Appearan | Saved connections, groups, favourites | `connections.json` through the core, in the data folder | Core ADR 0006; the core's `StoragePaths` roots all point at the data folder | | Passwords and passphrases | Credential Manager, written by the core | Generic credentials named `TablePro/connection//`, persisted for the user on this PC, the core's label in the comment, cut to 255 characters. A credential holds at most 2,560 bytes, so a longer secret, such as an Entra or RDS IAM token, goes on in `/1`, `/2` and on, each part with a `TablePro_Parts` attribute naming its write, part count and length; a part missing or from another write reads as no secret | | Settings | `settings.json` in the data folder; a write another program blocks is tried again at the next change and on exit | No shared settings spec: Linux keeps its preferences in GSettings | -| Session, window placement, object pane width, tab windows | `session.json` in the data folder, written 2 seconds after a change (a write the file refuses is tried again, up to 30 seconds apart), as the primary window closes, when Windows ends the session (`WM_ENDSESSION`), before the app holds a sign-out or a Restart Manager close (`WM_QUERYENDSESSION`) and before an exception nothing caught ends the app | No shared spec: Linux keeps its workspace store in the app | +| Session, window placement, object pane width, tab windows, the pending work a forced end would lose | `session.json` in the data folder, written 2 seconds after a change (a write the file refuses is tried again, up to 30 seconds apart), as the primary window closes, when Windows ends the session (`WM_ENDSESSION`), before the app holds a sign-out or a Restart Manager close (`WM_QUERYENDSESSION`) and before an exception nothing caught ends the app | No shared spec: Linux keeps its workspace store in the app | -The data folder is the package's `ApplicationData.Current.LocalFolder` (`%LOCALAPPDATA%\Packages\\LocalState`), which Windows removes with the app ([Store and retrieve settings and other app data](https://learn.microsoft.com/en-us/windows/apps/design/app-settings/store-and-retrieve-app-data)). An unpackaged development build uses `%LOCALAPPDATA%\TablePro`, and `TABLEPRO_DATA_DIR` overrides both for the UI tests. The session holds each open connection (a saved one by id, a file by path), its tabs (a query tab's text, a table tab's table with its page size and page), the selected tab, the front connection, and each tab window with its connection, its tabs and its bounds. +The data folder is the package's `ApplicationData.Current.LocalFolder` (`%LOCALAPPDATA%\Packages\\LocalState`), which Windows removes with the app ([Store and retrieve settings and other app data](https://learn.microsoft.com/en-us/windows/apps/design/app-settings/store-and-retrieve-app-data)). An unpackaged development build uses `%LOCALAPPDATA%\TablePro`, and `TABLEPRO_DATA_DIR` overrides both for the UI tests. The session holds each open connection (a saved one by id, a file by path), its tabs (a query tab's text, a table tab's table with its page size and page), the selected tab, the front connection, and each tab window with its connection, its tabs and its bounds. Every write but a close's last one also holds each table tab's pending changes and whether a tab held a transaction (Workspace, An open transaction); like a query tab's text, the typed values stay in the user's data folder. One process owns a data folder. `Program.Main` registers it with `AppInstance.FindOrRegisterForKey` under a hash of its path (`InstanceKey`) before XAML starts, so a second launch on the same folder redirects its activation to the running app and ends, and the running app brings its primary window to the front ([Create a single-instanced app](https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/applifecycle/applifecycle-single-instance)). `RedirectActivationToAsync` waits for the owner without a limit, so the launch also stops waiting when the owner's process ends or after 5 seconds, then looks again or starts its own window (`LaunchClaim`); a launch always ends with a window. The primary window gives the key up (`UnregisterKey`) once the last session is saved, before its connections close, and a failure anywhere in the guard is written to `crash.log` and the app starts as usual. Two processes would otherwise each write their copy of `session.json` and `settings.json` over the other's. The core also locks `connections.json` for each write and reads it again first, which covers a writer outside the app. @@ -184,7 +184,7 @@ Facts the CI runs on `windows-2025` and `windows-11-arm` established, which the - The core gained the library and connecting through it: `Core::library`, `connect_saved`, `test_connection`, `parse_connection_url`, `DatabaseSession::table_query` and `sorted_query` with `sql_syntax::with_order_by` and `sort_reference`, `ResultSet::sorted` over `value::order`, and `Core::with_system_secrets`, which keeps secrets in Credential Manager on Windows (`core/ARCHITECTURE.md`, Platforms). - Then what the shell's second pass needed: `DatabaseDriver::category` (`EngineCategory`) and `DriverInfo.category`; in the library, tags (`create_tag`, `update_tag`, `delete_tag`, `tag_connections`, and the tags in the snapshot), `rename_connection`, `add_favorites` and `remove_favorites` with a place, `move_to_group` with a place and `move_groups`; `ErrorInfo.secret`; `table_query` with an offset and `can_seek`, `table_row_count`; `health`, `health_change` and `reconnect` on the session; `QueryEditor::is_lost`; the transaction in `RunEvent::Finished`; and `gate_run` and `set_safe_mode` on the session. Each has its test in `core/crates/ffi/tests`. -- `tests/TablePro.App.Model.Tests` covers settings, the session file with the window, the pane and the tab windows, the library tree with tags and search, selection by connection, drops, the engine families, closed tabs, the pager with its page sizes and Go to page, and the workspace bars, a run's messages, the form's fields and the object folders on any machine. With fakes for the session, the editor and the run, it also covers the lifecycle models: a tab closed during each await of a run, a page load or a count, which lets go of its editor and session once and shows nothing after; a lost editor that held a transaction; Safe Mode, where Commit, Roll back and a sort's rerun are never asked about; sorting the rows held; closing a tab that holds a transaction; reconnecting with tabs, a cancelled reconnect kept to retry, a share an adopting window holds, a session that arrives after a disconnect or after its connect started over, which closes unseen, and the pending work a sign-out waits on. `tests/TablePro.App.UITests` drives the unpackaged build through UI Automation (FlaUI): first run, Settings, the form and its engine families, connecting to a SQLite file, opening, sorting and paging a table with a width set through Transform and the header's ItemStatus, a table's page size and Go to page kept across a relaunch, a tab moved to its own window that comes back with its place and merges back by drag, a tab dragged out whose window closes with its last tab, a query and its sort, a script's rows sorted where they are, a failed connect, a password asked for, session restore, the rail's mark, the pane's width and the window's place across a relaunch, Reopen closed tab, an open transaction's bars, a PostgreSQL notice under Messages, and rename, tags, a drop and selection mode on the Connections page, in light and dark, with screenshots. +- `tests/TablePro.App.Model.Tests` covers settings, the session file with the window, the pane and the tab windows, the library tree with tags and search, selection by connection, drops, the engine families, closed tabs, the pager with its page sizes and Go to page, and the workspace bars, a run's messages, the form's fields and the object folders on any machine. With fakes for the session, the editor and the run, it also covers the lifecycle models: a tab closed during each await of a run, a page load or a count, which lets go of its editor and session once and shows nothing after; a lost editor that held a transaction; Safe Mode, where Commit, Roll back and a sort's rerun are never asked about; sorting the rows held; closing a tab that holds a transaction; reconnecting with tabs, a cancelled reconnect kept to retry, a share an adopting window holds, a session that arrives after a disconnect or after its connect started over, which closes unseen, and the pending work a sign-out waits on. It also covers the work the session file keeps across a forced end: pending changes through the file and back, rows found by key after the page reorders, keys told apart by kind and a key two rows share finding neither, the open editor's text, the write before a save's first statement, what a page cannot take waiting through the file for the later page that holds its row, a lock keeping all of it, Discard, an unknown or running save that comes back with Save blocked until a reload or a discard, a table with no key keeping nothing, a file from an older build, and the tabs a launch with Reopen at startup off brings back. `tests/TablePro.App.UITests` drives the unpackaged build through UI Automation (FlaUI): first run, Settings, the form and its engine families, connecting to a SQLite file, opening, sorting and paging a table with a width set through Transform and the header's ItemStatus, a table's page size and Go to page kept across a relaunch, a tab moved to its own window that comes back with its place and merges back by drag, a tab dragged out whose window closes with its last tab, a query and its sort, a script's rows sorted where they are, a failed connect, a password asked for, session restore, the rail's mark, the pane's width and the window's place across a relaunch, Reopen closed tab, an open transaction's bars, a pending edit that comes back after the app is killed with Reopen at startup off, a PostgreSQL notice under Messages, and rename, tags, a drop and selection mode on the Connections page, in light and dark, with screenshots. - SSH connections use the core's in-process transport (core ADR 0009). Host-key, passphrase and interactive login prompts use native ContentDialogs. A changed host key requires confirmation to remove its old entry, then separate confirmation of the replacement key on retry. - Not built yet: importing from other apps (the importers move to the core first). - Unverified: Native AOT publishing of the app, and the app on a real Windows 10 machine. diff --git a/windows/docs/decisions/0006-editing-table-rows.md b/windows/docs/decisions/0006-editing-table-rows.md index 21ae760963..40ec03334a 100644 --- a/windows/docs/decisions/0006-editing-table-rows.md +++ b/windows/docs/decisions/0006-editing-table-rows.md @@ -28,6 +28,7 @@ A table tab edits its page as the macOS app does, with the commands and words of - A value still in the open editor counts as a pending change: Save takes it, and every close asks about it. - A sort, a page, a page size or Refresh asks "Discard unsaved changes?" while changes are pending, as macOS asks, since the edits name rows of the page shown. An open edit is kept first; one the grid cannot keep holds the reload back. - Closing the tab, Disconnect, Reconnect, connecting an edited connection, closing the window and Exit show the tab and ask "Do you want to save changes to name?" with Save, Don't save and Cancel, beside the questions about held transactions. The workspace asks, since a tab that is not shown is out of the tree. A save that fails keeps the tab open and the window with it. A close while a save runs waits for it and asks only about what it left pending. Making the connection read only asks with Don't save and Cancel alone, since the changes would not be written there. +- Windows ending the app without asking, as a forced update or "Sign out anyway" does, leaves them in the session file by key, and the relaunch puts them back as pending ([0004](0004-app-shell.md), Workspace, An open transaction). ### Saving diff --git a/windows/src/TablePro.App.Model/ConnectionLife.cs b/windows/src/TablePro.App.Model/ConnectionLife.cs index 6c276deafc..94bcb16c15 100644 --- a/windows/src/TablePro.App.Model/ConnectionLife.cs +++ b/windows/src/TablePro.App.Model/ConnectionLife.cs @@ -56,7 +56,7 @@ public interface IConnectionView Task CloseTabsAsync(bool keepClosed); // Until it connects, the tabs it was saved with are still to come; once connected, the strip is the truth. - SessionConnection Snapshot(SessionConnection origin); + SessionConnection Snapshot(SessionConnection origin, bool withWork); } // A saved connection is reopened by id, a file opened without saving by its path. @@ -166,7 +166,8 @@ public async Task DisconnectAsync(bool keepTabs = false) SetState(ConnectionState.NotConnected); } - public SessionConnection Snapshot() => _view.Snapshot(_restore ?? Origin); + // Tabs still to come keep the work they were saved with, since nothing has asked about it yet. + public SessionConnection Snapshot(bool withWork = false) => _view.Snapshot(_restore ?? Origin, withWork); private async Task RunConnectAsync() { diff --git a/windows/src/TablePro.App.Model/DefinitionTab.cs b/windows/src/TablePro.App.Model/DefinitionTab.cs index f3205f198b..9d728a146c 100644 --- a/windows/src/TablePro.App.Model/DefinitionTab.cs +++ b/windows/src/TablePro.App.Model/DefinitionTab.cs @@ -77,6 +77,9 @@ public DefinitionTab(ITabSession session, IDefinitionTabView view, ObjectEntry e ParentTable = Entry.ParentTable, }; + // A definition is read again from the server, so nothing of it waits to be saved. + public SessionTab WithPendingWork(SessionTab snapshot) => snapshot; + // Also Reload. A call during a read shares it, since a second read of the same object adds only a server trip. public async Task LoadAsync() { diff --git a/windows/src/TablePro.App.Model/QueryTab.cs b/windows/src/TablePro.App.Model/QueryTab.cs index 7855b3fb24..d91f535cb4 100644 --- a/windows/src/TablePro.App.Model/QueryTab.cs +++ b/windows/src/TablePro.App.Model/QueryTab.cs @@ -110,6 +110,13 @@ public QueryTab( public SessionTab Snapshot() => new() { Kind = TabKind.Query, Title = Title, Sql = _view.WholeText, Database = Database }; + // The server rolls the transaction back once the app ends, so a relaunch can say so. + public SessionTab WithPendingWork(SessionTab snapshot) + { + ArgumentNullException.ThrowIfNull(snapshot); + return WorkspaceNotices.Holds(Transaction) ? snapshot with { HeldTransaction = true } : snapshot; + } + public async Task RunAsync() { if (IsRunning || _confirming || _work.IsClosed) diff --git a/windows/src/TablePro.App.Model/SavedEdits.cs b/windows/src/TablePro.App.Model/SavedEdits.cs new file mode 100644 index 0000000000..04dd60ccb0 --- /dev/null +++ b/windows/src/TablePro.App.Model/SavedEdits.cs @@ -0,0 +1,431 @@ +using System.Globalization; +using System.Text; +using System.Text.Json.Serialization; +using TablePro.Interop; + +namespace TablePro.App.Model; + +// A stored cell as a key names it: the kind the core read it as, and its whole text, null for NULL. +public readonly record struct StoredValue(ValueKind Kind, string? Text); + +// One column's stored values for rowCount rows from firstRow; throws TableProException when they cannot be read. +public delegate IReadOnlyList StoredValueReader(int column, int firstRow, int rowCount); + +// Pending changes as the session file keeps them; a key names each row, since the next page can hold it elsewhere. +public sealed record SavedEdits +{ + private const int SharedKey = -1; + + // Each changed row once, in the order of its latest change, as a save orders them. + public IReadOnlyList Rows { get; set; } = []; + + // A changed cell, a deleted row and a new row count one each. + [JsonIgnore] + public int Changes => (Rows ?? []).Sum(row => row?.Changes ?? 0); + + // Null with nothing pending or no key to find rows again; a draft is the open editor's text, kept as if typed. + public static SavedEdits? From( + TableEdits edits, StoredValueReader stored, bool uncertain = false, CellDraft? draft = null) + { + ArgumentNullException.ThrowIfNull(edits); + ArgumentNullException.ThrowIfNull(stored); + var columns = edits.Columns; + var key = KeyColumns(columns); + var open = draft is { Row: >= 0, Column: >= 0 } typed + && typed.Row < edits.RowCount + && typed.Column < columns.Count + && !edits.IsDeleted(typed.Row) + ? typed + : null; + if (key.Count == 0 || (!edits.HasChanges && open is null)) + { + return null; + } + + var planned = edits.ToRowEdits(); + List<(int Row, SavedRowEdit Edit)> rows = []; + for (var index = 0; index < planned.Edits.Count; index++) + { + var saved = planned.Edits[index] switch + { + RowEdit.Insert insert => new SavedRowEdit + { + Cells = Named(columns, insert.Cells.Select((cell, column) => new CellChange(column, cell))), + Uncertain = uncertain, + }, + RowEdit.Delete delete => KeyOf(columns, key, (int)delete.Row, stored) is { } named + ? new SavedRowEdit { Key = named, Deleted = true, Uncertain = uncertain } + : null, + RowEdit.Update update => KeyOf(columns, key, (int)update.Row, stored) is { } named + ? new SavedRowEdit { Key = named, Cells = Named(columns, update.Cells), Uncertain = uncertain } + : null, + _ => null, + }; + if (saved is not null) + { + rows.Add((planned.Rows[index], saved)); + } + } + + if (open is not null && Drafted(columns, key, stored, edits, rows, open, uncertain) is { } drafted) + { + rows.Add((open.Row, drafted)); + } + + return rows.Count == 0 ? null : new SavedEdits { Rows = [.. rows.Select(row => row.Edit)] }; + } + + // Waiting holds what did not go back; Uncertain says a change that went back may be on the server already. + public (int Restored, bool Uncertain, SavedEdits? Waiting) RestoreTo( + TableEdits edits, StoredValueReader stored, Func set) + { + ArgumentNullException.ThrowIfNull(edits); + ArgumentNullException.ThrowIfNull(stored); + ArgumentNullException.ThrowIfNull(set); + var columns = edits.Columns; + var byName = new Dictionary(StringComparer.Ordinal); + for (var column = 0; column < columns.Count; column++) + { + byName.TryAdd(columns[column].Name, column); + } + + var key = KeyColumns(columns); + Dictionary? page = null; + var restored = 0; + var uncertain = false; + List waiting = []; + foreach (var saved in Rows ?? []) + { + if (saved is null) + { + continue; + } + + if (saved.Key is null) + { + // A new row goes back whole or waits whole, since each try adds it again. + var added = edits.AddRow(); + if (PutCells(saved, added, edits, byName, set).Count > 0) + { + edits.DeleteRows([added]); + waiting.Add(saved); + } + else + { + restored += saved.Changes; + uncertain |= saved.Uncertain; + } + + continue; + } + + page ??= PageRows(edits.DataRows, key, stored); + if (Wanted(saved.Key, columns, key) is not { } wanted + || !page.TryGetValue(wanted, out var row) + || row == SharedKey) + { + waiting.Add(saved); + continue; + } + + if (saved.Deleted) + { + edits.DeleteRows([row]); + restored += saved.Changes; + uncertain |= saved.Uncertain; + continue; + } + + var left = PutCells(saved, row, edits, byName, set); + restored += saved.Changes - left.Count; + uncertain |= saved.Uncertain && left.Count < saved.Changes; + if (left.Count > 0) + { + waiting.Add(saved with { Cells = left }); + } + } + + return (restored, uncertain, waiting.Count == 0 ? null : new SavedEdits { Rows = waiting }); + } + + // The changes still waiting, then the ones pending now, which a relaunch puts back in that order. + public static SavedEdits? Join(SavedEdits? waiting, SavedEdits? pending) + { + if (waiting is null || pending is null) + { + return waiting ?? pending; + } + + return new SavedEdits { Rows = [.. waiting.Rows ?? [], .. pending.Rows ?? []] }; + } + + // The open editor's text, as its commit would make it: the cell's edit and the row's latest change. + private static SavedRowEdit? Drafted( + IReadOnlyList columns, + List key, + StoredValueReader stored, + TableEdits edits, + List<(int Row, SavedRowEdit Edit)> rows, + CellDraft open, + bool uncertain) + { + var cell = SavedCell.From(new CellEdit.Text(open.Text)); + var name = columns[open.Column].Name; + var at = rows.FindIndex(row => row.Row == open.Row); + if (at >= 0) + { + var edited = rows[at].Edit; + rows.RemoveAt(at); + return edited with + { + Cells = new Dictionary(edited.Cells ?? SavedRowEdit.NoCells, StringComparer.Ordinal) + { + [name] = cell, + }, + }; + } + + return !edits.IsAdded(open.Row) && KeyOf(columns, key, open.Row, stored) is { } named + ? new SavedRowEdit + { + Key = named, + Cells = new Dictionary(StringComparer.Ordinal) { [name] = cell }, + Uncertain = uncertain, + } + : null; + } + + private static List KeyColumns(IReadOnlyList columns) => + [.. Enumerable.Range(0, columns.Count).Where(column => columns[column].PrimaryKey)]; + + private static Dictionary Named(IReadOnlyList columns, IEnumerable cells) + { + var named = new Dictionary(StringComparer.Ordinal); + foreach (var cell in cells) + { + named.TryAdd(columns[cell.Column].Name, SavedCell.From(cell.Edit)); + } + + return named; + } + + private static Dictionary? KeyOf( + IReadOnlyList columns, List key, int row, StoredValueReader stored) + { + var named = new Dictionary(StringComparer.Ordinal); + try + { + foreach (var column in key) + { + if (stored(column, row, 1) is not [var value]) + { + return null; + } + + named.TryAdd(columns[column].Name, SavedKeyPart.From(value)); + } + } + catch (TableProException) + { + // A row whose key cannot be read cannot be found again, so it is not kept. + return null; + } + + return named; + } + + // The page's rows by key, each key column read once; a key two rows share finds neither (SharedKey). + private static Dictionary PageRows(int dataRows, List key, StoredValueReader stored) + { + var rows = new Dictionary(StringComparer.Ordinal); + if (key.Count == 0 || dataRows == 0) + { + return rows; + } + + IReadOnlyList[] values; + try + { + values = [.. key.Select(column => stored(column, 0, dataRows))]; + } + catch (TableProException) + { + // Without the page's keys no row can be found, so every change waits. + return rows; + } + + var parts = new StoredValue[key.Count]; + // A row a key column did not read cannot be found. + var readable = values.Min(column => column.Count); + for (var row = 0; row < Math.Min(dataRows, readable); row++) + { + for (var part = 0; part < key.Count; part++) + { + parts[part] = values[part][row]; + } + + var joined = Joined(parts); + if (!rows.TryAdd(joined, row)) + { + rows[joined] = SharedKey; + } + } + + return rows; + } + + // The key must name the table's key columns now, no more and no fewer, each with a kind this build knows. + private static string? Wanted( + IReadOnlyDictionary saved, IReadOnlyList columns, List key) + { + if (key.Count == 0 || saved.Count != key.Count) + { + return null; + } + + var parts = new StoredValue[key.Count]; + for (var part = 0; part < key.Count; part++) + { + if (!saved.TryGetValue(columns[key[part]].Name, out var named) || named?.ToValue() is not { } value) + { + return null; + } + + parts[part] = value; + } + + return Joined(parts); + } + + // Kind and length first, so a BLOB and a text that read alike differ; a NULL holds its column's kind, so not that. + private static string Joined(StoredValue[] parts) + { + var joined = new StringBuilder(); + foreach (var part in parts) + { + if (part.Text is null) + { + joined.Append("-;"); + } + else + { + joined.Append(((byte)part.Kind).ToString(CultureInfo.InvariantCulture)).Append(':') + .Append(part.Text.Length.ToString(CultureInfo.InvariantCulture)).Append(':').Append(part.Text); + } + } + + return joined.ToString(); + } + + // The cells that did not go back, by column name. + private static Dictionary PutCells( + SavedRowEdit saved, + int row, + TableEdits edits, + Dictionary byName, + Func set) + { + var left = new Dictionary(StringComparer.Ordinal); + foreach (var (name, cell) in saved.Cells ?? SavedRowEdit.NoCells) + { + if (name is null || cell is null) + { + continue; + } + + if (!byName.TryGetValue(name, out var column) || cell.ToEdit() is not { } edit) + { + left[name] = cell; + continue; + } + + // A new row starts with each column's own value, which takes no edit. + if (edits.IsAdded(row) && Equals(edits.GetCell(row, column), edit)) + { + continue; + } + + if (!set(row, column, edit)) + { + left[name] = cell; + } + } + + return left; + } +} + +public sealed record SavedRowEdit +{ + internal static readonly IReadOnlyDictionary NoCells = new Dictionary(); + + // A data row's primary key by column name, each value with its kind; none for a new row. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public IReadOnlyDictionary? Key { get; set; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] + public bool Deleted { get; set; } + + // From a save whose outcome is unknown, or one running as the file was written: the server may hold it already. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] + public bool Uncertain { get; set; } + + // By column name: a data row's changed cells, or every cell of a new row. + public IReadOnlyDictionary Cells { get; set; } = NoCells; + + [JsonIgnore] + public int Changes => Deleted || Key is null ? 1 : (Cells ?? NoCells).Count; +} + +// A key value by its ValueKind's name and its whole text, null for NULL; a kind this build does not know finds no row. +public sealed record SavedKeyPart +{ + public string Kind { get; set; } = string.Empty; + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Text { get; set; } + + public static SavedKeyPart From(StoredValue value) => new() + { + Kind = Enum.GetName(value.Kind) ?? ((byte)value.Kind).ToString(CultureInfo.InvariantCulture), + Text = value.Text, + }; + + public StoredValue? ToValue() + { + if (Text is null) + { + return new StoredValue(ValueKind.Other, null); + } + + return SavedName.TryParse(Kind, out ValueKind kind) ? new StoredValue(kind, Text) : null; + } +} + +// A cell's edit by its CellEdit kind's name, so a kind a later build adds reads as none here, not as a broken file. +public sealed record SavedCell +{ + public string Kind { get; set; } = nameof(CellEdit.Text); + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? Text { get; set; } + + public static SavedCell From(CellEdit edit) + { + ArgumentNullException.ThrowIfNull(edit); + return edit switch + { + CellEdit.Text text => new SavedCell { Kind = nameof(CellEdit.Text), Text = text.Value }, + CellEdit.Null => new SavedCell { Kind = nameof(CellEdit.Null) }, + _ => new SavedCell { Kind = nameof(CellEdit.ServerDefault) }, + }; + } + + public CellEdit? ToEdit() => Kind switch + { + nameof(CellEdit.Text) => new CellEdit.Text(Text ?? string.Empty), + nameof(CellEdit.Null) => CellEdit.Null.Instance, + nameof(CellEdit.ServerDefault) => CellEdit.ServerDefault.Instance, + _ => null, + }; +} diff --git a/windows/src/TablePro.App.Model/SessionState.cs b/windows/src/TablePro.App.Model/SessionState.cs index 60d867e6fc..2f36601479 100644 --- a/windows/src/TablePro.App.Model/SessionState.cs +++ b/windows/src/TablePro.App.Model/SessionState.cs @@ -1,3 +1,4 @@ +using System.Text.Json.Serialization; using TablePro.Interop; namespace TablePro.App.Model; @@ -39,6 +40,18 @@ public sealed record SessionTab // The database a query tab opened from a definition runs in, where the definition names none. public string? Database { get; set; } + // A table tab's pending changes by key, which the session's writes keep until a close has asked about them. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public SavedEdits? Edits { get; set; } + + // The tab's own connection held a transaction, which the server rolled back as the app ended. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] + public bool HeldTransaction { get; set; } + + // What the app ended holding without a close, which a launch brings back even with Reopen at startup off. + [JsonIgnore] + public bool HasRecoveredWork => Edits is { Changes: > 0 } || HeldTransaction; + // A name this build does not define, as from a later build, reads as the fallback. public ObjectKind ObjectKindOr(ObjectKind fallback) => SavedName.TryParse(ObjectKind, out ObjectKind kind) ? kind : fallback; @@ -219,6 +232,64 @@ public SessionState Restorable() .Select(window => window with { Placement = Usable(window.Placement) })], }; } + + // Only the tabs holding recovered work, in their connections and windows, for a launch with Reopen at startup off. + public SessionState Recovered() + { + List kept = []; + var front = -1; + for (var index = 0; index < Connections.Count; index++) + { + if (RecoveredTabs(Connections[index]) is { } connection) + { + if (index == Front) + { + front = kept.Count; + } + + kept.Add(connection); + } + } + + return new SessionState + { + Connections = kept, + Front = front < 0 && kept.Count > 0 ? 0 : front, + Window = Window, + ObjectPaneWidth = ObjectPaneWidth, + TabWindows = [.. TabWindows + .Select(window => window is not null && RecoveredTabs(window.Connection) is { } connection + ? window with { Connection = connection } + : null) + .OfType()], + }; + } + + private static SessionConnection? RecoveredTabs(SessionConnection? connection) + { + if (connection is null) + { + return null; + } + + var tabs = connection.Tabs ?? []; + List kept = []; + var selected = 0; + for (var index = 0; index < tabs.Count; index++) + { + if (tabs[index] is { HasRecoveredWork: true } tab) + { + if (index == connection.SelectedTab) + { + selected = kept.Count; + } + + kept.Add(tab); + } + } + + return kept.Count == 0 ? null : connection with { Tabs = kept, SelectedTab = selected }; + } } public static class ObjectPane diff --git a/windows/src/TablePro.App.Model/TabSession.cs b/windows/src/TablePro.App.Model/TabSession.cs index 3cad780acc..5f39722dfc 100644 --- a/windows/src/TablePro.App.Model/TabSession.cs +++ b/windows/src/TablePro.App.Model/TabSession.cs @@ -62,6 +62,9 @@ public interface ITableEditor : IDisposable EditStart GetEditStart(ResultSet? rows, long row, int column); + // One column's stored values with their kinds, for rowCount rows from firstRow, as a key names a row in the file. + IReadOnlyList GetStoredValues(ResultSet? rows, int column, long firstRow, int rowCount); + CoreError? Check(int column, CellEdit edit, bool newRow); IRowSave Plan(ResultSet? rows, IReadOnlyList edits); @@ -173,6 +176,9 @@ public async Task OpenTableEditorAsync( internal sealed class CoreTableEditor(TableEditor editor) : ITableEditor { + // Rows read at a time for their kinds, so a page of any size takes a bounded window. + private const int KindWindow = 4096; + // The rows the edits name are gone, as when the page went before its save was planned. private static readonly CoreError RowsGone = new( "edit.out_of_range", ["edit.out_of_range"], "The page's rows are no longer held.", null, null); @@ -187,6 +193,45 @@ internal sealed class CoreTableEditor(TableEditor editor) : ITableEditor public EditStart GetEditStart(ResultSet? rows, long row, int column) => rows is null ? EditStart.Locked.Instance : editor.GetEditStart(rows, row, column); + // A window holds the kinds; the text is the whole value, which a window cuts. + public IReadOnlyList GetStoredValues(ResultSet? rows, int column, long firstRow, int rowCount) + { + ArgumentOutOfRangeException.ThrowIfNegative(rowCount); + if (rows is null) + { + throw new TableProException(RowsGone); + } + + var values = new StoredValue[rowCount]; + try + { + using var cursor = rows.OpenCursor(); + for (var start = 0; start < rowCount; start += KindWindow) + { + var count = Math.Min(KindWindow, rowCount - start); + var window = cursor.Fetch(firstRow + start, count, column, 1, maxCharacters: 1); + if (window.RowCount < count || window.ColumnCount < 1) + { + throw new TableProException(RowsGone); + } + + for (var row = 0; row < count; row++) + { + var kind = window.GetKind(row, 0); + values[start + row] = window.IsNull(row, 0) + ? new StoredValue(kind, null) + : new StoredValue(kind, rows.GetCellText(firstRow + start + row, column)); + } + } + } + catch (ObjectDisposedException) + { + throw new TableProException(RowsGone); + } + + return values; + } + public CoreError? Check(int column, CellEdit edit, bool newRow) => editor.Check(column, edit, newRow); public IRowSave Plan(ResultSet? rows, IReadOnlyList edits) => diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index 2587a0c034..b459bc4532 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -27,6 +27,9 @@ public enum CellValueKind Default, } +// The open editor's cell and text, which a commit would keep; Row counts the page's rows, then the new ones. +public sealed record CellDraft(int Row, int Column, string Text); + // The run that read the page shown, which the status words with the page. public readonly record struct PageRun(long Milliseconds, bool Truncated); @@ -87,6 +90,12 @@ public interface ITableTabView // The grid has an editor open, whose text counts as a change until it is kept or cancelled. bool HasOpenEdit { get; } + // The open editor's text where it differs from what it opened with; null otherwise. + CellDraft? OpenDraft { get; } + + // Writes the session file at once, the edits marked uncertain; a write the file refuses is logged, never thrown. + void WriteSessionNow(); + // The grid's open editor keeps its text first; false when the text was refused and the editor stays open. bool CommitOpenEdit(); @@ -113,6 +122,9 @@ public interface ITableTabView // Without the columns and their operators the filter bar has nothing to offer. void ShowFilterChoicesFailed(CoreError failure); + + // Recovered changes back and waiting, and whether Save waits for a reload or a discard; all empty hides it. + void ShowRecovered(int restored, int waiting, bool saveBlocked); } // A sort and a filter are the page's ORDER BY and WHERE, so they order and pick from the whole table. @@ -166,6 +178,12 @@ public sealed class TableTab : IWorkspaceTab private bool _saveBlocked; private Task _save = Task.FromResult(true); + // The block came from recovered changes, so the notice that says so goes with it. + private bool _recoveredBlock; + + // Changes the app ended holding without a close that no page has taken yet; each page read tries them again. + private SavedEdits? _recovered; + public TableTab( ITabSession session, ITableTabView view, @@ -192,6 +210,7 @@ public TableTab( // A restored filter stays until the user changes it, even when the first read refuses it. Filter = restore?.Filter?.ToFilter(); _shownFilter = Filter; + _recovered = restore?.Edits is { Changes: > 0 } recovered ? recovered : null; _structure = new KeptRead( _work, token => _session.GetStructureAsync(Table, ObjectKind, token), @@ -298,6 +317,7 @@ public bool Shows(string? schema, string table) => string.Equals(Table.Name, table, StringComparison.Ordinal) && string.Equals(Table.Schema, schema, StringComparison.Ordinal); + // Recovered changes not yet put back go along, since nothing has asked about them. public SessionTab Snapshot() => new() { Kind = TabKind.Table, @@ -308,8 +328,41 @@ public bool Shows(string? schema, string table) => PageSize = _chosenSize, Offset = _page.Offset > 0 ? _page.Offset : null, Filter = Filter is { } filter ? SavedFilter.From(filter) : null, + Edits = _recovered, }; + // Recovered changes still waiting, then the ones pending now, by key; a relaunch puts them back on its page. + public SessionTab WithPendingWork(SessionTab snapshot) + { + ArgumentNullException.ThrowIfNull(snapshot); + // The open editor's text goes too, as if kept, while the grid keeps it open. + var draft = _view.OpenDraft; + if (Edits is not { } edits || _tableEditor is null || (!edits.HasChanges && draft is null)) + { + return snapshot; + } + + // A save that may have written them, or is writing them now, leaves them blocked after a relaunch as here. + var pending = SavedEdits.From(edits, ReadStoredValues, uncertain: _saveBlocked || IsSaving, draft); + return snapshot with { Edits = SavedEdits.Join(_recovered, pending) }; + } + + // Recovered changes no page has taken yet, which the tab's bar counts and offers to discard. + public int WaitingChanges => _recovered?.Changes ?? 0; + + // Only the waiting changes go, without a question: the bar that offers this names them. + public void DiscardWaiting() + { + if (_recovered is null) + { + return; + } + + _recovered = null; + _view.ShowRecovered(0, 0, _saveBlocked && _recoveredBlock); + StateChanged?.Invoke(this, EventArgs.Empty); + } + // The edits name rows of the page shown, so a reload asks first while any is pending, as macOS asks. public async Task MayReloadAsync(ReloadReason reason) { @@ -330,7 +383,7 @@ public async Task MayReloadAsync(ReloadReason reason) } // The discarded edits took the blocked save with them, whether or not the reload then reads the page. - _saveBlocked = false; + Unblock(); Edits?.Discard(); return true; } @@ -579,7 +632,7 @@ public async Task DiscardAsync() return; } - _saveBlocked = false; + Unblock(); edits.Discard(); } @@ -819,8 +872,9 @@ await _results.ShowRunAsync(_run, _sort, read.VisibleColumns, keptSets: 0, cance _shownFilter = filter; _page = _page with { Rows = _results.RowCount }; // The server's rows are read again, so a save whose outcome was unknown may be judged by them now. - _saveBlocked = false; + Unblock(); BindEdits(); + RestoreRecovered(); CountIfNeeded(); } catch (TableProException exception) @@ -890,6 +944,52 @@ private void BindEdits() SetEdits(new TableEdits(editor.Columns, rows), shown); } + // Each change goes back as if typed on the row its key finds; a lock keeps every one, and the rest wait. + private void RestoreRecovered() + { + if (_recovered is not { } recovered || Edits is not { } edits) + { + return; + } + + if (Lock is not null) + { + _view.ShowRecovered(0, recovered.Changes, saveBlocked: false); + return; + } + + var (restored, uncertain, waiting) = recovered.RestoreTo(edits, ReadStoredValues, (row, column, edit) => + CellRefusal(edits, row, column) is null && Apply(edits, row, column, edit) is null); + _recovered = waiting; + // Changes a save may have written wait for a reload or a discard before the next save, as here after one. + if (uncertain) + { + _saveBlocked = true; + _recoveredBlock = true; + } + + _view.ShowRecovered(restored, waiting?.Changes ?? 0, uncertain); + if (restored > 0) + { + OnEditsChanged(this, EventArgs.Empty); + } + } + + // A reload or a discard settles a save whose outcome was unknown, and a recovered notice that said so is told. + private void Unblock() + { + _saveBlocked = false; + if (_recoveredBlock) + { + _recoveredBlock = false; + _view.ShowRecovered(0, WaitingChanges, saveBlocked: false); + } + } + + // A key column's stored values with their kinds, which name a row in the session file and find it again. + private IReadOnlyList ReadStoredValues(int column, int firstRow, int rowCount) => + _tableEditor!.GetStoredValues(_editsRows, column, firstRow, rowCount); + private void SetEdits(TableEdits? edits, ResultSet? rows) { if (Edits is null && edits is null) @@ -1089,6 +1189,8 @@ await _work.RunAsync(async _ => SetSaving(true); try { + // On disk before the first statement: an end while it runs leaves the edits blocked, not saved twice. + _view.WriteSessionNow(); outcome = await save.RunAsync(confirmed, CancellationToken.None).ConfigureAwait(true); } catch (TableProException exception) when (exception.Error.Codes.Any(NothingSent.Contains)) diff --git a/windows/src/TablePro.App.Model/WorkspaceTabs.cs b/windows/src/TablePro.App.Model/WorkspaceTabs.cs index 02ed65a2e0..6f4593b5cb 100644 --- a/windows/src/TablePro.App.Model/WorkspaceTabs.cs +++ b/windows/src/TablePro.App.Model/WorkspaceTabs.cs @@ -21,6 +21,9 @@ public interface IWorkspaceTab SessionTab Snapshot(); + // For the session's own writes alone: what an end without a close would lose, which a relaunch brings back. + SessionTab WithPendingWork(SessionTab snapshot); + // Once only, however often it is asked for: the tab lets go of its session exactly once. Task CloseAsync(); } diff --git a/windows/src/TablePro.App/MainWindow.xaml.cs b/windows/src/TablePro.App/MainWindow.xaml.cs index a68d556da1..b0dd7e6b74 100644 --- a/windows/src/TablePro.App/MainWindow.xaml.cs +++ b/windows/src/TablePro.App/MainWindow.xaml.cs @@ -89,12 +89,11 @@ internal MainWindow(Workbench workbench) Rail.SelectedItem = HomeItem; Closed += (_, _) => _home.WindowClosed(); UpdateRail(); - if (workbench.Settings.ReopenSession) - { - Restore(session); - _restoreWindows = session.TabWindows; - _ = RefreshMarksAsync(); - } + // What the app ended holding without a close comes back even with Reopen at startup off. + var reopened = workbench.Settings.ReopenSession ? session : session.Recovered(); + Restore(reopened); + _restoreWindows = reopened.TabWindows; + _ = RefreshMarksAsync(); } private MainWindow( @@ -284,6 +283,8 @@ public void ShowSettings() void IWorkspaceHost.MoveToNewWindow(TabViewItem tab) => _primary.MoveOut(tab); + void IWorkspaceHost.WriteSessionNow() => _primary.WriteSessionBeforeSave(); + internal void OpenFile(string path) { Open(new SessionConnection { FilePath = path, Name = Path.GetFileName(path) }); @@ -1030,8 +1031,8 @@ private async Task ShutDownAsync() form.Close(); } - // Before any tab closes, since a closed tab is no longer in what the session lists. - _ = _saves?.Save(SessionSnapshot(), last: true); + // Before any tab closes, since a closed tab is no longer in what the session lists; its work was asked about. + _ = _saves?.Save(SessionSnapshot(withWork: false), last: true); _workbench.SaveUnsavedSettings(); SessionSaved?.Invoke(this, EventArgs.Empty); DropSpare(); @@ -1118,7 +1119,7 @@ private async Task SaveSessionInBackgroundAsync() return; } - var saved = await _saves.SaveInBackgroundAsync(SessionSnapshot()); + var saved = await _saves.SaveInBackgroundAsync(SessionSnapshot(withWork: true)); if (saved == SessionSave.Written) { _nextRetry = SaveDelay; @@ -1147,7 +1148,7 @@ internal void SaveSessionBeforeCrash() try { _saveTimer?.Stop(); - _ = _saves.Save(SessionSnapshot(), last: true); + _ = _saves.Save(SessionSnapshot(withWork: true), last: true); } catch (Exception exception) { @@ -1164,7 +1165,7 @@ private void OnSessionEnding() } _saveTimer?.Stop(); - _ = _saves.Save(SessionSnapshot(), last: true); + _ = _saves.Save(SessionSnapshot(withWork: true), last: true); _workbench.SaveUnsavedSettings(); // Restart Manager asks the app to end itself; at a sign-out the process may be gone before this runs. DispatcherQueue.TryEnqueue(async () => @@ -1174,6 +1175,28 @@ private void OnSessionEnding() }); } + // The saving tab's edits go in uncertain, so an end before its answer leaves Save blocked; a failure is logged. + private void WriteSessionBeforeSave() + { + if (_closing || _saves is null) + { + return; + } + + try + { + if (_saves.Save(SessionSnapshot(withWork: true)) == SessionSave.Refused) + { + CrashLog.Write(new IOException("The session file refused the write made before a table save.")); + SessionChanged(); + } + } + catch (Exception exception) + { + CrashLog.Write(exception); + } + } + // A forced Restart Manager close ends the app with no WM_ENDSESSION after a FALSE, so the session is written first. private void OnSessionHeld() { @@ -1182,7 +1205,7 @@ private void OnSessionHeld() return; } - _ = _saves.Save(SessionSnapshot()); + _ = _saves.Save(SessionSnapshot(withWork: true)); _workbench.SaveUnsavedSettings(); } @@ -1206,15 +1229,16 @@ private void OnSessionHeld() }; } - private SessionState SessionSnapshot() + // withWork keeps the pending edits and held transactions a forced end would lose, for the relaunch to bring back. + private SessionState SessionSnapshot(bool withWork) { - var connections = _open.Select(open => Persisted(open.Snapshot())).ToList(); + var connections = _open.Select(open => Persisted(open.Snapshot(withWork))).ToList(); var front = _front is null ? (connections.Count > 0 ? 0 : -1) : _open.IndexOf(_front); var windows = _tabWindows .Where(window => window._front is not null) .Select(window => new TabWindowState { - Connection = Persisted(window._front!.Snapshot()), + Connection = Persisted(window._front!.Snapshot(withWork)), Placement = WindowInterop.Placement(window), }) .Where(window => window.Connection.Tabs.Count > 0) diff --git a/windows/src/TablePro.App/Program.cs b/windows/src/TablePro.App/Program.cs index 5790b5d06b..ff8cf522c0 100644 --- a/windows/src/TablePro.App/Program.cs +++ b/windows/src/TablePro.App/Program.cs @@ -22,6 +22,9 @@ private static void Main() return; } + // Only the process that owns the data folder, so a launch that handed over is never started again. + AppRestart.Register(); + AppInstance? current = null; Application.Start(_ => { diff --git a/windows/src/TablePro.App/Services/AppRestart.cs b/windows/src/TablePro.App/Services/AppRestart.cs new file mode 100644 index 0000000000..e98febc930 --- /dev/null +++ b/windows/src/TablePro.App/Services/AppRestart.cs @@ -0,0 +1,23 @@ +using System.Runtime.InteropServices; + +namespace TablePro.App.Services; + +// Restart Manager starts the app again after closing it for an update or a restart; the session file holds the work. +internal static partial class AppRestart +{ + private const uint NoCrash = 0x1; + private const uint NoHang = 0x2; + + // Not after a crash or a hang, which the same session could bring on again; no arguments, so it starts as a launch. + public static void Register() + { + var result = RegisterApplicationRestart(null, NoCrash | NoHang); + if (result != 0) + { + CrashLog.Write(Marshal.GetExceptionForHR(result)); + } + } + + [LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial int RegisterApplicationRestart(string? commandLine, uint flags); +} diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index 0c723caba4..bef28b743a 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -1314,6 +1314,33 @@ The connection was lost, and its open transaction with it. The next run opens a new connection. + + Transaction rolled back + + + A transaction was open on this tab when TablePro last closed. The server rolled it back. + + + Unsaved changes restored + + + TablePro closed before these changes were saved. They are pending again. + + + TablePro closed before it knew whether these changes were saved. They are pending again. + + + Unsaved changes waiting + + + TablePro closed before 1 change was saved. It comes back as pending when a page shows its row and the table can take it. + + + TablePro closed before {0:N0} changes were saved. They come back as pending when a page shows their rows and the table can take them. + + + Discard + Reconnect diff --git a/windows/src/TablePro.App/Views/DefinitionTabView.xaml.cs b/windows/src/TablePro.App/Views/DefinitionTabView.xaml.cs index 549d68fd05..76ed75318f 100644 --- a/windows/src/TablePro.App/Views/DefinitionTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/DefinitionTabView.xaml.cs @@ -71,6 +71,8 @@ public void FocusContent() public SessionTab Snapshot() => _model.Snapshot(); + public SessionTab WithPendingWork(SessionTab snapshot) => _model.WithPendingWork(snapshot); + public Task ConfirmCloseAsync(bool offerSave) => _model.ConfirmCloseAsync(offerSave); public Task CloseAsync() => _model.CloseAsync(); diff --git a/windows/src/TablePro.App/Views/IWorkspaceHost.cs b/windows/src/TablePro.App/Views/IWorkspaceHost.cs index 47eafd6f0e..58c0e09f87 100644 --- a/windows/src/TablePro.App/Views/IWorkspaceHost.cs +++ b/windows/src/TablePro.App/Views/IWorkspaceHost.cs @@ -19,4 +19,7 @@ internal interface IWorkspaceHost void TearOut(TabViewItem tab, WindowId window); void MoveToNewWindow(TabViewItem tab); + + // At once and on this thread, before a table tab's save sends anything; a refused write is logged. + void WriteSessionNow(); } diff --git a/windows/src/TablePro.App/Views/OpenConnection.cs b/windows/src/TablePro.App/Views/OpenConnection.cs index 078eac772b..a7e83b175b 100644 --- a/windows/src/TablePro.App/Views/OpenConnection.cs +++ b/windows/src/TablePro.App/Views/OpenConnection.cs @@ -104,7 +104,7 @@ public OpenConnection Adopt() public Task DisconnectAsync(bool keepTabs = false) => _life.DisconnectAsync(keepTabs); - public SessionConnection Snapshot() => _life.Snapshot(); + public SessionConnection Snapshot(bool withWork = false) => _life.Snapshot(withWork); void IConnectionView.ShowState(ConnectionState state) { @@ -169,7 +169,8 @@ async Task IConnectionView.RecoverHostKeyAsync( Task IConnectionView.CloseTabsAsync(bool keepClosed) => View.CloseTabsAsync(keepClosed); - SessionConnection IConnectionView.Snapshot(SessionConnection origin) => View.Snapshot(origin); + SessionConnection IConnectionView.Snapshot(SessionConnection origin, bool withWork) => + View.Snapshot(origin, withWork); private static Style Badge(string key) => (Style)Application.Current.Resources[key]; diff --git a/windows/src/TablePro.App/Views/QueryTabView.xaml b/windows/src/TablePro.App/Views/QueryTabView.xaml index 89cc98a940..4ff8db22e7 100644 --- a/windows/src/TablePro.App/Views/QueryTabView.xaml +++ b/windows/src/TablePro.App/Views/QueryTabView.xaml @@ -37,26 +37,37 @@ - - - - -