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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(query): add configurable result tab naming
二丫讲梵3ddb926c5a77
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vueindex 3fe44d99d3..2d0f8ff117 100644--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue@@ -92,6 +92,7 @@ import {type DataGridFilterEditorView,type DataGridToolbarLayout,type MultiStatementDefaultView,+ type ResultTabNamingMode,type OpenTabsRestoreMode,type AppCloseUnsavedTabsMode,type SidebarObjectInfoMode,@@ -732,6 +733,8 @@ const editShowColumnCommentsInHeader = ref(settingsStore.editorSettings.showColuconst editShowColumnTypesInHeader = ref(settingsStore.editorSettings.showColumnTypesInHeader);const editShowColumnHeaderTooltips = ref(settingsStore.editorSettings.showColumnHeaderTooltips);const editShowResultSourceDatabase = ref(settingsStore.editorSettings.showResultSourceDatabase);+const editResultTabNamingMode = ref<ResultTabNamingMode>(settingsStore.editorSettings.resultTabNamingMode);+const editResultTabPreferComments = ref(settingsStore.editorSettings.resultTabPreferComments);const editDataGridShowTransposeFieldMetadata = ref(settingsStore.editorSettings.dataGridShowTransposeFieldMetadata);const editColorizeDataGridCellTypes = ref(settingsStore.editorSettings.colorizeDataGridCellTypes);const editShowIndexIndicatorsInHeader = ref(settingsStore.editorSettings.showIndexIndicatorsInHeader);@@ -1082,6 +1085,8 @@ function currentEditorSettingsDraft(): EditorSettingsDraft {showColumnTypesInHeader: editShowColumnTypesInHeader.value,showColumnHeaderTooltips: editShowColumnHeaderTooltips.value,showResultSourceDatabase: editShowResultSourceDatabase.value,+ resultTabNamingMode: editResultTabNamingMode.value,+ resultTabPreferComments: editResultTabPreferComments.value,dataGridShowTransposeFieldMetadata: editDataGridShowTransposeFieldMetadata.value,colorizeDataGridCellTypes: editColorizeDataGridCellTypes.value,dataGridTypeColorSchemes: editDataGridTypeColorSchemes.value,@@ -1748,6 +1753,8 @@ function syncEditorSettingsDraftFromStore() {editShowColumnTypesInHeader.value = settingsStore.editorSettings.showColumnTypesInHeader;editShowColumnHeaderTooltips.value = settingsStore.editorSettings.showColumnHeaderTooltips;editShowResultSourceDatabase.value = settingsStore.editorSettings.showResultSourceDatabase;+ editResultTabNamingMode.value = settingsStore.editorSettings.resultTabNamingMode;+ editResultTabPreferComments.value = settingsStore.editorSettings.resultTabPreferComments;editDataGridShowTransposeFieldMetadata.value = settingsStore.editorSettings.dataGridShowTransposeFieldMetadata;editColorizeDataGridCellTypes.value = settingsStore.editorSettings.colorizeDataGridCellTypes;editDataGridTypeColorSchemes.value = cloneDataGridTypeColorSchemes(settingsStore.editorSettings.dataGridTypeColorSchemes);@@ -1889,6 +1896,8 @@ const editorSettingsDraftRefs: EditorSettingsDraftRefMap = {showColumnTypesInHeader: editShowColumnTypesInHeader,showColumnHeaderTooltips: editShowColumnHeaderTooltips,showResultSourceDatabase: editShowResultSourceDatabase,+ resultTabNamingMode: editResultTabNamingMode,+ resultTabPreferComments: editResultTabPreferComments,dataGridShowTransposeFieldMetadata: editDataGridShowTransposeFieldMetadata,colorizeDataGridCellTypes: editColorizeDataGridCellTypes,dataGridTypeColorSchemes: editDataGridTypeColorSchemes,@@ -2442,6 +2451,8 @@ function resetDefaultsForTab(tab: SettingsCategory) {editShowColumnTypesInHeader.value = DEFAULT_EDITOR_SETTINGS.showColumnTypesInHeader;editShowColumnHeaderTooltips.value = DEFAULT_EDITOR_SETTINGS.showColumnHeaderTooltips;editShowResultSourceDatabase.value = DEFAULT_EDITOR_SETTINGS.showResultSourceDatabase;+ editResultTabNamingMode.value = DEFAULT_EDITOR_SETTINGS.resultTabNamingMode;+ editResultTabPreferComments.value = DEFAULT_EDITOR_SETTINGS.resultTabPreferComments;editDataGridShowTransposeFieldMetadata.value = DEFAULT_EDITOR_SETTINGS.dataGridShowTransposeFieldMetadata;editColorizeDataGridCellTypes.value = DEFAULT_EDITOR_SETTINGS.colorizeDataGridCellTypes;// Back to the built-in palette, but keep the user's saved schemes available.@@ -8467,16 +8478,43 @@ onUnmounted(() => {</div><Switch id="show-column-header-tooltips" v-model="editShowColumnHeaderTooltips" /></div>- <div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">- <div class="space-y-1">- <Label for="show-result-source-database">- {{ t("settings.showResultSourceDatabase") }}- </Label>- <p class="text-xs text-muted-foreground">- {{ t("settings.showResultSourceDatabaseDescription") }}- </p>+ <div class="settings-item space-y-3 rounded-md border bg-muted/20 p-3">+ <div class="flex items-center justify-between gap-4">+ <div class="min-w-0 space-y-1">+ <Label>{{ t("settings.resultTabNamingMode") }}</Label>+ <p class="text-xs text-muted-foreground">+ {{ t("settings.resultTabNamingModeDescription") }}+ </p>+ </div>+ <Select v-model="editResultTabNamingMode">+ <SelectTrigger class="h-8 w-48 shrink-0">+ <SelectValue :placeholder="t('settings.resultTabNamingMode')" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="source">{{ t("settings.resultTabNamingModeSource") }}</SelectItem>+ <SelectItem value="ordinal">{{ t("settings.resultTabNamingModeOrdinal") }}</SelectItem>+ <SelectItem value="comment">{{ t("settings.resultTabNamingModeComment") }}</SelectItem>+ </SelectContent>+ </Select>+ </div>+ <div v-if="editResultTabNamingMode === 'source'" class="flex items-center justify-between gap-4 border-t border-border/60 pt-3">+ <div class="space-y-1 pl-1">+ <Label for="result-tab-prefer-comments">{{ t("settings.resultTabPreferComments") }}</Label>+ <p class="text-xs text-muted-foreground">{{ t("settings.resultTabPreferCommentsDescription") }}</p>+ </div>+ <Switch id="result-tab-prefer-comments" v-model="editResultTabPreferComments" />+ </div>+ <div v-if="editResultTabNamingMode === 'source'" class="flex items-center justify-between gap-4 border-t border-border/60 pt-3">+ <div class="space-y-1 pl-1">+ <Label for="show-result-source-database">+ {{ t("settings.showResultSourceDatabase") }}+ </Label>+ <p class="text-xs text-muted-foreground">+ {{ t("settings.showResultSourceDatabaseDescription") }}+ </p>+ </div>+ <Switch id="show-result-source-database" v-model="editShowResultSourceDatabase" /></div>- <Switch id="show-result-source-database" v-model="editShowResultSourceDatabase" /></div><div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2"><div class="space-y-1">diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vueindex 3c7e7f3657..46b6e0362b 100644--- a/apps/desktop/src/components/layout/ContentArea.vue+++ b/apps/desktop/src/components/layout/ContentArea.vue@@ -501,8 +501,12 @@ const activeQueryError = computed(() => {const hasQueryOutput = computed(() => tabHasQueryOutput(props.activeTab));// 结果集页签/列表的名称是否带库名,由编辑器设置控制(默认带库名)const includeResultSourceDatabase = computed(() => settingsStore.editorSettings.showResultSourceDatabase);-const visibleResultItems = computed(() => tabularResultItems(props.activeTab.results ?? (props.activeTab.result ? [props.activeTab.result] : undefined), { includeSourceDatabase: includeResultSourceDatabase.value }));-const tabularResults = computed(() => tabularResultItems(props.activeTab.results, { includeSourceDatabase: includeResultSourceDatabase.value }));+const resultTabNamingMode = computed(() => settingsStore.editorSettings.resultTabNamingMode);+const preferResultTabComments = computed(() => settingsStore.editorSettings.resultTabPreferComments);+const visibleResultItems = computed(() =>+ tabularResultItems(props.activeTab.results ?? (props.activeTab.result ? [props.activeTab.result] : undefined), { includeSourceDatabase: includeResultSourceDatabase.value, namingMode: resultTabNamingMode.value, preferComments: preferResultTabComments.value }),+);+const tabularResults = computed(() => tabularResultItems(props.activeTab.results, { includeSourceDatabase: includeResultSourceDatabase.value, namingMode: resultTabNamingMode.value, preferComments: preferResultTabComments.value }));const allResultExportSheets = computed(() =>tabularResults.value.map((item) => ({sheetName: item.label || t("tabs.resultN", { n: item.n }),@@ -514,10 +518,13 @@ const allResultExportSheets = computed(() =>const resultRuns = computed(() =>resultRunItems(props.activeTab, {includeSourceDatabase: includeResultSourceDatabase.value,+ namingMode: resultTabNamingMode.value,+ preferComments: preferResultTabComments.value,database: props.activeTab.database,databaseType: activeEffectiveDatabaseType.value,}),);+const resultRunFallbackLabel = (sequence: number) => t(resultTabNamingMode.value === "ordinal" ? "tabs.resultN" : "tabs.runN", { n: sequence });const activeResultGridCacheKey = computed(() => resultGridCacheKey(props.activeTab));const activeResultGridColumnWidthCacheKey = computed(() => resultGridColumnWidthCacheKey(props.activeTab));const activeResultGridInstanceKey = computed(() => resultGridInstanceKey(props.activeTab));@@ -1824,7 +1831,7 @@ defineExpose({@keydown="onResultRunTabKeydown($event, runIndex)"><Pin v-if="run.pinned" class="h-3 w-3 shrink-0 fill-current text-primary" />- {{ run.title || run.sourceLabel || t("tabs.runN", { n: run.sequence }) }}+ {{ run.title || run.sourceLabel || resultRunFallbackLabel(run.sequence) }}</button><buttontype="button"@@ -1844,7 +1851,7 @@ defineExpose({<DropdownMenu><DropdownMenuTrigger as-child><Button variant="ghost" size="sm" class="h-6 max-w-48 gap-1 px-2 text-xs">- <span class="min-w-0 truncate">{{ activeResultRunItem ? activeResultRunItem.title || activeResultRunItem.sourceLabel || t("tabs.runN", { n: activeResultRunItem.sequence }) : t("tabs.resultRuns") }}</span>+ <span class="min-w-0 truncate">{{ activeResultRunItem ? activeResultRunItem.title || activeResultRunItem.sourceLabel || resultRunFallbackLabel(activeResultRunItem.sequence) : t("tabs.resultRuns") }}</span><ChevronDown class="h-3.5 w-3.5 shrink-0" /></Button></DropdownMenuTrigger>@@ -1854,7 +1861,7 @@ defineExpose({<Check v-if="run.active" class="h-3.5 w-3.5 shrink-0" /><span v-else class="h-3.5 w-3.5 shrink-0" /><Pin v-if="run.pinned" class="h-3 w-3 shrink-0 fill-current text-primary" />- <span class="min-w-0 flex-1 truncate">{{ run.title || run.sourceLabel || t("tabs.runN", { n: run.sequence }) }}</span>+ <span class="min-w-0 flex-1 truncate">{{ run.title || run.sourceLabel || resultRunFallbackLabel(run.sequence) }}</span><buttontype="button"class="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.tsindex 846db47a83..6c8c667885 100644--- a/apps/desktop/src/i18n/locales/az.ts+++ b/apps/desktop/src/i18n/locales/az.ts@@ -7435,6 +7435,13 @@ export default withEnglishFallback({showColumnHeaderTooltipsDescription: "Kursor nəticə cədvəlindəki sütun başlıqlarının üzərinə gətirildikdə ətraflı ipucları göstər. Bu pəncərələri dayandırmaq üçün söndürün.",showResultSourceDatabase: "Nəticə adlarında verilənlər bazası adını göstər",showResultSourceDatabaseDescription: "Söndürüldükdə nəticə sekmələri yalnız cədvəl adını göstərir; tam ad (verilənlər bazası adı ilə) ipucunda görünməyə davam edir.",+ resultTabNamingMode: "Nəticə sekmələrinin adlandırılması",+ resultTabNamingModeDescription: "Nəticə sekmələrində mənbə cədvəlini, nömrəni və ya SQL ifadəsinin üstündəki şərhi göstərməyi seçin.",+ resultTabNamingModeSource: "Verilənlər bazası və cədvəl adı",+ resultTabNamingModeOrdinal: "Nəticə nömrəsi",+ resultTabNamingModeComment: "SQL şərhi",+ resultTabPreferComments: "Mövcud olduqda SQL şərhlərinə üstünlük ver",+ resultTabPreferCommentsDescription: "SQL ifadəsinin üstündəki şərhdən istifadə edin; həmişə mənbə cədvəlinin adını göstərmək üçün söndürün.",dataGridShowTransposeFieldMetadata: "Transpozisiya görünüşündə sahə metaverilənlərini göstər",dataGridShowTransposeFieldMetadataDescription: "Transpozisiya görünüşündə aktiv edilmiş sütun növlərini və şərhləri ayrı sətirlərdə göstər. Bu, sətrin hündürlüyünü artırır.",colorizeDataGridCellTypes: "Verilənlər cədvəlinin dəyərlərini rənglə fərqləndir",diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 4deaa6acdc..aaff615db5 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -8222,6 +8222,13 @@ export default {showColumnHeaderTooltipsDescription: "Show detail tooltips when hovering result grid column headers. Turn off to stop hover popups.",showResultSourceDatabase: "Include database name in result set names",showResultSourceDatabaseDescription: "When off, result set tabs show only the table name; the full name stays visible in the tooltip.",+ resultTabNamingMode: "Result tab naming",+ resultTabNamingModeDescription: "Choose whether result tabs use the source table, a numbered label, or the SQL comment above the statement.",+ resultTabNamingModeSource: "Database and table",+ resultTabNamingModeOrdinal: "Result number",+ resultTabNamingModeComment: "SQL comment",+ resultTabPreferComments: "Prefer SQL comments when available",+ resultTabPreferCommentsDescription: "Use the comment above the SQL statement when available; turn off to always use the source table name.",dataGridShowTransposeFieldMetadata: "Show field metadata in transpose view",dataGridShowTransposeFieldMetadataDescription: "Display enabled column types and comments on separate lines in transpose view. This increases row height.",colorizeDataGridCellTypes: "Color-code data grid values",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 79c738b84b..62305b2c97 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -7476,6 +7476,13 @@ export default withEnglishFallback({showColumnHeaderTooltipsDescription: "Muestra sugerencias con detalles al pasar el cursor sobre los encabezados de columna de la cuadrícula de resultados. Desactívalo para ocultarlas.",showResultSourceDatabase: "Incluir el nombre de la base de datos en los nombres de los resultados",showResultSourceDatabaseDescription: "Si se desactiva, las pestañas de resultados solo muestran el nombre de la tabla; el nombre completo sigue visible en la información emergente.",+ resultTabNamingMode: "Nombre de pestañas de resultados",+ resultTabNamingModeDescription: "Elige si las pestañas muestran la tabla de origen, un número o el comentario sobre la sentencia SQL.",+ resultTabNamingModeSource: "Base de datos y tabla",+ resultTabNamingModeOrdinal: "Número de resultado",+ resultTabNamingModeComment: "Comentario SQL",+ resultTabPreferComments: "Priorizar los comentarios SQL cuando existan",+ resultTabPreferCommentsDescription: "Usar el comentario situado encima de la sentencia SQL; desactivar para usar siempre el nombre de la tabla de origen.",dataGridShowTransposeFieldMetadata: "Mostrar metadatos de campo en la vista transpuesta",dataGridShowTransposeFieldMetadataDescription: "Muestra los tipos de columna y comentarios habilitados en líneas separadas en la vista transpuesta. Esto aumenta la altura de las filas.",colorizeDataGridCellTypes: "Colorear valores por tipo de dato",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex d3ecb0f469..2baae9d857 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -7400,6 +7400,13 @@ export default withEnglishFallback({showColumnHeaderTooltipsDescription: "Mostra tooltip con dettagli al passaggio del mouse sulle intestazioni di colonna della griglia dei risultati. Disattiva per nasconderli.",showResultSourceDatabase: "Includi il nome del database nei nomi dei risultati",showResultSourceDatabaseDescription: "Se disattivato, le schede dei risultati mostrano solo il nome della tabella; il nome completo resta visibile nel tooltip.",+ resultTabNamingMode: "Nome delle schede dei risultati",+ resultTabNamingModeDescription: "Scegli se le schede mostrano la tabella sorgente, un numero o il commento sopra l’istruzione SQL.",+ resultTabNamingModeSource: "Database e tabella",+ resultTabNamingModeOrdinal: "Numero risultato",+ resultTabNamingModeComment: "Commento SQL",+ resultTabPreferComments: "Preferisci i commenti SQL se presenti",+ resultTabPreferCommentsDescription: "Usa il commento sopra l’istruzione SQL; disattiva per usare sempre il nome della tabella di origine.",dataGridShowTransposeFieldMetadata: "Mostra i metadati dei campi nella vista trasposta",dataGridShowTransposeFieldMetadataDescription: "Visualizza i tipi di colonna e i commenti abilitati su righe separate nella vista trasposta. Questo aumenta l'altezza delle righe.",colorizeDataGridCellTypes: "Colora i valori in base al tipo di dato",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 1f6fa5e499..73a3a7f068 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -7427,6 +7427,13 @@ export default withEnglishFallback({showColumnHeaderTooltipsDescription: "結果グリッドの列ヘッダーにホバーしたときに詳細ツールチップを表示します。オフにすると表示されません。",showResultSourceDatabase: "結果セット名にデータベース名を含める",showResultSourceDatabaseDescription: "オフにすると結果セットのタブにはテーブル名のみを表示し、完全な名前(データベース名を含む)はツールチップで確認できます。",+ resultTabNamingMode: "結果タブの名前",+ resultTabNamingModeDescription: "結果タブにテーブル名、番号、または SQL 文の上にあるコメントを表示します。",+ resultTabNamingModeSource: "データベース名とテーブル名",+ resultTabNamingModeOrdinal: "結果番号",+ resultTabNamingModeComment: "SQL コメント",+ resultTabPreferComments: "SQL コメントがある場合は優先する",+ resultTabPreferCommentsDescription: "SQL 文の上のコメントを優先します。オフにすると常に参照元のテーブル名を表示します。",dataGridShowTransposeFieldMetadata: "転置ビューにフィールドメタデータを表示",dataGridShowTransposeFieldMetadataDescription: "有効なデータ型とコメントを転置ビューの別行に表示します。有効にすると行の高さが増えます。",colorizeDataGridCellTypes: "データ型に応じて値を色分け",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 41dda29e00..1564c1eb37 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -7174,6 +7174,13 @@ export default withEnglishFallback({showColumnHeaderTooltipsDescription: "결과 그리드의 컬럼 헤더에 마우스를 올리면 상세 툴팁을 표시합니다. 끄면 표시되지 않습니다.",showResultSourceDatabase: "결과 세트 이름에 데이터베이스 이름 포함",showResultSourceDatabaseDescription: "끄면 결과 세트 탭에 테이블 이름만 표시되며, 전체 이름(데이터베이스 이름 포함)은 툴팁에서 확인할 수 있습니다.",+ resultTabNamingMode: "결과 탭 이름 지정",+ resultTabNamingModeDescription: "결과 탭에 원본 테이블, 번호 또는 SQL 문 위의 주석을 표시할지 선택합니다.",+ resultTabNamingModeSource: "데이터베이스 및 테이블 이름",+ resultTabNamingModeOrdinal: "결과 번호",+ resultTabNamingModeComment: "SQL 주석",+ resultTabPreferComments: "SQL 주석이 있으면 우선 표시",+ resultTabPreferCommentsDescription: "SQL 문 위의 주석을 우선 표시합니다. 끄면 항상 원본 테이블 이름을 표시합니다.",dataGridShowTransposeFieldMetadata: "전치 보기에 필드 메타데이터 표시",dataGridShowTransposeFieldMetadataDescription: "활성화된 데이터 타입과 주석을 전치 보기의 별도 줄에 표시합니다. 활성화하면 행 높이가 증가합니다.",colorizeDataGridCellTypes: "데이터 타입별 값 색상 표시",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex c304bb1e22..c988487e2e 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -7402,6 +7402,13 @@ export default withEnglishFallback({showColumnHeaderTooltipsDescription: "Mostra dicas com detalhes ao passar o mouse sobre os cabeçalhos de coluna da grade de resultados. Desative para ocultá-las.",showResultSourceDatabase: "Incluir o nome do banco de dados nos nomes dos resultados",showResultSourceDatabaseDescription: "Quando desativado, as abas de resultados mostram apenas o nome da tabela; o nome completo (com o banco de dados) continua na dica de ferramenta.",+ resultTabNamingMode: "Nome das abas de resultado",+ resultTabNamingModeDescription: "Escolha se as abas mostram a tabela de origem, um número ou o comentário acima da instrução SQL.",+ resultTabNamingModeSource: "Banco de dados e tabela",+ resultTabNamingModeOrdinal: "Número do resultado",+ resultTabNamingModeComment: "Comentário SQL",+ resultTabPreferComments: "Priorizar comentários SQL quando disponíveis",+ resultTabPreferCommentsDescription: "Usar o comentário acima da instrução SQL; desative para usar sempre o nome da tabela de origem.",dataGridShowTransposeFieldMetadata: "Mostrar metadados de campo na visualização transposta",dataGridShowTransposeFieldMetadataDescription: "Exibir tipos de coluna e comentários habilitados em linhas separadas na visualização transposta. Isso aumenta a altura das linhas.",colorizeDataGridCellTypes: "Colorir valores por tipo de dado",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 217e709aa6..70ac760017 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -9639,6 +9639,13 @@ export default withEnglishFallback({showColumnHeaderTooltipsDescription: "Показывать подробную всплывающую подсказку при наведении курсора на имя поля в заголовке результатов; после отключения всплывающая подсказка при наведении больше не появляется.",showResultSourceDatabase: "Имя набора результатов содержит имя базы данных",showResultSourceDatabaseDescription: "После отключения вкладки наборов результатов будут отображать только имена таблиц; полное имя (включая имя базы данных) по-прежнему можно посмотреть во всплывающей подсказке.",+ resultTabNamingMode: "Имена вкладок результатов",+ resultTabNamingModeDescription: "Выберите, показывать ли исходную таблицу, номер или комментарий над SQL-оператором.",+ resultTabNamingModeSource: "Имя базы данных и таблицы",+ resultTabNamingModeOrdinal: "Номер результата",+ resultTabNamingModeComment: "Комментарий SQL",+ resultTabPreferComments: "Предпочитать комментарии SQL, если они есть",+ resultTabPreferCommentsDescription: "Использовать комментарий над SQL-запросом; отключите, чтобы всегда отображать имя исходной таблицы.",sidebarSearchOpenedDatabasesOnly: "Искать только в открытых базах данных",sidebarSearchOpenedDatabasesOnlyDescription: "Поиск на боковой панели загружает только открытые базы данных в текущем подключении (если ни одна не открыта, поиск выполняется по всем). Если отключить, поиск будет выполняться по всем базам данных этого подключения.",},diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex 677fcff419..075533023d 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -7317,6 +7317,13 @@ export default withEnglishFallback({showColumnHeaderTooltipsDescription: "Sonuç ızgarasında sütun başlıklarının üzerine gelindiğinde ayrıntı ipuçlarını göster. Açılır ipuçlarını durdurmak için kapatın.",showResultSourceDatabase: "Sonuç adlarında veritabanı adını göster",showResultSourceDatabaseDescription: "Kapalıyken sonuç sekmeleri yalnızca tablo adını gösterir; tam ad (veritabanı adı dahil) ipucunda görünmeye devam eder.",+ resultTabNamingMode: "Sonuç sekmesi adlandırması",+ resultTabNamingModeDescription: "Sonuç sekmelerinde kaynak tabloyu, bir numarayı veya SQL ifadesinin üzerindeki yorumu gösterin.",+ resultTabNamingModeSource: "Veritabanı ve tablo adı",+ resultTabNamingModeOrdinal: "Sonuç numarası",+ resultTabNamingModeComment: "SQL yorumu",+ resultTabPreferComments: "Varsa SQL yorumlarına öncelik ver",+ resultTabPreferCommentsDescription: "SQL ifadesinin üstündeki yorumu kullan; her zaman kaynak tablo adını göstermek için kapat.",dataGridShowTransposeFieldMetadata: "Devrik görünümde alan meta verisini göster",dataGridShowTransposeFieldMetadataDescription: "Etkin sütun türlerini ve açıklamalarını devrik görünümde ayrı satırlarda göster. Bu, satır yüksekliğini artırır.",colorizeDataGridCellTypes: "Veri tablosu değerlerini renklendir",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 5c2b26e903..1431aea4e8 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -8188,6 +8188,13 @@ export default withEnglishFallback({showColumnHeaderTooltipsDescription: "在结果表头字段名上悬浮时显示详情提示;关闭后悬浮不再弹出。",showResultSourceDatabase: "结果集名称包含数据库名",showResultSourceDatabaseDescription: "关闭后结果集页签只显示表名,完整名称(含数据库名)仍可在悬浮提示中查看。",+ resultTabNamingMode: "结果页签命名方式",+ resultTabNamingModeDescription: "选择结果页签使用来源表名、序号,还是 SQL 语句上方的注释。",+ resultTabNamingModeSource: "数据库名和表名",+ resultTabNamingModeOrdinal: "结果序号",+ resultTabNamingModeComment: "SQL 注释",+ resultTabPreferComments: "有注释时优先展示注释",+ resultTabPreferCommentsDescription: "开启后优先使用 SQL 语句上方的注释;关闭后按来源表名显示。",dataGridShowTransposeFieldMetadata: "在转置视图中显示字段元数据",dataGridShowTransposeFieldMetadataDescription: "在转置视图中分行显示已启用的数据类型和注释。开启后会增加行高。",colorizeDataGridCellTypes: "按数据类型为表格值着色",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 783266ac98..82b01a57d9 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -6719,6 +6719,13 @@ export default withEnglishFallback({showColumnHeaderTooltipsDescription: "在資料表格欄位名稱上懸浮時顯示詳細提示;關閉後懸浮不再彈出。",showResultSourceDatabase: "結果集名稱包含資料庫名稱",showResultSourceDatabaseDescription: "關閉後結果集頁籤只顯示資料表名稱,完整名稱(含資料庫名稱)仍可在懸浮提示中查看。",+ resultTabNamingMode: "結果頁籤命名方式",+ resultTabNamingModeDescription: "選擇結果頁籤使用來源資料表、序號,或 SQL 陳述式上方的註解。",+ resultTabNamingModeSource: "資料庫名稱和資料表名稱",+ resultTabNamingModeOrdinal: "結果序號",+ resultTabNamingModeComment: "SQL 註解",+ resultTabPreferComments: "有註解時優先顯示註解",+ resultTabPreferCommentsDescription: "開啟後優先使用 SQL 語句上方的註解;關閉後依來源資料表名稱顯示。",dataGridShowTransposeFieldMetadata: "在轉置檢視中顯示欄位中繼資料",dataGridShowTransposeFieldMetadataDescription: "在轉置檢視中分行顯示已啟用的資料類型和註解。開啟後會增加列高。",colorizeDataGridCellTypes: "依資料類型為表格值著色",diff --git a/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.ts b/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.tsindex 7802161482..14fd0d4e71 100644--- a/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.ts+++ b/apps/desktop/src/lib/__tests__/tabs/tabPresentation.spec.ts@@ -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", () => {diff --git a/apps/desktop/src/lib/app/openTabsPersistence.ts b/apps/desktop/src/lib/app/openTabsPersistence.tsindex 3db42de124..dc4913a794 100644--- a/apps/desktop/src/lib/app/openTabsPersistence.ts+++ b/apps/desktop/src/lib/app/openTabsPersistence.ts@@ -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,diff --git a/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.tsindex c91f9a9b29..c069ca567c 100644--- a/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts+++ b/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts@@ -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");});diff --git a/apps/desktop/src/lib/settings/editorSettingsDraft.ts b/apps/desktop/src/lib/settings/editorSettingsDraft.tsindex caaee5daf5..7191e2a3ae 100644--- a/apps/desktop/src/lib/settings/editorSettingsDraft.ts+++ b/apps/desktop/src/lib/settings/editorSettingsDraft.ts@@ -54,6 +54,8 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = ["showColumnTypesInHeader","showColumnHeaderTooltips","showResultSourceDatabase",+ "resultTabNamingMode",+ "resultTabPreferComments","dataGridShowTransposeFieldMetadata","colorizeDataGridCellTypes","dataGridTypeColorSchemes",diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.tsindex b8c66b933e..5aba629bf7 100644--- a/apps/desktop/src/lib/settings/settingsSearch.ts+++ b/apps/desktop/src/lib/settings/settingsSearch.ts@@ -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" },diff --git a/apps/desktop/src/lib/settings/settingsTransfer.ts b/apps/desktop/src/lib/settings/settingsTransfer.tsindex 986994c1de..9f3047d568 100644--- a/apps/desktop/src/lib/settings/settingsTransfer.ts+++ b/apps/desktop/src/lib/settings/settingsTransfer.ts@@ -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 maydiff --git a/apps/desktop/src/lib/tabs/tabPresentation.ts b/apps/desktop/src/lib/tabs/tabPresentation.tsindex 83cd904e16..835fdd3c5f 100644--- a/apps/desktop/src/lib/tabs/tabPresentation.ts+++ b/apps/desktop/src/lib/tabs/tabPresentation.ts@@ -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; vreturn 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" | "resultBareturn 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)…)diff --git a/apps/desktop/src/lib/tabs/tabResultCache.ts b/apps/desktop/src/lib/tabs/tabResultCache.tsindex 90b7b0bd67..cb3112dfd4 100644--- a/apps/desktop/src/lib/tabs/tabResultCache.ts+++ b/apps/desktop/src/lib/tabs/tabResultCache.ts@@ -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 | undefinsession_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): ColumnarQueryResulttruncated: 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): QueryResulsession_id: undefined,has_more: result.has_more,sourceLabel: result.sourceLabel,+ sourceLabelKind: result.sourceLabelKind,sourceQualifier: result.sourceQualifier,sourceName: result.sourceName,sourceStatement: result.sourceStatement,diff --git a/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.tsindex c8f2129feb..916d751b3b 100644--- a/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.ts+++ b/apps/desktop/src/stores/__tests__/queryStore.multiStatementError.spec.ts@@ -978,6 +978,10 @@ describe("queryStore multi-statement errors", () => {await store.executeTabSql(tabId, sql);expect(store.tabs.find((item) => item.id === tabId)?.results?.map((result) => result.sourceLabel)).toEqual(["Orders", "Users"]);+ expect(store.tabs.find((item) => item.id === tabId)?.results).toMatchObject([+ { sourceLabelKind: "comment", sourceQualifier: "app", sourceName: "orders" },+ { sourceLabelKind: "comment", sourceQualifier: "app", sourceName: "users" },+ ]);});it("does not repeatedly scan the full document when naming a selected large batch", async () => {diff --git a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts b/apps/desktop/src/stores/__tests__/settingsStore.spec.tsindex 8c5fddb4ad..cb4c7f015d 100644--- a/apps/desktop/src/stores/__tests__/settingsStore.spec.ts+++ b/apps/desktop/src/stores/__tests__/settingsStore.spec.ts@@ -20,6 +20,13 @@ import type { AiConfigItem } from "@/types/ai";import { DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION } from "@/lib/dataGrid/dataGridCopyExtractor";describe("normalizeEditorSettings", () => {+ it("preserves comment-first naming for existing settings and permits opting out", () => {+ expect(DEFAULT_EDITOR_SETTINGS.resultTabPreferComments).toBe(true);+ expect(normalizeEditorSettings({}).resultTabPreferComments).toBe(true);+ expect(normalizeEditorSettings({ resultTabPreferComments: false }).resultTabPreferComments).toBe(false);+ expect(normalizeEditorSettings({ resultTabPreferComments: "false" } as any).resultTabPreferComments).toBe(true);+ });+it("defaults and sanitizes AI conversation typography independently", () => {expect(normalizeEditorSettings({})).toMatchObject({ aiFontFamily: "", aiFontSize: 12 });expect(diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 88e732b2a3..3dc1e51e8d 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -405,6 +405,7 @@ function releaseResultObjectPayload(result: QueryResult): void {result.messages = undefined;result.error = undefined;result.sourceLabel = undefined;+ result.sourceLabelKind = undefined;result.sourceQualifier = undefined;result.sourceName = undefined;result.sourceStatement = undefined;@@ -464,9 +465,9 @@ function annotateQueryResultSources(results: QueryResult[], sql: string, databasconst customName = queryResultNameFromPreamble(preamble, { databaseType });if (customName) {result.sourceLabel = customName;- // 自定义名称(-- name: xxx)优先:清除结构化来源,避免“结果集名称包含数据库名”设置把它替换成表名- result.sourceQualifier = undefined;- result.sourceName = undefined;+ result.sourceLabelKind = "comment";+ // 保留结构化来源,方便“来源表名”模式在注释存在时仍显示表名。+ // “注释”模式通过 sourceLabelKind 选择这个自定义名称。}const successfulUseDatabase = result.execution_error !== true ? useDatabaseFromStatement(statement.sql, databaseType) : undefined;if (successfulUseDatabase) {@@ -688,7 +689,10 @@ function annotateQueryResultSource(result: QueryResult, sourceStatement: string,result.sourceQualifier = parts.qualifier;result.sourceName = parts.name;const label = parts.qualifier ? `${parts.qualifier}.${parts.name}` : parts.name;- if (label) result.sourceLabel = label;+ if (label) {+ result.sourceLabel = label;+ result.sourceLabelKind = "source";+ }}return result;}@@ -2184,6 +2188,7 @@ export const useQueryStore = defineStore("query", () => {createdAt,sourceLabel: primaryResult?.sourceLabel,sourceName: primaryResult?.sourceName,+ sourceLabelKind: primaryResult?.sourceLabelKind,result: tab.result,results: tab.results,activeResultIndex: tab.activeResultIndex,@@ -2621,6 +2626,7 @@ export const useQueryStore = defineStore("query", () => {customTitle: run.customTitle,sourceLabel: run.sourceLabel,sourceName: run.sourceName,+ sourceLabelKind: run.sourceLabelKind,activeResultIndex: run.activeResultIndex,resultCacheKey: run.resultCacheKey,resultEvicted: run.resultEvicted,@@ -5936,8 +5942,12 @@ export const useQueryStore = defineStore("query", () => {});if (nextLabel) {tab.result.sourceLabel = nextLabel;+ tab.result.sourceLabelKind = "source";const matching = tab.results?.find((result) => result === tab.result);- if (matching) matching.sourceLabel = nextLabel;+ if (matching) {+ matching.sourceLabel = nextLabel;+ matching.sourceLabelKind = "source";+ }}}}@@ -7119,6 +7129,7 @@ export const useQueryStore = defineStore("query", () => {annotated.sourceQualifier = currentDatabase || undefined;annotated.sourceName = mongoCommand.collection;annotated.sourceLabel = currentDatabase ? `${currentDatabase}.${mongoCommand.collection}` : mongoCommand.collection;+ annotated.sourceLabelKind = "source";}return commandTiming.finish(annotated);};diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.tsindex df331130aa..3a903e8adf 100644--- a/apps/desktop/src/stores/settingsStore.ts+++ b/apps/desktop/src/stores/settingsStore.ts@@ -727,6 +727,8 @@ export type DataGridFilterEditorView = "quick" | "conditions" | "text";export type DataGridToolbarLayout = "single" | "split";const RESULT_RUN_DISPLAY_MODES = ["tabs", "list"] as const;export type ResultRunDisplayMode = (typeof RESULT_RUN_DISPLAY_MODES)[number];+export const RESULT_TAB_NAMING_MODES = ["source", "ordinal", "comment"] as const;+export type ResultTabNamingMode = (typeof RESULT_TAB_NAMING_MODES)[number];const MULTI_STATEMENT_DEFAULT_VIEWS = ["result", "summary"] as const;export type MultiStatementDefaultView = (typeof MULTI_STATEMENT_DEFAULT_VIEWS)[number];export const TABLE_FONT_SIZE_MIN = 8;@@ -909,6 +911,10 @@ export interface EditorSettings {showColumnHeaderTooltips: boolean;/** 结果集页签/结果列表的名称是否带上库名(关闭后只显示表名,完整名称仍在悬浮提示中)。 */showResultSourceDatabase: boolean;+ /** Naming strategy for query result execution and result-set tabs. */+ resultTabNamingMode: ResultTabNamingMode;+ /** Prefer SQL preamble comments in source naming mode, preserving the original naming behavior. */+ resultTabPreferComments: boolean;dataGridShowTransposeFieldMetadata: boolean;colorizeDataGridCellTypes: boolean;dataGridTypeColorSchemes: DataGridTypeColorScheme[];@@ -1199,6 +1205,8 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {showColumnTypesInHeader: true,showColumnHeaderTooltips: true,showResultSourceDatabase: true,+ resultTabNamingMode: "source",+ resultTabPreferComments: true,dataGridShowTransposeFieldMetadata: false,colorizeDataGridCellTypes: false,dataGridTypeColorSchemes: [],@@ -1416,6 +1424,10 @@ function normalizeResultRunDisplayMode(value: unknown): ResultRunDisplayMode {return RESULT_RUN_DISPLAY_MODES.includes(value as ResultRunDisplayMode) ? (value as ResultRunDisplayMode) : DEFAULT_EDITOR_SETTINGS.resultRunDisplayMode;}+function normalizeResultTabNamingMode(value: unknown): ResultTabNamingMode {+ return RESULT_TAB_NAMING_MODES.includes(value as ResultTabNamingMode) ? (value as ResultTabNamingMode) : DEFAULT_EDITOR_SETTINGS.resultTabNamingMode;+}+function normalizeMultiStatementDefaultView(value: unknown): MultiStatementDefaultView {return MULTI_STATEMENT_DEFAULT_VIEWS.includes(value as MultiStatementDefaultView) ? (value as MultiStatementDefaultView) : DEFAULT_EDITOR_SETTINGS.multiStatementDefaultView;}@@ -1773,6 +1785,8 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, existshowColumnTypesInHeader: settings.showColumnTypesInHeader ?? DEFAULT_EDITOR_SETTINGS.showColumnTypesInHeader,showColumnHeaderTooltips: settings.showColumnHeaderTooltips ?? DEFAULT_EDITOR_SETTINGS.showColumnHeaderTooltips,showResultSourceDatabase: settings.showResultSourceDatabase ?? DEFAULT_EDITOR_SETTINGS.showResultSourceDatabase,+ resultTabNamingMode: normalizeResultTabNamingMode(settings.resultTabNamingMode),+ resultTabPreferComments: settings.resultTabPreferComments !== false,dataGridShowTransposeFieldMetadata: settings.dataGridShowTransposeFieldMetadata === true,colorizeDataGridCellTypes: settings.colorizeDataGridCellTypes ?? DEFAULT_EDITOR_SETTINGS.colorizeDataGridCellTypes,dataGridTypeColorSchemes,@@ -2614,6 +2628,8 @@ export const useSettingsStore = defineStore("settings", () => {if (partial.showColumnTypesInHeader !== undefined) editorSettings.value.showColumnTypesInHeader = partial.showColumnTypesInHeader;if (partial.showColumnHeaderTooltips !== undefined) editorSettings.value.showColumnHeaderTooltips = partial.showColumnHeaderTooltips;if (partial.showResultSourceDatabase !== undefined) editorSettings.value.showResultSourceDatabase = partial.showResultSourceDatabase;+ if (partial.resultTabNamingMode !== undefined) editorSettings.value.resultTabNamingMode = normalizeResultTabNamingMode(partial.resultTabNamingMode);+ if (partial.resultTabPreferComments !== undefined) editorSettings.value.resultTabPreferComments = partial.resultTabPreferComments !== false;if (partial.dataGridShowTransposeFieldMetadata !== undefined) editorSettings.value.dataGridShowTransposeFieldMetadata = partial.dataGridShowTransposeFieldMetadata === true;if (partial.colorizeDataGridCellTypes !== undefined) editorSettings.value.colorizeDataGridCellTypes = partial.colorizeDataGridCellTypes === true;if (partial.dataGridTypeColorSchemes !== undefined) {diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 04a15789a3..c65b6e4bfd 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -1258,6 +1258,8 @@ export interface QueryMessage {hint?: string;}+export type QueryResultSourceLabelKind = "source" | "comment";+export interface QueryResult {columns: string[];/** One SRID per geometry/geography column (first non-null observed). */@@ -1351,6 +1353,8 @@ export interface QueryResult {/** Preformatted Redis command output retained alongside the default grid rows. */redis_console_output?: string;sourceLabel?: string;+ /** Identifies whether sourceLabel came from a parsed object source or a SQL preamble comment. */+ sourceLabelKind?: QueryResultSourceLabelKind;/** 结果集来源的库名 / schema(与 sourceLabel 同时写入),供结果集页签按设置决定是否展示。 */sourceQualifier?: string;/** 结果集来源的对象名(通常为表名),关闭“结果集名称包含数据库名”时用于展示短名称。 */@@ -1433,6 +1437,8 @@ export interface QueryResultRun {*/sourceLabel?: string;sourceName?: string;+ /** Identifies whether sourceLabel came from a parsed object source or a SQL preamble comment. */+ sourceLabelKind?: QueryResultSourceLabelKind;/*** Logical-result identity for the tab-switch view snapshot cache. Distinct* from `resultGridRevision` (the grid remount key): this one changes on every