Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

fix(query): display execution duration when re-executing after error (#12749) (#12767)

lxk955e33c19b3b359
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index 44411e9b49..16b018a58d 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -2746,7 +2746,7 @@ defineExpose({
<ElasticsearchJsonResponsePanel v-if="activeElasticsearchJsonResponse" ref="elasticsearchJsonResponsePanelRef" class="flex-1 min-h-0" :status="activeElasticsearchJsonResponse.status" :body="activeElasticsearchJsonResponse.body" />
<ElasticsearchJsonResponsePanel v-else-if="showElasticsearchRawJson && activeElasticsearchRawBody" ref="elasticsearchJsonResponsePanelRef" class="flex-1 min-h-0" :status="200" :body="activeElasticsearchRawBody" can-show-table @show-table="showElasticsearchRawJson = false" />
<DataGrid
- v-else-if="activeTab.result && hasTabularResult"
+ v-else-if="activeTab.result && hasTabularResult && (!activeTab.isExecuting || !isQueryExecutionErrorResult(activeTab.result))"
ref="dataGridRef"
:key="activeResultGridInstanceKey"
:cache-key="activeResultGridCacheKey"
@@ -2902,7 +2902,7 @@ defineExpose({
</template>
</DataGrid>
<QueryLoadingState
- v-else-if="!activeTab.result && activeTab.isExecuting"
+ v-else-if="(!activeTab.result || isQueryExecutionErrorResult(activeTab.result)) && activeTab.isExecuting"
class="flex-1 min-h-0"
:label-key="queryExecutionLabelKey(activeTab)"
:elapsed-seconds="queryRunningElapsedSeconds"
@@ -3286,7 +3286,7 @@ defineExpose({
</Popover>
</div>
<DataGrid
- v-if="activeTab.result"
+ v-if="activeTab.result && (!activeTab.isExecuting || !isQueryExecutionErrorResult(activeTab.result))"
ref="dataGridRef"
class="flex-1 min-h-0"
:key="activeTab.id"
diff --git a/apps/desktop/src/components/layout/__tests__/ContentArea.errorReExecute.spec.ts b/apps/desktop/src/components/layout/__tests__/ContentArea.errorReExecute.spec.ts
new file mode 100644
index 0000000000..a66509c0d4
--- /dev/null
+++ b/apps/desktop/src/components/layout/__tests__/ContentArea.errorReExecute.spec.ts
@@ -0,0 +1,148 @@
+// @vitest-environment happy-dom
+import { createApp, defineComponent, h, nextTick, reactive } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { createI18n } from "vue-i18n";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { QueryResult, QueryTab } from "@/types/database";
+
+vi.mock("@/components/editor/QueryEditor.vue", () => ({ default: { render: () => null } }));
+vi.mock("@/components/transfer/QueryResultTransferDialog.vue", () => ({ __esModule: true, default: { render: () => null } }));
+vi.mock("@/components/grid/DataGrid.vue", () => ({
+ __esModule: true,
+ default: defineComponent({
+ render: () => h("div", { "data-test": "data-grid" }, "DataGrid Mock"),
+ }),
+}));
+
+import ContentArea from "../ContentArea.vue";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useQueryStore } from "@/stores/queryStore";
+
+const cleanups: Array<() => void> = [];
+afterEach(() => {
+ cleanups.splice(0).forEach((cleanup) => cleanup());
+ document.body.replaceChildren();
+ window.localStorage?.clear();
+});
+
+async function mountContentArea(options: { result?: QueryResult; isExecuting?: boolean; queryExecutionStartedAt?: number }) {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const connection = { id: "mysql-1", name: "MySQL", db_type: "mysql" as const, host: "localhost", port: 3306, username: "root", password: "" };
+ useConnectionStore().connections = [connection];
+ const tab = reactive<QueryTab>({
+ id: "query-tab-1",
+ title: "Query 1",
+ connectionId: connection.id,
+ database: "app",
+ mode: "query",
+ sql: "SELECT 1",
+ isExecuting: options.isExecuting ?? false,
+ queryExecutionStartedAt: options.queryExecutionStartedAt,
+ result: options.result,
+ activeResultIndex: 0,
+ });
+ useQueryStore().tabs.push(tab);
+
+ const state = reactive({ view: "result" as "result" | "messages" });
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const app = createApp(
+ defineComponent({
+ setup: () => () =>
+ h(ContentArea, {
+ activeTab: tab,
+ activeConnection: connection,
+ activeOutputView: state.view,
+ executableSql: "",
+ formatSqlRequest: null,
+ compressSqlRequest: null,
+ selectedSql: "",
+ cursorPos: 0,
+ resultOnly: true,
+ keywordCaseRequest: null,
+ blockDangerousRedisCommands: false,
+ "onUpdate:activeOutputView": (_tabId: string, view: string) => {
+ state.view = view as typeof state.view;
+ },
+ }),
+ }),
+ );
+ app.use(pinia);
+ app.use(
+ createI18n({
+ legacy: false,
+ locale: "zh-CN",
+ messages: {
+ "zh-CN": {
+ common: { loading: "正在执行", stopping: "停止中" },
+ toolbar: { stopQuery: "停止执行" },
+ grid: { cachedResultUnavailable: "结果不可用", reexecuteQuery: "重新执行" },
+ editor: { pressToExecute: "按快捷键执行", pressToSaveSql: "按快捷键保存" },
+ tabs: { resultN: "结果 {n}" },
+ },
+ },
+ missingWarn: false,
+ fallbackWarn: false,
+ }),
+ );
+ app.mount(host);
+ cleanups.push(() => app.unmount());
+ await nextTick();
+ await nextTick();
+ return { host, state, tab };
+}
+
+describe("ContentArea query loading state on error re-execute", () => {
+ const errorResult: QueryResult = {
+ columns: ["Error"],
+ execution_error: true,
+ rows: [["数据库操作已取消 (阶段: cancel)"]],
+ affected_rows: 0,
+ execution_time_ms: 0,
+ };
+
+ it("shows QueryLoadingState with elapsed time when re-executing after an error result", async () => {
+ const startedAt = Date.now() - 1500;
+ const { host, tab } = await mountContentArea({
+ result: errorResult,
+ isExecuting: true,
+ queryExecutionStartedAt: startedAt,
+ });
+
+ // When isExecuting is true and result is an error result, DataGrid must not be shown;
+ // QueryLoadingState must be displayed with the live elapsed duration and cancel button.
+ expect(host.querySelector('[data-test="data-grid"]')).toBeNull();
+ expect(host.textContent).toContain("正在执行");
+ expect(host.textContent).toMatch(/· \d+\.\d+s/);
+ expect(host.textContent).toContain("停止执行");
+
+ // Once execution completes with a success result, DataGrid replaces the loading state.
+ tab.isExecuting = false;
+ tab.queryExecutionStartedAt = undefined;
+ tab.result = {
+ columns: ["id"],
+ rows: [[1]],
+ affected_rows: 1,
+ execution_time_ms: 12,
+ client_request_wait_ms: 12,
+ };
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ await nextTick();
+
+ expect(host.querySelector('[data-test="data-grid"]')).not.toBeNull();
+ expect(host.textContent).not.toContain("正在执行");
+ });
+
+ it("shows DataGrid when tab has an error result and is not executing", async () => {
+ const { host } = await mountContentArea({
+ result: errorResult,
+ isExecuting: false,
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ await nextTick();
+ expect(host.querySelector('[data-test="data-grid"]')).not.toBeNull();
+ expect(host.textContent).not.toContain("正在执行");
+ });
+});
diff --git a/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.ts
index 1803dd41fe..c861a3a0f4 100644
--- a/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.ts
+++ b/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.ts
@@ -231,6 +231,56 @@ describe("queryStore multi-statement errors", () => {
expect(tab.result?.rows).toEqual([[2]]);
});
+ it("clears a previous error result during re-execution so the loading state is displayed", async () => {
+ const pendingExecution = deferred<QueryResult[]>();
+ mocks.executeMulti.mockResolvedValueOnce([{ columns: ["Error"], rows: [["syntax error"]], affected_rows: 0, execution_time_ms: 0, execution_error: true }]).mockImplementationOnce(() => pendingExecution.promise);
+ const { useQueryStore } = await import("@/stores/queryStore");
+ const store = useQueryStore();
+ const tabId = store.createTab("mysql-1", "app", "Query", "query", "app");
+
+ await store.executeTabSql(tabId, "SELECT bad");
+ const tab = store.tabs.find((item) => item.id === tabId)!;
+ expect(tab.result?.execution_error).toBe(true);
+
+ const execution = store.executeTabSql(tabId, "SELECT 1 AS value");
+ await vi.waitFor(() => expect(mocks.executeMulti).toHaveBeenCalledTimes(2));
+
+ expect(tab.isExecuting).toBe(true);
+ expect(tab.result).toBeUndefined();
+
+ pendingExecution.resolve([{ columns: ["value"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 }]);
+ await execution;
+
+ expect(tab.isExecuting).toBe(false);
+ expect(tab.result?.rows).toEqual([[1]]);
+ expect(tab.result?.execution_error).toBeUndefined();
+ });
+
+ it("clears a cancelled error result during re-execution so the loading state is displayed", async () => {
+ const pendingExecution = deferred<QueryResult[]>();
+ mocks.executeMulti.mockRejectedValueOnce(new Error("Query canceled")).mockImplementationOnce(() => pendingExecution.promise);
+ const { useQueryStore } = await import("@/stores/queryStore");
+ const store = useQueryStore();
+ const tabId = store.createTab("mysql-1", "app", "Query", "query", "app");
+
+ await store.executeTabSql(tabId, "SELECT sleep(10)");
+ const tab = store.tabs.find((item) => item.id === tabId)!;
+ expect(tab.result?.execution_error).toBe(true);
+ expect(tab.result?.rows[0]?.[0]).toContain("Query canceled");
+
+ const execution = store.executeTabSql(tabId, "SELECT 1 AS value");
+ await vi.waitFor(() => expect(mocks.executeMulti).toHaveBeenCalledTimes(2));
+
+ expect(tab.isExecuting).toBe(true);
+ expect(tab.result).toBeUndefined();
+
+ pendingExecution.resolve([{ columns: ["value"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 }]);
+ await execution;
+
+ expect(tab.isExecuting).toBe(false);
+ expect(tab.result?.rows).toEqual([[1]]);
+ });
+
it("opens the first error result from a mixed result batch", async () => {
const structuredError = structuredTimeoutError();
mocks.executeMulti.mockResolvedValue([
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index b6712276cf..de5022a330 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -7635,7 +7635,7 @@ export const useQueryStore = defineStore("query", () => {
// response as another run. Previously `resultAutoSave` only made the latter
// decision after clearing the displayed payload, which caused the result
// toolbar and grid to briefly disappear before the next Run was added.
- const captureAutoSavedResultRun = tab.mode === "query" && tab.resultAutoSave === true && (!!tab.activeResultRunId || !!tab.result);
+ const captureAutoSavedResultRun = tab.mode === "query" && tab.resultAutoSave === true && (!!tab.activeResultRunId || (!!tab.result && !isQueryExecutionErrorResult(tab.result)));
let captureResultRun = openInNewResultTab || captureAutoSavedResultRun;
let resultRunToRestore: string | undefined;
let reuseResultRun = false;
@@ -7696,8 +7696,10 @@ export const useQueryStore = defineStore("query", () => {
// Keep the last query result mounted while a replacement query is running.
// Clearing it first unmounts DataGrid and its toolbar, so a slow query makes
// the result actions disappear until the new response arrives (issue #10008).
- const preserveQueryResultDuringExecution = tab.mode === "query" && !!tab.result && !captureResultRun;
- const preserveResultDuringExecution = batchResume !== undefined || options?.preserveResultDuringExecution === true || captureAutoSavedResultRun || preserveQueryResultDuringExecution;
+ // An error/cancelled result has no dataset to preserve; clearing it lets
+ // QueryLoadingState display the live elapsed execution timer (issue #12749).
+ const preserveQueryResultDuringExecution = tab.mode === "query" && !!tab.result && !isQueryExecutionErrorResult(tab.result) && !captureResultRun;
+ const preserveResultDuringExecution = batchResume !== undefined || (options?.preserveResultDuringExecution === true && (!tab.result || !isQueryExecutionErrorResult(tab.result))) || captureAutoSavedResultRun || preserveQueryResultDuringExecution;
const updateActiveResultRun = !!tab.activeResultRunId && preserveResultDuringExecution;
tab.isExecuting = true;
tab.executingResultRunId = !captureResultRun && updateActiveResultRun ? tab.activeResultRunId : null;