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(grid): keep the active result tab across refreshes

zipg8e5b69bb7704
diff --git a/apps/desktop/src/composables/__tests__/useDataGridActions.refreshActiveResultRun.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridActions.refreshActiveResultRun.spec.ts
new file mode 100644
index 0000000000..5148d833a0
--- /dev/null
+++ b/apps/desktop/src/composables/__tests__/useDataGridActions.refreshActiveResultRun.spec.ts
@@ -0,0 +1,192 @@
+import { computed } from "vue";
+import { createPinia, setActivePinia } from "pinia";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ analyzeEditableQueryEditability: vi.fn(),
+ cancelQuery: vi.fn(),
+ closeClientConnectionSession: vi.fn(),
+ closeQuerySession: vi.fn(),
+ ensureConnected: vi.fn(),
+ executeMulti: vi.fn(),
+ executeMultiWithProgress: vi.fn(),
+ executeQuery: vi.fn(),
+ getConfig: vi.fn(),
+ prepareQueryPaginationExecutionPlan: vi.fn(),
+ saveOpenTabsState: vi.fn(),
+ clearDataGridPendingSnapshot: vi.fn(),
+ clearDataGridPendingSnapshotsForTab: vi.fn(),
+ toast: vi.fn(),
+ tabResultSnapshots: new Map<string, unknown>(),
+}));
+
+vi.mock("vue-i18n", () => ({
+ useI18n: () => ({ t: (key: string) => key }),
+ createI18n: () => ({ install: () => {}, global: { t: (key: string) => key, locale: { value: "en" } } }),
+}));
+
+vi.mock("@/lib/backend/api", () => ({
+ analyzeEditableQueryEditability: mocks.analyzeEditableQueryEditability,
+ buildSortedQuerySql: vi.fn(),
+ cancelQuery: mocks.cancelQuery,
+ closeClientConnectionSession: mocks.closeClientConnectionSession,
+ closeQuerySession: mocks.closeQuerySession,
+ executeMulti: mocks.executeMulti,
+ executeMultiWithProgress: mocks.executeMultiWithProgress,
+ executeQuery: mocks.executeQuery,
+ getColumns: vi.fn(),
+ deleteSchemaCachePrefix: vi.fn(),
+ listIndexes: vi.fn(),
+ prepareQueryPaginationExecutionPlan: mocks.prepareQueryPaginationExecutionPlan,
+ saveOpenTabsState: mocks.saveOpenTabsState,
+}));
+
+vi.mock("@/stores/connectionStore", () => ({
+ useConnectionStore: () => ({
+ ensureConnected: mocks.ensureConnected,
+ getConfig: mocks.getConfig,
+ recordConnectionLostError: vi.fn(),
+ metadataGenerationFor: () => 0,
+ lookupLocalCompletionTables: () => [],
+ connectionIdentifierQuote: undefined,
+ }),
+}));
+
+vi.mock("@/stores/settingsStore", () => ({
+ useSettingsStore: () => ({
+ editorSettings: {
+ autoCalculateTotalRows: false,
+ pageSize: 100,
+ continueOnErrorOnBatch: false,
+ defaultAutoKeepResults: false,
+ infiniteScroll: false,
+ queryResultMaxRowsEnabled: false,
+ queryResultMaxRows: 10_000,
+ tableOpenPageSize: 100,
+ generateSqlIncludeDatabaseName: false,
+ },
+ }),
+}));
+
+vi.mock("@/composables/useDataGridEditor", () => ({
+ clearDataGridPendingSnapshot: mocks.clearDataGridPendingSnapshot,
+ clearDataGridPendingSnapshotsForTab: mocks.clearDataGridPendingSnapshotsForTab,
+}));
+
+vi.mock("@/composables/useToast", () => ({
+ useToast: () => ({ toast: mocks.toast }),
+}));
+
+vi.mock("@/lib/tabs/tabResultCache", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/tabs/tabResultCache")>();
+ return {
+ ...actual,
+ writeTabResultSnapshot: vi.fn(async (key: string, snapshot: unknown) => {
+ mocks.tabResultSnapshots.set(key, actual.decodeTabResultSnapshot(actual.encodeTabResultSnapshot(snapshot as Parameters<typeof actual.encodeTabResultSnapshot>[0])));
+ return true;
+ }),
+ readTabResultSnapshot: vi.fn(async (key: string) => mocks.tabResultSnapshots.get(key)),
+ deleteTabResultSnapshot: vi.fn(async (key: string) => {
+ mocks.tabResultSnapshots.delete(key);
+ }),
+ };
+});
+
+function installLocalStorage() {
+ const data = new Map<string, string>();
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn((key: string) => data.get(key) ?? null),
+ setItem: vi.fn((key: string, value: string) => data.set(key, value)),
+ removeItem: vi.fn((key: string) => data.delete(key)),
+ });
+}
+
+function resultOf(rows: unknown[][]) {
+ return { columns: ["value"], rows, affected_rows: rows.length, execution_time_ms: 1 };
+}
+
+async function createAutoKeepTab() {
+ const { useQueryStore } = await import("@/stores/queryStore");
+ const store = useQueryStore();
+ const tabId = store.createTab("mysql-1", "app", "Query");
+ store.toggleResultAutoSave(tabId);
+ const tab = () => store.tabs.find((item) => item.id === tabId)!;
+ return { store, tabId, tab };
+}
+
+describe("useDataGridActions refreshActiveResultRun integration", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+ mocks.tabResultSnapshots.clear();
+ installLocalStorage();
+ setActivePinia(createPinia());
+ mocks.cancelQuery.mockResolvedValue(true);
+ mocks.ensureConnected.mockResolvedValue(undefined);
+ mocks.getConfig.mockReturnValue({ id: "mysql-1", name: "MySQL", db_type: "mysql", database: "app", query_timeout_secs: 30 });
+ mocks.prepareQueryPaginationExecutionPlan.mockImplementation(async (options: { sql: string }) => ({
+ sqlToExecute: options.sql,
+ pageSql: undefined,
+ pageLimit: undefined,
+ pageOffset: undefined,
+ countSql: undefined,
+ useAgentResultSession: false,
+ }));
+ mocks.analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "multiple-statements" });
+ mocks.executeMultiWithProgress.mockImplementation(async (connectionId: string, database: string, sql: string, onProgress: (progress: Record<string, unknown>) => void, schema: string | undefined, options: { executionId?: string } = {}) => {
+ const results = await mocks.executeMulti(connectionId, database, sql, schema, options.executionId, options);
+ const total = results.length;
+ results.forEach((result: { statement_index?: number; execution_error?: boolean; execution_time_ms?: number; affected_rows?: number; error?: unknown }, index: number) => {
+ const success = result.execution_error !== true;
+ onProgress({
+ executionId: options.executionId,
+ statementIndex: result.statement_index ?? index,
+ completed: index + 1,
+ total,
+ success,
+ executionTimeMs: result.execution_time_ms,
+ affectedRows: result.affected_rows,
+ error: success ? undefined : result.error,
+ });
+ });
+ return results;
+ });
+ });
+
+ it("refreshes and auto-refreshes the active result run in place, while executions still add a run", async () => {
+ mocks.executeMulti
+ .mockResolvedValueOnce([resultOf([[1]])])
+ .mockResolvedValueOnce([resultOf([[2]])])
+ .mockResolvedValueOnce([resultOf([[3]])])
+ .mockResolvedValueOnce([resultOf([[4]])])
+ .mockResolvedValueOnce([resultOf([[5]])]);
+ const { useQueryStore } = await import("@/stores/queryStore");
+ const { useDataGridActions } = await import("@/composables/useDataGridActions");
+ const { tabId, tab } = await createAutoKeepTab();
+ const store = useQueryStore();
+ const actions = useDataGridActions(computed(() => tab()));
+
+ // Two explicit executions: two result runs (auto-keep semantics).
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ expect(tab().resultRuns).toHaveLength(2);
+ const activeRunId = tab().activeResultRunId!;
+
+ // Toolbar refresh goes through the same onReloadData path as DataGrid.
+ await actions.onReloadData(tabId, "SELECT value FROM t", "", "", "", undefined, undefined, "refresh");
+ expect(tab().resultRuns).toHaveLength(2);
+ expect(tab().activeResultRunId).toBe(activeRunId);
+ expect(tab().result?.rows).toEqual([[3]]);
+
+ // Auto-refresh reuses the same in-place path.
+ await actions.onReloadData(tabId, "SELECT value FROM t", "", "", "", undefined, undefined, "auto-refresh");
+ expect(tab().resultRuns).toHaveLength(2);
+ expect(tab().activeResultRunId).toBe(activeRunId);
+ expect(tab().result?.rows).toEqual([[4]]);
+
+ // Run / Cmd+Enter is still an execution and adds a result run.
+ await actions.onExecuteSql(tabId, "SELECT value FROM t");
+ expect(tab().resultRuns).toHaveLength(3);
+ expect(tab().result?.rows).toEqual([[5]]);
+ });
+});
diff --git a/apps/desktop/src/composables/__tests__/useDataGridActions.spec.ts b/apps/desktop/src/composables/__tests__/useDataGridActions.spec.ts
index cb41e0396b..46b482e410 100644
--- a/apps/desktop/src/composables/__tests__/useDataGridActions.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useDataGridActions.spec.ts
@@ -824,10 +824,33 @@ describe("useDataGridActions", () => {
resultBaseSql: "SELECT 1",
resultSortedSql: undefined,
preserveResultDuringExecution: true,
+ refreshActiveResultRun: true,
}),
);
});
+ it("does not mark explicit executions as in-place result refreshes", async () => {
+ const tab = {
+ id: "tab-1",
+ connectionId: "postgres-1",
+ database: "app",
+ title: "Query",
+ sql: "SELECT 1",
+ result: { columns: ["value"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 },
+ mode: "query",
+ isDirty: false,
+ isExecuting: false,
+ isCancelling: false,
+ isExplaining: false,
+ } as QueryTab;
+ const actions = useDataGridActions(computed(() => tab));
+
+ await actions.onExecuteSql(tab.id, "SELECT 2");
+
+ expect(mocks.executeTabSql).toHaveBeenCalledWith("tab-1", "SELECT 2", expect.objectContaining({ preserveResultDuringExecution: true }));
+ expect(mocks.executeTabSql.mock.calls[0]![2]).not.toHaveProperty("refreshActiveResultRun");
+ });
+
it("marks row identity pending and refreshes metadata when real columns are missing, despite fallback result columns", async () => {
// 恢复的占位身份:真实 tableMeta.columns 为空,但存在(失败)结果列。
// tableMetaForDataTab 会用结果列合成 columns,不得据此跳过刷新
@@ -1054,6 +1077,7 @@ describe("useDataGridActions", () => {
"SELECT name, email FROM users",
expect.objectContaining({
resultBaseSql: "SELECT name, email FROM users",
+ refreshActiveResultRun: true,
querySort: {
resultColumns: ["name", "email"],
columnIndex: 1,
@@ -1125,6 +1149,7 @@ describe("useDataGridActions", () => {
{ offset: 300, limit: 100, sessionId: "cursor-3", clientSessionId: "client-1" },
]);
expect(mocks.executeTabSql.mock.calls.map((call) => call[2].retainDisplayedResult)).toEqual([true, true, undefined]);
+ expect(mocks.executeTabSql.mock.calls.map((call) => call[2].refreshActiveResultRun)).toEqual([true, true, true]);
expect(tab.resultPageOffset).toBe(300);
expect(tab.resultPageJumpProgress).toBeUndefined();
});
diff --git a/apps/desktop/src/composables/useDataGridActions.ts b/apps/desktop/src/composables/useDataGridActions.ts
index c38cfbce28..2bb04f070f 100644
--- a/apps/desktop/src/composables/useDataGridActions.ts
+++ b/apps/desktop/src/composables/useDataGridActions.ts
@@ -68,6 +68,12 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
return activeTab.value?.id === tabId ? activeTab.value : undefined;
}
+ function refreshActiveResultRunOptions(tab: QueryTab): { refreshActiveResultRun?: boolean } {
+ // Reloads/pagination/sorting re-run the displayed SQL; they are result-view
+ // operations and must not capture another result run when auto-keep is on.
+ return tab.mode === "query" ? { refreshActiveResultRun: true } : {};
+ }
+
function activeQueryTargetOptions(tab: QueryTab) {
const executionTarget = queryStore.activeResultExecutionTarget(tab.id);
if (!executionTarget) return {};
@@ -490,6 +496,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
tab.resultSortedSql = undefined;
await queryStore.executeTabSql(tab.id, resultGroupSql, {
...activeQueryTargetOptions(tab),
+ ...refreshActiveResultRunOptions(tab),
resultBaseSql: resultGroupSql,
resultSortedSql: undefined,
preserveResultDuringExecution: true,
@@ -502,6 +509,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
const rebuildHiddenKeySort = !!tab.result?.hidden_column_indexes?.length && tab.resultSortMode === "database" && !!tab.resultSortDirection && !!tab.resultSortColumn && !!sortColumns;
await queryStore.executeTabSql(tab.id, rebuildHiddenKeySort ? (tab.resultBaseSql ?? tab.sql) : tab.resultSortedSql, {
...activeQueryTargetOptions(tab),
+ ...refreshActiveResultRunOptions(tab),
resultBaseSql: tab.resultBaseSql ?? tab.sql,
...(rebuildHiddenKeySort
? {
@@ -522,6 +530,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
const hasMultiResults = tab.mode === "query" && (tab.results?.length ?? 0) > 1;
await queryStore.executeTabSql(tab.id, sql, {
...(tab.mode === "query" ? activeQueryTargetOptions(tab) : {}),
+ ...refreshActiveResultRunOptions(tab),
resultBaseSql: sql,
resultSortedSql: undefined,
preserveResultDuringExecution: true,
@@ -555,6 +564,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
const executePage = (pageOffset: number, pageSessionId?: string, retainDisplayedResult = false) =>
queryStore.executeTabSql(tab.id, baseSql, {
...activeQueryTargetOptions(tab),
+ ...refreshActiveResultRunOptions(tab),
resultBaseSql,
resultSortedSql: tab.resultSortedSql,
...(hasDatabaseSort
@@ -740,6 +750,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
if (!direction) {
await queryStore.executeTabSql(tab.id, baseSql, {
...activeQueryTargetOptions(tab),
+ ...refreshActiveResultRunOptions(tab),
resultBaseSql: baseSql,
resultSortedSql: undefined,
...(pagination ? { pagination } : {}),
@@ -761,6 +772,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
queryStore.updateSql(tab.id, sortedSql);
await queryStore.executeTabSql(tab.id, sortedSql, {
...activeQueryTargetOptions(tab),
+ ...refreshActiveResultRunOptions(tab),
resultBaseSql: baseSql,
resultSortedSql: sortedSql,
...(pagination ? { pagination } : {}),
@@ -792,6 +804,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
}
await queryStore.executeTabSql(tab.id, built.sql, {
...activeQueryTargetOptions(tab),
+ ...refreshActiveResultRunOptions(tab),
resultBaseSql: baseSql,
resultSortedSql: built.sql,
...(pagination ? { pagination } : {}),
@@ -803,6 +816,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
}
await queryStore.executeTabSql(tab.id, baseSql, {
...activeQueryTargetOptions(tab),
+ ...refreshActiveResultRunOptions(tab),
resultBaseSql: baseSql,
querySort: {
resultColumns: sortColumns.resultColumns,
diff --git a/apps/desktop/src/stores/__tests__/queryStore.refreshActiveResultRun.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.refreshActiveResultRun.spec.ts
new file mode 100644
index 0000000000..7a5ae24df9
--- /dev/null
+++ b/apps/desktop/src/stores/__tests__/queryStore.refreshActiveResultRun.spec.ts
@@ -0,0 +1,321 @@
+import { createPinia, setActivePinia } from "pinia";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ analyzeEditableQueryEditability: vi.fn(),
+ cancelQuery: vi.fn(),
+ closeClientConnectionSession: vi.fn(),
+ closeQuerySession: vi.fn(),
+ ensureConnected: vi.fn(),
+ executeMulti: vi.fn(),
+ executeMultiWithProgress: vi.fn(),
+ executeQuery: vi.fn(),
+ getConnectionConfig: vi.fn(),
+ prepareQueryPaginationExecutionPlan: vi.fn(),
+ saveOpenTabsState: vi.fn(),
+ clearDataGridPendingSnapshot: vi.fn(),
+ clearDataGridPendingSnapshotsForTab: vi.fn(),
+ tabResultSnapshots: new Map<string, unknown>(),
+}));
+
+vi.mock("@/lib/backend/api", () => ({
+ analyzeEditableQueryEditability: mocks.analyzeEditableQueryEditability,
+ cancelQuery: mocks.cancelQuery,
+ closeClientConnectionSession: mocks.closeClientConnectionSession,
+ closeQuerySession: mocks.closeQuerySession,
+ executeMulti: mocks.executeMulti,
+ executeMultiWithProgress: mocks.executeMultiWithProgress,
+ executeQuery: mocks.executeQuery,
+ prepareQueryPaginationExecutionPlan: mocks.prepareQueryPaginationExecutionPlan,
+ saveOpenTabsState: mocks.saveOpenTabsState,
+}));
+
+vi.mock("@/stores/connectionStore", () => ({
+ useConnectionStore: () => ({
+ ensureConnected: mocks.ensureConnected,
+ getConfig: mocks.getConnectionConfig,
+ recordConnectionLostError: vi.fn(),
+ }),
+}));
+
+vi.mock("@/stores/settingsStore", () => ({
+ useSettingsStore: () => ({
+ editorSettings: { autoCalculateTotalRows: false, pageSize: 100, continueOnErrorOnBatch: false, defaultAutoKeepResults: false },
+ }),
+}));
+
+vi.mock("@/composables/useDataGridEditor", () => ({
+ clearDataGridPendingSnapshot: mocks.clearDataGridPendingSnapshot,
+ clearDataGridPendingSnapshotsForTab: mocks.clearDataGridPendingSnapshotsForTab,
+}));
+
+vi.mock("@/lib/tabs/tabResultCache", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/tabs/tabResultCache")>();
+ return {
+ ...actual,
+ writeTabResultSnapshot: vi.fn(async (key: string, snapshot: unknown) => {
+ mocks.tabResultSnapshots.set(key, actual.decodeTabResultSnapshot(actual.encodeTabResultSnapshot(snapshot as Parameters<typeof actual.encodeTabResultSnapshot>[0])));
+ return true;
+ }),
+ readTabResultSnapshot: vi.fn(async (key: string) => mocks.tabResultSnapshots.get(key)),
+ deleteTabResultSnapshot: vi.fn(async (key: string) => {
+ mocks.tabResultSnapshots.delete(key);
+ }),
+ };
+});
+
+function installLocalStorage() {
+ const data = new Map<string, string>();
+ vi.stubGlobal("localStorage", {
+ getItem: vi.fn((key: string) => data.get(key) ?? null),
+ setItem: vi.fn((key: string, value: string) => data.set(key, value)),
+ removeItem: vi.fn((key: string) => data.delete(key)),
+ });
+}
+
+function deferred<T>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+function resultOf(rows: unknown[][]) {
+ return { columns: ["value"], rows, affected_rows: rows.length, execution_time_ms: 1 };
+}
+
+async function createStore() {
+ const { useQueryStore } = await import("@/stores/queryStore");
+ const store = useQueryStore();
+ const tabId = store.createTab("mysql-1", "app", "Query");
+ return { store, tabId };
+}
+
+describe("queryStore refreshActiveResultRun", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+ mocks.tabResultSnapshots.clear();
+ installLocalStorage();
+ setActivePinia(createPinia());
+ mocks.cancelQuery.mockResolvedValue(true);
+ mocks.getConnectionConfig.mockReturnValue({ id: "mysql-1", name: "MySQL", db_type: "mysql", database: "app", query_timeout_secs: 30 });
+ mocks.ensureConnected.mockResolvedValue(undefined);
+ mocks.prepareQueryPaginationExecutionPlan.mockImplementation(async (options: { sql: string }) => ({
+ sqlToExecute: options.sql,
+ pageSql: undefined,
+ pageLimit: undefined,
+ pageOffset: undefined,
+ countSql: undefined,
+ useAgentResultSession: false,
+ }));
+ mocks.analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "multiple-statements" });
+ mocks.executeMultiWithProgress.mockImplementation(async (connectionId: string, database: string, sql: string, onProgress: (progress: Record<string, unknown>) => void, schema: string | undefined, options: { executionId?: string } = {}) => {
+ const results = await mocks.executeMulti(connectionId, database, sql, schema, options.executionId, options);
+ const total = results.length;
+ results.forEach((result: { statement_index?: number; execution_error?: boolean; execution_time_ms?: number; affected_rows?: number; error?: unknown }, index: number) => {
+ const statementIndex = result.statement_index ?? index;
+ const success = result.execution_error !== true;
+ onProgress({
+ executionId: options.executionId,
+ statementIndex,
+ completed: index + 1,
+ total,
+ success,
+ executionTimeMs: result.execution_time_ms,
+ affectedRows: result.affected_rows,
+ error: success ? undefined : result.error,
+ });
+ });
+ return results;
+ });
+ });
+
+ it("updates the active result run in place on refresh while auto-keep is enabled", async () => {
+ mocks.executeMulti
+ .mockResolvedValueOnce([resultOf([[1]])])
+ .mockResolvedValueOnce([resultOf([[2]])])
+ .mockResolvedValueOnce([resultOf([[3]])]);
+ const { store, tabId } = await createStore();
+ expect(store.toggleResultAutoSave(tabId)).toBe(true);
+
+ // Two explicit executions keep two result runs (auto-keep semantics).
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ let tab = store.tabs.find((item) => item.id === tabId)!;
+ expect(tab.resultRuns).toHaveLength(2);
+ const activeRunId = tab.activeResultRunId!;
+ expect(activeRunId).toBeTruthy();
+ expect(tab.result?.rows).toEqual([[2]]);
+
+ // A refresh re-runs the displayed SQL but updates the active run instead of
+ // appending another result tab (issue #13043).
+ await store.executeTabSql(tabId, "SELECT value FROM t", {
+ resultBaseSql: "SELECT value FROM t",
+ preserveResultDuringExecution: true,
+ refreshActiveResultRun: true,
+ });
+
+ tab = store.tabs.find((item) => item.id === tabId)!;
+ expect(tab.resultRuns).toHaveLength(2);
+ expect(tab.activeResultRunId).toBe(activeRunId);
+ expect(tab.result?.rows).toEqual([[3]]);
+ expect(tab.resultRuns?.find((run) => run.id === activeRunId)?.result?.rows).toEqual([[3]]);
+ });
+
+ it("still captures a new run for explicit executions without the refresh flag", async () => {
+ mocks.executeMulti
+ .mockResolvedValueOnce([resultOf([[1]])])
+ .mockResolvedValueOnce([resultOf([[2]])])
+ .mockResolvedValueOnce([resultOf([[3]])]);
+ const { store, tabId } = await createStore();
+ store.toggleResultAutoSave(tabId);
+
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+
+ expect(store.tabs.find((item) => item.id === tabId)!.resultRuns).toHaveLength(3);
+ });
+
+ it("keeps the single displayed result on refresh when auto-keep is off", async () => {
+ mocks.executeMulti.mockResolvedValueOnce([resultOf([[1]])]).mockResolvedValueOnce([resultOf([[2]])]);
+ const { store, tabId } = await createStore();
+
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ await store.executeTabSql(tabId, "SELECT value FROM t", {
+ resultBaseSql: "SELECT value FROM t",
+ preserveResultDuringExecution: true,
+ refreshActiveResultRun: true,
+ });
+
+ const tab = store.tabs.find((item) => item.id === tabId)!;
+ expect(tab.resultRuns).toBeUndefined();
+ expect(tab.activeResultRunId).toBeUndefined();
+ expect(tab.result?.rows).toEqual([[2]]);
+ });
+
+ it("refreshes a pinned active run in place without losing its pin", async () => {
+ mocks.executeMulti.mockResolvedValueOnce([resultOf([[1]])]).mockResolvedValueOnce([resultOf([[2]])]);
+ const { store, tabId } = await createStore();
+ store.toggleResultAutoSave(tabId);
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ let tab = store.tabs.find((item) => item.id === tabId)!;
+ const runId = tab.activeResultRunId!;
+ expect(store.toggleResultRunPinned(tabId, runId)).toBe(true);
+
+ await store.executeTabSql(tabId, "SELECT value FROM t", {
+ resultBaseSql: "SELECT value FROM t",
+ preserveResultDuringExecution: true,
+ refreshActiveResultRun: true,
+ });
+
+ tab = store.tabs.find((item) => item.id === tabId)!;
+ expect(tab.resultRuns).toHaveLength(1);
+ expect(tab.activeResultRunId).toBe(runId);
+ expect(tab.resultRuns?.[0]?.pinned).toBe(true);
+ expect(tab.result?.rows).toEqual([[2]]);
+ });
+
+ it("shows the in-place refresh on the active run instead of clearing the grid", async () => {
+ mocks.executeMulti.mockResolvedValueOnce([resultOf([[1]])]).mockResolvedValueOnce([resultOf([[2]])]);
+ const { store, tabId } = await createStore();
+ store.toggleResultAutoSave(tabId);
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ const activeRunId = store.tabs.find((item) => item.id === tabId)!.activeResultRunId!;
+
+ const pending = deferred<ReturnType<typeof resultOf>[]>();
+ mocks.executeMulti.mockImplementationOnce(() => pending.promise);
+ const refresh = store.executeTabSql(tabId, "SELECT value FROM t", {
+ resultBaseSql: "SELECT value FROM t",
+ preserveResultDuringExecution: true,
+ refreshActiveResultRun: true,
+ });
+
+ await vi.waitFor(() => {
+ const tab = store.tabs.find((item) => item.id === tabId)!;
+ expect(tab.isExecuting).toBe(true);
+ expect(tab.executingResultRunId).toBe(activeRunId);
+ expect(tab.result?.rows).toEqual([[2]]);
+ });
+
+ pending.resolve([resultOf([[3]])]);
+ await refresh;
+
+ const tab = store.tabs.find((item) => item.id === tabId)!;
+ expect(tab.isExecuting).toBe(false);
+ expect(tab.activeResultRunId).toBe(activeRunId);
+ expect(tab.result?.rows).toEqual([[3]]);
+ expect(tab.resultRuns).toHaveLength(2);
+ });
+
+ it("does not overwrite a run the user switched to while a refresh executes", async () => {
+ mocks.executeMulti.mockResolvedValueOnce([resultOf([[1]])]).mockResolvedValueOnce([resultOf([[2]])]);
+ const { store, tabId } = await createStore();
+ store.toggleResultAutoSave(tabId);
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ const tab0 = store.tabs.find((item) => item.id === tabId)!;
+ const firstRunId = tab0.resultRuns![0]!.id;
+ const secondRunId = tab0.activeResultRunId!;
+
+ const pending = deferred<ReturnType<typeof resultOf>[]>();
+ mocks.executeMulti.mockImplementationOnce(() => pending.promise);
+ const refresh = store.executeTabSql(tabId, "SELECT value FROM t", {
+ resultBaseSql: "SELECT value FROM t",
+ preserveResultDuringExecution: true,
+ refreshActiveResultRun: true,
+ });
+ await vi.waitFor(() => {
+ expect(store.tabs.find((item) => item.id === tabId)!.executingResultRunId).toBe(secondRunId);
+ });
+
+ // The user switches to the first run while the refresh of the second run is
+ // still in flight.
+ await store.setActiveResultRun(tabId, firstRunId);
+ pending.resolve([resultOf([[3]])]);
+ await refresh;
+
+ const tab = store.tabs.find((item) => item.id === tabId)!;
+ expect(tab.isExecuting).toBe(false);
+ // Neither retained run may receive the refresh output of the other run.
+ expect(tab.resultRuns?.find((run) => run.id === firstRunId)?.result?.rows).toEqual([[1]]);
+ // The refreshed run kept its payload (possibly evicted to disk by the
+ // switch); restoring it must show its own data, not the refresh output.
+ await store.setActiveResultRun(tabId, secondRunId);
+ expect(store.tabs.find((item) => item.id === tabId)!.result?.rows).toEqual([[2]]);
+ });
+
+ it("keeps the retained run dataset when an in-place refresh fails", async () => {
+ mocks.executeMulti.mockResolvedValueOnce([resultOf([[1]])]);
+ const { store, tabId } = await createStore();
+ store.toggleResultAutoSave(tabId);
+ await store.executeTabSql(tabId, "SELECT value FROM t");
+ const runId = store.tabs.find((item) => item.id === tabId)!.activeResultRunId!;
+
+ const pending = deferred<ReturnType<typeof resultOf>[]>();
+ mocks.executeMulti.mockImplementationOnce(() => pending.promise);
+ const refresh = store.executeTabSql(tabId, "SELECT value FROM t", {
+ resultBaseSql: "SELECT value FROM t",
+ preserveResultDuringExecution: true,
+ refreshActiveResultRun: true,
+ });
+ await vi.waitFor(() => {
+ expect(store.tabs.find((item) => item.id === tabId)!.isExecuting).toBe(true);
+ });
+ pending.reject(new Error("connection lost"));
+ await refresh;
+
+ const tab = store.tabs.find((item) => item.id === tabId)!;
+ expect(tab.isExecuting).toBe(false);
+ expect(tab.activeResultRunId).toBe(runId);
+ // The error stays on the displayed surface; the retained run keeps its data.
+ expect(tab.result?.execution_error).toBe(true);
+ expect(tab.resultRuns?.find((run) => run.id === runId)?.result?.rows).toEqual([[1]]);
+ expect(tab.resultRuns?.find((run) => run.id === runId)?.result?.execution_error).toBeFalsy();
+ });
+});
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index d7048acbbb..4fad82b27c 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -2523,6 +2523,18 @@ export const useQueryStore = defineStore("query", () => {
}
}
+ /**
+ * Whether the active result run currently owns the displayed result object.
+ * Background follow-ups (metadata analysis, row counts) may only persist their
+ * updates into a run that still displays the result they analyzed; a run the
+ * user switched to mid-execution must not receive that result.
+ */
+ function activeResultRunOwnsDisplayedResult(tab: QueryTab): boolean {
+ if (!tab.activeResultRunId) return false;
+ const run = tab.resultRuns?.find((item) => item.id === tab.activeResultRunId);
+ return run?.result === tab.result || !!run?.results?.some((item) => item === tab.result);
+ }
+
function syncActiveResultRunFromDisplayed(tab: QueryTab, sql?: string) {
if (!tab.activeResultRunId || !tab.resultRuns?.length) return;
const index = tab.resultRuns.findIndex((run) => run.id === tab.activeResultRunId);
@@ -7567,7 +7579,7 @@ export const useQueryStore = defineStore("query", () => {
const current = tabs.value.find((t) => t.id === tabId);
if (!current || current.result !== result) return;
applyQueryDisplayMetadata(current, display);
- syncActiveResultRunFromDisplayed(current);
+ if (activeResultRunOwnsDisplayedResult(current)) syncActiveResultRunFromDisplayed(current);
queryExecutionLog("info", "metadata:display-ready", { traceId, elapsed: elapsed() });
};
// Metadata requests outlive the displayed result when another query starts
@@ -7579,7 +7591,7 @@ export const useQueryStore = defineStore("query", () => {
const current = tabs.value.find((t) => t.id === tabId);
if (patch && current?.result === result) {
applyQueryMetadataPatch(current, patch, databaseType, executionDatabase);
- syncActiveResultRunFromDisplayed(current);
+ if (activeResultRunOwnsDisplayedResult(current)) syncActiveResultRunFromDisplayed(current);
queryExecutionLog("info", "metadata:done", { traceId, elapsed: elapsed() });
} else {
queryExecutionLog("warn", "metadata:stale", { traceId, elapsed: elapsed() });
@@ -7593,7 +7605,7 @@ export const useQueryStore = defineStore("query", () => {
if (current.executionId !== executionId && current.result !== result) return;
current.resultTotalRowCount = totalRowCount;
current.resultTotalRowCountLoading = false;
- syncActiveResultRunFromDisplayed(current);
+ if (activeResultRunOwnsDisplayedResult(current)) syncActiveResultRunFromDisplayed(current);
}
type TotalRowCountSqlTarget = { sql: string; schema?: string };
@@ -7753,6 +7765,13 @@ export const useQueryStore = defineStore("query", () => {
sourceTraceId?: string;
skipEnsureConnected?: boolean;
openInNewResultTab?: boolean;
+ /**
+ * Re-run the displayed result in place: refresh / auto-refresh / page /
+ * sort are result-view operations, so with "auto-keep results" enabled
+ * they update the current result run instead of capturing a new one.
+ * Explicit executions keep capturing runs.
+ */
+ refreshActiveResultRun?: boolean;
targetContext?: SqlExecutionTargetContext;
executionTarget?: MultiDbExecutionTarget;
onExecutionStarted?: () => void;
@@ -7770,7 +7789,11 @@ 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 && !isQueryExecutionErrorResult(tab.result)));
+ // A refresh of the displayed result is not a new execution: it must update
+ // the active result run in place even when auto-keep is enabled, otherwise
+ // every refresh/auto-refresh tick would add a result tab (issue #13043).
+ const refreshActiveResultRun = tab.mode === "query" && options?.refreshActiveResultRun === true && !!tab.activeResultRunId;
+ const captureAutoSavedResultRun = tab.mode === "query" && tab.resultAutoSave === true && !refreshActiveResultRun && (!!tab.activeResultRunId || (!!tab.result && !isQueryExecutionErrorResult(tab.result)));
let captureResultRun = openInNewResultTab || captureAutoSavedResultRun;
let resultRunToRestore: string | undefined;
let reuseResultRun = false;
@@ -7834,10 +7857,13 @@ export const useQueryStore = defineStore("query", () => {
// 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 preserveResultDuringExecution = batchResume !== undefined || (options?.preserveResultDuringExecution === true && (!tab.result || !isQueryExecutionErrorResult(tab.result))) || captureAutoSavedResultRun || refreshActiveResultRun || preserveQueryResultDuringExecution;
const updateActiveResultRun = !!tab.activeResultRunId && preserveResultDuringExecution;
tab.isExecuting = true;
tab.executingResultRunId = !captureResultRun && updateActiveResultRun ? tab.activeResultRunId : null;
+ // The run this execution updates in place, locked before any await. Completion
+ // must not write into a different run the user switched to mid-execution.
+ const lockedResultRunId = tab.executingResultRunId;
options?.onExecutionStarted?.();
tab.isCancelling = false;
if (!tab.queryExecutionStartedAt) {
@@ -7905,6 +7931,7 @@ export const useQueryStore = defineStore("query", () => {
let executionDispatched = false;
let clientRequestStartedAt: number | undefined;
let producedResult = false;
+ let refreshFailedPreservingRun = false;
const resumedExecutionTarget = batchResume?.batch.executionTarget;
const executionConnectionId = resumedExecutionTarget?.connectionId ?? options?.executionTarget?.connectionId ?? tab.connectionId;
// Captured for the catch below: a single-statement failure aborts the whole
@@ -9342,7 +9369,12 @@ export const useQueryStore = defineStore("query", () => {
totalRowCountResolved = true;
}
touchResult(current);
- syncDisplayedResultRun(current, queryBaseSql, captureResultRun);
+ // Only sync the displayed run when it is still the run this execution
+ // targeted; switching result runs mid-execution must not overwrite the
+ // run the user is now looking at.
+ if (lockedResultRunId === null || current.activeResultRunId === lockedResultRunId) {
+ syncDisplayedResultRun(current, queryBaseSql, captureResultRun);
+ }
if (!batchPagination && !options?.appendResult && !resultLimitReached && !totalRowCountResolved && (current.mode === "query" || current.mode === "data") && current.result) {
countQueryTotalRowsInBackground({
tabId: id,
@@ -9448,7 +9480,9 @@ export const useQueryStore = defineStore("query", () => {
current.results = undefined;
current.activeResultIndex = undefined;
}
- if (!captureResultRun && previousDisplayedResults.some(Boolean)) {
+ if (!captureResultRun && !refreshActiveResultRun && previousDisplayedResults.some(Boolean)) {
+ // A failed in-place refresh keeps the retained run's previous dataset, so
+ // its large-value handles must not be released with the displayed error.
releaseReplacedResultLargeValues(current, ...previousDisplayedResults);
}
current.queryAnalysis = undefined;
@@ -9478,7 +9512,14 @@ export const useQueryStore = defineStore("query", () => {
publishResultGeneration(current, "execute");
// When a pinned result requires a new run, errors must use that same
// run instead of being replaced by the retained pinned result below.
- syncDisplayedResultRun(current, queryBaseSql, captureResultRun);
+ // A failed in-place refresh leaves the retained run untouched (the error
+ // stays on the displayed surface only), and a run switched to mid-execution
+ // must not receive this execution's error either.
+ if (refreshActiveResultRun) {
+ refreshFailedPreservingRun = true;
+ } else if (lockedResultRunId === null || current.activeResultRunId === lockedResultRunId) {
+ syncDisplayedResultRun(current, queryBaseSql, captureResultRun);
+ }
}
} finally {
unsubscribeQueryMessages?.();
@@ -9496,7 +9537,13 @@ export const useQueryStore = defineStore("query", () => {
const liveBatch = liveBatchSqlExecutions.get(current);
if (liveBatch?.executionId === executionId) current.batchSqlExecution = liveBatch;
finishBatchSqlExecution(current, executionId, current.isCancelling === true);
- if (current.activeResultRunId && current.result) syncActiveResultRunFromDisplayed(current);
+ if (current.activeResultRunId && current.result && !refreshFailedPreservingRun) {
+ // Same ownership rule as the completion syncs above: never write into a
+ // run this execution did not target.
+ if (current.executingResultRunId === null || current.activeResultRunId === current.executingResultRunId) {
+ syncActiveResultRunFromDisplayed(current);
+ }
+ }
if (captureResultRun && !current.activeResultRunId) {
restorePendingResultRun(current, executionId);
} else {
diff --git a/packages/app-tests/useDataGridActions.test.ts b/packages/app-tests/useDataGridActions.test.ts
index a299586218..a185e0a77e 100644
--- a/packages/app-tests/useDataGridActions.test.ts
+++ b/packages/app-tests/useDataGridActions.test.ts
@@ -287,6 +287,7 @@ test("query toolbar refresh reruns the complete multi-result SQL and keeps the a
resultSortedSql: undefined,
preserveResultDuringExecution: true,
preserveActiveResultIndex: true,
+ refreshActiveResultRun: true,
});
}
assert.equal(tab.results?.length, 2);