25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(sidebar): keep destructive table operations cancellable
Melody Ruch89e0f1734ba7
diff --git a/apps/desktop/src/components/editor/DangerConfirmDialog.vue b/apps/desktop/src/components/editor/DangerConfirmDialog.vueindex cabe1fa7f9..876a74de2c 100644--- a/apps/desktop/src/components/editor/DangerConfirmDialog.vue+++ b/apps/desktop/src/components/editor/DangerConfirmDialog.vue@@ -33,6 +33,8 @@ const props = withDefaults(suppressToggleLabel?: string;loading?: boolean;closeOnConfirm?: boolean;+ cancelable?: boolean;+ cancelRunningLoading?: boolean;}>(),{sql: "",@@ -45,11 +47,14 @@ const props = withDefaults(suppressToggleLabel: "",loading: false,closeOnConfirm: true,+ cancelable: false,+ cancelRunningLoading: false,},);const emit = defineEmits<{confirm: [];+ "cancel-running": [];}>();const code = computed(() => props.details || props.sql);@@ -119,7 +124,11 @@ async function copyFullCode() {</div><DialogFooter>- <Button variant="outline" :disabled="loading" @click="open = false">{{ t("dangerDialog.cancel") }}</Button>+ <Button v-if="loading && cancelable" variant="outline" :disabled="cancelRunningLoading" @click="$emit('cancel-running')">+ <Loader2 v-if="cancelRunningLoading" class="h-3.5 w-3.5 animate-spin" />+ {{ t("dangerDialog.cancelRunning") }}+ </Button>+ <Button v-else variant="outline" :disabled="loading" @click="open = false">{{ t("dangerDialog.cancel") }}</Button><Button variant="destructive" class="gap-1.5" :disabled="loading" @click="onConfirm"><Loader2 v-if="loading" class="h-3.5 w-3.5 animate-spin" />{{ confirmLabel || t("dangerDialog.confirm") }}diff --git a/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts b/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.tsindex 373bd13af6..6235136c3c 100644--- a/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts+++ b/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts@@ -20,7 +20,7 @@ vi.mock("@/lib/common/clipboard", () => ({const mountedApps: App[] = [];-async function mountDialog(sql: string) {+async function mountDialog(sql: string, extraProps: Record<string, unknown> = {}, listeners: Record<string, (...args: any[]) => void> = {}) {const state = reactive({ open: true });const container = document.createElement("div");document.body.append(container);@@ -30,6 +30,8 @@ async function mountDialog(sql: string) {h(DangerConfirmDialog, {open: state.open,sql,+ ...extraProps,+ ...listeners,"onUpdate:open": (value: boolean) => {state.open = value;},@@ -106,3 +108,51 @@ describe("DangerConfirmDialog SQL preview", () => {expect(copyToClipboard).toHaveBeenCalledWith(sql);});});++describe("DangerConfirmDialog running/cancel footer state", () => {+ function footerButtons() {+ const footer = document.body.querySelectorAll("button");+ return Array.from(footer);+ }++ it("keeps the default Cancel button unchanged when cancelable is not set (existing callers)", async () => {+ await mountDialog("DROP TABLE users;", { loading: true });++ const buttons = footerButtons();+ const cancelButton = buttons.find((button) => button.textContent?.trim() === "Cancel");+ expect(cancelButton).toBeDefined();+ expect(cancelButton?.disabled).toBe(true);+ expect(buttons.some((button) => button.textContent?.trim() === "Cancel Query")).toBe(false);+ });++ it("shows an active Cancel Query button while loading when cancelable is true", async () => {+ const onCancelRunning = vi.fn();+ await mountDialog("DELETE FROM big_orders;", { loading: true, cancelable: true }, { onCancelRunning });++ const buttons = footerButtons();+ const cancelRunningButton = buttons.find((button) => button.textContent?.trim() === "Cancel Query");+ expect(cancelRunningButton).toBeDefined();+ expect(cancelRunningButton?.disabled).toBe(false);++ cancelRunningButton?.click();+ await nextTick();++ expect(onCancelRunning).toHaveBeenCalledOnce();+ });++ it("disables the Cancel Query button while the cancel itself is in flight", async () => {+ await mountDialog("DELETE FROM big_orders;", { loading: true, cancelable: true, cancelRunningLoading: true });++ const buttons = footerButtons();+ const cancelRunningButton = buttons.find((button) => button.textContent?.trim() === "Cancel Query");+ expect(cancelRunningButton?.disabled).toBe(true);+ });++ it("does not show the Cancel Query button when cancelable is true but not loading", async () => {+ await mountDialog("DELETE FROM big_orders;", { loading: false, cancelable: true });++ const buttons = footerButtons();+ expect(buttons.some((button) => button.textContent?.trim() === "Cancel Query")).toBe(false);+ expect(buttons.some((button) => button.textContent?.trim() === "Cancel")).toBe(true);+ });+});diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vueindex c94a455ce5..5ec4c4243e 100644--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue@@ -62,7 +62,7 @@ import { sqlFormatDialectForDbType } from "@/lib/sql/sqlFormatter";import { createSidebarActionTarget, findSidebarActionTarget, matchesSidebarActionTarget, type SidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";import { syncSidebarTreeNodeExpansion } from "@/lib/sidebar/sidebarTreeExpansion";import type { SidebarDangerDialogRequest } from "@/lib/sidebar/sidebarDangerDialog";-import { resetSidebarTreeDialogState } from "./sidebarTreeDialogState";+import { resetSidebarTreeDialogState, sidebarDangerRunningExecutionId } from "./sidebarTreeDialogState";import { SidebarDangerConfirmDialog, SidebarDdlViewDialog, SidebarObjectSourceDialog, SidebarProcedureExecutionDialog, SidebarVisibleDatabasesDialog, SidebarVisibleNacosNamespacesDialog, SidebarVisibleSchemasDialog } from "./sidebarAsyncDialogs";import { sortConnectionListForDisplay } from "@/lib/sidebar/connectionListSort";import { sidebarDisplayTableName } from "@/lib/sidebar/sidebarTableNameDisplay";@@ -103,6 +103,7 @@ const sidebarContextMenuTarget = ref<SidebarActionTarget | null>(null);const sidebarDangerDialogRequest = ref<SidebarDangerDialogRequest | null>(null);const sidebarDangerDialogOpen = ref(false);const sidebarDangerDialogConfirming = ref(false);+const sidebarDangerDialogCancelling = ref(false);const sidebarTreeItemDialogController = ref<Record<string, any> | null>(null);const sidebarInstallExtensionTarget = ref<TreeNode | null>(null);const sidebarInstallExtensionDialogRef = ref<InstanceType<typeof InstallExtensionDialog> | null>(null);@@ -1594,6 +1595,11 @@ function openSidebarContextMenu(event: MouseEvent, node: TreeNode, openContextMefunction openSidebarDangerDialog(request: SidebarDangerDialogRequest) {sidebarDangerDialogRequest.value = request;sidebarDangerDialogConfirming.value = false;+ // Defense in depth: sidebarDangerDialogCancelling is a singleton shared+ // across every danger dialog. It should already settle on its own (see+ // confirmCancelWithRetryAndTimeout), but a fresh dialog must never inherit+ // a stuck "cancelling" state from a previous one.+ sidebarDangerDialogCancelling.value = false;sidebarDangerDialogOpen.value = true;}@@ -1604,9 +1610,43 @@ async function confirmSidebarDangerDialog() {sidebarDangerDialogConfirming.value = true;try {await request.confirm();- sidebarDangerDialogOpen.value = false;} finally {+ // A danger operation that hit a client-observed timeout is kept alive+ // (still cancellable) rather than settled outright — sidebarDangerRunningExecutionId+ // stays populated in that case, so keep the dialog "loading" (Cancel+ // Query still live, manual dismiss blocked) instead of closing on a+ // stale timeout result. The watcher below finishes the job once the+ // execution actually settles.+ if (!sidebarDangerRunningExecutionId.value) {+ sidebarDangerDialogConfirming.value = false;+ sidebarDangerDialogOpen.value = false;+ }+ }+}++// Finishes closing a danger dialog left open past a client-observed timeout+// once the deferred execution is actually confirmed cancelled — see+// confirmSidebarDangerDialog above.+watch(sidebarDangerRunningExecutionId, (value) => {+ if (!value && sidebarDangerDialogConfirming.value) {sidebarDangerDialogConfirming.value = false;+ sidebarDangerDialogOpen.value = false;+ }+});++async function cancelSidebarDangerDialogRunning() {+ const request = sidebarDangerDialogRequest.value;+ if (!request?.cancelRunning || sidebarDangerDialogCancelling.value) return;+ sidebarDangerDialogCancelling.value = true;+ try {+ await request.cancelRunning();+ } catch (error: any) {+ // Current cancelRunning implementations already swallow their own+ // rejections; this is a defensive fallback so the user still gets+ // feedback if a future implementation throws instead.+ toast(t("contextMenu.tableOperationFailed", { message: error?.message || String(error) }), 5000);+ } finally {+ sidebarDangerDialogCancelling.value = false;}}@@ -2433,7 +2473,10 @@ defineExpose({ focusSearch, createNewGroup, collapseAllTreeNodes });:confirm-label="sidebarDangerDialogRequest.confirmLabel":loading="sidebarDangerDialogConfirming || sidebarDangerDialogRequest.loading":close-on-confirm="false"+ :cancelable="!!sidebarDangerDialogRequest.cancelRunning"+ :cancel-running-loading="sidebarDangerDialogCancelling"@confirm="confirmSidebarDangerDialog"+ @cancel-running="cancelSidebarDangerDialogRunning"><template #options><div v-if="sidebarDangerDialogConfirming && sidebarDangerDialogRequest.progress" class="mb-3 rounded-md border bg-muted/20 px-3 py-2.5">diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vueindex 0beac59d15..6eb463cb35 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue@@ -68,6 +68,8 @@ import { useToast } from "@/composables/useToast";import { useDatabaseOptions } from "@/composables/useDatabaseOptions";import type { ColumnInfo, DatabaseType, TreeNode, TreeNodeType } from "@/types/database";import * as api from "@/lib/backend/api";+import { queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";+import { uuid } from "@/lib/common/utils";import { resolveDefaultDatabase } from "@/lib/database/defaultDatabase";import { connectionUsesVisibleSchemaFilter } from "@/lib/database/visibleDatabases";import { canTreeNodePin, canTreeNodeShowExpander } from "@/lib/sidebar/sidebarTreeItemLayout";@@ -175,6 +177,7 @@ import {fallbackCreateDatabaseCharset,sidebarTreeDialogOwner,sidebarDangerTarget,+ sidebarDangerRunningCancel,sidebarFormTarget,showDeleteConfirm,showDropTableConfirm,@@ -2490,15 +2493,29 @@ function openRenameObjectDialog() {showRenameObjectDialog.value = true;}-async function executeTreeNodeSqlWithProductionGuard(node: Pick<TreeNode, "connectionId" | "database" | "schema">, sql: string, options: { database?: string; schema?: string; executeAsScript?: boolean } = {}) {+async function executeTreeNodeSqlWithProductionGuard(+ node: Pick<TreeNode, "connectionId" | "database" | "schema">,+ sql: string,+ options: { database?: string; schema?: string; executeAsScript?: boolean; executionId?: string; isCancelledBeforeDispatch?: () => boolean; markDispatched?: () => void } = {},+) {if (!node.connectionId) return undefined;const database = options.database ?? node.database ?? "";+ const config = connectionStore.getConfig(node.connectionId);+ const timeoutSecs = queryTimeoutSecsForConnection(config, settingsStore.editorSettings.globalQueryTimeoutSecs);+ const executionId = options.executionId ?? uuid();return executeWithProductionSqlGuard({- connection: connectionStore.getConfig(node.connectionId),+ connection: config,database,sql,source: t("production.sourceSidebar"),- execute: () => (options.executeAsScript ? api.executeScript(node.connectionId!, database, sql, options.schema ?? node.schema) : api.executeQuery(node.connectionId!, database, sql, options.schema ?? node.schema)),+ execute: () => {+ // The caller may have observed a cancel click while we were still+ // waiting on connection setup or the production-safety confirmation+ // above — if so, never actually dispatch the SQL to the backend.+ if (options.isCancelledBeforeDispatch?.()) throw new Error("Operation cancelled before it was sent to the database.");+ options.markDispatched?.();+ return options.executeAsScript ? api.executeScript(node.connectionId!, database, sql, options.schema ?? node.schema) : api.executeQuery(node.connectionId!, database, sql, options.schema ?? node.schema, executionId, { timeoutSecs });+ },});}@@ -3965,6 +3982,8 @@ routeDangerDialog(showDropTableConfirm, () =>},}: undefined,+ closeOnConfirm: false,+ cancelRunning: () => sidebarDangerRunningCancel.value?.(),confirm: confirmDropTable,}),);@@ -3997,6 +4016,8 @@ routeDangerDialog(showEmptyTableConfirm, () =>return emptyTablePreviewSql.value;},confirmLabel: t("contextMenu.emptyTable"),+ closeOnConfirm: false,+ cancelRunning: () => sidebarDangerRunningCancel.value?.(),confirm: confirmEmptyTable,}),);@@ -4032,6 +4053,8 @@ routeDangerDialog(showTruncateTableConfirm, () =>},}: undefined,+ closeOnConfirm: false,+ cancelRunning: () => sidebarDangerRunningCancel.value?.(),confirm: confirmTruncateTable,}),);diff --git a/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts b/apps/desktop/src/components/sidebar/sidebarTreeDialogState.tsindex 68d3c70466..c4cd53f465 100644--- a/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts+++ b/apps/desktop/src/components/sidebar/sidebarTreeDialogState.ts@@ -14,6 +14,8 @@ export const fallbackCreateDatabaseCharset = fallbackCreateDatabaseCharsetMetadaexport const sidebarTreeDialogOwner = shallowRef<symbol | null>(null);export const sidebarDangerTarget = shallowRef<TreeNode | null>(null);+export const sidebarDangerRunningExecutionId = ref<string>("");+export const sidebarDangerRunningCancel = ref<(() => void | Promise<void>) | null>(null);export const sidebarFormTarget = shallowRef<TreeNode | null>(null);export const connectionDeleteTargetSnapshot = ref<ConnectionDeleteTarget[]>([]);export const connectionGroupDeleteTargetSnapshot = ref<ConnectionGroupDeleteTarget[]>([]);diff --git a/apps/desktop/src/composables/__tests__/useSidebarTableMutationRuntime.saphana.spec.ts b/apps/desktop/src/composables/__tests__/useSidebarTableMutationRuntime.saphana.spec.tsindex 9fea94fbaa..7cde3cf1e3 100644--- a/apps/desktop/src/composables/__tests__/useSidebarTableMutationRuntime.saphana.spec.ts+++ b/apps/desktop/src/composables/__tests__/useSidebarTableMutationRuntime.saphana.spec.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { shallowRef } from "vue";import type { TreeNode } from "@/types/database";-import { dropTableCascade, dropTablePreviewSql, emptyTablePreviewSql, sidebarDangerTarget, truncateTableCascade, truncateTablePreviewSql } from "@/components/sidebar/sidebarTreeDialogState";+import { dropTableCascade, dropTablePreviewSql, emptyTablePreviewSql, sidebarDangerRunningCancel, sidebarDangerRunningExecutionId, sidebarDangerTarget, truncateTableCascade, truncateTablePreviewSql } from "@/components/sidebar/sidebarTreeDialogState";const mocks = vi.hoisted(() => ({toast: vi.fn(),@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({refreshMutatedTableDataTabsForNode: vi.fn(),removeTreeNode: vi.fn(),releaseActiveNodeReference: vi.fn(),+ cancelQuery: vi.fn(),}));vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));@@ -24,6 +25,7 @@ vi.mock("@/lib/database/dbAdminSql", async (importOriginal) => ({buildEmptyTableSql: mocks.buildEmptyTableSql,buildTruncateTableSql: mocks.buildTruncateTableSql,}));+vi.mock("@/lib/backend/api", () => ({ cancelQuery: mocks.cancelQuery }));import { useSidebarTableMutationRuntime } from "@/composables/useSidebarTableMutationRuntime";@@ -71,13 +73,19 @@ describe("useSidebarTableMutationRuntime SAP HANA schema-scoped actions", () =>beforeEach(() => {vi.clearAllMocks();sidebarDangerTarget.value = null;+ sidebarDangerRunningExecutionId.value = "";+ sidebarDangerRunningCancel.value = null;dropTablePreviewSql.value = "";emptyTablePreviewSql.value = "";truncateTablePreviewSql.value = "";dropTableCascade.value = false;truncateTableCascade.value = false;mocks.ensureConnected.mockResolvedValue(undefined);- mocks.executeWithProductionGuard.mockResolvedValue(undefined);+ // A non-undefined result models the real executeWithProductionGuard+ // resolving to whatever execute() returned (a QueryResult); it only+ // resolves to `undefined` when the user declines the production-safety+ // confirmation — see the dedicated "declines" test below.+ mocks.executeWithProductionGuard.mockResolvedValue({});mocks.refreshMutatedTableDataTabsForNode.mockResolvedValue(undefined);mocks.buildDropTableSql.mockResolvedValue('DROP TABLE "APP"."ORDERS";');mocks.buildEmptyTableSql.mockResolvedValue('DELETE FROM "APP"."ORDERS";');@@ -94,7 +102,13 @@ describe("useSidebarTableMutationRuntime SAP HANA schema-scoped actions", () =>expect(builder).toHaveBeenCalledOnce();expect(builder).toHaveBeenCalledWith({ databaseType: "saphana", schema: "APP", tableName: "ORDERS" });expect(mocks.executeWithProductionGuard).toHaveBeenCalledOnce();- expect(mocks.executeWithProductionGuard).toHaveBeenCalledWith(node, sql, { database: "", schema: "APP" });+ expect(mocks.executeWithProductionGuard).toHaveBeenCalledWith(node, sql, {+ database: "",+ schema: "APP",+ executionId: expect.any(String),+ isCancelledBeforeDispatch: expect.any(Function),+ markDispatched: expect.any(Function),+ });});it("removes the dropped table and releases its active reference", async () => {@@ -120,7 +134,13 @@ describe("useSidebarTableMutationRuntime SAP HANA schema-scoped actions", () =>await feature[action]();- expect(mocks.executeWithProductionGuard).toHaveBeenCalledWith(node, sql, { database: "TENANT", schema: "APP" });+ expect(mocks.executeWithProductionGuard).toHaveBeenCalledWith(node, sql, {+ database: "TENANT",+ schema: "APP",+ executionId: expect.any(String),+ isCancelledBeforeDispatch: expect.any(Function),+ markDispatched: expect.any(Function),+ });});it.each([null, undefined])("rejects a %s database context", async (database) => {@@ -158,4 +178,186 @@ describe("useSidebarTableMutationRuntime SAP HANA schema-scoped actions", () =>expect(mocks.refreshMutatedTableDataTabsForNode).not.toHaveBeenCalled();expect(mocks.toast).toHaveBeenCalledWith("contextMenu.tableOperationFailed", 5000);});++ it("registers a running-execution cancel handler while empty table is in flight, and clears it afterward", async () => {+ const { feature } = runtime("");+ mocks.executeWithProductionGuard.mockImplementationOnce(async () => {+ expect(sidebarDangerRunningExecutionId.value).not.toBe("");+ expect(sidebarDangerRunningCancel.value).toBeTypeOf("function");+ });++ await feature.confirmEmptyTable();++ expect(sidebarDangerRunningExecutionId.value).toBe("");+ expect(sidebarDangerRunningCancel.value).toBeNull();+ });++ it("shows a timed-out (not failed) toast when the query is still running server-side, and keeps the cancel handle alive", async () => {+ const { feature } = runtime("");+ mocks.executeWithProductionGuard.mockImplementationOnce(async (_node: unknown, _sql: unknown, options: { markDispatched: () => void }) => {+ options.markDispatched();+ throw new Error("Query timed out after 60 seconds");+ });++ await feature.confirmEmptyTable();++ expect(mocks.toast).toHaveBeenCalledWith("contextMenu.tableOperationTimedOut", 8000);+ expect(mocks.toast).not.toHaveBeenCalledWith("contextMenu.tableOperationFailed", 5000);+ // A client-observed timeout must not remove the user's ability to cancel+ // — the underlying operation may still be running on the database.+ expect(sidebarDangerRunningExecutionId.value).not.toBe("");+ expect(sidebarDangerRunningCancel.value).toBeTypeOf("function");+ });++ it("classifies a JDBC-agent-routed timeout (SAP HANA/Oracle/DB2/SQL Server) as timed-out, not failed, even though its message has no timeout wording", async () => {+ const { feature } = runtime("");+ // AgentCallError::Timeout carries no `detail` (crates/dbx-core/src/backend_error.rs),+ // so BackendErrorException.message degrades to a generic fallback with no+ // "timed out" text — only the structured backendError distinguishes it.+ const agentTimeoutError = {+ name: "BackendErrorException",+ message: "Backend request failed",+ backendError: {+ version: 1,+ code: "DBX-JDBC-2001",+ messageKey: "backendErrors.jdbc.operationTimedOut",+ messageParams: { stage: "execute" },+ source: "jdbcAgent",+ operationOutcome: "unknown",+ },+ };+ mocks.executeWithProductionGuard.mockImplementationOnce(async (_node: unknown, _sql: unknown, options: { markDispatched: () => void }) => {+ options.markDispatched();+ throw agentTimeoutError;+ });++ await feature.confirmEmptyTable();++ expect(mocks.toast).toHaveBeenCalledWith("contextMenu.tableOperationTimedOut", 8000);+ expect(mocks.toast).not.toHaveBeenCalledWith("contextMenu.tableOperationFailed", 5000);+ // The cancel entry point must stay live for this database family too.+ expect(sidebarDangerRunningExecutionId.value).not.toBe("");+ expect(sidebarDangerRunningCancel.value).toBeTypeOf("function");+ });++ it("shows a cancelled toast when the user explicitly cancels the running query", async () => {+ const { feature } = runtime("");+ mocks.cancelQuery.mockResolvedValueOnce(true);+ mocks.executeWithProductionGuard.mockImplementationOnce(async (_node: unknown, _sql: unknown, options: { markDispatched: () => void }) => {+ options.markDispatched();+ await sidebarDangerRunningCancel.value?.();+ throw new Error("Query timed out after 60 seconds");+ });++ await feature.confirmEmptyTable();++ expect(mocks.cancelQuery).toHaveBeenCalledOnce();+ expect(mocks.toast).toHaveBeenCalledWith("contextMenu.tableOperationCancelled", 3000);+ expect(mocks.toast).not.toHaveBeenCalledWith("contextMenu.tableOperationTimedOut", 8000);+ expect(mocks.toast).not.toHaveBeenCalledWith("contextMenu.tableOperationFailed", 5000);+ expect(sidebarDangerRunningExecutionId.value).toBe("");+ expect(sidebarDangerRunningCancel.value).toBeNull();+ });++ it("never dispatches the SQL when the user cancels before the operation is sent to the database (registration race)", async () => {+ const { feature } = runtime("");+ mocks.ensureConnected.mockImplementationOnce(async () => {+ // The user clicks Cancel Query while we're still waiting on the+ // connection — well before the backend has any executionId to+ // register, let alone cancel.+ await sidebarDangerRunningCancel.value?.();+ });++ await feature.confirmEmptyTable();++ expect(mocks.executeWithProductionGuard).not.toHaveBeenCalled();+ expect(mocks.cancelQuery).not.toHaveBeenCalled();+ expect(mocks.toast).toHaveBeenCalledWith("contextMenu.tableOperationCancelled", 3000);+ expect(mocks.toast).not.toHaveBeenCalledWith("contextMenu.tableOperationFailed", 5000);+ expect(sidebarDangerRunningExecutionId.value).toBe("");+ expect(sidebarDangerRunningCancel.value).toBeNull();+ });++ it("does not report a false 'cancelled' outcome when the backend never confirms the cancel", async () => {+ const { feature } = runtime("");+ mocks.cancelQuery.mockResolvedValue(false);+ mocks.executeWithProductionGuard.mockImplementationOnce(async (_node: unknown, _sql: unknown, options: { markDispatched: () => void }) => {+ options.markDispatched();+ await sidebarDangerRunningCancel.value?.();+ throw new Error("some backend error unrelated to timeout");+ });++ await feature.confirmEmptyTable();++ // Bounded retry, not a single silently-ignored attempt.+ expect(mocks.cancelQuery.mock.calls.length).toBeGreaterThan(1);+ expect(mocks.toast).toHaveBeenCalledWith("contextMenu.tableOperationCancelUnconfirmed", 8000);+ expect(mocks.toast).not.toHaveBeenCalledWith("contextMenu.tableOperationCancelled", 3000);+ expect(mocks.toast).not.toHaveBeenCalledWith("contextMenu.tableOperationFailed", 5000);+ expect(sidebarDangerRunningExecutionId.value).toBe("");+ });++ it("lets a cancel confirmed after a timeout finish closing out the running execution", async () => {+ const { feature } = runtime("");+ mocks.executeWithProductionGuard.mockImplementationOnce(async (_node: unknown, _sql: unknown, options: { markDispatched: () => void }) => {+ options.markDispatched();+ throw new Error("Query timed out after 60 seconds");+ });++ await feature.confirmEmptyTable();+ expect(sidebarDangerRunningExecutionId.value).not.toBe("");+ mocks.toast.mockClear();++ // The dialog's Cancel Query button is still wired to the same handle;+ // the user clicks it after the timeout and the backend now confirms it.+ mocks.cancelQuery.mockResolvedValueOnce(true);+ await sidebarDangerRunningCancel.value?.();++ expect(mocks.toast).toHaveBeenCalledWith("contextMenu.tableOperationCancelled", 3000);+ expect(sidebarDangerRunningExecutionId.value).toBe("");+ expect(sidebarDangerRunningCancel.value).toBeNull();+ });++ it("does not let the cancel handle hang forever if cancelQuery itself never resolves", async () => {+ const { feature } = runtime("");+ mocks.executeWithProductionGuard.mockImplementationOnce(async (_node: unknown, _sql: unknown, options: { markDispatched: () => void }) => {+ options.markDispatched();+ throw new Error("Query timed out after 60 seconds");+ });++ await feature.confirmEmptyTable();+ expect(sidebarDangerRunningExecutionId.value).not.toBe("");++ vi.useFakeTimers();+ try {+ // A wedged connection: cancelQuery never settles at all.+ mocks.cancelQuery.mockImplementation(() => new Promise(() => {}));+ const cancelPromise = sidebarDangerRunningCancel.value?.();+ // CANCEL_QUERY_OVERALL_TIMEOUT_MS is 10s; advance past it.+ await vi.advanceTimersByTimeAsync(11_000);+ await cancelPromise;+ } finally {+ vi.useRealTimers();+ }++ // The closure above must have settled instead of hanging — a stuck+ // cancel handle would otherwise permanently disable the shared+ // sidebarDangerDialogCancelling state for every future danger dialog.+ expect(mocks.toast).not.toHaveBeenCalledWith("contextMenu.tableOperationCancelled", 3000);+ });++ it.each(actions)("does not report a false success for $action when the user declines the production-safety confirmation", async ({ action }) => {+ const { feature } = runtime("");+ mocks.executeWithProductionGuard.mockResolvedValueOnce(undefined);++ await feature[action]();++ expect(mocks.toast).not.toHaveBeenCalled();+ expect(mocks.closeDroppedTableObjectTabsForNode).not.toHaveBeenCalled();+ expect(mocks.removeTreeNode).not.toHaveBeenCalled();+ expect(mocks.releaseActiveNodeReference).not.toHaveBeenCalled();+ expect(mocks.refreshMutatedTableDataTabsForNode).not.toHaveBeenCalled();+ expect(sidebarDangerRunningExecutionId.value).toBe("");+ expect(sidebarDangerRunningCancel.value).toBeNull();+ });});diff --git a/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts b/apps/desktop/src/composables/useSidebarTableMutationRuntime.tsindex ca76a8acc7..1f68db45ad 100644--- a/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts+++ b/apps/desktop/src/composables/useSidebarTableMutationRuntime.ts@@ -6,8 +6,14 @@ import type { DatabaseType, TreeNode } from "@/types/database";import { supportsTableTruncate } from "@/lib/database/databaseCapabilities";import { buildDropTableSql, buildEmptyTableSql, buildMysqlAutoIncrementSql, buildTruncateTableSql, supportsDropTableCascade, supportsNativeMysqlAutoIncrement, supportsTruncateTableCascade, type MysqlAutoIncrementSqlOptions, type TableAdminSqlOptions } from "@/lib/database/dbAdminSql";import { isSqlServerLinkedNode } from "@/lib/database/sqlServerLinkedServers";+import { isQueryTimeoutErrorMessage } from "@/lib/sql/queryError";+import { uuid } from "@/lib/common/utils";+import * as api from "@/lib/backend/api";+import { normalizeBackendError, type BackendError } from "@/lib/backend/errorUtils";import {sidebarDangerTarget,+ sidebarDangerRunningExecutionId,+ sidebarDangerRunningCancel,showDropTableConfirm,showEmptyTableConfirm,showMysqlAutoIncrementConfirm,@@ -28,7 +34,7 @@ interface SidebarTableMutationRuntimeOptions {connectionStore: ReturnType<typeof useConnectionStore>;currentDatabaseType: () => DatabaseType | undefined;databaseTypeForNode: (node: TreeNode) => DatabaseType | undefined;- executeWithProductionGuard: (node: Pick<TreeNode, "connectionId" | "database" | "schema">, sql: string, options?: { database?: string; schema?: string }) => Promise<unknown>;+ executeWithProductionGuard: (node: Pick<TreeNode, "connectionId" | "database" | "schema">, sql: string, options?: { database?: string; schema?: string; executionId?: string; isCancelledBeforeDispatch?: () => boolean; markDispatched?: () => void }) => Promise<unknown>;closeDroppedTableObjectTabsForNode: (node: TreeNode) => void;refreshMutatedTableDataTabsForNode: (node: TreeNode) => Promise<void>;}@@ -151,19 +157,134 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRuntawait connectionStore.refreshObjectListTreeNode(node.connectionId, node.database, node.schema);}+ // Bounded, undelayed retry: register_task on the backend runs as the very+ // first statement of the execute_query command, so if cancelQuery races a+ // just-dispatched execution, a couple of retries are enough for the+ // registration to land — no artificial delay needed.+ const CANCEL_QUERY_MAX_ATTEMPTS = 5;+ // Overall cap on the whole retry sequence, mirroring queryStore.ts's+ // withCancelQueryTimeout/CANCEL_QUERY_TIMEOUT_MS for the main editor. If+ // api.cancelQuery itself hangs (e.g. a wedged connection), the retry loop+ // alone would never settle, which would permanently disable every future+ // danger dialog's Cancel Query button (sidebarDangerDialogCancelling is a+ // shared singleton — see ConnectionTree.vue).+ const CANCEL_QUERY_OVERALL_TIMEOUT_MS = 10_000;++ async function confirmCancelWithRetry(executionId: string): Promise<boolean> {+ for (let attempt = 0; attempt < CANCEL_QUERY_MAX_ATTEMPTS; attempt++) {+ let confirmed = false;+ try {+ confirmed = await api.cancelQuery(executionId);+ } catch {+ confirmed = false;+ }+ if (confirmed) return true;+ }+ return false;+ }++ function confirmCancelWithRetryAndTimeout(executionId: string): Promise<boolean> {+ const timeout = new Promise<boolean>((resolve) => {+ setTimeout(() => resolve(false), CANCEL_QUERY_OVERALL_TIMEOUT_MS);+ });+ return Promise.race([confirmCancelWithRetry(executionId), timeout]);+ }++ const DANGER_OPERATION_CANCELLED_BEFORE_DISPATCH_MESSAGE = "Operation cancelled before it was sent to the database.";++ interface DangerRunningExecution {+ executionId: string;+ isCancelledBeforeDispatch: () => boolean;+ markDispatched: () => void;+ wasCancelled: () => boolean;+ cancelConfirmed: () => boolean;+ markHandedOff: () => void;+ }++ function beginDangerRunningExecution(nodeLabel: string): DangerRunningExecution {+ const executionId = uuid();+ let dispatched = false;+ let cancelledByUser = false;+ let cancelConfirmedFlag = false;+ // Set once the owning confirm*Table() call has already given up waiting+ // (a client-observed timeout) and deferred final cleanup to a later+ // confirmed cancel — see markHandedOff below.+ let handedOff = false;++ sidebarDangerRunningExecutionId.value = executionId;+ sidebarDangerRunningCancel.value = async () => {+ cancelledByUser = true;+ // Nothing has reached the backend yet: the pending dispatch will see+ // isCancelledBeforeDispatch() and skip the network call entirely, so+ // this is already a confirmed cancellation.+ const confirmed = dispatched ? await confirmCancelWithRetryAndTimeout(executionId) : true;+ if (confirmed) cancelConfirmedFlag = true;+ if (handedOff && confirmed && sidebarDangerRunningExecutionId.value === executionId) {+ toast(t("contextMenu.tableOperationCancelled", { name: nodeLabel }), 3000);+ endDangerRunningExecution();+ }+ };++ return {+ executionId,+ isCancelledBeforeDispatch: () => cancelledByUser && !dispatched,+ markDispatched: () => {+ dispatched = true;+ },+ wasCancelled: () => cancelledByUser,+ cancelConfirmed: () => cancelConfirmedFlag,+ markHandedOff: () => {+ handedOff = true;+ },+ };+ }++ function endDangerRunningExecution() {+ sidebarDangerRunningExecutionId.value = "";+ sidebarDangerRunningCancel.value = null;+ }++ function toastDangerOperationError(name: string, message: string, wasCancelled: boolean, cancelConfirmed: boolean, backendError?: BackendError) {+ if (cancelConfirmed) {+ toast(t("contextMenu.tableOperationCancelled", { name }), 3000);+ } else if (wasCancelled) {+ toast(t("contextMenu.tableOperationCancelUnconfirmed", { name, message }), 8000);+ } else if (isQueryTimeoutErrorMessage(message, backendError)) {+ toast(t("contextMenu.tableOperationTimedOut", { name, message }), 8000);+ } else {+ toast(t("contextMenu.tableOperationFailed", { message }), 5000);+ }+ }+async function confirmDropTable() {const node = sidebarDangerTarget.value ?? activeNode.value;if (!node.connectionId || node.database == null) return;+ const { executionId, isCancelledBeforeDispatch, markDispatched, wasCancelled, cancelConfirmed, markHandedOff } = beginDangerRunningExecution(node.label);try {await connectionStore.ensureConnected(node.connectionId);const sql = dropTablePreviewSql.value || (await buildDropTableSql(tableAdminSqlOptionsForNode(node, { cascade: dropTableCascade.value && supportsDropTableCascade(databaseTypeForNode(node)) })));- await options.executeWithProductionGuard(node, sql, { database: node.database, schema: node.schema });+ if (isCancelledBeforeDispatch()) throw new Error(DANGER_OPERATION_CANCELLED_BEFORE_DISPATCH_MESSAGE);+ const executed = await options.executeWithProductionGuard(node, sql, { database: node.database, schema: node.schema, executionId, isCancelledBeforeDispatch, markDispatched });+ if (executed === undefined) {+ // The user declined the production-safety confirmation: the SQL was+ // never sent, so this must not be reported as a successful drop.+ endDangerRunningExecution();+ return;+ }toast(t("contextMenu.dropTableSuccess", { name: node.label }), 3000);options.closeDroppedTableObjectTabsForNode(node);connectionStore.removeTreeNode(node.id);options.releaseActiveNodeReference([node.id]);+ endDangerRunningExecution();} catch (error: any) {- toast(t("contextMenu.tableOperationFailed", { message: error?.message || String(error) }), 5000);+ const message = error?.message || String(error);+ const backendError = normalizeBackendError(error) ?? undefined;+ toastDangerOperationError(node.label, message, wasCancelled(), cancelConfirmed(), backendError);+ if (cancelConfirmed() || !isQueryTimeoutErrorMessage(message, backendError)) {+ endDangerRunningExecution();+ } else {+ markHandedOff();+ }}}@@ -175,15 +296,31 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRuntasync function confirmEmptyTable() {const node = sidebarDangerTarget.value ?? activeNode.value;if (!node.connectionId || node.database == null) return;+ const { executionId, isCancelledBeforeDispatch, markDispatched, wasCancelled, cancelConfirmed, markHandedOff } = beginDangerRunningExecution(node.label);try {await connectionStore.ensureConnected(node.connectionId);const sql = emptyTablePreviewSql.value || (await buildEmptyTableSql(tableAdminSqlOptionsForNode(node)));- await options.executeWithProductionGuard(node, sql, { database: node.database, schema: node.schema });+ if (isCancelledBeforeDispatch()) throw new Error(DANGER_OPERATION_CANCELLED_BEFORE_DISPATCH_MESSAGE);+ const executed = await options.executeWithProductionGuard(node, sql, { database: node.database, schema: node.schema, executionId, isCancelledBeforeDispatch, markDispatched });+ if (executed === undefined) {+ // The user declined the production-safety confirmation: the SQL was+ // never sent, so this must not be reported as a successful empty.+ endDangerRunningExecution();+ return;+ }const messageKey = databaseTypeForNode(node) === "clickhouse" ? "contextMenu.emptyTableSubmitted" : "contextMenu.emptyTableSuccess";toast(t(messageKey, { name: node.label }), 3000);await options.refreshMutatedTableDataTabsForNode(node);+ endDangerRunningExecution();} catch (error: any) {- toast(t("contextMenu.tableOperationFailed", { message: error?.message || String(error) }), 5000);+ const message = error?.message || String(error);+ const backendError = normalizeBackendError(error) ?? undefined;+ toastDangerOperationError(node.label, message, wasCancelled(), cancelConfirmed(), backendError);+ if (cancelConfirmed() || !isQueryTimeoutErrorMessage(message, backendError)) {+ endDangerRunningExecution();+ } else {+ markHandedOff();+ }}}@@ -196,14 +333,30 @@ export function useSidebarTableMutationRuntime(options: SidebarTableMutationRuntasync function confirmTruncateTable() {const node = sidebarDangerTarget.value ?? activeNode.value;if (!node.connectionId || node.database == null) return;+ const { executionId, isCancelledBeforeDispatch, markDispatched, wasCancelled, cancelConfirmed, markHandedOff } = beginDangerRunningExecution(node.label);try {await connectionStore.ensureConnected(node.connectionId);const sql = truncateTablePreviewSql.value || (await buildTruncateTableSql(tableAdminSqlOptionsForNode(node, { cascade: truncateTableCascade.value && supportsTruncateTableCascade(databaseTypeForNode(node)) })));- await options.executeWithProductionGuard(node, sql, { database: node.database, schema: node.schema });+ if (isCancelledBeforeDispatch()) throw new Error(DANGER_OPERATION_CANCELLED_BEFORE_DISPATCH_MESSAGE);+ const executed = await options.executeWithProductionGuard(node, sql, { database: node.database, schema: node.schema, executionId, isCancelledBeforeDispatch, markDispatched });+ if (executed === undefined) {+ // The user declined the production-safety confirmation: the SQL was+ // never sent, so this must not be reported as a successful truncate.+ endDangerRunningExecution();+ return;+ }toast(t("contextMenu.truncateTableSuccess", { name: node.label }), 3000);await options.refreshMutatedTableDataTabsForNode(node);+ endDangerRunningExecution();} catch (error: any) {- toast(t("contextMenu.tableOperationFailed", { message: error?.message || String(error) }), 5000);+ const message = error?.message || String(error);+ const backendError = normalizeBackendError(error) ?? undefined;+ toastDangerOperationError(node.label, message, wasCancelled(), cancelConfirmed(), backendError);+ if (cancelConfirmed() || !isQueryTimeoutErrorMessage(message, backendError)) {+ endDangerRunningExecution();+ } else {+ markHandedOff();+ }}}diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 4ff784ee79..958b0510dd 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -2918,6 +2918,9 @@ export default {truncateTableSuccess: 'Table "{name}" truncated',duplicateStructureSuccess: 'Table cloned as "{name}"',tableOperationFailed: "Operation failed: {message}",+ tableOperationTimedOut: 'The operation on "{name}" is taking longer than expected and has not been cancelled — it may still be running on the database. Check the result later, or click Cancel to stop it. ({message})',+ tableOperationCancelled: 'Operation on "{name}" cancelled',+ tableOperationCancelUnconfirmed: 'The cancel request for "{name}" was not confirmed by the database — the operation may have already finished or may still be running. Check the result to be sure. ({message})',objectDropRefreshFailed: "Objects were deleted, but refreshing the sidebar failed: {message}",duplicateNameTitle: "Clone as New Table",duplicateNamePlaceholder: "New table name",@@ -4816,6 +4819,7 @@ export default {mongoFieldDetails: "Field: {field}",mongoArrayItemDetails: "Array item index: {index}",cancel: "Cancel",+ cancelRunning: "Cancel Query",confirm: "Execute",},production: {diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 4664021105..264af65325 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -2835,6 +2835,9 @@ export default withEnglishFallback({truncateTableSuccess: 'Tabla "{name}" truncada',duplicateStructureSuccess: 'Tabla clonada como "{name}"',tableOperationFailed: "Error en la operación: {message}",+ tableOperationTimedOut: 'La operación en "{name}" está tardando más de lo esperado y no se ha cancelado; es posible que siga ejecutándose en la base de datos. Compruebe el resultado más tarde o haga clic en Cancelar para detenerla. ({message})',+ tableOperationCancelled: 'Operación en "{name}" cancelada',+ tableOperationCancelUnconfirmed: 'La solicitud de cancelación de "{name}" no fue confirmada por la base de datos; la operación puede haber terminado o seguir en ejecución. Compruebe el resultado real. ({message})',objectDropRefreshFailed: "Los objetos se eliminaron, pero no se pudo actualizar la barra lateral: {message}",duplicateNameTitle: "Clonar como tabla nueva",duplicateNamePlaceholder: "Nombre de la nueva tabla",@@ -4658,6 +4661,7 @@ export default withEnglishFallback({mongoFieldDetails: "Campo: {field}",mongoArrayItemDetails: "Índice del elemento del arreglo: {index}",cancel: "Cancelar",+ cancelRunning: "Cancelar consulta",confirm: "Ejecutar",},sqlParameters: {diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 5f8ef212b8..090f1f780f 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -2833,6 +2833,9 @@ export default withEnglishFallback({truncateTableSuccess: 'Tabella "{name}" troncata',duplicateStructureSuccess: 'Tabella clonata come "{name}"',tableOperationFailed: "Operazione non riuscita: {message}",+ tableOperationTimedOut: 'L\'operazione su "{name}" sta impiegando più tempo del previsto e non è stata annullata: potrebbe essere ancora in esecuzione sul database. Controlla il risultato più tardi oppure fai clic su Annulla per interromperla. ({message})',+ tableOperationCancelled: 'Operazione su "{name}" annullata',+ tableOperationCancelUnconfirmed: 'La richiesta di annullamento per "{name}" non è stata confermata dal database: l\'operazione potrebbe essere già terminata o essere ancora in esecuzione. Verifica il risultato effettivo. ({message})',objectDropRefreshFailed: "Gli oggetti sono stati eliminati, ma l'aggiornamento della barra laterale non è riuscito: {message}",duplicateNameTitle: "Clona as Nuova Tabella",duplicateNamePlaceholder: "Nuovo nome tabella",@@ -4656,6 +4659,7 @@ export default withEnglishFallback({mongoFieldDetails: "Campo: {field}",mongoArrayItemDetails: "Indice elemento array: {index}",cancel: "Annulla",+ cancelRunning: "Annulla query",confirm: "Esegui",},sqlParameters: {diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 19a3e20afb..d30ae234bb 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -2856,6 +2856,9 @@ export default withEnglishFallback({truncateTableSuccess: "テーブル「{name}」をトランケートしました",duplicateStructureSuccess: "テーブルを「{name}」として複製しました",tableOperationFailed: "操作に失敗しました: {message}",+ tableOperationTimedOut: "「{name}」の操作に予想より時間がかかっており、まだキャンセルされていません。データベース側では実行が続いている可能性があります。後で結果を確認するか、キャンセルをクリックして停止してください。({message})",+ tableOperationCancelled: "「{name}」の操作をキャンセルしました",+ tableOperationCancelUnconfirmed: "「{name}」のキャンセル要求はデータベース側で確認されませんでした。操作はすでに完了しているか、まだ実行中の可能性があります。実際の結果をご確認ください。({message})",objectDropRefreshFailed: "オブジェクトは削除されましたが、サイドバーの更新に失敗しました: {message}",duplicateNameTitle: "新しいテーブルとして複製",duplicateNamePlaceholder: "新しいテーブル名",@@ -4686,6 +4689,7 @@ export default withEnglishFallback({mongoFieldDetails: "フィールド: {field}",mongoArrayItemDetails: "配列アイテムインデックス: {index}",cancel: "キャンセル",+ cancelRunning: "クエリをキャンセル",confirm: "実行",},sqlParameters: {diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex d88f415cad..28b0e31e5e 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -2752,6 +2752,9 @@ export default withEnglishFallback({truncateTableSuccess: '테이블 "{name}" TRUNCATE됨',duplicateStructureSuccess: '테이블이 "{name}"(으)로 복제됨',tableOperationFailed: "작업 실패: {message}",+ tableOperationTimedOut: '"{name}"에 대한 작업이 예상보다 오래 걸리고 있으며 취소되지 않았습니다. 데이터베이스에서 계속 실행 중일 수 있습니다. 나중에 결과를 확인하거나 취소를 클릭하여 중지하세요. ({message})',+ tableOperationCancelled: '"{name}" 작업이 취소되었습니다',+ tableOperationCancelUnconfirmed: '"{name}"에 대한 취소 요청이 데이터베이스에서 확인되지 않았습니다. 작업이 이미 완료되었거나 계속 실행 중일 수 있습니다. 실제 결과를 확인하세요. ({message})',objectDropRefreshFailed: "개체는 삭제되었지만 사이드바 새로 고침에 실패했습니다: {message}",duplicateNameTitle: "새 테이블로 복제",duplicateNamePlaceholder: "새 테이블 이름",@@ -4300,6 +4303,7 @@ export default withEnglishFallback({mongoFieldDetails: "필드: {field}",mongoArrayItemDetails: "배열 항목 인덱스: {index}",cancel: "취소",+ cancelRunning: "쿼리 취소",confirm: "실행",},production: {diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex ca886039d7..42e5d2f79e 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -2835,6 +2835,9 @@ export default withEnglishFallback({truncateTableSuccess: 'Tabela "{name}" truncada',duplicateStructureSuccess: 'Tabela clonada como "{name}"',tableOperationFailed: "Falha na operação: {message}",+ tableOperationTimedOut: 'A operação em "{name}" está demorando mais do que o esperado e não foi cancelada — ela pode continuar em execução no banco de dados. Verifique o resultado mais tarde ou clique em Cancelar para interrompê-la. ({message})',+ tableOperationCancelled: 'Operação em "{name}" cancelada',+ tableOperationCancelUnconfirmed: 'A solicitação de cancelamento de "{name}" não foi confirmada pelo banco de dados — a operação pode já ter terminado ou ainda estar em execução. Verifique o resultado real. ({message})',objectDropRefreshFailed: "Os objetos foram excluídos, mas não foi possível atualizar a barra lateral: {message}",duplicateNameTitle: "Clonar como Nova Tabela",duplicateNamePlaceholder: "Nome da nova tabela",@@ -4658,6 +4661,7 @@ export default withEnglishFallback({mongoFieldDetails: "Campo: {field}",mongoArrayItemDetails: "Índice do item do array: {index}",cancel: "Cancelar",+ cancelRunning: "Cancelar consulta",confirm: "Executar",},sqlParameters: {diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 966fb83203..612bf18ab8 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -2842,6 +2842,9 @@ export default withEnglishFallback({truncateTableSuccess: "表「{name}」已截断",duplicateStructureSuccess: "已克隆为新表「{name}」",tableOperationFailed: "操作失败:{message}",+ tableOperationTimedOut: "「{name}」的操作耗时较长,尚未被取消,可能仍在数据库端继续执行。请稍后自行确认执行结果,或点击「取消」手动终止。({message})",+ tableOperationCancelled: "「{name}」的操作已取消",+ tableOperationCancelUnconfirmed: "「{name}」的取消请求未被数据库确认,该操作可能已经完成,也可能仍在继续执行,请自行核实实际结果。({message})",objectDropRefreshFailed: "对象已删除,但侧边栏刷新失败:{message}",duplicateNameTitle: "克隆为新表",duplicateNamePlaceholder: "新表名",@@ -4803,6 +4806,7 @@ export default withEnglishFallback({mongoFieldDetails: "字段:{field}",mongoArrayItemDetails: "数组项索引:{index}",cancel: "取消",+ cancelRunning: "取消查询",confirm: "执行",},production: {diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 4f95607232..192539c9c8 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -2834,6 +2834,9 @@ export default withEnglishFallback({truncateTableSuccess: "資料表「{name}」已截斷",duplicateStructureSuccess: "已克隆為新資料表「{name}」",tableOperationFailed: "操作失敗:{message}",+ tableOperationTimedOut: "「{name}」的操作耗時較長,尚未被取消,可能仍在資料庫端繼續執行。請稍後自行確認執行結果,或點擊「取消」手動終止。({message})",+ tableOperationCancelled: "「{name}」的操作已取消",+ tableOperationCancelUnconfirmed: "「{name}」的取消請求未被資料庫確認,該操作可能已經完成,也可能仍在繼續執行,請自行核實實際結果。({message})",objectDropRefreshFailed: "物件已刪除,但側邊欄重新整理失敗:{message}",duplicateNameTitle: "克隆為新資料表",duplicateNamePlaceholder: "新資料表名稱",@@ -3985,6 +3988,7 @@ export default withEnglishFallback({mongoFieldDetails: "欄位:{field}",mongoArrayItemDetails: "陣列項索引:{index}",cancel: "取消",+ cancelRunning: "取消查詢",confirm: "執行",},sqlParameters: {diff --git a/apps/desktop/src/lib/sidebar/sidebarDangerDialog.ts b/apps/desktop/src/lib/sidebar/sidebarDangerDialog.tsindex 7f02d38aad..d2e076929e 100644--- a/apps/desktop/src/lib/sidebar/sidebarDangerDialog.ts+++ b/apps/desktop/src/lib/sidebar/sidebarDangerDialog.ts@@ -33,5 +33,6 @@ export interface SidebarDangerDialogRequest {progress?: SidebarDangerDialogProgress;option?: SidebarDangerDialogOption;textInput?: SidebarDangerDialogTextInput;+ cancelRunning?: () => void | Promise<void>;confirm: () => void | Promise<void>;}diff --git a/crates/dbx-core/Cargo.toml b/crates/dbx-core/Cargo.tomlindex 93b8e7b152..5bd073ec57 100644--- a/crates/dbx-core/Cargo.toml+++ b/crates/dbx-core/Cargo.toml@@ -90,3 +90,4 @@ windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem", "Win32[dev-dependencies]mysql_common = { git = "https://github.com/t8y2/rust_mysql_common.git", rev = "47740d85a8277167a5717afac785d37b46a36296", default-features = false }+tokio = { version = "1", features = ["test-util"] }diff --git a/crates/dbx-core/src/query_cancel.rs b/crates/dbx-core/src/query_cancel.rsindex 42e50e0e61..bd70afe80d 100644--- a/crates/dbx-core/src/query_cancel.rs+++ b/crates/dbx-core/src/query_cancel.rs@@ -1,8 +1,16 @@use std::collections::HashMap;use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, Mutex};+use std::time::Duration;use tokio_util::sync::CancellationToken;+/// How long a [`RegisteredQuery::detach`]ed registration stays reachable for+/// an explicit cancel before it is automatically reclaimed. Bounds the+/// resource this leaves behind (pool-activity accounting, and — while it+/// exists — any KILL-QUERY-style interrupt) to a single session's worth of+/// recently-timed-out operations, rather than leaking indefinitely.+const DETACHED_REGISTRATION_GRACE_PERIOD: Duration = Duration::from_secs(30 * 60);+#[derive(Clone, Debug, Default, PartialEq, Eq)]pub struct RunningQueryDiagnostics {pub active_execution_ids: Vec<String>,@@ -88,7 +96,7 @@ impl RunningQueries {}}- RegisteredQuery { execution_id, registration_id, token, running_queries: self.clone() }+ RegisteredQuery { execution_id, registration_id, token, running_queries: self.clone(), detached: false }}pub fn register_interrupt(&self, execution_id: &str, interrupt: impl Fn() + Send + 'static) {@@ -230,23 +238,49 @@ pub struct RegisteredQuery {registration_id: u64,token: CancellationToken,running_queries: RunningQueries,+ detached: bool,}impl RegisteredQuery {pub fn token(&self) -> CancellationToken {self.token.clone()}++ /// Consumes the guard without immediately removing its `RunningQueries`+ /// entry.+ ///+ /// Used when a caller is giving up on *waiting* for a query (e.g. a+ /// client-observed timeout) but the statement may still be executing+ /// server-side: the registration — and any KILL-QUERY-style interrupt+ /// registered against it — must stay reachable so a later explicit+ /// `cancel()` can still reach it, instead of losing that capability the+ /// instant the caller stops awaiting the result. The entry is still+ /// reclaimed automatically after [`DETACHED_REGISTRATION_GRACE_PERIOD`]+ /// so it does not leak forever if nobody ever revisits it.+ pub fn detach(mut self) {+ self.detached = true;+ let running_queries = self.running_queries.clone();+ let execution_id = self.execution_id.clone();+ let registration_id = self.registration_id;+ tokio::spawn(async move {+ tokio::time::sleep(DETACHED_REGISTRATION_GRACE_PERIOD).await;+ running_queries.remove(&execution_id, registration_id);+ });+ }}impl Drop for RegisteredQuery {fn drop(&mut self) {- self.running_queries.remove(&self.execution_id, self.registration_id);+ if !self.detached {+ self.running_queries.remove(&self.execution_id, self.registration_id);+ }}}#[cfg(test)]mod tests {- use super::{RunningQueries, RunningTaskKind, RunningTaskMetadata};+ use super::{RunningQueries, RunningTaskKind, RunningTaskMetadata, DETACHED_REGISTRATION_GRACE_PERIOD};+ use std::time::Duration;#[test]fn cancel_marks_registered_query_as_cancelled() {@@ -282,6 +316,46 @@ mod tests {assert!(!running.has("exec-1"));}+ #[tokio::test(start_paused = true)]+ async fn detached_registration_survives_and_stays_cancellable() {+ let running = RunningQueries::default();+ let interrupted = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let flag = interrupted.clone();+ let registered = running.register("exec-timeout".to_string());+ running.register_interrupt("exec-timeout", move || {+ flag.store(true, std::sync::atomic::Ordering::SeqCst);+ });++ // Simulate the Tauri command giving up on waiting (client-observed+ // timeout) while the statement may still be running server-side.+ registered.detach();+ assert!(running.has("exec-timeout"));++ // A later explicit cancel must still reach the (still registered)+ // KILL-QUERY-style interrupt.+ assert!(running.cancel("exec-timeout"));+ assert!(interrupted.load(std::sync::atomic::Ordering::SeqCst));+ }++ #[tokio::test(start_paused = true)]+ async fn detached_registration_is_reclaimed_after_the_grace_period() {+ let running = RunningQueries::default();+ let registered = running.register("exec-timeout".to_string());++ registered.detach();+ assert!(running.has("exec-timeout"));++ // Let the spawned cleanup task reach its `sleep().await` and+ // register its timer before we fast-forward the clock, then let it+ // run to completion afterward.+ tokio::task::yield_now().await;+ tokio::time::advance(DETACHED_REGISTRATION_GRACE_PERIOD + Duration::from_secs(1)).await;+ tokio::task::yield_now().await;+ tokio::task::yield_now().await;++ assert!(!running.has("exec-timeout"));+ }+#[test]fn stale_registration_drop_does_not_remove_replacement() {let running = RunningQueries::default();diff --git a/packages/app-tests/sidebarMutationRuntime.test.ts b/packages/app-tests/sidebarMutationRuntime.test.tsindex a09753bd3f..378607d265 100644--- a/packages/app-tests/sidebarMutationRuntime.test.ts+++ b/packages/app-tests/sidebarMutationRuntime.test.ts@@ -32,7 +32,7 @@ test("mutation families retain accepted targets, failures, and refresh work", ()const body = functionBody(name);assert.match(body, /sidebarDangerTarget\.value \?\? activeNode\.value/);assert.match(body, /refreshMutatedTableDataTabsForNode\(node\)/);- assert.match(body, /tableOperationFailed/);+ assert.match(body, /toastDangerOperationError\(node\.label/);}for (const name of ["confirmCreateNacosNamespace", "confirmEditNacosNamespace", "confirmDropDatabase"]) {diff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rsindex a651cca57d..0786b54401 100644--- a/src-tauri/src/commands/query.rs+++ b/src-tauri/src/commands/query.rs@@ -51,7 +51,7 @@ pub async fn execute_query(});let cancel_token = registered_query.as_ref().map(|query| query.token());- dbx_core::query::execute_sql_statement_with_options_typed(+ let result = dbx_core::query::execute_sql_statement_with_options_typed(&state,&connection_id,&database,@@ -72,8 +72,20 @@ pub async fn execute_query(..Default::default()},)- .await- .map_err(dbx_core::query::QueryExecutionError::into_backend_error)+ .await;++ if matches!(result, Err(dbx_core::query::QueryExecutionError::Timeout(_))) {+ // We're giving up on waiting, not cancelling: the statement may+ // still be executing server-side. Keep the registration (and any+ // KILL-QUERY-style interrupt registered against it) reachable so a+ // later explicit cancel_query call can still reach it, instead of+ // losing that capability the instant this command returns.+ if let Some(registered_query) = registered_query {+ registered_query.detach();+ }+ }++ result.map_err(dbx_core::query::QueryExecutionError::into_backend_error)}#[tauri::command]