From 1b071ab747af60dd19dac418f51751f19440f04d Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 13:45:54 +0700 Subject: [PATCH 1/3] fix(macos): fix the verified defects from the app audit --- .../TextViewController+UnfilteredEdits.swift | 10 + .../Controller/TextViewController.swift | 2 +- .../ReplaceCharactersUnfilteredTests.swift | 40 +++ .../AI/Chat/ChatToolArgumentDecoder.swift | 18 +- .../Core/AI/Chat/ChatToolCallRepair.swift | 28 +- .../Core/AI/Chat/ChatToolRegistry.swift | 6 + .../ConfirmDestructiveOperationChatTool.swift | 19 +- .../Core/Compare/CompareObjectResult.swift | 10 +- .../Core/Compare/CompareRunner+Data.swift | 10 +- .../TablePro/Core/Compare/CompareRunner.swift | 55 +++- .../Core/Compare/CompareSyncExecutor.swift | 57 +++- .../Compare/CompareSyncSession+Editing.swift | 32 ++- .../Core/Compare/DataCompareOptions.swift | 14 + .../Core/Compare/ResultSetComparison.swift | 83 ++++-- .../Core/Compare/SourceObjectDiffEngine.swift | 62 +++-- .../Compare/SourceObjectSyncBuilder.swift | 3 + .../Compare/StructureCompareOptions.swift | 17 +- .../Core/Compare/StructureDiffEngine.swift | 52 +++- .../Core/Compare/TableStructureSnapshot.swift | 28 ++ .../Coordinators/RowEditingCoordinator.swift | 70 ++++- .../Access/DatabaseAccessBridge.swift | 55 +++- .../Database/DatabaseManager+Sessions.swift | 59 +++-- .../MCP/Protocol/Tools/ExplainQueryTool.swift | 4 +- .../Core/SSH/LibSSH2TunnelFactory.swift | 82 +++--- .../Export/ConnectionBundleExporter.swift | 13 +- .../Export/TableTransferService.swift | 1 + .../Storage/CredentialProfileStorage.swift | 11 +- .../Core/Storage/SSHProfileStorage.swift | 11 +- .../SyncCoordinator+RemoteDeletions.swift | 16 +- .../TablePro/Core/Sync/SyncRecordMapper.swift | 24 +- .../Core/Sync/SyncSettingsDocument.swift | 45 ++++ .../Core/Vim/VimEngine+Controls.swift | 2 +- .../Core/Vim/VimEngine+InsertReplace.swift | 10 +- .../TablePro/Core/Vim/VimEngine+Macros.swift | 2 + .../Core/Vim/VimEngine+NormalMode.swift | 28 +- .../Core/Vim/VimEngine+Operators.swift | 34 +-- .../Core/Vim/VimEngine+RegistersMarks.swift | 1 + .../TablePro/Core/Vim/VimEngine+Repeat.swift | 155 ++++++++--- .../Core/Vim/VimEngine+VisualMode.swift | 12 +- apple/TablePro/Core/Vim/VimEngine.swift | 42 ++- .../Core/Vim/VimTextBufferAdapter.swift | 15 +- .../Models/UI/MultiRowEditState.swift | 61 +++-- .../TablePro/Resources/Localizable.xcstrings | 27 ++ .../AIChatViewModel+Streaming.swift | 15 +- .../TablePro/ViewModels/AIChatViewModel.swift | 11 +- .../ERDiagramViewModel+Editing.swift | 4 +- .../ViewModels/ERDiagramViewModel.swift | 36 +-- .../WelcomeViewModel+TeamLibrary.swift | 6 +- .../DataGridModel+ColumnGeometry.swift | 5 + .../Views/Editor/EditorUndoHistories.swift | 8 +- .../Editor/QueryParameterPanelView.swift | 19 +- .../Views/Editor/SQLEditorController.swift | 50 +++- .../Views/Editor/SQLEditorCoordinator.swift | 2 +- .../Views/Export/TableTransferSheet.swift | 148 ++++++++++- .../Main/Child/MainEditorContentView.swift | 23 +- ...MainContentCommandActions+FileSaving.swift | 4 - .../MainContentCoordinator+Navigation.swift | 22 +- .../MainContentView+EventHandlers.swift | 13 +- .../MainContentCommandActions+Closing.swift | 39 +-- .../Main/MainContentCommandActions.swift | 52 ++-- .../InspectorPopOutRegistry.swift | 28 +- .../Views/RowInspector/RowInspectorView.swift | 19 +- .../Sidebar/Menu/FavoritesMenuSpec.swift | 26 +- .../Structure/StructureSectionAdapter.swift | 11 + ...onfirmDestructiveOperationScopeTests.swift | 155 +++++++++++ .../Core/AI/ExecuteToolUsesOrderTests.swift | 112 ++++++++ .../CompareCrossSchemaFollowUpTests.swift | 168 ++++++++++++ .../CompareCrossSchemaScriptingTests.swift | 244 ++++++++++++++++++ .../Compare/CompareSchemaPairingTests.swift | 82 ++++++ ...areSyncExecutorTransactionOwnerTests.swift | 215 +++++++++++++++ .../CrossEngineTimestampCompareTests.swift | 65 +++++ .../InspectorDetachedStagingTests.swift | 194 ++++++++++++++ ...DatabaseAccessBridgeExplainHoldTests.swift | 98 +++++++ .../DisconnectWhileConnectingTests.swift | 139 ++++++++++ .../ResolveScopeReachabilityTests.swift | 96 +++++++ .../TableTransferDestinationSchemaTests.swift | 118 +++++++++ .../Auth/BuildJumpAuthenticatorTests.swift | 98 +++++++ .../Services/TeamCatalogPublisherTests.swift | 22 ++ .../Storage/ProfileStorageSafetyTests.swift | 4 +- .../Sync/SyncProfileDeletionTrustTests.swift | 97 +++++++ .../Sync/SyncSettingsUnreadOptionsTests.swift | 131 ++++++++++ .../Core/Vim/VimEngineDotRepeatTests.swift | 132 ++++++++++ ...VimTextBufferAdapterCommandEditTests.swift | 49 ++++ .../MultiRowEditStateClearedFieldTests.swift | 13 - .../MultiRowEditStateSetValueTests.swift | 16 -- ...MultiRowEditStateDetachedCommitTests.swift | 141 +++++++--- .../AIChatTranscriptTrimTests.swift | 110 ++++++++ .../ERDiagramSchemaBindingTests.swift | 62 +++++ .../ViewModels/ERDiagramSchemaKeyTests.swift | 7 - .../DataGridHiddenColumnMoveTests.swift | 66 +++++ .../QueryParameterPanelClearAllTests.swift | 37 +++ .../Editor/SQLEditorTabSelectionTests.swift | 110 ++++++++ .../InPlaceNavigationKeepsWorkTests.swift | 84 ++++++ .../Main/QueryParameterBindingTests.swift | 31 +++ .../Main/SaveFileBesideResultEditsTests.swift | 204 +++++++++++++++ .../Sidebar/FavoritesMenuSpecTests.swift | 9 +- ...tructureSectionColumnVisibilityTests.swift | 87 +++++++ 97 files changed, 4528 insertions(+), 535 deletions(-) create mode 100644 apple/Packages/TableProEditor/Tests/TableProEditorKitTests/Controller/ReplaceCharactersUnfilteredTests.swift create mode 100644 apple/TablePro/Core/Sync/SyncSettingsDocument.swift create mode 100644 apple/TableProTests/Core/AI/Chat/ConfirmDestructiveOperationScopeTests.swift create mode 100644 apple/TableProTests/Core/AI/ExecuteToolUsesOrderTests.swift create mode 100644 apple/TableProTests/Core/Compare/CompareCrossSchemaFollowUpTests.swift create mode 100644 apple/TableProTests/Core/Compare/CompareCrossSchemaScriptingTests.swift create mode 100644 apple/TableProTests/Core/Compare/CompareSchemaPairingTests.swift create mode 100644 apple/TableProTests/Core/Compare/CompareSyncExecutorTransactionOwnerTests.swift create mode 100644 apple/TableProTests/Core/Compare/CrossEngineTimestampCompareTests.swift create mode 100644 apple/TableProTests/Core/Coordinators/InspectorDetachedStagingTests.swift create mode 100644 apple/TableProTests/Core/Database/DatabaseAccessBridgeExplainHoldTests.swift create mode 100644 apple/TableProTests/Core/Database/DisconnectWhileConnectingTests.swift create mode 100644 apple/TableProTests/Core/Database/ResolveScopeReachabilityTests.swift create mode 100644 apple/TableProTests/Core/Export/TableTransferDestinationSchemaTests.swift create mode 100644 apple/TableProTests/Core/SSH/Auth/BuildJumpAuthenticatorTests.swift create mode 100644 apple/TableProTests/Core/Sync/SyncProfileDeletionTrustTests.swift create mode 100644 apple/TableProTests/Core/Sync/SyncSettingsUnreadOptionsTests.swift create mode 100644 apple/TableProTests/Core/Vim/VimEngineDotRepeatTests.swift create mode 100644 apple/TableProTests/Core/Vim/VimTextBufferAdapterCommandEditTests.swift create mode 100644 apple/TableProTests/ViewModels/AIChatTranscriptTrimTests.swift create mode 100644 apple/TableProTests/ViewModels/ERDiagramSchemaBindingTests.swift create mode 100644 apple/TableProTests/Views/DataGrid/DataGridHiddenColumnMoveTests.swift create mode 100644 apple/TableProTests/Views/Editor/QueryParameterPanelClearAllTests.swift create mode 100644 apple/TableProTests/Views/Editor/SQLEditorTabSelectionTests.swift create mode 100644 apple/TableProTests/Views/Main/InPlaceNavigationKeepsWorkTests.swift create mode 100644 apple/TableProTests/Views/Main/QueryParameterBindingTests.swift create mode 100644 apple/TableProTests/Views/Main/SaveFileBesideResultEditsTests.swift create mode 100644 apple/TableProTests/Views/Structure/StructureSectionColumnVisibilityTests.swift diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+UnfilteredEdits.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+UnfilteredEdits.swift index 0b13653b05..083d4e4c69 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+UnfilteredEdits.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController+UnfilteredEdits.swift @@ -27,6 +27,16 @@ public extension TextViewController { textView.replaceCharacters(in: span, with: rebuilt, skipUpdateSelection: true) } + // A key command's edit, as Vim's are: a plain replace that leaves undo grouping and the selection to the text view, + // with no typing filters and no suggestion triggers. + func replaceCharactersUnfiltered(in range: NSRange, with string: String) { + guard let textView else { return } + let wasUnfiltered = isApplyingUnfilteredEdits + isApplyingUnfilteredEdits = true + defer { isApplyingUnfilteredEdits = wasUnfiltered } + textView.replaceCharacters(in: range, with: string) + } + // A command's replacement, unlike `setText`, keeps the undo history: one undo group, no typing filters, no // suggestion triggers. The binding gets the text before this returns, so a run right after reads it. @discardableResult diff --git a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController.swift b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController.swift index 9944635022..2e20435e8b 100644 --- a/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController.swift +++ b/apple/Packages/TableProEditor/Sources/TableProEditorKit/Controller/TextViewController.swift @@ -209,7 +209,7 @@ public class TextViewController: NSViewController { /// The gutter's width is reserved on the clip view, so the clip view's own origin moves whenever the gutter shows, /// hides or gains a digit. This is the position ``SourceEditorState`` records and restores, so a saved position /// means the same text regardless. - var scrollPosition: CGPoint { + public var scrollPosition: CGPoint { get { let origin = scrollView.contentView.bounds.origin return CGPoint(x: origin.x + scrollView.floatingSubviewInsets.left, y: origin.y) diff --git a/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/Controller/ReplaceCharactersUnfilteredTests.swift b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/Controller/ReplaceCharactersUnfilteredTests.swift new file mode 100644 index 0000000000..6b78472495 --- /dev/null +++ b/apple/Packages/TableProEditor/Tests/TableProEditorKitTests/Controller/ReplaceCharactersUnfilteredTests.swift @@ -0,0 +1,40 @@ +import AppKit +@testable import TableProEditorKit +import TableProTextEngine +import Testing + +@MainActor +struct ReplaceCharactersUnfilteredTests { + @Test("A key command's open bracket over a character replaces it and wraps nothing") + func openBracketReplacesTheCharacter() { + let controller = Mock.loadedTextViewController(string: "a x b") + controller.replaceCharactersUnfiltered(in: NSRange(location: 2, length: 1), with: "(") + #expect(controller.textView.string == "a ( b") + } + + @Test("A key command's delete of an open bracket leaves the closing one") + func deletingAnOpenBracketKeepsTheCloser() { + let controller = Mock.loadedTextViewController(string: "COUNT()") + controller.replaceCharactersUnfiltered(in: NSRange(location: 5, length: 1), with: "") + #expect(controller.textView.string == "COUNT)") + } + + @Test("Typing after a key command's edit still runs the typing filters") + func typingAfterwardIsFiltered() { + let controller = Mock.loadedTextViewController(string: "") + controller.replaceCharactersUnfiltered(in: NSRange(location: 0, length: 0), with: "\t") + #expect(controller.textView.string == "\t") + + controller.textView.replaceCharacters(in: NSRange(location: 1, length: 0), with: "\t") + #expect(controller.textView.string == "\t ") + } + + @Test("A key command's edit is undoable") + func editIsUndoable() { + let (window, controller) = Mock.focusedTextViewController(string: "a x b") + defer { window.orderOut(nil) } + controller.replaceCharactersUnfiltered(in: NSRange(location: 2, length: 1), with: "(") + controller.textView.undoManager?.undo() + #expect(controller.textView.string == "a x b") + } +} diff --git a/apple/TablePro/Core/AI/Chat/ChatToolArgumentDecoder.swift b/apple/TablePro/Core/AI/Chat/ChatToolArgumentDecoder.swift index ff6e3fa601..2135bb48e5 100644 --- a/apple/TablePro/Core/AI/Chat/ChatToolArgumentDecoder.swift +++ b/apple/TablePro/Core/AI/Chat/ChatToolArgumentDecoder.swift @@ -6,10 +6,19 @@ import Foundation import TableProMCP -/// Typed decoders for `JsonValue` input arguments coming from the AI. -/// Mirrors `MCPArgumentDecoder` for the MCP protocol but operates on the -/// chat-side `JsonValue` enum. enum ChatToolArgumentDecoder { + // Refused, not ignored: the approval card reads the input, so an ignored key can name a target the call never uses. + static func rejectUnknownKeys(_ args: JsonValue, declaredBy schema: JsonValue) throws { + guard case .object(let dict) = args else { return } + // Undeclared, and `ChatToolTarget` refuses any connection but the session's. + var allowed: Set = ["connection_id"] + if case .object(let root) = schema, case .object(let properties)? = root["properties"] { + allowed.formUnion(properties.keys) + } + let unknown = dict.keys.filter { !allowed.contains($0) }.sorted() + guard unknown.isEmpty else { throw ChatToolArgumentError.unknownKeys(unknown) } + } + static func requireString(_ args: JsonValue, key: String) throws -> String { guard case .object(let dict) = args, let value = dict[key], case .string(let str) = value else { throw ChatToolArgumentError.missingOrInvalid(key: key, expected: "string") @@ -60,11 +69,14 @@ enum ChatToolArgumentDecoder { enum ChatToolArgumentError: Error, LocalizedError { case missingOrInvalid(key: String, expected: String) + case unknownKeys([String]) var errorDescription: String? { switch self { case .missingOrInvalid(let key, let expected): return "Argument '\(key)' is missing or not a \(expected)" + case .unknownKeys(let keys): + return "Unknown argument(s): \(keys.joined(separator: ", ")). Pass only the arguments this tool declares." } } } diff --git a/apple/TablePro/Core/AI/Chat/ChatToolCallRepair.swift b/apple/TablePro/Core/AI/Chat/ChatToolCallRepair.swift index b499238ae4..c0f08a6845 100644 --- a/apple/TablePro/Core/AI/Chat/ChatToolCallRepair.swift +++ b/apple/TablePro/Core/AI/Chat/ChatToolCallRepair.swift @@ -5,8 +5,8 @@ import Foundation -// Providers reject a request in which a tool call has no result. A stopped round, or a transcript -// saved by a build that left one open, must still be sendable. +// Providers reject a request in which a tool call has no result, or a result has no call. A stopped round, a +// transcript saved by a build that left one open, or one cut short on disk must still be sendable. enum ChatToolCallRepair { static let interruptedContent = "This tool call was interrupted before it returned a result." static let stoppedBeforeRunContent = "The user stopped the response before this tool call ran." @@ -18,6 +18,9 @@ enum ChatToolCallRepair { for (index, original) in turns.enumerated() { var turn = original + if turn.role == .user { + turn.blocks = droppingOrphanResults(turn.blocks, after: repaired.last) + } if !owed.isEmpty { if turn.role == .user, !toolResultIds(in: turn).isEmpty { turn.blocks.insert(contentsOf: owed.map { .toolResult($0) }, at: 0) @@ -26,6 +29,8 @@ enum ChatToolCallRepair { } owed = [] } + // A turn that held only results for calls no longer in the transcript has nothing left to send. + if turn.blocks.isEmpty, !original.blocks.isEmpty { continue } repaired.append(turn) guard turn.role == .assistant else { continue } owed = unansweredResults(for: turn, next: index + 1 < turns.count ? turns[index + 1] : nil) @@ -89,6 +94,25 @@ enum ChatToolCallRepair { } } + // A result answers a call only in the turn right after it. + private static func droppingOrphanResults( + _ blocks: [ChatContentBlockWire], + after previous: ChatTurnWire? + ) -> [ChatContentBlockWire] { + let calls = previous?.role == .assistant ? toolUseIds(in: previous) : [] + return blocks.filter { block in + guard case .toolResult(let result) = block.kind else { return true } + return calls.contains(result.toolUseId) + } + } + + private static func toolUseIds(in turn: ChatTurnWire?) -> Set { + Set((turn?.blocks ?? []).compactMap { block -> String? in + guard case .toolUse(let call) = block.kind else { return nil } + return call.id + }) + } + private static func toolResultIds(in turn: ChatTurnWire) -> Set { Set(turn.blocks.compactMap { block -> String? in guard case .toolResult(let result) = block.kind else { return nil } diff --git a/apple/TablePro/Core/AI/Chat/ChatToolRegistry.swift b/apple/TablePro/Core/AI/Chat/ChatToolRegistry.swift index d5aba3e1ca..f92c9425b5 100644 --- a/apple/TablePro/Core/AI/Chat/ChatToolRegistry.swift +++ b/apple/TablePro/Core/AI/Chat/ChatToolRegistry.swift @@ -84,6 +84,12 @@ final class ChatToolRegistry { allTools(for: mode).map(\.spec) } + // An outside server's tool is `.readOnly` only so every mode offers it; it may write anything. + func onlyReads(toolName: String) -> Bool { + guard let tool = tools[toolName], !(tool is MCPRemoteToolAdapter) else { return false } + return tool.mode == .readOnly + } + func requiresApproval(toolName: String) -> Bool { guard let tool = tools[toolName] else { return true } return tool.mode.requiresApproval diff --git a/apple/TablePro/Core/AI/Chat/Tools/ConfirmDestructiveOperationChatTool.swift b/apple/TablePro/Core/AI/Chat/Tools/ConfirmDestructiveOperationChatTool.swift index 44c10fac30..dbbe701973 100644 --- a/apple/TablePro/Core/AI/Chat/Tools/ConfirmDestructiveOperationChatTool.swift +++ b/apple/TablePro/Core/AI/Chat/Tools/ConfirmDestructiveOperationChatTool.swift @@ -20,15 +20,26 @@ struct ConfirmDestructiveOperationChatTool: ChatTool { "query": ChatToolSchemaBuilder.string(description: "The destructive query to execute"), "confirmation_phrase": ChatToolSchemaBuilder.string( description: "Must be exactly: I understand this is irreversible" + ), + "database": ChatToolSchemaBuilder.string( + description: "Run against this database. Pass null to use current.", + optional: true + ), + "schema": ChatToolSchemaBuilder.string( + description: "Run against this schema. Pass null to use current.", + optional: true ) - ], - required: ["query", "confirmation_phrase"] + ] ) let mode: ChatToolMode = .agentOnly func execute(input: JsonValue, context: ChatToolContext) async throws -> ChatToolResult { + try ChatToolArgumentDecoder.rejectUnknownKeys(input, declaredBy: inputSchema) let query = try ChatToolArgumentDecoder.requireString(input, key: "query") let confirmationPhrase = try ChatToolArgumentDecoder.requireString(input, key: "confirmation_phrase") + // The approval card names these, so the statement runs where the card says. + let database = ChatToolArgumentDecoder.optionalString(input, key: "database") + let schema = ChatToolArgumentDecoder.optionalString(input, key: "schema") guard confirmationPhrase == Self.requiredPhrase else { return ChatToolResult( @@ -73,8 +84,8 @@ struct ConfirmDestructiveOperationChatTool: ChatTool { let maxRows = MCPLimitResolver.resolveMaxRows(requested: nil, settings: mcpSettings) let scope = try await context.bridge.resolveScope( connectionId: connectionId, - database: nil, - schema: nil + database: database, + schema: schema ) let planned = try await context.bridge.plannedScript(scope: scope, query: query, maxRows: maxRows) let operation = try await context.authPolicy.checkSafeModeDialog( diff --git a/apple/TablePro/Core/Compare/CompareObjectResult.swift b/apple/TablePro/Core/Compare/CompareObjectResult.swift index 8dec1068e1..b93ba08419 100644 --- a/apple/TablePro/Core/Compare/CompareObjectResult.swift +++ b/apple/TablePro/Core/Compare/CompareObjectResult.swift @@ -61,6 +61,8 @@ internal struct CompareObjectResult: Identifiable, Hashable, Sendable { internal let definitionMatches: Bool // What the source recorded for a routine or trigger, such as MySQL's sql_mode, set around its CREATE. internal let sourceCreationScope: PluginStatementScope? + // Why the row is compared but never scripted, such as a definition read from another schema than the target's. + internal let scriptRefusal: String? internal init( identity: CompareObjectIdentity, @@ -73,7 +75,8 @@ internal struct CompareObjectResult: Identifiable, Hashable, Sendable { sourceIndexes: [EditableIndexDefinition]? = nil, targetIndexes: [EditableIndexDefinition]? = nil, definitionMatches: Bool = false, - sourceCreationScope: PluginStatementScope? = nil + sourceCreationScope: PluginStatementScope? = nil, + scriptRefusal: String? = nil ) { self.identity = identity self.status = status @@ -86,6 +89,7 @@ internal struct CompareObjectResult: Identifiable, Hashable, Sendable { self.targetIndexes = targetIndexes self.definitionMatches = definitionMatches self.sourceCreationScope = sourceCreationScope + self.scriptRefusal = scriptRefusal } // PluginStatementScope is only Equatable; equal results share an identity. @@ -110,7 +114,7 @@ internal struct CompareObjectResult: Identifiable, Hashable, Sendable { internal var isComparable: Bool { comparisonError == nil } internal var suggestedAction: TableSyncAction { - guard comparisonError == nil else { return .skip } + guard comparisonError == nil, scriptRefusal == nil else { return .skip } switch status { case .onlyInSource: return .create case .onlyInTarget: return .drop @@ -120,7 +124,7 @@ internal struct CompareObjectResult: Identifiable, Hashable, Sendable { } internal var availableActions: [TableSyncAction] { - guard comparisonError == nil else { return [.skip] } + guard comparisonError == nil, scriptRefusal == nil else { return [.skip] } switch status { case .onlyInSource: return [.skip, .create] case .onlyInTarget: return [.skip, .drop] diff --git a/apple/TablePro/Core/Compare/CompareRunner+Data.swift b/apple/TablePro/Core/Compare/CompareRunner+Data.swift index 4227d26368..b28cc07b7c 100644 --- a/apple/TablePro/Core/Compare/CompareRunner+Data.swift +++ b/apple/TablePro/Core/Compare/CompareRunner+Data.swift @@ -189,8 +189,14 @@ internal extension CompareRunner { try Task.checkCancellation() let options = session.structureOptions + let sourceSchema = StructureCompareOptions.listedSchema( + endpoint: context.source.schema, tableSchemas: sourceReads.map(\.table.schema) + ) + let targetSchema = StructureCompareOptions.listedSchema( + endpoint: context.target.schema, tableSchemas: targetReads.map(\.table.schema) + ) let targetByKey = Dictionary( - targetReads.map { (options.matchKey(name: $0.table.name, schema: $0.table.schema), $0) }, + targetReads.map { (options.matchKey(name: $0.table.name, schema: $0.table.schema, listedIn: targetSchema), $0) }, uniquingKeysWith: { first, _ in first } ) let previous = Dictionary( @@ -204,7 +210,7 @@ internal extension CompareRunner { var plans: [DataComparePlan] = [] for read in sourceReads { guard read.failure == nil else { continue } - let pairKey = options.matchKey(name: read.table.name, schema: read.table.schema) + let pairKey = options.matchKey(name: read.table.name, schema: read.table.schema, listedIn: sourceSchema) guard let counterpart = targetByKey[pairKey], counterpart.failure == nil else { continue } let plan = makePlan( read: read, diff --git a/apple/TablePro/Core/Compare/CompareRunner.swift b/apple/TablePro/Core/Compare/CompareRunner.swift index 902d61e917..b007f0f326 100644 --- a/apple/TablePro/Core/Compare/CompareRunner.swift +++ b/apple/TablePro/Core/Compare/CompareRunner.swift @@ -328,8 +328,21 @@ internal struct CompareRunner { $0.snapshot?.droppingCatalogSpellings(ownSchema: context.target.schema) } - let engine = StructureDiffEngine(options: session.structureOptions) - let tableReport = engine.compare(source: sourceSnapshots, target: targetSnapshots) + let options = session.structureOptions + let sourceSchema = StructureCompareOptions.listedSchema( + endpoint: context.source.schema, tableSchemas: sourceTables.map(\.table.schema) + ) + let targetSchema = StructureCompareOptions.listedSchema( + endpoint: context.target.schema, tableSchemas: targetTables.map(\.table.schema) + ) + let tableReport = StructureDiffEngine(options: options).compare( + source: sourceSnapshots, + target: targetSnapshots, + sourceSchema: sourceSchema, + targetSchema: targetSchema, + unreadableSource: sourceTables.filter { $0.failure != nil }.map { (name: $0.table.name, schema: $0.table.schema) }, + unreadableTarget: targetTables.filter { $0.failure != nil }.map { (name: $0.table.name, schema: $0.table.schema) } + ) let sourceByName = Dictionary( sourceSnapshots.map { ($0.qualifiedName, $0) }, uniquingKeysWith: { first, _ in first } @@ -337,12 +350,20 @@ internal struct CompareRunner { let targetByName = Dictionary( targetSnapshots.map { ($0.qualifiedName, $0) }, uniquingKeysWith: { first, _ in first } ) + // A pair across two schemas carries the source's name, so its target is found the way the engine paired it. + let targetByKey = Dictionary( + targetSnapshots.map { (options.matchKey(name: $0.name, schema: $0.schema, listedIn: targetSchema), $0) }, + uniquingKeysWith: { first, _ in first } + ) var results = tableReport.results.map { result -> CompareObjectResult in - CompareObjectResult.from( + let target = result.status == .onlyInTarget + ? targetByName[result.id] + : targetByKey[options.matchKey(name: result.tableName, schema: result.schema, listedIn: sourceSchema)] + return CompareObjectResult.from( result, sourceDefinition: sourceByName[result.id].map(TableDefinitionRenderer.lines) ?? [], - targetDefinition: targetByName[result.id].map(TableDefinitionRenderer.lines) ?? [] + targetDefinition: target.map(TableDefinitionRenderer.lines) ?? [] ) } results += unreadableResults(sourceTables, targetTables) @@ -407,7 +428,7 @@ internal struct CompareRunner { async let targetDefinitions = metadataService.viewDefinitions( for: context.target, connection: context.targetConnection, views: targetViews ) - results += try await diffEngine.compare(source: sourceDefinitions, target: targetDefinitions) + results += try await Self.compare(sourceDefinitions, targetDefinitions, with: diffEngine, context) } if includedKinds.contains(.procedure) || includedKinds.contains(.function) { @@ -417,7 +438,7 @@ internal struct CompareRunner { async let targetRoutines = metadataService.routineReads( for: context.target, connection: context.targetConnection ) - results += try await diffEngine.compare(source: sourceRoutines, target: targetRoutines) + results += try await Self.compare(sourceRoutines, targetRoutines, with: diffEngine, context) } if includedKinds.contains(.trigger) { @@ -432,12 +453,26 @@ internal struct CompareRunner { connection: context.targetConnection, tables: targetReads.map(\.table.name) ) - results += try await diffEngine.compare(source: sourceTriggers, target: targetTriggers) + results += try await Self.compare(sourceTriggers, targetTriggers, with: diffEngine, context) } return results.filter { includedKinds.contains($0.identity.kind) } } + private static func compare( + _ source: [RoutineSourceRead], + _ target: [RoutineSourceRead], + with engine: SourceObjectDiffEngine, + _ context: Context + ) -> [CompareObjectResult] { + engine.compare( + source: source, + target: target, + sourceSchema: StructureCompareOptions.listedSchema(endpoint: context.source.schema, tableSchemas: source.map(\.schema)), + targetSchema: StructureCompareOptions.listedSchema(endpoint: context.target.schema, tableSchemas: target.map(\.schema)) + ) + } + private func structureStatements(_ context: Context) async throws -> [SyncStatement] { guard let report = session.report else { return [] } let snapshots = session.sourceSnapshots @@ -449,7 +484,11 @@ internal struct CompareRunner { case .skip: return nil case .create: guard let snapshot = snapshots[result.identity.qualifiedName] else { return nil } - return .createTable(snapshot) + return .createTable(snapshot.placingReferences( + from: snapshot.schema ?? context.source.schema, + into: context.target.schema, + options: session.structureOptions + )) case .drop: return .dropTable(name: result.identity.name, schema: result.identity.schema) case .alter: diff --git a/apple/TablePro/Core/Compare/CompareSyncExecutor.swift b/apple/TablePro/Core/Compare/CompareSyncExecutor.swift index f5dd7f1942..7175fc1d8d 100644 --- a/apple/TablePro/Core/Compare/CompareSyncExecutor.swift +++ b/apple/TablePro/Core/Compare/CompareSyncExecutor.swift @@ -87,21 +87,31 @@ internal struct CompareSyncRunResult { /// expects. internal let commitFailure: String? + // A run that had to roll back and could not, so the target is in neither state the user expects. + internal let rollbackFailure: String? + /// Tables whose storage cannot roll back, so a rolled-back run still left their rows written. internal let nonTransactionalObjects: [String] + // Set when the run joined a transaction the session already held: that transaction's state once the run ended. + internal let joinedSessionTransaction: PluginSessionTransactionState? + internal init( outcomes: [SyncStatementOutcome], rolledBack: Bool, cancelled: Bool, commitFailure: String? = nil, - nonTransactionalObjects: [String] = [] + rollbackFailure: String? = nil, + nonTransactionalObjects: [String] = [], + joinedSessionTransaction: PluginSessionTransactionState? = nil ) { self.outcomes = outcomes self.rolledBack = rolledBack self.cancelled = cancelled self.commitFailure = commitFailure + self.rollbackFailure = rollbackFailure self.nonTransactionalObjects = nonTransactionalObjects + self.joinedSessionTransaction = joinedSessionTransaction } internal var executedCount: Int { @@ -207,7 +217,9 @@ internal actor CompareSyncExecutor { progress: Progress, nonTransactionalObjects: Set ) async throws -> CompareSyncRunResult { - let usesTransaction = settings.usesTransaction(for: mode, driver: driver) + let owner = await Self.transactionOwner(of: driver) + let usesTransaction = owner.sendsBegin && owner.commitsAtEnd + && settings.usesTransaction(for: mode, driver: driver) if usesTransaction { try await driver.beginTransaction() } @@ -264,16 +276,24 @@ internal actor CompareSyncExecutor { await closeSessionScopes(openScopes, on: driver) - let shouldRollback = usesTransaction + var shouldRollback = usesTransaction && (cancelled || (stopped && settings.errorHandling == .stopAndRollback)) + // PostgreSQL answers a COMMIT in an aborted transaction with ROLLBACK and no error, so Stop and keep what ran kept nothing. + if usesTransaction, !shouldRollback, await driver.sessionTransactionState() == .abortedTransaction { + shouldRollback = true + } var commitFailure: String? + var rollbackFailure: String? if usesTransaction { if shouldRollback { - try? await driver.rollbackTransaction() + do { + try await driver.rollbackTransaction() + } catch { + Self.logger.error("Sync rollback failed: \(error.publicLogShape, privacy: .public)") + rollbackFailure = error.localizedDescription + } } else { - /// A commit that throws used to propagate past the whole run, so the result was - /// discarded and the user got an error with no record of which statements had - /// already executed. The failure belongs in the result, not instead of it. + // The failure belongs in the result, not instead of it: the outcomes say what already ran. do { try await driver.commitTransaction() } catch { @@ -282,16 +302,35 @@ internal actor CompareSyncExecutor { } } } + let joined: PluginSessionTransactionState? = owner == .session + ? await driver.sessionTransactionState() + : nil /// Named from what ran, not from what the script mentioned: a table whose statements never /// reached the target has nothing left in it to warn about. let written = Set(outcomes.filter { $0.didExecute }.map { $0.statement.objectName }) return CompareSyncRunResult( outcomes: outcomes, - rolledBack: shouldRollback, + rolledBack: shouldRollback && rollbackFailure == nil, cancelled: cancelled, commitFailure: commitFailure, - nonTransactionalObjects: nonTransactionalObjects.intersection(written).sorted() + rollbackFailure: rollbackFailure, + nonTransactionalObjects: nonTransactionalObjects.intersection(written).sorted(), + joinedSessionTransaction: joined + ) + } + + // Asked inside the target's lease, which on DuckDB and PGlite is the session the user's own transaction may be open + // on: a BEGIN of the run's own aborts it on DuckDB, and its COMMIT commits their pending work on PGlite. + private static func transactionOwner(of driver: any PluginDatabaseDriver) async -> WriteTransactionOwner { + let state: PluginSessionTransactionState = driver.supportsTransactions + ? await driver.sessionTransactionState() + : .unknown + // `.automatic`: a pooled lease is closed while idle, which would roll a held run back after it reported success. + return WriteTransactionOwner.resolve( + supportsTransactions: driver.supportsTransactions, + sessionState: state, + commitMode: .automatic ) } diff --git a/apple/TablePro/Core/Compare/CompareSyncSession+Editing.swift b/apple/TablePro/Core/Compare/CompareSyncSession+Editing.swift index d6862ad7a1..ba68b91ba5 100644 --- a/apple/TablePro/Core/Compare/CompareSyncSession+Editing.swift +++ b/apple/TablePro/Core/Compare/CompareSyncSession+Editing.swift @@ -12,6 +12,7 @@ // import Foundation +import TableProPluginKit internal extension CompareSyncSession { // MARK: - Target @@ -44,6 +45,24 @@ internal extension CompareSyncSession { /// What the run did, in the window rather than in the sheet that closed before it started. func reportRunResult(_ result: CompareSyncRunResult, target: DatabaseEndpoint) { + if let joined = result.joinedSessionTransaction { + informationalMessage = joined == .abortedTransaction + ? String( + localized: "This sync ran inside the transaction already open on this connection, which can no longer be committed. Roll it back." + ) + : String( + localized: "This sync ran inside the transaction already open on this connection. Commit it to keep the changes, or roll it back to discard them." + ) + } + if let rollbackFailure = result.rollbackFailure { + errorMessage = String( + format: String( + localized: "The run stopped, but the transaction could not be rolled back: %@. Compare again to see where the target stands." + ), + rollbackFailure + ) + return + } if result.rollbackLeftWritesInPlace { errorMessage = String( format: String( @@ -61,17 +80,24 @@ internal extension CompareSyncSession { return } guard result.failedCount > 0 else { return } - errorMessage = result.rolledBack - ? String( + if result.rolledBack { + errorMessage = String( format: String(localized: "%d statements failed, so the run was rolled back and %@ is unchanged."), result.failedCount, target.qualifiedDescription ) - : String( + } else if result.joinedSessionTransaction != nil { + errorMessage = String( + format: String(localized: "%d statements failed. What already ran is pending in the transaction on this connection."), + result.failedCount + ) + } else { + errorMessage = String( format: String( localized: "%d statements failed. What already ran stays applied. Compare again to see where the target stands." ), result.failedCount ) + } } // MARK: - Key columns diff --git a/apple/TablePro/Core/Compare/DataCompareOptions.swift b/apple/TablePro/Core/Compare/DataCompareOptions.swift index 1a591e9426..84ee53f7a2 100644 --- a/apple/TablePro/Core/Compare/DataCompareOptions.swift +++ b/apple/TablePro/Core/Compare/DataCompareOptions.swift @@ -167,12 +167,26 @@ internal struct CellValueComparator { } private func compareInstants(_ lhs: String, _ rhs: String) -> ValueComparison { + let (lhs, rhs) = Self.wallClocksWhenOneSideIsZoned(lhs, rhs) guard let left = TimestampValue.parse(lhs), let right = TimestampValue.parse(rhs) else { return ValueComparison(isEqual: false, rule: .exactValue) } let equal = left.equals(right, fractionalDigits: options.timestampFractionalDigits) return ValueComparison(isEqual: equal, rule: .timestampPrecision) } + + // A value with no zone names no instant. A zoned one written into it keeps its wall clock (the copier and the sync + // strip the offset, PostgreSQL ignores it), and a zone-less one written into a zoned column reads back at the + // session's offset, so a pair with one zoned side meets on the wall clock or a sync never converges. + private static func wallClocksWhenOneSideIsZoned(_ lhs: String, _ rhs: String) -> (String, String) { + let left = CrossEngineValueCoercer.strippingTimeZoneOffset(lhs.trimmingCharacters(in: .whitespaces)) + let right = CrossEngineValueCoercer.strippingTimeZoneOffset(rhs.trimmingCharacters(in: .whitespaces)) + switch (left, right) { + case (let left?, nil): return (left, rhs) + case (nil, let right?): return (lhs, right) + default: return (lhs, rhs) + } + } } /// An instant, held as whole nanoseconds since the epoch. diff --git a/apple/TablePro/Core/Compare/ResultSetComparison.swift b/apple/TablePro/Core/Compare/ResultSetComparison.swift index 1ead931fdc..b506e879ea 100644 --- a/apple/TablePro/Core/Compare/ResultSetComparison.swift +++ b/apple/TablePro/Core/Compare/ResultSetComparison.swift @@ -190,7 +190,7 @@ internal enum ResultComparisonEngine { pairing: ResultColumnPairing, keyPairs: [Int] ) throws -> ResultComparison { - let kinds = valueKinds(pairing: pairing, left: left, right: right) + let columnReadings = readings(pairing: pairing, left: left, right: right) let keySet = Set(keyPairs) let compared = pairing.pairs.indices.filter { !keySet.contains($0) } @@ -198,7 +198,7 @@ internal enum ResultComparisonEngine { rightByKey.reserveCapacity(right.rows.count) for index in right.rows.indices { try checkCancellation(at: index) - let key = keyPairs.map { token(right.rows[index], pairing.pairs[$0].right, kinds[$0], in: right) } + let key = keyPairs.map { token(right.rows[index], pairing.pairs[$0].right, columnReadings[$0], in: right) } guard rightByKey.updateValue(index, forKey: key) == nil else { throw duplicateKeyError(right.rows[index], keyPairs.map { pairing.pairs[$0].right }, onLeft: false) } @@ -212,7 +212,7 @@ internal enum ResultComparisonEngine { for index in left.rows.indices { try checkCancellation(at: index) let leftRow = left.rows[index] - let key = keyPairs.map { token(leftRow, pairing.pairs[$0].left, kinds[$0], in: left) } + let key = keyPairs.map { token(leftRow, pairing.pairs[$0].left, columnReadings[$0], in: left) } guard seenOnLeft.insert(key).inserted else { throw duplicateKeyError(leftRow, keyPairs.map { pairing.pairs[$0].left }, onLeft: true) } @@ -224,7 +224,7 @@ internal enum ResultComparisonEngine { let rightRow = right.rows[partner] let changed = compared.filter { pairIndex in let pair = pairing.pairs[pairIndex] - return token(leftRow, pair.left, kinds[pairIndex], in: left) != token(rightRow, pair.right, kinds[pairIndex], in: right) + return token(leftRow, pair.left, columnReadings[pairIndex], in: left) != token(rightRow, pair.right, columnReadings[pairIndex], in: right) } entries.append(ResultComparisonEntry( kind: changed.isEmpty ? .same : .changed, @@ -246,12 +246,12 @@ internal enum ResultComparisonEngine { right: ResultComparisonSide, pairing: ResultColumnPairing ) throws -> ResultComparison { - let kinds = valueKinds(pairing: pairing, left: left, right: right) + let columnReadings = readings(pairing: pairing, left: left, right: right) var rightByValues: [[CellToken]: [Int]] = [:] for index in right.rows.indices { try checkCancellation(at: index) - let values = pairing.pairs.indices.map { token(right.rows[index], pairing.pairs[$0].right, kinds[$0], in: right) } + let values = pairing.pairs.indices.map { token(right.rows[index], pairing.pairs[$0].right, columnReadings[$0], in: right) } rightByValues[values, default: []].append(index) } @@ -262,7 +262,7 @@ internal enum ResultComparisonEngine { for index in left.rows.indices { try checkCancellation(at: index) - let values = pairing.pairs.indices.map { token(left.rows[index], pairing.pairs[$0].left, kinds[$0], in: left) } + let values = pairing.pairs.indices.map { token(left.rows[index], pairing.pairs[$0].left, columnReadings[$0], in: left) } let next = taken[values, default: 0] guard let bucket = rightByValues[values], next < bucket.count else { entries.append(ResultComparisonEntry(kind: .onlyLeft, leftRow: index, rightRow: nil)) @@ -279,8 +279,8 @@ internal enum ResultComparisonEngine { return ResultComparison(entries: entries, keyPairs: []) } - // One equality for keys, whole rows and values, matching `CellValueComparator` at its default - // options: an absent field is not NULL, and two spellings of one instant agree to the microsecond. + // One key per value, so keys, whole rows and values share one equivalence: an absent field is not NULL, and two + // spellings of one instant agree to the microsecond. private enum CellToken: Hashable { case absent case null @@ -289,8 +289,21 @@ internal enum ResultComparisonEngine { case instant(Int64) } + private struct ColumnReading { + let kind: ValueComparisonKind + // One side's values all carry an offset and the other's none, so both are read on the wall clock. + let wallClock: Bool + } + + private enum Zoning { + case empty + case zoned + case unzoned + case mixed + } + private static func token( - _ row: Row, _ column: Int, _ kind: ValueComparisonKind, in side: ResultComparisonSide + _ row: Row, _ column: Int, _ reading: ColumnReading, in side: ResultComparisonSide ) -> CellToken { guard !side.isAbsent(row, column: column) else { return .absent } switch row[column] { @@ -299,33 +312,63 @@ internal enum ResultComparisonEngine { case .bytes(let data): return .bytes(data) case .text(let text): - guard kind == .temporal || kind == .unknown, let microseconds = instantMicroseconds(text) else { - return .text(text) - } + guard reading.kind == .temporal || reading.kind == .unknown else { return .text(text) } + let wallClock = reading.wallClock ? Self.withoutOffset(text) : nil + guard let microseconds = instantMicroseconds(wallClock ?? text) else { return .text(text) } return .instant(microseconds) } } + private static func withoutOffset(_ text: String) -> String? { + CrossEngineValueCoercer.strippingTimeZoneOffset(text.trimmingCharacters(in: .whitespaces)) + } + + // Read from every value, so row order and NULLs decide nothing; a column holding both spellings is mixed. + private static func zoning(of side: ResultComparisonSide, column: Int) -> Zoning { + var zoning = Zoning.empty + for row in side.rows where !side.isAbsent(row, column: column) { + guard case .text(let text) = row[column], startsLikeATimestamp(text) else { continue } + switch (zoning, withoutOffset(text) != nil) { + case (.empty, true): zoning = .zoned + case (.empty, false): zoning = .unzoned + case (.zoned, false), (.unzoned, true): return .mixed + default: break + } + } + return zoning + } + // Every pattern `TimestampValue` reads starts with `yyyy-`, so anything else skips the formatters. - private static func instantMicroseconds(_ text: String) -> Int64? { + private static func startsLikeATimestamp(_ text: String) -> Bool { let head = Array(text.utf8.drop { $0 == UInt8(ascii: " ") }.prefix(5)) - guard head.count == 5, head[4] == UInt8(ascii: "-"), - head[0 ..< 4].allSatisfy({ $0 >= UInt8(ascii: "0") && $0 <= UInt8(ascii: "9") }), - let instant = TimestampValue.parse(text) else { return nil } + return head.count == 5 && head[4] == UInt8(ascii: "-") + && head[0 ..< 4].allSatisfy { $0 >= UInt8(ascii: "0") && $0 <= UInt8(ascii: "9") } + } + + private static func instantMicroseconds(_ text: String) -> Int64? { + guard startsLikeATimestamp(text), let instant = TimestampValue.parse(text) else { return nil } let nanoseconds = instant.nanosecondsSinceEpoch let quotient = nanoseconds / 1_000 return nanoseconds % 1_000 < 0 ? quotient - 1 : quotient } - private static func valueKinds( + private static func readings( pairing: ResultColumnPairing, left: ResultComparisonSide, right: ResultComparisonSide - ) -> [ValueComparisonKind] { + ) -> [ColumnReading] { pairing.pairs.map { pair in let leftKind = ValueComparisonKind(columnType: left.columnType(at: pair.left)) let rightKind = ValueComparisonKind(columnType: right.columnType(at: pair.right)) - return leftKind == rightKind ? leftKind : .unknown + let kind = leftKind == rightKind ? leftKind : .unknown + guard kind == .temporal || kind == .unknown else { return ColumnReading(kind: kind, wallClock: false) } + let zonings = (zoning(of: left, column: pair.left), zoning(of: right, column: pair.right)) + switch zonings { + case (.zoned, .unzoned), (.unzoned, .zoned): + return ColumnReading(kind: kind, wallClock: true) + default: + return ColumnReading(kind: kind, wallClock: false) + } } } diff --git a/apple/TablePro/Core/Compare/SourceObjectDiffEngine.swift b/apple/TablePro/Core/Compare/SourceObjectDiffEngine.swift index b7259c0f28..2bb535523b 100644 --- a/apple/TablePro/Core/Compare/SourceObjectDiffEngine.swift +++ b/apple/TablePro/Core/Compare/SourceObjectDiffEngine.swift @@ -45,32 +45,53 @@ internal struct SourceObjectDiffEngine { internal func compare( source: [RoutineSourceRead], - target: [RoutineSourceRead] + target: [RoutineSourceRead], + sourceSchema: String? = nil, + targetSchema: String? = nil ) -> [CompareObjectResult] { let targetByKey = Dictionary( - target.map { (matchKey(for: $0), $0) }, + target.map { (matchKey(for: $0, listedIn: targetSchema), $0) }, uniquingKeysWith: { first, _ in first } ) var handled: Set = [] var results: [CompareObjectResult] = [] for read in source { - let key = matchKey(for: read) + let key = matchKey(for: read, listedIn: sourceSchema) handled.insert(key) - results.append(result(identifiedBy: read, source: read, target: targetByKey[key])) + let target = targetByKey[key] + results.append(result( + identifiedBy: read, + source: read, + target: target, + scriptRefusal: scriptRefusal(for: read, into: target?.schema ?? targetSchema) + )) } - for read in target where !handled.contains(matchKey(for: read)) { + for read in target where !handled.contains(matchKey(for: read, listedIn: targetSchema)) { results.append(result(identifiedBy: read, source: nil, target: read)) } return results } + // The definition is the source's own text and can name the schema it was read from, so it is never run into another. + private func scriptRefusal(for source: RoutineSourceRead, into targetSchema: String?) -> String? { + guard let sourceSchema = source.schema, let targetSchema, !sourceSchema.isEmpty, !targetSchema.isEmpty, + options.matchKey(sourceSchema) != options.matchKey(targetSchema) else { return nil } + return String( + format: String( + localized: "%1$@ is compared but not scripted, because its definition was read from %2$@ and can name that schema rather than %3$@." + ), + source.name, sourceSchema, targetSchema + ) + } + private func result( identifiedBy read: RoutineSourceRead, source: RoutineSourceRead?, - target: RoutineSourceRead? + target: RoutineSourceRead?, + scriptRefusal: String? = nil ) -> CompareObjectResult { let sourceDefect = source.flatMap { SourceDefinitionDefect.of($0, sentAs: sourceScriptText) } let targetDefect = target.flatMap { SourceDefinitionDefect.of($0, sentAs: targetScriptText) } @@ -79,26 +100,29 @@ internal struct SourceObjectDiffEngine { ?? targetDefect.map { $0.reason(on: .target) } ?? indexes.failure let definitionMatches = comparisonError == nil && definitionsMatch(source: source, target: target) + let resolvedStatus = status( + source: source, + target: target, + comparable: comparisonError == nil, + definitionMatches: definitionMatches, + indexes: indexes + ) + let scriptRefusal = resolvedStatus == .identical ? nil : scriptRefusal return CompareObjectResult( identity: CompareObjectIdentity( kind: read.kind, schema: read.schema, name: read.name, signature: read.signature ), - status: status( - source: source, - target: target, - comparable: comparisonError == nil, - definitionMatches: definitionMatches, - indexes: indexes - ), + status: resolvedStatus, changes: comparisonError == nil ? indexes.changes : [], sourceDefinition: source.map(displayedLines) ?? [], targetDefinition: target.map(displayedLines) ?? [], - notes: comparisonError == nil ? indexes.notes : [], + notes: comparisonError == nil ? (scriptRefusal.map { [$0] } ?? []) + indexes.notes : [], comparisonError: comparisonError, sourceIndexes: indexes.source, targetIndexes: indexes.target, definitionMatches: definitionMatches, - sourceCreationScope: source?.creationScope + sourceCreationScope: source?.creationScope, + scriptRefusal: scriptRefusal ) } @@ -170,11 +194,11 @@ internal struct SourceObjectDiffEngine { return SqlNormalizer.lines(read.source) } - private func matchKey(for read: RoutineSourceRead) -> String { - let name = options.ignoreIdentifierCase ? read.name.lowercased() : read.name - let schema = options.ignoreIdentifierCase ? (read.schema ?? "").lowercased() : (read.schema ?? "") + // Keyed as a table is, so the schema each side was listed from drops out and `dbo.v` pairs with `staging.v`. + private func matchKey(for read: RoutineSourceRead, listedIn listedSchema: String?) -> String { + let qualified = options.matchKey(name: read.name, schema: read.schema, listedIn: listedSchema) let signature = (read.signature ?? "").replacingOccurrences(of: " ", with: "").lowercased() - return "\(read.kind.rawValue)|\(schema)|\(name)|\(signature)" + return "\(read.kind.rawValue)|\(qualified)|\(signature)" } // Cut before folding: a folded line comment swallows the body, and Oracle stores `END` without its `;` INVALID. diff --git a/apple/TablePro/Core/Compare/SourceObjectSyncBuilder.swift b/apple/TablePro/Core/Compare/SourceObjectSyncBuilder.swift index 27464be9e6..2930afbf68 100644 --- a/apple/TablePro/Core/Compare/SourceObjectSyncBuilder.swift +++ b/apple/TablePro/Core/Compare/SourceObjectSyncBuilder.swift @@ -53,6 +53,9 @@ internal struct SourceObjectSyncBuilder { } internal func build(for result: CompareObjectResult, action: TableSyncAction) throws -> [SyncStatement] { + if action != .skip, let refusal = result.scriptRefusal { + throw CompareSyncError.unsupportedOperation(refusal) + } switch action { case .skip: return [] diff --git a/apple/TablePro/Core/Compare/StructureCompareOptions.swift b/apple/TablePro/Core/Compare/StructureCompareOptions.swift index 1014569150..5cafed16c6 100644 --- a/apple/TablePro/Core/Compare/StructureCompareOptions.swift +++ b/apple/TablePro/Core/Compare/StructureCompareOptions.swift @@ -26,16 +26,21 @@ internal extension StructureCompareOptions { return ignoreIdentifierCase ? trimmed.lowercased() : trimmed } - /// Two schemas of one database can hold the same table name, so the name alone cannot identify - /// a table. Matching on it collapsed `public.users` and `audit.users` onto one result, diffed - /// both against whichever target arrived first, and never reported the other as target-only. - /// The schema joins the key only when both sides carry one, so a schemaless engine is - /// unaffected. - func matchKey(name: String, schema: String?) -> String { + // Two schemas of one listing can hold the same name, so another schema joins the key. The schema the side was + // listed from does not: SQL Server spells it on every table, and `dbo.users` has to pair with `staging.users`. + func matchKey(name: String, schema: String?, listedIn listedSchema: String? = nil) -> String { guard let schema, !schema.isEmpty else { return matchKey(name) } + if let listedSchema, matchKey(listedSchema) == matchKey(schema) { return matchKey(name) } return "\(matchKey(schema))\u{1F}\(matchKey(name))" } + // The endpoint's schema, or with none the one schema its listing carries: a listing is one schema, the session's own. + static func listedSchema(endpoint: String?, tableSchemas: [String?]) -> String? { + if let endpoint, !endpoint.isEmpty { return endpoint } + let carried = Set(tableSchemas.compactMap { $0 }.filter { !$0.isEmpty }) + return carried.count == 1 ? carried.first : nil + } + func normalizedText(_ value: String?) -> String? { guard let value else { return nil } var result = value diff --git a/apple/TablePro/Core/Compare/StructureDiffEngine.swift b/apple/TablePro/Core/Compare/StructureDiffEngine.swift index 1b6e3dfc6b..25afb31fc5 100644 --- a/apple/TablePro/Core/Compare/StructureDiffEngine.swift +++ b/apple/TablePro/Core/Compare/StructureDiffEngine.swift @@ -20,17 +20,31 @@ internal struct StructureDiffEngine { internal func compare( source: [TableStructureSnapshot], - target: [TableStructureSnapshot] + target: [TableStructureSnapshot], + sourceSchema: String? = nil, + targetSchema: String? = nil, + unreadableSource: [(name: String, schema: String?)] = [], + unreadableTarget: [(name: String, schema: String?)] = [] ) -> StructureDiffReport { - let targetByKey = indexByMatchKey(target) + let targetByKey = indexByMatchKey(target, listedIn: targetSchema) + // A counterpart that could not be read is not a missing one: its own row reports it, and a Create or Drop would not. + let unreadableInSource = Set(unreadableSource.map { + options.matchKey(name: $0.name, schema: $0.schema, listedIn: sourceSchema) + }) + let unreadableInTarget = Set(unreadableTarget.map { + options.matchKey(name: $0.name, schema: $0.schema, listedIn: targetSchema) + }) + + let crossing = Self.crossing(from: sourceSchema, to: targetSchema, options: options) var results: [TableDiffResult] = [] - var handled: Set = [] + var handled = unreadableInSource for snapshot in source { - let key = options.matchKey(name: snapshot.name, schema: snapshot.schema) + let key = options.matchKey(name: snapshot.name, schema: snapshot.schema, listedIn: sourceSchema) handled.insert(key) guard let counterpart = targetByKey[key] else { + guard !unreadableInTarget.contains(key) else { continue } results.append(TableDiffResult( tableName: snapshot.name, schema: snapshot.schema, @@ -38,10 +52,19 @@ internal struct StructureDiffEngine { )) continue } - results.append(compareTable(source: snapshot, target: counterpart)) + guard let crossing else { + results.append(compareTable(source: snapshot, target: counterpart)) + continue + } + // A key to each side's own schema is a key to the target's own: compared that way, and written that way. + results.append(compareTable( + source: snapshot.movingReferences(from: crossing.source, to: crossing.target, folding: { options.matchKey($0) }), + target: counterpart.movingReferences(from: crossing.target, to: crossing.target, folding: { options.matchKey($0) }) + )) } - for snapshot in target where !handled.contains(options.matchKey(name: snapshot.name, schema: snapshot.schema)) { + for snapshot in target + where !handled.contains(options.matchKey(name: snapshot.name, schema: snapshot.schema, listedIn: targetSchema)) { results.append(TableDiffResult( tableName: snapshot.name, schema: snapshot.schema, @@ -84,9 +107,22 @@ internal struct StructureDiffEngine { ) } - private func indexByMatchKey(_ snapshots: [TableStructureSnapshot]) -> [String: TableStructureSnapshot] { + private static func crossing( + from source: String?, + to target: String?, + options: StructureCompareOptions + ) -> (source: String, target: String)? { + guard let source, let target, !source.isEmpty, !target.isEmpty, + options.matchKey(source) != options.matchKey(target) else { return nil } + return (source, target) + } + + private func indexByMatchKey( + _ snapshots: [TableStructureSnapshot], + listedIn listedSchema: String? + ) -> [String: TableStructureSnapshot] { Dictionary( - snapshots.map { (options.matchKey(name: $0.name, schema: $0.schema), $0) }, + snapshots.map { (options.matchKey(name: $0.name, schema: $0.schema, listedIn: listedSchema), $0) }, uniquingKeysWith: { first, _ in first } ) } diff --git a/apple/TablePro/Core/Compare/TableStructureSnapshot.swift b/apple/TablePro/Core/Compare/TableStructureSnapshot.swift index 109a568875..267a7b62b7 100644 --- a/apple/TablePro/Core/Compare/TableStructureSnapshot.swift +++ b/apple/TablePro/Core/Compare/TableStructureSnapshot.swift @@ -80,6 +80,34 @@ internal struct TableStructureSnapshot: Hashable { return copy } + // A table created in another schema takes its keys to its own schema's tables with it. + internal func placingReferences( + from sourceSchema: String?, + into targetSchema: String?, + options: StructureCompareOptions + ) -> TableStructureSnapshot { + guard let sourceSchema, let targetSchema, !sourceSchema.isEmpty, !targetSchema.isEmpty, + options.matchKey(sourceSchema) != options.matchKey(targetSchema) else { return self } + return movingReferences(from: sourceSchema, to: targetSchema) { options.matchKey($0) } + } + + // A key to `own` schema, or to none, names `replacement` instead; a key to a third schema is left as it is. + internal func movingReferences( + from own: String, + to replacement: String, + folding fold: (String) -> String + ) -> TableStructureSnapshot { + var copy = self + copy.foreignKeys = foreignKeys.map { foreignKey in + let referenced = foreignKey.referencedSchema ?? "" + guard referenced.isEmpty || fold(referenced) == fold(own) else { return foreignKey } + var moved = foreignKey + moved.referencedSchema = replacement + return moved + } + return copy + } + /// The same structure with every definition under one shared `id`, so two reads of a table /// nobody touched compare equal. Replacing the three arrays on a copy, rather than rebuilding /// the snapshot, keeps every other field in the comparison. diff --git a/apple/TablePro/Core/Coordinators/RowEditingCoordinator.swift b/apple/TablePro/Core/Coordinators/RowEditingCoordinator.swift index 0f70b51891..b7c34051a0 100644 --- a/apple/TablePro/Core/Coordinators/RowEditingCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/RowEditingCoordinator.swift @@ -296,18 +296,80 @@ final class RowEditingCoordinator: ObservableObject { ) } + // A claimed execution or a landing save replaces the rows, which clears anything staged on them meanwhile. + func holdInspectorRows(tabId: UUID, columnIndex: Int, rowIDs: [RowID]) -> InspectorDetachedTarget? { + guard !rowIDs.isEmpty, parent.tabManager.tabs.contains(where: { $0.id == tabId }), + !isSaving(tabId: tabId), !parent.tabExecution.isExecuting(tabId) else { return nil } + let tableRows = parent.tabSessionRegistry.tableRows(for: tabId) + guard tableRows.columns.indices.contains(columnIndex) else { return nil } + let changeManager = parent.changeManager(forTab: tabId) + var rowsAsRead: [[PluginCellValue]] = [] + rowsAsRead.reserveCapacity(rowIDs.count) + for rowID in rowIDs { + guard let storageRow = tableRows.index(of: rowID), !changeManager.isRowDeleted(rowID) else { return nil } + // As read, so staged edits keep the hold; an inserted row's id names it alone. + let current = Array(tableRows.rows[storageRow].values) + rowsAsRead.append( + rowID.isInserted ? [] : changeManager.pending.imageAsRead(ofRow: rowID, current: current, absentColumns: []).row + ) + } + return InspectorDetachedTarget( + tabId: tabId, + columnIndex: columnIndex, + columnName: tableRows.columns[columnIndex], + rowIDs: rowIDs, + rowsAsRead: rowsAsRead + ) + } + + // Read from the target's own tab: the selected one may be another table with other column types. + func stageDetachedInspectorEdit(_ text: String, to target: InspectorDetachedTarget) { + let tableRows = parent.tabSessionRegistry.tableRows(for: target.tabId) + let columnIndex = target.columnIndex + let value: PluginCellValue + let isExpression: Bool + if let typed = CellEntry.typed( + text, + columnType: tableRows.editingColumnType(at: columnIndex), + databaseType: parent.connection.type, + writer: parent.changeManager(forTab: target.tabId).cellWriterSupport + ) { + value = typed.value + isExpression = typed.isExpression + } else if let entered = tableRows.enteredValue(text, forColumn: columnIndex) { + value = entered + isExpression = false + } else { + return + } + // A value window commits per keystroke like its field, so its typing folds into one undo step the same way. + stageInspectorEdits( + valuesByRow: Dictionary(target.rowIDs.map { ($0, value) }, uniquingKeysWith: { first, _ in first }), + columnIndex: columnIndex, + continuity: .typing, + expressionRowIDs: isExpression ? Set(target.rowIDs) : [], + inTab: target.tabId + ) + } + private func stageInspectorEdits( valuesByRow: [RowID: PluginCellValue], columnIndex: Int, continuity: FieldEditContinuity, removingFieldFrom removedRowIDs: Set = [], - expressionRowIDs: Set = [] + expressionRowIDs: Set = [], + inTab targetTabId: UUID? = nil ) { if continuity == .discrete { endInspectorEditRun() } - guard !parent.isSavingSelectedTab, - let (tab, tabIndex) = parent.tabManager.selectedTabAndIndex, !valuesByRow.isEmpty else { return } + let located: (tab: QueryTab, index: Int)? + if let targetTabId { + located = parent.tabManager.tabs.firstIndex { $0.id == targetTabId }.map { (parent.tabManager.tabs[$0], $0) } + } else { + located = parent.tabManager.selectedTabAndIndex + } + guard let (tab, tabIndex) = located, !isSaving(tabId: tab.id), !valuesByRow.isEmpty else { return } let tabId = tab.id let changeManager = parent.changeManager(forTab: tabId) let tableRows = parent.tabSessionRegistry.tableRows(for: tabId) @@ -504,3 +566,5 @@ final class RowEditingCoordinator: ObservableObject { } } } + +extension RowEditingCoordinator: InspectorDetachedStaging {} diff --git a/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift b/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift index 12cd37becb..53ddcfb222 100644 --- a/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift +++ b/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift @@ -240,10 +240,35 @@ internal actor DatabaseAccessBridge { String(localized: "No database to run against. Pass a database name.") ) } + try Self.refuseUnreachable(scope, manager: manager) return scope } } + // Pinning skips a container the engine cannot switch to, so the call would run where the session already is while + // the caller, and an approval card, name the other one. + @MainActor + private static func refuseUnreachable(_ scope: DatabaseScope, manager: DatabaseManager) throws { + guard let session = manager.session(for: scope.connectionId) else { return } + let databaseType = session.connection.type + let current = session.resolvedBrowseDatabase + if !scope.isServerScoped, scope.database != current, + !manager.pluginManager.supportsDatabaseSwitching(for: databaseType) { + throw DatabaseAccessError.invalidArgument(String( + format: String(localized: "This connection cannot run against database %1$@, only its own: %2$@. Leave database out or pass %2$@."), + scope.database, + current + )) + } + if let schema = scope.schema, schema != session.browseSchema, + !manager.pluginManager.supportsSchemaSwitching(for: databaseType) { + throw DatabaseAccessError.invalidArgument(String( + format: String(localized: "This connection has no schema to switch to, so it cannot run against schema %@. Leave schema out."), + schema + )) + } + } + internal func switchDatabase(connectionId: UUID, database: String) async throws { let manager = await databaseManager try await manager.switchDatabase(to: database, for: connectionId) @@ -529,14 +554,24 @@ internal actor DatabaseAccessBridge { let manager = await databaseManager let route = await MainActor.run { manager.executionRoute(for: scope) } + let (commitMode, grammar) = await MainActor.run { + (manager.commitMode(for: connectionId), SQLLexicalResolver.executionGrammar(for: databaseType, connectionId: connectionId)) + } + // A plan that runs the statement is held by Manual Commit as the statement would be, as the in-app Explain is. + let agentGuard = AgentTransactionGuard( + commitMode: commitMode, databaseType: databaseType, grammar: grammar, connectionId: connectionId + ) + let gated = ExplainRequest.gatedSQL(subject: statement, runsStatement: step.runsStatement, databaseType: databaseType) let startTime = CFAbsoluteTimeGetCurrent() let statementRan = CatalogEvent.statementsRan( connectionId: connectionId, statements: [statement], databaseType: databaseType ) let variantId = step.variantId - let result: QueryResult + var result: QueryResult + let tableEdits: SucceededStatements? + let transactionNotice: String? do { - result = try await runRacingTimeout( + (result, tableEdits, transactionNotice) = try await runRacingTimeout( scope: scope, route: route, policy: policy, @@ -545,7 +580,15 @@ internal actor DatabaseAccessBridge { onLateCompletion: { CatalogChangeService.post(statementRan) } ) { driver in reach.mark() - return try await driver.explainPlan(statement: statement, variantId: variantId) + let ran = try await agentGuard.running([gated], writes: writes, on: driver) { _ in + try await driver.explainPlan(statement: statement, variantId: variantId) + } + let edits = writes + ? await SucceededStatements.single( + statement, scope: scope, databaseType: databaseType, grammar: grammar, ranOn: driver + ) + : nil + return (ran.value, edits, ran.notice) } } catch { if writes { @@ -556,6 +599,12 @@ internal actor DatabaseAccessBridge { if writes { CatalogChangeService.post(statementRan) } + if let tableEdits { + CatalogChangeService.post(.statementsSucceeded(tableEdits)) + } + if let transactionNotice { + result.statusMessage = [result.statusMessage, transactionNotice].compactMap { $0 }.joined(separator: " ") + } return StatementOutcome( result: result, executionTimeMs: (CFAbsoluteTimeGetCurrent() - startTime) * 1_000, budget: nil ) diff --git a/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift b/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift index 8288b0af98..a4106cbc57 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+Sessions.swift @@ -154,32 +154,33 @@ extension DatabaseManager { try Task.checkCancellation() try ensureAttemptIsCurrent(attempt, for: connection.id, driver: driver) + guard var session = activeSessions[connection.id] else { + throw abandonUnownedConnect(connection) + } // Batch all session mutations into a single write to fire objectWillChange once. - if var session = activeSessions[connection.id] { - session.connection = successfulConnectionRecord( - from: routedConnection, - preservingSessionFieldsFrom: session.connection - ) - dialedConnections[connection.id] = routedConnection - session.commitMode = session.connection.commitMode - session.driver = driver - session.status = driver.status - session.effectiveConnection = effectiveConnection - session.connectionWarning = openingWarning(driver: driver, startupFailures: startupFailures, for: connection.id) - // A connect answers whatever went wrong before it, including a reconnect that gave up on this entry. - session.liveness = .live - session.recovery = nil - disconnectReasons.removeValue(forKey: connection.id) - markSessionVerified(connection.id) - if let passwordOverride, !connection.usesIAMToken { - session.cachedPassword = passwordOverride - // Only once it authenticated: a mistyped answer shared with the profile locked every connection out. - if promptsForPassword { - promptedPasswords[promptCacheKey] = passwordOverride - } + session.connection = successfulConnectionRecord( + from: routedConnection, + preservingSessionFieldsFrom: session.connection + ) + dialedConnections[connection.id] = routedConnection + session.commitMode = session.connection.commitMode + session.driver = driver + session.status = driver.status + session.effectiveConnection = effectiveConnection + session.connectionWarning = openingWarning(driver: driver, startupFailures: startupFailures, for: connection.id) + // A connect answers whatever went wrong before it, including a reconnect that gave up on this entry. + session.liveness = .live + session.recovery = nil + disconnectReasons.removeValue(forKey: connection.id) + markSessionVerified(connection.id) + if let passwordOverride, !connection.usesIAMToken { + session.cachedPassword = passwordOverride + // Only once it authenticated: a mistyped answer shared with the profile locked every connection out. + if promptsForPassword { + promptedPasswords[promptCacheKey] = passwordOverride } - setSession(session, for: connection.id) } + setSession(session, for: connection.id) // Before `finish`, so the clear is still the current attempt's to make. clearConnectionStage(for: connection.id) @@ -334,6 +335,15 @@ extension DatabaseManager { } } + // An entry removed with no cancel reaching the attempt leaves nobody to close its tunnel or fire its script; the + // connect's catch disconnects the driver of a cancelled attempt. + private func abandonUnownedConnect(_ connection: DatabaseConnection) -> CancellationError { + invalidateConnectionAttempt(connection.id) + closeActiveTunnel(for: connection) + postDisconnectScripts.fire(for: connection.id) + return CancellationError() + } + private func isAttemptCancelled(_ attempt: Int, for connectionId: UUID) -> Bool { Task.isCancelled || !connectionAttempts.isCurrent(attempt, for: connectionId) } @@ -806,6 +816,9 @@ extension DatabaseManager { } disconnectsInFlight.insert(sessionId) defer { disconnectsInFlight.remove(sessionId) } + // A connect still running would dial a tunnel and arm a post-disconnect script after the entry is gone. + invalidateConnectionAttempt(sessionId) + await ensureConnectedDedup.cancel(key: sessionId) // Before the tunnel closes, so a reconnect attempt cannot rebuild it behind the teardown. endRecoveryLoop(for: sessionId) diff --git a/apple/TablePro/Core/MCP/Protocol/Tools/ExplainQueryTool.swift b/apple/TablePro/Core/MCP/Protocol/Tools/ExplainQueryTool.swift index 69d3515294..5b44c14604 100644 --- a/apple/TablePro/Core/MCP/Protocol/Tools/ExplainQueryTool.swift +++ b/apple/TablePro/Core/MCP/Protocol/Tools/ExplainQueryTool.swift @@ -53,7 +53,9 @@ public struct ExplainQueryTool: MCPToolImplementation { of: .object(["type": .string("array"), "items": MCPToolSchema.cell]) ), "plan_text": MCPToolSchema.string(String(localized: "Flattened plan text")), - "status_message": MCPToolSchema.string(String(localized: "Why values are masked, when they are")), + "status_message": MCPToolSchema.string( + String(localized: "Why values are masked, and what happened to the open transaction, when either applies") + ), "is_truncated": MCPToolSchema.boolean( String(localized: "Present and true when the answer's size limit cut plan_text or left the parsed plan or rows out") ), diff --git a/apple/TablePro/Core/SSH/LibSSH2TunnelFactory.swift b/apple/TablePro/Core/SSH/LibSSH2TunnelFactory.swift index d1f5c51706..abdadb8e54 100644 --- a/apple/TablePro/Core/SSH/LibSSH2TunnelFactory.swift +++ b/apple/TablePro/Core/SSH/LibSSH2TunnelFactory.swift @@ -513,6 +513,7 @@ internal enum LibSSH2TunnelFactory { let authenticator = try buildJumpAuthenticator( jumpHost: firstJump.formHop ?? SSHJumpHost(), resolved: firstJump.target, + credentials: credentials, attempt: attempt, timeoutEndpoint: endpoint ) @@ -571,6 +572,7 @@ internal enum LibSSH2TunnelFactory { let authenticator = try buildJumpAuthenticator( jumpHost: resolved.jumps[jumpIndex + 1].formHop ?? SSHJumpHost(), resolved: nextTarget, + credentials: credentials, attempt: attempt, timeoutEndpoint: endpoint ) @@ -755,7 +757,8 @@ internal enum LibSSH2TunnelFactory { attempt: SSHConnectionAttempt? = nil, timeoutEndpoint: ConnectionTimeoutEndpoint? = nil ) throws -> any SSHAuthenticator { - let promptProvider = credentials.keyboardInteractivePromptProvider ?? PromptKeyboardInteractiveProvider( + let promptProvider = keyboardInteractivePromptProvider( + credentials: credentials, attempt: attempt, timeoutEndpoint: timeoutEndpoint ) @@ -827,12 +830,7 @@ internal enum LibSSH2TunnelFactory { promptProvider: promptProvider ), ], - endsChainOn: Set( - AgentSocketOrigin.allCases.map(AuthFailureReason.agentUnavailable) - + AgentSocketOrigin.allCases.map(AuthFailureReason.agentNoIdentities) - + AgentSocketOrigin.allCases.map(AuthFailureReason.agentNoMatchingIdentity) - + [.agentIdentityFileUnreadable, .agentServerClosedConnection] - ) + endsChainOn: agentSuppliedNoFirstFactor ) case .keyboardInteractive: @@ -847,6 +845,24 @@ internal enum LibSSH2TunnelFactory { } } + private static let agentSuppliedNoFirstFactor = Set( + AgentSocketOrigin.allCases.map(AuthFailureReason.agentUnavailable) + + AgentSocketOrigin.allCases.map(AuthFailureReason.agentNoIdentities) + + AgentSocketOrigin.allCases.map(AuthFailureReason.agentNoMatchingIdentity) + + [.agentIdentityFileUnreadable, .agentServerClosedConnection] + ) + + private static func keyboardInteractivePromptProvider( + credentials: SSHTunnelCredentials, + attempt: SSHConnectionAttempt?, + timeoutEndpoint: ConnectionTimeoutEndpoint? + ) -> any KeyboardInteractivePromptProvider { + credentials.keyboardInteractivePromptProvider ?? PromptKeyboardInteractiveProvider( + attempt: attempt, + timeoutEndpoint: timeoutEndpoint + ) + } + private static func effectiveKeyPaths(for resolved: ResolvedSSHTarget) -> [String] { if !resolved.identityFiles.isEmpty { return resolved.identityFiles @@ -980,19 +996,31 @@ internal enum LibSSH2TunnelFactory { } } - private static func buildJumpAuthenticator( + // A hop signs in on its own, so a bastion asking for a code after the key (publickey,keyboard-interactive) + // gets the same second step the SSH host does. A hop has no TOTP secret of its own, so the code is asked for. + internal static func buildJumpAuthenticator( jumpHost: SSHJumpHost, resolved: ResolvedSSHTarget, - attempt: SSHConnectionAttempt?, - timeoutEndpoint: ConnectionTimeoutEndpoint? + credentials: SSHTunnelCredentials, + attempt: SSHConnectionAttempt? = nil, + timeoutEndpoint: ConnectionTimeoutEndpoint? = nil ) throws -> any SSHAuthenticator { + let secondFactor = KeyboardInteractiveAuthenticator( + password: nil, + totpProvider: nil, + promptProvider: keyboardInteractivePromptProvider( + credentials: credentials, + attempt: attempt, + timeoutEndpoint: timeoutEndpoint + ) + ) switch jumpHost.authMethod { case .privateKey: let keyPaths = effectiveKeyPaths(for: resolved) guard !keyPaths.isEmpty else { throw SSHTunnelError.authenticationFailed(reason: .privateKey) } - let authenticators = keyPaths.map { path in + let authenticators: [any SSHAuthenticator] = keyPaths.map { path in KeyFileAuthenticator( keyPath: path, providedPassphrase: nil, @@ -1002,15 +1030,13 @@ internal enum LibSSH2TunnelFactory { timeoutEndpoint: timeoutEndpoint ) } - return authenticators.count == 1 - ? authenticators[0] - : CompositeAuthenticator(authenticators: authenticators) + return CompositeAuthenticator(authenticators: authenticators + [secondFactor]) case .sshAgent where resolved.agentDisabled: let keyPaths = jumpHost.privateKeyPath.isEmpty ? effectiveKeyPaths(for: resolved) : [jumpHost.privateKeyPath] guard !keyPaths.isEmpty else { throw SSHTunnelError.authenticationFailed(reason: .agentDisabledByConfig) } - let authenticators = keyPaths.map { path in + let authenticators: [any SSHAuthenticator] = keyPaths.map { path in KeyFileAuthenticator( keyPath: path, providedPassphrase: nil, @@ -1020,9 +1046,7 @@ internal enum LibSSH2TunnelFactory { timeoutEndpoint: timeoutEndpoint ) } - return authenticators.count == 1 - ? authenticators[0] - : CompositeAuthenticator(authenticators: authenticators) + return CompositeAuthenticator(authenticators: authenticators + [secondFactor]) case .sshAgent: let socketPath: String? = resolved.agentSocketPath.isEmpty ? nil : resolved.agentSocketPath let agent = AgentAuthenticator( @@ -1031,18 +1055,18 @@ internal enum LibSSH2TunnelFactory { identityFiles: resolved.identityFiles, identitiesOnly: resolved.identitiesOnly ) - if !jumpHost.privateKeyPath.isEmpty { - let keyAuth = KeyFileAuthenticator( - keyPath: jumpHost.privateKeyPath, - providedPassphrase: nil, - useKeychain: resolved.useKeychain, - addKeysToAgent: resolved.addKeysToAgent, - attempt: attempt, - timeoutEndpoint: timeoutEndpoint - ) - return CompositeAuthenticator(authenticators: [agent, keyAuth]) + guard !jumpHost.privateKeyPath.isEmpty else { + return CompositeAuthenticator(authenticators: [agent, secondFactor], endsChainOn: agentSuppliedNoFirstFactor) } - return agent + let keyAuth = KeyFileAuthenticator( + keyPath: jumpHost.privateKeyPath, + providedPassphrase: nil, + useKeychain: resolved.useKeychain, + addKeysToAgent: resolved.addKeysToAgent, + attempt: attempt, + timeoutEndpoint: timeoutEndpoint + ) + return CompositeAuthenticator(authenticators: [agent, keyAuth, secondFactor]) } } diff --git a/apple/TablePro/Core/Services/Export/ConnectionBundleExporter.swift b/apple/TablePro/Core/Services/Export/ConnectionBundleExporter.swift index be10ae94da..4e0271fa39 100644 --- a/apple/TablePro/Core/Services/Export/ConnectionBundleExporter.swift +++ b/apple/TablePro/Core/Services/Export/ConnectionBundleExporter.swift @@ -86,6 +86,11 @@ internal struct ConnectionBundleExporter { return settings } + // A teammate's copy drops both on read, so publishing them would only leave a token typed into one in the shared copy. + func teamShareableSettings(for connection: DatabaseConnection) -> ExportableConnection { + portableSettings(for: connection).withoutStartupCommands().withoutTunnelCommand() + } + func groupPath(for connection: DatabaseConnection) -> [String] { let groupsById = Dictionary(groups.loadGroups().map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) var path: [String] = [] @@ -102,9 +107,10 @@ internal struct ConnectionBundleExporter { tags.tags(for: connection.tagIds).map(\.name) } + // The Team Catalog's file, so its settings follow what a team may see. func connectionsOnlyBundle(for connections: [DatabaseConnection]) throws -> ConnectionBundle { try BundleExportAssembler.assemble( - exportInput(for: connections, includesCredentials: false, library: nil), + exportInput(for: connections, includesCredentials: false, library: nil, settings: teamShareableSettings(for:)), options: .connectionsOnly, appVersion: appVersion ) @@ -210,13 +216,14 @@ internal struct ConnectionBundleExporter { private func exportInput( for exported: [DatabaseConnection], includesCredentials: Bool, - library: SavedQueryLibrary? + library: SavedQueryLibrary?, + settings: ((DatabaseConnection) -> ExportableConnection)? = nil ) -> BundleExportInput { BundleExportInput( connections: exported.map { connection in BundleExportInput.Connection( id: connection.id, - settings: portableSettings(for: connection, keepingLocalCredentials: true), + settings: settings?(connection) ?? portableSettings(for: connection, keepingLocalCredentials: true), groupId: connection.groupId, tagIds: connection.tagIds, credentialProfileId: connection.credentialMode.profileId, diff --git a/apple/TablePro/Core/Services/Export/TableTransferService.swift b/apple/TablePro/Core/Services/Export/TableTransferService.swift index ce333de921..9c1f5ee43d 100644 --- a/apple/TablePro/Core/Services/Export/TableTransferService.swift +++ b/apple/TablePro/Core/Services/Export/TableTransferService.swift @@ -267,6 +267,7 @@ final class TableTransferService: ObservableObject { driver: destinationDriver, databaseType: request.destinationType, targetTable: object.name, + targetSchema: request.destinationSchema, columnMapping: mapping, sourceFields: Set(request.sourceColumns[object.name] ?? []), isCancelled: { [flag = cancellationFlag] in flag.isCancelled } diff --git a/apple/TablePro/Core/Storage/CredentialProfileStorage.swift b/apple/TablePro/Core/Storage/CredentialProfileStorage.swift index adad2a60d6..b5c02405f2 100644 --- a/apple/TablePro/Core/Storage/CredentialProfileStorage.swift +++ b/apple/TablePro/Core/Storage/CredentialProfileStorage.swift @@ -183,7 +183,7 @@ final class CredentialProfileStorage { profiles[index] = profile guard saveProfiles(profiles) else { return false } // Best effort: the connect path resolves the username from the profile either way. - if !writeUsernameThrough(profile) { + if !writeUsernameThrough(profile, byUser: true) { Self.logger.error( "Saved credential profile \(profile.id.uuidString, privacy: .public) but could not update the connections linked to it" ) @@ -200,7 +200,7 @@ final class CredentialProfileStorage { var current = profiles.first { $0.id == profile.id } ?? profile current.secureFieldIds = Array(Set(current.secureFieldIds).union(profile.secureFieldIds)).sorted() profiles.removeAll { $0.id == profile.id } - guard unlinkConnections(from: current) else { return false } + guard unlinkConnections(from: current, byUser: true) else { return false } guard saveProfiles(profiles) else { return false } syncTracker.markDeleted(.credentialProfile, id: profile.id.uuidString) @@ -210,7 +210,7 @@ final class CredentialProfileStorage { // connection.username stays filled for a linked connection: the IAM signer, ~/.pgpass, dump flags and sync read it raw. @discardableResult - func writeUsernameThrough(_ profile: CredentialProfile, byUser: Bool = true) -> Bool { + func writeUsernameThrough(_ profile: CredentialProfile, byUser: Bool) -> Bool { let storage = connectionStorageProvider() let linked = Set( storage.loadConnections() @@ -222,8 +222,9 @@ final class CredentialProfileStorage { } } + // `byUser` false (a sync pull) never signs connections.json, which may hold a command nobody here approved. @discardableResult - func unlinkConnections(from profile: CredentialProfile) -> Bool { + func unlinkConnections(from profile: CredentialProfile, byUser: Bool) -> Bool { let storage = connectionStorageProvider() // An unreadable library may hold connections that use this profile, and they would be left pointing at nothing. guard !storage.isLibraryUnreadable else { @@ -249,7 +250,7 @@ final class CredentialProfileStorage { } let carriesSource = storeIsTrusted - let converted = storage.mutateConnections(ids: Set(linked.map { $0.id })) { connection in + let converted = storage.mutateConnections(ids: Set(linked.map { $0.id }), byUser: byUser) { connection in connection.credentialMode = .inline connection.username = profile.username // Every inline password flag is written, or a stale prompt or pgpass flag overrides the password just copied in. diff --git a/apple/TablePro/Core/Storage/SSHProfileStorage.swift b/apple/TablePro/Core/Storage/SSHProfileStorage.swift index 4c77829cba..10dee1f46d 100644 --- a/apple/TablePro/Core/Storage/SSHProfileStorage.swift +++ b/apple/TablePro/Core/Storage/SSHProfileStorage.swift @@ -96,7 +96,7 @@ final class SSHProfileStorage { profiles[index] = profile guard saveProfiles(profiles) else { return false } // Best effort: a connection whose snapshot was not rewritten is resolved against the profile at connect time. - if !refreshLinkedConnections(with: profile) { + if !refreshLinkedConnections(with: profile, byUser: true) { Self.logger.error("Saved SSH profile \(profile.id.uuidString, privacy: .public) but could not update the connections linked to it") } return true @@ -109,7 +109,7 @@ final class SSHProfileStorage { // The stored record, not the caller's copy: unlinking writes its configuration into every linked connection. let current = profiles.first { $0.id == profile.id } ?? profile profiles.removeAll { $0.id == profile.id } - guard unlinkConnections(fromProfile: current) else { return false } + guard unlinkConnections(fromProfile: current, byUser: true) else { return false } guard saveProfiles(profiles) else { return false } syncTracker.markDeleted(.sshProfile, id: profile.id.uuidString) @@ -123,7 +123,7 @@ final class SSHProfileStorage { // A linked connection tunnels through its stored snapshot, so an edited profile has to be written into each one. @discardableResult - func refreshLinkedConnections(with profile: SSHProfile, byUser: Bool = true) -> Bool { + func refreshLinkedConnections(with profile: SSHProfile, byUser: Bool) -> Bool { let storage = connectionStorageProvider() let linked = Set( storage.loadConnections() @@ -144,8 +144,9 @@ final class SSHProfileStorage { } // The tunnel comes from the profile as it stands, never a stale snapshot, or new credentials reach the old server. + // `byUser` false (a sync pull) never signs connections.json, which may hold a command nobody here approved. @discardableResult - func unlinkConnections(fromProfile profile: SSHProfile) -> Bool { + func unlinkConnections(fromProfile profile: SSHProfile, byUser: Bool) -> Bool { let storage = connectionStorageProvider() // An unreadable library may hold connections that use this profile, and they would be left pointing at nothing. guard !storage.isLibraryUnreadable else { @@ -164,7 +165,7 @@ final class SSHProfileStorage { return false } - let converted = storage.mutateConnections(ids: Set(linked.map { $0.id })) { connection in + let converted = storage.mutateConnections(ids: Set(linked.map { $0.id }), byUser: byUser) { connection in let current = profile.applied(to: connection) guard case .profile(_, let config) = current.sshTunnelMode else { return } connection = current diff --git a/apple/TablePro/Core/Sync/Extensions/SyncCoordinator+RemoteDeletions.swift b/apple/TablePro/Core/Sync/Extensions/SyncCoordinator+RemoteDeletions.swift index 5926dc7439..204b6c7de5 100644 --- a/apple/TablePro/Core/Sync/Extensions/SyncCoordinator+RemoteDeletions.swift +++ b/apple/TablePro/Core/Sync/Extensions/SyncCoordinator+RemoteDeletions.swift @@ -153,13 +153,8 @@ extension SyncCoordinator { return true } - /// Unlinking reads a profile's secrets, so it runs while they still exist. Dropping the record - /// alone left every connection using it addressing a profile id that no longer resolved, and - /// left its keychain items with nothing able to name them. - /// - /// Returns false when a conversion could not be persisted, which withholds the pull token: the - /// alternative is acknowledging a delete whose connections still point at the profile, with the - /// conversion lost and no tombstone left to replay it. + // Unlinking reads the profile's secrets, so it runs while they still exist. False withholds the pull token: + // acknowledging the delete would leave connections pointing at the profile with nothing left to replay it. private func applyRemoteSSHProfileDeletions(_ profileIds: Set) -> Bool { guard !profileIds.isEmpty else { return true } @@ -167,7 +162,7 @@ extension SyncCoordinator { let deleted = profiles.filter { profileIds.contains($0.id) } profiles.removeAll { profileIds.contains($0.id) } - for profile in deleted where !services.sshProfileStorage.unlinkConnections(fromProfile: profile) { + for profile in deleted where !services.sshProfileStorage.unlinkConnections(fromProfile: profile, byUser: false) { Self.logger.error( "Kept SSH profile \(profile.id.uuidString, privacy: .public): its connections could not be converted" ) @@ -181,8 +176,7 @@ extension SyncCoordinator { return true } - /// A profile deleted on another Mac hands its credentials to the connections using it here - /// too, so they keep connecting rather than losing the password the link took away. + // A profile deleted on another Mac hands its credentials to the connections using it here, so they keep connecting. private func applyRemoteCredentialProfileDeletions(_ profileIds: Set) -> Bool { guard !profileIds.isEmpty else { return true } @@ -197,7 +191,7 @@ extension SyncCoordinator { let deleted = profiles.filter { profileIds.contains($0.id) } profiles.removeAll { profileIds.contains($0.id) } - for profile in deleted where !services.credentialProfileStorage.unlinkConnections(from: profile) { + for profile in deleted where !services.credentialProfileStorage.unlinkConnections(from: profile, byUser: false) { Self.logger.error( "Kept credential profile \(profile.id.uuidString, privacy: .public): its connections could not be converted" ) diff --git a/apple/TablePro/Core/Sync/SyncRecordMapper.swift b/apple/TablePro/Core/Sync/SyncRecordMapper.swift index 3743973c48..8244d2274e 100644 --- a/apple/TablePro/Core/Sync/SyncRecordMapper.swift +++ b/apple/TablePro/Core/Sync/SyncRecordMapper.swift @@ -482,24 +482,28 @@ struct SyncRecordMapper { static func settingsEdit( category: String, - settingsData: Data, + settingsData local: Data, in zone: CKRecordZone.ID, base: CKRecord? ) -> SyncRecordEdit { - let record = toCKRecord(category: category, settingsData: settingsData, in: zone, base: base?.copy() as? CKRecord) let baseData = base.flatMap(Self.settingsData(from:)) + let settingsData = SyncSettingsDocument.carryingUnreadOptions(of: baseData, into: local, category: category) ?? local + let record = toCKRecord(category: category, settingsData: settingsData, in: zone, base: base?.copy() as? CKRecord) // A base an older build wrote in another key order holds the same options, which is no edit. let baseAsWritten = SyncJSONMerge.sameDocument(baseData, settingsData) ? record : nil let mergesOptions = mergesOptions(of: category) return SyncRecordEdit(AppSettingsSyncField.self, record: record, base: base, baseAsWritten: baseAsWritten) { merged, server in - guard mergesOptions, let document = SyncJSONMerge.document( - base: baseData, - local: settingsData, - server: Self.settingsData(from: server) - ) else { return } - merged.fields(AppSettingsSyncField.self)[.settingsJson] = category == CustomSlashCommandStorage.syncCategory - ? Self.renamingCommandCollisions(in: document) - : document + let serverData = Self.settingsData(from: server) + let fields = merged.fields(AppSettingsSyncField.self) + if mergesOptions, let document = SyncJSONMerge.document(base: baseData, local: settingsData, server: serverData) { + fields[.settingsJson] = category == CustomSlashCommandStorage.syncCategory + ? Self.renamingCommandCollisions(in: document) + : document + } else if fields[.settingsJson] as? Data == settingsData, + let carried = SyncSettingsDocument.carryingUnreadOptions(of: serverData, into: local, category: category) { + // Going up whole, it still keeps the options a newer build wrote on the server. + fields[.settingsJson] = carried + } } } diff --git a/apple/TablePro/Core/Sync/SyncSettingsDocument.swift b/apple/TablePro/Core/Sync/SyncSettingsDocument.swift new file mode 100644 index 0000000000..5917ee837e --- /dev/null +++ b/apple/TablePro/Core/Sync/SyncSettingsDocument.swift @@ -0,0 +1,45 @@ +import Foundation + +// A settings record can hold options a newer build wrote. This build's types drop them on decode, so a push puts +// them back from the record it builds on, or a Mac on an older build resets them on every other Mac. +enum SyncSettingsDocument { + // Nil when `source` cannot be read as this category, so nothing can be told apart in it. + static func carryingUnreadOptions(of source: Data?, into local: Data, category: String) -> Data? { + guard let source, + let sourceObject = object(source), + let readObject = readBack(source, category: category).flatMap(object), + var localObject = object(local) + else { return nil } + let unread = sourceObject.filter { readObject[$0.key] == nil && localObject[$0.key] == nil } + guard !unread.isEmpty else { return local } + localObject.merge(unread) { mine, _ in mine } + return try? JSONSerialization.data(withJSONObject: localObject, options: [.sortedKeys]) + } + + // What this build keeps of a document: decoded with its own type and written again. + private static func readBack(_ data: Data, category: String) -> Data? { + switch category { + case AppSettingsCategory.general: roundTrip(GeneralSettings.self, data) + case AppSettingsCategory.appearance: roundTrip(AppearanceSettings.self, data) + case AppSettingsCategory.editor: roundTrip(EditorSettings.self, data) + case AppSettingsCategory.dataGrid: roundTrip(DataGridSettings.self, data) + case AppSettingsCategory.history: roundTrip(HistorySettings.self, data) + case AppSettingsCategory.tabs: roundTrip(TabSettings.self, data) + case AppSettingsCategory.keyboard: roundTrip(KeyboardSettings.self, data) + case AppSettingsCategory.ai: roundTrip(AISettings.self, data) + case AppSettingsCategory.notifications: roundTrip(NotificationSettings.self, data) + case AppSettingsCategory.formatter: roundTrip(SQLFormatterSettings.self, data) + case AppSettingsCategory.valueColors: roundTrip(ValueColorSettings.self, data) + default: nil + } + } + + private static func roundTrip(_: Settings.Type, _ data: Data) -> Data? { + guard let settings = try? JSONDecoder().decode(Settings.self, from: data) else { return nil } + return try? JSONEncoder().encode(settings) + } + + private static func object(_ data: Data) -> [String: Any]? { + (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + } +} diff --git a/apple/TablePro/Core/Vim/VimEngine+Controls.swift b/apple/TablePro/Core/Vim/VimEngine+Controls.swift index 1c6c0e238d..c67154241a 100644 --- a/apple/TablePro/Core/Vim/VimEngine+Controls.swift +++ b/apple/TablePro/Core/Vim/VimEngine+Controls.swift @@ -139,7 +139,7 @@ extension VimEngine { } let replacement = formatNumber(match.value + delta, hex: match.isHex, hexUppercase: match.hexUppercase) let range = NSRange(location: match.start, length: match.end - match.start) - buffer.replaceCharacters(in: range, with: replacement) + replace(range, with: replacement, in: buffer) let newEnd = match.start + (replacement as NSString).length buffer.setSelectedRange(NSRange(location: max(match.start, newEnd - 1), length: 0)) } diff --git a/apple/TablePro/Core/Vim/VimEngine+InsertReplace.swift b/apple/TablePro/Core/Vim/VimEngine+InsertReplace.swift index 25a07cb2d1..28ca003aff 100644 --- a/apple/TablePro/Core/Vim/VimEngine+InsertReplace.swift +++ b/apple/TablePro/Core/Vim/VimEngine+InsertReplace.swift @@ -69,7 +69,7 @@ extension VimEngine { let overwritten = pos < contentEnd ? buffer.characterRange(at: pos) : NSRange(location: pos, length: 0) let original = overwritten.length > 0 ? buffer.string(in: overwritten) : nil replaceModeEdits.append(VimReplaceModeEdit(offset: pos, original: original, insertedLength: insertedLength)) - buffer.replaceCharacters(in: overwritten, with: typed) + replace(overwritten, with: typed, in: buffer) return true } @@ -79,7 +79,7 @@ extension VimEngine { if let last = replaceModeEdits.last, last.offset + last.insertedLength == pos { replaceModeEdits.removeLast() let inserted = NSRange(location: last.offset, length: last.insertedLength) - buffer.replaceCharacters(in: inserted, with: last.original ?? "") + replace(inserted, with: last.original ?? "", in: buffer) buffer.setSelectedRange(NSRange(location: last.offset, length: 0)) } else { replaceModeEdits.removeAll() @@ -159,7 +159,7 @@ extension VimEngine { func deleteBackwardInInsert(to target: Int, in buffer: VimTextBuffer) { let pos = buffer.selectedRange().location guard pos > target else { return } - buffer.replaceCharacters(in: NSRange(location: target, length: pos - target), with: "") + replace(NSRange(location: target, length: pos - target), with: "", in: buffer) buffer.setSelectedRange(NSRange(location: target, length: 0)) } @@ -175,10 +175,10 @@ extension VimEngine { stripCount += 1 } guard stripCount > 0 else { return } - buffer.replaceCharacters(in: NSRange(location: lineRange.location, length: stripCount), with: "") + replace(NSRange(location: lineRange.location, length: stripCount), with: "", in: buffer) buffer.setSelectedRange(NSRange(location: max(lineRange.location, pos - stripCount), length: 0)) } else { - buffer.replaceCharacters(in: NSRange(location: lineRange.location, length: 0), with: indent) + replace(NSRange(location: lineRange.location, length: 0), with: indent, in: buffer) buffer.setSelectedRange(NSRange(location: pos + indent.count, length: 0)) } } diff --git a/apple/TablePro/Core/Vim/VimEngine+Macros.swift b/apple/TablePro/Core/Vim/VimEngine+Macros.swift index bfbcf57621..e7122aa9d1 100644 --- a/apple/TablePro/Core/Vim/VimEngine+Macros.swift +++ b/apple/TablePro/Core/Vim/VimEngine+Macros.swift @@ -19,6 +19,8 @@ extension VimEngine { return } lastInvokedMacro = target + // `.` repeats the last change the macro made, not the macro. + changeDraft = nil let count = max(1, pendingMacroCount) pendingMacroCount = 1 for _ in 0.. 0 || digit > 0 { + if isCountKey(char), let digit = char.wholeNumberValue { if countPrefix <= 99_999 { countPrefix = countPrefix * 10 + digit } return true } @@ -37,6 +37,14 @@ extension VimEngine { || pendingTextObject || pendingMacroTarget != nil || pendingBracket != nil } + // A digit that adds to the count, not one that names a register, a character or the `0` motion. + func isCountKey(_ char: Character) -> Bool { + guard !pendingRegisterSelect, !takesCharacterArgument, char.isASCII, let digit = char.wholeNumberValue else { + return false + } + return countPrefix > 0 || digit > 0 + } + private func processNormalCommand(_ char: Character, shift: Bool, in buffer: VimTextBuffer) -> Bool { // swiftlint:disable:this function_body_length if let req = pendingFindChar { pendingFindChar = nil @@ -115,12 +123,7 @@ extension VimEngine { executeMotion(in: buffer) { self.moveRight(count, in: buffer) } return true case "w": - let count = consumeCount() - let op = pendingOperator - wordMotion(count, bigWord: false, in: buffer) - if let op { - recordDot(.operatorWithMotion(op: op, motion: "w", shift: false, count: count)) - } + wordMotion(consumeCount(), bigWord: false, in: buffer) return true case "b" where buffer.selectedRange().location == 0, "B" where buffer.selectedRange().location == 0: // Nothing before the start of the text, so the motion fails and an operator does nothing. @@ -236,7 +239,7 @@ extension VimEngine { let lineEnd = lineRange.location + lineRange.length let lineEndsWithNewline = lineEnd > lineRange.location && buffer.character(at: lineEnd - 1) == 0x0A - buffer.replaceCharacters(in: NSRange(location: lineEnd, length: 0), with: "\n") + replace(NSRange(location: lineEnd, length: 0), with: "\n", in: buffer) let cursorPos = lineEndsWithNewline ? lineEnd : lineEnd + 1 buffer.setSelectedRange(NSRange(location: cursorPos, length: 0)) setMode(.insert) @@ -245,7 +248,7 @@ extension VimEngine { countPrefix = 0 let pos = buffer.selectedRange().location let lineRange = buffer.lineRange(forOffset: pos) - buffer.replaceCharacters(in: NSRange(location: lineRange.location, length: 0), with: "\n") + replace(NSRange(location: lineRange.location, length: 0), with: "\n", in: buffer) buffer.setSelectedRange(NSRange(location: lineRange.location, length: 0)) setMode(.insert) return true @@ -432,8 +435,7 @@ extension VimEngine { return true case ".": - let count = consumeCount() - replayLastDot(count: count, in: buffer) + repeatLastChange(count: countPrefix > 0 ? consumeCount() : nil) return true case "(", ")": @@ -508,9 +510,7 @@ extension VimEngine { return true case "x": - let count = consumeCount() - deleteCharUnderCursor(count, in: buffer) - recordDot(.deleteCharForward(count: count)) + deleteCharUnderCursor(consumeCount(), in: buffer) return true default: diff --git a/apple/TablePro/Core/Vim/VimEngine+Operators.swift b/apple/TablePro/Core/Vim/VimEngine+Operators.swift index 92e0c30f17..b215cd61f4 100644 --- a/apple/TablePro/Core/Vim/VimEngine+Operators.swift +++ b/apple/TablePro/Core/Vim/VimEngine+Operators.swift @@ -95,7 +95,7 @@ extension VimEngine { case .delete: let text = buffer.string(in: range) writeToActiveRegister(text: text, linewise: linewise, asDelete: true) - buffer.replaceCharacters(in: range, with: "") + replace(range, with: "", in: buffer) let landing = linewise ? firstNonBlankOffset(from: range.location, in: buffer) : range.location buffer.setSelectedRange(NSRange(location: clampToContentPosition(landing, in: buffer), length: 0)) case .yank: @@ -109,20 +109,20 @@ extension VimEngine { let keepsLineBreak = linewise && NSMaxRange(range) <= buffer.length && range.length > 0 && buffer.character(at: NSMaxRange(range) - 1) == 0x0A let deleted = keepsLineBreak ? NSRange(location: range.location, length: range.length - 1) : range - buffer.replaceCharacters(in: deleted, with: "") + replace(deleted, with: "", in: buffer) buffer.setSelectedRange(NSRange(location: range.location, length: 0)) setMode(.insert) case .lowercase: let transformed = buffer.string(in: range).lowercased() - buffer.replaceCharacters(in: range, with: transformed) + replace(range, with: transformed, in: buffer) buffer.setSelectedRange(NSRange(location: range.location, length: 0)) case .uppercase: let transformed = buffer.string(in: range).uppercased() - buffer.replaceCharacters(in: range, with: transformed) + replace(range, with: transformed, in: buffer) buffer.setSelectedRange(NSRange(location: range.location, length: 0)) case .toggleCase: let transformed = toggleCaseTransform(buffer.string(in: range)) - buffer.replaceCharacters(in: range, with: transformed) + replace(range, with: transformed, in: buffer) buffer.setSelectedRange(NSRange(location: range.location, length: 0)) case .indent: applyIndent(in: range, outdent: false, in: buffer) @@ -165,7 +165,7 @@ extension VimEngine { } return indent + line }.joined() - buffer.replaceCharacters(in: range, with: transformed) + replace(range, with: transformed, in: buffer) let firstNonBlank = firstNonBlankOffset(from: range.location, in: buffer) buffer.setSelectedRange(NSRange(location: firstNonBlank, length: 0)) } @@ -182,7 +182,7 @@ extension VimEngine { } let deleteRange = NSRange(location: startRange.location, length: endOffset - startRange.location) writeToActiveRegister(text: buffer.string(in: deleteRange), linewise: true, asDelete: true) - buffer.replaceCharacters(in: deleteRange, with: "") + replace(deleteRange, with: "", in: buffer) let newPos = min(startRange.location, max(0, buffer.length - 1)) if buffer.length > 0 { buffer.setSelectedRange(NSRange(location: newPos, length: 0)) @@ -219,7 +219,7 @@ extension VimEngine { && buffer.character(at: endOffset - 1) == 0x0A ? endOffset - 1 : endOffset let deleteRange = NSRange(location: startRange.location, length: deleteEnd - startRange.location) writeToActiveRegister(text: buffer.string(in: deleteRange), linewise: true, asDelete: true) - buffer.replaceCharacters(in: deleteRange, with: "") + replace(deleteRange, with: "", in: buffer) buffer.setSelectedRange(NSRange(location: startRange.location, length: 0)) setMode(.insert) } @@ -244,7 +244,7 @@ extension VimEngine { text = "\n" + text.dropLast() firstLine = insertPos + 1 } - buffer.replaceCharacters(in: NSRange(location: insertPos, length: 0), with: text) + replace(NSRange(location: insertPos, length: 0), with: text, in: buffer) insertPos = firstLine buffer.setSelectedRange(NSRange(location: firstNonBlankOffset(from: insertPos, in: buffer), length: 0)) return @@ -253,7 +253,7 @@ extension VimEngine { let text = String(repeating: source.text, count: copies) // On an empty line the caret is on the line break, and `p` puts the text before it. let insertPos = after && pos < contentEnd(ofLineAt: pos, in: buffer) ? characterEnd(at: pos, in: buffer) : pos - buffer.replaceCharacters(in: NSRange(location: insertPos, length: 0), with: text) + replace(NSRange(location: insertPos, length: 0), with: text, in: buffer) let length = (text as NSString).length // Text over several lines leaves the cursor at its start, a single line on its last character. let landing = text.contains("\n") ? insertPos : characterStart(at: insertPos + length - 1, in: buffer) @@ -272,7 +272,7 @@ extension VimEngine { let range = NSRange(location: pos, length: end - pos) writeToActiveRegister(text: buffer.string(in: range), linewise: false, asDelete: true) noteEdit(at: pos, in: buffer) - buffer.replaceCharacters(in: range, with: "") + replace(range, with: "", in: buffer) let newContentEnd = contentEnd - range.length if pos >= newContentEnd && newContentEnd > lineRange.location { buffer.setSelectedRange(NSRange(location: characterStart(at: newContentEnd - 1, in: buffer), length: 0)) @@ -288,7 +288,7 @@ extension VimEngine { guard start < pos else { return } let range = NSRange(location: start, length: pos - start) writeToActiveRegister(text: buffer.string(in: range), linewise: false, asDelete: true) - buffer.replaceCharacters(in: range, with: "") + replace(range, with: "", in: buffer) buffer.setSelectedRange(NSRange(location: start, length: 0)) } @@ -303,7 +303,7 @@ extension VimEngine { guard end > pos else { setMode(.insert); return } let range = NSRange(location: pos, length: end - pos) writeToActiveRegister(text: buffer.string(in: range), linewise: false, asDelete: true) - buffer.replaceCharacters(in: range, with: "") + replace(range, with: "", in: buffer) buffer.setSelectedRange(NSRange(location: pos, length: 0)) setMode(.insert) } @@ -319,7 +319,7 @@ extension VimEngine { guard end > pos else { return } let range = NSRange(location: pos, length: end - pos) let transformed = toggleCaseTransform(buffer.string(in: range)) - buffer.replaceCharacters(in: range, with: transformed) + replace(range, with: transformed, in: buffer) // A case change can change the length, as ß becomes SS. let newEnd = pos + (transformed as NSString).length let newContentEnd = contentEnd + newEnd - end @@ -351,7 +351,7 @@ extension VimEngine { case .toggleCase: transformed = toggleCaseTransform(original) default: return } - buffer.replaceCharacters(in: range, with: transformed) + replace(range, with: transformed, in: buffer) buffer.setSelectedRange(NSRange(location: startRange.location, length: 0)) } @@ -425,7 +425,7 @@ extension VimEngine { && !currentLineIsEmpty let replacementRange = NSRange(location: newlineOffset, length: stripStart - newlineOffset) let replacement = shouldInsertSpace ? " " : "" - buffer.replaceCharacters(in: replacementRange, with: replacement) + replace(replacementRange, with: replacement, in: buffer) let clamped = min(newlineOffset, max(0, buffer.length - 1)) buffer.setSelectedRange(NSRange(location: clamped, length: 0)) return true @@ -447,7 +447,7 @@ extension VimEngine { } let unit = char == "\r" || char == "\n" ? "\n" : String(char) let replacement = String(repeating: unit, count: count) - buffer.replaceCharacters(in: NSRange(location: pos, length: end - pos), with: replacement) + replace(NSRange(location: pos, length: end - pos), with: replacement, in: buffer) let lastStart = pos + (replacement as NSString).length - (unit as NSString).length buffer.setSelectedRange(NSRange(location: lastStart, length: 0)) return true diff --git a/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift b/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift index c09092fe22..78ad81ffdf 100644 --- a/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift +++ b/apple/TablePro/Core/Vim/VimEngine+RegistersMarks.swift @@ -167,6 +167,7 @@ extension VimEngine { // redo that reverses it puts them back, as Vim's undo restores its marks. Typing the same text back is not undo, // and an undo reverses only edits, a redo only undos. func textWillChange(in range: NSRange, with replacement: String, source: VimEditSource = .edit) { + noteInsertedText(in: range, with: replacement) guard let buffer else { return } let hasPositions = !marks.isEmpty || lastJumpOrigin != nil || lastInsertOffset != nil || lastVisualStart != nil || lastVisualEnd != nil diff --git a/apple/TablePro/Core/Vim/VimEngine+Repeat.swift b/apple/TablePro/Core/Vim/VimEngine+Repeat.swift index ebfbc9d7dc..ad482c7c93 100644 --- a/apple/TablePro/Core/Vim/VimEngine+Repeat.swift +++ b/apple/TablePro/Core/Vim/VimEngine+Repeat.swift @@ -16,38 +16,133 @@ extension VimEngine { } } - func recordDot(_ kind: VimDotKind) { - lastDotKind = kind - } - - func replayLastDot(count: Int, in buffer: VimTextBuffer) { - guard let kind = lastDotKind else { return } - for _ in 0.. VimInsertStep? { + guard let draft = changeDraft, let range = draft.insertedRange else { return nil } + changeDraft?.insertedRange = nil + changeDraft?.deletedBeforeInsert = 0 + let text = buffer?.string(in: range) ?? "" + guard draft.deletedBeforeInsert > 0 || !text.isEmpty else { return nil } + return .typed(deleting: draft.deletedBeforeInsert, text: text) + } + + func changeKeyDidProcess() { + guard !isRepeatingChange, let draft = changeDraft else { return } + switch mode { + case .insert: + guard draft.insertedRange == nil else { return } + changeDraft?.changesText = true + changeDraft?.insertedRange = NSRange(location: buffer?.selectedRange().location ?? 0, length: 0) + case .replace: + changeDraft?.changesText = true + case .normal: + guard !hasPendingCommand, countPrefix == 0, operatorCount == 0, selectedRegister == nil else { return } + let typed = takeTypedStep() + changeDraft = nil + guard draft.changesText else { return } + let enteredInsert = draft.insertedRange != nil || !draft.insertSteps.isEmpty + let steps = draft.insertSteps + [typed].compactMap { $0 } + lastChange = VimChange(keys: draft.keys, insertSteps: enteredInsert ? steps : nil) + case .visual, .commandLine: + return + } + } + + // Keeps the range of the text typed since Insert mode began in step with every edit, typed or not. + func noteInsertedText(in range: NSRange, with replacement: String) { + guard mode == .insert, let inserted = changeDraft?.insertedRange else { return } + let replacementLength = (replacement as NSString).length + let delta = replacementLength - range.length + if NSMaxRange(range) < inserted.location { + changeDraft?.insertedRange = NSRange(location: inserted.location + delta, length: inserted.length) + } else if range.location > NSMaxRange(inserted) { + // Typing somewhere else starts the insert over there, as moving the cursor in Insert mode does in Vim. + changeDraft?.insertSteps = [] + changeDraft?.deletedBeforeInsert = 0 + changeDraft?.insertedRange = NSRange(location: range.location, length: replacementLength) + } else { + // Backspace past where the typing began deletes text the repeat has to delete too. + let deletedBefore = inserted.location - range.location - replacementLength + if deletedBefore > 0, let buffer { + let deleted = buffer.string(in: NSRange(location: range.location + replacementLength, length: deletedBefore)) + changeDraft?.deletedBeforeInsert += deleted.count + } + let start = range.location < inserted.location + ? min(inserted.location, range.location + replacementLength) + : inserted.location + let end = NSMaxRange(range) >= NSMaxRange(inserted) + ? range.location + replacementLength + : NSMaxRange(inserted) + delta + changeDraft?.insertedRange = NSRange(location: start, length: max(0, end - start)) + } + } + + // A count given to `.` replaces the change's own, and the change keeps it, as in Vim. + func repeatLastChange(count: Int?) { + changeDraft = nil + guard !isRepeatingChange, var change = lastChange else { return } + if let count { + change.keys = String(count).map { VimChangeKey(character: $0, shift: false, isCount: true) } + + change.keys.filter { !$0.isCount } + lastChange = change + } + let recording = macroRecording + macroRecording = nil + isRepeatingChange = true + defer { + isRepeatingChange = false + macroRecording = recording + } + for key in change.keys { + _ = process(key.character, shift: key.shift) + } + if let buffer { + for step in change.insertSteps ?? [] where mode == .insert { + switch step { + case .typed(let deleting, let text): + deleteBeforeCaret(deleting, in: buffer) + if !text.isEmpty { + replace(NSRange(location: buffer.selectedRange().location, length: 0), with: text, in: buffer) + } + case .key(let key): + _ = process(key, shift: false) } - case .toggleCase(let original): - toggleCaseUnderCursor(original, in: buffer) - case .joinLines(let withSpace, let original): - joinLines(original, withSpace: withSpace, in: buffer) - case .replaceChar(let ch, _): - pendingReplaceChar = true - _ = executeReplaceChar(ch, in: buffer) } } + if mode != .normal { + _ = process("\u{1B}", shift: false) + } + } + + private func deleteBeforeCaret(_ count: Int, in buffer: VimTextBuffer) { + let caret = buffer.selectedRange().location + let start = characterOffset(before: caret, count: count, limit: 0, in: buffer) + guard start < caret else { return } + replace(NSRange(location: start, length: caret - start), with: "", in: buffer) } } diff --git a/apple/TablePro/Core/Vim/VimEngine+VisualMode.swift b/apple/TablePro/Core/Vim/VimEngine+VisualMode.swift index 758de77f87..5a7459faf2 100644 --- a/apple/TablePro/Core/Vim/VimEngine+VisualMode.swift +++ b/apple/TablePro/Core/Vim/VimEngine+VisualMode.swift @@ -151,7 +151,7 @@ extension VimEngine { recordVisualSelection(linewise: isLinewise, in: buffer) if sel.length > 0 { writeToActiveRegister(text: buffer.string(in: sel), linewise: isLinewise, asDelete: true) - buffer.replaceCharacters(in: sel, with: "") + replace(sel, with: "", in: buffer) } setMode(.normal) return true @@ -175,10 +175,10 @@ extension VimEngine { && sel.location + sel.length - 1 < buffer.length && buffer.character(at: sel.location + sel.length - 1) == 0x0A ? NSRange(location: sel.location, length: sel.length - 1) : sel - buffer.replaceCharacters(in: trimmed, with: "") + replace(trimmed, with: "", in: buffer) buffer.setSelectedRange(NSRange(location: sel.location, length: 0)) } else { - buffer.replaceCharacters(in: sel, with: "") + replace(sel, with: "", in: buffer) } } setMode(.insert) @@ -261,7 +261,7 @@ extension VimEngine { case .toggleCase: transformed = toggleCaseTransform(original) default: return } - buffer.replaceCharacters(in: sel, with: transformed) + replace(sel, with: transformed, in: buffer) buffer.setSelectedRange(NSRange(location: sel.location, length: 0)) setMode(.normal) } @@ -280,7 +280,7 @@ extension VimEngine { } offset = characterEnd(at: offset, in: buffer) } - buffer.replaceCharacters(in: sel, with: replacement) + replace(sel, with: replacement, in: buffer) buffer.setSelectedRange(NSRange(location: sel.location, length: 0)) setMode(.normal) } @@ -291,7 +291,7 @@ extension VimEngine { let text = activePasteRegister().text guard sel.length > 0 else { setMode(.normal); return } let replaced = buffer.string(in: sel) - buffer.replaceCharacters(in: sel, with: text) + replace(sel, with: text, in: buffer) if !keepingRegister { writeToActiveRegister(text: replaced, linewise: linewise, asDelete: true) } diff --git a/apple/TablePro/Core/Vim/VimEngine.swift b/apple/TablePro/Core/Vim/VimEngine.swift index bbc486345a..65479de8fe 100644 --- a/apple/TablePro/Core/Vim/VimEngine.swift +++ b/apple/TablePro/Core/Vim/VimEngine.swift @@ -28,14 +28,32 @@ struct VimLastFindChar { let till: Bool } -enum VimDotKind { - case deleteCharForward(count: Int) - case deleteCharBackward(count: Int) - case operatorWithMotion(op: VimOperator, motion: Character, shift: Bool, count: Int) - case operatorDoubled(op: VimOperator, count: Int) - case toggleCase(count: Int) - case joinLines(withSpace: Bool, count: Int) - case replaceChar(char: Character, count: Int) +struct VimChangeKey { + let character: Character + let shift: Bool + let isCount: Bool +} + +enum VimInsertStep { + // What the text view did: characters deleted before the caret, then the text typed. + case typed(deleting: Int, text: String) + // A key the engine handles in Insert mode, such as Ctrl-W, which Vim replays as the key. + case key(Character) +} + +// `:help .`: the keys of the last command that changed the text, and what it did in Insert mode if it went on there. +struct VimChange { + var keys: [VimChangeKey] + var insertSteps: [VimInsertStep]? +} + +struct VimChangeDraft { + var keys: [VimChangeKey] = [] + var changesText = false + var insertSteps: [VimInsertStep] = [] + // Where the text typed since Insert mode began, or since the last engine key, sits, kept in step with every edit. + var insertedRange: NSRange? + var deletedBeforeInsert = 0 } // `:help exclusive`, `:help inclusive`, `:help linewise`. @@ -85,7 +103,9 @@ final class VimEngine { var pendingBracket: VimBracketPending? var selectedRegister: Character? var lastFindChar: VimLastFindChar? - var lastDotKind: VimDotKind? + var lastChange: VimChange? + var changeDraft: VimChangeDraft? + var isRepeatingChange = false var marks: [Character: Int] = [:] var namedRegisters: [Character: VimRegister] = [:] var numberedRegisters: [VimRegister] = Array(repeating: VimRegister(), count: 10) @@ -122,6 +142,7 @@ final class VimEngine { func process(_ char: Character, shift: Bool) -> Bool { let recordingTarget = macroRecording + changeKeyWillProcess(char, shift: shift) let consumed: Bool switch mode { case .normal: @@ -140,6 +161,7 @@ final class VimEngine { if let target = recordingTarget, macroRecording == target { macroBuffers[target, default: []].append((char, shift)) } + changeKeyDidProcess() if !mode.isVisual, let buffer { cursorOffset = buffer.selectedRange().location } @@ -157,10 +179,12 @@ final class VimEngine { replaceModeEdits.removeAll() editsOnCurrentLine = 0 lastEditedLine = nil + changeDraft = nil } func reset() { cancelPendingCommand() + changeDraft = nil mode = .normal } diff --git a/apple/TablePro/Core/Vim/VimTextBufferAdapter.swift b/apple/TablePro/Core/Vim/VimTextBufferAdapter.swift index 99ec98c957..34e225a93b 100644 --- a/apple/TablePro/Core/Vim/VimTextBufferAdapter.swift +++ b/apple/TablePro/Core/Vim/VimTextBufferAdapter.swift @@ -1,10 +1,13 @@ import AppKit import Foundation +import TableProEditorKit import TableProTextEngine @MainActor final class VimTextBufferAdapter: VimTextBuffer { private weak var textView: TextView? + // The editor runs its typing filters and completion triggers on every edit it does not hear is a command. + private weak var controller: TextViewController? private struct LineStorageTrust { weak var storage: NSTextStorage? @@ -18,6 +21,11 @@ final class VimTextBufferAdapter: VimTextBuffer { self.textView = textView } + init(controller: TextViewController) { + self.controller = controller + self.textView = controller.textView + } + private var text: NSString? { textView?.textStorage?.mutableString } @@ -138,8 +146,11 @@ final class VimTextBufferAdapter: VimTextBuffer { } func replaceCharacters(in range: NSRange, with string: String) { - guard let textView else { return } - textView.replaceCharacters(in: range, with: string) + if let controller { + controller.replaceCharactersUnfiltered(in: range, with: string) + } else { + textView?.replaceCharacters(in: range, with: string) + } } func undo() { diff --git a/apple/TablePro/Models/UI/MultiRowEditState.swift b/apple/TablePro/Models/UI/MultiRowEditState.swift index 2842465463..51ccb3bb79 100644 --- a/apple/TablePro/Models/UI/MultiRowEditState.swift +++ b/apple/TablePro/Models/UI/MultiRowEditState.swift @@ -106,6 +106,22 @@ struct InspectorFieldEdit: Equatable { var isExpression = false } +// RowIDs are positions a re-run or a sort hands to other records, so a value window also holds each row as it was read. +struct InspectorDetachedTarget: Equatable { + let tabId: UUID + let columnIndex: Int + let columnName: String + let rowIDs: [RowID] + let rowsAsRead: [[PluginCellValue]] +} + +@MainActor +protocol InspectorDetachedStaging: AnyObject { + // Nil once the tab cannot take an edit, or a row is gone or deleted. + func holdInspectorRows(tabId: UUID, columnIndex: Int, rowIDs: [RowID]) -> InspectorDetachedTarget? + func stageDetachedInspectorEdit(_ text: String, to target: InspectorDetachedTarget) +} + @MainActor final class MultiRowEditState: ObservableObject { @Published var fields: [FieldEditState] = [] @@ -124,11 +140,12 @@ final class MultiRowEditState: ObservableObject { @Published var onFieldRemoved: ((Int, [RowID]) -> Void)? - // A value window outliving its selection names its rows, since its fields are gone; the flag says the value is SQL. - @Published var onDetachedFieldChanged: ((Int, PluginCellValue, [RowID], Bool) -> Void)? + // Kept while another tab or no editable row is selected: a value window writes to the tab it opened from. + weak var detachedStager: (any InspectorDetachedStaging)? // The rows an edit is staged against, captured when the selection was configured, never a display position. @Published private(set) var rowIDs: [RowID] = [] + private(set) var tabId: UUID? @Published private(set) var allRows: [[String?]] = [] // Per row of allRows: the columns it has no field for. @@ -140,7 +157,6 @@ final class MultiRowEditState: ObservableObject { @Published private(set) var columnTypes: [ColumnType] = [] // By column, not editor id: every selection change reissues those. Cleared when the columns change. @Published private(set) var expandedColumn: Int? - private var nonNullableColumns: Set = [] // Nil and .none offer no Set Value command and promote nothing. private(set) var databaseType: DatabaseType? @@ -162,6 +178,7 @@ final class MultiRowEditState: ObservableObject { } func configure( + tabId: UUID? = nil, rowIDs: [RowID], allRows: [[String?]], absentCells: [Set] = [], @@ -182,8 +199,9 @@ final class MultiRowEditState: ObservableObject { cellWriter: CellWriterSupport = .none ) { let columnsChanged = self.columns != columns - let selectionChanged = self.rowIDs != rowIDs + let selectionChanged = self.rowIDs != rowIDs || self.tabId != tabId + self.tabId = tabId self.rowIDs = rowIDs self.allRows = allRows self.absentCells = absentCells @@ -191,7 +209,6 @@ final class MultiRowEditState: ObservableObject { self.expressionCells = expressionCells self.columns = columns self.columnTypes = columnTypes - self.nonNullableColumns = nonNullableColumns self.databaseType = databaseType if columnsChanged { expandedColumn = nil } self.cellWriter = cellWriter @@ -457,20 +474,24 @@ final class MultiRowEditState: ObservableObject { Set(rowIDs.indices.filter { expressionCells[safe: $0]?.contains(index) == true }.map { rowIDs[$0] }) } - // Once the selection has moved, the value goes to the rows the window was opened for, not to what is selected now. - func updateDetachedField(columnIndex: Int, rowIDs: [RowID], value: String?) { - guard !rowIDs.isEmpty else { return } - if self.rowIDs == rowIDs, fields.indices.contains(columnIndex) { - updateField(at: columnIndex, value: value) - return - } - if let value, let sql = typedExpression(value, columnType: columnTypes[safe: columnIndex]) { - onDetachedFieldChanged?(columnIndex, .text(sql), rowIDs, true) - return + func holdDetachedField(columnIndex: Int) -> InspectorDetachedTarget? { + guard let tabId, !rowIDs.isEmpty, columns.indices.contains(columnIndex) else { return nil } + return detachedStager?.holdInspectorRows(tabId: tabId, columnIndex: columnIndex, rowIDs: rowIDs) + } + + // The window writes to the tab and records it opened on, whatever is selected now. False once those records are + // gone, deleted or replaced, and the window closes. + func commitDetachedField(_ value: String, to target: InspectorDetachedTarget) -> Bool { + guard let stager = detachedStager, + stager.holdInspectorRows(tabId: target.tabId, columnIndex: target.columnIndex, rowIDs: target.rowIDs) == target + else { return false } + if tabId == target.tabId, rowIDs == target.rowIDs, columns[safe: target.columnIndex] == target.columnName, + fields.indices.contains(target.columnIndex) { + updateField(at: target.columnIndex, value: value) + } else { + stager.stageDetachedInspectorEdit(value, to: target) } - let staged = PluginCellValue.entered(value, columnType: columnTypes[safe: columnIndex]) - if staged.isNull, columns[safe: columnIndex].map(nonNullableColumns.contains) == true { return } - onDetachedFieldChanged?(columnIndex, staged, rowIDs, false) + return true } private static func resolvePendingValue(_ value: String?, original: String?, isJson: Bool) -> String? { @@ -608,7 +629,8 @@ final class MultiRowEditState: ObservableObject { onFieldValuesChanged = nil onFieldReverted = nil onFieldRemoved = nil - onDetachedFieldChanged = nil + detachedStager = nil + tabId = nil rowIDs = [] allRows = [] absentCells = [] @@ -616,7 +638,6 @@ final class MultiRowEditState: ObservableObject { expressionCells = [] columns = [] columnTypes = [] - nonNullableColumns = [] expandedColumn = nil databaseType = nil cellWriter = .none diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 0e7bc22986..ae214fc738 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -7503,6 +7503,9 @@ }, "%1$@ is at %2$@ of the largest value %3$@ holds." : { + }, + "%1$@ is compared but not scripted, because its definition was read from %2$@ and can name that schema rather than %3$@." : { + }, "%1$@ is covered by %2$@." : { @@ -10780,6 +10783,9 @@ } } } + }, + "%d statements failed. What already ran is pending in the transaction on this connection." : { + }, "%d statements failed. What already ran stays applied. Compare again to see where the target stands." : { "localizations" : { @@ -194393,6 +194399,9 @@ }, "The descriptor set names an unknown field type %llu." : { + }, + "The destination changed while the transfer started. Check it and transfer again." : { + }, "The destination has no table named %@" : { "localizations" : { @@ -198556,6 +198565,9 @@ }, "The run button sits in the gutter, which needs line numbers." : { + }, + "The run stopped, but the transaction could not be rolled back: %@. Compare again to see where the target stands." : { + }, "The run was rolled back, but %@ cannot roll back, so the rows already written there stay. Compare again to see where the target stands." : { "localizations" : { @@ -203786,6 +203798,9 @@ "This connection cannot read its catalog for an export." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "This connection cannot run against database %1$@, only its own: %2$@. Leave database out or pass %2$@." : { + }, "This connection cannot send statements with bound values." : { "extractionState" : "manual", @@ -203893,6 +203908,9 @@ } } } + }, + "This connection has no schema to switch to, so it cannot run against schema %@. Leave schema out." : { + }, "This connection has no tunnel command to run." : { "localizations" : { @@ -209267,6 +209285,12 @@ } } } + }, + "This sync ran inside the transaction already open on this connection, which can no longer be committed. Roll it back." : { + + }, + "This sync ran inside the transaction already open on this connection. Commit it to keep the changes, or roll it back to discard them." : { + }, "This Tab" : { @@ -224643,6 +224667,9 @@ } } } + }, + "Why values are masked, and what happened to the open transaction, when either applies" : { + }, "Why values are masked, when they are" : { diff --git a/apple/TablePro/ViewModels/AIChatViewModel+Streaming.swift b/apple/TablePro/ViewModels/AIChatViewModel+Streaming.swift index 7f17df24e1..5367794023 100644 --- a/apple/TablePro/ViewModels/AIChatViewModel+Streaming.swift +++ b/apple/TablePro/ViewModels/AIChatViewModel+Streaming.swift @@ -738,7 +738,20 @@ extension AIChatViewModel { explicitlyApproved: Set = [], registry: ChatToolRegistry? = nil ) async -> [ToolResultBlock] { - await withTaskGroup(of: (Int, ToolResultBlock).self) { group in + let onlyReads = await MainActor.run { + let activeRegistry = registry ?? ChatToolRegistry.shared + return blocks.allSatisfy { activeRegistry.onlyReads(toolName: $0.name) } + } + // Writes run in the order proposed and approved: an INSERT must not reach the driver before its CREATE TABLE. + guard onlyReads else { + var results: [ToolResultBlock] = [] + for block in blocks { + let blockContext = context.carrying(approvalWasExplicit: explicitlyApproved.contains(block.id)) + results.append(await runToolUse(block, scope: scope, context: blockContext, registry: registry)) + } + return results + } + return await withTaskGroup(of: (Int, ToolResultBlock).self) { group in for (index, block) in blocks.enumerated() { let blockContext = context.carrying( approvalWasExplicit: explicitlyApproved.contains(block.id) diff --git a/apple/TablePro/ViewModels/AIChatViewModel.swift b/apple/TablePro/ViewModels/AIChatViewModel.swift index 058dc3c544..01dda40b29 100644 --- a/apple/TablePro/ViewModels/AIChatViewModel.swift +++ b/apple/TablePro/ViewModels/AIChatViewModel.swift @@ -614,10 +614,19 @@ final class AIChatViewModel: ObservableObject { if messages.count > Self.maxMessageCount { messages.removeFirst(messages.count - Self.maxMessageCount) } - while messages.first?.role == .assistant { + // Cut between rounds: a tool result whose call was cut away makes providers refuse the whole request. + while let first = messages.first, !Self.opensRound(first) { messages.removeFirst() } } + + private static func opensRound(_ turn: ChatTurn) -> Bool { + guard turn.role == .user else { return false } + return !turn.blocks.contains { block in + if case .toolResult = block.kind { return true } + return false + } + } } // A change to any of these means another server, so the list on hand no longer describes it. diff --git a/apple/TablePro/ViewModels/ERDiagramViewModel+Editing.swift b/apple/TablePro/ViewModels/ERDiagramViewModel+Editing.swift index 508bdbe2fe..fc735a9c3a 100644 --- a/apple/TablePro/ViewModels/ERDiagramViewModel+Editing.swift +++ b/apple/TablePro/ViewModels/ERDiagramViewModel+Editing.swift @@ -405,8 +405,8 @@ extension ERDiagramViewModel { let kind = kind(of: table) coordinator?.openTableTab( table, - schema: schemaName, - database: databaseName, + schema: scope?.schema ?? schemaName, + database: scope?.database ?? databaseName, showStructure: showStructure, isView: !kind.allowsRowEditing, objectType: kind, diff --git a/apple/TablePro/ViewModels/ERDiagramViewModel.swift b/apple/TablePro/ViewModels/ERDiagramViewModel.swift index 75b68cfa37..c10252afa7 100644 --- a/apple/TablePro/ViewModels/ERDiagramViewModel.swift +++ b/apple/TablePro/ViewModels/ERDiagramViewModel.swift @@ -16,20 +16,17 @@ final class ERDiagramViewModel: ObservableObject { let schemaKey: String let schemaName: String? - /// The diagram is bound to the database and the schema its tab was opened on, so moving - /// the sidebar to another database or schema cannot repoint an open diagram. + // Fixed at the first load: with no schema of its own, a re-resolved scope followed the sidebar's browse schema. + private var loadedScope: DatabaseScope? + var scope: DatabaseScope? { - services.databaseManager.resolvedScope(database: databaseName, schema: schemaName, for: connectionId) + loadedScope + ?? services.databaseManager.resolvedScope(database: databaseName, schema: schemaName, for: connectionId) } nonisolated private static let noSchemaMarker = "default" - /// `schemaKey` is the diagram's identity, written as `database.schema` with - /// `noSchemaMarker` standing in for an engine that has no schemas. It is also the only - /// record of the schema a diagram tab was opened on, because `addERDiagramTab` writes a - /// database into the tab's table context but never a schema. Stripping the database - /// prefix rather than splitting on the separator keeps a database name that contains a - /// dot intact. + // `schemaKey` is the diagram's identity; stripping the database prefix keeps a database name with a dot intact. nonisolated static func resolveSchemaName(fromSchemaKey schemaKey: String, databaseName: String) -> String? { let prefix = databaseName + "." guard !databaseName.isEmpty, schemaKey.hasPrefix(prefix) else { return nil } @@ -42,11 +39,6 @@ final class ERDiagramViewModel: ObservableObject { "\(databaseName).\(schema ?? noSchemaMarker)" } - nonisolated static func schemaKeyPreserves(_ schema: String, databaseName: String) -> Bool { - resolveSchemaName(fromSchemaKey: schemaKey(databaseName: databaseName, schema: schema), databaseName: databaseName) - == schema - } - // MARK: - State enum LoadState: Equatable { @@ -163,6 +155,7 @@ final class ERDiagramViewModel: ObservableObject { connectionId: UUID, databaseName: String, schemaKey: String, + schemaName: String? = nil, connection: DatabaseConnection? = nil, services: AppServices = .live, autoPanClock: any Clock = ContinuousClock() @@ -170,7 +163,9 @@ final class ERDiagramViewModel: ObservableObject { self.connectionId = connectionId self.databaseName = databaseName self.schemaKey = schemaKey - self.schemaName = Self.resolveSchemaName(fromSchemaKey: schemaKey, databaseName: databaseName) + // The key writes a schema named `default` and no schema alike, so the schema the tab recorded wins. + self.schemaName = schemaName?.nilIfEmpty + ?? Self.resolveSchemaName(fromSchemaKey: schemaKey, databaseName: databaseName) self.connection = connection self.services = services self.autoPanClock = autoPanClock @@ -181,6 +176,16 @@ final class ERDiagramViewModel: ObservableObject { } } + convenience init(tab: QueryTab, connection: DatabaseConnection) { + self.init( + connectionId: connection.id, + databaseName: tab.tableContext.databaseName, + schemaKey: tab.display.erDiagramSchemaKey ?? tab.tableContext.databaseName, + schemaName: tab.tableContext.schemaName, + connection: connection + ) + } + deinit { autoPanTask?.cancel() layoutTask?.cancel() @@ -219,6 +224,7 @@ final class ERDiagramViewModel: ObservableObject { loadState = .failed(String(localized: "This diagram is not bound to a database")) return } + loadedScope = scope do { let (fetched, kinds) = try await fetchGraph(in: scope) diff --git a/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift b/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift index 3250049fca..8283fd3cc1 100644 --- a/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift +++ b/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift @@ -39,12 +39,8 @@ extension WelcomeViewModel { confirm: @MainActor ([DatabaseConnection]) async -> Bool ) async -> TeamLibraryPublishOutcome { guard await confirm(connections) else { return .declined } - // A pull drops both, so sending them would only put a token typed into a command on the server. let plan = connections.map { - TeamLibraryPublishPlan.Connection( - id: $0.id, - settings: exporter.portableSettings(for: $0).withoutStartupCommands().withoutTunnelCommand() - ) + TeamLibraryPublishPlan.Connection(id: $0.id, settings: exporter.teamShareableSettings(for: $0)) } do throws(TeamLibraryPublishError) { return .finished(try await sync.publishConnections(plan, to: teamID)) diff --git a/apple/TablePro/Views/DataGrid/DataGridModel+ColumnGeometry.swift b/apple/TablePro/Views/DataGrid/DataGridModel+ColumnGeometry.swift index fbc39d7465..004acc16ad 100644 --- a/apple/TablePro/Views/DataGrid/DataGridModel+ColumnGeometry.swift +++ b/apple/TablePro/Views/DataGrid/DataGridModel+ColumnGeometry.swift @@ -10,7 +10,12 @@ extension DataGridModel { // owned; the order splices into the stored one so a hidden column keeps its slot. func columnGeometryDidChange(widths: [String: CGFloat], order: [String]?) { guard !widths.isEmpty || order != nil else { return } + let dataOrder = rows.columns updateColumnLayout { layout in + // No stored order means data order; splicing into nothing kept only the shown names, which an ephemeral store drops. + if order != nil, layout.columnOrder == nil, !dataOrder.isEmpty { + layout.columnOrder = dataOrder + } var captured = layout captured.columnWidths.merge(widths) { _, new in new } if !widths.isEmpty { diff --git a/apple/TablePro/Views/Editor/EditorUndoHistories.swift b/apple/TablePro/Views/Editor/EditorUndoHistories.swift index cbfa10f327..7f0fa3ab01 100644 --- a/apple/TablePro/Views/Editor/EditorUndoHistories.swift +++ b/apple/TablePro/Views/Editor/EditorUndoHistories.swift @@ -3,15 +3,17 @@ // TablePro // -import Foundation +import AppKit 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. +// What a query tab leaves in the shared editor while another tab is shown. Every part is a place in `text`, so it +// comes back only while the tab still holds that text. struct EditorTabHistory { let text: String let undo: EditorUndoHistory? let vimMarks: VimDocumentMarks? + let selection: [NSRange] + let scrollPosition: CGPoint } @MainActor diff --git a/apple/TablePro/Views/Editor/QueryParameterPanelView.swift b/apple/TablePro/Views/Editor/QueryParameterPanelView.swift index b552706cb2..59a0958248 100644 --- a/apple/TablePro/Views/Editor/QueryParameterPanelView.swift +++ b/apple/TablePro/Views/Editor/QueryParameterPanelView.swift @@ -44,13 +44,9 @@ struct QueryParameterPanelView: View { Spacer() - Button("Clear All") { - for index in parameters.indices { - parameters[index].value = "" - } - } - .buttonStyle(.bordered) - .controlSize(.small) + Button("Clear All", action: clearAllValues) + .buttonStyle(.bordered) + .controlSize(.small) Button(String(localized: "Close parameter panel"), systemImage: "xmark", action: onDismiss) .labelStyle(.iconOnly) @@ -63,6 +59,15 @@ struct QueryParameterPanelView: View { .paneBarBackground(Color(nsColor: .controlBackgroundColor)) } + // One write: the binding reads the tab as it was at render, so a write per row starts each from the old values. + func clearAllValues() { + parameters = parameters.map { parameter in + var cleared = parameter + cleared.value = "" + return cleared + } + } + private var parameterRows: some View { VStack(spacing: 0) { ForEach(parameters) { parameter in diff --git a/apple/TablePro/Views/Editor/SQLEditorController.swift b/apple/TablePro/Views/Editor/SQLEditorController.swift index 1e88ef5b96..6098ba4e86 100644 --- a/apple/TablePro/Views/Editor/SQLEditorController.swift +++ b/apple/TablePro/Views/Editor/SQLEditorController.swift @@ -104,7 +104,7 @@ final class SQLEditorController { applyInput(newInput) pushEditor() if switchesTab { - restoreTabHistory(of: newInput) + restoreSelection(from: restoreTabHistory(of: newInput), orRestoredRange: newInput.restoredCursorRange) } if newInput.pendingStatementJump != old.pendingStatementJump, let jump = newInput.pendingStatementJump { @@ -148,26 +148,48 @@ 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. + // One editor serves every query tab, and handing it another tab's text clears its history and Vim marks and + // leaves the outgoing tab's selection and scroll on it. 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) + histories.store(EditorTabHistory( + text: undo?.text ?? textViewController.textView.string, + undo: undo, + vimMarks: coordinator.vimDocumentMarks, + selection: textViewController.cursorPositions.map(\.range), + scrollPosition: textViewController.scrollPosition + ), 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 } + // A tab whose text changed while it was away gets none of it back. + @discardableResult + private func restoreTabHistory(of input: SQLEditorInput) -> EditorTabHistory? { + guard let tabID = input.tabID, let saved = input.undoHistories?.take(for: tabID) else { return nil } 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) + guard matches else { return nil } + if let vimMarks = saved.vimMarks { + coordinator.restoreVimDocumentMarks(vimMarks) + } + return saved + } + + // A tab shown here before gets back its own selection and scroll; any other starts at its saved caret or the top. + private func restoreSelection(from history: EditorTabHistory?, orRestoredRange restoredRange: NSRange?) { + let controller = textViewController + // The frame still has the outgoing document's height until the next layout pass, which would clamp the scroll. + controller.textView.updateFrameIfNeeded() + if let history { + let selection = history.selection.isEmpty ? [NSRange(location: 0, length: 0)] : history.selection + controller.setCursorPositions(selection.map { CursorPosition(range: $0) }) + controller.scrollPosition = history.scrollPosition + return + } + controller.scrollPosition = .zero + let length = controller.textView.textStorage.length + let caret = (restoredRange ?? NSRange(location: 0, length: 0)).clampedToTextLength(length) + controller.setCursorPositions([CursorPosition(range: caret)], scrollToVisible: restoredRange != nil) } private func applyInput(_ input: SQLEditorInput) { diff --git a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift index 0cff4ab7fb..2c609a0848 100644 --- a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift +++ b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift @@ -686,7 +686,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie private func installVimKeyInterceptor(controller: TextViewController) { guard let textView = controller.textView else { return } - let adapter = VimTextBufferAdapter(textView: textView) + let adapter = VimTextBufferAdapter(controller: controller) let engine = VimEngine(buffer: adapter) engine.onModeChange = { [weak self] mode in diff --git a/apple/TablePro/Views/Export/TableTransferSheet.swift b/apple/TablePro/Views/Export/TableTransferSheet.swift index 64dbec7225..a4e70f6c4c 100644 --- a/apple/TablePro/Views/Export/TableTransferSheet.swift +++ b/apple/TablePro/Views/Export/TableTransferSheet.swift @@ -29,6 +29,10 @@ struct TableTransferSheet: View { @State private var destinationDatabase = "" @State private var availableDestinations: [DatabaseConnection] = [] @State private var destinationDatabases: [String] = [] + @State private var destinationSchemas: [String] = [] + @State private var destinationSchema = "" + // Loads of the destination's databases and schemas still running: until they end, the scope is not known. + @State private var resolvingDestination = 0 @State private var sourceTables: [ExportObjectItem] = [] @State private var deleteExistingRows = false @State private var wrapInTransaction = true @@ -55,7 +59,7 @@ struct TableTransferSheet: View { } private var canTransfer: Bool { - !isRunning && !selectedTables.isEmpty && destinationConnection != nil && !hasContestedMapping + !isRunning && !selectedTables.isEmpty && destinationScope != nil && !hasContestedMapping } /// Two source columns mapped to one destination column build an INSERT naming it twice, which @@ -127,20 +131,48 @@ struct TableTransferSheet: View { } } .onChange(of: destinationConnectionId) { _ in + resolvingDestination += 1 Task { + defer { resolvingDestination -= 1 } await loadDestinationDatabases() - await loadColumnsForSelection() + await loadDestinationSchemas() + await reloadDestinationColumns() } } if !destinationDatabases.isEmpty { - Picker("Database", selection: $destinationDatabase) { + Picker("Database", selection: Binding( + get: { destinationDatabase }, + set: { database in + destinationDatabase = database + resolvingDestination += 1 + Task { + defer { resolvingDestination -= 1 } + await loadDestinationSchemas() + await reloadDestinationColumns() + } + } + )) { ForEach(destinationDatabases, id: \.self) { database in Text(database).tag(database) } } } + if !destinationSchemas.isEmpty { + Picker("Schema", selection: Binding( + get: { destinationSchema }, + set: { schema in + destinationSchema = schema + Task { await reloadDestinationColumns() } + } + )) { + ForEach(destinationSchemas, id: \.self) { schema in + Text(schema).tag(schema) + } + } + } + Text("Tables") .font(.subheadline.weight(.medium)) .foregroundStyle(.secondary) @@ -295,7 +327,7 @@ struct TableTransferSheet: View { guard let index = sourceTables.firstIndex(where: { $0.id == table.id }) else { return } sourceTables[index].isSelected = isOn guard isOn else { return } - Task { await loadColumnsForSelection() } + Task { await loadColumnsForSelection(on: destinationScope) } } ) } @@ -350,6 +382,60 @@ struct TableTransferSheet: View { } } + // Without a schema the writes resolved to wherever the destination session was, often another table of that name. + @MainActor + private func loadDestinationSchemas() async { + destinationSchemas = [] + destinationSchema = "" + guard let destinationConnection, + PluginManager.shared.supportsSchemaSwitching(for: destinationConnection.type) else { return } + let database = destinationDatabase.isEmpty ? destinationConnection.database : destinationDatabase + let scope = DatabaseScope(connectionId: destinationConnection.id, database: database, schema: nil) + do { + let schemas = try await DatabaseManager.shared.withMetadataDriver( + scope: scope, workload: .interactive + ) { driver in + try await driver.fetchSchemas() + } + guard destinationConnectionId == scope.connectionId, destinationDatabaseName == database else { return } + destinationSchemas = schemas + destinationSchema = Self.defaultDestinationSchema( + source: sourceScope.schema, + current: DatabaseManager.shared.resolvedScope( + database: database, schema: nil, for: destinationConnection.id + )?.schema, + engineDefault: PluginManager.shared.defaultSchemaName(for: destinationConnection.type), + available: schemas + ) + } catch { + Self.logger.warning("Failed to list destination schemas: \(error.localizedDescription)") + } + } + + // The source's own schema when the destination has one of that name, then where the destination is browsing. + nonisolated static func defaultDestinationSchema( + source: String?, + current: String?, + engineDefault: String?, + available: [String] + ) -> String { + for candidate in [source, current, engineDefault] { + if let candidate, available.contains(candidate) { return candidate } + } + return available.first ?? "" + } + + @MainActor + private func reloadDestinationColumns() async { + destinationColumns = [:] + await loadColumnsForSelection(on: Self.destinationScope( + connection: destinationConnection, + database: destinationDatabase, + schema: destinationSchema, + isResolving: false + )) + } + private func transferTitle(destination: DatabaseConnection) -> String { let template = selectedTables.count == 1 ? String(localized: "Transfer %1$lld table into %2$@?") @@ -373,7 +459,7 @@ struct TableTransferSheet: View { /// before anything is written. Only the ticked ones, because a database of four hundred tables /// would otherwise pay for four hundred column reads to open a sheet. @MainActor - private func loadColumnsForSelection() async { + private func loadColumnsForSelection(on destinationScope: DatabaseScope?) async { let tables = selectedTables.map(\.name) guard !tables.isEmpty, let destinationConnection else { return } isMatching = true @@ -385,6 +471,13 @@ struct TableTransferSheet: View { guard let destinationScope else { return } for table in tables where destinationColumns[table] == nil { let found = await columns(of: table, on: destinationScope) + // A schema or database picked while this read ran owns the columns now. + guard Self.destinationScope( + connection: destinationConnection, + database: destinationDatabase, + schema: destinationSchema, + isResolving: false + ) == destinationScope else { return } destinationColumns[table] = found.isEmpty ? nil : found } } @@ -417,16 +510,34 @@ struct TableTransferSheet: View { ) } - /// The database the user picked, not wherever the destination connection was last parked. Both - /// the column read and the write go through this: the picker used to bind to a value nothing - /// read, so choosing a database changed the label and sent the rows somewhere else. private var destinationScope: DatabaseScope? { + Self.destinationScope( + connection: destinationConnection, + database: destinationDatabase, + schema: destinationSchema, + isResolving: resolvingDestination > 0 + ) + } + + private var destinationDatabaseName: String? { guard let destinationConnection else { return nil } - let database = destinationDatabase.isEmpty - ? destinationConnection.database - : destinationDatabase + return destinationDatabase.isEmpty ? destinationConnection.database : destinationDatabase + } + + // The database and schema the user picked, not wherever the destination session was last parked. None while they + // are still loading: a scope taken then named no schema, and the writes went to the session's own. + nonisolated static func destinationScope( + connection: DatabaseConnection?, + database: String, + schema: String, + isResolving: Bool + ) -> DatabaseScope? { + guard let connection, !isResolving else { return nil } return DatabaseScope( - connectionId: destinationConnection.id, database: database, schema: nil) + connectionId: connection.id, + database: database.isEmpty ? connection.database : database, + schema: schema.isEmpty ? nil : schema + ) } // MARK: - Running @@ -461,7 +572,17 @@ struct TableTransferSheet: View { job.end() } - await loadColumnsForSelection() + await loadColumnsForSelection(on: destinationScope) + // The mapping is read from the scope this run writes to, or not at all. + guard Self.destinationScope( + connection: destinationConnection, + database: destinationDatabase, + schema: destinationSchema, + isResolving: false + ) == destinationScope else { + errorMessage = String(localized: "The destination changed while the transfer started. Check it and transfer again.") + return + } var mappings: [String: [String: String]] = [:] var unmapped: [String] = [] @@ -484,6 +605,7 @@ struct TableTransferSheet: View { objects: selectedTables, sourceType: sourceConnection.type, destinationType: destinationConnection.type, + destinationSchema: destinationScope.schema, columnMapping: mappings, sourceColumns: sourceColumns, deleteExistingRows: deleteExistingRows, diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index d6e71b3a62..ca1f290397 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -375,12 +375,7 @@ struct MainEditorContentView: View { .frame(maxWidth: .infinity, maxHeight: .infinity) .onAppear { guard coordinator.erDiagramModels[tab.id] == nil else { return } - let vm = ERDiagramViewModel( - connectionId: connection.id, - databaseName: tab.tableContext.databaseName, - schemaKey: tab.display.erDiagramSchemaKey ?? tab.tableContext.databaseName, - connection: connection - ) + let vm = ERDiagramViewModel(tab: tab, connection: connection) vm.coordinator = coordinator vm.tabId = tab.id coordinator.erDiagramModels[tab.id] = vm @@ -394,7 +389,11 @@ struct MainEditorContentView: View { guard coordinator.canBuildJoinQuery else { return nil } let coordinator = coordinator return { tables in - coordinator.openJoinBuilder(database: diagram.databaseName, schema: diagram.schemaName, tables: tables) + coordinator.openJoinBuilder( + database: diagram.scope?.database ?? diagram.databaseName, + schema: diagram.scope?.schema ?? diagram.schemaName, + tables: tables + ) } } @@ -482,10 +481,14 @@ struct MainEditorContentView: View { ) } - private func parameterBinding(for tab: QueryTab) -> Binding<[QueryParameter]> { + // Reads the live tab: from the render-time copy, each write in a row started from the array as first drawn. + static func parameterBinding(for tab: QueryTab, in tabManager: QueryTabManager) -> Binding<[QueryParameter]> { let tabId = tab.id + let fallbackParameters = tab.content.queryParameters return Binding( - get: { tab.content.queryParameters }, + get: { + tabManager.tabs.first(where: { $0.id == tabId })?.content.queryParameters ?? fallbackParameters + }, set: { newValue in tabManager.mutate(tabId: tabId) { $0.content.queryParameters = newValue } } @@ -1140,7 +1143,7 @@ extension MainEditorContentView { let commands = commandAvailability(for: tab) let isExecuting = coordinator.tabExecution.isExecuting(tab.id) let showsHistoryTip = showsHistoryTip - let parameters = parameterBinding(for: tab) + let parameters = Self.parameterBinding(for: tab, in: tabManager) let isParameterPanelVisible = parameterVisibilityBinding(for: tab) let header: (VimMode?) -> AnyView = { vimMode in AnyView(VStack(alignment: .leading, spacing: 0) { diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCommandActions+FileSaving.swift b/apple/TablePro/Views/Main/Extensions/MainContentCommandActions+FileSaving.swift index 66c0a1b483..0983911923 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCommandActions+FileSaving.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCommandActions+FileSaving.swift @@ -17,10 +17,6 @@ import TableProUtilities extension MainContentCommandActions { nonisolated private static let fileLogger = Logger(subsystem: "com.TablePro", category: "MainContentCommandActions") - func saveFileToSourceURL() { - Task { await saveSelectedFileAwaiting() } - } - @discardableResult func saveSelectedFileAwaiting() async -> Bool { guard let tab = coordinator?.tabManager.selectedTab, diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift index 6b3f930d40..b29a72b909 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Navigation.swift @@ -103,9 +103,10 @@ extension MainContentCoordinator { requestGridFocus() } - // In-place navigation would retarget the selected tab, and a pinned or named one is never retargeted. - let keepsSelectedTab = navigationModel == .inPlace - && (tabManager.selectedTab?.isPinned == true || tabManager.selectedTab?.isNamedByUser == true) + // In-place navigation would retarget the selected tab, so it keeps one that is pinned, named or holds work. + let keepsSelectedTab = navigationModel == .inPlace && tabManager.selectedTab.map { tab in + tab.isPinned || tab.isNamedByUser || selectedTabResistsRetarget(tab) + } == true if tabManager.tabs.isEmpty || keepsSelectedTab { let didOpen = addFirstTableTab( tableName: tableName, @@ -419,18 +420,21 @@ extension MainContentCoordinator { /// only be followed from a grid and the row the reader clicked is in that grid. var isActiveTabReusable: Bool { guard let tab = tabManager.selectedTab, !tab.isPinned else { return false } - if selectedTabHoldsProtectedContent { return false } - if selectedTabFilterState.hasAppliedFilters - || tab.hasUserActiveSort - || tab.display.hasPinnedResults { - return false - } + if selectedTabResistsRetarget(tab) { return false } if tab.tabType == .createTable { return true } if tab.isPreview { return true } if tab.tabType == .query { return true } return false } + // Retargeting drops the tab's work, filters, sort and pinned results, so both reuse paths ask this first. + private func selectedTabResistsRetarget(_ tab: QueryTab) -> Bool { + selectedTabHoldsProtectedContent + || selectedTabFilterState.hasAppliedFilters + || tab.hasUserActiveSort + || tab.display.hasPinnedResults + } + func promotePreviewTab() { guard let selectedTabId = tabManager.selectedTabId else { return } tabManager.promotePreviewTab(id: selectedTabId) diff --git a/apple/TablePro/Views/Main/Extensions/MainContentView+EventHandlers.swift b/apple/TablePro/Views/Main/Extensions/MainContentView+EventHandlers.swift index ef113e1a30..7a5e9ef344 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentView+EventHandlers.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentView+EventHandlers.swift @@ -147,6 +147,7 @@ extension MainContentView { func updateSidebarEditState() { // A selection change, refresh or undo rebuilds the fields, so the typed run ends here, not in another row's step. coordinator.endInspectorEditRun() + trailingPaneState.inspector.editState.detachedStager = coordinator.rowEditingCoordinator // A structure definition is edited by the structure inspector, not the row fields. switch gridSelectionOwner { case .schemaGrid, .none: @@ -191,6 +192,7 @@ extension MainContentView { } } trailingPaneState.inspector.editState.configure( + tabId: tab.id, rowIDs: selectedRows.map(\.id), allRows: stringRows, absentCells: selectedRows.map { tableRows.absentColumns(of: $0.id) }, @@ -251,16 +253,6 @@ extension MainContentView { trailingPaneState.inspector.editState.onFieldRemoved = { columnIndex, rowIDs in capturedCoordinator.stageInspectorFieldRemoval(columnIndex: columnIndex, rowIDs: rowIDs) } - trailingPaneState.inspector.editState.onDetachedFieldChanged = { columnIndex, newValue, rowIDs, isExpression in - // A value window commits per keystroke like its field, so its typing folds into one undo step the same way. - capturedCoordinator.rowEditingCoordinator.stageInspectorFieldEdit( - columnIndex: columnIndex, - value: newValue, - rowIDs: rowIDs, - continuity: .typing, - isExpression: isExpression - ) - } } // Only the editor comes from the format; the value stays raw, since a formatted timestamp saved back would corrupt it. @@ -303,6 +295,5 @@ extension MainContentView { trailingPaneState.inspector.editState.onFieldValuesChanged = nil trailingPaneState.inspector.editState.onFieldReverted = nil trailingPaneState.inspector.editState.onFieldRemoved = nil - trailingPaneState.inspector.editState.onDetachedFieldChanged = nil } } diff --git a/apple/TablePro/Views/Main/MainContentCommandActions+Closing.swift b/apple/TablePro/Views/Main/MainContentCommandActions+Closing.swift index 43b5b9408d..fe86e2f3fd 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions+Closing.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions+Closing.swift @@ -110,10 +110,14 @@ extension MainContentCommandActions { } // False once another tab is in front or the tab is gone: the mounted editors, grid and inspector it saves are the front tab's. + private func isShowing(_ tabId: UUID?) -> Bool { + guard let manager = coordinator?.tabManager else { return false } + return manager.selectedTabId == tabId && (tabId == nil || manager.selectedTabIndex != nil) + } + func saveWork(onTab tabId: UUID?) async -> Bool { guard let coordinator = coordinator else { return true } - let manager = coordinator.tabManager - let stillOnTab = { manager.selectedTabId == tabId && (tabId == nil || manager.selectedTabIndex != nil) } + let stillOnTab = { self.isShowing(tabId) } guard stillOnTab() else { return false } if isUsersRolesTab, coordinator.usersRolesActions?.hasChanges() == true { @@ -131,26 +135,27 @@ extension MainContentCommandActions { } guard await applyDiagramEdits(ofTab: tabId, in: coordinator), stillOnTab() else { return false } guard await applyTypeChanges(ofTab: tabId), stillOnTab() else { return false } + return await saveRowsThenFile(onTab: tabId) + } - // Data grid changes or pending table operations take priority + // A query result's edits and the tab's .sql file are separate work that one Save answers for; it stops at the first failure. + func saveRowsThenFile(onTab tabId: UUID?) async -> Bool { + guard let coordinator else { return true } + guard isShowing(tabId) else { return false } + // The grid save writes the inspector's edits too: they are staged in the same change manager. if hasDataWork { - return await withCheckedContinuation { continuation in + guard coordinator.admitsSheetCommand() else { return false } + let saved = await withCheckedContinuation { continuation in coordinator.saveCompletionContinuation = continuation - saveChanges() - // Still there when the command went somewhere other than the grid save, which reports nothing back. + saveDataWork() + // Still there when the grid save never started, which reports nothing back. coordinator.takeSaveCompletion()?.resume(returning: false) } + guard saved, isShowing(tabId) else { return false } + } else if trailingPaneState.inspector.editState.hasEdits { + guard await saveInspectorEditsAwaiting(), isShowing(tabId) else { return false } } - - if trailingPaneState.inspector.editState.hasEdits { - return await saveInspectorEditsAwaiting() - } - - // File save (query editor with source file) - if coordinator.tabManager.selectedTab?.content.isFileDirty == true { - return await saveSelectedFileAwaiting() - } - - return true + guard coordinator.tabManager.selectedTab?.content.isFileDirty == true else { return true } + return await saveSelectedFileAwaiting() } } diff --git a/apple/TablePro/Views/Main/MainContentCommandActions.swift b/apple/TablePro/Views/Main/MainContentCommandActions.swift index a603cb4978..ae2353f682 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions.swift @@ -137,12 +137,6 @@ final class MainContentCommandActions: ObservableObject { // MARK: - Save Action - private func saveInspectorEdits() { - Task { [weak self] in - await self?.saveInspectorEditsAwaiting() - } - } - // A close waits on this: started and left, the write could land after the window it reports to closed. @discardableResult func saveInspectorEditsAwaiting() async -> Bool { @@ -871,37 +865,33 @@ final class MainContentCommandActions: ObservableObject { return } if saveSelectedTypeChanges() { return } + let selectedTab = coordinator?.tabManager.selectedTab if let session = stagedStructureSession, let coordinator { Task { _ = await session.applyStagedChanges(coordinator: coordinator) } - } else if hasDataWork { - // Data grid first: its edits sync to the sidebar editState, and its path uses the plugin driver for statements. - var truncates = pendingTruncates.wrappedValue - var deletes = pendingDeletes.wrappedValue - var options = tableOperationOptions.wrappedValue - coordinator?.saveChanges( - pendingTruncates: &truncates, - pendingDeletes: &deletes, - tableOperationOptions: &options - ) - pendingTruncates.wrappedValue = truncates - pendingDeletes.wrappedValue = deletes - tableOperationOptions.wrappedValue = options - } else if trailingPaneState.inspector.editState.hasEdits { - // Save sidebar-only edits (edits made directly in the right panel) - saveInspectorEdits() - } - // File save: write query back to source file - else if let tab = coordinator?.tabManager.selectedTab, - tab.content.sourceFileURL != nil, tab.content.isFileDirty { - saveFileToSourceURL() - } - // Save As: untitled query tab with content - else if let tab = coordinator?.tabManager.selectedTab, - tab.tabType == .query, tab.content.sourceFileURL == nil, tab.hasQueryText { + } else if hasDataWork || trailingPaneState.inspector.editState.hasEdits || selectedTab?.content.isFileDirty == true { + let tabId = selectedTab?.id + Task { await saveRowsThenFile(onTab: tabId) } + } else if let selectedTab, selectedTab.tabType == .query, selectedTab.content.sourceFileURL == nil, + selectedTab.hasQueryText { saveFileAs() } } + // Its path uses the plugin driver for statements, and writes the staged TRUNCATE and DROP too. + func saveDataWork() { + var truncates = pendingTruncates.wrappedValue + var deletes = pendingDeletes.wrappedValue + var options = tableOperationOptions.wrappedValue + coordinator?.saveChanges( + pendingTruncates: &truncates, + pendingDeletes: &deletes, + tableOperationOptions: &options + ) + pendingTruncates.wrappedValue = truncates + pendingDeletes.wrappedValue = deletes + tableOperationOptions.wrappedValue = options + } + func saveFileAs() { guard let coordinator, coordinator.admitsSheetCommand() else { return } let tabId = coordinator.tabManager.selectedTab?.id diff --git a/apple/TablePro/Views/RowInspector/InspectorPopOutRegistry.swift b/apple/TablePro/Views/RowInspector/InspectorPopOutRegistry.swift index b62bb99911..8e6d388e9d 100644 --- a/apple/TablePro/Views/RowInspector/InspectorPopOutRegistry.swift +++ b/apple/TablePro/Views/RowInspector/InspectorPopOutRegistry.swift @@ -3,7 +3,7 @@ // TablePro // -import Foundation +import AppKit // An editable pop-out commits to the row ids it opened on, which a reload hands to other rows, so Auto Refresh waits on it. @MainActor @@ -30,3 +30,29 @@ internal enum InspectorPopOutRegistry { entries.removeAll { $0.owner == nil || $0.window == nil } } } + +// An editable pop-out's writes, held to the tab and records it opened on. It closes rather than write elsewhere. +@MainActor +internal final class InspectorPopOutSession { + private weak var editState: MultiRowEditState? + private weak var window: ValueViewerWindowController? + private let target: InspectorDetachedTarget + + internal init?(editState: MultiRowEditState, columnIndex: Int) { + guard let target = editState.holdDetachedField(columnIndex: columnIndex) else { return nil } + self.editState = editState + self.target = target + } + + internal func attach(_ window: ValueViewerWindowController, openedFrom owner: TrailingPaneState) { + self.window = window + InspectorPopOutRegistry.record(window, openedFrom: owner) + } + + internal func commit(_ value: String) { + guard editState?.commitDetachedField(value, to: target) != true else { return } + NSSound.beep() + window?.close() + window = nil + } +} diff --git a/apple/TablePro/Views/RowInspector/RowInspectorView.swift b/apple/TablePro/Views/RowInspector/RowInspectorView.swift index c0f7a4581e..cf984df721 100644 --- a/apple/TablePro/Views/RowInspector/RowInspectorView.swift +++ b/apple/TablePro/Views/RowInspector/RowInspectorView.swift @@ -138,24 +138,19 @@ internal struct RowInspectorView: View { private func popOut(field: FieldEditState, text: String, kind: FieldEditorKind) { let isEditable = context.isEditable && !context.isRowDeleted && !field.isServerOwned - // Captured, not looked up per keystroke: the window outlives the selection it opened on. - let columnIndex = field.columnIndex - let rowIDs = state.editState.rowIDs - let commit: ((String) -> Void)? = isEditable - ? { [editState = state.editState] newValue in - editState.updateDetachedField(columnIndex: columnIndex, rowIDs: rowIDs, value: newValue) - } - : nil + // Held when it opens, not looked up per keystroke: the window outlives the selection and the tab it opened on. + let session = isEditable ? InspectorPopOutSession(editState: state.editState, columnIndex: field.columnIndex) : nil + let commit: ((String) -> Void)? = session.map { session in { session.commit($0) } } switch InspectorPopOutWindow.resolve(for: kind) { case .json: let window = JSONViewerWindowController.open( text: text, columnName: field.columnName, - isEditable: isEditable, + isEditable: commit != nil, onCommit: commit ) - if commit != nil { InspectorPopOutRegistry.record(window, openedFrom: paneState) } + session?.attach(window, openedFrom: paneState) case .php: PhpViewerWindowController.open(text: text, columnName: field.columnName) case .binary(let format): @@ -169,10 +164,10 @@ internal struct RowInspectorView: View { let window = TextViewerWindowController.open( text: text, columnName: field.columnName, - isEditable: isEditable, + isEditable: commit != nil, onCommit: commit ) - if commit != nil { InspectorPopOutRegistry.record(window, openedFrom: paneState) } + session?.attach(window, openedFrom: paneState) } } } diff --git a/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift b/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift index 6fee2bfcf8..25c5b8b240 100644 --- a/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift +++ b/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift @@ -51,7 +51,7 @@ internal enum FavoritesMenuSpec { case .database(let entry): return databaseSections(entry, context: context) case .table(let row): - return tableSections(row, context: context) + return tableSections(row) case .query(let node): return querySections(node, context: context) case .header, .teamQuery: @@ -92,29 +92,19 @@ internal enum FavoritesMenuSpec { ] } - /// Spelled as the Database menu and the object tree spell it. It read "Show ER Diagram" here - /// and "View ER Diagram" everywhere else, which is one command reading as two. - private static func tableSections( - _ row: FavoriteTableRow, - context: FavoritesMenuContext - ) -> [FavoritesMenuSection] { - var opens: [FavoritesMenuItem] = [.command(String(localized: "Open Table"), .openTable(row))] - if canShowDiagram(ofSchema: row.otherSchema, context: context) { - opens.append(.command(String(localized: "View ER Diagram"), .showERDiagram(schema: row.otherSchema))) - } - return [ - FavoritesMenuSection(opens), + // "View ER Diagram" as the Database menu and the object tree spell it, so it reads as one command. + private static func tableSections(_ row: FavoriteTableRow) -> [FavoritesMenuSection] { + [ + FavoritesMenuSection([ + .command(String(localized: "Open Table"), .openTable(row)), + .command(String(localized: "View ER Diagram"), .showERDiagram(schema: row.otherSchema)) + ]), FavoritesMenuSection([ .command(String(localized: "Remove from Favorites"), .removeTableFavorite(row.entry)) ]) ] } - private static func canShowDiagram(ofSchema schema: String?, context: FavoritesMenuContext) -> Bool { - guard let schema else { return true } - return ERDiagramViewModel.schemaKeyPreserves(schema, databaseName: context.activeDatabase ?? "") - } - private static func querySections( _ node: FavoriteNode, context: FavoritesMenuContext diff --git a/apple/TablePro/Views/Structure/StructureSectionAdapter.swift b/apple/TablePro/Views/Structure/StructureSectionAdapter.swift index fb6f4082a3..95bb50b091 100644 --- a/apple/TablePro/Views/Structure/StructureSectionAdapter.swift +++ b/apple/TablePro/Views/Structure/StructureSectionAdapter.swift @@ -481,6 +481,17 @@ extension StructureSectionAdapter: DataGridActions { sortDidChange(sort) } + // The store persists the hidden set per section, for every table. + func gridHideColumn(_ column: DataGridColumn) { + // With no column left, no header remains to choose Show All Columns from. + guard model.columns.count > 1 else { return } + model.updateColumnLayout { $0.hiddenColumns.insert(column.name) } + } + + func gridShowAllColumns() { + model.updateColumnLayout { $0.hiddenColumns.removeAll() } + } + // A value filter rearranges the list, which withdraws the column move. func gridConfirmDisplayOrderChange(then apply: @escaping @MainActor () -> Void) { apply() diff --git a/apple/TableProTests/Core/AI/Chat/ConfirmDestructiveOperationScopeTests.swift b/apple/TableProTests/Core/AI/Chat/ConfirmDestructiveOperationScopeTests.swift new file mode 100644 index 0000000000..e1e109b0e6 --- /dev/null +++ b/apple/TableProTests/Core/AI/Chat/ConfirmDestructiveOperationScopeTests.swift @@ -0,0 +1,155 @@ +// +// ConfirmDestructiveOperationScopeTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProMCP +import Testing + +private actor DiscardingHistory: QueryHistoryRecording { + func record(_ request: QueryHistoryRecordRequest) async -> Bool { true } +} + +// The approval card names the database and schema from the call's input, and an explicit Run skips the gate's own +// dialog, so the statement has to run in exactly what the input names. +@MainActor +struct ConfirmDestructiveOperationScopeTests { + private func session(database: String, type: DatabaseType = .postgresql) -> ScriptAnsweringDriver { + var connection = TestFixtures.makeConnection(database: database, type: type) + connection.aiPolicy = .alwaysAllow + let driver = ScriptAnsweringDriver(connection: connection) { _ in .empty } + var session = ConnectionSession(connection: connection) + session.driver = driver + DatabaseManager.shared.injectSession(session, for: connection.id) + return driver + } + + private func context(_ driver: ScriptAnsweringDriver, gate: any ExecutionGate) -> ChatToolContext { + ChatToolContext( + connectionId: driver.connection.id, + bridge: MCPConnectionBridge(), + authPolicy: MCPAuthPolicy( + connectionResolver: { _ in nil }, + connectionIdsProvider: { [] }, + historyRecorder: DiscardingHistory(), + executionGate: gate + ), + chatMode: .agent, + sessionId: UUID(), + approvalWasExplicit: true, + policyLookup: { _ in .alwaysAllow } + ) + } + + private func input(_ extra: [String: JsonValue]) -> JsonValue { + .object([ + "query": .string("DROP TABLE orders"), + "confirmation_phrase": .string(ConfirmDestructiveOperationChatTool.requiredPhrase) + ].merging(extra) { first, _ in first }) + } + + @Test("A database and schema the call names are where the statement runs, not the session's current ones") + func namedScopeIsTheRunScope() async throws { + let driver = session(database: "prod") + defer { DatabaseManager.shared.removeSession(for: driver.connection.id) } + let gate = RequestRecordingGate(allows: false) + + await #expect(throws: (any Error).self) { + _ = try await ConfirmDestructiveOperationChatTool().execute( + input: input(["database": .string("staging"), "schema": .string("archive")]), + context: context(driver, gate: gate) + ) + } + + let request = try #require(await gate.requests.first) + #expect(request.scope?.database == "staging") + #expect(request.scope?.schema == "archive") + #expect(driver.sentStatements.isEmpty && driver.sentBatches.isEmpty) + } + + @Test("A call that names no database runs in the session's current one") + func unnamedScopeIsTheCurrentDatabase() async throws { + let driver = session(database: "prod") + defer { DatabaseManager.shared.removeSession(for: driver.connection.id) } + let gate = RequestRecordingGate(allows: false) + + await #expect(throws: (any Error).self) { + _ = try await ConfirmDestructiveOperationChatTool().execute( + input: input(["database": .null]), + context: context(driver, gate: gate) + ) + } + + let request = try #require(await gate.requests.first) + #expect(request.scope?.database == "prod") + } + + @Test("On a connection that cannot change database, naming another one is refused before anything is asked or run") + func unreachableDatabaseIsRefused() async { + let driver = session(database: "prod.sqlite", type: .sqlite) + defer { DatabaseManager.shared.removeSession(for: driver.connection.id) } + let gate = RequestRecordingGate(allows: true) + + await #expect(throws: DatabaseAccessError.self) { + _ = try await ConfirmDestructiveOperationChatTool().execute( + input: input(["database": .string("staging.sqlite")]), + context: context(driver, gate: gate) + ) + } + + #expect(await gate.requests.isEmpty) + #expect(driver.sentStatements.isEmpty && driver.sentBatches.isEmpty) + } + + @Test("Naming the database a fixed connection is already on still runs there") + func currentDatabaseOfAFixedConnectionIsTaken() async throws { + let driver = session(database: "prod.sqlite", type: .sqlite) + defer { DatabaseManager.shared.removeSession(for: driver.connection.id) } + let gate = RequestRecordingGate(allows: false) + + await #expect(throws: (any Error).self) { + _ = try await ConfirmDestructiveOperationChatTool().execute( + input: input(["database": .string("prod.sqlite")]), + context: context(driver, gate: gate) + ) + } + + let request = try #require(await gate.requests.first) + #expect(request.scope?.database == "prod.sqlite") + } + + @Test("An argument the tool does not declare is refused before anything is asked or run") + func undeclaredArgumentIsRefused() async throws { + let driver = session(database: "prod") + defer { DatabaseManager.shared.removeSession(for: driver.connection.id) } + let gate = RequestRecordingGate(allows: true) + + await #expect(throws: ChatToolArgumentError.self) { + _ = try await ConfirmDestructiveOperationChatTool().execute( + input: input(["target_database": .string("staging")]), + context: context(driver, gate: gate) + ) + } + + #expect(await gate.requests.isEmpty) + #expect(driver.sentStatements.isEmpty && driver.sentBatches.isEmpty) + } + + @Test("The session's own connection_id is still taken, since the connection check answers it") + func sessionConnectionIdIsAccepted() async throws { + let driver = session(database: "prod") + defer { DatabaseManager.shared.removeSession(for: driver.connection.id) } + let gate = RequestRecordingGate(allows: false) + + await #expect(throws: (any Error).self) { + _ = try await ConfirmDestructiveOperationChatTool().execute( + input: input(["connection_id": .string(driver.connection.id.uuidString)]), + context: context(driver, gate: gate) + ) + } + + #expect(await gate.requests.count == 1) + } +} diff --git a/apple/TableProTests/Core/AI/ExecuteToolUsesOrderTests.swift b/apple/TableProTests/Core/AI/ExecuteToolUsesOrderTests.swift new file mode 100644 index 0000000000..e93507a7f2 --- /dev/null +++ b/apple/TableProTests/Core/AI/ExecuteToolUsesOrderTests.swift @@ -0,0 +1,112 @@ +// +// ExecuteToolUsesOrderTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProMCP +import TableProTestSupport +import Testing + +private final class CallLog: @unchecked Sendable { + private let lock = NSLock() + private var recorded: [String] = [] + + var events: [String] { lock.withLock { recorded } } + + func record(_ event: String) { + lock.withLock { recorded.append(event) } + } +} + +private struct RecordingTool: ChatTool { + let name: String + let mode: ChatToolMode + let log: CallLog + var gate: AsyncGate? + let description = "" + let inputSchema: JsonValue = .object(["type": .string("object")]) + + func execute(input: JsonValue, context: ChatToolContext) async throws -> ChatToolResult { + log.record("\(name) started") + if let gate { await gate.wait() } + log.record("\(name) finished") + return ChatToolResult(content: name) + } +} + +@MainActor +struct ExecuteToolUsesOrderTests { + private func context() -> ChatToolContext { + ChatToolContext(connectionId: nil, bridge: MCPConnectionBridge(), authPolicy: MCPAuthPolicy(), chatMode: .agent) + } + + private func scope() -> ChatToolScope { + ChatToolScope(sessionId: UUID(), connectionId: nil, mode: .agent) + } + + @Test("A round with a write runs its calls one at a time, in the order proposed") + func writeRoundRunsInOrder() async { + let log = CallLog() + let gate = AsyncGate() + let registry = ChatToolRegistry() + registry.register(RecordingTool(name: "create_table", mode: .write, log: log, gate: gate)) + registry.register(RecordingTool(name: "insert_rows", mode: .write, log: log)) + let blocks = [ + ToolUseBlock(id: "u1", name: "create_table", input: .object([:])), + ToolUseBlock(id: "u2", name: "insert_rows", input: .object([:])) + ] + let context = context() + let scope = scope() + + let run = Task { + await AIChatViewModel.executeToolUses(blocks, scope: scope, context: context, registry: registry) + } + await gate.arrived(1) + await gate.open() + let results = await run.value + + #expect(log.events == ["create_table started", "create_table finished", "insert_rows started", "insert_rows finished"]) + #expect(results.map(\.toolUseId) == ["u1", "u2"]) + } + + @Test("A round of reads still runs its calls at once") + func readRoundRunsConcurrently() async { + let log = CallLog() + let gate = AsyncGate() + let registry = ChatToolRegistry() + registry.register(RecordingTool(name: "describe_orders", mode: .readOnly, log: log, gate: gate)) + registry.register(RecordingTool(name: "describe_items", mode: .readOnly, log: log, gate: gate)) + let blocks = [ + ToolUseBlock(id: "u1", name: "describe_orders", input: .object([:])), + ToolUseBlock(id: "u2", name: "describe_items", input: .object([:])) + ] + let context = context() + let scope = scope() + + let run = Task { + await AIChatViewModel.executeToolUses(blocks, scope: scope, context: context, registry: registry) + } + let bothHeld: Void? = await BoundedCall.result { await gate.arrived(2) } + await gate.open() + let results = await run.value + + #expect(bothHeld != nil) + #expect(results.map(\.toolUseId) == ["u1", "u2"]) + } + + @Test("Only a built-in read runs beside other calls; a write or an unknown name does not") + func onlyReadsRunConcurrently() { + let log = CallLog() + let registry = ChatToolRegistry() + registry.register(RecordingTool(name: "reader", mode: .readOnly, log: log)) + registry.register(RecordingTool(name: "writer", mode: .write, log: log)) + registry.register(RecordingTool(name: "destroyer", mode: .agentOnly, log: log)) + + #expect(registry.onlyReads(toolName: "reader")) + #expect(!registry.onlyReads(toolName: "writer")) + #expect(!registry.onlyReads(toolName: "destroyer")) + #expect(!registry.onlyReads(toolName: "ghost")) + } +} diff --git a/apple/TableProTests/Core/Compare/CompareCrossSchemaFollowUpTests.swift b/apple/TableProTests/Core/Compare/CompareCrossSchemaFollowUpTests.swift new file mode 100644 index 0000000000..98d42e443b --- /dev/null +++ b/apple/TableProTests/Core/Compare/CompareCrossSchemaFollowUpTests.swift @@ -0,0 +1,168 @@ +// +// CompareCrossSchemaFollowUpTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +// Views, routines and triggers were keyed with their schema, so `dbo` against `staging` paired none of them. +struct CompareSourceObjectSchemaPairingTests { + private let engine = SourceObjectDiffEngine( + sourceDatabaseType: .mssql, targetDatabaseType: .mssql, targetIndexedKinds: [] + ) + + private func read( + _ name: String, + kind: CompareObjectKind, + schema: String, + signature: String? = nil, + source: String + ) -> RoutineSourceRead { + RoutineSourceRead(name: name, kind: kind, schema: schema, signature: signature, source: source) + } + + @Test + func viewsRoutinesAndTriggersOfTwoSchemasPairWhenEachIsItsSidesOwn() { + let source = [ + read("active_users", kind: .view, schema: "dbo", source: "CREATE VIEW active_users AS SELECT 1 AS id"), + read("purge", kind: .procedure, schema: "dbo", source: "CREATE PROCEDURE purge AS SELECT 1"), + read("stamp", kind: .trigger, schema: "dbo", signature: "users", source: "CREATE TRIGGER stamp ON users AFTER INSERT AS SELECT 1") + ] + let target = [ + read("active_users", kind: .view, schema: "staging", source: "CREATE VIEW active_users AS SELECT 1 AS id"), + read("purge", kind: .procedure, schema: "staging", source: "CREATE PROCEDURE purge AS SELECT 1"), + read("stamp", kind: .trigger, schema: "staging", signature: "users", source: "CREATE TRIGGER stamp ON users AFTER INSERT AS SELECT 1") + ] + + let results = engine.compare(source: source, target: target, sourceSchema: "dbo", targetSchema: "staging") + + #expect(results.count == 3) + #expect(results.allSatisfy { $0.status == .identical }) + } + + @Test + func anotherSchemaInTheListingStillKeysItsOwnObjects() { + let results = engine.compare( + source: [ + read("audit", kind: .function, schema: "dbo", source: "CREATE FUNCTION audit() RETURNS INT AS BEGIN RETURN 1 END"), + read("audit", kind: .function, schema: "history", source: "CREATE FUNCTION audit() RETURNS INT AS BEGIN RETURN 1 END") + ], + target: [read("audit", kind: .function, schema: "staging", source: "CREATE FUNCTION audit() RETURNS INT AS BEGIN RETURN 1 END")], + sourceSchema: "dbo", + targetSchema: "staging" + ) + + #expect(results.count == 2) + #expect(results.contains { $0.identity.schema == "dbo" && $0.status == .identical }) + #expect(results.contains { $0.identity.schema == "history" && $0.status == .onlyInSource }) + } +} + +// A target table that could not be read across two schemas left the source's table as "only in source", which +// suggested a CREATE of a table already there; a source one unread suggested dropping the target's. +struct CompareUnreadableCounterpartTests { + private func snapshot(_ name: String, schema: String?) -> TableStructureSnapshot { + TableStructureSnapshot( + name: name, + schema: schema, + columns: [TestFixtures.makeEditableColumn(name: "id", dataType: "INT", isPrimaryKey: true)] + ) + } + + @Test + func aTargetTableThatCouldNotBeReadIsNotReportedAsMissing() { + let report = StructureDiffEngine().compare( + source: [snapshot("users", schema: "dbo"), snapshot("orders", schema: "dbo")], + target: [snapshot("orders", schema: "staging")], + sourceSchema: "dbo", + targetSchema: "staging", + unreadableTarget: [(name: "users", schema: "staging")] + ) + + #expect(report.count(of: .onlyInSource) == 0) + #expect(report.count(of: .identical) == 1) + } + + @Test + func aSourceTableThatCouldNotBeReadLeavesNoDropBehind() { + let report = StructureDiffEngine().compare( + source: [snapshot("orders", schema: "dbo")], + target: [snapshot("users", schema: "staging"), snapshot("orders", schema: "staging")], + sourceSchema: "dbo", + targetSchema: "staging", + unreadableSource: [(name: "users", schema: "dbo")] + ) + + #expect(report.count(of: .onlyInTarget) == 0) + #expect(report.count(of: .identical) == 1) + } + + @Test + func aTableWithNoUnreadableCounterpartIsStillOneSided() { + let report = StructureDiffEngine().compare( + source: [snapshot("users", schema: "dbo"), snapshot("audit", schema: "dbo")], + target: [], + sourceSchema: "dbo", + targetSchema: "staging", + unreadableTarget: [(name: "users", schema: "staging")] + ) + + #expect(report.results.map { $0.tableName } == ["audit"]) + #expect(report.count(of: .onlyInSource) == 1) + } +} + +// A timestamptz on one side and a datetime on the other compared as instants, so the wall clock the copy wrote read as +// a change. +struct ResultComparisonWallClockTests { + private func side(_ rows: [[String?]], atType: ColumnType) -> ResultComparisonSide { + ResultComparisonSide( + title: "Result", + detail: "Query 1", + columns: ["id", "at"], + columnTypes: [.integer(rawType: nil), atType], + rows: ContiguousArray(rows.enumerated().map { index, values in + Row(id: .existing(index), values: ContiguousArray(values.map { $0.map(PluginCellValue.text) ?? .null })) + }) + ) + } + + private func compare(_ left: ResultComparisonSide, _ right: ResultComparisonSide, key: [String]) throws -> ResultComparison { + let pairing = ResultColumnPairing(left: left.columns, right: right.columns) + let keyPairs = key.compactMap { name in pairing.pairs.firstIndex { $0.name == name } } + return try ResultComparisonEngine.compare(left: left, right: right, pairing: pairing, keyPairs: keyPairs) + } + + private let zoned = ColumnType.timestamp(rawType: "timestamptz") + private let naive = ColumnType.datetime(rawType: "datetime") + + @Test + func aZonedColumnAndTheWallClockOfItAreTheSameRows() throws { + let left = side([["1", nil], ["2", "2024-01-01 10:00:00+07"]], atType: zoned) + let right = side([["1", nil], ["2", "2024-01-01 10:00:00"]], atType: naive) + + #expect(try compare(left, right, key: []).differenceCount == 0) + #expect(try compare(left, right, key: ["id"]).differenceCount == 0) + #expect(try compare(left, right, key: ["at"]).differenceCount == 0) + } + + @Test + func anotherWallClockAgainstAZonedColumnIsAChange() throws { + let left = side([["1", "2024-01-01 10:00:00+07"]], atType: zoned) + let right = side([["1", "2024-01-01 03:00:00"]], atType: naive) + + #expect(try compare(left, right, key: ["id"]).count(of: .changed) == 1) + } + + @Test + func twoZonedColumnsStillCompareInstants() throws { + let left = side([["1", "2024-01-01 10:00:00+07"]], atType: zoned) + let right = side([["1", "2024-01-01 03:00:00+00:00"]], atType: zoned) + + #expect(try compare(left, right, key: ["id"]).differenceCount == 0) + } +} diff --git a/apple/TableProTests/Core/Compare/CompareCrossSchemaScriptingTests.swift b/apple/TableProTests/Core/Compare/CompareCrossSchemaScriptingTests.swift new file mode 100644 index 0000000000..28fe986a74 --- /dev/null +++ b/apple/TableProTests/Core/Compare/CompareCrossSchemaScriptingTests.swift @@ -0,0 +1,244 @@ +// +// CompareCrossSchemaScriptingTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +private final class ScriptingDriver: PluginDriverStub, @unchecked Sendable { + var supportsSchemas: Bool { true } + var currentSchema: String? { "staging" } +} + +// A view paired across `dbo` and `staging` kept the source's identity and text, so an Alter dropped `dbo.v`, the +// source's own view on a compare within one database, and ran a definition that can name `dbo` again. +struct CompareCrossSchemaSourceObjectTests { + private let engine = SourceObjectDiffEngine( + sourceDatabaseType: .mssql, targetDatabaseType: .mssql, targetIndexedKinds: [] + ) + + private func view(_ schema: String, _ body: String) -> RoutineSourceRead { + RoutineSourceRead(name: "v", kind: .view, schema: schema, signature: nil, source: "CREATE VIEW \(schema).v AS \(body)") + } + + @Test + func aPairAcrossTwoSchemasIsShownButNeverScripted() throws { + let results = engine.compare( + source: [view("dbo", "SELECT 1 AS a")], + target: [view("staging", "SELECT 2 AS a")], + sourceSchema: "dbo", + targetSchema: "staging" + ) + + let result = try #require(results.first) + #expect(results.count == 1) + #expect(result.status == .differs) + #expect(result.suggestedAction == .skip) + #expect(result.availableActions == [.skip]) + #expect(result.notes.contains { $0.contains("not scripted") }) + let builder = SourceObjectSyncBuilder(targetDriver: ScriptingDriver(), targetDatabaseType: .mssql, indexSchema: "staging") + #expect(throws: CompareSyncError.self) { try builder.build(for: result, action: .alter) } + } + + @Test + func anObjectOnlyInTheSourceIsNotCreatedFromAnotherSchemasText() throws { + let results = engine.compare( + source: [view("dbo", "SELECT 1 AS a")], + target: [], + sourceSchema: "dbo", + targetSchema: "staging" + ) + + let result = try #require(results.first) + #expect(result.status == .onlyInSource) + #expect(result.suggestedAction == .skip) + } + + @Test + func theSameSchemaOnBothSidesStillScripts() throws { + let results = engine.compare( + source: [view("dbo", "SELECT 1 AS a")], + target: [view("dbo", "SELECT 2 AS a")], + sourceSchema: "dbo", + targetSchema: "dbo" + ) + + let result = try #require(results.first) + #expect(result.suggestedAction == .alter) + #expect(result.scriptRefusal == nil) + } + + @Test + func aTargetOnlyObjectIsStillDroppedByItsOwnName() throws { + let results = engine.compare(source: [], target: [view("staging", "SELECT 1 AS a")], sourceSchema: "dbo", targetSchema: "staging") + + let result = try #require(results.first) + #expect(result.suggestedAction == .drop) + #expect(result.identity.schema == "staging") + } +} + +// A child paired across `dbo` and `staging` compared its key to `dbo.parent` with the target's key to `staging.parent`, +// so it dropped the key and added one that pointed the target's table at the source's parent. +struct CompareCrossSchemaForeignKeyTests { + private func child(_ schema: String, referencing referencedSchema: String?) -> TableStructureSnapshot { + var foreignKeys: [EditableForeignKeyDefinition] = [] + if let referencedSchema { + var key = TestFixtures.makeEditableForeignKey(name: "child_parent", columns: ["parent_id"], refTable: "parent") + key.referencedSchema = referencedSchema + foreignKeys = [key] + } + return TableStructureSnapshot( + name: "child", + schema: schema, + columns: [ + TestFixtures.makeEditableColumn(name: "id", dataType: "INT", isPrimaryKey: true), + TestFixtures.makeEditableColumn(name: "parent_id", dataType: "INT") + ], + foreignKeys: foreignKeys + ) + } + + private func compare(_ source: TableStructureSnapshot, _ target: TableStructureSnapshot) -> StructureDiffReport { + StructureDiffEngine().compare(source: [source], target: [target], sourceSchema: "dbo", targetSchema: "staging") + } + + private func addedKeys(_ report: StructureDiffReport) -> [EditableForeignKeyDefinition] { + report.results.flatMap(\.changes).compactMap { change in + guard case .addForeignKey(let key) = change else { return nil } + return key + } + } + + @Test + func aKeyToEachSidesOwnSchemaIsTheSameKey() { + let report = compare(child("dbo", referencing: "dbo"), child("staging", referencing: "staging")) + + #expect(report.count(of: .identical) == 1) + } + + @Test + func anAddedKeyPointsAtTheTargetsOwnTable() { + let report = compare(child("dbo", referencing: "dbo"), child("staging", referencing: nil)) + + #expect(addedKeys(report).map { $0.referencedSchema } == ["staging"]) + } + + @Test + func aKeyToAThirdSchemaKeepsPointingThere() { + let report = compare(child("dbo", referencing: "shared"), child("staging", referencing: nil)) + + #expect(addedKeys(report).map { $0.referencedSchema } == ["shared"]) + } + + @Test + func aTableCreatedInAnotherSchemaTakesItsOwnKeysWithIt() { + let options = StructureCompareOptions.default + let own = child("dbo", referencing: "dbo").placingReferences(from: "dbo", into: "staging", options: options) + let third = child("dbo", referencing: "shared").placingReferences(from: "dbo", into: "staging", options: options) + let same = child("dbo", referencing: "dbo").placingReferences(from: "dbo", into: "dbo", options: options) + + #expect(own.foreignKeys.map { $0.referencedSchema } == ["staging"]) + #expect(third.foreignKeys.map { $0.referencedSchema } == ["shared"]) + #expect(same.foreignKeys.map { $0.referencedSchema } == ["dbo"]) + } +} + +// A transfer pressed while the schema list was loading took a scope with no schema, and its writes went to whatever +// schema the destination session was on. +struct TableTransferDestinationScopeTests { + private let connection = DatabaseConnection(name: "Warehouse", database: "app", type: .postgresql) + + @Test + func whileTheDestinationLoadsThereIsNoScopeToTransferInto() { + #expect(TableTransferSheet.destinationScope( + connection: connection, database: "app", schema: "", isResolving: true + ) == nil) + } + + @Test + func aResolvedDestinationNamesItsSchema() { + let scope = TableTransferSheet.destinationScope( + connection: connection, database: "app", schema: "sales", isResolving: false + ) + + #expect(scope == DatabaseScope(connectionId: connection.id, database: "app", schema: "sales")) + #expect(TableTransferSheet.destinationScope(connection: nil, database: "app", schema: "sales", isResolving: false) == nil) + } +} + +// Each side keys every value one way per column: on the wall clock when one side's values all carry an offset and the +// other's none, and on the instant otherwise. A pairwise rule matched `10:00+07` with `10:00` and `10:00` with `10:00Z` +// but not `10:00+07` with `10:00Z`, so equal multisets reported differences, and NULL layouts multiplied its indexes. +struct ResultComparisonMixedZoneTests { + private func side(_ columns: [String], _ rows: [[String?]]) -> ResultComparisonSide { + ResultComparisonSide( + title: "Result", + detail: "Query 1", + columns: columns, + columnTypes: columns.map { $0 == "id" ? .integer(rawType: nil) : .timestamp(rawType: nil) }, + rows: ContiguousArray(rows.enumerated().map { index, values in + Row(id: .existing(index), values: ContiguousArray(values.map { $0.map(PluginCellValue.text) ?? .null })) + }) + ) + } + + private func compare(_ left: ResultComparisonSide, _ right: ResultComparisonSide, key: [String]) throws -> ResultComparison { + let pairing = ResultColumnPairing(left: left.columns, right: right.columns) + let keyPairs = key.compactMap { name in pairing.pairs.firstIndex { $0.name == name } } + return try ResultComparisonEngine.compare(left: left, right: right, pairing: pairing, keyPairs: keyPairs) + } + + @Test + func aReorderedMultisetOfMixedValuesIsTheSameRows() throws { + let values = ["2024-01-01 10:00:00+07", "2024-01-01 10:00:00", "2024-01-01 10:00:00Z"] + let left = side(["at"], values.map { [$0] as [String?] }) + + for order in [[1, 2, 0], [2, 1, 0], [0, 1, 2]] { + let right = side(["at"], order.map { [values[$0]] as [String?] }) + #expect(try compare(left, right, key: []).differenceCount == 0, "order \(order)") + } + } + + @Test + func aColumnMixingZonedAndUnzonedValuesComparesInstants() throws { + let left = side(["id", "at"], [["1", "2024-01-01 10:00:00+07"], ["2", "2024-01-01 10:00:00+07"]]) + let right = side(["id", "at"], [["1", "2024-01-01 10:00:00"], ["2", "2024-01-01 03:00:00+00:00"]]) + + #expect(try compare(left, right, key: ["id"]).entries.map { $0.kind } == [.changed, .same]) + } + + @Test + func nullableZonedColumnsAgainstTheirWallClocksAreTheSameRows() throws { + let left = side(["id", "at", "seen"], [ + ["1", nil, "2024-01-01 10:00:00+07"], + ["2", "2024-01-02 10:00:00+07", nil], + ["3", nil, nil], + ["4", "2024-01-03 10:00:00+07", "2024-01-03 11:00:00+07"] + ]) + let right = side(["id", "at", "seen"], [ + ["4", "2024-01-03 10:00:00", "2024-01-03 11:00:00"], + ["3", nil, nil], + ["2", "2024-01-02 10:00:00", nil], + ["1", nil, "2024-01-01 10:00:00"] + ]) + + #expect(try compare(left, right, key: ["id"]).differenceCount == 0) + #expect(try compare(left, right, key: []).differenceCount == 0) + } + + @Test + func rowOrderDoesNotChangeTheAnswer() throws { + let left: [[String?]] = [["1", "2024-01-01 10:00:00+07"], ["2", "2024-01-02 10:00:00+07"]] + let right: [[String?]] = [["1", "2024-01-01 10:00:00"], ["2", "2024-01-02 10:00:00"]] + + for key in [["id"], [], ["at"]] { + #expect(try compare(side(["id", "at"], left), side(["id", "at"], Array(right.reversed())), key: key).differenceCount == 0) + #expect(try compare(side(["id", "at"], Array(left.reversed())), side(["id", "at"], right), key: key).differenceCount == 0) + } + } +} diff --git a/apple/TableProTests/Core/Compare/CompareSchemaPairingTests.swift b/apple/TableProTests/Core/Compare/CompareSchemaPairingTests.swift new file mode 100644 index 0000000000..1b9e574b1c --- /dev/null +++ b/apple/TableProTests/Core/Compare/CompareSchemaPairingTests.swift @@ -0,0 +1,82 @@ +// +// CompareSchemaPairingTests.swift +// TableProTests +// + +import Foundation +import Testing + +@testable import TablePro + +// SQL Server spells the listed schema on every table, so `app.dbo` against `app.staging` paired nothing: each table +// was listed as only in the source and again as only in the target. +struct CompareSchemaPairingTests { + private func snapshot(_ name: String, schema: String?) -> TableStructureSnapshot { + TableStructureSnapshot( + name: name, + schema: schema, + columns: [TestFixtures.makeEditableColumn(name: "id", dataType: "INT", isPrimaryKey: true)] + ) + } + + @Test + func tablesOfTwoSchemasPairWhenEachIsItsSidesOwn() { + let report = StructureDiffEngine().compare( + source: [snapshot("users", schema: "dbo"), snapshot("orders", schema: "dbo")], + target: [snapshot("users", schema: "staging"), snapshot("orders", schema: "staging")], + sourceSchema: "dbo", + targetSchema: "staging" + ) + + #expect(report.count(of: .identical) == 2) + #expect(report.count(of: .onlyInSource) == 0) + #expect(report.count(of: .onlyInTarget) == 0) + } + + // A window opened from a connection has no schema on its source, and SQL Server still lists `dbo` on each table. + @Test + func aSourceWithNoSchemaPairsThroughTheSchemaItsListingCarries() { + let source = [snapshot("users", schema: "dbo")] + let target = [snapshot("users", schema: "dbo")] + + let report = StructureDiffEngine().compare( + source: source, + target: target, + sourceSchema: StructureCompareOptions.listedSchema(endpoint: nil, tableSchemas: source.map(\.schema)), + targetSchema: StructureCompareOptions.listedSchema(endpoint: "dbo", tableSchemas: target.map(\.schema)) + ) + + #expect(report.count(of: .identical) == 1) + } + + @Test + func anotherSchemaInTheListingStillKeysItsOwnTables() { + let report = StructureDiffEngine().compare( + source: [snapshot("users", schema: "public"), snapshot("users", schema: "audit")], + target: [snapshot("users", schema: "public")], + sourceSchema: "public", + targetSchema: "public" + ) + + #expect(report.count(of: .identical) == 1) + #expect(report.count(of: .onlyInSource) == 1) + } + + @Test + func theListedSchemaIsTheEndpointsOrTheOneTheListingCarries() { + #expect(StructureCompareOptions.listedSchema(endpoint: "staging", tableSchemas: ["dbo"]) == "staging") + #expect(StructureCompareOptions.listedSchema(endpoint: nil, tableSchemas: ["dbo", "dbo"]) == "dbo") + #expect(StructureCompareOptions.listedSchema(endpoint: nil, tableSchemas: ["public", "audit"]) == nil) + #expect(StructureCompareOptions.listedSchema(endpoint: nil, tableSchemas: [nil, nil]) == nil) + #expect(StructureCompareOptions.listedSchema(endpoint: "", tableSchemas: []) == nil) + } + + @Test + func theListedSchemaFoldsLikeTheNameWhenCaseIsIgnored() { + var options = StructureCompareOptions.default + + #expect(options.matchKey(name: "Users", schema: "DBO", listedIn: "dbo") == options.matchKey("users")) + options.ignoreIdentifierCase = false + #expect(options.matchKey(name: "Users", schema: "DBO", listedIn: "dbo") != options.matchKey("Users")) + } +} diff --git a/apple/TableProTests/Core/Compare/CompareSyncExecutorTransactionOwnerTests.swift b/apple/TableProTests/Core/Compare/CompareSyncExecutorTransactionOwnerTests.swift new file mode 100644 index 0000000000..94c6b77940 --- /dev/null +++ b/apple/TableProTests/Core/Compare/CompareSyncExecutorTransactionOwnerTests.swift @@ -0,0 +1,215 @@ +// +// CompareSyncExecutorTransactionOwnerTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +// Answers the session's state the way PostgreSQL does: a failed statement inside a transaction aborts it. +private final class SessionStateDriver: PluginDriverStub, @unchecked Sendable { + var state: PluginSessionTransactionState + var events: [String] = [] + var failing: Set = [] + var abortsOnFailure = false + var rollbackError: (any Error)? + + init(state: PluginSessionTransactionState) { + self.state = state + } + + var supportsTransactions: Bool { true } + var supportsTransactionalDDL: Bool { true } + + func sessionTransactionState() async -> PluginSessionTransactionState { state } + + func execute(query: String) async throws -> PluginQueryResult { + events.append(query) + if failing.contains(query) { + if abortsOnFailure, state == .inTransaction { state = .abortedTransaction } + throw CompareSyncError.unsupportedOperation("duplicate key value violates unique constraint") + } + return PluginQueryResult(columns: [], columnTypeNames: [], rows: [], rowsAffected: 1, executionTime: 0) + } + + func beginTransaction() async throws { + events.append("BEGIN") + state = .inTransaction + } + + func commitTransaction() async throws { + events.append("COMMIT") + state = .idle + } + + func rollbackTransaction() async throws { + events.append("ROLLBACK") + if let rollbackError { throw rollbackError } + state = .idle + } +} + +private struct RollbackRefused: Error, LocalizedError { + var errorDescription: String? { "server closed the connection unexpectedly" } +} + +struct CompareSyncExecutorTransactionOwnerTests { + private let target = DatabaseEndpoint( + scope: DatabaseScope(connectionId: UUID(), database: "app", schema: nil), + connectionName: "local", + databaseType: .duckdb, + safeModeLevel: .silent, + color: .blue + ) + + private func apply( + _ sql: [String], + on driver: SessionStateDriver, + errorHandling: ImportErrorHandling = .stopAndRollback + ) async throws -> CompareSyncRunResult { + var settings = CompareSyncExecutionSettings() + settings.errorHandling = errorHandling + return try await CompareSyncExecutor(gate: AlwaysAllowGate()).apply( + statements: sql.map { SyncStatement(sql: $0, objectName: "t", summary: $0) }, + mode: .data, + settings: settings, + target: target, + driver: driver, + progress: Progress() + ) + } + + // MARK: - Who owns the transaction + + // On DuckDB and PGlite the target is the session itself, where the user's BEGIN may still be open. + @Test + func aTransactionTheSessionHoldsGetsNoBeginCommitOrRollbackOfTheRun() async throws { + let driver = SessionStateDriver(state: .inTransaction) + + let result = try await apply(["INSERT A;", "INSERT B;"], on: driver) + + #expect(driver.events == ["INSERT A;", "INSERT B;"]) + #expect(!result.rolledBack) + #expect(result.joinedSessionTransaction == .inTransaction) + } + + @Test + func aFailureInsideTheSessionsTransactionLeavesItsEndingToItsOwner() async throws { + let driver = SessionStateDriver(state: .inTransaction) + driver.failing = ["INSERT B;"] + driver.abortsOnFailure = true + + let result = try await apply(["INSERT A;", "INSERT B;", "INSERT C;"], on: driver) + + #expect(driver.events == ["INSERT A;", "INSERT B;"]) + #expect(!result.rolledBack) + #expect(result.joinedSessionTransaction == .abortedTransaction) + } + + @Test + func anIdleSessionGetsTheRunsOwnTransaction() async throws { + let driver = SessionStateDriver(state: .idle) + + let result = try await apply(["INSERT A;"], on: driver) + + #expect(driver.events == ["BEGIN", "INSERT A;", "COMMIT"]) + #expect(result.joinedSessionTransaction == nil) + } + + // MARK: - Stop and keep what ran + + // PostgreSQL answers that COMMIT with ROLLBACK and no error, so the 50 statements the result called kept were gone. + @Test + func stopAndKeepWhatRanReportsTheRollbackAnAbortedTransactionEndsIn() async throws { + let driver = SessionStateDriver(state: .idle) + driver.failing = ["INSERT B;"] + driver.abortsOnFailure = true + + let result = try await apply(["INSERT A;", "INSERT B;", "INSERT C;"], on: driver, errorHandling: .stopAndCommit) + + #expect(driver.events == ["BEGIN", "INSERT A;", "INSERT B;", "ROLLBACK"]) + #expect(result.rolledBack) + #expect(result.commitFailure == nil) + } + + @Test + func stopAndKeepWhatRanCommitsWhereAFailureLeavesTheTransactionOpen() async throws { + let driver = SessionStateDriver(state: .idle) + driver.failing = ["INSERT B;"] + + let result = try await apply(["INSERT A;", "INSERT B;", "INSERT C;"], on: driver, errorHandling: .stopAndCommit) + + #expect(driver.events == ["BEGIN", "INSERT A;", "INSERT B;", "COMMIT"]) + #expect(!result.rolledBack) + } + + @Test + func aRollbackThatFailsIsReportedRatherThanCountedAsDone() async throws { + let driver = SessionStateDriver(state: .idle) + driver.failing = ["INSERT B;"] + driver.rollbackError = RollbackRefused() + + let result = try await apply(["INSERT A;", "INSERT B;"], on: driver) + + #expect(driver.events.last == "ROLLBACK") + #expect(!result.rolledBack) + #expect(result.rollbackFailure == "server closed the connection unexpectedly") + } +} + +@MainActor +struct CompareSyncRunReportTests { + private let target = DatabaseEndpoint( + scope: DatabaseScope(connectionId: UUID(), database: "app", schema: nil), + connectionName: "local", + databaseType: .duckdb, + safeModeLevel: .silent, + color: .blue + ) + + private func failedRun(joined: PluginSessionTransactionState?, rollbackFailure: String? = nil) -> CompareSyncRunResult { + let ran = SyncStatement(sql: "INSERT A;", objectName: "t", summary: "A") + let failed = SyncStatement(sql: "INSERT B;", objectName: "t", summary: "B") + return CompareSyncRunResult( + outcomes: [ + SyncStatementOutcome(id: ran.id, statement: ran, error: nil, wasSkipped: false, didExecute: true), + SyncStatementOutcome(id: failed.id, statement: failed, error: "duplicate key", wasSkipped: false) + ], + rolledBack: false, + cancelled: false, + rollbackFailure: rollbackFailure, + joinedSessionTransaction: joined + ) + } + + @Test + func aRunThatJoinedAnAbortedTransactionSaysToRollItBackAndClaimsNothingApplied() { + let session = CompareSyncSession(connectionsProvider: { [] }) + + session.reportRunResult(failedRun(joined: .abortedTransaction), target: target) + + #expect(session.informationalMessage?.contains("can no longer be committed") == true) + #expect(session.errorMessage?.contains("stays applied") == false) + } + + @Test + func aRunThatJoinedAnOpenTransactionSaysItIsPending() { + let session = CompareSyncSession(connectionsProvider: { [] }) + + session.reportRunResult(failedRun(joined: .inTransaction), target: target) + + #expect(session.informationalMessage?.contains("Commit it to keep the changes") == true) + } + + @Test + func aFailedRollbackIsWhatTheWindowReports() { + let session = CompareSyncSession(connectionsProvider: { [] }) + + session.reportRunResult(failedRun(joined: nil, rollbackFailure: "connection lost"), target: target) + + #expect(session.errorMessage?.contains("could not be rolled back: connection lost") == true) + } +} diff --git a/apple/TableProTests/Core/Compare/CrossEngineTimestampCompareTests.swift b/apple/TableProTests/Core/Compare/CrossEngineTimestampCompareTests.swift new file mode 100644 index 0000000000..a7c26f2709 --- /dev/null +++ b/apple/TableProTests/Core/Compare/CrossEngineTimestampCompareTests.swift @@ -0,0 +1,65 @@ +// +// CrossEngineTimestampCompareTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +// A PostgreSQL server on Asia/Bangkok renders a timestamptz at +07. The copier and the sync write its wall clock into a +// MySQL datetime, and the comparator read that datetime as UTC, so every row stayed an update after every Apply. +struct CrossEngineTimestampCompareTests { + private let comparator = CellValueComparator(options: .default) + + private func written(_ value: PluginCellValue) -> PluginCellValue { + CrossEngineValueCoercer.coerce( + value, + pair: CrossEngineValueCoercer.ColumnPair( + source: SQLTypeParser.parse("timestamptz", family: .postgres).kind, + target: SQLTypeParser.parse("datetime", family: .mysql).kind + ), + from: .postgres, + to: .mysql + ) + } + + @Test + func aZonedSourceAndTheWallClockTheCopyWroteCompareEqual() { + let source = PluginCellValue.text("2024-01-01 10:00:00+07") + let target = written(source) + + #expect(target == .text("2024-01-01 10:00:00")) + #expect(comparator.compare(source, target, as: .temporal).isEqual) + } + + @Test + func aNaiveSourceAndTheZonedValueItReadsBackAsCompareEqual() { + let outcome = comparator.compare( + .text("2024-01-01 10:00:00.250000"), + .text("2024-01-01 10:00:00.25+07:00"), + as: .temporal + ) + + #expect(outcome.isEqual) + #expect(outcome.rule == .timestampPrecision) + } + + @Test + func anotherWallClockAgainstAZonedValueIsADifference() { + #expect(!comparator.compare(.text("2024-01-01 10:00:00+07"), .text("2024-01-01 03:00:00"), as: .temporal).isEqual) + } + + @Test + func twoZonedValuesStillCompareAsInstants() { + #expect(comparator.compare(.text("2024-01-01 10:00:00+07"), .text("2024-01-01 03:00:00+00:00"), as: .temporal).isEqual) + #expect(!comparator.compare(.text("2024-01-01 10:00:00+07"), .text("2024-01-01 10:00:00+00:00"), as: .temporal).isEqual) + } + + @Test + func anUndeclaredColumnFollowsTheSameRule() { + #expect(comparator.compare(.text("2024-01-01 10:00:00+07"), .text("2024-01-01 10:00:00"), as: .unknown).isEqual) + } +} diff --git a/apple/TableProTests/Core/Coordinators/InspectorDetachedStagingTests.swift b/apple/TableProTests/Core/Coordinators/InspectorDetachedStagingTests.swift new file mode 100644 index 0000000000..b49881d9fe --- /dev/null +++ b/apple/TableProTests/Core/Coordinators/InspectorDetachedStagingTests.swift @@ -0,0 +1,194 @@ +// +// InspectorDetachedStagingTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +// An inspector value window writes to the tab and records it opened on, never to whatever the inspector shows now. +@MainActor +struct InspectorDetachedStagingTests { + private static let userColumns = ["id", "name", "created_at", "doc"] + private static let userTypes: [ColumnType] = [ + .integer(rawType: "int4"), .text(rawType: "varchar"), .timestamp(rawType: "timestamptz"), .json(rawType: "jsonb") + ] + + private let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(type: .postgresql)) + private let editState = MultiRowEditState() + + private static func userRows(_ names: [String]) -> TableRows { + TableRows.from( + queryRows: names.enumerated().map { index, name in + [.text("\(index + 1)"), .text(name), .text("2024-01-01 00:00:00+00"), .text("{\"a\":1}")] + }, + columns: userColumns, + columnTypes: userTypes, + columnNullable: ["created_at": false], + hasAuthoritativeSchema: true + ) + } + + private func addTableTab(_ table: String, rows: TableRows, columns: [String]) -> UUID { + var tab = QueryTab(title: table, query: "SELECT * FROM \(table)", tabType: .table, tableName: table) + tab.execution.lastExecutedAt = Date() + fixture.addTab(tab, rows: rows) + fixture.coordinator.changeManager(forTab: tab.id).configureForTable( + tableName: table, + columns: columns, + primaryKeyColumns: ["id"], + databaseType: .postgresql, + generatedColumns: [], + triggerReload: false + ) + return tab.id + } + + // Wired the way the inspector wires it: configured from the selected tab, staged through the coordinator. + private func show(tab tabId: UUID, rowIDs: [RowID]) { + let rows = fixture.coordinator.tabSessionRegistry.tableRows(for: tabId) + let selected = rowIDs.compactMap { rows.row(withID: $0) } + editState.detachedStager = fixture.coordinator.rowEditingCoordinator + editState.configure( + tabId: tabId, + rowIDs: selected.map(\.id), + allRows: selected.map { $0.values.map(\.asText) }, + columns: rows.columns, + columnTypes: rows.columnTypes + ) + } + + private func usersTab() -> UUID { + addTableTab("users", rows: Self.userRows(["Alice", "Bob", "Carol"]), columns: Self.userColumns) + } + + private func ordersTab() -> UUID { + addTableTab( + "orders", + rows: TableRows.from( + queryRows: [[.text("10"), .text("5.00")], [.text("11"), .text("7.50")]], + columns: ["id", "total"], + columnTypes: [.integer(rawType: "int4"), .text(rawType: "numeric")], + hasAuthoritativeSchema: true + ), + columns: ["id", "total"] + ) + } + + private func change(in tabId: UUID, rowID: RowID, column: Int) -> CellChange? { + fixture.coordinator.changeManager(forTab: tabId).rowChanges + .first { $0.rowID == rowID && $0.type == .update }? + .cellChanges + .first { $0.columnIndex == column } + } + + private func value(in tabId: UUID, rowID: RowID, column: Int) -> PluginCellValue? { + fixture.coordinator.tabSessionRegistry.tableRows(for: tabId).row(withID: rowID)?.values[column] + } + + @Test("a window opened on one tab stages into that tab while another tab with the same row ids is shown") + func stagesIntoItsOwnTabAfterATabSwitch() throws { + let users = usersTab() + show(tab: users, rowIDs: [.existing(1)]) + let target = try #require(editState.holdDetachedField(columnIndex: 1)) + + let orders = ordersTab() + show(tab: orders, rowIDs: [.existing(1)]) + #expect(editState.commitDetachedField("Zed", to: target)) + + #expect(change(in: users, rowID: .existing(1), column: 1)?.newValue == .text("Zed")) + #expect(value(in: users, rowID: .existing(1), column: 1) == .text("Zed")) + #expect(!fixture.coordinator.changeManager(forTab: orders).hasChanges) + #expect(value(in: orders, rowID: .existing(1), column: 1) == .text("7.50")) + } + + @Test("a re-run that puts another record at the window's row id ends the window's edits") + func refusesAReplacedRecord() throws { + let users = usersTab() + show(tab: users, rowIDs: [.existing(1)]) + let target = try #require(editState.holdDetachedField(columnIndex: 1)) + + fixture.coordinator.setActiveTableRows(Self.userRows(["Carol", "Alice", "Bob"]), for: users) + + #expect(!editState.commitDetachedField("Zed", to: target)) + #expect(!fixture.coordinator.changeManager(forTab: users).hasChanges) + #expect(value(in: users, rowID: .existing(1), column: 1) == .text("Alice")) + } + + @Test("a row deleted after the window opened takes no edit") + func refusesADeletedRow() throws { + let users = usersTab() + show(tab: users, rowIDs: [.existing(1)]) + let target = try #require(editState.holdDetachedField(columnIndex: 1)) + let original = try #require(fixture.coordinator.tabSessionRegistry.tableRows(for: users).row(withID: .existing(1))) + + fixture.coordinator.changeManager(forTab: users).recordRowDeletion(rowID: .existing(1), originalRow: Array(original.values)) + + #expect(!editState.commitDetachedField("Zed", to: target)) + #expect(change(in: users, rowID: .existing(1), column: 1) == nil) + } + + @Test("a closed tab ends the window's edits") + func refusesAClosedTab() throws { + let users = usersTab() + show(tab: users, rowIDs: [.existing(1)]) + let target = try #require(editState.holdDetachedField(columnIndex: 1)) + let orders = ordersTab() + show(tab: orders, rowIDs: [.existing(0)]) + + fixture.tabManager.tabs.removeAll { $0.id == users } + + #expect(!editState.commitDetachedField("Zed", to: target)) + } + + @Test("typing goes on across the window's own writes, as one typed run") + func ownWritesKeepTheHold() throws { + let users = usersTab() + show(tab: users, rowIDs: [.existing(1)]) + let target = try #require(editState.holdDetachedField(columnIndex: 1)) + show(tab: ordersTab(), rowIDs: [.existing(0)]) + + #expect(editState.commitDetachedField("Z", to: target)) + #expect(editState.commitDetachedField("Ze", to: target)) + + #expect(change(in: users, rowID: .existing(1), column: 1)?.newValue == .text("Ze")) + #expect(change(in: users, rowID: .existing(1), column: 1)?.oldValue == .text("Bob")) + } + + // Two windows on one record: the first one's write must not read as another record to the second. + @Test("a SQL function typed in the window is staged as SQL by the window's own tab, plain text stays text") + func typedFunctionIsPromotedByTheTargetTab() throws { + let users = usersTab() + show(tab: users, rowIDs: [.existing(1)]) + let timestamp = try #require(editState.holdDetachedField(columnIndex: 2)) + let name = try #require(editState.holdDetachedField(columnIndex: 1)) + show(tab: ordersTab(), rowIDs: [.existing(0)]) + + #expect(editState.commitDetachedField("CURRENT_TIMESTAMP", to: timestamp)) + #expect(editState.commitDetachedField("now()", to: name)) + + let changes = fixture.coordinator.changeManager(forTab: users) + #expect(change(in: users, rowID: .existing(1), column: 2)?.newValue == .text("CURRENT_TIMESTAMP")) + #expect(changes.isExpression(rowID: .existing(1), columnIndex: 2)) + #expect(change(in: users, rowID: .existing(1), column: 1)?.newValue == .text("now()")) + #expect(!changes.isExpression(rowID: .existing(1), columnIndex: 1)) + } + + @Test("a cleared JSON value goes to the window's rows as NULL, a cleared NOT NULL value stages nothing") + func clearedValuesFollowTheTargetColumn() throws { + let users = usersTab() + show(tab: users, rowIDs: [.existing(1)]) + let doc = try #require(editState.holdDetachedField(columnIndex: 3)) + let createdAt = try #require(editState.holdDetachedField(columnIndex: 2)) + show(tab: ordersTab(), rowIDs: [.existing(0)]) + + #expect(editState.commitDetachedField("", to: createdAt)) + #expect(change(in: users, rowID: .existing(1), column: 2) == nil) + + #expect(editState.commitDetachedField("", to: doc)) + #expect(change(in: users, rowID: .existing(1), column: 3)?.newValue == .null) + } +} diff --git a/apple/TableProTests/Core/Database/DatabaseAccessBridgeExplainHoldTests.swift b/apple/TableProTests/Core/Database/DatabaseAccessBridgeExplainHoldTests.swift new file mode 100644 index 0000000000..eb86aa375d --- /dev/null +++ b/apple/TableProTests/Core/Database/DatabaseAccessBridgeExplainHoldTests.swift @@ -0,0 +1,98 @@ +// +// DatabaseAccessBridgeExplainHoldTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +private final class PlanningDriver: PluginDriverStub, @unchecked Sendable { + private let lock = NSLock() + private var sent: [String] = [] + private var state: PluginSessionTransactionState = .idle + + var statements: [String] { lock.withLock { sent } } + + func execute(query: String) async throws -> PluginQueryResult { + lock.withLock { + sent.append(query) + switch query.uppercased() { + case "BEGIN": state = .inTransaction + case "COMMIT", "ROLLBACK": state = .idle + default: break + } + } + return .empty + } + + func explainPlan(statement: String, variantId: String) async throws -> PluginQueryResult { + lock.withLock { sent.append("PLAN \(variantId): \(statement)") } + return .empty + } + + func sessionTransactionState() async -> PluginSessionTransactionState { lock.withLock { state } } + + func switchDatabase(to database: String) async throws {} +} + +// An actual plan runs the statement, so an MCP explain_query in Manual Commit is held the way execute_query is. +@MainActor +struct DatabaseAccessBridgeExplainHoldTests { + private static let update = "UPDATE t SET a = 1" + + private func seed() -> (connection: DatabaseConnection, driver: PlanningDriver) { + var connection = TestFixtures.makeConnection(database: "app", type: .postgresql) + connection.commitMode = .manual + let driver = PlanningDriver() + var session = ConnectionSession( + connection: connection, + driver: PluginDriverAdapter(connection: connection, pluginDriver: driver) + ) + session.browseDatabase = "app" + session.status = .connected + DatabaseManager.shared.injectSession(session, for: connection.id) + return (connection, driver) + } + + private func plan(_ connection: DatabaseConnection, runsStatement: Bool) async throws -> QueryResult { + let scope = DatabaseScope(connectionId: connection.id, database: "app", schema: nil) + let operation = try await ApprovedOperationFixture.approve( + [OperationStatement(sql: Self.update)], scope: scope, databaseType: .postgresql + ) + let outcome = try await DatabaseAccessBridge().runExplainPlan( + operation, + step: ExplainRequest.DriverStep(variantId: "actual", runsStatement: runsStatement), + timeoutSeconds: 30, + cancellation: nil + ) + return outcome.result + } + + @Test("A plan that runs a write in Manual Commit opens the transaction first and leaves it for the user") + func runningPlanIsHeld() async throws { + let (connection, driver) = seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + + let result = try await plan(connection, runsStatement: true) + + let begin = try #require(driver.statements.firstIndex(of: "BEGIN")) + let plan = try #require(driver.statements.firstIndex(of: "PLAN actual: \(Self.update)")) + #expect(begin < plan) + #expect(!driver.statements.contains("COMMIT")) + #expect(result.statusMessage?.contains(ManualCommit.pendingNotice) == true) + } + + @Test("A plan that only plans the write opens no transaction") + func plannedOnlyIsNotHeld() async throws { + let (connection, driver) = seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + + let result = try await plan(connection, runsStatement: false) + + #expect(driver.statements.contains("PLAN actual: \(Self.update)")) + #expect(!driver.statements.contains("BEGIN")) + #expect(result.statusMessage == nil) + } +} diff --git a/apple/TableProTests/Core/Database/DisconnectWhileConnectingTests.swift b/apple/TableProTests/Core/Database/DisconnectWhileConnectingTests.swift new file mode 100644 index 0000000000..bd902543b4 --- /dev/null +++ b/apple/TableProTests/Core/Database/DisconnectWhileConnectingTests.swift @@ -0,0 +1,139 @@ +// +// DisconnectWhileConnectingTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProTestSupport +import Testing + +@MainActor +private final class HeldScriptQuestion: PreConnectScriptAsking { + let gate = AsyncGate() + + func ask(connectionName: String, script: String, postDisconnectScript: String?) async -> ConsentAnswer { + await gate.wait() + return .approved + } +} + +private final class RanPostDisconnectScripts: @unchecked Sendable { + private let lock = NSLock() + private var recorded: [PendingPostDisconnectScript] = [] + + var scripts: [PendingPostDisconnectScript] { lock.withLock { recorded } } + + func record(_ script: PendingPostDisconnectScript) { + lock.withLock { recorded.append(script) } + } +} + +// Closing a connection that is still connecting must end the connect too, or it finishes with nothing that owns its +// driver, its tunnel or its post-disconnect script. +@MainActor +struct DisconnectWhileConnectingTests { + private struct Fixture { + let manager: DatabaseManager + let question: HeldScriptQuestion + let ran: RanPostDisconnectScripts + let connection: DatabaseConnection + let marker: URL + let cleanUp: () async -> Void + + var scriptRan: Bool { FileManager.default.fileExists(atPath: marker.path) } + } + + private func makeFixture(preConnectScript: Bool) throws -> Fixture { + FakeMSSQLPluginRegistration.registerIfNeeded() + let unique = UUID().uuidString + let fileURL = FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-disconnect-connecting-\(unique).json") + let marker = FileManager.default.temporaryDirectory + .appendingPathComponent("tablepro-disconnect-connecting-ran-\(unique)") + let suite = try EphemeralDefaults() + let storage = ConnectionStorage(fileURL: fileURL, userDefaults: suite.defaults, keychain: InMemoryKeychain()) + let question = HeldScriptQuestion() + let ran = RanPostDisconnectScripts() + let manager = DatabaseManager( + connectionStorage: storage, + preConnectScriptConsent: PreConnectScriptConsent(asker: question), + postDisconnectScripts: PostDisconnectScripts(run: { ran.record($0) }), + recoveryClock: ManualClock() + ) + + var connection = TestFixtures.makeConnection(name: "Closing", type: .mssql) + connection.username = "reporting" + if preConnectScript { + connection.preConnectScript = "touch '\(marker.path)'" + connection.postDisconnectScript = "vpn down" + } + storage.addConnection(connection) + FakeMSSQLPlugin.recordConfigurations(for: connection.id) + + let connectionId = connection.id + return Fixture( + manager: manager, + question: question, + ran: ran, + connection: connection, + marker: marker, + cleanUp: { + await manager.stopHealthMonitor(for: connectionId) + manager.driver(for: connectionId)?.disconnect() + manager.removeSession(for: connectionId) + FakeMSSQLPlugin.clearConnectHold(for: connectionId) + FakeMSSQLPlugin.clearConfigurations(for: connectionId) + suite.defaults.removePersistentDomain(forName: suite.suiteName) + try? FileManager.default.removeItem(at: fileURL) + try? FileManager.default.removeItem(at: marker) + } + ) + } + + @Test("Closing while the pre-connect script waits for consent runs no script, opens no driver and arms nothing") + func closeDuringConsentStopsTheConnect() async throws { + let fixture = try makeFixture(preConnectScript: true) + let id = fixture.connection.id + let manager = fixture.manager + let connection = fixture.connection + + let connect = Task { try await manager.ensureConnected(connection) } + await fixture.question.gate.arrived(1) + #expect(manager.session(for: id) != nil) + + await manager.disconnectSession(id, origin: .userRequested) + await fixture.question.gate.open() + let outcome = await connect.result + + #expect(throws: CancellationError.self) { try outcome.get() } + #expect(!fixture.scriptRan) + #expect(FakeMSSQLPlugin.configurations(for: id).isEmpty) + #expect(!manager.postDisconnectScripts.isArmed(for: id)) + #expect(fixture.ran.scripts.isEmpty) + #expect(manager.session(for: id) == nil) + #expect(manager.healthMonitors[id] == nil) + await fixture.cleanUp() + } + + @Test("A connect whose entry went with no cancel reaching it ends instead of finishing unowned") + func connectWithItsEntryGoneEnds() async throws { + let fixture = try makeFixture(preConnectScript: false) + let id = fixture.connection.id + let manager = fixture.manager + let connection = fixture.connection + let hold = FakeMSSQLPlugin.holdConnect(for: id) + + let connect = Task { try await manager.ensureConnected(connection) } + await hold.waitUntilReached() + manager.removeSession(for: id) + await hold.release() + let outcome = await connect.result + + #expect(throws: CancellationError.self) { try outcome.get() } + #expect(manager.session(for: id) == nil) + #expect(manager.healthMonitors[id] == nil) + #expect(manager.currentStage(for: id) == nil) + await fixture.cleanUp() + } +} diff --git a/apple/TableProTests/Core/Database/ResolveScopeReachabilityTests.swift b/apple/TableProTests/Core/Database/ResolveScopeReachabilityTests.swift new file mode 100644 index 0000000000..c38469da05 --- /dev/null +++ b/apple/TableProTests/Core/Database/ResolveScopeReachabilityTests.swift @@ -0,0 +1,96 @@ +// +// ResolveScopeReachabilityTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProMCP +import Testing + +private actor DiscardingHistory: QueryHistoryRecording { + func record(_ request: QueryHistoryRecordRequest) async -> Bool { true } +} + +// A statement is pinned only to a container its engine can switch to, so a name it cannot reach is refused up front +// rather than dropped at the pin, where the statement would run in the session's own database. +@MainActor +struct ResolveScopeReachabilityTests { + private func session(_ type: DatabaseType, database: String) -> ScriptAnsweringDriver { + var connection = TestFixtures.makeConnection(database: database, type: type) + connection.aiPolicy = .alwaysAllow + let driver = ScriptAnsweringDriver(connection: connection) + var session = ConnectionSession(connection: connection) + session.driver = driver + DatabaseManager.shared.injectSession(session, for: connection.id) + return driver + } + + @Test("A fixed-database connection refuses another database and keeps its own") + func fixedDatabaseRefusesAnother() async throws { + let driver = session(.sqlite, database: "prod.sqlite") + defer { DatabaseManager.shared.removeSession(for: driver.connection.id) } + let bridge = DatabaseAccessBridge() + let id = driver.connection.id + + await #expect(throws: DatabaseAccessError.self) { + _ = try await bridge.resolveScope(connectionId: id, database: "staging.sqlite", schema: nil) + } + let named = try await bridge.resolveScope(connectionId: id, database: "prod.sqlite", schema: nil) + let unnamed = try await bridge.resolveScope(connectionId: id, database: nil, schema: nil) + #expect(named.database == "prod.sqlite") + #expect(unnamed.database == "prod.sqlite") + } + + @Test("An engine with no schemas refuses a schema, and one that switches databases still takes another database") + func schemaLessEngineRefusesASchema() async throws { + let driver = session(.mysql, database: "shop") + defer { DatabaseManager.shared.removeSession(for: driver.connection.id) } + let bridge = DatabaseAccessBridge() + let id = driver.connection.id + + await #expect(throws: DatabaseAccessError.self) { + _ = try await bridge.resolveScope(connectionId: id, database: nil, schema: "archive") + } + let other = try await bridge.resolveScope(connectionId: id, database: "warehouse", schema: nil) + #expect(other.database == "warehouse") + } + + @Test("A schema-switching engine still takes another schema") + func schemaEngineTakesASchema() async throws { + let driver = session(.postgresql, database: "shop") + defer { DatabaseManager.shared.removeSession(for: driver.connection.id) } + + let scope = try await DatabaseAccessBridge().resolveScope( + connectionId: driver.connection.id, database: nil, schema: "archive" + ) + + #expect(scope.schema == "archive") + } + + @Test("MCP execute_query naming another database on a fixed-database connection runs nothing") + func mcpExecuteQueryRefusesAnotherDatabase() async { + let driver = session(.sqlite, database: "prod.sqlite") + defer { DatabaseManager.shared.removeSession(for: driver.connection.id) } + let services = MCPToolServices( + connectionBridge: MCPConnectionBridge(), + authPolicy: MCPAuthPolicy( + connectionResolver: { _ in nil }, connectionIdsProvider: { [] }, historyRecorder: DiscardingHistory() + ) + ) + + await #expect(throws: (any Error).self) { + _ = try await ExecuteQueryTool().perform( + arguments: .object([ + "connection_id": .string(driver.connection.id.uuidString), + "query": .string("SELECT * FROM orders"), + "database": .string("staging.sqlite") + ]), + context: MCPToolTestHarness.context(), + services: services + ) + } + + #expect(driver.sentStatements.isEmpty && driver.sentBatches.isEmpty) + } +} diff --git a/apple/TableProTests/Core/Export/TableTransferDestinationSchemaTests.swift b/apple/TableProTests/Core/Export/TableTransferDestinationSchemaTests.swift new file mode 100644 index 0000000000..30ab06b881 --- /dev/null +++ b/apple/TableProTests/Core/Export/TableTransferDestinationSchemaTests.swift @@ -0,0 +1,118 @@ +// +// TableTransferDestinationSchemaTests.swift +// TableProTests +// + +import Foundation +import TableProPluginKit +import Testing + +@testable import TablePro + +private final class SchemaTransferStubDriver: PluginDriverStub, @unchecked Sendable { + let header: [String] + let rows: [PluginRow] + let columns: [String] + private(set) var executedQueries: [String] = [] + private(set) var columnReadSchemas: [String?] = [] + + init(header: [String] = [], rows: [PluginRow] = [], columns: [String] = []) { + self.header = header + self.rows = rows + self.columns = columns + } + + func quoteIdentifier(_ name: String) -> String { + "\"\(name.replacingOccurrences(of: "\"", with: "\"\""))\"" + } + + func defaultExportQuery(table: String, schema: String?) -> String? { + "SELECT * FROM \(table)" + } + + func streamRows(query: String) -> AsyncThrowingStream { + let header = PluginStreamHeader(columns: header, columnTypeNames: header.map { _ in "TEXT" }) + let rows = rows + return AsyncThrowingStream { continuation in + continuation.yield(.header(header)) + continuation.yield(.rows(rows)) + continuation.finish() + } + } + + func execute(query: String) async throws -> PluginQueryResult { + executedQueries.append(query) + return PluginQueryResult(columns: [], columnTypeNames: [], rows: [], rowsAffected: 0, executionTime: 0) + } + + func executeParameterized(query: String, parameters: [PluginCellValue]) async throws -> PluginQueryResult { + executedQueries.append(query) + return PluginQueryResult(columns: [], columnTypeNames: [], rows: [], rowsAffected: 1, executionTime: 0) + } + + func fetchColumns(table: String, schema: String?) async throws -> [PluginColumnInfo] { + columnReadSchemas.append(schema) + return columns.map { PluginColumnInfo(name: $0, dataType: "TEXT") } + } +} + +// The destination had `sales.orders` and an older `public.orders`. With no schema the DELETE and the INSERTs resolved +// through the session's search_path, emptied and refilled `public.orders`, and left `sales.orders` untouched. +struct TableTransferDestinationSchemaTests { + private func adapter(_ driver: SchemaTransferStubDriver, type: DatabaseType) -> PluginDriverAdapter { + PluginDriverAdapter(connection: DatabaseConnection(name: "Test", type: type), pluginDriver: driver) + } + + @MainActor @Test + func theDeleteAndTheInsertsNameTheDestinationSchema() async throws { + let source = SchemaTransferStubDriver( + header: ["id", "total"], rows: [[.text("1"), .text("9.50")]], columns: ["id", "total"] + ) + let destination = SchemaTransferStubDriver(columns: ["id", "total"]) + let request = TableTransferService.Request( + objects: [ExportObjectItem(name: "orders", kind: .table, isSelected: true)], + sourceType: .mysql, + destinationType: .postgresql, + destinationSchema: "sales", + sourceColumns: ["orders": ["id", "total"]], + deleteExistingRows: true, + wrapInTransaction: false + ) + + try await TableTransferService().transfer( + request: request, + sourceDriver: adapter(source, type: .mysql), + destinationDriver: adapter(destination, type: .postgresql) + ) + + let writes = destination.executedQueries.filter { $0.contains("orders") } + #expect(writes.contains { $0.uppercased().hasPrefix("DELETE") || $0.uppercased().hasPrefix("TRUNCATE") }) + #expect(writes.contains { $0.uppercased().hasPrefix("INSERT") }) + #expect(writes.allSatisfy { $0.contains("\"sales\".\"orders\"") }) + #expect(destination.columnReadSchemas.allSatisfy { $0 == "sales" }) + } + + @Test + func theSourcesSchemaIsTheDefaultWhenTheDestinationHasIt() { + let pick = TableTransferSheet.defaultDestinationSchema( + source: "sales", current: "public", engineDefault: "public", available: ["public", "sales"] + ) + #expect(pick == "sales") + } + + @Test + func theDestinationsOwnSchemaIsTheDefaultOtherwise() { + #expect(TableTransferSheet.defaultDestinationSchema( + source: "dbo", current: "reporting", engineDefault: "public", available: ["public", "reporting"] + ) == "reporting") + #expect(TableTransferSheet.defaultDestinationSchema( + source: nil, current: nil, engineDefault: "public", available: ["audit", "public"] + ) == "public") + #expect(TableTransferSheet.defaultDestinationSchema( + source: nil, current: nil, engineDefault: "dbo", available: ["audit"] + ) == "audit") + #expect(TableTransferSheet.defaultDestinationSchema( + source: "sales", current: nil, engineDefault: nil, available: [] + ).isEmpty) + } +} diff --git a/apple/TableProTests/Core/SSH/Auth/BuildJumpAuthenticatorTests.swift b/apple/TableProTests/Core/SSH/Auth/BuildJumpAuthenticatorTests.swift new file mode 100644 index 0000000000..ba2d251fa5 --- /dev/null +++ b/apple/TableProTests/Core/SSH/Auth/BuildJumpAuthenticatorTests.swift @@ -0,0 +1,98 @@ +import Foundation +@testable import TableProSSHConfig +import TableProSSHTransport +import Testing + +@testable import TablePro + +// A bastion with `AuthenticationMethods publickey,keyboard-interactive` takes the key as one factor and +// asks for a code next, so every jump hop chain ends in keyboard-interactive, as the SSH host's does (#1920). +struct BuildJumpAuthenticatorTests { + private func resolved(identityFiles: [String] = [], agentDisabled: Bool = false) -> ResolvedSSHTarget { + ResolvedSSHTarget( + originalHost: "bastion.example.com", + host: "bastion.example.com", + port: 22, + username: "jump", + identityFiles: identityFiles, + agentSocketPath: "", + agentSocketOrigin: .environment, + agentDisabled: agentDisabled, + identitiesOnly: false, + useKeychain: false, + addKeysToAgent: false, + proxyJump: [] + ) + } + + private let credentials = SSHTunnelCredentials( + sshPassword: "the SSH host's password", + keyPassphrase: nil, + totpSecret: "JBSWY3DPEHPK3PXP", + keyboardInteractivePromptProvider: nil + ) + + private func hop(_ authMethod: SSHJumpAuthMethod, privateKeyPath: String = "") -> SSHJumpHost { + SSHJumpHost(host: "bastion.example.com", username: "jump", authMethod: authMethod, privateKeyPath: privateKeyPath) + } + + private func buildChain(_ jumpHost: SSHJumpHost, _ target: ResolvedSSHTarget) throws -> CompositeAuthenticator { + let authenticator = try LibSSH2TunnelFactory.buildJumpAuthenticator( + jumpHost: jumpHost, + resolved: target, + credentials: credentials + ) + return try #require(authenticator as? CompositeAuthenticator) + } + + // The hop prompts for its code: the SSH host's password and TOTP secret belong to another server. + private func expectPromptedSecondFactor(_ chain: CompositeAuthenticator) throws { + let secondFactor = try #require(chain.authenticators.last as? KeyboardInteractiveAuthenticator) + #expect(secondFactor.password == nil) + #expect(secondFactor.totpProvider == nil) + } + + @Test("A private key hop asks for a second factor after its one key") + func privateKeyHopEndsInKeyboardInteractive() throws { + let chain = try buildChain(hop(.privateKey, privateKeyPath: "/home/alice/.ssh/bastion"), resolved(identityFiles: ["/home/alice/.ssh/bastion"])) + + #expect(chain.authenticators.count == 2) + try expectPromptedSecondFactor(chain) + } + + @Test("A private key hop tries every resolved key before the second factor") + func privateKeyHopKeepsEveryKey() throws { + let chain = try buildChain(hop(.privateKey), resolved(identityFiles: ["/home/alice/.ssh/id_ed25519", "/home/alice/.ssh/id_rsa"])) + + #expect(chain.authenticators.count == 3) + try expectPromptedSecondFactor(chain) + } + + @Test("An SSH agent hop asks for a second factor, and stops when the agent offered no key") + func agentHopEndsInKeyboardInteractive() throws { + let chain = try buildChain(hop(.sshAgent), resolved()) + + #expect(chain.authenticators.count == 2) + #expect(chain.authenticators.first is AgentAuthenticator) + try expectPromptedSecondFactor(chain) + #expect(chain.endsChainOn.contains(.agentUnavailable(.environment))) + } + + @Test("An SSH agent hop with a key file falls back to the key, then asks for a second factor") + func agentHopWithKeyFileEndsInKeyboardInteractive() throws { + let chain = try buildChain(hop(.sshAgent, privateKeyPath: "/home/alice/.ssh/bastion"), resolved()) + + #expect(chain.authenticators.count == 3) + #expect(chain.authenticators.first is AgentAuthenticator) + try expectPromptedSecondFactor(chain) + #expect(chain.endsChainOn.isEmpty) + } + + @Test("A hop whose agent the config turns off signs in with its key, then asks for a second factor") + func agentDisabledHopEndsInKeyboardInteractive() throws { + let chain = try buildChain(hop(.sshAgent, privateKeyPath: "/home/alice/.ssh/bastion"), resolved(agentDisabled: true)) + + #expect(chain.authenticators.count == 2) + try expectPromptedSecondFactor(chain) + } +} diff --git a/apple/TableProTests/Core/Services/TeamCatalogPublisherTests.swift b/apple/TableProTests/Core/Services/TeamCatalogPublisherTests.swift index 69e05a8227..085eabddea 100644 --- a/apple/TableProTests/Core/Services/TeamCatalogPublisherTests.swift +++ b/apple/TableProTests/Core/Services/TeamCatalogPublisherTests.swift @@ -115,6 +115,28 @@ struct TeamCatalogPublisherTests { #expect(!raw.contains("passwordSource")) } + @Test("Published file carries neither the tunnel command nor the startup commands") + func publishLeavesCommandsOut() throws { + let folder = try makeTempDirectory() + defer { try? FileManager.default.removeItem(at: folder) } + var connection = DatabaseConnection(name: "Prod DB", type: .postgresql) + connection.tunnelCommandMode = .inline(TunnelCommandConfiguration( + method: .custom, + command: "cloudflared access tcp --url localhost:{port} --service-token-secret S3cret" + )) + connection.startupCommands = "SET app.token = 'S3cret';" + try #require(ConnectionBundleExporter().portableSettings(for: connection).tunnelCommand != nil) + + let written = try TeamCatalogPublisher.publish([connection], to: folder) + + let data = try Data(contentsOf: try #require(written.first)) + let settings = try #require(try ConnectionBundleCodec.decode(data).connections.first?.settings) + #expect(settings.name == "Prod DB") + #expect(settings.tunnelCommand == nil) + #expect(settings.startupCommands == nil) + #expect(!(String(bytes: data, encoding: .utf8) ?? "").contains("S3cret")) + } + @Test("Filename is filesystem-safe and keyed by connection id") func filenameIsFilesystemSafeAndStable() { let connection = DatabaseConnection(name: "Prod / DB: primary") diff --git a/apple/TableProTests/Core/Storage/ProfileStorageSafetyTests.swift b/apple/TableProTests/Core/Storage/ProfileStorageSafetyTests.swift index 5f4c37266e..ab8d0c8364 100644 --- a/apple/TableProTests/Core/Storage/ProfileStorageSafetyTests.swift +++ b/apple/TableProTests/Core/Storage/ProfileStorageSafetyTests.swift @@ -121,7 +121,7 @@ struct ProfileStorageSafetyTests { let profile = CredentialProfile(name: "Prod reader", username: "app_reader") #expect(storage.addProfile(profile)) - #expect(!storage.unlinkConnections(from: profile)) + #expect(!storage.unlinkConnections(from: profile, byUser: true)) #expect(!storage.deleteProfile(profile)) #expect(storage.profile(for: profile.id) != nil) } @@ -133,7 +133,7 @@ struct ProfileStorageSafetyTests { let profile = makeSSHProfile() #expect(storage.addProfile(profile)) - #expect(!storage.unlinkConnections(fromProfile: profile)) + #expect(!storage.unlinkConnections(fromProfile: profile, byUser: true)) #expect(!storage.deleteProfile(profile)) #expect(storage.profile(for: profile.id) != nil) } diff --git a/apple/TableProTests/Core/Sync/SyncProfileDeletionTrustTests.swift b/apple/TableProTests/Core/Sync/SyncProfileDeletionTrustTests.swift new file mode 100644 index 0000000000..9c21b89f99 --- /dev/null +++ b/apple/TableProTests/Core/Sync/SyncProfileDeletionTrustTests.swift @@ -0,0 +1,97 @@ +import CloudKit +import Foundation +@testable import TablePro +import TableProSSHConfig +import TableProSyncTransport +import Testing + +@MainActor +struct SyncProfileDeletionTrustTests { + private static let zoneID = SyncTestEnvironment.zoneID + private let environment: SyncTestEnvironment + + init() throws { + environment = try SyncTestEnvironment(label: "sync-profile-deletion-trust") + } + + private var connectionsFileURL: URL { + environment.directory.appendingPathComponent("connections.json") + } + + // Same records, different bytes, tag left as it was: what any editor outside TablePro leaves behind. + private func editConnectionsOutsideTablePro() throws { + let original = try Data(contentsOf: connectionsFileURL) + let object = try JSONSerialization.jsonObject(with: original) + try JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]).write(to: connectionsFileURL) + environment.connections.invalidateCache() + _ = environment.connections.loadConnections() + } + + private func pullDeletion(of type: SyncRecordType, id: UUID) async -> Bool { + let coordinator = environment.makeCoordinator(transport: ScriptedSyncTransport(zoneID: Self.zoneID)) + return await coordinator.applyPullResult(PullResult( + changedRecords: [], + deletedRecordIDs: [SyncRecordMapper.recordID(type: type, id: id.uuidString, in: Self.zoneID)], + newToken: nil + )) + } + + private func expectStillUntrusted() { + #expect(!environment.connections.storeIsTrusted) + environment.connections.invalidateCache() + _ = environment.connections.loadConnections() + #expect(!environment.connections.storeIsTrusted) + } + + @Test("An SSH profile deleted on another Mac converts its connections without signing a connections.json edited elsewhere") + func remoteSSHProfileDeletionKeepsUntrustedFileUntrusted() async throws { + let profiles = SSHProfileStorage( + userDefaults: environment.defaults, + keychain: environment.keychain, + syncTracker: environment.tracker, + connectionStorage: environment.connections + ) + let profile = SSHProfile(name: "Bastion", host: "bastion.example.com", port: 22, username: "deploy", authMethod: .password) + #expect(profiles.addProfile(profile)) + var connection = TestFixtures.makeConnection() + connection.sshTunnelMode = .profile(id: profile.id, snapshot: profile.toSSHConfiguration()) + connection.sshConfig = profile.toSSHConfiguration() + connection.sshProfileId = profile.id + #expect(environment.connections.addConnection(connection)) + try editConnectionsOutsideTablePro() + try #require(!environment.connections.storeIsTrusted) + + #expect(await pullDeletion(of: .sshProfile, id: profile.id)) + + let converted = try #require(environment.connections.loadConnection(id: connection.id)) + #expect(!converted.isLinked(toSSHProfile: profile.id)) + #expect(converted.resolvedSSHConfig.host == "bastion.example.com") + expectStillUntrusted() + } + + @Test("A credential profile deleted on another Mac converts its connections without signing a connections.json edited elsewhere") + func remoteCredentialProfileDeletionKeepsUntrustedFileUntrusted() async throws { + let profiles = CredentialProfileStorage( + fileURL: environment.directory.appendingPathComponent("credentialProfiles.json"), + keychain: environment.keychain, + syncTracker: environment.tracker, + connectionStorage: environment.connections, + integrity: ConnectionStoreIntegrity(keySource: StoredIntegrityKeySource(store: environment.keychain)) + ) + let profile = CredentialProfile(name: "Prod reader", username: "app_reader", passwordMode: .stored) + #expect(profiles.addProfile(profile)) + var connection = TestFixtures.makeConnection() + connection.credentialMode = .profile(id: profile.id) + connection.username = profile.username + #expect(environment.connections.addConnection(connection)) + try editConnectionsOutsideTablePro() + try #require(!environment.connections.storeIsTrusted) + + #expect(await pullDeletion(of: .credentialProfile, id: profile.id)) + + let converted = try #require(environment.connections.loadConnection(id: connection.id)) + #expect(converted.credentialMode == .inline) + #expect(converted.username == "app_reader") + expectStillUntrusted() + } +} diff --git a/apple/TableProTests/Core/Sync/SyncSettingsUnreadOptionsTests.swift b/apple/TableProTests/Core/Sync/SyncSettingsUnreadOptionsTests.swift new file mode 100644 index 0000000000..fa8dc69ae5 --- /dev/null +++ b/apple/TableProTests/Core/Sync/SyncSettingsUnreadOptionsTests.swift @@ -0,0 +1,131 @@ +import CloudKit +import Foundation +@testable import TablePro +import TableProSyncTransport +import Testing + +@MainActor +struct SyncSettingsUnreadOptionsTests { + private static let zoneID = SyncTestEnvironment.zoneID + private static let editor = AppSettingsCategory.editor + + private static func encoded(_ settings: EditorSettings) throws -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys + return try encoder.encode(settings) + } + + // The document a newer build writes: this build's options plus one it has no field for. + private static func newerDocument(_ settings: EditorSettings, futureOption: String = "kept") throws -> Data { + var object = try #require(try JSONSerialization.jsonObject(with: encoded(settings)) as? [String: Any]) + object["futureOption"] = futureOption + return try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) + } + + private static func document(of record: CKRecord) throws -> [String: Any] { + let data = try #require(SyncRecordMapper.settingsData(from: record)) + return try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + } + + private static func record(_ data: Data) -> CKRecord { + SyncRecordMapper.toCKRecord(category: editor, settingsData: data, in: zoneID) + } + + @Test("A push keeps an option a newer build wrote into the record it builds on") + func pushKeepsAnOptionThisBuildCannotRead() throws { + let base = Self.record(try Self.newerDocument(.default)) + + let edit = SyncRecordMapper.settingsEdit( + category: Self.editor, + settingsData: try Self.encoded(EditorSettings(tabWidth: 2)), + in: Self.zoneID, + base: base + ) + + let pushed = try Self.document(of: edit.record) + #expect(pushed["futureOption"] as? String == "kept") + #expect(pushed["tabWidth"] as? Int == 2) + } + + @Test("A settings category this build did not change is no edit when the record holds an option it cannot read") + func unreadOptionAloneIsNoEdit() throws { + let base = Self.record(try Self.newerDocument(.default)) + + let edit = SyncRecordMapper.settingsEdit( + category: Self.editor, + settingsData: try Self.encoded(.default), + in: Self.zoneID, + base: base + ) + + #expect(edit.changesContent == false) + } + + @Test("A push merged over another Mac's change keeps the option a newer build wrote") + func mergedPushKeepsAnOptionThisBuildCannotRead() throws { + let base = Self.record(try Self.newerDocument(.default)) + let server = try #require(base.copy() as? CKRecord) + server.fields(AppSettingsSyncField.self)[.settingsJson] = try Self.newerDocument(EditorSettings(wordWrap: true)) + + let edit = SyncRecordMapper.settingsEdit( + category: Self.editor, + settingsData: try Self.encoded(EditorSettings(tabWidth: 2)), + in: Self.zoneID, + base: base + ) + + let merged = try Self.document(of: try #require(edit.rebased(onto: server))) + #expect(merged["futureOption"] as? String == "kept") + #expect(merged["tabWidth"] as? Int == 2) + #expect(merged["wordWrap"] as? Bool == true) + } + + @Test("A push with no cached record that meets the server's copy keeps the option a newer build wrote there") + func uncachedPushKeepsTheServersUnreadOption() throws { + let server = Self.record(try Self.newerDocument(.default, futureOption: "on the server")) + + let edit = SyncRecordMapper.settingsEdit( + category: Self.editor, + settingsData: try Self.encoded(EditorSettings(tabWidth: 2)), + in: Self.zoneID, + base: nil + ) + + let rebased = try Self.document(of: try #require(edit.rebased(onto: server))) + #expect(rebased["futureOption"] as? String == "on the server") + #expect(rebased["tabWidth"] as? Int == 2) + } + + @Test("An option this build reads takes this Mac's value, not the record's") + func readableOptionFollowsThisMac() throws { + let base = Self.record(try Self.newerDocument(EditorSettings(keyBindings: .vim))) + + let edit = SyncRecordMapper.settingsEdit( + category: Self.editor, + settingsData: try Self.encoded(EditorSettings(keyBindings: .standard)), + in: Self.zoneID, + base: base + ) + + let pushed = try Self.document(of: edit.record) + #expect(pushed["keyBindings"] as? String == EditorKeyBindings.standard.rawValue) + #expect(pushed["vimModeEnabled"] as? Bool == false) + } + + @Test("A sync run sends this Mac's settings change with the option a newer build wrote") + func syncRunCarriesTheUnreadOption() async throws { + let environment = try SyncTestEnvironment(label: "sync-settings-unread-options") + let cached = Self.record(try Self.newerDocument(.default)) + environment.recordCache.store([cached]) + AppSettingsStorage(userDefaults: environment.defaults).saveEditor(EditorSettings(tabWidth: 2)) + environment.tracker.markDirty(.settings, ids: [Self.editor]) + let transport = ScriptedSyncTransport(zoneID: Self.zoneID) + + _ = await environment.makeCoordinator(transport: transport).runSyncCycle() + + let pushed = try #require(await transport.pushedRecords.last { $0.recordID == cached.recordID }) + let document = try Self.document(of: pushed) + #expect(document["futureOption"] as? String == "kept") + #expect(document["tabWidth"] as? Int == 2) + } +} diff --git a/apple/TableProTests/Core/Vim/VimEngineDotRepeatTests.swift b/apple/TableProTests/Core/Vim/VimEngineDotRepeatTests.swift new file mode 100644 index 0000000000..c64448eebf --- /dev/null +++ b/apple/TableProTests/Core/Vim/VimEngineDotRepeatTests.swift @@ -0,0 +1,132 @@ +// `.` repeats the last command that changed the text, with what was typed in Insert mode after it. + +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct VimEngineDotRepeatTests { + private let buffer: VimTextBufferMock + private let engine: VimEngine + + init() { + buffer = VimTextBufferMock(text: "") + engine = VimEngine(buffer: buffer) + buffer.editObserver = engine + } + + private func load(_ text: String, caret: Int = 0) { + buffer.text = text + buffer.setSelectedRange(NSRange(location: caret, length: 0)) + } + + // A key the engine leaves to the text view is applied as the editor does: Backspace deletes, anything else types. + private func keys(_ chars: String) { + for char in chars where !engine.process(char, shift: char.isUppercase) { + if char == "\u{7F}" { + guard caret > 0 else { continue } + buffer.replaceCharacters(in: NSRange(location: caret - 1, length: 1), with: "") + } else { + buffer.replaceCharacters(in: buffer.selectedRange(), with: String(char)) + } + } + } + + private var caret: Int { buffer.selectedRange().location } + + @Test("dd, then . on the next line deletes that line, after an x before it") + func dotRepeatsDeleteLineAfterX() { + load("one\ntwo\nthree\nfour\n") + keys("x") + keys("jdd") + #expect(buffer.text == "ne\nthree\nfour\n") + keys(".") + #expect(buffer.text == "ne\nfour\n") + } + + @Test("cw with typed text, then . changes the next word the same way") + func dotRepeatsChangeWordWithItsText() { + load("SELECT a, b FROM t", caret: 7) + keys("cwid\u{1B}") + #expect(buffer.text == "SELECT id, b FROM t") + #expect(engine.mode == .normal) + keys("w") + keys("w") + #expect(caret == 11) + keys(".") + #expect(buffer.text == "SELECT id, id FROM t") + #expect(engine.mode == .normal) + } + + @Test("J, then . joins the next line too") + func dotRepeatsJoin() { + load("a\nb\nc\n") + keys("J") + #expect(buffer.text == "a b\nc\n") + keys(".") + #expect(buffer.text == "a b c\n") + } + + @Test("~, then . toggles the next character") + func dotRepeatsToggleCase() { + load("abc") + keys("~") + keys(".") + #expect(buffer.text == "ABc") + } + + @Test("A with typed text, then . on the next line appends the same text") + func dotRepeatsAppend() { + load("SELECT 1\nSELECT 2\n") + keys("A;\u{1B}") + keys("j.") + #expect(buffer.text == "SELECT 1;\nSELECT 2;\n") + } + + @Test("Backspace past where the typing began deletes as much again on .") + func dotRepeatsBackspacePastTheInsertStart() { + load("abc\ndefgh") + keys("A\u{7F}\u{7F}X\u{1B}") + #expect(buffer.text == "aX\ndefgh") + keys("j.") + #expect(buffer.text == "aX\ndefX") + } + + @Test("Ctrl-U in Insert mode replays as the key, deleting to the start of the line it is on") + func dotRepeatsControlU() { + load("abc\ndefgh") + keys("A\u{15}X\u{1B}") + #expect(buffer.text == "X\ndefgh") + keys("j.") + #expect(buffer.text == "X\nX") + } + + @Test("Ctrl-W in Insert mode replays as the key, deleting the word before the caret") + func dotRepeatsControlW() { + load("SELECT abc\nSELECT defgh") + keys("A\u{17}x\u{1B}") + #expect(buffer.text == "SELECT x\nSELECT defgh") + keys("j.") + #expect(buffer.text == "SELECT x\nSELECT x") + } + + @Test("A yank between a change and . leaves the change to repeat") + func yankIsNotAChange() { + load("abcdef\nxyz\n") + keys("x") + keys("yy") + keys(".") + #expect(buffer.text == "cdef\nxyz\n") + } + + @Test("A count on . replaces the change's count, and the next . keeps it") + func countOnDotReplacesTheCount() { + load("abcdefghij") + keys("2x") + #expect(buffer.text == "cdefghij") + keys("3.") + #expect(buffer.text == "fghij") + keys(".") + #expect(buffer.text == "ij") + } +} diff --git a/apple/TableProTests/Core/Vim/VimTextBufferAdapterCommandEditTests.swift b/apple/TableProTests/Core/Vim/VimTextBufferAdapterCommandEditTests.swift new file mode 100644 index 0000000000..eb30702dc2 --- /dev/null +++ b/apple/TableProTests/Core/Vim/VimTextBufferAdapterCommandEditTests.swift @@ -0,0 +1,49 @@ +// The editor runs its typing filters on every edit it is not told is a command: an open bracket wraps a selection, +// deleting one takes its closer, a quote doubles. Vim's edits are commands, so they land exactly as the engine asks. + +import AppKit +@testable import TablePro +import TableProEditorKit +import TableProTextEngine +import Testing + +@MainActor +struct VimTextBufferAdapterCommandEditTests { + private func run(_ keys: String, on text: String, at offset: Int) -> String { + let controller = EditorControllerFixture.make(string: text) + let adapter = VimTextBufferAdapter(controller: controller) + let engine = VimEngine(buffer: adapter) + return withExtendedLifetime(controller) { + adapter.setSelectedRange(NSRange(location: offset, length: 0)) + for key in keys { + _ = engine.process(key, shift: key.isUppercase) + } + return controller.textView.string + } + } + + @Test("x on an open bracket deletes that bracket only") + func deleteOpenBracket() { + #expect(run("x", on: "SELECT COUNT() FROM t", at: 12) == "SELECT COUNT) FROM t") + } + + @Test("r( replaces the character with a bracket and wraps nothing") + func replaceWithBracket() { + #expect(run("r(", on: "a x b", at: 2) == "a ( b") + } + + @Test("~ on a quote leaves the quote as it is") + func toggleCaseOnQuote() { + #expect(run("~", on: "'abc'", at: 0) == "'abc'") + } + + @Test("R types over a character with a quote, and adds no closing quote") + func replaceModeQuote() { + #expect(run("R'\u{1B}", on: "WHERE n = x", at: 10) == "WHERE n = '") + } + + @Test("o opens an empty line and leaves the next line's indent alone") + func openLineBelow() { + #expect(run("o\u{1B}", on: " a\n b", at: 4) == " a\n\n b") + } +} diff --git a/apple/TableProTests/Models/MultiRowEditStateClearedFieldTests.swift b/apple/TableProTests/Models/MultiRowEditStateClearedFieldTests.swift index 05e863605b..0adc12dec0 100644 --- a/apple/TableProTests/Models/MultiRowEditStateClearedFieldTests.swift +++ b/apple/TableProTests/Models/MultiRowEditStateClearedFieldTests.swift @@ -11,7 +11,6 @@ import Testing @MainActor private final class StagedFieldRecorder { var values: [Int: PluginCellValue] = [:] - var detachedValues: [Int: PluginCellValue] = [:] } @MainActor @@ -19,7 +18,6 @@ struct MultiRowEditStateClearedFieldTests { private static let columns = ["id", "deleted_at", "name", "doc", "created_at"] private static let deletedAt = 1 private static let name = 2 - private static let doc = 3 private static let createdAt = 4 private func makeState(_ recorder: StagedFieldRecorder) -> MultiRowEditState { @@ -38,7 +36,6 @@ struct MultiRowEditStateClearedFieldTests { nonNullableColumns: ["created_at"] ) state.onFieldChanged = { index, value, _ in recorder.values[index] = value } - state.onDetachedFieldChanged = { index, value, _, _ in recorder.detachedValues[index] = value } return state } @@ -87,14 +84,4 @@ struct MultiRowEditStateClearedFieldTests { #expect(recorder.values[Self.createdAt] == .text("2023-12-01 09:00:00")) #expect(state.fields[Self.createdAt].hasEdit == false) } - - @Test("A detached window's cleared JSON goes to its rows as NULL") - func clearedDetachedJSONStagesNull() { - let recorder = StagedFieldRecorder() - let state = makeState(recorder) - - state.updateDetachedField(columnIndex: Self.doc, rowIDs: [.existing(7)], value: "") - - #expect(recorder.detachedValues[Self.doc] == .null) - } } diff --git a/apple/TableProTests/Models/MultiRowEditStateSetValueTests.swift b/apple/TableProTests/Models/MultiRowEditStateSetValueTests.swift index 0989b77300..a5bdbc02f1 100644 --- a/apple/TableProTests/Models/MultiRowEditStateSetValueTests.swift +++ b/apple/TableProTests/Models/MultiRowEditStateSetValueTests.swift @@ -204,22 +204,6 @@ struct MultiRowEditStateSetValueTests { #expect(literals == [.text("now()")]) } - @Test("A value window over rows that are no longer selected promotes typed text the same way") - func detachedTypedFunctionIsPromoted() { - let state = makeState() - var detached: [(value: PluginCellValue, rowIDs: [RowID], isExpression: Bool)] = [] - state.onDetachedFieldChanged = { _, value, rowIDs, isExpression in detached.append((value, rowIDs, isExpression)) } - - state.updateDetachedField(columnIndex: 1, rowIDs: [.existing(5)], value: "CURRENT_TIMESTAMP") - state.updateDetachedField(columnIndex: 2, rowIDs: [.existing(5)], value: "now()") - - #expect(detached.count == 2) - #expect(detached.first?.value == .text("CURRENT_TIMESTAMP")) - #expect(detached.first?.isExpression == true) - #expect(detached.last?.value == .text("now()")) - #expect(detached.last?.isExpression == false) - } - // The grid staged `now()`; the user types over it in the inspector, then types it back. @Test("Clearing a field back to the SQL its rows held sends it back as SQL, not as text") func revertKeepsTheExpression() { diff --git a/apple/TableProTests/Models/UI/MultiRowEditStateDetachedCommitTests.swift b/apple/TableProTests/Models/UI/MultiRowEditStateDetachedCommitTests.swift index c25b6739df..3c90890aaf 100644 --- a/apple/TableProTests/Models/UI/MultiRowEditStateDetachedCommitTests.swift +++ b/apple/TableProTests/Models/UI/MultiRowEditStateDetachedCommitTests.swift @@ -9,65 +9,140 @@ import Testing @testable import TablePro +// Stands in for the coordinator: one table per tab id, with the record each RowID holds as read. +@MainActor +private final class RecordingStager: InspectorDetachedStaging { + static let columns = ["id", "name"] + + var tabs: [UUID: [RowID: [PluginCellValue]]] = [:] + var staged: [(text: String, target: InspectorDetachedTarget)] = [] + + func holdInspectorRows(tabId: UUID, columnIndex: Int, rowIDs: [RowID]) -> InspectorDetachedTarget? { + guard let rows = tabs[tabId], Self.columns.indices.contains(columnIndex) else { return nil } + var rowsAsRead: [[PluginCellValue]] = [] + for rowID in rowIDs { + guard let row = rows[rowID] else { return nil } + rowsAsRead.append(row) + } + return InspectorDetachedTarget( + tabId: tabId, columnIndex: columnIndex, columnName: Self.columns[columnIndex], rowIDs: rowIDs, rowsAsRead: rowsAsRead + ) + } + + func stageDetachedInspectorEdit(_ text: String, to target: InspectorDetachedTarget) { + staged.append((text, target)) + } +} + @MainActor struct MultiRowEditStateDetachedCommitTests { - private func makeState(rowIDs: [RowID], values: [[String?]]) -> MultiRowEditState { - let state = MultiRowEditState() + private let tabA = UUID() + private let tabB = UUID() + + private func configure(_ state: MultiRowEditState, tab: UUID?, rowIDs: [RowID], values: [[String?]]) { state.configure( + tabId: tab, rowIDs: rowIDs, allRows: values, - columns: ["id", "name"], + columns: RecordingStager.columns, columnTypes: [.text(rawType: nil), .text(rawType: nil)] ) + } + + private func makeState(_ stager: RecordingStager) -> MultiRowEditState { + stager.tabs[tabA] = [ + .existing(1): [.text("2"), .text("Bob")], + .existing(2): [.text("3"), .text("Carol")], + ] + stager.tabs[tabB] = [.existing(1): [.text("9"), .text("Order")]] + let state = MultiRowEditState() + state.detachedStager = stager + configure(state, tab: tabA, rowIDs: [.existing(1)], values: [["2", "Bob"]]) return state } - @Test("a commit while the same rows are selected is an ordinary field edit") - func commitsThroughTheFieldWhileTheSelectionHolds() { - let state = makeState(rowIDs: [.existing(1)], values: [["2", "Bob"]]) + @Test("a commit while the window's tab and rows are shown is an ordinary field edit") + func commitsThroughTheFieldWhileTheSelectionHolds() throws { + let stager = RecordingStager() + let state = makeState(stager) var fieldEdits: [(Int, PluginCellValue)] = [] - var detached: [(Int, PluginCellValue, [RowID])] = [] state.onFieldChanged = { columnIndex, value, _ in fieldEdits.append((columnIndex, value)) } - state.onDetachedFieldChanged = { columnIndex, value, rowIDs, _ in detached.append((columnIndex, value, rowIDs)) } + let target = try #require(state.holdDetachedField(columnIndex: 1)) - state.updateDetachedField(columnIndex: 1, rowIDs: [.existing(1)], value: "Zed") + #expect(state.commitDetachedField("Zed", to: target)) #expect(fieldEdits.count == 1) - #expect(detached.isEmpty) + #expect(stager.staged.isEmpty) #expect(state.fields[1].pendingValue == "Zed") } - // The field's id is reissued on every selection change, so a lookup by id dropped the text silently. + // RowIDs are positions, so another tab's selection names the same row ids as the window's. + @Test("a commit after another tab took the inspector goes to the window's own tab, never the shown one") + func commitsToTheOpenedTabAfterATabSwitch() throws { + let stager = RecordingStager() + let state = makeState(stager) + let target = try #require(state.holdDetachedField(columnIndex: 1)) + state.onFieldChanged = { _, _, _ in Issue.record("the shown tab's field must not take the window's text") } + + configure(state, tab: tabB, rowIDs: [.existing(1)], values: [["9", "Order"]]) + #expect(state.commitDetachedField("Zed", to: target)) + + #expect(stager.staged.count == 1) + #expect(stager.staged.first?.target.tabId == tabA) + #expect(stager.staged.first?.target.rowIDs == [.existing(1)]) + #expect(stager.staged.first?.text == "Zed") + #expect(state.fields[1].pendingValue == nil) + } + @Test("a commit after the selection moved writes the rows the window was opened for") - func commitsToTheOpenedRowsAfterTheSelectionMoved() { - let state = makeState(rowIDs: [.existing(1)], values: [["2", "Bob"]]) - var detached: [(Int, PluginCellValue, [RowID])] = [] + func commitsToTheOpenedRowsAfterTheSelectionMoved() throws { + let stager = RecordingStager() + let state = makeState(stager) + let target = try #require(state.holdDetachedField(columnIndex: 1)) state.onFieldChanged = { _, _, _ in Issue.record("the field path must not take a moved selection") } - state.onDetachedFieldChanged = { columnIndex, value, rowIDs, _ in detached.append((columnIndex, value, rowIDs)) } - state.configure( - rowIDs: [.existing(2)], - allRows: [["3", "Carol"]], - columns: ["id", "name"], - columnTypes: [.text(rawType: nil), .text(rawType: nil)] - ) - state.updateDetachedField(columnIndex: 1, rowIDs: [.existing(1)], value: "Zed") + configure(state, tab: tabA, rowIDs: [.existing(2)], values: [["3", "Carol"]]) + #expect(state.commitDetachedField("Zed", to: target)) - #expect(detached.count == 1) - #expect(detached.first?.2 == [.existing(1)]) - #expect(detached.first?.1 == .text("Zed")) + #expect(stager.staged.map { $0.target.rowIDs } == [[.existing(1)]]) #expect(state.fields[1].pendingValue == nil) } - @Test("a commit naming no rows does nothing") - func commitWithoutRowsDoesNothing() { - let state = makeState(rowIDs: [.existing(1)], values: [["2", "Bob"]]) - var detached = 0 - state.onDetachedFieldChanged = { _, _, _, _ in detached += 1 } + @Test("a commit is refused once another record sits at the window's row id") + func refusesAReplacedRecord() throws { + let stager = RecordingStager() + let state = makeState(stager) + let target = try #require(state.holdDetachedField(columnIndex: 1)) + state.onFieldChanged = { _, _, _ in Issue.record("a replaced record must take no edit") } - state.updateDetachedField(columnIndex: 1, rowIDs: [], value: "Zed") + stager.tabs[tabA]?[.existing(1)] = [.text("7"), .text("Dave")] - #expect(detached == 0) - #expect(state.fields[1].pendingValue == nil) + #expect(!state.commitDetachedField("Zed", to: target)) + #expect(stager.staged.isEmpty) + } + + @Test("a commit is refused once the window's tab is gone") + func refusesAClosedTab() throws { + let stager = RecordingStager() + let state = makeState(stager) + let target = try #require(state.holdDetachedField(columnIndex: 1)) + configure(state, tab: tabB, rowIDs: [.existing(1)], values: [["9", "Order"]]) + + stager.tabs[tabA] = nil + + #expect(!state.commitDetachedField("Zed", to: target)) + #expect(stager.staged.isEmpty) + } + + @Test("no window takes edits without a tab or rows to hold") + func noHoldWithoutATabOrRows() { + let stager = RecordingStager() + let state = makeState(stager) + + configure(state, tab: nil, rowIDs: [.existing(1)], values: [["2", "Bob"]]) + #expect(state.holdDetachedField(columnIndex: 1) == nil) + + configure(state, tab: tabA, rowIDs: [], values: []) + #expect(state.holdDetachedField(columnIndex: 1) == nil) } } diff --git a/apple/TableProTests/ViewModels/AIChatTranscriptTrimTests.swift b/apple/TableProTests/ViewModels/AIChatTranscriptTrimTests.swift new file mode 100644 index 0000000000..e05a2e7b1c --- /dev/null +++ b/apple/TableProTests/ViewModels/AIChatTranscriptTrimTests.swift @@ -0,0 +1,110 @@ +// +// AIChatTranscriptTrimTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProMCP +import Testing + +@MainActor +struct AIChatTranscriptTrimTests { + private func call(_ id: String) -> ChatContentBlockWire { + .toolUse(ToolUseBlock(id: id, name: "describe_table", input: .object([:]))) + } + + private func result(_ id: String) -> ChatContentBlockWire { + .toolResult(ToolResultBlock(toolUseId: id, content: "ok")) + } + + private func calls(in turn: ChatTurnWire) -> Set { + Set(turn.blocks.compactMap { block -> String? in + guard case .toolUse(let use) = block.kind else { return nil } + return use.id + }) + } + + private func results(in turn: ChatTurnWire) -> [String] { + turn.blocks.compactMap { block -> String? in + guard case .toolResult(let result) = block.kind else { return nil } + return result.toolUseId + } + } + + // Every result answers a call in the turn right before it, which is what providers accept. + private func everyResultHasItsCall(_ turns: [ChatTurnWire]) -> Bool { + turns.indices.allSatisfy { index in + let answered = results(in: turns[index]) + guard !answered.isEmpty else { return true } + guard index > 0, turns[index - 1].role == .assistant else { return false } + return Set(answered).isSubset(of: calls(in: turns[index - 1])) + } + } + + // Exchanges of a question, a tool round and an answer, then the question being sent: 201 turns. + private func toolTranscript() -> [ChatTurnWire] { + var turns: [ChatTurnWire] = [] + for exchange in 0..<50 { + turns.append(ChatTurnWire(role: .user, blocks: [.text("question \(exchange)")])) + turns.append(ChatTurnWire(role: .assistant, blocks: [call("call_\(exchange)")])) + turns.append(ChatTurnWire(role: .user, blocks: [result("call_\(exchange)")])) + turns.append(ChatTurnWire(role: .assistant, blocks: [.text("answer \(exchange)")])) + } + turns.append(ChatTurnWire(role: .user, blocks: [.text("and now?")])) + return turns + } + + @Test("A trimmed tool transcript starts at a question, never at a result whose call was cut") + func trimStartsAtARound() { + let viewModel = AIChatViewModel() + viewModel.messages = toolTranscript().map { ChatTurn(wire: $0) } + + viewModel.trimMessagesIfNeeded() + + let wire = viewModel.messages.map { $0.wireSnapshot } + let opening = wire.first?.blocks.first.flatMap { block -> String? in + guard case .text(let text) = block.kind else { return nil } + return text + } + #expect(wire.count <= AIChatViewModel.maxMessageCount) + #expect(wire.first?.role == .user) + #expect(opening == "question 1") + #expect(everyResultHasItsCall(wire)) + #expect(ChatToolCallRepair.answeringEveryToolCall(wire) == wire) + } + + @Test("A transcript cut short on disk drops a leading result whose call is gone and keeps its text") + func repairDropsALeadingOrphan() { + let turns = [ + ChatTurnWire(role: .user, blocks: [result("call_gone"), .text("also, count rows")]), + ChatTurnWire(role: .assistant, blocks: [.text("12")]), + ChatTurnWire(role: .user, blocks: [.text("thanks")]) + ] + + let repaired = ChatToolCallRepair.answeringEveryToolCall(turns) + + #expect(repaired.count == 3) + #expect(results(in: repaired[0]).isEmpty) + #expect(repaired[0].blocks.count == 1) + #expect(everyResultHasItsCall(repaired)) + } + + @Test("A turn that held only orphan results is dropped, and a result for another round's call goes") + func repairDropsOrphanTurnsAndStrayResults() { + let turns = [ + ChatTurnWire(role: .user, blocks: [result("call_gone")]), + ChatTurnWire(role: .assistant, blocks: [.text("done")]), + ChatTurnWire(role: .user, blocks: [.text("count users")]), + ChatTurnWire(role: .assistant, blocks: [call("a")]), + ChatTurnWire(role: .user, blocks: [result("a"), result("call_gone")]) + ] + + let repaired = ChatToolCallRepair.answeringEveryToolCall(turns) + + #expect(repaired.count == 4) + #expect(repaired.first?.role == .assistant) + #expect(results(in: repaired[3]) == ["a"]) + #expect(everyResultHasItsCall(repaired)) + } +} diff --git a/apple/TableProTests/ViewModels/ERDiagramSchemaBindingTests.swift b/apple/TableProTests/ViewModels/ERDiagramSchemaBindingTests.swift new file mode 100644 index 0000000000..eaa181a26e --- /dev/null +++ b/apple/TableProTests/ViewModels/ERDiagramSchemaBindingTests.swift @@ -0,0 +1,62 @@ +// A diagram's key writes a schema named `default` and no schema alike, so a Trino `hive.default` +// diagram was unbound and followed the sidebar's browse schema on refresh and on Save. + +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct ERDiagramSchemaBindingTests { + private func connectBrowsing(schema: String) -> DatabaseConnection { + let connection = TestFixtures.makeConnection(database: "hive", type: .duckdb) + let driver = ERDiagramCatalogDriver( + connection: connection, + columns: [CatalogName("events"): [TestFixtures.makeColumnInfo(name: "id", isPrimaryKey: true)]], + holds: [], + failingReads: 0 + ) + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connected + session.browseDatabase = connection.database + session.browseSchema = schema + DatabaseManager.shared.injectSession(session, for: connection.id) + return connection + } + + @Test("A diagram tab opened on the schema named default stays on it while the sidebar browses another") + func recordedDefaultSchemaBindsTheDiagram() throws { + let connection = connectBrowsing(schema: "staging") + defer { DatabaseManager.shared.removeSession(for: connection.id) } + let tabManager = QueryTabManager() + tabManager.addERDiagramTab( + schemaKey: ERDiagramViewModel.schemaKey(databaseName: "hive", schema: "default"), + databaseName: "hive", + schemaName: "default" + ) + let tab = try #require(tabManager.selectedTab) + + let viewModel = ERDiagramViewModel(tab: tab, connection: connection) + + #expect(viewModel.schemaName == "default") + #expect(viewModel.scope?.schema == "default") + } + + @Test("Refresh and staged edits keep the schema the diagram loaded after the sidebar moves") + func loadFixesTheScope() async throws { + let connection = connectBrowsing(schema: "default") + defer { DatabaseManager.shared.removeSession(for: connection.id) } + let viewModel = ERDiagramViewModel( + connectionId: connection.id, + databaseName: "hive", + schemaKey: "hive.default", + connection: connection + ) + await viewModel.loadDiagram() + try #require(viewModel.loadState == .loaded) + + DatabaseManager.shared.updateSession(connection.id) { $0.browseSchema = "staging" } + + #expect(viewModel.scope?.schema == "default") + #expect(viewModel.edits?.schemaName == "default") + } +} diff --git a/apple/TableProTests/ViewModels/ERDiagramSchemaKeyTests.swift b/apple/TableProTests/ViewModels/ERDiagramSchemaKeyTests.swift index 26d78a1481..ee629417de 100644 --- a/apple/TableProTests/ViewModels/ERDiagramSchemaKeyTests.swift +++ b/apple/TableProTests/ViewModels/ERDiagramSchemaKeyTests.swift @@ -64,13 +64,6 @@ struct ERDiagramSchemaKeyTests { #expect(ERDiagramViewModel.schemaKey(databaseName: "app", schema: nil) == "app.default") } - @Test("A key keeps a schema only when a database is named and the schema is not the marker") - func keyPreservesSchema() { - #expect(ERDiagramViewModel.schemaKeyPreserves("sales", databaseName: "app")) - #expect(!ERDiagramViewModel.schemaKeyPreserves("sales", databaseName: "")) - #expect(!ERDiagramViewModel.schemaKeyPreserves("default", databaseName: "app")) - } - @Test("The view model binds to the schema its key names") func viewModelBindsSchema() { let viewModel = ERDiagramViewModel( diff --git a/apple/TableProTests/Views/DataGrid/DataGridHiddenColumnMoveTests.swift b/apple/TableProTests/Views/DataGrid/DataGridHiddenColumnMoveTests.swift new file mode 100644 index 0000000000..ccad8f1e0a --- /dev/null +++ b/apple/TableProTests/Views/DataGrid/DataGridHiddenColumnMoveTests.swift @@ -0,0 +1,66 @@ +// +// DataGridHiddenColumnMoveTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +// A header drag reports the shown columns only; a query tab's store reads back an order only when it names them all. +@MainActor +struct DataGridHiddenColumnMoveTests { + private let fixture = CoordinatorFixture() + + private func queryTabModel() -> (tabId: UUID, model: DataGridModel) { + let columns = ["id", "name", "email", "created_at"] + let tab = fixture.addTab( + QueryTab(title: "Query 1", query: "SELECT id, name, email, created_at FROM users", tabType: .query), + rows: TableRows.from( + queryRows: [columns.map { PluginCellValue.text("\($0) value") }], + columns: columns, + columnTypes: Array(repeating: .text(rawType: "TEXT"), count: columns.count) + ) + ) + return (tab.id, fixture.coordinator.gridModel(forTab: tab.id)) + } + + @Test("A column moved past a hidden one keeps its place through the next resize") + func movedColumnSurvivesAResize() { + let (tabId, model) = queryTabModel() + defer { fixture.coordinator.releaseGridModel(forTab: tabId, persistingLayout: false) } + fixture.coordinator.hideColumn("email") + #expect(model.columns.orderedNames == ["id", "name", "created_at"]) + + model.columnGeometryDidChange(widths: [:], order: ["id", "created_at", "name"]) + model.columnGeometryDidChange(widths: ["name": 200], order: nil) + + #expect(model.columns.orderedNames == ["id", "created_at", "name"]) + #expect(model.store.columnLayout.columnOrder == ["id", "created_at", "email", "name"]) + } + + @Test("A column moved past a hidden one keeps its place through a re-run of the same columns") + func movedColumnSurvivesARerun() { + let (tabId, model) = queryTabModel() + defer { fixture.coordinator.releaseGridModel(forTab: tabId, persistingLayout: false) } + fixture.coordinator.hideColumn("email") + + model.columnGeometryDidChange(widths: [:], order: ["id", "created_at", "name"]) + model.reloadRows() + + #expect(model.columns.orderedNames == ["id", "created_at", "name"]) + } + + @Test("A hidden column shown again comes back in the slot it held") + func shownColumnReturnsToItsSlot() { + let (tabId, model) = queryTabModel() + defer { fixture.coordinator.releaseGridModel(forTab: tabId, persistingLayout: false) } + fixture.coordinator.hideColumn("email") + model.columnGeometryDidChange(widths: [:], order: ["id", "created_at", "name"]) + + fixture.coordinator.showAllColumns() + + #expect(model.columns.orderedNames == ["id", "created_at", "email", "name"]) + } +} diff --git a/apple/TableProTests/Views/Editor/QueryParameterPanelClearAllTests.swift b/apple/TableProTests/Views/Editor/QueryParameterPanelClearAllTests.swift new file mode 100644 index 0000000000..687c911d14 --- /dev/null +++ b/apple/TableProTests/Views/Editor/QueryParameterPanelClearAllTests.swift @@ -0,0 +1,37 @@ +// The panel's binding reads the tab as it was when the view rendered, as the query tab's does, so every write starts +// from those values. + +import SwiftUI +@testable import TablePro +import Testing + +@MainActor +struct QueryParameterPanelClearAllTests { + private final class Tab { + var parameters: [QueryParameter] + + init(_ parameters: [QueryParameter]) { + self.parameters = parameters + } + } + + @Test("Clear All clears every parameter, not only the last one") + func clearAllClearsEveryValue() { + let tab = Tab([ + QueryParameter(name: "id", value: "42"), + QueryParameter(name: "name", value: "bob"), + QueryParameter(name: "limit", value: "10", type: .integer), + ]) + let rendered = tab.parameters + let panel = QueryParameterPanelView( + parameters: Binding(get: { rendered }, set: { tab.parameters = $0 }), + onDismiss: {} + ) + + panel.clearAllValues() + + #expect(tab.parameters.map { $0.value } == ["", "", ""]) + #expect(tab.parameters.map { $0.name } == ["id", "name", "limit"]) + #expect(tab.parameters.map { $0.type } == [.string, .string, .integer]) + } +} diff --git a/apple/TableProTests/Views/Editor/SQLEditorTabSelectionTests.swift b/apple/TableProTests/Views/Editor/SQLEditorTabSelectionTests.swift new file mode 100644 index 0000000000..ea7d1efe5c --- /dev/null +++ b/apple/TableProTests/Views/Editor/SQLEditorTabSelectionTests.swift @@ -0,0 +1,110 @@ +// One SQL editor serves every query tab of a window, and a new tab's text kept the outgoing tab's caret, clamped. + +import AppKit +import SwiftUI +@testable import TablePro +import TableProEditorKit +import TableProTextEngine +import Testing + +@MainActor +struct SQLEditorTabSelectionTests { + private final class Tabs { + var texts: [UUID: String] = [:] + + func binding(_ id: UUID) -> Binding { + Binding(get: { self.texts[id] ?? "" }, set: { self.texts[id] = $0 }) + } + } + + private let tabs = Tabs() + private let histories = EditorUndoHistories() + private let first = UUID() + private let second = UUID() + + init() { + tabs.texts[first] = String(repeating: "SELECT id FROM users;\n", count: 100) + tabs.texts[second] = "SELECT 2;\nSELECT 3;" + } + + private func input(_ tab: UUID, restoredCursorRange: NSRange? = nil) -> SQLEditorInput { + SQLEditorInput( + text: tabs.binding(tab), + cursorPositions: .constant([]), + databaseType: .sqlite, + tabID: tab, + undoHistories: histories, + restoredCursorRange: restoredCursorRange + ) + } + + private func makeEditor() -> SQLEditorController { + let editor = SQLEditorController(input: input(first)) + let view = editor.textViewController.view + view.frame = NSRect(x: 0, y: 0, width: 800, height: 300) + view.layoutSubtreeIfNeeded() + return editor + } + + private func selection(_ editor: SQLEditorController) -> [NSRange] { + editor.textViewController.textView.selectionManager.textSelections.map { $0.range } + } + + private func select(_ range: NSRange, in editor: SQLEditorController) { + editor.textViewController.setCursorPositions([CursorPosition(range: range)]) + } + + @Test("A tab shown for the first time starts at the top, not at the last tab's caret") + func newTabStartsAtTheTop() { + let editor = makeEditor() + defer { editor.teardown() } + select(NSRange(location: 900, length: 0), in: editor) + + editor.apply(input(second)) + + #expect(editor.textViewController.textView.string == tabs.texts[second]) + #expect(selection(editor) == [NSRange(location: 0, length: 0)]) + } + + @Test("Each tab gets its own selection back when it is shown again") + func eachTabKeepsItsSelection() { + let editor = makeEditor() + defer { editor.teardown() } + select(NSRange(location: 900, length: 6), in: editor) + + editor.apply(input(second)) + select(NSRange(location: 3, length: 0), in: editor) + editor.apply(input(first)) + #expect(selection(editor) == [NSRange(location: 900, length: 6)]) + + editor.apply(input(second)) + #expect(selection(editor) == [NSRange(location: 3, length: 0)]) + } + + @Test("A tab's saved caret from the last session applies when the tab is first shown") + func savedCaretAppliesOnFirstShow() { + let editor = makeEditor() + defer { editor.teardown() } + select(NSRange(location: 900, length: 0), in: editor) + + editor.apply(input(second, restoredCursorRange: NSRange(location: 10, length: 6))) + + #expect(selection(editor) == [NSRange(location: 10, length: 6)]) + } + + @Test("Each tab gets its own scroll position back") + func eachTabKeepsItsScroll() { + let editor = makeEditor() + defer { editor.teardown() } + let controller = editor.textViewController + controller.scrollPosition = CGPoint(x: 0, y: 600) + let scrolled = controller.scrollPosition + #expect(scrolled.y > 0) + + editor.apply(input(second)) + #expect(controller.scrollPosition.y < 1) + + editor.apply(input(first)) + #expect(controller.scrollPosition.y == scrolled.y) + } +} diff --git a/apple/TableProTests/Views/Main/InPlaceNavigationKeepsWorkTests.swift b/apple/TableProTests/Views/Main/InPlaceNavigationKeepsWorkTests.swift new file mode 100644 index 0000000000..c207787c76 --- /dev/null +++ b/apple/TableProTests/Views/Main/InPlaceNavigationKeepsWorkTests.swift @@ -0,0 +1,84 @@ +// Redis lists its databases as db0...dbN and a click retargets the selected tab in place. That +// retarget used to take over a tab holding typed commands or staged edits, with no prompt and no undo. + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +@MainActor +struct InPlaceNavigationKeepsWorkTests { + private func makeRedisCoordinator() -> MainContentCoordinator { + MainContentCoordinator( + connection: TestFixtures.makeConnection(database: "0", type: .redis), + tabManager: QueryTabManager(), + toolbarState: ConnectionToolbarState() + ) + } + + @Test("A database click opens its own tab instead of replacing typed, unrun commands") + func keepsTypedCommands() throws { + let coordinator = makeRedisCoordinator() + defer { coordinator.teardown() } + let tabManager = coordinator.tabManager + tabManager.addTab(initialQuery: "GET session:42") + let queryTab = try #require(tabManager.selectedTabId) + + coordinator.openTableTab("db3") + + #expect(tabManager.tabs.count == 2) + let kept = try #require(tabManager.tabs.first { $0.id == queryTab }) + #expect(kept.tabType == .query) + #expect(kept.content.query == "GET session:42") + #expect(tabManager.selectedTab?.tableContext.tableName == "db3") + } + + @Test("A database click keeps a database tab that holds staged edits") + func keepsStagedEdits() throws { + let coordinator = makeRedisCoordinator() + defer { coordinator.teardown() } + let tabManager = coordinator.tabManager + coordinator.openTableTab("db0") + let edited = try #require(tabManager.selectedTabId) + coordinator.changeManager(forTab: edited).recordRowDeletion(rowID: .existing(0), originalRow: ["1"]) + + coordinator.openTableTab("db3") + + #expect(tabManager.tabs.count == 2) + #expect(tabManager.tabs.first { $0.id == edited }?.tableContext.tableName == "db0") + #expect(coordinator.hasStagedRowEdits(inTab: edited)) + #expect(tabManager.selectedTab?.tableContext.tableName == "db3") + } + + @Test("A database click keeps a database tab the user sorted") + func keepsASortedTab() throws { + let coordinator = makeRedisCoordinator() + defer { coordinator.teardown() } + let tabManager = coordinator.tabManager + coordinator.openTableTab("db0") + let sorted = try #require(tabManager.selectedTabId) + tabManager.mutate(tabId: sorted) { tab in + tab.sortState = SortState(columns: [SortColumn(columnIndex: 0, direction: .ascending)], source: .user) + } + + coordinator.openTableTab("db3") + + #expect(tabManager.tabs.count == 2) + #expect(tabManager.tabs.first { $0.id == sorted }?.tableContext.tableName == "db0") + #expect(tabManager.selectedTab?.tableContext.tableName == "db3") + } + + @Test("A database click still retargets a database tab that holds nothing") + func retargetsAnUntouchedDatabaseTab() throws { + let coordinator = makeRedisCoordinator() + defer { coordinator.teardown() } + let tabManager = coordinator.tabManager + coordinator.openTableTab("db0") + let browsing = try #require(tabManager.selectedTabId) + + coordinator.openTableTab("db3") + + #expect(tabManager.tabs.map { $0.id } == [browsing]) + #expect(tabManager.selectedTab?.tableContext.tableName == "db3") + } +} diff --git a/apple/TableProTests/Views/Main/QueryParameterBindingTests.swift b/apple/TableProTests/Views/Main/QueryParameterBindingTests.swift new file mode 100644 index 0000000000..bcde69367f --- /dev/null +++ b/apple/TableProTests/Views/Main/QueryParameterBindingTests.swift @@ -0,0 +1,31 @@ +// The parameter panel's binding read the tab copy taken when the editor was drawn, so a second +// write before the next render started from the first array and undid the first write. + +import Foundation +import SwiftUI +@testable import TablePro +import Testing + +@MainActor +struct QueryParameterBindingTests { + @Test("Two parameter writes before a render both land") + func secondWriteBuildsOnTheFirst() throws { + let tabManager = QueryTabManager() + tabManager.addTab(initialQuery: "SELECT * FROM users WHERE id = :id AND name = :name") + let tabId = try #require(tabManager.selectedTabId) + tabManager.mutate(tabId: tabId) { tab in + tab.content.queryParameters = [ + QueryParameter(name: "id", value: "42"), + QueryParameter(name: "name", value: "bob") + ] + } + let drawn = try #require(tabManager.selectedTab) + let parameters = MainEditorContentView.parameterBinding(for: drawn, in: tabManager) + + parameters.wrappedValue[0].value = "" + parameters.wrappedValue[1].value = "" + + let values = tabManager.tabs.first { $0.id == tabId }?.content.queryParameters.map { $0.value } + #expect(values == ["", ""]) + } +} diff --git a/apple/TableProTests/Views/Main/SaveFileBesideResultEditsTests.swift b/apple/TableProTests/Views/Main/SaveFileBesideResultEditsTests.swift new file mode 100644 index 0000000000..687c9d9d09 --- /dev/null +++ b/apple/TableProTests/Views/Main/SaveFileBesideResultEditsTests.swift @@ -0,0 +1,204 @@ +// A query tab opened from a .sql file can hold result edits too. Save and Save on close wrote the edits +// and reported success, and the file on disk kept its old text. + +import AppKit +import Foundation +import SwiftUI +@testable import TablePro +import TableProPluginKit +import TableProTestSupport +import TableProUtilities +import Testing + +private final class FileTabRowWriter: PluginDriverStub, @unchecked Sendable { + private let lock = NSLock() + private var received: [String] = [] + private var database: String? + + var queries: [String] { lock.withLock { received } } + var supportsSchemas: Bool { false } + var supportsTransactions: Bool { false } + var currentSchema: String? { nil } + var currentDatabase: String? { lock.withLock { database } } + var serverVersion: String? { nil } + + func ping() async throws {} + func switchDatabase(to database: String) async throws { + lock.withLock { self.database = database } + } + func execute(query: String) async throws -> PluginQueryResult { + lock.withLock { received.append(query) } + return PluginQueryResult(columns: [], columnTypeNames: [], rows: [], rowsAffected: 1, executionTime: 0) + } +} + +@MainActor +struct SaveFileBesideResultEditsTests { + @MainActor + private struct Harness { + let fixture: CoordinatorFixture + let actions: MainContentCommandActions + let writer: FileTabRowWriter + let window: NSWindow + let folder: URL + let fileURL: URL + let tabId: UUID + + var tab: QueryTab? { fixture.tabManager.tabs.first { $0.id == tabId } } + + func tearDown() { + window.orderOut(nil) + DatabaseManager.shared.removeSession(for: fixture.connection.id) + try? FileManager.default.removeItem(at: folder) + } + } + + // report.sql open in a query tab, its text edited, and a cell of its result edited. + private func makeHarness() throws -> Harness { + let connection = TestFixtures.makeConnection() + let writer = FileTabRowWriter() + var session = ConnectionSession( + connection: connection, + driver: PluginDriverAdapter(connection: connection, pluginDriver: writer) + ) + session.status = .connected + session.browseDatabase = connection.database + DatabaseManager.shared.injectSession(session, for: connection.id) + + let fixture = CoordinatorFixture(connection: connection) + fixture.coordinator.executionGate = AlwaysAllowGate() + // A failed save reports in a sheet on this window rather than in a modal alert nothing answers. + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 400, height: 300), + styleMask: [.titled], + backing: .buffered, + defer: true + ) + window.isReleasedWhenClosed = false + fixture.coordinator.contentWindow = window + + var selectedTables: Set = [] + var pendingTruncates: Set = [] + var pendingDeletes: Set = [] + var tableOperationOptions: [DatabaseTreeTableRef: TableOperationOptions] = [:] + let actions = MainContentCommandActions( + coordinator: fixture.coordinator, + connection: connection, + selectedTables: Binding(get: { selectedTables }, set: { selectedTables = $0 }), + pendingTruncates: Binding(get: { pendingTruncates }, set: { pendingTruncates = $0 }), + pendingDeletes: Binding(get: { pendingDeletes }, set: { pendingDeletes = $0 }), + tableOperationOptions: Binding( + get: { tableOperationOptions }, + set: { tableOperationOptions = $0 } + ), + trailingPaneState: TrailingPaneState() + ) + actions.window = window + actions.chooseSaveURL = { _ in + Issue.record("Save As was not expected") + return nil + } + + let folder = FileManager.default.temporaryDirectory + .appendingPathComponent("save-on-close-file-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let fileURL = folder.appendingPathComponent("report.sql") + try Data("SELECT * FROM users".utf8).write(to: fileURL) + let loaded = try #require(FileTextLoader.load(fileURL)) + fixture.tabManager.addTab(initialQuery: loaded.content, sourceFileURL: fileURL, sourceFileStamp: loaded.stamp) + let tabId = try #require(fixture.tabManager.selectedTabId) + fixture.tabManager.mutate(tabId: tabId) { tab in + tab.content.query = "SELECT * FROM users WHERE id = 1" + tab.tableContext.tableName = "users" + tab.execution.lastExecutedAt = Date() + } + fixture.coordinator.setActiveTableRows( + TableRows.from( + queryRows: [[.text("1"), .text("a")]], + columns: ["id", "name"], + columnTypes: [.text(rawType: nil), .text(rawType: nil)], + hasAuthoritativeSchema: true + ), + for: tabId + ) + fixture.changeManager.configureForTable( + tableName: "users", + columns: ["id", "name"], + primaryKeyColumns: ["id"], + databaseType: .mysql, + generatedColumns: [] + ) + fixture.changeManager.recordCellChange( + rowID: .existing(0), columnIndex: 1, columnName: "name", + oldValue: "a", newValue: "z", originalRow: ["1", "a"] + ) + return Harness( + fixture: fixture, + actions: actions, + writer: writer, + window: window, + folder: folder, + fileURL: fileURL, + tabId: tabId + ) + } + + @Test("One Save writes the result edits and the tab's .sql file") + func saveWritesTheResultEditsAndTheFile() async throws { + let harness = try makeHarness() + defer { harness.tearDown() } + + harness.actions.saveChanges() + + try await waitUntil(timeout: .seconds(5)) { harness.tab?.content.isFileDirty == false } + #expect(harness.writer.queries.contains { $0.hasPrefix("UPDATE") }) + #expect(!harness.fixture.coordinator.hasStagedRowEdits(inTab: harness.tabId)) + #expect(try String(contentsOf: harness.fileURL, encoding: .utf8) == "SELECT * FROM users WHERE id = 1") + } + + @Test("Save on close writes the tab's .sql file beside its result edits") + func saveOnCloseWritesTheFileToo() async throws { + let harness = try makeHarness() + defer { harness.tearDown() } + + let mayClose = await harness.actions.saveSelectedTabWork() + + #expect(mayClose) + #expect(harness.writer.queries.contains { $0.hasPrefix("UPDATE") }) + #expect(try String(contentsOf: harness.fileURL, encoding: .utf8) == "SELECT * FROM users WHERE id = 1") + #expect(harness.tab?.content.isFileDirty == false) + } + + @Test("Closing the connection writes the on-screen tab's .sql file beside its result edits") + func connectionCloseWritesTheFileToo() async throws { + let harness = try makeHarness() + defer { harness.tearDown() } + + let mayClose = await harness.actions.saveEveryTabsWork() + + #expect(mayClose) + #expect(harness.writer.queries.contains { $0.hasPrefix("UPDATE") }) + #expect(try String(contentsOf: harness.fileURL, encoding: .utf8) == "SELECT * FROM users WHERE id = 1") + } + + @Test("Save on close keeps the tab open when its file changed on disk, after the result edits saved") + func fileConflictKeepsTheTabAfterTheResultEditsSave() async throws { + let harness = try makeHarness() + defer { harness.tearDown() } + let handle = try FileHandle(forWritingTo: harness.fileURL) + try handle.truncate(atOffset: 0) + try handle.write(contentsOf: Data("SELECT 0".utf8)) + try handle.close() + try FileManager.default.setAttributes( + [.modificationDate: Date(timeIntervalSinceNow: -3_600)], + ofItemAtPath: harness.fileURL.path + ) + + let mayClose = await harness.actions.saveSelectedTabWork() + + #expect(!mayClose) + #expect(harness.writer.queries.contains { $0.hasPrefix("UPDATE") }) + #expect(harness.fixture.coordinator.fileConflictRequest?.tabId == harness.tabId) + #expect(try String(contentsOf: harness.fileURL, encoding: .utf8) == "SELECT 0") + } +} diff --git a/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift b/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift index ba18f3a01e..c3b25e5b51 100644 --- a/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift +++ b/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift @@ -155,8 +155,9 @@ struct FavoritesMenuSpecTests { #expect(issued.contains(.removeTableFavorite(row.entry))) } - @Test("A diagram the tab could not tell apart from the browsed schema's is not offered") - func unrepresentableDiagramIsNotOffered() { + // The diagram tab records the schema it was opened on, so neither case loses it to the browsed one. + @Test("A table in a schema named default, or with no active database, still offers its own diagram") + func diagramIsOfferedWhateverTheSchemaIsCalled() { let noDatabase = commands(FavoritesMenuSpec.sections(for: context( clicked: .table(table(schema: "sales", otherSchema: "sales")), activeDatabase: nil @@ -169,8 +170,8 @@ struct FavoritesMenuSpecTests { activeDatabase: nil ))) - #expect(!noDatabase.contains { if case .showERDiagram = $0 { true } else { false } }) - #expect(!markerSchema.contains { if case .showERDiagram = $0 { true } else { false } }) + #expect(noDatabase.contains(.showERDiagram(schema: "sales"))) + #expect(markerSchema.contains(.showERDiagram(schema: "default"))) #expect(browsedSchema.contains(.showERDiagram(schema: nil))) } diff --git a/apple/TableProTests/Views/Structure/StructureSectionColumnVisibilityTests.swift b/apple/TableProTests/Views/Structure/StructureSectionColumnVisibilityTests.swift new file mode 100644 index 0000000000..33098a5f3e --- /dev/null +++ b/apple/TableProTests/Views/Structure/StructureSectionColumnVisibilityTests.swift @@ -0,0 +1,87 @@ +// +// StructureSectionColumnVisibilityTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +// Hide Column and Show All Columns reach a section through `model.actions`, as the header menu sends them. +@MainActor +struct StructureSectionColumnVisibilityTests { + private let suite: EphemeralDefaults + + init() throws { + suite = try EphemeralDefaults() + } + + private func makeEditor() -> StructureDefinitionEditor { + let manager = StructureChangeManager() + manager.loadSchema( + tableName: "orders", + columns: [ + ColumnInfo(name: "id", dataType: "INT", isNullable: false, isPrimaryKey: true), + ColumnInfo(name: "total", dataType: "DECIMAL(10,2)", isNullable: true, isPrimaryKey: false), + ], + indexes: [IndexInfo(name: "ix_total", columns: ["total"], isUnique: false, isPrimary: false, type: "BTREE")], + foreignKeys: [], + primaryKey: ["id"] + ) + let editor = StructureDefinitionEditor( + manager: manager, + context: .existingTable( + connection: TestFixtures.makeConnection(database: "shop", type: .mysql), + databaseName: "shop", + schemaName: nil, + tableName: "orders", + objectKind: .table, + isSessionBound: false + ), + defaults: suite.defaults + ) + editor.refresh() + return editor + } + + @Test("Show All Columns brings back the fields the Columns section starts with hidden") + func showAllColumnsRevealsTheDefaultHiddenFields() { + let editor = makeEditor() + let adapter = editor.adapter(for: .columns) + let collation = StructureColumnField.collation.displayName + #expect(!adapter.model.columns.orderedNames.contains(collation)) + + adapter.model.actions?.gridShowAllColumns() + + #expect(adapter.model.columns.orderedNames.contains(collation)) + #expect(adapter.model.columns.count == adapter.model.rows.columns.count) + #expect(StructureGridStateStore(section: .columns, defaults: suite.defaults).columnLayout.hiddenColumns.isEmpty) + } + + @Test("Hide Column takes the column out of the section's grid and keeps it hidden for the next table") + func hideColumnHidesAndPersists() throws { + let editor = makeEditor() + let adapter = editor.adapter(for: .indexes) + let column = try #require(adapter.model.columns.column(at: 0)) + + adapter.model.actions?.gridHideColumn(column) + + #expect(adapter.model.columns.column(id: column.id) == nil) + #expect(StructureGridStateStore(section: .indexes, defaults: suite.defaults).columnLayout.hiddenColumns == [column.name]) + } + + @Test("The last shown column stays, so the header still offers Show All Columns") + func lastShownColumnCannotBeHidden() throws { + let editor = makeEditor() + let adapter = editor.adapter(for: .indexes) + let names = adapter.model.rows.columns + adapter.model.updateColumnLayout { $0.hiddenColumns = Set(names.dropFirst()) } + let last = try #require(adapter.model.columns.column(at: 0)) + #expect(adapter.model.columns.count == 1) + + adapter.model.actions?.gridHideColumn(last) + + #expect(adapter.model.columns.orderedNames == [last.name]) + } +} From f06b75b499b68dfa96cd1afc98587ffa5ab4de88 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 13:46:21 +0700 Subject: [PATCH 2/3] docs(changelog): add the fragments for #4429 --- apple/changelog.d/4429.fixed.1.md | 1 + apple/changelog.d/4429.fixed.10.md | 1 + apple/changelog.d/4429.fixed.11.md | 1 + apple/changelog.d/4429.fixed.12.md | 1 + apple/changelog.d/4429.fixed.13.md | 1 + apple/changelog.d/4429.fixed.14.md | 1 + apple/changelog.d/4429.fixed.15.md | 1 + apple/changelog.d/4429.fixed.16.md | 1 + apple/changelog.d/4429.fixed.17.md | 1 + apple/changelog.d/4429.fixed.18.md | 1 + apple/changelog.d/4429.fixed.19.md | 1 + apple/changelog.d/4429.fixed.2.md | 1 + apple/changelog.d/4429.fixed.20.md | 1 + apple/changelog.d/4429.fixed.21.md | 1 + apple/changelog.d/4429.fixed.3.md | 1 + apple/changelog.d/4429.fixed.4.md | 1 + apple/changelog.d/4429.fixed.5.md | 1 + apple/changelog.d/4429.fixed.6.md | 1 + apple/changelog.d/4429.fixed.7.md | 1 + apple/changelog.d/4429.fixed.8.md | 1 + apple/changelog.d/4429.fixed.9.md | 1 + apple/changelog.d/4429.fixed.md | 1 + apple/changelog.d/4429.security.1.md | 1 + apple/changelog.d/4429.security.2.md | 1 + apple/changelog.d/4429.security.3.md | 1 + apple/changelog.d/4429.security.4.md | 1 + apple/changelog.d/4429.security.md | 1 + 27 files changed, 27 insertions(+) create mode 100644 apple/changelog.d/4429.fixed.1.md create mode 100644 apple/changelog.d/4429.fixed.10.md create mode 100644 apple/changelog.d/4429.fixed.11.md create mode 100644 apple/changelog.d/4429.fixed.12.md create mode 100644 apple/changelog.d/4429.fixed.13.md create mode 100644 apple/changelog.d/4429.fixed.14.md create mode 100644 apple/changelog.d/4429.fixed.15.md create mode 100644 apple/changelog.d/4429.fixed.16.md create mode 100644 apple/changelog.d/4429.fixed.17.md create mode 100644 apple/changelog.d/4429.fixed.18.md create mode 100644 apple/changelog.d/4429.fixed.19.md create mode 100644 apple/changelog.d/4429.fixed.2.md create mode 100644 apple/changelog.d/4429.fixed.20.md create mode 100644 apple/changelog.d/4429.fixed.21.md create mode 100644 apple/changelog.d/4429.fixed.3.md create mode 100644 apple/changelog.d/4429.fixed.4.md create mode 100644 apple/changelog.d/4429.fixed.5.md create mode 100644 apple/changelog.d/4429.fixed.6.md create mode 100644 apple/changelog.d/4429.fixed.7.md create mode 100644 apple/changelog.d/4429.fixed.8.md create mode 100644 apple/changelog.d/4429.fixed.9.md create mode 100644 apple/changelog.d/4429.fixed.md create mode 100644 apple/changelog.d/4429.security.1.md create mode 100644 apple/changelog.d/4429.security.2.md create mode 100644 apple/changelog.d/4429.security.3.md create mode 100644 apple/changelog.d/4429.security.4.md create mode 100644 apple/changelog.d/4429.security.md diff --git a/apple/changelog.d/4429.fixed.1.md b/apple/changelog.d/4429.fixed.1.md new file mode 100644 index 0000000000..b227f00551 --- /dev/null +++ b/apple/changelog.d/4429.fixed.1.md @@ -0,0 +1 @@ +Hide Column and Show All Columns did nothing in the Structure tab. diff --git a/apple/changelog.d/4429.fixed.10.md b/apple/changelog.d/4429.fixed.10.md new file mode 100644 index 0000000000..7c84014388 --- /dev/null +++ b/apple/changelog.d/4429.fixed.10.md @@ -0,0 +1 @@ +View ER Diagram was missing from the Favorites menu for a table in a schema named default. diff --git a/apple/changelog.d/4429.fixed.11.md b/apple/changelog.d/4429.fixed.11.md new file mode 100644 index 0000000000..a7e8615d79 --- /dev/null +++ b/apple/changelog.d/4429.fixed.11.md @@ -0,0 +1 @@ +Compare & Sync Apply sent its own BEGIN and COMMIT into a transaction already open on DuckDB or PGlite. diff --git a/apple/changelog.d/4429.fixed.12.md b/apple/changelog.d/4429.fixed.12.md new file mode 100644 index 0000000000..3d1886995c --- /dev/null +++ b/apple/changelog.d/4429.fixed.12.md @@ -0,0 +1 @@ +Stop and keep what ran in Compare & Sync reported changes PostgreSQL had rolled back as applied. diff --git a/apple/changelog.d/4429.fixed.13.md b/apple/changelog.d/4429.fixed.13.md new file mode 100644 index 0000000000..772679ed11 --- /dev/null +++ b/apple/changelog.d/4429.fixed.13.md @@ -0,0 +1 @@ +Compare showed a timestamptz copied into a column without a time zone as changed after every sync. diff --git a/apple/changelog.d/4429.fixed.14.md b/apple/changelog.d/4429.fixed.14.md new file mode 100644 index 0000000000..48b4fd9b84 --- /dev/null +++ b/apple/changelog.d/4429.fixed.14.md @@ -0,0 +1 @@ +Compare & Sync listed tables, views and routines in two schemas as one-sided instead of pairing them. diff --git a/apple/changelog.d/4429.fixed.15.md b/apple/changelog.d/4429.fixed.15.md new file mode 100644 index 0000000000..59d3347341 --- /dev/null +++ b/apple/changelog.d/4429.fixed.15.md @@ -0,0 +1 @@ +Compare & Sync offered to create or drop a table whose counterpart in the other schema could not be read. diff --git a/apple/changelog.d/4429.fixed.16.md b/apple/changelog.d/4429.fixed.16.md new file mode 100644 index 0000000000..178196784c --- /dev/null +++ b/apple/changelog.d/4429.fixed.16.md @@ -0,0 +1 @@ +Transfer Tables wrote into the destination session's current schema; it now has a Schema picker. diff --git a/apple/changelog.d/4429.fixed.17.md b/apple/changelog.d/4429.fixed.17.md new file mode 100644 index 0000000000..f328276fc9 --- /dev/null +++ b/apple/changelog.d/4429.fixed.17.md @@ -0,0 +1 @@ +Long AI chat conversations with tool calls stopped sending after the transcript was trimmed. diff --git a/apple/changelog.d/4429.fixed.18.md b/apple/changelog.d/4429.fixed.18.md new file mode 100644 index 0000000000..15fbc56f8b --- /dev/null +++ b/apple/changelog.d/4429.fixed.18.md @@ -0,0 +1 @@ +Approved write tool calls from one AI chat reply could run at the same time and out of order. diff --git a/apple/changelog.d/4429.fixed.19.md b/apple/changelog.d/4429.fixed.19.md new file mode 100644 index 0000000000..806729a81d --- /dev/null +++ b/apple/changelog.d/4429.fixed.19.md @@ -0,0 +1 @@ +Closing a connection that was still connecting left its SSH tunnel open until quit. diff --git a/apple/changelog.d/4429.fixed.2.md b/apple/changelog.d/4429.fixed.2.md new file mode 100644 index 0000000000..1956294d14 --- /dev/null +++ b/apple/changelog.d/4429.fixed.2.md @@ -0,0 +1 @@ +A moved column snapped back in a query result that had a hidden column. diff --git a/apple/changelog.d/4429.fixed.20.md b/apple/changelog.d/4429.fixed.20.md new file mode 100644 index 0000000000..e5c7bf3e48 --- /dev/null +++ b/apple/changelog.d/4429.fixed.20.md @@ -0,0 +1 @@ +A jump host that asks for a code after the key (publickey,keyboard-interactive) could not sign in. diff --git a/apple/changelog.d/4429.fixed.21.md b/apple/changelog.d/4429.fixed.21.md new file mode 100644 index 0000000000..38e53a781e --- /dev/null +++ b/apple/changelog.d/4429.fixed.21.md @@ -0,0 +1 @@ +Syncing a settings change from an older Mac reset options a newer build had set, such as Emacs key bindings. diff --git a/apple/changelog.d/4429.fixed.3.md b/apple/changelog.d/4429.fixed.3.md new file mode 100644 index 0000000000..e5c7abf7a3 --- /dev/null +++ b/apple/changelog.d/4429.fixed.3.md @@ -0,0 +1 @@ +Vim commands like x, r, ~ and o added or removed auto-paired brackets and quotes. diff --git a/apple/changelog.d/4429.fixed.4.md b/apple/changelog.d/4429.fixed.4.md new file mode 100644 index 0000000000..6b47b65e00 --- /dev/null +++ b/apple/changelog.d/4429.fixed.4.md @@ -0,0 +1 @@ +Vim's . repeated an older change instead of the last one, such as dd, J, ~ or text typed in Insert mode. diff --git a/apple/changelog.d/4429.fixed.5.md b/apple/changelog.d/4429.fixed.5.md new file mode 100644 index 0000000000..6b206c9bf3 --- /dev/null +++ b/apple/changelog.d/4429.fixed.5.md @@ -0,0 +1 @@ +Clear All in the query parameter panel cleared only the last parameter. diff --git a/apple/changelog.d/4429.fixed.6.md b/apple/changelog.d/4429.fixed.6.md new file mode 100644 index 0000000000..cbfbf08bca --- /dev/null +++ b/apple/changelog.d/4429.fixed.6.md @@ -0,0 +1 @@ +Switching query tabs carried the previous tab's caret and scroll position into the new tab. diff --git a/apple/changelog.d/4429.fixed.7.md b/apple/changelog.d/4429.fixed.7.md new file mode 100644 index 0000000000..4052bfa6cd --- /dev/null +++ b/apple/changelog.d/4429.fixed.7.md @@ -0,0 +1 @@ +Save and Save on close wrote a query result's edits but skipped the tab's unsaved .sql file. diff --git a/apple/changelog.d/4429.fixed.8.md b/apple/changelog.d/4429.fixed.8.md new file mode 100644 index 0000000000..31ec83fa77 --- /dev/null +++ b/apple/changelog.d/4429.fixed.8.md @@ -0,0 +1 @@ +Clicking a Redis database replaced the selected tab and its unsaved commands, staged edits or sort. diff --git a/apple/changelog.d/4429.fixed.9.md b/apple/changelog.d/4429.fixed.9.md new file mode 100644 index 0000000000..2595b9597f --- /dev/null +++ b/apple/changelog.d/4429.fixed.9.md @@ -0,0 +1 @@ +An ER diagram of a schema named default refreshed and saved against the schema the sidebar moved to. diff --git a/apple/changelog.d/4429.fixed.md b/apple/changelog.d/4429.fixed.md new file mode 100644 index 0000000000..91561342a8 --- /dev/null +++ b/apple/changelog.d/4429.fixed.md @@ -0,0 +1 @@ +Typing in a value window popped out of the inspector could change a row in another tab or another record. diff --git a/apple/changelog.d/4429.security.1.md b/apple/changelog.d/4429.security.1.md new file mode 100644 index 0000000000..e6235be901 --- /dev/null +++ b/apple/changelog.d/4429.security.1.md @@ -0,0 +1 @@ +An AI or MCP call naming another database on SQLite, or a schema on MySQL, ran in the current one instead. diff --git a/apple/changelog.d/4429.security.2.md b/apple/changelog.d/4429.security.2.md new file mode 100644 index 0000000000..17a8bb622d --- /dev/null +++ b/apple/changelog.d/4429.security.2.md @@ -0,0 +1 @@ +MCP explain_query with an actual plan committed its statement under Manual Commit. diff --git a/apple/changelog.d/4429.security.3.md b/apple/changelog.d/4429.security.3.md new file mode 100644 index 0000000000..5088ad1bbf --- /dev/null +++ b/apple/changelog.d/4429.security.3.md @@ -0,0 +1 @@ +A synced SSH or credential profile deletion could mark an externally edited connections file as trusted. diff --git a/apple/changelog.d/4429.security.4.md b/apple/changelog.d/4429.security.4.md new file mode 100644 index 0000000000..26f4dd1891 --- /dev/null +++ b/apple/changelog.d/4429.security.4.md @@ -0,0 +1 @@ +Publishing to the Team Catalog wrote tunnel commands and startup commands in plain text to the shared folder. diff --git a/apple/changelog.d/4429.security.md b/apple/changelog.d/4429.security.md new file mode 100644 index 0000000000..2241c7837d --- /dev/null +++ b/apple/changelog.d/4429.security.md @@ -0,0 +1 @@ +The AI chat's destructive tool ran in the current database while its approval card named another one. From be19ff417ec0c484c6b6ae1f6a3c308350a1223e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Mon, 23 Nov 2026 14:05:47 +0700 Subject: [PATCH 3/3] fix(vim): repeat a visual change over the same extent and keep Return typed in Replace mode --- .../TablePro/Core/Vim/VimEngine+Repeat.swift | 89 ++++++++++++++++--- apple/TablePro/Core/Vim/VimEngine.swift | 27 +++++- .../Core/Vim/VimEngineDotRepeatTests.swift | 41 ++++++++- 3 files changed, 139 insertions(+), 18 deletions(-) diff --git a/apple/TablePro/Core/Vim/VimEngine+Repeat.swift b/apple/TablePro/Core/Vim/VimEngine+Repeat.swift index ad482c7c93..eda4c2743d 100644 --- a/apple/TablePro/Core/Vim/VimEngine+Repeat.swift +++ b/apple/TablePro/Core/Vim/VimEngine+Repeat.swift @@ -22,25 +22,82 @@ extension VimEngine { buffer.replaceCharacters(in: range, with: string) } - // A change starts at the first key of a Normal mode command, count and register included. Typed keys are not kept: - // the text view applies them, so what they did is read from the text. + // A change starts at the first key of a Normal mode command, count and register included. In Insert and Replace + // mode a key the text view applies is not kept: what it did is read from the text. func changeKeyWillProcess(_ char: Character, shift: Bool) { guard !isRepeatingChange else { return } if changeDraft == nil { guard mode == .normal else { return } changeDraft = VimChangeDraft() } - guard mode != .insert else { - if changeDraft?.insertedRange != nil, VimInsertControl(rawValue: char) != nil { + guard !mode.isInsert else { + if changeDraft?.insertedRange != nil, engineApplies(char) { let typed = takeTypedStep() changeDraft?.insertSteps += [typed, .key(char)].compactMap { $0 } } return } + if mode.isVisual, !hasPendingVisualKey, let buffer { + let commandStart = changeDraft?.keys.count ?? 0 + changeDraft?.visualExtent = visualExtent(of: buffer.selectedRange(), in: buffer) + changeDraft?.visualCommandStart = commandStart + changeDraft?.visualRegister = selectedRegister + } let isCount = mode == .normal && isCountKey(char) changeDraft?.keys.append(VimChangeKey(character: char, shift: shift, isCount: isCount)) } + // Replace mode overwrites with every key but Return, which the text view inserts. Escape ends the change. + private func engineApplies(_ char: Character) -> Bool { + guard char != "\u{1B}" else { return false } + if mode == .replace { return char != "\r" && char != "\n" } + return VimInsertControl(rawValue: char) != nil + } + + private var hasPendingVisualKey: Bool { + pendingG || pendingReplaceCharForVisual || pendingTextObject || pendingRegisterSelect + } + + private func visualExtent(of selection: NSRange, in buffer: VimTextBuffer) -> VimVisualExtent { + let last = selection.length > 0 ? characterStart(at: NSMaxRange(selection) - 1, in: buffer) : selection.location + let first = buffer.lineAndColumn(forOffset: selection.location) + let end = buffer.lineAndColumn(forOffset: last) + let lines = end.line - first.line + 1 + return VimVisualExtent( + linewise: mode.isVisualLinewise, + lines: lines, + characters: lines == 1 ? buffer.string(in: selection).count : 0, + lastColumn: end.column + ) + } + + // The keys of the command that ended Visual mode, behind the register it was given. + private func visualOperatorKeys(of draft: VimChangeDraft) -> [VimChangeKey] { + let keys = Array(draft.keys[draft.visualCommandStart...]) + guard let register = draft.visualRegister else { return keys } + let named = [Character("\""), register].map { VimChangeKey(character: $0, shift: false, isCount: false) } + return named + keys + } + + // Selects as much from the caret as the change's selection held, in the same Visual mode. + private func selectVisualExtent(_ extent: VimVisualExtent, in buffer: VimTextBuffer) { + let caret = buffer.selectedRange().location + let lastLine = min(buffer.lineCount - 1, buffer.lineAndColumn(forOffset: caret).line + extent.lines - 1) + let end: Int + if extent.linewise { + end = buffer.offset(forLine: lastLine, column: 0) + } else if extent.lines > 1 { + end = buffer.offset(forLine: lastLine, column: extent.lastColumn) + } else { + let lastOnLine = max(caret, contentEnd(ofLineAt: caret, in: buffer) - 1) + end = characterOffset(after: caret, count: extent.characters - 1, limit: lastOnLine, in: buffer) + } + visualAnchor = caret + cursorOffset = caret + setMode(.visual(linewise: extent.linewise)) + updateVisualSelection(cursorPos: end, linewise: extent.linewise, in: buffer) + } + // Ends the typed run, which the next edit starts again at the caret. private func takeTypedStep() -> VimInsertStep? { guard let draft = changeDraft, let range = draft.insertedRange else { return nil } @@ -54,12 +111,10 @@ extension VimEngine { func changeKeyDidProcess() { guard !isRepeatingChange, let draft = changeDraft else { return } switch mode { - case .insert: + case .insert, .replace: guard draft.insertedRange == nil else { return } changeDraft?.changesText = true changeDraft?.insertedRange = NSRange(location: buffer?.selectedRange().location ?? 0, length: 0) - case .replace: - changeDraft?.changesText = true case .normal: guard !hasPendingCommand, countPrefix == 0, operatorCount == 0, selectedRegister == nil else { return } let typed = takeTypedStep() @@ -67,15 +122,16 @@ extension VimEngine { guard draft.changesText else { return } let enteredInsert = draft.insertedRange != nil || !draft.insertSteps.isEmpty let steps = draft.insertSteps + [typed].compactMap { $0 } - lastChange = VimChange(keys: draft.keys, insertSteps: enteredInsert ? steps : nil) + let visual = draft.visualExtent.map { VimVisualChange(extent: $0, operatorKeys: visualOperatorKeys(of: draft)) } + lastChange = VimChange(keys: draft.keys, insertSteps: enteredInsert ? steps : nil, visual: visual) case .visual, .commandLine: return } } - // Keeps the range of the text typed since Insert mode began in step with every edit, typed or not. + // Keeps the range of the text typed since Insert or Replace mode began in step with every edit, typed or not. func noteInsertedText(in range: NSRange, with replacement: String) { - guard mode == .insert, let inserted = changeDraft?.insertedRange else { return } + guard mode.isInsert, let inserted = changeDraft?.insertedRange else { return } let replacementLength = (replacement as NSString).length let delta = replacementLength - range.length if NSMaxRange(range) < inserted.location { @@ -118,11 +174,18 @@ extension VimEngine { isRepeatingChange = false macroRecording = recording } - for key in change.keys { - _ = process(key.character, shift: key.shift) + if let visual = change.visual, let buffer { + selectVisualExtent(visual.extent, in: buffer) + for key in visual.operatorKeys { + _ = process(key.character, shift: key.shift) + } + } else { + for key in change.keys { + _ = process(key.character, shift: key.shift) + } } if let buffer { - for step in change.insertSteps ?? [] where mode == .insert { + for step in change.insertSteps ?? [] where mode.isInsert { switch step { case .typed(let deleting, let text): deleteBeforeCaret(deleting, in: buffer) diff --git a/apple/TablePro/Core/Vim/VimEngine.swift b/apple/TablePro/Core/Vim/VimEngine.swift index 65479de8fe..f336313565 100644 --- a/apple/TablePro/Core/Vim/VimEngine.swift +++ b/apple/TablePro/Core/Vim/VimEngine.swift @@ -37,23 +37,44 @@ struct VimChangeKey { enum VimInsertStep { // What the text view did: characters deleted before the caret, then the text typed. case typed(deleting: Int, text: String) - // A key the engine handles in Insert mode, such as Ctrl-W, which Vim replays as the key. + // A key the engine applies in Insert or Replace mode, such as Ctrl-W or an overwrite, which Vim replays as the key. case key(Character) } -// `:help .`: the keys of the last command that changed the text, and what it did in Insert mode if it went on there. +// `:help visual-repeat`: the same number of characters within one line, the same number of lines with the same +// column in the last for several, the same number of lines for a linewise selection. +struct VimVisualExtent { + let linewise: Bool + let lines: Int + let characters: Int + let lastColumn: Int +} + +struct VimVisualChange { + let extent: VimVisualExtent + let operatorKeys: [VimChangeKey] +} + +// `:help .`: the keys of the last command that changed the text, and what it did in Insert or Replace mode if it went on +// there. A Visual mode change keeps the selection's extent and the keys of its operator instead of its motions. struct VimChange { var keys: [VimChangeKey] var insertSteps: [VimInsertStep]? + var visual: VimVisualChange? } struct VimChangeDraft { var keys: [VimChangeKey] = [] var changesText = false var insertSteps: [VimInsertStep] = [] - // Where the text typed since Insert mode began, or since the last engine key, sits, kept in step with every edit. + // Where the text typed since Insert or Replace mode began, or since the last engine key, sits, kept in step with + // every edit. var insertedRange: NSRange? var deletedBeforeInsert = 0 + // The selection as the last Visual mode command found it, where that command's keys start and the register it got. + var visualExtent: VimVisualExtent? + var visualCommandStart = 0 + var visualRegister: Character? } // `:help exclusive`, `:help inclusive`, `:help linewise`. diff --git a/apple/TableProTests/Core/Vim/VimEngineDotRepeatTests.swift b/apple/TableProTests/Core/Vim/VimEngineDotRepeatTests.swift index c64448eebf..64b6ef0d63 100644 --- a/apple/TableProTests/Core/Vim/VimEngineDotRepeatTests.swift +++ b/apple/TableProTests/Core/Vim/VimEngineDotRepeatTests.swift @@ -20,14 +20,15 @@ struct VimEngineDotRepeatTests { buffer.setSelectedRange(NSRange(location: caret, length: 0)) } - // A key the engine leaves to the text view is applied as the editor does: Backspace deletes, anything else types. + // A key the engine leaves to the text view is applied as the editor does: Backspace deletes, Return breaks the + // line, anything else types. private func keys(_ chars: String) { for char in chars where !engine.process(char, shift: char.isUppercase) { if char == "\u{7F}" { guard caret > 0 else { continue } buffer.replaceCharacters(in: NSRange(location: caret - 1, length: 1), with: "") } else { - buffer.replaceCharacters(in: buffer.selectedRange(), with: String(char)) + buffer.replaceCharacters(in: buffer.selectedRange(), with: char == "\r" ? "\n" : String(char)) } } } @@ -110,6 +111,42 @@ struct VimEngineDotRepeatTests { #expect(buffer.text == "SELECT x\nSELECT x") } + @Test("A Visual mode delete within a line, then . deletes as many characters from the caret") + func dotRepeatsVisualDeleteOverAsManyCharacters() { + load("one longer rest") + keys("ved") + #expect(buffer.text == " longer rest") + keys("w.") + #expect(buffer.text == " ger rest") + } + + @Test("A Visual mode delete over two lines, then . deletes to the same column two lines down") + func dotRepeatsVisualDeleteOverAsManyLines() { + load("abc def\nghi jkl\nmn opqrst uv\nwxyz wxyz\n") + keys("vjed") + #expect(buffer.text == " jkl\nmn opqrst uv\nwxyz wxyz\n") + keys("j.") + #expect(buffer.text == " jkl\nz wxyz\n") + } + + @Test("A Visual line delete, then . deletes as many lines") + func dotRepeatsVisualLineDeleteOverAsManyLines() { + load("1\n2\n3\n4\n5\n6\n", caret: 8) + keys("VGd") + #expect(buffer.text == "1\n2\n3\n4\n") + keys("gg.") + #expect(buffer.text == "3\n4\n") + } + + @Test("Return in Replace mode breaks the line again on .") + func dotRepeatsReturnInReplaceMode() { + load("abcd\nefgh\n") + keys("RX\rY\u{1B}") + #expect(buffer.text == "X\nYcd\nefgh\n") + keys("j.") + #expect(buffer.text == "X\nYcd\nX\nYgh\n") + } + @Test("A yank between a change and . leaves the change to repeat") func yankIsNotAChange() { load("abcdef\nxyz\n")