diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+UndoHistory.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+UndoHistory.swift new file mode 100644 index 0000000000..750cf9647f --- /dev/null +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+UndoHistory.swift @@ -0,0 +1,54 @@ +// +// TextViewController+UndoHistory.swift +// TableProEditorKit +// + +import AppKit +import TableProTextEngine + +// Every step's ranges point into `text`, so the history is only good for that exact text. +public struct EditorUndoHistory { + let history: CEUndoManager.History + public let text: String +} + +public extension TextViewController { + func takeUndoHistory() -> EditorUndoHistory? { + guard let textView, let undoManager = textView.editorUndoManager else { return nil } + let history = undoManager.history + guard !history.isEmpty else { return nil } + undoManager.clearStack() + return EditorUndoHistory(history: history, text: textView.string) + } + + @discardableResult + func restoreUndoHistory(_ history: EditorUndoHistory) -> Bool { + // Literal equality: the text can be megabytes, and canonical `==` normalizes all of it. + guard let textView, let undoManager = textView.editorUndoManager, + (history.text as NSString).isEqual(to: textView.string) else { return false } + undoManager.restore(history.history) + return true + } + + // A whole-document change made by code, as one step Undo takes back. Like Replace All it skips the typing filters + // and the suggestion triggers. The selection stays where it was, clamped, as `setText` leaves it. + func replaceDocumentText(_ text: String) { + guard let textView else { return } + guard textView.isEditable else { + setText(text) + return + } + endSnippetSession() + let selection = textView.selectionManager.textSelections.map(\.range) + textView.undoManager?.beginUndoGrouping() + isApplyingUnfilteredEdits = true + textView.replaceCharacters( + in: NSRange(location: 0, length: textView.textStorage.length), + with: text, + skipUpdateSelection: true + ) + isApplyingUnfilteredEdits = false + textView.undoManager?.endUndoGrouping() + textView.selectionManager.setSelectedRanges(selection) + } +} diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/SourceEditor+Coordinator.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/SourceEditor+Coordinator.swift index b19f9c59c6..1f5b44908c 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/SourceEditor+Coordinator.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/SourceEditor+Coordinator.swift @@ -37,11 +37,12 @@ public extension SourceEditor { init( text: TextAPI, + documentID: AnyHashable? = nil, editorState: Binding, highlightProviders: [any HighlightProviding]?, textCoordinators: [any TextViewCoordinator] ) { - self.textSync = TextBindingSync(text: text, phase: phase) + self.textSync = TextBindingSync(text: text, documentID: documentID, phase: phase) self._editorState = editorState self.highlightProviders = highlightProviders ?? [TreeSitterClient()] self.textCoordinators = textCoordinators diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/SourceEditor.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/SourceEditor.swift index 413bc50586..d42f0647f1 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/SourceEditor.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/SourceEditor.swift @@ -39,7 +39,8 @@ public struct SourceEditor: NSViewControllerRepresentable { foldProvider: LineFoldProvider? = nil, undoManager: CEUndoManager? = nil, coordinators: [any TextViewCoordinator] = [], - completionDelegate: CodeSuggestionDelegate? = nil + completionDelegate: CodeSuggestionDelegate? = nil, + documentID: AnyHashable? = nil ) { self.text = .binding(text) self.language = language @@ -50,6 +51,7 @@ public struct SourceEditor: NSViewControllerRepresentable { self.undoManager = undoManager self.coordinators = coordinators self.completionDelegate = completionDelegate + self.documentID = documentID } /// Initializes a new source editor @@ -96,6 +98,8 @@ public struct SourceEditor: NSViewControllerRepresentable { var undoManager: CEUndoManager? var coordinators: [any TextViewCoordinator] var completionDelegate: CodeSuggestionDelegate? + // While it stays the same, a new binding value is an edit Undo can take back; a new one starts a new history. + var documentID: AnyHashable? public typealias NSViewControllerType = TextViewController @@ -135,6 +139,7 @@ public struct SourceEditor: NSViewControllerRepresentable { public func makeCoordinator() -> Coordinator { Coordinator( text: text, + documentID: documentID, editorState: $state, highlightProviders: highlightProviders, textCoordinators: coordinators @@ -166,7 +171,11 @@ public struct SourceEditor: NSViewControllerRepresentable { coordinator.textSync.text = text if case .binding(let binding) = text { - coordinator.textSync.applyRepresentableText(binding.wrappedValue, controller: controller) + coordinator.textSync.applyRepresentableText( + binding.wrappedValue, + documentID: documentID, + controller: controller + ) } if !coordinator.phase.consumePendingEditorChange() { diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/TextBindingSync.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/TextBindingSync.swift index 9bf4a5641b..f306bdfee1 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/TextBindingSync.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/SourceEditor/TextBindingSync.swift @@ -20,12 +20,14 @@ final class TextBindingSync { var text: SourceEditor.TextAPI private(set) var lastSyncedText: String? + private(set) var documentID: AnyHashable? private let phase: RepresentableSyncPhase private(set) var writebackTask: Task? - init(text: SourceEditor.TextAPI, phase: RepresentableSyncPhase) { + init(text: SourceEditor.TextAPI, documentID: AnyHashable? = nil, phase: RepresentableSyncPhase) { self.text = text + self.documentID = documentID self.phase = phase if case .binding(let binding) = text { lastSyncedText = binding.wrappedValue @@ -90,27 +92,29 @@ final class TextBindingSync { return newText } - /// Pushes an external binding change down into the text view. The editor's - /// content wins while one of its own edits is still in flight, so user - /// typing is never clobbered by a stale binding snapshot. - /// - /// Routes through `TextViewController.setText` on purpose. The text-view - /// level `replaceCharacters` is the user-edit path: it is gated on - /// `isEditable`, runs mutation filters, and fires suggestion triggers, - /// none of which should happen for a programmatic whole-document - /// replacement. The controller-level call also rebuilds the highlighter - /// for the replacement storage; calling the text view directly leaves - /// tree-sitter state for the old document and highlighting never recovers. - func applyRepresentableText(_ newValue: String, controller: TextViewController) { + // The editor's content wins while one of its own edits is in flight. In the same named document a new value is one + // undoable edit; another document, or an owner that names none, gets `setText`: a new history and a highlighter + // rebuilt for the new storage, even when the text is the same. + func applyRepresentableText( + _ newValue: String, + documentID: AnyHashable? = nil, + controller: TextViewController + ) { guard !phase.isEditorChangePending else { return } + let isSameDocument = documentID == self.documentID + self.documentID = documentID // Compare with NSString literal equality. The text can be multiple megabytes and bridged from NSTextStorage, // so Swift's canonical `!=` walks the whole string through Unicode normalization on every representable update. - if let lastSyncedText, (newValue as NSString).isEqual(to: lastSyncedText) { return } + if isSameDocument, let lastSyncedText, (newValue as NSString).isEqual(to: lastSyncedText) { return } writebackTask?.cancel() writebackTask = nil phase.applyRepresentableValue { - controller.setText(newValue) + if isSameDocument, documentID != nil { + controller.replaceDocumentText(newValue) + } else { + controller.setText(newValue) + } } lastSyncedText = newValue } diff --git a/apple/Packages/TableProEditor/Sources/TableProTextEngine/Utils/CEUndoManager.swift b/apple/Packages/TableProEditor/Sources/TableProTextEngine/Utils/CEUndoManager.swift index 730b98a2b7..aa121c0e98 100644 --- a/apple/Packages/TableProEditor/Sources/TableProTextEngine/Utils/CEUndoManager.swift +++ b/apple/Packages/TableProEditor/Sources/TableProTextEngine/Utils/CEUndoManager.swift @@ -17,16 +17,23 @@ import TextStory /// If needed, the automatic undo grouping can be overridden using the `beginGrouping()` and `endGrouping()` methods. public class CEUndoManager: UndoManager { /// Represents a group of mutations that should be treated as one mutation when undoing/redoing. - private struct UndoGroup { + struct UndoGroup { var mutations: [Mutation] } /// A single undo mutation. - private struct Mutation { + struct Mutation { var mutation: TextMutation var inverse: TextMutation } + public struct History { + var undoStack: [UndoGroup] + var redoStack: [UndoGroup] + + public var isEmpty: Bool { undoStack.isEmpty && redoStack.isEmpty } + } + private var _isUndoing: Bool = false private var _isRedoing: Bool = false @@ -195,6 +202,18 @@ public class CEUndoManager: UndoManager { redoStack.removeAll() } + public var history: History { + History(undoStack: undoStack, redoStack: redoStack) + } + + // The next edit starts its own step instead of joining the restored history's last one. + public func restore(_ history: History) { + undoStack = history.undoStack + redoStack = history.redoStack + isGrouping = false + shouldBreakNextGroup = true + } + // MARK: - Mutations override public func registerUndo(withTarget target: Any, selector: Selector, object anObject: Any?) { diff --git a/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/SourceEditorUndoHistoryTests.swift b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/SourceEditorUndoHistoryTests.swift new file mode 100644 index 0000000000..8af3872bdf --- /dev/null +++ b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/SourceEditorUndoHistoryTests.swift @@ -0,0 +1,181 @@ +// +// SourceEditorUndoHistoryTests.swift +// TableProEditorKitTests +// +// An owner that names its document gets text it sets in that document as an edit Undo takes back, and a new +// document as a new history. A history saved with a document comes back only onto the same text. +// + +import AppKit +import SwiftUI +@testable import TableProEditorKit +import TableProTextEngine +import Testing + +@MainActor +private final class DocumentOwner { + var text: String + var documentID: AnyHashable? + + init(text: String, documentID: AnyHashable?) { + self.text = text + self.documentID = documentID + } + + func editor(_ state: Binding) -> SourceEditor { + SourceEditor( + Binding(get: { self.text }, set: { self.text = $0 }), + language: .default, + configuration: Mock.config(), + state: state, + highlightProviders: [], + documentID: documentID + ) + } +} + +@MainActor +struct SourceEditorUndoHistoryTests { + private static let query = AnyHashable("query") + private static let other = AnyHashable("other") + + private func mount(_ owner: DocumentOwner) -> (SourceEditorHost, NSWindow) { + let host = SourceEditorHost { owner.editor($0) } + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 600, height: 400), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentView = host.controller.view + window.contentView?.layoutSubtreeIfNeeded() + return (host, window) + } + + private func show(_ text: String, as documentID: AnyHashable?, owner: DocumentOwner, host: SourceEditorHost) { + owner.text = text + owner.documentID = documentID + host.update { owner.editor($0) } + } + + // The owner's update pass after the editor writes the text back, as SwiftUI runs it. + private func type(_ string: String, at location: Int, owner: DocumentOwner, host: SourceEditorHost) { + host.controller.textView.replaceCharacters(in: NSRange(location: location, length: 0), with: string) + host.update { owner.editor($0) } + } + + private func selection(_ host: SourceEditorHost) -> [NSRange] { + host.controller.textView.selectionManager.textSelections.map(\.range) + } + + @Test("Text the owner sets in the same document is one step Undo takes back") + func sameDocumentChangeIsUndoable() { + let owner = DocumentOwner(text: "SELECT 1", documentID: Self.query) + let (host, window) = mount(owner) + defer { window.orderOut(nil) } + + show("", as: Self.query, owner: owner, host: host) + #expect(host.controller.textView.string == "") + + host.controller.textView.undoManager?.undo() + #expect(host.controller.textView.string == "SELECT 1") + #expect(owner.text == "SELECT 1") + } + + @Test("Text set in the same document skips the typing filters") + func sameDocumentChangeIsUnfiltered() { + let owner = DocumentOwner(text: "SELECT 1", documentID: Self.query) + let (host, window) = mount(owner) + defer { window.orderOut(nil) } + + show("(", as: Self.query, owner: owner, host: host) + + #expect(host.controller.textView.string == "(") + } + + @Test("Text set in the same document leaves the caret where it was") + func sameDocumentChangeKeepsTheCaret() { + let owner = DocumentOwner(text: "SELECT 1", documentID: Self.query) + let (host, window) = mount(owner) + defer { window.orderOut(nil) } + host.controller.setCursorPositions([CursorPosition(range: NSRange(location: 3, length: 0))]) + + show("SELECT 2", as: Self.query, owner: owner, host: host) + + #expect(host.controller.textView.string == "SELECT 2") + #expect(selection(host) == [NSRange(location: 3, length: 0)]) + } + + @Test("Another document starts a new history") + func newDocumentStartsANewHistory() { + let owner = DocumentOwner(text: "SELECT 1", documentID: Self.query) + let (host, window) = mount(owner) + defer { window.orderOut(nil) } + type("0", at: 8, owner: owner, host: host) + #expect(host.controller.textView.undoManager?.canUndo == true) + + show("SELECT 2", as: Self.other, owner: owner, host: host) + + #expect(host.controller.textView.string == "SELECT 2") + #expect(host.controller.textView.undoManager?.canUndo == false) + } + + @Test("Another document with the same text still starts a new history") + func newDocumentWithTheSameTextStartsANewHistory() { + let owner = DocumentOwner(text: "SELECT 1", documentID: Self.query) + let (host, window) = mount(owner) + defer { window.orderOut(nil) } + type("0", at: 8, owner: owner, host: host) + + show("SELECT 10", as: Self.other, owner: owner, host: host) + + #expect(host.controller.textView.undoManager?.canUndo == false) + } + + @Test("An owner that names no document gets a new history on every change, as before") + func unnamedDocumentKeepsReplacingTheText() { + let owner = DocumentOwner(text: "SELECT 1", documentID: nil) + let (host, window) = mount(owner) + defer { window.orderOut(nil) } + type("0", at: 8, owner: owner, host: host) + + show("SELECT 2", as: nil, owner: owner, host: host) + + #expect(host.controller.textView.string == "SELECT 2") + #expect(host.controller.textView.undoManager?.canUndo == false) + } + + @Test("A history saved with its document comes back with it") + func savedHistoryComesBackWithItsDocument() throws { + let owner = DocumentOwner(text: "SELECT 1", documentID: Self.query) + let (host, window) = mount(owner) + defer { window.orderOut(nil) } + type("0", at: 8, owner: owner, host: host) + + let saved = try #require(host.controller.takeUndoHistory()) + #expect(host.controller.textView.undoManager?.canUndo == false) + #expect(host.controller.takeUndoHistory() == nil) + show("SELECT 2", as: Self.other, owner: owner, host: host) + show("SELECT 10", as: Self.query, owner: owner, host: host) + + #expect(host.controller.restoreUndoHistory(saved)) + host.controller.textView.undoManager?.undo() + #expect(host.controller.textView.string == "SELECT 1") + } + + @Test("A saved history is not put back on text that changed") + func savedHistoryIsDroppedForChangedText() throws { + let owner = DocumentOwner(text: "SELECT 1", documentID: Self.query) + let (host, window) = mount(owner) + defer { window.orderOut(nil) } + type("0", at: 8, owner: owner, host: host) + + let saved = try #require(host.controller.takeUndoHistory()) + show("SELECT 2", as: Self.other, owner: owner, host: host) + show("SELECT 99", as: Self.query, owner: owner, host: host) + + #expect(!host.controller.restoreUndoHistory(saved)) + #expect(host.controller.textView.undoManager?.canUndo == false) + } +} diff --git a/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/UndoHistoryTests.swift b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/UndoHistoryTests.swift new file mode 100644 index 0000000000..004d528fc4 --- /dev/null +++ b/apple/Packages/TableProEditor/Tests/TableProTextEngineTests/UndoHistoryTests.swift @@ -0,0 +1,56 @@ +import AppKit +@testable import TableProTextEngine +import Testing + +@MainActor +struct UndoHistoryTests { + private func makeTextView() throws -> (TextView, CEUndoManager) { + let textView = TextView(string: "") + return (textView, try #require(textView.editorUndoManager)) + } + + @Test("A history taken out and put back undoes the edits it recorded") + func undoStackRoundTrip() throws { + let (textView, undoManager) = try makeTextView() + textView.replaceCharacters(in: NSRange(location: 0, length: 0), with: "SELECT 1") + textView.replaceCharacters(in: NSRange(location: 7, length: 1), with: "2") + let history = undoManager.history + undoManager.clearStack() + #expect(undoManager.history.isEmpty) + #expect(!undoManager.canUndo) + + undoManager.restore(history) + undoManager.undo() + #expect(textView.string == "SELECT 1") + undoManager.undo() + #expect(textView.string == "") + } + + @Test("A restored history keeps the steps Redo can apply") + func redoStackRoundTrip() throws { + let (textView, undoManager) = try makeTextView() + textView.replaceCharacters(in: NSRange(location: 0, length: 0), with: "SELECT 1") + undoManager.undo() + let history = undoManager.history + undoManager.clearStack() + + undoManager.restore(history) + undoManager.redo() + + #expect(textView.string == "SELECT 1") + } + + @Test("Typing after a restore is its own undo step") + func typingAfterRestoreStartsANewStep() throws { + let (textView, undoManager) = try makeTextView() + textView.replaceCharacters(in: NSRange(location: 0, length: 0), with: "a") + let history = undoManager.history + undoManager.clearStack() + undoManager.restore(history) + + textView.replaceCharacters(in: NSRange(location: 1, length: 0), with: "b") + undoManager.undo() + + #expect(textView.string == "a") + } +} diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift index 3072505f7c..961b5699a0 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift @@ -157,12 +157,24 @@ extension QueryExecutionCoordinator { let plan = await batchResultPlan(prepared, outputs: Self.outputs(of: run.outcome), tabId: tabId) let sessionNotice = Self.runNotice(outcome: run.outcome, sessionState: run.sessionState) + guard parent.tabExecution.settle(claim) || reportsUnknownCommitAfterStop(run.outcome, claim: claim) else { + await keepBatchesAfterStop( + prepared, run: run, plan: plan, parameters: parameters, claim: claim, sessionNotice: sessionNotice + ) + return + } + parent.retireQueryTask(.claim(claim)) + switch run.outcome { case .cancelled(let outputs): - guard parent.tabExecution.settle(claim) else { return } - parent.retireQueryTask(.claim(claim)) keepStoppedBatches( - prepared, outputs: outputs, parameters: parameters, tabId: tabId, sessionNotice: sessionNotice, plan: plan + prepared, + outputs: outputs, + parameters: parameters, + tabId: tabId, + sessionNotice: sessionNotice, + plan: plan, + presentsResults: true ) parent.reportEndedExecutions([ EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) @@ -387,9 +399,6 @@ extension QueryExecutionCoordinator { sessionNotice: String?, plan: BatchResultPlan ) { - guard parent.tabExecution.settle(claim) else { return } - parent.retireQueryTask(.claim(claim)) - let totalRowsAffected = outputs.reduce(0) { $0 + $1.rowsAffected } reportOperation( kind: .queryBatch, @@ -406,16 +415,49 @@ 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, + plan: BatchResultPlan, + parameters: [QueryParameter], + claim: TabExecutionClaim, + sessionNotice: String? + ) async { + let kept = run.outcome.keptAfterStop(plan: run.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 + ? plan + : await batchResultPlan(prepared, outputs: kept, tabId: claim.tabId) + let presentsResults = stoppedRunCanReplaceResults(onTab: claim.tabId) + guard parent.tabExecution.settleStopped(claim, replacingContent: presentsResults) else { return } + keepStoppedBatches( + prepared, + outputs: kept, + parameters: parameters, + tabId: claim.tabId, + sessionNotice: sessionNotice, + plan: keptPlan, + presentsResults: presentsResults + ) + parent.reportEndedExecutions([ + EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) + ]) + } + private func keepStoppedBatches( _ prepared: [PreparedBatch], outputs: [BatchOutput], parameters: [QueryParameter], tabId: UUID, sessionNotice: String?, - plan: BatchResultPlan + plan: BatchResultPlan, + presentsResults: Bool ) { guard !outputs.isEmpty else { return } recordBatchHistory(prepared, outputs: outputs, parameters: parameters, tabId: tabId, failedIndex: nil) + guard presentsResults else { return } presentMultiStatementResults( tabId: tabId, timing: PluginQueryTiming(total: outputs.reduce(0) { $0 + $1.executionTime }), @@ -450,8 +492,6 @@ extension QueryExecutionCoordinator { errorResult.failedQuery = report.failedSQL errorResult.statementAnchor = failedBatch?.batch.anchor - guard parent.tabExecution.settle(claim) else { return } - parent.retireQueryTask(.claim(claim)) reportOperation(kind: .queryBatch, claim: claim, outcome: .failed(reason: context.errorDescription)) recordBatchHistory( prepared, diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift index 7006e2f157..ada9d8c639 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+MultiStatement.swift @@ -294,8 +294,8 @@ extension QueryExecutionCoordinator { parent.tabManager.mutate(at: idx) { tab in if tab.tabType == .query { + // The schema stays: on a query tab it is the picker's binding, and a run summary has no origin to give. tab.tableContext.tableName = activeOrigin?.tableName - tab.tableContext.schemaName = activeOrigin?.schemaName tab.tableContext.primaryKeyColumns = activeOrigin?.primaryKeyColumns ?? [] tab.tableContext.isEditable = activeOrigin?.isEditable ?? false } else if activeOrigin?.tableName == nil { diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift index 0520265783..641a46bbc1 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift @@ -96,6 +96,30 @@ private struct ExecutedStatementHistory { let results: [QueryResult] let parameters: [QueryParameter] let connection: DatabaseConnection + + func keeping(_ kept: [QueryResult]) -> ExecutedStatementHistory { + ExecutedStatementHistory(prepared: prepared, results: kept, parameters: parameters, connection: connection) + } +} + +extension BatchStatementOutcome { + // The units a run the user stopped keeps: those that completed, and none that its plan rolled back. + func keptAfterStop(plan: BatchTransactionPlan) -> [Output] { + switch self { + case .completed(let results), .cancelled(let results): + return results + case .failed(_, .commitOutcomeUnknown, _): + // Nothing can say whether these were saved, so they are not recorded as plain successes. + return [] + case .failed(let results, _, _): + return plan.keepsExecutedStatements ? Array(results.prefix(succeededCount)) : [] + } + } + + var leftCommitOutcomeUnknown: Bool { + guard case .failed(_, .commitOutcomeUnknown, _) = self else { return false } + return true + } } extension QueryExecutionCoordinator { @@ -447,30 +471,31 @@ extension QueryExecutionCoordinator { tabId: tabId ) - switch outcome { - case .cancelled(let results): - guard parent.tabExecution.settle(claim) else { return } - parent.retireQueryTask(.claim(claim)) - keepStoppedStatements( - history: ExecutedStatementHistory( - prepared: sent, results: results, parameters: parameters, connection: conn - ), - tabId: tabId, + let history = ExecutedStatementHistory( + prepared: sent, results: results, parameters: parameters, connection: conn + ) + guard parent.tabExecution.settle(claim) || reportsUnknownCommitAfterStop(outcome, claim: claim) else { + keepStatementsAfterStop( + history.keeping(outcome.keptAfterStop(plan: run.plan)), + claim: claim, sessionNotice: sessionNotice, built: built ) + return + } + parent.retireQueryTask(.claim(claim)) + + switch outcome { + case .cancelled: + keepStoppedStatements( + history: history, tabId: tabId, sessionNotice: sessionNotice, built: built, presentsResults: true + ) parent.reportEndedExecutions([ EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) ]) - case .completed(let results): + case .completed: applyCompletedStatements( - history: ExecutedStatementHistory( - prepared: sent, results: results, parameters: parameters, connection: conn - ), - tabId: tabId, - claim: claim, - sessionNotice: sessionNotice, - built: built + history: history, tabId: tabId, claim: claim, sessionNotice: sessionNotice, built: built ) case .failed(let results, let failure, let errorDescription): handleMultiStatementError( @@ -482,9 +507,7 @@ extension QueryExecutionCoordinator { plan: run.plan, sessionState: run.sessionState ), - history: ExecutedStatementHistory( - prepared: sent, results: results, parameters: parameters, connection: conn - ), + history: history, tabId: tabId, claim: claim, anchors: sent.map(\.anchor), @@ -637,16 +660,52 @@ extension QueryExecutionCoordinator { ) } - /// A Stop cannot take back what a plan without a transaction already committed, so the results - /// and the history of the statements that ran stay rather than being dropped with the run. + // A commit nobody can confirm is reported as one even after a Stop, rather than kept as plain successes. + func reportsUnknownCommitAfterStop(_ outcome: BatchStatementOutcome, claim: TabExecutionClaim) -> Bool { + outcome.leftCommitOutcomeUnknown + && stoppedRunCanReplaceResults(onTab: claim.tabId) + && parent.tabExecution.settleStopped(claim, replacingContent: true) + } + + // A stopped run comes back after the tab went idle. Edits staged since then keep the result they were made on. + func stoppedRunCanReplaceResults(onTab tabId: UUID) -> Bool { + guard let tab = parent.tabManager.tabs.first(where: { $0.id == tabId }) else { return false } + return !parent.holdsUnsavedWork(tab) + } + + // 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, + 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 } + keepStoppedStatements( + history: history, + tabId: claim.tabId, + sessionNotice: sessionNotice, + built: built, + presentsResults: presentsResults + ) + parent.reportEndedExecutions([ + EndedExecution(tabId: claim.tabId, startedAt: claim.startedAt, reason: .cancelledByUser) + ]) + } + + // 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, sessionNotice: String?, - built: StatementRowsBuild + built: StatementRowsBuild, + presentsResults: Bool ) { guard !history.results.isEmpty else { return } recordExecutedStatements(history, tabId: tabId, commitOutcomeIsUnknown: false) + guard presentsResults else { return } presentMultiStatementResults( tabId: tabId, timing: PluginQueryTiming.batch(of: history.results), @@ -656,9 +715,7 @@ extension QueryExecutionCoordinator { ) } - /// Settles first, then writes. Everything below the gate belongs to a batch that still owns its - /// tab: its history rows, its outcome notification and its result sets. A superseded batch - /// writes none of them, which is what the single-statement path has always done. + // Below the caller's settle gate: a superseded batch writes no history rows, outcome or result sets. private func applyCompletedStatements( history: ExecutedStatementHistory, tabId: UUID, @@ -666,9 +723,6 @@ extension QueryExecutionCoordinator { sessionNotice: String?, built: StatementRowsBuild ) { - guard parent.tabExecution.settle(claim) else { return } - parent.retireQueryTask(.claim(claim)) - let totalRowsAffected = history.results.reduce(0) { $0 + $1.rowsAffected } reportOperation( kind: .queryBatch, @@ -827,7 +881,7 @@ extension QueryExecutionCoordinator { } } - // Reports only, below the settle gate: the lease already rolled back, and a superseded batch writes no history. + // Below the caller's settle gate: the lease already rolled back, and a superseded batch writes no history. private func handleMultiStatementError( _ context: MultiStatementFailureContext, history: ExecutedStatementHistory, @@ -850,12 +904,6 @@ extension QueryExecutionCoordinator { .flatMap { anchors.indices.contains($0) ? anchors[$0] : nil } let failedStatementSQL = report.failedSQL - guard parent.tabExecution.settle(claim) else { return } - parent.retireQueryTask(.claim(claim)) - - /// Below the settle gate for the same reason the success arm is: a superseded batch - /// has its error dropped here, so announcing it would report on work the user has - /// already navigated away from. reportOperation(kind: .queryBatch, claim: claim, outcome: .failed(reason: errorDescription)) recordExecutedStatements( history, diff --git a/apple/TablePro/Core/Execution/TabExecutionRegistry.swift b/apple/TablePro/Core/Execution/TabExecutionRegistry.swift index dce0de9b95..2e022ef07e 100644 --- a/apple/TablePro/Core/Execution/TabExecutionRegistry.swift +++ b/apple/TablePro/Core/Execution/TabExecutionRegistry.swift @@ -68,6 +68,7 @@ internal struct TabExecutionRegistry { private var entries: [UUID: Entry] = [:] private var contentEpochs: [UUID: Int] = [:] private var unclaimedWork: [UUID: Set] = [:] + private var stoppedEpochs: [UUID: Int] = [:] private var lastEpoch: Int = 0 internal init() {} @@ -75,6 +76,7 @@ internal struct TabExecutionRegistry { internal mutating func claim(_ tabId: UUID, startedAt: ContinuousClock.Instant = .now) -> TabExecutionClaim { lastEpoch += 1 entries[tabId] = Entry(epoch: lastEpoch, startedAt: startedAt) + stoppedEpochs.removeValue(forKey: tabId) contentEpochs[tabId] = lastEpoch return TabExecutionClaim(tabId: tabId, epoch: lastEpoch, startedAt: startedAt) } @@ -113,6 +115,7 @@ internal struct TabExecutionRegistry { EndedExecution(tabId: tabId, startedAt: $0.startedAt, reason: reason) } unclaimedWork.removeValue(forKey: tabId) + stoppedEpochs.removeValue(forKey: tabId) lastEpoch += 1 contentEpochs[tabId] = lastEpoch return ended @@ -125,6 +128,7 @@ internal struct TabExecutionRegistry { } entries.removeAll() unclaimedWork.removeAll() + stoppedEpochs.removeAll() for tabId in tabIds { lastEpoch += 1 contentEpochs[tabId] = lastEpoch @@ -179,7 +183,12 @@ internal struct TabExecutionRegistry { guard entries[tabId]?.isUninterruptible != true else { return StopOutcome(ended: [], keptUninterruptibleClaim: true) } - let ended = entries.removeValue(forKey: tabId).map { + let removed = entries.removeValue(forKey: tabId) + if let removed { + // Statements that ran before the Stop can stay on the server, and the run still has to keep them. + stoppedEpochs[tabId] = removed.epoch + } + let ended = removed.map { [EndedExecution(tabId: tabId, startedAt: $0.startedAt, reason: .cancelledByUser)] } ?? [] lastEpoch += 1 @@ -187,6 +196,17 @@ internal struct TabExecutionRegistry { return StopOutcome(ended: ended, keptUninterruptibleClaim: false) } + // Replacing content mints a new epoch, so work started on the old result after the Stop cannot write over the kept one. + internal mutating func settleStopped(_ claim: TabExecutionClaim, replacingContent: Bool) -> Bool { + guard stoppedEpochs[claim.tabId] == claim.epoch else { return false } + stoppedEpochs.removeValue(forKey: claim.tabId) + if replacingContent { + lastEpoch += 1 + contentEpochs[claim.tabId] = lastEpoch + } + return true + } + /// Work that runs against a tab without owning its result. /// /// Fetch All is why this exists. `claim` mints a new content epoch, which is the very value the diff --git a/apple/TablePro/Core/Services/Infrastructure/ConnectionWorkspace.swift b/apple/TablePro/Core/Services/Infrastructure/ConnectionWorkspace.swift index 640d218993..964e95b0e8 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ConnectionWorkspace.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ConnectionWorkspace.swift @@ -13,7 +13,7 @@ import Foundation @MainActor internal final class ConnectionWorkspace { internal let connectionId: UUID - internal let payload: EditorTabPayload? + internal private(set) var payload: EditorTabPayload? internal let autoConnect: Bool internal var payloadConnection: DatabaseConnection? @@ -304,6 +304,12 @@ internal final class ConnectionWorkspace { ) } + // The session's tabs were saved as it went down, so a reconnect restores them rather than opening the founding content again. + internal func retireFoundingPayload() { + guard let payload, payload.intent != .restoreOrDefault else { return } + self.payload = EditorTabPayload(connectionId: connectionId, intent: .restoreOrDefault) + } + /// Opens what the payload names. Held until the session exists if the connection is still /// being established. internal func open(_ payload: EditorTabPayload) { diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift index f0cfcd9f62..c5d66aba1d 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController.swift @@ -636,6 +636,7 @@ internal final class MainSplitViewController: NSSplitViewController { workspace.sessionState?.coordinator.teardown(endsTabSession: false) workspace.sessionState = nil workspace.session = nil + workspace.retireFoundingPayload() if let releasedCoordinator, toolbarOwner?.coordinator === releasedCoordinator { toolbarOwner?.repoint(to: nil) } diff --git a/apple/TablePro/Core/Services/Infrastructure/TabPersistenceCoordinator.swift b/apple/TablePro/Core/Services/Infrastructure/TabPersistenceCoordinator.swift index 72da8fa986..f667112ce4 100644 --- a/apple/TablePro/Core/Services/Infrastructure/TabPersistenceCoordinator.swift +++ b/apple/TablePro/Core/Services/Infrastructure/TabPersistenceCoordinator.swift @@ -58,6 +58,11 @@ internal final class TabPersistenceCoordinator: ObservableObject { hasObservedTabs = true } + // A workspace founded on one table or query never read the saved set, and the gate refuses its saves until it does. + internal func readsSavedTabs(foundedWith intent: TabIntent?) -> Bool { + intent == nil || intent == .restoreOrDefault || !hasObservedTabs + } + // The gate is one session's knowledge of the disk. Left open after the connection's last window closed, a // window later opened on content alone, which skips the restore, would write its one tab over the saved set. internal func endSession() { diff --git a/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift b/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift index 6b72f1d6b7..d032c21940 100644 --- a/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift +++ b/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift @@ -5,7 +5,41 @@ import Foundation +// What Vim remembers about one document, by offset into its text. +struct VimDocumentMarks { + var marks: [Character: Int] = [:] + var lastVisualStart: Int? + var lastVisualEnd: Int? + var lastVisualLinewise = false + var lastJumpOrigin: Int? + var lastInsertOffset: Int? + + var isEmpty: Bool { + marks.isEmpty && lastVisualStart == nil && lastVisualEnd == nil && lastJumpOrigin == nil && lastInsertOffset == nil + } +} + extension VimEngine { + var documentMarks: VimDocumentMarks { + VimDocumentMarks( + marks: marks, + lastVisualStart: lastVisualStart, + lastVisualEnd: lastVisualEnd, + lastVisualLinewise: lastVisualLinewise, + lastJumpOrigin: lastJumpOrigin, + lastInsertOffset: lastInsertOffset + ) + } + + func restoreDocumentMarks(_ saved: VimDocumentMarks) { + marks = saved.marks + lastVisualStart = saved.lastVisualStart + lastVisualEnd = saved.lastVisualEnd + lastVisualLinewise = saved.lastVisualLinewise + lastJumpOrigin = saved.lastJumpOrigin + lastInsertOffset = saved.lastInsertOffset + } + func writeToActiveRegister(text: String, linewise: Bool, asDelete: Bool) { if selectedRegister == "_" { selectedRegister = nil diff --git a/apple/TablePro/Core/Vim/VimEngine.swift b/apple/TablePro/Core/Vim/VimEngine.swift index c7e0af73b2..f69914e272 100644 --- a/apple/TablePro/Core/Vim/VimEngine.swift +++ b/apple/TablePro/Core/Vim/VimEngine.swift @@ -138,6 +138,15 @@ final class VimEngine { buffer?.invalidateLineCache() } + // Offsets into the old text mean nothing in the new one. Registers, macros and the last search carry over, as + // they do between buffers in Vim. + func documentDidReplace() { + restoreDocumentMarks(VimDocumentMarks()) + replaceModeEdits.removeAll() + editsOnCurrentLine = 0 + lastEditedLine = nil + } + func reset() { pendingOperator = nil countPrefix = 0 diff --git a/apple/TablePro/Models/Query/ResultOrigin.swift b/apple/TablePro/Models/Query/ResultOrigin.swift index ef3dfd03cb..1f8c805752 100644 --- a/apple/TablePro/Models/Query/ResultOrigin.swift +++ b/apple/TablePro/Models/Query/ResultOrigin.swift @@ -62,6 +62,7 @@ enum ResultEditRefusal: Equatable { case unknownTable case view(PluginViewReadOnlyReason?) case databaseMoved + case schemaMoved case keysUnresolved case masked @@ -73,6 +74,8 @@ enum ResultEditRefusal: Equatable { return Self.viewMessage(reason) case .databaseMoved: return String(localized: "These rows came from another database than the one this tab is now using.") + case .schemaMoved: + return String(localized: "These rows came from another schema than the one this tab is now using.") case .keysUnresolved: return String(localized: "TablePro has not looked up this table's key columns, so it cannot tell which row an edit would change.") case .masked: @@ -122,7 +125,11 @@ extension PluginViewRowEditing { // Fail-closed: a result with no captured origin refuses rather than borrowing the tab's current table. enum ResultEditability { - static func refusal(for origin: ResultOrigin?, currentDatabaseName: String) -> ResultEditRefusal? { + static func refusal( + for origin: ResultOrigin?, + currentDatabaseName: String, + currentSchemaName: String? + ) -> ResultEditRefusal? { guard let origin else { return .unknownTable } // A query tab learns its relation is a view only from the driver's answer. if origin.isView || origin.viewRowEditing != nil { @@ -134,11 +141,20 @@ enum ResultEditability { return .unknownTable } guard origin.keysResolved else { return .keysUnresolved } - guard origin.databaseName.isEmpty || currentDatabaseName.isEmpty - || origin.databaseName == currentDatabaseName - else { - return .databaseMoved - } + guard !origin.wasRead(elsewhereThanDatabase: currentDatabaseName) else { return .databaseMoved } + // The schema picker moves only the schema, so the database check above cannot see it. + guard origin.schemaName == currentSchemaName else { return .schemaMoved } return nil } } + +extension ResultOrigin { + // An unknown database on either side is not a move. + func wasRead(elsewhereThanDatabase database: String) -> Bool { + !databaseName.isEmpty && !database.isEmpty && databaseName != database + } + + func wasRead(elsewhereThanDatabase database: String, schema: String?) -> Bool { + wasRead(elsewhereThanDatabase: database) || schemaName != schema + } +} diff --git a/apple/TablePro/Models/UI/WindowSidebarState.swift b/apple/TablePro/Models/UI/WindowSidebarState.swift index 5dc1aed215..7eace22f4d 100644 --- a/apple/TablePro/Models/UI/WindowSidebarState.swift +++ b/apple/TablePro/Models/UI/WindowSidebarState.swift @@ -18,6 +18,12 @@ struct DatabaseTableKey: Hashable, Sendable, Codable { let table: String } +struct PendingTableOperation: Identifiable, Equatable, Sendable { + let id = UUID() + let operation: TableOperationType + let tables: [DatabaseTreeTableRef] +} + @MainActor internal final class WindowSidebarState: ObservableObject { private let connectionId: UUID? @@ -55,6 +61,19 @@ internal final class WindowSidebarState: ObservableObject { var acceptsObjectMarkRefresh: Bool { selectedTables.isEmpty && selectedRowCount == 0 } + + // The connection's queues are shared by every window hosting it, but a Truncate or Drop prompt belongs to the window that asked. + @Published private(set) var pendingTableOperation: PendingTableOperation? + + func requestTableOperation(_ operation: TableOperationType, on tables: [DatabaseTreeTableRef]) { + pendingTableOperation = PendingTableOperation(operation: operation, tables: tables) + } + + func resolveTableOperation(_ request: PendingTableOperation) { + guard pendingTableOperation?.id == request.id else { return } + pendingTableOperation = nil + } + @Published var expandedTreeSchemas: Set = [] { didSet { persistExpansion() } } @Published var expandedTreeDatabases: Set = [] { didSet { persistExpansion() } } @Published var expandedTreeDatabaseSchemas: Set = [] { didSet { persistExpansion() } } diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 59ea7fab79..a3f7909720 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -113018,6 +113018,9 @@ } } } + }, + "Moving this tab to another database or schema will discard all unsaved changes." : { + }, "Moving through this tab's history replaces what it is showing and will discard all unsaved changes." : { "localizations" : { @@ -196838,6 +196841,9 @@ } } } + }, + "These rows came from another schema than the one this tab is now using." : { + }, "These rows cannot be edited because TablePro cannot tell which table they came from." : { "localizations" : { diff --git a/apple/TablePro/ViewModels/SidebarViewModel.swift b/apple/TablePro/ViewModels/SidebarViewModel.swift index 08ecd41429..de9a265379 100644 --- a/apple/TablePro/ViewModels/SidebarViewModel.swift +++ b/apple/TablePro/ViewModels/SidebarViewModel.swift @@ -19,14 +19,12 @@ final class SidebarViewModel: ObservableObject { static func shared( connectionId: UUID, databaseType: DatabaseType, - selectedTables: Binding>, pendingTruncates: Binding>, pendingDeletes: Binding>, tableOperationOptions: Binding<[DatabaseTreeTableRef: TableOperationOptions]> ) -> SidebarViewModel { if let existing = registry[connectionId] { existing.updateBindings( - selectedTables: selectedTables, pendingTruncates: pendingTruncates, pendingDeletes: pendingDeletes, tableOperationOptions: tableOperationOptions @@ -34,7 +32,6 @@ final class SidebarViewModel: ObservableObject { return existing } let viewModel = SidebarViewModel( - selectedTables: selectedTables, pendingTruncates: pendingTruncates, pendingDeletes: pendingDeletes, tableOperationOptions: tableOperationOptions, @@ -50,12 +47,10 @@ final class SidebarViewModel: ObservableObject { } func updateBindings( - selectedTables: Binding>, pendingTruncates: Binding>, pendingDeletes: Binding>, tableOperationOptions: Binding<[DatabaseTreeTableRef: TableOperationOptions]> ) { - selectedTablesBinding = selectedTables pendingTruncatesBinding = pendingTruncates pendingDeletesBinding = pendingDeletes tableOperationOptionsBinding = tableOperationOptions @@ -181,13 +176,9 @@ final class SidebarViewModel: ObservableObject { ) } } - @Published var showOperationDialog = false - @Published var pendingOperationType: TableOperationType? - @Published var pendingOperationTables: [DatabaseTreeTableRef] = [] // MARK: - Binding Storage - @Published private var selectedTablesBinding: Binding> @Published private var pendingTruncatesBinding: Binding> @Published private var pendingDeletesBinding: Binding> @Published private var tableOperationOptionsBinding: Binding<[DatabaseTreeTableRef: TableOperationOptions]> @@ -205,11 +196,6 @@ final class SidebarViewModel: ObservableObject { // MARK: - Convenience Accessors - var selectedTables: Set { - get { selectedTablesBinding.wrappedValue } - set { selectedTablesBinding.wrappedValue = newValue } - } - var pendingTruncates: Set { get { pendingTruncatesBinding.wrappedValue } set { pendingTruncatesBinding.wrappedValue = newValue } @@ -233,7 +219,6 @@ final class SidebarViewModel: ObservableObject { // MARK: - Initialization init( - selectedTables: Binding>, pendingTruncates: Binding>, pendingDeletes: Binding>, tableOperationOptions: Binding<[DatabaseTreeTableRef: TableOperationOptions]>, @@ -242,7 +227,6 @@ final class SidebarViewModel: ObservableObject { defaults: UserDefaults = AppStorageEnvironment.shared.defaults, clock: any Clock = ContinuousClock() ) { - self.selectedTablesBinding = selectedTables self.pendingTruncatesBinding = pendingTruncates self.pendingDeletesBinding = pendingDeletes self.tableOperationOptionsBinding = tableOperationOptions @@ -348,22 +332,16 @@ final class SidebarViewModel: ObservableObject { // MARK: - Batch Operations - /// A queued Truncate or Drop carries the row it was raised from, not that row's name. - /// The queue lives on the connection and outlives a database switch, so a name-keyed entry - /// was resolved at Save time against whatever the tab in front pointed at by then. - func batchToggleTruncate(refs: [DatabaseTreeTableRef]? = nil) { - let targets = refs ?? Array(selectedTables) + // Refs, not names: the queue outlives a database switch, so a name would resolve at Save time against whatever tab is in front. + func batchToggleTruncate(refs targets: [DatabaseTreeTableRef], from window: WindowSidebarState) { guard !targets.isEmpty else { return } - /// Unstaging comes first: a queued operation must always be removable, even once the - /// engine can no longer express it. Validating ahead of this left a Redis truncate stuck - /// in the queue after a `SELECT` moved the session to another database. + // Unstaging comes first, so a queued truncate stays removable after a Redis SELECT leaves the engine unable to express it. guard !targets.allSatisfy({ pendingTruncates.contains($0) }) else { unstage(targets, from: &pendingTruncatesBinding.wrappedValue) return } - /// The last gate before the queue, refusing the whole batch the way both menus now do - /// rather than truncating the part of a selection that happens to qualify. + // The whole batch is refused, as both menus do, rather than truncating the part that qualifies. guard TableOperationEligibility.canTruncate(targets) else { Self.logger.warning("Refused to stage a truncate against an object that holds no rows of its own") return @@ -373,29 +351,23 @@ final class SidebarViewModel: ObservableObject { Self.logger.warning("Refused to stage a truncate the engine has no statement for") return } - pendingOperationType = .truncate - pendingOperationTables = targets - showOperationDialog = true + window.requestTableOperation(.truncate, on: targets) } - func batchToggleDelete(refs: [DatabaseTreeTableRef]? = nil) { - let targets = refs ?? Array(selectedTables) + func batchToggleDelete(refs targets: [DatabaseTreeTableRef], from window: WindowSidebarState) { guard !targets.isEmpty else { return } guard !targets.allSatisfy({ pendingDeletes.contains($0) }) else { unstage(targets, from: &pendingDeletesBinding.wrappedValue) return } - /// The same last gate Truncate has. Without it a queued drop the engine cannot express - /// reached Save and was rejected there, after the dialog had already promised it. + // Without this gate a drop the engine cannot express reached Save and failed there, after the prompt promised it. if let eligibility = tableOperationEligibility(for: targets), !TableOperationEligibility.canDrop(targets, context: eligibility) { Self.logger.warning("Refused to stage a drop the engine has no statement for") return } - pendingOperationType = .drop - pendingOperationTables = targets - showOperationDialog = true + window.requestTableOperation(.drop, on: targets) } /// Nil when there is no driver to ask, which is not the same as "refused": with no session @@ -419,20 +391,13 @@ final class SidebarViewModel: ObservableObject { tableOperationOptions = options } - func cancelPendingOperation() { - pendingOperationType = nil - pendingOperationTables = [] - } - - func confirmOperation(options: TableOperationOptions) { - guard let operationType = pendingOperationType else { return } - + func confirmOperation(_ request: PendingTableOperation, options: TableOperationOptions) { var updatedTruncates = pendingTruncates var updatedDeletes = pendingDeletes var updatedOptions = tableOperationOptions - for ref in pendingOperationTables { - if operationType == .truncate { + for ref in request.tables { + if request.operation == .truncate { updatedDeletes.remove(ref) updatedTruncates.insert(ref) } else { @@ -445,16 +410,13 @@ final class SidebarViewModel: ObservableObject { pendingTruncates = updatedTruncates pendingDeletes = updatedDeletes tableOperationOptions = updatedOptions - - pendingOperationType = nil - pendingOperationTables = [] } // MARK: - Clipboard - func copySelectedTableNames() { - guard !selectedTables.isEmpty else { return } - let names = selectedTables.map { $0.table.name }.sorted() + static func copyTableNames(of tables: Set) { + guard !tables.isEmpty else { return } + let names = tables.map { $0.table.name }.sorted() ClipboardService.shared.writeText(names.joined(separator: ",")) } diff --git a/apple/TablePro/Views/Editor/EditorUndoHistories.swift b/apple/TablePro/Views/Editor/EditorUndoHistories.swift new file mode 100644 index 0000000000..cbfa10f327 --- /dev/null +++ b/apple/TablePro/Views/Editor/EditorUndoHistories.swift @@ -0,0 +1,37 @@ +// +// EditorUndoHistories.swift +// TablePro +// + +import Foundation +import TableProEditorKit + +// What a query tab leaves in the shared editor while another tab is shown. Both parts are offsets into `text`, so +// they come back only while the tab still holds that text. +struct EditorTabHistory { + let text: String + let undo: EditorUndoHistory? + let vimMarks: VimDocumentMarks? +} + +@MainActor +final class EditorUndoHistories { + private var entries: [UUID: EditorTabHistory] = [:] + + func store(_ history: EditorTabHistory?, for tabId: UUID) { + entries[tabId] = history + } + + func take(for tabId: UUID) -> EditorTabHistory? { + entries.removeValue(forKey: tabId) + } + + func forget(_ tabId: UUID) { + entries.removeValue(forKey: tabId) + } + + func forgetAll(except openTabIds: Set) { + guard entries.keys.contains(where: { !openTabIds.contains($0) }) else { return } + entries = entries.filter { openTabIds.contains($0.key) } + } +} diff --git a/apple/TablePro/Views/Editor/QueryEditorBar.swift b/apple/TablePro/Views/Editor/QueryEditorBar.swift index 7418150171..63ff45bc24 100644 --- a/apple/TablePro/Views/Editor/QueryEditorBar.swift +++ b/apple/TablePro/Views/Editor/QueryEditorBar.swift @@ -54,6 +54,8 @@ struct QueryEditorBar: View { schemaName: scope.schemaName, onChange: onContainerChanged ) + // A run moved to another database mid-flight would either land its rows there or lose what it committed. + .disabled(isExecuting) if let vimMode { VimModeIndicatorView(mode: vimMode) diff --git a/apple/TablePro/Views/Editor/SQLEditorController.swift b/apple/TablePro/Views/Editor/SQLEditorController.swift index e62f529488..ce77c85748 100644 --- a/apple/TablePro/Views/Editor/SQLEditorController.swift +++ b/apple/TablePro/Views/Editor/SQLEditorController.swift @@ -21,6 +21,7 @@ struct SQLEditorInput { var databaseScope: DatabaseScope? var connectionId: UUID? var tabID: UUID? + var undoHistories: EditorUndoHistories? var sourceFileURL: URL? var claimFocusOnAppear = false /// Called once the editor has latched a focus claim, so the owner's one-shot intent is cleared. @@ -87,6 +88,7 @@ final class SQLEditorController { view.setAccessibilityRole(.group) view.setAccessibilityLabel(String(localized: "SQL query editor")) view.setAccessibilityIdentifier("sql-editor-textview") + restoreTabHistory(of: input) observeEditorSettings() observeVimMode() @@ -100,12 +102,17 @@ final class SQLEditorController { func apply(_ newInput: SQLEditorInput) { guard !isTornDown else { return } let old = input - if newInput.tabID != old.tabID { + let switchesTab = newInput.tabID != old.tabID + if switchesTab { handOverPendingText(to: old.text) + saveTabHistory(of: old) } input = newInput applyInput(newInput) pushEditor() + if switchesTab { + restoreTabHistory(of: newInput) + } if newInput.pendingStatementJump != old.pendingStatementJump, let jump = newInput.pendingStatementJump { coordinator.jumpToStatement(jump) @@ -136,6 +143,7 @@ final class SQLEditorController { guard !isTornDown else { return } isTornDown = true handOverPendingText(to: input.text) + saveTabHistory(of: input) profileTask?.cancel() profileTask = nil revisionSubscription = nil @@ -151,6 +159,28 @@ final class SQLEditorController { Task { @MainActor in binding.wrappedValue = text } } + // One editor serves every query tab, and handing it another tab's text clears its history and Vim marks. + private func saveTabHistory(of input: SQLEditorInput) { + guard let tabID = input.tabID, let histories = input.undoHistories else { return } + let undo = textViewController.takeUndoHistory() + let vimMarks = coordinator.vimDocumentMarks + guard undo != nil || vimMarks != nil else { + histories.store(nil, for: tabID) + return + } + let text = undo?.text ?? textViewController.textView.string + histories.store(EditorTabHistory(text: text, undo: undo, vimMarks: vimMarks), for: tabID) + } + + // A tab whose text changed while it was away gets neither back. + private func restoreTabHistory(of input: SQLEditorInput) { + guard let tabID = input.tabID, let saved = input.undoHistories?.take(for: tabID) else { return } + let matches = saved.undo.map { textViewController.restoreUndoHistory($0) } + ?? (saved.text as NSString).isEqual(to: textViewController.textView.string) + guard matches, let vimMarks = saved.vimMarks else { return } + coordinator.restoreVimDocumentMarks(vimMarks) + } + private func applyInput(_ input: SQLEditorInput) { coordinator.onCloseTab = input.onCloseTab coordinator.onExecuteQuery = input.onExecuteQuery @@ -226,7 +256,8 @@ final class SQLEditorController { state: state, foldProvider: foldProvider, coordinators: [coordinator], - completionDelegate: completionAdapter + completionDelegate: completionAdapter, + documentID: input.tabID.map { AnyHashable($0) } ) } diff --git a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift index 1ec3d48dc9..6f08bee71e 100644 --- a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift +++ b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift @@ -111,9 +111,25 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie controller.restoreCollapsedFolds(ranges) } + var vimDocumentMarks: VimDocumentMarks? { + guard let vimEngine else { return pendingVimDocumentMarks } + let marks = vimEngine.documentMarks + return marks.isEmpty ? nil : marks + } + + func restoreVimDocumentMarks(_ marks: VimDocumentMarks) { + guard let vimEngine else { + pendingVimDocumentMarks = marks + return + } + vimEngine.restoreDocumentMarks(marks) + } + /// Vim mode for UI observation @Published private(set) var vimMode: VimMode = .normal private var vimEngine: VimEngine? + // Vim is installed once the editor is in a window, so marks restored before that wait here. + private var pendingVimDocumentMarks: VimDocumentMarks? private var vimKeyInterceptor: VimKeyInterceptor? private var emacsKeyInterceptor: EmacsKeyInterceptor? private var commandHandler = VimCommandLineHandler() @@ -265,6 +281,8 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie func textViewDidReplaceDocument(controller: TextViewController) { vimEngine?.invalidateLineCache() + vimEngine?.documentDidReplace() + pendingVimDocumentMarks = nil foldPreview.dismiss() inlineSuggestionManager?.dismissSuggestion() statementRunController.refreshControls(in: controller) @@ -729,6 +747,10 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie let interceptor = VimKeyInterceptor(engine: engine, inlineSuggestionManager: inlineSuggestionManager) interceptor.install(controller: controller) + if let marks = pendingVimDocumentMarks { + engine.restoreDocumentMarks(marks) + pendingVimDocumentMarks = nil + } self.vimEngine = engine self.vimKeyInterceptor = interceptor self.vimMode = .normal diff --git a/apple/TablePro/Views/Main/Child/DataTabSQLExporter.swift b/apple/TablePro/Views/Main/Child/DataTabSQLExporter.swift index 7e4e542b48..ec2299d278 100644 --- a/apple/TablePro/Views/Main/Child/DataTabSQLExporter.swift +++ b/apple/TablePro/Views/Main/Child/DataTabSQLExporter.swift @@ -36,7 +36,10 @@ final class DataTabSQLExporter: DataGridSQLExporting { let tableName = tab.tableContext.tableName else { return nil } return Target( tableName: tableName, - schemaName: tab.tableContext.schemaName, + // A query tab's schema is the picker's; the rows name the schema they were read in. + schemaName: tab.tabType == .query + ? tab.display.activeResultSet?.origin?.schemaName ?? tab.tableContext.schemaName + : tab.tableContext.schemaName, primaryKeyColumns: tab.tableContext.primaryKeyColumns, databaseType: coordinator.connection.type, connectionId: coordinator.connectionId, diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index a246fc2a70..e71cca6db9 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -478,17 +478,7 @@ struct MainEditorContentView: View { // The tab owns the new container for life, so it moves to that entry and the window follows, like selecting its tab. private func changeContainer(for tab: QueryTab, to name: String) { - let tabId = tab.id - guard tabManager.containerName(of: tab) != name, - tabManager.mutate(tabId: tabId, { tab in - QueryContainerRebinding.rebind(&tab.tableContext, to: name, target: containerSwitchTarget) - }) else { return } - tabManager.markTabRenamed(tabId) - SchemaProviderRegistry.shared.reclaimUnheldProviders(for: connectionId) - guard tabManager.selectedTabId == tabId, - ContainerChangeRerunPolicy.reruns(showing: tabManager.selectedTab?.display.activeResultSet) else { return } - // The statement at the caret may not be the one that produced the rows, so a write asks first. - coordinator.runQuery(viewport: .firstRow, extraCapabilities: .confirmsWrites) + coordinator.changeQueryContainer(of: tab.id, to: name, target: containerSwitchTarget) } private func dismissDiskChangeBanner(tabId: UUID) { @@ -1222,6 +1212,7 @@ extension MainEditorContentView { databaseScope: queryScope, connectionId: coordinator.connection.id, tabID: tab.id, + undoHistories: coordinator.editorUndoHistories, sourceFileURL: tab.content.sourceFileURL, claimFocusOnAppear: claimFocus, onFocusClaimed: { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Alerts.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Alerts.swift index fda3245d62..6147d54473 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Alerts.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Alerts.swift @@ -61,6 +61,8 @@ extension MainContentCoordinator { /// edits: the table is fetched again with a different column list. case .columnVisibility: return String(localized: "Showing or hiding columns will reload data and discard all unsaved changes.") + case .containerChange: + return String(localized: "Moving this tab to another database or schema will discard all unsaved changes.") } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift new file mode 100644 index 0000000000..6421fa5ef7 --- /dev/null +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ContainerChange.swift @@ -0,0 +1,43 @@ +// +// MainContentCoordinator+ContainerChange.swift +// TablePro +// + +import Foundation + +extension MainContentCoordinator { + // Everything the tab was doing belongs to the object it named: its run, its edit in progress and the cached metadata. + internal func retargetTab(_ tabId: UUID) { + existingGridModel(forTab: tabId)?.discardEditing() + flushColumnLayoutPersistence() + supersedeExecution(for: tabId) + releaseRetargetedTabState(for: tabId) + } + + // A rebind is a retarget: rows read from the old container must never land, or stay editable, under the new one. + 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 + guard confirmed, let self, canChangeContainer(of: tabId, to: name) else { return } + retargetTab(tabId) + guard tabManager.mutate(tabId: tabId, { tab in + QueryContainerRebinding.rebind(&tab.tableContext, to: name, target: target) + // Rows still on screen were read from the old container; Load More would page them from the new one. + tab.pagination.resetLoadMore() + }) else { return } + tabManager.markTabRenamed(tabId) + SchemaProviderRegistry.shared.reclaimUnheldProviders(for: connectionId) + guard ContainerChangeRerunPolicy.reruns(showing: tabManager.selectedTab?.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) + } + } + + // The picker is off while the tab runs: a running tab moved elsewhere would land its rows under the new database. + private func canChangeContainer(of tabId: UUID, to name: String) -> Bool { + guard tabManager.selectedTabId == tabId, !tabExecution.isExecuting(tabId), + let tab = tabManager.tabs.first(where: { $0.id == tabId }) else { return false } + return tabManager.containerName(of: tab) != name + } +} diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultEditing.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultEditing.swift index 42a1a7eec2..66ef37bdcc 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultEditing.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ResultEditing.swift @@ -16,10 +16,21 @@ extension MainContentCoordinator { guard tab.tabType == .query else { return tab.tableContext.viewEditRefusal } return ResultEditability.refusal( for: tab.display.activeResultSet?.origin, - currentDatabaseName: scope(for: tab)?.database ?? browseDatabaseName + currentDatabaseName: boundDatabaseName(of: tab), + currentSchemaName: tab.tableContext.schemaName ) } + // Rows read in another database or schema than the tab names now: paging them would read from the new one. + func wasReadElsewhere(_ resultSet: ResultSet, in tab: QueryTab) -> Bool { + guard tab.tabType == .query, let origin = resultSet.origin else { return false } + return origin.wasRead(elsewhereThanDatabase: boundDatabaseName(of: tab), schema: tab.tableContext.schemaName) + } + + private func boundDatabaseName(of tab: QueryTab) -> String { + scope(for: tab)?.database ?? browseDatabaseName + } + /// The one answer to "may the rows on screen be written to". /// /// The grid, the row inspector and the Edit menu each used to decide this for themselves and diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift index 857cecd874..c8cdf4bfd3 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabClosing.swift @@ -76,6 +76,8 @@ extension MainContentCoordinator { prune(&erDiagramModels, keeping: openTabIds) discardTableHealthModels(tableHealthModels.keys.filter { !openTabIds.contains($0) }) prune(&navigationHistories, keeping: openTabIds) + // The editor stores the outgoing tab's history on its next update, after the close forgot it. + editorUndoHistories.forgetAll(except: openTabIds) toolbarState.forgetQueryTimings(keeping: openTabIds) for (tabId, session) in structureSessions where !openTabIds.contains(tabId) { session.releaseViewWiring() @@ -112,6 +114,7 @@ extension MainContentCoordinator { erDiagramModels.removeValue(forKey: tab.id) discardTableHealthModels([tab.id]) navigationHistories.removeValue(forKey: tab.id) + editorUndoHistories.forget(tab.id) releaseGridModel(forTab: tab.id) tableMetadataCache.removeValue(forKey: tab.id) guard isSelectedTab(tab) else { return } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabRestore.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabRestore.swift index d79285c440..3d0961cf40 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabRestore.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TabRestore.swift @@ -135,7 +135,8 @@ extension MainContentCoordinator { ) } - internal func restoreSavedTabs() async { + // `keepingEntry`: the window was opened on content, which decides the database it shows, even when it names none. + internal func restoreSavedTabs(keepingEntry: Bool = false) async { /// The split view controller owns the window and is wired up before the content view is built, /// unlike the content view's own window, which arrives from `configureWindow`. guard let window = splitViewController?.view.window else { @@ -180,8 +181,8 @@ extension MainContentCoordinator { await applyRestoredGroup( restoredTabs, selectedTabId: result.selectedTabId ?? restoredTabs.first?.id, - activeDatabase: result.lastActiveDatabase, - activeSchema: result.lastActiveSchema, + activeDatabase: keepingEntry ? nil : result.lastActiveDatabase, + activeSchema: keepingEntry ? nil : result.lastActiveSchema, loadTiming: window.isKeyWindow ? .immediate : .deferred ) } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift index b6fc23496b..27fc922ce3 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+TableRowsMutation.swift @@ -159,8 +159,8 @@ extension MainContentCoordinator { guard tabManager.tabs[tabIdx].tabType == .query else { return } let origin = resultSet.origin tabManager.mutate(at: tabIdx) { tab in + // Not the schema: it is the tab's binding, and a pinned result from another schema would move the next run there. tab.tableContext.tableName = origin?.tableName - tab.tableContext.schemaName = origin?.schemaName tab.tableContext.primaryKeyColumns = origin?.primaryKeyColumns ?? [] tab.tableContext.isEditable = origin?.isEditable ?? false tab.tableContext.isView = origin?.isView ?? false @@ -221,13 +221,15 @@ extension MainContentCoordinator { private func syncLoadMoreState(from resultSet: ResultSet, at tabIdx: Int) { guard tabManager.tabs[tabIdx].tabType == .query else { return } + let readElsewhere = wasReadElsewhere(resultSet, in: tabManager.tabs[tabIdx]) tabManager.mutate(at: tabIdx) { tab in - if resultSet.isTruncated { + if resultSet.isTruncated, !readElsewhere { tab.pagination.hasMoreRows = true tab.pagination.isLoadingMore = false } else { tab.pagination.resetLoadMore() } + guard !readElsewhere else { return } tab.pagination.setBaseQueryForMore( resultSet.baseQuery, parameterValues: resultSet.baseQueryParameterValues diff --git a/apple/TablePro/Views/Main/Extensions/MainContentView+Setup.swift b/apple/TablePro/Views/Main/Extensions/MainContentView+Setup.swift index 0cef1d7cf8..ab54949fc8 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentView+Setup.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentView+Setup.swift @@ -37,8 +37,10 @@ extension MainContentView { } } - if payload == nil || payload?.intent == .restoreOrDefault { - await coordinator.restoreSavedTabs() + // The merge keeps the founding tab, its selection and its entry in front of the saved ones. + if coordinator.persistence.readsSavedTabs(foundedWith: payload?.intent) { + let foundedOnContent = payload.map { $0.intent != .restoreOrDefault } ?? false + await coordinator.restoreSavedTabs(keepingEntry: foundedOnContent) } // Before the schema load, which can take seconds, so a move waiting on the restore lands now. coordinator.settleTabRestore() diff --git a/apple/TablePro/Views/Main/MainContentCommandActions.swift b/apple/TablePro/Views/Main/MainContentCommandActions.swift index 0decc6483f..8cbfd7e5b0 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions.swift @@ -215,9 +215,12 @@ final class MainContentCommandActions: ObservableObject { let rowIDs = selectedDataRowIDs if !rowIDs.isEmpty { coordinator?.deleteRows(rowIDs) - } else if !selectedTables.wrappedValue.isEmpty { - // Through the sidebar's own path, which asks before it queues a drop. - coordinator?.sidebarViewModel?.batchToggleDelete(refs: Array(selectedTables.wrappedValue)) + } else if !selectedTables.wrappedValue.isEmpty, let coordinator { + // Through the sidebar's own path, which asks this window before it queues a drop. + coordinator.sidebarViewModel?.batchToggleDelete( + refs: Array(selectedTables.wrappedValue), + from: coordinator.windowSidebarState + ) } } @@ -814,13 +817,16 @@ final class MainContentCommandActions: ObservableObject { } func copyTableNames() { - coordinator?.sidebarViewModel?.copySelectedTableNames() + SidebarViewModel.copyTableNames(of: selectedTables.wrappedValue) } func truncateTables() { guard coordinator?.admitsSheetCommand() == true else { return } - guard canTruncateSelectedTables else { return } - coordinator?.sidebarViewModel?.batchToggleTruncate() + guard canTruncateSelectedTables, let coordinator else { return } + coordinator.sidebarViewModel?.batchToggleTruncate( + refs: Array(selectedTables.wrappedValue), + from: coordinator.windowSidebarState + ) } // MARK: - Filter Operations (Group A: Called Directly) diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index d603b2f471..896bc3d933 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -26,6 +26,7 @@ enum DiscardAction { case displayOrder case columnVisibility case run + case containerChange } struct DisplayFormatsCacheEntry { @@ -288,6 +289,8 @@ final class MainContentCoordinator: ObservableObject { var deferredRestoreLoadTabId: UUID? var displayFormatsCache: [UUID: DisplayFormatsCacheEntry] = [:] + // One editor serves every query tab of the window, so each tab's undo history waits here while another is shown. + let editorUndoHistories = EditorUndoHistories() // Published because the inspector rebuilds its snapshot from it (load, comment refetch, rename). @Published var tableMetadataCache: [UUID: TableMetadataCacheEntry] = [:] // Bumped per Table Info invalidation so an in-flight read can't mark the cache current; per window, as it can precede a tab entry. @@ -658,10 +661,7 @@ final class MainContentCoordinator: ObservableObject { self?.browseCursorCoordinator.browseContainerDidChange() } tabManager.onTabRetargeted = { [weak self] tabId in - self?.existingGridModel(forTab: tabId)?.discardEditing() - self?.flushColumnLayoutPersistence() - self?.supersedeExecution(for: tabId) - self?.releaseRetargetedTabState(for: tabId) + self?.retargetTab(tabId) } // Synchronous: queue .main satisfies assumeIsolated, and the write finishes before exit, unlike Task-based saves. diff --git a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift index 3d05770683..dd17344ce9 100644 --- a/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift +++ b/apple/TablePro/Views/Sidebar/DatabaseTreeOutlineCoordinator+Commands.swift @@ -89,11 +89,13 @@ extension DatabaseTreeOutlineCoordinator { } case .truncateTables(let targets, let ref): activateThen(ref) { [weak self] in - self?.viewModel?.batchToggleTruncate(refs: targets) + guard let self, let windowState = self.windowState else { return } + self.viewModel?.batchToggleTruncate(refs: targets, from: windowState) } case .dropTables(let targets, let ref): activateThen(ref) { [weak self] in - self?.viewModel?.batchToggleDelete(refs: targets) + guard let self, let windowState = self.windowState else { return } + self.viewModel?.batchToggleDelete(refs: targets, from: windowState) } case .beginRenameTable(let ref, let isRecentRow): activateThen(ref) { [weak self] in diff --git a/apple/TablePro/Views/Sidebar/SidebarView.swift b/apple/TablePro/Views/Sidebar/SidebarView.swift index ec55eab1ab..514b7184ce 100644 --- a/apple/TablePro/Views/Sidebar/SidebarView.swift +++ b/apple/TablePro/Views/Sidebar/SidebarView.swift @@ -148,20 +148,14 @@ struct SidebarView: View { self.windowState = windowState _pendingTruncates = pendingTruncates _pendingDeletes = pendingDeletes - let selectedBinding = Binding( - get: { windowState.selectedTables }, - set: { windowState.selectTables($0) } - ) let vm = SidebarViewModel.shared( connectionId: connectionId, databaseType: databaseType, - selectedTables: selectedBinding, pendingTruncates: pendingTruncates, pendingDeletes: pendingDeletes, tableOperationOptions: tableOperationOptions ) - /// Nothing observable is written here. This initializer runs on every evaluation of the - /// parent's body, and the view model already seeds its own filter and watches the field. + // Nothing observable is written here: this runs on every evaluation of the parent's body. _viewModel = StateObject(wrappedValue: vm) self.connectionId = connectionId self.coordinator = coordinator @@ -213,34 +207,30 @@ struct SidebarView: View { // A refresh can put the catalog back to loading before the frame, and a stale true skips the next hold. CommittedTurn.after(in: coordinator?.contentWindow) { showsLoadedCatalog = isCatalogLoaded } } - .onChange(of: viewModel.showOperationDialog) { isPresented in - guard isPresented else { return } - presentOperationAlert() + .onChange(of: windowState.pendingTableOperation?.id) { _ in + guard let request = windowState.pendingTableOperation else { return } + presentOperationAlert(for: request) } } - private func presentOperationAlert() { - guard let operationType = viewModel.pendingOperationType, - let firstTable = viewModel.pendingOperationTables.first - else { - viewModel.showOperationDialog = false + private func presentOperationAlert(for request: PendingTableOperation) { + let windowState = windowState + guard let firstTable = request.tables.first else { + windowState.resolveTableOperation(request) return } let prompt = TableOperationPrompt( - operationType: operationType, + operationType: request.operation, tableName: firstTable.table.name, - tableCount: viewModel.pendingOperationTables.count, + tableCount: request.tables.count, cascadeSupported: PluginManager.shared.supportsCascadeDrop(for: viewModel.databaseType), foreignKeyDisableSupported: PluginManager.shared.supportsForeignKeyDisable(for: viewModel.databaseType) ) let model = viewModel TableOperationAlert.present(prompt: prompt, window: coordinator?.contentWindow) { options in - model.showOperationDialog = false - guard let options else { - model.cancelPendingOperation() - return - } - model.confirmOperation(options: options) + windowState.resolveTableOperation(request) + guard let options else { return } + model.confirmOperation(request, options: options) } } diff --git a/apple/TableProTests/Core/Coordinators/StoppedRunKeepsWorkTests.swift b/apple/TableProTests/Core/Coordinators/StoppedRunKeepsWorkTests.swift new file mode 100644 index 0000000000..4ba335d3a8 --- /dev/null +++ b/apple/TableProTests/Core/Coordinators/StoppedRunKeepsWorkTests.swift @@ -0,0 +1,319 @@ +// +// StoppedRunKeepsWorkTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import TableProSQLGrammar +import TableProTestSupport +import Testing + +@MainActor +struct StoppedRunKeepsWorkTests { + private static let script = "INSERT INTO t VALUES (1);\nINSERT INTO t VALUES (2);\nINSERT INTO t VALUES (3);" + + private let connection: DatabaseConnection + private let storage: QueryHistoryStorage + private let fixture: CoordinatorFixture + + init() { + let connection = TestFixtures.makeConnection() + let storage = QueryHistoryStorage( + databaseURL: FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-tests") + .appendingPathComponent("stopped_run_\(UUID().uuidString).db"), + removeDatabaseOnDeinit: true + ) + self.connection = connection + self.storage = storage + fixture = CoordinatorFixture( + connection: connection, + services: .live.recordingHistory(in: QueryHistoryManager(storage: storage, isCapturePaused: { false })) + ) + } + + @Test("Stop on Run All in an open transaction keeps the statements that ran, and their history") + func stopKeepsTheStatementsThatRan() async throws { + let driver = HeldStatementDriver(connection: connection, holding: 2, onCancel: .keepsRunning) + defer { finish(driver) } + let run = try startRun(on: driver) + + try await waitUntil { driver.isHolding } + fixture.coordinator.stopExecution(for: run.tabId) + driver.finishHeldStatement() + await run.handle.value + + let tab = try #require(fixture.tabManager.tabs.first { $0.id == run.tabId }) + #expect(driver.sentStatements.count == 2) + #expect(tab.display.resultSets.count == 1) + #expect(tab.display.resultSets.first?.rowsAffected == 2) + #expect(tab.execution.rowsAffected == 2) + #expect(tab.execution.statusMessage == PluginSessionTransactionState.inTransaction.openTransactionNotice) + #expect(fixture.coordinator.tabExecution.isAnyExecuting == false) + + let entries = try await history(count: 2) + #expect(entries.map { $0.query } == ["INSERT INTO t VALUES (1);", "INSERT INTO t VALUES (2);"]) + #expect(entries.allSatisfy { $0.wasSuccessful }) + } + + @Test("Stop that interrupts a statement reads as a stop: the statements before it are kept, with no error") + func stopThatInterruptsAStatementKeepsTheOnesBefore() async throws { + let driver = HeldStatementDriver(connection: connection, holding: 3, onCancel: .failsTheStatement) + defer { finish(driver) } + let run = try startRun(on: driver) + + try await waitUntil { driver.isHolding } + fixture.coordinator.stopExecution(for: run.tabId) + try await waitUntil { !driver.isHolding } + await run.handle.value + + let tab = try #require(fixture.tabManager.tabs.first { $0.id == run.tabId }) + let results = tab.display.resultSets + #expect(driver.sentStatements.count == 3) + #expect(results.count == 1) + #expect(results.first?.rowsAffected == 2) + #expect(results.allSatisfy { $0.errorMessage == nil }) + #expect(tab.execution.errorMessage == nil) + #expect(tab.execution.statusMessage == PluginSessionTransactionState.inTransaction.openTransactionNotice) + #expect(fixture.coordinator.tabExecution.isAnyExecuting == false) + + let entries = try await history(count: 2) + #expect(entries.map { $0.query } == ["INSERT INTO t VALUES (1);", "INSERT INTO t VALUES (2);"]) + #expect(entries.allSatisfy { $0.wasSuccessful }) + } + + @Test("A stopped run that comes back after edits were staged keeps them and only writes history") + func stoppedRunKeepsEditsStagedAfterStop() async throws { + let driver = HeldStatementDriver(connection: connection, holding: 2, onCancel: .keepsRunning) + defer { finish(driver) } + let run = try startRun(on: driver) + + try await waitUntil { driver.isHolding } + fixture.coordinator.stopExecution(for: run.tabId) + let contentAfterStop = fixture.coordinator.tabExecution.contentEpoch(for: run.tabId) + fixture.changeManager.recordRowDeletion(rowID: .existing(0), originalRow: [.text("1")]) + driver.finishHeldStatement() + await run.handle.value + + let tab = try #require(fixture.tabManager.tabs.first { $0.id == run.tabId }) + #expect(fixture.changeManager.hasChanges) + #expect(tab.display.resultSets.isEmpty) + #expect(fixture.coordinator.tabExecution.isSameContent(contentAfterStop, for: run.tabId)) + #expect(fixture.coordinator.tabExecution.isAnyExecuting == false) + + let entries = try await history(count: 2) + #expect(entries.map { $0.query } == ["INSERT INTO t VALUES (1);", "INSERT INTO t VALUES (2);"]) + } + + @Test("A run that a new run superseded after its Stop writes nothing") + func supersededStoppedRunWritesNothing() async throws { + let driver = HeldStatementDriver(connection: connection, holding: 2, onCancel: .keepsRunning) + defer { finish(driver) } + let run = try startRun(on: driver) + + try await waitUntil { driver.isHolding } + fixture.coordinator.stopExecution(for: run.tabId) + let successor = fixture.coordinator.beginTabExecution(for: run.tabId) + driver.finishHeldStatement() + await run.handle.value + + let tab = try #require(fixture.tabManager.tabs.first { $0.id == run.tabId }) + #expect(tab.display.resultSets.isEmpty) + #expect(tab.execution.statusMessage == nil) + #expect(fixture.coordinator.tabExecution.isCurrent(successor.claim)) + } + + private func startRun(on driver: HeldStatementDriver) throws -> (tabId: UUID, handle: Task) { + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connected + session.browseDatabase = connection.database + DatabaseManager.shared.injectSession(session, for: connection.id) + + let tab = fixture.addTab(QueryTab(title: "Query", query: Self.script, tabType: .query)) + let statements = SQLStatementScanner.executableStatements( + in: Self.script, grammar: fixture.coordinator.lexicalGrammar + ) + fixture.coordinator.queryExecutionCoordinator.executeMultipleStatements(statements) + let handle = try #require(fixture.coordinator.queryTasks.task(for: tab.id)) + return (tab.id, handle) + } + + private func finish(_ driver: HeldStatementDriver) { + driver.finishHeldStatement() + DatabaseManager.shared.removeSession(for: connection.id) + } + + // History is written on tasks the run does not await. + private func history(count: Int) async throws -> [QueryHistoryEntry] { + let storage = self.storage + let scope = QueryHistoryScope.connection(connection.id) + try await waitUntil { await storage.count(scope: scope) == count } + let page = await storage.fetch(QueryHistoryFilter(scope: scope), after: nil, limit: count + 1) + return page.entries.sorted { $0.query < $1.query } + } +} + +// Holds the statement at `heldPosition` until the test lets it go, or until a Stop's driver cancel fails it. +private final class HeldStatementDriver: DatabaseDriver, @unchecked Sendable { + enum OnCancel { + case keepsRunning + case failsTheStatement + } + + struct Interrupted: LocalizedError { + var errorDescription: String? { "canceling statement due to user request" } + } + + let connection: DatabaseConnection + var status: ConnectionStatus = .connected + var serverVersion: String? { nil } + var sessionLexicalState: PluginSessionLexicalState? { nil } + + private let heldPosition: Int + private let onCancel: OnCancel + private let lock = NSLock() + private var sent: [String] = [] + private var held: CheckedContinuation? + + init(connection: DatabaseConnection, holding heldPosition: Int, onCancel: OnCancel) { + self.connection = connection + self.heldPosition = heldPosition + self.onCancel = onCancel + } + + var sentStatements: [String] { + lock.withLock { sent } + } + + var isHolding: Bool { + lock.withLock { held != nil } + } + + func finishHeldStatement() { + takeHeld()?.resume() + } + + func cancelQuery() throws { + guard onCancel == .failsTheStatement else { return } + takeHeld()?.resume(throwing: Interrupted()) + } + + func sessionTransactionState() async -> PluginSessionTransactionState { .inTransaction } + + private func takeHeld() -> CheckedContinuation? { + lock.withLock { + let continuation = held + held = nil + return continuation + } + } + + private func run(_ query: String) async throws -> QueryResult { + let position = lock.withLock { + sent.append(query) + return sent.count + } + if position == heldPosition { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + lock.withLock { held = continuation } + } + } + return QueryResult(columns: [], columnTypes: [], rows: [], rowsAffected: 1, executionTime: 0, error: nil) + } + + func execute(query: String) async throws -> QueryResult { try await run(query) } + func executeParameterized(query: String, parameters: [Any?]) async throws -> QueryResult { try await run(query) } + func executeUserQuery(query: String, rowCap: Int?, parameters: [Any?]?) async throws -> QueryResult { + try await run(query) + } + + func connect() async throws {} + func disconnect() {} + func testConnection() async throws -> Bool { true } + func ping() async throws {} + func applyQueryTimeout(_ seconds: Int) async throws {} + + func fetchTables() async throws -> [TableInfo] { [] } + func fetchTables(schema: String?) async throws -> [TableInfo] { [] } + func fetchColumns(table: String) async throws -> [ColumnInfo] { [] } + func fetchAllColumns() async throws -> [String: [ColumnInfo]] { [:] } + func fetchIndexes(table: String) async throws -> [IndexInfo] { [] } + func fetchForeignKeys(table: String) async throws -> [ForeignKeyInfo] { [] } + func fetchApproximateRowCount(table: String) async throws -> Int? { nil } + func fetchDatabases() async throws -> [String] { [] } + func fetchDatabaseMetadata(_ database: String) async throws -> DatabaseMetadata { + DatabaseMetadata( + id: database, + name: database, + tableCount: nil, + sizeBytes: nil, + lastAccessed: nil, + isSystemDatabase: false, + icon: "cylinder" + ) + } + + func fetchTableDDL(table: String) async throws -> String { "" } + func fetchTableMetadata(tableName: String) async throws -> TableMetadata { + TableMetadata( + tableName: tableName, + dataSize: nil, + indexSize: nil, + totalSize: nil, + avgRowLength: nil, + rowCount: nil, + comment: nil, + engine: nil, + collation: nil, + createTime: nil, + updateTime: nil + ) + } + + func fetchViewDefinition(view: String) async throws -> String { "" } + func beginTransaction() async throws {} + 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/Execution/TabExecutionRegistryTests.swift b/apple/TableProTests/Core/Execution/TabExecutionRegistryTests.swift index 44649cef4f..8bc43894d0 100644 --- a/apple/TableProTests/Core/Execution/TabExecutionRegistryTests.swift +++ b/apple/TableProTests/Core/Execution/TabExecutionRegistryTests.swift @@ -400,6 +400,142 @@ struct TabExecutionRegistryTests { #expect(registry.isStoppable(tabId) == false) } + // MARK: - A stopped claim keeping its work + + @Test("A claim Stop ended keeps its work once, and settle still refuses it") + func stoppedClaimKeepsItsWorkOnce() { + var registry = TabExecutionRegistry() + let tabId = UUID() + let claim = registry.claim(tabId) + + _ = registry.stop(tabId) + + let settled = registry.settle(claim) + #expect(settled == false) + let kept = registry.settleStopped(claim, replacingContent: true) + #expect(kept) + let keptAgain = registry.settleStopped(claim, replacingContent: true) + #expect(keptAgain == false) + #expect(registry.isAnyExecuting == false) + } + + @Test("Keeping a stopped claim's work gives the tab new content only when it replaces the result") + func keepingStoppedWorkChangesTheContentOnlyWhenItReplaces() { + var replacing = TabExecutionRegistry() + let replacingTab = UUID() + let replacingClaim = replacing.claim(replacingTab) + _ = replacing.stop(replacingTab) + let replacedContent = replacing.contentEpoch(for: replacingTab) + + let replaced = replacing.settleStopped(replacingClaim, replacingContent: true) + + #expect(replaced) + #expect(replacing.isSameContent(replacedContent, for: replacingTab) == false) + + var keeping = TabExecutionRegistry() + let keepingTab = UUID() + let keepingClaim = keeping.claim(keepingTab) + _ = keeping.stop(keepingTab) + let keptContent = keeping.contentEpoch(for: keepingTab) + + let kept = keeping.settleStopped(keepingClaim, replacingContent: false) + + #expect(kept) + #expect(keeping.isSameContent(keptContent, for: keepingTab)) + } + + @Test("A second Stop with nothing running leaves the stopped claim its work") + func secondStopKeepsTheStoppedClaim() { + var registry = TabExecutionRegistry() + let tabId = UUID() + let claim = registry.claim(tabId) + _ = registry.stop(tabId) + + let second = registry.stop(tabId) + + #expect(second.ended.isEmpty) + let kept = registry.settleStopped(claim, replacingContent: true) + #expect(kept) + } + + @Test("A new run after Stop leaves the stopped claim nothing to write") + func newRunForgetsTheStoppedClaim() { + var registry = TabExecutionRegistry() + let tabId = UUID() + let stopped = registry.claim(tabId) + _ = registry.stop(tabId) + + let successor = registry.claim(tabId) + + let kept = registry.settleStopped(stopped, replacingContent: true) + #expect(kept == false) + #expect(registry.isCurrent(successor)) + } + + @Test( + "A retarget, a tab close or a lost session after Stop leaves the stopped claim nothing to write", + arguments: [ExecutionEndReason.supersededNavigation, .abandoned, .sessionEnded] + ) + func invalidationForgetsTheStoppedClaim(reason: ExecutionEndReason) { + var registry = TabExecutionRegistry() + let tabId = UUID() + let stopped = registry.claim(tabId) + _ = registry.stop(tabId) + + _ = registry.invalidate(tabId, reason: reason) + + let kept = registry.settleStopped(stopped, replacingContent: true) + #expect(kept == false) + + var all = TabExecutionRegistry() + let allTabId = UUID() + let allStopped = all.claim(allTabId) + _ = all.stop(allTabId) + + _ = all.invalidateAll(reason: reason) + + let keptAll = all.settleStopped(allStopped, replacingContent: true) + #expect(keptAll == false) + } + + @Test("Stop records nothing for a committing claim it keeps") + func keptCommittingClaimIsNotStopped() { + var registry = TabExecutionRegistry() + let tabId = UUID() + let claim = registry.claim(tabId) + let marked = registry.enterUninterruptiblePhase(claim) + #expect(marked) + + let outcome = registry.stop(tabId) + + #expect(outcome.keptUninterruptibleClaim) + let kept = registry.settleStopped(claim, replacingContent: true) + #expect(kept == false) + let settled = registry.settle(claim) + #expect(settled) + } + + @Test("Only the claim Stop ended, on its own tab, keeps its work") + func onlyTheStoppedClaimKeepsItsWork() { + var registry = TabExecutionRegistry() + let tabId = UUID() + let other = UUID() + let earlier = registry.claim(tabId) + _ = registry.stop(tabId) + let later = registry.claim(tabId) + let otherClaim = registry.claim(other) + _ = registry.stop(tabId) + + let keptEarlier = registry.settleStopped(earlier, replacingContent: true) + #expect(keptEarlier == false) + let keptOther = registry.settleStopped(otherClaim, replacingContent: true) + #expect(keptOther == false) + let keptLater = registry.settleStopped(later, replacingContent: true) + #expect(keptLater) + let settledOther = registry.settle(otherClaim) + #expect(settledOther) + } + @Test("A run's start is the claim's own, and work with no claim reports none") func startedAtIsTheClaimsOwn() { var registry = TabExecutionRegistry() diff --git a/apple/TableProTests/Core/Services/ContentFoundedRestoreTests.swift b/apple/TableProTests/Core/Services/ContentFoundedRestoreTests.swift new file mode 100644 index 0000000000..fb057f2811 --- /dev/null +++ b/apple/TableProTests/Core/Services/ContentFoundedRestoreTests.swift @@ -0,0 +1,51 @@ +// +// ContentFoundedRestoreTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct ContentFoundedRestoreTests { + @Test("A workspace founded on one table reads the saved tabs while the connection has not read them") + func contentFoundingReadsSavedTabsWhileTheGateIsClosed() { + let persistence = TabPersistenceCoordinator(connectionId: UUID()) + + #expect(persistence.readsSavedTabs(foundedWith: .openContent)) + #expect(persistence.readsSavedTabs(foundedWith: .newEmptyTab)) + #expect(persistence.readsSavedTabs(foundedWith: .restoreOrDefault)) + #expect(persistence.readsSavedTabs(foundedWith: nil)) + } + + @Test("A tab torn off into a second window does not pull the saved set in after it") + func contentFoundingSkipsTheRestoreOnceTheConnectionReadIt() async { + let persistence = TabPersistenceCoordinator(connectionId: UUID()) + _ = await persistence.restoreFromDisk() + + #expect(!persistence.readsSavedTabs(foundedWith: .openContent)) + #expect(persistence.readsSavedTabs(foundedWith: .restoreOrDefault)) + } + + @Test("A content-founded workspace restores its saved tabs after a reconnect instead of reopening the founding tab") + func releasedWorkspaceRestoresOnReconnect() { + let connectionId = UUID() + let workspace = ConnectionWorkspace( + connectionId: connectionId, + payload: EditorTabPayload(connectionId: connectionId, tabType: .table, tableName: "users"), + autoConnect: false, + payloadConnection: nil, + session: nil, + sessionState: nil, + trailingPaneState: nil, + phase: .connected + ) + + workspace.retireFoundingPayload() + + #expect(workspace.payload?.intent == .restoreOrDefault) + #expect(workspace.payload?.connectionId == connectionId) + #expect(workspace.payload?.tableName == nil) + } +} diff --git a/apple/TableProTests/Core/Services/Query/SidebarSchemaFilterTests.swift b/apple/TableProTests/Core/Services/Query/SidebarSchemaFilterTests.swift index b0028c93be..d42f233767 100644 --- a/apple/TableProTests/Core/Services/Query/SidebarSchemaFilterTests.swift +++ b/apple/TableProTests/Core/Services/Query/SidebarSchemaFilterTests.swift @@ -88,7 +88,6 @@ struct SidebarSchemaFilterTests { } SharedSidebarState.forConnection(connection.id).setSchemaFilter(["attendance"], for: "shop") let viewModel = SidebarViewModel( - selectedTables: .constant([]), pendingTruncates: .constant([]), pendingDeletes: .constant([]), tableOperationOptions: .constant([:]), @@ -113,7 +112,6 @@ struct SidebarSchemaFilterTests { driver.allSchemaTablesError = DatabaseError.queryFailed("listing timed out") } let viewModel = SidebarViewModel( - selectedTables: .constant([]), pendingTruncates: .constant([]), pendingDeletes: .constant([]), tableOperationOptions: .constant([:]), @@ -153,7 +151,6 @@ struct SidebarSchemaFilterTests { } SharedSidebarState.forConnection(connection.id).setSchemaFilter(["attendance"], for: "shop") let viewModel = SidebarViewModel( - selectedTables: .constant([]), pendingTruncates: .constant([]), pendingDeletes: .constant([]), tableOperationOptions: .constant([:]), @@ -178,7 +175,6 @@ struct SidebarSchemaFilterTests { private func makeViewModel(_ connection: DatabaseConnection) -> SidebarViewModel { SidebarViewModel( - selectedTables: .constant([]), pendingTruncates: .constant([]), pendingDeletes: .constant([]), tableOperationOptions: .constant([:]), diff --git a/apple/TableProTests/Models/Query/ResultEditabilityTests.swift b/apple/TableProTests/Models/Query/ResultEditabilityTests.swift index ff496e37f7..a947ea0b1d 100644 --- a/apple/TableProTests/Models/Query/ResultEditabilityTests.swift +++ b/apple/TableProTests/Models/Query/ResultEditabilityTests.swift @@ -16,6 +16,7 @@ struct ResultEditabilityTests { private func origin( tableName: String? = "users", + schemaName: String? = nil, databaseName: String = "app", isEditable: Bool = true, isView: Bool = false, @@ -23,7 +24,7 @@ struct ResultEditabilityTests { ) -> ResultOrigin { ResultOrigin( tableName: tableName, - schemaName: nil, + schemaName: schemaName, databaseName: databaseName, primaryKeyColumns: ["id"], isEditable: isEditable, @@ -36,37 +37,37 @@ struct ResultEditabilityTests { func queryResultOverAViewTakesTheViewGate() { var result = origin() result.viewRowEditing = editable(keys: ["id"]) - #expect(ResultEditability.refusal(for: result, currentDatabaseName: "app") == nil) + #expect(ResultEditability.refusal(for: result, currentDatabaseName: "app", currentSchemaName: nil) == nil) result.primaryKeyColumns = ["name"] - #expect(ResultEditability.refusal(for: result, currentDatabaseName: "app") == .view(nil)) + #expect(ResultEditability.refusal(for: result, currentDatabaseName: "app", currentSchemaName: nil) == .view(nil)) result.viewRowEditing = .readOnly(.couldNotCheck) - #expect(ResultEditability.refusal(for: result, currentDatabaseName: "app") == .view(.couldNotCheck)) + #expect(ResultEditability.refusal(for: result, currentDatabaseName: "app", currentSchemaName: nil) == .view(.couldNotCheck)) } @Test("A result that captured its table is editable") func capturedTableIsEditable() { - #expect(ResultEditability.refusal(for: origin(), currentDatabaseName: "app") == nil) + #expect(ResultEditability.refusal(for: origin(), currentDatabaseName: "app", currentSchemaName: nil) == nil) } @Test("A result with no captured origin refuses instead of borrowing the tab's table") func missingOriginRefuses() { - #expect(ResultEditability.refusal(for: nil, currentDatabaseName: "app") == .unknownTable) + #expect(ResultEditability.refusal(for: nil, currentDatabaseName: "app", currentSchemaName: nil) == .unknownTable) } @Test("A result whose statement resolved no single table refuses") func unresolvedTableRefuses() { #expect( - ResultEditability.refusal(for: origin(tableName: nil, isEditable: false), currentDatabaseName: "app") + ResultEditability.refusal(for: origin(tableName: nil, isEditable: false), currentDatabaseName: "app", currentSchemaName: nil) == .unknownTable ) #expect( - ResultEditability.refusal(for: origin(tableName: ""), currentDatabaseName: "app") == .unknownTable + ResultEditability.refusal(for: origin(tableName: ""), currentDatabaseName: "app", currentSchemaName: nil) == .unknownTable ) } @Test("A view refuses, and says so rather than reporting an unknown table") func viewRefuses() { - #expect(ResultEditability.refusal(for: origin(isView: true), currentDatabaseName: "app") == .view(nil)) + #expect(ResultEditability.refusal(for: origin(isView: true), currentDatabaseName: "app", currentSchemaName: nil) == .view(nil)) } @Test("An updatable view that exposes its table's key is written like a table") @@ -74,7 +75,7 @@ struct ResultEditabilityTests { var view = origin(isView: true) view.objectType = .view view.viewRowEditing = editable(keys: ["id"]) - #expect(ResultEditability.refusal(for: view, currentDatabaseName: "app") == nil) + #expect(ResultEditability.refusal(for: view, currentDatabaseName: "app", currentSchemaName: nil) == nil) } @Test("A view refuses when the keys the edit would use are not the driver's") @@ -82,16 +83,16 @@ struct ResultEditabilityTests { var view = origin(isView: true) view.viewRowEditing = editable(keys: ["id"]) view.primaryKeyColumns = [] - #expect(ResultEditability.refusal(for: view, currentDatabaseName: "app") == .view(nil)) + #expect(ResultEditability.refusal(for: view, currentDatabaseName: "app", currentSchemaName: nil) == .view(nil)) view.primaryKeyColumns = ["code"] - #expect(ResultEditability.refusal(for: view, currentDatabaseName: "app") == .view(nil)) + #expect(ResultEditability.refusal(for: view, currentDatabaseName: "app", currentSchemaName: nil) == .view(nil)) } @Test("A read-only view carries the driver's reason into the refusal") func readOnlyViewSaysWhy() { var view = origin(isView: true) view.viewRowEditing = .readOnly(.keyNotExposed) - #expect(ResultEditability.refusal(for: view, currentDatabaseName: "app") == .view(.keyNotExposed)) + #expect(ResultEditability.refusal(for: view, currentDatabaseName: "app", currentSchemaName: nil) == .view(.keyNotExposed)) } @Test("A materialized view never takes a view's editing answer") @@ -99,27 +100,41 @@ struct ResultEditabilityTests { var matview = origin(isView: true) matview.objectType = .materializedView matview.viewRowEditing = editable(keys: ["id"]) - #expect(ResultEditability.refusal(for: matview, currentDatabaseName: "app") == .view(nil)) + #expect(ResultEditability.refusal(for: matview, currentDatabaseName: "app", currentSchemaName: nil) == .view(nil)) } @Test("A result captured against another database refuses once the tab has moved") func databaseMoveRefuses() { #expect( - ResultEditability.refusal(for: origin(databaseName: "app"), currentDatabaseName: "reporting") + ResultEditability.refusal(for: origin(databaseName: "app"), currentDatabaseName: "reporting", currentSchemaName: nil) == .databaseMoved ) } + @Test("A result read in one schema refuses once the tab's schema picker moved") + func schemaMoveRefuses() { + #expect( + ResultEditability.refusal( + for: origin(schemaName: "staging"), currentDatabaseName: "app", currentSchemaName: "production" + ) == .schemaMoved + ) + #expect( + ResultEditability.refusal( + for: origin(schemaName: "staging"), currentDatabaseName: "app", currentSchemaName: "staging" + ) == nil + ) + } + @Test("An unknown database on either side is not treated as a move") func unknownDatabaseDoesNotRefuse() { - #expect(ResultEditability.refusal(for: origin(databaseName: ""), currentDatabaseName: "app") == nil) - #expect(ResultEditability.refusal(for: origin(databaseName: "app"), currentDatabaseName: "") == nil) + #expect(ResultEditability.refusal(for: origin(databaseName: ""), currentDatabaseName: "app", currentSchemaName: nil) == nil) + #expect(ResultEditability.refusal(for: origin(databaseName: "app"), currentDatabaseName: "", currentSchemaName: nil) == nil) } @Test("A result whose key columns were never looked up refuses") func unresolvedKeysRefuse() { #expect( - ResultEditability.refusal(for: origin(keysResolved: false), currentDatabaseName: "app") + ResultEditability.refusal(for: origin(keysResolved: false), currentDatabaseName: "app", currentSchemaName: nil) == .keysUnresolved ) } @@ -128,7 +143,7 @@ struct ResultEditabilityTests { func resolvedButKeylessTableStaysEditable() { var keyless = origin() keyless.primaryKeyColumns = [] - #expect(ResultEditability.refusal(for: keyless, currentDatabaseName: "app") == nil) + #expect(ResultEditability.refusal(for: keyless, currentDatabaseName: "app", currentSchemaName: nil) == nil) } @Test("Every refusal carries a sentence for the user") @@ -138,7 +153,7 @@ struct ResultEditabilityTests { .baseTableHidden, .baseTableHasNoKey, .keyNotExposed, .couldNotCheck, ] let viewRefusals = reasons.map { ResultEditRefusal.view($0) } - for refusal in [ResultEditRefusal.unknownTable, .databaseMoved, .keysUnresolved] + viewRefusals { + for refusal in [ResultEditRefusal.unknownTable, .databaseMoved, .schemaMoved, .keysUnresolved] + viewRefusals { #expect(!refusal.message.isEmpty) } } diff --git a/apple/TableProTests/ViewModels/SidebarTableOperationWindowTests.swift b/apple/TableProTests/ViewModels/SidebarTableOperationWindowTests.swift new file mode 100644 index 0000000000..946cfa21a0 --- /dev/null +++ b/apple/TableProTests/ViewModels/SidebarTableOperationWindowTests.swift @@ -0,0 +1,89 @@ +import Foundation +import SwiftUI +import Testing +@testable import TablePro + +@MainActor +struct SidebarTableOperationWindowTests { + private final class ConnectionQueues { + var truncates: Set = [] + var deletes: Set = [] + var options: [DatabaseTreeTableRef: TableOperationOptions] = [:] + } + + private let queues = ConnectionQueues() + + private func makeSharedViewModel() -> SidebarViewModel { + let queues = queues + return SidebarViewModel( + pendingTruncates: Binding(get: { queues.truncates }, set: { queues.truncates = $0 }), + pendingDeletes: Binding(get: { queues.deletes }, set: { queues.deletes = $0 }), + tableOperationOptions: Binding(get: { queues.options }, set: { queues.options = $0 }), + databaseType: .mysql, + connectionId: UUID() + ) + } + + private func makeRef(_ name: String) -> DatabaseTreeTableRef { + DatabaseTreeTableRef(database: "shop", schema: nil, table: TestFixtures.makeTableInfo(name: name)) + } + + @Test("A truncate asks only the window it came from, and its confirm writes that window's tables") + func truncateBelongsToTheAskingWindow() throws { + let viewModel = makeSharedViewModel() + let windowA = WindowSidebarState() + let windowB = WindowSidebarState() + let users = makeRef("users") + let orders = makeRef("orders") + windowA.selectTables([users]) + windowB.selectTables([orders]) + + viewModel.batchToggleTruncate(refs: Array(windowA.selectedTables), from: windowA) + + let requestA = try #require(windowA.pendingTableOperation) + #expect(requestA.operation == .truncate) + #expect(requestA.tables == [users]) + #expect(windowB.pendingTableOperation == nil) + + viewModel.batchToggleDelete(refs: Array(windowB.selectedTables), from: windowB) + let requestB = try #require(windowB.pendingTableOperation) + #expect(windowA.pendingTableOperation == requestA) + + let options = TableOperationOptions(ignoreForeignKeys: true) + viewModel.confirmOperation(requestA, options: options) + windowA.resolveTableOperation(requestA) + + #expect(queues.truncates == [users]) + #expect(queues.deletes.isEmpty) + #expect(queues.options == [users: options]) + #expect(windowA.pendingTableOperation == nil) + #expect(windowB.pendingTableOperation == requestB) + } + + @Test("Answering an earlier prompt acts on its own tables, not on a request posted after it") + func confirmActsOnTheRequestItWasShownFor() throws { + let viewModel = makeSharedViewModel() + let window = WindowSidebarState() + let users = makeRef("users") + let orders = makeRef("orders") + + viewModel.batchToggleTruncate(refs: [users], from: window) + let first = try #require(window.pendingTableOperation) + viewModel.batchToggleDelete(refs: [orders], from: window) + let second = try #require(window.pendingTableOperation) + + let options = TableOperationOptions(cascade: true) + viewModel.confirmOperation(first, options: options) + window.resolveTableOperation(first) + + #expect(queues.truncates == [users]) + #expect(queues.deletes.isEmpty) + #expect(queues.options == [users: options]) + #expect(window.pendingTableOperation == second) + + window.resolveTableOperation(second) + + #expect(window.pendingTableOperation == nil) + #expect(queues.deletes.isEmpty) + } +} diff --git a/apple/TableProTests/ViewModels/SidebarViewModelTests.swift b/apple/TableProTests/ViewModels/SidebarViewModelTests.swift index d6689d4181..ae130dca2c 100644 --- a/apple/TableProTests/ViewModels/SidebarViewModelTests.swift +++ b/apple/TableProTests/ViewModels/SidebarViewModelTests.swift @@ -8,34 +8,25 @@ import Testing @MainActor private func makeSUT( - tables: [TableInfo] = [], - selectedTables: Set = [], pendingTruncates: Set = [], pendingDeletes: Set = [], tableOperationOptions: [DatabaseTreeTableRef: TableOperationOptions] = [:], databaseType: DatabaseType = .mysql ) -> ( vm: SidebarViewModel, - tables: Binding<[TableInfo]>, - selectedTables: Binding>, pendingTruncates: Binding>, pendingDeletes: Binding>, tableOperationOptions: Binding<[DatabaseTreeTableRef: TableOperationOptions]> ) { - var tablesState = tables - var selectedState = selectedTables var truncatesState = pendingTruncates var deletesState = pendingDeletes var optionsState = tableOperationOptions - let tablesBinding = Binding(get: { tablesState }, set: { tablesState = $0 }) - let selectedBinding = Binding(get: { selectedState }, set: { selectedState = $0 }) let truncatesBinding = Binding(get: { truncatesState }, set: { truncatesState = $0 }) let deletesBinding = Binding(get: { deletesState }, set: { deletesState = $0 }) let optionsBinding = Binding(get: { optionsState }, set: { optionsState = $0 }) let vm = SidebarViewModel( - selectedTables: selectedBinding, pendingTruncates: truncatesBinding, pendingDeletes: deletesBinding, tableOperationOptions: optionsBinding, @@ -43,7 +34,7 @@ private func makeSUT( connectionId: UUID() ) - return (vm, tablesBinding, selectedBinding, truncatesBinding, deletesBinding, optionsBinding) + return (vm, truncatesBinding, deletesBinding, optionsBinding) } @MainActor @@ -61,74 +52,75 @@ struct SidebarViewModelTests { // MARK: - Batch Toggle Truncate - @Test("batchToggleTruncate shows dialog for new tables") + @Test("batchToggleTruncate asks the window for new tables") @MainActor func batchToggleTruncateShowsDialog() { let table = makeRef("users") - let (vm, _, _, _, _, _) = makeSUT(selectedTables: [table]) + let (vm, _, _, _) = makeSUT() + let window = WindowSidebarState() - vm.batchToggleTruncate() + vm.batchToggleTruncate(refs: [table], from: window) - #expect(vm.showOperationDialog) - #expect(vm.pendingOperationType == .truncate) - #expect(vm.pendingOperationTables == [table]) + #expect(window.pendingTableOperation?.operation == .truncate) + #expect(window.pendingTableOperation?.tables == [table]) } - @Test("batchToggleTruncate cancels when all already pending") + @Test("batchToggleTruncate unstages when all already pending") @MainActor func batchToggleTruncateCancels() { let table = makeRef("users") - let (vm, _, _, truncatesBinding, _, optionsBinding) = makeSUT( - selectedTables: [table], + let (vm, truncatesBinding, _, optionsBinding) = makeSUT( pendingTruncates: [table], tableOperationOptions: [table: TableOperationOptions()] ) + let window = WindowSidebarState() - vm.batchToggleTruncate() + vm.batchToggleTruncate(refs: [table], from: window) - #expect(!vm.showOperationDialog) + #expect(window.pendingTableOperation == nil) #expect(!truncatesBinding.wrappedValue.contains(table)) #expect(optionsBinding.wrappedValue[table] == nil) } - @Test("batchToggleTruncate does nothing when no selection") + @Test("batchToggleTruncate does nothing for no tables") @MainActor func batchToggleTruncateNoSelection() { - let (vm, _, _, _, _, _) = makeSUT() + let (vm, _, _, _) = makeSUT() + let window = WindowSidebarState() - vm.batchToggleTruncate() + vm.batchToggleTruncate(refs: [], from: window) - #expect(!vm.showOperationDialog) + #expect(window.pendingTableOperation == nil) } // MARK: - Batch Toggle Delete - @Test("batchToggleDelete shows dialog for new tables") + @Test("batchToggleDelete asks the window for new tables") @MainActor func batchToggleDeleteShowsDialog() { let table = makeRef("orders") - let (vm, _, _, _, _, _) = makeSUT(selectedTables: [table]) + let (vm, _, _, _) = makeSUT() + let window = WindowSidebarState() - vm.batchToggleDelete() + vm.batchToggleDelete(refs: [table], from: window) - #expect(vm.showOperationDialog) - #expect(vm.pendingOperationType == .drop) - #expect(vm.pendingOperationTables == [table]) + #expect(window.pendingTableOperation?.operation == .drop) + #expect(window.pendingTableOperation?.tables == [table]) } - @Test("batchToggleDelete cancels when all already pending") + @Test("batchToggleDelete unstages when all already pending") @MainActor func batchToggleDeleteCancels() { let table = makeRef("orders") - let (vm, _, _, _, deletesBinding, optionsBinding) = makeSUT( - selectedTables: [table], + let (vm, _, deletesBinding, optionsBinding) = makeSUT( pendingDeletes: [table], tableOperationOptions: [table: TableOperationOptions()] ) + let window = WindowSidebarState() - vm.batchToggleDelete() + vm.batchToggleDelete(refs: [table], from: window) - #expect(!vm.showOperationDialog) + #expect(window.pendingTableOperation == nil) #expect(!deletesBinding.wrappedValue.contains(table)) #expect(optionsBinding.wrappedValue[table] == nil) } @@ -139,16 +131,10 @@ struct SidebarViewModelTests { @MainActor func confirmTruncateMovesFromDeletes() { let table = makeRef("users") - let (vm, _, _, truncatesBinding, deletesBinding, optionsBinding) = makeSUT( - selectedTables: [table], - pendingDeletes: [table] - ) - - vm.pendingOperationType = .truncate - vm.pendingOperationTables = [table] + let (vm, truncatesBinding, deletesBinding, optionsBinding) = makeSUT(pendingDeletes: [table]) let options = TableOperationOptions(ignoreForeignKeys: true) - vm.confirmOperation(options: options) + vm.confirmOperation(PendingTableOperation(operation: .truncate, tables: [table]), options: options) #expect(truncatesBinding.wrappedValue.contains(table)) #expect(!deletesBinding.wrappedValue.contains(table)) @@ -159,16 +145,10 @@ struct SidebarViewModelTests { @MainActor func confirmDropMovesFromTruncates() { let table = makeRef("users") - let (vm, _, _, truncatesBinding, deletesBinding, optionsBinding) = makeSUT( - selectedTables: [table], - pendingTruncates: [table] - ) - - vm.pendingOperationType = .drop - vm.pendingOperationTables = [table] + let (vm, truncatesBinding, deletesBinding, optionsBinding) = makeSUT(pendingTruncates: [table]) let options = TableOperationOptions(cascade: true) - vm.confirmOperation(options: options) + vm.confirmOperation(PendingTableOperation(operation: .drop, tables: [table]), options: options) #expect(!truncatesBinding.wrappedValue.contains(table)) #expect(deletesBinding.wrappedValue.contains(table)) @@ -180,58 +160,34 @@ struct SidebarViewModelTests { func confirmOperationStoresOptions() { let t1 = makeRef("t1") let t2 = makeRef("t2") - let (vm, _, _, _, _, optionsBinding) = makeSUT(selectedTables: [t1, t2]) - - vm.pendingOperationType = .truncate - vm.pendingOperationTables = [t1, t2] + let (vm, _, _, optionsBinding) = makeSUT() let options = TableOperationOptions(ignoreForeignKeys: true, cascade: true) - vm.confirmOperation(options: options) + vm.confirmOperation(PendingTableOperation(operation: .truncate, tables: [t1, t2]), options: options) #expect(optionsBinding.wrappedValue[t1] == options) #expect(optionsBinding.wrappedValue[t2] == options) } - - @Test("confirmOperation resets dialog state after confirm") - @MainActor - func confirmOperationResetsDialogState() { - let table = makeRef("users") - let (vm, _, _, _, _, _) = makeSUT(selectedTables: [table]) - - vm.pendingOperationType = .truncate - vm.pendingOperationTables = [table] - vm.showOperationDialog = true - - vm.confirmOperation(options: TableOperationOptions()) - - #expect(vm.pendingOperationType == nil) - #expect(vm.pendingOperationTables.isEmpty) - } - } extension GlobalStateSuites { @Suite(.recordingClipboard) @MainActor struct SidebarViewModelCopyTests { - @Test("copySelectedTableNames copies sorted comma-separated names") + @Test("copyTableNames copies sorted comma-separated names") func copyTableNames() throws { let clipboard = try #require(RecordingClipboard.current) - let t1 = makeRef("zebra") - let t2 = makeRef("alpha") - let (vm, _, _, _, _, _) = makeSUT(selectedTables: [t1, t2]) - vm.copySelectedTableNames() + SidebarViewModel.copyTableNames(of: [makeRef("zebra"), makeRef("alpha")]) #expect(clipboard.text == "alpha,zebra") } - @Test("copySelectedTableNames does nothing when no selection") + @Test("copyTableNames does nothing for no tables") func copyTableNamesNoSelection() throws { let clipboard = try #require(RecordingClipboard.current) - let (vm, _, _, _, _, _) = makeSUT() - vm.copySelectedTableNames() + SidebarViewModel.copyTableNames(of: []) #expect(clipboard.text == nil) } @@ -247,16 +203,13 @@ private func makeViewModel( defaults: UserDefaults, clock: any Clock = ContinuousClock() ) -> SidebarViewModel { - var selectedState: Set = [] var truncates: Set = [] var deletes: Set = [] var options: [DatabaseTreeTableRef: TableOperationOptions] = [:] - let selectedBinding = Binding(get: { selectedState }, set: { selectedState = $0 }) let truncatesBinding = Binding(get: { truncates }, set: { truncates = $0 }) let deletesBinding = Binding(get: { deletes }, set: { deletes = $0 }) let optionsBinding = Binding(get: { options }, set: { options = $0 }) return SidebarViewModel( - selectedTables: selectedBinding, pendingTruncates: truncatesBinding, pendingDeletes: deletesBinding, tableOperationOptions: optionsBinding, diff --git a/apple/TableProTests/Views/Editor/SQLEditorTabHistoryTests.swift b/apple/TableProTests/Views/Editor/SQLEditorTabHistoryTests.swift new file mode 100644 index 0000000000..35c6ca944a --- /dev/null +++ b/apple/TableProTests/Views/Editor/SQLEditorTabHistoryTests.swift @@ -0,0 +1,138 @@ +// One SQL editor serves every query tab of a window. Handing it another tab's text, or text a command wrote to the +// tab (Clear Query, a history entry, an AI suggestion), went through `setText`, which cleared the undo history. + +import AppKit +import SwiftUI +import TableProEditorKit +import TableProTestSupport +import TableProTextEngine +import Testing + +@testable import TablePro + +@MainActor +struct SQLEditorTabHistoryTests { + private final class Tabs { + var texts: [UUID: String] = [:] + + func binding(_ id: UUID) -> Binding { + Binding(get: { self.texts[id] ?? "" }, set: { self.texts[id] = $0 }) + } + } + + private func input(_ tabs: Tabs, tab id: UUID, histories: EditorUndoHistories) -> SQLEditorInput { + SQLEditorInput( + text: tabs.binding(id), + cursorPositions: .constant([]), + databaseType: .sqlite, + tabID: id, + undoHistories: histories + ) + } + + // The tab's next render after the edit wrote its text, as the query tab runs it. + private func type(_ string: String, at location: Int, in editor: SQLEditorController, input: SQLEditorInput) { + editor.textViewController.textView.replaceCharacters(in: NSRange(location: location, length: 0), with: string) + editor.apply(input) + } + + @Test("Undo after switching away and back takes back the tab's last edit") + func undoSurvivesATabSwitch() throws { + let tabs = Tabs() + let histories = EditorUndoHistories() + let first = UUID() + let second = UUID() + tabs.texts[first] = "SELECT 1" + tabs.texts[second] = "SELECT 2" + let editor = SQLEditorController(input: input(tabs, tab: first, histories: histories)) + defer { editor.teardown() } + let textView = try #require(editor.textViewController.textView) + type("0", at: 8, in: editor, input: input(tabs, tab: first, histories: histories)) + try #require(tabs.texts[first] == "SELECT 10") + + editor.apply(input(tabs, tab: second, histories: histories)) + #expect(textView.string == "SELECT 2") + #expect(textView.undoManager?.canUndo == false) + + editor.apply(input(tabs, tab: first, histories: histories)) + #expect(textView.string == "SELECT 10") + textView.undoManager?.undo() + #expect(textView.string == "SELECT 1") + #expect(tabs.texts[first] == "SELECT 1") + } + + @Test("Text a command writes to the tab, as Clear Query does, can be undone") + func clearQueryCanBeUndone() throws { + let tabs = Tabs() + let histories = EditorUndoHistories() + let tab = UUID() + tabs.texts[tab] = "SELECT 1" + let editor = SQLEditorController(input: input(tabs, tab: tab, histories: histories)) + defer { editor.teardown() } + let textView = try #require(editor.textViewController.textView) + + tabs.texts[tab] = "" + editor.apply(input(tabs, tab: tab, histories: histories)) + #expect(textView.string == "") + + textView.undoManager?.undo() + #expect(textView.string == "SELECT 1") + #expect(tabs.texts[tab] == "SELECT 1") + } + + @Test("A tab whose text changed while it was away comes back with no history") + func changedTabTextDropsItsHistory() throws { + let tabs = Tabs() + let histories = EditorUndoHistories() + let first = UUID() + let second = UUID() + tabs.texts[first] = "SELECT 1" + tabs.texts[second] = "SELECT 2" + let editor = SQLEditorController(input: input(tabs, tab: first, histories: histories)) + defer { editor.teardown() } + let textView = try #require(editor.textViewController.textView) + type("0", at: 8, in: editor, input: input(tabs, tab: first, histories: histories)) + + editor.apply(input(tabs, tab: second, histories: histories)) + tabs.texts[first] = "SELECT 3" + editor.apply(input(tabs, tab: first, histories: histories)) + + #expect(textView.string == "SELECT 3") + #expect(textView.undoManager?.canUndo == false) + } + + @Test("A new editor for the tab, as after a table tab was shown, gets the tab's history back") + func historyOutlivesTheEditor() throws { + let tabs = Tabs() + let histories = EditorUndoHistories() + let tab = UUID() + tabs.texts[tab] = "SELECT 1" + let editor = SQLEditorController(input: input(tabs, tab: tab, histories: histories)) + type("0", at: 8, in: editor, input: input(tabs, tab: tab, histories: histories)) + editor.teardown() + + let next = SQLEditorController(input: input(tabs, tab: tab, histories: histories)) + defer { next.teardown() } + let textView = try #require(next.textViewController.textView) + #expect(textView.string == "SELECT 10") + textView.undoManager?.undo() + + #expect(textView.string == "SELECT 1") + } + + @Test("Vim marks restored before Vim is installed wait for it, and a replaced document drops them") + func pendingVimMarksFollowTheDocument() { + let coordinator = SQLEditorCoordinator(diagnosticsClock: ManualClock()) + coordinator.databaseType = .mysql + let controller = EditorControllerFixture.make(string: "SELECT 1", coordinators: [coordinator]) + defer { coordinator.destroy() } + var marks = VimDocumentMarks() + marks.marks["a"] = 3 + + coordinator.restoreVimDocumentMarks(marks) + #expect(coordinator.vimDocumentMarks?.marks["a"] == 3) + + controller.setText("SELECT 2") + #expect(coordinator.vimDocumentMarks == nil) + } +} diff --git a/apple/TableProTests/Views/Editor/VimDocumentMarksTests.swift b/apple/TableProTests/Views/Editor/VimDocumentMarksTests.swift new file mode 100644 index 0000000000..5056ec1b91 --- /dev/null +++ b/apple/TableProTests/Views/Editor/VimDocumentMarksTests.swift @@ -0,0 +1,55 @@ +// Marks are offsets into one document. The SQL editor hands one engine every query tab's text, so a tab's marks are +// saved and restored with its text and dropped when another document comes in. + +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct VimDocumentMarksTests { + private let buffer: VimTextBufferMock + private let engine: VimEngine + + init() { + buffer = VimTextBufferMock(text: "hello world\nsecond line\nthird line\n") + engine = VimEngine(buffer: buffer) + } + + private func keys(_ chars: String) { + for char in chars { _ = engine.process(char, shift: false) } + } + + private var pos: Int { buffer.selectedRange().location } + + @Test("Marks saved with a document come back with it") + func marksRoundTrip() { + buffer.setSelectedRange(NSRange(location: 7, length: 0)) + keys("ma") + let saved = engine.documentMarks + + engine.documentDidReplace() + #expect(engine.documentMarks.isEmpty) + buffer.setSelectedRange(NSRange(location: 20, length: 0)) + keys("`a") + #expect(pos == 20) + + engine.restoreDocumentMarks(saved) + keys("`a") + #expect(pos == 7) + } + + @Test("A replaced document drops the last visual range and the insert point") + func replacedDocumentDropsTheOtherOffsets() { + engine.lastVisualStart = 0 + engine.lastVisualEnd = 4 + engine.lastVisualLinewise = true + engine.lastInsertOffset = 12 + + engine.documentDidReplace() + + #expect(engine.lastVisualStart == nil) + #expect(engine.lastVisualEnd == nil) + #expect(!engine.lastVisualLinewise) + #expect(engine.lastInsertOffset == nil) + } +} diff --git a/apple/TableProTests/Views/Main/QueryContainerChangeTests.swift b/apple/TableProTests/Views/Main/QueryContainerChangeTests.swift new file mode 100644 index 0000000000..f107a28891 --- /dev/null +++ b/apple/TableProTests/Views/Main/QueryContainerChangeTests.swift @@ -0,0 +1,109 @@ +// +// QueryContainerChangeTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +@MainActor +struct QueryContainerChangeTests { + private func queryTab(database: String, schema: String? = nil) -> QueryTab { + var tab = QueryTab(title: "Query 1", query: "SELECT * FROM users", tabType: .query) + tab.tableContext.databaseName = database + tab.tableContext.schemaName = schema + return tab + } + + // Rows read from `users`, the way a finished run leaves them: editable, keyed, with more to load. + private func showRows(on tab: inout QueryTab, database: String, schema: String?) { + let rows = ResultSet( + label: "users", + tableRows: TableRows.from(queryRows: [[.text("42")]], columns: ["id"], columnTypes: [.text(rawType: "INTEGER")]) + ) + rows.origin = ResultOrigin( + tableName: "users", + schemaName: schema, + databaseName: database, + primaryKeyColumns: ["id"], + isEditable: true, + keysResolved: true + ) + tab.display.resultSets = [rows] + tab.tableContext.tableName = "users" + tab.tableContext.isEditable = true + tab.pagination.hasMoreRows = true + tab.pagination.baseQueryForMore = "SELECT * FROM users" + } + + @Test("The picker does not move a tab while its query runs") + func runningTabKeepsItsDatabase() { + let fixture = CoordinatorFixture() + let tab = fixture.addTab(queryTab(database: "staging")) + let running = fixture.coordinator.tabExecution.claim(tab.id) + + fixture.coordinator.changeQueryContainer(of: tab.id, to: "production", target: .database) + + #expect(fixture.coordinator.tabExecution.isCurrent(running)) + #expect(fixture.tabManager.tabs.first { $0.id == tab.id }?.tableContext.databaseName == "staging") + } + + @Test("Rows still on screen from the old database cannot be edited or paged from the new one") + func movedTabLeavesTheOldRowsReadOnly() { + let fixture = CoordinatorFixture() + fixture.coordinator.executionGate = AlwaysDenyGate.cancelling + var tab = queryTab(database: "staging") + showRows(on: &tab, database: "staging", schema: nil) + fixture.addTab(tab) + #expect(fixture.coordinator.activeResultEditRefusal == nil) + + fixture.coordinator.changeQueryContainer(of: tab.id, to: "production", target: .database) + + let moved = fixture.tabManager.tabs.first { $0.id == tab.id } + #expect(moved?.tableContext.databaseName == "production") + #expect(moved?.pagination.hasMoreRows == false) + #expect(moved?.pagination.baseQueryForMore == nil) + #expect(fixture.coordinator.activeResultEditRefusal == .databaseMoved) + } + + @Test("Rows left from the old schema after the schema picker moved the tab cannot be edited") + func schemaPickerLeavesTheOldRowsReadOnly() { + let fixture = CoordinatorFixture() + fixture.coordinator.executionGate = AlwaysDenyGate.cancelling + var tab = queryTab(database: "app", schema: "staging") + showRows(on: &tab, database: "app", schema: "staging") + fixture.addTab(tab) + #expect(fixture.coordinator.activeResultEditRefusal == nil) + + fixture.coordinator.changeQueryContainer(of: tab.id, to: "production", target: .schema) + + #expect(fixture.tabManager.tabs.first { $0.id == tab.id }?.tableContext.schemaName == "production") + #expect(fixture.coordinator.activeResultEditRefusal == .schemaMoved) + } + + @Test("Showing a pinned result read in another schema leaves the tab where the picker put it, and offers no Fetch All") + func resultSwitchKeepsTheSchemaBinding() throws { + let fixture = CoordinatorFixture() + var tab = queryTab(database: "app", schema: "staging") + showRows(on: &tab, database: "app", schema: "staging") + let stagingResult = try #require(tab.display.resultSets.first) + stagingResult.isTruncated = true + stagingResult.baseQuery = "SELECT * FROM users" + let productionResult = ResultSet(label: "Result 2") + productionResult.origin = ResultOrigin(tableName: nil, schemaName: "production", databaseName: "app") + tab.display.resultSets.append(productionResult) + tab.display.activeResultSetId = productionResult.id + tab.tableContext.schemaName = "production" + fixture.addTab(tab) + + fixture.coordinator.applyResultSetSwitch(to: stagingResult.id, in: tab.id) + + let switched = fixture.tabManager.tabs.first { $0.id == tab.id } + #expect(switched?.tableContext.schemaName == "production") + #expect(switched?.pagination.hasMoreRows == false) + #expect(switched?.pagination.baseQueryForMore == nil) + #expect(fixture.coordinator.activeResultEditRefusal == .schemaMoved) + } +} diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeAttachedSchemaTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeAttachedSchemaTests.swift index 08da1f5199..b605b1f234 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeAttachedSchemaTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeAttachedSchemaTests.swift @@ -76,7 +76,6 @@ struct DatabaseTreeAttachedSchemaTests { let sidebarState = SharedSidebarState.forConnection(connection.id) sidebarState.sidebarLayout = .flat let viewModel = SidebarViewModel( - selectedTables: .constant([]), pendingTruncates: .constant([]), pendingDeletes: .constant([]), tableOperationOptions: .constant([:]), diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeFilterMemoTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeFilterMemoTests.swift index b06d1d8826..ce7331b5b3 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeFilterMemoTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeFilterMemoTests.swift @@ -172,7 +172,6 @@ struct DatabaseTreeFilterMemoTests { let sidebarState = SharedSidebarState.forConnection(connection.id) sidebarState.sidebarLayout = .flat let viewModel = SidebarViewModel( - selectedTables: .constant([]), pendingTruncates: .constant([]), pendingDeletes: .constant([]), tableOperationOptions: .constant([:]), diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeFlatRootTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeFlatRootTests.swift index bc8187afbd..a7b949761c 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeFlatRootTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeFlatRootTests.swift @@ -45,7 +45,6 @@ struct DatabaseTreeFlatRootTests { let sidebarState = SharedSidebarState.forConnection(connection.id) sidebarState.sidebarLayout = .flat let viewModel = SidebarViewModel( - selectedTables: .constant([]), pendingTruncates: .constant([]), pendingDeletes: .constant([]), tableOperationOptions: .constant([:]), diff --git a/apple/TableProTests/Views/Sidebar/DatabaseTreeReconcileTests.swift b/apple/TableProTests/Views/Sidebar/DatabaseTreeReconcileTests.swift index 7446b88e1c..d28f57b3b2 100644 --- a/apple/TableProTests/Views/Sidebar/DatabaseTreeReconcileTests.swift +++ b/apple/TableProTests/Views/Sidebar/DatabaseTreeReconcileTests.swift @@ -53,7 +53,6 @@ struct DatabaseTreeReconcileTests { let sidebarState = SharedSidebarState.forConnection(connection.id) sidebarState.sidebarLayout = .flat let viewModel = SidebarViewModel( - selectedTables: .constant([]), pendingTruncates: .constant([]), pendingDeletes: .constant([]), tableOperationOptions: .constant([:]), diff --git a/apple/changelog.d/4225.fixed.1.md b/apple/changelog.d/4225.fixed.1.md new file mode 100644 index 0000000000..45dca2cf50 --- /dev/null +++ b/apple/changelog.d/4225.fixed.1.md @@ -0,0 +1 @@ +Stop on Run All dropped the results and history of the statements that had already run. diff --git a/apple/changelog.d/4225.fixed.2.md b/apple/changelog.d/4225.fixed.2.md new file mode 100644 index 0000000000..b2d9f77b0e --- /dev/null +++ b/apple/changelog.d/4225.fixed.2.md @@ -0,0 +1 @@ +A connection first opened on a table or query from a link never saved its tabs, so they were lost at quit. diff --git a/apple/changelog.d/4225.fixed.3.md b/apple/changelog.d/4225.fixed.3.md new file mode 100644 index 0000000000..dc305be738 --- /dev/null +++ b/apple/changelog.d/4225.fixed.3.md @@ -0,0 +1 @@ +Truncate and Copy in one window acted on the table selected in another window of the same connection. diff --git a/apple/changelog.d/4225.fixed.4.md b/apple/changelog.d/4225.fixed.4.md new file mode 100644 index 0000000000..844e7bbc9d --- /dev/null +++ b/apple/changelog.d/4225.fixed.4.md @@ -0,0 +1 @@ +Switching tabs, Clear Query, loading from history or applying an AI rewrite wiped the SQL editor's undo history. diff --git a/apple/changelog.d/4225.fixed.5.md b/apple/changelog.d/4225.fixed.5.md new file mode 100644 index 0000000000..c56a3c1fc9 --- /dev/null +++ b/apple/changelog.d/4225.fixed.5.md @@ -0,0 +1 @@ +Showing an earlier result read in another schema moved the query tab back to that schema. diff --git a/apple/changelog.d/4225.fixed.md b/apple/changelog.d/4225.fixed.md new file mode 100644 index 0000000000..ce9fe0a25d --- /dev/null +++ b/apple/changelog.d/4225.fixed.md @@ -0,0 +1 @@ +Changing a query tab's database while its query ran put the old database's rows under the new one, and Save wrote there.