diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift index d804798354..46fd174885 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Batches.swift @@ -679,6 +679,7 @@ extension QueryExecutionCoordinator { } // One entry per result in the order `batchResultSets` places them; a count result has no rows to build. var shapes: [Bool] = [] + var superseded: Set = [] var sources: [(sql: String?, result: QueryResult)] = [] var sourceCandidates: [Int] = [] for (mapped, output) in zip(queries, outputs) { @@ -689,6 +690,7 @@ extension QueryExecutionCoordinator { continue } // Result sets the batch let go still count toward the run's results, and are never shown. + superseded.formUnion(shapes.count..<(shapes.count + output.supersededResultSetCount)) shapes += repeatElement(true, count: output.supersededResultSetCount) let pairs: [(sql: String?, result: QueryResult)] = mapped.map { mapped in zip(mapped, output.resultSets).map { (sql: $0.sql as String?, result: $1) } @@ -699,7 +701,11 @@ extension QueryExecutionCoordinator { sources.append(pair) } } - let results = RunResultPlan(producesRows: shapes) + let results = RunResultPlan( + producesRows: shapes, + keepingRowResults: AppSettingsManager.shared.dataGrid.resultSetLimitPerRun, + unavailable: superseded + ) let shown = zip(sources, sourceCandidates).map { source, candidate in results.showsRows(ofStatement: candidate) ? source : nil } diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift index f413c7d2e9..ca2b2933d3 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift @@ -98,9 +98,13 @@ private struct ExecutedStatementHistory { let results: [QueryResult] let parameters: [QueryParameter] let connection: DatabaseConnection + // Read once per run: the rows built off the main actor and the results shown take the same plan. + let rowResultLimit: Int? func keeping(_ kept: [QueryResult]) -> ExecutedStatementHistory { - ExecutedStatementHistory(prepared: prepared, results: kept, parameters: parameters, connection: connection) + ExecutedStatementHistory( + prepared: prepared, results: kept, parameters: parameters, connection: connection, rowResultLimit: rowResultLimit + ) } } @@ -470,7 +474,8 @@ extension QueryExecutionCoordinator { case .completed(let ran), .cancelled(let ran), .failed(let ran, _, _): results = ran } - let resultPlan = RunResultPlan(producesRows: results.map { !$0.columns.isEmpty }) + let rowResultLimit = AppSettingsManager.shared.dataGrid.resultSetLimitPerRun + let resultPlan = RunResultPlan(producesRows: results.map { !$0.columns.isEmpty }, keepingRowResults: rowResultLimit) let built = await buildStatementRows( zip(sent, results).enumerated().map { index, pair in resultPlan.showsRows(ofStatement: index) ? (sql: pair.0.originalSQL as String?, result: pair.1) : nil @@ -479,7 +484,7 @@ extension QueryExecutionCoordinator { ) let history = ExecutedStatementHistory( - prepared: sent, results: results, parameters: parameters, connection: conn + prepared: sent, results: results, parameters: parameters, connection: conn, rowResultLimit: rowResultLimit ) guard parent.tabExecution.settle(claim) || reportsUnknownCommitAfterStop(outcome, claim: claim) else { keepStatementsAfterStop( @@ -773,7 +778,7 @@ extension QueryExecutionCoordinator { let firstNumber = parent.tabManager.tabs.first { $0.id == tabId }?.display.pinnedResultCount ?? 0 let reading = parent.tableNameReading let ran = Array(zip(history.prepared, history.results)) - let plan = RunResultPlan(producesRows: ran.map { !$0.1.columns.isEmpty }) + let plan = RunResultPlan(producesRows: ran.map { !$0.1.columns.isEmpty }, keepingRowResults: history.rowResultLimit) let resultSets = plan.entries.enumerated().map { position, entry -> ResultSet in switch entry { case .summary(let indices): diff --git a/apple/TablePro/Core/Coordinators/RunResultPlan.swift b/apple/TablePro/Core/Coordinators/RunResultPlan.swift index 45ec117b36..a8e079d8a3 100644 --- a/apple/TablePro/Core/Coordinators/RunResultPlan.swift +++ b/apple/TablePro/Core/Coordinators/RunResultPlan.swift @@ -8,10 +8,8 @@ import TableProPluginKit // Which statements of a run become results of their own. Two or more statements that return no // rows share one summary, placed where the last of them ran, so the result of the last statement -// stays the last result. Only the last `maxRowResults` results that return rows are kept. +// stays the last result. With a limit, only that many of the newest results that return rows are kept. struct RunResultPlan: Equatable, Sendable { - static let maxRowResults = 100 - enum Entry: Equatable, Sendable { case statement(Int) case summary([Int]) @@ -25,9 +23,11 @@ struct RunResultPlan: Equatable, Sendable { var droppedRowResultCount: Int { rowResultCount - keptRowResultCount } - init(producesRows: [Bool], maxRowResults: Int = Self.maxRowResults) { + // `unavailable` are results that return rows but are already gone, so they count as dropped whatever the limit. + init(producesRows: [Bool], keepingRowResults limit: Int?, unavailable: Set = []) { let rowIndices = producesRows.indices.filter { producesRows[$0] } - let kept = Set(rowIndices.suffix(max(0, maxRowResults))) + let available = rowIndices.filter { !unavailable.contains($0) } + let kept = Set(limit.map { available.suffix(max(1, $0)) } ?? available[...]) let summarized = producesRows.indices.filter { !producesRows[$0] } let collapses = summarized.count >= 2 @@ -71,12 +71,14 @@ struct RunResultPlan: Equatable, Sendable { } var droppedNotice: String? { - guard droppedRowResultCount > 0 else { return nil } - return String( - format: String(localized: "Showing the last %1$@ of %2$@ results that returned rows."), - keptRowResultCount.formatted(), - rowResultCount.formatted() - ) + switch droppedRowResultCount { + case ...0: + return nil + case 1: + return String(localized: "1 earlier result was dropped.") + default: + return String(format: String(localized: "%@ earlier results were dropped."), droppedRowResultCount.formatted()) + } } } diff --git a/apple/TablePro/Core/Database/Access/AgentTransactionGuard.swift b/apple/TablePro/Core/Database/Access/AgentTransactionGuard.swift index a69f121875..bc9ed2421c 100644 --- a/apple/TablePro/Core/Database/Access/AgentTransactionGuard.swift +++ b/apple/TablePro/Core/Database/Access/AgentTransactionGuard.swift @@ -127,7 +127,10 @@ internal struct AgentTransactionGuard: Sendable { throw error } let pendingMatters = commitMode == .manual && writes - guard pendingMatters || startState.holdsUserTransaction else { return (value, nil) } + // A Teradata ANSI session holds every change in a transaction it opens, which then refuses the next statement. + let mayHoldWrite = writes && !controls && startState == .idle + && family.failedStatementAbortsTransaction && !family.takesBackAFailedStatement + guard pendingMatters || startState.holdsUserTransaction || mayHoldWrite else { return (value, nil) } let endState = await driver.heldSessionTransactionState() let notice = Self.notice( startState: startState, endState: endState, pendingMatters: pendingMatters, openedHold: opened @@ -142,7 +145,8 @@ internal struct AgentTransactionGuard: Sendable { openedHold: Bool ) -> String? { if startState.holdsUserTransaction || openedHold, endState == .idle { return ManualCommit.transactionEndedNotice } - return pendingMatters && endState.holdsUserTransaction ? ManualCommit.pendingNotice : nil + if pendingMatters { return endState.holdsUserTransaction ? ManualCommit.pendingNotice : nil } + return startState == .idle && !openedHold && endState.holdsUserTransaction ? ManualCommit.statementOpenedNotice : nil } nonisolated private func savepointed( diff --git a/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift b/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift index cb24fe0eac..55fed94963 100644 --- a/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift +++ b/apple/TablePro/Core/Database/Access/DatabaseAccessBridge.swift @@ -557,8 +557,9 @@ internal actor DatabaseAccessBridge { ) } - // One approved INSERT per row, on one write lease, each with the values it was approved with. - internal func runInserts(_ operation: ApprovedOperation) async throws -> Int { + // One approved INSERT per row, on one write lease, each with the values it was approved with. The notice says the + // rows are pending in a transaction. + internal func runInserts(_ operation: ApprovedOperation) async throws -> (affected: Int, notice: String?) { let reach = DriverReach() do { return try await runApprovedInserts(operation, reach: reach) @@ -567,7 +568,10 @@ internal actor DatabaseAccessBridge { } } - private func runApprovedInserts(_ operation: ApprovedOperation, reach: DriverReach) async throws -> Int { + private func runApprovedInserts( + _ operation: ApprovedOperation, + reach: DriverReach + ) async throws -> (affected: Int, notice: String?) { guard operation.kind == .writeQuery, operation.unit == .statement, !operation.statements.isEmpty else { throw Self.notApproved } let scope = operation.scope @@ -590,7 +594,7 @@ internal actor DatabaseAccessBridge { scope: scope, route: route, cancellation: .protectedWrite - ) { driver -> Int in + ) { driver -> (affected: Int, notice: String?) in reach.mark() // The hold and savepoint execute_query gets, so a Manual Commit insert waits for Commit too. let ran = try await agentGuard.running( @@ -607,7 +611,7 @@ internal actor DatabaseAccessBridge { } return affected } - return ran.value + return (ran.value, ran.notice) } } diff --git a/apple/TablePro/Core/MCP/MCPConnectionBridge.swift b/apple/TablePro/Core/MCP/MCPConnectionBridge.swift index 9d10a04494..019a44a119 100644 --- a/apple/TablePro/Core/MCP/MCPConnectionBridge.swift +++ b/apple/TablePro/Core/MCP/MCPConnectionBridge.swift @@ -218,11 +218,15 @@ public actor MCPConnectionBridge { func insertRows(_ operation: ApprovedOperation, table: String) async throws -> JsonValue { let inserted = try await access.runInserts(operation) - return .object([ + var reply: [String: JsonValue] = [ "table": .string(table), "rows_submitted": .int(operation.statements.count), - "rows_affected": .int(inserted) - ]) + "rows_affected": .int(inserted.affected) + ] + if let notice = inserted.notice { + reply["status_message"] = .string(notice) + } + return .object(reply) } func transactionControl(_ operation: ApprovedOperation, action: String) async throws -> JsonValue { diff --git a/apple/TablePro/Core/MCP/Protocol/Tools/DataTools.swift b/apple/TablePro/Core/MCP/Protocol/Tools/DataTools.swift index de2f24e50e..989b5526b3 100644 --- a/apple/TablePro/Core/MCP/Protocol/Tools/DataTools.swift +++ b/apple/TablePro/Core/MCP/Protocol/Tools/DataTools.swift @@ -348,7 +348,8 @@ public struct InsertRowsTool: MCPToolImplementation { properties: [ "table": MCPToolSchema.string(String(localized: "Table that received the rows")), "rows_submitted": MCPToolSchema.integer(String(localized: "Rows sent")), - "rows_affected": MCPToolSchema.integer(String(localized: "Rows the engine reported inserting")) + "rows_affected": MCPToolSchema.integer(String(localized: "Rows the engine reported inserting")), + "status_message": MCPToolSchema.string(String(localized: "What happened to the open transaction, when it matters")) ], required: ["table", "rows_submitted", "rows_affected"] ) diff --git a/apple/TablePro/Core/Services/Execution/BatchTransactionPolicy.swift b/apple/TablePro/Core/Services/Execution/BatchTransactionPolicy.swift index 63f319fb41..fed3e0fdf3 100644 --- a/apple/TablePro/Core/Services/Execution/BatchTransactionPolicy.swift +++ b/apple/TablePro/Core/Services/Execution/BatchTransactionPolicy.swift @@ -81,6 +81,8 @@ internal enum BatchTransactionPolicy { return SqlBlockStructure.beginStartsTransaction(followedBy: cursor.next()?.word) case "START": return cursor.next()?.word == "TRANSACTION" + case "BT": + return family == .teradata case "XA": let following = cursor.next()?.word return following == "START" || following == "BEGIN" diff --git a/apple/TablePro/Core/Services/Execution/ManualCommit.swift b/apple/TablePro/Core/Services/Execution/ManualCommit.swift index 41289f10d5..3c15baeb50 100644 --- a/apple/TablePro/Core/Services/Execution/ManualCommit.swift +++ b/apple/TablePro/Core/Services/Execution/ManualCommit.swift @@ -298,11 +298,14 @@ internal enum ManualCommit { grammar: SQLLexicalGrammar ) -> Bool { if startsTransaction(statements, databaseType: databaseType, grammar: grammar) { return true } + let isTeradata = TransactionEngineFamily.of(databaseType) == .teradata return statements.contains { statement in if CatalogChangeClassifier.effect(of: statement, databaseType: databaseType, grammar: grammar).endsTransaction { return true } - return transactionControlKeywords.contains(QueryClassifier.leadingKeyword(of: statement, grammar: grammar)) + let keyword = QueryClassifier.leadingKeyword(of: statement, grammar: grammar) + // Teradata's short form of END TRANSACTION. + return transactionControlKeywords.contains(keyword) || (isTeradata && keyword == "ET") } } @@ -326,6 +329,12 @@ internal enum ManualCommit { String(localized: "The open transaction on this connection ended while this statement ran.") } + internal static var statementOpenedNotice: String { + String( + localized: "This change is pending in a transaction the statement opened. Other statements are refused until it is committed or rolled back." + ) + } + internal static var pendingNotice: String { String(localized: "Manual Commit is on for this connection, so this change is pending until the user commits it in TablePro.") } diff --git a/apple/TablePro/Core/Services/Execution/TransactionEngineFamily.swift b/apple/TablePro/Core/Services/Execution/TransactionEngineFamily.swift index 77fc766a05..25bc70a772 100644 --- a/apple/TablePro/Core/Services/Execution/TransactionEngineFamily.swift +++ b/apple/TablePro/Core/Services/Execution/TransactionEngineFamily.swift @@ -68,11 +68,11 @@ internal enum TransactionEngineFamily: String, Hashable, Sendable, CaseIterable // After a failed statement the block takes nothing but a rollback, so one error costs every pending change. internal var failedStatementAbortsTransaction: Bool { switch self { - case .postgres, .redshift, .cockroach, .duckdb: + // Teradata mode rolls back the whole transaction on any failed request, ANSI mode on a failure such as a + // deadlock; the family cannot see the session's mode, so it takes the stricter one. + case .postgres, .redshift, .cockroach, .duckdb, .teradata: return true - // Teradata mode rolls back the whole transaction on a failed request and ANSI mode only the request; the - // family cannot see the session's mode, so Teradata keeps the answer it had before it had a family. - case .mysql, .sqlite, .sqlServer, .oracle, .redis, .teradata, .other: + case .mysql, .sqlite, .sqlServer, .oracle, .redis, .other: return false } } diff --git a/apple/TablePro/Models/Settings/AppSettings.swift b/apple/TablePro/Models/Settings/AppSettings.swift index 676f9b38c0..9d4d1cf751 100644 --- a/apple/TablePro/Models/Settings/AppSettings.swift +++ b/apple/TablePro/Models/Settings/AppSettings.swift @@ -124,6 +124,8 @@ struct DataGridSettings: Codable, Equatable { var defaultSortDirection: SortDirection var rowCopyFormat: RowCopyFormat var showInvisibleCharacters: Bool + // 0 keeps every result a run returns. + var resultSetsKeptPerRun: Int static let `default` = DataGridSettings( rowHeight: .normal, @@ -140,7 +142,8 @@ struct DataGridSettings: Codable, Equatable { defaultSortBehavior: .none, defaultSortDirection: .ascending, rowCopyFormat: .rows, - showInvisibleCharacters: true + showInvisibleCharacters: true, + resultSetsKeptPerRun: 0 ) init( @@ -158,7 +161,8 @@ struct DataGridSettings: Codable, Equatable { defaultSortBehavior: DefaultSortBehavior = .none, defaultSortDirection: SortDirection = .ascending, rowCopyFormat: RowCopyFormat = .rows, - showInvisibleCharacters: Bool = true + showInvisibleCharacters: Bool = true, + resultSetsKeptPerRun: Int = 0 ) { self.rowHeight = rowHeight self.dateFormat = dateFormat @@ -175,6 +179,7 @@ struct DataGridSettings: Codable, Equatable { self.defaultSortDirection = defaultSortDirection self.rowCopyFormat = rowCopyFormat self.showInvisibleCharacters = showInvisibleCharacters + self.resultSetsKeptPerRun = resultSetsKeptPerRun } init(from decoder: Decoder) throws { @@ -202,6 +207,7 @@ struct DataGridSettings: Codable, Equatable { showInvisibleCharacters = container.decodeSetting( .showInvisibleCharacters, default: fallback.showInvisibleCharacters ) + resultSetsKeptPerRun = container.decodeSetting(.resultSetsKeptPerRun, default: fallback.resultSetsKeptPerRun) } // MARK: - Validated Properties @@ -244,6 +250,11 @@ struct DataGridSettings: Codable, Equatable { return nil } + // Nil keeps every result. + var resultSetLimitPerRun: Int? { + resultSetsKeptPerRun > 0 ? resultSetsKeptPerRun : nil + } + var validatedQueryResultRowCap: Int { if queryResultRowCap == 0 { return 0 } return queryResultRowCap.clamped(to: SettingsValidationRules.queryResultRowCapRange) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 93949bd22a..ab34bdc913 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -3473,6 +3473,9 @@ "%@ during the Bolt handshake. If the server requires TLS, turn on SSL." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "%@ earlier results were dropped." : { + }, "%@ ends on %@ and does not renew." : { "localizations" : { @@ -13622,6 +13625,9 @@ } } } + }, + "1 earlier result was dropped." : { + }, "1 field" : { @@ -16988,6 +16994,9 @@ } } } + }, + "A run that returns more results with rows keeps only the newest. Pinned results always stay." : { + }, "a running query" : { @@ -113469,6 +113478,9 @@ } } } + }, + "Multiple Results" : { + }, "Multiple statements are not permitted for this client" : { "localizations" : { @@ -152680,6 +152692,9 @@ } } } + }, + "Results kept per run:" : { + }, "Resume" : { "localizations" : { @@ -197879,6 +197894,9 @@ }, "This change does not apply to this kind of type." : { + }, + "This change is pending in a transaction the statement opened. Other statements are refused until it is committed or rolled back." : { + }, "This change needs %@ to be recreated, and it cannot be recreated from the definition the database stored for it. Virtual tables, such as full-text search tables, are the usual reason." : { "localizations" : { @@ -216228,6 +216246,9 @@ } } } + }, + "What happened to the open transaction, when it matters" : { + }, "What is switched on here is ignored when two structures are compared. These drift between environments by design." : { "localizations" : { diff --git a/apple/TablePro/Views/Results/CellImageViewer.swift b/apple/TablePro/Views/Results/CellImageViewer.swift index a6e5fc24f0..9117a4677f 100644 --- a/apple/TablePro/Views/Results/CellImageViewer.swift +++ b/apple/TablePro/Views/Results/CellImageViewer.swift @@ -42,6 +42,8 @@ internal struct CellImageViewer: View { let format: CellImageFormat let sourceKind: CellImageSourceKind var onPopOut: (() -> Void)? + // A new one is another value, which opens on the picture. + var documentID: AnyHashable? @ViewBuilder let source: () -> Source @State private var mode: CellImageViewMode = .image @@ -53,6 +55,9 @@ internal struct CellImageViewer: View { content .frame(maxWidth: .infinity, maxHeight: .infinity) } + .onChange(of: documentID) { _ in + mode = .image + } } private var toolbar: some View { diff --git a/apple/TablePro/Views/Results/JSONCodeEditor.swift b/apple/TablePro/Views/Results/JSONCodeEditor.swift index 4c78a44aa4..1b310abff9 100644 --- a/apple/TablePro/Views/Results/JSONCodeEditor.swift +++ b/apple/TablePro/Views/Results/JSONCodeEditor.swift @@ -16,6 +16,8 @@ internal struct JSONCodeEditor: View { @ObservedObject private var themeEngine = ThemeEngine.shared @Binding var text: String let isEditable: Bool + // A new one is text replaced from outside: a new undo history, read from the top. + let documentID: AnyHashable? @State private var editorState = SourceEditorState() @State private var configuration: SourceEditorConfiguration @@ -24,9 +26,15 @@ internal struct JSONCodeEditor: View { /// modifier names the representable and never reaches it. @State private var coordinators: [any TextViewCoordinator] - init(text: Binding, isEditable: Bool, accessibilityIdentifier: String? = nil) { + init( + text: Binding, + isEditable: Bool, + accessibilityIdentifier: String? = nil, + documentID: AnyHashable? = nil + ) { self._text = text self.isEditable = isEditable + self.documentID = documentID self._configuration = State(wrappedValue: Self.makeConfiguration(isEditable: isEditable)) self._coordinators = State( wrappedValue: accessibilityIdentifier.map { [EditorAccessibilityIdentifier($0)] } ?? [] @@ -39,9 +47,14 @@ internal struct JSONCodeEditor: View { language: .json, configuration: configuration, state: $editorState, - coordinators: coordinators + coordinators: coordinators, + documentID: documentID ) .frame(maxWidth: .infinity, maxHeight: .infinity) + .onChange(of: documentID) { _ in + editorState.cursorPositions = [CursorPosition(range: NSRange(location: 0, length: 0))] + editorState.scrollPosition = .zero + } .onChange(of: isEditable) { _ in rebuildConfiguration() } diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/BlobHexEditorView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/BlobHexEditorView.swift index 0a3583e812..0522158661 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/BlobHexEditorView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/BlobHexEditorView.swift @@ -29,6 +29,8 @@ internal struct BlobHexEditorView: View { /// committed. A first-appearance flag would not do: this branch is rebuilt when the field leaves /// read-only (a row marked deleted, then restored), and its new `onChange` misses what changed. @State private var draftSource: String? + // Another document reloads the draft even while the field has focus. + @State private var draftDocument: UUID? var body: some View { if context.isReadOnly { @@ -85,9 +87,10 @@ internal struct BlobHexEditorView: View { statusLine } .onAppear(perform: loadDraftIfStale) - .onChange(of: context.value.wrappedValue) { _ in - if !isFocused { - loadDraft() + // The argument, never `context`: an action reads the previous render's. + .onChange(of: DraftSource(documentID: context.documentID, stored: context.value.wrappedValue)) { source in + if source.documentID != draftDocument || !isFocused { + loadDraft(from: source) } } } @@ -113,16 +116,25 @@ internal struct BlobHexEditorView: View { /// One place that formats the stored value for editing, so the draft and the truncation flag /// are always taken from the same read rather than from two. + private struct DraftSource: Equatable { + let documentID: UUID? + let stored: String + } + private func loadDraft() { - let stored = context.value.wrappedValue - let formatted = BlobFormattingService.shared.format(stored, for: .edit) ?? "" + loadDraft(from: DraftSource(documentID: context.documentID, stored: context.value.wrappedValue)) + } + + private func loadDraft(from source: DraftSource) { + let formatted = BlobFormattingService.shared.format(source.stored, for: .edit) ?? "" hexEditText = formatted isTruncated = formatted.hasSuffix("…") - draftSource = stored + draftSource = source.stored + draftDocument = source.documentID } private func loadDraftIfStale() { - guard draftSource != context.value.wrappedValue else { return } + guard draftSource != context.value.wrappedValue || draftDocument != context.documentID else { return } loadDraft() } @@ -132,6 +144,8 @@ internal struct BlobHexEditorView: View { loadDraft() return } + // The bytes the field already holds stage nothing, so leaving it untouched never marks the row edited. + guard !(raw as NSString).isEqual(to: context.value.wrappedValue) else { return } if let commitBytes = context.commitBytes, let data = raw.data(using: .isoLatin1) { commitBytes(data) diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/FieldEditorContext.swift b/apple/TablePro/Views/RowInspector/FieldEditors/FieldEditorContext.swift index a8e66e7b6b..a3a0441f30 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/FieldEditorContext.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/FieldEditorContext.swift @@ -27,6 +27,9 @@ internal struct FieldEditorContext { internal let allowsNullAndDefault: Bool internal let isBinaryValue: Bool + // The field's editor id: a new one is another row or a new read, so an editor seeded from the value starts over. + internal let documentID: UUID? + internal init( columnName: String, columnType: ColumnType, @@ -38,7 +41,8 @@ internal struct FieldEditorContext { commitBytes: ((Data) -> Void)? = nil, editor: FieldEditorKind? = nil, allowsNullAndDefault: Bool = true, - isBinaryValue: Bool = false + isBinaryValue: Bool = false, + documentID: UUID? = nil ) { self.columnName = columnName self.columnType = columnType @@ -51,6 +55,7 @@ internal struct FieldEditorContext { self.editor = editor self.allowsNullAndDefault = allowsNullAndDefault self.isBinaryValue = isBinaryValue + self.documentID = documentID } internal var hasMultipleValues: Bool { valueState == .multipleValues } diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/GeometryFieldView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/GeometryFieldView.swift index 0efecf9236..35a5ec6684 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/GeometryFieldView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/GeometryFieldView.swift @@ -29,9 +29,14 @@ internal struct GeometryFieldView: View { Mode(rawValue: storedMode) ?? .map } + // The latch of the row on screen: a mode another row decided is undecided here. + private var rowLatch: ModeLatch { + latch.scoped(to: context.documentID) + } + var body: some View { let resolution = resolvePreview() - let mode = latch.shown(preferred: preferredMode, preview: resolution.preview) + let mode = rowLatch.shown(preferred: preferredMode, preview: resolution.preview) VStack(alignment: .leading, spacing: 4) { toolbar(mode: mode, preview: resolution.preview) switch mode { @@ -43,30 +48,34 @@ internal struct GeometryFieldView: View { } // On a bare container the row's accessibility value lands on the picker and the caption. .accessibilityElement(children: .contain) - .onAppear { onTabStopChange?(mode == .text) } - // No reset on disappear: the lazy list unmounts off-screen rows, and Tab would then stop on a map. - .onChange(of: mode) { onTabStopChange?($0 == .text) } - // Reruns when a read starts or ends, so whichever preview comes first latches the mode. - .task(id: resolution.pending) { + // No reset on disappear: the lazy list unmounts off-screen rows, and Tab would then stop on a map. Keyed by the + // document too, since the registry files the field under an id each row reissues. + .task(id: TabStop(documentID: context.documentID, isText: mode == .text)) { + onTabStopChange?(mode == .text) + } + // Reruns when a read starts or ends, or another row opens, so whichever preview comes first latches the mode. + .task(id: PreviewRead(documentID: context.documentID, pending: resolution.pending)) { + latch = rowLatch guard let pending = resolution.pending else { latch.offer(preferred: preferredMode, preview: resolution.preview) return } - guard let loaded = await previews.load(pending, source: descriptor.source) else { return } + guard let loaded = await previews.load(pending, source: descriptor.source), !Task.isCancelled else { return } + latch = rowLatch latch.offer(preferred: preferredMode, preview: loaded) } } // Text mode reads nothing: the value is parsed only while a map is, or may be, on screen. private func resolvePreview() -> GeometryFieldPreviewStore.Resolution { - guard latch.needsPreview(preferred: preferredMode) else { + guard rowLatch.needsPreview(preferred: preferredMode) else { return GeometryFieldPreviewStore.Resolution(preview: nil, pending: nil) } let request = GeometryFieldPreviewStore.Request( text: context.value.wrappedValue, state: context.valueState ) - return previews.resolve(request, source: descriptor.source) + return previews.resolve(request, source: descriptor.source, documentID: context.documentID) } // MARK: - Toolbar @@ -112,6 +121,7 @@ internal struct GeometryFieldView: View { Binding( get: { mode }, set: { chosen in + latch = rowLatch latch.choose(chosen) storedMode = chosen.rawValue } @@ -221,6 +231,18 @@ internal struct GeometryFieldView: View { // MARK: - Mode +private extension GeometryFieldView { + struct TabStop: Equatable { + let documentID: UUID? + let isText: Bool + } + + struct PreviewRead: Equatable { + let documentID: UUID? + let pending: GeometryFieldPreviewStore.Request? + } +} + internal extension GeometryFieldView { enum Mode: String, Hashable, Sendable { case text @@ -237,9 +259,14 @@ internal extension GeometryFieldView { } } - // Decided once per view: following the text would swap the editor from under the caret once a typed value draws. + // Decided once per row: following the text would swap the editor from under the caret once a typed value draws. struct ModeLatch: Equatable { private(set) var mode: Mode? + private(set) var documentID: UUID? + + func scoped(to documentID: UUID?) -> ModeLatch { + documentID == self.documentID ? self : ModeLatch(mode: nil, documentID: documentID) + } mutating func offer(preferred: Mode, preview: GeometryFieldPreview?) { guard mode == nil else { return } @@ -283,6 +310,8 @@ internal final class GeometryFieldPreviewStore: ObservableObject { internal private(set) var token = 0 private var loaded: Request? private var pending: Request? + // Another row drops the last row's preview, which would otherwise stay up while the new value reads. + private var documentID: UUID? // A parse runs to the end, so a pane re-added mid-read joins it instead of starting a second one. private var inFlight: (request: Request, task: Task)? private let reader: Reader @@ -293,7 +322,13 @@ internal final class GeometryFieldPreviewStore: ObservableObject { self.reader = reader } - internal func resolve(_ request: Request, source: GeometryFieldSource) -> Resolution { + internal func resolve(_ request: Request, source: GeometryFieldSource, documentID: UUID? = nil) -> Resolution { + if documentID != self.documentID { + self.documentID = documentID + loaded = nil + pending = nil + preview = nil + } if request == loaded { return Resolution(preview: preview, pending: nil) } if request == pending { return Resolution(preview: preview, pending: request) } guard GeometryFieldPreview.readsSynchronously(request.text) else { diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/ImageFieldView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/ImageFieldView.swift index c7c997d0dc..ae541ef1c0 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/ImageFieldView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/ImageFieldView.swift @@ -31,6 +31,7 @@ internal struct ImageFieldView: View { columnName: context.columnName ) }, + documentID: context.documentID.map { AnyHashable($0) }, source: { source } ) .frame(height: 220) @@ -55,7 +56,8 @@ internal struct ImageFieldView: View { text: context.value, isEditable: !context.isReadOnly, font: themeEngine.valueFont, - style: .code + style: .code, + documentID: context.documentID.map { AnyHashable($0) } ) case .hex: BlobHexEditorView(context: context, drawsWell: false) diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift index 509332cab1..3b3b35a614 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift @@ -11,12 +11,16 @@ internal struct JsonEditorView: View { var isExpanded = false @State private var model: JsonFieldEditingModel + @State private var openedDocument: UUID? + // Moves each time the text is replaced from outside, which gives the editor a new history. + @State private var replacements = 0 init(context: FieldEditorContext, onPopOut: ((String) -> Void)? = nil, isExpanded: Bool = false) { self.context = context self.onPopOut = onPopOut self.isExpanded = isExpanded self._model = State(wrappedValue: JsonFieldEditingModel(storedValue: context.value.wrappedValue)) + self._openedDocument = State(wrappedValue: context.documentID) } // Through the model: binding `$model.displayText` directly would publish the model's own corrections. @@ -44,19 +48,31 @@ internal struct JsonEditorView: View { JSONCodeEditor( text: editorText, isEditable: !context.isReadOnly, - accessibilityIdentifier: "inspector-json-field" + accessibilityIdentifier: "inspector-json-field", + documentID: AnyHashable(replacements) ) .valueWell(clipsContent: true) } } // On a bare container the row's accessibility value lands on the Open in Window button too. .accessibilityElement(children: .contain) - // `newValue`, never `context.value`: the action's context is a render behind and undid every keystroke (#3051). - .onChange(of: context.value.wrappedValue) { newValue in - _ = model.received(newValue) + // The argument, never `context`: the action's context is a render behind and undid every keystroke (#3051). + .onChange(of: JsonFieldSource(documentID: context.documentID, value: context.value.wrappedValue)) { source in + if source.documentID != openedDocument { + openedDocument = source.documentID + model = JsonFieldEditingModel(storedValue: source.value) + replacements &+= 1 + } else if model.received(source.value) { + replacements &+= 1 + } } } + private struct JsonFieldSource: Equatable { + let documentID: UUID? + let value: String + } + private func header(onPopOut: @escaping (String) -> Void) -> some View { HStack(spacing: 8) { Spacer(minLength: 4) diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift index 31b682b5ec..9e392e782b 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift @@ -29,7 +29,8 @@ internal struct MultiLineEditorView: View { font: themeEngine.valueFont, movesFocusOnTab: true, style: .code, - marksInvisibleCharacters: settingsManager.dataGrid.showInvisibleCharacters + marksInvisibleCharacters: settingsManager.dataGrid.showInvisibleCharacters, + documentID: context.documentID.map { AnyHashable($0) } ) .valueWell(clipsContent: true) .overlay(alignment: .topLeading) { placeholder } diff --git a/apple/TablePro/Views/RowInspector/InspectorFieldListView.swift b/apple/TablePro/Views/RowInspector/InspectorFieldListView.swift index 9e4569be96..47ca65287f 100644 --- a/apple/TablePro/Views/RowInspector/InspectorFieldListView.swift +++ b/apple/TablePro/Views/RowInspector/InspectorFieldListView.swift @@ -181,7 +181,8 @@ internal struct InspectorFieldListView: View { : nil, editor: kind, allowsNullAndDefault: offersDatabaseValues, - isBinaryValue: field.isBinaryValue + isBinaryValue: field.isBinaryValue, + documentID: field.editorID ) } diff --git a/apple/TablePro/Views/RowInspector/InspectorFieldRow.swift b/apple/TablePro/Views/RowInspector/InspectorFieldRow.swift index 528cc509ab..dc464b9ee2 100644 --- a/apple/TablePro/Views/RowInspector/InspectorFieldRow.swift +++ b/apple/TablePro/Views/RowInspector/InspectorFieldRow.swift @@ -182,14 +182,13 @@ internal struct InspectorFieldRow: View { .accessibilityValue(context.valueState.placeholder ?? context.value.wrappedValue) } - // An editor bound straight to the value follows a new row in place. The others seed state from the - // value, such as a draft, a parsed tree or a text view's typing undo, so they start over with it. + // These follow a new row in place and start over through the context's `documentID`. The others hold a popover + // or a viewer seeded from the value, so they are built again with it. private var editorIdentity: AnyHashable { switch kind { - case .singleLine, .boolean, .enumPicker: + case .singleLine, .boolean, .enumPicker, .multiLine, .json, .blobHex, .image, .geometry: return AnyHashable(fieldID) - case .json, .phpSerialized, .binaryValue, .image, .geometry, .blobHex, .setPicker, .arrayElements, .vector, - .multiLine: + case .phpSerialized, .binaryValue, .setPicker, .arrayElements, .vector: return AnyHashable(editorID) } } diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index 433c38d4d7..9b3c11ec12 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -125,5 +125,18 @@ struct DataGridSection: View { """) } } + + Section { + Picker("Results kept per run:", selection: $settings.resultSetsKeptPerRun) { + Text("No limit").tag(0) + ForEach([10, 20, 50, 100, 200, 500, 1_000], id: \.self) { count in + Text(count.formatted()).tag(count) + } + } + } header: { + Text("Multiple Results") + } footer: { + Text("A run that returns more results with rows keeps only the newest. Pinned results always stay.") + } } } diff --git a/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift b/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift index 93bf43bc6c..5a3997dd4c 100644 --- a/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift +++ b/apple/TablePro/Views/Shared/FieldEditors/TextValueEditor.swift @@ -22,6 +22,8 @@ internal struct TextValueEditor: NSViewRepresentable { var textContainerInset = NSSize(width: 4, height: 6) var style: Style = .plain var marksInvisibleCharacters = false + // A new one is another document: the view shows it from the top, with no undo left from the one before. + var documentID: AnyHashable? func makeNSView(context: Context) -> NSScrollView { let scrollView = NSTextView.scrollableTextView() @@ -35,6 +37,7 @@ internal struct TextValueEditor: NSViewRepresentable { textView.string = text context.coordinator.lastAppliedText = text + context.coordinator.documentID = documentID return scrollView } @@ -42,6 +45,11 @@ internal struct TextValueEditor: NSViewRepresentable { guard let textView = scrollView.documentView as? NSTextView else { return } applyConfiguration(to: scrollView, textView: textView, coordinator: context.coordinator) + if context.coordinator.documentID != documentID { + context.coordinator.documentID = documentID + openDocument(in: textView, coordinator: context.coordinator) + return + } guard context.coordinator.lastAppliedText != text else { return } context.coordinator.lastAppliedText = text @@ -51,6 +59,21 @@ internal struct TextValueEditor: NSViewRepresentable { textView.setSelectedRange(NSRange(location: clamped, length: 0)) } + // The typing undo indexes into the text being replaced, and undoing it afterwards raises (measured). NSTextView files + // it under its text storage, so only this view's history goes. + private func openDocument(in textView: NSTextView, coordinator: Coordinator) { + textView.breakUndoCoalescing() + if let storage = textView.textStorage { + textView.undoManager?.removeAllActions(withTarget: storage) + } + if coordinator.lastAppliedText != text { + coordinator.lastAppliedText = text + textView.string = text + } + textView.setSelectedRange(NSRange(location: 0, length: 0)) + textView.scroll(.zero) + } + func makeCoordinator() -> Coordinator { Coordinator(text: $text, movesFocusOnTab: movesFocusOnTab) } @@ -123,6 +146,7 @@ internal struct TextValueEditor: NSViewRepresentable { /// moved" without bridging the whole NSString back, which costs 45ms on a 1 MB value and /// would run on every SwiftUI update pass. var lastAppliedText: String = "" + var documentID: AnyHashable? var themeStyle: ThemeTextViewStyle? var invisibleCharacters: InvisibleCharacterTextDisplay? diff --git a/apple/TableProTests/Core/Coordinators/RunResultLimitTests.swift b/apple/TableProTests/Core/Coordinators/RunResultLimitTests.swift new file mode 100644 index 0000000000..80a05afd60 --- /dev/null +++ b/apple/TableProTests/Core/Coordinators/RunResultLimitTests.swift @@ -0,0 +1,81 @@ +// +// RunResultLimitTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +extension GlobalStateSuites { + @MainActor + struct RunResultLimitTests { + // SQL Server: the grammar that reads GO lines as batch separators. + private let fixture = CoordinatorFixture(connection: TestFixtures.makeConnection(database: "shop", type: .mssql)) + + // Every batch answers `setsPerBatch` one-row result sets, numbered across the run. + private func run(_ text: String, setsPerBatch: Int) async throws -> [ResultSet] { + let connection = fixture.connection + let counter = BatchCounter() + let driver = ScriptAnsweringDriver(connection: connection, answer: { _ in + let first = counter.take(setsPerBatch) + return ScriptAnsweringDriver.batch((first.. Int { + lock.withLock { + defer { next += count } + return next + 1 + } + } +} diff --git a/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift b/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift index 89855fefbd..435a31ba59 100644 --- a/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift +++ b/apple/TableProTests/Core/Coordinators/RunResultPlanTests.swift @@ -12,36 +12,63 @@ import Testing struct RunResultPlanTests { @Test("Statements that return no rows share one summary placed where the last of them ran") func columnlessStatementsCollapse() { - let plan = RunResultPlan(producesRows: [false, false, true, false, true]) + let plan = RunResultPlan(producesRows: [false, false, true, false, true], keepingRowResults: nil) #expect(plan.entries == [.statement(2), .summary([0, 1, 3]), .statement(4)]) #expect(plan.droppedNotice == nil) } @Test("A single statement without rows keeps its own result") func singleColumnlessStatementStays() { - let plan = RunResultPlan(producesRows: [false, true]) + let plan = RunResultPlan(producesRows: [false, true], keepingRowResults: nil) #expect(plan.entries == [.statement(0), .statement(1)]) } @Test("A run that ends on a statement without rows ends on the summary") func summaryIsLastWhenTheRunEndsWithoutRows() { - let plan = RunResultPlan(producesRows: [true, false, false]) + let plan = RunResultPlan(producesRows: [true, false, false], keepingRowResults: nil) #expect(plan.entries.last == .summary([1, 2])) } @Test("Only the last results that return rows are kept, and only their rows are built") func rowResultsAreCapped() { - let plan = RunResultPlan(producesRows: Array(repeating: true, count: 5), maxRowResults: 2) + let plan = RunResultPlan(producesRows: Array(repeating: true, count: 5), keepingRowResults: 2) #expect(plan.entries == [.statement(3), .statement(4)]) #expect(plan.droppedRowResultCount == 3) #expect(plan.showsRows(ofStatement: 4)) #expect(!plan.showsRows(ofStatement: 0)) - #expect(plan.droppedNotice != nil) + #expect(plan.droppedNotice == "3 earlier results were dropped.") + } + + @Test("Without a limit every result that returns rows is kept") + func noLimitKeepsEveryRowResult() { + let plan = RunResultPlan(producesRows: Array(repeating: true, count: 1_000), keepingRowResults: nil) + #expect(plan.entries.count == 1_000) + #expect(plan.droppedRowResultCount == 0) + #expect(plan.droppedNotice == nil) + } + + @Test("One dropped result is named in the singular") + func oneDroppedResult() { + let plan = RunResultPlan(producesRows: [true, true, false], keepingRowResults: 1) + #expect(plan.entries == [.statement(1), .statement(2)]) + #expect(plan.droppedNotice == "1 earlier result was dropped.") + } + + @Test("Results already gone count as dropped and never take a kept place") + func unavailableResultsCountAsDropped() { + let plan = RunResultPlan(producesRows: [true, true, true, true], keepingRowResults: nil, unavailable: [0, 1]) + #expect(plan.entries == [.statement(2), .statement(3)]) + #expect(plan.position(ofStatement: 2) == 0) + #expect(plan.droppedNotice == "2 earlier results were dropped.") + + let limited = RunResultPlan(producesRows: [true, true, true, true], keepingRowResults: 1, unavailable: [0]) + #expect(limited.entries == [.statement(3)]) + #expect(limited.droppedRowResultCount == 3) } @Test("A long script of writes becomes one result") func longWriteScriptIsOneResult() { - let plan = RunResultPlan(producesRows: Array(repeating: false, count: 10_000)) + let plan = RunResultPlan(producesRows: Array(repeating: false, count: 10_000), keepingRowResults: nil) #expect(plan.entries.count == 1) #expect(!plan.showsRows(ofStatement: 0)) } diff --git a/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift b/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift index 784e91df77..c040c811c8 100644 --- a/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift +++ b/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift @@ -433,7 +433,7 @@ struct SessionTransactionTrackerTests { kind: .writeQuery ) - _ = try await DatabaseAccessBridge().runInserts(operation) + let inserted = try await DatabaseAccessBridge().runInserts(operation) let begin = try #require(driver.statements.firstIndex(of: "BEGIN")) let first = try #require(driver.statements.firstIndex(of: rows[0])) @@ -441,6 +441,22 @@ struct SessionTransactionTrackerTests { #expect(driver.statements.contains(rows[1])) #expect(!driver.statements.contains("COMMIT")) #expect(Self.states(connection.id) == [.open]) + #expect(inserted.notice == ManualCommit.pendingNotice) + } + + @Test("An insert_rows that leaves a Teradata ANSI transaction open says so") + func mcpInsertRowsThatOpenATransactionSaySo() async throws { + let (connection, driver) = Self.seed(type: .teradata) + defer { DatabaseManager.shared.removeSession(for: connection.id) } + driver.writesOpenATransaction = true + let operation = try await ApprovedOperationFixture.approve( + [OperationStatement(sql: "INSERT INTO t VALUES (1)")], scope: Self.scope(connection.id), databaseType: .teradata, + kind: .writeQuery + ) + + let inserted = try await DatabaseAccessBridge().runInserts(operation) + + #expect(inserted.notice == ManualCommit.statementOpenedNotice) } @Test("An insert_rows of several rows joining an open SQLite transaction is taken back whole when a row fails") @@ -608,9 +624,10 @@ struct SessionTransactionTrackerTests { ]) } - @Test("An agent statement over an open DuckDB transaction is refused, since a failure would abort it") - func agentStatementRefusedWithoutSavepoints() async throws { - let (connection, driver) = Self.seed(type: .duckdb) + @Test("An agent statement over an open transaction with no savepoint is refused, since a failure would abort it", + arguments: [DatabaseType.duckdb, .teradata]) + func agentStatementRefusedWithoutSavepoints(type: DatabaseType) async throws { + let (connection, driver) = Self.seed(type: type) defer { DatabaseManager.shared.removeSession(for: connection.id) } try await Self.run("BEGIN", on: connection.id) let sent = driver.statements.count @@ -624,6 +641,37 @@ struct SessionTransactionTrackerTests { #expect(driver.statements.count == sent) } + @Test("An agent's write that leaves a Teradata ANSI transaction open says so, and the next statement is refused") + func agentWriteThatOpensATransactionSaysSo() async throws { + let (connection, driver) = Self.seed(type: .teradata) + defer { DatabaseManager.shared.removeSession(for: connection.id) } + driver.writesOpenATransaction = true + + let outcome = try await DatabaseAccessBridge().runStatement( + scope: Self.scope(connection.id), query: "UPDATE t SET a = 1", maxRows: 10, timeoutSeconds: 30, cancellation: nil + ) + #expect(outcome.result.statusMessage?.contains(ManualCommit.statementOpenedNotice) == true) + + let error = await #expect(throws: (any Error).self) { + _ = try await DatabaseAccessBridge().runStatement( + scope: Self.scope(connection.id), query: "SELECT 1", maxRows: 10, timeoutSeconds: 30, cancellation: nil + ) + } + #expect(error?.localizedDescription == AbortingTransactionRefusal().errorDescription) + } + + @Test("An agent's own BEGIN on PostgreSQL gets no notice that later statements are refused") + func agentBeginIsNotTakenForAHeldWrite() async throws { + let (connection, _) = Self.seed(type: .postgresql) + defer { DatabaseManager.shared.removeSession(for: connection.id) } + + let outcome = try await DatabaseAccessBridge().runStatement( + scope: Self.scope(connection.id), query: "BEGIN", maxRows: 10, timeoutSeconds: 30, cancellation: nil + ) + + #expect(outcome.result.statusMessage?.contains(ManualCommit.statementOpenedNotice) != true) + } + @Test("Turning Manual Commit on writes the session and the connection it was opened from") func menuToggleWritesTheSession() { let (connection, _) = Self.seed(type: .postgresql) @@ -693,6 +741,13 @@ private final class TransactionScriptedDriver: PluginDriverStub, @unchecked Send private var current: PluginSessionTransactionState = .idle private var sent: [String] = [] private var abortsNext = false + private var opensOnWrite = false + + // As a Teradata ANSI session does: a change opens a transaction only COMMIT ends. + var writesOpenATransaction: Bool { + get { lock.withLock { opensOnWrite } } + set { lock.withLock { opensOnWrite = newValue } } + } var state: PluginSessionTransactionState { get { lock.withLock { current } } @@ -725,6 +780,8 @@ private final class TransactionScriptedDriver: PluginDriverStub, @unchecked Send switch query.uppercased() { case "BEGIN": current = .inTransaction case "COMMIT", "ROLLBACK": current = .idle + case let write where opensOnWrite && (write.hasPrefix("UPDATE") || write.hasPrefix("INSERT")): + current = .inTransaction default: break } return false diff --git a/apple/TableProTests/Core/Services/Execution/ManualCommitTests.swift b/apple/TableProTests/Core/Services/Execution/ManualCommitTests.swift index 91a94286a0..c891b8e502 100644 --- a/apple/TableProTests/Core/Services/Execution/ManualCommitTests.swift +++ b/apple/TableProTests/Core/Services/Execution/ManualCommitTests.swift @@ -148,7 +148,7 @@ struct ManualCommitTests { #expect(AgentTransactionGuard.protection(family: .duckdb, sessionState: .inTransaction, controlsTransaction: false) == .refuse) #expect(AgentTransactionGuard.protection(family: .redshift, sessionState: .inTransaction, controlsTransaction: false) == .refuse) #expect(AgentTransactionGuard.protection(family: .mysql, sessionState: .inTransaction, controlsTransaction: false) == .none) - #expect(AgentTransactionGuard.protection(family: .teradata, sessionState: .inTransaction, controlsTransaction: false) == .none) + #expect(AgentTransactionGuard.protection(family: .teradata, sessionState: .inTransaction, controlsTransaction: false) == .refuse) #expect(AgentTransactionGuard.protection(family: .postgres, sessionState: .idle, controlsTransaction: false) == .none) #expect(AgentTransactionGuard.protection(family: .postgres, sessionState: .inTransaction, controlsTransaction: true) == .none) } @@ -207,6 +207,22 @@ struct ManualCommitTests { #expect(AgentTransactionGuard.notice( startState: .inTransaction, endState: .inTransaction, pendingMatters: false, openedHold: false ) == nil) + #expect(AgentTransactionGuard.notice(startState: .idle, endState: .inTransaction, pendingMatters: false, openedHold: false) + == ManualCommit.statementOpenedNotice) + #expect(AgentTransactionGuard.notice(startState: .idle, endState: .idle, pendingMatters: false, openedHold: false) == nil) + } + + @Test("Teradata's BT and ET are transaction control, and only there") + func teradataShortFormsControlTheTransaction() { + let teradata = DatabaseType.teradata + for sql in ["BT", "ET", "bt;"] { + #expect(ManualCommit.controlsTransaction([sql], databaseType: teradata, grammar: teradata.lexicalGrammar), "\(sql)") + } + #expect(ManualCommit.startsTransaction(["BT"], databaseType: teradata, grammar: teradata.lexicalGrammar)) + #expect(!ManualCommit.startsTransaction(["ET"], databaseType: teradata, grammar: teradata.lexicalGrammar)) + let postgres = DatabaseType.postgresql + #expect(!ManualCommit.controlsTransaction(["ET"], databaseType: postgres, grammar: postgres.lexicalGrammar)) + #expect(!ManualCommit.controlsTransaction(["BT"], databaseType: postgres, grammar: postgres.lexicalGrammar)) } @Test("The refusal says how to run the change") diff --git a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift index 61d44164de..6e8110f87e 100644 --- a/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift +++ b/apple/TableProTests/Models/Settings/SettingsFieldDecodingTests.swift @@ -66,6 +66,20 @@ struct SettingsFieldDecodingTests { #expect(decoded.rowCopyFormat == .csvWithHeaders) } + @Test("Data Grid settings saved before results kept per run keep every result, and a choice round-trips") + func resultSetsKeptPerRunDefaultsToNoLimit() throws { + let legacy = try decode(DataGridSettings.self, #"{"showRowNumbers":false}"#) + #expect(legacy.resultSetsKeptPerRun == 0) + #expect(legacy.resultSetLimitPerRun == nil) + + var chosen = DataGridSettings.default + chosen.resultSetsKeptPerRun = 50 + let decoded = try decode(DataGridSettings.self, String(decoding: try JSONEncoder().encode(chosen), as: UTF8.self)) + #expect(decoded.resultSetLimitPerRun == 50) + + #expect(try decode(DataGridSettings.self, #"{"resultSetsKeptPerRun":-3}"#).resultSetLimitPerRun == nil) + } + @Test("Color values by type is off by default and in stored value colors without it, and a choice round-trips") func valueColorsDefaultOff() throws { #expect(ValueColorSettings.default.colorsValuesByType == false) diff --git a/apple/TableProTests/Views/Main/ResultRowsBuildOffMainTests.swift b/apple/TableProTests/Views/Main/ResultRowsBuildOffMainTests.swift index cee195562e..ce095016eb 100644 --- a/apple/TableProTests/Views/Main/ResultRowsBuildOffMainTests.swift +++ b/apple/TableProTests/Views/Main/ResultRowsBuildOffMainTests.swift @@ -160,19 +160,6 @@ struct ResultRowsBuildOffMainTests { #expect(result.tableRows.value(at: 1, column: 1) == .text("j•••@example.com")) } - @Test("A batch with more results than a run keeps shows the last ones and says how many there were") - func batchKeepsTheLastResults() async throws { - let count = RunResultPlan.maxRowResults + 2 - let answered = (1...count).map { ScriptAnsweringDriver.resultSet(columns: Self.columns, rows: [["\($0)", "x@example.com"]]) } - - let results = try await runBatch(answeredWith: answered) - - #expect(results.count == RunResultPlan.maxRowResults) - #expect(results.first?.tableRows.value(at: 0, column: 0) == .text("3")) - #expect(results.last?.tableRows.value(at: 0, column: 0) == .text("\(count)")) - #expect(results.allSatisfy { $0.statusMessage?.contains(count.formatted()) == true }) - } - @Test("A batch's numbered result sets are each masked and keep their order") func batchNumberedResultsAreMasked() async throws { let first = ScriptAnsweringDriver.resultSet(columns: Self.columns, rows: [["1", "jane@example.com"]]) diff --git a/apple/TableProTests/Views/RowInspector/GeometryFieldModeTests.swift b/apple/TableProTests/Views/RowInspector/GeometryFieldModeTests.swift index 118c5262df..72042bc4d2 100644 --- a/apple/TableProTests/Views/RowInspector/GeometryFieldModeTests.swift +++ b/apple/TableProTests/Views/RowInspector/GeometryFieldModeTests.swift @@ -108,6 +108,16 @@ struct GeometryFieldModeTests { #expect(latch.shown(preferred: .text, preview: drawable) == .map) } + @Test("A mode latched for one row is undecided for the next") + func latchBelongsToItsRow() { + let first = UUID() + var latch = ModeLatch().scoped(to: first) + latch.offer(preferred: .map, preview: .unavailable(.null)) + + #expect(latch.scoped(to: first).mode == .text) + #expect(latch.scoped(to: UUID()).mode == nil) + } + @Test("A large value shows Map while it is first read, then follows the read") func aLargeValueWaitsForItsFirstRead() { var latch = ModeLatch() diff --git a/apple/TableProTests/Views/RowInspector/GeometryFieldPreviewStoreTests.swift b/apple/TableProTests/Views/RowInspector/GeometryFieldPreviewStoreTests.swift index ab3c5e4ab1..54dceb1ead 100644 --- a/apple/TableProTests/Views/RowInspector/GeometryFieldPreviewStoreTests.swift +++ b/apple/TableProTests/Views/RowInspector/GeometryFieldPreviewStoreTests.swift @@ -44,6 +44,20 @@ struct GeometryFieldPreviewStoreTests { #expect(store.token == token) } + @Test("Another row drops the last row's preview while its own large value reads") + func anotherRowDropsThePreview() { + let store = GeometryFieldPreviewStore() + let first = UUID() + _ = store.resolve(request("POINT(1 2)"), source: .spatialColumn, documentID: first) + + let sameRow = store.resolve(request(largeLine), source: .spatialColumn, documentID: first) + let nextRow = store.resolve(request(largeLine), source: .spatialColumn, documentID: UUID()) + + #expect(isDrawable(sameRow.preview)) + #expect(nextRow.preview == nil) + #expect(nextRow.pending == request(largeLine)) + } + @Test("A new value is read and moves the token") func newValueMovesTheToken() { let store = GeometryFieldPreviewStore() diff --git a/apple/TableProTests/Views/RowInspector/InspectorRowChangeTests.swift b/apple/TableProTests/Views/RowInspector/InspectorRowChangeTests.swift index 0d56a676c0..de86e6b977 100644 --- a/apple/TableProTests/Views/RowInspector/InspectorRowChangeTests.swift +++ b/apple/TableProTests/Views/RowInspector/InspectorRowChangeTests.swift @@ -4,12 +4,14 @@ import SwiftUI import TableProTestSupport import Testing -// Selecting another row updates the list in place: a field bound to the value keeps its control and -// shows the new value, and an editor that seeds state from the value is built again. +// Selecting another row updates the list in place: each field keeps its control and shows the new value, and an +// editor that seeds state from the value starts over inside it. @MainActor struct InspectorRowChangeTests { - private static let columns = ["id", "name", "note"] - private static let types: [ColumnType] = [.integer(rawType: "INT"), .text(rawType: "VARCHAR(40)"), .text(rawType: "TEXT")] + private static let columns = ["id", "name", "note", "meta"] + private static let types: [ColumnType] = [ + .integer(rawType: "INT"), .text(rawType: "VARCHAR(40)"), .text(rawType: "TEXT"), .json(rawType: "JSON"), + ] private static func descendants(of root: NSView, as type: View.Type) -> [View] { let own = (root as? View).map { [$0] } ?? [] @@ -19,7 +21,7 @@ struct InspectorRowChangeTests { private static func select(_ row: Int, in state: MultiRowEditState) { state.configure( rowIDs: [.existing(row)], - allRows: [["\(row)", "name \(row)", "note \(row)"]], + allRows: [["\(row)", "name \(row)", "note \(row)", #"{"row": \#(row)}"#]], absentCells: [[]], columns: columns, columnTypes: types @@ -69,8 +71,8 @@ struct InspectorRowChangeTests { #expect(after.allSatisfy { field in fields.contains { $0 === field } }) } - @Test("A multi-line field is built again for the newly selected row") - func multiLineFieldStartsOverForANewRow() async throws { + @Test("A multi-line field keeps its text view, shows the new row from the start and drops the old row's typing undo") + func multiLineFieldStartsOverInPlace() async throws { let state = MultiRowEditState() Self.select(0, in: state) let window = Self.host(state) @@ -81,6 +83,16 @@ struct InspectorRowChangeTests { } try await waitUntil { noteViews().map(\.string) == ["note 0"] } let before = try #require(noteViews().first) + let undo = try #require(window.undoManager) + // The test host sends no events, so the group the end of the typing event would close is closed here. + undo.groupsByEvent = false + defer { undo.groupsByEvent = true } + window.makeFirstResponder(before) + before.setSelectedRange(NSRange(location: 6, length: 0)) + undo.beginUndoGrouping() + before.insertText(" typed", replacementRange: NSRange(location: NSNotFound, length: 0)) + undo.endUndoGrouping() + #expect(undo.canUndo) Self.select(1, in: state) try await waitUntil { @@ -88,6 +100,35 @@ struct InspectorRowChangeTests { return noteViews().map(\.string) == ["note 1"] } - #expect(noteViews().first !== before) + #expect(noteViews().first === before) + #expect(before.selectedRange() == NSRange(location: 0, length: 0)) + #expect(before.undoManager === undo) + #expect(!undo.canUndo) + } + + @Test("A JSON field keeps its editor and shows the newly selected row's document") + func jsonFieldFollowsTheRowInPlace() async throws { + let state = MultiRowEditState() + Self.select(0, in: state) + let window = Self.host(state) + defer { window.orderOut(nil) } + let root = try #require(window.contentView) + func jsonEditors() -> [NSView] { + Self.descendants(of: root, as: NSView.self).filter { $0.accessibilityIdentifier() == "inspector-json-field" } + } + func shows(_ row: Int) -> Bool { + jsonEditors().contains { ($0.accessibilityValue() as? String)?.contains("\"row\": \(row)") == true } + } + try await waitUntil { shows(0) } + let before = try #require(jsonEditors().first) + + Self.select(1, in: state) + try await waitUntil { + root.layoutSubtreeIfNeeded() + return shows(1) + } + + #expect(jsonEditors().count == 1) + #expect(jsonEditors().first === before) } } diff --git a/apple/changelog.d/4246.added.md b/apple/changelog.d/4246.added.md new file mode 100644 index 0000000000..26e0f0821f --- /dev/null +++ b/apple/changelog.d/4246.added.md @@ -0,0 +1 @@ +Settings > Data > Results kept per run limits how many results with rows a run keeps. diff --git a/apple/changelog.d/4246.changed.1.md b/apple/changelog.d/4246.changed.1.md new file mode 100644 index 0000000000..4592f97d1b --- /dev/null +++ b/apple/changelog.d/4246.changed.1.md @@ -0,0 +1 @@ +A Teradata script that starts with BT runs as its own transaction instead of inside one TablePro opens. diff --git a/apple/changelog.d/4246.changed.md b/apple/changelog.d/4246.changed.md new file mode 100644 index 0000000000..604becf744 --- /dev/null +++ b/apple/changelog.d/4246.changed.md @@ -0,0 +1 @@ +An AI agent's statement over an open Teradata transaction is refused, since a failure would roll it all back. diff --git a/apple/changelog.d/4246.fixed.1.md b/apple/changelog.d/4246.fixed.1.md new file mode 100644 index 0000000000..b6eaa8ac14 --- /dev/null +++ b/apple/changelog.d/4246.fixed.1.md @@ -0,0 +1 @@ +Tabbing through a binary field in the inspector without changing it marked the row as edited. diff --git a/apple/changelog.d/4246.fixed.2.md b/apple/changelog.d/4246.fixed.2.md new file mode 100644 index 0000000000..8714393345 --- /dev/null +++ b/apple/changelog.d/4246.fixed.2.md @@ -0,0 +1 @@ +An MCP client's insert_rows reply never said that Manual Commit held the inserted rows. diff --git a/apple/changelog.d/4246.fixed.md b/apple/changelog.d/4246.fixed.md new file mode 100644 index 0000000000..dff1c4e2e9 --- /dev/null +++ b/apple/changelog.d/4246.fixed.md @@ -0,0 +1 @@ +Moving from row to row with the inspector open was slow with text, JSON, binary, image or geometry fields.