From 9dee16af7ed5a75882a80f699b85ea535f9e4735 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 02:51:06 +0700 Subject: [PATCH 1/2] fix(macos): commit Teradata DDL the app runs, stop Run All at DDL, and offer Commit when closing with an open transaction --- .../TableProSQLGrammar/SQLCatalogEffect.swift | 3 +- .../TeradataConnection.swift | 29 +- .../TeradataStatementKind.swift | 18 + .../SQLCatalogEffectClassifierTests.swift | 1 + .../TeradataTransactionTests.swift | 59 +++ .../TeradataPluginDriver+DDL.swift | 5 + apple/TablePro/AppDelegate.swift | 11 +- ...QueryExecutionCoordinator+Parameters.swift | 32 +- .../RowEditingCoordinator+SaveChanges.swift | 13 +- .../Core/DataWrite/DataWriteExecutor.swift | 63 ++- .../Core/Database/AppDefinitionCommit.swift | 101 +++++ .../DatabaseManager+OpenTransactions.swift | 7 + .../Database/DatabaseManager+Schema.swift | 25 +- .../Database/DatabaseManager+Startup.swift | 5 +- .../Core/Database/ObjectCommentEditing.swift | 8 +- .../Core/ObjectCopy/ObjectCopyRunner.swift | 97 ++++- .../AutocommitOnlyStatement+Teradata.swift | 33 +- .../Execution/BatchCommitStatement.swift | 3 + .../Execution/BatchStatementRun.swift | 53 ++- .../Execution/BatchTransactionPolicy.swift | 2 + .../Execution/MultiStatementFailure.swift | 99 ++++- .../Execution/TransactionEndStatement.swift | 25 ++ .../Execution/TransactionEngineFamily.swift | 12 + .../Services/Export/RowImportTableMaker.swift | 45 +- .../ConnectionCloseAction.swift | 138 +++--- .../ConnectionDisconnectAction.swift | 67 ++- .../Infrastructure/LaunchIntentRouter.swift | 5 +- ...itViewController+DatabaseMenuActions.swift | 2 +- .../Infrastructure/QuitApproval.swift | 162 +++++-- .../Infrastructure/TransactionEndPrompt.swift | 263 ++++++++++++ .../TransactionEndingFlow.swift | 125 ++++++ .../Infrastructure/WorkspaceCloseAction.swift | 143 ++++--- .../Operations/RunningWorkPrompt.swift | 5 - .../TablePro/Core/Updates/AppRelauncher.swift | 49 ++- .../Core/Utilities/UI/AlertHelper.swift | 48 +++ .../TablePro/Resources/Localizable.xcstrings | 96 +++++ .../Child/ConnectionTransactionActions.swift | 71 ++- .../Main/Child/ConnectionTransactionBar.swift | 9 +- .../MainContentCoordinator+Rename.swift | 9 +- ...DataWriteExecutorTableOperationTests.swift | 172 ++++++++ .../Database/AppDefinitionCommitTests.swift | 348 +++++++++++++++ .../SessionTransactionTrackerTests.swift | 6 +- .../Core/Menu/ManualCommitMenuTests.swift | 13 +- .../Core/Operations/RunningWorkTests.swift | 15 +- .../AutocommitOnlyStatementTests.swift | 39 ++ .../Execution/BatchCommitStatementTests.swift | 38 ++ .../Execution/BatchStatementRunTests.swift | 332 +++++++++++++- .../BatchTransactionPolicyTests.swift | 15 + .../MultiStatementFailureTests.swift | 130 ++++++ .../TransactionEngineFamilyTests.swift | 8 + .../ConnectionCloseActionTests.swift | 69 +-- .../ConnectionDisconnectActionTests.swift | 42 +- .../QuitTransactionPromptTests.swift | 224 +++++++++- .../TransactionEndPromptTests.swift | 267 ++++++++++++ .../TransactionEndingFlowTests.swift | 405 ++++++++++++++++++ .../Utilities/TransactionEndAlertTests.swift | 76 ++++ .../Services/Updates/AppRelauncherTests.swift | 113 ++++- .../TableProUITests/ManualCommitUITests.swift | 23 + 58 files changed, 3817 insertions(+), 459 deletions(-) create mode 100644 apple/TablePro/Core/Database/AppDefinitionCommit.swift create mode 100644 apple/TablePro/Core/Services/Execution/TransactionEndStatement.swift create mode 100644 apple/TablePro/Core/Services/Infrastructure/TransactionEndPrompt.swift create mode 100644 apple/TablePro/Core/Services/Infrastructure/TransactionEndingFlow.swift create mode 100644 apple/TableProTests/Core/DataWrite/DataWriteExecutorTableOperationTests.swift create mode 100644 apple/TableProTests/Core/Database/AppDefinitionCommitTests.swift create mode 100644 apple/TableProTests/Core/Services/Infrastructure/TransactionEndPromptTests.swift create mode 100644 apple/TableProTests/Core/Services/Infrastructure/TransactionEndingFlowTests.swift create mode 100644 apple/TableProTests/Core/Utilities/TransactionEndAlertTests.swift diff --git a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLCatalogEffect.swift b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLCatalogEffect.swift index 5b233db5ff..bb1b393ae0 100644 --- a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLCatalogEffect.swift +++ b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLCatalogEffect.swift @@ -160,7 +160,8 @@ public enum SQLCatalogEffectClassifier { sql.range(of: #"\bINTO\b"#, options: [.regularExpression, .caseInsensitive]) != nil } - private static let transactionEndKeywords: Set = ["COMMIT", "END", "ROLLBACK", "ABORT"] + // ET is Teradata's END TRANSACTION. + private static let transactionEndKeywords: Set = ["COMMIT", "END", "ROLLBACK", "ABORT", "ET"] // PostgreSQL's `DISCARD TEMP` and `DISCARD ALL` drop the session's temporary tables. private static let discardedTableTargets: Set = ["TEMP", "TEMPORARY", "ALL"] diff --git a/apple/Packages/TableProCore/Sources/TableProTeradataCore/TeradataConnection.swift b/apple/Packages/TableProCore/Sources/TableProTeradataCore/TeradataConnection.swift index 6549494aff..3483dee05c 100644 --- a/apple/Packages/TableProCore/Sources/TableProTeradataCore/TeradataConnection.swift +++ b/apple/Packages/TableProCore/Sources/TableProTeradataCore/TeradataConnection.swift @@ -33,6 +33,8 @@ public final class TeradataConnection: @unchecked Sendable { private var _sessionMode: TeradataTransactionMode private var _sessionModeSource: TeradataSessionModeSource private var _transaction: TeradataTransactionTracker + // Nil until a switch the connection made itself, and again once a request of the user's may have moved it. + private var _defaultDatabase: String? // 3110: "The transaction was aborted by the user." public static let userAbortCode = 3_110 @@ -170,6 +172,7 @@ public final class TeradataConnection: @unchecked Sendable { _sessionMode = mode _sessionModeSource = source _transaction = TeradataTransactionTracker(mode: mode) + _defaultDatabase = config.database.flatMap { $0.isEmpty ? nil : $0 } } } @@ -223,10 +226,18 @@ public final class TeradataConnection: @unchecked Sendable { // After DATABASE inside a transaction only the closing statement is legal (ANSI counts it as DDL; Teradata mode // is not documented either way), so a switch never joins an open one, and in ANSI it is committed at once. + // The host re-sends the switch before every statement, so one to where the session already is sends nothing. public func switchDatabase(to database: String) throws { - let (mode, state) = socketLock.withLock { (_sessionMode, _transaction.state) } - guard state != .open else { throw TeradataWireError.openTransactionBlocksDatabaseSwitch } + let (mode, state, current) = socketLock.withLock { (_sessionMode, _transaction.state, _defaultDatabase) } + guard state != .open else { + // Teradata compares database names without regard to case. + guard let current, current.caseInsensitiveCompare(database) == .orderedSame else { + throw TeradataWireError.openTransactionBlocksDatabaseSwitch + } + return + } _ = try execute(TeradataSchemaQueries.setDatabase(database)) + socketLock.withLock { _defaultDatabase = database } if mode == .ansi { _ = try execute(TeradataTransactionSQL.commit(.ansi)) } @@ -280,6 +291,7 @@ public final class TeradataConnection: @unchecked Sendable { ) throws -> Int { guard socket != nil else { throw TeradataWireError.connectionFailed("not connected") } let kinds = TeradataStatementKind.kinds(in: sql) + let movesDatabase = TeradataStatementKind.mayMoveDefaultDatabase(sql) let requestNumber = nextRequest() let body = TeradataMessages.optionsParcel(returnStatementInfo: false).encoded() + TeradataMessages.requestParcel(sql: sql).encoded() @@ -303,7 +315,7 @@ public final class TeradataConnection: @unchecked Sendable { case .refused(let error): guard case .server(let code, _)? = error as? TeradataWireError else { // Refused by its reader rather than the server, so the request ran. - socketLock.withLock { _transaction.ran(kinds) } + recordRan(kinds, movesDatabase: movesDatabase) throw error } let abortRolledBack = socketLock.withLock { () -> Bool in @@ -316,15 +328,22 @@ public final class TeradataConnection: @unchecked Sendable { } throw error case .outputEnded where stopped: - socketLock.withLock { _transaction.ran(kinds) } + recordRan(kinds, movesDatabase: movesDatabase) throw TeradataWireError.cancelled case .answered, .outputEnded: - socketLock.withLock { _transaction.ran(kinds) } + recordRan(kinds, movesDatabase: movesDatabase) try reader.finish(onColumns: onColumns) return reader.activityCount } } + private func recordRan(_ kinds: [TeradataStatementKind], movesDatabase: Bool) { + socketLock.withLock { + _transaction.ran(kinds) + if movesDatabase { _defaultDatabase = nil } + } + } + private func exchange( _ body: [UInt8], requestNumber: UInt32, diff --git a/apple/Packages/TableProCore/Sources/TableProTeradataCore/TeradataStatementKind.swift b/apple/Packages/TableProCore/Sources/TableProTeradataCore/TeradataStatementKind.swift index 989c8dbc2a..9e331afb1f 100644 --- a/apple/Packages/TableProCore/Sources/TableProTeradataCore/TeradataStatementKind.swift +++ b/apple/Packages/TableProCore/Sources/TableProTeradataCore/TeradataStatementKind.swift @@ -14,6 +14,24 @@ enum TeradataStatementKind: Equatable { TeradataRequestTokens.statements(in: request).map { kind(of: $0[...]) } } + // `DATABASE x`, `SET SESSION DATABASE x` and its `SS` abbreviation move the session's default database, and a + // macro or procedure can hold one where the request text does not show it. + static func mayMoveDefaultDatabase(_ request: String) -> Bool { + TeradataRequestTokens.statements(in: request).contains { statement in + let words = statement.prefix(3).map(\.word) + switch words.first { + case "DATABASE"?, "EXEC"?, "EXECUTE"?, "CALL"?: + return true + case "SET"?: + return words.count > 2 && words[1] == "SESSION" && words[2] == "DATABASE" + case "SS"?: + return words.count > 1 && words[1] == "DATABASE" + default: + return false + } + } + } + private static let readKeywords: Set = ["SELECT", "SEL", "HELP", "SHOW", "EXPLAIN"] private static let writeKeywords: Set = ["INSERT", "INS", "UPDATE", "UPD", "DELETE", "DEL", "MERGE"] private static let lockTypes: Set = ["ACCESS", "READ", "WRITE", "EXCLUSIVE", "SHARE", "CHECKSUM", "LOAD"] diff --git a/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLCatalogEffectClassifierTests.swift b/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLCatalogEffectClassifierTests.swift index 25e49d5127..b1b960672e 100644 --- a/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLCatalogEffectClassifierTests.swift +++ b/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLCatalogEffectClassifierTests.swift @@ -56,6 +56,7 @@ struct SQLCatalogEffectClassifierTests { #expect(SQLCatalogEffectClassifier.effect(of: "rollback", grammar: grammar("MySQL")).endsTransaction) #expect(SQLCatalogEffectClassifier.effect(of: "ROLLBACK TO SAVEPOINT a", grammar: grammar("PostgreSQL")) == .none) #expect(SQLCatalogEffectClassifier.effect(of: "BEGIN", grammar: grammar("PostgreSQL")) == .none) + #expect(SQLCatalogEffectClassifier.effect(of: "ET", grammar: grammar("Teradata")).endsTransaction) } @Test("Code the text cannot show refreshes every kind") diff --git a/apple/Packages/TableProCore/Tests/TableProTeradataCoreTests/TeradataTransactionTests.swift b/apple/Packages/TableProCore/Tests/TableProTeradataCoreTests/TeradataTransactionTests.swift index 03a1018f8c..b842c9060a 100644 --- a/apple/Packages/TableProCore/Tests/TableProTeradataCoreTests/TeradataTransactionTests.swift +++ b/apple/Packages/TableProCore/Tests/TableProTeradataCoreTests/TeradataTransactionTests.swift @@ -459,6 +459,65 @@ struct TeradataTransactionStatementTests { #expect(throws: TeradataWireError.self) { try tera.switchDatabase(to: "hr") } #expect(try TeradataWire.sentSQL(teraTransport) == [TeradataSchemaQueries.setDatabase("sales"), "BEGIN TRANSACTION"]) } + + @Test("Inside an open transaction a switch to the database the session is on sends nothing") + func switchToTheCurrentDatabaseInsideATransaction() throws { + let (ansi, ansiTransport) = TeradataWire.connection( + [TeradataWire.finished, TeradataWire.finished, TeradataWire.finished], mode: .ansi + ) + try ansi.switchDatabase(to: "sales") + _ = try ansi.execute("UPDATE sales.t SET a = 1") + + try ansi.switchDatabase(to: "SALES") + + #expect(try TeradataWire.sentSQL(ansiTransport) == [ + TeradataSchemaQueries.setDatabase("sales"), "COMMIT WORK", "UPDATE sales.t SET a = 1", + ]) + #expect(ansi.transactionState == .open) + + let (tera, teraTransport) = TeradataWire.connection([TeradataWire.finished, TeradataWire.finished], mode: .tera) + try tera.switchDatabase(to: "sales") + try tera.beginTransaction() + try tera.switchDatabase(to: "sales") + #expect(try TeradataWire.sentSQL(teraTransport) == [TeradataSchemaQueries.setDatabase("sales"), "BEGIN TRANSACTION"]) + } + + @Test( + "A request that moves the default database leaves the next switch inside a transaction refused", + arguments: ["DATABASE hr", "SET SESSION DATABASE hr", "SS DATABASE hr", "EXEC sales.refresh", "CALL sales.load()"] + ) + func userMovedDatabaseIsNotTrusted(_ statement: String) throws { + let (ansi, ansiTransport) = TeradataWire.connection( + [TeradataWire.finished, TeradataWire.finished, TeradataWire.finished], mode: .ansi + ) + try ansi.switchDatabase(to: "sales") + _ = try ansi.execute(statement) + + #expect(throws: TeradataWireError.self) { try ansi.switchDatabase(to: "sales") } + #expect(try TeradataWire.sentSQL(ansiTransport).count == 3) + } +} + +struct TeradataDefaultDatabaseStatementTests { + @Test( + "Statements that can move the default database", + arguments: [ + ("DATABASE hr", true), + ("database \"hr\";", true), + ("SET SESSION DATABASE hr", true), + ("ss database hr", true), + ("EXEC sales.refresh", true), + ("CALL sales.load()", true), + ("SELECT 1; DATABASE hr", true), + ("SET SESSION DATEFORM = ANSIDATE", false), + ("SELECT DATABASE", false), + ("CREATE DATABASE hr FROM dbc AS PERM = 0", false), + ("COMMENT ON DATABASE hr AS 'x'", false), + ] + ) + func mayMoveDefaultDatabase(_ request: String, _ moves: Bool) { + #expect(TeradataStatementKind.mayMoveDefaultDatabase(request) == moves) + } } struct TeradataUnreadableColumnTests { diff --git a/apple/Plugins/TeradataDriverPlugin/TeradataPluginDriver+DDL.swift b/apple/Plugins/TeradataDriverPlugin/TeradataPluginDriver+DDL.swift index 8adab53cd0..2c577c9976 100644 --- a/apple/Plugins/TeradataDriverPlugin/TeradataPluginDriver+DDL.swift +++ b/apple/Plugins/TeradataDriverPlugin/TeradataPluginDriver+DDL.swift @@ -105,6 +105,11 @@ extension TeradataPluginDriver { ) } + // Teradata has no TRUNCATE; DELETE ... ALL is its documented way to empty a table, and it has no CASCADE. + func truncateTableStatements(table: String, schema: String?, cascade: Bool) -> [String]? { + ["DELETE FROM \(TeradataSchemaQueries.qualifiedName(database: effectiveDatabase(schema), table: table)) ALL"] + } + func createViewTemplate() -> String? { "CREATE VIEW view_name AS\nSELECT column1, column2\nFROM table_name\nWHERE condition;" } diff --git a/apple/TablePro/AppDelegate.swift b/apple/TablePro/AppDelegate.swift index c833ee9f38..ee214d45f4 100644 --- a/apple/TablePro/AppDelegate.swift +++ b/apple/TablePro/AppDelegate.swift @@ -177,13 +177,20 @@ class AppDelegate: NSObject, NSApplicationDelegate { } func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { - guard QuitApproval.approve() else { + guard let plan = QuitApproval.approve() else { AppRelauncher.shared.terminationWasCancelled() return .terminateCancel } Task { - // First, while the drivers are open: a debug stop rolls back the routine's transaction. + // Before anything the app could not take back if it stays open. + guard await QuitApproval.commitBeforeQuitting(plan) else { + NSApp.reply(toApplicationShouldTerminate: false) + AppRelauncher.shared.terminationWasCancelled() + return + } + RunningWorkRegistry.shared.cancel(plan.work) + // While the drivers are open: a debug stop rolls back the routine's transaction. await AppModuleTermination.stopModuleWork() await MCPServerManager.shared.stop() await DatabaseManager.shared.runPostDisconnectScriptsBeforeQuit() diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift index f413c7d2e9..152579be1e 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Parameters.swift @@ -46,9 +46,11 @@ private struct PreparedStatement: @unchecked Sendable { let anchor: StatementAnchor? /// Where the script was cut after this statement, which a replan of the rest starts from. let statement: SQLStatementScanner.ExecutableStatement? - /// Whether this is the script's own `COMMIT`, read from the text before the lease is taken so - /// the run never lexes inside it. + // Read from the text before the lease is taken, so the run never lexes inside it. let isCommitPoint: Bool + let endsItsTransaction: Bool + let closesTransaction: Bool + let movesDatabase: Bool } // What a run sends: the rest is cut again from the script once a statement changes how the session reads literals. @@ -441,7 +443,8 @@ extension QueryExecutionCoordinator { ) let outcome = run.outcome let sent = running.prepared - let sessionNotice = run.plan.readsSessionEndState ? run.sessionState.openTransactionNotice : nil + let readsEndState = run.plan.readsSessionEndState || run.plan == .autocommit + let sessionNotice = readsEndState ? run.sessionState.openTransactionNotice : nil let ranStatements: [String] switch outcome { @@ -544,6 +547,8 @@ extension QueryExecutionCoordinator { : SQLParameterExtractor.convertToNativeStyle(sql: sql, parameters: parameters, style: style, grammar: grammar) let executableSQL = conversion?.sql ?? sql let bounded = resolveStatement(sql: executableSQL, tabType: tabType, bypassLimit: bypassRowLimit) + let family = TransactionEngineFamily.of(parent.connection.type) + let definitionEnds = family.definitionEndsTransaction return PreparedStatement( originalSQL: sql, executableSQL: executableSQL, @@ -552,7 +557,10 @@ extension QueryExecutionCoordinator { rowCap: bounded.rowCap, anchor: StatementAnchor(statement), statement: statement, - isCommitPoint: BatchCommitStatement.matches(sql, grammar: grammar) + isCommitPoint: BatchCommitStatement.matches(sql, grammar: grammar), + endsItsTransaction: definitionEnds && AutocommitOnlyStatement.matches(sql, family: family, grammar: grammar), + closesTransaction: definitionEnds && TransactionEndStatement.matches(sql, grammar: grammar), + movesDatabase: AutocommitOnlyStatement.movesDatabase(sql, family: family, grammar: grammar) ) } @@ -571,6 +579,7 @@ extension QueryExecutionCoordinator { let failureOutput = ServerOutputBox() let commitOutput = ServerOutputBox() let databaseType = parent.connection.type + let definitionEnds = TransactionEngineFamily.of(databaseType).definitionEndsTransaction let safeModeIsReadOnly = parent.runsAtReadOnly let grammar = parent.lexicalGrammar let statementTexts = prepared.map(\.sentSQL) @@ -601,6 +610,9 @@ extension QueryExecutionCoordinator { gate: self.claimGate(for: claim), failureSQL: \.executableSQL, isCommitPoint: \.isCommitPoint, + endsItsTransaction: \.endsItsTransaction, + closesTransaction: \.closesTransaction, + movesDatabase: \.movesDatabase, replanned: { ran in running.replanned( after: ran, @@ -629,14 +641,15 @@ extension QueryExecutionCoordinator { let endState: PluginSessionTransactionState = asksEndState ? await driver.heldSessionTransactionState() : .unknown - // An unwrapped run can still leave a transaction open: a Teradata ANSI session holds its DDL in one. - let failedState: PluginSessionTransactionState = sessionPlan == .autocommit && !outcome.isCompleted + // An unwrapped run can still leave a transaction open: a Teradata ANSI session holds its DDL in one, completed or not. + let readsHeldWork = sessionPlan == .autocommit && (!outcome.isCompleted || definitionEnds) + let heldState: PluginSessionTransactionState = readsHeldWork ? (asksEndState ? endState : await driver.heldSessionTransactionState()) : .idle return MultiStatementRun( outcome: outcome, plan: sessionPlan, - sessionState: failedState, + sessionState: heldState, startState: startState, endState: endState ) @@ -931,7 +944,10 @@ extension QueryExecutionCoordinator { .flatMap { anchors.indices.contains($0) ? anchors[$0] : nil } let failedStatementSQL = report.failedSQL - reportOperation(kind: .queryBatch, claim: claim, outcome: .failed(reason: errorDescription)) + // A run stopped to wait for a commit has no server error, so the notification carries the report. + reportOperation( + kind: .queryBatch, claim: claim, outcome: .failed(reason: errorDescription.isEmpty ? report.message : errorDescription) + ) recordExecutedStatements( history, tabId: tabId, diff --git a/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift b/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift index 33ece94cc8..805110f096 100644 --- a/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift +++ b/apple/TablePro/Core/Coordinators/RowEditingCoordinator+SaveChanges.swift @@ -352,18 +352,19 @@ extension RowEditingCoordinator { } if clearTableOps { - /// On an engine whose DDL commits as it runs, a TRUNCATE before the failure has - /// already emptied its table, and nothing reports which ones ran. Queuing them - /// again would empty the table a second time on the next Save, rows added since - /// included, so they are left for the user to stage again. + // The executor throws every refusal before its first statement. + let ranNothing = error is any ManualCommitRefusing + // Where DDL commits as it runs a failed save may have emptied a table, and a requeued truncate empties it again. let ddlRolledBack = DatabaseManager.shared.driver(for: conn.id)?.supportsTransactionalDDL ?? false restorePendingTableOperations( connectionId: conn.id, - truncates: ddlRolledBack ? truncatedTables : [], + truncates: ranNothing || ddlRolledBack ? truncatedTables : [], deletes: deletedTables, options: capturedOptions ) - reconcileDropsAfterFailedSave(deletedTables, scope: scope) + if !ranNothing { + reconcileDropsAfterFailedSave(deletedTables, scope: scope) + } } failSave( diff --git a/apple/TablePro/Core/DataWrite/DataWriteExecutor.swift b/apple/TablePro/Core/DataWrite/DataWriteExecutor.swift index 1bc2d5077c..00d4028167 100644 --- a/apple/TablePro/Core/DataWrite/DataWriteExecutor.swift +++ b/apple/TablePro/Core/DataWrite/DataWriteExecutor.swift @@ -26,6 +26,7 @@ import Foundation import os import TableProPluginKit +import TableProSQLGrammar struct DataWriteStepResult: Sendable { let executionTime: TimeInterval @@ -118,6 +119,11 @@ enum DataWriteExecutor { try ManualCommit.refuseUnheldWrite(supportsTransactions: driver.supportsTransactions, sessionState: state) } + let endsSegment = definitionSteps(steps, of: plan) + if endsSegment.contains(true) { + try await refuseDefinitions(on: driver, commitMode: commitMode) + } + // A row a lookup cannot find on its own refuses the save before anything is written. Each step reads its // lookup again right before it runs, since the steps ahead of it can move or change its rows. for step in steps { @@ -174,6 +180,9 @@ enum DataWriteExecutor { let countsKeyedUpdates = DataWriteRowCounts.countsMatchedRows(for: plan.databaseType) && plan.viewTarget == nil // A delete earlier in the save can cascade to a row a later update edits, which then matches nothing. var ranDelete = false + let closesSegments = endsSegment.contains(true) && owner == .app + var committedCount = 0 + var lastSegmentClosed = false do { if owner.sendsBegin { @@ -181,7 +190,7 @@ enum DataWriteExecutor { if owner == .held { ManualCommit.turnHold?.mark(true) } } - for step in steps { + for (index, step) in steps.enumerated() { let start = Date() var statement = step.statement if let lookup = step.lookup { @@ -231,9 +240,19 @@ enum DataWriteExecutor { if let check = step.lookup?.check { try await confirmLanded(check, for: step, on: driver) } + + if closesSegments, endsSegment[index] { + try await TaskCancellationShield.run { try await driver.commitTransaction() } + committedCount = results.count + lastSegmentClosed = index == steps.count - 1 + if !lastSegmentClosed { + try await driver.beginTransaction(mode: mode) + } + } } - if owner.commitsAtEnd { + // Teradata mode answers an END TRANSACTION with no BT open with an error. + if owner.commitsAtEnd, !lastSegmentClosed { try await driver.commitTransaction() } } catch { @@ -249,11 +268,16 @@ enum DataWriteExecutor { } await drainEpilogue() - /// Without a transaction the statements that already ran are on the server for good, - /// and so they are when the rollback itself failed. Reporting that as a plain failure - /// tells the user to try again, and trying again writes them a second time. A run that - /// joined the user's own transaction is the third case: the statements are pending in - /// it, and only the user can commit or roll it back. + if committedCount > 0 { + throw DataWritePartialCommitError( + committed: rollbackSucceeded ? Array(results.prefix(committedCount)) : results, + totalStatements: steps.count, + engine: plan.databaseType.rawValue, + disposition: .written, + underlying: error + ) + } + // What ran stays written, or pending in a transaction only the user ends, so a plain failure would invite a retry. if !rollbackSucceeded, !results.isEmpty { throw DataWritePartialCommitError( committed: results, @@ -270,6 +294,31 @@ enum DataWriteExecutor { return DataWriteRun(results: results, sideStatements: sideStatements) } + // Teradata takes only COMMIT or ROLLBACK after a definition statement; its truncate is a DELETE, which joins as DML. + private static func definitionSteps(_ steps: [DataWriteStep], of plan: DataWritePlan) -> [Bool] { + let family = TransactionEngineFamily.of(plan.databaseType) + guard family.definitionEndsTransaction else { return Array(repeating: false, count: steps.count) } + let grammar = SQLLexicalResolver.readings(for: plan.databaseType, session: plan.sessionLexicalState).execution + return steps.map { AutocommitOnlyStatement.matches($0.statement.sql, family: family, grammar: grammar) } + } + + // Refused before anything runs: the commit after a definition statement would end the transaction the session holds. + private static func refuseDefinitions(on driver: DatabaseDriver, commitMode: ConnectionCommitMode) async throws { + let owner = WriteTransactionOwner.resolve( + supportsTransactions: driver.supportsTransactions, + sessionState: await driver.heldSessionTransactionState(), + commitMode: commitMode + ) + switch owner { + case .session: + throw DefinitionInOpenTransactionRefusal() + case .held: + throw ManualCommitRefusal() + case .app, .none: + return + } + } + private static func openPreservingScope(on driver: DatabaseDriver) async -> PluginSessionScope? { do { return try await driver.openSessionScope(for: .preserve) diff --git a/apple/TablePro/Core/Database/AppDefinitionCommit.swift b/apple/TablePro/Core/Database/AppDefinitionCommit.swift new file mode 100644 index 0000000000..c31da06e56 --- /dev/null +++ b/apple/TablePro/Core/Database/AppDefinitionCommit.swift @@ -0,0 +1,101 @@ +// +// AppDefinitionCommit.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +// Refused before anything ran, so an external caller reads it as it is. +internal struct DefinitionInOpenTransactionRefusal: ManualCommitRefusing, Equatable { + var errorDescription: String? { + String( + localized: "A transaction is open on this connection, and this change would have to end it. Commit or roll back the transaction, then try again." + ) + } +} + +// One statement the app runs with no BEGIN of its own; a Teradata ANSI session keeps it pending until a COMMIT. +internal enum AppDefinitionCommit { + internal static func run( + family: TransactionEngineFamily, + refusesOpenTransaction: Bool, + readState: () async -> PluginSessionTransactionState, + commit: @escaping @Sendable () async throws -> Void, + rollback: @escaping @Sendable () async throws -> Void, + body: () async throws -> T + ) async throws -> T { + guard family.unwrappedWorkStaysOpen else { return try await body() } + let before = await readState() + if refusesOpenTransaction, before.holdsUserTransaction { + throw DefinitionInOpenTransactionRefusal() + } + do { + let value = try await body() + try await commitIfOpen(family: family, readState: readState, commit: commit) + return value + } catch { + // Teradata keeps a failed request's locks until the transaction ends. + if before == .idle { + _ = try? await TaskCancellationShield.run(rollback) + } + throw error + } + } + + internal static func commitIfOpen( + family: TransactionEngineFamily, + readState: () async -> PluginSessionTransactionState, + commit: @escaping @Sendable () async throws -> Void + ) async throws { + guard family.unwrappedWorkStaysOpen, await readState() == .inTransaction else { return } + // The work it ends has already run, so a cancelled task must not refuse it. + try await TaskCancellationShield.run(commit) + } +} + +extension AppDefinitionCommit { + internal static func run( + on driver: DatabaseDriver, + refusesOpenTransaction: Bool, + body: () async throws -> T + ) async throws -> T { + try await run( + family: TransactionEngineFamily.of(driver.connection.type), + refusesOpenTransaction: refusesOpenTransaction, + readState: { await driver.heldSessionTransactionState() }, + commit: { try await driver.commitTransaction() }, + rollback: { try await driver.rollbackTransaction() }, + body: body + ) + } + + internal static func run( + on driver: any PluginDatabaseDriver, + family: TransactionEngineFamily, + refusesOpenTransaction: Bool, + body: () async throws -> T + ) async throws -> T { + try await run( + family: family, + refusesOpenTransaction: refusesOpenTransaction, + readState: { await Self.heldState(of: driver) }, + commit: { try await driver.commitTransaction() }, + rollback: { try await driver.rollbackTransaction() }, + body: body + ) + } + + internal static func commitIfOpen(on driver: any PluginDatabaseDriver, family: TransactionEngineFamily) async throws { + try await commitIfOpen( + family: family, + readState: { await Self.heldState(of: driver) }, + commit: { try await driver.commitTransaction() } + ) + } + + private static func heldState(of driver: any PluginDatabaseDriver) async -> PluginSessionTransactionState { + guard driver.supportsTransactions else { return .unknown } + return await driver.sessionTransactionState() + } +} diff --git a/apple/TablePro/Core/Database/DatabaseManager+OpenTransactions.swift b/apple/TablePro/Core/Database/DatabaseManager+OpenTransactions.swift index 6739a615f7..e922e93eb5 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+OpenTransactions.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+OpenTransactions.swift @@ -103,6 +103,13 @@ extension DatabaseManager { return safety } + // A turn running on the hold's own connection, which a commit would have to wait behind. + internal func isLaneBusy(holding hold: SessionTransactionTracker.Hold) -> Bool { + let key = hold.key.lane.map { SessionDriverGate.Key(connectionId: hold.connectionId, database: $0) } + ?? browsedGateKey(for: hold.connectionId) + return sessionDriverGate.isHeld(key) + } + /// Ends the transaction a hold shows, on the connection that holds it. Refused when that /// connection was replaced, or when other work ran there after the hold was read: the user /// confirmed what they saw, not a transaction someone opened since. diff --git a/apple/TablePro/Core/Database/DatabaseManager+Schema.swift b/apple/TablePro/Core/Database/DatabaseManager+Schema.swift index f08b0e99c2..5b3342fe02 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+Schema.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+Schema.swift @@ -72,7 +72,7 @@ extension DatabaseManager { do { for stmt in statements { let startedAt = Date() - _ = try await driver.execute(query: stmt.sql) + try await Self.runSchemaStatement(stmt.sql, on: driver, wrapped: useTransaction, isPooled: isPooled) measured.append(Date().timeIntervalSince(startedAt)) } if useTransaction { @@ -86,6 +86,9 @@ extension DatabaseManager { Self.logger.error("Rollback failed after schema change error: \(error.localizedDescription)") } } + if measured.isEmpty, error is DefinitionInOpenTransactionRefusal { + throw error + } let applied: [SchemaStatement] = useTransaction ? [] : statements.prefix(measured.count).filter { !$0.carriesCredentials } @@ -99,6 +102,8 @@ extension DatabaseManager { } } catch let refusal as SchemaOperationRefusedError { throw refusal + } catch let refusal as DefinitionInOpenTransactionRefusal { + throw refusal } catch let failure as SchemaChangeFailedAfterWriting { Self.reportCatalogChangeAfterFailure(in: scope) reportSavedChange(of: script, in: scope) @@ -137,6 +142,22 @@ extension DatabaseManager { driver.supportsTransactions && driver.supportsTransactionalDDL } + // On the session driver the commit after an unwrapped statement would end the user's open transaction too. + nonisolated private static func runSchemaStatement( + _ sql: String, + on driver: DatabaseDriver, + wrapped: Bool, + isPooled: Bool + ) async throws { + guard !wrapped else { + _ = try await driver.execute(query: sql) + return + } + _ = try await AppDefinitionCommit.run(on: driver, refusesOpenTransaction: !isPooled) { + try await driver.execute(query: sql) + } + } + /// A save that only set the comment changed no column, so it is announced as a comment change. private func reportSavedChange(of script: SchemaChangeScript, in scope: DatabaseScope) { guard script.setsCommentOnly else { @@ -272,7 +293,7 @@ extension DatabaseManager { do { for statement in statements { let startedAt = Date() - _ = try await driver.execute(query: statement) + try await Self.runSchemaStatement(statement, on: driver, wrapped: useTransaction, isPooled: isPooled) measured.append(Date().timeIntervalSince(startedAt)) } if useTransaction { diff --git a/apple/TablePro/Core/Database/DatabaseManager+Startup.swift b/apple/TablePro/Core/Database/DatabaseManager+Startup.swift index 3804867891..9f76d161dc 100644 --- a/apple/TablePro/Core/Database/DatabaseManager+Startup.swift +++ b/apple/TablePro/Core/Database/DatabaseManager+Startup.swift @@ -69,7 +69,10 @@ extension DatabaseManager { let grammar = SQLLexicalResolver.readings(for: databaseType, session: driver.sessionLexicalState).execution for statement in Self.startupStatements(from: commands, databaseType: databaseType, grammar: grammar) { do { - _ = try await driver.execute(query: statement) + // Teradata ANSI keeps `DATABASE` pending and takes only COMMIT after it; a failed commit fails the statement. + _ = try await AppDefinitionCommit.run(on: driver, refusesOpenTransaction: false) { + try await driver.execute(query: statement) + } Self.startupLogger.info( "Startup command succeeded for '\(connectionName, privacy: .private)': \(statement, privacy: .private)" ) diff --git a/apple/TablePro/Core/Database/ObjectCommentEditing.swift b/apple/TablePro/Core/Database/ObjectCommentEditing.swift index 15b025159d..3502c381ad 100644 --- a/apple/TablePro/Core/Database/ObjectCommentEditing.swift +++ b/apple/TablePro/Core/Database/ObjectCommentEditing.swift @@ -101,12 +101,16 @@ enum DatabaseObjectCommandRunner { if let denial = decision.denialError { throw denial } let startedAt = Date() + let route = DatabaseManager.shared.schemaChangeRoute(for: scope) + let refusesOpenTransaction = !route.isPooled try await DatabaseManager.shared.withScopedDriver( scope: scope, - route: DatabaseManager.shared.schemaChangeRoute(for: scope), + route: route, cancellation: .protectedWrite ) { driver in - _ = try await driver.execute(query: sql) + _ = try await AppDefinitionCommit.run(on: driver, refusesOpenTransaction: refusesOpenTransaction) { + try await driver.execute(query: sql) + } } await DatabaseManager.shared.historyRecorder.record( diff --git a/apple/TablePro/Core/ObjectCopy/ObjectCopyRunner.swift b/apple/TablePro/Core/ObjectCopy/ObjectCopyRunner.swift index 784eeac6eb..e5e5c79c14 100644 --- a/apple/TablePro/Core/ObjectCopy/ObjectCopyRunner.swift +++ b/apple/TablePro/Core/ObjectCopy/ObjectCopyRunner.swift @@ -275,6 +275,7 @@ internal struct ObjectCopyRunner { let pinsSession = plan.isStructureReadPinned && VerbatimTransferScopes.isSameEngine( source: request.source.databaseType, target: request.target.databaseType ) + let family = TransactionEngineFamily.of(request.target.databaseType) return try await manager.withMetadataDriver(scope: scope) { driver in guard let plugin = CompareMetadataService.pluginDriver(from: driver) else { @@ -285,6 +286,7 @@ internal struct ObjectCopyRunner { let usesTransaction = hasCleanup && errorHandling == .stopAndRollback && plugin.supportsTransactionalDDL && owner.sendsBegin && owner.commitsAtEnd if usesTransaction { try await plugin.beginTransaction(mode: .readWrite) } + let committingEach = usesTransaction ? nil : Self.standaloneFamily(family, owner: owner) var result: DDLResult do { @@ -297,6 +299,7 @@ internal struct ObjectCopyRunner { on: plugin, pinsSession: pinsSession, errorHandling: errorHandling, + committingEach: committingEach, progress: progress ) } @@ -309,7 +312,8 @@ internal struct ObjectCopyRunner { /// `sql_mode`: it gets its own creation settings, or else the target's. if !result.stopped { let definitions = await Self.execute( - definitionGroups, on: plugin, errorHandling: errorHandling, progress: progress + definitionGroups, on: plugin, errorHandling: errorHandling, committingEach: committingEach, + progress: progress ) result.outcomes += definitions.outcomes result.cancelled = definitions.cancelled @@ -352,6 +356,7 @@ internal struct ObjectCopyRunner { on driver: any PluginDatabaseDriver, pinsSession: Bool, errorHandling: ImportErrorHandling, + committingEach family: TransactionEngineFamily?, progress: ObjectCopyProgress ) async throws -> DDLResult { let writesAnything = !schemaStatements.isEmpty || groups.contains { !$0.statements.isEmpty } @@ -363,9 +368,11 @@ internal struct ObjectCopyRunner { /// table, view or routine can be created if the schema naming it is not there, so /// carrying on would report every one of them as its own failure for one cause. for statement in schemaStatements { - _ = try await driver.execute(query: statement.sql) + try await executeStatement(statement.sql, on: driver, committingEach: family) } - let result = await execute(groups, on: driver, errorHandling: errorHandling, progress: progress) + let result = await execute( + groups, on: driver, errorHandling: errorHandling, committingEach: family, progress: progress + ) await scopes?.close() return result } catch { @@ -374,10 +381,34 @@ internal struct ObjectCopyRunner { } } + // nil inside the phase's own transaction; otherwise a statement the session keeps pending is committed on its own. + nonisolated private static func executeStatement( + _ sql: String, + on driver: any PluginDatabaseDriver, + committingEach family: TransactionEngineFamily? + ) async throws { + guard let family else { + _ = try await driver.execute(query: sql) + return + } + _ = try await AppDefinitionCommit.run(on: driver, family: family, refusesOpenTransaction: false) { + try await driver.execute(query: sql) + } + } + + // A phase that joined a transaction the session already held leaves it to its owner, as its result reports. + nonisolated private static func standaloneFamily( + _ family: TransactionEngineFamily, + owner: WriteTransactionOwner + ) -> TransactionEngineFamily? { + owner == .session ? nil : family + } + nonisolated private static func execute( _ groups: [ObjectCopyStatementGroup], on driver: any PluginDatabaseDriver, errorHandling: ImportErrorHandling, + committingEach family: TransactionEngineFamily?, progress: ObjectCopyProgress ) async -> DDLResult { var result = DDLResult() @@ -391,7 +422,7 @@ internal struct ObjectCopyRunner { let opened = await openSettings(of: group, on: driver) do { for statement in group.statements { - _ = try await driver.execute(query: statement.sql) + try await executeStatement(statement.sql, on: driver, committingEach: family) } if opened { await closeSettings(of: group, on: driver) } result.outcomes.append(ObjectCopyObjectOutcome( @@ -495,13 +526,15 @@ internal struct ObjectCopyRunner { guard !runnable.isEmpty else { return DDLResult() } let errorHandling = request.errorHandling + let family = TransactionEngineFamily.of(request.target.databaseType) return try await manager.withMetadataDriver(scope: request.target.scope) { driver in guard let plugin = CompareMetadataService.pluginDriver(from: driver) else { throw ObjectCopyError.refused(Self.noTargetDriver) } let owner = await Self.transactionOwner(of: driver) var result = await Self.execute( - runnable, on: plugin, errorHandling: errorHandling, progress: progress + runnable, on: plugin, errorHandling: errorHandling, + committingEach: Self.standaloneFamily(family, owner: owner), progress: progress ) result.joinedSessionTransaction = owner == .session return result @@ -619,8 +652,9 @@ internal struct ObjectCopyRunner { result.joinedSessionTransaction = owner == .session // Checks stay on for the clears: a table outside the copy that references a cleared one // keeps its own ON DELETE rule, and MySQL cannot prove no other database holds one. + // In this phase's own transaction or the session's, so a clear never commits on its own. let cleared = await Self.execute( - clearGroups, on: targetPlugin, errorHandling: errorHandling, progress: progress + clearGroups, on: targetPlugin, errorHandling: errorHandling, committingEach: nil, progress: progress ) result.outcomes += cleared.outcomes.filter { $0.error != nil } result.cancelled = cleared.cancelled @@ -805,6 +839,7 @@ internal struct ObjectCopyRunner { let copier = ObjectCopyRowCopier( step: step, sourceDatabaseType: request.source.databaseType, targetDatabaseType: targetType ) + let family = TransactionEngineFamily.of(targetType) /// The injected manager on both sides. Reaching for the singleton on the target bypassed /// the caller's own connections and routing, which is the whole point of injecting one. @@ -816,20 +851,48 @@ internal struct ObjectCopyRunner { throw ObjectCopyError.refused(Self.noTargetDriver) } let owner = await Self.transactionOwner(of: targetDriver) - return try await manager.withMetadataDriver( - scope: sourceScope, workload: .bulk - ) { sourceDriver in - guard let sourcePlugin = CompareMetadataService.pluginDriver(from: sourceDriver) else { - throw ObjectCopyError.refused(Self.noSourceDriver) - } - let readContext = sourceDriver.readOnlyRunContext(safeModeIsReadOnly: sourceIsReadOnly) - let outcome = try await BulkReadTimeout.lifted(on: [sourceDriver]) { - try await copier.copy(from: sourcePlugin, to: targetPlugin, readContext: readContext) { rows in - progress.setRowsForCurrentObject(rows, completedBefore: completedBefore) + let committingEach = Self.standaloneFamily(family, owner: owner) + let copied: CopiedRows + do { + copied = try await manager.withMetadataDriver( + scope: sourceScope, workload: .bulk + ) { sourceDriver in + guard let sourcePlugin = CompareMetadataService.pluginDriver(from: sourceDriver) else { + throw ObjectCopyError.refused(Self.noSourceDriver) } + let readContext = sourceDriver.readOnlyRunContext(safeModeIsReadOnly: sourceIsReadOnly) + let outcome = try await BulkReadTimeout.lifted(on: [sourceDriver]) { + try await copier.copy(from: sourcePlugin, to: targetPlugin, readContext: readContext) { rows in + progress.setRowsForCurrentObject(rows, completedBefore: completedBefore) + } + } + return CopiedRows(outcome: outcome, joinedSessionTransaction: owner == .session) } - return CopiedRows(outcome: outcome, joinedSessionTransaction: owner == .session) + } catch { + // A failed table keeps the rows written before the failure, as it reports them. + do { + try await Self.commitRows(on: targetPlugin, committingEach: committingEach) + } catch let commitError { + Self.logger.error("Committing the rows before a copy failure failed: \(commitError.publicLogShape, privacy: .public)") + } + throw error } + try await Self.commitRows(on: targetPlugin, committingEach: committingEach) + return copied + } + } + + // A commit that fails is rolled back: a pooled connection would otherwise carry the rows into its next lease. + nonisolated private static func commitRows( + on plugin: any PluginDatabaseDriver, + committingEach family: TransactionEngineFamily? + ) async throws { + guard let family else { return } + do { + try await AppDefinitionCommit.commitIfOpen(on: plugin, family: family) + } catch { + _ = try? await TaskCancellationShield.run { try await plugin.rollbackTransaction() } + throw error } } diff --git a/apple/TablePro/Core/Services/Execution/AutocommitOnlyStatement+Teradata.swift b/apple/TablePro/Core/Services/Execution/AutocommitOnlyStatement+Teradata.swift index 680bb09c20..f9f31f294c 100644 --- a/apple/TablePro/Core/Services/Execution/AutocommitOnlyStatement+Teradata.swift +++ b/apple/TablePro/Core/Services/Execution/AutocommitOnlyStatement+Teradata.swift @@ -27,7 +27,26 @@ internal extension AutocommitOnlyStatement { case "DELETE": return following == "DATABASE" || following == "USER" case "SET": - return teradataSessionSettings.contains(following) + guard following == "QUERY_BAND" else { return teradataSessionSettings.contains(following) } + return queryBandScope(&cursor) != "TRANSACTION" + default: + return false + } + } + + // DATABASE, SET SESSION DATABASE and its SS abbreviation move the session's default database. + static func movesDatabase(_ statement: String, family: TransactionEngineFamily, grammar: SQLLexicalGrammar) -> Bool { + guard family == .teradata else { return false } + var cursor = SQLTokenCursor(statement as NSString, grammar: grammar) + guard let keyword = cursor.next()?.word else { return false } + switch keyword { + case "DATABASE": + return true + case "SET": + guard cursor.next()?.word == "SESSION" else { return false } + return cursor.next()?.word == "DATABASE" + case "SS": + return cursor.next()?.word == "DATABASE" default: return false } @@ -45,5 +64,15 @@ private extension AutocommitOnlyStatement { static let teradataStatisticsWords: Set = ["STATISTICS", "STATS", "STAT", "SUMMARY"] - static let teradataSessionSettings: Set = ["SESSION", "ROLE", "QUERY_BAND", "TIME", "TRANSFORM"] + static let teradataSessionSettings: Set = ["SESSION", "ROLE", "TIME", "TRANSFORM"] + + // SET QUERY_BAND ... FOR TRANSACTION is DML and FOR SESSION is DDL, and the FOR clause follows the band. + static func queryBandScope(_ cursor: inout SQLTokenCursor) -> String? { + var scope: String? + while let token = cursor.next() { + guard token.word == "FOR", cursor.parenDepth == 0 else { continue } + scope = cursor.next()?.word + } + return scope + } } diff --git a/apple/TablePro/Core/Services/Execution/BatchCommitStatement.swift b/apple/TablePro/Core/Services/Execution/BatchCommitStatement.swift index 5eec82effb..22f4f1dd9e 100644 --- a/apple/TablePro/Core/Services/Execution/BatchCommitStatement.swift +++ b/apple/TablePro/Core/Services/Execution/BatchCommitStatement.swift @@ -35,6 +35,9 @@ internal enum BatchCommitStatement { case "END": guard let follower = cursor.next()?.word else { return true } return transactionNouns.contains(follower) + // Teradata's abbreviation of END TRANSACTION. + case "ET": + return cursor.next() == nil default: return false } diff --git a/apple/TablePro/Core/Services/Execution/BatchStatementRun.swift b/apple/TablePro/Core/Services/Execution/BatchStatementRun.swift index fb6aca5752..186f91a400 100644 --- a/apple/TablePro/Core/Services/Execution/BatchStatementRun.swift +++ b/apple/TablePro/Core/Services/Execution/BatchStatementRun.swift @@ -75,6 +75,9 @@ internal enum BatchStatementRun { gate: BatchClaimGate, failureSQL: (Statement) -> String, isCommitPoint: (Statement) -> Bool, + endsItsTransaction: (Statement) -> Bool = { _ in false }, + closesTransaction: (Statement) -> Bool = { _ in false }, + movesDatabase: (Statement) -> Bool = { _ in false }, serverError: (Output) -> String? = { _ in nil }, replanned: @escaping @MainActor @Sendable (_ ranCount: Int) async -> [Statement]? = { _ in nil }, commitOutput: ServerOutputBox = ServerOutputBox(), @@ -93,13 +96,23 @@ internal enum BatchStatementRun { var results: [Output] = [] var queue = statements var position = 0 + var databaseMove: String? while position < queue.count { let statement = queue[position] guard !Task.isCancelled, gate.isCurrent() else { await rollback(driver: driver, connectionId: connectionId, plan: plan, sentBegin: sentBegin) return .cancelled(results: plan.keepsExecutedStatements ? results : []) } - let ran = await runStatement( + let moves = movesDatabase(statement) + // `.unknown` also stands for a statement nobody asked about. + let heldBefore: PluginSessionTransactionState = moves ? await driver.heldSessionTransactionState() : .unknown + // A new run is pinned back to the tab's database, so the rest of this one would land in the wrong one. + if heldBefore.holdsUserTransaction { + return .failed( + results: results, failure: .databaseMoveAwaitsCommit(sql: failureSQL(statement)), errorDescription: "" + ) + } + var ran = await runStatement( statement, isCommitPoint: isCommitPoint(statement), driver: driver, @@ -107,6 +120,12 @@ internal enum BatchStatementRun { gate: gate, execute: execute ) + // An ANSI session holds the move in a transaction of its own, which the app's own switch commits the same way. + if heldBefore == .idle, case .committed(let result) = ran, + await driver.heldSessionTransactionState() == .inTransaction { + ran = await committingMove(result, driver: driver, connectionId: connectionId, gate: gate) + } + if moves, case .committed = ran { databaseMove = failureSQL(statement) } switch ran { case .stopped: await rollback(driver: driver, connectionId: connectionId, plan: plan, sentBegin: sentBegin) @@ -139,6 +158,15 @@ internal enum BatchStatementRun { if position < queue.count, let rest = await replanned(position) { queue = Array(queue.prefix(position)) + rest } + // The next statement would be refused, inside BT with the whole block rolled back, so the user commits first. + if position < queue.count, !Task.isCancelled, gate.isCurrent(), endsItsTransaction(statement), + !closesTransaction(queue[position]), await driver.heldSessionTransactionState() == .inTransaction { + return .failed( + results: results, + failure: .awaitsCommit(sql: failureSQL(statement), databaseMove: databaseMove), + errorDescription: "" + ) + } } guard plan.commitsAtEnd, sentBegin else { return .completed(results: results) } @@ -178,6 +206,29 @@ internal enum BatchStatementRun { ) { @Sendable in try await execute(statement) } } + // Protected like a script's own COMMIT, and the run carries on after it. + private static func committingMove( + _ result: Output, + driver: DatabaseDriver, + connectionId: UUID, + gate: BatchClaimGate + ) async -> BatchCommitOutcome { + let committed = await BatchCommitPoint.run( + driver: driver, + connectionId: connectionId, + gate: gate, + exit: .resumes + ) { @Sendable in try await driver.commitTransaction() } + switch committed { + case .stopped: + return .stopped + case .committed: + return .committed(result) + case .failed(let failure): + return .failed(failure) + } + } + /// The app's own commit, and the last thing the run does. The mark it takes is held until the /// claim settles rather than released here: between the server's answer and the settle there is /// no statement left to stop, and a Stop landing in that gap would drop the results of work the 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/MultiStatementFailure.swift b/apple/TablePro/Core/Services/Execution/MultiStatementFailure.swift index 6356e80926..9aa97a005d 100644 --- a/apple/TablePro/Core/Services/Execution/MultiStatementFailure.swift +++ b/apple/TablePro/Core/Services/Execution/MultiStatementFailure.swift @@ -19,6 +19,10 @@ internal enum MultiStatementFailure: Equatable, Sendable { /// and committed its row once the lock was released. Nothing here can say whether the /// transaction took, so nothing here may report a rollback. case commitOutcomeUnknown + // Stopped after `sql`, which takes nothing after it but the transaction's end; `databaseMove` is an earlier move that ran. + case awaitsCommit(sql: String, databaseMove: String? = nil) + // Stopped before `sql`, a database move, because the session holds a transaction the move cannot join. + case databaseMoveAwaitsCommit(sql: String) func ranStatementCount(executedCount: Int, totalCount: Int) -> Int { switch self { @@ -26,7 +30,7 @@ internal enum MultiStatementFailure: Equatable, Sendable { return 0 case .statement: return min(executedCount + 1, totalCount) - case .batch, .commit, .commitOutcomeUnknown: + case .batch, .commit, .commitOutcomeUnknown, .awaitsCommit, .databaseMoveAwaitsCommit: return executedCount } } @@ -80,9 +84,102 @@ internal struct MultiStatementFailureContext: Equatable, Sendable { ) case .commitOutcomeUnknown: return unknownCommitReport() + case .awaitsCommit(_, let databaseMove): + return awaitsCommitReport(databaseMove: databaseMove) + case .databaseMoveAwaitsCommit: + return databaseMoveReport() } } + // The bar's Commit, as a typed COMMIT is refused after a DATABASE; a move is redone, as a new run is pinned to the tab's database. + private func awaitsCommitReport(databaseMove: String?) -> MultiStatementFailureReport { + let next = executedCount + 1 + let message: String + if plan == .scriptTransaction { + // The rest has to open its own BT again, or the script's ET ends a block the app opened for it. + let opening = databaseMove.map { "\(Self.statementText($0)); BT" } ?? "BT" + message = String( + format: String( + localized: """ + Statement %1$d/%2$d is a DDL statement, and the session takes nothing after it but COMMIT \ + or ROLLBACK. The run stopped before statement %3$d. Click Commit on the Transaction Open \ + bar, then begin the rest with “%4$@”. + """ + ), + executedCount, totalCount, next, opening + ) + } else if let databaseMove { + message = String( + format: String( + localized: """ + Statement %1$d/%2$d is a DDL statement, and the session takes nothing after it but COMMIT \ + or ROLLBACK. The run stopped before statement %3$d. Click Commit on the Transaction Open \ + bar. A new run starts in the tab's database, so begin the rest with “%4$@”. + """ + ), + executedCount, totalCount, next, Self.statementText(databaseMove) + ) + } else { + message = String( + format: String( + localized: """ + Statement %1$d/%2$d is a DDL statement, and the session takes nothing after it but COMMIT \ + or ROLLBACK. The run stopped before statement %3$d. Click Commit on the Transaction Open \ + bar, then run the rest. + """ + ), + executedCount, totalCount, next + ) + } + return MultiStatementFailureReport( + message: message, + resultLabel: String(localized: "Stopped"), + failedStatementIndex: next <= totalCount ? executedCount : nil, + failedSQL: nil + ) + } + + // Run again from the move itself: a new run is pinned to the tab's database until the move runs. + private func databaseMoveReport() -> MultiStatementFailureReport { + let position = executedCount + 1 + let message: String + if plan == .scriptTransaction { + // A rerun from the move would leave the script's BT behind, and what ran before the BT is already committed. + message = String( + format: String( + localized: """ + Statement %1$d/%2$d moves the session to another database, which this session takes only \ + outside a transaction. The run stopped before it. Click Roll Back on the Transaction Open \ + bar, move the statement above the script's BT, then run the script again from there. + """ + ), + position, totalCount + ) + } else { + message = String( + format: String( + localized: """ + Statement %1$d/%2$d moves the session to another database, which this session takes only \ + outside a transaction. The run stopped before it. Click Commit or Roll Back on the \ + Transaction Open bar, then run the script again from statement %1$d. + """ + ), + position, totalCount + ) + } + return MultiStatementFailureReport( + message: message, + resultLabel: String(localized: "Stopped"), + failedStatementIndex: position <= totalCount ? executedCount : nil, + failedSQL: nil + ) + } + + private static func statementText(_ sql: String) -> String { + let trimmed = sql.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.hasSuffix(";") ? String(trimmed.dropLast()) : trimmed + } + /// Worded without a rollback in it. The app sent the commit, the connection went before the /// answer, and the server decides on its own: the same kill that rolled a commit back under a /// read lock was ignored by a commit waiting on `binlog_group_commit_sync_delay`, which then diff --git a/apple/TablePro/Core/Services/Execution/TransactionEndStatement.swift b/apple/TablePro/Core/Services/Execution/TransactionEndStatement.swift new file mode 100644 index 0000000000..d7797aca30 --- /dev/null +++ b/apple/TablePro/Core/Services/Execution/TransactionEndStatement.swift @@ -0,0 +1,25 @@ +// +// TransactionEndStatement.swift +// TablePro +// + +import Foundation +import TableProSQLGrammar +import TableProUtilities + +// A statement that ends the session's transaction, by commit or by rollback: all Teradata takes after DDL. +internal enum TransactionEndStatement { + private static let rollbackWords: Set = ["ROLLBACK", "ABORT"] + + internal static func matches(_ statement: NSString, grammar: SQLLexicalGrammar) -> Bool { + if BatchCommitStatement.matches(statement, grammar: grammar) { return true } + var cursor = SQLTokenCursor(statement, grammar: grammar) + guard let keyword = cursor.next()?.word, rollbackWords.contains(keyword) else { return false } + // ROLLBACK TO SAVEPOINT keeps the transaction open. + return cursor.next()?.word != "TO" + } + + internal static func matches(_ statement: String, grammar: SQLLexicalGrammar) -> Bool { + matches(statement as NSString, grammar: grammar) + } +} diff --git a/apple/TablePro/Core/Services/Execution/TransactionEngineFamily.swift b/apple/TablePro/Core/Services/Execution/TransactionEngineFamily.swift index 77fc766a05..fad3821187 100644 --- a/apple/TablePro/Core/Services/Execution/TransactionEngineFamily.swift +++ b/apple/TablePro/Core/Services/Execution/TransactionEngineFamily.swift @@ -77,6 +77,18 @@ internal enum TransactionEngineFamily: String, Hashable, Sendable, CaseIterable } } + // Teradata holds a definition statement in a transaction in an ANSI session, and inside one takes nothing after + // it but COMMIT or ROLLBACK: Error 3722 in ANSI mode, Failure 3932 inside BT, which rolls the whole block back. + internal var definitionEndsTransaction: Bool { + self == .teradata + } + + // A Teradata ANSI session opens a transaction with any request and ends it only with COMMIT or ROLLBACK, so work + // the app runs without a BEGIN of its own is still pending, and a pooled connection's logoff rolls it back. + internal var unwrappedWorkStaysOpen: Bool { + self == .teradata + } + // Redshift and DuckDB have no savepoint to take a failed statement back to. internal var takesBackAFailedStatement: Bool { self == .postgres || self == .cockroach diff --git a/apple/TablePro/Core/Services/Export/RowImportTableMaker.swift b/apple/TablePro/Core/Services/Export/RowImportTableMaker.swift index 3e8c0b0efb..795793dde5 100644 --- a/apple/TablePro/Core/Services/Export/RowImportTableMaker.swift +++ b/apple/TablePro/Core/Services/Export/RowImportTableMaker.swift @@ -81,17 +81,16 @@ internal struct RowImportTableMaker { ) } } - for step in steps { - switch step { - case .create(let table, let statements, let sql): - for statement in statements { - try await runOnLeasedDriver(statement, scope: scope, table: table, clearing: false, run: importRun) - createdAny = true - } - onCreated(table, sql) - case .clear(let table, let sql): - try await runOnLeasedDriver(sql, scope: scope, table: table, clearing: true, run: importRun) + // Every create before any clear: on Teradata ANSI a clear leaves its DELETE pending, which refuses a later create. + for case .create(let table, let statements, let sql) in steps { + for statement in statements { + try await runOnLeasedDriver(statement, scope: scope, table: table, clearing: false, run: importRun) + createdAny = true } + onCreated(table, sql) + } + for case .clear(let table, let sql) in steps { + try await runOnLeasedDriver(sql, scope: scope, table: table, clearing: true, run: importRun) } return receipt } @@ -173,19 +172,37 @@ internal struct RowImportTableMaker { if let run { _ = try await run.admit(.data) } defer { run?.release() } let route = DatabaseManager.shared.executionRoute(for: scope) + let refusesOpenTransaction = !route.isPooled try await DatabaseManager.shared.withScopedDriver( scope: scope, route: route, cancellation: .protectedWrite ) { driver in if let run { - try await Self.executePreparation(sql, table: table, clearing: clearing, driver: driver, run: run) + try await Self.executePreparation( + sql, table: table, clearing: clearing, refusesOpenTransaction: refusesOpenTransaction, + driver: driver, run: run + ) } else { - _ = try await driver.execute(query: sql) + try await Self.executeStep(sql, clearing: clearing, refusesOpenTransaction: refusesOpenTransaction, on: driver) } } } + // A clear belongs to the import's own transaction; only a table this makes is committed on its own. + nonisolated private static func executeStep( + _ sql: String, clearing: Bool, refusesOpenTransaction: Bool, on driver: DatabaseDriver + ) async throws { + guard !clearing else { + _ = try await driver.execute(query: sql) + return + } + _ = try await AppDefinitionCommit.run(on: driver, refusesOpenTransaction: refusesOpenTransaction) { + try await driver.execute(query: sql) + } + } + nonisolated private static func executePreparation( - _ sql: String, table: TableScope, clearing: Bool, driver: DatabaseDriver, run: ImportRun + _ sql: String, table: TableScope, clearing: Bool, refusesOpenTransaction: Bool, driver: DatabaseDriver, + run: ImportRun ) async throws { let id = UUID() let rollback: ImportTableRollback @@ -208,7 +225,7 @@ internal struct RowImportTableMaker { $0.preparations[id] = ImportPreparationEffect(table: table, clearing: clearing) } do { - _ = try await driver.execute(query: sql) + try await executeStep(sql, clearing: clearing, refusesOpenTransaction: refusesOpenTransaction, on: driver) let state = driver.supportsTransactions ? ImportSessionState(await driver.heldSessionTransactionState()) : .idle run.record { diff --git a/apple/TablePro/Core/Services/Infrastructure/ConnectionCloseAction.swift b/apple/TablePro/Core/Services/Infrastructure/ConnectionCloseAction.swift index f14c1cfce1..5cc66ab9fc 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ConnectionCloseAction.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ConnectionCloseAction.swift @@ -9,10 +9,12 @@ import Foundation // Disconnect keeps the connection to reconnect, an entry close takes one container, this ends the connection and every entry. @MainActor internal enum ConnectionCloseAction { + // Asked in this order. The transaction comes last and is read then: a Save under Manual Commit lands in a held one. internal enum Decision: Equatable { case closeImmediately - case confirmEndingTransaction + case confirmRunningWork case confirmUnsavedWork + case confirmEndingTransaction } // Every window hosting the connection, every tab in each: saving only the selected tab closed over the rest. @@ -34,112 +36,84 @@ internal enum ConnectionCloseAction { return MainContentCommandActions.unsavedWorkMessage(keepsTabsOpen: keepsTabsOpen) } - // The transaction is asked before unsaved work, whose Save writes at once. - internal static func decision(hasSession: Bool, holdsTransaction: Bool, hasUnsavedWork: Bool) -> Decision { - guard hasSession else { return .closeImmediately } - if holdsTransaction { return .confirmEndingTransaction } - return hasUnsavedWork ? .confirmUnsavedWork : .closeImmediately - } - - internal static func transactionMessage(for databases: [String]) -> String? { - guard let first = databases.first else { return nil } - guard databases.count > 1 else { - return String( - format: String(localized: "The database “%@” has an open transaction. Closing rolls it back and discards its uncommitted changes."), - first - ) - } - return String( - format: String(localized: "These databases have open transactions: %@. Closing rolls them back and discards their uncommitted changes."), - ListFormatter.localizedString(byJoining: databases.map { "“\($0)”" }) - ) + // The Save alert names the running work, so the two never ask separately. + internal static func decision(hasSession: Bool, hasRunningWork: Bool, hasUnsavedWork: Bool) -> Decision { + if hasSession, hasUnsavedWork { return .confirmUnsavedWork } + if hasRunningWork { return .confirmRunningWork } + return hasSession ? .confirmEndingTransaction : .closeImmediately } internal static func close(connectionId: UUID, registry: RunningWorkRegistry = .shared) async { // Every window hosting the connection: a torn-off tab keeps its edits in its own coordinator. let coordinators = WindowManager.shared.coordinators(for: connectionId) let coordinator = coordinators.first ?? WindowManager.shared.coordinator(for: connectionId) + let hasSession = coordinator != nil // Read at each decision: the window stays editable while the alerts are awaited. let hasUnsavedWork = { coordinators.contains { $0.hasAnyUnsavedWork() } || (coordinators.isEmpty && coordinator?.hasAnyUnsavedWork() == true) } - let holding = await DatabaseManager.shared.databasesHoldingTransaction(for: connectionId) - var decision = decision( - hasSession: coordinator != nil, - holdsTransaction: !holding.isEmpty, - hasUnsavedWork: hasUnsavedWork() - ) // Shown, then asked; a close that closes nothing puts the user back where they were. let wasShowing = WindowManager.shared.shownConnection(besides: connectionId) + func restore() { + WindowManager.shared.show(wasShowing, inWindowHosting: connectionId) + } let work = registry.items(in: .connection(connectionId)) - var hasAnsweredForWork = false - // With nothing unsaved, one alert names the work and any open transaction. - if !work.isEmpty, !hasUnsavedWork(), let prompt = RunningWorkPrompt.make( - action: .close, - work: work, - otherLosses: RunningWorkPrompt.transactionLines(for: holding) - ) { - guard await RunningWorkApproval.confirm(prompt, window: reveal(connectionId: connectionId)) else { - WindowManager.shared.show(wasShowing, inWindowHosting: connectionId) - return + var namedWork = false + var decision = decision(hasSession: hasSession, hasRunningWork: !work.isEmpty, hasUnsavedWork: hasUnsavedWork()) + + if decision == .confirmRunningWork { + if let prompt = RunningWorkPrompt.make(action: .close, work: work) { + guard await RunningWorkApproval.confirm(prompt, window: reveal(connectionId: connectionId)) else { + restore() + return + } } - hasAnsweredForWork = true - // Another window on the connection stayed editable while the alert was up. - decision = Self.decision(hasSession: coordinator != nil, holdsTransaction: false, hasUnsavedWork: hasUnsavedWork()) + namedWork = true + decision = Self.decision(hasSession: hasSession, hasRunningWork: false, hasUnsavedWork: hasUnsavedWork()) } - if decision == .confirmEndingTransaction, let coordinator, let message = transactionMessage(for: holding) { - let confirmed = await AlertHelper.confirmDestructive( - title: String(format: String(localized: "Close the connection “%@”?"), coordinator.connection.name), - message: message, - confirmButton: String(localized: "Close"), + + if decision == .confirmUnsavedWork { + let targets = coordinators.isEmpty ? [coordinator].compactMap { $0 } : coordinators + switch await AlertHelper.confirmSaveChanges( + message: RunningWorkPrompt.saveMessage( + unsavedWorkMessage(across: targets), + action: .close, + alsoStopping: namedWork ? [] : work + ), window: reveal(connectionId: connectionId) - ) - guard confirmed else { - WindowManager.shared.show(wasShowing, inWindowHosting: connectionId) - return - } - decision = Self.decision(hasSession: true, holdsTransaction: false, hasUnsavedWork: hasUnsavedWork()) - } - guard decision == .confirmUnsavedWork else { - // The edits were saved meanwhile, so the work still needs its own answer. - if !hasAnsweredForWork, let prompt = RunningWorkPrompt.make(action: .close, work: work) { - guard await RunningWorkApproval.confirm(prompt, window: reveal(connectionId: connectionId)) else { - WindowManager.shared.show(wasShowing, inWindowHosting: connectionId) + ) { + case .save: + guard await saveEveryWindowsWork(across: coordinators, fallback: coordinator) else { + restore() return } + case .dontSave: + break + case .cancel: + restore() + return } - registry.cancel(work) - WindowManager.shared.closeWindow(for: connectionId) - return + decision = .confirmEndingTransaction } - // Work is stopped only once the close is certain: a cancelled or failed save keeps it running. - let presentingWindow = reveal(connectionId: connectionId) - let targets = coordinators.isEmpty ? [coordinator].compactMap { $0 } : coordinators - switch await AlertHelper.confirmSaveChanges( - message: RunningWorkPrompt.saveMessage( - unsavedWorkMessage(across: targets), - action: .close, - alsoStopping: hasAnsweredForWork ? [] : work - ), - window: presentingWindow - ) { - case .save: - // Save closes too, once the save has landed. - guard await saveEveryWindowsWork(across: coordinators, fallback: coordinator) else { - WindowManager.shared.show(wasShowing, inWindowHosting: connectionId) - break + if decision == .confirmEndingTransaction { + let name = coordinator?.connection.name ?? DatabaseManager.shared.session(for: connectionId)?.connection.name ?? "" + let outcome = await TransactionEndingFlow.resolve( + connectionId: connectionId, + action: .closeConnection(name: name), + window: { reveal(connectionId: connectionId) } + ) + guard outcome != .cancelled else { + restore() + return } - registry.cancel(work) - WindowManager.shared.closeWindow(for: connectionId) - case .dontSave: - registry.cancel(work) - WindowManager.shared.closeWindow(for: connectionId) - case .cancel: - WindowManager.shared.show(wasShowing, inWindowHosting: connectionId) } + + // Stopped only once the close is certain: a Cancel, a failed save or a failed commit keeps the work running. + registry.cancel(work) + WindowManager.shared.closeWindow(for: connectionId) } // The answer can name a connection never on screen, so it is brought forward first. diff --git a/apple/TablePro/Core/Services/Infrastructure/ConnectionDisconnectAction.swift b/apple/TablePro/Core/Services/Infrastructure/ConnectionDisconnectAction.swift index 138049f5ea..caf8207e37 100644 --- a/apple/TablePro/Core/Services/Infrastructure/ConnectionDisconnectAction.swift +++ b/apple/TablePro/Core/Services/Infrastructure/ConnectionDisconnectAction.swift @@ -15,55 +15,50 @@ internal enum ConnectionDisconnectAction { presentingWindow: NSWindow?, registry: RunningWorkRegistry = .shared ) async { - let holding = await DatabaseManager.shared.databasesHoldingTransaction(for: connectionId) let hasUnsavedWork = MainContentCoordinator.hasUnsavedWork(forConnection: connectionId) let work = registry.items(in: .connection(connectionId)) + var namedUnsavedWork = false if let prompt = RunningWorkPrompt.make( action: .disconnect, work: work, - otherLosses: otherLosses(holdingTransaction: holding, hasUnsavedWork: hasUnsavedWork) + otherLosses: otherLosses(hasUnsavedWork: hasUnsavedWork) ) { guard await RunningWorkApproval.confirm(prompt, window: presentingWindow) else { return } - registry.cancel(work) - } else if let message = confirmationMessage(holdingTransaction: holding, hasUnsavedWork: hasUnsavedWork) { - let confirmed = await AlertHelper.confirmDestructive( - title: String(format: String(localized: "Disconnect from “%@”?"), connectionName), - message: message, - confirmButton: String(localized: "Disconnect"), - window: presentingWindow - ) - guard confirmed else { return } + namedUnsavedWork = hasUnsavedWork } + switch await TransactionEndingFlow.resolve( + connectionId: connectionId, + action: .disconnect(name: connectionName), + hasUnsavedWork: hasUnsavedWork && !namedUnsavedWork, + window: { presentingWindow } + ) { + case .cancelled: + return + case .ended: + break + case .nothingOpen: + let unsaved = MainContentCoordinator.hasUnsavedWork(forConnection: connectionId) + if !namedUnsavedWork, let message = confirmationMessage(hasUnsavedWork: unsaved) { + let confirmed = await AlertHelper.confirmDestructive( + title: String(format: String(localized: "Disconnect from “%@”?"), connectionName), + message: message, + confirmButton: String(localized: "Disconnect"), + window: presentingWindow + ) + guard confirmed else { return } + } + } + // Stopped only once every answer is in and any commit landed. + registry.cancel(work) await DatabaseManager.shared.disconnectSession(connectionId, origin: .userRequested) } // Nil means disconnect without asking: ending a session the user asked to end loses nothing. - internal static func confirmationMessage(holdingTransaction holding: [String], hasUnsavedWork: Bool) -> String? { - if let message = transactionMessage(for: holding) { - return message - } - return hasUnsavedWork ? String(localized: "Unsaved changes will be lost.") : nil + internal static func confirmationMessage(hasUnsavedWork: Bool) -> String? { + hasUnsavedWork ? String(localized: "Unsaved changes will be lost.") : nil } - internal static func otherLosses(holdingTransaction holding: [String], hasUnsavedWork: Bool) -> [String] { - var losses = RunningWorkPrompt.transactionLines(for: holding) - if hasUnsavedWork { - losses.append(String(localized: "Unsaved changes")) - } - return losses - } - - internal static func transactionMessage(for databases: [String]) -> String? { - guard let first = databases.first else { return nil } - guard databases.count > 1 else { - return String( - format: String(localized: "The database “%@” has an open transaction. Disconnecting rolls it back and discards its uncommitted changes."), - first - ) - } - return String( - format: String(localized: "These databases have open transactions: %@. Disconnecting rolls them back and discards their uncommitted changes."), - ListFormatter.localizedString(byJoining: databases.map { "“\($0)”" }) - ) + internal static func otherLosses(hasUnsavedWork: Bool) -> [String] { + hasUnsavedWork ? [String(localized: "Unsaved changes")] : [] } } diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift index a67a39c49b..5842ab53a5 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift @@ -78,7 +78,10 @@ internal final class LaunchIntentRouter { isIdleMachineSession: { AppActivationPolicyController.shared.isIdleMachineSession } ) guard quits else { return } - NSApp.terminate(nil) + // A terminate from inside a main-actor job never lets the quit's reply task run. + RunLoop.main.perform { + MainActor.assumeIsolated { NSApp.terminate(nil) } + } } // A launch made only to serve MCP has nothing left to do once the server is refused or fails to start. diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+DatabaseMenuActions.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+DatabaseMenuActions.swift index 0a425d1a55..3992905063 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+DatabaseMenuActions.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+DatabaseMenuActions.swift @@ -176,7 +176,7 @@ extension MainSplitViewController { isManualCommitOn: DatabaseManager.shared.commitMode(for: coordinator.connectionId) == .manual, canHoldTransactions: reportsState, holdsTransaction: hold != nil, - canCommit: hold.map { ConnectionTransactionActions.offersCommit($0, safeModeLevel: session.safeModeLevel) } ?? false + canCommit: hold.map { ConnectionTransactionActions.offersCommit($0) } ?? false ) } diff --git a/apple/TablePro/Core/Services/Infrastructure/QuitApproval.swift b/apple/TablePro/Core/Services/Infrastructure/QuitApproval.swift index 9750866d0c..9e4ed6c691 100644 --- a/apple/TablePro/Core/Services/Infrastructure/QuitApproval.swift +++ b/apple/TablePro/Core/Services/Infrastructure/QuitApproval.swift @@ -1,47 +1,75 @@ import AppKit +// What an approved quit or relaunch does before it goes ahead. +internal struct QuitPlan { + // Empty when nothing holds a transaction or the answer was Roll Back. + internal let commits: [SessionTransactionTracker.Hold] + // Stopped only once the commits landed, so a failed commit leaves it running. + internal let work: [RunningWork] +} + // The termination notification comes after AppKit is told yes, too late to cancel a quit. @MainActor internal enum QuitApproval { internal static func approve( registry: RunningWorkRegistry = .shared, relaunchApproved: Bool = AppRelauncher.shared.hasApprovedRunningWork - ) -> Bool { - // A relaunch asked both questions before it quit; the work it approved stopping stops now. + ) -> QuitPlan? { + // A relaunch asked every question and committed before it quit; the work it approved stopping stops now. guard !relaunchApproved else { - registry.cancel(registry.items(in: .app)) - return true + return QuitPlan(commits: [], work: registry.items(in: .app)) } - // The theme editor can still cancel, so it asks before any work is stopped. - guard ThemeEditorWindows.shared.prepareToTerminate() else { return false } + // The theme editor can still cancel, so it asks before anything else. + guard ThemeEditorWindows.shared.prepareToTerminate() else { return nil } return approvesStoppingWork(registry: registry, action: .quit) } - // One alert for what a quit or relaunch loses. Running work lists the unsaved tabs with it. + // Running work, then the open transactions, then unsaved tabs when no alert named them. Nil when any answer was Cancel. internal static func approvesStoppingWork( registry: RunningWorkRegistry, action: RunningWorkAction, - stopsWork: Bool = true - ) -> Bool { + databaseManager: DatabaseManager = .shared, + hasUnsavedTabs: @MainActor () -> Bool = { MainContentCoordinator.hasAnyUnsavedChanges() }, + confirmWork: @MainActor (RunningWorkPrompt) -> Bool = RunningWorkApproval.confirmModally, + answerTransaction: @MainActor (TransactionEndPrompt) -> AlertHelper.TransactionEndAnswer + = QuitApproval.answerTransactionModally, + confirmDiscardingTabs: @MainActor (RunningWorkAction) -> Bool = QuitApproval.approvesDiscardingUnsavedTabs + ) -> QuitPlan? { // A large document's last keys reach its tab on a delay; without them a dirty file reads as clean. EditorEventRouter.shared.flushAllPendingText() let work = registry.items(in: .app) - let hasUnsavedTabs = MainContentCoordinator.hasAnyUnsavedChanges() - let transactions = openTransactionNames( - holds: Array(DatabaseManager.shared.sessionTransactions.holds.values), - connectionName: { DatabaseManager.shared.session(for: $0)?.connection.name } - ) - let losses = (hasUnsavedTabs ? [String(localized: "Unsaved edits in open tabs")] : []) - + RunningWorkPrompt.transactionLines(for: transactions) - if let prompt = RunningWorkPrompt.make(action: action, work: work, otherLosses: losses) { - guard RunningWorkApproval.confirmModally(prompt) else { return false } - if stopsWork { registry.cancel(work) } - return true + let unsavedTabs = hasUnsavedTabs() + var namedUnsavedTabs = false + if let prompt = RunningWorkPrompt.make( + action: action, + work: work, + otherLosses: unsavedTabs ? [String(localized: "Unsaved edits in open tabs")] : [] + ) { + guard confirmWork(prompt) else { return nil } + namedUnsavedTabs = unsavedTabs } - if let prompt = transactionPrompt(action: action, connections: transactions, hasUnsavedTabs: hasUnsavedTabs) { - return RunningWorkApproval.confirmModally(prompt) + let holds = databaseManager.sessionTransactions.holds.values.sorted { lhs, rhs in + (lhs.connectionId.uuidString, lhs.key.lane ?? "") < (rhs.connectionId.uuidString, rhs.key.lane ?? "") } - return !hasUnsavedTabs || approvesDiscardingUnsavedTabs() + var commits: [SessionTransactionTracker.Hold] = [] + if let prompt = transactionPrompt( + action: action, + holds: holds, + hasUnsavedTabs: unsavedTabs && !namedUnsavedTabs, + databaseManager: databaseManager + ) { + switch answerTransaction(prompt) { + case .cancel: + return nil + case .rollBack: + break + case .commit: + commits = holds + } + namedUnsavedTabs = unsavedTabs + } + guard !unsavedTabs || namedUnsavedTabs || confirmDiscardingTabs(action) else { return nil } + return QuitPlan(commits: commits, work: work) } // The server rolls back what a quit leaves open, so a hold is asked about like unsaved work. @@ -57,39 +85,81 @@ internal enum QuitApproval { return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending } } + // Tracker holds only, so every connection the prompt names has holds to commit through. internal static func transactionPrompt( action: RunningWorkAction, - connections: [String], - hasUnsavedTabs: Bool - ) -> RunningWorkPrompt? { - guard let first = connections.first else { return nil } - let rolledBack = connections.count == 1 - ? String(format: String(localized: "Uncommitted changes on “%@” are rolled back when TablePro quits."), first) - : String( - format: String(localized: "Uncommitted changes on %@ are rolled back when TablePro quits."), - ListFormatter.localizedString(byJoining: connections.map { "“\($0)”" }) - ) - let unsaved = String(localized: "Some tabs have unsaved edits. Quitting will discard these changes.") - let relaunches = action == .relaunch - return RunningWorkPrompt( - title: relaunches - ? String(localized: "Relaunch with an Open Transaction?") - : String(localized: "Quit with an Open Transaction?"), - message: hasUnsavedTabs ? "\(rolledBack)\n\n\(unsaved)" : rolledBack, - confirmButton: relaunches ? String(localized: "Relaunch Anyway") : String(localized: "Quit Anyway") + holds: [SessionTransactionTracker.Hold], + hasUnsavedTabs: Bool, + databaseManager: DatabaseManager = .shared + ) -> TransactionEndPrompt? { + TransactionEndPrompt.make( + action: action == .relaunch ? .relaunch : .quit, + names: openTransactionNames( + holds: holds, + connectionName: { databaseManager.session(for: $0)?.connection.name } + ), + holds: holds, + savedUnderManualCommit: holds.contains { databaseManager.commitMode(for: $0.connectionId) == .manual }, + hasUnsavedWork: hasUnsavedTabs, + effectiveLevel: { ExecutionGateProvider.effectiveSafeModeLevel(for: $0, in: databaseManager) }, + busy: { databaseManager.isLaneBusy(holding: $0) } ) } - private static func approvesDiscardingUnsavedTabs() -> Bool { + // Runs before anything a quit cannot take back. False keeps the app open: the gate was cancelled, the commit + // failed, or a transaction is still open after it (a nested one, or one opened since the answer). + internal static func commitBeforeQuitting( + _ plan: QuitPlan, + databaseManager: DatabaseManager = .shared, + commit: @MainActor ([SessionTransactionTracker.Hold]) async throws -> Bool + = { try await ConnectionTransactionActions.commitBeforeEnding($0) }, + reportFailure: @MainActor (String) -> Void = { TransactionEndingFlow.showCommitFailure($0, window: nil) } + ) async -> Bool { + guard !plan.commits.isEmpty else { return true } + do { + guard try await commit(plan.commits) else { return false } + } catch is CancellationError { + return false + } catch { + reportFailure(error.localizedDescription) + return false + } + let open = Array(databaseManager.sessionTransactions.holds.values) + guard open.isEmpty else { + let names = openTransactionNames( + holds: open, + connectionName: { databaseManager.session(for: $0)?.connection.name } + ) + reportFailure(String( + format: String(localized: "A transaction is still open on %@."), + ListFormatter.localizedString(byJoining: names.map { "“\($0)”" }) + )) + return false + } + return true + } + + private static func answerTransactionModally(_ prompt: TransactionEndPrompt) -> AlertHelper.TransactionEndAnswer { // A quit can come from outside the app, and a background process has no Dock icon to reach the alert by. AppActivationPolicyController.shared.activate(ignoringOtherApps: true) + return AlertHelper.answerTransactionEndModally(prompt) + } + + internal static func approvesDiscardingUnsavedTabs(_ action: RunningWorkAction) -> Bool { + // A quit can come from outside the app, and a background process has no Dock icon to reach the alert by. + AppActivationPolicyController.shared.activate(ignoringOtherApps: true) + let relaunches = action == .relaunch let alert = NSAlert() alert.messageText = String(localized: "You have unsaved changes") - alert.informativeText = String(localized: "Some tabs have unsaved edits. Quitting will discard these changes.") + alert.informativeText = relaunches + ? String(localized: "Some tabs have unsaved edits. Relaunching will discard these changes.") + : String(localized: "Some tabs have unsaved edits. Quitting will discard these changes.") alert.alertStyle = .warning - alert.addButton(withTitle: String(localized: "Cancel")) - alert.addButton(withTitle: String(localized: "Quit Anyway")) - alert.buttons[1].hasDestructiveAction = true + AlertHelper.addCancelButton(to: alert, title: String(localized: "Cancel")) + let confirm = alert.addButton( + withTitle: relaunches ? String(localized: "Relaunch Anyway") : String(localized: "Quit Anyway") + ) + confirm.hasDestructiveAction = true return alert.runModal() == .alertSecondButtonReturn } } diff --git a/apple/TablePro/Core/Services/Infrastructure/TransactionEndPrompt.swift b/apple/TablePro/Core/Services/Infrastructure/TransactionEndPrompt.swift new file mode 100644 index 0000000000..e0d4b6bb73 --- /dev/null +++ b/apple/TablePro/Core/Services/Infrastructure/TransactionEndPrompt.swift @@ -0,0 +1,263 @@ +// +// TransactionEndPrompt.swift +// TablePro +// + +import Foundation + +// What closing, disconnecting, quitting or relaunching asks about an open transaction it would end. +internal struct TransactionEndPrompt: Equatable, Sendable { + internal enum Action: Equatable, Sendable { + case closeEntry(database: String) + case closeConnection(name: String) + case disconnect(name: String) + case quit + case relaunch + + var followsSavePrompt: Bool { + switch self { + case .closeEntry, .closeConnection: return true + case .disconnect, .quit, .relaunch: return false + } + } + } + + internal enum CommitBlock: Equatable, Sendable { + case aborted + case readOnly + case busy + // A database the live read found holding one, with no tracked hold to commit through. + case untracked + } + + internal let title: String + internal let message: String + internal let commitBlock: CommitBlock? + // The roll-back alert's confirming button, shown when Commit is not offered. + internal let confirmButton: String + + internal var offersCommit: Bool { commitBlock == nil } + + // A failed transaction can never commit, so it is named before the reasons that pass. `effectiveLevel` is the + // gate's level per connection, so the bar, the menu and this alert offer Commit by the same rule. + internal static func commitBlock( + holds: [SessionTransactionTracker.Hold], + untracked: Bool, + effectiveLevel: (UUID) -> SafeModeLevel, + busy: (SessionTransactionTracker.Hold) -> Bool + ) -> CommitBlock? { + if holds.contains(where: { $0.state == .aborted }) { return .aborted } + let refused = holds.contains { hold in + !ConnectionTransactionActions.offersCommit(hold.state, effectiveLevel: effectiveLevel(hold.connectionId)) + } + if refused { return .readOnly } + if holds.contains(where: { busy($0) }) { return .busy } + if untracked || holds.isEmpty { return .untracked } + return nil + } + + // Nil when nothing holds a transaction. `names` are databases, or connections for quit and relaunch. + internal static func make( + action: Action, + names: [String], + holds: [SessionTransactionTracker.Hold], + untracked: Bool = false, + savedUnderManualCommit: Bool = false, + hasUnsavedWork: Bool = false, + effectiveLevel: (UUID) -> SafeModeLevel, + busy: (SessionTransactionTracker.Hold) -> Bool + ) -> TransactionEndPrompt? { + guard !names.isEmpty else { return nil } + let block = commitBlock(holds: holds, untracked: untracked, effectiveLevel: effectiveLevel, busy: busy) + let several = max(names.count, holds.count) > 1 + var paragraphs: [String] + if block == nil { + paragraphs = [commitLead(action, names: names, holds: holds)] + } else { + paragraphs = [rollBackLead(action, names: names, holds: holds)] + if let reason = block.flatMap(reason(for:)) { + paragraphs.append(reason) + } + } + // Only a close asked Save first, so only there can the transaction hold edits the user just saved. + if savedUnderManualCommit, action.followsSavePrompt { + paragraphs.append(String(localized: "Edits saved with Manual Commit on are not committed yet.")) + } + if hasUnsavedWork, let line = unsavedLine(for: action) { + paragraphs.append(line) + } + return TransactionEndPrompt( + title: block == nil ? commitTitle(action, several: several) : rollBackTitle(action), + message: paragraphs.joined(separator: "\n\n"), + commitBlock: block, + confirmButton: rollBackButton(action) + ) + } + + private static func quoted(_ names: [String]) -> String { + ListFormatter.localizedString(byJoining: names.map { "“\($0)”" }) + } + + private static func commitTitle(_ action: Action, several: Bool) -> String { + switch action { + case .closeEntry(let database): + return String( + format: String(localized: "Do you want to commit the open transaction before closing the database “%@”?"), + database + ) + case .closeConnection(let name): + return String( + format: several + ? String(localized: "Do you want to commit the open transactions before closing “%@”?") + : String(localized: "Do you want to commit the open transaction before closing “%@”?"), + name + ) + case .disconnect(let name): + return String( + format: several + ? String(localized: "Do you want to commit the open transactions before disconnecting from “%@”?") + : String(localized: "Do you want to commit the open transaction before disconnecting from “%@”?"), + name + ) + case .quit: + return several + ? String(localized: "Do you want to commit the open transactions before quitting?") + : String(localized: "Do you want to commit the open transaction before quitting?") + case .relaunch: + return several + ? String(localized: "Do you want to commit the open transactions before relaunching?") + : String(localized: "Do you want to commit the open transaction before relaunching?") + } + } + + private static func commitLead(_ action: Action, names: [String], holds: [SessionTransactionTracker.Hold]) -> String { + switch action { + case .closeEntry: + return String(localized: "Changes you don’t commit are rolled back.") + case .closeConnection, .disconnect: + // One session for every database: the title names the connection, and its database can be a file path. + if names.count == 1, holds.allSatisfy({ $0.key.lane == nil }) { + return String(localized: "Changes you don’t commit are rolled back.") + } + guard names.count > 1 else { + return String( + format: String(localized: "The database “%@” has an open transaction. Changes you don’t commit are rolled back."), + names[0] + ) + } + return String( + format: String(localized: "These databases have open transactions: %@. Changes you don’t commit are rolled back."), + quoted(names) + ) + case .quit, .relaunch: + if names.count > 1 { + return String( + format: String(localized: "These connections have open transactions: %@. Changes you don’t commit are rolled back."), + quoted(names) + ) + } + return String( + format: holds.count > 1 + ? String(localized: "The connection “%@” has open transactions. Changes you don’t commit are rolled back.") + : String(localized: "The connection “%@” has an open transaction. Changes you don’t commit are rolled back."), + names[0] + ) + } + } + + private static func rollBackTitle(_ action: Action) -> String { + switch action { + case .closeEntry(let database): + return String(format: String(localized: "Close the database “%@”?"), database) + case .closeConnection(let name): + return String(format: String(localized: "Close the connection “%@”?"), name) + case .disconnect(let name): + return String(format: String(localized: "Disconnect from “%@”?"), name) + case .quit: + return String(localized: "Quit with an Open Transaction?") + case .relaunch: + return String(localized: "Relaunch with an Open Transaction?") + } + } + + private static func rollBackLead(_ action: Action, names: [String], holds: [SessionTransactionTracker.Hold]) -> String { + let several = names.count > 1 + let oneSession = !several && !holds.isEmpty && holds.allSatisfy { $0.key.lane == nil } + switch action { + case .closeConnection where oneSession: + return String(localized: "This connection has an open transaction. Closing rolls it back and discards its uncommitted changes.") + case .disconnect where oneSession: + return String( + localized: "This connection has an open transaction. Disconnecting rolls it back and discards its uncommitted changes." + ) + case .closeEntry: + return String( + localized: "This database has an open transaction. Closing it rolls the transaction back and discards its uncommitted changes." + ) + case .closeConnection: + return several + ? String( + format: String(localized: "These databases have open transactions: %@. Closing rolls them back and discards their uncommitted changes."), + quoted(names) + ) + : String( + format: String(localized: "The database “%@” has an open transaction. Closing rolls it back and discards its uncommitted changes."), + names[0] + ) + case .disconnect: + return several + ? String( + format: String(localized: "These databases have open transactions: %@. Disconnecting rolls them back and discards their uncommitted changes."), + quoted(names) + ) + : String( + format: String(localized: "The database “%@” has an open transaction. Disconnecting rolls it back and discards its uncommitted changes."), + names[0] + ) + case .quit: + return several + ? String(format: String(localized: "Uncommitted changes on %@ are rolled back when TablePro quits."), quoted(names)) + : String(format: String(localized: "Uncommitted changes on “%@” are rolled back when TablePro quits."), names[0]) + case .relaunch: + return several + ? String(format: String(localized: "Uncommitted changes on %@ are rolled back when TablePro relaunches."), quoted(names)) + : String(format: String(localized: "Uncommitted changes on “%@” are rolled back when TablePro relaunches."), names[0]) + } + } + + private static func reason(for block: CommitBlock) -> String? { + switch block { + case .aborted: + return String(localized: "A statement failed in the transaction, so it can only be rolled back.") + case .readOnly: + return String(localized: "Read-Only Safe Mode does not allow a commit.") + case .busy: + return String(localized: "A statement is still running in the transaction, so it cannot be committed now.") + case .untracked: + return nil + } + } + + // A close asks about unsaved work on its own Save alert first, so only these carry it here. + private static func unsavedLine(for action: Action) -> String? { + switch action { + case .disconnect: + return String(localized: "Unsaved changes will be lost.") + case .quit: + return String(localized: "Some tabs have unsaved edits. Quitting will discard these changes.") + case .relaunch: + return String(localized: "Some tabs have unsaved edits. Relaunching will discard these changes.") + case .closeEntry, .closeConnection: + return nil + } + } + + private static func rollBackButton(_ action: Action) -> String { + switch action { + case .closeEntry, .closeConnection: return String(localized: "Close") + case .disconnect: return String(localized: "Disconnect") + case .quit: return String(localized: "Quit Anyway") + case .relaunch: return String(localized: "Relaunch Anyway") + } + } +} diff --git a/apple/TablePro/Core/Services/Infrastructure/TransactionEndingFlow.swift b/apple/TablePro/Core/Services/Infrastructure/TransactionEndingFlow.swift new file mode 100644 index 0000000000..1dc5780dd6 --- /dev/null +++ b/apple/TablePro/Core/Services/Infrastructure/TransactionEndingFlow.swift @@ -0,0 +1,125 @@ +// +// TransactionEndingFlow.swift +// TablePro +// + +import AppKit +import Foundation + +// Close, entry close and disconnect end a session that can hold a transaction: this asks how it ends first. +@MainActor +internal enum TransactionEndingFlow { + internal enum Outcome: Equatable { + case nothingOpen + case ended + case cancelled + } + + // A database the read found holding one, and the tracked hold a commit goes through, if any. + internal struct Entry: Equatable { + let name: String + let hold: SessionTransactionTracker.Hold? + } + + internal static func resolve( + connectionId: UUID, + action: TransactionEndPrompt.Action, + among databases: Set? = nil, + hasUnsavedWork: Bool = false, + window: @MainActor () -> NSWindow?, + databaseManager: DatabaseManager = .shared, + ask: @MainActor (TransactionEndPrompt, NSWindow?) async -> AlertHelper.TransactionEndAnswer + = AlertHelper.answerTransactionEnd(_:window:), + commit: @MainActor ([SessionTransactionTracker.Hold]) async throws -> Bool + = { try await ConnectionTransactionActions.commitBeforeEnding($0) }, + reportFailure: @MainActor (String, NSWindow?) -> Void = TransactionEndingFlow.showCommitFailure(_:window:) + ) async -> Outcome { + var parent: NSWindow? + return await run( + read: { await entries(for: connectionId, among: databases, in: databaseManager) }, + prompt: { entries in + prompt(for: entries, action: action, connectionId: connectionId, hasUnsavedWork: hasUnsavedWork, in: databaseManager) + }, + ask: { prompt in + parent = window() + return await ask(prompt, parent) + }, + commit: commit, + reportFailure: { reportFailure($0, parent) } + ) + } + + // Roll Back sends nothing: ending the session rolls it back, and an explicit one would wait behind running work. + // Each answer reads again, so a transaction opened meanwhile, or one a commit left open, is asked about too. + internal static func run( + read: @MainActor () async -> [Entry], + prompt: @MainActor ([Entry]) -> TransactionEndPrompt?, + ask: @MainActor (TransactionEndPrompt) async -> AlertHelper.TransactionEndAnswer, + commit: @MainActor ([SessionTransactionTracker.Hold]) async throws -> Bool, + reportFailure: @MainActor (String) -> Void + ) async -> Outcome { + var rolledBack: Set = [] + var outcome = Outcome.nothingOpen + while true { + let entries = await read().filter { !rolledBack.contains($0.name) } + guard let question = prompt(entries) else { return outcome } + outcome = .ended + switch await ask(question) { + case .cancel: + return .cancelled + case .rollBack: + rolledBack.formUnion(entries.map { $0.name }) + case .commit: + do { + guard try await commit(entries.compactMap { $0.hold }) else { return .cancelled } + } catch is CancellationError { + return .cancelled + } catch { + reportFailure(error.localizedDescription) + return .cancelled + } + } + } + } + + // Read fresh at every question: the answer to the one before can land after work opened or ended a transaction. + internal static func entries( + for connectionId: UUID, + among databases: Set?, + in manager: DatabaseManager + ) async -> [Entry] { + let names = await manager.databasesHoldingTransaction(for: connectionId, among: databases) + let browsed = manager.session(for: connectionId)?.resolvedBrowseDatabase ?? "" + let holds = manager.sessionTransactions.holds(for: connectionId) + return names.map { name in + Entry(name: name, hold: holds.first { ($0.key.lane ?? browsed) == name }) + } + } + + internal static func showCommitFailure(_ message: String, window: NSWindow?) { + AlertHelper.showErrorSheet( + title: String(localized: "Could Not Commit the Transaction"), + message: message, + window: AlertHelper.resolveWindow(window).map(AlertOperationConfirming.frontmostSheet(of:)) + ) + } + + private static func prompt( + for entries: [Entry], + action: TransactionEndPrompt.Action, + connectionId: UUID, + hasUnsavedWork: Bool, + in manager: DatabaseManager + ) -> TransactionEndPrompt? { + TransactionEndPrompt.make( + action: action, + names: entries.map { $0.name }, + holds: entries.compactMap { $0.hold }, + untracked: entries.contains { $0.hold == nil }, + savedUnderManualCommit: manager.commitMode(for: connectionId) == .manual, + hasUnsavedWork: hasUnsavedWork, + effectiveLevel: { ExecutionGateProvider.effectiveSafeModeLevel(for: $0, in: manager) }, + busy: { manager.isLaneBusy(holding: $0) } + ) + } +} diff --git a/apple/TablePro/Core/Services/Infrastructure/WorkspaceCloseAction.swift b/apple/TablePro/Core/Services/Infrastructure/WorkspaceCloseAction.swift index b124761aaf..99c83fd07b 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WorkspaceCloseAction.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WorkspaceCloseAction.swift @@ -75,9 +75,7 @@ internal enum WorkspaceCloseAction { await ConnectionCloseAction.close(connectionId: workspace.connectionId) return } - /// Every window hosting the connection. A tab torn off into its own window can be the - /// container's only remaining tab, and closing the entry from the window that happens to - /// answer first would leave that tab open under an entry the user just closed. + // Every window hosting the connection: a torn-off tab can be the container's only one. let hostedWorkspaces = WindowManager.shared.workspaces(for: workspace.connectionId) guard let hosted = hostedWorkspaces.first else { Self.logger.error("close has no hosted workspace container=\(workspace.container, privacy: .private(mask: .hash))") @@ -86,16 +84,9 @@ internal enum WorkspaceCloseAction { let coordinators = hostedWorkspaces.compactMap { $0.sessionState?.coordinator } let coordinator = coordinators.first - /// Where the user was before the alert. Confirming reveals the work at risk, which switches - /// the window to that connection and selects one of the tabs, and an answer that closes - /// nothing has to put all of that back: leaving the user on a connection they did not ask - /// for, with the entry still listed, is a close that reads as a switch. + // Asking reveals the work at risk, so an answer that closes nothing puts the window back here. let wasShowing = WindowManager.shared.shownConnection(besides: workspace.connectionId) - guard await confirmEndingTransaction(in: workspace) else { - Self.logger.info("close cancelled at the transaction prompt container=\(workspace.container, privacy: .private(mask: .hash))") - return - } - // Taken after the transaction prompt: the tabs stay editable while it is answered. + // Running work, then unsaved work, then the transaction, read after the save: Save under Manual Commit lands in one. let victims = committedTabs(in: workspace.container, across: coordinators) // Closing a tab stops its query, so a yes needs no cancel of its own. let running = RunningWorkRegistry.shared.items(in: .tabs(Set(victims.map(\.id)))) @@ -115,16 +106,15 @@ internal enum WorkspaceCloseAction { return } } - guard let closable = await confirm( + guard let confirmed = await confirm( victims, across: coordinators, revealing: workspace, alsoStopping: holdsUnsavedWork ? running : [] ) else { WindowManager.shared.show(wasShowing, inWindowHosting: workspace.connectionId) Self.logger.info("close cancelled at the save prompt container=\(workspace.container, privacy: .private(mask: .hash))") return } - /// A tab whose work the save could not take keeps the container open, because it is still - /// work in it. Closing the entry regardless would destroy exactly what the alert said would - /// stay, which is the promise the wording makes. + let closable = confirmed.closable + // A tab whose work the save could not take keeps the container open: the alert promised it would stay. guard closable.isSuperset(of: Set(victims.map(\.id))) else { closeTabs(victims.map(\.id).filter { closable.contains($0) }, across: coordinators) WindowManager.shared.show(wasShowing, inWindowHosting: workspace.connectionId) @@ -136,11 +126,29 @@ internal enum WorkspaceCloseAction { ) return } - /// The entry goes now, before the connection leaves the container, because leaving it is a - /// schema reload, and on an engine that can neither change database on a live connection nor - /// open a second one, a reconnect: waiting for that left the row the user just closed sitting - /// there for seconds while the window loaded somewhere else. `beginClosing` is what lets the strip drop the - /// browse cursor's own row early, and the cursor follows underneath. + // Before anything closes, so a Cancel or a failed commit leaves the entry as it was. + guard await resolveTransaction(in: workspace) else { + confirmed.restoreRevealed() + WindowManager.shared.show(wasShowing, inWindowHosting: workspace.connectionId) + Self.logger.info("close cancelled at the transaction prompt container=\(workspace.container, privacy: .private(mask: .hash))") + return + } + // One session serves every entry, so its transaction outlives the close, and an engine that cannot switch + // database inside one refuses the move: moving first means a refusal closes nothing. + let movesFirst = await holdsSessionWideTransaction(workspace.connectionId) + if movesFirst { + guard await browseAway(from: workspace, among: containers, coordinator: coordinator) else { + confirmed.restoreRevealed() + WindowManager.shared.show(wasShowing, inWindowHosting: workspace.connectionId) + Self.logger.error( + "close could not leave container=\(workspace.container, privacy: .private(mask: .hash))" + ) + return + } + } + // Otherwise the entry goes before the connection leaves the container: leaving can be a reconnect, and + // waiting for it left the closed row on the strip for seconds. `beginClosing` lets the strip drop the + // browse cursor's own row early, and the cursor follows underneath. if !victims.isEmpty { closeTabs(victims.map(\.id), across: coordinators) } @@ -158,7 +166,10 @@ internal enum WorkspaceCloseAction { """ ) - let left = await browseAway(from: workspace, among: containers, coordinator: coordinator) + var left = true + if !movesFirst { + left = await browseAway(from: workspace, among: containers, coordinator: coordinator) + } if left { leave(workspace, in: coordinators) } @@ -166,9 +177,7 @@ internal enum WorkspaceCloseAction { hostedWorkspace.endClosing() } guard left else { - /// The connection never left, so the container is open again: it is where the next tab - /// still opens, and a strip that did not list it would be lying about where the user is. - /// The driver's own error is already on screen. + // The connection never left, so the next tab still opens there; the driver's error is already on screen. for hostedWorkspace in hostedWorkspaces { hostedWorkspace.openContainer(workspace.container) } @@ -179,9 +188,7 @@ internal enum WorkspaceCloseAction { return } - /// Read again rather than reusing the list from before the switch: a table opened while the - /// reconnect ran anchors the container all over again, and the entry would come back with - /// one stray tab under it. A tab that new has nothing to lose. + // Read again: a table opened while the switch ran anchors the container anew, and has nothing to lose. let opened = coordinators.flatMap { tabs(in: workspace.container, of: $0) } if !opened.isEmpty { closeTabs(opened.map(\.id), across: coordinators) @@ -189,43 +196,27 @@ internal enum WorkspaceCloseAction { hostedWorkspace.closeContainer(workspace.container) } } - /// The database keeps its own connection and its catalog while its entry is listed; closing the - /// entry is what ends them, and the connection has already moved off it above. + // Closing the entry ends the database's own connection and catalog; the browse cursor moved off it above. DatabaseManager.shared.sessionLanes.close(database: workspace.container, for: workspace.connectionId) SchemaService.shared.forget(database: workspace.container, connectionId: workspace.connectionId) } - /// Shown, then asked, for the same reason a connection close reveals itself first: an alert - /// about work the user cannot see names tabs they have no way to look at before answering. - /// Selecting one of the victims is also what makes Save save a victim. It runs only when there - /// is something to confirm, because raising a background connection's window and moving its tab - /// selection is a side effect no one asked for when the close has nothing to lose. - /// nil when the user cancelled; otherwise the victims that may now be closed, which is every one - /// of them unless Save could not reach some. - /// Asked of the window that owns each tab. - /// - /// A tab's live grid and structure edits exist only in its own coordinator: a background - /// snapshot of a tab in another window reads as clean whatever is staged in it. Once a - /// connection can be hosted twice, a container's tabs span both windows, and putting all of - /// them to the coordinator that answered first reported the foreign ones as safe and closed - /// over the edits without a prompt. - /// - /// Cancel anywhere cancels everything, because the entry either closes or it does not. + // nil when the user cancelled; otherwise the victims that may close (all, unless Save could not reach some) and + // the windows revealed to ask, for a later Cancel to put back. Each tab is asked of the window that owns it, + // since its live edits exist only in its own coordinator, and only when it holds unsaved work: revealing a + // background window is a side effect no one asked for when nothing is lost. Cancel anywhere cancels everything. private static func confirm( _ victims: [QueryTab], across coordinators: [MainContentCoordinator], revealing workspace: WorkspaceID, alsoStopping running: [RunningWork] - ) async -> Set? { + ) async -> Confirmation? { var running = running let everything = Set(victims.map(\.id)) - guard !victims.isEmpty else { return everything } + guard !victims.isEmpty else { return Confirmation(closable: everything, revealed: []) } var closable: Set = [] - /// What each window was showing before it was brought forward to ask, the entry and its tab - /// as well as the connection. A dirty split connection reveals more than one of them, and - /// the caller can only put one back, so an abandoned close left the others switched to a - /// connection the user never chose. + // A dirty split connection reveals more than one window, and the caller can only put one back. var revealed: [RevealedWindow] = [] func restoreRevealed() { for window in revealed { @@ -259,12 +250,24 @@ internal enum WorkspaceCloseAction { closable.formUnion(resolved) } } - /// A victim no window claims is already gone, so nothing is holding work for it. + // A victim no window claims is already gone, so nothing is holding work for it. let unclaimed = victims.map(\.id).filter { id in !coordinators.contains { coordinator in coordinator.tabManager.tabs.contains { $0.id == id } } } closable.formUnion(unclaimed) - return closable + return Confirmation(closable: closable, revealed: revealed) + } + + @MainActor + private struct Confirmation { + let closable: Set + let revealed: [RevealedWindow] + + func restoreRevealed() { + for window in revealed { + window.restore() + } + } } /// A window as it was before it was brought forward to ask: the connection it showed, and that @@ -294,27 +297,27 @@ internal enum WorkspaceCloseAction { } } - /// Asked before the unsaved-work prompt, whose Save writes at once, so a Cancel here leaves - /// everything as it was. Nothing is revealed: the alert names the database, and the transaction - /// is not in any one tab. Only a database with its own connection loses a transaction on close. - private static func confirmEndingTransaction(in workspace: WorkspaceID) async -> Bool { + // Only a database with its own connection loses a transaction when its entry closes. Nothing is revealed: the + // alert names the database, and the transaction is in no one tab. + private static func resolveTransaction(in workspace: WorkspaceID) async -> Bool { let manager = DatabaseManager.shared guard let session = manager.session(for: workspace.connectionId), manager.usesDatabaseLanes(session) else { return true } - let holding = await manager.databasesHoldingTransaction( - for: workspace.connectionId, - among: [workspace.container] - ) - guard !holding.isEmpty else { return true } - return await AlertHelper.confirmDestructive( - title: String(format: String(localized: "Close the database “%@”?"), workspace.container), - message: String( - localized: "This database has an open transaction. Closing it rolls the transaction back and discards its uncommitted changes." - ), - confirmButton: String(localized: "Close"), - window: WindowManager.shared.window(for: workspace.connectionId) + let outcome = await TransactionEndingFlow.resolve( + connectionId: workspace.connectionId, + action: .closeEntry(database: workspace.container), + among: [workspace.container], + window: { WindowManager.shared.window(for: workspace.connectionId) } ) + return outcome != .cancelled + } + + private static func holdsSessionWideTransaction(_ connectionId: UUID) async -> Bool { + let manager = DatabaseManager.shared + guard let session = manager.session(for: connectionId), !manager.usesDatabaseLanes(session) else { return false } + let holding = await manager.databasesHoldingTransaction(for: connectionId) + return !holding.isEmpty } /// Leaves the container before it stops being listed, and only when it is the one being browsed. diff --git a/apple/TablePro/Core/Services/Operations/RunningWorkPrompt.swift b/apple/TablePro/Core/Services/Operations/RunningWorkPrompt.swift index 5d254a3e4a..e0a1b3d463 100644 --- a/apple/TablePro/Core/Services/Operations/RunningWorkPrompt.swift +++ b/apple/TablePro/Core/Services/Operations/RunningWorkPrompt.swift @@ -41,11 +41,6 @@ internal struct RunningWorkPrompt: Equatable, Sendable { return ([message, lines, consequence(of: action)] + notes(for: work)).joined(separator: "\n\n") } - // An open transaction rides along as a loss: closing or disconnecting rolls it back. - internal static func transactionLines(for databases: [String]) -> [String] { - databases.map { String(format: String(localized: "Open transaction in “%@”"), $0) } - } - internal static func line(for work: RunningWork) -> String { let subject = work.subject.trimmingCharacters(in: .whitespacesAndNewlines) let connection = work.connectionName diff --git a/apple/TablePro/Core/Updates/AppRelauncher.swift b/apple/TablePro/Core/Updates/AppRelauncher.swift index 9fed1e282b..8da45182c0 100644 --- a/apple/TablePro/Core/Updates/AppRelauncher.swift +++ b/apple/TablePro/Core/Updates/AppRelauncher.swift @@ -17,30 +17,37 @@ final class AppRelauncher { } private let defaults: UserDefaults - private let approveStoppingWork: @MainActor () -> Bool + private let approveStoppingWork: @MainActor () -> QuitPlan? + private let commitBeforeQuitting: @MainActor (QuitPlan) async -> Bool private let reviewUnsavedDocuments: @MainActor (@escaping @MainActor (Bool) -> Void) -> Void private let installPendingUpdate: @MainActor () -> Bool private let terminate: @MainActor () -> Void + private let performOutsideTask: @MainActor (@escaping @MainActor () -> Void) -> Void private let reopenAfterExit: @MainActor (_ pid: pid_t, _ bundleURL: URL) throws -> Void private var route: Route? + private(set) var pendingCommit: Task? init( defaults: UserDefaults = AppStorageEnvironment.shared.defaults, - approveStoppingWork: @escaping @MainActor () -> Bool = { + approveStoppingWork: @escaping @MainActor () -> QuitPlan? = { // Everything that can still refuse asks here, before Sparkle or the quit takes over. - ThemeEditorWindows.shared.prepareToTerminate() - && QuitApproval.approvesStoppingWork(registry: .shared, action: .relaunch, stopsWork: false) + guard ThemeEditorWindows.shared.prepareToTerminate() else { return nil } + return QuitApproval.approvesStoppingWork(registry: .shared, action: .relaunch) }, + commitBeforeQuitting: @escaping @MainActor (QuitPlan) async -> Bool = { await QuitApproval.commitBeforeQuitting($0) }, reviewUnsavedDocuments: @escaping @MainActor (@escaping @MainActor (Bool) -> Void) -> Void = UnsavedDocumentReview.run, installPendingUpdate: @escaping @MainActor () -> Bool = { SoftwareUpdater.shared.installAndRelaunch() }, terminate: @escaping @MainActor () -> Void = { NSApp.terminate(nil) }, + performOutsideTask: @escaping @MainActor (@escaping @MainActor () -> Void) -> Void = AppRelauncher.performOnNextRunLoopTurn, reopenAfterExit: @escaping @MainActor (_ pid: pid_t, _ bundleURL: URL) throws -> Void = AppRelauncher.reopenAfterExit(pid:bundleURL:) ) { self.defaults = defaults self.approveStoppingWork = approveStoppingWork + self.commitBeforeQuitting = commitBeforeQuitting self.reviewUnsavedDocuments = reviewUnsavedDocuments self.installPendingUpdate = installPendingUpdate self.terminate = terminate + self.performOutsideTask = performOutsideTask self.reopenAfterExit = reopenAfterExit } @@ -51,12 +58,36 @@ final class AppRelauncher { // Documents are reviewed first: AppKit cancels a quit there before the app delegate hears of it. func relaunch() { + // A commit still running is this same relaunch. + guard pendingCommit == nil else { return } reviewUnsavedDocuments { [weak self] proceed in - guard let self, proceed, self.approveStoppingWork() else { return } - self.route = .sparkleInstall - guard !self.installPendingUpdate() else { return } - self.route = .reopenAfterExit - self.terminate() + guard let self, proceed, let plan = self.approveStoppingWork() else { return } + guard !plan.commits.isEmpty else { + self.quitToRelaunch() + return + } + // The commit runs before Sparkle or the quit takes over, since the quit it starts asks nothing. + self.pendingCommit = Task { [weak self] in + guard let self else { return } + let committed = await self.commitBeforeQuitting(plan) + self.pendingCommit = nil + guard committed else { return } + // A terminate from inside a main-actor job never lets the quit's reply task run. + self.performOutsideTask { [weak self] in self?.quitToRelaunch() } + } + } + } + + private func quitToRelaunch() { + route = .sparkleInstall + guard !installPendingUpdate() else { return } + route = .reopenAfterExit + terminate() + } + + static func performOnNextRunLoopTurn(_ body: @escaping @MainActor () -> Void) { + RunLoop.main.perform { + MainActor.assumeIsolated(body) } } diff --git a/apple/TablePro/Core/Utilities/UI/AlertHelper.swift b/apple/TablePro/Core/Utilities/UI/AlertHelper.swift index 1c6f1c04de..de6cc1c69e 100644 --- a/apple/TablePro/Core/Utilities/UI/AlertHelper.swift +++ b/apple/TablePro/Core/Utilities/UI/AlertHelper.swift @@ -381,6 +381,54 @@ final class AlertHelper { } } + // MARK: - Ending a Transaction + + enum TransactionEndAnswer: Equatable, Sendable { + case commit, rollBack, cancel + } + + // The Save alert's order: Commit keeps Return, Cancel takes Escape, Roll Back takes no key. Without Commit, the roll-back alert. + static func makeTransactionEndAlert(_ prompt: TransactionEndPrompt) -> NSAlert { + let alert = NSAlert() + alert.messageText = prompt.title + alert.informativeText = prompt.message + alert.alertStyle = .warning + guard prompt.offersCommit else { + addConfirmAndCancel(to: alert, confirmButton: prompt.confirmButton, cancelButton: String(localized: "Cancel")) + return alert + } + let commit = alert.addButton(withTitle: String(localized: "Commit")) + commit.keyEquivalent = "\r" + addCancelButton(to: alert, title: String(localized: "Cancel")) + let rollBack = alert.addButton(withTitle: String(localized: "Roll Back")) + rollBack.hasDestructiveAction = true + rollBack.keyEquivalent = "" + return alert + } + + static func transactionEndAnswer(to response: NSApplication.ModalResponse, offersCommit: Bool) -> TransactionEndAnswer { + switch response { + case .alertFirstButtonReturn: + return offersCommit ? .commit : .rollBack + case .alertThirdButtonReturn where offersCommit: + return .rollBack + default: + return .cancel + } + } + + // On the window's frontmost sheet: work still running can hold a progress sheet there. + static func answerTransactionEnd(_ prompt: TransactionEndPrompt, window: NSWindow?) async -> TransactionEndAnswer { + let parent = resolveWindow(window).map(AlertOperationConfirming.frontmostSheet(of:)) + let clicked = await response(to: makeTransactionEndAlert(prompt), in: parent) + return transactionEndAnswer(to: clicked, offersCommit: prompt.offersCommit) + } + + // Quit and relaunch need the answer before they return. + static func answerTransactionEndModally(_ prompt: TransactionEndPrompt) -> TransactionEndAnswer { + transactionEndAnswer(to: makeTransactionEndAlert(prompt).runModal(), offersCommit: prompt.offersCommit) + } + // MARK: - Three-Way Confirmations // `detail` is the text the answer is given against, so it goes whole into a scrolling box that reveals invisible diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 93949bd22a..c0355199df 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -17296,6 +17296,12 @@ } } } + }, + "A statement failed in the transaction, so it can only be rolled back." : { + + }, + "A statement is still running in the transaction, so it cannot be committed now." : { + }, "A statement on '%1$@' matched %2$d rows instead of %3$d, so nothing was saved." : { "localizations" : { @@ -17685,9 +17691,15 @@ }, "A transaction is open on this connection, and this change cannot run inside it. Nothing was run. Commit or roll back the transaction, then try again." : { + }, + "A transaction is open on this connection, and this change would have to end it. Commit or roll back the transaction, then try again." : { + }, "A transaction is open on this connection. Commit or roll it back in TablePro, then run the shortcut again." : { + }, + "A transaction is still open on %@." : { + }, "A transaction is still open on this connection. Commit or roll it back." : { @@ -36698,6 +36710,9 @@ }, "Changes Unavailable" : { + }, + "Changes you don’t commit are rolled back." : { + }, "Changing %@ from %@ to %@ can truncate existing values." : { "localizations" : { @@ -53273,6 +53288,9 @@ } } } + }, + "Could Not Commit the Transaction" : { + }, "Could Not Compare" : { "localizations" : { @@ -66841,6 +66859,33 @@ } } } + }, + "Do you want to commit the open transaction before closing “%@”?" : { + + }, + "Do you want to commit the open transaction before closing the database “%@”?" : { + + }, + "Do you want to commit the open transaction before disconnecting from “%@”?" : { + + }, + "Do you want to commit the open transaction before quitting?" : { + + }, + "Do you want to commit the open transaction before relaunching?" : { + + }, + "Do you want to commit the open transactions before closing “%@”?" : { + + }, + "Do you want to commit the open transactions before disconnecting from “%@”?" : { + + }, + "Do you want to commit the open transactions before quitting?" : { + + }, + "Do you want to commit the open transactions before relaunching?" : { + }, "Do you want to save changes?" : { "localizations" : { @@ -71484,6 +71529,9 @@ }, "Edits %@" : { + }, + "Edits saved with Manual Commit on are not committed yet." : { + }, "Effective" : { "localizations" : { @@ -144790,6 +144838,9 @@ } } } + }, + "Read-Only Safe Mode does not allow a commit." : { + }, "Read-only SQL over Iceberg tables in R2" : { "localizations" : { @@ -171389,6 +171440,9 @@ } } } + }, + "Some tabs have unsaved edits. Relaunching will discard these changes." : { + }, "Some values are set outside this file" : { "localizations" : { @@ -175078,6 +175132,21 @@ } } } + }, + "Statement %1$d/%2$d is a DDL statement, and the session takes nothing after it but COMMIT or ROLLBACK. The run stopped before statement %3$d. Click Commit on the Transaction Open bar, then begin the rest with “%4$@”." : { + + }, + "Statement %1$d/%2$d is a DDL statement, and the session takes nothing after it but COMMIT or ROLLBACK. The run stopped before statement %3$d. Click Commit on the Transaction Open bar, then run the rest." : { + + }, + "Statement %1$d/%2$d is a DDL statement, and the session takes nothing after it but COMMIT or ROLLBACK. The run stopped before statement %3$d. Click Commit on the Transaction Open bar. A new run starts in the tab's database, so begin the rest with “%4$@”." : { + + }, + "Statement %1$d/%2$d moves the session to another database, which this session takes only outside a transaction. The run stopped before it. Click Commit or Roll Back on the Transaction Open bar, then run the script again from statement %1$d." : { + + }, + "Statement %1$d/%2$d moves the session to another database, which this session takes only outside a transaction. The run stopped before it. Click Roll Back on the Transaction Open bar, move the statement above the script's BT, then run the script again from there." : { + }, "Statement %lld" : { "extractionState" : "stale", @@ -187753,6 +187822,12 @@ "The condition of index %@ cannot be written as SQL." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "The connection “%@” has an open transaction. Changes you don’t commit are rolled back." : { + + }, + "The connection “%@” has open transactions. Changes you don’t commit are rolled back." : { + }, "The connection closed." : { @@ -188551,6 +188626,9 @@ }, "The data has no values to insert into %@." : { + }, + "The database “%@” has an open transaction. Changes you don’t commit are rolled back." : { + }, "The database “%@” has an open transaction. Closing rolls it back and discards its uncommitted changes." : { "localizations" : { @@ -197396,6 +197474,9 @@ }, "These columns would leave too little room to scroll the rest." : { + }, + "These connections have open transactions: %@. Changes you don’t commit are rolled back." : { + }, "These connections open their tunnel by running a command on this Mac, every time they connect:\n\n%@" : { "extractionState" : "stale", @@ -197413,6 +197494,9 @@ }, "These connections run commands every time they connect: a tunnel command on this Mac, SQL on the server, or both.\n\n%@" : { + }, + "These databases have open transactions: %@. Changes you don’t commit are rolled back." : { + }, "These databases have open transactions: %@. Closing rolls them back and discards their uncommitted changes." : { "localizations" : { @@ -198164,6 +198248,9 @@ "This connection has a transaction open. Commit or roll it back in TablePro, then try again." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "This connection has an open transaction. Closing rolls it back and discards its uncommitted changes." : { + }, "This connection has an open transaction. Commit or roll it back first." : { "extractionState" : "manual", @@ -198176,6 +198263,9 @@ } } } + }, + "This connection has an open transaction. Disconnecting rolls it back and discards its uncommitted changes." : { + }, "This connection has another database attached, which closing the file would detach." : { "extractionState" : "manual", @@ -208426,9 +208516,15 @@ }, "Uncommitted changes on “%@” are rolled back when TablePro quits." : { + }, + "Uncommitted changes on “%@” are rolled back when TablePro relaunches." : { + }, "Uncommitted changes on %@ are rolled back when TablePro quits." : { + }, + "Uncommitted changes on %@ are rolled back when TablePro relaunches." : { + }, "Under MCP Servers click \"+ Add Custom Server\", select the Local tab, paste the JSON below, then click Add Server" : { "localizations" : { diff --git a/apple/TablePro/Views/Main/Child/ConnectionTransactionActions.swift b/apple/TablePro/Views/Main/Child/ConnectionTransactionActions.swift index a1d5d3b0d6..e3d41788f6 100644 --- a/apple/TablePro/Views/Main/Child/ConnectionTransactionActions.swift +++ b/apple/TablePro/Views/Main/Child/ConnectionTransactionActions.swift @@ -25,35 +25,66 @@ internal enum ConnectionTransactionActions { } // A COMMIT is a write, so it asks what a typed one asks: nothing at Silent, a confirmation at Alert, Touch ID at Safe Mode. + // False when the user cancelled that question. + @discardableResult static func commit( _ hold: SessionTransactionTracker.Hold, databaseManager: DatabaseManager = .shared, gate: any ExecutionGate = ExecutionGateProvider.shared - ) async throws { - guard let session = databaseManager.session(for: hold.connectionId) else { return } - let decision = await gate.authorize( - OperationRequest( - connectionId: hold.connectionId, - databaseType: session.connection.type, - sql: "COMMIT", - kind: .writeQuery, - caller: .userInterface, - capabilities: .interactiveUser, - operationDescription: String(localized: "Commit the transaction") + ) async throws -> Bool { + try await commitBeforeEnding([hold], databaseManager: databaseManager, gate: gate) + } + + // Every connection is asked before anything is sent, so a Cancel on any of them commits nothing. + static func commitBeforeEnding( + _ holds: [SessionTransactionTracker.Hold], + databaseManager: DatabaseManager = .shared, + gate: any ExecutionGate = ExecutionGateProvider.shared + ) async throws -> Bool { + var connectionIds: [UUID] = [] + for hold in holds where !connectionIds.contains(hold.connectionId) { + connectionIds.append(hold.connectionId) + } + for connectionId in connectionIds { + guard let session = databaseManager.session(for: connectionId) else { continue } + let decision = await gate.authorize( + OperationRequest( + connectionId: connectionId, + databaseType: session.connection.type, + sql: "COMMIT", + kind: .writeQuery, + caller: .userInterface, + capabilities: .interactiveUser, + operationDescription: String(localized: "Commit the transaction") + ) ) - ) - switch decision { - case .authorized: + switch decision { + case .authorized: + break + case .denied(_, .cancelledByUser): + return false + case .denied(let reason, .policy): + throw SessionTransactionDenial(reason: reason) + } + } + // A session that ended took its transaction with it. + for hold in holds where databaseManager.session(for: hold.connectionId) != nil { try await databaseManager.endTransaction(hold, committing: true) - case .denied(_, .cancelledByUser): - return - case .denied(let reason, .policy): - throw SessionTransactionDenial(reason: reason) } + return true } - static func offersCommit(_ hold: SessionTransactionTracker.Hold, safeModeLevel: SafeModeLevel) -> Bool { - hold.state == .open && !safeModeLevel.blocksAllWrites + // The bar, the menu and the close prompts all ask this. The level is the one the gate decides the COMMIT at, the + // managed floor included: the session's own level offered Commit under a managed Read-Only floor the gate then denied. + nonisolated static func offersCommit(_ state: SessionTransactionTracker.State, effectiveLevel: SafeModeLevel) -> Bool { + state == .open && !effectiveLevel.blocksAllWrites + } + + static func offersCommit(_ hold: SessionTransactionTracker.Hold, databaseManager: DatabaseManager = .shared) -> Bool { + offersCommit( + hold.state, + effectiveLevel: ExecutionGateProvider.effectiveSafeModeLevel(for: hold.connectionId, in: databaseManager) + ) } static func perform(window: NSWindow?, _ action: @MainActor () async throws -> Void) async { diff --git a/apple/TablePro/Views/Main/Child/ConnectionTransactionBar.swift b/apple/TablePro/Views/Main/Child/ConnectionTransactionBar.swift index 53a5c82487..7ea1ea2af6 100644 --- a/apple/TablePro/Views/Main/Child/ConnectionTransactionBar.swift +++ b/apple/TablePro/Views/Main/Child/ConnectionTransactionBar.swift @@ -21,7 +21,7 @@ internal struct ConnectionTransactionBarContent: Equatable { isAborted ? Self.abortedSymbolName : Self.openSymbolName } - init(isAborted: Bool, connectionName: String, database: String?, safeModeLevel: SafeModeLevel) { + init(isAborted: Bool, connectionName: String, database: String?, effectiveSafeModeLevel: SafeModeLevel) { self.isAborted = isAborted let database = database.flatMap { $0.isEmpty ? nil : $0 } if isAborted { @@ -42,7 +42,7 @@ internal struct ConnectionTransactionBarContent: Equatable { accessibilityLabel = database.map { String(format: String(localized: "Transaction open on %1$@, %2$@"), $0, connectionName) } ?? String(format: String(localized: "Transaction open on %@"), connectionName) - offersCommit = !safeModeLevel.blocksAllWrites + offersCommit = ConnectionTransactionActions.offersCommit(.open, effectiveLevel: effectiveSafeModeLevel) } } @@ -51,7 +51,8 @@ internal struct ConnectionTransactionBar: View { let connectionId: UUID @ObservedObject var transactions: SessionTransactionTracker let databaseManager: DatabaseManager - // Passed from the toolbar state the window observes: the session's own level publishes nothing. + // Passed from the toolbar state the window observes, so the bar redraws when the level changes; the session's own + // level publishes nothing. Commit follows the gate's level, read in `content(for:in:)`. let safeModeLevel: SafeModeLevel @State private var actingOn: SessionTransactionTracker.Key? @@ -75,7 +76,7 @@ internal struct ConnectionTransactionBar: View { isAborted: hold.state == .aborted, connectionName: session.connection.name, database: hold.key.lane ?? namedDatabase(of: session), - safeModeLevel: safeModeLevel + effectiveSafeModeLevel: ExecutionGateProvider.effectiveSafeModeLevel(for: connectionId, in: databaseManager) ) } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Rename.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Rename.swift index 868274dbb0..9e8bae0e34 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Rename.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Rename.swift @@ -41,12 +41,15 @@ extension MainContentCoordinator { do { let route = DatabaseManager.shared.executionRoute(for: scope) + let refusesOpenTransaction = !route.isPooled try await DatabaseManager.shared.withScopedDriver( scope: scope, route: route, cancellation: .protectedWrite ) { driver in - try await driver.renameTable( - name: oldName, schema: schema, to: newName, objectType: objectType - ) + try await AppDefinitionCommit.run(on: driver, refusesOpenTransaction: refusesOpenTransaction) { + try await driver.renameTable( + name: oldName, schema: schema, to: newName, objectType: objectType + ) + } } } catch { presentRenameFailure(error, object: ref.id) diff --git a/apple/TableProTests/Core/DataWrite/DataWriteExecutorTableOperationTests.swift b/apple/TableProTests/Core/DataWrite/DataWriteExecutorTableOperationTests.swift new file mode 100644 index 0000000000..e240154fb3 --- /dev/null +++ b/apple/TableProTests/Core/DataWrite/DataWriteExecutorTableOperationTests.swift @@ -0,0 +1,172 @@ +// +// DataWriteExecutorTableOperationTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +private final class TableOperationDriver: PluginDriverStub, @unchecked Sendable { + struct Failure: Error {} + + private let lock = NSLock() + private let state: PluginSessionTransactionState + private let failing: String? + private var sent: [String] = [] + + init(state: PluginSessionTransactionState = .idle, failing: String? = nil) { + self.state = state + self.failing = failing + } + + var supportsSchemas: Bool { false } + var supportsTransactions: Bool { true } + var currentSchema: String? { nil } + var serverVersion: String? { nil } + + var trace: [String] { lock.withLock { sent } } + + func execute(query: String) async throws -> PluginQueryResult { + lock.withLock { sent.append(query) } + if query == failing { throw Failure() } + return .empty + } + + func sessionTransactionState() async -> PluginSessionTransactionState { state } + + func beginTransaction(mode: PluginTransactionAccessMode) async throws { lock.withLock { sent.append("BEGIN") } } + func commitTransaction() async throws { lock.withLock { sent.append("COMMIT") } } + func rollbackTransaction() async throws { lock.withLock { sent.append("ROLLBACK") } } + + func switchDatabase(to database: String) async throws {} +} + +struct DataWriteExecutorTableOperationTests { + private static let dropA = "DROP TABLE a" + private static let dropB = "DROP TABLE b" + + private static let truncateA = "DELETE FROM a ALL" + + private static func dropPlan(_ databaseType: DatabaseType) -> DataWritePlan { + tableOperationPlan([dropA, dropB], databaseType: databaseType) + } + + private static func tableOperationPlan(_ statements: [String], databaseType: DatabaseType = .teradata) -> DataWritePlan { + DataWritePlan( + scope: DatabaseScope(connectionId: UUID(), database: "sales", schema: nil), + databaseType: databaseType, + steps: statements.map { + DataWriteStep(kind: .tableOperation, statement: ParameterizedStatement(sql: $0, parameters: [])) + } + ) + } + + private static func adapter(_ driver: TableOperationDriver, type: DatabaseType) -> DatabaseDriver { + PluginDriverAdapter(connection: TestFixtures.makeConnection(type: type), pluginDriver: driver) + } + + @Test("Two Teradata drops each end their own transaction, with no commit after the last") + func teradataDropsCommitOneByOne() async throws { + let driver = TableOperationDriver() + + let run = try await DataWriteExecutor.run( + Self.dropPlan(.teradata), commitMode: .automatic, on: Self.adapter(driver, type: .teradata) + ) + + #expect(run.results.count == 2) + #expect(driver.trace == ["BEGIN", Self.dropA, "COMMIT", "BEGIN", Self.dropB, "COMMIT"]) + } + + @Test("Drops on an engine without the rule keep one transaction") + func otherEnginesKeepOneTransaction() async throws { + let driver = TableOperationDriver() + + _ = try await DataWriteExecutor.run( + Self.dropPlan(.mysql), commitMode: .automatic, on: Self.adapter(driver, type: .mysql) + ) + + #expect(driver.trace == ["BEGIN", Self.dropA, Self.dropB, "COMMIT"]) + } + + @Test("Teradata drops are refused before anything runs while the session holds a transaction") + func teradataDropsRefusedInsideAnOpenTransaction() async throws { + let driver = TableOperationDriver(state: .inTransaction) + + await #expect(throws: DefinitionInOpenTransactionRefusal()) { + try await DataWriteExecutor.run( + Self.dropPlan(.teradata), commitMode: .automatic, on: Self.adapter(driver, type: .teradata) + ) + } + #expect(driver.trace.isEmpty) + } + + @Test("Teradata drops are refused before anything runs under Manual Commit") + func teradataDropsRefusedUnderManualCommit() async throws { + let driver = TableOperationDriver() + + await #expect(throws: ManualCommitRefusal()) { + try await DataWriteExecutor.run( + Self.dropPlan(.teradata), commitMode: .manual, on: Self.adapter(driver, type: .teradata) + ) + } + #expect(driver.trace.isEmpty) + } + + @Test("A Teradata drop that fails after another committed reports that one as written") + func failedSecondDropReportsTheFirstAsWritten() async throws { + let driver = TableOperationDriver(failing: Self.dropB) + + do { + _ = try await DataWriteExecutor.run( + Self.dropPlan(.teradata), commitMode: .automatic, on: Self.adapter(driver, type: .teradata) + ) + Issue.record("The save reported success") + } catch let partial as DataWritePartialCommitError { + #expect(partial.committed.count == 1) + #expect(partial.totalStatements == 2) + #expect(partial.disposition == .written) + } + #expect(driver.trace == ["BEGIN", Self.dropA, "COMMIT", "BEGIN", Self.dropB, "ROLLBACK"]) + } + + @Test("A Teradata truncate joins the drop's transaction, which the drop then ends") + func teradataTruncateJoinsTheDropsSegment() async throws { + let driver = TableOperationDriver() + + _ = try await DataWriteExecutor.run( + Self.tableOperationPlan([Self.truncateA, Self.dropB]), commitMode: .automatic, + on: Self.adapter(driver, type: .teradata) + ) + + #expect(driver.trace == ["BEGIN", Self.truncateA, Self.dropB, "COMMIT"]) + } + + @Test("A Teradata truncate after a drop runs in a transaction of its own, committed at the end") + func teradataTruncateAfterADropGetsTheFinalCommit() async throws { + let driver = TableOperationDriver() + + _ = try await DataWriteExecutor.run( + Self.tableOperationPlan([Self.dropB, Self.truncateA]), commitMode: .automatic, + on: Self.adapter(driver, type: .teradata) + ) + + #expect(driver.trace == ["BEGIN", Self.dropB, "COMMIT", "BEGIN", Self.truncateA, "COMMIT"]) + } + + @Test("A Teradata truncate alone is held under Manual Commit and joins an open session transaction") + func teradataTruncateAloneIsDML() async throws { + let held = TableOperationDriver() + _ = try await DataWriteExecutor.run( + Self.tableOperationPlan([Self.truncateA]), commitMode: .manual, on: Self.adapter(held, type: .teradata) + ) + #expect(held.trace == ["BEGIN", Self.truncateA]) + + let joined = TableOperationDriver(state: .inTransaction) + _ = try await DataWriteExecutor.run( + Self.tableOperationPlan([Self.truncateA]), commitMode: .automatic, on: Self.adapter(joined, type: .teradata) + ) + #expect(joined.trace == [Self.truncateA]) + } +} diff --git a/apple/TableProTests/Core/Database/AppDefinitionCommitTests.swift b/apple/TableProTests/Core/Database/AppDefinitionCommitTests.swift new file mode 100644 index 0000000000..e841072e3a --- /dev/null +++ b/apple/TableProTests/Core/Database/AppDefinitionCommitTests.swift @@ -0,0 +1,348 @@ +// +// AppDefinitionCommitTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +private final class DefinitionLedger: @unchecked Sendable { + struct Failure: Error, Equatable { + let step: String + } + + private let lock = NSLock() + private var current: PluginSessionTransactionState + private var sent: [String] = [] + + init(state: PluginSessionTransactionState = .idle) { + current = state + } + + var state: PluginSessionTransactionState { + get { lock.withLock { current } } + set { lock.withLock { current = newValue } } + } + + var calls: [String] { lock.withLock { sent } } + + func record(_ call: String) { + lock.withLock { sent.append(call) } + } +} + +struct AppDefinitionCommitTests { + private static func run( + _ ledger: DefinitionLedger, + family: TransactionEngineFamily = .teradata, + refuses: Bool = false, + commitFails: Bool = false, + body: () async throws -> Void + ) async throws { + try await AppDefinitionCommit.run( + family: family, + refusesOpenTransaction: refuses, + readState: { ledger.state }, + commit: { + // A driver's cancel handler refuses a statement sent from a cancelled task. + try Task.checkCancellation() + ledger.record("COMMIT") + if commitFails { throw DefinitionLedger.Failure(step: "COMMIT") } + ledger.state = .idle + }, + rollback: { + try Task.checkCancellation() + ledger.record("ROLLBACK") + ledger.state = .idle + }, + body: body + ) + } + + private static func definition(_ ledger: DefinitionLedger) { + ledger.record("CREATE") + ledger.state = .inTransaction + } + + @Test("A statement that leaves the session in a transaction is committed") + func commitsWhatTheStatementLeftOpen() async throws { + let ledger = DefinitionLedger() + + try await Self.run(ledger) { Self.definition(ledger) } + + #expect(ledger.calls == ["CREATE", "COMMIT"]) + #expect(ledger.state == .idle) + } + + @Test("A statement that leaves the session idle sends no commit") + func noCommitWhenIdleAfter() async throws { + let ledger = DefinitionLedger() + + try await Self.run(ledger) { ledger.record("CREATE") } + + #expect(ledger.calls == ["CREATE"]) + } + + @Test( + "On the session route an open transaction refuses the statement before it runs", + arguments: [PluginSessionTransactionState.inTransaction, .abortedTransaction] + ) + func refusesAnOpenTransactionOnTheSessionRoute(state: PluginSessionTransactionState) async throws { + let ledger = DefinitionLedger(state: state) + + await #expect(throws: DefinitionInOpenTransactionRefusal()) { + try await Self.run(ledger, refuses: true) { Self.definition(ledger) } + } + #expect(ledger.calls.isEmpty) + } + + @Test("On a pooled connection a transaction left pending is no reason to refuse, and is committed") + func pooledRouteNeverRefuses() async throws { + let ledger = DefinitionLedger(state: .inTransaction) + + try await Self.run(ledger, refuses: false) { Self.definition(ledger) } + + #expect(ledger.calls == ["CREATE", "COMMIT"]) + } + + @Test("A failed statement on an idle session is rolled back, and its own error is thrown") + func failedStatementOnAnIdleSessionRollsBack() async throws { + let ledger = DefinitionLedger() + + await #expect(throws: DefinitionLedger.Failure(step: "CREATE")) { + try await Self.run(ledger) { + ledger.record("CREATE") + throw DefinitionLedger.Failure(step: "CREATE") + } + } + #expect(ledger.calls == ["CREATE", "ROLLBACK"]) + } + + @Test("A failed statement on a session already in a transaction leaves that transaction alone") + func failedStatementInsideATransactionSendsNoRollback() async throws { + let ledger = DefinitionLedger(state: .inTransaction) + + await #expect(throws: DefinitionLedger.Failure(step: "CREATE")) { + try await Self.run(ledger) { + ledger.record("CREATE") + throw DefinitionLedger.Failure(step: "CREATE") + } + } + #expect(ledger.calls == ["CREATE"]) + } + + @Test("A commit that fails on a session idle before the statement is rolled back") + func failedCommitRollsBack() async throws { + let ledger = DefinitionLedger() + + await #expect(throws: DefinitionLedger.Failure(step: "COMMIT")) { + try await Self.run(ledger, commitFails: true) { Self.definition(ledger) } + } + #expect(ledger.calls == ["CREATE", "COMMIT", "ROLLBACK"]) + } + + @Test("An engine without the rule runs the statement as it is: no refusal, commit or rollback") + func otherFamiliesPassThrough() async throws { + let ledger = DefinitionLedger(state: .inTransaction) + + try await Self.run(ledger, family: .postgres, refuses: true) { Self.definition(ledger) } + await #expect(throws: DefinitionLedger.Failure(step: "CREATE")) { + try await Self.run(ledger, family: .other) { throw DefinitionLedger.Failure(step: "CREATE") } + } + + #expect(ledger.calls == ["CREATE"]) + } + + @Test("The commit still goes out when the task is cancelled once the statement ran") + func commitSurvivesCancellation() async throws { + let ledger = DefinitionLedger() + + let task = Task { + try await Self.run(ledger) { + Self.definition(ledger) + withUnsafeCurrentTask { $0?.cancel() } + } + } + try await task.value + + #expect(ledger.calls == ["CREATE", "COMMIT"]) + } +} + +private final class AnsiSessionDriver: PluginDriverStub, @unchecked Sendable { + private let lock = NSLock() + private var current: PluginSessionTransactionState + private var sent: [String] = [] + + init(state: PluginSessionTransactionState = .idle) { + current = state + } + + var supportsSchemas: Bool { false } + var currentSchema: String? { nil } + var serverVersion: String? { nil } + var supportsTransactions: Bool { true } + + var state: PluginSessionTransactionState { + get { lock.withLock { current } } + set { lock.withLock { current = newValue } } + } + + var statements: [String] { lock.withLock { sent } } + + // ANSI: any request opens a transaction, and only COMMIT or ROLLBACK ends it. + func execute(query: String) async throws -> PluginQueryResult { + lock.withLock { + sent.append(query) + current = query == "COMMIT" || query == "ROLLBACK" ? .idle : .inTransaction + } + return .empty + } + + func sessionTransactionState() async -> PluginSessionTransactionState { state } + + func switchDatabase(to database: String) async throws {} + + func generateCreateTableSQL(definition: PluginCreateTableDefinition) -> String? { + "CREATE TABLE \(definition.tableName) (id INTEGER)" + } +} + +@Suite(.serialized) +@MainActor +struct TeradataDefinitionCommitTests { + private static let first = "ALTER TABLE orders ADD a INTEGER;" + private static let second = "ALTER TABLE orders ADD b INTEGER;" + + private static func inject(database: String) -> (DatabaseConnection, AnsiSessionDriver) { + let connection = TestFixtures.makeConnection(database: "orders", type: .teradata) + let driver = AnsiSessionDriver() + var session = ConnectionSession( + connection: connection, + driver: PluginDriverAdapter(connection: connection, pluginDriver: driver) + ) + session.browseDatabase = database + session.status = .connected + DatabaseManager.shared.injectSession(session, for: connection.id) + return (connection, driver) + } + + private static func injectPooled(_ connection: DatabaseConnection) async throws -> (DatabaseScope, AnsiSessionDriver) { + let scope = DatabaseScope(connectionId: connection.id, database: "orders", schema: nil) + let pooled = AnsiSessionDriver() + let adapter = PluginDriverAdapter(connection: connection, pluginDriver: pooled) + try await adapter.connect() + MetadataConnectionPool.shared.injectEntry(adapter, scope: scope) + return (scope, pooled) + } + + private static func tearDown(_ connection: DatabaseConnection) { + MetadataConnectionPool.shared.closeAll(connectionId: connection.id) + DatabaseManager.shared.removeSession(for: connection.id) + } + + private static func script() -> SchemaChangeScript { + SchemaChangeScript( + tableName: "orders", + statements: [first, second].map { SchemaStatement(sql: $0, description: $0, isDestructive: false) }, + operations: [], + review: PluginSchemaChangeReview() + ) + } + + @Test("A Teradata Structure save commits each statement before the next") + func structureSaveCommitsEachStatement() async throws { + let (connection, _) = Self.inject(database: "orders") + defer { Self.tearDown(connection) } + let (scope, pooled) = try await Self.injectPooled(connection) + + try await DatabaseManager.shared.executeSchemaChanges( + Self.script(), databaseType: .teradata, scope: scope, gate: AlwaysAllowGate() + ) + + #expect(pooled.statements == [Self.first, "COMMIT", Self.second, "COMMIT"]) + #expect(pooled.state == .idle) + } + + @Test("Teradata Create Table commits each statement before the next") + func createTableCommitsEachStatement() async throws { + let (connection, _) = Self.inject(database: "orders") + defer { Self.tearDown(connection) } + let (scope, pooled) = try await Self.injectPooled(connection) + + try await DatabaseManager.shared.executeCreateTable( + statements: [Self.first, Self.second], databaseType: .teradata, scope: scope, gate: AlwaysAllowGate() + ) + + #expect(pooled.statements == [Self.first, "COMMIT", Self.second, "COMMIT"]) + } + + @Test("A Teradata Structure save on the session driver is refused while the session holds a transaction") + func sessionRouteSaveRefusedInsideAnOpenTransaction() async throws { + let (connection, driver) = Self.inject(database: "") + defer { Self.tearDown(connection) } + driver.state = .inTransaction + let scope = DatabaseScope(connectionId: connection.id, database: "", schema: nil) + + await #expect(throws: DefinitionInOpenTransactionRefusal()) { + try await DatabaseManager.shared.executeSchemaChanges( + Self.script(), databaseType: .teradata, scope: scope, gate: AlwaysAllowGate() + ) + } + #expect(driver.statements.isEmpty) + #expect(driver.state == .inTransaction) + } + + @Test("A Teradata batch import makes its new tables before it clears a reused one") + func importCreatesBeforeItClears() async throws { + let (connection, driver) = Self.inject(database: "orders") + defer { Self.tearDown(connection) } + let scope = DatabaseScope(connectionId: connection.id, database: "orders", schema: nil) + var planner = NewTableImportPlanner() + planner.recordCreated(TableScope(table: "reused", in: scope), createTableSQL: "CREATE TABLE reused (id INTEGER)") + let definitions = ["reused", "fresh"].map { + PluginCreateTableDefinition(tableName: $0, columns: [], primaryKeyColumns: []) + } + var created: [String] = [] + + _ = try await RowImportTableMaker(connection: connection, gate: AlwaysAllowGate()) + .prepare(definitions, scope: scope, planner: planner) { table, _ in created.append(table.table) } + + #expect(created == ["fresh"]) + #expect(driver.statements.count == 3) + #expect(Array(driver.statements.prefix(2)) == ["CREATE TABLE fresh (id INTEGER)", "COMMIT"]) + #expect(driver.statements.last?.hasPrefix("DELETE") == true) + } + + @Test("Teradata startup commands are committed one by one") + func startupCommandsAreCommitted() async throws { + let connection = TestFixtures.makeConnection(type: .teradata) + let driver = AnsiSessionDriver() + let adapter = PluginDriverAdapter(connection: connection, pluginDriver: driver) + let commands = "DATABASE sales\nSET SESSION DATEFORM = ANSIDATE" + let statements = DatabaseManager.startupStatements(from: commands, databaseType: .teradata) + + let failures = await DatabaseManager.shared.executeStartupCommands( + commands, on: adapter, connectionName: "Test" + ) + + #expect(failures.isEmpty) + #expect(statements.count == 2) + #expect(driver.statements == statements.flatMap { [$0, "COMMIT"] }) + #expect(driver.state == .idle) + } + + @Test("Startup commands on an engine without the rule send no commit") + func startupCommandsElsewhereSendNoCommit() async { + let connection = TestFixtures.makeConnection(type: .mysql) + let driver = AnsiSessionDriver() + let adapter = PluginDriverAdapter(connection: connection, pluginDriver: driver) + let commands = "SET NAMES utf8mb4" + + _ = await DatabaseManager.shared.executeStartupCommands(commands, on: adapter, connectionName: "Test") + + #expect(driver.statements == DatabaseManager.startupStatements(from: commands, databaseType: .mysql)) + } +} diff --git a/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift b/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift index 784e91df77..4fe71cd071 100644 --- a/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift +++ b/apple/TableProTests/Core/Database/SessionTransactionTrackerTests.swift @@ -658,7 +658,7 @@ struct SessionTransactionTrackerTests { isAborted: false, connectionName: "Prod", database: "sales", - safeModeLevel: .silent + effectiveSafeModeLevel: .silent ) #expect(open.title == "Transaction Open") #expect(open.subtitle == "sales") @@ -669,7 +669,7 @@ struct SessionTransactionTrackerTests { isAborted: false, connectionName: "Prod", database: nil, - safeModeLevel: .readOnly + effectiveSafeModeLevel: .readOnly ) #expect(!readOnly.offersCommit) #expect(readOnly.subtitle == "Prod") @@ -678,7 +678,7 @@ struct SessionTransactionTrackerTests { isAborted: true, connectionName: "Prod", database: "", - safeModeLevel: .silent + effectiveSafeModeLevel: .silent ) #expect(!aborted.offersCommit) #expect(aborted.title == "Transaction Failed") diff --git a/apple/TableProTests/Core/Menu/ManualCommitMenuTests.swift b/apple/TableProTests/Core/Menu/ManualCommitMenuTests.swift index 57a454cc2a..244921f413 100644 --- a/apple/TableProTests/Core/Menu/ManualCommitMenuTests.swift +++ b/apple/TableProTests/Core/Menu/ManualCommitMenuTests.swift @@ -108,13 +108,12 @@ struct ManualCommitMenuTests { #expect(enabled(commit, context)) } - @Test("Commit is offered for an open hold below Read-Only, never for an aborted one") + // The level is the gate's, managed floor included, so Commit is never offered for the gate to refuse. + @Test("Commit is offered for an open hold below the effective Read-Only, never for an aborted one") func commitFollowsSafeModeAndState() { - let key = SessionTransactionTracker.Key(connectionId: UUID(), lane: nil) - let open = SessionTransactionTracker.Hold(key: key, state: .open, revision: 1) - let aborted = SessionTransactionTracker.Hold(key: key, state: .aborted, revision: 1) - #expect(ConnectionTransactionActions.offersCommit(open, safeModeLevel: .silent)) - #expect(!ConnectionTransactionActions.offersCommit(open, safeModeLevel: .readOnly)) - #expect(!ConnectionTransactionActions.offersCommit(aborted, safeModeLevel: .silent)) + #expect(ConnectionTransactionActions.offersCommit(.open, effectiveLevel: .silent)) + #expect(ConnectionTransactionActions.offersCommit(.open, effectiveLevel: .safeModeFull)) + #expect(!ConnectionTransactionActions.offersCommit(.open, effectiveLevel: .readOnly)) + #expect(!ConnectionTransactionActions.offersCommit(.aborted, effectiveLevel: .silent)) } } diff --git a/apple/TableProTests/Core/Operations/RunningWorkTests.swift b/apple/TableProTests/Core/Operations/RunningWorkTests.swift index 2b223d8bb4..4486651f38 100644 --- a/apple/TableProTests/Core/Operations/RunningWorkTests.swift +++ b/apple/TableProTests/Core/Operations/RunningWorkTests.swift @@ -121,13 +121,13 @@ struct RunningWorkTests { let prompt = try #require(RunningWorkPrompt.make( action: .close, work: [work(.restore, subject: "sales"), work(.query, subject: "Query 2")], - otherLosses: RunningWorkPrompt.transactionLines(for: ["app"]) + otherLosses: ["Unsaved changes"] )) #expect(prompt.message.hasPrefix(""" Restoring “sales” on Production Running query in “Query 2” on Production - Open transaction in “app” + Unsaved changes Closing stops this work. """)) @@ -151,13 +151,18 @@ struct RunningWorkTests { """) } - @Test("The quit a relaunch starts stops the approved work without asking again") - func relaunchApprovedQuitStopsWork() { + // The work is stopped by the quit once its commits landed, never by the approval. + @Test("The quit a relaunch starts asks nothing and plans the approved work's stop") + func relaunchApprovedQuitStopsWork() throws { var stopped = 0 let registry = RunningWorkRegistry(providers: []) registry.begin(.restore, subject: "sales", connectionName: "", connectionIds: []) { stopped += 1 } - #expect(QuitApproval.approve(registry: registry, relaunchApproved: true)) + let plan = try #require(QuitApproval.approve(registry: registry, relaunchApproved: true)) + #expect(plan.commits.isEmpty) + #expect(stopped == 0) + + registry.cancel(plan.work) #expect(stopped == 1) } diff --git a/apple/TableProTests/Core/Services/Execution/AutocommitOnlyStatementTests.swift b/apple/TableProTests/Core/Services/Execution/AutocommitOnlyStatementTests.swift index 2322218c1e..3f3173c46e 100644 --- a/apple/TableProTests/Core/Services/Execution/AutocommitOnlyStatementTests.swift +++ b/apple/TableProTests/Core/Services/Execution/AutocommitOnlyStatementTests.swift @@ -413,6 +413,8 @@ struct AutocommitOnlyStatementTeradataTests { "SET SESSION DATABASE sales", "SET SESSION DATEFORM = ANSIDATE", "SET QUERY_BAND = 'app=tp;' FOR SESSION", + "SET QUERY_BAND = 'app=tp;' UPDATE FOR SESSION VOLATILE", + "SET QUERY_BAND = NONE FOR SESSION", "SET ROLE analyst", "SET TIME ZONE LOCAL", "MODIFY USER u AS PERM = 1e9", @@ -453,9 +455,46 @@ struct AutocommitOnlyStatementTeradataTests { "CHECKPOINT sales.j", "LOCKING ROW FOR ACCESS SELECT * FROM sales.t", "SELECT 'CREATE TABLE t (a INTEGER)'", + "SET QUERY_BAND = 'a=1;' FOR TRANSACTION", + "set query_band = 'job=nightly;' for transaction;", + "SET QUERY_BAND = NONE FOR TRANSACTION", ] ) func teradataAcceptances(statement: String) { #expect(!AutocommitOnlyFixture.matches(statement, .teradata)) } + + private static func movesDatabase(_ statement: String, _ family: TransactionEngineFamily = .teradata) -> Bool { + AutocommitOnlyStatement.movesDatabase( + statement, family: family, grammar: AutocommitOnlyFixture.grammar(for: family) + ) + } + + @Test( + "These move the session's default database", + arguments: [ + "DATABASE sales", "database sales;", "SET SESSION DATABASE sales", "SS DATABASE sales", + "-- switch\nDATABASE sales", + ] + ) + func teradataDatabaseMoves(statement: String) { + #expect(Self.movesDatabase(statement)) + } + + @Test( + "These leave the default database where it is", + arguments: [ + "SET SESSION DATEFORM = ANSIDATE", "DELETE DATABASE sales", "CREATE DATABASE d FROM sales AS PERM = 1e6", + "SELECT DATABASE", "SS", "SET SESSION", "MODIFY DATABASE sales AS PERM = 1e9", + ] + ) + func teradataNonMoves(statement: String) { + #expect(!Self.movesDatabase(statement)) + } + + @Test("A database move is read only on Teradata") + func databaseMoveIsTeradataOnly() { + #expect(!Self.movesDatabase("DATABASE sales", .postgres)) + #expect(!Self.movesDatabase("SET SESSION DATABASE sales", .mysql)) + } } diff --git a/apple/TableProTests/Core/Services/Execution/BatchCommitStatementTests.swift b/apple/TableProTests/Core/Services/Execution/BatchCommitStatementTests.swift index 687173ca76..f0abccfd27 100644 --- a/apple/TableProTests/Core/Services/Execution/BatchCommitStatementTests.swift +++ b/apple/TableProTests/Core/Services/Execution/BatchCommitStatementTests.swift @@ -38,6 +38,16 @@ struct BatchCommitStatementTests { #expect(Self.matches(sql)) } + @Test("Teradata's ET is a commit point", arguments: ["ET", "et", "ET;", "-- done\nET"]) + func teradataETIsACommitPoint(sql: String) { + #expect(Self.matches(sql, type: .teradata)) + } + + @Test("ET followed by anything is not ET") + func etWithAFollowerIsNotACommitPoint() { + #expect(Self.matches("ET AL", type: .teradata) == false) + } + /// A block terminator is never a transaction's end, whichever engine wrote it. @Test( "END that closes a block is not a commit point", @@ -83,3 +93,31 @@ struct BatchCommitStatementTests { #expect(Self.matches("/*!40101 COMMIT */", type: .mysql)) } } + +struct TransactionEndStatementTests { + private static func matches(_ sql: String) -> Bool { + TransactionEndStatement.matches(sql, grammar: DatabaseType.teradata.lexicalGrammar) + } + + @Test( + "A commit or a rollback ends the transaction", + arguments: [ + "COMMIT", "COMMIT WORK", "ET", "END TRANSACTION", "ROLLBACK", "ROLLBACK WORK", "rollback;", "ABORT", + "ABORT 'bad load' WHERE 1 = 1", + ] + ) + func endsTheTransaction(sql: String) { + #expect(Self.matches(sql)) + } + + @Test( + "Anything else leaves it open", + arguments: [ + "ROLLBACK TO SAVEPOINT s", "BT", "BEGIN TRANSACTION", "INSERT INTO t VALUES (1)", "SELECT 'ROLLBACK'", + "CREATE TABLE t (a INTEGER)", "", + ] + ) + func leavesTheTransactionOpen(sql: String) { + #expect(Self.matches(sql) == false) + } +} diff --git a/apple/TableProTests/Core/Services/Execution/BatchStatementRunTests.swift b/apple/TableProTests/Core/Services/Execution/BatchStatementRunTests.swift index d29ac4858a..c9fb0067c7 100644 --- a/apple/TableProTests/Core/Services/Execution/BatchStatementRunTests.swift +++ b/apple/TableProTests/Core/Services/Execution/BatchStatementRunTests.swift @@ -20,7 +20,10 @@ struct BatchStatementRunTests { commitPoints: Set = [], failing: String? = nil, stopsAfter: Int = .max, - commitOutput: ServerOutputBox = ServerOutputBox() + commitOutput: ServerOutputBox = ServerOutputBox(), + endsItsTransaction: (String) -> Bool = { _ in false }, + closesTransaction: (String) -> Bool = { _ in false }, + movesDatabase: (String) -> Bool = { _ in false } ) async -> BatchStatementOutcome { let claims = probe ?? ClaimProbe() return await BatchStatementRun.run( @@ -32,6 +35,9 @@ struct BatchStatementRunTests { gate: claims.gate, failureSQL: { $0 }, isCommitPoint: { commitPoints.contains($0) }, + endsItsTransaction: endsItsTransaction, + closesTransaction: closesTransaction, + movesDatabase: movesDatabase, commitOutput: commitOutput ) { statement in if claims.recordExecution() == stopsAfter { claims.stop() } @@ -599,6 +605,318 @@ struct BatchStatementRunTests { return } } + + // MARK: - A statement the session takes nothing after but the end of its transaction + + private static let create = "CREATE MULTISET TABLE sales.t (id INTEGER) PRIMARY INDEX (id)" + private static let insert = "INSERT INTO sales.t VALUES (1)" + + nonisolated private static func teradataDefinition(_ sql: String) -> Bool { + AutocommitOnlyStatement.matches(sql, family: .teradata, grammar: DatabaseType.teradata.lexicalGrammar) + } + + nonisolated private static func teradataEnd(_ sql: String) -> Bool { + TransactionEndStatement.matches(sql, grammar: DatabaseType.teradata.lexicalGrammar) + } + + nonisolated private static func teradataMove(_ sql: String) -> Bool { + AutocommitOnlyStatement.movesDatabase(sql, family: .teradata, grammar: DatabaseType.teradata.lexicalGrammar) + } + + private static func runTeradata( + _ statements: [String], + plan: BatchTransactionPlan = .autocommit, + driver: TransactionRecordingDriver, + probe: ClaimProbe? = nil, + stopsAfter: Int = .max + ) async -> BatchStatementOutcome { + await Self.run( + plan: plan, + driver: driver, + probe: probe, + statements: statements, + stopsAfter: stopsAfter, + endsItsTransaction: teradataDefinition, + closesTransaction: teradataEnd, + movesDatabase: teradataMove + ) + } + + // Error 3722 in ANSI mode; inside BT, Failure 3932 would roll back the whole block. + @Test("A run stops after DDL the session holds open, before the next statement, and keeps the DDL's result") + func stopsAfterADefinitionTheSessionHolds() async { + let driver = TransactionRecordingDriver() + driver.sessionState = .inTransaction + + let outcome = await Self.runTeradata([Self.create, Self.insert], driver: driver) + + #expect(driver.events.isEmpty) + #expect(driver.executedQueries == [Self.create]) + guard case .failed(let results, let failure, let description) = outcome else { + Issue.record("expected a stopped run, got \(outcome)") + return + } + #expect(results.count == 1) + #expect(failure == .awaitsCommit(sql: Self.create)) + #expect(description.isEmpty) + #expect(outcome.succeededCount == 1) + #expect(outcome.ranCount(of: 2) == 1) + } + + @Test( + "The stop commits nothing and rolls nothing back, whatever the plan", + arguments: [BatchTransactionPlan.autocommit, .scriptTransaction, .sessionTransaction, .heldTransaction, .appTransaction] + ) + func theStopLeavesTheTransactionOpen(plan: BatchTransactionPlan) async { + let driver = TransactionRecordingDriver() + driver.sessionState = .inTransaction + + let outcome = await Self.runTeradata([Self.create, Self.insert], plan: plan, driver: driver) + + #expect(!driver.events.contains(.commit)) + #expect(!driver.events.contains(.rollback)) + guard case .failed(_, .awaitsCommit, _) = outcome else { + Issue.record("expected a stopped run, got \(outcome)") + return + } + } + + @Test( + "A run carries on when the next statement ends the transaction", + arguments: ["COMMIT WORK", "COMMIT", "ROLLBACK", "ROLLBACK WORK", "ABORT", "ET", "END TRANSACTION"] + ) + func carriesOnIntoTheTransactionEnd(end: String) async { + let driver = TransactionRecordingDriver() + driver.sessionState = .inTransaction + + let outcome = await Self.runTeradata([Self.create, end, Self.insert], driver: driver) + + #expect(driver.executedQueries == [Self.create, end, Self.insert]) + #expect(outcome.isCompleted) + } + + // Teradata mode outside BT commits each request itself, and an unresolved mode cannot say. + @Test( + "A run carries on when the session holds no transaction after the DDL", + arguments: [PluginSessionTransactionState.idle, .unknown] + ) + func carriesOnWhenNothingIsHeld(state: PluginSessionTransactionState) async { + let driver = TransactionRecordingDriver() + driver.sessionState = state + + let outcome = await Self.runTeradata([Self.create, Self.insert], driver: driver) + + #expect(driver.executedQueries == [Self.create, Self.insert]) + #expect(outcome.isCompleted) + } + + @Test("A run whose engine has no such rule carries on past DDL") + func carriesOnWithoutTheRule() async { + let driver = TransactionRecordingDriver() + driver.sessionState = .inTransaction + + let outcome = await Self.run(plan: .autocommit, driver: driver, statements: [Self.create, Self.insert]) + + #expect(driver.executedQueries == [Self.create, Self.insert]) + #expect(outcome.isCompleted) + } + + @Test("DDL as the last statement completes the run") + func definitionLastCompletes() async { + let driver = TransactionRecordingDriver() + driver.sessionState = .inTransaction + + let outcome = await Self.runTeradata([Self.insert, Self.create], driver: driver) + + #expect(driver.executedQueries == [Self.insert, Self.create]) + #expect(outcome.isCompleted) + } + + @Test("The stop reads the statement a replan put next") + func theStopReadsTheReplannedStatement() async { + let driver = TransactionRecordingDriver() + driver.sessionState = .inTransaction + let claims = ClaimProbe() + + let outcome = await BatchStatementRun.run( + [Self.create, Self.insert], + plan: .autocommit, + mode: .readWrite, + driver: driver, + connectionId: claims.connectionId, + gate: claims.gate, + failureSQL: { $0 }, + isCommitPoint: { _ in false }, + endsItsTransaction: Self.teradataDefinition, + closesTransaction: Self.teradataEnd, + replanned: { ran in ran == 1 ? ["COMMIT WORK", Self.insert] : nil } + ) { statement in + try await driver.execute(query: statement) + } + + #expect(driver.executedQueries == [Self.create, "COMMIT WORK", Self.insert]) + #expect(outcome.isCompleted) + } + + // A Stop that lands on the DDL is a Stop: the plan takes back what it opened. + @Test("A Stop during the DDL is reported as a Stop, not as a wait for the commit") + func aStopDuringTheDefinitionWins() async { + let driver = TransactionRecordingDriver() + driver.sessionState = .inTransaction + + let outcome = await Self.runTeradata( + ["BT", Self.create, Self.insert], plan: .scriptTransaction, driver: driver, stopsAfter: 2 + ) + + #expect(driver.events == [.rollback]) + #expect(driver.executedQueries == ["BT", Self.create]) + guard case .cancelled = outcome else { + Issue.record("expected a cancelled run, got \(outcome)") + return + } + } + + // MARK: - A statement that moves the session's database + + private static let move = "DATABASE sales_dev" + private static let delete = "DELETE FROM orders" + + // A new run is pinned back to the tab's database, so the DELETE would land in the wrong one. + @Test( + "A run stops before a database move while the session holds a transaction, and sends nothing of it", + arguments: [BatchTransactionPlan.autocommit, .scriptTransaction, .sessionTransaction] + ) + func stopsBeforeAMoveInsideATransaction(plan: BatchTransactionPlan) async { + let driver = TransactionRecordingDriver() + driver.sessionState = .inTransaction + + let outcome = await Self.runTeradata([Self.insert, Self.move, Self.delete], plan: plan, driver: driver) + + #expect(driver.executedQueries == [Self.insert]) + #expect(driver.events.isEmpty) + guard case .failed(let results, let failure, let description) = outcome else { + Issue.record("expected a stopped run, got \(outcome)") + return + } + #expect(results.count == 1) + #expect(failure == .databaseMoveAwaitsCommit(sql: Self.move)) + #expect(description.isEmpty) + #expect(outcome.ranCount(of: 3) == 1) + } + + @Test( + "Every spelling of a move stops inside a transaction", + arguments: ["DATABASE sales_dev", "SET SESSION DATABASE sales_dev", "SS DATABASE sales_dev"] + ) + func everyMoveSpellingStops(move: String) async { + let driver = TransactionRecordingDriver() + driver.sessionState = .inTransaction + + let outcome = await Self.runTeradata([move, Self.delete], driver: driver) + + #expect(driver.executedQueries.isEmpty) + guard case .failed(_, .databaseMoveAwaitsCommit(let sql), _) = outcome else { + Issue.record("expected a stopped run, got \(outcome)") + return + } + #expect(sql == move) + } + + // ANSI opens a transaction for the move alone; the app's own switch commits it the same way. + @Test("A move on an idle session is committed at once, and the run carries on in the same run") + func moveOnAnIdleSessionIsCommitted() async { + let probe = ClaimProbe() + let driver = TransactionRecordingDriver() + driver.sessionState = .idle + driver.stateAfterStatement = [Self.move: .inTransaction] + driver.stateAfterCommit = .idle + + let outcome = await Self.runTeradata([Self.move, Self.delete], driver: driver, probe: probe) + + #expect(driver.executedQueries == [Self.move, Self.delete]) + #expect(driver.events == [.commit]) + #expect(probe.commitPhaseEntries == 1) + #expect(probe.commitPhaseExits == 1) + #expect(probe.isStoppable) + guard case .completed(let results) = outcome else { + Issue.record("expected a completed run, got \(outcome)") + return + } + #expect(results.count == 2) + } + + @Test("A move that leaves the session idle is not committed") + func moveThatOpensNothingIsLeftAlone() async { + let driver = TransactionRecordingDriver() + driver.sessionState = .idle + + let outcome = await Self.runTeradata([Self.move, Self.delete], driver: driver) + + #expect(driver.executedQueries == [Self.move, Self.delete]) + #expect(driver.events.isEmpty) + #expect(outcome.isCompleted) + } + + @Test("A move's commit the server refused fails the run at the move") + func refusedMoveCommitFailsTheRun() async { + let driver = TransactionRecordingDriver(failsCommit: true) + driver.sessionState = .idle + driver.stateAfterStatement = [Self.move: .inTransaction] + + let outcome = await Self.runTeradata([Self.move, Self.delete], driver: driver) + + #expect(driver.executedQueries == [Self.move]) + #expect(driver.events == [.commit]) + guard case .failed(let results, let failure, _) = outcome else { + Issue.record("expected a failed run, got \(outcome)") + return + } + #expect(results.isEmpty) + #expect(failure == .statement(sql: Self.move)) + } + + @Test("A move on a session that cannot say what it holds runs as before") + func moveOnAnUnknownSessionRunsAsBefore() async { + let driver = TransactionRecordingDriver() + driver.sessionState = .unknown + + let outcome = await Self.runTeradata([Self.move, Self.delete], driver: driver) + + #expect(driver.executedQueries == [Self.move, Self.delete]) + #expect(driver.events.isEmpty) + #expect(outcome.isCompleted) + } + + @Test("A run whose engine has no such rule runs a move inside a transaction") + func moveWithoutTheRuleRuns() async { + let driver = TransactionRecordingDriver() + driver.sessionState = .inTransaction + + let outcome = await Self.run(plan: .autocommit, driver: driver, statements: [Self.insert, Self.move, Self.delete]) + + #expect(driver.executedQueries == [Self.insert, Self.move, Self.delete]) + #expect(driver.events.isEmpty) + #expect(outcome.isCompleted) + } + + @Test("A stop after DDL that follows a move names the move, which a new run has to repeat") + func stopAfterAMoveNamesTheMove() async { + let driver = TransactionRecordingDriver() + driver.sessionState = .idle + driver.stateAfterStatement = [Self.move: .inTransaction, Self.create: .inTransaction] + driver.stateAfterCommit = .idle + + let outcome = await Self.runTeradata([Self.move, Self.create, Self.delete], driver: driver) + + #expect(driver.executedQueries == [Self.move, Self.create]) + #expect(driver.events == [.commit]) + guard case .failed(let results, let failure, _) = outcome else { + Issue.record("expected a stopped run, got \(outcome)") + return + } + #expect(results.count == 2) + #expect(failure == .awaitsCommit(sql: Self.create, databaseMove: Self.move)) + } } private enum TestError: Error { @@ -717,6 +1035,11 @@ private final class TransactionRecordingDriver: DatabaseDriver, @unchecked Senda private(set) var cancelCount = 0 private(set) var commitSawCancellation = false private(set) var rollbackSawCancellation = false + private(set) var executedQueries: [String] = [] + var sessionState: PluginSessionTransactionState = .unknown + // What the session holds once a statement of this text ran, and once a commit went through. + var stateAfterStatement: [String: PluginSessionTransactionState] = [:] + var stateAfterCommit: PluginSessionTransactionState? /// What each statement the run executes through this driver should throw, by its text. Only the /// commit-point cases use it: everything else fails through the run's own closure. @@ -753,6 +1076,7 @@ private final class TransactionRecordingDriver: DatabaseDriver, @unchecked Senda if let hook = whileCommitting { await MainActor.run { hook() } } commitSawCancellation = commitSawCancellation || Task.isCancelled if failsCommit { throw commitError } + if let stateAfterCommit { sessionState = stateAfterCommit } } func rollbackTransaction() async throws { @@ -769,10 +1093,16 @@ private final class TransactionRecordingDriver: DatabaseDriver, @unchecked Senda return serverOutputs.isEmpty ? .none : serverOutputs.removeFirst() } + func sessionTransactionState() async -> PluginSessionTransactionState { + sessionState + } + func execute(query: String) async throws -> QueryResult { executedStatements += 1 + executedQueries.append(query) if executedStatements == 1, let hook = whileExecuting { await MainActor.run { hook() } } if let error = failingStatements[query] { throw error } + if let next = stateAfterStatement[query] { sessionState = next } return .empty } diff --git a/apple/TableProTests/Core/Services/Execution/BatchTransactionPolicyTests.swift b/apple/TableProTests/Core/Services/Execution/BatchTransactionPolicyTests.swift index f088b1728b..177584a048 100644 --- a/apple/TableProTests/Core/Services/Execution/BatchTransactionPolicyTests.swift +++ b/apple/TableProTests/Core/Services/Execution/BatchTransactionPolicyTests.swift @@ -265,6 +265,21 @@ struct BatchTransactionPolicyTests { #expect(Self.plan(["BEGIN TRANSACTION", "INSERT INTO t VALUES (1)", "END TRANSACTION"], .teradata) == .scriptTransaction) } + // A wrap around BT would nest it, so its ET would close only the inner level. + @Test("BT opens a Teradata script's own transaction, and nothing on another engine") + func teradataBTIsTransactionControl() { + #expect(Self.plan(["BT", "INSERT INTO t VALUES (1)", "ET"], .teradata) == .scriptTransaction) + #expect(Self.plan(["bt;", "CREATE TABLE t (a INTEGER)", "ET"], .teradata) == .scriptTransaction) + #expect(Self.plan(["BT", "INSERT INTO t VALUES (1)"], .postgresql) == .appTransaction) + } + + // SET QUERY_BAND ... FOR TRANSACTION is DML, legal inside the wrap. + @Test("A transaction query band keeps a Teradata batch wrapped, and a session one does not") + func teradataQueryBandScope() { + #expect(Self.plan(["SET QUERY_BAND = 'job=x;' FOR TRANSACTION", "UPDATE t SET a = 1"], .teradata) == .appTransaction) + #expect(Self.plan(["SET QUERY_BAND = 'job=x;' FOR SESSION", "UPDATE t SET a = 1"], .teradata) == .autocommit) + } + @Test("A SQLite savepoint opens a transaction, so the script owns it after all") func savepointAfterAnUnwrappingStatement() { #expect(Self.plan(["VACUUM", "SAVEPOINT a", "INSERT INTO t VALUES (1)"], .sqlite) == .scriptTransaction) diff --git a/apple/TableProTests/Core/Services/Execution/MultiStatementFailureTests.swift b/apple/TableProTests/Core/Services/Execution/MultiStatementFailureTests.swift index 91e157e6e9..98bf4eca5a 100644 --- a/apple/TableProTests/Core/Services/Execution/MultiStatementFailureTests.swift +++ b/apple/TableProTests/Core/Services/Execution/MultiStatementFailureTests.swift @@ -370,4 +370,134 @@ struct MultiStatementFailureTests { #expect(MultiStatementFailure.batch(sql: "x").ranStatementCount(executedCount: 2, totalCount: 3) == 2) #expect(MultiStatementFailure.statement(sql: "x").ranStatementCount(executedCount: 2, totalCount: 3) == 3) } + + // MARK: - A run stopped to wait for the commit + + @Test( + "A run stopped after DDL tells the user to commit, and names the statement it stopped before", + arguments: [BatchTransactionPlan.autocommit, .sessionTransaction] + ) + func awaitsCommitTellsTheUserToCommit(plan: BatchTransactionPlan) { + let report = Self.report( + .awaitsCommit(sql: "CREATE TABLE t (a INTEGER)"), + executed: 2, + total: 4, + error: "", + plan: plan, + sessionState: .inTransaction + ) + #expect(report.message == """ + Statement 2/4 is a DDL statement, and the session takes nothing after it but COMMIT or ROLLBACK. \ + The run stopped before statement 3. Click Commit on the Transaction Open bar, then run the rest. + """) + #expect(!report.message.contains("still open")) + #expect(!report.message.localizedCaseInsensitiveContains("failed")) + #expect(report.resultLabel == "Stopped") + #expect(report.failedStatementIndex == 2) + #expect(report.failedSQL == nil) + } + + @Test("A run stopped to wait for the commit counts only the statements that ran") + func awaitsCommitCountsWhatRan() { + #expect(MultiStatementFailure.awaitsCommit(sql: "x").ranStatementCount(executedCount: 2, totalCount: 4) == 2) + #expect( + MultiStatementFailure.databaseMoveAwaitsCommit(sql: "DATABASE y").ranStatementCount(executedCount: 1, totalCount: 3) + == 1 + ) + } + + // A new run is pinned back to the tab's database, so the rest needs the move again. + @Test("A stop after DDL that followed a database move says to begin the rest with the move") + func awaitsCommitAfterAMoveNamesTheMove() { + let report = Self.report( + .awaitsCommit(sql: "CREATE TABLE t (a INTEGER)", databaseMove: " DATABASE sales_dev\n"), + executed: 3, + total: 5, + error: "", + plan: .autocommit, + sessionState: .inTransaction + ) + #expect(report.message == """ + Statement 3/5 is a DDL statement, and the session takes nothing after it but COMMIT or ROLLBACK. \ + The run stopped before statement 4. Click Commit on the Transaction Open bar. A new run starts in \ + the tab's database, so begin the rest with “DATABASE sales_dev”. + """) + #expect(report.resultLabel == "Stopped") + #expect(report.failedStatementIndex == 3) + #expect(report.failedSQL == nil) + } + + @Test( + "A run stopped before a database move says to end the transaction and run again from the move", + arguments: [BatchTransactionPlan.autocommit, .sessionTransaction] + ) + func databaseMoveTellsTheUserToEndTheTransaction(plan: BatchTransactionPlan) { + let report = Self.report( + .databaseMoveAwaitsCommit(sql: "DATABASE sales_dev"), + executed: 1, + total: 3, + error: "", + plan: plan, + sessionState: .inTransaction + ) + #expect(report.message == """ + Statement 2/3 moves the session to another database, which this session takes only outside a \ + transaction. The run stopped before it. Click Commit or Roll Back on the Transaction Open bar, then run \ + the script again from statement 2. + """) + #expect(!report.message.contains("still open")) + #expect(!report.message.localizedCaseInsensitiveContains("failed")) + #expect(report.resultLabel == "Stopped") + #expect(report.failedStatementIndex == 1) + #expect(report.failedSQL == nil) + } + + // The script's own BT would be left behind by a rerun from the move, and its ET would then fail. + @Test("A stop before a database move inside the script's BT says to roll back and move it above the BT") + func databaseMoveInsideTheScriptsBlock() { + let report = Self.report( + .databaseMoveAwaitsCommit(sql: "DATABASE sales_dev"), + executed: 2, + total: 4, + error: "", + plan: .scriptTransaction, + sessionState: .inTransaction + ) + #expect(report.message == """ + Statement 3/4 moves the session to another database, which this session takes only outside a \ + transaction. The run stopped before it. Click Roll Back on the Transaction Open bar, move the statement \ + above the script's BT, then run the script again from there. + """) + #expect(report.resultLabel == "Stopped") + #expect(report.failedStatementIndex == 2) + #expect(report.failedSQL == nil) + } + + // The rest has to open the block again, or its ET would end one the app opened around it. + @Test("A stop after DDL inside the script's BT says to begin the rest with BT, after the move if there was one") + func awaitsCommitInsideTheScriptsBlock() { + let plain = Self.report( + .awaitsCommit(sql: "CREATE TABLE t (a INTEGER)"), + executed: 2, + total: 4, + error: "", + plan: .scriptTransaction, + sessionState: .inTransaction + ) + #expect(plain.message == """ + Statement 2/4 is a DDL statement, and the session takes nothing after it but COMMIT or ROLLBACK. \ + The run stopped before statement 3. Click Commit on the Transaction Open bar, then begin the rest with \ + “BT”. + """) + let moved = Self.report( + .awaitsCommit(sql: "CREATE TABLE t (a INTEGER)", databaseMove: "DATABASE sales_dev;"), + executed: 3, + total: 5, + error: "", + plan: .scriptTransaction, + sessionState: .inTransaction + ) + #expect(moved.message.hasSuffix("then begin the rest with “DATABASE sales_dev; BT”.")) + #expect(moved.failedStatementIndex == 3) + } } diff --git a/apple/TableProTests/Core/Services/Execution/TransactionEngineFamilyTests.swift b/apple/TableProTests/Core/Services/Execution/TransactionEngineFamilyTests.swift index 181e681d0b..45c3e2c438 100644 --- a/apple/TableProTests/Core/Services/Execution/TransactionEngineFamilyTests.swift +++ b/apple/TableProTests/Core/Services/Execution/TransactionEngineFamilyTests.swift @@ -74,6 +74,14 @@ struct TransactionEngineFamilyTests { } } + @Test("Only Teradata ends a transaction at a definition statement and keeps unwrapped work open") + func teradataAloneHoldsDefinitionsAndUnwrappedWork() { + for family in TransactionEngineFamily.allCases { + #expect(family.definitionEndsTransaction == (family == .teradata)) + #expect(family.unwrappedWorkStaysOpen == (family == .teradata)) + } + } + @Test("Redis has rules of its own, so it is not the fallback") func redisIsItsOwnFamily() { #expect(TransactionEngineFamily.of(.redis) == .redis) diff --git a/apple/TableProTests/Core/Services/Infrastructure/ConnectionCloseActionTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ConnectionCloseActionTests.swift index 82b2d215b0..ef18231f34 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ConnectionCloseActionTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ConnectionCloseActionTests.swift @@ -9,83 +9,52 @@ import Testing @MainActor struct ConnectionCloseActionTests { - /// The case the old command failed on. A connection the window hosts but that has no session - /// yet still has a rail row, and Close on it resolved no coordinator and returned in silence. - /// There is nothing to lose there, so it closes without asking rather than doing nothing. + // A connection the window hosts with no session yet still has a rail row; Close on it once did nothing. @Test("A connection with no session closes without asking") func sessionlessClosesImmediately() { #expect( - ConnectionCloseAction.decision(hasSession: false, holdsTransaction: false, hasUnsavedWork: false) == .closeImmediately + ConnectionCloseAction.decision(hasSession: false, hasRunningWork: false, hasUnsavedWork: false) == .closeImmediately ) } - /// Unsaved work reported for a connection that has no session cannot be acted on, so it must - /// not gate the close behind an alert whose Save button has nothing to call. @Test("Unsaved work without a session still closes without asking") func sessionlessIgnoresUnsavedWork() { #expect( - ConnectionCloseAction.decision(hasSession: false, holdsTransaction: false, hasUnsavedWork: true) == .closeImmediately + ConnectionCloseAction.decision(hasSession: false, hasRunningWork: false, hasUnsavedWork: true) == .closeImmediately ) } - @Test("A clean connection closes without asking") - func cleanSessionClosesImmediately() { + @Test("Running work is asked about even without a session") + func sessionlessStillAsksAboutRunningWork() { #expect( - ConnectionCloseAction.decision(hasSession: true, holdsTransaction: false, hasUnsavedWork: false) == .closeImmediately + ConnectionCloseAction.decision(hasSession: false, hasRunningWork: true, hasUnsavedWork: false) == .confirmRunningWork ) } - @Test("A connection with unsaved work asks first") - func unsavedWorkIsConfirmed() { + // The transaction is read after the answers, so with nothing else to ask it is the next step. + @Test("A clean connection goes straight to the transaction step") + func cleanSessionReadsTheTransaction() { #expect( - ConnectionCloseAction.decision(hasSession: true, holdsTransaction: false, hasUnsavedWork: true) == .confirmUnsavedWork + ConnectionCloseAction.decision(hasSession: true, hasRunningWork: false, hasUnsavedWork: false) + == .confirmEndingTransaction ) } - /// Closing ends the session connection, and the server rolls back what it was holding. - @Test("A connection holding an open transaction asks first") - func openTransactionIsConfirmed() { + @Test("Running work with nothing unsaved gets its own alert") + func runningWorkIsConfirmed() { #expect( - ConnectionCloseAction.decision(hasSession: true, holdsTransaction: true, hasUnsavedWork: false) - == .confirmEndingTransaction + ConnectionCloseAction.decision(hasSession: true, hasRunningWork: true, hasUnsavedWork: false) == .confirmRunningWork ) } - /// Save on the unsaved-work alert writes at once, so the transaction has to be asked about - /// while a Cancel can still leave everything as it was. - @Test("An open transaction is asked about before unsaved work") - func openTransactionComesBeforeUnsavedWork() { + // A Save under Manual Commit writes into a held transaction, which the close must still ask about after it. + @Test("Unsaved work is asked before the transaction, and names the running work on the same alert") + func unsavedWorkComesFirst() { #expect( - ConnectionCloseAction.decision(hasSession: true, holdsTransaction: true, hasUnsavedWork: true) - == .confirmEndingTransaction + ConnectionCloseAction.decision(hasSession: true, hasRunningWork: false, hasUnsavedWork: true) == .confirmUnsavedWork ) - } - - @Test("A transaction reported without a session still closes without asking") - func sessionlessIgnoresTransaction() { #expect( - ConnectionCloseAction.decision(hasSession: false, holdsTransaction: true, hasUnsavedWork: true) - == .closeImmediately + ConnectionCloseAction.decision(hasSession: true, hasRunningWork: true, hasUnsavedWork: true) == .confirmUnsavedWork ) } - - @Test("No open transaction adds nothing to the close prompt") - func noTransactionNoMessage() { - #expect(ConnectionCloseAction.transactionMessage(for: []) == nil) - } - - @Test("One open transaction names its database") - func oneTransactionNamesTheDatabase() throws { - let message = try #require(ConnectionCloseAction.transactionMessage(for: ["app"])) - #expect(message.contains("“app”")) - #expect(message.contains("Closing rolls it back")) - } - - @Test("Several open transactions list every database") - func severalTransactionsListEveryDatabase() throws { - let message = try #require(ConnectionCloseAction.transactionMessage(for: ["app", "logs"])) - #expect(message.contains("“app”")) - #expect(message.contains("“logs”")) - #expect(message.contains("Closing rolls them back")) - } } diff --git a/apple/TableProTests/Core/Services/Infrastructure/ConnectionDisconnectActionTests.swift b/apple/TableProTests/Core/Services/Infrastructure/ConnectionDisconnectActionTests.swift index 9b5ba01fe5..6446cea1ec 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/ConnectionDisconnectActionTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/ConnectionDisconnectActionTests.swift @@ -9,44 +9,20 @@ import Testing @MainActor struct ConnectionDisconnectActionTests { - @Test("No open transaction adds nothing to the disconnect prompt") - func noTransactionNoMessage() { - #expect(ConnectionDisconnectAction.transactionMessage(for: []) == nil) - } - - @Test("One open transaction names its database") - func oneTransactionNamesTheDatabase() throws { - let message = try #require(ConnectionDisconnectAction.transactionMessage(for: ["app"])) - #expect(message.contains("“app”")) - #expect(message.contains("Disconnecting rolls it back")) - } - - @Test("Several open transactions list every database") - func severalTransactionsListEveryDatabase() throws { - let message = try #require(ConnectionDisconnectAction.transactionMessage(for: ["app", "logs"])) - #expect(message.contains("“app”")) - #expect(message.contains("“logs”")) - #expect(message.contains("Disconnecting rolls them back")) - } - @Test("A clean connection disconnects without asking") func cleanConnectionAsksNothing() { - #expect(ConnectionDisconnectAction.confirmationMessage(holdingTransaction: [], hasUnsavedWork: false) == nil) - #expect(ConnectionDisconnectAction.otherLosses(holdingTransaction: [], hasUnsavedWork: false).isEmpty) + #expect(ConnectionDisconnectAction.confirmationMessage(hasUnsavedWork: false) == nil) + #expect(ConnectionDisconnectAction.otherLosses(hasUnsavedWork: false).isEmpty) } - @Test("With running work, the transaction and the unsaved changes join the same alert") - func lossesJoinTheRunningWorkAlert() { - let losses = ConnectionDisconnectAction.otherLosses(holdingTransaction: ["app"], hasUnsavedWork: true) - - #expect(losses == ["Open transaction in “app”", "Unsaved changes"]) + // The transaction gets its own alert after this one, with Commit, so it never rides along here. + @Test("With running work, only the unsaved changes join the running-work alert") + func unsavedChangesJoinTheRunningWorkAlert() { + #expect(ConnectionDisconnectAction.otherLosses(hasUnsavedWork: true) == ["Unsaved changes"]) } - @Test("Without running work, an open transaction is asked about before unsaved changes") - func transactionOutranksUnsavedWork() throws { - let message = try #require( - ConnectionDisconnectAction.confirmationMessage(holdingTransaction: ["app"], hasUnsavedWork: true) - ) - #expect(message.contains("open transaction")) + @Test("Unsaved changes alone are asked about") + func unsavedChangesAreConfirmed() { + #expect(ConnectionDisconnectAction.confirmationMessage(hasUnsavedWork: true) == "Unsaved changes will be lost.") } } diff --git a/apple/TableProTests/Core/Services/Infrastructure/QuitTransactionPromptTests.swift b/apple/TableProTests/Core/Services/Infrastructure/QuitTransactionPromptTests.swift index d2d1425135..909e0eba18 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/QuitTransactionPromptTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/QuitTransactionPromptTests.swift @@ -8,25 +8,55 @@ import Foundation import TableProPluginKit import Testing +@Suite(.serialized) @MainActor struct QuitTransactionPromptTests { - @Test("Quit names the connection holding a transaction and offers Quit Anyway") - func quitNamesTheOpenTransaction() throws { - let prompt = try #require(QuitApproval.transactionPrompt(action: .quit, connections: ["Prod"], hasUnsavedTabs: false)) - #expect(prompt.title == "Quit with an Open Transaction?") - #expect(prompt.message == "Uncommitted changes on “Prod” are rolled back when TablePro quits.") - #expect(prompt.confirmButton == "Quit Anyway") + private static func seed(name: String) -> (connection: DatabaseConnection, driver: QuitStubDriver) { + let connection = TestFixtures.makeConnection(name: name, database: "app", type: .mysql) + let driver = QuitStubDriver() + 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) } - @Test("Unsaved tabs ride along on the transaction question rather than asking again") - func unsavedTabsRideAlong() throws { - let prompt = try #require(QuitApproval.transactionPrompt(action: .quit, connections: ["Prod"], hasUnsavedTabs: true)) - #expect(prompt.message.hasSuffix("Some tabs have unsaved edits. Quitting will discard these changes.")) + private static func begin(on connectionId: UUID) async throws { + _ = try await DatabaseManager.shared.withScopedDriver( + scope: DatabaseScope(connectionId: connectionId, database: "app", schema: nil), + route: .sessionDriver, + cancellation: .protectedWrite + ) { driver in + try await driver.execute(query: "BEGIN") + } } - @Test("No open transaction asks nothing") - func noTransactionAsksNothing() { - #expect(QuitApproval.transactionPrompt(action: .quit, connections: [], hasUnsavedTabs: true) == nil) + private static func plan( + registry: RunningWorkRegistry, + hasUnsavedTabs: Bool = false, + answer: AlertHelper.TransactionEndAnswer, + asked: inout [TransactionEndPrompt] + ) -> QuitPlan? { + var seen: [TransactionEndPrompt] = [] + let plan = QuitApproval.approvesStoppingWork( + registry: registry, + action: .quit, + hasUnsavedTabs: { hasUnsavedTabs }, + confirmWork: { _ in true }, + answerTransaction: { prompt in + seen.append(prompt) + return answer + }, + confirmDiscardingTabs: { _ in + Issue.record("The transaction prompt already named the unsaved tabs") + return false + } + ) + asked = seen + return plan } @Test("Each connection holding a transaction is named once, whatever its lanes") @@ -47,10 +77,178 @@ struct QuitTransactionPromptTests { #expect(named == ["Prod", "Staging"]) } + + @Test("Commit on the quit prompt plans the commits and stops no work yet") + func commitPlansTheHolds() async throws { + let (connection, _) = Self.seed(name: "Prod") + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.begin(on: connection.id) + var stopped = 0 + let registry = RunningWorkRegistry(providers: []) + registry.begin(.restore, subject: "sales", connectionName: "Prod", connectionIds: [connection.id]) { stopped += 1 } + var asked: [TransactionEndPrompt] = [] + + let plan = try #require(Self.plan(registry: registry, answer: .commit, asked: &asked)) + + #expect(asked.count == 1) + #expect(asked.first?.offersCommit == true) + #expect(asked.first?.message.contains("“Prod”") == true) + #expect(plan.commits.contains { $0.connectionId == connection.id }) + #expect(plan.work.count == 1) + #expect(stopped == 0) + } + + // Quitting ends the session, and the server rolls back what it held. + @Test("Roll Back on the quit prompt plans no commit") + func rollBackPlansNothing() async throws { + let (connection, _) = Self.seed(name: "Prod") + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.begin(on: connection.id) + var asked: [TransactionEndPrompt] = [] + + let plan = try #require(Self.plan(registry: RunningWorkRegistry(providers: []), answer: .rollBack, asked: &asked)) + + #expect(plan.commits.isEmpty) + } + + @Test("Cancel on the quit prompt keeps the app open") + func cancelKeepsTheAppOpen() async throws { + let (connection, _) = Self.seed(name: "Prod") + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.begin(on: connection.id) + var asked: [TransactionEndPrompt] = [] + + #expect(Self.plan(registry: RunningWorkRegistry(providers: []), answer: .cancel, asked: &asked) == nil) + } + + @Test("Unsaved tabs ride along on the transaction question rather than asking again") + func unsavedTabsRideAlong() async throws { + let (connection, _) = Self.seed(name: "Prod") + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.begin(on: connection.id) + var asked: [TransactionEndPrompt] = [] + + _ = Self.plan(registry: RunningWorkRegistry(providers: []), hasUnsavedTabs: true, answer: .rollBack, asked: &asked) + + #expect(asked.first?.message.hasSuffix("Some tabs have unsaved edits. Quitting will discard these changes.") == true) + } + + @Test("The commit lands before the quit goes ahead") + func commitBeforeQuittingCommits() async throws { + let (connection, driver) = Self.seed(name: "Prod") + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.begin(on: connection.id) + let plan = QuitPlan(commits: DatabaseManager.shared.sessionTransactions.holds(for: connection.id), work: []) + var failures: [String] = [] + + let quits = await QuitApproval.commitBeforeQuitting( + plan, + commit: { try await ConnectionTransactionActions.commitBeforeEnding($0, gate: AlwaysAllowGate()) }, + reportFailure: { failures.append($0) } + ) + + #expect(quits) + #expect(driver.statements.last == "COMMIT") + #expect(failures.isEmpty) + } + + @Test("Cancelling the Safe Mode question keeps the app open and says nothing") + func gateCancelKeepsTheAppOpen() async throws { + let (connection, driver) = Self.seed(name: "Prod") + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.begin(on: connection.id) + let plan = QuitPlan(commits: DatabaseManager.shared.sessionTransactions.holds(for: connection.id), work: []) + var failures: [String] = [] + + let quits = await QuitApproval.commitBeforeQuitting( + plan, + commit: { try await ConnectionTransactionActions.commitBeforeEnding($0, gate: AlwaysDenyGate.cancelling) }, + reportFailure: { failures.append($0) } + ) + + #expect(!quits) + #expect(!driver.statements.contains("COMMIT")) + #expect(failures.isEmpty) + } + + @Test("A failed commit keeps the app open and shows why") + func failedCommitKeepsTheAppOpen() async throws { + let (connection, _) = Self.seed(name: "Prod") + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.begin(on: connection.id) + let plan = QuitPlan(commits: DatabaseManager.shared.sessionTransactions.holds(for: connection.id), work: []) + var failures: [String] = [] + + let quits = await QuitApproval.commitBeforeQuitting( + plan, + commit: { _ in throw SessionTransactionActionError.cannotCommit }, + reportFailure: { failures.append($0) } + ) + + #expect(!quits) + #expect(failures == [SessionTransactionActionError.cannotCommit.localizedDescription]) + } + + // A nested Teradata BT survives one END TRANSACTION; quitting after it would roll back what was committed. + @Test("A transaction still open after the commit keeps the app open and names its connection") + func stillOpenKeepsTheAppOpen() async throws { + let (connection, _) = Self.seed(name: "Prod") + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.begin(on: connection.id) + let plan = QuitPlan(commits: DatabaseManager.shared.sessionTransactions.holds(for: connection.id), work: []) + var failures: [String] = [] + + let quits = await QuitApproval.commitBeforeQuitting( + plan, + commit: { _ in true }, + reportFailure: { failures.append($0) } + ) + + #expect(!quits) + #expect(failures.count == 1) + #expect(failures.first?.contains("“Prod”") == true) + } + + @Test("Nothing to commit quits without touching the server") + func nothingToCommitQuits() async { + let quits = await QuitApproval.commitBeforeQuitting( + QuitPlan(commits: [], work: []), + commit: { _ in + Issue.record("Nothing to commit") + return false + }, + reportFailure: { _ in Issue.record("Nothing failed") } + ) + + #expect(quits) + } } private final class QuitStubDriver: PluginDriverStub, @unchecked Sendable { + private let lock = NSLock() + private var current: PluginSessionTransactionState = .idle + private var sent: [String] = [] + var supportsSchemas: Bool { false } var currentSchema: String? { nil } var serverVersion: String? { nil } + var statements: [String] { lock.withLock { sent } } + + func execute(query: String) async throws -> PluginQueryResult { + lock.withLock { + sent.append(query) + switch query.uppercased() { + case "BEGIN": current = .inTransaction + case "COMMIT", "ROLLBACK": current = .idle + default: break + } + } + return .empty + } + + func sessionTransactionState() async -> PluginSessionTransactionState { + lock.withLock { current } + } + + func switchDatabase(to database: String) async throws {} } diff --git a/apple/TableProTests/Core/Services/Infrastructure/TransactionEndPromptTests.swift b/apple/TableProTests/Core/Services/Infrastructure/TransactionEndPromptTests.swift new file mode 100644 index 0000000000..cfa4d2ccec --- /dev/null +++ b/apple/TableProTests/Core/Services/Infrastructure/TransactionEndPromptTests.swift @@ -0,0 +1,267 @@ +// +// TransactionEndPromptTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct TransactionEndPromptTests { + private static func hold( + _ connectionId: UUID = UUID(), + lane: String? = nil, + state: SessionTransactionTracker.State = .open + ) -> SessionTransactionTracker.Hold { + SessionTransactionTracker.Hold(key: .init(connectionId: connectionId, lane: lane), state: state, revision: 0) + } + + private static func make( + _ action: TransactionEndPrompt.Action, + names: [String], + holds: [SessionTransactionTracker.Hold], + untracked: Bool = false, + savedUnderManualCommit: Bool = false, + hasUnsavedWork: Bool = false, + readOnly: Set = [], + busy: Set = [] + ) -> TransactionEndPrompt? { + TransactionEndPrompt.make( + action: action, + names: names, + holds: holds, + untracked: untracked, + savedUnderManualCommit: savedUnderManualCommit, + hasUnsavedWork: hasUnsavedWork, + effectiveLevel: { readOnly.contains($0) ? .readOnly : .silent }, + busy: { busy.contains($0.key) } + ) + } + + @Test("Nothing holding a transaction asks nothing") + func noTransactionNoPrompt() { + #expect(Self.make(.disconnect(name: "Prod"), names: [], holds: []) == nil) + #expect(Self.make(.quit, names: [], holds: []) == nil) + } + + @Test("Disconnect asks to commit, names a database with its own session and says what is rolled back") + func disconnectOffersCommit() throws { + let prompt = try #require(Self.make(.disconnect(name: "Prod"), names: ["app"], holds: [Self.hold(lane: "app")])) + + #expect(prompt.offersCommit) + #expect(prompt.title == "Do you want to commit the open transaction before disconnecting from “Prod”?") + #expect(prompt.message == "The database “app” has an open transaction. Changes you don’t commit are rolled back.") + #expect(!prompt.message.contains("\u{2014}")) + } + + // A SQLite connection's database is its file path, which the title's connection name already stands for. + @Test("A connection with one session for every database is not asked about by database name") + func oneSessionConnectionNamesNoDatabase() throws { + let prompt = try #require(Self.make(.disconnect(name: "Fixture"), names: ["/tmp/a.sqlite"], holds: [Self.hold()])) + + #expect(prompt.message == "Changes you don’t commit are rolled back.") + let held = Self.hold() + let busy = try #require(Self.make( + .disconnect(name: "Fixture"), names: ["/tmp/a.sqlite"], holds: [held], busy: [held.key] + )) + #expect(!busy.offersCommit) + #expect(busy.message.hasPrefix("This connection has an open transaction. Disconnecting rolls it back")) + #expect(!busy.message.contains("a.sqlite")) + } + + @Test("Several databases make the question plural and list every one") + func severalDatabasesAreListed() throws { + let id = UUID() + let prompt = try #require(Self.make( + .closeConnection(name: "Prod"), + names: ["app", "logs"], + holds: [Self.hold(id, lane: "app"), Self.hold(id, lane: "logs")] + )) + + #expect(prompt.title == "Do you want to commit the open transactions before closing “Prod”?") + #expect(prompt.message.contains("“app”")) + #expect(prompt.message.contains("“logs”")) + #expect(prompt.message.hasSuffix("Changes you don’t commit are rolled back.")) + } + + @Test("A database entry is named in the question") + func entryCloseNamesTheDatabase() throws { + let prompt = try #require(Self.make(.closeEntry(database: "logs"), names: ["logs"], holds: [Self.hold(lane: "logs")])) + + #expect(prompt.title == "Do you want to commit the open transaction before closing the database “logs”?") + #expect(prompt.message == "Changes you don’t commit are rolled back.") + } + + @Test("Disconnect keeps the unsaved-changes line, since Commit then disconnect still loses them") + func disconnectKeepsUnsavedLine() throws { + let prompt = try #require(Self.make(.disconnect(name: "Prod"), names: ["app"], holds: [Self.hold()], hasUnsavedWork: true)) + + #expect(prompt.message.hasSuffix("Unsaved changes will be lost.")) + } + + @Test("A close asked about unsaved work on its own Save alert, so it carries no unsaved line") + func closeCarriesNoUnsavedLine() throws { + let prompt = try #require(Self.make(.closeConnection(name: "Prod"), names: ["app"], holds: [Self.hold()], hasUnsavedWork: true)) + + #expect(!prompt.message.contains("Unsaved")) + } + + @Test("Under Manual Commit the message says saved edits are not committed yet") + func manualCommitNote() throws { + let prompt = try #require(Self.make( + .closeConnection(name: "Prod"), names: ["app"], holds: [Self.hold()], savedUnderManualCommit: true + )) + + #expect(prompt.message.contains("Edits saved with Manual Commit on are not committed yet.")) + let disconnect = try #require(Self.make( + .disconnect(name: "Prod"), names: ["app"], holds: [Self.hold()], savedUnderManualCommit: true + )) + #expect(!disconnect.message.contains("Manual Commit")) + } + + @Test("Quit names each connection and keeps the unsaved-tabs line") + func quitNamesConnections() throws { + let prompt = try #require(Self.make(.quit, names: ["Prod"], holds: [Self.hold()], hasUnsavedWork: true)) + + #expect(prompt.offersCommit) + #expect(prompt.title == "Do you want to commit the open transaction before quitting?") + #expect(prompt.message.hasPrefix("The connection “Prod” has an open transaction. Changes you don’t commit are rolled back.")) + #expect(prompt.message.hasSuffix("Some tabs have unsaved edits. Quitting will discard these changes.")) + } + + @Test("A connection holding two lanes is one name with plural transactions") + func quitOneConnectionTwoLanes() throws { + let id = UUID() + let prompt = try #require(Self.make(.quit, names: ["Prod"], holds: [Self.hold(id, lane: "app"), Self.hold(id, lane: "logs")])) + + #expect(prompt.title == "Do you want to commit the open transactions before quitting?") + #expect(prompt.message.hasPrefix("The connection “Prod” has open transactions.")) + } + + @Test("Relaunch speaks of relaunching, never of quitting") + func relaunchWording() throws { + let commit = try #require(Self.make(.relaunch, names: ["Prod"], holds: [Self.hold()], hasUnsavedWork: true)) + #expect(commit.title == "Do you want to commit the open transaction before relaunching?") + #expect(commit.message.hasSuffix("Some tabs have unsaved edits. Relaunching will discard these changes.")) + #expect(!commit.message.contains("Quitting")) + + let rollBack = try #require(Self.make( + .relaunch, names: ["Prod"], holds: [Self.hold(state: .aborted)], hasUnsavedWork: true + )) + #expect(rollBack.title == "Relaunch with an Open Transaction?") + #expect(rollBack.confirmButton == "Relaunch Anyway") + #expect(rollBack.message.hasPrefix("Uncommitted changes on “Prod” are rolled back when TablePro relaunches.")) + #expect(!rollBack.message.contains("quits")) + #expect(!rollBack.message.contains("Quitting")) + } + + @Test("Each action keeps its roll-back button when Commit is not offered") + func rollBackButtons() throws { + let aborted = [Self.hold(state: .aborted)] + + #expect(Self.make(.closeEntry(database: "app"), names: ["app"], holds: aborted)?.confirmButton == "Close") + #expect(Self.make(.closeConnection(name: "Prod"), names: ["app"], holds: aborted)?.confirmButton == "Close") + #expect(Self.make(.disconnect(name: "Prod"), names: ["app"], holds: aborted)?.confirmButton == "Disconnect") + #expect(Self.make(.quit, names: ["Prod"], holds: aborted)?.confirmButton == "Quit Anyway") + #expect(Self.make(.relaunch, names: ["Prod"], holds: aborted)?.confirmButton == "Relaunch Anyway") + } + + @Test("A failed statement leaves only Roll Back and says why") + func abortedOffersNoCommit() throws { + let prompt = try #require(Self.make(.disconnect(name: "Prod"), names: ["app"], holds: [Self.hold(lane: "app", state: .aborted)])) + + #expect(prompt.commitBlock == .aborted) + #expect(!prompt.offersCommit) + #expect(prompt.title == "Disconnect from “Prod”?") + #expect(prompt.message.hasPrefix( + "The database “app” has an open transaction. Disconnecting rolls it back and discards its uncommitted changes." + )) + #expect(prompt.message.contains("A statement failed in the transaction, so it can only be rolled back.")) + } + + @Test("Read-Only Safe Mode leaves only Roll Back and says why") + func readOnlyOffersNoCommit() throws { + let id = UUID() + let prompt = try #require(Self.make(.closeConnection(name: "Prod"), names: ["app"], holds: [Self.hold(id)], readOnly: [id])) + + #expect(prompt.commitBlock == .readOnly) + #expect(prompt.title == "Close the connection “Prod”?") + #expect(prompt.message.contains("Read-Only Safe Mode does not allow a commit.")) + } + + // The gate commits at the connection's level raised to the managed floor, so the prompt reads that level. + @Test("A managed Read-Only floor leaves only Roll Back when the connection itself is below it") + func managedFloorOffersNoCommit() throws { + let floor = ManagedFloorPolicy(floor: .readOnly) + let prompt = try #require(TransactionEndPrompt.make( + action: .disconnect(name: "Prod"), + names: ["app"], + holds: [Self.hold()], + effectiveLevel: { _ in ManagedPolicyResolver.effectiveSafeModeLevel(connectionLevel: .silent, policy: floor) }, + busy: { _ in false } + )) + + #expect(prompt.commitBlock == .readOnly) + } + + @Test("A statement still running in the transaction leaves only Roll Back and says why") + func busyOffersNoCommit() throws { + let hold = Self.hold(lane: "app") + let prompt = try #require(Self.make(.closeEntry(database: "app"), names: ["app"], holds: [hold], busy: [hold.key])) + + #expect(prompt.commitBlock == .busy) + #expect(prompt.title == "Close the database “app”?") + #expect(prompt.message.contains("A statement is still running in the transaction, so it cannot be committed now.")) + } + + // The live read can find one the tracker never recorded, and a commit goes through a tracked hold only. + @Test("A database with no tracked hold leaves only Roll Back") + func untrackedOffersNoCommit() throws { + let id = UUID() + let partly = try #require(Self.make( + .disconnect(name: "Prod"), names: ["app", "logs"], holds: [Self.hold(id, lane: "app")], untracked: true + )) + #expect(partly.commitBlock == .untracked) + #expect(partly.message.hasPrefix("These databases have open transactions: ")) + #expect(partly.message.contains("“logs”")) + + let none = try #require(Self.make(.disconnect(name: "Prod"), names: ["app"], holds: [])) + #expect(none.commitBlock == .untracked) + } + + @Test("A failed transaction is named before the other reasons") + func abortedOutranksTheRest() { + let id = UUID() + let aborted = Self.hold(id, lane: "app", state: .aborted) + let block = TransactionEndPrompt.commitBlock( + holds: [aborted], + untracked: true, + effectiveLevel: { _ in .readOnly }, + busy: { _ in true } + ) + + #expect(block == .aborted) + } + + @Test("One hold that cannot commit blocks Commit for all") + func oneBlockedHoldBlocksAll() { + let id = UUID() + let block = TransactionEndPrompt.commitBlock( + holds: [Self.hold(id, lane: "app"), Self.hold(id, lane: "logs", state: .aborted)], + untracked: false, + effectiveLevel: { _ in .silent }, + busy: { _ in false } + ) + + #expect(block == .aborted) + } +} + +private struct ManagedFloorPolicy: ManagedPolicyReading { + let floor: SafeModeLevel + + func string(_ policy: ManagedPolicy) -> String? { + policy == .minimumSafeModeLevel ? floor.rawValue : nil + } +} diff --git a/apple/TableProTests/Core/Services/Infrastructure/TransactionEndingFlowTests.swift b/apple/TableProTests/Core/Services/Infrastructure/TransactionEndingFlowTests.swift new file mode 100644 index 0000000000..837298e97f --- /dev/null +++ b/apple/TableProTests/Core/Services/Infrastructure/TransactionEndingFlowTests.swift @@ -0,0 +1,405 @@ +// +// TransactionEndingFlowTests.swift +// TableProTests +// + +import AppKit +import Foundation +@testable import TablePro +import TableProPluginKit +import TableProTestSupport +import Testing + +@Suite(.serialized) +@MainActor +struct TransactionEndingFlowTests { + private static func seed( + name: String = "Prod", + safeModeLevel: SafeModeLevel = .silent + ) -> (connection: DatabaseConnection, driver: EndingScriptedDriver) { + var connection = TestFixtures.makeConnection(name: name, database: "app", type: .mysql) + connection.safeModeLevel = safeModeLevel + let driver = EndingScriptedDriver() + 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 static func run(_ sql: String, on connectionId: UUID) async throws { + let scope = DatabaseScope(connectionId: connectionId, database: "app", schema: nil) + _ = try await DatabaseManager.shared.withScopedDriver( + scope: scope, + route: .sessionDriver, + cancellation: .protectedWrite + ) { driver in + try await driver.execute(query: sql) + } + } + + private static func holds(_ connectionId: UUID) -> [SessionTransactionTracker.Hold] { + DatabaseManager.shared.sessionTransactions.holds(for: connectionId) + } + + // The flow as a close or disconnect runs it, with the alert answered by the test and the gate injected. + private static func resolve( + _ connectionId: UUID, + answers: [AlertHelper.TransactionEndAnswer], + asked: inout [TransactionEndPrompt], + failures: inout [String], + gate: any ExecutionGate = AlwaysAllowGate(), + commit: (@MainActor ([SessionTransactionTracker.Hold]) async throws -> Bool)? = nil + ) async -> TransactionEndingFlow.Outcome { + var remaining = answers + var seen: [TransactionEndPrompt] = [] + var reported: [String] = [] + let outcome = await TransactionEndingFlow.resolve( + connectionId: connectionId, + action: .disconnect(name: "Prod"), + window: { nil }, + ask: { prompt, _ in + seen.append(prompt) + return remaining.isEmpty ? .cancel : remaining.removeFirst() + }, + commit: { holds in + if let commit { return try await commit(holds) } + return try await ConnectionTransactionActions.commitBeforeEnding(holds, gate: gate) + }, + reportFailure: { message, _ in reported.append(message) } + ) + asked = seen + failures = reported + return outcome + } + + @Test("Nothing open asks nothing and lets the close go ahead") + func nothingOpenAsksNothing() async throws { + let (connection, _) = Self.seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + var asked: [TransactionEndPrompt] = [] + var failures: [String] = [] + + let outcome = await Self.resolve(connection.id, answers: [.commit], asked: &asked, failures: &failures) + + #expect(outcome == .nothingOpen) + #expect(asked.isEmpty) + } + + @Test("Commit commits the open transaction, then the close goes ahead") + func commitThenProceed() async throws { + let (connection, driver) = Self.seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.run("BEGIN", on: connection.id) + var asked: [TransactionEndPrompt] = [] + var failures: [String] = [] + + let outcome = await Self.resolve(connection.id, answers: [.commit], asked: &asked, failures: &failures) + + #expect(outcome == .ended) + #expect(asked.count == 1) + #expect(asked.first?.offersCommit == true) + #expect(driver.statements.filter { $0 == "COMMIT" }.count == 1) + #expect(driver.statements.last == "COMMIT") + #expect(Self.holds(connection.id).isEmpty) + #expect(failures.isEmpty) + } + + // The disconnect that follows ends the session, and the server rolls back what it held. + @Test("Roll Back sends nothing and asks no more") + func rollBackProceedsWithoutReasking() async throws { + let (connection, driver) = Self.seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.run("BEGIN", on: connection.id) + var asked: [TransactionEndPrompt] = [] + var failures: [String] = [] + + let outcome = await Self.resolve(connection.id, answers: [.rollBack, .commit], asked: &asked, failures: &failures) + + #expect(outcome == .ended) + #expect(asked.count == 1) + #expect(!driver.statements.contains("COMMIT")) + #expect(!driver.statements.contains("ROLLBACK")) + #expect(Self.holds(connection.id).count == 1) + } + + @Test("Cancel keeps the transaction and the connection") + func cancelKeepsEverything() async throws { + let (connection, driver) = Self.seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.run("BEGIN", on: connection.id) + var asked: [TransactionEndPrompt] = [] + var failures: [String] = [] + + let outcome = await Self.resolve(connection.id, answers: [.cancel], asked: &asked, failures: &failures) + + #expect(outcome == .cancelled) + #expect(!driver.statements.contains("COMMIT")) + #expect(!driver.statements.contains("ROLLBACK")) + #expect(Self.holds(connection.id).count == 1) + } + + @Test("Cancelling the Safe Mode question commits nothing and keeps the connection") + func gateCancelKeepsTheConnection() async throws { + let (connection, driver) = Self.seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.run("BEGIN", on: connection.id) + var asked: [TransactionEndPrompt] = [] + var failures: [String] = [] + + let outcome = await Self.resolve( + connection.id, answers: [.commit], asked: &asked, failures: &failures, gate: AlwaysDenyGate.cancelling + ) + + #expect(outcome == .cancelled) + #expect(!driver.statements.contains("COMMIT")) + #expect(!driver.statements.contains("ROLLBACK")) + #expect(failures.isEmpty) + } + + // A commit that failed and a close that went ahead anyway would be a rollback nobody chose. + @Test("A failed commit shows the error and keeps the connection") + func failedCommitKeepsTheConnection() async throws { + let (connection, driver) = Self.seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.run("BEGIN", on: connection.id) + var asked: [TransactionEndPrompt] = [] + var failures: [String] = [] + + let outcome = await Self.resolve(connection.id, answers: [.commit], asked: &asked, failures: &failures) { _ in + throw SessionTransactionActionError.cannotCommit + } + + #expect(outcome == .cancelled) + #expect(failures == [SessionTransactionActionError.cannotCommit.localizedDescription]) + #expect(!driver.statements.contains("COMMIT")) + #expect(!driver.statements.contains("ROLLBACK")) + #expect(Self.holds(connection.id).count == 1) + } + + // Read-Only is the strictest level, so no managed floor on the test Mac can change this answer. + @Test("The close prompt, the bar and the menu all withhold Commit at the gate's Read-Only level") + func readOnlyWithholdsCommitEverywhere() async throws { + let (connection, _) = Self.seed(safeModeLevel: .readOnly) + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.run("BEGIN", on: connection.id) + let hold = try #require(Self.holds(connection.id).first) + var asked: [TransactionEndPrompt] = [] + var failures: [String] = [] + + let outcome = await Self.resolve(connection.id, answers: [.cancel], asked: &asked, failures: &failures) + + #expect(outcome == .cancelled) + #expect(asked.first?.commitBlock == .readOnly) + #expect(!ConnectionTransactionActions.offersCommit(hold)) + let bar = ConnectionTransactionBarContent( + isAborted: false, + connectionName: "Prod", + database: "app", + effectiveSafeModeLevel: ExecutionGateProvider.effectiveSafeModeLevel(for: connection.id) + ) + #expect(!bar.offersCommit) + } + + @Test("A Read-Only refusal of the commit shows the reason and keeps the connection") + func policyDenialKeepsTheConnection() async throws { + let (connection, _) = Self.seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.run("BEGIN", on: connection.id) + var asked: [TransactionEndPrompt] = [] + var failures: [String] = [] + + let outcome = await Self.resolve( + connection.id, answers: [.commit], asked: &asked, failures: &failures, gate: AlwaysDenyGate() + ) + + #expect(outcome == .cancelled) + #expect(failures == ["Read-Only connection"]) + } + + // A nested Teradata BT survives one END TRANSACTION; closing after it would roll back what the user committed. + @Test("A transaction still open after Commit is asked about again") + func stillOpenAfterCommitAsksAgain() async throws { + let (connection, _) = Self.seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.run("BEGIN", on: connection.id) + var asked: [TransactionEndPrompt] = [] + var failures: [String] = [] + + let outcome = await Self.resolve( + connection.id, answers: [.commit, .rollBack], asked: &asked, failures: &failures + ) { _ in true } + + #expect(outcome == .ended) + #expect(asked.count == 2) + } + + @Test("A transaction a second Commit ends lets the close go ahead") + func secondCommitEndsIt() async throws { + let (connection, driver) = Self.seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.run("BEGIN", on: connection.id) + var asked: [TransactionEndPrompt] = [] + var failures: [String] = [] + var commits = 0 + + let outcome = await Self.resolve( + connection.id, answers: [.commit, .commit], asked: &asked, failures: &failures + ) { holds in + commits += 1 + guard commits > 1 else { return true } + return try await ConnectionTransactionActions.commitBeforeEnding(holds, gate: AlwaysAllowGate()) + } + + #expect(outcome == .ended) + #expect(asked.count == 2) + #expect(driver.statements.filter { $0 == "COMMIT" }.count == 1) + #expect(driver.statements.last == "COMMIT") + } + + private static func entry(_ name: String, on connectionId: UUID) -> TransactionEndingFlow.Entry { + TransactionEndingFlow.Entry( + name: name, + hold: SessionTransactionTracker.Hold(key: .init(connectionId: connectionId, lane: name), state: .open, revision: 1) + ) + } + + @Test("A database that starts holding one after Roll Back is asked about, alone") + func newDatabaseAfterRollBackAsksAgain() async { + let id = UUID() + let app = Self.entry("app", on: id) + let logs = Self.entry("logs", on: id) + var reads: [[TransactionEndingFlow.Entry]] = [[app], [app, logs], [app, logs]] + var listed: [[String]] = [] + + let outcome = await TransactionEndingFlow.run( + read: { reads.isEmpty ? [] : reads.removeFirst() }, + prompt: { entries in + if !entries.isEmpty { listed.append(entries.map { $0.name }) } + return TransactionEndPrompt.make( + action: .closeConnection(name: "Prod"), + names: entries.map { $0.name }, + holds: entries.compactMap { $0.hold }, + effectiveLevel: { _ in .silent }, + busy: { _ in false } + ) + }, + ask: { _ in .rollBack }, + commit: { _ in + Issue.record("Roll Back commits nothing") + return true + }, + reportFailure: { _ in } + ) + + #expect(outcome == .ended) + #expect(listed == [["app"], ["logs"]]) + } + + @Test("Commit goes through only the holds the question listed") + func commitTakesTheListedHolds() async { + let app = Self.entry("app", on: UUID()) + var reads: [[TransactionEndingFlow.Entry]] = [[app], []] + var committed: [[SessionTransactionTracker.Hold]] = [] + + let outcome = await TransactionEndingFlow.run( + read: { reads.isEmpty ? [] : reads.removeFirst() }, + prompt: { entries in + TransactionEndPrompt.make( + action: .closeConnection(name: "Prod"), + names: entries.map { $0.name }, + holds: entries.compactMap { $0.hold }, + effectiveLevel: { _ in .silent }, + busy: { _ in false } + ) + }, + ask: { _ in .commit }, + commit: { holds in + committed.append(holds) + return true + }, + reportFailure: { _ in } + ) + + #expect(outcome == .ended) + #expect(committed.count == 1) + #expect(committed.first?.map { $0.key.lane } == ["app"]) + } + + @Test("Commit asks the gate once per connection before anything is sent") + func commitAuthorizesOncePerConnection() async throws { + let (first, _) = Self.seed(name: "First") + let (second, _) = Self.seed(name: "Second") + defer { + DatabaseManager.shared.removeSession(for: first.id) + DatabaseManager.shared.removeSession(for: second.id) + } + let gate = RequestRecordingGate(allows: true) + // Never recorded by the tracker, so the first one refused proves every question came before it. + let holds = [ + SessionTransactionTracker.Hold(key: .init(connectionId: first.id, lane: "app"), state: .open, revision: 9), + SessionTransactionTracker.Hold(key: .init(connectionId: first.id, lane: "logs"), state: .open, revision: 9), + SessionTransactionTracker.Hold(key: .init(connectionId: second.id, lane: nil), state: .open, revision: 9), + ] + + await #expect(throws: SessionTransactionActionError.transactionChanged) { + _ = try await ConnectionTransactionActions.commitBeforeEnding(holds, gate: gate) + } + let requests = await gate.requests + #expect(requests.map { $0.connectionId } == [first.id, second.id]) + #expect(requests.allSatisfy { $0.sql == "COMMIT" }) + } + + // A commit would wait behind the running turn, so the prompt offers Roll Back only while one runs. + @Test("A turn running on the hold's connection makes its lane busy") + func turnMakesTheLaneBusy() async throws { + let (connection, _) = Self.seed() + defer { DatabaseManager.shared.removeSession(for: connection.id) } + try await Self.run("BEGIN", on: connection.id) + let hold = try #require(Self.holds(connection.id).first) + let key = DatabaseManager.shared.browsedGateKey(for: connection.id) + let gate = AsyncGate() + + let turn = Task { + try await DatabaseManager.shared.sessionDriverGate.withExclusiveAccess(key) { + await gate.wait() + } + } + await gate.arrived(1) + #expect(DatabaseManager.shared.isLaneBusy(holding: hold)) + await gate.open() + try await turn.value + + #expect(!DatabaseManager.shared.isLaneBusy(holding: hold)) + } +} + +// Answers its session state from the statements it saw, like a server that reports the flag in every reply. +private final class EndingScriptedDriver: PluginDriverStub, @unchecked Sendable { + private let lock = NSLock() + private var current: PluginSessionTransactionState = .idle + private var sent: [String] = [] + + var statements: [String] { lock.withLock { sent } } + + func execute(query: String) async throws -> PluginQueryResult { + lock.withLock { + sent.append(query) + switch query.uppercased() { + case "BEGIN": current = .inTransaction + case "COMMIT", "ROLLBACK": current = .idle + default: break + } + } + return .empty + } + + func sessionTransactionState() async -> PluginSessionTransactionState { + lock.withLock { current } + } + + func switchDatabase(to database: String) async throws {} +} diff --git a/apple/TableProTests/Core/Utilities/TransactionEndAlertTests.swift b/apple/TableProTests/Core/Utilities/TransactionEndAlertTests.swift new file mode 100644 index 0000000000..923b8a9006 --- /dev/null +++ b/apple/TableProTests/Core/Utilities/TransactionEndAlertTests.swift @@ -0,0 +1,76 @@ +// +// TransactionEndAlertTests.swift +// TableProTests +// + +import AppKit +@testable import TablePro +import Testing + +@MainActor +struct TransactionEndAlertTests { + private static let escape = "\u{1B}" + private static let returnKey = "\r" + + private static func prompt(state: SessionTransactionTracker.State) throws -> TransactionEndPrompt { + let hold = SessionTransactionTracker.Hold(key: .init(connectionId: UUID(), lane: nil), state: state, revision: 0) + return try #require(TransactionEndPrompt.make( + action: .disconnect(name: "Prod"), + names: ["app"], + holds: [hold], + effectiveLevel: { _ in .silent }, + busy: { _ in false } + )) + } + + // The Save alert's order: the default first, Cancel second, the destructive choice third. + @Test("Commit, Cancel, then Roll Back, in the order NSDocument uses for Save") + func buttonOrder() throws { + let alert = AlertHelper.makeTransactionEndAlert(try Self.prompt(state: .open)) + + #expect(alert.buttons.map { $0.title } == ["Commit", "Cancel", "Roll Back"]) + #expect(alert.alertStyle == .warning) + } + + @Test("Return commits, Escape cancels, and Roll Back takes a deliberate click") + func keyBindings() throws { + let alert = AlertHelper.makeTransactionEndAlert(try Self.prompt(state: .open)) + + #expect(alert.buttons[0].keyEquivalent == Self.returnKey) + #expect(alert.buttons[1].keyEquivalent == Self.escape) + #expect(alert.buttons[2].keyEquivalent == "") + #expect(alert.buttons.filter { $0.keyEquivalent == Self.returnKey }.count == 1) + #expect(alert.buttons.filter { $0.keyEquivalent == Self.escape }.count == 1) + } + + @Test("Roll Back is the destructive button and Commit is not") + func rollBackIsDestructive() throws { + let alert = AlertHelper.makeTransactionEndAlert(try Self.prompt(state: .open)) + + #expect(alert.buttons[2].hasDestructiveAction) + #expect(!alert.buttons[0].hasDestructiveAction) + #expect(!alert.buttons[1].hasDestructiveAction) + } + + @Test("Each button maps to its answer") + func answers() { + #expect(AlertHelper.transactionEndAnswer(to: .alertFirstButtonReturn, offersCommit: true) == .commit) + #expect(AlertHelper.transactionEndAnswer(to: .alertSecondButtonReturn, offersCommit: true) == .cancel) + #expect(AlertHelper.transactionEndAnswer(to: .alertThirdButtonReturn, offersCommit: true) == .rollBack) + #expect(AlertHelper.transactionEndAnswer(to: .abort, offersCommit: true) == .cancel) + } + + @Test("Without Commit, the roll-back alert keeps Escape on Cancel and takes Return off its button") + func rollBackOnlyAlert() throws { + let prompt = try Self.prompt(state: .aborted) + let alert = AlertHelper.makeTransactionEndAlert(prompt) + + #expect(alert.buttons.map { $0.title } == ["Disconnect", "Cancel"]) + #expect(alert.buttons[0].hasDestructiveAction) + #expect(alert.buttons[0].keyEquivalent == "") + #expect(alert.buttons[1].keyEquivalent == Self.escape) + #expect(AlertHelper.transactionEndAnswer(to: .alertFirstButtonReturn, offersCommit: false) == .rollBack) + #expect(AlertHelper.transactionEndAnswer(to: .alertSecondButtonReturn, offersCommit: false) == .cancel) + #expect(AlertHelper.transactionEndAnswer(to: .alertThirdButtonReturn, offersCommit: false) == .cancel) + } +} diff --git a/apple/TableProTests/Services/Updates/AppRelauncherTests.swift b/apple/TableProTests/Services/Updates/AppRelauncherTests.swift index b97f4483c7..2c15e63a13 100644 --- a/apple/TableProTests/Services/Updates/AppRelauncherTests.swift +++ b/apple/TableProTests/Services/Updates/AppRelauncherTests.swift @@ -1,5 +1,6 @@ import Foundation @testable import TablePro +import TableProTestSupport import Testing @MainActor @@ -14,6 +15,10 @@ final class AppRelauncherFixture { let suite: EphemeralDefaults var documentsReviewed = true var stoppingWorkApproved = true + var commits: [SessionTransactionTracker.Hold] = [] + var commitSucceeds = true + var commitGate: AsyncGate? + private(set) var commitCalls = 0 private(set) var workQuestions = 0 private(set) var approvedWhenQuitting: [Bool] = [] var hasPendingUpdate = false @@ -21,6 +26,8 @@ final class AppRelauncherFixture { var reopenFails = false private(set) var installs = 0 private(set) var terminations = 0 + // Runs that went through the next run loop turn rather than inside the commit's task. + private(set) var deferredRuns = 0 private(set) var reopens: [(pid: pid_t, bundleURL: URL)] = [] private(set) var relauncher: AppRelauncher! @@ -30,7 +37,12 @@ final class AppRelauncherFixture { defaults: suite.defaults, approveStoppingWork: { [unowned self] in workQuestions += 1 - return stoppingWorkApproved + return stoppingWorkApproved ? QuitPlan(commits: commits, work: []) : nil + }, + commitBeforeQuitting: { [unowned self] _ in + commitCalls += 1 + await commitGate?.wait() + return commitSucceeds }, reviewUnsavedDocuments: { [unowned self] completion in completion(documentsReviewed) }, installPendingUpdate: { [unowned self] in @@ -48,6 +60,10 @@ final class AppRelauncherFixture { relauncher.terminationWasCancelled() } }, + performOutsideTask: { [unowned self] body in + deferredRuns += 1 + body() + }, reopenAfterExit: { [unowned self] pid, url in if reopenFails { throw CocoaError(.executableLoad) } reopens.append((pid, url)) @@ -196,6 +212,101 @@ struct AppRelauncherTests { #expect(!fixture.reopenRequested) } + @Test("With nothing to commit, the relaunch quits at once") + func noCommitQuitsAtOnce() throws { + let fixture = try AppRelauncherFixture() + + fixture.relauncher.relaunch() + + #expect(fixture.commitCalls == 0) + #expect(fixture.relauncher.pendingCommit == nil) + #expect(fixture.deferredRuns == 0) + #expect(fixture.terminations == 1) + } + + // The quit a relaunch starts asks nothing, so a transaction it would end is committed first. + @Test("With an open transaction to commit, the relaunch quits only after the commit, outside its task") + func quitsOnlyAfterTheCommit() async throws { + let fixture = try AppRelauncherFixture() + let gate = AsyncGate() + fixture.commits = [Self.hold()] + fixture.commitGate = gate + + fixture.relauncher.relaunch() + let commit = try #require(fixture.relauncher.pendingCommit) + await gate.arrived(1) + + #expect(fixture.terminations == 0) + #expect(!fixture.relauncher.isRelaunchPending) + + await gate.open() + await commit.value + + #expect(fixture.commitCalls == 1) + #expect(fixture.deferredRuns == 1) + #expect(fixture.terminations == 1) + #expect(fixture.reopens.count == 1) + #expect(fixture.relauncher.pendingCommit == nil) + } + + @Test("Sparkle takes over only after the commit, outside its task") + func sparkleInstallsAfterTheCommit() async throws { + let fixture = try AppRelauncherFixture() + fixture.commits = [Self.hold()] + fixture.hasPendingUpdate = true + + fixture.relauncher.relaunch() + let commit = try #require(fixture.relauncher.pendingCommit) + await commit.value + + #expect(fixture.deferredRuns == 1) + #expect(fixture.installs == 1) + #expect(fixture.relauncher.isRelaunchPending) + } + + @Test("A commit that fails or is cancelled stops the relaunch, and a later quit stays a quit") + func failedCommitStopsTheRelaunch() async throws { + let fixture = try AppRelauncherFixture() + fixture.commits = [Self.hold()] + fixture.commitSucceeds = false + fixture.hasPendingUpdate = true + + fixture.relauncher.relaunch() + let commit = try #require(fixture.relauncher.pendingCommit) + await commit.value + + #expect(fixture.commitCalls == 1) + #expect(fixture.deferredRuns == 0) + #expect(fixture.installs == 0) + #expect(fixture.terminations == 0) + #expect(!fixture.relauncher.isRelaunchPending) + #expect(!fixture.relauncher.hasApprovedRunningWork) + #expect(fixture.relauncher.pendingCommit == nil) + } + + @Test("A second relaunch while the commit runs asks nothing again") + func relaunchDuringTheCommitIsIgnored() async throws { + let fixture = try AppRelauncherFixture() + let gate = AsyncGate() + fixture.commits = [Self.hold()] + fixture.commitGate = gate + + fixture.relauncher.relaunch() + let commit = try #require(fixture.relauncher.pendingCommit) + await gate.arrived(1) + fixture.relauncher.relaunch() + await gate.open() + await commit.value + + #expect(fixture.workQuestions == 1) + #expect(fixture.commitCalls == 1) + #expect(fixture.terminations == 1) + } + + private static func hold() -> SessionTransactionTracker.Hold { + SessionTransactionTracker.Hold(key: .init(connectionId: UUID(), lane: nil), state: .open, revision: 0) + } + @Test("The next launch reads the reopen request once") func reopenRequestIsReadOnce() throws { let fixture = try AppRelauncherFixture() diff --git a/apple/TableProUITests/ManualCommitUITests.swift b/apple/TableProUITests/ManualCommitUITests.swift index f355a330eb..2522edba99 100644 --- a/apple/TableProUITests/ManualCommitUITests.swift +++ b/apple/TableProUITests/ManualCommitUITests.swift @@ -25,4 +25,27 @@ final class ManualCommitUITests: UITestCase { let rows = FixtureFile.rows("SELECT body FROM note WHERE id = 1", in: launch.database) XCTAssertEqual(rows, [["Buy milk"]], "The rolled-back UPDATE must leave the row as it was") } + + func testDisconnectCommitsTheHeldUpdate() throws { + let launch = try launchWithFixture() + let window = launch.window + let app = launch.app + XCTAssertTrue(app.menuBars.firstMatch.waitToExist(timeout: 20), "The app must publish its menu bar") + + menuItem("Manual Commit", under: "Database", in: app).click() + typeQuery("UPDATE note SET body = 'Kept' WHERE id = 1;", in: window) + app.typeShortcut(.runQuery) + let bar = window.descendants(matching: .any)["connection-transaction-bar"].firstMatch + XCTAssertTrue(bar.waitToExist(timeout: 20), "A write in Manual Commit must leave its transaction open") + + menuItem("Disconnect", under: "Database", in: app).click() + let commit = window.sheets.buttons["Commit"].firstMatch + XCTAssertTrue(waitUntilHittable(commit, timeout: 10), "Disconnect must offer Commit for the open transaction") + XCTAssertTrue(window.sheets.buttons["Roll Back"].firstMatch.exists, "Disconnect must offer Roll Back beside Commit") + commit.click() + + XCTAssertTrue(bar.waitForNonExistence(timeout: 20), "Committing must end the transaction before the disconnect") + let rows = FixtureFile.rows("SELECT body FROM note WHERE id = 1", in: launch.database) + XCTAssertEqual(rows, [["Kept"]], "Commit on Disconnect must keep the held UPDATE") + } } From fed1ef040facc2a611d14810d93118f1057dedf3 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 02:51:52 +0700 Subject: [PATCH 2/2] docs(changelog): add the fragments for #4247 --- apple/changelog.d/4247.changed.md | 1 + apple/changelog.d/4247.fixed.1.md | 1 + apple/changelog.d/4247.fixed.2.md | 1 + apple/changelog.d/4247.fixed.3.md | 1 + apple/changelog.d/4247.fixed.4.md | 1 + apple/changelog.d/4247.fixed.5.md | 1 + apple/changelog.d/4247.fixed.md | 1 + 7 files changed, 7 insertions(+) create mode 100644 apple/changelog.d/4247.changed.md create mode 100644 apple/changelog.d/4247.fixed.1.md create mode 100644 apple/changelog.d/4247.fixed.2.md create mode 100644 apple/changelog.d/4247.fixed.3.md create mode 100644 apple/changelog.d/4247.fixed.4.md create mode 100644 apple/changelog.d/4247.fixed.5.md create mode 100644 apple/changelog.d/4247.fixed.md diff --git a/apple/changelog.d/4247.changed.md b/apple/changelog.d/4247.changed.md new file mode 100644 index 0000000000..abcaf1023f --- /dev/null +++ b/apple/changelog.d/4247.changed.md @@ -0,0 +1 @@ +Closing, disconnecting, quitting or relaunching with an open transaction now offers Commit as well as Roll Back. diff --git a/apple/changelog.d/4247.fixed.1.md b/apple/changelog.d/4247.fixed.1.md new file mode 100644 index 0000000000..b4409789be --- /dev/null +++ b/apple/changelog.d/4247.fixed.1.md @@ -0,0 +1 @@ +On Teradata, Run All failed on the statement after a DDL statement instead of stopping and asking you to commit. diff --git a/apple/changelog.d/4247.fixed.2.md b/apple/changelog.d/4247.fixed.2.md new file mode 100644 index 0000000000..8066cf29cd --- /dev/null +++ b/apple/changelog.d/4247.fixed.2.md @@ -0,0 +1 @@ +On Teradata, every statement after an uncommitted change was refused, a typed COMMIT included. diff --git a/apple/changelog.d/4247.fixed.3.md b/apple/changelog.d/4247.fixed.3.md new file mode 100644 index 0000000000..3abb4c2ee0 --- /dev/null +++ b/apple/changelog.d/4247.fixed.3.md @@ -0,0 +1 @@ +On Teradata, saving two staged table drops failed, and Truncate sent a TRUNCATE statement Teradata does not have. diff --git a/apple/changelog.d/4247.fixed.4.md b/apple/changelog.d/4247.fixed.4.md new file mode 100644 index 0000000000..164b9cbe2d --- /dev/null +++ b/apple/changelog.d/4247.fixed.4.md @@ -0,0 +1 @@ +Closing a connection under Manual Commit rolled back the edits you had just chosen to save. diff --git a/apple/changelog.d/4247.fixed.5.md b/apple/changelog.d/4247.fixed.5.md new file mode 100644 index 0000000000..3d1661f393 --- /dev/null +++ b/apple/changelog.d/4247.fixed.5.md @@ -0,0 +1 @@ +A TablePro opened only to serve MCP kept running after MCP refused it. diff --git a/apple/changelog.d/4247.fixed.md b/apple/changelog.d/4247.fixed.md new file mode 100644 index 0000000000..6aff4835cf --- /dev/null +++ b/apple/changelog.d/4247.fixed.md @@ -0,0 +1 @@ +On Teradata ANSI sessions, structure edits, new tables, renames and drops were left uncommitted and could be lost.