From cdfc0af7a8fed8b85b0998135069284190b1a232 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 01:17:55 +0700 Subject: [PATCH 1/2] refactor(execution): run every query through one tab lifecycle and stop keystrokes waking the window --- .../Core/Coordinators/FilterCoordinator.swift | 199 +++---- .../Core/Coordinators/FindCoordinator.swift | 2 +- .../Coordinators/PaginationCoordinator.swift | 29 +- .../QueryExecutionCoordinator+Batches.swift | 202 +++---- ...QueryExecutionCoordinator+ExplainRun.swift | 159 ++++++ .../QueryExecutionCoordinator+Helpers.swift | 144 ++--- ...yExecutionCoordinator+MultiStatement.swift | 73 ++- ...QueryExecutionCoordinator+Parameters.swift | 533 +++--------------- .../QueryExecutionCoordinator+SingleRun.swift | 260 +++++++++ .../QueryExecutionCoordinator.swift | 177 ++---- .../RowEditingCoordinator+Discard.swift | 18 +- .../RowEditingCoordinator+SaveChanges.swift | 10 +- apple/TablePro/Core/Execution/TabRun.swift | 113 ++++ .../Infrastructure/MainWindowToolbar.swift | 4 +- .../Models/Query/QueryTabManager.swift | 49 +- .../Main/Child/MainEditorContentView.swift | 36 +- .../Main/ConnectionCatalogSnapshot.swift | 50 ++ ...MainContentCommandActions+FileSaving.swift | 4 +- .../MainContentCoordinator+AutoRefresh.swift | 2 +- .../MainContentCoordinator+ChangeGuard.swift | 64 ++- ...nContentCoordinator+ColumnFetchScope.swift | 14 +- ...nContentCoordinator+ColumnVisibility.swift | 27 +- ...inContentCoordinator+ContainerChange.swift | 7 +- .../MainContentCoordinator+ExecuteAll.swift | 49 +- .../MainContentCoordinator+Explain.swift | 209 +------ .../MainContentCoordinator+FKNavigation.swift | 9 +- .../MainContentCoordinator+FilterState.swift | 2 +- .../MainContentCoordinator+Filtering.swift | 4 + .../MainContentCoordinator+Masking.swift | 14 +- .../MainContentCoordinator+Navigation.swift | 41 +- ...ContentCoordinator+NavigationHistory.swift | 23 +- .../MainContentCoordinator+QueryHelpers.swift | 14 +- .../MainContentCoordinator+QueryRouting.swift | 3 +- .../MainContentCoordinator+Refresh.swift | 37 +- .../MainContentCoordinator+ResultReload.swift | 43 +- .../MainContentCoordinator+Rewind.swift | 17 +- ...ainContentCoordinator+SidebarActions.swift | 4 +- .../MainContentCoordinator+SidebarSave.swift | 4 +- .../MainContentCoordinator+TabRestore.swift | 3 +- ...ainContentCoordinator+TableFirstLoad.swift | 2 +- ...ContentCoordinator+TableRowsMutation.swift | 4 +- ...nContentCoordinator+TableRowsRefresh.swift | 4 +- .../MainContentCommandActions+BulkClose.swift | 22 +- .../MainContentCommandActions+Closing.swift | 53 +- .../MainContentCommandActions+Diagram.swift | 6 +- .../MainContentCommandActions+Structure.swift | 13 +- .../MainContentCommandActions+UserTypes.swift | 14 +- .../Main/MainContentCommandActions.swift | 86 +-- .../Views/Main/MainContentCoordinator.swift | 394 ++++--------- .../TablePro/Views/Main/MainContentView.swift | 6 +- .../CopyFromStandardInputRunTests.swift | 2 +- .../Coordinators/RunResultLimitTests.swift | 2 +- .../Coordinators/RunResultPlanTests.swift | 2 +- .../StoppedRunKeepsWorkTests.swift | 42 +- .../Services/Telemetry/TelemetryTests.swift | 2 +- .../Helpers/CoordinatorFixture.swift | 47 ++ .../Views/Main/AuthorizedRunTargetTests.swift | 6 +- .../Main/ExplainAuthorizationTests.swift | 6 +- ...inContentCoordinatorAutoRefreshTests.swift | 2 +- .../MainContentCoordinatorSortTests.swift | 34 +- .../Main/MainViewInvalidationTests.swift | 99 ++++ .../Main/QueryParameterDetectionTests.swift | 4 +- .../Main/QueryTabVersionTriggerTests.swift | 6 +- .../ReadOnlySafeModeEntryPointTests.swift | 18 +- .../Main/ResultRowsBuildOffMainTests.swift | 2 +- .../Views/Main/RunDiscardGuardTests.swift | 8 +- .../Views/Main/ScriptErrorResultTests.swift | 2 +- .../Views/Main/TabQueryIsolationTests.swift | 14 +- .../Views/Main/TabRunLifecycleTests.swift | 159 ++++++ .../TableLoadAfterSafeModePromptTests.swift | 4 +- .../Main/TableLoadConfirmationTests.swift | 4 +- .../TableLoadForeignKeyPrefetchTests.swift | 2 +- 72 files changed, 1830 insertions(+), 1893 deletions(-) create mode 100644 apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+ExplainRun.swift create mode 100644 apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+SingleRun.swift create mode 100644 apple/TablePro/Core/Execution/TabRun.swift create mode 100644 apple/TablePro/Views/Main/ConnectionCatalogSnapshot.swift create mode 100644 apple/TableProTests/Views/Main/MainViewInvalidationTests.swift create mode 100644 apple/TableProTests/Views/Main/TabRunLifecycleTests.swift diff --git a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift index 81e0ff81c9..e68042bb85 100644 --- a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift @@ -17,48 +17,30 @@ final class FilterCoordinator: ObservableObject { // MARK: - Filtering - func applyFilters(_ filters: [TableFilter], logicMode: FilterLogicMode? = nil) { - guard let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex, - let tableName = tab.tableContext.tableName else { return } - - let capturedTabIndex = tabIndex - let capturedTableName = tableName - let capturedFilters = filters - let capturedLogicMode = logicMode - parent.confirmDiscardChangesIfNeeded(action: .filter) { [weak self] confirmed in + func applyFilters(_ filters: [TableFilter], logicMode: FilterLogicMode? = nil, forTab tabId: UUID) { + guard let tableName = existingTab(tabId)?.tableContext.tableName else { return } + parent.confirmDiscardChangesIfNeeded(forTab: tabId, action: .filter) { [weak self] confirmed in guard let self, confirmed else { return } - commitFilters( - capturedFilters, - logicMode: capturedLogicMode, - tabIndex: capturedTabIndex, - tableName: capturedTableName - ) + commitFilters(filters, logicMode: logicMode, tabId: tabId, tableName: tableName) } } - /// Writes the one predicate a reference jump carries and re-queries for it. - /// - /// The caller has already taken the discard guard, because it also records the view the tab is - /// leaving and both have to land on the same side of a refusal. - func commitReferenceFilter(_ filter: TableFilter) { - guard let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex, - let tableName = tab.tableContext.tableName else { return } - setFKFilter(filter) - commitFilters([filter], logicMode: nil, tabIndex: tabIndex, tableName: tableName) + // The caller holds the discard guard: it also records the view the tab leaves, and both land on one side of a refusal. + func commitReferenceFilter(_ filter: TableFilter, forTab tabId: UUID) { + guard let tableName = existingTab(tabId)?.tableContext.tableName else { return } + mutateFilterState(ofTab: tabId) { $0.setReferenceFilter(filter) } + commitFilters([filter], logicMode: nil, tabId: tabId, tableName: tableName) } - /// Builds the query first and writes the filter state only once it exists, so a refusal leaves - /// the panel, the commit and the rows on screen as they were, with the reason in their place. + // Builds the query before writing the filter state, so a refusal leaves the panel, commit and rows as they were. private func commitFilters( _ filters: [TableFilter], logicMode: FilterLogicMode?, - tabIndex: Int, + tabId: UUID, tableName: String, adopting proposed: TabFilterState? = nil ) { - guard tabIndex < parent.tabManager.tabs.count else { return } - - let tab = parent.tabManager.tabs[tabIndex] + guard let tab = existingTab(tabId) else { return } var next = proposed ?? tab.filterState if let logicMode { next.filterLogicMode = logicMode @@ -84,7 +66,7 @@ final class FilterCoordinator: ObservableObject { ) else { let message = FilterSQLGenerator.refusalMessage(for: filters, databaseType: parent.connection.type) ?? String(localized: "This database cannot filter rows with these conditions.") - parent.tabManager.mutate(at: tabIndex) { + parent.tabManager.mutate(tabId: tabId) { $0.execution.errorMessage = message } return @@ -92,13 +74,15 @@ final class FilterCoordinator: ObservableObject { next.executedFilters = filters next.executedLogicMode = next.filterLogicMode - parent.tabManager.mutate(at: tabIndex) { + parent.tabManager.mutate(tabId: tabId) { $0.pagination.reset() $0.content.query = newQuery $0.filterState = next } - saveLastFilters(of: parent.tabManager.tabs[tabIndex]) - parent.runQuery(viewport: .firstRow) + if let committed = existingTab(tabId) { + saveLastFilters(of: committed) + } + parent.runQuery(onTab: tabId, viewport: .firstRow) } /// Stops filtering and keeps the rows in the panel, so Apply brings them back. @@ -114,21 +98,18 @@ final class FilterCoordinator: ObservableObject { } private func unsetFilters(removingRows: Bool) { - guard let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex, - let tableName = tab.tableContext.tableName else { return } - - let capturedTabIndex = tabIndex - let capturedTableName = tableName - parent.confirmDiscardChangesIfNeeded(action: .filter) { [weak self] confirmed in - guard let self, confirmed else { return } - guard capturedTabIndex < parent.tabManager.tabs.count else { return } + guard let (selected, _) = parent.tabManager.selectedTabAndIndex, + let tableName = selected.tableContext.tableName else { return } - parent.tabManager.mutate(at: capturedTabIndex) { $0.pagination.reset() } + let tabId = selected.id + parent.confirmDiscardChangesIfNeeded(forTab: tabId, action: .filter) { [weak self] confirmed in + guard let self, confirmed, + parent.tabManager.mutate(tabId: tabId, { $0.pagination.reset() }), + let tab = existingTab(tabId) else { return } - let tab = parent.tabManager.tabs[capturedTabIndex] - let buffer = parent.tabSessionRegistry.tableRows(for: tab.id) + let buffer = parent.tabSessionRegistry.tableRows(for: tabId) let newQuery = parent.queryBuilder.buildBaseQuery( - tableName: capturedTableName, + tableName: tableName, schemaName: tab.tableContext.schemaName, sortState: querySortState(for: tab), columns: buffer.columns, @@ -138,7 +119,7 @@ final class FilterCoordinator: ObservableObject { offset: tab.pagination.currentOffset ) - parent.tabManager.mutate(at: capturedTabIndex) { + parent.tabManager.mutate(tabId: tabId) { $0.content.query = newQuery $0.filterState.commit = nil $0.filterState.executedFilters = [] @@ -147,11 +128,11 @@ final class FilterCoordinator: ObservableObject { $0.filterState.filters = [] } } - /// Saved rather than deleted, because the rows left in the panel are still the table's - /// working set and reopening it should bring them back with nothing running. Removing - /// the rows empties that set, and an empty set is what the storage reads as a delete. - saveLastFilters(of: parent.tabManager.tabs[capturedTabIndex]) - parent.runQuery(viewport: .firstRow) + // Saved, not deleted: the rows left in the panel are the table's working set, and an empty set reads as a delete. + if let unset = existingTab(tabId) { + saveLastFilters(of: unset) + } + parent.runQuery(onTab: tabId, viewport: .firstRow) } } @@ -195,58 +176,52 @@ final class FilterCoordinator: ObservableObject { } func applyBrowseSearch(_ search: BrowseSearchState) { - guard let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex, - let tableName = tab.tableContext.tableName else { return } + guard let (selected, _) = parent.tabManager.selectedTabAndIndex, + let tableName = selected.tableContext.tableName else { return } - let capturedTabIndex = tabIndex - let capturedTableName = tableName - parent.confirmDiscardChangesIfNeeded(action: .filter) { [weak self] confirmed in - guard let self, confirmed else { return } - guard capturedTabIndex < parent.tabManager.tabs.count else { return } + let tabId = selected.id + parent.confirmDiscardChangesIfNeeded(forTab: tabId, action: .filter) { [weak self] confirmed in + guard let self, confirmed, existingTab(tabId) != nil else { return } - mutateSelectedTabFilterState { state in + mutateFilterState(ofTab: tabId) { state in state.browseSearch = search state.isVisible = true } - /// The total on screen counted the previous search's keys, or the whole database. An - /// exact one is never replaced by a later estimate, so left in place it would go on - /// describing this search. - parent.tabManager.mutate(at: capturedTabIndex) { tab in + // An exact total is never replaced by a later estimate, so the previous search's would describe this one. + parent.tabManager.mutate(tabId: tabId) { tab in tab.pagination.reset() tab.pagination.retireDerivedRowCount() } - rebuildTableQuery(at: capturedTabIndex) - saveBrowseSearch(for: capturedTableName) - parent.runQuery(viewport: .firstRow) + rebuildTableQuery(forTab: tabId) + saveBrowseSearch(for: tableName, ofTab: tabId) + parent.runQuery(onTab: tabId, viewport: .firstRow) } } func clearBrowseSearchAndReload() { - guard let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex, - let tableName = tab.tableContext.tableName else { return } + guard let (selected, _) = parent.tabManager.selectedTabAndIndex, + let tableName = selected.tableContext.tableName else { return } - let capturedTabIndex = tabIndex - let capturedTableName = tableName - parent.confirmDiscardChangesIfNeeded(action: .filter) { [weak self] confirmed in - guard let self, confirmed else { return } - guard capturedTabIndex < parent.tabManager.tabs.count else { return } + let tabId = selected.id + parent.confirmDiscardChangesIfNeeded(forTab: tabId, action: .filter) { [weak self] confirmed in + guard let self, confirmed, existingTab(tabId) != nil else { return } - mutateSelectedTabFilterState { state in + mutateFilterState(ofTab: tabId) { state in state.browseSearch = BrowseSearchState() } - /// A total counted for the search does not describe the whole database. - parent.tabManager.mutate(at: capturedTabIndex) { tab in + // A total counted for the search does not describe the whole database. + parent.tabManager.mutate(tabId: tabId) { tab in tab.pagination.reset() tab.pagination.retireDerivedRowCount() } - rebuildTableQuery(at: capturedTabIndex) - saveBrowseSearch(for: capturedTableName) - parent.runQuery(viewport: .firstRow) + rebuildTableQuery(forTab: tabId) + saveBrowseSearch(for: tableName, ofTab: tabId) + parent.runQuery(onTab: tabId, viewport: .firstRow) } } - func saveBrowseSearch(for tableName: String) { - guard let tab = parent.tabManager.selectedTab else { return } + func saveBrowseSearch(for tableName: String, ofTab tabId: UUID) { + guard let tab = existingTab(tabId) else { return } FilterSettingsStorage.shared.saveBrowseSearch( tab.filterState.browseSearch, for: tableName, @@ -301,6 +276,11 @@ final class FilterCoordinator: ObservableObject { } } + func rebuildTableQuery(forTab tabId: UUID) { + guard let index = parent.tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } + rebuildTableQuery(at: index) + } + // The table tab's view, its filters, search and sort, read from the first row: what Share Result reads. func viewQuery(for tab: QueryTab, limit: Int) -> String? { guard let tableName = tab.tableContext.tableName else { return nil } @@ -434,9 +414,9 @@ final class FilterCoordinator: ObservableObject { /// One CONTAINS row per searchable column, joined with OR, replacing the filter set. Only the /// find bar calls this, and only when no filters are applied, because `filterLogicMode` is one /// mode for the whole array: switching it to OR would silently loosen filters the user wrote. - func applyCrossColumnSearch(term: String, columns: [String]) { + func applyCrossColumnSearch(term: String, columns: [String], forTab tabId: UUID) { guard !columns.isEmpty, parent.supportsMatchAnyFilters || columns.count == 1 else { return } - applyFilters(TabFilterState.crossColumnSearchFilters(term: term, columns: columns), logicMode: .or) + applyFilters(TabFilterState.crossColumnSearchFilters(term: term, columns: columns), logicMode: .or, forTab: tabId) } func addFilterForColumn(_ columnName: String) { @@ -446,12 +426,6 @@ final class FilterCoordinator: ObservableObject { } } - func setFKFilter(_ filter: TableFilter) { - mutateSelectedTabFilterState { state in - state.setReferenceFilter(filter) - } - } - // MARK: - Apply func applySingleFilter(_ filter: TableFilter) { @@ -480,40 +454,32 @@ final class FilterCoordinator: ObservableObject { return !usesBrowseSearch } - /// Narrows what the grid shows by one more condition, which a cell's Filter menu offers. - func applyCellFilter(_ filter: TableFilter) { + // A cell's Filter menu: narrows the grid by one more condition. + func applyCellFilter(_ filter: TableFilter, forTab tabId: UUID) { guard canFilterRows, filter.isValid, - !TabFilterState.isRunning(filter, in: selectedTabFilterState) else { return } - applyTransition { state in + let tab = existingTab(tabId), + !TabFilterState.isRunning(filter, in: tab.filterState) else { return } + applyTransition(forTab: tabId) { state in state = TabFilterState.cellFilterState(state, adding: filter) } } - /// Writes the commit, persists it and re-queries, all behind the discard guard. - /// - /// Behind it, because `commit` is the record of what the rows on screen were fetched with. - /// Setting it first and taking the guard afterwards left a declined apply reporting a filter - /// the grid had never run, saved to disk, and re-run by the next page turn. + // Behind the discard guard: `commit` records what the rows on screen were fetched with, so a declined apply must not write it. private func applyCommit(_ commit: FilterCommit) { - applyTransition { $0.commit = commit } + guard let tabId = parent.tabManager.selectedTabAndIndex?.tab.id else { return } + applyTransition(forTab: tabId) { $0.commit = commit } } - private func applyTransition(_ transition: @escaping (inout TabFilterState) -> Void) { - guard let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex, - let tableName = tab.tableContext.tableName else { return } - - let capturedTabIndex = tabIndex - let capturedTableName = tableName - parent.confirmDiscardChangesIfNeeded(action: .filter) { [weak self] confirmed in - guard let self, confirmed else { return } - guard capturedTabIndex < parent.tabManager.tabs.count else { return } - var next = parent.tabManager.tabs[capturedTabIndex].filterState + private func applyTransition(forTab tabId: UUID, _ transition: @escaping (inout TabFilterState) -> Void) { + guard let tableName = existingTab(tabId)?.tableContext.tableName else { return } + parent.confirmDiscardChangesIfNeeded(forTab: tabId, action: .filter) { [weak self] confirmed in + guard let self, confirmed, var next = existingTab(tabId)?.filterState else { return } transition(&next) commitFilters( next.appliedFilters, logicMode: nil, - tabIndex: capturedTabIndex, - tableName: capturedTableName, + tabId: tabId, + tableName: tableName, adopting: next ) } @@ -655,11 +621,20 @@ final class FilterCoordinator: ObservableObject { // MARK: - Private + private func existingTab(_ tabId: UUID) -> QueryTab? { + parent.tabManager.tabs.first { $0.id == tabId } + } + private func mutateSelectedTabFilterState(_ mutate: (inout TabFilterState) -> Void) { guard let index = parent.tabManager.selectedTabIndex else { return } mutateFilterState(at: index, mutate) } + private func mutateFilterState(ofTab tabId: UUID, _ mutate: (inout TabFilterState) -> Void) { + guard let index = parent.tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } + mutateFilterState(at: index, mutate) + } + private func mutateFilterState(at index: Int, _ mutate: (inout TabFilterState) -> Void) { guard index < parent.tabManager.tabs.count else { return } var newState = parent.tabManager.tabs[index].filterState diff --git a/apple/TablePro/Core/Coordinators/FindCoordinator.swift b/apple/TablePro/Core/Coordinators/FindCoordinator.swift index 0d6b7f247a..8cb4e3aeaf 100644 --- a/apple/TablePro/Core/Coordinators/FindCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/FindCoordinator.swift @@ -56,7 +56,7 @@ final class FindCoordinator { guard parent.tabManager.selectedTabId == tabID else { return } let columns = serverSearchableColumns(in: parent.tabSessionRegistry.tableRows(for: tabID)) guard !columns.isEmpty else { return } - parent.filterCoordinator.applyCrossColumnSearch(term: term, columns: columns) + parent.filterCoordinator.applyCrossColumnSearch(term: term, columns: columns, forTab: tabID) } func serverSearchableColumns(in rows: TableRows) -> [String] { diff --git a/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift b/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift index 7836d93b37..69b016d835 100644 --- a/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift @@ -23,10 +23,10 @@ final class PaginationCoordinator: ObservableObject { // MARK: - Pagination func goToNextPage() { - guard canSeek, let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex else { return } + guard canSeek, let (tab, _) = parent.tabManager.selectedTabAndIndex else { return } let loadedRowCount = parent.tabSessionRegistry.tableRows(for: tab.id).rows.count guard tab.pagination.canGoToNextPage(loadedRowCount: loadedRowCount) else { return } - paginateAfterConfirmation(tabIndex: tabIndex) { $0.goToNextPage(loadedRowCount: loadedRowCount) } + paginateAfterConfirmation(tabId: tab.id) { $0.goToNextPage(loadedRowCount: loadedRowCount) } } func goToPreviousPage() { @@ -80,9 +80,8 @@ final class PaginationCoordinator: ObservableObject { ), confirmTitle: String(localized: "Show All") ) { [weak self] in - guard let self, - let tabIndex = parent.tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } - paginateAfterConfirmation(tabIndex: tabIndex) { pagination in + guard let self, parent.tabManager.tabs.contains(where: { $0.id == tabId }) else { return } + paginateAfterConfirmation(tabId: tabId) { pagination in pagination.updatePageSize(max(total, 1)) pagination.goToFirstPage() } @@ -116,32 +115,28 @@ final class PaginationCoordinator: ObservableObject { where condition: (PaginationState) -> Bool = { _ in true }, mutate: @escaping (inout PaginationState) -> Void ) { - guard let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex, + guard let (tab, _) = parent.tabManager.selectedTabAndIndex, condition(tab.pagination) else { return } - paginateAfterConfirmation(tabIndex: tabIndex, mutate: mutate) + paginateAfterConfirmation(tabId: tab.id, mutate: mutate) } private func paginateAfterConfirmation( - tabIndex: Int, + tabId: UUID, mutate: @escaping (inout PaginationState) -> Void ) { - let tabId = parent.tabManager.tabs[tabIndex].id - parent.confirmDiscardChangesIfNeeded(action: .pagination) { [weak self] confirmed in + parent.confirmDiscardChangesIfNeeded(forTab: tabId, action: .pagination) { [weak self] confirmed in guard let self, confirmed else { return } guard parent.tabManager.mutate(tabId: tabId, { tab in mutate(&tab.pagination) tab.paginationVersion += 1 }) else { return } - reloadCurrentPage() + reloadPage(ofTab: tabId) } } - private func reloadCurrentPage() { - guard let tabIndex = parent.tabManager.selectedTabIndex, - tabIndex < parent.tabManager.tabs.count else { return } - - parent.rebuildTableQuery(at: tabIndex) - parent.runQuery(viewport: .firstRow) + private func reloadPage(ofTab tabId: UUID) { + parent.rebuildTableQuery(forTab: tabId) + parent.runQuery(onTab: tabId, viewport: .firstRow) } // MARK: - Cancel Current Query diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift index 06ca9d36e6..93f75b9988 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift @@ -101,90 +101,54 @@ extension QueryExecutionCoordinator { ) } - /// Runs each batch whole, in order, on one lease, and stops at the first that fails. - /// - /// The app opens no transaction around the run, as SQL Server's own tools do not: a batch carries on past most - /// errors, so an app-owned rollback would take back statements that ran after the failure, and the script's own - /// `BEGIN TRAN`, `TRY...CATCH` and procedures are what decide. A transaction the script leaves open is reported. - /// Manual Commit is the exception: the run is held, and a failure or a Stop rolls it back. + // No app transaction around the run: a batch carries on past most errors, so a rollback would undo later work. Manual Commit holds it. func executeBatches( _ batches: [ExecutableBatch], parameters: [QueryParameter], - bypassRowLimit: Bool = false, - onTab target: UUID? = nil + onTab tabId: UUID, + bypassRowLimit: Bool = false ) { - guard let (selectedTab, index) = parent.executionTab(target), - !parent.tabExecution.isExecuting(selectedTab.id) else { return } - - if let firstMissing = parameters.first(where: { - !$0.isNull && $0.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - }) { - parent.tabManager.mutate(at: index) { - $0.execution.errorMessage = String( - format: String(localized: "Missing value for parameter: %@"), - ":\(firstMissing.name)" - ) - } - return - } - - guard let scope = parent.scope(for: selectedTab) else { - parent.tabManager.mutate(at: index) { - $0.execution.errorMessage = String(localized: "Not connected to database") - } - return - } - - parent.tabManager.mutate(at: index) { tab in - tab.execution.executionTime = nil - tab.execution.errorMessage = nil - } + guard let run = TabRun.begin(onTab: tabId, parameters: parameters, in: parent), + let tab = parent.tabManager.tabs.first(where: { $0.id == tabId }) else { return } - let conn = parent.connection - let tabId = selectedTab.id - let (claim, lease) = parent.beginTabExecution(for: tabId) + let conn = run.connection let prepared = prepareBatches( batches, parameters: parameters, - query: selectedTab.content.query, + query: tab.content.query, bypassRowLimit: bypassRowLimit ) let statementTexts = batches.flatMap { $0.statements.map(\.sql) } let mode = OperationKind.worst(of: statementTexts, databaseType: conn.type).transactionAccessMode - let batchTask = Task { [weak self, parent] in + run.launch { [weak self] run in guard let self else { return } - let run = await runBatches(prepared, scope: scope, mode: mode, claim: claim, lease: lease) - postRanStatements(of: prepared, run: run, scope: scope, connection: conn) - let plan = await batchResultPlan(prepared, outputs: Self.outputs(of: run.outcome), tabId: tabId) + let ran = await runBatches(prepared, scope: run.scope, mode: mode, claim: run.claim, lease: run.lease) + postRanStatements(of: prepared, run: ran, scope: run.scope, connection: conn) + let plan = await batchResultPlan(prepared, outputs: Self.outputs(of: ran.outcome), tabId: tabId) - let sessionNotice = Self.runNotice(outcome: run.outcome, sessionState: run.sessionState) - guard parent.tabExecution.settle(claim) || reportsUnknownCommitAfterStop(run.outcome, claim: claim) else { + let sessionNotice = Self.runNotice(outcome: ran.outcome, sessionState: ran.sessionState) + guard run.settle() || reportsUnknownCommitAfterStop(ran.outcome, claim: run.claim) else { await keepBatchesAfterStop( - prepared, run: run, plan: plan, parameters: parameters, claim: claim, sessionNotice: sessionNotice + prepared, ran: ran, plan: plan, run: run, sessionNotice: sessionNotice ) return } - parent.retireQueryTask(.claim(claim)) - switch run.outcome { + switch ran.outcome { case .cancelled(let outputs): keepStoppedBatches( prepared, outputs: outputs, - parameters: parameters, - tabId: tabId, + run: run, sessionNotice: sessionNotice, plan: plan, presentsResults: true ) - parent.reportEndedExecutions([ - EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) - ]) + run.reportCancelled() case .completed(let outputs): applyCompletedBatches( - prepared, outputs: outputs, parameters: parameters, - tabId: tabId, claim: claim, sessionNotice: sessionNotice, plan: plan + prepared, outputs: outputs, run: run, sessionNotice: sessionNotice, plan: plan ) case .failed(let outputs, let failure, let errorDescription): handleBatchFailure( @@ -193,21 +157,18 @@ extension QueryExecutionCoordinator { errorDescription: errorDescription, executedCount: outputs.count, totalCount: prepared.count, - plan: run.plan, - sessionState: run.sessionState, + plan: ran.plan, + sessionState: ran.sessionState, unit: .batch ), prepared: prepared, outputs: outputs, - parameters: parameters, - tabId: tabId, - claim: claim, - failureOutput: run.failureOutput, + run: run, + failureOutput: ran.failureOutput, plan: plan ) } } - parent.installQueryTask(batchTask, owner: .claim(claim), lease: lease) } // MARK: - Preparation @@ -414,24 +375,21 @@ extension QueryExecutionCoordinator { private func applyCompletedBatches( _ prepared: [PreparedBatch], outputs: [BatchOutput], - parameters: [QueryParameter], - tabId: UUID, - claim: TabExecutionClaim, + run: TabRun, sessionNotice: String?, plan: BatchResultPlan ) { let totalRowsAffected = outputs.reduce(0) { $0 + $1.rowsAffected } - reportOperation( - kind: .queryBatch, - claim: claim, - outcome: .succeeded(OperationSummary(rowsAffected: totalRowsAffected, statementCount: outputs.count)) + run.report( + .queryBatch, + .succeeded(OperationSummary(rowsAffected: totalRowsAffected, statementCount: outputs.count)) ) - recordBatchHistory(prepared, outputs: outputs, parameters: parameters, tabId: tabId, failedIndex: nil) + recordBatchHistory(prepared, outputs: outputs, run: run, failedIndex: nil) presentMultiStatementResults( - tabId: tabId, + tabId: run.tabId, timing: PluginQueryTiming(total: outputs.reduce(0) { $0 + $1.executionTime }), totalRowsAffected: totalRowsAffected, - newResultSets: batchResultSets(prepared, outputs: outputs, tabId: tabId, plan: plan), + newResultSets: batchResultSets(prepared, outputs: outputs, tabId: run.tabId, plan: plan), sessionNotice: sessionNotice ) } @@ -439,51 +397,46 @@ extension QueryExecutionCoordinator { // A Stop during a batch reads as one between batches: the completed ones are kept, with no error result. private func keepBatchesAfterStop( _ prepared: [PreparedBatch], - run: BatchRun, + ran: BatchRun, plan: BatchResultPlan, - parameters: [QueryParameter], - claim: TabExecutionClaim, + run: TabRun, sessionNotice: String? ) async { - let kept = run.outcome.keptAfterStop(plan: run.plan) + let kept = ran.outcome.keptAfterStop(plan: ran.plan) guard !kept.isEmpty else { return } // A failed batch's own results were in the plan, so a run that drops it is planned again. - let keptPlan = kept.count == Self.outputs(of: run.outcome).count + let keptPlan = kept.count == Self.outputs(of: ran.outcome).count ? plan - : await batchResultPlan(prepared, outputs: kept, tabId: claim.tabId) - let presentsResults = stoppedRunCanReplaceResults(onTab: claim.tabId) - guard parent.tabExecution.settleStopped(claim, replacingContent: presentsResults) else { return } + : await batchResultPlan(prepared, outputs: kept, tabId: run.tabId) + let presentsResults = stoppedRunCanReplaceResults(onTab: run.tabId) + guard parent.tabExecution.settleStopped(run.claim, replacingContent: presentsResults) else { return } keepStoppedBatches( prepared, outputs: kept, - parameters: parameters, - tabId: claim.tabId, + run: run, sessionNotice: sessionNotice, plan: keptPlan, presentsResults: presentsResults ) - parent.reportEndedExecutions([ - EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) - ]) + run.reportCancelled() } private func keepStoppedBatches( _ prepared: [PreparedBatch], outputs: [BatchOutput], - parameters: [QueryParameter], - tabId: UUID, + run: TabRun, sessionNotice: String?, plan: BatchResultPlan, presentsResults: Bool ) { guard !outputs.isEmpty else { return } - recordBatchHistory(prepared, outputs: outputs, parameters: parameters, tabId: tabId, failedIndex: nil) + recordBatchHistory(prepared, outputs: outputs, run: run, failedIndex: nil) guard presentsResults else { return } presentMultiStatementResults( - tabId: tabId, + tabId: run.tabId, timing: PluginQueryTiming(total: outputs.reduce(0) { $0 + $1.executionTime }), totalRowsAffected: outputs.reduce(0) { $0 + $1.rowsAffected }, - newResultSets: batchResultSets(prepared, outputs: outputs, tabId: tabId, plan: plan), + newResultSets: batchResultSets(prepared, outputs: outputs, tabId: run.tabId, plan: plan), sessionNotice: sessionNotice ) } @@ -492,9 +445,7 @@ extension QueryExecutionCoordinator { _ context: MultiStatementFailureContext, prepared: [PreparedBatch], outputs: [BatchOutput], - parameters: [QueryParameter], - tabId: UUID, - claim: TabExecutionClaim, + run: TabRun, failureOutput: PluginServerOutput, plan: BatchResultPlan ) { @@ -505,77 +456,50 @@ extension QueryExecutionCoordinator { } else { printed = failureOutput } - let message = ServerOutputCapture.failureMessage(report.message, output: printed) let failedBatch = report.failedStatementIndex.flatMap { prepared.indices.contains($0) ? prepared[$0] : nil } let errorResult = ResultSet(label: report.resultLabel) - errorResult.errorMessage = message + errorResult.errorMessage = ServerOutputCapture.failureMessage(report.message, output: printed) errorResult.failedQuery = report.failedSQL errorResult.statementAnchor = failedBatch?.batch.anchor - reportOperation(kind: .queryBatch, claim: claim, outcome: .failed(reason: context.errorDescription)) + run.report(.queryBatch, .failed(reason: context.errorDescription)) recordBatchHistory( prepared, outputs: outputs, - parameters: parameters, - tabId: tabId, + run: run, failedIndex: report.failedStatementIndex, failureDescription: context.errorDescription ) - - let timing = PluginQueryTiming(total: outputs.reduce(0) { $0 + $1.executionTime }) - parent.flushBufferToActiveResult(tabId: tabId, pinnedOnly: true) - parent.tabManager.mutate(tabId: tabId) { tab in - // The Error result carries the failure, so the banner stays on it rather than over every other result. - tab.execution.errorMessage = nil - tab.execution.errorQuery = nil - tab.execution.executionTime = timing.total - tab.execution.lastExecutedAt = Date() - tab.display.replaceUnpinnedResults( - with: batchResultSets(prepared, outputs: outputs, tabId: tabId, plan: plan) + [errorResult] - ) - if tab.display.isResultsCollapsed { - tab.display.isResultsCollapsed = false - } - } - parent.seedBufferFromActiveResult(tabId: tabId) - parent.dropEdits(ofReplacedResultIn: tabId) - if parent.tabManager.selectedTabId == tabId { - parent.toolbarState.isResultsCollapsed = false - parent.toolbarState.recordQueryTiming(timing, for: tabId) - parent.announceQueryError(report.message) - } + presentFailedRun( + tabId: run.tabId, + resultSets: batchResultSets(prepared, outputs: outputs, tabId: run.tabId, plan: plan), + error: errorResult, + timing: PluginQueryTiming(total: outputs.reduce(0) { $0 + $1.executionTime }), + announcing: report.message + ) } - /// One history entry per batch, because the batch is what ran. A failed batch is recorded as failed, with the - /// error it raised. + // One history entry per batch, because the batch is what ran; a failed batch is recorded as failed. private func recordBatchHistory( _ prepared: [PreparedBatch], outputs: [BatchOutput], - parameters: [QueryParameter], - tabId: UUID, + run: TabRun, failedIndex: Int?, failureDescription: String? = nil ) { - let connection = parent.connection for (index, entry) in prepared.enumerated() { let failed = index == failedIndex guard failed || index < outputs.count else { continue } let summary = index < outputs.count ? outputs[index].summary : BatchSummary(rowCount: 0, executionTime: 0) - recordHistory( - QueryHistoryRecordRequest( - query: entry.batch.sql.hasSuffix(";") ? entry.batch.sql : entry.batch.sql + ";", - connectionId: connection.id, - databaseName: historyDatabaseName(tabId: tabId), - databaseType: connection.type, - schemaName: historySchemaName(tabId: tabId), - source: .editor, - executionTime: summary.executionTime, - rowCount: failed ? -1 : summary.rowCount, - wasSuccessful: !failed, - errorMessage: failed ? failureDescription : nil - ) - ) + run.recordHistory(RunHistoryEntry( + query: entry.batch.sql, + terminates: true, + source: .editor, + executionTime: summary.executionTime, + rowCount: failed ? -1 : summary.rowCount, + failure: failed ? (failureDescription ?? "") : nil + )) } } diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+ExplainRun.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+ExplainRun.swift new file mode 100644 index 0000000000..9908ea48be --- /dev/null +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+ExplainRun.swift @@ -0,0 +1,159 @@ +// +// QueryExecutionCoordinator+ExplainRun.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +extension QueryExecutionCoordinator { + func executeExplain(_ request: ExplainRequest, anchor: StatementAnchor?, onTab tabId: UUID) { + guard let run = TabRun.begin(onTab: tabId, in: parent) else { return } + let conn = run.connection + let safeModeIsReadOnly = parent.runsAtReadOnly + // EXPLAIN ANALYZE and an actual plan run the statement, so Manual Commit holds them as it would the write. + let ranWrite = request.operationKind(databaseType: conn.type).declaresWrite + let held = parent.manualCommitRun(skipped: !ranWrite) + let failureOutput = ServerOutputBox() + + run.launch { [weak self] run in + guard let self else { return } + let parent = self.parent + do { + let fetchResult = try await parent.services.databaseManager.withScopedDriver( + scope: run.scope, + route: parent.services.databaseManager.executionRoute(for: run.scope), + cancellation: .cancellableRead(run.lease), sessionWork: .statements + ) { [queryExecutor = parent.queryExecutor] 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 + if let step = request.driverStep { + return try await QueryExecutor.fetchExplainPlan( + driver: driver, statement: request.subjectSQL, variantId: step.variantId + ) + } + return try await queryExecutor.executeQuery( + driver: driver, sql: request.sql, parameters: nil, rowCap: nil, safeModeIsReadOnly: safeModeIsReadOnly + ) + } + } + } + if ranWrite { MainContentCoordinator.postStatementRan(request.subjectSQL, on: conn) } + let rawText = ExplainPlanTextFlattener.flatten(rows: fetchResult.rows) + + guard run.settle() else { return } + guard !Task.isCancelled else { + run.reportCancelled() + return + } + run.report(.query, .succeeded(OperationSummary())) + installExplainPlan( + ExplainResultRouter.RoutedPlan( + rawText: rawText, + plan: ExplainPlanParserRegistry.plan(from: rawText, format: request.format), + format: request.format, + variantKey: request.variantKey, + subjectSQL: request.subjectSQL + ), + onTab: tabId, + executionTime: fetchResult.executionTime, + rowCount: fetchResult.rows.count, + resultSQL: request.replayableSQL, + historySQL: request.sql, + connection: conn, + anchor: anchor, + serverOutput: fetchResult.serverOutput + ) + } catch { + if ranWrite { MainContentCoordinator.postStatementRan(request.subjectSQL, on: conn) } + parent.finishFailedQuery( + error, + tabId: tabId, + sql: request.sql, + connection: conn, + claim: run.claim, + isAutoLoad: false, + trigger: .userInitiated, + traceToken: nil, + serverOutput: failureOutput.output, + historySource: .explain + ) + } + } + } + + // The one place a plan lands, from a typed EXPLAIN or the Explain button: same result, plan capture and history row. + func installExplainPlan( + _ routed: ExplainResultRouter.RoutedPlan, + onTab tabId: UUID, + executionTime: TimeInterval, + rowCount: Int, + resultSQL: String?, + historySQL: String, + connection conn: DatabaseConnection, + queryParameterValues: [QueryParameter]? = nil, + anchor: StatementAnchor? = nil, + timing: PluginQueryTiming? = nil, + serverOutput: PluginServerOutput + ) { + let databaseName = historyDatabaseName(tabId: tabId) + let schemaName = historySchemaName(tabId: tabId) + let historyId = UUID() + let captured = QueryPlanCaptureBuilder.make( + subjectSQL: routed.subjectSQL, + rawPlan: routed.rawText, + format: routed.format, + variantKey: routed.variantKey, + scope: QueryPlanScope( + connectionId: conn.id, + databaseType: conn.type, + databaseName: databaseName, + schemaName: schemaName + ), + executionTime: executionTime, + capturedAt: Date(), + historyId: historyId, + queryParameters: queryParameterValues + ) + parent.flushBufferToActiveResult(tabId: tabId, pinnedOnly: true) + parent.tabManager.mutate(tabId: tabId) { tab in + tab.execution.executionTime = executionTime + tab.execution.rowsAffected = 0 + tab.execution.statusMessage = nil + tab.execution.lastExecutedAt = Date() + tab.pagination.resetLoadMore() + tab.display.replaceUnpinnedResults( + with: [ExplainResultSetFactory.make( + rawText: routed.rawText, + plan: routed.plan, + sql: resultSQL, + executionTime: executionTime, + anchor: anchor, + planContext: captured.context, + serverOutput: serverOutput + )] + ) + if tab.display.isResultsCollapsed { + tab.display.isResultsCollapsed = false + } + } + parent.seedBufferFromActiveResult(tabId: tabId) + parent.dropEdits(ofReplacedResultIn: tabId) + if parent.tabManager.selectedTabId == tabId { + parent.toolbarState.isResultsCollapsed = false + } + + recordRunHistory( + RunHistoryEntry( + id: historyId, + query: historySQL, + source: .explain, + executionTime: executionTime, + rowCount: rowCount, + planCapture: captured.capture, + timing: timing + ), + tabId: tabId + ) + } +} diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift index 1c988b5ece..cad990ed1f 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift @@ -236,12 +236,12 @@ extension QueryExecutionCoordinator { databaseType: conn.type, declaredVariants: conn.type.explainVariants ) { - applyExplainResult( - tabId: tabId, - routed: routed, + installExplainPlan( + routed, + onTab: tabId, executionTime: executionTime, rowCount: rows.count, - sql: sql, + resultSQL: sql, historySQL: historySQL ?? sql, connection: conn, queryParameterValues: queryParameterValues, @@ -351,7 +351,9 @@ extension QueryExecutionCoordinator { tab.display.isResultsCollapsed = false } } - parent.toolbarState.isResultsCollapsed = false + if parent.tabManager.selectedTabId == tabId { + parent.toolbarState.isResultsCollapsed = false + } let resolvedPKs = Self.resolvedPrimaryKeys( reported: metadata?.primaryKeyColumns, @@ -383,108 +385,44 @@ extension QueryExecutionCoordinator { if trigger.recordsHistory { recordSuccessfulRun( - query: historySQL ?? sql, tabId: tabId, connection: conn, + query: historySQL ?? sql, tabId: tabId, executionTime: executionTime, rowCount: rows.count, timing: timing ) } } - private func applyExplainResult( - tabId: UUID, - routed: ExplainResultRouter.RoutedPlan, - executionTime: TimeInterval, - rowCount: Int, - sql: String, - historySQL: String, - connection conn: DatabaseConnection, - queryParameterValues: [QueryParameter]?, - anchor: StatementAnchor? = nil, - timing: PluginQueryTiming? = nil, - serverOutput: PluginServerOutput - ) { - let databaseName = historyDatabaseName(tabId: tabId) - let schemaName = historySchemaName(tabId: tabId) - let historyId = UUID() - let captured = QueryPlanCaptureBuilder.make( - subjectSQL: routed.subjectSQL, - rawPlan: routed.rawText, - format: routed.format, - variantKey: routed.variantKey, - scope: QueryPlanScope( - connectionId: conn.id, - databaseType: conn.type, - databaseName: databaseName, - schemaName: schemaName - ), - executionTime: executionTime, - capturedAt: Date(), - historyId: historyId, - queryParameters: queryParameterValues - ) - parent.flushBufferToActiveResult(tabId: tabId, pinnedOnly: true) - parent.tabManager.mutate(tabId: tabId) { tab in - tab.execution.executionTime = executionTime - tab.execution.rowsAffected = 0 - tab.execution.statusMessage = nil - tab.execution.lastExecutedAt = Date() - tab.pagination.resetLoadMore() - tab.display.replaceUnpinnedResults( - with: [ExplainResultSetFactory.make( - rawText: routed.rawText, - plan: routed.plan, - sql: sql, - executionTime: executionTime, - anchor: anchor, - planContext: captured.context, - serverOutput: serverOutput - )] - ) - if tab.display.isResultsCollapsed { - tab.display.isResultsCollapsed = false - } - } - parent.seedBufferFromActiveResult(tabId: tabId) - parent.dropEdits(ofReplacedResultIn: tabId) - parent.toolbarState.isResultsCollapsed = false - - recordHistory( - QueryHistoryRecordRequest( - id: historyId, - query: historySQL, - connectionId: conn.id, - databaseName: databaseName, - databaseType: conn.type, - schemaName: schemaName, - source: .explain, - executionTime: executionTime, - rowCount: rowCount, - wasSuccessful: true, - planCapture: captured.capture, - timing: timing - ) - ) - } - private func recordSuccessfulRun( query: String, tabId: UUID, - connection conn: DatabaseConnection, executionTime: TimeInterval, rowCount: Int, timing: PluginQueryTiming? ) { - recordHistory( + recordRunHistory( + RunHistoryEntry(query: query, executionTime: executionTime, rowCount: rowCount, timing: timing), + tabId: tabId + ) + } + + // The one history writer for a tab's runs: every kind files under the tab's database and schema as the row is written. + @discardableResult + func recordRunHistory(_ entry: RunHistoryEntry, tabId: UUID) -> Task { + let conn = parent.connection + return recordHistory( QueryHistoryRecordRequest( - query: query, + id: entry.id, + query: entry.terminates && !entry.query.hasSuffix(";") ? entry.query + ";" : entry.query, connectionId: conn.id, databaseName: historyDatabaseName(tabId: tabId), databaseType: conn.type, schemaName: historySchemaName(tabId: tabId), - source: historySource(tabId: tabId), - executionTime: executionTime, - rowCount: rowCount, - wasSuccessful: true, - timing: timing + source: entry.source ?? historySource(tabId: tabId), + executionTime: entry.executionTime, + rowCount: entry.rowCount, + wasSuccessful: entry.failure == nil, + errorMessage: entry.failure, + planCapture: entry.planCapture, + timing: entry.timing ) ) } @@ -498,7 +436,9 @@ extension QueryExecutionCoordinator { ) { let isNonSQL = PluginManager.shared.editorLanguage(for: connectionType) != .sql let contentEpoch = parent.tabExecution.contentEpoch(for: tabId) - let resultSetId = parent.tabManager.tabs.first { $0.id == tabId }?.display.activeResultSetId + let tab = parent.tabManager.tabs.first { $0.id == tabId } + let resultSetId = tab?.display.activeResultSetId + let scope = tab.flatMap(parent.scope(for:)) Task(priority: .utility) { [weak self, parent] in // The caller marked the total pending; every exit that skips `resolveRowCount` must release it, or Count Exactly never returns. guard let self else { @@ -534,7 +474,8 @@ extension QueryExecutionCoordinator { let columnEnumValues = await parent.fetchEnumValues( columnInfo: schema.columns, tableName: tableName, - connectionType: connectionType + connectionType: connectionType, + scope: scope ) guard !columnEnumValues.isEmpty else { return } @@ -886,7 +827,8 @@ extension QueryExecutionCoordinator { tabId: UUID, connection conn: DatabaseConnection, serverOutput: PluginServerOutput = .none, - trigger: TableLoadTrigger = .userInitiated + trigger: TableLoadTrigger = .userInitiated, + historySource: QueryHistorySource? = nil ) { let diagnosis = DatabaseWriteRejectionDiagnosis.formatted(error) let message = ServerOutputCapture.failureMessage(diagnosis, output: serverOutput) @@ -900,19 +842,15 @@ extension QueryExecutionCoordinator { } guard trigger.recordsHistory else { return } - recordHistory( - QueryHistoryRecordRequest( + recordRunHistory( + RunHistoryEntry( query: sql, - connectionId: conn.id, - databaseName: historyDatabaseName(tabId: tabId), - databaseType: conn.type, - schemaName: historySchemaName(tabId: tabId), - source: historySource(tabId: tabId), + source: historySource, executionTime: 0, rowCount: -1, - wasSuccessful: false, - errorMessage: error.localizedDescription - ) + failure: error.localizedDescription + ), + tabId: tabId ) } } diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift index 6a06da7ab5..10ca26f1b3 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift @@ -28,11 +28,11 @@ struct StatementRowsBuild: Sendable { extension QueryExecutionCoordinator { func executeMultipleStatements( _ statements: [SQLStatementScanner.ExecutableStatement], - bypassRowLimit: Bool = false, - onTab target: UUID? = nil + onTab tabId: UUID, + bypassRowLimit: Bool = false ) { executeMultipleStatementsWithParameters( - statements, parameters: [], bypassRowLimit: bypassRowLimit, onTab: target + statements, parameters: [], onTab: tabId, bypassRowLimit: bypassRowLimit ) } @@ -260,41 +260,7 @@ extension QueryExecutionCoordinator { ) } - /// `unresolvedOutcome` is what a statement whose commit went unanswered carries. The statement - /// itself succeeded, so its rows and its timing are real, but whether the server kept it is not - /// something anything here can find out, and a plain success badge would say it did. - func recordStatementHistory( - sql: String, - result: QueryResult, - connection: DatabaseConnection, - databaseName: String, - parameterValues: [QueryParameter]? = nil, - unresolvedOutcome: String? = nil - ) { - let historySQL = sql.hasSuffix(";") ? sql : sql + ";" - recordHistory( - QueryHistoryRecordRequest( - query: historySQL, - connectionId: connection.id, - databaseName: databaseName, - databaseType: connection.type, - source: .editor, - executionTime: result.executionTime, - rowCount: result.rows.count, - wasSuccessful: unresolvedOutcome == nil, - errorMessage: unresolvedOutcome, - timing: result.resolvedTiming - ) - ) - } - - /// The settle gate, the task retirement, the history and the outcome notification belong to the - /// caller: a stopped run has already settled its claim and reports a cancellation rather than a - /// success, and still shows the results of the statements its plan could not take back. - /// - /// `sessionNotice` is the one thing a successful run may still have to say: a batch that joined - /// a transaction the user already had open committed nothing, and nothing else in the window - /// reports an open transaction. + // Below the caller's settle gate. `sessionNotice` says a batch joined a transaction the user had open and committed nothing. func presentMultiStatementResults( tabId: UUID, timing: PluginQueryTiming, @@ -359,8 +325,37 @@ extension QueryExecutionCoordinator { parameterValues: activeResultSet?.baseQueryParameterValues ) } - parent.toolbarState.isResultsCollapsed = false + parent.dropEdits(ofReplacedResultIn: tabId) + if parent.tabManager.selectedTabId == tabId { + parent.toolbarState.isResultsCollapsed = false + } + } + // Below the caller's settle gate: the results that ran stay, with the error as the last one. + func presentFailedRun( + tabId: UUID, + resultSets: [ResultSet], + error: ResultSet, + timing: PluginQueryTiming, + announcing message: String + ) { + parent.flushBufferToActiveResult(tabId: tabId, pinnedOnly: true) + parent.tabManager.mutate(tabId: tabId) { tab in + // The Error result carries the failure, so the banner stays on it rather than over every other result. + tab.execution.errorMessage = nil + tab.execution.errorQuery = nil + tab.execution.executionTime = timing.total + tab.execution.lastExecutedAt = Date() + tab.display.replaceUnpinnedResults(with: resultSets + [error]) + if tab.display.isResultsCollapsed { + tab.display.isResultsCollapsed = false + } + } + parent.seedBufferFromActiveResult(tabId: tabId) parent.dropEdits(ofReplacedResultIn: tabId) + guard parent.tabManager.selectedTabId == tabId else { return } + parent.toolbarState.isResultsCollapsed = false + parent.toolbarState.recordQueryTiming(timing, for: tabId) + parent.announceQueryError(message) } } diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift index 78a08b097b..663826ec04 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift @@ -10,14 +10,6 @@ import TableProSQLGrammar private let paramLog = Logger(subsystem: "com.TablePro", category: "QueryParameters") -/// One statement of a multi-statement run, resolved before the transaction opens so the -/// lease holds nothing but driver work. -/// Carries the driver-bound parameter values into the scoped-driver closure. The values are -/// handed to the driver and never touched again by the caller, which is what `[Any?]` hides. -private struct BoundParameterValues: @unchecked Sendable { - let values: [Any?] -} - /// What one multi-statement run left behind, and the plan it actually ran under. /// /// The plan is decided twice: from the statement text before any driver is leased, and again inside @@ -99,13 +91,12 @@ private struct ExecutedStatementHistory { let prepared: [PreparedStatement] let results: [QueryResult] let parameters: [QueryParameter] - let connection: DatabaseConnection // Read once per run: the rows built off the main actor and the results shown take the same plan. let rowResultLimit: Int? func keeping(_ kept: [QueryResult]) -> ExecutedStatementHistory { ExecutedStatementHistory( - prepared: prepared, results: kept, parameters: parameters, connection: connection, rowResultLimit: rowResultLimit + prepared: prepared, results: kept, parameters: parameters, rowResultLimit: rowResultLimit ) } } @@ -135,269 +126,22 @@ extension QueryExecutionCoordinator { QueryExecutor.detectAndReconcileParameters(sql: sql, existing: existing, grammar: parent.lexicalGrammar) } - func executeQueryWithParameters( - _ sql: String, - parameters: [QueryParameter], - bypassRowLimit: Bool = false, - anchor: StatementAnchor? = nil, - install: ResultInstall = .newResult, - onTab target: UUID? = nil - ) { - guard let (_, index) = parent.executionTab(target) else { return } - - let missing = parameters.filter { - !$0.isNull && $0.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - } - if let firstMissing = missing.first { - parent.tabManager.mutate(at: index) { - $0.execution.errorMessage = String( - format: String(localized: "Missing value for parameter: %@"), - ":\(firstMissing.name)" - ) - } - return - } - - let style = PluginMetadataRegistry.shared.snapshot( - for: parent.connection.type - )?.parameterStyle ?? .questionMark - let conversion = SQLParameterExtractor.convertToNativeStyle( - sql: sql, - parameters: parameters, - style: style, - grammar: parent.lexicalGrammar - ) - - paramLog.info("Executing parameterized query: \(conversion.sql.prefix(100), privacy: .private) with \(conversion.values.count) parameters") - - executeQueryInternalParameterized( - conversion.sql, - parameters: conversion.values, - originalParameters: parameters, - bypassRowLimit: bypassRowLimit, - originalSQL: sql, - anchor: anchor, - install: install, - onTab: target - ) - } - - /// The query runs on the tab's own database, not on wherever the connection's shared - /// driver happens to be pointing. - func executeQueryInternalParameterized( - _ sql: String, - parameters: [Any?], - originalParameters: [QueryParameter], - bypassRowLimit: Bool = false, - originalSQL: String? = nil, - anchor: StatementAnchor? = nil, - install: ResultInstall = .newResult, - onTab target: UUID? = nil - ) { - guard let (selectedTab, index) = parent.executionTab(target), - !parent.tabExecution.isExecuting(selectedTab.id) else { return } - - guard let scope = parent.scope(for: selectedTab) else { - parent.tabManager.mutate(at: index) { - $0.execution.errorMessage = String(localized: "Not connected to database") - } - return - } - - parent.tabManager.mutate(at: index) { tab in - tab.execution.executionTime = nil - tab.execution.errorMessage = nil - } - let tab = parent.tabManager.tabs[index] - - let conn = parent.connection - let tabId = parent.tabManager.tabs[index].id - let (claim, lease) = parent.beginTabExecution(for: tabId) - - let statement = resolveStatement(sql: sql, tabType: tab.tabType, bypassLimit: bypassRowLimit) - let rowCap = statement.rowCap - let (tableName, isEditable) = parent.resolveTableEditability(tab: tab, sql: sql) - - let needsMetadataFetch: Bool - if isEditable, let tableName { - needsMetadataFetch = !isMetadataCached(tabId: tabId, tableName: tableName) - } else { - needsMetadataFetch = false - } - /// Captured now, while the result this decision was made against is still the active one. - let cachedMetadata: ParsedSchemaMetadata? = needsMetadataFetch ? nil : ParsedSchemaMetadata.cached( - rows: parent.tabSessionRegistry.tableRows(for: tabId), - context: tab.tableContext - ) - - let readsView = tab.tableContext.knowsView(named: tableName) - let boundValues = BoundParameterValues(values: parameters) - let failureOutput = ServerOutputBox() - let grammar = parent.lexicalGrammar - let safeModeIsReadOnly = parent.runsAtReadOnly - let held = parent.manualCommitRun(skipped: tab.tabType != .query) - let parameterizedTask = Task { [weak self, parent] in - guard let self else { return } - - let schemaTask = parent.startSchemaFetch( - tableName, uncached: needsMetadataFetch, isView: readsView, scope: scope - ) - - do { - let (fetchResult, tableEdits) = try await DatabaseManager.shared.withScopedDriver( - scope: scope, - route: DatabaseManager.shared.executionRoute(for: scope), - 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. - await DatabaseManager.shared.noteSessionStatements([statement.sql], ranOn: driver, scope: scope) - return try await queryExecutor.executeQuery( - driver: driver, - sql: statement.sql, - parameters: boundValues.values, - rowCap: rowCap, - safeModeIsReadOnly: safeModeIsReadOnly, - capturingOutputInto: failureOutput - ) - } - let edits = await SucceededStatements.single( - statement.sql, scope: scope, databaseType: conn.type, grammar: grammar, ranOn: driver - ) - return (fetched, edits) - } - MainContentCoordinator.postStatementRan(statement.sql, on: conn, succeeded: tableEdits) - - guard !Task.isCancelled else { - schemaTask?.cancel() - await parent.resetExecutionState(claim: claim, executionTime: fetchResult.executionTime) - return - } - - let inlineMeta = needsMetadataFetch - ? QueryExecutor.inlineMetadata(from: fetchResult.resultColumnMeta, columns: fetchResult.columns) - : nil - - let applied = await applyParameterizedResult( - tabId: tabId, - fetchResult: fetchResult, - inlineMetadata: inlineMeta ?? cachedMetadata, - tableName: tableName, - isEditable: isEditable, - sql: sql, - connection: conn, - claim: claim, - originalParameters: originalParameters, - nativeParameters: parameters, - originalSQL: originalSQL, - anchor: anchor, - install: install - ) - guard applied else { - schemaTask?.cancel() - return - } - - if isEditable, let tableName { - if needsMetadataFetch { - launchPhase2Work( - tableName: tableName, - tabId: tabId, - connectionType: conn.type, - schemaTask: schemaTask - ) - } else { - launchPhase2Count( - tableName: tableName, - tabId: tabId, - connectionType: conn.type - ) - } - } else if !isEditable || tableName == nil { - await MainActor.run { [parent] in - parent.clearChangesIfCurrent(claim: claim) - } - } - } catch { - schemaTask?.cancel() - CatalogChangeService.post( - .statementsRan(connectionId: conn.id, statements: [statement.sql], databaseType: conn.type) - ) - await MainActor.run { [weak self] in - guard let self else { return } - guard parent.tabExecution.settle(claim) else { - parent.reportStopRollback(error, tabId: tabId) - return - } - parent.tabManager.mutate(tabId: tabId) { tab in - tab.pagination.isLoadingMore = false - } - parent.retireQueryTask(.claim(claim)) - if DatabaseCancellationDiagnosis.isCancellation(error) || Task.isCancelled { - parent.reportEndedExecutions([ - EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) - ]) - parent.reportStopRollback(error, tabId: tabId) - return - } - handleQueryExecutionError( - error, - sql: sql, - tabId: tabId, - connection: conn, - serverOutput: failureOutput.output - ) - reportOperation(kind: .query, claim: claim, outcome: .failed(reason: error.localizedDescription)) - } - } - } - parent.installQueryTask(parameterizedTask, owner: .claim(claim), lease: lease) - } - // One lease for every statement, so the transaction and its rollback reach the same handle. func executeMultipleStatementsWithParameters( _ statements: [SQLStatementScanner.ExecutableStatement], parameters: [QueryParameter], - bypassRowLimit: Bool = false, - onTab target: UUID? = nil + onTab tabId: UUID, + bypassRowLimit: Bool = false ) { - guard let (selectedTab, index) = parent.executionTab(target), - !parent.tabExecution.isExecuting(selectedTab.id) else { return } - - let missing = parameters.filter { - !$0.isNull && $0.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - } - if let firstMissing = missing.first { - parent.tabManager.mutate(at: index) { - $0.execution.errorMessage = String( - format: String(localized: "Missing value for parameter: %@"), - ":\(firstMissing.name)" - ) - } - return - } - - guard let scope = parent.scope(for: selectedTab) else { - parent.tabManager.mutate(at: index) { - $0.execution.errorMessage = String(localized: "Not connected to database") - } - return - } + guard let run = TabRun.begin(onTab: tabId, parameters: parameters, in: parent), + let tab = parent.tabManager.tabs.first(where: { $0.id == tabId }) else { return } let style = PluginMetadataRegistry.shared.snapshot( for: parent.connection.type )?.parameterStyle ?? .questionMark - - parent.tabManager.mutate(at: index) { tab in - tab.execution.executionTime = nil - tab.execution.errorMessage = nil - } - - let conn = parent.connection - let tabId = parent.tabManager.tabs[index].id - let (claim, lease) = parent.beginTabExecution(for: tabId) - let tabType = parent.tabManager.tabs[index].tabType + let conn = run.connection + let scope = run.scope + let tabType = tab.tabType let statementTexts = statements.map(\.sql) let transactionKind = OperationKind.worst(of: statementTexts, databaseType: conn.type) @@ -416,7 +160,7 @@ extension QueryExecutionCoordinator { let asksEndState = SucceededStatements.runNeedsEndState( prepared.map(\.sentSQL), databaseType: conn.type, grammar: grammar ) - let script = parent.tabManager.tabs[index].content.query + let script = tab.content.query let running = RunningStatements( prepared: prepared, grammar: grammar, @@ -434,23 +178,23 @@ extension QueryExecutionCoordinator { ) } - let multiStatementTask = Task { [weak self, parent] in + run.launch { [weak self] run in guard let self else { return } - let run = await runMultiStatementTransaction( + let ran = await runMultiStatementTransaction( prepared: prepared, running: running, scope: scope, mode: transactionKind.transactionAccessMode, plan: plan, asksEndState: asksEndState, - claim: claim, - lease: lease + claim: run.claim, + lease: run.lease ) - let outcome = run.outcome + let outcome = ran.outcome let sent = running.prepared - let readsEndState = run.plan.readsSessionEndState || run.plan == .autocommit - let sessionNotice = readsEndState ? run.sessionState.openTransactionNotice : nil + let readsEndState = ran.plan.readsSessionEndState || ran.plan == .autocommit + let sessionNotice = readsEndState ? ran.sessionState.openTransactionNotice : nil let ranStatements: [String] switch outcome { @@ -470,7 +214,7 @@ extension QueryExecutionCoordinator { databaseType: conn.type, statements: sent.prefix(outcome.succeededCount).map(\.sentSQL), commit: .run( - startedIn: run.startState, endedIn: run.endState, plan: run.plan, completed: outcome.isCompleted + startedIn: ran.startState, endedIn: ran.endState, plan: ran.plan, completed: outcome.isCompleted ) ))) @@ -489,31 +233,26 @@ extension QueryExecutionCoordinator { ) let history = ExecutedStatementHistory( - prepared: sent, results: results, parameters: parameters, connection: conn, rowResultLimit: rowResultLimit + prepared: sent, results: results, parameters: parameters, rowResultLimit: rowResultLimit ) - guard parent.tabExecution.settle(claim) || reportsUnknownCommitAfterStop(outcome, claim: claim) else { + guard run.settle() || reportsUnknownCommitAfterStop(outcome, claim: run.claim) else { keepStatementsAfterStop( - history.keeping(outcome.keptAfterStop(plan: run.plan)), - claim: claim, + history.keeping(outcome.keptAfterStop(plan: ran.plan)), + run: run, sessionNotice: sessionNotice, built: built ) return } - parent.retireQueryTask(.claim(claim)) switch outcome { case .cancelled: keepStoppedStatements( - history: history, tabId: tabId, sessionNotice: sessionNotice, built: built, presentsResults: true + history: history, run: run, sessionNotice: sessionNotice, built: built, presentsResults: true ) - parent.reportEndedExecutions([ - EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) - ]) + run.reportCancelled() case .completed: - applyCompletedStatements( - history: history, tabId: tabId, claim: claim, sessionNotice: sessionNotice, built: built - ) + applyCompletedStatements(history: history, run: run, sessionNotice: sessionNotice, built: built) case .failed(let results, let failure, let errorDescription): handleMultiStatementError( MultiStatementFailureContext( @@ -521,20 +260,18 @@ extension QueryExecutionCoordinator { errorDescription: errorDescription, executedCount: results.count, totalCount: sent.count, - plan: run.plan, - sessionState: run.sessionState + plan: ran.plan, + sessionState: ran.sessionState ), history: history, - tabId: tabId, - claim: claim, + run: run, anchors: sent.map(\.anchor), timing: PluginQueryTiming.batch(of: results), - failureOutput: run.failureOutput, + failureOutput: ran.failureOutput, built: built ) } } - parent.installQueryTask(multiStatementTask, owner: .claim(claim), lease: lease) } private func prepareStatement( @@ -725,41 +462,39 @@ extension QueryExecutionCoordinator { // A Stop during a statement reads as one between statements: the completed ones are kept, with no error result. private func keepStatementsAfterStop( _ history: ExecutedStatementHistory, - claim: TabExecutionClaim, + run: TabRun, sessionNotice: String?, built: StatementRowsBuild ) { guard !history.results.isEmpty else { return } - let presentsResults = stoppedRunCanReplaceResults(onTab: claim.tabId) - guard parent.tabExecution.settleStopped(claim, replacingContent: presentsResults) else { return } + let presentsResults = stoppedRunCanReplaceResults(onTab: run.tabId) + guard parent.tabExecution.settleStopped(run.claim, replacingContent: presentsResults) else { return } keepStoppedStatements( history: history, - tabId: claim.tabId, + run: run, sessionNotice: sessionNotice, built: built, presentsResults: presentsResults ) - parent.reportEndedExecutions([ - EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) - ]) + run.reportCancelled() } // A Stop cannot take back what a plan without a transaction already committed, so those statements keep their history. private func keepStoppedStatements( history: ExecutedStatementHistory, - tabId: UUID, + run: TabRun, sessionNotice: String?, built: StatementRowsBuild, presentsResults: Bool ) { guard !history.results.isEmpty else { return } - recordExecutedStatements(history, tabId: tabId, commitOutcomeIsUnknown: false) + recordExecutedStatements(history, run: run, commitOutcomeIsUnknown: false) guard presentsResults else { return } presentMultiStatementResults( - tabId: tabId, + tabId: run.tabId, timing: PluginQueryTiming.batch(of: history.results), totalRowsAffected: history.results.reduce(0) { $0 + $1.rowsAffected }, - newResultSets: statementResultSets(history, tabId: tabId, built: built), + newResultSets: statementResultSets(history, tabId: run.tabId, built: built), sessionNotice: sessionNotice ) } @@ -767,25 +502,21 @@ extension QueryExecutionCoordinator { // Below the caller's settle gate: a superseded batch writes no history rows, outcome or result sets. private func applyCompletedStatements( history: ExecutedStatementHistory, - tabId: UUID, - claim: TabExecutionClaim, + run: TabRun, sessionNotice: String?, built: StatementRowsBuild ) { let totalRowsAffected = history.results.reduce(0) { $0 + $1.rowsAffected } - reportOperation( - kind: .queryBatch, - claim: claim, - outcome: .succeeded( - OperationSummary(rowsAffected: totalRowsAffected, statementCount: history.results.count) - ) + run.report( + .queryBatch, + .succeeded(OperationSummary(rowsAffected: totalRowsAffected, statementCount: history.results.count)) ) - recordExecutedStatements(history, tabId: tabId, commitOutcomeIsUnknown: false) + recordExecutedStatements(history, run: run, commitOutcomeIsUnknown: false) presentMultiStatementResults( - tabId: tabId, + tabId: run.tabId, timing: PluginQueryTiming.batch(of: history.results), totalRowsAffected: totalRowsAffected, - newResultSets: statementResultSets(history, tabId: tabId, built: built), + newResultSets: statementResultSets(history, tabId: run.tabId, built: built), sessionNotice: sessionNotice ) } @@ -821,112 +552,25 @@ extension QueryExecutionCoordinator { return resultSets } - /// A commit whose connection died before the answer leaves every statement of the batch in a - /// state nothing can report as done, so history says so rather than claiming a success it - /// cannot prove. + // A commit whose connection died before the answer cannot be reported as done, so history says so. private func recordExecutedStatements( _ history: ExecutedStatementHistory, - tabId: UUID, + run: TabRun, commitOutcomeIsUnknown: Bool ) { let unresolvedOutcome = commitOutcomeIsUnknown ? String(localized: "The connection was lost while committing, so this may not be saved.") : nil for (statement, result) in zip(history.prepared, history.results) { - recordStatementHistory( - sql: statement.originalSQL, - result: result, - connection: history.connection, - databaseName: historyDatabaseName(tabId: tabId), - parameterValues: statement.parameterValues == nil ? nil : history.parameters, - unresolvedOutcome: unresolvedOutcome - ) - } - } - - func applyParameterizedResult( - tabId: UUID, - fetchResult: QueryFetchResult, - inlineMetadata: ParsedSchemaMetadata?, - tableName: String?, - isEditable: Bool, - sql: String, - connection: DatabaseConnection, - claim: TabExecutionClaim, - originalParameters: [QueryParameter], - nativeParameters: [Any?], - originalSQL: String? = nil, - anchor: StatementAnchor? = nil, - install: ResultInstall = .newResult - ) async -> Bool { - let prepared = await TableRows.preparing( - fetchResult.rows, - exportDocuments: fetchResult.exportDocuments, - absentCells: fetchResult.absentCells, - shape: phase1RowShape( - tabId: tabId, tableName: tableName, columns: fetchResult.columns, columnTypes: fetchResult.columnTypes - ) - ) - return await MainActor.run { [weak self] in - guard let self else { return false } - guard parent.tabExecution.settle(claim) else { return false } - parent.retireQueryTask(.claim(claim)) - guard !Task.isCancelled else { - parent.reportEndedExecutions([ - EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) - ]) - return false - } - parent.toolbarState.recordQueryTiming(fetchResult.resolvedTiming, for: claim.tabId) - reportOperation( - kind: .query, - claim: claim, - outcome: .succeeded( - OperationSummary( - rowsReturned: fetchResult.rows.count, - rowsAffected: fetchResult.rowsAffected - ) - ) - ) - - guard parent.rereadStillApplies(install.source) else { return false } - applyPhase1Result( - tabId: tabId, - columns: fetchResult.columns, - columnTypes: fetchResult.columnTypes, - rows: fetchResult.rows, - executionTime: fetchResult.executionTime, - rowsAffected: fetchResult.rowsAffected, - statusMessage: fetchResult.statusMessage, - tableName: tableName, - isEditable: isEditable, - metadata: inlineMetadata, - hasSchema: false, - read: TableFreshness.Read(startedAt: claim.startedAt, includesDefinition: false), - sql: sql, - connection: connection, - isTruncated: fetchResult.isTruncated, - queryParameterValues: originalParameters, - historySQL: originalSQL, - anchor: anchor, - timing: fetchResult.resolvedTiming, - viewport: install.viewport, - source: install.source, - serverOutput: fetchResult.serverOutput, - exportDocuments: fetchResult.exportDocuments, - absentCells: fetchResult.absentCells, - columnOrigins: fetchResult.columnOrigins, - prepared: prepared - ) - - let parameterValues = nativeParameters.map(TypedParameterValue.kept) - let statement = originalSQL.map { NamedParameterStatement(sql: $0, parameters: originalParameters) } - parent.tabManager.mutate(tabId: tabId) { - $0.pagination.baseQueryParameterValues = parameterValues - $0.display.activeResultSet?.baseQueryParameterValues = parameterValues - $0.display.activeResultSet?.namedParameterStatement = statement - } - return true + run.recordHistory(RunHistoryEntry( + query: statement.originalSQL, + terminates: true, + source: .editor, + executionTime: result.executionTime, + rowCount: result.rows.count, + failure: unresolvedOutcome, + timing: result.resolvedTiming + )) } } @@ -934,71 +578,44 @@ extension QueryExecutionCoordinator { private func handleMultiStatementError( _ context: MultiStatementFailureContext, history: ExecutedStatementHistory, - tabId: UUID, - claim: TabExecutionClaim, + run: TabRun, anchors: [StatementAnchor?], timing: PluginQueryTiming, failureOutput: PluginServerOutput, built: StatementRowsBuild ) { - let cumulativeTime = timing.total let errorDescription = context.errorDescription let report = context.report() - let contextMsg = ServerOutputCapture.failureMessage(report.message, output: failureOutput) let errorRS = ResultSet(label: report.resultLabel) - errorRS.errorMessage = contextMsg + errorRS.errorMessage = ServerOutputCapture.failureMessage(report.message, output: failureOutput) errorRS.failedQuery = report.failedSQL errorRS.statementAnchor = report.failedStatementIndex .flatMap { anchors.indices.contains($0) ? anchors[$0] : nil } - let failedStatementSQL = report.failedSQL // A run stopped to wait for a commit has no server error, so the notification carries the report. - reportOperation( - kind: .queryBatch, claim: claim, outcome: .failed(reason: errorDescription.isEmpty ? report.message : errorDescription) - ) + run.report(.queryBatch, .failed(reason: errorDescription.isEmpty ? report.message : errorDescription)) recordExecutedStatements( history, - tabId: tabId, + run: run, commitOutcomeIsUnknown: context.failure == .commitOutcomeUnknown ) - - parent.flushBufferToActiveResult(tabId: tabId, pinnedOnly: true) - parent.tabManager.mutate(tabId: tabId) { tab in - // The Error result carries the failure, so the banner stays on it rather than over every other result. - tab.execution.errorMessage = nil - tab.execution.errorQuery = nil - tab.execution.executionTime = cumulativeTime - tab.execution.lastExecutedAt = Date() - - tab.display.replaceUnpinnedResults(with: statementResultSets(history, tabId: tabId, built: built) + [errorRS]) - if tab.display.isResultsCollapsed { - tab.display.isResultsCollapsed = false - } - } - parent.seedBufferFromActiveResult(tabId: tabId) - parent.dropEdits(ofReplacedResultIn: tabId) - if parent.tabManager.selectedTabId == tabId { - parent.toolbarState.isResultsCollapsed = false - parent.toolbarState.recordQueryTiming(timing, for: tabId) - parent.announceQueryError(report.message) - } - - guard let rawSQL = failedStatementSQL else { return } - let recordSQL = rawSQL.hasSuffix(";") ? rawSQL : rawSQL + ";" - recordHistory( - QueryHistoryRecordRequest( - query: recordSQL, - connectionId: history.connection.id, - databaseName: historyDatabaseName(tabId: tabId), - databaseType: history.connection.type, - schemaName: historySchemaName(tabId: tabId), - source: .editor, - executionTime: cumulativeTime, - rowCount: -1, - wasSuccessful: false, - errorMessage: errorDescription - ) + presentFailedRun( + tabId: run.tabId, + resultSets: statementResultSets(history, tabId: run.tabId, built: built), + error: errorRS, + timing: timing, + announcing: report.message ) + + guard let failedSQL = report.failedSQL else { return } + run.recordHistory(RunHistoryEntry( + query: failedSQL, + terminates: true, + source: .editor, + executionTime: timing.total, + rowCount: -1, + failure: errorDescription + )) } } diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+SingleRun.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+SingleRun.swift new file mode 100644 index 0000000000..24cabdb7d4 --- /dev/null +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+SingleRun.swift @@ -0,0 +1,260 @@ +// +// QueryExecutionCoordinator+SingleRun.swift +// TablePro +// + +import Foundation +import os +import TableProPluginKit +import TableProSQLGrammar + +private let singleRunLog = Logger(subsystem: "com.TablePro", category: "QueryParameters") + +// The values a parameterized statement sends, handed to the driver and never read again by the caller. +struct BoundStatement: @unchecked Sendable { + let values: [Any?] + let parameters: [QueryParameter] + // The statement as typed, with its `:name` markers: what history and Fix with AI show. + let originalSQL: String? +} + +struct SingleRunRequest { + let sql: String + var bound: BoundStatement? + var isAutoLoad = false + var trigger: TableLoadTrigger = .userInitiated + var bypassRowLimit = false + var anchor: StatementAnchor? + var install: ResultInstall = .newResult +} + +extension QueryExecutionCoordinator { + func executeQueryWithParameters( + _ sql: String, + parameters: [QueryParameter], + onTab tabId: UUID, + bypassRowLimit: Bool = false, + anchor: StatementAnchor? = nil, + install: ResultInstall = .newResult + ) { + let style = PluginMetadataRegistry.shared.snapshot(for: parent.connection.type)?.parameterStyle ?? .questionMark + let conversion = SQLParameterExtractor.convertToNativeStyle( + sql: sql, + parameters: parameters, + style: style, + grammar: parent.lexicalGrammar + ) + singleRunLog.info( + "Executing parameterized query: \(conversion.sql.prefix(100), privacy: .private) with \(conversion.values.count) parameters" + ) + var request = SingleRunRequest(sql: conversion.sql) + request.bound = BoundStatement(values: conversion.values, parameters: parameters, originalSQL: sql) + request.bypassRowLimit = bypassRowLimit + request.anchor = anchor + request.install = install + startSingleRun(request, onTab: tabId) + } + + func startSingleRun(_ request: SingleRunRequest, onTab tabId: UUID) { + guard let run = TabRun.begin(onTab: tabId, parameters: request.bound?.parameters ?? [], in: parent) else { return } + runSingle(request, in: run) + } + + // swiftlint:disable:next function_body_length + private func runSingle(_ request: SingleRunRequest, in run: TabRun) { + guard let tab = parent.tabManager.tabs.first(where: { $0.id == run.tabId }) else { return } + let tabId = run.tabId + let sql = request.sql + let isAutoLoad = request.isAutoLoad + let trigger = request.trigger + let conn = run.connection + let scope = run.scope + + let traceToken = trigger.tracesLoad ? parent.adoptOrBeginExecutionTrace(tabId: tabId) : nil + parent.traceExecutionStarted(traceToken, epoch: run.claim.epoch, isAutoLoad: isAutoLoad) + + let statement = resolveStatement(sql: sql, tabType: tab.tabType, bypassLimit: request.bypassRowLimit) + let rowCap = statement.rowCap + let (tableName, isEditable) = parent.resolveTableEditability(tab: tab, sql: sql) + + let needsDefinition = parent.tabSessionRegistry.needsDefinition(tabId) + let needsMetadataFetch = tableName.map { isEditable && !isMetadataCached(tabId: tabId, tableName: $0) } ?? false + // Captured now, while the result this decision was made against is still the active one. + let cachedMetadata: ParsedSchemaMetadata? = needsMetadataFetch ? nil : ParsedSchemaMetadata.cached( + rows: parent.tabSessionRegistry.tableRows(for: tabId), + context: tab.tableContext + ) + if let tableName { + MainContentCoordinator.logger.info( + "[fk] metadata decision table=\(tableName, privacy: .private(mask: .hash)) isEditable=\(isEditable) needsFetch=\(needsMetadataFetch)" + ) + } + let isTableTab = tab.tabType == .table + let readsView = tab.tableContext.knowsView(named: tableName) + let (grammar, lengthColumns) = (parent.lexicalGrammar, parent.unloadedValueLengthColumns(for: tab)) + let safeModeIsReadOnly = parent.runsAtReadOnly + let held = parent.manualCommitRun(skipped: isTableTab || isAutoLoad) + let bound = request.bound + let failureOutput = ServerOutputBox() + + run.launch { [weak self] run in + guard let self else { return } + let parent = self.parent + + if isAutoLoad, await !parent.connectBeforeAutoLoad(conn, claim: run.claim, trigger: trigger, traceToken: traceToken) { + return + } + + let schemaTask = parent.startSchemaFetch(tableName, uncached: needsMetadataFetch, isView: readsView, scope: scope) + + let fetchBeganAt = ContinuousClock.now + do { + let (fetchResult, tableEdits) = try await parent.withExecutionDriver( + scope: scope, + isTableTab: isTableTab, + lease: run.lease + ) { [queryExecutor = parent.queryExecutor, manager = parent.services.databaseManager] 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. + if !isAutoLoad { await manager.noteSessionStatements([statement.sql], ranOn: driver, scope: scope) } + return try await queryExecutor.executeQuery( + driver: driver, + sql: statement.sql, + parameters: bound?.values, + rowCap: rowCap, + safeModeIsReadOnly: safeModeIsReadOnly, + capturingOutputInto: isTableTab ? nil : failureOutput + ) + } + let edits = isAutoLoad ? nil : await SucceededStatements.single( + statement.sql, scope: scope, databaseType: conn.type, grammar: grammar, ranOn: driver + ) + return (fetched.foldingUnloadedValues(lengthColumns: lengthColumns), edits) + } + let fetchEndedAt = ContinuousClock.now + if !isAutoLoad { MainContentCoordinator.postStatementRan(statement.sql, on: conn, succeeded: tableEdits) } + + guard !Task.isCancelled else { + schemaTask?.cancel() + parent.traceFetchCancelled(traceToken, began: fetchBeganAt, ended: fetchEndedAt) + parent.resetExecutionState(claim: run.claim, executionTime: fetchResult.executionTime) + return + } + + let inlineMeta = needsMetadataFetch + ? QueryExecutor.inlineMetadata(from: fetchResult.resultColumnMeta, columns: fetchResult.columns) + : nil + // Rows and definition commit together after a definition change, so new columns never sit under old keys or defaults. + let definition = needsDefinition ? try? await schemaTask?.value : nil + let prepared = await parent.preparedPhase1Rows( + fetchResult, tabId: tabId, tableName: tableName, isTableTab: isTableTab + ) + + parent.traceFetchCompleted(traceToken, began: fetchBeganAt, ended: fetchEndedAt, result: fetchResult) + // Settle first: it gates every write below, and sharing a guard with the cancel check would leave the tab claimed forever. + guard run.settle() else { + parent.traceStaleResultDropped(traceToken) + schemaTask?.cancel() + return + } + guard !Task.isCancelled else { + parent.traceStaleResultDropped(traceToken) + run.reportCancelled() + schemaTask?.cancel() + return + } + guard parent.rereadStillApplies(request.install.source) else { + parent.traceStaleResultDropped(traceToken) + schemaTask?.cancel() + return + } + // A menu or value window opened during the read names rows by position, so a tick's rows wait for the next one. + guard trigger != .autoRefresh || !parent.autoRefreshHeldByTransientUI(tabId) else { + schemaTask?.cancel() + return + } + parent.toolbarState.recordQueryTiming(fetchResult.resolvedTiming, for: tabId) + parent.traceApplyingResult(traceToken, tabId: tabId) + + let definitionMetadata = parent.adoptLoadedDefinition(definition, of: tableName, in: scope, readBy: run.claim) + applyPhase1Result( + tabId: tabId, + columns: fetchResult.columns, + columnTypes: fetchResult.columnTypes, + rows: fetchResult.rows, + executionTime: fetchResult.executionTime, + rowsAffected: fetchResult.rowsAffected, + statusMessage: fetchResult.statusMessage, + tableName: tableName, + isEditable: isEditable, + metadata: definitionMetadata ?? inlineMeta ?? cachedMetadata, + hasSchema: definitionMetadata != nil, + read: TableFreshness.Read(startedAt: run.claim.startedAt, includesDefinition: definitionMetadata != nil), + sql: sql, + connection: conn, + isTruncated: fetchResult.isTruncated, + queryParameterValues: bound?.parameters, + historySQL: bound?.originalSQL, + anchor: request.anchor, + timing: fetchResult.resolvedTiming, + viewport: request.install.viewport, + source: request.install.source, + serverOutput: fetchResult.serverOutput, + rowLocators: isTableTab ? fetchResult.rowLocators : nil, + exportDocuments: fetchResult.exportDocuments, + absentCells: fetchResult.absentCells, + unloadedCells: fetchResult.unloadedCells, + columnOrigins: fetchResult.columnOrigins, + prepared: prepared, + trigger: trigger + ) + if let bound { + keepBoundValues(bound, onTab: tabId) + } + + parent.scheduleTraceCompletion(traceToken, outcome: .completed) + run.report( + .query, + .succeeded(OperationSummary(rowsReturned: fetchResult.rows.count, rowsAffected: fetchResult.rowsAffected)), + trigger: trigger + ) + + // Phase 2 writes onto whatever the tab holds, so only the run that applied its rows starts it. + parent.launchPhase2AfterApply( + tableName: tableName, + isEditable: isEditable, + tabId: tabId, + trigger: trigger, + needsMetadataFetch: needsMetadataFetch, + schemaTask: schemaTask, + claim: run.claim + ) + } catch { + schemaTask?.cancel() + if !isAutoLoad { MainContentCoordinator.postStatementRan(statement.sql, on: conn) } + parent.finishFailedQuery( + error, + tabId: tabId, + sql: sql, + connection: conn, + claim: run.claim, + isAutoLoad: isAutoLoad, + trigger: trigger, + traceToken: traceToken, + serverOutput: failureOutput.output + ) + } + } + } + + // Load More and a re-read send the result's own values again, not whatever the panel holds by then. + private func keepBoundValues(_ bound: BoundStatement, onTab tabId: UUID) { + let parameterValues = bound.values.map(TypedParameterValue.kept) + let statement = bound.originalSQL.map { NamedParameterStatement(sql: $0, parameters: bound.parameters) } + parent.tabManager.mutate(tabId: tabId) { + $0.pagination.baseQueryParameterValues = parameterValues + $0.display.activeResultSet?.baseQueryParameterValues = parameterValues + $0.display.activeResultSet?.namedParameterStatement = statement + } + } +} diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator.swift index 243da63feb..bada0bb7ea 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator.swift @@ -22,60 +22,21 @@ final class QueryExecutionCoordinator: ObservableObject { self.parent = parent } - // MARK: - Run All Statements - - func runAllStatements(extraCapabilities: CallerCapabilities = []) { - guard let (tab, index) = parent.tabManager.selectedTabAndIndex, - !parent.tabExecution.isExecuting(tab.id), - tab.tabType == .query else { return } - - let batches = executionBatches(in: tab.content.query) - let statements = batches.flatMap(\.statements) - guard !statements.isEmpty else { return } - parent.tabVersions.record(tab, connectionId: parent.connectionId, reason: .run) - - if AppSettingsManager.shared.editor.queryParametersEnabled, parent.bindsNamedParameters { - let combinedSQL = SQLParameterExtractor.parameterSource(of: statements) - let detectedNames = SQLParameterExtractor.extractParameters(from: combinedSQL, grammar: parent.lexicalGrammar) - - if !detectedNames.isEmpty { - let reconciled = detectAndReconcileParameters( - sql: combinedSQL, - existing: parent.tabManager.tabs[index].content.queryParameters - ) - parent.tabManager.mutate(at: index) { $0.content.queryParameters = reconciled } - - if !parent.tabManager.tabs[index].content.isParameterPanelVisible { - parent.tabManager.mutate(at: index) { $0.content.isParameterPanelVisible = true } - return - } - - dispatchParameterizedBatches( - batches, - parameters: reconciled, - tabIndex: index, - extraCapabilities: extraCapabilities - ) - return - } - } - - dispatchBatches(batches, tabIndex: index, extraCapabilities: extraCapabilities) - } - + // `parameters` nil runs the text as written; a list binds each statement's `:name` markers. func dispatchBatches( _ batches: [ExecutableBatch], - tabIndex index: Int, + parameters: [QueryParameter]? = nil, + onTab tabId: UUID, bypassRowLimit: Bool = false, extraCapabilities: CallerCapabilities = [], install: ResultInstall = .newResult ) { guard !parent.isShowingSafeModePrompt, let route = executionRoute(for: batches) else { return } - guard !refuses(route, tabIndex: index), let target = runTarget(at: index) else { return } + guard !refuses(route, onTab: tabId), let target = runTarget(onTab: tabId) else { return } parent.isShowingSafeModePrompt = true let request = makeExecuteRequest( statements: batches.flatMap(\.statements), - tabIndex: index, + onTab: tabId, extraCapabilities: extraCapabilities ) Task { [parent] in @@ -83,39 +44,54 @@ final class QueryExecutionCoordinator: ObservableObject { switch await parent.executionGate.authorize(request) { case .authorized: guard parent.rereadCanStart(install.source), stillHolds(target) else { return } - switch route { - case .single(let only): - parent.executeQueryInternal( - only.sql, - bypassRowLimit: bypassRowLimit, - anchor: install.anchor ?? StatementAnchor(only), - viewport: install.viewport, - source: install.source, - onTab: target.tabId - ) - case .statements(let statements): - executeMultipleStatements(statements, bypassRowLimit: bypassRowLimit, onTab: target.tabId) - case .batches(let batches): - executeBatches(batches, parameters: [], bypassRowLimit: bypassRowLimit, onTab: target.tabId) - case .needsBatchDriver: - break - } + start(route, parameters: parameters, bypassRowLimit: bypassRowLimit, install: install, onTab: target.tabId) case .denied(let reason, _): parent.tabManager.mutate(tabId: target.tabId) { $0.execution.errorMessage = reason } } } } - private func runTarget(at index: Int) -> RunTarget? { - guard parent.tabManager.tabs.indices.contains(index) else { return nil } - let tab = parent.tabManager.tabs[index] + private func start( + _ route: QueryExecutionRoute, + parameters: [QueryParameter]?, + bypassRowLimit: Bool, + install: ResultInstall, + onTab tabId: UUID + ) { + switch route { + case .single(let only): + let anchor = install.anchor ?? StatementAnchor(only) + if let parameters { + executeQueryWithParameters( + only.sql, parameters: parameters, onTab: tabId, + bypassRowLimit: bypassRowLimit, anchor: anchor, install: install + ) + } else { + startSingleRun( + SingleRunRequest(sql: only.sql, bypassRowLimit: bypassRowLimit, anchor: anchor, install: install), + onTab: tabId + ) + } + case .statements(let statements): + executeMultipleStatementsWithParameters( + statements, parameters: parameters ?? [], onTab: tabId, bypassRowLimit: bypassRowLimit + ) + case .batches(let batches): + executeBatches(batches, parameters: parameters ?? [], onTab: tabId, bypassRowLimit: bypassRowLimit) + case .needsBatchDriver: + break + } + } + + func runTarget(onTab tabId: UUID) -> RunTarget? { + guard let tab = parent.tabManager.tabs.first(where: { $0.id == tabId }) else { return nil } return RunTarget( tabId: tab.id, databaseName: tab.tableContext.databaseName, schemaName: tab.tableContext.schemaName ) } // The approval prompt is not window-modal: the tab can be closed or repointed at another database before the answer. - private func stillHolds(_ target: RunTarget) -> Bool { + func stillHolds(_ target: RunTarget) -> Bool { guard let tab = parent.tabManager.tabs.first(where: { $0.id == target.tabId }) else { return false } // A tab bound to no database follows the connection, which a queued switch may move meanwhile. let moved = !target.databaseName.isEmpty @@ -133,11 +109,10 @@ final class QueryExecutionCoordinator: ObservableObject { private func makeExecuteRequest( statements: [SQLStatementScanner.ExecutableStatement], - tabIndex index: Int, + onTab tabId: UUID, extraCapabilities: CallerCapabilities = [] ) -> OperationRequest { let sql = statements.map(\.sql) - let tabs = parent.tabManager.tabs return OperationRequest( connectionId: parent.connectionId, databaseType: parent.connection.type, @@ -146,76 +121,14 @@ final class QueryExecutionCoordinator: ObservableObject { caller: .userInterface, capabilities: CallerCapabilities.interactiveUser.union(extraCapabilities), operationDescription: String(localized: "Execute Query"), - runsIn: tabs.indices.contains(index) ? parent.scope(for: tabs[index]) : nil - ) - } - - func dispatchParameterizedBatches( - _ batches: [ExecutableBatch], - parameters: [QueryParameter], - tabIndex index: Int, - bypassRowLimit: Bool = false, - extraCapabilities: CallerCapabilities = [], - install: ResultInstall = .newResult - ) { - guard !parent.isShowingSafeModePrompt, let route = executionRoute(for: batches) else { return } - guard !refuses(route, tabIndex: index), let target = runTarget(at: index) else { return } - parent.isShowingSafeModePrompt = true - let request = makeExecuteRequest( - statements: batches.flatMap(\.statements), - tabIndex: index, - extraCapabilities: extraCapabilities + runsIn: parent.tabManager.tabs.first { $0.id == tabId }.flatMap(parent.scope(for:)) ) - Task { [parent] in - defer { parent.isShowingSafeModePrompt = false } - switch await parent.executionGate.authorize(request) { - case .authorized: - guard parent.rereadCanStart(install.source), stillHolds(target) else { return } - executeParameterizedAfterSafeMode( - route, - parameters: parameters, - bypassRowLimit: bypassRowLimit, - install: install, - tabId: target.tabId - ) - case .denied(let reason, _): - parent.tabManager.mutate(tabId: target.tabId) { $0.execution.errorMessage = reason } - } - } - } - - private func executeParameterizedAfterSafeMode( - _ route: QueryExecutionRoute, - parameters: [QueryParameter], - bypassRowLimit: Bool, - install: ResultInstall, - tabId: UUID - ) { - switch route { - case .single(let only): - executeQueryWithParameters( - only.sql, - parameters: parameters, - bypassRowLimit: bypassRowLimit, - anchor: install.anchor ?? StatementAnchor(only), - install: install, - onTab: tabId - ) - case .statements(let statements): - executeMultipleStatementsWithParameters( - statements, parameters: parameters, bypassRowLimit: bypassRowLimit, onTab: tabId - ) - case .batches(let batches): - executeBatches(batches, parameters: parameters, bypassRowLimit: bypassRowLimit, onTab: tabId) - case .needsBatchDriver: - break - } } // A run the driver cannot carry out as written says so before anything is sent, rather than running part of it. - private func refuses(_ route: QueryExecutionRoute, tabIndex index: Int) -> Bool { + private func refuses(_ route: QueryExecutionRoute, onTab tabId: UUID) -> Bool { guard case .needsBatchDriver = route else { return false } - parent.tabManager.mutate(at: index) { + parent.tabManager.mutate(tabId: tabId) { $0.execution.errorMessage = String( localized: "Update the database driver in Settings > Extensions to run a batch more than once with GO." ) diff --git a/apple/TablePro/Core/Coordinators/RowEditingCoordinator+Discard.swift b/apple/TablePro/Core/Coordinators/RowEditingCoordinator+Discard.swift index a1c92171de..33f6f5324c 100644 --- a/apple/TablePro/Core/Coordinators/RowEditingCoordinator+Discard.swift +++ b/apple/TablePro/Core/Coordinators/RowEditingCoordinator+Discard.swift @@ -68,15 +68,23 @@ extension RowEditingCoordinator { // Edits are written into the loaded rows too; a discard that does not re-query must undo them here or they stay untracked. func restoreRowBufferToOriginals() { - guard let (tab, _) = parent.tabManager.selectedTabAndIndex, - let tableRows = parent.tabSessionRegistry.existingTableRows(for: tab.id) else { + guard let tabId = parent.tabManager.selectedTabId else { parent.gridDisplayRevision &+= 1 return } - let tabId = tab.id - let insertedIDs = parent.changeManager.insertedRowIDs + restoreRowBufferToOriginals(forTab: tabId) + } + + func restoreRowBufferToOriginals(forTab tabId: UUID) { + guard parent.tabManager.tabs.contains(where: { $0.id == tabId }), + let tableRows = parent.tabSessionRegistry.existingTableRows(for: tabId) else { + parent.gridDisplayRevision &+= 1 + return + } + let changeManager = parent.changeManager(forTab: tabId) + let insertedIDs = changeManager.insertedRowIDs var absentCells: Set = [] - let edits = parent.changeManager.getOriginalValues().compactMap { original in + let edits = changeManager.getOriginalValues().compactMap { original in tableRows.index(of: original.rowID).map { storageRow -> (row: Int, column: Int, value: PluginCellValue) in if original.isAbsent { absentCells.insert(CellPosition(row: storageRow, column: original.columnIndex)) diff --git a/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift b/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift index 348ac4c2c9..9560381c13 100644 --- a/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift +++ b/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift @@ -68,7 +68,9 @@ extension RowEditingCoordinator { return } - guard parent.selectedTabScope != nil else { + // With no tab the save is table operations staged from the sidebar, on the browse scope. + let savingTab = savingTabId.flatMap { id in parent.tabManager.tabs.first { $0.id == id } } + guard (savingTab.flatMap({ parent.scope(for: $0) }) ?? parent.browseScope) != nil else { failSave(message: String(localized: "Not connected to database"), tabId: savingTabId, waiter: waiter) return } @@ -420,7 +422,7 @@ extension RowEditingCoordinator { /// retiring it the reload's automatic count refuses to replace it, and the bar /// keeps the pre-save total with no `Count Exactly` offered to correct it. parent.tabManager.mutate(at: savedTabIndex) { $0.pagination.retireDerivedRowCount() } - parent.reloadActiveResult() + parent.reloadActiveResult(onTab: parent.tabManager.tabs[savedTabIndex].id) } // The saving tab reloads itself and is left out. @@ -699,9 +701,7 @@ extension RowEditingCoordinator { } fileprivate extension RowEditingCoordinator { - /// The save is owned by the tab that started it, not by whichever tab is selected when it - /// lands: `failSave` writes into the selected tab, so keying a completion off that would - /// attribute a slow save to a tab the user switched to while waiting. + // Keyed on the tab that started the save, never the one in front when it lands. func reportSaveFinished( _ outcome: OperationOutcome, connection: DatabaseConnection, diff --git a/apple/TablePro/Core/Execution/TabRun.swift b/apple/TablePro/Core/Execution/TabRun.swift new file mode 100644 index 0000000000..c670125930 --- /dev/null +++ b/apple/TablePro/Core/Execution/TabRun.swift @@ -0,0 +1,113 @@ +// +// TabRun.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +// One execution on one tab, from claim to settle. Every run kind goes through it, so a lifecycle fix lands once. +@MainActor +struct TabRun { + let tabId: UUID + let claim: TabExecutionClaim + let lease: DriverLeaseOwner + let scope: DatabaseScope + let connection: DatabaseConnection + private weak var coordinator: MainContentCoordinator? + + // Supersedes whatever the tab was running: refusing a busy tab is the entry point's job, before any prompt. + static func begin( + onTab tabId: UUID, + parameters: [QueryParameter] = [], + in coordinator: MainContentCoordinator + ) -> TabRun? { + guard let tab = coordinator.tabManager.tabs.first(where: { $0.id == tabId }) else { return nil } + if let missing = parameters.first(where: { !$0.isNull && $0.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) { + coordinator.tabManager.mutate(tabId: tabId) { + $0.execution.errorMessage = String(format: String(localized: "Missing value for parameter: %@"), ":\(missing.name)") + } + return nil + } + // Claimed before the scope is known, so a load that cannot start still ends the one it replaces. + let (claim, lease) = coordinator.beginTabExecution(for: tabId) + coordinator.tabManager.mutate(tabId: tabId) { tab in + tab.execution.executionTime = nil + tab.execution.errorMessage = nil + } + guard let scope = coordinator.scope(for: tab) else { + guard coordinator.tabExecution.settle(claim) else { return nil } + coordinator.tabManager.mutate(tabId: tabId) { tab in + tab.execution.errorMessage = String(localized: "Not connected to database") + tab.pagination.isLoading = false + } + return nil + } + return TabRun( + tabId: tabId, + claim: claim, + lease: lease, + scope: scope, + connection: coordinator.connection, + coordinator: coordinator + ) + } + + func launch(_ work: @escaping @MainActor (TabRun) async -> Void) { + guard let coordinator else { return } + let run = self + // Held to the end: the strategies reach the coordinator through unowned references while a closed window's run unwinds. + let task = Task { [coordinator] in + await work(run) + withExtendedLifetime(coordinator) {} + } + coordinator.installQueryTask(task, owner: .claim(claim), lease: lease) + } + + // The run's authority to write: true only while its claim still owned the tab. + func settle() -> Bool { + guard let coordinator, coordinator.tabExecution.settle(claim) else { return false } + coordinator.retireQueryTask(.claim(claim)) + return true + } + + // A run that still owns what the tab shows; its claim may already be settled. + var ownsContent: Bool { + coordinator?.tabExecution.ownsContent(claim) ?? false + } + + func reportCancelled() { + coordinator?.reportEndedExecutions([ + EndedExecution(tabId: tabId, startedAt: claim.startedAt, reason: .cancelledByUser) + ]) + } + + func report(_ kind: TrackedOperationKind, _ outcome: OperationOutcome, trigger: TableLoadTrigger = .userInitiated) { + guard case .userInitiated = trigger, let coordinator else { return } + coordinator.reportOperation( + kind: kind, + claim: claim, + databaseName: coordinator.operationDatabaseName(tabId: tabId), + outcome: outcome + ) + } + + @discardableResult + func recordHistory(_ entry: RunHistoryEntry) -> Task? { + coordinator?.queryExecutionCoordinator.recordRunHistory(entry, tabId: tabId) + } +} + +struct RunHistoryEntry { + var id = UUID() + let query: String + // A statement of a script is filed with its terminator; a single run keeps the text as typed. + var terminates = false + // Nil takes the tab's: a table tab's SQL is the app's own browse, not something the user typed. + var source: QueryHistorySource? + let executionTime: TimeInterval + let rowCount: Int + var failure: String? + var planCapture: QueryPlanCapture? + var timing: PluginQueryTiming? +} diff --git a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift index ba1335db96..f87ccc80bc 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainWindowToolbar.swift @@ -213,8 +213,8 @@ internal final class MainWindowToolbar: NSObject, NSToolbarDelegate { /// also what re-runs `StatefulToolbarItem.validate()`, so the safe-mode glyph tracks the level /// through the same channel rather than through an observer of its own. /// - /// The tab manager is watched for the visibility key alone. It publishes on every edit to a - /// tab, typing included, so its observer builds the key from its eight inputs, compares it and + /// The tab manager is watched for the visibility key alone. It publishes on every tab edit + /// except plain typing, so its observer builds the key from its eight inputs, compares it and /// returns: no whole context, no validation pass and no write. private func observeItemState() { itemStateObservation = nil diff --git a/apple/TablePro/Models/Query/QueryTabManager.swift b/apple/TablePro/Models/Query/QueryTabManager.swift index d8aa4523cb..edcad8ebbe 100644 --- a/apple/TablePro/Models/Query/QueryTabManager.swift +++ b/apple/TablePro/Models/Query/QueryTabManager.swift @@ -10,16 +10,23 @@ import TableProUtilities @MainActor final class QueryTabManager: ObservableObject { - @Published var tabs: [QueryTab] = [] { - didSet { + private var _tabs: [QueryTab] = [] + + // Not @Published so the editor's keystrokes can skip the publish (`setEditorText`); every other write still sends it. + var tabs: [QueryTab] { + get { _tabs } + set { + objectWillChange.send() + let oldValue = _tabs + _tabs = newValue _tabIndexMapDirty = true _visibleTabs = nil - if oldValue.map(\.id) != tabs.map(\.id) { + if oldValue.map(\.id) != _tabs.map(\.id) { tabStructureVersion += 1 - pruneActivations(keeping: tabs) + pruneActivations(keeping: _tabs) } - publishAnchorChange(oldTabs: oldValue, newTabs: tabs) - syncTabSessionRegistry(oldTabs: oldValue, newTabs: tabs) + publishAnchorChange(oldTabs: oldValue, newTabs: _tabs) + syncTabSessionRegistry(oldTabs: oldValue, newTabs: _tabs) reconcileVisibleContainer() } } @@ -743,6 +750,25 @@ final class QueryTabManager: ObservableObject { return true } + // In place and silent unless a fact drawn from the text flips: a keystroke moves no id, anchor or container. + @discardableResult + func setEditorText(_ text: String, ofTab tabId: UUID) -> Bool { + rebuildTabIndexMapIfNeeded() + guard let index = _tabIndexMap[tabId], _tabs.indices.contains(index) else { return false } + var edited = _tabs[index] + let before = EditorTextFacts(edited) + edited.content.query = text + guard EditorTextFacts(edited) == before else { + tabs[index] = edited + return true + } + _tabs[index].content = edited.content + if let visibleIndex = _visibleTabs?.firstIndex(where: { $0.id == tabId }) { + _visibleTabs?[visibleIndex].content = edited.content + } + return true + } + func markTabRenamed(_ tabId: UUID) { guard tabs.contains(where: { $0.id == tabId }) else { return } tabStructureVersion += 1 @@ -756,6 +782,17 @@ final class QueryTabManager: ObservableObject { } } +// Run, Explain, Format, the AI actions, the unsaved dot, the pending-change badge and Tear Off read these from the text. +private struct EditorTextFacts: Equatable { + let hasQueryText: Bool + let isFileDirty: Bool + + init(_ tab: QueryTab) { + hasQueryText = tab.hasQueryText + isFileDirty = tab.content.isFileDirty + } +} + // MARK: - Visible Container extension QueryTabManager { diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index 9e6568bc13..cadbd52927 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -23,7 +23,6 @@ internal enum ContainerChangeRerunPolicy { } struct MainEditorContentView: View { - @ObservedObject private var schemaService = SchemaService.shared @ObservedObject private var featureAccess = FeatureAccess.shared @ObservedObject private var settingsManager = AppSettingsManager.shared // Must clear the nested editor/results split's required minimums, or dragging the drawer asks AppKit for an unreachable height. @@ -37,6 +36,7 @@ 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 selectedEdits: SelectedTabEdits + @ObservedObject var catalogSnapshot: ConnectionCatalogSnapshot private var changeManager: DataChangeManager { selectedEdits.manager } let connection: DatabaseConnection let windowId: UUID @@ -58,7 +58,6 @@ struct MainEditorContentView: View { @State private var queryInsightsViewModels: [UUID: QueryInsightsViewModel] = [:] @State private var tableListingModels = TableListingModelStore() - @ObservedObject private var treeService = DatabaseTreeMetadataService.shared // Table highlight rules live here, not on the tab; unobserved, Add Rule on a table tab changed nothing on screen. @ObservedObject private var highlightRuleStorage = HighlightRuleStorage.shared @@ -441,12 +440,12 @@ struct MainEditorContentView: View { switch containerSwitchTarget { case .database: return DatabaseSwitchList.sections( - databases: treeService.databases(for: connectionId), + databases: catalogSnapshot.databases, selected: SharedSidebarState.forConnection(connectionId).databaseFilterSelected, activeDatabase: containerName(for: tab) ).all case .schema: - return schemaService.schemas(for: connectionId).map { DatabaseMetadata.minimal(name: $0) } + return catalogSnapshot.schemas.map { DatabaseMetadata.minimal(name: $0) } case nil: return [] } @@ -500,16 +499,17 @@ struct MainEditorContentView: View { }, set: { newValue in // By ID: mid-switch, flushTextUpdate() fires for the old tab while selectedTabIndex already points to the new one. - guard tabManager.mutate(tabId: tabId, { $0.content.query = newValue }) else { return } + guard tabManager.setEditorText(newValue, ofTab: tabId) else { return } coordinator.scheduleDraftSave(editedTab: tabId) // Scratch tabs dirty too. Only this tab's window: a background window tab's editor stays mounted and can fire here. guard tabId == tabManager.selectedTabId, - let index = tabManager.tabs.firstIndex(where: { $0.id == tabId }), + let tab = tabManager.tabs.first(where: { $0.id == tabId }), let window = coordinator.contentWindow else { return } - let showsIndicator = coordinator.showsUnsavedIndicator(for: tabManager.tabs[index]) + let showsIndicator = coordinator.showsUnsavedIndicator(for: tab) Task { @MainActor in + guard window.isDocumentEdited != showsIndicator else { return } window.isDocumentEdited = showsIndicator } } @@ -556,7 +556,7 @@ struct MainEditorContentView: View { InlineErrorBanner( message: error.message, onFixWithAI: coordinator.aiQueryActionAvailability(for: tab).isVisible - ? { coordinator.fixErrorWithAI(query: error.query ?? tab.content.query, error: error.message) } + ? { fixWithAI(error, inTab: tab) } : nil, onDismiss: error.isDismissible ? { @@ -571,6 +571,12 @@ struct MainEditorContentView: View { } } + // Read at click time: typing does not rebuild this view, so the captured tab's text can be stale. + private func fixWithAI(_ error: QueryTabError, inTab tab: QueryTab) { + let current = tabManager.tabs.first(where: { $0.id == tab.id }) ?? tab + coordinator.fixErrorWithAI(query: error.query ?? current.content.query, error: error.message) + } + private func structureScope(for tab: QueryTab) -> DatabaseScope? { coordinator.scope(for: tab) } @@ -972,7 +978,7 @@ struct MainEditorContentView: View { onCancel: { coordinator.stopExecution(for: tab.id) } ), selectionSummary: coordinator.selectionSummary, - isRefreshingSchema: schemaService.isRefreshing(connectionId: connectionId), + isRefreshingSchema: catalogSnapshot.isRefreshing, viewMode: resultsViewModeBinding(for: tab), resultSetMenu: resultSetMenuModel(for: tab, placedIn: .statusBar), resultSetActions: resultSetActions(for: tab), @@ -1191,11 +1197,11 @@ extension MainEditorContentView { vimMode: vimMode, showsHistoryTip: showsHistoryTip, onAIAction: { action in coordinator.runAIQueryAction(action, target: .selectionOrStatementAtCursor) }, - onRun: { coordinator.runQuery(viewport: .firstRow) }, - onRunAllStatements: { coordinator.runAllStatements() }, - onRunWithoutLimit: { coordinator.runQuery(viewport: .firstRow, bypassRowLimit: true) }, + onRun: { coordinator.runQuery(onTab: tab.id, viewport: .firstRow) }, + onRunAllStatements: { coordinator.runAllStatements(onTab: tab.id) }, + onRunWithoutLimit: { coordinator.runQuery(onTab: tab.id, viewport: .firstRow, bypassRowLimit: true) }, onStop: { coordinator.stopExecution(for: tab.id) }, - onExplain: { variant in coordinator.runExplain(variant: variant) }, + onExplain: { variant in coordinator.runExplain(onTab: tab.id, variant: variant) }, onFormat: { EditorEventRouter.shared.performFormatSQLForKeyWindow() }, onSaveAsFavorite: { coordinator.saveCurrentQueryAsFavorite() }, onClearQuery: { coordinator.commandActions?.clearQuery() }, @@ -1238,11 +1244,11 @@ extension MainEditorContentView { onCloseTab: { coordinator.commandActions?.closeTab() }, - onExecuteQuery: { coordinator.runQuery(viewport: .firstRow) }, + onExecuteQuery: { coordinator.runQuery(onTab: tab.id, viewport: .firstRow) }, onSelectTab: { number in coordinator.commandActions?.selectTab(number: number) }, onSelectAdjacentTab: { offset in coordinator.commandActions?.selectTab(offsetBy: offset) }, tabCount: { coordinator.tabManager.visibleTabs.count }, - onRunStatement: { sql, offset in coordinator.runStatement(sql, sourceOffset: offset) }, + onRunStatement: { sql, offset in coordinator.runStatement(sql, sourceOffset: offset, onTab: tab.id) }, isExecuting: isExecuting, currentAIAvailability: { coordinator.aiQueryActionAvailability }, onAIAction: { action, target in coordinator.runAIQueryAction(action, target: target) }, diff --git a/apple/TablePro/Views/Main/ConnectionCatalogSnapshot.swift b/apple/TablePro/Views/Main/ConnectionCatalogSnapshot.swift new file mode 100644 index 0000000000..ea71bbac65 --- /dev/null +++ b/apple/TablePro/Views/Main/ConnectionCatalogSnapshot.swift @@ -0,0 +1,50 @@ +// +// ConnectionCatalogSnapshot.swift +// TablePro +// + +import Combine +import Foundation + +// The services key every list by connection, so observing them re-rendered every window on any connection's load. +@MainActor +final class ConnectionCatalogSnapshot: ObservableObject { + @Published private(set) var tables: [TableInfo] + @Published private(set) var schemas: [String] + @Published private(set) var isRefreshing: Bool + @Published private(set) var databases: [DatabaseMetadata] + + let connectionId: UUID + private let schemaService: SchemaService + private let treeService: DatabaseTreeMetadataService + private var observations: [AnyCancellable] = [] + + init(connectionId: UUID, schemaService: SchemaService, treeService: DatabaseTreeMetadataService) { + self.connectionId = connectionId + self.schemaService = schemaService + self.treeService = treeService + tables = schemaService.tables(for: connectionId) + schemas = schemaService.schemas(for: connectionId) + isRefreshing = schemaService.isRefreshing(connectionId: connectionId) + databases = treeService.databases(for: connectionId) + observations = [ + schemaService.onMainActorChange { [weak self] in self?.readSchemaService() }, + treeService.onMainActorChange { [weak self] in self?.readTreeService() } + ] + } + + // Each write is guarded: an unguarded @Published write publishes an equal value too. + private func readSchemaService() { + let tables = schemaService.tables(for: connectionId) + if tables != self.tables { self.tables = tables } + let schemas = schemaService.schemas(for: connectionId) + if schemas != self.schemas { self.schemas = schemas } + let isRefreshing = schemaService.isRefreshing(connectionId: connectionId) + if isRefreshing != self.isRefreshing { self.isRefreshing = isRefreshing } + } + + private func readTreeService() { + let databases = treeService.databases(for: connectionId) + if databases != self.databases { self.databases = databases } + } +} diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCommandActions+FileSaving.swift b/apple/TablePro/Views/Main/Extensions/MainContentCommandActions+FileSaving.swift index 1ed52c735f..66c0a1b483 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCommandActions+FileSaving.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCommandActions+FileSaving.swift @@ -34,7 +34,7 @@ extension MainContentCommandActions { switch change { case .missing: Self.fileLogger.info("Save of a file no longer on disk went to Save As: \(url.lastPathComponent, privacy: .private(mask: .hash))") - return await saveFileAsAwaiting() + return await saveFileAsAwaiting(forTab: tab.id) case .modified: requestConflictResolution(tab: tab, url: url) return false @@ -58,7 +58,7 @@ extension MainContentCommandActions { return false } catch { Self.fileLogger.error("Failed to save file: \(error.publicLogShape, privacy: .public)") - return await saveFileAsAwaiting() + return await saveFileAsAwaiting(forTab: tabId) } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+AutoRefresh.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+AutoRefresh.swift index 474224b02a..c77abe9c0c 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+AutoRefresh.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+AutoRefresh.swift @@ -138,7 +138,7 @@ extension MainContentCoordinator { recordAutoRefreshPause(nil, forTab: tabId) } // Not runQuery, which commits an open edit, nor reloadTableTab, which retires the count. - if let load = executeTableTabQueryDirectly(trigger: .autoRefresh, viewport: .keepPlace) + if let load = executeTableTabQueryDirectly(onTab: tabId, trigger: .autoRefresh, viewport: .keepPlace) ?? queryTasks.task(for: tabId) { await load.value } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift index 6f4dbaecda..77c015e5ef 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift @@ -11,33 +11,43 @@ extension MainContentCoordinator { action: DiscardAction, completion: @escaping (Bool) -> Void ) { - commitActiveGridEdit() - guard changeManager.hasChanges else { - completion(true) - return - } - - guard !isShowingConfirmAlert else { - completion(false) - return - } + confirmDiscard(forTab: tabManager.selectedTabId, action: action, restoringRows: false, completion: completion) + } - Task { - let confirmed = await confirmDiscardChanges(action: action, window: contentWindow) - if confirmed { - changeManager.clearChangesAndUndoHistory() - } - completion(confirmed) - } + func confirmDiscardChangesIfNeeded( + forTab tabId: UUID, + action: DiscardAction, + completion: @escaping (Bool) -> Void + ) { + confirmDiscard(forTab: tabId, action: action, restoringRows: false, completion: completion) } // Not the plain gate: a value filter keeps the loaded rows, so edited values would stay on screen untracked (#2667). func confirmDiscardRestoringRowsIfNeeded( action: DiscardAction, completion: @escaping (Bool) -> Void + ) { + confirmDiscard(forTab: tabManager.selectedTabId, action: action, restoringRows: true, completion: completion) + } + + func confirmDiscardRestoringRowsIfNeeded( + forTab tabId: UUID, + action: DiscardAction, + completion: @escaping (Bool) -> Void + ) { + confirmDiscard(forTab: tabId, action: action, restoringRows: true, completion: completion) + } + + // The tab is fixed before the alert: the selection can move while it is up, and its edits are the ones asked about. + private func confirmDiscard( + forTab tabId: UUID?, + action: DiscardAction, + restoringRows: Bool, + completion: @escaping (Bool) -> Void ) { commitActiveGridEdit() - guard changeManager.hasChanges else { + let manager = tabId.map { changeManager(forTab: $0) } ?? changeManager + guard manager.hasChanges else { completion(true) return } @@ -49,11 +59,21 @@ extension MainContentCoordinator { Task { let confirmed = await confirmDiscardChanges(action: action, window: contentWindow) - if confirmed { - rowEditingCoordinator.restoreRowBufferToOriginals() - changeManager.clearChangesAndUndoHistory() + guard confirmed else { + completion(false) + return + } + if let tabId { + guard tabManager.tabs.contains(where: { $0.id == tabId }) else { + completion(false) + return + } + if restoringRows { + rowEditingCoordinator.restoreRowBufferToOriginals(forTab: tabId) + } } - completion(confirmed) + manager.clearChangesAndUndoHistory() + completion(true) } } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnFetchScope.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnFetchScope.swift index 017d9f3cf7..604a4a64a6 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnFetchScope.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnFetchScope.swift @@ -71,7 +71,7 @@ extension MainContentCoordinator { tab.valueFilter.activeColumns.compactMap { tab.valueFilter.columnName(forColumn: $0) } } - func requeryWithColumnScope(debounced: Bool = false) { + func requeryWithColumnScope(forTab tabId: UUID, debounced: Bool = false) { columnScopeRequeryTask?.cancel() columnScopeRequeryTask = Task { @MainActor [weak self] in guard let self else { return } @@ -79,19 +79,17 @@ extension MainContentCoordinator { try? await Task.sleep(for: .milliseconds(250)) guard !Task.isCancelled else { return } } - guard await self.rebuildSelectedTableColumnScopedQuery() else { return } - self.runQuery(viewport: .keepPlace) + guard await self.rebuildColumnScopedQuery(forTab: tabId) else { return } + self.runQuery(onTab: tabId, viewport: .keepPlace) } } - /// Re-resolves the tab by id after the await. An index taken before it points at whatever tab - /// occupies that slot now, which after a close or a reorder is a different tab entirely. + // Re-resolves the tab by id after the await: an index taken before it can name another tab after a close or reorder. @discardableResult - func rebuildSelectedTableColumnScopedQuery() async -> Bool { - guard let tab = tabManager.selectedTab, + func rebuildColumnScopedQuery(forTab tabId: UUID) async -> Bool { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }), tab.tabType == .table, let tableName = tab.tableContext.tableName else { return false } - let tabId = tab.id await loadSchemaColumns(for: tableName, scope: scope(for: tab)) guard !Task.isCancelled, let index = tabManager.tabs.firstIndex(where: { $0.id == tabId }), diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnVisibility.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnVisibility.swift index 543e5a7ecc..95e2d6d3c1 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnVisibility.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnVisibility.swift @@ -44,10 +44,11 @@ extension MainContentCoordinator { // Confirms like sort, pagination and the WHERE filter: re-running with a new column list drops unsaved edits (#2667). private func changeColumnScope(_ mutate: @escaping (inout Set) -> Void) { - confirmDiscardRestoringRowsIfNeeded(action: .columnVisibility) { [weak self] confirmed in + guard let tabId = tabManager.selectedTabId else { return } + confirmDiscardRestoringRowsIfNeeded(forTab: tabId, action: .columnVisibility) { [weak self] confirmed in guard confirmed, let self else { return } - self.mutateSelectedTabHiddenColumns(mutate) - self.requeryWithColumnScope(debounced: true) + self.mutateHiddenColumns(ofTab: tabId, mutate) + self.requeryWithColumnScope(forTab: tabId, debounced: true) } } @@ -96,14 +97,15 @@ extension MainContentCoordinator { // Clearing the hidden set re-queries, so reset confirms too; declining keeps the width reset, since widths cannot void edits. func resetColumns() { - confirmDiscardRestoringRowsIfNeeded(action: .columnVisibility) { [weak self] confirmed in + guard let tabId = tabManager.selectedTabId else { return } + confirmDiscardRestoringRowsIfNeeded(forTab: tabId, action: .columnVisibility) { [weak self] confirmed in guard confirmed, let self else { return } - self.applyColumnReset() + self.applyColumnReset(toTab: tabId) } } - private func applyColumnReset() { - guard let index = tabManager.selectedTabIndex else { return } + private func applyColumnReset(toTab tabId: UUID) { + guard let index = tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } let tab = tabManager.tabs[index] // Through the model, which rebuilds its columns: a query tab's requery reloads nothing, so it alone shows them again. if let entry = dataGridEntries[tab.id] { @@ -114,7 +116,7 @@ extension MainContentCoordinator { FileColumnLayoutPersister.shared.clear(for: key) } tabManager.mutate(at: index) { $0.columnLayout = ColumnLayoutState() } - requeryWithColumnScope(debounced: false) + requeryWithColumnScope(forTab: tabId, debounced: false) } // A temporary table's layout is not kept: the key would be the permanent table's of the same name. @@ -134,7 +136,7 @@ extension MainContentCoordinator { guard let tab = tabManager.selectedTab, !tab.columnLayout.hiddenColumns.isEmpty else { return } - await rebuildSelectedTableColumnScopedQuery() + await rebuildColumnScopedQuery(forTab: tab.id) } private func persistTabHiddenColumns(_ tab: QueryTab) { @@ -143,7 +145,12 @@ extension MainContentCoordinator { } private func mutateSelectedTabHiddenColumns(persist: Bool = true, _ mutate: (inout Set) -> Void) { - guard let index = tabManager.selectedTabIndex else { return } + guard let tabId = tabManager.selectedTabId else { return } + mutateHiddenColumns(ofTab: tabId, persist: persist, mutate) + } + + private func mutateHiddenColumns(ofTab tabId: UUID, persist: Bool = true, _ mutate: (inout Set) -> Void) { + guard let index = tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } var hidden = tabManager.tabs[index].columnLayout.hiddenColumns mutate(&hidden) guard hidden != tabManager.tabs[index].columnLayout.hiddenColumns else { return } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift index 6421fa5ef7..c4d58ff3b5 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift @@ -18,7 +18,7 @@ extension MainContentCoordinator { internal func changeQueryContainer(of tabId: UUID, to name: String, target: ContainerSwitchTarget?) { guard canChangeContainer(of: tabId, to: name) else { return } // Asked before the tab moves, so Cancel leaves the staged edits with the database their rows came from. - confirmDiscardRestoringRowsIfNeeded(action: .containerChange) { [weak self] confirmed in + confirmDiscardRestoringRowsIfNeeded(forTab: tabId, action: .containerChange) { [weak self] confirmed in guard confirmed, let self, canChangeContainer(of: tabId, to: name) else { return } retargetTab(tabId) guard tabManager.mutate(tabId: tabId, { tab in @@ -28,9 +28,10 @@ extension MainContentCoordinator { }) else { return } tabManager.markTabRenamed(tabId) SchemaProviderRegistry.shared.reclaimUnheldProviders(for: connectionId) - guard ContainerChangeRerunPolicy.reruns(showing: tabManager.selectedTab?.display.activeResultSet) else { return } + let rebound = tabManager.tabs.first { $0.id == tabId } + guard ContainerChangeRerunPolicy.reruns(showing: rebound?.display.activeResultSet) else { return } // The statement at the caret may not be the one that produced the rows, so a write asks first. - runQuery(viewport: .firstRow, extraCapabilities: .confirmsWrites) + runQuery(onTab: tabId, viewport: .firstRow, extraCapabilities: .confirmsWrites) } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift index dae3b24d50..f3187fbf30 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift @@ -6,23 +6,6 @@ import Foundation extension MainContentCoordinator { - func runAllStatements(extraCapabilities: CallerCapabilities = []) { - guard let tab = tabManager.selectedTabAndIndex?.tab, tab.tabType == .query, - !tabExecution.isExecuting(tab.id) else { return } - confirmRunDiscard(onTab: tab.id) { [weak self] in - guard let self else { return } - flushEditorText(forTab: tab.id) - queryExecutionCoordinator.runAllStatements(extraCapabilities: extraCapabilities) - } - } - - // A run authorized for a tab stays on it; nil is the selected tab. - func executionTab(_ tabId: UUID?) -> (tab: QueryTab, index: Int)? { - guard let tabId else { return tabManager.selectedTabAndIndex } - guard let index = tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return nil } - return (tabManager.tabs[index], index) - } - // A run replaces the result the staged edits belong to. A tab with no result has none of its own: // for a turn after a switch the change manager still holds the outgoing tab's. func confirmRunDiscard(onTab tabId: UUID, then run: @escaping () -> Void) { @@ -31,7 +14,7 @@ extension MainContentCoordinator { run() return } - confirmDiscardRestoringRowsIfNeeded(action: .run) { [weak self] confirmed in + confirmDiscardRestoringRowsIfNeeded(forTab: tabId, action: .run) { [weak self] confirmed in guard let self, confirmed, tabManager.selectedTabId == tabId, !tabExecution.isExecuting(tabId) else { return } run() } @@ -40,34 +23,4 @@ extension MainContentCoordinator { func flushEditorText(forTab tabId: UUID) { EditorEventRouter.shared.flushPendingText(forTab: tabId, connectionId: connectionId) } - - internal func dispatchBatches( - _ batches: [ExecutableBatch], - tabIndex index: Int, - bypassRowLimit: Bool = false, - extraCapabilities: CallerCapabilities = [] - ) { - queryExecutionCoordinator.dispatchBatches( - batches, - tabIndex: index, - bypassRowLimit: bypassRowLimit, - extraCapabilities: extraCapabilities - ) - } - - internal func dispatchParameterizedBatches( - _ batches: [ExecutableBatch], - parameters: [QueryParameter], - tabIndex index: Int, - bypassRowLimit: Bool = false, - extraCapabilities: CallerCapabilities = [] - ) { - queryExecutionCoordinator.dispatchParameterizedBatches( - batches, - parameters: parameters, - tabIndex: index, - bypassRowLimit: bypassRowLimit, - extraCapabilities: extraCapabilities - ) - } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift index 1712b38a27..ba73ef1963 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Explain.swift @@ -14,21 +14,21 @@ import TableProSQLGrammar extension MainContentCoordinator { @discardableResult - func runExplain(variant: ExplainVariant? = nil) -> Task? { - guard let tabId = tabManager.selectedTabId else { return nil } + func runExplain(onTab tabId: UUID, variant: ExplainVariant? = nil) -> Task? { + guard tabManager.selectedTab?.id == tabId else { return nil } // Nil when the discard prompt has to ask first: the plan follows the answer. var started: Task? confirmRunDiscard(onTab: tabId) { [weak self] in - started = self?.startExplain(variant: variant) + started = self?.startExplain(variant: variant, onTab: tabId) } return started } - private func startExplain(variant: ExplainVariant?) -> Task? { - if let tabId = tabManager.selectedTabId { flushEditorText(forTab: tabId) } - guard let (tab, index) = tabManager.selectedTabAndIndex else { return nil } - guard !tabExecution.isExecuting(tab.id) else { - traceExecutionBlocked(tabId: tab.id, site: "runExplain") + private func startExplain(variant: ExplainVariant?, onTab tabId: UUID) -> Task? { + flushEditorText(forTab: tabId) + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return nil } + guard !tabExecution.isExecuting(tabId) else { + traceExecutionBlocked(tabId: tabId, site: "runExplain") return nil } guard !isShowingSafeModePrompt else { return nil } @@ -40,22 +40,23 @@ extension MainContentCoordinator { databaseType: connection.type, statement: statement.sql ) else { - tabManager.mutate(at: index) { + tabManager.mutate(tabId: tabId) { $0.execution.errorMessage = String( localized: "EXPLAIN is not supported for this database type." ) } return nil } + guard let target = queryExecutionCoordinator.runTarget(onTab: tabId) else { return nil } isShowingSafeModePrompt = true - let tabId = tab.id let authorization = authorizationRequest(for: request, runsIn: scope(for: tab)) return Task { defer { isShowingSafeModePrompt = false } switch await executionGate.authorize(authorization) { case .authorized: - executeExplain(request, anchor: anchor, tabId: tabId) + guard queryExecutionCoordinator.stillHolds(target) else { return } + queryExecutionCoordinator.executeExplain(request, anchor: anchor, onTab: tabId) case .denied(let reason, .policy): tabManager.mutate(tabId: tabId) { $0.execution.errorMessage = reason } case .denied(_, .cancelledByUser): @@ -103,190 +104,4 @@ extension MainContentCoordinator { .first? .offset(by: sourceOffset) } - - // MARK: - Execution - - private func executeExplain(_ request: ExplainRequest, anchor: StatementAnchor?, tabId: UUID) { - guard let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return } - guard let scope = scope(for: tab) else { - tabManager.mutate(tabId: tabId) { - $0.execution.errorMessage = String(localized: "Not connected to database") - } - return - } - - let (claim, lease) = beginTabExecution(for: tabId) - let conn = connection - let safeModeIsReadOnly = runsAtReadOnly - - tabManager.mutate(tabId: tabId) { $0.execution.errorMessage = nil } - - // EXPLAIN ANALYZE and an actual plan run the statement, and a CREATE TABLE AS among them changes the catalog. - // Under Manual Commit such a run is held, as the write itself would be. - let ranWrite = request.operationKind(databaseType: conn.type).declaresWrite - let failureOutput = ServerOutputBox() - let explainTask = Task { [weak self] in - guard let self else { return } - do { - let fetchResult = try await services.databaseManager.withScopedDriver( - scope: scope, - route: services.databaseManager.executionRoute(for: scope), - 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 - if let step = request.driverStep { - return try await QueryExecutor.fetchExplainPlan( - driver: driver, statement: request.subjectSQL, variantId: step.variantId - ) - } - return try await queryExecutor.executeQuery( - driver: driver, sql: request.sql, parameters: nil, rowCap: nil, safeModeIsReadOnly: safeModeIsReadOnly - ) - } - } - } - if ranWrite { Self.postStatementRan(request.subjectSQL, on: conn) } - let rawText = ExplainPlanTextFlattener.flatten(rows: fetchResult.rows) - let plan = ExplainPlanParserRegistry.plan(from: rawText, format: request.format) - - await MainActor.run { [weak self] in - guard let self else { return } - - // Every write below belongs to whoever owns the tab now. A superseded plan - // that cleared the spinner or nilled the task handle would be reporting on a - // query that is still running, so the gate comes before all of them. - guard tabExecution.settle(claim) else { return } - retireQueryTask(.claim(claim)) - guard !Task.isCancelled else { - reportEndedExecutions([ - EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) - ]) - return - } - - reportOperation( - kind: .query, - claim: claim, - databaseName: operationDatabaseName(tabId: tabId), - outcome: .succeeded(OperationSummary()) - ) - /// The same builder and the same database and schema the history row uses, so a - /// plan captured here and one captured from a hand-typed EXPLAIN land in one - /// chain instead of two that never compare. - let historyId = UUID() - let captured = QueryPlanCaptureBuilder.make( - subjectSQL: request.subjectSQL, - rawPlan: rawText, - format: request.format, - variantKey: request.variantKey, - scope: QueryPlanScope( - connectionId: conn.id, - databaseType: conn.type, - databaseName: queryExecutionCoordinator.historyDatabaseName(tabId: tabId), - schemaName: queryExecutionCoordinator.historySchemaName(tabId: tabId) - ), - executionTime: fetchResult.executionTime, - capturedAt: Date(), - historyId: historyId, - queryParameters: nil - ) - flushBufferToActiveResult(tabId: tabId, pinnedOnly: true) - tabManager.mutate(tabId: tabId) { tab in - tab.execution.executionTime = fetchResult.executionTime - tab.execution.rowsAffected = 0 - tab.execution.statusMessage = nil - tab.execution.lastExecutedAt = Date() - tab.pagination.resetLoadMore() - tab.display.replaceUnpinnedResults( - with: [ExplainResultSetFactory.make( - rawText: rawText, - plan: plan, - sql: request.replayableSQL, - executionTime: fetchResult.executionTime, - anchor: anchor, - planContext: captured.context, - serverOutput: fetchResult.serverOutput - )] - ) - if tab.display.isResultsCollapsed { - tab.display.isResultsCollapsed = false - } - } - seedBufferFromActiveResult(tabId: tabId) - dropEdits(ofReplacedResultIn: tabId) - toolbarState.isResultsCollapsed = false - - recordHistory( - QueryHistoryRecordRequest( - id: historyId, - query: request.sql, - connectionId: conn.id, - databaseName: captured.context.identity.scope.databaseName, - databaseType: conn.type, - schemaName: captured.context.identity.scope.schemaName, - source: .explain, - executionTime: fetchResult.executionTime, - rowCount: fetchResult.rows.count, - wasSuccessful: true, - planCapture: captured.capture - ) - ) - } - } catch { - if ranWrite { Self.postStatementRan(request.subjectSQL, on: conn) } - await MainActor.run { [weak self] in - guard let self else { return } - guard tabExecution.settle(claim) else { return } - retireQueryTask(.claim(claim)) - - // A cancelled EXPLAIN is not a failure the user needs told about, and it does - // not belong in history either. - if DatabaseCancellationDiagnosis.isCancellation(error) || Task.isCancelled { - reportEndedExecutions([ - EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) - ]) - return - } - - reportOperation( - kind: .query, - claim: claim, - databaseName: operationDatabaseName(tabId: tabId), - outcome: .failed(reason: error.localizedDescription) - ) - - tabManager.mutate(tabId: tabId) { tab in - tab.execution.errorMessage = ServerOutputCapture.failureMessage( - error.localizedDescription, output: failureOutput.output - ) - tab.execution.lastExecutedAt = Date() - if tab.display.isResultsCollapsed { - tab.display.isResultsCollapsed = false - } - } - if tabManager.selectedTabId == tabId { - toolbarState.isResultsCollapsed = false - announceQueryError(error.localizedDescription) - } - - recordHistory( - QueryHistoryRecordRequest( - query: request.sql, - connectionId: conn.id, - databaseName: queryExecutionCoordinator.historyDatabaseName(tabId: tabId), - databaseType: conn.type, - schemaName: queryExecutionCoordinator.historySchemaName(tabId: tabId), - source: .explain, - executionTime: 0, - rowCount: -1, - wasSuccessful: false, - errorMessage: error.localizedDescription - ) - ) - } - } - } - installQueryTask(explainTask, owner: .claim(claim), lease: lease) - } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+FKNavigation.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+FKNavigation.swift index ebc823b1b9..5a09f6b069 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+FKNavigation.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+FKNavigation.swift @@ -191,14 +191,15 @@ extension MainContentCoordinator { return nil } - // One discard guard: applyFilters deferred behind the alert but setFKFilter didn't, so a refusal left a stale filter. + // One discard guard over the filter and the history entry, so a refusal writes neither. private func refilterSelectedTab(with filter: TableFilter, showsReferenceAlready: Bool) { + guard let tabId = tabManager.selectedTabId else { return } // Not recorded when the tab already shows this reference, or Back would step through identical entries. let departing = showsReferenceAlready ? nil : captureNavigationEntry() - confirmDiscardChangesIfNeeded(action: .filter) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .filter) { [weak self] confirmed in guard let self, confirmed else { return } - filterCoordinator.commitReferenceFilter(filter) - commitNavigationEntry(departing) + filterCoordinator.commitReferenceFilter(filter, forTab: tabId) + commitNavigationEntry(departing, inTab: tabId) } } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+FilterState.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+FilterState.swift index 64f2d425af..72d023e36d 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+FilterState.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+FilterState.swift @@ -37,7 +37,7 @@ extension MainContentCoordinator { func applyCellFilter(_ filter: TableFilter, forTab tabId: UUID) { guard tabManager.selectedTab?.id == tabId else { return } - filterCoordinator.applyCellFilter(filter) + filterCoordinator.applyCellFilter(filter, forTab: tabId) } func toggleFilterPanel() { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Filtering.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Filtering.swift index 87e1361485..e0ae134256 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Filtering.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Filtering.swift @@ -46,4 +46,8 @@ extension MainContentCoordinator { func rebuildTableQuery(at tabIndex: Int) { filterCoordinator.rebuildTableQuery(at: tabIndex) } + + func rebuildTableQuery(forTab tabId: UUID) { + filterCoordinator.rebuildTableQuery(forTab: tabId) + } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Masking.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Masking.swift index 3062dd7eda..276fec1e9a 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Masking.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Masking.swift @@ -97,16 +97,18 @@ extension MainContentCoordinator { ) async { guard let tab = tabManager.tabs.first(where: { $0.id == tabId }), !tab.revealsMaskedValues else { return } guard await authenticator.authenticate(reason: Self.revealMaskedValuesReason) else { return } - tabManager.mutate(tabId: tabId) { $0.revealsMaskedValues = true } - guard tabManager.selectedTabId == tabId else { return } - switch tab.tabType { + // Read again after the prompt: the editor text, or the tab itself, may have changed while it was up. + guard tabManager.mutate(tabId: tabId, { $0.revealsMaskedValues = true }), + tabManager.selectedTabId == tabId, + let revealed = tabManager.tabs.first(where: { $0.id == tabId }) else { return } + switch revealed.tabType { case .table: - runQuery(viewport: .keepPlace) + runQuery(onTab: tabId, viewport: .keepPlace) default: // Running a query tab again could repeat a write, so only a read reruns; anything else shows on its next run. - let classification = QueryClassifier.classify(tab.content.query, databaseType: connection.type) + let classification = QueryClassifier.classify(revealed.content.query, databaseType: connection.type) guard classification.tier == .safe else { return } - runQuery(viewport: .keepPlace) + runQuery(onTab: tabId, viewport: .keepPlace) } } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift index ecd1426d4c..c66b07c690 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift @@ -144,9 +144,9 @@ extension MainContentCoordinator { databaseName: currentDatabase, schemaName: resolvedSchema ) - if replaced { + if replaced, let tabId = tabManager.selectedTabId { clearFilterState() - discardRowsForRetarget() + discardRowsForRetarget(ofTab: tabId) restoreLastHiddenColumnsForTable() restoreFiltersForSelectedTab() if let dbIndex = Int(currentDatabase) { @@ -357,9 +357,11 @@ extension MainContentCoordinator { return false } if let token { TableLoadTracer.shared.stage(.replaceTabContent, token: token) } - commitNavigationEntry(departing) - clearFilterState() - discardRowsForRetarget(resultsViewMode: showStructure ? .structure : .data) + if let tabId = tabManager.selectedTabId { + commitNavigationEntry(departing, inTab: tabId) + clearFilterState() + discardRowsForRetarget(ofTab: tabId, resultsViewMode: showStructure ? .structure : .data) + } restoreLastHiddenColumnsForTable() restoreFiltersForSelectedTab() if let tabId = tabManager.selectedTab?.id { @@ -375,17 +377,11 @@ extension MainContentCoordinator { return true } - /// Drops the outgoing table's rows and says, in the same step, that a load is running. - /// - /// The two belong together. A cleared buffer that nothing has called a load is what the status - /// bar reads as "this tab has no result", and it removes every control that depends on one, so - /// the bar collapses and then refills as the fetch lands. The execution claim cannot stand in - /// for the flag: retargeting only schedules the load, so the claim arrives a main-actor turn - /// later and leaves a renderable frame in between. - func discardRowsForRetarget(resultsViewMode: ResultsViewMode? = nil) { - guard let (tab, tabIndex) = tabManager.selectedTabAndIndex else { return } - setActiveTableRows(TableRows(), for: tab.id) - tabManager.mutate(at: tabIndex) { tab in + // Marks the load in the same step: a cleared buffer with no load is "no result" to the status bar, which collapses until the fetch lands. + func discardRowsForRetarget(ofTab tabId: UUID, resultsViewMode: ResultsViewMode? = nil) { + guard tabManager.tabs.contains(where: { $0.id == tabId }) else { return } + setActiveTableRows(TableRows(), for: tabId) + tabManager.mutate(tabId: tabId) { tab in if let resultsViewMode { tab.display.resultsViewMode = resultsViewMode } @@ -770,10 +766,12 @@ extension MainContentCoordinator { } guard !Task.isCancelled else { return } toolbarState.currentDatabase = database - if let tabId, tabManager.selectedTabId != tabId { - declineTableLoad(for: tabId) - } else { - executeTableTabQueryDirectly(viewport: .firstRow) + if let tabId { + if tabManager.selectedTabId != tabId { + declineTableLoad(for: tabId) + } else { + executeTableTabQueryDirectly(onTab: tabId, viewport: .firstRow) + } } loadRedisKeyTree(databaseIndex: dbIndex) @@ -827,6 +825,7 @@ extension MainContentCoordinator { initialQuery: RedisKeyTreeCommand.openKey(keyName, keyType: keyType, inDatabase: databaseIndex), title: keyName ) - runQuery(viewport: .firstRow) + guard let tabId = tabManager.selectedTabId else { return } + runQuery(onTab: tabId, viewport: .firstRow) } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+NavigationHistory.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+NavigationHistory.swift index 75bddf5a99..2ebb3f2e0f 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+NavigationHistory.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+NavigationHistory.swift @@ -64,8 +64,8 @@ extension MainContentCoordinator { } // Only in-place retargets record; a jump that opens its own tab leaves the source open and starts with an empty history. - func commitNavigationEntry(_ entry: TabNavigationEntry?) { - guard let entry, let tabId = tabManager.selectedTabId else { return } + func commitNavigationEntry(_ entry: TabNavigationEntry?, inTab tabId: UUID) { + guard let entry, tabManager.tabs.contains(where: { $0.id == tabId }) else { return } navigationHistories[tabId, default: TabNavigationHistory()].record(entry) } @@ -101,16 +101,18 @@ extension MainContentCoordinator { // Captures before the discard guard: discarding keeps edited values in `TableRows`, so a later capture anchors on dropped keys. private func step(back: Bool) { + guard let tabId = tabManager.selectedTabId else { return } let departing = captureNavigationEntry() - confirmDiscardChangesIfNeeded(action: .navigation) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .navigation) { [weak self] confirmed in guard confirmed else { return } - self?.commitStep(back: back, from: departing) + self?.commitStep(back: back, from: departing, inTab: tabId) } } // Stacks change on a copy, written back only once the restore lands, so a failed retarget leaves the history untouched. - private func commitStep(back: Bool, from departing: TabNavigationEntry?) { - guard let tabId = navigableTabId, + private func commitStep(back: Bool, from departing: TabNavigationEntry?, inTab tabId: UUID) { + // The restore retargets the selected tab, so a step whose tab lost the selection behind the alert stops. + guard navigableTabId == tabId, var history = navigationHistories[tabId], let current = departing else { return } guard let entry = back ? history.stepBack(from: current) : history.stepForward(from: current) else { @@ -144,11 +146,10 @@ extension MainContentCoordinator { return false } - discardRowsForRetarget(resultsViewMode: entry.resultsViewMode) - guard let (tab, tabIndex) = tabManager.selectedTabAndIndex, tab.id == tabId else { return false } + discardRowsForRetarget(ofTab: tabId, resultsViewMode: entry.resultsViewMode) // Always carry the page: `replaceTabContent` resets to the default page size, so a recorded page would come back resized. - tabManager.mutate(at: tabIndex) { tab in + guard tabManager.mutate(tabId: tabId, { tab in tab.filterState = entry.filterState tab.pendingRestoredSort = entry.sortColumns.isEmpty ? nil : entry.sortColumns tab.restoredSortSource = entry.sortSource @@ -158,10 +159,10 @@ extension MainContentCoordinator { tab.restoredPage = max(1, entry.page) tab.restoredPageSize = entry.pageSize tab.restoredRowAnchor = entry.anchorRowKey - } + }) else { return false } restoreLastHiddenColumnsForTable() - filterCoordinator.rebuildTableQuery(at: tabIndex) + filterCoordinator.rebuildTableQuery(forTab: tabId) cancelTableLoad(for: tabId) lazyLoadCurrentTabIfNeeded() return true diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift index a2347a5a70..397f1c5248 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryHelpers.swift @@ -62,7 +62,8 @@ extension MainContentCoordinator { isAutoLoad: Bool, trigger: TableLoadTrigger, traceToken: TableLoadTraceToken?, - serverOutput: PluginServerOutput = .none + serverOutput: PluginServerOutput = .none, + historySource: QueryHistorySource? = nil ) { guard tabExecution.settle(claim) else { reportStopRollback(error, tabId: tabId) @@ -89,7 +90,10 @@ extension MainContentCoordinator { parkedTableLoad = ParkedTableLoad(tabId: tabId, trigger: trigger) return } - handleQueryExecutionError(error, sql: sql, tabId: tabId, connection: conn, serverOutput: serverOutput, trigger: trigger) + handleQueryExecutionError( + error, sql: sql, tabId: tabId, connection: conn, serverOutput: serverOutput, trigger: trigger, + historySource: historySource + ) reportQueryOperation( claim: claim, trigger: trigger, outcome: .failed(reason: error.localizedDescription) ) @@ -270,7 +274,8 @@ extension MainContentCoordinator { tabId: UUID, connection conn: DatabaseConnection, serverOutput: PluginServerOutput = .none, - trigger: TableLoadTrigger = .userInitiated + trigger: TableLoadTrigger = .userInitiated, + historySource: QueryHistorySource? = nil ) { queryExecutionCoordinator.handleQueryExecutionError( error, @@ -278,7 +283,8 @@ extension MainContentCoordinator { tabId: tabId, connection: conn, serverOutput: serverOutput, - trigger: trigger + trigger: trigger, + historySource: historySource ) } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryRouting.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryRouting.swift index 7a0405359a..977a0a0dd7 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryRouting.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+QueryRouting.swift @@ -49,7 +49,8 @@ extension MainContentCoordinator { databaseName: targetDatabase ?? browseDatabaseName, claimFocus: true ) - runAllStatements(extraCapabilities: .confirmsWrites) + guard let tabId = tabManager.selectedTabId else { return } + runAllStatements(onTab: tabId, extraCapabilities: .confirmsWrites) } /// Deleting a connection deletes its query history with it, so an id that resolves to nothing diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Refresh.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Refresh.swift index 33edc43c0c..26c5422927 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Refresh.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Refresh.swift @@ -19,6 +19,7 @@ extension MainContentCoordinator { } else { refreshPendingTrailing = true } + let requestedTabId = tabManager.selectedTabId refreshCoalesceTask?.cancel() refreshCoalesceTask = Task { [weak self] in try? await Task.sleep(for: Self.refreshCoalesceInterval) @@ -26,6 +27,8 @@ extension MainContentCoordinator { self.refreshCoalesceTask = nil if self.refreshPendingTrailing { self.refreshPendingTrailing = false + // A tab selected since the request is not the one it asked to refresh. + guard self.tabManager.selectedTabId == requestedTabId else { return } self.fireRefresh(hasPendingTableOps: hasPendingTableOps, onDiscard: onDiscard) } } @@ -72,35 +75,39 @@ extension MainContentCoordinator { hasPendingTableOps: Bool, onDiscard: @escaping () -> Void ) { - guard let (tab, tabIndex) = tabManager.selectedTabAndIndex, + guard let (tab, _) = tabManager.selectedTabAndIndex, tab.tabType == .table, tab.display.resultsViewMode != .structure else { return } + let tabId = tab.id commitActiveGridEdit() - guard changeManager.hasChanges || hasPendingTableOps else { - reloadTableTab(at: tabIndex) + let manager = changeManager(forTab: tabId) + guard manager.hasChanges || hasPendingTableOps else { + reloadTableTab(tabId) return } Task { let confirmed = await confirmDiscardChanges(action: .refresh, window: contentWindow) - guard confirmed else { return } + guard confirmed, tabManager.tabs.contains(where: { $0.id == tabId }) else { return } onDiscard() - rowEditingCoordinator.restoreRowBufferToOriginals() - changeManager.clearChangesAndUndoHistory() - guard let (tab, tabIndex) = tabManager.selectedTabAndIndex, - tab.tabType == .table else { return } - reloadTableTab(at: tabIndex) + rowEditingCoordinator.restoreRowBufferToOriginals(forTab: tabId) + manager.clearChangesAndUndoHistory() + guard tabManager.tabs.first(where: { $0.id == tabId })?.tabType == .table else { return } + reloadTableTab(tabId) } } - func reloadTableTab(at tabIndex: Int) { - stopExecution(for: tabManager.tabs[tabIndex].id) + func reloadTableTab(_ tabId: UUID) { + guard tabManager.tabs.contains(where: { $0.id == tabId }) else { return } + stopExecution(for: tabId) // A refresh retires the earlier exact count, else the automatic count refuses to re-derive rather than downgrade it to an estimate. - tabManager.mutate(at: tabIndex) { $0.pagination.retireDerivedRowCount() } - rebuildTableQuery(at: tabIndex) - runQuery(viewport: .keepPlace) + tabManager.mutate(tabId: tabId) { $0.pagination.retireDerivedRowCount() } + rebuildTableQuery(forTab: tabId) + runQuery(onTab: tabId, viewport: .keepPlace) // The next tick counts from this load settling, not from the last one. - restartAutoRefresh() + if tabManager.selectedTabId == tabId { + restartAutoRefresh() + } } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultReload.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultReload.swift index 1c9a68c265..ba397a5d2c 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultReload.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultReload.swift @@ -7,26 +7,25 @@ import Foundation import TableProSQLGrammar extension MainContentCoordinator { - /// Reads the tab's rows again after a write, keeping its place, value filter and selection. - /// A query tab re-reads its active result, never the statement at the editor's caret. - func reloadActiveResult() { - guard let tab = tabManager.selectedTab else { return } + // Reads the tab's rows again after a write, keeping its place; a query tab re-reads its active result, not the caret's statement. + func reloadActiveResult(onTab tabId: UUID) { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return } guard tab.tabType == .query else { - runQuery(viewport: .keepPlace) + runQuery(onTab: tabId, viewport: .keepPlace) return } guard tab.display.activeResultSet != nil, let rerun = tab.sortRerun else { return } - rerunActiveResult(rerun, viewport: .keepPlace) + rerunActiveResult(rerun, viewport: .keepPlace, onTab: tabId) } @discardableResult - func rerunActiveResult(_ rerun: ResultRerun, viewport: GridReloadIntent) -> Bool { - guard let (tab, index) = tabManager.selectedTabAndIndex, - !tabExecution.isExecuting(tab.id), + func rerunActiveResult(_ rerun: ResultRerun, viewport: GridReloadIntent, onTab tabId: UUID) -> Bool { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }), + !tabExecution.isExecuting(tabId), let batches = rerunBatches(for: rerun, of: tab) else { return false } let target = RereadTarget( - tabId: tab.id, + tabId: tabId, resultId: tab.display.activeResultSetId, databaseName: tab.tableContext.databaseName, schemaName: tab.tableContext.schemaName @@ -37,16 +36,12 @@ extension MainContentCoordinator { anchor: tab.display.activeResultSet?.statementAnchor ) tabManager.tabStructureVersion += 1 - if let parameters = rerun.boundParameters { - queryExecutionCoordinator.dispatchParameterizedBatches( - batches, - parameters: parameters, - tabIndex: index, - install: install - ) - } else { - queryExecutionCoordinator.dispatchBatches(batches, tabIndex: index, install: install) - } + queryExecutionCoordinator.dispatchBatches( + batches, + parameters: rerun.boundParameters, + onTab: tabId, + install: install + ) return true } @@ -63,7 +58,7 @@ extension MainContentCoordinator { return } let capturedColumns = tabSessionRegistry.tableRows(for: tabId).columns - confirmDiscardChangesIfNeeded(action: .sort) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .sort) { [weak self] confirmed in guard let self, confirmed, self.tabManager.selectedTabId == tabId, !self.tabExecution.isExecuting(tabId) else { return } let orderClause = newState.columns.compactMap { sortCol -> String? in @@ -75,7 +70,7 @@ extension MainContentCoordinator { let orderQuery = rerun.transformingSQL { QuerySqlParser.applyingOrderBy(orderClause, to: $0, grammar: self.lexicalGrammar) } - guard let current = self.tabManager.selectedTab, + guard let current = self.tabManager.tabs.first(where: { $0.id == tabId }), self.rerunBatches(for: orderQuery, of: current) != nil, self.tabManager.mutate(tabId: tabId, { tab in tab.sortState = newState @@ -83,7 +78,7 @@ extension MainContentCoordinator { tab.pagination.reset() tab.pagination.resetLoadMore() }) else { return } - self.rerunActiveResult(orderQuery, viewport: .firstRow) + self.rerunActiveResult(orderQuery, viewport: .firstRow, onTab: tabId) } } @@ -97,7 +92,7 @@ extension MainContentCoordinator { && tab.tableContext.schemaName == target.schemaName } - /// A run executes on the selected tab, so a re-read authorized after a tab switch would run there. + // A re-read approved after the reader moved to another tab is dropped rather than run behind their back. func rereadCanStart(_ source: ResultSourceChange) -> Bool { guard case .reread(let target) = source else { return true } return tabManager.selectedTabId == target.tabId && rereadStillApplies(source) diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Rewind.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Rewind.swift index 78278d541e..157835bccb 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Rewind.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Rewind.swift @@ -159,13 +159,16 @@ extension MainContentCoordinator { func applyRewind() async { guard let plan = rewindPlan else { return } - let executor = RewindExecutor(connection: connection, scope: scope(for: plan.record)) + let restoredScope = scope(for: plan.record) + // Read before the write: the tab in front by the time it lands may be another one. + let tabId = tabManager.selectedTab?.id + let executor = RewindExecutor(connection: connection, scope: restoredScope) do { let result = try await executor.apply(plan) Self.rewindLogger.info("Rewind restored \(result.restoredRows, privacy: .public) rows") rewindPlan = nil - if tabManager.selectedTab?.tableContext.tableName == plan.record.target.table { - reloadActiveResult() + if let tabId, tabShows(tabId, table: plan.record.target.table, in: restoredScope) { + reloadActiveResult(onTab: tabId) } } catch { let writeError = error as? DataWriteError @@ -178,6 +181,14 @@ extension MainContentCoordinator { } } + // Matched on database and schema too: a same-named table elsewhere was not restored. + private func tabShows(_ tabId: UUID, table: String, in restoredScope: DatabaseScope) -> Bool { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }), + tab.tableContext.tableName == table, + let tabScope = scope(for: tab) else { return false } + return tabScope.database == restoredScope.database && tabScope.schema == restoredScope.schema + } + // Shaped by the record, not the live tab: the save's columns and keys matter, and the tab may have moved on. private func rewindStatementFactory(for record: RewindRecord) -> RowChangeStatementFactory { let operation = record.operations.first diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarActions.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarActions.swift index 1e5f9ff31e..725dc15952 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarActions.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarActions.swift @@ -75,7 +75,7 @@ extension MainContentCoordinator { return } // The active result's unsaved edits leave with it, so this asks first, as switching does. - confirmDiscardChangesIfNeeded(action: .resultClose) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .resultClose) { [weak self] confirmed in guard confirmed, let self, let tabIdx = self.tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } let replacementId = replacement(self.tabManager.tabs[tabIdx].display) @@ -117,7 +117,7 @@ extension MainContentCoordinator { clearUnpinnedResults(in: tabId) return } - confirmDiscardChangesIfNeeded(action: .clearResults) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .clearResults) { [weak self] confirmed in if confirmed { self?.clearUnpinnedResults(in: tabId) } } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarSave.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarSave.swift index 61f0a3abf2..ee6324ea61 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarSave.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarSave.swift @@ -11,7 +11,7 @@ extension MainContentCoordinator { editState: MultiRowEditState ) async throws { let changes = sidebarEditChanges(editedFields: editState.getEditedFields()) - guard !changes.isEmpty else { return } + guard !changes.isEmpty, let tabId = tabManager.selectedTab?.id else { return } // Held to its row counts as a grid save is, so a write that found no row fails instead of saving nothing. let viewTarget = activeViewWriteTarget var factory = try sidebarStatementFactory() @@ -20,7 +20,7 @@ extension MainContentCoordinator { guard !steps.isEmpty else { return } try await executeSidebarChanges(steps: steps, viewTarget: viewTarget) - reloadActiveResult() + reloadActiveResult(onTab: tabId) } func sidebarEditStatements( diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabRestore.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabRestore.swift index 3d0961cf40..72bfef850b 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabRestore.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabRestore.swift @@ -42,7 +42,8 @@ extension MainContentCoordinator { } await switchContainers(database: activeDatabase, schema: activeSchema) - if isTableTab { + // A tab picked while the switch ran loads as a selection, not as this restore. + if isTableTab, tabManager.selectedTab?.id == selected.id { lazyLoadCurrentTabIfNeeded(trigger: .restore) } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableFirstLoad.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableFirstLoad.swift index b4ff31a747..c902c4b76a 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableFirstLoad.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableFirstLoad.swift @@ -24,7 +24,7 @@ extension MainContentCoordinator { return } let viewport = restoredRowAnchor(forTab: tabId).map(GridReloadIntent.restoreRow) ?? .keepPlace - executeTableTabQueryDirectly(trigger: trigger, viewport: viewport) + executeTableTabQueryDirectly(onTab: tabId, trigger: trigger, viewport: viewport) } @discardableResult diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift index b47d74f496..f0ea11b74e 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift @@ -105,7 +105,7 @@ extension MainContentCoordinator { guard let tabIdx = tabManager.tabs.firstIndex(where: { $0.id == tabId }), tabManager.tabs[tabIdx].display.activeResultSetId != resultSetId else { return } - confirmDiscardChangesIfNeeded(action: .resultSwitch) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .resultSwitch) { [weak self] confirmed in guard confirmed else { return } self?.applyResultSetSwitch(to: resultSetId, in: tabId) self?.revealStatement(behind: resultSetId, in: tabId) @@ -204,7 +204,7 @@ extension MainContentCoordinator { // A SQL Server batch result may have no single statement behind it, and re-running with ORDER BY would resend writes, so sort here. func sortHeldRows(by state: SortState, tabId: UUID) { - confirmDiscardChangesIfNeeded(action: .sort) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .sort) { [weak self] confirmed in guard let self, confirmed else { return } let rows = self.tabSessionRegistry.tableRows(for: tabId) let sorted = state.columns.isEmpty diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsRefresh.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsRefresh.swift index 9518e36e50..70fdd18ab4 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsRefresh.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsRefresh.swift @@ -94,8 +94,8 @@ extension MainContentCoordinator { case .noReload: break case .reloadNow: - guard let index = tabManager.selectedTabIndex else { return } - reloadTableTab(at: index) + guard let selectedId = tabManager.selectedTabId else { return } + reloadTableTab(selectedId) case .reloadBehindStructure: guard let selectedId = selectedState?.id else { return } if case .running = selectedState?.load { diff --git a/apple/TablePro/Views/Main/MainContentCommandActions+BulkClose.swift b/apple/TablePro/Views/Main/MainContentCommandActions+BulkClose.swift index 49f8f70d4e..f470e23d2e 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions+BulkClose.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions+BulkClose.swift @@ -153,12 +153,14 @@ extension MainContentCommandActions { // A victim it cannot save keeps its tab, a file conflict too: the conflict sheet is one window-level slot with no queue. private func saveVictims(_ victims: [QueryTab]) async -> Set { guard let coordinator else { return Set(victims.map(\.id)) } - guard await applyStagedStructureEdits(in: victims) else { return [] } - guard await saveWorkOnScreen(among: victims) else { return [] } + let onScreenId = coordinator.tabManager.selectedTabId + guard await applyStagedStructureEdits(in: victims, besides: onScreenId) else { return [] } + guard await saveWorkOnScreen(onScreenId, among: victims) else { return [] } var closable: Set = [] var files: [(tab: QueryTab, url: URL)] = [] - for victim in victims where !coordinator.isSelectedTab(victim) { + // A victim picked while the save waited stays open: its mounted work was never saved. + for victim in victims where victim.id != onScreenId && !coordinator.isSelectedTab(victim) { switch coordinator.savability(of: victim) { case .nothingAtRisk: closable.insert(victim.id) @@ -173,19 +175,17 @@ extension MainContentCommandActions { } } closable.formUnion(await saveFiles(files)) - if let selected = coordinator.tabManager.selectedTab, victims.contains(where: { $0.id == selected.id }) { - closable.insert(selected.id) + if let onScreenId, victims.contains(where: { $0.id == onScreenId }) { + closable.insert(onScreenId) } return closable } - // Always runs: a staged TRUNCATE and inspector edits belong to the connection, and only saveSelectedTabWork applies them. - private func saveWorkOnScreen(among victims: [QueryTab]) async -> Bool { - guard let coordinator else { return true } - let selected = coordinator.tabManager.selectedTab - let onScreenIsAVictim = victims.isEmpty || victims.contains { $0.id == selected?.id } + // Always runs: a staged TRUNCATE and inspector edits belong to the connection, and only saveWork(onTab:) applies them. + private func saveWorkOnScreen(_ onScreenId: UUID?, among victims: [QueryTab]) async -> Bool { + let onScreenIsAVictim = victims.isEmpty || victims.contains { $0.id == onScreenId } guard onScreenIsAVictim else { return true } - return await saveSelectedTabWork() + return await saveWork(onTab: onScreenId) } // Victims only (empty means the whole connection); connection-wide flags count only when the on-screen tab is a victim. diff --git a/apple/TablePro/Views/Main/MainContentCommandActions+Closing.swift b/apple/TablePro/Views/Main/MainContentCommandActions+Closing.swift index 5c96cd52ee..43b5b9408d 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions+Closing.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions+Closing.swift @@ -67,7 +67,8 @@ extension MainContentCommandActions { closeAnchorWindow ) { case .save: - guard await saveSelectedTabWork() else { return } + // A tab picked during the prompt refuses the save, and with it the close: its editors are not this tab's. + guard await saveWork(onTab: id) else { return } stop(work) closeRevealedTab(id, returningTo: previousSelection) case .dontSave: @@ -102,4 +103,54 @@ extension MainContentCommandActions { coordinator.tabManager.tabs.contains(where: { $0.id == id }) else { return } coordinator.tabManager.selectedTabId = id } + + // False while work is still staged after the attempt (review sheet, refused or cancelled DDL, file conflict, Save As cancel). + func saveSelectedTabWork() async -> Bool { + await saveWork(onTab: coordinator?.tabManager.selectedTabId) + } + + // False once another tab is in front or the tab is gone: the mounted editors, grid and inspector it saves are the front tab's. + func saveWork(onTab tabId: UUID?) async -> Bool { + guard let coordinator = coordinator else { return true } + let manager = coordinator.tabManager + let stillOnTab = { manager.selectedTabId == tabId && (tabId == nil || manager.selectedTabIndex != nil) } + guard stillOnTab() else { return false } + + if isUsersRolesTab, coordinator.usersRolesActions?.hasChanges() == true { + coordinator.usersRolesActions?.reviewAndApply() + return false + } + + // Keyed on the session, not resultsViewMode, which let a Data-view or background tab close over its staged ALTERs. + if let tabId, + let session = coordinator.structureSessions[tabId], + session.changeManager.hasChanges { + guard await session.applyStagedChanges(coordinator: coordinator).allowsClose, stillOnTab() else { + return false + } + } + guard await applyDiagramEdits(ofTab: tabId, in: coordinator), stillOnTab() else { return false } + guard await applyTypeChanges(ofTab: tabId), stillOnTab() else { return false } + + // Data grid changes or pending table operations take priority + if hasDataWork { + return await withCheckedContinuation { continuation in + coordinator.saveCompletionContinuation = continuation + saveChanges() + // Still there when the command went somewhere other than the grid save, which reports nothing back. + coordinator.takeSaveCompletion()?.resume(returning: false) + } + } + + if trailingPaneState.inspector.editState.hasEdits { + return await saveInspectorEditsAwaiting() + } + + // File save (query editor with source file) + if coordinator.tabManager.selectedTab?.content.isFileDirty == true { + return await saveSelectedFileAwaiting() + } + + return true + } } diff --git a/apple/TablePro/Views/Main/MainContentCommandActions+Diagram.swift b/apple/TablePro/Views/Main/MainContentCommandActions+Diagram.swift index f5164e5d6b..977061e396 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions+Diagram.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions+Diagram.swift @@ -20,10 +20,8 @@ extension MainContentCommandActions { return true } - func applySelectedDiagramEdits(in coordinator: MainContentCoordinator) async -> Bool { - guard let diagram = diagramHoldingWork(in: coordinator.tabManager.selectedTabId, of: coordinator) else { - return true - } + func applyDiagramEdits(ofTab tabId: UUID?, in coordinator: MainContentCoordinator) async -> Bool { + guard let diagram = diagramHoldingWork(in: tabId, of: coordinator) else { return true } return await diagram.applyStagedEdits(coordinator: coordinator).allowsClose } diff --git a/apple/TablePro/Views/Main/MainContentCommandActions+Structure.swift b/apple/TablePro/Views/Main/MainContentCommandActions+Structure.swift index 80643e9853..20f7bb7f30 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions+Structure.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions+Structure.swift @@ -26,8 +26,8 @@ extension MainContentCommandActions { switch discardTarget { case .structure(let session): session.discardChangesAfterConfirming() - case .data: - Task { await discardDataWorkAfterConfirming() } + case .data(let tabId): + Task { await discardDataWorkAfterConfirming(onTab: tabId) } case nil: break } @@ -35,7 +35,7 @@ extension MainContentCommandActions { private enum DiscardTarget { case structure(StructureEditingSession) - case data + case data(tabId: UUID) } // Create Table has no saved state to return to. @@ -43,10 +43,11 @@ extension MainContentCommandActions { guard let tab = coordinator?.tabManager.selectedTab, tab.tabType == .table || tab.tabType == .query else { return nil } if let session = stagedStructureSession { return .structure(session) } - return hasDataWork && coordinator?.isSavingSelectedTab != true ? .data : nil + return hasDataWork && coordinator?.isSavingSelectedTab != true ? .data(tabId: tab.id) : nil } - private func discardDataWorkAfterConfirming() async { + // Discards nothing once another tab is in front: the grid work it would clear is that tab's. + private func discardDataWorkAfterConfirming(onTab tabId: UUID) async { let confirmed = await AlertHelper.confirmDestructive( title: String(localized: "Discard Changes?"), message: String(localized: "The changes you have not saved will be lost."), @@ -54,7 +55,7 @@ extension MainContentCommandActions { cancelButton: String(localized: "Cancel"), window: closeAnchorWindow ) - guard confirmed else { return } + guard confirmed, coordinator?.tabManager.selectedTab?.id == tabId else { return } discardDataWork() } diff --git a/apple/TablePro/Views/Main/MainContentCommandActions+UserTypes.swift b/apple/TablePro/Views/Main/MainContentCommandActions+UserTypes.swift index 11e449750d..a7976b2043 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions+UserTypes.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions+UserTypes.swift @@ -14,19 +14,17 @@ extension MainContentCommandActions { return true } - /// False when the selected type tab's queue is still staged after the attempt, which stands a - /// close down. - func applySelectedTypeChanges() async -> Bool { - guard let coordinator, let tabId = coordinator.tabManager.selectedTabId, + // False when the type tab's queue is still staged after the attempt, which stands a close down. + func applyTypeChanges(ofTab tabId: UUID?) async -> Bool { + guard let coordinator, let tabId, coordinator.userTypeEditors[tabId]?.hasChanges == true else { return true } return await coordinator.applyUserTypeChanges(tabId: tabId).allowsClose } - /// The type tabs a window or batch close asked about that are not on screen. - func applyBackgroundTypeChanges(in tabs: [QueryTab]) async -> Bool { + // The type tabs a window or batch close asked about, other than the one on screen. + func applyBackgroundTypeChanges(in tabs: [QueryTab], besides onScreenId: UUID?) async -> Bool { guard let coordinator else { return true } - let selectedId = coordinator.tabManager.selectedTabId - for tab in tabs where tab.id != selectedId && coordinator.hasStagedTypeChanges(in: tab) { + for tab in tabs where tab.id != onScreenId && coordinator.hasStagedTypeChanges(in: tab) { guard await coordinator.applyUserTypeChanges(tabId: tab.id).allowsClose else { return false } } return true diff --git a/apple/TablePro/Views/Main/MainContentCommandActions.swift b/apple/TablePro/Views/Main/MainContentCommandActions.swift index f86a21a6c9..2c04094af5 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions.swift @@ -37,7 +37,7 @@ final class MainContentCommandActions: ObservableObject { private let pendingTruncates: Binding> private let pendingDeletes: Binding> private let tableOperationOptions: Binding<[DatabaseTreeTableRef: TableOperationOptions]> - private let trailingPaneState: TrailingPaneState + let trailingPaneState: TrailingPaneState weak var window: NSWindow? { didSet { @@ -145,7 +145,7 @@ final class MainContentCommandActions: ObservableObject { // A close waits on this: started and left, the write could land after the window it reports to closed. @discardableResult - private func saveInspectorEditsAwaiting() async -> Bool { + func saveInspectorEditsAwaiting() async -> Bool { let editState = trailingPaneState.inspector.editState do { try await coordinator?.saveSidebarEdits(editState: editState) @@ -737,48 +737,6 @@ final class MainContentCommandActions: ObservableObject { coordinator.toolbarState.isTableTab = false } - // False while work is still staged after the attempt (review sheet, refused or cancelled DDL, file conflict, Save As cancel). - func saveSelectedTabWork() async -> Bool { - guard let coordinator = coordinator else { return true } - - if isUsersRolesTab, coordinator.usersRolesActions?.hasChanges() == true { - coordinator.usersRolesActions?.reviewAndApply() - return false - } - - // Keyed on the session, not resultsViewMode, which let a Data-view or background tab close over its staged ALTERs. - if let tabId = coordinator.tabManager.selectedTabId, - let session = coordinator.structureSessions[tabId], - session.changeManager.hasChanges { - guard await session.applyStagedChanges(coordinator: coordinator).allowsClose else { - return false - } - } - guard await applySelectedDiagramEdits(in: coordinator) else { return false } - guard await applySelectedTypeChanges() else { return false } - - // Data grid changes or pending table operations take priority - if hasDataWork { - return await withCheckedContinuation { continuation in - coordinator.saveCompletionContinuation = continuation - saveChanges() - // Still there when the command went somewhere other than the grid save, which reports nothing back. - coordinator.takeSaveCompletion()?.resume(returning: false) - } - } - - if trailingPaneState.inspector.editState.hasEdits { - return await saveInspectorEditsAwaiting() - } - - // File save (query editor with source file) - if coordinator.tabManager.selectedTab?.content.isFileDirty == true { - return await saveSelectedFileAwaiting() - } - - return true - } - // The prompt asked about every connection in the window, so Save reaches every tab of each; one it cannot save keeps the window. private func saveAndClose(asBatchSurvivor: Bool?) async -> Bool { let host = window?.contentViewController as? MainSplitViewController @@ -794,17 +752,16 @@ final class MainContentCommandActions: ObservableObject { return true } - // Reaches every tab the window or batch prompt asked about; the selected tab is left to saveSelectedTabWork. - func applyStagedStructureEdits(in tabs: [QueryTab]) async -> Bool { + // Reaches every tab the window or batch prompt asked about; the one on screen is left to saveWork(onTab:). + func applyStagedStructureEdits(in tabs: [QueryTab], besides onScreenId: UUID?) async -> Bool { guard let coordinator else { return true } - let selectedId = coordinator.tabManager.selectedTabId let victims = tabs.filter { tab in - tab.id != selectedId && coordinator.hasStagedStructureEdits(in: tab) + tab.id != onScreenId && coordinator.hasStagedStructureEdits(in: tab) } for tab in victims { guard await applyStagedSchemaWork(of: tab, in: coordinator) else { return false } } - return await applyBackgroundTypeChanges(in: tabs) + return await applyBackgroundTypeChanges(in: tabs, besides: onScreenId) } @@ -933,20 +890,20 @@ final class MainContentCommandActions: ObservableObject { } func saveFileAs() { - guard coordinator?.admitsSheetCommand() == true else { return } - Task { await saveFileAsAwaiting() } + guard let coordinator, coordinator.admitsSheetCommand() else { return } + let tabId = coordinator.tabManager.selectedTab?.id + Task { await saveFileAsAwaiting(forTab: tabId) } } + // A failed write passes its own tab: by the time it falls back here another tab can be in front. @discardableResult - func saveFileAsAwaiting() async -> Bool { - if let tabId = coordinator?.tabManager.selectedTabId { - coordinator?.flushEditorText(forTab: tabId) - } - guard let tab = coordinator?.tabManager.selectedTab, + func saveFileAsAwaiting(forTab requestedTabId: UUID? = nil) async -> Bool { + guard let tabId = requestedTabId ?? coordinator?.tabManager.selectedTab?.id else { return false } + coordinator?.flushEditorText(forTab: tabId) + guard let tab = coordinator?.tabManager.tabs.first(where: { $0.id == tabId }), tab.tabType == .query else { return false } let content = tab.content.query let suggestedName = tab.content.sourceFileURL?.lastPathComponent ?? "\(tab.title).sql" - let tabId = tab.id guard let url = await chooseSaveURL(suggestedName) else { return false } do { try await SQLFileService.writeFile(content: content, to: url, encoding: .utf8) @@ -973,7 +930,8 @@ final class MainContentCommandActions: ObservableObject { } func explainQuery() { - coordinator?.runExplain() + guard let coordinator, let tabId = coordinator.tabManager.selectedTab?.id else { return } + coordinator.runExplain(onTab: tabId) } var aiQueryActionAvailability: AIQueryActionAvailability { @@ -1117,11 +1075,13 @@ final class MainContentCommandActions: ObservableObject { } func runQuery() { - if let coordinator, let draft = coordinator.activeCreateTableDraft { + guard let coordinator else { return } + if let draft = coordinator.activeCreateTableDraft { draft.create(coordinator: coordinator) return } - coordinator?.runQuery(viewport: .keepPlace) + guard let tabId = coordinator.tabManager.selectedTab?.id else { return } + coordinator.runQuery(onTab: tabId, viewport: .keepPlace) } var canCreateDraftTable: Bool { @@ -1129,11 +1089,13 @@ final class MainContentCommandActions: ObservableObject { } func runQueryWithoutLimit() { - coordinator?.runQuery(viewport: .keepPlace, bypassRowLimit: true) + guard let coordinator, let tabId = coordinator.tabManager.selectedTab?.id else { return } + coordinator.runQuery(onTab: tabId, viewport: .keepPlace, bypassRowLimit: true) } func runAllStatements() { - coordinator?.runAllStatements() + guard let coordinator, let tabId = coordinator.tabManager.selectedTab?.id else { return } + coordinator.runAllStatements(onTab: tabId) } func cancelCurrentQuery() { diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index 40992d76a5..6d5c189348 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -171,6 +171,8 @@ final class MainContentCoordinator: ObservableObject { } let selectionSummary = SelectionSummaryState() let tabManager: QueryTabManager + // This connection's catalog facts the main views read, so another connection's schema load wakes none of them. + let catalogSnapshot: ConnectionCatalogSnapshot // Each tab stages its edits in its own manager; this one answers while no tab is selected. let idleChangeManager = DataChangeManager() var tabEdits: [UUID: TabEdits] = [:] @@ -598,6 +600,11 @@ final class MainContentCoordinator: ObservableObject { self.connection = connection self.windowSidebarState = WindowSidebarState(connectionId: connection.id) self.tabManager = tabManager + self.catalogSnapshot = ConnectionCatalogSnapshot( + connectionId: connection.id, + schemaService: services.schemaService, + treeService: DatabaseTreeMetadataService.shared + ) idleChangeManager.databaseType = connection.type self.selectedTabEdits = SelectedTabEdits(idleChangeManager) self.toolbarState = toolbarState @@ -961,31 +968,33 @@ final class MainContentCoordinator: ObservableObject { // MARK: - Query Execution + // A query tab runs only while it is the selected tab: the statement comes from the editor's caret. func runQuery( + onTab tabId: UUID, viewport: GridReloadIntent, trigger: TableLoadTrigger = .userInitiated, bypassRowLimit: Bool = false, extraCapabilities: CallerCapabilities = [] ) { - guard let tab = tabManager.selectedTabAndIndex?.tab else { return } - guard !tabExecution.isExecuting(tab.id) else { - traceExecutionBlocked(tabId: tab.id, site: "runQuery") + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return } + guard !tabExecution.isExecuting(tabId) else { + traceExecutionBlocked(tabId: tabId, site: "runQuery") return } if tab.tabType == .table { - commitActiveGridEdit() - executeTableTabQueryDirectly(trigger: trigger, viewport: viewport) + if tabManager.selectedTab?.id == tabId { commitActiveGridEdit() } + executeTableTabQueryDirectly(onTab: tabId, trigger: trigger, viewport: viewport) return } - let tabId = tab.id + guard tabManager.selectedTab?.id == tabId else { return } confirmRunDiscard(onTab: tabId) { [weak self] in guard let self else { return } flushEditorText(forTab: tabId) - guard let (tab, index) = executionTab(tabId) else { return } + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return } // The offset lets each result point back at its statement. Both paths pass untrimmed text and let the scanner trim. let target = selectionOrStatementAtCursor(in: tab.content.query) executeResolvedSQL( - target.sql, tabIndex: index, bypassRowLimit: bypassRowLimit, + target.sql, onTab: tabId, bypassRowLimit: bypassRowLimit, sourceOffset: target.offset, extraCapabilities: extraCapabilities ) } @@ -993,81 +1002,91 @@ final class MainContentCoordinator: ObservableObject { // Takes SQL, not a range: the editor text and the tab binding can briefly differ, and a range on the wrong one truncates silently. @discardableResult - func runStatement(_ sql: String, sourceOffset: Int? = nil) -> Bool { - guard let tab = tabManager.selectedTabAndIndex?.tab, tab.tabType == .query else { return false } - guard !tabExecution.isExecuting(tab.id) else { - traceExecutionBlocked(tabId: tab.id, site: "runStatement") + func runStatement(_ sql: String, sourceOffset: Int? = nil, onTab tabId: UUID) -> Bool { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }), tab.tabType == .query, + tabManager.selectedTab?.id == tabId else { return false } + guard !tabExecution.isExecuting(tabId) else { + traceExecutionBlocked(tabId: tabId, site: "runStatement") return false } // False when the discard prompt has to ask first: the run follows the answer, the caret stays. var started = false - confirmRunDiscard(onTab: tab.id) { [weak self] in - guard let self, let (_, index) = executionTab(tab.id) else { return } - started = executeResolvedSQL(sql, tabIndex: index, bypassRowLimit: false, sourceOffset: sourceOffset) + confirmRunDiscard(onTab: tabId) { [weak self] in + guard let self else { return } + started = executeResolvedSQL(sql, onTab: tabId, bypassRowLimit: false, sourceOffset: sourceOffset) } return started } + func runAllStatements(onTab tabId: UUID, extraCapabilities: CallerCapabilities = []) { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }), tab.tabType == .query, + tabManager.selectedTab?.id == tabId, !tabExecution.isExecuting(tabId) else { return } + confirmRunDiscard(onTab: tabId) { [weak self] in + guard let self else { return } + flushEditorText(forTab: tabId) + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return } + executeResolvedSQL( + tab.content.query, onTab: tabId, bypassRowLimit: false, extraCapabilities: extraCapabilities + ) + } + } + // Returns false when a parameter panel opens instead, so callers don't advance the caret on a run that didn't happen. @discardableResult private func executeResolvedSQL( _ sql: String, - tabIndex index: Int, + onTab tabId: UUID, bypassRowLimit: Bool, sourceOffset: Int? = nil, extraCapabilities: CallerCapabilities = [] ) -> Bool { let batches = queryExecutionCoordinator.executionBatches(in: sql, sourceOffset: sourceOffset ?? 0) let statements = batches.flatMap(\.statements) - guard !statements.isEmpty else { return false } - tabVersions.record(tabManager.tabs[index], connectionId: connectionId, reason: .run) + guard !statements.isEmpty, let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return false } + tabVersions.record(tab, connectionId: connectionId, reason: .run) + var parameters: [QueryParameter]? if services.appSettings.editor.queryParametersEnabled, bindsNamedParameters { let combinedSQL = SQLParameterExtractor.parameterSource(of: statements) let detectedNames = SQLParameterExtractor.extractParameters(from: combinedSQL, grammar: lexicalGrammar) if !detectedNames.isEmpty { - let reconciled = detectAndReconcileParameters( - sql: combinedSQL, - existing: tabManager.tabs[index].content.queryParameters - ) - tabManager.mutate(at: index) { $0.content.queryParameters = reconciled } + let reconciled = detectAndReconcileParameters(sql: combinedSQL, existing: tab.content.queryParameters) + tabManager.mutate(tabId: tabId) { $0.content.queryParameters = reconciled } - if !tabManager.tabs[index].content.isParameterPanelVisible { - tabManager.mutate(at: index) { $0.content.isParameterPanelVisible = true } + guard tab.content.isParameterPanelVisible else { + tabManager.mutate(tabId: tabId) { $0.content.isParameterPanelVisible = true } return false } - - tabManager.tabStructureVersion += 1 - dispatchParameterizedBatches( - batches, - parameters: reconciled, - tabIndex: index, - bypassRowLimit: bypassRowLimit, - extraCapabilities: extraCapabilities - ) - return true + parameters = reconciled } } tabManager.tabStructureVersion += 1 - dispatchBatches(batches, tabIndex: index, bypassRowLimit: bypassRowLimit, extraCapabilities: extraCapabilities) + queryExecutionCoordinator.dispatchBatches( + batches, + parameters: parameters, + onTab: tabId, + bypassRowLimit: bypassRowLimit, + extraCapabilities: extraCapabilities + ) return true } // App-built SELECTs skip dangerous-query checks but keep safe mode. Returns the confirmation task when Safe Mode asks first. @discardableResult func executeTableTabQueryDirectly( + onTab tabId: UUID, trigger: TableLoadTrigger = .userInitiated, viewport: GridReloadIntent ) -> Task? { - guard let tab = tabManager.selectedTab else { return nil } - TableLoadTracer.shared.stage(.executeRequested, tabId: tab.id) + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return nil } + TableLoadTracer.shared.stage(.executeRequested, tabId: tabId) let sql = tab.content.query guard !sql.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { - traceNavigationAbandoned(tabId: tab.id, outcome: .emptyQuery) + traceNavigationAbandoned(tabId: tabId, outcome: .emptyQuery) return nil } @@ -1075,252 +1094,78 @@ final class MainContentCoordinator: ObservableObject { let asksBeforeFirstLoad = level.appliesToAllQueries && level.requiresConfirmation && tab.execution.lastExecutedAt == nil let gatesRawFilter = rawFilterNeedsReadOnlyGate(Self.browseFilters(tab.filterState)) - if asksBeforeFirstLoad || gatesRawFilter { - guard !isShowingSafeModePrompt else { - turnAwayTableLoad(tabId: tab.id, trigger: trigger) - return nil - } - isShowingSafeModePrompt = true - let tabId = tab.id - let askedContext = tab.tableContext - let askedScope = scope(for: tab) - return Task { - let decision = await executionGate.authorize( - OperationRequest( - connectionId: connectionId, - databaseType: connection.type, - sql: sql, - kind: .readQuery, - caller: .userInterface, - capabilities: .interactiveUser, - operationDescription: String(localized: "Execute Query"), - runsIn: askedScope - ) + guard asksBeforeFirstLoad || gatesRawFilter else { + executeQueryInternal(sql, onTab: tabId, isAutoLoad: true, trigger: trigger, viewport: viewport, source: .sameSource) + return nil + } + guard !isShowingSafeModePrompt else { + turnAwayTableLoad(tabId: tabId, trigger: trigger) + return nil + } + isShowingSafeModePrompt = true + let askedContext = tab.tableContext + let askedScope = scope(for: tab) + return Task { + let decision = await executionGate.authorize( + OperationRequest( + connectionId: connectionId, + databaseType: connection.type, + sql: sql, + kind: .readQuery, + caller: .userInterface, + capabilities: .interactiveUser, + operationDescription: String(localized: "Execute Query"), + runsIn: askedScope ) - isShowingSafeModePrompt = false - // Only on the tab and table the sheet showed: elsewhere it put these rows under another name; SQL alone misses a Redis db switch. - let asked = tabManager.tabs.first(where: { $0.id == tabId }) - guard tabManager.selectedTabId == tabId, - let asked, - asked.content.query == sql, - asked.tableContext.tableName == askedContext.tableName, - asked.tableContext.databaseName == askedContext.databaseName else { - traceNavigationAbandoned(tabId: tabId, outcome: .superseded) - if tabManager.selectedTabId != tabId { - declineTableLoad(for: tabId) - } - lazyLoadCurrentTabIfNeeded(trigger: trigger) - return - } - switch decision { - case .authorized: - executeQueryInternal( - sql, isAutoLoad: true, trigger: trigger, viewport: viewport, source: .sameSource, onTab: tabId - ) - case .denied(let reason, _): - traceNavigationAbandoned(tabId: tabId, outcome: .safeModeDenied) - queryExecutionCoordinator.presentTabFailure(reason, announcing: reason, onTab: tabId) + ) + isShowingSafeModePrompt = false + // Only on the tab and table the sheet showed: elsewhere it put these rows under another name; SQL alone misses a Redis db switch. + let asked = tabManager.tabs.first(where: { $0.id == tabId }) + guard tabManager.selectedTabId == tabId, + let asked, + asked.content.query == sql, + asked.tableContext.tableName == askedContext.tableName, + asked.tableContext.databaseName == askedContext.databaseName else { + traceNavigationAbandoned(tabId: tabId, outcome: .superseded) + if tabManager.selectedTabId != tabId { + declineTableLoad(for: tabId) } + lazyLoadCurrentTabIfNeeded(trigger: trigger) + return + } + switch decision { + case .authorized: + executeQueryInternal( + sql, onTab: tabId, isAutoLoad: true, trigger: trigger, viewport: viewport, source: .sameSource + ) + case .denied(let reason, _): + traceNavigationAbandoned(tabId: tabId, outcome: .safeModeDenied) + queryExecutionCoordinator.presentTabFailure(reason, announcing: reason, onTab: tabId) } } - executeQueryInternal(sql, isAutoLoad: true, trigger: trigger, viewport: viewport, source: .sameSource) - return nil } internal func executeQueryInternal( _ sql: String, + onTab tabId: UUID, isAutoLoad: Bool = false, trigger: TableLoadTrigger = .userInitiated, bypassRowLimit: Bool = false, anchor: StatementAnchor? = nil, viewport: GridReloadIntent = .firstRow, - source: ResultSourceChange = .newSource, - onTab target: UUID? = nil + source: ResultSourceChange = .newSource ) { - guard let (selectedTab, index) = executionTab(target) else { return } - - let (claim, lease) = beginTabExecution(for: selectedTab.id) - - tabManager.mutate(at: index) { tab in - tab.execution.executionTime = nil - tab.execution.errorMessage = nil - } - let tab = tabManager.tabs[index] - - let conn = connection - let tabId = tabManager.tabs[index].id - - let traceToken = trigger.tracesLoad ? adoptOrBeginExecutionTrace(tabId: tabId) : nil - traceExecutionStarted(traceToken, epoch: claim.epoch, isAutoLoad: isAutoLoad) - - let statement = resolveStatement(sql: sql, tabType: tab.tabType, bypassLimit: bypassRowLimit) - let rowCap = statement.rowCap - let (tableName, isEditable) = resolveTableEditability(tab: tab, sql: sql) - - let needsDefinition = tabSessionRegistry.needsDefinition(tabId) - let needsMetadataFetch = tableName.map { isEditable && !isMetadataCached(tabId: tabId, tableName: $0) } ?? false - // Captured now, while the result this decision was made against is still the active one. - let cachedMetadata: ParsedSchemaMetadata? = needsMetadataFetch ? nil : ParsedSchemaMetadata.cached( - rows: tabSessionRegistry.tableRows(for: tabId), - context: tabManager.tabs[index].tableContext + queryExecutionCoordinator.startSingleRun( + SingleRunRequest( + sql: sql, + isAutoLoad: isAutoLoad, + trigger: trigger, + bypassRowLimit: bypassRowLimit, + anchor: anchor, + install: ResultInstall(viewport: viewport, source: source) + ), + onTab: tabId ) - if let tableName { - Self.logger.info( - "[fk] metadata decision table=\(tableName, privacy: .private(mask: .hash)) isEditable=\(isEditable) needsFetch=\(needsMetadataFetch)" - ) - } - guard let scope = scope(for: tab) else { - guard tabExecution.settle(claim) else { return } - tabManager.mutate(at: index) { tab in - tab.execution.errorMessage = String(localized: "Not connected to database") - tab.pagination.isLoading = false - } - return - } - let isTableTab = tab.tabType == .table - let readsView = tab.tableContext.knowsView(named: tableName) - let (grammar, lengthColumns) = (lexicalGrammar, unloadedValueLengthColumns(for: tab)) - let safeModeIsReadOnly = runsAtReadOnly - let held = manualCommitRun(skipped: isTableTab || isAutoLoad) - - let failureOutput = ServerOutputBox() - let queryTask = Task { [weak self] in - guard let self else { return } - - if isAutoLoad, await !connectBeforeAutoLoad(conn, claim: claim, trigger: trigger, traceToken: traceToken) { - return - } - - let schemaTask = startSchemaFetch(tableName, uncached: needsMetadataFetch, isView: readsView, scope: scope) - - let fetchBeganAt = ContinuousClock.now - do { - let (fetchResult, tableEdits) = try await withExecutionDriver( - scope: scope, - isTableTab: isTableTab, - lease: lease - ) { [queryExecutor, manager = services.databaseManager] 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. - if !isAutoLoad { await manager.noteSessionStatements([statement.sql], ranOn: driver, scope: scope) } - return try await queryExecutor.executeQuery( - driver: driver, - sql: statement.sql, - parameters: nil, - rowCap: rowCap, - safeModeIsReadOnly: safeModeIsReadOnly, - capturingOutputInto: isTableTab ? nil : failureOutput - ) - } - let edits = isAutoLoad ? nil : await SucceededStatements.single( - statement.sql, scope: scope, databaseType: conn.type, grammar: grammar, ranOn: driver - ) - return (fetched.foldingUnloadedValues(lengthColumns: lengthColumns), edits) - } - let fetchEndedAt = ContinuousClock.now - if !isAutoLoad { Self.postStatementRan(statement.sql, on: conn, succeeded: tableEdits) } - - guard !Task.isCancelled else { - schemaTask?.cancel() - traceFetchCancelled(traceToken, began: fetchBeganAt, ended: fetchEndedAt) - await resetExecutionState(claim: claim, executionTime: fetchResult.executionTime) - return - } - - let inlineMeta = needsMetadataFetch - ? QueryExecutor.inlineMetadata(from: fetchResult.resultColumnMeta, columns: fetchResult.columns) - : nil - // Rows and definition commit together after a definition change, so new columns never sit under old keys or defaults. - let definition = needsDefinition ? try? await schemaTask?.value : nil - let prepared = await preparedPhase1Rows(fetchResult, tabId: tabId, tableName: tableName, isTableTab: isTableTab) - - let applied = await MainActor.run { [weak self] () -> Bool in - guard let self else { return false } - traceFetchCompleted(traceToken, began: fetchBeganAt, ended: fetchEndedAt, result: fetchResult) - - // Settle first: it gates every write below, and sharing a guard with the cancel check would leave the tab claimed forever. - guard tabExecution.settle(claim) else { - traceStaleResultDropped(traceToken) - return false - } - retireQueryTask(.claim(claim)) - guard !Task.isCancelled, rereadStillApplies(source) else { - traceStaleResultDropped(traceToken) - return false - } - // A menu or value window opened during the read names rows by position, so a tick's rows wait for the next one. - guard trigger != .autoRefresh || !autoRefreshHeldByTransientUI(tabId) else { return false } - toolbarState.recordQueryTiming(fetchResult.resolvedTiming, for: tabId) - - traceApplyingResult(traceToken, tabId: tabId) - - let definitionMetadata = adoptLoadedDefinition(definition, of: tableName, in: scope, readBy: claim) - applyPhase1Result( - tabId: tabId, - columns: fetchResult.columns, - columnTypes: fetchResult.columnTypes, - rows: fetchResult.rows, - executionTime: fetchResult.executionTime, - rowsAffected: fetchResult.rowsAffected, - statusMessage: fetchResult.statusMessage, - tableName: tableName, - isEditable: isEditable, - metadata: definitionMetadata ?? inlineMeta ?? cachedMetadata, - hasSchema: definitionMetadata != nil, - read: TableFreshness.Read(startedAt: claim.startedAt, includesDefinition: definitionMetadata != nil), - sql: sql, - connection: conn, - isTruncated: fetchResult.isTruncated, - anchor: anchor, - timing: fetchResult.resolvedTiming, - viewport: viewport, - source: source, - serverOutput: fetchResult.serverOutput, - rowLocators: isTableTab ? fetchResult.rowLocators : nil, - exportDocuments: fetchResult.exportDocuments, - absentCells: fetchResult.absentCells, - unloadedCells: fetchResult.unloadedCells, - columnOrigins: fetchResult.columnOrigins, - prepared: prepared, - trigger: trigger - ) - - scheduleTraceCompletion(traceToken, outcome: .completed) - reportFetchedQuery(claim: claim, trigger: trigger, result: fetchResult) - return true - } - // Phase 2 writes onto whatever the tab holds, so only the execution that applied its rows may start it. - guard applied else { - schemaTask?.cancel() - return - } - - launchPhase2AfterApply( - tableName: tableName, - isEditable: isEditable, - tabId: tabId, - trigger: trigger, - needsMetadataFetch: needsMetadataFetch, - schemaTask: schemaTask, - claim: claim - ) - } catch { - schemaTask?.cancel() - if !isAutoLoad { Self.postStatementRan(statement.sql, on: conn) } - finishFailedQuery( - error, - tabId: tabId, - sql: sql, - connection: conn, - claim: claim, - isAutoLoad: isAutoLoad, - trigger: trigger, - traceToken: traceToken, - serverOutput: failureOutput.output - ) - } - } - installQueryTask(queryTask, owner: .claim(claim), lease: lease) } internal func resolveTableEditability(tab: QueryTab, sql: String) -> (tableName: String?, isEditable: Bool) { @@ -1349,7 +1194,8 @@ final class MainContentCoordinator: ObservableObject { func fetchEnumValues( columnInfo: [ColumnInfo], tableName: String, - connectionType: DatabaseType + connectionType: DatabaseType, + scope: DatabaseScope? ) async -> [String: [String]] { var result: [String: [String]] = [:] @@ -1360,7 +1206,7 @@ final class MainContentCoordinator: ObservableObject { } if result.isEmpty, - let scope = selectedTabScope, + let scope, let createSQL = try? await services.databaseManager.withMetadataDriver(scope: scope, { driver in try await driver.fetchTableDDL(table: tableName, schema: scope.schema) }) { @@ -1390,7 +1236,7 @@ final class MainContentCoordinator: ObservableObject { guard supportsColumnSort else { return } let tabId = tab.id let capturedSort = newState - confirmDiscardChangesIfNeeded(action: .sort) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .sort) { [weak self] confirmed in guard let self, confirmed else { return } guard self.tabManager.mutate(tabId: tabId, { tab in tab.sortState = capturedSort @@ -1399,7 +1245,7 @@ final class MainContentCoordinator: ObservableObject { }) else { return } guard let tabIndex = self.tabManager.tabs.firstIndex(where: { $0.id == tabId }) else { return } self.rebuildTableQuery(at: tabIndex) - self.runQuery(viewport: .firstRow) + self.runQuery(onTab: tabId, viewport: .firstRow) } } } diff --git a/apple/TablePro/Views/Main/MainContentView.swift b/apple/TablePro/Views/Main/MainContentView.swift index ee2e011fd1..240ee5a83f 100644 --- a/apple/TablePro/Views/Main/MainContentView.swift +++ b/apple/TablePro/Views/Main/MainContentView.swift @@ -21,14 +21,14 @@ struct MainContentView: View { @Binding var windowTitle: String @Binding var windowSubtitle: String @Binding var windowRepresentedURL: URL? - @ObservedObject var schemaService = SchemaService.shared @Binding var pendingTruncates: Set @Binding var pendingDeletes: Set @Binding var tableOperationOptions: [DatabaseTreeTableRef: TableOperationOptions] @ObservedObject var trailingPaneState: TrailingPaneState + @ObservedObject var catalogSnapshot: ConnectionCatalogSnapshot var tables: [TableInfo] { - schemaService.tables(for: connection.id) + catalogSnapshot.tables } // MARK: - State Objects @@ -77,6 +77,7 @@ struct MainContentView: View { self._pendingDeletes = pendingDeletes self._tableOperationOptions = tableOperationOptions self.trailingPaneState = trailingPaneState + self.catalogSnapshot = coordinator.catalogSnapshot self.tabManager = tabManager self.selectedEdits = coordinator.selectedTabEdits self.toolbarState = toolbarState @@ -532,6 +533,7 @@ struct MainContentView: View { coordinator: coordinator, historyState: HistoryPanelState.forConnection(connection.id), selectedEdits: selectedEdits, + catalogSnapshot: catalogSnapshot, connection: connection, windowId: windowId, connectionId: connection.id, diff --git a/apple/TableProTests/Core/Coordinators/CopyFromStandardInputRunTests.swift b/apple/TableProTests/Core/Coordinators/CopyFromStandardInputRunTests.swift index de62791f4c..9e1a513ccf 100644 --- a/apple/TableProTests/Core/Coordinators/CopyFromStandardInputRunTests.swift +++ b/apple/TableProTests/Core/Coordinators/CopyFromStandardInputRunTests.swift @@ -29,7 +29,7 @@ struct CopyFromStandardInputRunTests { let statements = SQLStatementScanner.executableStatements( in: script, grammar: fixture.coordinator.lexicalGrammar ) - fixture.coordinator.queryExecutionCoordinator.executeMultipleStatements(statements) + fixture.coordinator.queryExecutionCoordinator.executeMultipleStatements(statements, onTab: fixture.coordinator.commandTabId) let handle = try #require(fixture.coordinator.queryTasks.task(for: tab.id)) await handle.value return try #require(fixture.tabManager.tabs.first { $0.id == tab.id }) diff --git a/apple/TableProTests/Core/Coordinators/RunResultLimitTests.swift b/apple/TableProTests/Core/Coordinators/RunResultLimitTests.swift index 80a05afd60..33a5e33718 100644 --- a/apple/TableProTests/Core/Coordinators/RunResultLimitTests.swift +++ b/apple/TableProTests/Core/Coordinators/RunResultLimitTests.swift @@ -32,7 +32,7 @@ extension GlobalStateSuites { let tab = fixture.addTab(QueryTab(title: "Query", query: text, tabType: .query)) let runner: QueryExecutionCoordinator = fixture.coordinator.queryExecutionCoordinator - runner.executeBatches(runner.executionBatches(in: text), parameters: []) + runner.executeBatches(runner.executionBatches(in: text), parameters: [], onTab: tab.id) let handle = try #require(fixture.coordinator.queryTasks.task(for: tab.id)) await handle.value return try #require(fixture.tabManager.tabs.first { $0.id == tab.id }).display.resultSets diff --git a/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift b/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift index 27914afa19..013b9bdb47 100644 --- a/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift +++ b/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift @@ -100,7 +100,7 @@ struct RunAllSummaryResultTests { tabManager.tabs.append(tab) tabManager.selectedTabId = tab.id - coordinator.runAllStatements() + coordinator.runAllStatements(onTab: coordinator.commandTabId) try await waitUntil { !coordinator.tabExecution.isExecuting(tab.id) && tabManager.tabs.first?.display.resultSets.isEmpty == false } diff --git a/apple/TableProTests/Core/Coordinators/StoppedRunKeepsWorkTests.swift b/apple/TableProTests/Core/Coordinators/StoppedRunKeepsWorkTests.swift index 4ba335d3a8..3d335b6a79 100644 --- a/apple/TableProTests/Core/Coordinators/StoppedRunKeepsWorkTests.swift +++ b/apple/TableProTests/Core/Coordinators/StoppedRunKeepsWorkTests.swift @@ -135,7 +135,7 @@ struct StoppedRunKeepsWorkTests { let statements = SQLStatementScanner.executableStatements( in: Self.script, grammar: fixture.coordinator.lexicalGrammar ) - fixture.coordinator.queryExecutionCoordinator.executeMultipleStatements(statements) + fixture.coordinator.queryExecutionCoordinator.executeMultipleStatements(statements, onTab: fixture.coordinator.commandTabId) let handle = try #require(fixture.coordinator.queryTasks.task(for: tab.id)) return (tab.id, handle) } @@ -277,43 +277,3 @@ private final class HeldStatementDriver: DatabaseDriver, @unchecked Sendable { func commitTransaction() async throws {} func rollbackTransaction() async throws {} } - -@MainActor -private extension AppServices { - func recordingHistory(in queryHistoryManager: QueryHistoryManager) -> AppServices { - AppServices( - appEvents: appEvents, - appSettings: appSettings, - appSettingsStorage: appSettingsStorage, - connectionStorage: connectionStorage, - databaseManager: databaseManager, - pluginManager: pluginManager, - schemaService: schemaService, - schemaRefreshService: schemaRefreshService, - schemaProviderRegistry: schemaProviderRegistry, - catalogChangeService: catalogChangeService, - sqlFavoriteManager: sqlFavoriteManager, - favoriteTablesStorage: favoriteTablesStorage, - favoriteDatabasesStorage: favoriteDatabasesStorage, - tableFolderStorage: tableFolderStorage, - aiChatStorage: aiChatStorage, - aiKeyStorage: aiKeyStorage, - aiAccessApprovals: aiAccessApprovals, - groupStorage: groupStorage, - tagStorage: tagStorage, - sshProfileStorage: sshProfileStorage, - credentialProfileStorage: credentialProfileStorage, - featureAccess: featureAccess, - syncMetadataStorage: syncMetadataStorage, - favoritesExpansionState: favoritesExpansionState, - linkedFolderWatcher: linkedFolderWatcher, - queryHistoryManager: queryHistoryManager, - dateFormattingService: dateFormattingService, - copilotService: copilotService, - mcpServerManager: mcpServerManager, - syncTracker: syncTracker, - welcomeRouter: welcomeRouter, - telemetry: telemetry - ) - } -} diff --git a/apple/TableProTests/Core/Services/Telemetry/TelemetryTests.swift b/apple/TableProTests/Core/Services/Telemetry/TelemetryTests.swift index 55622df7f7..0e14703868 100644 --- a/apple/TableProTests/Core/Services/Telemetry/TelemetryTests.swift +++ b/apple/TableProTests/Core/Services/Telemetry/TelemetryTests.swift @@ -400,7 +400,7 @@ struct TelemetryTests { ) window.addTab(QueryTab(title: "Query 1", query: "SELECT 1", tabType: .query)) - window.coordinator.runQuery(viewport: .firstRow) + window.coordinator.runQuery(onTab: window.coordinator.commandTabId, viewport: .firstRow) try await waitUntil { fixture.client?.captured.contains("first_query_executed") == true } #expect(Array(fixture.client?.calls.dropFirst() ?? []) == [ diff --git a/apple/TableProTests/Helpers/CoordinatorFixture.swift b/apple/TableProTests/Helpers/CoordinatorFixture.swift index a2d7b5ccf9..fd6d821f8c 100644 --- a/apple/TableProTests/Helpers/CoordinatorFixture.swift +++ b/apple/TableProTests/Helpers/CoordinatorFixture.swift @@ -1,3 +1,4 @@ +import Foundation @testable import TablePro /// Tears the coordinator down when the fixture goes away: an untorn coordinator keeps its @@ -43,3 +44,49 @@ final class CoordinatorFixture { if injectedSession { DatabaseManager.shared.removeSession(for: connection.id) } } } + +extension MainContentCoordinator { + // What a menu command passes: the shown tab, or an id no tab has, so the command does nothing. + var commandTabId: UUID { tabManager.selectedTab?.id ?? UUID() } +} + +@MainActor +extension AppServices { + // Live services that write query history into the given manager, so a test can read what a run filed. + func recordingHistory(in queryHistoryManager: QueryHistoryManager) -> AppServices { + AppServices( + appEvents: appEvents, + appSettings: appSettings, + appSettingsStorage: appSettingsStorage, + connectionStorage: connectionStorage, + databaseManager: databaseManager, + pluginManager: pluginManager, + schemaService: schemaService, + schemaRefreshService: schemaRefreshService, + schemaProviderRegistry: schemaProviderRegistry, + catalogChangeService: catalogChangeService, + sqlFavoriteManager: sqlFavoriteManager, + favoriteTablesStorage: favoriteTablesStorage, + favoriteDatabasesStorage: favoriteDatabasesStorage, + tableFolderStorage: tableFolderStorage, + aiChatStorage: aiChatStorage, + aiKeyStorage: aiKeyStorage, + aiAccessApprovals: aiAccessApprovals, + groupStorage: groupStorage, + tagStorage: tagStorage, + sshProfileStorage: sshProfileStorage, + credentialProfileStorage: credentialProfileStorage, + featureAccess: featureAccess, + syncMetadataStorage: syncMetadataStorage, + favoritesExpansionState: favoritesExpansionState, + linkedFolderWatcher: linkedFolderWatcher, + queryHistoryManager: queryHistoryManager, + dateFormattingService: dateFormattingService, + copilotService: copilotService, + mcpServerManager: mcpServerManager, + syncTracker: syncTracker, + welcomeRouter: welcomeRouter, + telemetry: telemetry + ) + } +} diff --git a/apple/TableProTests/Views/Main/AuthorizedRunTargetTests.swift b/apple/TableProTests/Views/Main/AuthorizedRunTargetTests.swift index 0163e4f39c..b1bfa004ac 100644 --- a/apple/TableProTests/Views/Main/AuthorizedRunTargetTests.swift +++ b/apple/TableProTests/Views/Main/AuthorizedRunTargetTests.swift @@ -19,7 +19,7 @@ struct AuthorizedRunTargetTests { let asking = fixture.addTab(QueryTab(title: "A", query: "DELETE FROM orders", tabType: .query)) let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) - #expect(fixture.coordinator.runStatement("DELETE FROM orders")) + #expect(fixture.coordinator.runStatement("DELETE FROM orders", onTab: fixture.coordinator.commandTabId)) try await waitUntil { gate.askedCount == 1 } fixture.tabManager.selectedTabId = other.id await gate.answer(allowing: true) @@ -41,7 +41,7 @@ struct AuthorizedRunTargetTests { let asking = fixture.addTab(QueryTab(title: "A", query: "DELETE FROM orders", tabType: .query)) fixture.tabManager.mutate(tabId: asking.id) { $0.tableContext.databaseName = "staging" } - #expect(fixture.coordinator.runStatement("DELETE FROM orders")) + #expect(fixture.coordinator.runStatement("DELETE FROM orders", onTab: fixture.coordinator.commandTabId)) try await waitUntil { gate.askedCount == 1 } fixture.tabManager.mutate(tabId: asking.id) { $0.tableContext.databaseName = "production" } await gate.answer(allowing: true) @@ -60,7 +60,7 @@ struct AuthorizedRunTargetTests { let asking = fixture.addTab(QueryTab(title: "A", query: "DELETE FROM orders", tabType: .query)) let other = fixture.addTab(QueryTab(title: "B", query: "SELECT 1", tabType: .query), select: false) - #expect(fixture.coordinator.runStatement("DELETE FROM orders")) + #expect(fixture.coordinator.runStatement("DELETE FROM orders", onTab: fixture.coordinator.commandTabId)) try await waitUntil { gate.askedCount == 1 } fixture.tabManager.selectedTabId = other.id fixture.tabManager.tabs.swapAt(0, 1) diff --git a/apple/TableProTests/Views/Main/ExplainAuthorizationTests.swift b/apple/TableProTests/Views/Main/ExplainAuthorizationTests.swift index 528352be8e..7efdac17d4 100644 --- a/apple/TableProTests/Views/Main/ExplainAuthorizationTests.swift +++ b/apple/TableProTests/Views/Main/ExplainAuthorizationTests.swift @@ -128,8 +128,8 @@ struct ExplainAuthorizationTests { let harness = Harness(level: .alert, query: "SELECT 1", confirming: StubConfirming(answer: true)) defer { harness.tearDown() } - let first = harness.coordinator.runExplain(variant: Self.plan) - let second = harness.coordinator.runExplain(variant: Self.plan) + let first = harness.coordinator.runExplain(onTab: harness.coordinator.commandTabId, variant: Self.plan) + let second = harness.coordinator.runExplain(onTab: harness.coordinator.commandTabId, variant: Self.plan) await first?.value await harness.coordinator.queryTasks.task(for: harness.tabId)?.value @@ -230,7 +230,7 @@ struct ExplainAuthorizationTests { } func explain(_ variant: ExplainVariant) async { - await coordinator.runExplain(variant: variant)?.value + await coordinator.runExplain(onTab: coordinator.commandTabId, variant: variant)?.value await coordinator.queryTasks.task(for: tabId)?.value } diff --git a/apple/TableProTests/Views/Main/MainContentCoordinatorAutoRefreshTests.swift b/apple/TableProTests/Views/Main/MainContentCoordinatorAutoRefreshTests.swift index 69c5ad667e..e8ebb8fcc5 100644 --- a/apple/TableProTests/Views/Main/MainContentCoordinatorAutoRefreshTests.swift +++ b/apple/TableProTests/Views/Main/MainContentCoordinatorAutoRefreshTests.swift @@ -31,7 +31,7 @@ struct MainContentCoordinatorAutoRefreshTests { let harness = AutoRefreshHarness() defer { harness.tearDown() } - harness.coordinator.executeTableTabQueryDirectly(viewport: .keepPlace) + harness.coordinator.executeTableTabQueryDirectly(onTab: harness.coordinator.commandTabId, viewport: .keepPlace) await harness.coordinator.queryTasks.task(for: harness.tabId)?.value await harness.recordMarker() diff --git a/apple/TableProTests/Views/Main/MainContentCoordinatorSortTests.swift b/apple/TableProTests/Views/Main/MainContentCoordinatorSortTests.swift index 940dd8eae0..a46d579ade 100644 --- a/apple/TableProTests/Views/Main/MainContentCoordinatorSortTests.swift +++ b/apple/TableProTests/Views/Main/MainContentCoordinatorSortTests.swift @@ -223,7 +223,7 @@ struct MainContentCoordinatorSortTests { let harness = try await ParameterizedRunHarness.running( query: "INSERT INTO audit (msg) VALUES (:m);\nSELECT id, msg FROM audit WHERE msg = :m", parameterValue: "hello" - ) { coordinator in coordinator.runAllStatements() } + ) { coordinator in coordinator.runAllStatements(onTab: coordinator.commandTabId) } defer { harness.tearDown() } #expect(harness.driver.sentSQL.contains { $0.hasPrefix("INSERT") }) @@ -240,7 +240,7 @@ struct MainContentCoordinatorSortTests { let statement = "SELECT id, msg FROM audit WHERE msg = :m" let editorText = "DELETE FROM audit WHERE msg = :m;\n\(statement)" let harness = try await ParameterizedRunHarness.running(query: editorText, parameterValue: "hello") { coordinator in - coordinator.runStatement(statement, sourceOffset: (editorText as NSString).range(of: statement).location) + coordinator.runStatement(statement, sourceOffset: (editorText as NSString).range(of: statement).location, onTab: coordinator.commandTabId) } defer { harness.tearDown() } #expect(harness.driver.sentSQL.allSatisfy { !$0.contains("DELETE") }) @@ -260,7 +260,7 @@ struct MainContentCoordinatorSortTests { let harness = try await ParameterizedRunHarness.running( query: "SELECT id, msg FROM audit WHERE msg = :m", parameterValue: "hello" - ) { coordinator in coordinator.runStatement("SELECT id, msg FROM audit WHERE msg = :m") } + ) { coordinator in coordinator.runStatement("SELECT id, msg FROM audit WHERE msg = :m", onTab: coordinator.commandTabId) } defer { harness.tearDown() } harness.tabManager.mutate(tabId: harness.tabId) { $0.content.queryParameters = [QueryParameter(name: "m", value: "typed later")] @@ -280,7 +280,7 @@ struct MainContentCoordinatorSortTests { let harness = try await ParameterizedRunHarness.running( query: statement, parameters: [QueryParameter(name: "m", value: "hello"), QueryParameter(name: "pinned", value: "2")] - ) { coordinator in coordinator.runStatement(statement) } + ) { coordinator in coordinator.runStatement(statement, onTab: coordinator.commandTabId) } defer { harness.tearDown() } let sorted = try await harness.sort(byColumn: 1) @@ -298,7 +298,7 @@ struct MainContentCoordinatorSortTests { let statement = "SELECT id, msg FROM audit WHERE msg = :m" let editorText = "DELETE FROM audit WHERE msg = :m;\n\(statement)" let harness = try await ParameterizedRunHarness.running(query: editorText, parameterValue: "hello") { coordinator in - coordinator.runStatement(statement, sourceOffset: (editorText as NSString).range(of: statement).location) + coordinator.runStatement(statement, sourceOffset: (editorText as NSString).range(of: statement).location, onTab: coordinator.commandTabId) } defer { harness.tearDown() } @@ -314,7 +314,7 @@ struct MainContentCoordinatorSortTests { func reloadKeepsTheGridSort() async throws { let statement = "SELECT id, msg FROM audit WHERE msg = :m" let harness = try await ParameterizedRunHarness.running(query: statement, parameterValue: "hello") { coordinator in - coordinator.runStatement(statement) + coordinator.runStatement(statement, onTab: coordinator.commandTabId) } defer { harness.tearDown() } _ = try await harness.sort(byColumn: 1) @@ -331,7 +331,7 @@ struct MainContentCoordinatorSortTests { func reloadKeepsTheStatementsOwnOrderBy() async throws { let statement = "SELECT id, msg FROM audit WHERE msg = :m ORDER BY id DESC" let harness = try await ParameterizedRunHarness.running(query: statement, parameterValue: "hello") { coordinator in - coordinator.runStatement(statement) + coordinator.runStatement(statement, onTab: coordinator.commandTabId) } defer { harness.tearDown() } @@ -345,7 +345,7 @@ struct MainContentCoordinatorSortTests { func reloadKeepsTheValueFilter() async throws { let statement = "SELECT id, msg FROM audit WHERE msg = :m" let harness = try await ParameterizedRunHarness.running(query: statement, parameterValue: "hello") { coordinator in - coordinator.runStatement(statement) + coordinator.runStatement(statement, onTab: coordinator.commandTabId) } defer { harness.tearDown() } var filter = GridValueFilterState() @@ -361,7 +361,7 @@ struct MainContentCoordinatorSortTests { func runDropsTheGridSort() async throws { let statement = "SELECT id, msg FROM audit WHERE msg = :m" let harness = try await ParameterizedRunHarness.running(query: statement, parameterValue: "hello") { coordinator in - coordinator.runStatement(statement) + coordinator.runStatement(statement, onTab: coordinator.commandTabId) } defer { harness.tearDown() } _ = try await harness.sort(byColumn: 1) @@ -380,7 +380,7 @@ struct MainContentCoordinatorSortTests { written.baseQuery = "UPDATE users SET name = 'x' WHERE id = 1 RETURNING id, name" tabManager.mutate(at: idx) { $0.display.replaceUnpinnedResults(with: [written]) } - #expect(!coordinator.rerunActiveResult(.statement(written.baseQuery ?? ""), viewport: .keepPlace)) + #expect(!coordinator.rerunActiveResult(.statement(written.baseQuery ?? ""), viewport: .keepPlace, onTab: coordinator.commandTabId)) } @Test("A re-read lands only on its own result and database, and starts only on the selected tab") @@ -419,13 +419,13 @@ struct MainContentCoordinatorSortTests { func reloadDroppedWhenTheResultChangesFirst() async throws { let statement = "SELECT id, msg FROM audit WHERE msg = :m" let harness = try await ParameterizedRunHarness.running(query: statement, parameterValue: "hello") { coordinator in - coordinator.runStatement(statement) + coordinator.runStatement(statement, onTab: coordinator.commandTabId) } defer { harness.tearDown() } let alreadySent = harness.driver.sent.count let other = ResultSet(label: "Result 2", tableRows: TableRows()) - harness.coordinator.reloadActiveResult() + harness.coordinator.reloadActiveResult(onTab: harness.coordinator.commandTabId) harness.tabManager.mutate(tabId: harness.tabId) { tab in tab.display.resultSets.append(other) tab.display.activeResultSetId = other.id @@ -446,7 +446,7 @@ struct MainContentCoordinatorSortTests { func reloadKeepsAPinnedResultInItsPlace() async throws { let statement = "SELECT id, msg FROM audit WHERE msg = :m" let harness = try await ParameterizedRunHarness.running(query: statement, parameterValue: "hello") { coordinator in - coordinator.runStatement(statement) + coordinator.runStatement(statement, onTab: coordinator.commandTabId) } defer { harness.tearDown() } let before = try #require(harness.tabManager.tabs.first { $0.id == harness.tabId }?.display.activeResultSet) @@ -471,7 +471,7 @@ struct MainContentCoordinatorSortTests { func headerClickDuringRunLeavesNothingForTheNextRun(ending: InFlightRunEnding) async throws { let statement = "SELECT id, msg FROM audit WHERE msg = :m" let harness = try await ParameterizedRunHarness.running(query: statement, parameterValue: "hello") { coordinator in - coordinator.runStatement(statement) + coordinator.runStatement(statement, onTab: coordinator.commandTabId) } defer { harness.tearDown() } let alreadySent = harness.driver.sent.count @@ -503,7 +503,7 @@ struct MainContentCoordinatorSortTests { ]) func sortAfterFetchAllRerunsItsOwnStatement(script: String) async throws { let harness = try await ParameterizedRunHarness.running(query: script, parameterValue: "hello") { coordinator in - coordinator.runAllStatements() + coordinator.runAllStatements(onTab: coordinator.commandTabId) } defer { harness.tearDown() } try await harness.fetchAll() @@ -820,7 +820,7 @@ private struct ParameterizedRunHarness { /// Reads the result again the way a save does and returns every statement that sent. func reload() async throws -> [SentStatement] { let alreadySent = driver.sent.count - coordinator.reloadActiveResult() + coordinator.reloadActiveResult(onTab: coordinator.commandTabId) try await waitUntilIdle { driver.sent.dropFirst(alreadySent).contains { $0.sql.hasPrefix(Self.resultPrefix) } } @@ -830,7 +830,7 @@ private struct ParameterizedRunHarness { /// Presses Run with the caret where it is and returns every statement the run sent. func runAtCaret() async throws -> [SentStatement] { let alreadySent = driver.sent.count - coordinator.runQuery(viewport: .firstRow) + coordinator.runQuery(onTab: coordinator.commandTabId, viewport: .firstRow) try await waitUntilIdle { driver.sent.dropFirst(alreadySent).contains { $0.sql.hasPrefix(Self.resultPrefix) } } diff --git a/apple/TableProTests/Views/Main/MainViewInvalidationTests.swift b/apple/TableProTests/Views/Main/MainViewInvalidationTests.swift new file mode 100644 index 0000000000..6d18d31421 --- /dev/null +++ b/apple/TableProTests/Views/Main/MainViewInvalidationTests.swift @@ -0,0 +1,99 @@ +// +// MainViewInvalidationTests.swift +// TableProTests +// + +import Combine +import Foundation +@testable import TablePro +import TableProTestSupport +import Testing + +@MainActor +struct MainViewInvalidationTests { + private final class PublishCounter { + private(set) var count = 0 + private var subscription: AnyCancellable? + + init(_ publisher: some Publisher) { + subscription = publisher.sink { [weak self] _ in self?.count += 1 } + } + } + + private static func manager(with tabs: [QueryTab]) -> QueryTabManager { + let manager = QueryTabManager() + manager.tabs = tabs + manager.selectedTabId = tabs.first?.id + return manager + } + + @Test("Typing into the editor stores the text without publishing the tab list") + func keystrokeDoesNotPublishTabs() { + let tab = QueryTab(title: "Query 1", query: "SELECT 1", tabType: .query) + let manager = Self.manager(with: [tab, QueryTab(title: "Query 2", tabType: .query)]) + _ = manager.visibleTabs + let counter = PublishCounter(manager.objectWillChange.map { _ in () }) + + #expect(manager.setEditorText("SELECT 12", ofTab: tab.id)) + #expect(manager.setEditorText("SELECT 123", ofTab: tab.id)) + + #expect(counter.count == 0) + #expect(manager.tabs.first?.content.query == "SELECT 123") + #expect(manager.visibleTabs.first?.content.query == "SELECT 123") + #expect(manager.selectedTab?.content.query == "SELECT 123") + } + + @Test("A keystroke that empties or fills the editor still publishes, so Run and the unsaved dot follow it") + func emptinessFlipPublishes() { + let tab = QueryTab(title: "Query 1", query: "", tabType: .query) + let manager = Self.manager(with: [tab]) + let counter = PublishCounter(manager.objectWillChange.map { _ in () }) + + manager.setEditorText("S", ofTab: tab.id) + #expect(counter.count == 1) + manager.setEditorText("SE", ofTab: tab.id) + #expect(counter.count == 1) + manager.setEditorText("", ofTab: tab.id) + #expect(counter.count == 2) + #expect(manager.tabs.first?.content.query == "") + } + + @Test("Text for a tab the manager does not hold is refused") + func unknownTabIsRefused() { + let manager = Self.manager(with: [QueryTab(title: "Query 1", tabType: .query)]) + #expect(!manager.setEditorText("SELECT 1", ofTab: UUID())) + } + + // The snapshot reads the services a run loop turn after they publish; this waits out that turn. + private static func drainMainRunLoop() async { + await withCheckedContinuation { continuation in + RunLoop.main.perform { continuation.resume() } + } + } + + @Test("Another connection's catalog load leaves this connection's snapshot quiet") + func otherConnectionLoadIsSilent() async throws { + let mine = TestFixtures.makeConnection(name: "Mine") + let other = TestFixtures.makeConnection(name: "Other") + let schemaService = SchemaService() + let snapshot = ConnectionCatalogSnapshot( + connectionId: mine.id, + schemaService: schemaService, + treeService: DatabaseTreeMetadataService.shared + ) + let counter = PublishCounter(snapshot.objectWillChange.map { _ in () }) + + let otherDriver = MockDatabaseDriver(connection: other) + otherDriver.tablesToReturn = [TestFixtures.makeTableInfo(name: "events", type: .table)] + await schemaService.reload(connectionId: other.id, driver: otherDriver, connection: other) + await Self.drainMainRunLoop() + #expect(schemaService.tables(for: other.id).map(\.name) == ["events"]) + #expect(counter.count == 0) + + let mineDriver = MockDatabaseDriver(connection: mine) + mineDriver.tablesToReturn = [TestFixtures.makeTableInfo(name: "orders", type: .table)] + await schemaService.reload(connectionId: mine.id, driver: mineDriver, connection: mine) + try await waitUntil { snapshot.tables.map(\.name) == ["orders"] } + #expect(counter.count >= 1) + } +} diff --git a/apple/TableProTests/Views/Main/QueryParameterDetectionTests.swift b/apple/TableProTests/Views/Main/QueryParameterDetectionTests.swift index 1934076d2e..061052e444 100644 --- a/apple/TableProTests/Views/Main/QueryParameterDetectionTests.swift +++ b/apple/TableProTests/Views/Main/QueryParameterDetectionTests.swift @@ -29,7 +29,7 @@ extension GlobalStateSuites { let harness = QueryTabHarness(type: .elasticsearch, query: query) defer { harness.tearDown() } - #expect(harness.coordinator.runStatement(query, sourceOffset: 0)) + #expect(harness.coordinator.runStatement(query, sourceOffset: 0, onTab: harness.coordinator.commandTabId)) let tab = try #require(harness.tabManager.tabs.first) #expect(tab.content.queryParameters.isEmpty) @@ -42,7 +42,7 @@ extension GlobalStateSuites { let harness = QueryTabHarness(type: .mysql, query: query) defer { harness.tearDown() } - #expect(!harness.coordinator.runStatement(query, sourceOffset: 0)) + #expect(!harness.coordinator.runStatement(query, sourceOffset: 0, onTab: harness.coordinator.commandTabId)) let tab = try #require(harness.tabManager.tabs.first) #expect(tab.content.queryParameters.map(\.name) == ["name"]) diff --git a/apple/TableProTests/Views/Main/QueryTabVersionTriggerTests.swift b/apple/TableProTests/Views/Main/QueryTabVersionTriggerTests.swift index 1a0301d4ba..48970e215c 100644 --- a/apple/TableProTests/Views/Main/QueryTabVersionTriggerTests.swift +++ b/apple/TableProTests/Views/Main/QueryTabVersionTriggerTests.swift @@ -51,7 +51,7 @@ struct QueryTabVersionTriggerTests { func runRecordsTheText() async throws { let (fixture, tab, _) = makeFixture(query: "SELECT 1") - fixture.coordinator.runQuery(viewport: .firstRow) + fixture.coordinator.runQuery(onTab: fixture.coordinator.commandTabId, viewport: .firstRow) try await waitUntil { !storage.summaries(tabId: tab.id).isEmpty } let recorded = versions(of: tab.id) @@ -63,7 +63,7 @@ struct QueryTabVersionTriggerTests { func runAllRecordsTheText() async throws { let (fixture, tab, _) = makeFixture(query: "SELECT 1; SELECT 2") - fixture.coordinator.runAllStatements() + fixture.coordinator.runAllStatements(onTab: fixture.coordinator.commandTabId) try await waitUntil { !storage.summaries(tabId: tab.id).isEmpty } #expect(versions(of: tab.id).first?.text == "SELECT 1; SELECT 2") @@ -128,7 +128,7 @@ struct QueryTabVersionTriggerTests { let (fixture, tab, clock) = makeFixture(query: "SELECT secret") capture.isPaused = true - fixture.coordinator.runQuery(viewport: .firstRow) + fixture.coordinator.runQuery(onTab: fixture.coordinator.commandTabId, viewport: .firstRow) fixture.coordinator.loadQueryIntoEditor("SELECT other") #expect(fixture.coordinator.tabVersions.record(tab, connectionId: fixture.connection.id, reason: .run) == nil) diff --git a/apple/TableProTests/Views/Main/ReadOnlySafeModeEntryPointTests.swift b/apple/TableProTests/Views/Main/ReadOnlySafeModeEntryPointTests.swift index 0032a8c583..99559c2214 100644 --- a/apple/TableProTests/Views/Main/ReadOnlySafeModeEntryPointTests.swift +++ b/apple/TableProTests/Views/Main/ReadOnlySafeModeEntryPointTests.swift @@ -219,7 +219,7 @@ struct ReadOnlySafeModeEntryPointTests { defer { fixture.coordinator.cancelAllQueryTasks() } fixture.addTab(QueryTab(title: "Query", query: "SELECT purge_orders()", tabType: .query)) - #expect(fixture.coordinator.runStatement("SELECT purge_orders()")) + #expect(fixture.coordinator.runStatement("SELECT purge_orders()", onTab: fixture.coordinator.commandTabId)) try await waitUntil { driver.call(containing: Self.purge) != nil } #expect(driver.call(containing: Self.purge)?.context?.enforcesReadOnly == true) @@ -231,7 +231,7 @@ struct ReadOnlySafeModeEntryPointTests { defer { fixture.coordinator.cancelAllQueryTasks() } fixture.addTab(QueryTab(title: "Query", query: "SELECT purge_orders()", tabType: .query)) - #expect(fixture.coordinator.runStatement("SELECT purge_orders()")) + #expect(fixture.coordinator.runStatement("SELECT purge_orders()", onTab: fixture.coordinator.commandTabId)) try await waitUntil { driver.call(containing: Self.purge) != nil } #expect(driver.call(containing: Self.purge)?.context?.enforcesReadOnly != true) @@ -245,7 +245,7 @@ struct ReadOnlySafeModeEntryPointTests { defer { fixture.coordinator.cancelAllQueryTasks() } fixture.addTab(QueryTab(title: "Query", query: "SELECT purge_orders();\nSELECT 42", tabType: .query)) - fixture.coordinator.queryExecutionCoordinator.runAllStatements() + fixture.coordinator.runAllStatements(onTab: fixture.coordinator.commandTabId) try await waitUntil { driver.call(containing: "42") != nil } let statements = driver.calls.filter { $0.query.contains(Self.purge) || $0.query.contains("42") } @@ -260,7 +260,7 @@ struct ReadOnlySafeModeEntryPointTests { defer { fixture.coordinator.cancelAllQueryTasks() } fixture.addTab(QueryTab(title: "Query", query: "SELECT purge_orders();\nSELECT 42", tabType: .query)) - fixture.coordinator.queryExecutionCoordinator.runAllStatements() + fixture.coordinator.runAllStatements(onTab: fixture.coordinator.commandTabId) try await waitUntil { driver.entries.contains("COMMIT") } let entries = driver.entries @@ -280,7 +280,7 @@ struct ReadOnlySafeModeEntryPointTests { defer { fixture.coordinator.cancelAllQueryTasks() } fixture.addTab(rawFilterTableTab()) - #expect(fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) == nil) + #expect(fixture.coordinator.executeTableTabQueryDirectly(onTab: fixture.coordinator.commandTabId, viewport: .firstRow) == nil) try await waitUntil { driver.call(containing: Self.purge) != nil } #expect(await gate.requests.isEmpty) @@ -295,11 +295,11 @@ struct ReadOnlySafeModeEntryPointTests { defer { fixture.coordinator.cancelAllQueryTasks() } let tab = fixture.addTab(rawFilterTableTab()) - let first = fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) + let first = fixture.coordinator.executeTableTabQueryDirectly(onTab: fixture.coordinator.commandTabId, viewport: .firstRow) #expect(first != nil) await first?.value try await waitUntil { driver.call(containing: Self.purge) != nil } - let second = fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) + let second = fixture.coordinator.executeTableTabQueryDirectly(onTab: fixture.coordinator.commandTabId, viewport: .firstRow) #expect(second != nil) await second?.value @@ -329,7 +329,7 @@ struct ReadOnlySafeModeEntryPointTests { defer { fixture.coordinator.cancelAllQueryTasks() } fixture.addTab(QueryTab(title: "order_cleanup", query: "SELECT * FROM order_cleanup LIMIT 100", tabType: .table, tableName: "order_cleanup")) - #expect(fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) == nil) + #expect(fixture.coordinator.executeTableTabQueryDirectly(onTab: fixture.coordinator.commandTabId, viewport: .firstRow) == nil) try await waitUntil { driver.call(containing: "FROM order_cleanup") != nil } #expect(await gate.requests.isEmpty) @@ -631,7 +631,7 @@ struct ReadOnlySafeModeEntryPointTests { defer { fixture.coordinator.cancelAllQueryTasks() } fixture.addTab(rawFilterTableTab()) - let refusal = fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) + let refusal = fixture.coordinator.executeTableTabQueryDirectly(onTab: fixture.coordinator.commandTabId, viewport: .firstRow) #expect(refusal != nil) await refusal?.value diff --git a/apple/TableProTests/Views/Main/ResultRowsBuildOffMainTests.swift b/apple/TableProTests/Views/Main/ResultRowsBuildOffMainTests.swift index ce095016eb..6f2b1ec452 100644 --- a/apple/TableProTests/Views/Main/ResultRowsBuildOffMainTests.swift +++ b/apple/TableProTests/Views/Main/ResultRowsBuildOffMainTests.swift @@ -141,7 +141,7 @@ struct ResultRowsBuildOffMainTests { let tab = fixture.addTab(QueryTab(title: "Query", query: "SELECT * FROM users", tabType: .query)) let runner: QueryExecutionCoordinator = fixture.coordinator.queryExecutionCoordinator - runner.executeBatches(runner.executionBatches(in: "SELECT * FROM users"), parameters: []) + runner.executeBatches(runner.executionBatches(in: "SELECT * FROM users"), parameters: [], onTab: tab.id) let handle = try #require(fixture.coordinator.queryTasks.task(for: tab.id)) await handle.value return try #require(fixture.tabManager.tabs.first { $0.id == tab.id }).display.resultSets diff --git a/apple/TableProTests/Views/Main/RunDiscardGuardTests.swift b/apple/TableProTests/Views/Main/RunDiscardGuardTests.swift index 662d476199..599c230e51 100644 --- a/apple/TableProTests/Views/Main/RunDiscardGuardTests.swift +++ b/apple/TableProTests/Views/Main/RunDiscardGuardTests.swift @@ -23,7 +23,7 @@ struct RunDiscardGuardTests { func runStatementAsksFirst() { let (fixture, tabId) = makeEditedResult() - #expect(!fixture.coordinator.runStatement("SELECT * FROM users")) + #expect(!fixture.coordinator.runStatement("SELECT * FROM users", onTab: fixture.coordinator.commandTabId)) #expect(fixture.changeManager.hasChanges) #expect(!fixture.coordinator.isShowingSafeModePrompt) @@ -34,8 +34,8 @@ struct RunDiscardGuardTests { func runAndRunAllAskFirst() { let (fixture, tabId) = makeEditedResult() - fixture.coordinator.runQuery(viewport: .firstRow) - fixture.coordinator.runAllStatements() + fixture.coordinator.runQuery(onTab: fixture.coordinator.commandTabId, viewport: .firstRow) + fixture.coordinator.runAllStatements(onTab: fixture.coordinator.commandTabId) #expect(fixture.changeManager.hasChanges) #expect(!fixture.coordinator.isShowingSafeModePrompt) @@ -50,6 +50,6 @@ struct RunDiscardGuardTests { fixture.changeManager.hasChanges = true fixture.coordinator.isShowingConfirmAlert = true - #expect(fixture.coordinator.runStatement("SELECT 1")) + #expect(fixture.coordinator.runStatement("SELECT 1", onTab: fixture.coordinator.commandTabId)) } } diff --git a/apple/TableProTests/Views/Main/ScriptErrorResultTests.swift b/apple/TableProTests/Views/Main/ScriptErrorResultTests.swift index bf13db0680..af920e17a3 100644 --- a/apple/TableProTests/Views/Main/ScriptErrorResultTests.swift +++ b/apple/TableProTests/Views/Main/ScriptErrorResultTests.swift @@ -34,7 +34,7 @@ struct ScriptErrorResultTests { tabManager.tabs.append(tab) tabManager.selectedTabId = tab.id - coordinator.runAllStatements() + coordinator.runAllStatements(onTab: coordinator.commandTabId) try await waitUntil { !coordinator.tabExecution.isExecuting(tab.id) && tabManager.tabs.first?.display.resultSets.last?.errorMessage != nil diff --git a/apple/TableProTests/Views/Main/TabQueryIsolationTests.swift b/apple/TableProTests/Views/Main/TabQueryIsolationTests.swift index 3ac5d6f381..d1861836b2 100644 --- a/apple/TableProTests/Views/Main/TabQueryIsolationTests.swift +++ b/apple/TableProTests/Views/Main/TabQueryIsolationTests.swift @@ -35,17 +35,17 @@ struct TabQueryIsolationTests { @Test("Running a query in another tab leaves the first tab's batch alone") func runQueryLeavesTheOtherTabAlone() async { await withTwoTabs { coordinator, _, _ in - coordinator.executeQueryInternal("SELECT 1") + coordinator.executeQueryInternal("SELECT 1", onTab: coordinator.commandTabId) } } @Test("Running a parameterized query in another tab leaves the first tab's batch alone") func parameterizedQueryLeavesTheOtherTabAlone() async { await withTwoTabs { coordinator, _, _ in - coordinator.queryExecutionCoordinator.executeQueryInternalParameterized( - "SELECT ?", - parameters: ["1"], - originalParameters: [] + coordinator.queryExecutionCoordinator.executeQueryWithParameters( + "SELECT :id", + parameters: [QueryParameter(name: "id", value: "1")], + onTab: coordinator.commandTabId ) } } @@ -55,7 +55,8 @@ struct TabQueryIsolationTests { await withTwoTabs { coordinator, _, _ in coordinator.queryExecutionCoordinator.executeMultipleStatementsWithParameters( SQLStatementScanner.executableStatements(in: "SELECT 1; SELECT 2"), - parameters: [] + parameters: [], + onTab: coordinator.commandTabId ) } } @@ -67,6 +68,7 @@ struct TabQueryIsolationTests { await withTwoTabs { coordinator, _, _ in coordinator.executionGate = AlwaysAllowGate() await coordinator.runExplain( + onTab: coordinator.commandTabId, variant: ExplainVariant(id: "plain", label: "Explain", sqlPrefix: "EXPLAIN") )?.value } diff --git a/apple/TableProTests/Views/Main/TabRunLifecycleTests.swift b/apple/TableProTests/Views/Main/TabRunLifecycleTests.swift new file mode 100644 index 0000000000..07241c8a59 --- /dev/null +++ b/apple/TableProTests/Views/Main/TabRunLifecycleTests.swift @@ -0,0 +1,159 @@ +// +// TabRunLifecycleTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import TableProSQLGrammar +import TableProTestSupport +import Testing + +@MainActor +struct TabRunLifecycleTests { + private let connection: DatabaseConnection + private let storage: QueryHistoryStorage + private let fixture: CoordinatorFixture + private let driver: MockDatabaseDriver + + init() { + let connection = TestFixtures.makeConnection(database: "app") + let storage = QueryHistoryStorage( + databaseURL: FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-tests") + .appendingPathComponent("tab_run_\(UUID().uuidString).db"), + removeDatabaseOnDeinit: true + ) + self.connection = connection + self.storage = storage + driver = MockDatabaseDriver(connection: connection) + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connected + session.browseDatabase = "app" + DatabaseManager.shared.injectSession(session, for: connection.id) + fixture = CoordinatorFixture( + connection: connection, + services: .live.recordingHistory(in: QueryHistoryManager(storage: storage, isCapturePaused: { false })) + ) + fixture.coordinator.executionGate = AlwaysAllowGate() + } + + private func tearDown() { + fixture.coordinator.cancelAllQueryTasks() + DatabaseManager.shared.removeSession(for: connection.id) + } + + private func queryTab(_ query: String, select: Bool = true) -> QueryTab { + var tab = QueryTab(title: "Query", query: query, tabType: .query) + tab.tableContext.databaseName = "app" + tab.tableContext.schemaName = "sales" + return fixture.addTab(tab, select: select) + } + + private func tableTab(_ name: String, select: Bool) -> QueryTab { + var tab = QueryTab(title: name, query: "SELECT * FROM \(name)", tabType: .table, tableName: name) + tab.tableContext.databaseName = "app" + return fixture.addTab(tab, select: select) + } + + @Test("Every statement of a script is filed in history under the tab's schema, like a single statement") + func statementRunHistoryCarriesTheSchema() async throws { + defer { tearDown() } + let script = "INSERT INTO t VALUES (1);\nINSERT INTO t VALUES (2);" + let tab = queryTab(script) + let statements = SQLStatementScanner.executableStatements(in: script, grammar: fixture.coordinator.lexicalGrammar) + + fixture.coordinator.queryExecutionCoordinator.executeMultipleStatements(statements, onTab: tab.id) + await fixture.coordinator.queryTasks.task(for: tab.id)?.value + + let scope = QueryHistoryScope.connection(connection.id) + try await waitUntil { await storage.count(scope: scope) == 2 } + let entries = await storage.fetch(QueryHistoryFilter(scope: scope), after: nil, limit: 3).entries + #expect(entries.count == 2) + #expect(entries.allSatisfy { $0.schemaName == "sales" && $0.databaseName == "app" }) + } + + @Test("Run All saves the tab list the way Run does") + func runAllSavesTheTabList() { + defer { tearDown() } + let tab = queryTab("SELECT 1;\nSELECT 2;") + let before = fixture.tabManager.tabStructureVersion + + fixture.coordinator.runAllStatements(onTab: tab.id) + + #expect(fixture.tabManager.tabStructureVersion == before + 1) + } + + @Test("A result that lands in a background tab leaves the window's results toggle alone") + func backgroundResultLeavesTheToolbarAlone() { + defer { tearDown() } + let background = queryTab("SELECT 1", select: false) + fixture.tabManager.mutate(tabId: background.id) { $0.display.isResultsCollapsed = true } + _ = queryTab("SELECT 2") + fixture.coordinator.toolbarState.isResultsCollapsed = true + + fixture.coordinator.queryExecutionCoordinator.presentMultiStatementResults( + tabId: background.id, + timing: PluginQueryTiming(total: 0.1), + totalRowsAffected: 1, + newResultSets: [ResultSet(label: "Result 1", tableRows: TableRows())], + sessionNotice: nil + ) + + #expect(fixture.coordinator.toolbarState.isResultsCollapsed) + #expect(fixture.tabManager.tabs.first { $0.id == background.id }?.display.isResultsCollapsed == false) + } + + @Test("Run names its tab: a query tab the editor is not showing is refused") + func runRefusesAQueryTabTheEditorIsNotShowing() { + defer { tearDown() } + let hidden = queryTab("SELECT 1", select: false) + let shown = queryTab("SELECT 2") + + fixture.coordinator.runQuery(onTab: hidden.id, viewport: .firstRow) + #expect(fixture.coordinator.runStatement("SELECT 1", onTab: hidden.id) == false) + + #expect(!fixture.coordinator.tabExecution.isExecuting(hidden.id)) + #expect(!fixture.coordinator.tabExecution.isExecuting(shown.id)) + #expect(fixture.tabManager.selectedTabId == shown.id) + } + + @Test("A reload of a background table tab runs that tab, not the selected one") + func tableReloadRunsTheTabItNames() { + defer { tearDown() } + let background = tableTab("orders", select: false) + let shown = tableTab("customers", select: true) + + fixture.coordinator.runQuery(onTab: background.id, viewport: .keepPlace) + + #expect(fixture.coordinator.tabExecution.isExecuting(background.id)) + #expect(!fixture.coordinator.tabExecution.isExecuting(shown.id)) + } + + @Test("A script still running when its window closes unwinds without reaching a released coordinator") + func statementRunOutlivesItsWindow() async throws { + defer { tearDown() } + let gate = AsyncGate() + driver.executeGate = gate + let tabManager = QueryTabManager() + var coordinator: MainContentCoordinator? = MainContentCoordinator( + connection: connection, + tabManager: tabManager, + toolbarState: ConnectionToolbarState() + ) + let script = "INSERT INTO t VALUES (1);\nINSERT INTO t VALUES (2);" + let tab = QueryTab(title: "Query", query: script, tabType: .query) + tabManager.tabs = [tab] + tabManager.selectedTabId = tab.id + let statements = SQLStatementScanner.executableStatements(in: script, grammar: try #require(coordinator).lexicalGrammar) + try #require(coordinator).queryExecutionCoordinator.executeMultipleStatements(statements, onTab: tab.id) + let handle = try #require(coordinator?.queryTasks.task(for: tab.id)) + await gate.arrived(1) + + coordinator?.teardown() + coordinator = nil + await gate.open() + await handle.value + } +} diff --git a/apple/TableProTests/Views/Main/TableLoadAfterSafeModePromptTests.swift b/apple/TableProTests/Views/Main/TableLoadAfterSafeModePromptTests.swift index 920544485f..60e7160fb2 100644 --- a/apple/TableProTests/Views/Main/TableLoadAfterSafeModePromptTests.swift +++ b/apple/TableProTests/Views/Main/TableLoadAfterSafeModePromptTests.swift @@ -21,13 +21,13 @@ struct TableLoadAfterSafeModePromptTests { defer { fixture.coordinator.cancelAllQueryTasks() } fixture.addTab(QueryTab(title: "Query", query: "SELECT 1", tabType: .query)) - #expect(fixture.coordinator.runStatement("SELECT 1")) + #expect(fixture.coordinator.runStatement("SELECT 1", onTab: fixture.coordinator.commandTabId)) try await waitUntil { gate.askedCount == 1 } var table = QueryTab(title: "users", query: "SELECT * FROM users LIMIT 1000", tabType: .table, tableName: "users") table.pagination.isLoading = true fixture.addTab(table) - #expect(fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) == nil) + #expect(fixture.coordinator.executeTableTabQueryDirectly(onTab: fixture.coordinator.commandTabId, viewport: .firstRow) == nil) #expect(fixture.tabManager.tabs.first { $0.id == table.id }?.pagination.isLoading == false) await gate.answer(allowing: true) diff --git a/apple/TableProTests/Views/Main/TableLoadConfirmationTests.swift b/apple/TableProTests/Views/Main/TableLoadConfirmationTests.swift index 649b394295..db09c161fc 100644 --- a/apple/TableProTests/Views/Main/TableLoadConfirmationTests.swift +++ b/apple/TableProTests/Views/Main/TableLoadConfirmationTests.swift @@ -16,7 +16,7 @@ struct TableLoadConfirmationTests { defer { harness.tearDown() } let tabId = harness.addTableTab("users") - let confirmation = harness.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) + let confirmation = harness.coordinator.executeTableTabQueryDirectly(onTab: tabId, viewport: .firstRow) await harness.gate.release() await confirmation?.value @@ -34,7 +34,7 @@ struct TableLoadConfirmationTests { defer { harness.tearDown() } let firstId = harness.addTableTab("users") - let confirmation = harness.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) + let confirmation = harness.coordinator.executeTableTabQueryDirectly(onTab: firstId, viewport: .firstRow) await harness.gate.untilAsked() let secondId = harness.addTableTab("orders") await harness.gate.release() diff --git a/apple/TableProTests/Views/Main/TableLoadForeignKeyPrefetchTests.swift b/apple/TableProTests/Views/Main/TableLoadForeignKeyPrefetchTests.swift index 997eef8b29..73f465e477 100644 --- a/apple/TableProTests/Views/Main/TableLoadForeignKeyPrefetchTests.swift +++ b/apple/TableProTests/Views/Main/TableLoadForeignKeyPrefetchTests.swift @@ -36,7 +36,7 @@ struct TableLoadForeignKeyPrefetchTests { tabManager.selectedTabId = tab.id let scope = try #require(coordinator.scope(for: tab)) - coordinator.executeQueryInternal("SELECT * FROM orders") + coordinator.executeQueryInternal("SELECT * FROM orders", onTab: coordinator.commandTabId) _ = try? await waitUntil { paused.isRaised } try #require(paused.isRaised, "The row query never reached the driver") From e5f12d489d2288e7b6a8c92feb4058149ce635de Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Sun, 15 Nov 2026 01:33:00 +0700 Subject: [PATCH 2/2] fix(edits): restore a tab's rows with every confirmed discard, so a reload that never lands leaves no untracked edits --- .../Views/Main/Child/DataTabGridAdapter.swift | 2 +- .../MainContentCoordinator+ChangeGuard.swift | 28 ++++--------------- ...nContentCoordinator+ColumnVisibility.swift | 4 +-- ...inContentCoordinator+ContainerChange.swift | 2 +- .../MainContentCoordinator+ExecuteAll.swift | 2 +- apple/changelog.d/4286.changed.md | 1 + apple/changelog.d/4286.fixed.1.md | 1 + apple/changelog.d/4286.fixed.md | 1 + 8 files changed, 13 insertions(+), 28 deletions(-) create mode 100644 apple/changelog.d/4286.changed.md create mode 100644 apple/changelog.d/4286.fixed.1.md create mode 100644 apple/changelog.d/4286.fixed.md diff --git a/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift b/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift index 7a43968b12..6134fb01bc 100644 --- a/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift +++ b/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift @@ -141,7 +141,7 @@ final class DataTabGridAdapter: DataGridDataSource, DataGridActions { apply() return } - coordinator.confirmDiscardRestoringRowsIfNeeded(action: .displayOrder) { confirmed in + coordinator.confirmDiscardChangesIfNeeded(action: .displayOrder) { confirmed in guard confirmed else { return } apply() } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift index 77c015e5ef..d36abcb28e 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ChangeGuard.swift @@ -11,7 +11,7 @@ extension MainContentCoordinator { action: DiscardAction, completion: @escaping (Bool) -> Void ) { - confirmDiscard(forTab: tabManager.selectedTabId, action: action, restoringRows: false, completion: completion) + confirmDiscard(forTab: tabManager.selectedTabId, action: action, completion: completion) } func confirmDiscardChangesIfNeeded( @@ -19,30 +19,14 @@ extension MainContentCoordinator { action: DiscardAction, completion: @escaping (Bool) -> Void ) { - confirmDiscard(forTab: tabId, action: action, restoringRows: false, completion: completion) + confirmDiscard(forTab: tabId, action: action, completion: completion) } - // Not the plain gate: a value filter keeps the loaded rows, so edited values would stay on screen untracked (#2667). - func confirmDiscardRestoringRowsIfNeeded( - action: DiscardAction, - completion: @escaping (Bool) -> Void - ) { - confirmDiscard(forTab: tabManager.selectedTabId, action: action, restoringRows: true, completion: completion) - } - - func confirmDiscardRestoringRowsIfNeeded( - forTab tabId: UUID, - action: DiscardAction, - completion: @escaping (Bool) -> Void - ) { - confirmDiscard(forTab: tabId, action: action, restoringRows: true, completion: completion) - } - - // The tab is fixed before the alert: the selection can move while it is up, and its edits are the ones asked about. + // The tab is fixed before the alert, since the selection can move while it is up. Its rows go back to their + // originals with the edits: a reload that is refused, fails or never runs would leave edited values on screen untracked (#2667). private func confirmDiscard( forTab tabId: UUID?, action: DiscardAction, - restoringRows: Bool, completion: @escaping (Bool) -> Void ) { commitActiveGridEdit() @@ -68,9 +52,7 @@ extension MainContentCoordinator { completion(false) return } - if restoringRows { - rowEditingCoordinator.restoreRowBufferToOriginals(forTab: tabId) - } + rowEditingCoordinator.restoreRowBufferToOriginals(forTab: tabId) } manager.clearChangesAndUndoHistory() completion(true) diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnVisibility.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnVisibility.swift index 95e2d6d3c1..f61413a98e 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnVisibility.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ColumnVisibility.swift @@ -45,7 +45,7 @@ extension MainContentCoordinator { // Confirms like sort, pagination and the WHERE filter: re-running with a new column list drops unsaved edits (#2667). private func changeColumnScope(_ mutate: @escaping (inout Set) -> Void) { guard let tabId = tabManager.selectedTabId else { return } - confirmDiscardRestoringRowsIfNeeded(forTab: tabId, action: .columnVisibility) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .columnVisibility) { [weak self] confirmed in guard confirmed, let self else { return } self.mutateHiddenColumns(ofTab: tabId, mutate) self.requeryWithColumnScope(forTab: tabId, debounced: true) @@ -98,7 +98,7 @@ extension MainContentCoordinator { // Clearing the hidden set re-queries, so reset confirms too; declining keeps the width reset, since widths cannot void edits. func resetColumns() { guard let tabId = tabManager.selectedTabId else { return } - confirmDiscardRestoringRowsIfNeeded(forTab: tabId, action: .columnVisibility) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .columnVisibility) { [weak self] confirmed in guard confirmed, let self else { return } self.applyColumnReset(toTab: tabId) } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift index c4d58ff3b5..b70f263cda 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift @@ -18,7 +18,7 @@ extension MainContentCoordinator { internal func changeQueryContainer(of tabId: UUID, to name: String, target: ContainerSwitchTarget?) { guard canChangeContainer(of: tabId, to: name) else { return } // Asked before the tab moves, so Cancel leaves the staged edits with the database their rows came from. - confirmDiscardRestoringRowsIfNeeded(forTab: tabId, action: .containerChange) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .containerChange) { [weak self] confirmed in guard confirmed, let self, canChangeContainer(of: tabId, to: name) else { return } retargetTab(tabId) guard tabManager.mutate(tabId: tabId, { tab in diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift index f3187fbf30..94218c2e8f 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ExecuteAll.swift @@ -14,7 +14,7 @@ extension MainContentCoordinator { run() return } - confirmDiscardRestoringRowsIfNeeded(forTab: tabId, action: .run) { [weak self] confirmed in + confirmDiscardChangesIfNeeded(forTab: tabId, action: .run) { [weak self] confirmed in guard let self, confirmed, tabManager.selectedTabId == tabId, !tabExecution.isExecuting(tabId) else { return } run() } diff --git a/apple/changelog.d/4286.changed.md b/apple/changelog.d/4286.changed.md new file mode 100644 index 0000000000..472e271b00 --- /dev/null +++ b/apple/changelog.d/4286.changed.md @@ -0,0 +1 @@ +Typing in the query editor no longer redraws the tab strip and the rest of the window on every keystroke. diff --git a/apple/changelog.d/4286.fixed.1.md b/apple/changelog.d/4286.fixed.1.md new file mode 100644 index 0000000000..4ac30b1c94 --- /dev/null +++ b/apple/changelog.d/4286.fixed.1.md @@ -0,0 +1 @@ +Choosing Save when closing a tab could save another tab instead if the selection changed while the prompt was up. diff --git a/apple/changelog.d/4286.fixed.md b/apple/changelog.d/4286.fixed.md new file mode 100644 index 0000000000..62ece4639c --- /dev/null +++ b/apple/changelog.d/4286.fixed.md @@ -0,0 +1 @@ +Query History saved the statements of a script without their schema, so reopening one ran in the default schema.