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

@@ -92,6 +92,7 @@ import {
type DataGridFilterEditorView, type DataGridFilterEditorView,
type DataGridToolbarLayout, type DataGridToolbarLayout,
type MultiStatementDefaultView, type MultiStatementDefaultView,
type ResultTabNamingMode,
type OpenTabsRestoreMode, type OpenTabsRestoreMode,
type AppCloseUnsavedTabsMode, type AppCloseUnsavedTabsMode,
type SidebarObjectInfoMode, type SidebarObjectInfoMode,
@@ -732,6 +733,8 @@ const editShowColumnCommentsInHeader = ref(settingsStore.editorSettings.showColu
const editShowColumnTypesInHeader = ref(settingsStore.editorSettings.showColumnTypesInHeader); const editShowColumnTypesInHeader = ref(settingsStore.editorSettings.showColumnTypesInHeader);
const editShowColumnHeaderTooltips = ref(settingsStore.editorSettings.showColumnHeaderTooltips); const editShowColumnHeaderTooltips = ref(settingsStore.editorSettings.showColumnHeaderTooltips);
const editShowResultSourceDatabase = ref(settingsStore.editorSettings.showResultSourceDatabase); 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 editDataGridShowTransposeFieldMetadata = ref(settingsStore.editorSettings.dataGridShowTransposeFieldMetadata);
const editColorizeDataGridCellTypes = ref(settingsStore.editorSettings.colorizeDataGridCellTypes); const editColorizeDataGridCellTypes = ref(settingsStore.editorSettings.colorizeDataGridCellTypes);
const editShowIndexIndicatorsInHeader = ref(settingsStore.editorSettings.showIndexIndicatorsInHeader); const editShowIndexIndicatorsInHeader = ref(settingsStore.editorSettings.showIndexIndicatorsInHeader);
@@ -1082,6 +1085,8 @@ function currentEditorSettingsDraft(): EditorSettingsDraft {
showColumnTypesInHeader: editShowColumnTypesInHeader.value, showColumnTypesInHeader: editShowColumnTypesInHeader.value,
showColumnHeaderTooltips: editShowColumnHeaderTooltips.value, showColumnHeaderTooltips: editShowColumnHeaderTooltips.value,
showResultSourceDatabase: editShowResultSourceDatabase.value, showResultSourceDatabase: editShowResultSourceDatabase.value,
resultTabNamingMode: editResultTabNamingMode.value,
resultTabPreferComments: editResultTabPreferComments.value,
dataGridShowTransposeFieldMetadata: editDataGridShowTransposeFieldMetadata.value, dataGridShowTransposeFieldMetadata: editDataGridShowTransposeFieldMetadata.value,
colorizeDataGridCellTypes: editColorizeDataGridCellTypes.value, colorizeDataGridCellTypes: editColorizeDataGridCellTypes.value,
dataGridTypeColorSchemes: editDataGridTypeColorSchemes.value, dataGridTypeColorSchemes: editDataGridTypeColorSchemes.value,
@@ -1748,6 +1753,8 @@ function syncEditorSettingsDraftFromStore() {
editShowColumnTypesInHeader.value = settingsStore.editorSettings.showColumnTypesInHeader; editShowColumnTypesInHeader.value = settingsStore.editorSettings.showColumnTypesInHeader;
editShowColumnHeaderTooltips.value = settingsStore.editorSettings.showColumnHeaderTooltips; editShowColumnHeaderTooltips.value = settingsStore.editorSettings.showColumnHeaderTooltips;
editShowResultSourceDatabase.value = settingsStore.editorSettings.showResultSourceDatabase; editShowResultSourceDatabase.value = settingsStore.editorSettings.showResultSourceDatabase;
editResultTabNamingMode.value = settingsStore.editorSettings.resultTabNamingMode;
editResultTabPreferComments.value = settingsStore.editorSettings.resultTabPreferComments;
editDataGridShowTransposeFieldMetadata.value = settingsStore.editorSettings.dataGridShowTransposeFieldMetadata; editDataGridShowTransposeFieldMetadata.value = settingsStore.editorSettings.dataGridShowTransposeFieldMetadata;
editColorizeDataGridCellTypes.value = settingsStore.editorSettings.colorizeDataGridCellTypes; editColorizeDataGridCellTypes.value = settingsStore.editorSettings.colorizeDataGridCellTypes;
editDataGridTypeColorSchemes.value = cloneDataGridTypeColorSchemes(settingsStore.editorSettings.dataGridTypeColorSchemes); editDataGridTypeColorSchemes.value = cloneDataGridTypeColorSchemes(settingsStore.editorSettings.dataGridTypeColorSchemes);
@@ -1889,6 +1896,8 @@ const editorSettingsDraftRefs: EditorSettingsDraftRefMap = {
showColumnTypesInHeader: editShowColumnTypesInHeader, showColumnTypesInHeader: editShowColumnTypesInHeader,
showColumnHeaderTooltips: editShowColumnHeaderTooltips, showColumnHeaderTooltips: editShowColumnHeaderTooltips,
showResultSourceDatabase: editShowResultSourceDatabase, showResultSourceDatabase: editShowResultSourceDatabase,
resultTabNamingMode: editResultTabNamingMode,
resultTabPreferComments: editResultTabPreferComments,
dataGridShowTransposeFieldMetadata: editDataGridShowTransposeFieldMetadata, dataGridShowTransposeFieldMetadata: editDataGridShowTransposeFieldMetadata,
colorizeDataGridCellTypes: editColorizeDataGridCellTypes, colorizeDataGridCellTypes: editColorizeDataGridCellTypes,
dataGridTypeColorSchemes: editDataGridTypeColorSchemes, dataGridTypeColorSchemes: editDataGridTypeColorSchemes,
@@ -2442,6 +2451,8 @@ function resetDefaultsForTab(tab: SettingsCategory) {
editShowColumnTypesInHeader.value = DEFAULT_EDITOR_SETTINGS.showColumnTypesInHeader; editShowColumnTypesInHeader.value = DEFAULT_EDITOR_SETTINGS.showColumnTypesInHeader;
editShowColumnHeaderTooltips.value = DEFAULT_EDITOR_SETTINGS.showColumnHeaderTooltips; editShowColumnHeaderTooltips.value = DEFAULT_EDITOR_SETTINGS.showColumnHeaderTooltips;
editShowResultSourceDatabase.value = DEFAULT_EDITOR_SETTINGS.showResultSourceDatabase; editShowResultSourceDatabase.value = DEFAULT_EDITOR_SETTINGS.showResultSourceDatabase;
editResultTabNamingMode.value = DEFAULT_EDITOR_SETTINGS.resultTabNamingMode;
editResultTabPreferComments.value = DEFAULT_EDITOR_SETTINGS.resultTabPreferComments;
editDataGridShowTransposeFieldMetadata.value = DEFAULT_EDITOR_SETTINGS.dataGridShowTransposeFieldMetadata; editDataGridShowTransposeFieldMetadata.value = DEFAULT_EDITOR_SETTINGS.dataGridShowTransposeFieldMetadata;
editColorizeDataGridCellTypes.value = DEFAULT_EDITOR_SETTINGS.colorizeDataGridCellTypes; editColorizeDataGridCellTypes.value = DEFAULT_EDITOR_SETTINGS.colorizeDataGridCellTypes;
// Back to the built-in palette, but keep the user's saved schemes available. // Back to the built-in palette, but keep the user's saved schemes available.
@@ -8467,16 +8478,43 @@ onUnmounted(() => {
</div> </div>
<Switch id="show-column-header-tooltips" v-model="editShowColumnHeaderTooltips" /> <Switch id="show-column-header-tooltips" v-model="editShowColumnHeaderTooltips" />
</div> </div>
<div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2"> <div class="settings-item space-y-3 rounded-md border bg-muted/20 p-3">
<div class="space-y-1"> <div class="flex items-center justify-between gap-4">
<Label for="show-result-source-database"> <div class="min-w-0 space-y-1">
{{ t("settings.showResultSourceDatabase") }} <Label>{{ t("settings.resultTabNamingMode") }}</Label>
</Label> <p class="text-xs text-muted-foreground">
<p class="text-xs text-muted-foreground"> {{ t("settings.resultTabNamingModeDescription") }}
{{ t("settings.showResultSourceDatabaseDescription") }} </p>
</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> </div>
<Switch id="show-result-source-database" v-model="editShowResultSourceDatabase" />
</div> </div>
<div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2"> <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"> <div class="space-y-1">
@@ -501,8 +501,12 @@ const activeQueryError = computed(() => {
const hasQueryOutput = computed(() => tabHasQueryOutput(props.activeTab)); const hasQueryOutput = computed(() => tabHasQueryOutput(props.activeTab));
// 结果集页签/列表的名称是否带库名,由编辑器设置控制(默认带库名) // 结果集页签/列表的名称是否带库名,由编辑器设置控制(默认带库名)
const includeResultSourceDatabase = computed(() => settingsStore.editorSettings.showResultSourceDatabase); const includeResultSourceDatabase = computed(() => settingsStore.editorSettings.showResultSourceDatabase);
const visibleResultItems = computed(() => tabularResultItems(props.activeTab.results ?? (props.activeTab.result ? [props.activeTab.result] : undefined), { includeSourceDatabase: includeResultSourceDatabase.value })); const resultTabNamingMode = computed(() => settingsStore.editorSettings.resultTabNamingMode);
const tabularResults = computed(() => tabularResultItems(props.activeTab.results, { includeSourceDatabase: includeResultSourceDatabase.value })); 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(() => const allResultExportSheets = computed(() =>
tabularResults.value.map((item) => ({ tabularResults.value.map((item) => ({
sheetName: item.label || t("tabs.resultN", { n: item.n }), sheetName: item.label || t("tabs.resultN", { n: item.n }),
@@ -514,10 +518,13 @@ const allResultExportSheets = computed(() =>
const resultRuns = computed(() => const resultRuns = computed(() =>
resultRunItems(props.activeTab, { resultRunItems(props.activeTab, {
includeSourceDatabase: includeResultSourceDatabase.value, includeSourceDatabase: includeResultSourceDatabase.value,
namingMode: resultTabNamingMode.value,
preferComments: preferResultTabComments.value,
database: props.activeTab.database, database: props.activeTab.database,
databaseType: activeEffectiveDatabaseType.value, databaseType: activeEffectiveDatabaseType.value,
}), }),
); );
const resultRunFallbackLabel = (sequence: number) => t(resultTabNamingMode.value === "ordinal" ? "tabs.resultN" : "tabs.runN", { n: sequence });
const activeResultGridCacheKey = computed(() => resultGridCacheKey(props.activeTab)); const activeResultGridCacheKey = computed(() => resultGridCacheKey(props.activeTab));
const activeResultGridColumnWidthCacheKey = computed(() => resultGridColumnWidthCacheKey(props.activeTab)); const activeResultGridColumnWidthCacheKey = computed(() => resultGridColumnWidthCacheKey(props.activeTab));
const activeResultGridInstanceKey = computed(() => resultGridInstanceKey(props.activeTab)); const activeResultGridInstanceKey = computed(() => resultGridInstanceKey(props.activeTab));
@@ -1824,7 +1831,7 @@ defineExpose({
@keydown="onResultRunTabKeydown($event, runIndex)" @keydown="onResultRunTabKeydown($event, runIndex)"
> >
<Pin v-if="run.pinned" class="h-3 w-3 shrink-0 fill-current text-primary" /> <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> </button>
<button <button
type="button" type="button"
@@ -1844,7 +1851,7 @@ defineExpose({
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger as-child> <DropdownMenuTrigger as-child>
<Button variant="ghost" size="sm" class="h-6 max-w-48 gap-1 px-2 text-xs"> <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" /> <ChevronDown class="h-3.5 w-3.5 shrink-0" />
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
@@ -1854,7 +1861,7 @@ defineExpose({
<Check v-if="run.active" class="h-3.5 w-3.5 shrink-0" /> <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" /> <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" /> <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>
<button <button
type="button" type="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" class="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"
+7
View File
@@ -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.", 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", 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.", 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", 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.", 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", colorizeDataGridCellTypes: "Verilənlər cədvəlinin dəyərlərini rənglə fərqləndir",
+7
View File
@@ -8222,6 +8222,13 @@ export default {
showColumnHeaderTooltipsDescription: "Show detail tooltips when hovering result grid column headers. Turn off to stop hover popups.", showColumnHeaderTooltipsDescription: "Show detail tooltips when hovering result grid column headers. Turn off to stop hover popups.",
showResultSourceDatabase: "Include database name in result set names", 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.", 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", dataGridShowTransposeFieldMetadata: "Show field metadata in transpose view",
dataGridShowTransposeFieldMetadataDescription: "Display enabled column types and comments on separate lines in transpose view. This increases row height.", dataGridShowTransposeFieldMetadataDescription: "Display enabled column types and comments on separate lines in transpose view. This increases row height.",
colorizeDataGridCellTypes: "Color-code data grid values", colorizeDataGridCellTypes: "Color-code data grid values",
+7
View File
@@ -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.", 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", 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.", 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", 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.", 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", colorizeDataGridCellTypes: "Colorear valores por tipo de dato",
+7
View File
@@ -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.", 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", 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.", 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", 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.", 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", colorizeDataGridCellTypes: "Colora i valori in base al tipo di dato",
+7
View File
@@ -7427,6 +7427,13 @@ export default withEnglishFallback({
showColumnHeaderTooltipsDescription: "結果グリッドの列ヘッダーにホバーしたときに詳細ツールチップを表示します。オフにすると表示されません。", showColumnHeaderTooltipsDescription: "結果グリッドの列ヘッダーにホバーしたときに詳細ツールチップを表示します。オフにすると表示されません。",
showResultSourceDatabase: "結果セット名にデータベース名を含める", showResultSourceDatabase: "結果セット名にデータベース名を含める",
showResultSourceDatabaseDescription: "オフにすると結果セットのタブにはテーブル名のみを表示し、完全な名前(データベース名を含む)はツールチップで確認できます。", showResultSourceDatabaseDescription: "オフにすると結果セットのタブにはテーブル名のみを表示し、完全な名前(データベース名を含む)はツールチップで確認できます。",
resultTabNamingMode: "結果タブの名前",
resultTabNamingModeDescription: "結果タブにテーブル名、番号、または SQL 文の上にあるコメントを表示します。",
resultTabNamingModeSource: "データベース名とテーブル名",
resultTabNamingModeOrdinal: "結果番号",
resultTabNamingModeComment: "SQL コメント",
resultTabPreferComments: "SQL コメントがある場合は優先する",
resultTabPreferCommentsDescription: "SQL 文の上のコメントを優先します。オフにすると常に参照元のテーブル名を表示します。",
dataGridShowTransposeFieldMetadata: "転置ビューにフィールドメタデータを表示", dataGridShowTransposeFieldMetadata: "転置ビューにフィールドメタデータを表示",
dataGridShowTransposeFieldMetadataDescription: "有効なデータ型とコメントを転置ビューの別行に表示します。有効にすると行の高さが増えます。", dataGridShowTransposeFieldMetadataDescription: "有効なデータ型とコメントを転置ビューの別行に表示します。有効にすると行の高さが増えます。",
colorizeDataGridCellTypes: "データ型に応じて値を色分け", colorizeDataGridCellTypes: "データ型に応じて値を色分け",
+7
View File
@@ -7174,6 +7174,13 @@ export default withEnglishFallback({
showColumnHeaderTooltipsDescription: "결과 그리드의 컬럼 헤더에 마우스를 올리면 상세 툴팁을 표시합니다. 끄면 표시되지 않습니다.", showColumnHeaderTooltipsDescription: "결과 그리드의 컬럼 헤더에 마우스를 올리면 상세 툴팁을 표시합니다. 끄면 표시되지 않습니다.",
showResultSourceDatabase: "결과 세트 이름에 데이터베이스 이름 포함", showResultSourceDatabase: "결과 세트 이름에 데이터베이스 이름 포함",
showResultSourceDatabaseDescription: "끄면 결과 세트 탭에 테이블 이름만 표시되며, 전체 이름(데이터베이스 이름 포함)은 툴팁에서 확인할 수 있습니다.", showResultSourceDatabaseDescription: "끄면 결과 세트 탭에 테이블 이름만 표시되며, 전체 이름(데이터베이스 이름 포함)은 툴팁에서 확인할 수 있습니다.",
resultTabNamingMode: "결과 탭 이름 지정",
resultTabNamingModeDescription: "결과 탭에 원본 테이블, 번호 또는 SQL 문 위의 주석을 표시할지 선택합니다.",
resultTabNamingModeSource: "데이터베이스 및 테이블 이름",
resultTabNamingModeOrdinal: "결과 번호",
resultTabNamingModeComment: "SQL 주석",
resultTabPreferComments: "SQL 주석이 있으면 우선 표시",
resultTabPreferCommentsDescription: "SQL 문 위의 주석을 우선 표시합니다. 끄면 항상 원본 테이블 이름을 표시합니다.",
dataGridShowTransposeFieldMetadata: "전치 보기에 필드 메타데이터 표시", dataGridShowTransposeFieldMetadata: "전치 보기에 필드 메타데이터 표시",
dataGridShowTransposeFieldMetadataDescription: "활성화된 데이터 타입과 주석을 전치 보기의 별도 줄에 표시합니다. 활성화하면 행 높이가 증가합니다.", dataGridShowTransposeFieldMetadataDescription: "활성화된 데이터 타입과 주석을 전치 보기의 별도 줄에 표시합니다. 활성화하면 행 높이가 증가합니다.",
colorizeDataGridCellTypes: "데이터 타입별 값 색상 표시", colorizeDataGridCellTypes: "데이터 타입별 값 색상 표시",
+7
View File
@@ -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.", 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", 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.", 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", 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.", 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", colorizeDataGridCellTypes: "Colorir valores por tipo de dado",
+7
View File
@@ -9639,6 +9639,13 @@ export default withEnglishFallback({
showColumnHeaderTooltipsDescription: "Показывать подробную всплывающую подсказку при наведении курсора на имя поля в заголовке результатов; после отключения всплывающая подсказка при наведении больше не появляется.", showColumnHeaderTooltipsDescription: "Показывать подробную всплывающую подсказку при наведении курсора на имя поля в заголовке результатов; после отключения всплывающая подсказка при наведении больше не появляется.",
showResultSourceDatabase: "Имя набора результатов содержит имя базы данных", showResultSourceDatabase: "Имя набора результатов содержит имя базы данных",
showResultSourceDatabaseDescription: "После отключения вкладки наборов результатов будут отображать только имена таблиц; полное имя (включая имя базы данных) по-прежнему можно посмотреть во всплывающей подсказке.", showResultSourceDatabaseDescription: "После отключения вкладки наборов результатов будут отображать только имена таблиц; полное имя (включая имя базы данных) по-прежнему можно посмотреть во всплывающей подсказке.",
resultTabNamingMode: "Имена вкладок результатов",
resultTabNamingModeDescription: "Выберите, показывать ли исходную таблицу, номер или комментарий над SQL-оператором.",
resultTabNamingModeSource: "Имя базы данных и таблицы",
resultTabNamingModeOrdinal: "Номер результата",
resultTabNamingModeComment: "Комментарий SQL",
resultTabPreferComments: "Предпочитать комментарии SQL, если они есть",
resultTabPreferCommentsDescription: "Использовать комментарий над SQL-запросом; отключите, чтобы всегда отображать имя исходной таблицы.",
sidebarSearchOpenedDatabasesOnly: "Искать только в открытых базах данных", sidebarSearchOpenedDatabasesOnly: "Искать только в открытых базах данных",
sidebarSearchOpenedDatabasesOnlyDescription: "Поиск на боковой панели загружает только открытые базы данных в текущем подключении (если ни одна не открыта, поиск выполняется по всем). Если отключить, поиск будет выполняться по всем базам данных этого подключения.", sidebarSearchOpenedDatabasesOnlyDescription: "Поиск на боковой панели загружает только открытые базы данных в текущем подключении (если ни одна не открыта, поиск выполняется по всем). Если отключить, поиск будет выполняться по всем базам данных этого подключения.",
}, },
+7
View File
@@ -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.", 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", 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.", 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", 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.", 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", colorizeDataGridCellTypes: "Veri tablosu değerlerini renklendir",
+7
View File
@@ -8188,6 +8188,13 @@ export default withEnglishFallback({
showColumnHeaderTooltipsDescription: "在结果表头字段名上悬浮时显示详情提示;关闭后悬浮不再弹出。", showColumnHeaderTooltipsDescription: "在结果表头字段名上悬浮时显示详情提示;关闭后悬浮不再弹出。",
showResultSourceDatabase: "结果集名称包含数据库名", showResultSourceDatabase: "结果集名称包含数据库名",
showResultSourceDatabaseDescription: "关闭后结果集页签只显示表名,完整名称(含数据库名)仍可在悬浮提示中查看。", showResultSourceDatabaseDescription: "关闭后结果集页签只显示表名,完整名称(含数据库名)仍可在悬浮提示中查看。",
resultTabNamingMode: "结果页签命名方式",
resultTabNamingModeDescription: "选择结果页签使用来源表名、序号,还是 SQL 语句上方的注释。",
resultTabNamingModeSource: "数据库名和表名",
resultTabNamingModeOrdinal: "结果序号",
resultTabNamingModeComment: "SQL 注释",
resultTabPreferComments: "有注释时优先展示注释",
resultTabPreferCommentsDescription: "开启后优先使用 SQL 语句上方的注释;关闭后按来源表名显示。",
dataGridShowTransposeFieldMetadata: "在转置视图中显示字段元数据", dataGridShowTransposeFieldMetadata: "在转置视图中显示字段元数据",
dataGridShowTransposeFieldMetadataDescription: "在转置视图中分行显示已启用的数据类型和注释。开启后会增加行高。", dataGridShowTransposeFieldMetadataDescription: "在转置视图中分行显示已启用的数据类型和注释。开启后会增加行高。",
colorizeDataGridCellTypes: "按数据类型为表格值着色", colorizeDataGridCellTypes: "按数据类型为表格值着色",
+7
View File
@@ -6719,6 +6719,13 @@ export default withEnglishFallback({
showColumnHeaderTooltipsDescription: "在資料表格欄位名稱上懸浮時顯示詳細提示;關閉後懸浮不再彈出。", showColumnHeaderTooltipsDescription: "在資料表格欄位名稱上懸浮時顯示詳細提示;關閉後懸浮不再彈出。",
showResultSourceDatabase: "結果集名稱包含資料庫名稱", showResultSourceDatabase: "結果集名稱包含資料庫名稱",
showResultSourceDatabaseDescription: "關閉後結果集頁籤只顯示資料表名稱,完整名稱(含資料庫名稱)仍可在懸浮提示中查看。", showResultSourceDatabaseDescription: "關閉後結果集頁籤只顯示資料表名稱,完整名稱(含資料庫名稱)仍可在懸浮提示中查看。",
resultTabNamingMode: "結果頁籤命名方式",
resultTabNamingModeDescription: "選擇結果頁籤使用來源資料表、序號,或 SQL 陳述式上方的註解。",
resultTabNamingModeSource: "資料庫名稱和資料表名稱",
resultTabNamingModeOrdinal: "結果序號",
resultTabNamingModeComment: "SQL 註解",
resultTabPreferComments: "有註解時優先顯示註解",
resultTabPreferCommentsDescription: "開啟後優先使用 SQL 語句上方的註解;關閉後依來源資料表名稱顯示。",
dataGridShowTransposeFieldMetadata: "在轉置檢視中顯示欄位中繼資料", dataGridShowTransposeFieldMetadata: "在轉置檢視中顯示欄位中繼資料",
dataGridShowTransposeFieldMetadataDescription: "在轉置檢視中分行顯示已啟用的資料類型和註解。開啟後會增加列高。", dataGridShowTransposeFieldMetadataDescription: "在轉置檢視中分行顯示已啟用的資料類型和註解。開啟後會增加列高。",
colorizeDataGridCellTypes: "依資料類型為表格值著色", colorizeDataGridCellTypes: "依資料類型為表格值著色",
+94 -2
View File
@@ -204,7 +204,7 @@ describe("query result labels", () => {
expect(withoutDatabase?.title).toBe("cosimulation2.0.data_monitor"); 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( const [item] = tabularResultItems(
[ [
{ {
@@ -213,17 +213,81 @@ describe("query result labels", () => {
affected_rows: 0, affected_rows: 0,
execution_time_ms: 1, execution_time_ms: 1,
sourceLabel: "My weekly report", sourceLabel: "My weekly report",
sourceLabelKind: "comment",
sourceQualifier: "app", sourceQualifier: "app",
sourceName: "users", sourceName: "users",
sourceStatement: "SELECT * FROM users", sourceStatement: "SELECT * FROM users",
}, },
], ],
{ includeSourceDatabase: false }, { includeSourceDatabase: false, namingMode: "comment" },
); );
expect(item?.label).toBe("My weekly report"); expect(item?.label).toBe("My weekly report");
expect(item?.title).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", () => { describe("query result grid identity", () => {
@@ -283,6 +347,34 @@ describe("result run labels", () => {
expect(items[0]?.sourceLabel).toBe("cosimulation2.0.users"); 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", () => { 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"; import { sanitizeTabUiState } from "@/lib/tabs/tabUiState";
export const OPEN_TABS_STORAGE_KEY = "dbx-open-tabs"; export const OPEN_TABS_STORAGE_KEY = "dbx-open-tabs";
@@ -19,6 +19,7 @@ export interface SavedQueryResultRun {
/** 结果来源(库名.表名 / 表名),用于结果标签命名;与结果 payload 分离,回收 payload 后仍可显示 */ /** 结果来源(库名.表名 / 表名),用于结果标签命名;与结果 payload 分离,回收 payload 后仍可显示 */
sourceLabel?: string; sourceLabel?: string;
sourceName?: string; sourceName?: string;
sourceLabelKind?: QueryResultSourceLabelKind;
} }
export interface SavedOpenTab { export interface SavedOpenTab {
@@ -228,6 +229,7 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
createdAt: run.createdAt, createdAt: run.createdAt,
...(run.sourceLabel ? { sourceLabel: run.sourceLabel } : {}), ...(run.sourceLabel ? { sourceLabel: run.sourceLabel } : {}),
...(run.sourceName ? { sourceName: run.sourceName } : {}), ...(run.sourceName ? { sourceName: run.sourceName } : {}),
...(run.sourceLabelKind ? { sourceLabelKind: run.sourceLabelKind } : {}),
...(run.customTitle ? { customTitle: true } : {}), ...(run.customTitle ? { customTitle: true } : {}),
...(run.pinned ? { pinned: true } : {}), ...(run.pinned ? { pinned: true } : {}),
activeResultIndex: run.activeResultIndex, activeResultIndex: run.activeResultIndex,
@@ -14,6 +14,15 @@ function fileWith(editor: Record<string, unknown>, overrides: Record<string, unk
} }
describe("settingsTransfer", () => { 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", () => { it("builds a dated transfer filename", () => {
expect(buildSettingsTransferFilename(new Date(2026, 8, 6))).toBe("dbx-settings-2026-09-06.json"); 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", "showColumnTypesInHeader",
"showColumnHeaderTooltips", "showColumnHeaderTooltips",
"showResultSourceDatabase", "showResultSourceDatabase",
"resultTabNamingMode",
"resultTabPreferComments",
"dataGridShowTransposeFieldMetadata", "dataGridShowTransposeFieldMetadata",
"colorizeDataGridCellTypes", "colorizeDataGridCellTypes",
"dataGridTypeColorSchemes", "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-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: "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-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-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-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" }, { 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", "showColumnTypesInHeader",
"showColumnHeaderTooltips", "showColumnHeaderTooltips",
"showResultSourceDatabase", "showResultSourceDatabase",
"resultTabNamingMode",
"resultTabPreferComments",
"dataGridShowTransposeFieldMetadata", "dataGridShowTransposeFieldMetadata",
"colorizeDataGridCellTypes", "colorizeDataGridCellTypes",
"dataGridTypeColorSchemes", "dataGridTypeColorSchemes",
@@ -278,6 +280,7 @@ const PASS_THROUGH_BOOLEAN_KEYS = [
"showColumnTypesInHeader", "showColumnTypesInHeader",
"showColumnHeaderTooltips", "showColumnHeaderTooltips",
"showResultSourceDatabase", "showResultSourceDatabase",
"resultTabPreferComments",
"colorizeDataGridCellTypes", "colorizeDataGridCellTypes",
"showIndexIndicatorsInHeader", "showIndexIndicatorsInHeader",
"compactColumnHeaderActions", "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. // 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, fontSize: (value) => typeof value === "number" && Number.isFinite(value) && value >= EDITOR_MIN_FONT_SIZE && value <= EDITOR_MAX_FONT_SIZE,
appLayout: (value) => value === "separated" || value === "classic", appLayout: (value) => value === "separated" || value === "classic",
resultTabNamingMode: (value) => value === "source" || value === "ordinal" || value === "comment",
activeCustomThemeId: (value) => typeof value === "string" && value.trim().length > 0, activeCustomThemeId: (value) => typeof value === "string" && value.trim().length > 0,
// normalizeToolbarItems keeps unknown/typed values for every known key, so // 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 // 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 type { SqlErrorPosition } from "@/lib/backend/errorUtils";
import { queryResultSourceNameParts } from "@/lib/sql/queryResultSource"; import { queryResultSourceNameParts } from "@/lib/sql/queryResultSource";
import type { BatchSqlExecution, ConnectionConfig, DatabaseType, QueryResult, QueryResultRun, QueryTab } from "@/types/database"; 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; type Translate = (key: string, params?: Record<string, unknown>) => string;
export type OutputView = "result" | "summary" | "explain" | "chart"; export type OutputView = "result" | "summary" | "explain" | "chart";
@@ -336,8 +337,23 @@ export function tabTooltipLines(tab: QueryTab, t: Translate): { label: string; v
return lines; return lines;
} }
export function queryResultStatementLabel(result: Pick<QueryResult, "sourceLabel">): string | undefined { type ResultSourceFields = Pick<QueryResult, "sourceLabel" | "sourceLabelKind" | "sourceQualifier" | "sourceName">;
return result.sourceLabel; 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 { 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); 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 []; if (!results) return [];
return results return results
.map((result, index) => ({ result, index })) .map((result, index) => ({ result, index }))
.filter((item) => item.result.columns.length > 0 && item.result.server_message !== true) .filter((item) => item.result.columns.length > 0 && item.result.server_message !== true)
.map((item, ordinal) => { .map((item, ordinal) => {
const label = queryResultStatementLabel(item.result); const displaySource = resultNamingLabel(item.result, options);
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 displayLabel = displaySource ? middleEllipsis(displaySource) : undefined; const displayLabel = displaySource ? middleEllipsis(displaySource) : undefined;
return { return {
...item, ...item,
@@ -508,31 +518,33 @@ export function activeResultRun(tab: Pick<QueryTab, "resultRuns" | "activeResult
* 执行批次默认显示名:取该批次主结果的来源(库名.表名 / 表名)。 * 执行批次默认显示名:取该批次主结果的来源(库名.表名 / 表名)。
* 连表查询同样取 FROM 之后的第一个物理表,与结果集页签的来源解析保持一致。 * 连表查询同样取 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 里的来源会丢失 // 优先用批次自带的来源:非活动批次的结果 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; if (own) return own;
const candidates = run.result ? [run.result, ...(run.results ?? [])] : (run.results ?? []); const candidates = run.result ? [run.result, ...(run.results ?? [])] : (run.results ?? []);
for (const result of candidates) { for (const result of candidates) {
if (!result) continue; if (!result) continue;
// 批次级来源缺失时回退到结果本身;关闭“结果集名称包含数据库名”时优先用对象名 // 批次级来源缺失时回退到结果本身;关闭“结果集名称包含数据库名”时优先用对象名
const label = includeSourceDatabase ? result.sourceLabel || result.sourceName : result.sourceName || result.sourceLabel; const label = resultNamingLabel(result, options);
if (label) return label; if (label) return label;
} }
// 历史批次(功能上线前创建的)没有来源信息:用批次 SQL 重新解析,连表查询同样取第一个物理表 // 历史批次(功能上线前创建的)没有来源信息:用批次 SQL 重新解析,连表查询同样取第一个物理表
if (run.sql && fallback.databaseType) { if (namingMode === "source" && run.sql && fallback.databaseType) {
const parts = queryResultSourceNameParts(run.sql, { database: fallback.database, databaseType: 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; if (parts) return includeSourceDatabase ? (parts.qualifier ? `${parts.qualifier}.${parts.name}` : parts.name) : parts.name;
} }
return undefined; 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 }[] { 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 includeSourceDatabase = options.includeSourceDatabase !== false;
const fallback = { database: options.database, databaseType: options.databaseType }; const fallback = { database: options.database, databaseType: options.databaseType };
const seenBySource = new Map<string, number>(); const seenBySource = new Map<string, number>();
return (tab.resultRuns ?? []).map((run) => { return (tab.resultRuns ?? []).map((run) => {
const source = resultRunSourceLabel(run, includeSourceDatabase, fallback); const source = resultRunSourceLabel(run, options, fallback);
let sourceLabel = source; let sourceLabel = source;
if (source) { if (source) {
// 同一张表被查询多次时用序号后缀区分页签(users、users (2)…) // 同一张表被查询多次时用序号后缀区分页签(users、users (2)…)
@@ -81,6 +81,7 @@ interface ColumnarQueryResult {
truncated?: boolean; truncated?: boolean;
has_more?: boolean; has_more?: boolean;
sourceLabel?: string; sourceLabel?: string;
sourceLabelKind?: QueryResult["sourceLabelKind"];
sourceQualifier?: string; sourceQualifier?: string;
sourceName?: string; sourceName?: string;
sourceStatement?: string; sourceStatement?: string;
@@ -377,6 +378,7 @@ function stripSessionIds(result: QueryResult | undefined): QueryResult | undefin
session_id: undefined, session_id: undefined,
has_more: result.has_more, has_more: result.has_more,
sourceLabel: result.sourceLabel, sourceLabel: result.sourceLabel,
sourceLabelKind: result.sourceLabelKind,
sourceQualifier: result.sourceQualifier, sourceQualifier: result.sourceQualifier,
sourceName: result.sourceName, sourceName: result.sourceName,
sourceStatement: result.sourceStatement, sourceStatement: result.sourceStatement,
@@ -440,6 +442,7 @@ function toColumnarResult(result: QueryResult | undefined): ColumnarQueryResult
truncated: result.truncated, truncated: result.truncated,
has_more: result.has_more, has_more: result.has_more,
sourceLabel: result.sourceLabel, sourceLabel: result.sourceLabel,
sourceLabelKind: result.sourceLabelKind,
sourceQualifier: result.sourceQualifier, sourceQualifier: result.sourceQualifier,
sourceName: result.sourceName, sourceName: result.sourceName,
sourceStatement: result.sourceStatement, sourceStatement: result.sourceStatement,
@@ -477,6 +480,7 @@ function fromColumnarResult(result: ColumnarQueryResult | undefined): QueryResul
session_id: undefined, session_id: undefined,
has_more: result.has_more, has_more: result.has_more,
sourceLabel: result.sourceLabel, sourceLabel: result.sourceLabel,
sourceLabelKind: result.sourceLabelKind,
sourceQualifier: result.sourceQualifier, sourceQualifier: result.sourceQualifier,
sourceName: result.sourceName, sourceName: result.sourceName,
sourceStatement: result.sourceStatement, sourceStatement: result.sourceStatement,
@@ -978,6 +978,10 @@ describe("queryStore multi-statement errors", () => {
await store.executeTabSql(tabId, sql); 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?.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 () => { it("does not repeatedly scan the full document when naming a selected large batch", async () => {
@@ -20,6 +20,13 @@ import type { AiConfigItem } from "@/types/ai";
import { DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION } from "@/lib/dataGrid/dataGridCopyExtractor"; import { DATA_GRID_EXTRACTOR_OPTIONS_MIGRATION_VERSION } from "@/lib/dataGrid/dataGridCopyExtractor";
describe("normalizeEditorSettings", () => { 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", () => { it("defaults and sanitizes AI conversation typography independently", () => {
expect(normalizeEditorSettings({})).toMatchObject({ aiFontFamily: "", aiFontSize: 12 }); expect(normalizeEditorSettings({})).toMatchObject({ aiFontFamily: "", aiFontSize: 12 });
expect( expect(
+16 -5
View File
@@ -405,6 +405,7 @@ function releaseResultObjectPayload(result: QueryResult): void {
result.messages = undefined; result.messages = undefined;
result.error = undefined; result.error = undefined;
result.sourceLabel = undefined; result.sourceLabel = undefined;
result.sourceLabelKind = undefined;
result.sourceQualifier = undefined; result.sourceQualifier = undefined;
result.sourceName = undefined; result.sourceName = undefined;
result.sourceStatement = undefined; result.sourceStatement = undefined;
@@ -464,9 +465,9 @@ function annotateQueryResultSources(results: QueryResult[], sql: string, databas
const customName = queryResultNameFromPreamble(preamble, { databaseType }); const customName = queryResultNameFromPreamble(preamble, { databaseType });
if (customName) { if (customName) {
result.sourceLabel = customName; result.sourceLabel = customName;
// 自定义名称(-- name: xxx)优先:清除结构化来源,避免“结果集名称包含数据库名”设置把它替换成表名 result.sourceLabelKind = "comment";
result.sourceQualifier = undefined; // 保留结构化来源,方便“来源表名”模式在注释存在时仍显示表名。
result.sourceName = undefined; // “注释”模式通过 sourceLabelKind 选择这个自定义名称。
} }
const successfulUseDatabase = result.execution_error !== true ? useDatabaseFromStatement(statement.sql, databaseType) : undefined; const successfulUseDatabase = result.execution_error !== true ? useDatabaseFromStatement(statement.sql, databaseType) : undefined;
if (successfulUseDatabase) { if (successfulUseDatabase) {
@@ -688,7 +689,10 @@ function annotateQueryResultSource(result: QueryResult, sourceStatement: string,
result.sourceQualifier = parts.qualifier; result.sourceQualifier = parts.qualifier;
result.sourceName = parts.name; result.sourceName = parts.name;
const label = parts.qualifier ? `${parts.qualifier}.${parts.name}` : 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; return result;
} }
@@ -2184,6 +2188,7 @@ export const useQueryStore = defineStore("query", () => {
createdAt, createdAt,
sourceLabel: primaryResult?.sourceLabel, sourceLabel: primaryResult?.sourceLabel,
sourceName: primaryResult?.sourceName, sourceName: primaryResult?.sourceName,
sourceLabelKind: primaryResult?.sourceLabelKind,
result: tab.result, result: tab.result,
results: tab.results, results: tab.results,
activeResultIndex: tab.activeResultIndex, activeResultIndex: tab.activeResultIndex,
@@ -2621,6 +2626,7 @@ export const useQueryStore = defineStore("query", () => {
customTitle: run.customTitle, customTitle: run.customTitle,
sourceLabel: run.sourceLabel, sourceLabel: run.sourceLabel,
sourceName: run.sourceName, sourceName: run.sourceName,
sourceLabelKind: run.sourceLabelKind,
activeResultIndex: run.activeResultIndex, activeResultIndex: run.activeResultIndex,
resultCacheKey: run.resultCacheKey, resultCacheKey: run.resultCacheKey,
resultEvicted: run.resultEvicted, resultEvicted: run.resultEvicted,
@@ -5936,8 +5942,12 @@ export const useQueryStore = defineStore("query", () => {
}); });
if (nextLabel) { if (nextLabel) {
tab.result.sourceLabel = nextLabel; tab.result.sourceLabel = nextLabel;
tab.result.sourceLabelKind = "source";
const matching = tab.results?.find((result) => result === tab.result); 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.sourceQualifier = currentDatabase || undefined;
annotated.sourceName = mongoCommand.collection; annotated.sourceName = mongoCommand.collection;
annotated.sourceLabel = currentDatabase ? `${currentDatabase}.${mongoCommand.collection}` : mongoCommand.collection; annotated.sourceLabel = currentDatabase ? `${currentDatabase}.${mongoCommand.collection}` : mongoCommand.collection;
annotated.sourceLabelKind = "source";
} }
return commandTiming.finish(annotated); return commandTiming.finish(annotated);
}; };
+16
View File
@@ -727,6 +727,8 @@ export type DataGridFilterEditorView = "quick" | "conditions" | "text";
export type DataGridToolbarLayout = "single" | "split"; export type DataGridToolbarLayout = "single" | "split";
const RESULT_RUN_DISPLAY_MODES = ["tabs", "list"] as const; const RESULT_RUN_DISPLAY_MODES = ["tabs", "list"] as const;
export type ResultRunDisplayMode = (typeof RESULT_RUN_DISPLAY_MODES)[number]; 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; const MULTI_STATEMENT_DEFAULT_VIEWS = ["result", "summary"] as const;
export type MultiStatementDefaultView = (typeof MULTI_STATEMENT_DEFAULT_VIEWS)[number]; export type MultiStatementDefaultView = (typeof MULTI_STATEMENT_DEFAULT_VIEWS)[number];
export const TABLE_FONT_SIZE_MIN = 8; export const TABLE_FONT_SIZE_MIN = 8;
@@ -909,6 +911,10 @@ export interface EditorSettings {
showColumnHeaderTooltips: boolean; showColumnHeaderTooltips: boolean;
/** 结果集页签/结果列表的名称是否带上库名(关闭后只显示表名,完整名称仍在悬浮提示中)。 */ /** 结果集页签/结果列表的名称是否带上库名(关闭后只显示表名,完整名称仍在悬浮提示中)。 */
showResultSourceDatabase: 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; dataGridShowTransposeFieldMetadata: boolean;
colorizeDataGridCellTypes: boolean; colorizeDataGridCellTypes: boolean;
dataGridTypeColorSchemes: DataGridTypeColorScheme[]; dataGridTypeColorSchemes: DataGridTypeColorScheme[];
@@ -1199,6 +1205,8 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
showColumnTypesInHeader: true, showColumnTypesInHeader: true,
showColumnHeaderTooltips: true, showColumnHeaderTooltips: true,
showResultSourceDatabase: true, showResultSourceDatabase: true,
resultTabNamingMode: "source",
resultTabPreferComments: true,
dataGridShowTransposeFieldMetadata: false, dataGridShowTransposeFieldMetadata: false,
colorizeDataGridCellTypes: false, colorizeDataGridCellTypes: false,
dataGridTypeColorSchemes: [], 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; 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 { function normalizeMultiStatementDefaultView(value: unknown): MultiStatementDefaultView {
return MULTI_STATEMENT_DEFAULT_VIEWS.includes(value as MultiStatementDefaultView) ? (value as MultiStatementDefaultView) : DEFAULT_EDITOR_SETTINGS.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>, exist
showColumnTypesInHeader: settings.showColumnTypesInHeader ?? DEFAULT_EDITOR_SETTINGS.showColumnTypesInHeader, showColumnTypesInHeader: settings.showColumnTypesInHeader ?? DEFAULT_EDITOR_SETTINGS.showColumnTypesInHeader,
showColumnHeaderTooltips: settings.showColumnHeaderTooltips ?? DEFAULT_EDITOR_SETTINGS.showColumnHeaderTooltips, showColumnHeaderTooltips: settings.showColumnHeaderTooltips ?? DEFAULT_EDITOR_SETTINGS.showColumnHeaderTooltips,
showResultSourceDatabase: settings.showResultSourceDatabase ?? DEFAULT_EDITOR_SETTINGS.showResultSourceDatabase, showResultSourceDatabase: settings.showResultSourceDatabase ?? DEFAULT_EDITOR_SETTINGS.showResultSourceDatabase,
resultTabNamingMode: normalizeResultTabNamingMode(settings.resultTabNamingMode),
resultTabPreferComments: settings.resultTabPreferComments !== false,
dataGridShowTransposeFieldMetadata: settings.dataGridShowTransposeFieldMetadata === true, dataGridShowTransposeFieldMetadata: settings.dataGridShowTransposeFieldMetadata === true,
colorizeDataGridCellTypes: settings.colorizeDataGridCellTypes ?? DEFAULT_EDITOR_SETTINGS.colorizeDataGridCellTypes, colorizeDataGridCellTypes: settings.colorizeDataGridCellTypes ?? DEFAULT_EDITOR_SETTINGS.colorizeDataGridCellTypes,
dataGridTypeColorSchemes, dataGridTypeColorSchemes,
@@ -2614,6 +2628,8 @@ export const useSettingsStore = defineStore("settings", () => {
if (partial.showColumnTypesInHeader !== undefined) editorSettings.value.showColumnTypesInHeader = partial.showColumnTypesInHeader; if (partial.showColumnTypesInHeader !== undefined) editorSettings.value.showColumnTypesInHeader = partial.showColumnTypesInHeader;
if (partial.showColumnHeaderTooltips !== undefined) editorSettings.value.showColumnHeaderTooltips = partial.showColumnHeaderTooltips; if (partial.showColumnHeaderTooltips !== undefined) editorSettings.value.showColumnHeaderTooltips = partial.showColumnHeaderTooltips;
if (partial.showResultSourceDatabase !== undefined) editorSettings.value.showResultSourceDatabase = partial.showResultSourceDatabase; 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.dataGridShowTransposeFieldMetadata !== undefined) editorSettings.value.dataGridShowTransposeFieldMetadata = partial.dataGridShowTransposeFieldMetadata === true;
if (partial.colorizeDataGridCellTypes !== undefined) editorSettings.value.colorizeDataGridCellTypes = partial.colorizeDataGridCellTypes === true; if (partial.colorizeDataGridCellTypes !== undefined) editorSettings.value.colorizeDataGridCellTypes = partial.colorizeDataGridCellTypes === true;
if (partial.dataGridTypeColorSchemes !== undefined) { if (partial.dataGridTypeColorSchemes !== undefined) {
+6
View File
@@ -1258,6 +1258,8 @@ export interface QueryMessage {
hint?: string; hint?: string;
} }
export type QueryResultSourceLabelKind = "source" | "comment";
export interface QueryResult { export interface QueryResult {
columns: string[]; columns: string[];
/** One SRID per geometry/geography column (first non-null observed). */ /** 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. */ /** Preformatted Redis command output retained alongside the default grid rows. */
redis_console_output?: string; redis_console_output?: string;
sourceLabel?: string; sourceLabel?: string;
/** Identifies whether sourceLabel came from a parsed object source or a SQL preamble comment. */
sourceLabelKind?: QueryResultSourceLabelKind;
/** 结果集来源的库名 / schema(与 sourceLabel 同时写入),供结果集页签按设置决定是否展示。 */ /** 结果集来源的库名 / schema(与 sourceLabel 同时写入),供结果集页签按设置决定是否展示。 */
sourceQualifier?: string; sourceQualifier?: string;
/** 结果集来源的对象名(通常为表名),关闭“结果集名称包含数据库名”时用于展示短名称。 */ /** 结果集来源的对象名(通常为表名),关闭“结果集名称包含数据库名”时用于展示短名称。 */
@@ -1433,6 +1437,8 @@ export interface QueryResultRun {
*/ */
sourceLabel?: string; sourceLabel?: string;
sourceName?: 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 * Logical-result identity for the tab-switch view snapshot cache. Distinct
* from `resultGridRevision` (the grid remount key): this one changes on every * from `resultGridRevision` (the grid remount key): this one changes on every