feat(explain): add plan canvas with actual execution plans

This commit is contained in:
Fernando Possebon authored and GitHub committed 2026-08-03 03:06:36 +08:00
1 parent cc7b2b17c5
commit ed1e36912c
28 files changed
+2281 -43

No files matched your search

@@ -0,0 +1,154 @@
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
buildExplainSql: vi.fn(),
parseExplainResult: vi.fn(),
executeQuery: vi.fn(),
closeClientSession: vi.fn(),
saveOpenTabsState: vi.fn(),
getConfig: vi.fn(),
}));
vi.mock("@/lib/diagram/explainPlan", () => ({
buildExplainSql: mocks.buildExplainSql,
parseExplainResult: mocks.parseExplainResult,
parseDamengExplainText: vi.fn(),
parseOracleExplainText: vi.fn(),
sqlServerExplainResult: vi.fn(),
}));
vi.mock("@/lib/backend/api", () => ({
executeQuery: mocks.executeQuery,
closeClientConnectionSession: mocks.closeClientSession,
saveOpenTabsState: mocks.saveOpenTabsState,
}));
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
getConfig: mocks.getConfig,
recordConnectionLostError: vi.fn(),
}),
}));
vi.mock("@/stores/settingsStore", () => ({
useSettingsStore: () => ({
editorSettings: { pageSize: 100, openTabsRestoreMode: "all", confirmUnsavedSqlClose: false },
}),
}));
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)),
});
}
const SOURCE_SQL = "SELECT * FROM orders";
async function explain(explainMode?: string) {
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("pg-1", "shop", "Query", "query", "public");
await store.explainTabSql(tabId, SOURCE_SQL, "postgres", explainMode);
return { store, tabId };
}
describe("queryStore PostgreSQL EXPLAIN ANALYZE", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.unstubAllGlobals();
installLocalStorage();
setActivePinia(createPinia());
mocks.getConfig.mockReturnValue({ id: "pg-1", name: "Postgres", db_type: "postgres" });
mocks.buildExplainSql.mockResolvedValue({ ok: true, sql: "EXPLAIN (FORMAT JSON) SELECT * FROM orders" });
mocks.executeQuery.mockResolvedValue({ columns: ["QUERY PLAN"], rows: [["[]"]], affected_rows: 0, execution_time_ms: 1 });
mocks.parseExplainResult.mockReturnValue({ databaseType: "postgres", raw: [], nodes: [] });
mocks.saveOpenTabsState.mockResolvedValue(undefined);
});
it("requests ANALYZE when the autotrace toggle is on", async () => {
await explain("autotrace");
expect(mocks.buildExplainSql).toHaveBeenCalledTimes(1);
expect(mocks.buildExplainSql).toHaveBeenCalledWith("postgres", SOURCE_SQL, "json", true);
});
it("leaves the plain explain call untouched in the default mode", async () => {
const { tabId } = await explain();
expect(mocks.buildExplainSql).toHaveBeenCalledWith("postgres", SOURCE_SQL);
expect(mocks.executeQuery.mock.calls[0][5]).toMatchObject({ clientSessionId: `${tabId}:explain` });
expect(mocks.executeQuery.mock.calls[0][5].executionMode).toBeUndefined();
});
it("leaves the plain explain call untouched when the toggle is explicitly off", async () => {
await explain("explain");
expect(mocks.buildExplainSql).toHaveBeenCalledWith("postgres", SOURCE_SQL);
});
it("runs the analyzed statement the backend built and parses its plan", async () => {
mocks.buildExplainSql.mockResolvedValue({ ok: true, sql: "EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders" });
const parsedPlan = { databaseType: "postgres", raw: [], nodes: [{ id: "0", title: "Sort", nodeType: "Sort", details: ["Actual Rows: 84000"], children: [] }] };
mocks.parseExplainResult.mockReturnValue(parsedPlan);
const { store, tabId } = await explain("autotrace");
expect(mocks.executeQuery).toHaveBeenCalledTimes(1);
expect(mocks.executeQuery.mock.calls[0][2]).toBe("EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders");
expect(mocks.executeQuery.mock.calls[0][5]).toMatchObject({
clientSessionId: expect.stringMatching(new RegExp(`^${tabId}:explain:`)),
executionMode: "postgres_read_only_transaction",
});
expect(mocks.closeClientSession).toHaveBeenCalledWith("pg-1", "shop", mocks.executeQuery.mock.calls[0][5].clientSessionId);
expect(store.tabs.find((tab) => tab.id === tabId)).toMatchObject({
isExplaining: false,
explainClientSessionId: undefined,
explainPlan: parsedPlan,
explainSql: "EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders",
explainError: undefined,
});
});
it("surfaces a backend rejection of the analyzed statement", async () => {
mocks.buildExplainSql.mockResolvedValue({ ok: false, reason: "unsafe" });
const { store, tabId } = await explain("autotrace");
expect(mocks.executeQuery).not.toHaveBeenCalled();
expect(store.tabs.find((tab) => tab.id === tabId)).toMatchObject({
isExplaining: false,
explainPlan: undefined,
explainError: "unsafe",
});
});
it("closes the isolated session after an analyzed query error", async () => {
mocks.buildExplainSql.mockResolvedValue({ ok: true, sql: "EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM orders" });
mocks.executeQuery.mockRejectedValue(new Error("query failed"));
const { store, tabId } = await explain("autotrace");
const clientSessionId = mocks.executeQuery.mock.calls[0][5].clientSessionId;
expect(mocks.closeClientSession).toHaveBeenCalledWith("pg-1", "shop", clientSessionId);
expect(store.tabs.find((tab) => tab.id === tabId)).toMatchObject({
isExplaining: false,
explainClientSessionId: undefined,
explainPlan: undefined,
explainError: "query failed",
});
});
it("does not send the analyze flag for other engines sharing this path", async () => {
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("pg-1", "shop", "Query", "query", "public");
await store.explainTabSql(tabId, SOURCE_SQL, "questdb", "autotrace");
expect(mocks.buildExplainSql).toHaveBeenCalledWith("questdb", SOURCE_SQL);
});
});
@@ -110,6 +110,42 @@ describe("queryStore SQL Server explain", () => {
await vi.waitFor(() => expect(mocks.closeClientConnectionSession).toHaveBeenCalledWith("sqlserver-1", "dbx_explain_plan_test", clientSessionId));
});
it("switches to STATISTICS XML when the autotrace toggle is on", async () => {
const actualPlanSql = `SET STATISTICS XML ON;\nGO\n${sourceSql}\nGO\nSET STATISTICS XML OFF;`;
// STATISTICS XML runs the statement, so the row set precedes the plan.
const rowsResult: QueryResult = { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 3 };
mocks.buildExplainSql.mockResolvedValue({ ok: true, sql: actualPlanSql });
mocks.executeMulti.mockResolvedValue([rowsResult, planResult]);
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo");
await store.explainTabSql(tabId, sourceSql, "sqlserver", "autotrace");
const tab = store.tabs.find((item) => item.id === tabId)!;
expect(mocks.buildExplainSql).toHaveBeenCalledWith("sqlserver", sourceSql, "json", true);
expect(mocks.executeQuery.mock.calls[0]?.[2]).toBe("SET STATISTICS XML ON;");
expect(mocks.executeQuery.mock.calls[1]?.[2]).toBe("SET STATISTICS XML OFF;");
expect(mocks.executeQuery.mock.calls[1]?.[5]).toMatchObject({ timeoutSecs: 5, executionMode: "simple" });
expect(mocks.executeMulti.mock.calls[0]?.[2]).toBe(sourceSql);
expect(mocks.sqlServerExplainResult).toHaveBeenCalledWith([rowsResult, planResult]);
expect(tab.explainSql).toBe(actualPlanSql);
expect(tab.explainPlan).toEqual(visualPlan);
expect(tab.explainError).toBeUndefined();
});
it("keeps SHOWPLAN when the autotrace toggle is off", async () => {
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("sqlserver-1", "dbx_explain_plan_test", "Query", "query", "dbo");
await store.explainTabSql(tabId, sourceSql, "sqlserver", "explain");
expect(mocks.buildExplainSql).toHaveBeenCalledWith("sqlserver", sourceSql);
expect(mocks.executeQuery.mock.calls[0]?.[2]).toBe("SET SHOWPLAN_XML ON;");
expect(mocks.executeQuery.mock.calls[1]?.[2]).toBe("SET SHOWPLAN_XML OFF;");
});
it("shows an execution error and still closes the SHOWPLAN session", async () => {
mocks.sqlServerExplainResult.mockReturnValue({ error: "Invalid object name 'missing_table'" });
const { useQueryStore } = await import("@/stores/queryStore");
+21 -9
View File
@@ -4469,9 +4469,15 @@ export const useQueryStore = defineStore("query", () => {
}
if (databaseType === "sqlserver") {
// SQL Server reuses the autotrace toggle to ask for the actual execution plan:
// STATISTICS XML runs the statement and adds runtime counters to the same
// ShowPlanXML document, while SHOWPLAN_XML only estimates.
const actualPlan = explainMode === "autotrace";
const planCaptureOn = actualPlan ? "SET STATISTICS XML ON;" : "SET SHOWPLAN_XML ON;";
const planCaptureOff = actualPlan ? "SET STATISTICS XML OFF;" : "SET SHOWPLAN_XML OFF;";
let built: BuildExplainSqlResult;
try {
built = await buildExplainSql(databaseType, sql);
built = actualPlan ? await buildExplainSql(databaseType, sql, "json", true) : await buildExplainSql(databaseType, sql);
} catch (e: any) {
tab.isExplaining = false;
tab.explainExecutionId = undefined;
@@ -4488,14 +4494,14 @@ export const useQueryStore = defineStore("query", () => {
tab.explainSql = built.sql;
const clientSessionId = `${tabClientSessionId(tab, "explain")}:${executionId}`;
tab.explainClientSessionId = clientSessionId;
let showplanEnabled = false;
let planCaptureEnabled = false;
try {
await api.executeQuery(tab.connectionId, tab.database, "SET SHOWPLAN_XML ON;", tab.schema, executionId, {
await api.executeQuery(tab.connectionId, tab.database, planCaptureOn, tab.schema, executionId, {
clientSessionId,
timeoutSecs: queryTimeoutSecs,
executionMode: "simple",
});
showplanEnabled = true;
planCaptureEnabled = true;
if (tabs.value.find((t) => t.id === id)?.explainExecutionId !== executionId) {
return { ok: true as const, sql: built.sql };
}
@@ -4526,9 +4532,9 @@ export const useQueryStore = defineStore("query", () => {
current.explainError = String(e?.message || e);
}
} finally {
if (showplanEnabled) {
if (planCaptureEnabled) {
try {
await api.executeQuery(tab.connectionId, tab.database, "SET SHOWPLAN_XML OFF;", tab.schema, undefined, {
await api.executeQuery(tab.connectionId, tab.database, planCaptureOff, tab.schema, undefined, {
clientSessionId,
timeoutSecs: queryTimeoutSecs > 0 ? Math.min(queryTimeoutSecs, 5) : 5,
executionMode: "simple",
@@ -4548,7 +4554,8 @@ export const useQueryStore = defineStore("query", () => {
return { ok: true as const, sql: built.sql };
}
const built = await buildExplainSql(databaseType, sql);
const postgresAnalyze = databaseType === "postgres" && explainMode === "autotrace";
const built = postgresAnalyze ? await buildExplainSql(databaseType, sql, "json", true) : await buildExplainSql(databaseType, sql);
if (!built.ok) {
tab.explainPlan = undefined;
tab.explainError = built.reason;
@@ -4558,12 +4565,14 @@ export const useQueryStore = defineStore("query", () => {
}
tab.explainSql = built.sql;
const clientSessionId = tabClientSessionId(tab, "explain");
const clientSessionId = postgresAnalyze ? `${tabClientSessionId(tab, "explain")}:${executionId}` : tabClientSessionId(tab, "explain");
if (postgresAnalyze) tab.explainClientSessionId = clientSessionId;
try {
const result = await api.executeQuery(tab.connectionId, tab.database, built.sql, tab.schema, executionId, {
clientSessionId,
catalog: tab.catalog,
timeoutSecs: queryTimeoutSecs,
executionMode: postgresAnalyze ? "postgres_read_only_transaction" : undefined,
});
const current = tabs.value.find((t) => t.id === id);
if (current?.explainExecutionId === executionId) {
@@ -4582,7 +4591,10 @@ export const useQueryStore = defineStore("query", () => {
current.isExplaining = false;
current.explainExecutionId = undefined;
}
void closeClientSessionId(tab.connectionId, tab.database, clientSessionId, tab.catalog, { tabId: tab.id });
if (current?.explainClientSessionId === clientSessionId) current.explainClientSessionId = undefined;
const closePromise = closeClientSessionId(tab.connectionId, tab.database, clientSessionId, tab.catalog, { tabId: tab.id, explainExecutionId: executionId });
if (postgresAnalyze) await closePromise;
else void closePromise;
}
return { ok: true as const, sql: built.sql };
}