diff --git a/agents/drivers/xugu/transaction_management_live_test.go b/agents/drivers/xugu/transaction_management_live_test.go new file mode 100644 index 0000000000..6d26d36ec5 --- /dev/null +++ b/agents/drivers/xugu/transaction_management_live_test.go @@ -0,0 +1,116 @@ +package main + +import ( + "context" + "database/sql" + "fmt" + "os" + "regexp" + "testing" + "time" +) + +// TestLiveXuguTransactionManagement verifies the SQL used by the desktop +// transaction panel against a real XuguDB instance. The only killed target is +// a transaction opened by this test; no application transaction is touched. +func TestLiveXuguTransactionManagement(t *testing.T) { + if os.Getenv("XUGU_LIVE_TEST") != "1" { + t.Skip("set XUGU_LIVE_TEST=1 with XUGU_LIVE_* connection settings") + } + params := liveXuguParams(t) + params.Database = "SYSTEM" + admin, err := openDB(params) + if err != nil { + t.Fatal(err) + } + defer admin.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + var ownNode, ownSession int64 + if err := admin.QueryRowContext(ctx, "SELECT NODEID, SESSION_ID FROM SYS_SESSIONS WHERE SESSION_ID = USERENV('SID')").Scan(&ownNode, &ownSession); err != nil { + t.Fatalf("own-session SQL: %v", err) + } + if ownNode <= 0 || ownSession < 0 { + t.Fatalf("invalid own-session identity: node=%d session=%d", ownNode, ownSession) + } + + const listSQL = `SELECT T.NODEID AS NODE_ID, + CAST(T.TRANID AS VARCHAR(32)) AS TRANSACTION_ID, + S.SESSION_ID AS SESSION_ID, + S.USER_NAME AS USER_NAME, + S.DB_NAME AS DB_NAME, + S.IP AS CLIENT_IP, + T.START_T AS START_TIME +FROM SYS_ALL_TRANS T +JOIN SYS_ALL_SESSIONS S + ON T.NODEID = S.NODEID AND T.TRANID = S.CURR_TID +ORDER BY T.START_T` + rows, err := admin.QueryContext(ctx, listSQL) + if err != nil { + t.Fatalf("transaction-list SQL: %v", err) + } + if err := rows.Close(); err != nil { + t.Fatal(err) + } + + // Keep a dedicated second connection in one explicit transaction so the + // administrative session can only terminate this test-owned transaction. + worker, err := openDB(params) + if err != nil { + t.Fatal(err) + } + defer worker.Close() + conn, err := worker.Conn(ctx) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + tx, err := conn.BeginTx(ctx, &sql.TxOptions{}) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + var targetNode, targetSession int64 + var targetTransaction string + if err := tx.QueryRowContext(ctx, "SELECT NODEID, SESSION_ID, CAST(CURR_TID AS VARCHAR(32)) FROM SYS_SESSIONS WHERE SESSION_ID = USERENV('SID')").Scan(&targetNode, &targetSession, &targetTransaction); err != nil { + t.Fatalf("test-owned transaction identity: %v", err) + } + if targetNode <= 0 || targetSession < 0 || targetTransaction == "" || targetTransaction == "0" || (targetNode == ownNode && targetSession == ownSession) { + t.Fatalf("unsafe test target: node=%d session=%d transaction=%q", targetNode, targetSession, targetTransaction) + } + + var listed bool + rows, err = admin.QueryContext(ctx, listSQL) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var node, session int64 + var transaction string + var user, dbName, ip sql.NullString + var start any + if err := rows.Scan(&node, &transaction, &session, &user, &dbName, &ip, &start); err != nil { + rows.Close() + t.Fatal(err) + } + if node == targetNode && session == targetSession && transaction == targetTransaction { + listed = true + } + } + if err := rows.Err(); err != nil { + rows.Close() + t.Fatal(err) + } + rows.Close() + if !listed { + t.Fatalf("test-owned transaction %s was not listed", targetTransaction) + } + if !regexp.MustCompile(`^[1-9][0-9]*$`).MatchString(targetTransaction) { + t.Fatalf("invalid server transaction id %q", targetTransaction) + } + // Exercise the exact literal statement sent by the desktop panel. + if _, err := admin.ExecContext(ctx, fmt.Sprintf("CALL DBMS_DBA.KILL_TRANS(%d, %s)", targetNode, targetTransaction)); err != nil { + t.Fatalf("terminate test-owned transaction: %v", err) + } +} diff --git a/apps/desktop/src/components/admin/ProcessListPanel.vue b/apps/desktop/src/components/admin/ProcessListPanel.vue index f0319a0e04..6d3da69cbe 100644 --- a/apps/desktop/src/components/admin/ProcessListPanel.vue +++ b/apps/desktop/src/components/admin/ProcessListPanel.vue @@ -13,6 +13,7 @@ import * as api from "@/lib/backend/api"; import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard"; import { clampInterval, createProcessListLoadCoordinator, DEFAULT_REFRESH_SECONDS, processListExecutionError, processListSessionCount } from "@/lib/database/mysqlProcessList"; import { resolveProcessListDriverForConnection, type ProcessRow } from "@/lib/database/processListDrivers"; +import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect"; import { processListSelectionAfterClick } from "@/lib/database/processListSelection"; import { useTabUiState } from "@/lib/tabs/tabUiState"; @@ -34,12 +35,16 @@ const { initialState: restoredUiState, track: trackUiState } = useTabUiState<{ // The panel is only opened for supported engines; guard the driver defensively so // a missing one degrades to an empty table rather than crashing the render. const driver = computed(() => resolveProcessListDriverForConnection(props.connection)); +const xuguAdminRequired = computed(() => effectiveDatabaseTypeForConnection(props.connection) === "xugu" && driver.value === null); const columns = computed(() => driver.value?.columns ?? []); const numericKeys = computed(() => new Set(columns.value.filter((column) => column.numeric).map((column) => column.key))); const rows = ref([]); const truncated = ref(false); const ownSessionId = ref(null); +const ownNodeId = ref(null); +const transactionMode = computed(() => driver.value?.mode === "transaction"); +const transactionIdentityUnavailable = computed(() => transactionMode.value && (ownSessionId.value === null || ownNodeId.value === null)); const loading = ref(false); const loadCoordinator = createProcessListLoadCoordinator(); const loadError = ref(""); @@ -154,14 +159,14 @@ function requestBatchCancel() { async function confirmBatchCancel() { const targets = batchTargets.value; const activeDriver = driver.value; - if (!targets?.length || !activeDriver?.supportsBatchCancel || ownSessionId.value === null || canceling.value) return; + if (!targets?.length || !activeDriver?.supportsBatchCancel || !activeDriver.buildCancelQuerySql || ownSessionId.value === null || canceling.value) return; const connection = { ...props.connection }; const generation = connectionGeneration; const isCurrent = () => !disposed && generation === connectionGeneration; canceling.value = true; let executed = false; try { - const statements = targets.map((row) => ({ id: row.id, sql: activeDriver.buildCancelQuerySql(row.id) })); + const statements = targets.map((row) => ({ id: row.id, sql: activeDriver.buildCancelQuerySql!(row.id) })); const result = await executeWithProductionSqlGuard({ connection, database: "", @@ -296,14 +301,23 @@ async function load(options: { silent?: boolean } = {}) { try { let idResult; try { - idResult = await api.executeQuery(connectionId, "", activeDriver.ownSessionSql, undefined, undefined, { maxRows: 1 }); + idResult = await api.executeQuery(connectionId, activeDriver.database ?? "", activeDriver.ownSessionSql, undefined, undefined, { maxRows: 1 }); } catch (error) { if (!activeDriver.fallbackOwnSessionSql || !activeDriver.shouldUseFallbackOwnSessionSql?.(error)) throw error; - idResult = await api.executeQuery(connectionId, "", activeDriver.fallbackOwnSessionSql, undefined, undefined, { maxRows: 1 }); + idResult = await api.executeQuery(connectionId, activeDriver.database ?? "", activeDriver.fallbackOwnSessionSql, undefined, undefined, { maxRows: 1 }); + } + const ownRow = idResult?.rows?.[0]; + if (activeDriver.mode === "transaction") { + const nodeId = Number(ownRow?.[0]); + const sessionId = Number(ownRow?.[1]); + if (isCurrent() && Number.isSafeInteger(nodeId) && nodeId > 0 && Number.isSafeInteger(sessionId) && sessionId >= 0) { + ownNodeId.value = nodeId; + ownSessionId.value = sessionId; + } + } else { + const parsed = Number(ownRow?.[0]); + if (isCurrent() && Number.isInteger(parsed) && parsed > 0) ownSessionId.value = parsed; } - const raw = idResult?.rows?.[0]?.[0]; - const parsed = Number(raw); - if (isCurrent() && Number.isInteger(parsed) && parsed > 0) ownSessionId.value = parsed; } catch { // Non-fatal: without our own id we simply cannot dim the self row. } @@ -312,10 +326,10 @@ async function load(options: { silent?: boolean } = {}) { const listSql = fallbackListSql.value ?? activeDriver.listSql; let result; try { - result = await api.executeQuery(connectionId, "", listSql, undefined, undefined, { maxRows: activeDriver.maxRows }); + result = await api.executeQuery(connectionId, activeDriver.database ?? "", listSql, undefined, undefined, { maxRows: activeDriver.maxRows }); } catch (error) { if (fallbackListSql.value || !activeDriver.fallbackListSql || !activeDriver.shouldUseFallbackListSql?.(error)) throw error; - result = await api.executeQuery(connectionId, "", activeDriver.fallbackListSql, undefined, undefined, { maxRows: activeDriver.maxRows }); + result = await api.executeQuery(connectionId, activeDriver.database ?? "", activeDriver.fallbackListSql, undefined, undefined, { maxRows: activeDriver.maxRows }); // Cache the compatible query so old servers do not fail once per refresh. if (isCurrent()) fallbackListSql.value = activeDriver.fallbackListSql; } @@ -323,7 +337,17 @@ async function load(options: { silent?: boolean } = {}) { rows.value = activeDriver.mapRows(result); truncated.value = result.truncated === true; } catch (error: any) { - if (isCurrent()) loadError.value = error?.message || String(error); + if (isCurrent()) { + if (activeDriver.mode === "transaction") { + // A failed refresh must not leave stale kill targets on screen. A + // connection failure is not evidence that there are no transactions. + rows.value = []; + truncated.value = false; + ownSessionId.value = null; + ownNodeId.value = null; + } + loadError.value = activeDriver.mode === "transaction" ? t("processList.transactionLoadFailed", { message: error?.message || String(error) }) : error?.message || String(error); + } } finally { loading.value = false; refreshing.value = false; @@ -333,38 +357,48 @@ async function load(options: { silent?: boolean } = {}) { } function isOwnSession(row: ProcessRow): boolean { + if (transactionMode.value) return ownNodeId.value !== null && ownSessionId.value !== null && row.nodeId === ownNodeId.value && row.id === ownSessionId.value; return ownSessionId.value !== null && row.id === ownSessionId.value; } function requestCancel(row: ProcessRow) { - if (isOwnSession(row) || actionsLocked.value || refreshing.value) return; + if (isOwnSession(row) || transactionIdentityUnavailable.value || actionsLocked.value || refreshing.value) return; cancelTarget.value = row; } async function confirmCancel() { const target = cancelTarget.value; const activeDriver = driver.value; - if (!target || !activeDriver || canceling.value) return; + if (!target || !activeDriver || canceling.value || isOwnSession(target) || transactionIdentityUnavailable.value || (transactionMode.value ? !activeDriver.buildKillTransactionSql : !activeDriver.buildCancelQuerySql)) return; const connection = { ...props.connection }; const generation = connectionGeneration; const isCurrent = () => !disposed && generation === connectionGeneration; canceling.value = true; try { - const cancelSql = activeDriver.buildCancelQuerySql(target.id); + const cancelSql = transactionMode.value ? activeDriver.buildKillTransactionSql!(target) : activeDriver.buildCancelQuerySql!(target.id); let usedFallbackCancelSql = false; const executeCancelSql = async (sql: string) => { if (!isCurrent()) return undefined; - const results = await api.executeMulti(connection.id, "", sql, undefined, undefined, { maxRows: 1 }); + const results = await api.executeMulti(connection.id, activeDriver.database ?? "", sql, undefined, undefined, { maxRows: 1 }); const executionError = processListExecutionError(results); if (executionError) throw new Error(executionError); return results; }; const result = await executeWithProductionSqlGuard({ connection, - database: "", + database: activeDriver.database ?? "", sql: cancelSql, source: t("production.sourceAdmin"), execute: async () => { + if (activeDriver.mode === "transaction") { + // A confirmation dialog may stay open while the Agent reconnects. + // Refuse to kill until the executing session has been identified again. + const identity = await api.executeQuery(connection.id, activeDriver.database ?? "", activeDriver.ownSessionSql, undefined, undefined, { maxRows: 1 }); + const currentNode = Number(identity.rows?.[0]?.[0]); + const currentSession = Number(identity.rows?.[0]?.[1]); + if (!Number.isSafeInteger(currentNode) || currentNode <= 0 || !Number.isSafeInteger(currentSession) || currentSession < 0) throw new Error(t("processList.transactionNeedsSession")); + if (currentNode === target.nodeId && currentSession === target.id) throw new Error(t("processList.transactionCannotKillSelf")); + } try { return await executeCancelSql(cancelSql); } catch (error) { @@ -377,10 +411,10 @@ async function confirmCancel() { if (result === undefined || !isCurrent()) return; const cancelResultError = usedFallbackCancelSql ? activeDriver.fallbackCancelQueryResultError?.(result) : activeDriver.cancelQueryResultError?.(result); if (cancelResultError) throw new Error(cancelResultError); - toast(t("processList.killSuccess", { id: target.id }), 2500); + toast(t(activeDriver.mode === "transaction" ? "processList.transactionKillSuccess" : "processList.killSuccess", { id: target.transactionId ?? target.id }), 2500); cancelTarget.value = null; } catch (error: any) { - if (isCurrent()) toast(t("processList.killFailed", { message: error?.message || String(error) }), 5000); + if (isCurrent()) toast(t(activeDriver.mode === "transaction" ? "processList.transactionKillFailed" : "processList.killFailed", { message: error?.message || String(error) }), 5000); } finally { canceling.value = false; if (cancelTarget.value === null) void load({ silent: true }); @@ -485,6 +519,7 @@ watch( rows.value = []; truncated.value = false; ownSessionId.value = null; + ownNodeId.value = null; search.value = ""; sortKey.value = driver.value?.defaultSortKey ?? "time"; sortDir.value = "desc"; @@ -501,13 +536,21 @@ onBeforeUnmount(() => {