feat(query): auto-keep results by default and fix restore race

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-09-10 15:57:27 +08:00
1 parent 5b5d58cd2a
commit e0cc787f0a
19 files changed
+231 -17

No files matched your search

@@ -4,6 +4,7 @@ import { BackendErrorException } from "@/lib/backend/errorUtils";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
defaultAutoKeepResults: false,
analyzeEditableQueryEditability: vi.fn(),
cancelQuery: vi.fn(),
closeClientConnectionSession: vi.fn(),
@@ -42,7 +43,7 @@ vi.mock("@/stores/connectionStore", () => ({
vi.mock("@/stores/settingsStore", () => ({
useSettingsStore: () => ({
editorSettings: { autoCalculateTotalRows: false, pageSize: 100, continueOnErrorOnBatch: false },
editorSettings: { autoCalculateTotalRows: false, pageSize: 100, continueOnErrorOnBatch: false, defaultAutoKeepResults: mocks.defaultAutoKeepResults },
}),
}));
@@ -112,6 +113,7 @@ function structuredSqlError(detail = "duplicate key") {
describe("queryStore multi-statement errors", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.defaultAutoKeepResults = false;
vi.unstubAllGlobals();
mocks.tabResultSnapshots.clear();
installLocalStorage();
@@ -1221,4 +1223,103 @@ describe("queryStore multi-statement errors", () => {
expect(tab.resultRuns).toBeUndefined();
expect(tab.activeResultRunId).toBeUndefined();
});
async function prepareDiskBackedAutoKeptResult() {
mocks.defaultAutoKeepResults = true;
const { useQueryStore } = await import("@/stores/queryStore");
const cache = await import("@/lib/tabs/tabResultCache");
const store = useQueryStore();
const id = store.createTab("mysql-1", "app", "Restore");
mocks.executeMulti.mockResolvedValue([{ columns: ["value"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 }]);
await store.executeCurrentSql("SELECT 1");
const tab = store.tabs.find((item) => item.id === id)!;
const run = tab.resultRuns![0]!;
const snapshot = mocks.tabResultSnapshots.get(run.resultCacheKey!) as Awaited<ReturnType<typeof cache.readTabResultSnapshot>>;
tab.result = undefined;
tab.results = undefined;
run.result = undefined;
run.results = undefined;
mocks.executeMulti.mockClear();
const read = deferred<Awaited<ReturnType<typeof cache.readTabResultSnapshot>>>();
vi.mocked(cache.readTabResultSnapshot).mockImplementationOnce(() => read.promise);
return { store, id, tab, read, snapshot };
}
it("reserves execution before restoring retained results and rejects a repeated run", async () => {
const { store, tab, read, snapshot } = await prepareDiskBackedAutoKeptResult();
const execution = store.executeCurrentSql("SELECT 2");
expect(tab.isExecuting).toBe(true);
expect(tab.executionId).toBeTruthy();
await expect(store.executeCurrentSql("SELECT 2")).resolves.toBe(false);
expect(mocks.executeMulti).not.toHaveBeenCalled();
read.resolve(snapshot);
await execution;
expect(mocks.executeMulti).toHaveBeenCalledTimes(1);
expect(tab.resultRuns).toHaveLength(2);
expect(tab.isExecuting).toBe(false);
expect(tab.executionId).toBeUndefined();
});
it("cancels result restoration without dispatch and ignores its late payload", async () => {
const { store, id, tab, read, snapshot } = await prepareDiskBackedAutoKeptResult();
const execution = store.executeCurrentSql("SELECT 2");
await expect(store.cancelTabExecution(id)).resolves.toBe(true);
expect(tab.isExecuting).toBe(false);
expect(mocks.cancelQuery).not.toHaveBeenCalled();
expect(mocks.executeMulti).not.toHaveBeenCalled();
mocks.executeMulti.mockResolvedValueOnce([{ columns: ["value"], rows: [[3]], affected_rows: 0, execution_time_ms: 1 }]);
await store.executeCurrentSql("SELECT 3");
read.resolve(snapshot);
await expect(execution).resolves.toBe(false);
expect(mocks.executeMulti).toHaveBeenCalledTimes(1);
expect(tab.result?.rows).toEqual([[3]]);
expect(tab.isExecuting).toBe(false);
});
it("releases the preparation reservation when result restoration rejects", async () => {
const { store, tab, read } = await prepareDiskBackedAutoKeptResult();
const execution = store.executeCurrentSql("SELECT 2");
const rejected = expect(execution).rejects.toThrow("disk read failed");
read.reject(new Error("disk read failed"));
await rejected;
expect(tab.isExecuting).toBe(false);
expect(tab.executionId).toBeUndefined();
expect(tab.queryExecutionStartedAt).toBeUndefined();
expect(mocks.executeMulti).not.toHaveBeenCalled();
await store.executeCurrentSql("SELECT 3");
expect(mocks.executeMulti).toHaveBeenCalledTimes(1);
});
it("does not revive a closed tab when its pending result read completes", async () => {
const { store, id, tab, read, snapshot } = await prepareDiskBackedAutoKeptResult();
const execution = store.executeCurrentSql("SELECT 2");
store.closeTab(id, { force: true });
read.resolve(snapshot);
await expect(execution).resolves.toBe(false);
expect(store.tabs.some((item) => item.id === id)).toBe(false);
expect(tab.result).toBeUndefined();
expect(mocks.executeMulti).not.toHaveBeenCalled();
});
it("preserves an imported plain result on the first query when auto-keep is the default", async () => {
mocks.defaultAutoKeepResults = true;
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const sourceId = store.createTab("mysql-1", "app", "Source");
store.toggleResultAutoSave(sourceId);
mocks.executeMulti.mockResolvedValueOnce([{ columns: ["value"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 }]);
await store.executeCurrentSql("SELECT 1");
const bytes = await store.exportResultArchive(sourceId);
const importedId = await store.importResultArchive(bytes!);
const tab = store.tabs.find((item) => item.id === importedId)!;
expect(tab.resultAutoSave).toBe(true);
expect(tab.resultRuns).toBeUndefined();
expect(tab.result?.rows).toEqual([[1]]);
mocks.executeMulti.mockResolvedValueOnce([{ columns: ["value"], rows: [[2]], affected_rows: 0, execution_time_ms: 1 }]);
await store.executeCurrentSql("SELECT 2");
expect(tab.resultRuns).toHaveLength(2);
expect(tab.result?.rows).toEqual([[2]]);
await expect(store.setActiveResultRun(importedId!, tab.resultRuns![0]!.id)).resolves.toBe(true);
expect(tab.result?.rows).toEqual([[1]]);
});
});
+86 -14
View File
@@ -1028,6 +1028,23 @@ export const useQueryStore = defineStore("query", () => {
return true;
}
function initializeResultAutoSave(tab: QueryTab) {
if (tab.mode === "query" && tab.resultAutoSave === undefined && settingsStore.editorSettings.defaultAutoKeepResults === true) {
tab.resultAutoSave = true;
}
}
// Apply after the settings mutation completes, never during tab registration
// or restoration while the workspace still has incomplete group membership.
watch(
() => settingsStore.editorSettings.defaultAutoKeepResults,
(enabled) => {
for (const tab of tabs.value) {
if (tab.mode === "query") setResultAutoSave(tab, enabled === true);
}
},
);
/**
* Atomically registers a freshly built tab: the tab joins the focused group
* and (by default) becomes that group's active tab and the global active tab
@@ -1037,6 +1054,7 @@ export const useQueryStore = defineStore("query", () => {
*/
function registerOpenTab(tab: QueryTab, options: { activate?: boolean; insertAfterTabId?: string } = {}): string {
assertUpdateAllowsInteraction();
initializeResultAutoSave(tab);
const anchorIndex = options.insertAfterTabId ? tabs.value.findIndex((item) => item.id === options.insertAfterTabId) : -1;
if (anchorIndex >= 0) {
tabs.value.splice(anchorIndex + 1, 0, tab);
@@ -1205,6 +1223,7 @@ export const useQueryStore = defineStore("query", () => {
const savedSqlEditorPositionTimers = new Map<string, ReturnType<typeof setTimeout>>();
const pendingTabSessionResets = new Map<string, Promise<void>>();
const pendingResultRunRestores = new Map<string, string>();
const pendingResultRunPreparations = new WeakMap<QueryTab, string>();
const multiDbExecutionWorkers = new Map<string, QueryTab>();
const multiDbExecutionWorkerScopes = new Map<string, Set<string>>();
let resultCacheTrimScheduled = false;
@@ -1615,7 +1634,7 @@ export const useQueryStore = defineStore("query", () => {
return true;
}
async function restoreResultRunPayload(tab: QueryTab, runId: string) {
async function restoreResultRunPayload(tab: QueryTab, runId: string, isCurrent?: () => boolean) {
const run = tab.resultRuns?.find((item) => item.id === runId);
if (!run || run.result || run.results?.length) return run;
@@ -1623,6 +1642,7 @@ export const useQueryStore = defineStore("query", () => {
if (!cacheKey) return run;
const snapshot = await readTabResultSnapshot(cacheKey);
if (isCurrent && !isCurrent()) return undefined;
const snapshotRun = snapshot?.resultRuns?.find((item) => item.id === runId);
if (!snapshotRun) return run;
@@ -1651,11 +1671,12 @@ export const useQueryStore = defineStore("query", () => {
return restoredRun;
}
async function setActiveResultRun(id: string, runId: string, options: { evictInactive?: boolean } = {}) {
async function setActiveResultRun(id: string, runId: string, options: { evictInactive?: boolean; isCurrent?: () => boolean } = {}) {
const tab = findExecutionTab(id);
if (!tab) return false;
const existingRun = tab.resultRuns?.find((item) => item.id === runId);
const run = existingRun && resultRunHasPayload(existingRun) ? existingRun : await restoreResultRunPayload(tab, runId);
const run = existingRun && resultRunHasPayload(existingRun) ? existingRun : await restoreResultRunPayload(tab, runId, options.isCurrent);
if (options.isCurrent && !options.isCurrent()) return false;
if (!run?.result && !run?.results?.length) return false;
projectResultRun(tab, run);
if (options.evictInactive !== false) evictInactiveResultRunPayloads(tab);
@@ -1974,11 +1995,15 @@ export const useQueryStore = defineStore("query", () => {
function toggleResultAutoSave(id: string): boolean {
const tab = tabs.value.find((t) => t.id === id);
if (!tab || tab.mode !== "query") return false;
tab.resultAutoSave = tab.resultAutoSave ? undefined : true;
if (tab.resultAutoSave && tab.result && !tab.activeResultRunId) {
setResultAutoSave(tab, tab.resultAutoSave !== true);
return tab.resultAutoSave === true;
}
function setResultAutoSave(tab: QueryTab, enabled: boolean) {
tab.resultAutoSave = enabled;
if (enabled && !tab.isExecuting && tab.result && !tab.activeResultRunId) {
captureDisplayedResultRun(tab, tab.resultBaseSql ?? tab.lastExecutedSql ?? tab.sql);
}
return tab.resultAutoSave === true;
}
function syncActiveResultRunFromDisplayed(tab: QueryTab, sql?: string) {
@@ -2142,6 +2167,7 @@ export const useQueryStore = defineStore("query", () => {
tab.schema = connectionObjectTreeNodeSchema(connection, tab.database, tab.schema);
}
}
restored.tabs.forEach(initializeResultAutoSave);
tabs.value = restored.tabs;
for (const tab of restored.tabs) {
if (tab.mode === "data") {
@@ -2450,6 +2476,7 @@ export const useQueryStore = defineStore("query", () => {
const restoredResult = restoreCachedResultPayload(restoredTab, await readTabResultSnapshot(handoff.resultCacheKey));
if (!restoredResult) restoredTab.resultCacheState = "missing";
}
initializeResultAutoSave(restoredTab);
const existingIndex = tabs.value.findIndex((tab) => tab.id === handoff.tabId);
if (existingIndex >= 0) {
tabs.value.splice(existingIndex, 1, restoredTab);
@@ -3770,6 +3797,7 @@ export const useQueryStore = defineStore("query", () => {
whereInput: original.whereInput,
previewSql: original.previewSql,
};
initializeResultAutoSave(newTab);
tabs.value.splice(idx + 1, 0, newTab);
const owner = groupForTab(id);
@@ -4629,6 +4657,7 @@ export const useQueryStore = defineStore("query", () => {
const executionTabId = options?.tabId ?? activeTabId.value;
if (!executionTabId) return;
const tab = tabs.value.find((item) => item.id === executionTabId);
if (tab && pendingResultRunPreparations.has(tab)) return false;
const previousGridKey = tab ? resultGridInstanceKey(tab) : undefined;
if (tab?.mode === "query") {
tab.resultSortColumn = undefined;
@@ -5353,7 +5382,9 @@ export const useQueryStore = defineStore("query", () => {
const tab = tabs.value.find((t) => t.id === tabId);
if (!tab || tab.result !== result) return;
queryExecutionLog("info", "metadata:start", { traceId, elapsed: elapsed() });
const patch = await buildQueryMetadataPatch(tab, sql, executionDatabase, traceId, elapsed, hiddenPrimaryKeys);
// Metadata requests outlive the displayed result when another query starts
// or a retained run is selected. Analyze this result, not the live tab.
const patch = await buildQueryMetadataPatch({ ...tab, result }, sql, executionDatabase, traceId, elapsed, hiddenPrimaryKeys);
if (patch?.queryAnalysis && hasHiddenPhysicalRowKey(databaseType, hiddenPrimaryKeys)) {
patch.queryAnalysis = { ...patch.queryAnalysis, allowInsert: false };
}
@@ -5543,6 +5574,7 @@ export const useQueryStore = defineStore("query", () => {
assertUpdateAllowsInteraction();
const tab = findExecutionTab(id);
if (!tab || !sql.trim()) return;
if (pendingResultRunPreparations.has(tab)) return false;
const openInNewResultTab = tab.mode === "query" && options?.openInNewResultTab === true;
// Auto-saved results need two independent decisions: keep the currently
@@ -5550,24 +5582,54 @@ 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);
let captureResultRun = openInNewResultTab || captureAutoSavedResultRun;
let resultRunToRestore: string | undefined;
let reuseResultRun = false;
if (!captureResultRun && tab.mode === "query" && !tab.resultAutoSave && tab.activeResultRunId) {
const activeRun = tab.resultRuns?.find((run) => run.id === tab.activeResultRunId);
if (activeRun?.pinned) {
const reusableRun = tab.resultRuns?.find((run) => !run.pinned);
if (reusableRun) {
// A stale disk snapshot must not make us fall back to overwriting
// the pinned active run. Capture a fresh run instead.
captureResultRun = !(await setActiveResultRun(id, reusableRun.id));
resultRunToRestore = reusableRun.id;
reuseResultRun = true;
} else {
captureResultRun = true;
}
}
}
if (captureResultRun && tab.activeResultRunId && !tab.result) {
await setActiveResultRun(id, tab.activeResultRunId);
if (findExecutionTab(id) !== tab) return false;
if (captureResultRun && tab.activeResultRunId && !tab.result) resultRunToRestore = tab.activeResultRunId;
if (resultRunToRestore) {
// Reserve before disk I/O so another click cannot queue a second SQL.
const preparationId = uuid();
pendingResultRunPreparations.set(tab, preparationId);
tab.isExecuting = true;
tab.isCancelling = false;
tab.executionId = preparationId;
tab.executingResultRunId = null;
tab.queryExecutionStartedAt = Date.now();
const isCurrent = () => findExecutionTab(id) === tab && tab.executionId === preparationId && pendingResultRunPreparations.get(tab) === preparationId;
let prepared = false;
try {
const restored = await setActiveResultRun(id, resultRunToRestore, { isCurrent });
if (!isCurrent()) return false;
if (reuseResultRun) captureResultRun = !restored;
prepared = true;
} catch (error) {
if (!isCurrent()) return false;
throw error;
} finally {
if (pendingResultRunPreparations.get(tab) === preparationId) {
pendingResultRunPreparations.delete(tab);
if (!prepared && tab.executionId === preparationId) {
tab.isExecuting = false;
tab.isCancelling = false;
tab.executionId = undefined;
tab.executingResultRunId = undefined;
tab.queryExecutionStartedAt = undefined;
}
}
}
}
const executionId = uuid();
const executionEditorFingerprint = tab.mode === "query" ? sqlTextFingerprint(tab.sql) : undefined;
@@ -7147,6 +7209,16 @@ export const useQueryStore = defineStore("query", () => {
// 单调递增、不随取消结果回退:导航流程据此判断"执行期间用户请求过停止"
// (isCancelling 在取消失败或查询先完成时会被清掉,无法承担这个语义)
tab.cancelRequestCount = (tab.cancelRequestCount ?? 0) + 1;
if (pendingResultRunPreparations.get(tab) === executionId) {
// No SQL was dispatched; invalidate the disk read without a backend cancel.
pendingResultRunPreparations.delete(tab);
tab.isExecuting = false;
tab.isCancelling = false;
tab.executionId = undefined;
tab.executingResultRunId = undefined;
tab.queryExecutionStartedAt = undefined;
return true;
}
const cancellationStartedAt = performance.now();
try {
const canceled = await withCancelQueryTimeout(api.cancelQuery(executionId));
+4
View File
@@ -804,6 +804,7 @@ export interface EditorSettings {
dataGridExtractorOptions: DataGridExtractorOptions;
dataGridExtractorOptionsMigrationVersion: number;
resultRunDisplayMode: ResultRunDisplayMode;
defaultAutoKeepResults: boolean;
multiStatementDefaultView: MultiStatementDefaultView;
dataGridAutoTransposeSingleRow: boolean;
dataGridCellDetailButtonVisible: boolean;
@@ -1040,6 +1041,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
dataGridExtractorOptions: normalizeDataGridExtractorOptions(DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS),
dataGridExtractorOptionsMigrationVersion: DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION,
resultRunDisplayMode: "tabs",
defaultAutoKeepResults: false,
multiStatementDefaultView: "result",
dataGridAutoTransposeSingleRow: false,
dataGridCellDetailButtonVisible: true,
@@ -1497,6 +1499,7 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
dataGridExtractorOptions,
dataGridExtractorOptionsMigrationVersion: DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION,
resultRunDisplayMode: normalizeResultRunDisplayMode(settings.resultRunDisplayMode),
defaultAutoKeepResults: settings.defaultAutoKeepResults === true,
multiStatementDefaultView: normalizeMultiStatementDefaultView(settings.multiStatementDefaultView),
dataGridAutoTransposeSingleRow: settings.dataGridAutoTransposeSingleRow === true,
dataGridCellDetailButtonVisible: typeof settings.dataGridCellDetailButtonVisible === "boolean" ? settings.dataGridCellDetailButtonVisible : DEFAULT_EDITOR_SETTINGS.dataGridCellDetailButtonVisible,
@@ -2255,6 +2258,7 @@ export const useSettingsStore = defineStore("settings", () => {
if (partial.dataGridExtractorOptions !== undefined) editorSettings.value.dataGridExtractorOptions = normalizeDataGridExtractorOptions(partial.dataGridExtractorOptions);
if (partial.dataGridExtractorOptionsMigrationVersion !== undefined) editorSettings.value.dataGridExtractorOptionsMigrationVersion = DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION;
if (partial.resultRunDisplayMode !== undefined) editorSettings.value.resultRunDisplayMode = normalizeResultRunDisplayMode(partial.resultRunDisplayMode);
if (partial.defaultAutoKeepResults !== undefined) editorSettings.value.defaultAutoKeepResults = partial.defaultAutoKeepResults === true;
if (partial.multiStatementDefaultView !== undefined) editorSettings.value.multiStatementDefaultView = normalizeMultiStatementDefaultView(partial.multiStatementDefaultView);
if (partial.dataGridAutoTransposeSingleRow !== undefined) editorSettings.value.dataGridAutoTransposeSingleRow = partial.dataGridAutoTransposeSingleRow === true;
if (partial.dataGridCellDetailButtonVisible !== undefined) editorSettings.value.dataGridCellDetailButtonVisible = typeof partial.dataGridCellDetailButtonVisible === "boolean" ? partial.dataGridCellDetailButtonVisible : DEFAULT_EDITOR_SETTINGS.dataGridCellDetailButtonVisible;