fix(grid): show column comments for grouped query results

This commit is contained in:
jearhe authored and GitHub committed 2026-08-18 11:50:49 +08:00
1 parent 4c260b1a2f
commit 8271ba2a71
8 files changed
+1220 -8

No files matched your search

@@ -0,0 +1,243 @@
import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
/**
* Request-count regression for grouped-query display metadata enrichment.
*
* Proves the contract from the #6463 review:
* - GROUP BY result-comment enrichment issues `getColumns` only (never
* `listIndexes` for display);
* - cold-cache counts are linear in the number of distinct source tables;
* - warm repeat issues zero additional metadata calls;
* - concurrent same-table enrichments dedupe to a single `getColumns`;
* - multi-source loads are scheduled under bounded concurrency;
* - metadata failure never affects the query result or editability.
*/
const executeMulti = vi.fn();
const executeQuery = vi.fn();
const analyzeEditableQueryEditability = vi.fn();
const getColumns = vi.fn();
const listIndexes = vi.fn();
const listObjects = vi.fn();
const getConnectionConfig = vi.fn();
const lookupLocalCompletionTables = vi.fn();
const buildSortedQuerySql = vi.fn();
const buildDataGridCountSql = vi.fn();
const prepareQueryPaginationExecutionPlan = vi.fn(async (options) => ({
sqlToExecute: options.sql,
pageSql: undefined,
pageLimit: undefined,
pageOffset: undefined,
countSql: undefined,
useAgentResultSession: false,
}));
const editorSettings = {
pageSize: 100,
autoCalculateTotalRows: false,
};
vi.mock("@/lib/backend/api", () => ({
analyzeEditableQueryEditability,
buildDataGridCountSql,
buildSortedQuerySql,
closeClientConnectionSession: vi.fn().mockResolvedValue(undefined),
closeQuerySession: vi.fn().mockResolvedValue(undefined),
executeMulti,
executeQuery,
getColumns,
listIndexes,
listObjects,
prepareQueryPaginationExecutionPlan,
saveOpenTabsState: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: vi.fn().mockResolvedValue(undefined),
getConfig: getConnectionConfig,
lookupLocalCompletionTables,
recordConnectionLostError: vi.fn(),
}),
}));
vi.mock("@/stores/settingsStore", () => ({
useSettingsStore: () => ({
editorSettings,
}),
}));
function column(name: string, comment: string | null, isPrimaryKey = false) {
return { name, data_type: "varchar", is_nullable: true, column_default: null, is_primary_key: isPrimaryKey, extra: null, comment };
}
const usersColumns = [column("id", "用户ID", true), column("department", "所属部门")];
const ordersColumns = [column("id", "订单ID", true), column("user_id", "下单用户")];
const paymentsColumns = [column("id", "支付ID", true), column("user_id", "支付用户")];
function columnSetFor(table: string) {
if (table === "orders") return ordersColumns;
if (table === "payments") return paymentsColumns;
return usersColumns;
}
describe("queryStore grouped-result metadata request counts", () => {
beforeEach(async () => {
vi.clearAllMocks();
const { clearTableMetadataCache } = await import("@/lib/metadata/tableMetadataCache");
clearTableMetadataCache();
setActivePinia(createPinia());
getConnectionConfig.mockReturnValue({ id: "mysql-1", name: "MySQL", db_type: "mysql", database: "app", query_timeout_secs: 30 });
getColumns.mockImplementation(async (_connectionId: string, _database: string, _schema: string, table: string) => columnSetFor(table));
listIndexes.mockResolvedValue([]);
listObjects.mockResolvedValue([]);
lookupLocalCompletionTables.mockReturnValue([]);
buildSortedQuerySql.mockResolvedValue({ ok: true, sql: `${"SELECT *"} ORDER BY 1` });
buildDataGridCountSql.mockResolvedValue("SELECT COUNT(*) FROM `users`");
executeQuery.mockResolvedValue({
columns: ["row_count"],
rows: [[0]],
affected_rows: 0,
execution_time_ms: 1,
});
analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "aggregation" });
});
afterEach(() => {
expect(listObjects).not.toHaveBeenCalled();
});
function groupedResult(columns: string[]) {
return [{ columns, rows: columns.map(() => [0]), affected_rows: 0, execution_time_ms: 1 }];
}
// Robust under the full-suite worker load (maxWorkers=4): never rely on the
// default 1s vi.waitFor window for an async enrichment pipeline.
const waitFor = (fn: () => void | Promise<void>) => vi.waitFor(fn, { timeout: 8000, interval: 25 });
it("R1 — cold single-source grouped query: 1 getColumns, 0 listIndexes", async () => {
executeMulti.mockResolvedValue(groupedResult(["department", "total"]));
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT department, COUNT(*) AS total FROM users GROUP BY department");
const tab = store.tabs.find((item) => item.id === tabId)!;
await waitFor(() => expect(tab.resultColumnComments).toBeDefined());
expect(tab.queryEditabilityReason).toBe("aggregation");
expect(getColumns).toHaveBeenCalledTimes(1);
expect(listIndexes).toHaveBeenCalledTimes(0);
}, 20000);
it("R2 — warm repeat of the same grouped query: 0 additional metadata calls", async () => {
executeMulti.mockResolvedValue(groupedResult(["department", "total"]));
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT department, COUNT(*) AS total FROM users GROUP BY department");
let tab = store.tabs.find((item) => item.id === tabId)!;
await waitFor(() => expect(tab.resultColumnComments).toBeDefined());
expect(getColumns).toHaveBeenCalledTimes(1);
const tabId2 = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId2, "SELECT department, COUNT(*) AS total FROM users GROUP BY department");
tab = store.tabs.find((item) => item.id === tabId2)!;
await waitFor(() => expect(tab.resultColumnComments).toBeDefined());
// The second execution reuses the warm columns cache: no new metadata calls.
expect(getColumns).toHaveBeenCalledTimes(1);
expect(listIndexes).toHaveBeenCalledTimes(0);
});
it("R3 — cold 3-source grouped query: 3 getColumns, 0 listIndexes", async () => {
executeMulti.mockResolvedValue(groupedResult(["department", "c1", "c2"]));
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT u.department, COUNT(o.id), COUNT(p.id) FROM users u JOIN orders o ON o.user_id = u.id JOIN payments p ON p.user_id = u.id GROUP BY u.department");
const tab = store.tabs.find((item) => item.id === tabId)!;
await waitFor(() => expect(tab.resultColumnComments).toBeDefined());
expect(tab.queryEditabilityReason).toBe("aggregation");
expect(getColumns).toHaveBeenCalledTimes(3);
expect(listIndexes).toHaveBeenCalledTimes(0);
}, 20000);
it("R5 — concurrent same-table grouped enrichments dedupe to 1 getColumns", async () => {
executeMulti.mockResolvedValue(groupedResult(["department", "total"]));
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const firstTab = store.createTab("mysql-1", "app", "Query");
const secondTab = store.createTab("mysql-1", "app", "Query");
await Promise.all([store.executeTabSql(firstTab, "SELECT department, COUNT(*) AS total FROM users GROUP BY department"), store.executeTabSql(secondTab, "SELECT department, COUNT(*) AS total FROM users GROUP BY department")]);
const first = store.tabs.find((item) => item.id === firstTab)!;
const second = store.tabs.find((item) => item.id === secondTab)!;
await waitFor(() => expect(first.resultColumnComments).toBeDefined());
await waitFor(() => expect(second.resultColumnComments).toBeDefined());
// Both enrichments resolve users.department; the shared columns
// cache/in-flight coordinator collapses them to a single getColumns.
expect(getColumns).toHaveBeenCalledTimes(1);
expect(listIndexes).toHaveBeenCalledTimes(0);
});
it("R4 — multi-source loads run under bounded concurrency (3rd waits for a slot)", async () => {
const releases: Record<string, (value: ReturnType<typeof columnSetFor> | PromiseLike<ReturnType<typeof columnSetFor>>) => void> = {};
const started: string[] = [];
getColumns.mockImplementation((_connectionId: string, _database: string, _schema: string, table: string) => {
started.push(table);
return new Promise((resolve) => {
releases[table] = resolve;
});
});
executeMulti.mockResolvedValue(groupedResult(["department", "c1", "c2"]));
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
const exec = store.executeTabSql(tabId, "SELECT u.department, COUNT(o.id), COUNT(p.id) FROM users u JOIN orders o ON o.user_id = u.id JOIN payments p ON p.user_id = u.id GROUP BY u.department");
// The limiter (maxActive=2) admits exactly two column loads; the third
// source stays queued until a slot frees. Waiting on the condition (not a
// fixed sleep) keeps this deterministic.
await vi.waitFor(() => expect(started).toHaveLength(2), { timeout: 8000, interval: 25 });
// The third source has NOT started yet: concurrency is bounded.
expect(started).toHaveLength(2);
// Free one slot: the third source then begins.
releases[started[0]!]!(columnSetFor(started[0]!));
await vi.waitFor(() => expect(started).toHaveLength(3), { timeout: 8000, interval: 25 });
// Release everything so the store execution can drain.
for (const table of started) {
releases[table]?.(columnSetFor(table));
}
await exec;
expect(listIndexes).toHaveBeenCalledTimes(0);
});
it("R10 — metadata failure shows the result, keeps aggregation read-only, and never fetches indexes", async () => {
getColumns.mockRejectedValue(new Error("metadata unavailable"));
executeMulti.mockResolvedValue([
{
columns: ["department", "total"],
rows: [["sales", 12]],
affected_rows: 0,
execution_time_ms: 1,
},
]);
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT department, COUNT(*) AS total FROM users GROUP BY department");
const tab = store.tabs.find((item) => item.id === tabId)!;
await waitFor(() => expect(tab.queryEditabilityReason).toBe("aggregation"));
// Best-effort: no comments claimed, query result preserved, editability
// unchanged, and no index fallback was triggered by the display failure.
expect(tab.resultColumnComments).toBeUndefined();
expect(tab.tableMeta).toBeUndefined();
expect(tab.result?.rows.length).toBe(1);
expect(listIndexes).toHaveBeenCalledTimes(0);
expect(getColumns).toHaveBeenCalledTimes(1);
}, 20000);
});
@@ -0,0 +1,302 @@
import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const executeMulti = vi.fn();
const executeQuery = vi.fn();
const analyzeEditableQueryEditability = vi.fn();
const getColumns = vi.fn();
const listIndexes = vi.fn();
const listObjects = vi.fn();
const getConnectionConfig = vi.fn();
const lookupLocalCompletionTables = vi.fn();
const buildSortedQuerySql = vi.fn();
const buildDataGridCountSql = vi.fn();
const prepareQueryPaginationExecutionPlan = vi.fn(async (options) => ({
sqlToExecute: options.sql,
pageSql: undefined,
pageLimit: undefined,
pageOffset: undefined,
countSql: undefined,
useAgentResultSession: false,
}));
const editorSettings = {
pageSize: 100,
autoCalculateTotalRows: false,
};
vi.mock("@/lib/backend/api", () => ({
analyzeEditableQueryEditability,
buildDataGridCountSql,
buildSortedQuerySql,
closeClientConnectionSession: vi.fn().mockResolvedValue(undefined),
closeQuerySession: vi.fn().mockResolvedValue(undefined),
executeMulti,
executeQuery,
getColumns,
listIndexes,
listObjects,
prepareQueryPaginationExecutionPlan,
saveOpenTabsState: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: vi.fn().mockResolvedValue(undefined),
getConfig: getConnectionConfig,
lookupLocalCompletionTables,
recordConnectionLostError: vi.fn(),
}),
}));
vi.mock("@/stores/settingsStore", () => ({
useSettingsStore: () => ({
editorSettings,
}),
}));
function column(name: string, comment: string | null, isPrimaryKey = false) {
return { name, data_type: "varchar", is_nullable: true, column_default: null, is_primary_key: isPrimaryKey, extra: null, comment };
}
const usersColumns = [column("id", "用户ID", true), column("department", "所属部门"), column("status", "用户状态")];
const ordersColumns = [column("id", "订单ID", true), column("user_id", "下单用户"), column("amount", "订单金额"), column("created_at", "创建时间")];
describe("queryStore grouped-result column comments", () => {
beforeEach(async () => {
vi.clearAllMocks();
const { clearTableMetadataCache } = await import("@/lib/metadata/tableMetadataCache");
clearTableMetadataCache();
setActivePinia(createPinia());
getConnectionConfig.mockReturnValue({ id: "mysql-1", name: "MySQL", db_type: "mysql", database: "app", query_timeout_secs: 30 });
getColumns.mockImplementation(async (_connectionId: string, _database: string, _schema: string, table: string) => (table === "orders" ? ordersColumns : usersColumns));
listIndexes.mockResolvedValue([]);
listObjects.mockResolvedValue([]);
lookupLocalCompletionTables.mockReturnValue([]);
buildSortedQuerySql.mockResolvedValue({ ok: true, sql: `${"SELECT *"} ORDER BY 1` });
buildDataGridCountSql.mockResolvedValue("SELECT COUNT(*) FROM `users`");
executeQuery.mockResolvedValue({
columns: ["row_count"],
rows: [[0]],
affected_rows: 0,
execution_time_ms: 1,
});
});
afterEach(() => {
expect(listObjects).not.toHaveBeenCalled();
});
it("shows physical column comments for grouped results while staying read-only (T1)", async () => {
analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "aggregation" });
executeMulti.mockResolvedValue([
{
columns: ["department", "total"],
rows: [["sales", 12]],
affected_rows: 0,
execution_time_ms: 1,
},
]);
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT department, COUNT(*) AS total FROM users GROUP BY department");
const tab = store.tabs.find((item) => item.id === tabId)!;
await vi.waitFor(() => expect(tab.resultColumnComments).toBeDefined());
// Grouped results stay read-only: no editable analysis, no tableMeta.
expect(tab.queryEditabilityReason).toBe("aggregation");
expect(tab.queryAnalysis).toBeUndefined();
expect(tab.querySourceColumns).toBeUndefined();
expect(tab.tableMeta).toBeUndefined();
// Only the directly projected physical column carries its comment; the
// aggregate expression resolves to nothing and must not guess.
expect(tab.resultColumnComments).toEqual(["所属部门", undefined]);
expect(tab.queryDisplaySourceColumns).toEqual([{ sourceKey: "users:0", sourceColumn: "department" }, undefined]);
});
it("resolves aliased grouped columns back to their physical column (T2)", async () => {
analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "aggregation" });
executeMulti.mockResolvedValue([
{
columns: ["dept", "total"],
rows: [["sales", 12]],
affected_rows: 0,
execution_time_ms: 1,
},
]);
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT department AS dept, COUNT(*) AS total FROM users GROUP BY department");
const tab = store.tabs.find((item) => item.id === tabId)!;
await vi.waitFor(() => expect(tab.resultColumnComments).toBeDefined());
expect(tab.queryEditabilityReason).toBe("aggregation");
expect(tab.resultColumnComments).toEqual(["所属部门", undefined]);
expect(tab.queryDisplaySourceColumns).toEqual([{ sourceKey: "users:0", sourceColumn: "department" }, undefined]);
});
it("keeps comments for HAVING queries (T3)", async () => {
analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "aggregation" });
executeMulti.mockResolvedValue([
{
columns: ["department", "total"],
rows: [["sales", 12]],
affected_rows: 0,
execution_time_ms: 1,
},
]);
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT department, COUNT(*) AS total FROM users GROUP BY department HAVING COUNT(*) > 1");
const tab = store.tabs.find((item) => item.id === tabId)!;
await vi.waitFor(() => expect(tab.resultColumnComments).toBeDefined());
expect(tab.queryEditabilityReason).toBe("aggregation");
expect(tab.resultColumnComments).toEqual(["所属部门", undefined]);
});
it("resolves qualified grouped columns in a JOIN without leaking other sources (T4)", async () => {
analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "aggregation" });
executeMulti.mockResolvedValue([
{
columns: ["department", "order_count"],
rows: [["sales", 3]],
affected_rows: 0,
execution_time_ms: 1,
},
]);
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT u.department, COUNT(o.id) AS order_count FROM users u JOIN orders o ON o.user_id = u.id GROUP BY u.department");
const tab = store.tabs.find((item) => item.id === tabId)!;
await vi.waitFor(() => expect(tab.resultColumnComments).toBeDefined());
expect(tab.queryEditabilityReason).toBe("aggregation");
expect(tab.resultColumnComments).toEqual(["所属部门", undefined]);
expect(tab.queryDisplaySourceColumns).toEqual([{ sourceKey: "u:0", sourceColumn: "department" }, undefined]);
});
it("maps multiple grouped physical columns (T5)", async () => {
analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "aggregation" });
executeMulti.mockResolvedValue([
{
columns: ["department", "status", "count"],
rows: [["sales", "active", 12]],
affected_rows: 0,
execution_time_ms: 1,
},
]);
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT department, status, COUNT(*) AS count FROM users GROUP BY department, status");
const tab = store.tabs.find((item) => item.id === tabId)!;
await vi.waitFor(() => expect(tab.resultColumnComments).toBeDefined());
expect(tab.resultColumnComments).toEqual(["所属部门", "用户状态", undefined]);
});
it("does not claim a comment for computed/aggregate expressions (T6/T7)", async () => {
analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "aggregation" });
executeMulti.mockResolvedValue([
{
columns: ["day", "total_amount"],
rows: [["2026-01-01", 100]],
affected_rows: 0,
execution_time_ms: 1,
},
]);
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT DATE(created_at) AS day, SUM(amount) AS total_amount FROM orders GROUP BY user_id");
const tab = store.tabs.find((item) => item.id === tabId)!;
await vi.waitFor(() => expect(tab.resultColumnComments).toBeDefined());
// `day` is DATE(created_at) and `total_amount` is SUM(amount): neither may
// inherit the operand column's comment.
expect(tab.resultColumnComments).toEqual([undefined, undefined]);
expect(tab.queryDisplaySourceColumns).toEqual([undefined, undefined]);
});
it("keeps ordinary editable queries free of the new display fields (T10)", async () => {
analyzeEditableQueryEditability.mockResolvedValue({
editable: true,
analysis: {
schema: undefined,
tableName: "users",
tableAlias: undefined,
selectStar: false,
columns: [
{ sourceName: "id", sourceKey: "users:0", resultName: "id", expression: "id" },
{ sourceName: "department", sourceKey: "users:0", resultName: "department", expression: "department" },
],
},
});
executeMulti.mockResolvedValue([
{
columns: ["id", "department"],
rows: [[1, "sales"]],
affected_rows: 0,
execution_time_ms: 1,
},
]);
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT id, department FROM users");
const tab = store.tabs.find((item) => item.id === tabId)!;
await vi.waitFor(() => expect(tab.tableMeta?.tableName).toBe("users"));
expect(tab.resultColumnComments).toBeUndefined();
expect(tab.queryDisplaySourceColumns).toBeUndefined();
expect(tab.querySourceColumns).toEqual(["id", "department"]);
});
it("falls back gracefully when metadata loading fails (best-effort)", async () => {
analyzeEditableQueryEditability.mockResolvedValue({ editable: false, reason: "aggregation" });
getColumns.mockRejectedValue(new Error("metadata unavailable"));
executeMulti.mockResolvedValue([
{
columns: ["department", "total"],
rows: [["sales", 12]],
affected_rows: 0,
execution_time_ms: 1,
},
]);
const { useQueryStore } = await import("@/stores/queryStore");
const store = useQueryStore();
const tabId = store.createTab("mysql-1", "app", "Query");
await store.executeTabSql(tabId, "SELECT department, COUNT(*) AS total FROM users GROUP BY department");
// The result stays queryEditabilityReason=aggregation; enrichment failure
// must never fail the query nor claim comments.
const tab = store.tabs.find((item) => item.id === tabId)!;
await vi.waitFor(() => expect(tab.queryEditabilityReason).toBe("aggregation"));
expect(tab.resultColumnComments).toBeUndefined();
expect(tab.queryDisplaySourceColumns).toBeUndefined();
expect(tab.tableMeta).toBeUndefined();
expect(tab.result?.rows.length).toBe(1);
});
});
+83 -2
View File
@@ -7,7 +7,7 @@ import { orderPinnedFirst } from "@/lib/app/pinnedItems";
import { canCancelQueryExecution } from "@/lib/sql/queryExecutionState";
import { buildExplainSql, parseExplainResult, parseDamengExplainText, parseOracleExplainText, sqlServerExplainResult, type BuildExplainSqlResult } from "@/lib/diagram/explainPlan";
import { mysqlExplainCompatibilityHint } from "@/lib/diagram/mysqlExplainCompatibility";
import { allEditableColumnsWriteable, allPrimaryKeysPresent, analyzeEditableQueryEditability, resolveMetadataColumnName, resolveSourceColumnsByOrdinal, sourceColumnsForResult, type EditableQueryInfo, type EditableQuerySource } from "@/lib/sql/sqlAnalysis";
import { allEditableColumnsWriteable, allPrimaryKeysPresent, analyzeEditableQueryEditability, analyzeSelectStructureForDisplay, resolveMetadataColumnName, resolveSourceColumnsByOrdinal, sourceColumnsForResult, type EditableQueryInfo, type EditableQuerySource } from "@/lib/sql/sqlAnalysis";
import { buildQueryWithHiddenPrimaryKeys, hiddenResultColumnIndexes, type HiddenPrimaryKeyProjection } from "@/lib/sql/editableQueryHiddenKeys";
import { ACTIVE_TAB_STORAGE_KEY, OPEN_TABS_STORAGE_KEY, restoreOpenTabsPayload, restoreOpenTabsState, serializeOpenTabs } from "@/lib/app/openTabsPersistence";
import {
@@ -41,7 +41,8 @@ import { TABLE_DATA_EXPORT_PAGE_SIZE } from "@/lib/table/tableDataExport";
import { tableMetaForDataTab } from "@/lib/table/tableDataTabMeta";
import { dataTabExecutionDatabase } from "@/lib/table/dataTabExecutionDatabase";
import { tableOpenPageLimit } from "@/lib/table/tableOpenPageLimit";
import { getCachedTableMetadata, loadTableIndexes, loadTableMetadata, type TableMetadataRequest } from "@/lib/metadata/tableMetadataCache";
import { getCachedTableMetadata, loadTableColumns, loadTableIndexes, loadTableMetadata, type TableMetadataRequest } from "@/lib/metadata/tableMetadataCache";
import { MetadataTaskLimiter } from "@/lib/metadata/metadataTaskLimiter";
import { buildTableSelectSql, quoteTableDataIdentifier } from "@/lib/table/tableSelectSql";
import { connectionObjectTreeNodeSchema, connectionQueryExecutionSchema, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection, gaussdbCountQueryDopHint, metadataSchemaForConnection } from "@/lib/database/jdbcDialect";
import { frontendQueryTimeoutDelayMs, frontendQueryTimeoutSecsForSql, queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";
@@ -82,6 +83,15 @@ import type { MultiDbExecutionTarget, MultiDbResultRunExecution } from "@/types/
const ORACLE_LIKE_METADATA_TYPES = new Set<string>(["oracle", "dameng", "oceanbase-oracle"]);
const ORACLE_DEFERRED_LOB_TYPES = new Set<string>(["CLOB", "NCLOB", "BLOB", "BFILE"]);
// Bounded concurrency for grouped-query display column loads, scoped per
// connection so different connections never block each other. Matches the
// project's existing completion-metadata concurrency policy (<2>).
const GROUPED_DISPLAY_METADATA_CONCURRENCY = 2;
const GROUPED_DISPLAY_LIMITER_SCOPE_PREFIX = "query-column-comments:";
const groupedDisplayMetadataLimiter = new MetadataTaskLimiter(GROUPED_DISPLAY_METADATA_CONCURRENCY, (event) => {
console.debug("[DBX][metadata-load:grouped-display-limiter]", event);
});
const UPPERCASE_FOLDED_METADATA_TYPES = new Set<string>([...ORACLE_LIKE_METADATA_TYPES, "saphana"]);
const HIDDEN_QUERY_KEY_DATABASE_TYPES = new Set<DatabaseType>(["mysql", "postgres", "sqlserver", "oracle"]);
const QUERY_RESULT_EXPORT_UNSUPPORTED_ERROR = "Streaming export is unsupported for this query. Simplify it or use a supported driver.";
@@ -3566,6 +3576,25 @@ export const useQueryStore = defineStore("query", () => {
};
}
function loadedEditableSourceFromColumns(target: EditableSourceMetadataTarget, loadedColumns: Awaited<ReturnType<typeof loadTableColumns>>): LoadedEditableSource {
return {
source: target.source,
analysis: target.analysis,
tableMeta: {
catalog: target.request.catalog,
database: target.request.database,
schema: target.writeSchema,
tableName: target.request.tableName,
tableType: loadedColumns.tableType,
columns: loadedColumns.columns,
// Display-only enrichment never resolves row identity (indexes), so
// there are no primary keys to carry; resolveMultiSourceColumnInfo only
// consumes `source` + `columns`.
primaryKeys: [],
},
};
}
async function loadEditableQuerySource(tab: QueryTab, analysis: EditableQueryInfo, source: EditableQuerySource, conn: ConnectionConfig | undefined, dbType: string, executionDatabase: string, traceId?: string, elapsed?: () => string): Promise<LoadedEditableSource> {
const target = resolveEditableSourceMetadataTarget(tab, analysis, source, conn, dbType, executionDatabase);
queryExecutionLog("info", "metadata:table:start", {
@@ -3696,6 +3725,51 @@ export const useQueryStore = defineStore("query", () => {
}
}
/**
* Display-only result-column enrichment for aggregated (GROUP BY / HAVING)
* results: parse the SELECT structure, load every source table's metadata,
* resolve each result column back to exactly one base-table column by
* projection ordinal, and return the resolved comments + display mapping.
* Best-effort by design: returns `undefined` when the statement cannot be
* structurally parsed or source metadata cannot be loaded — the query result
* itself and editability are never affected.
*/
async function resolveAggregationDisplayColumnInfo(tab: QueryTab, sql: string, executionDatabase: string, traceId: string | undefined): Promise<{ comments: Array<string | undefined>; mapping: Array<QueryResultSourceColumnRef | undefined> } | undefined> {
if (tab.mode !== "query" || !tab.connectionId || !tab.result || !tab.result.columns.length) return undefined;
const conn = useConnectionStore().getConfig(tab.connectionId);
const dbType = conn?.db_type || "";
const analysis = analyzeSelectStructureForDisplay(sql);
if (!analysis) return undefined;
const sources = editableQuerySources(analysis);
if (!sources.length) return undefined;
try {
// Resolve every source's metadata target up front, then load *columns
// only* (display payload — no index discovery) under a connection-scoped
// bounded-concurrency limiter. The shared table-column cache/in-flight
// coordinator deduplicates identical tables across concurrent callers,
// so this path issues no indexes requests and never loads full editable
// metadata.
const loadedSources: LoadedEditableSource[] = [];
const targets = sources.map((source) => resolveEditableSourceMetadataTarget(tab, analysis, source, conn, dbType, executionDatabase));
const limiterScope = `${GROUPED_DISPLAY_LIMITER_SCOPE_PREFIX}${tab.connectionId}`;
await Promise.all(
targets.map((target) =>
groupedDisplayMetadataLimiter.run(limiterScope, "query-column-comments", async () => {
const loadedColumns = await loadTableColumns({
...target.request,
traceLogger: (event) => queryExecutionLog("debug", "metadata:table-columns-trace", { sourceTraceId: traceId, ...event }),
});
loadedSources.push(loadedEditableSourceFromColumns(target, loadedColumns));
}),
),
);
return resolveMultiSourceColumnInfo(dbType, analysis, tab.result.columns, loadedSources);
} catch (err) {
console.error("[DBX] ERROR fetching columns for grouped query metadata:", err);
return undefined;
}
}
async function buildQueryMetadataPatch(tab: QueryTab, sql: string, executionDatabase: string, traceId?: string, elapsed?: () => string, hiddenPrimaryKeys: HiddenPrimaryKeyProjection[] = []): Promise<QueryMetadataPatch | undefined> {
if (tab.mode !== "query") return;
if (!tab.result || !tab.result.columns.length) {
@@ -3716,11 +3790,18 @@ export const useQueryStore = defineStore("query", () => {
elapsed: elapsed?.(),
});
if (!editability.editable) {
// Grouped (aggregation) results stay read-only, but their directly
// projected base-table columns can still be resolved for display metadata
// (column comments). This enrichment is display-only — it never enables
// row mutation for aggregated results (fixes #6463). Every other
// non-editable reason keeps the previous behavior.
const displayInfo = editability.reason === "aggregation" ? await resolveAggregationDisplayColumnInfo(tab, sql, executionDatabase, traceId) : undefined;
return {
queryAnalysis: undefined,
querySourceColumns: undefined,
queryEditabilityReason: editability.reason,
tableMeta: undefined,
...(displayInfo ? { resultColumnComments: displayInfo.comments, queryDisplaySourceColumns: displayInfo.mapping } : {}),
};
}
const analysis = editability.analysis;