feat(query): add configurable result tab naming

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-09-30 21:16:39 +08:00
1 parent 87546f8e4f
commit 3ddb926c5a
26 files changed
+332 -39

No files matched your search

+94 -2
View File
@@ -204,7 +204,7 @@ describe("query result labels", () => {
expect(withoutDatabase?.title).toBe("cosimulation2.0.data_monitor");
});
it("keeps a custom result name even when the database is hidden", () => {
it("uses a custom result name in comment mode even when the database is hidden", () => {
const [item] = tabularResultItems(
[
{
@@ -213,17 +213,81 @@ describe("query result labels", () => {
affected_rows: 0,
execution_time_ms: 1,
sourceLabel: "My weekly report",
sourceLabelKind: "comment",
sourceQualifier: "app",
sourceName: "users",
sourceStatement: "SELECT * FROM users",
},
],
{ includeSourceDatabase: false },
{ includeSourceDatabase: false, namingMode: "comment" },
);
expect(item?.label).toBe("My weekly report");
expect(item?.title).toBe("My weekly report");
});
it("uses the source table in source mode when a SQL comment also names the result", () => {
const [item] = tabularResultItems(
[
{
columns: ["id"],
rows: [[1]],
affected_rows: 0,
execution_time_ms: 1,
sourceLabel: "My weekly report",
sourceLabelKind: "comment",
sourceQualifier: "app",
sourceName: "users",
},
],
{ namingMode: "source", preferComments: false },
);
expect(item?.label).toBe("app.users");
});
it.each([
["source", undefined, true, "Weekly report"],
["source", true, false, "Weekly report"],
["source", false, true, "app.users"],
["source", false, false, "users"],
["comment", false, true, "Weekly report"],
["ordinal", true, true, undefined],
] as const)("respects %s naming with preferComments=%s and includeSourceDatabase=%s", (namingMode, preferComments, includeSourceDatabase, expected) => {
const result: QueryResult = { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 1, sourceLabel: "Weekly report", sourceLabelKind: "comment", sourceQualifier: "app", sourceName: "users" };
expect(tabularResultItems([result], { namingMode, preferComments, includeSourceDatabase })[0]?.label).toBe(expected);
});
it("uses the explicit label kind for comment mode and keeps legacy source labels out", () => {
const comment = tabularResultItems(
[
{
columns: ["id"],
rows: [[1]],
affected_rows: 0,
execution_time_ms: 1,
sourceLabel: "Weekly report",
sourceLabelKind: "comment",
},
],
{ namingMode: "comment" },
)[0];
const legacySource = tabularResultItems(
[
{
columns: ["id"],
rows: [[1]],
affected_rows: 0,
execution_time_ms: 1,
sourceLabel: "app.users",
},
],
{ namingMode: "comment" },
)[0];
expect(comment?.label).toBe("Weekly report");
expect(legacySource?.label).toBeUndefined();
});
});
describe("query result grid identity", () => {
@@ -283,6 +347,34 @@ describe("result run labels", () => {
expect(items[0]?.sourceLabel).toBe("cosimulation2.0.users");
});
it("uses explicit comment labels while ignoring legacy source labels in comment mode", () => {
const commentRun = run("run-1", 1, { ...sourceResult("Weekly report", "app", "users"), sourceLabelKind: "comment", sourceName: undefined });
const legacySourceRun = run("run-2", 2, { ...sourceResult("app.orders", "app", "orders"), sourceLabelKind: undefined });
expect(resultRunItems(queryTab({ resultRuns: [commentRun, legacySourceRun] }) as QueryTab, { namingMode: "comment" }).map((item) => item.sourceLabel)).toEqual(["Weekly report", undefined]);
expect(resultRunItems(queryTab({ resultRuns: [commentRun] }) as QueryTab, { namingMode: "ordinal" })[0]?.sourceLabel).toBeUndefined();
});
it("uses the source table for a commented run in source mode", () => {
const commentRun = run("run-1", 1, { ...sourceResult("Weekly report", "app", "users"), sourceLabelKind: "comment" });
expect(resultRunItems(queryTab({ resultRuns: [commentRun] }) as QueryTab, { namingMode: "source", preferComments: false }).map((item) => item.sourceLabel)).toEqual(["app.users"]);
});
it.each([false, true])("switches comment preference after the run payload is evicted (%s)", (preferComments) => {
const commentRun = run("run-1", 1, undefined, { sourceLabel: "Weekly report", sourceLabelKind: "comment", sourceName: "users" });
const tab = queryTab({ resultRuns: [commentRun] }) as QueryTab;
expect(resultRunItems(tab, { database: "app", databaseType: "mysql", preferComments })[0]?.sourceLabel).toBe(preferComments ? "Weekly report" : "app.users");
expect(resultRunItems(tab, { database: "app", databaseType: "mysql", preferComments, includeSourceDatabase: false })[0]?.sourceLabel).toBe(preferComments ? "Weekly report" : "users");
expect(resultRunItems(tab, { namingMode: "comment", preferComments })[0]?.sourceLabel).toBe("Weekly report");
expect(resultRunItems(tab, { namingMode: "ordinal", preferComments })[0]?.sourceLabel).toBeUndefined();
});
it("prefers comments by default for stored runs without a result payload", () => {
const commentRun = run("run-1", 1, undefined, { sourceLabel: "Weekly report", sourceLabelKind: "comment" });
expect(resultRunItems(queryTab({ resultRuns: [commentRun] }) as QueryTab)[0]?.sourceLabel).toBe("Weekly report");
});
});
describe("tab group presentation", () => {
@@ -1,4 +1,4 @@
import type { QueryTab, TabOutputView } from "@/types/database";
import type { QueryResultSourceLabelKind, QueryTab, TabOutputView } from "@/types/database";
import { sanitizeTabUiState } from "@/lib/tabs/tabUiState";
export const OPEN_TABS_STORAGE_KEY = "dbx-open-tabs";
@@ -19,6 +19,7 @@ export interface SavedQueryResultRun {
/** 结果来源(库名.表名 / 表名),用于结果标签命名;与结果 payload 分离,回收 payload 后仍可显示 */
sourceLabel?: string;
sourceName?: string;
sourceLabelKind?: QueryResultSourceLabelKind;
}
export interface SavedOpenTab {
@@ -228,6 +229,7 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
createdAt: run.createdAt,
...(run.sourceLabel ? { sourceLabel: run.sourceLabel } : {}),
...(run.sourceName ? { sourceName: run.sourceName } : {}),
...(run.sourceLabelKind ? { sourceLabelKind: run.sourceLabelKind } : {}),
...(run.customTitle ? { customTitle: true } : {}),
...(run.pinned ? { pinned: true } : {}),
activeResultIndex: run.activeResultIndex,
@@ -14,6 +14,15 @@ function fileWith(editor: Record<string, unknown>, overrides: Record<string, unk
}
describe("settingsTransfer", () => {
it("round-trips an opt-out of comment-first result names and rejects non-booleans", () => {
const text = serializeSettingsTransfer({ ...DEFAULT_EDITOR_SETTINGS, resultTabPreferComments: false });
const result = parseSettingsTransferFile(text);
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.editorSettings.resultTabPreferComments).toBe(false);
expect(transferCategoryForKey("resultTabPreferComments")).toBe("data");
expect(parseSettingsTransferFile(fileWith({ resultTabPreferComments: "false" })).ok).toBe(false);
});
it("builds a dated transfer filename", () => {
expect(buildSettingsTransferFilename(new Date(2026, 8, 6))).toBe("dbx-settings-2026-09-06.json");
});
@@ -54,6 +54,8 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = [
"showColumnTypesInHeader",
"showColumnHeaderTooltips",
"showResultSourceDatabase",
"resultTabNamingMode",
"resultTabPreferComments",
"dataGridShowTransposeFieldMetadata",
"colorizeDataGridCellTypes",
"dataGridTypeColorSchemes",
@@ -229,6 +229,8 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
{ id: "data-grid-header-types", category: "data", titleKey: "settings.showColumnTypesInHeader", descriptionKey: "settings.showColumnTypesInHeaderDescription", targetId: "data" },
{ id: "data-grid-header-tooltips", category: "data", titleKey: "settings.showColumnHeaderTooltips", descriptionKey: "settings.showColumnHeaderTooltipsDescription", targetId: "data" },
{ id: "result-source-database-name", category: "data", titleKey: "settings.showResultSourceDatabase", descriptionKey: "settings.showResultSourceDatabaseDescription", targetId: "data" },
{ id: "result-tab-naming-mode", category: "data", titleKey: "settings.resultTabNamingMode", descriptionKey: "settings.resultTabNamingModeDescription", targetId: "data" },
{ id: "result-tab-prefer-comments", category: "data", titleKey: "settings.resultTabPreferComments", descriptionKey: "settings.resultTabPreferCommentsDescription", targetId: "data" },
{ id: "data-grid-transpose-field-metadata", category: "data", titleKey: "settings.dataGridShowTransposeFieldMetadata", descriptionKey: "settings.dataGridShowTransposeFieldMetadataDescription", targetId: "data" },
{ id: "data-grid-cell-type-colors", category: "data", titleKey: "settings.colorizeDataGridCellTypes", descriptionKey: "settings.colorizeDataGridCellTypesDescription", targetId: "data" },
{ id: "data-grid-type-colors", category: "data", titleKey: "settings.dataGridTypeColorScheme", descriptionKey: "settings.dataGridTypeColorSchemeDescription", targetId: "data-grid-type-colors" },
@@ -147,6 +147,8 @@ const SETTINGS_TRANSFER_CATEGORY_KEYS: Record<SettingsTransferCategoryId, readon
"showColumnTypesInHeader",
"showColumnHeaderTooltips",
"showResultSourceDatabase",
"resultTabNamingMode",
"resultTabPreferComments",
"dataGridShowTransposeFieldMetadata",
"colorizeDataGridCellTypes",
"dataGridTypeColorSchemes",
@@ -278,6 +280,7 @@ const PASS_THROUGH_BOOLEAN_KEYS = [
"showColumnTypesInHeader",
"showColumnHeaderTooltips",
"showResultSourceDatabase",
"resultTabPreferComments",
"colorizeDataGridCellTypes",
"showIndexIndicatorsInHeader",
"compactColumnHeaderActions",
@@ -302,6 +305,7 @@ const PASS_THROUGH_FIELD_VALIDATORS: Partial<Record<EditorSettingsDraftKey, (val
// The editor font slider and the Ctrl+wheel zoom both clamp to this range.
fontSize: (value) => typeof value === "number" && Number.isFinite(value) && value >= EDITOR_MIN_FONT_SIZE && value <= EDITOR_MAX_FONT_SIZE,
appLayout: (value) => value === "separated" || value === "classic",
resultTabNamingMode: (value) => value === "source" || value === "ordinal" || value === "comment",
activeCustomThemeId: (value) => typeof value === "string" && value.trim().length > 0,
// normalizeToolbarItems keeps unknown/typed values for every known key, so
// each one must already be the boolean the UI writes, and no extra key may
+29 -17
View File
@@ -13,6 +13,7 @@ import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";
import type { SqlErrorPosition } from "@/lib/backend/errorUtils";
import { queryResultSourceNameParts } from "@/lib/sql/queryResultSource";
import type { BatchSqlExecution, ConnectionConfig, DatabaseType, QueryResult, QueryResultRun, QueryTab } from "@/types/database";
import type { ResultTabNamingMode } from "@/stores/settingsStore";
type Translate = (key: string, params?: Record<string, unknown>) => string;
export type OutputView = "result" | "summary" | "explain" | "chart";
@@ -336,8 +337,23 @@ export function tabTooltipLines(tab: QueryTab, t: Translate): { label: string; v
return lines;
}
export function queryResultStatementLabel(result: Pick<QueryResult, "sourceLabel">): string | undefined {
return result.sourceLabel;
type ResultSourceFields = Pick<QueryResult, "sourceLabel" | "sourceLabelKind" | "sourceQualifier" | "sourceName">;
type ResultNamingOptions = { includeSourceDatabase?: boolean; namingMode?: ResultTabNamingMode; preferComments?: boolean };
function resultSourceLabel(result: ResultSourceFields, includeSourceDatabase: boolean): string | undefined {
if (result.sourceName) {
if (!includeSourceDatabase) return result.sourceName;
return result.sourceQualifier ? `${result.sourceQualifier}.${result.sourceName}` : result.sourceName;
}
return result.sourceLabelKind === "comment" ? undefined : result.sourceLabel;
}
function resultNamingLabel(result: ResultSourceFields, options: ResultNamingOptions): string | undefined {
if (options.namingMode === "ordinal") return undefined;
const commentLabel = result.sourceLabelKind === "comment" ? result.sourceLabel : undefined;
if (options.namingMode === "comment") return commentLabel;
if (options.preferComments !== false && commentLabel) return commentLabel;
return resultSourceLabel(result, options.includeSourceDatabase !== false);
}
export function middleEllipsis(value: string, maxLength = 24): string {
@@ -475,19 +491,13 @@ export function queryResultExecutionSql(tab: Pick<QueryTab, "result" | "resultBa
return tab.resultSortedSql || resultSqlForGrid(tab);
}
export function tabularResultItems(results: QueryResult[] | undefined, options: { includeSourceDatabase?: boolean } = {}): { result: QueryResult; index: number; n: number; label?: string; displayLabel?: string; labelTruncated: boolean; title?: string }[] {
export function tabularResultItems(results: QueryResult[] | undefined, options: ResultNamingOptions = {}): { result: QueryResult; index: number; n: number; label?: string; displayLabel?: string; labelTruncated: boolean; title?: string }[] {
if (!results) return [];
return results
.map((result, index) => ({ result, index }))
.filter((item) => item.result.columns.length > 0 && item.result.server_message !== true)
.map((item, ordinal) => {
const label = queryResultStatementLabel(item.result);
const { sourceName, sourceQualifier } = item.result;
// 只有在标签确实由“库名.对象名”拼成时才启用短名称,避免覆盖 `-- name: xxx` 之类的自定义名称
const qualifiedLabel = sourceName ? (sourceQualifier ? `${sourceQualifier}.${sourceName}` : sourceName) : undefined;
// 关闭“结果集名称包含数据库名”时,页签与结果列表只展示对象名;
// 完整名称(含库名)仍保留在 title,供悬浮提示与搜索使用。
const displaySource = options.includeSourceDatabase === false && sourceName && qualifiedLabel === label ? sourceName : label;
const displaySource = resultNamingLabel(item.result, options);
const displayLabel = displaySource ? middleEllipsis(displaySource) : undefined;
return {
...item,
@@ -508,31 +518,33 @@ export function activeResultRun(tab: Pick<QueryTab, "resultRuns" | "activeResult
* 执行批次默认显示名:取该批次主结果的来源(库名.表名 / 表名)。
* 连表查询同样取 FROM 之后的第一个物理表,与结果集页签的来源解析保持一致。
*/
function resultRunSourceLabel(run: QueryResultRun, includeSourceDatabase: boolean, fallback: { database?: string; databaseType?: DatabaseType }): string | undefined {
function resultRunSourceLabel(run: QueryResultRun, options: ResultNamingOptions, fallback: { database?: string; databaseType?: DatabaseType }): string | undefined {
const includeSourceDatabase = options.includeSourceDatabase !== false;
const namingMode = options.namingMode ?? "source";
if (namingMode === "ordinal") return undefined;
// 优先用批次自带的来源:非活动批次的结果 payload 会被回收,payload 里的来源会丢失
const own = includeSourceDatabase ? run.sourceLabel || run.sourceName : run.sourceName || run.sourceLabel;
const own = run.sourceLabelKind === "comment" ? (namingMode === "comment" || options.preferComments !== false ? run.sourceLabel : undefined) : namingMode === "comment" ? undefined : includeSourceDatabase ? run.sourceLabel || run.sourceName : run.sourceName || run.sourceLabel;
if (own) return own;
const candidates = run.result ? [run.result, ...(run.results ?? [])] : (run.results ?? []);
for (const result of candidates) {
if (!result) continue;
// 批次级来源缺失时回退到结果本身;关闭“结果集名称包含数据库名”时优先用对象名
const label = includeSourceDatabase ? result.sourceLabel || result.sourceName : result.sourceName || result.sourceLabel;
const label = resultNamingLabel(result, options);
if (label) return label;
}
// 历史批次(功能上线前创建的)没有来源信息:用批次 SQL 重新解析,连表查询同样取第一个物理表
if (run.sql && fallback.databaseType) {
if (namingMode === "source" && run.sql && fallback.databaseType) {
const parts = queryResultSourceNameParts(run.sql, { database: fallback.database, databaseType: fallback.databaseType });
if (parts) return includeSourceDatabase ? (parts.qualifier ? `${parts.qualifier}.${parts.name}` : parts.name) : parts.name;
}
return undefined;
}
export function resultRunItems(tab: Pick<QueryTab, "resultRuns" | "activeResultRunId">, options: { includeSourceDatabase?: boolean; database?: string; databaseType?: DatabaseType } = {}): { id: string; title: string; sequence: number; active: boolean; pinned: boolean; sourceLabel?: string }[] {
const includeSourceDatabase = options.includeSourceDatabase !== false;
export function resultRunItems(tab: Pick<QueryTab, "resultRuns" | "activeResultRunId">, options: ResultNamingOptions & { database?: string; databaseType?: DatabaseType } = {}): { id: string; title: string; sequence: number; active: boolean; pinned: boolean; sourceLabel?: string }[] {
const fallback = { database: options.database, databaseType: options.databaseType };
const seenBySource = new Map<string, number>();
return (tab.resultRuns ?? []).map((run) => {
const source = resultRunSourceLabel(run, includeSourceDatabase, fallback);
const source = resultRunSourceLabel(run, options, fallback);
let sourceLabel = source;
if (source) {
// 同一张表被查询多次时用序号后缀区分页签(users、users (2)…)
@@ -81,6 +81,7 @@ interface ColumnarQueryResult {
truncated?: boolean;
has_more?: boolean;
sourceLabel?: string;
sourceLabelKind?: QueryResult["sourceLabelKind"];
sourceQualifier?: string;
sourceName?: string;
sourceStatement?: string;
@@ -377,6 +378,7 @@ function stripSessionIds(result: QueryResult | undefined): QueryResult | undefin
session_id: undefined,
has_more: result.has_more,
sourceLabel: result.sourceLabel,
sourceLabelKind: result.sourceLabelKind,
sourceQualifier: result.sourceQualifier,
sourceName: result.sourceName,
sourceStatement: result.sourceStatement,
@@ -440,6 +442,7 @@ function toColumnarResult(result: QueryResult | undefined): ColumnarQueryResult
truncated: result.truncated,
has_more: result.has_more,
sourceLabel: result.sourceLabel,
sourceLabelKind: result.sourceLabelKind,
sourceQualifier: result.sourceQualifier,
sourceName: result.sourceName,
sourceStatement: result.sourceStatement,
@@ -477,6 +480,7 @@ function fromColumnarResult(result: ColumnarQueryResult | undefined): QueryResul
session_id: undefined,
has_more: result.has_more,
sourceLabel: result.sourceLabel,
sourceLabelKind: result.sourceLabelKind,
sourceQualifier: result.sourceQualifier,
sourceName: result.sourceName,
sourceStatement: result.sourceStatement,