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(toolbar): redesign query result toolbar layout
二丫讲梵add57d3ae05c
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vueindex 96257cb41c..e8a105149a 100644--- a/apps/desktop/src/App.vue+++ b/apps/desktop/src/App.vue@@ -1918,7 +1918,7 @@ onUnmounted(() => {@editor-selection-state-change="(tabId: string, selection: { anchor: number; head: number }) => queryStore.updateEditorSelection(tabId, selection)"@format-error="toast(t('toolbar.formatSqlFailed'))"@save-sql="void openSaveSqlDialog()"- @reload="(sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number) => onReloadData(sql, searchText, whereInput, orderBy, limit, offset)"+ @reload="(sql, searchText, whereInput, orderBy, limit, offset, intent) => onReloadData(sql, searchText, whereInput, orderBy, limit, offset, intent)"@paginate="onPaginate"@sort="onSort"@execute-sql="onExecuteSql"diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vueindex e5cc33d356..2938ddc591 100644--- a/apps/desktop/src/components/grid/DataGrid.vue+++ b/apps/desktop/src/components/grid/DataGrid.vue@@ -177,6 +177,7 @@ import { useConnectionStore } from "@/stores/connectionStore";import { useQueryStore } from "@/stores/queryStore";import { useSettingsStore } from "@/stores/settingsStore";import type { DataGridSortDirection, DataGridSortMode } from "@/lib/dataGrid/dataGridSort";+import { DATA_GRID_COMPACT_TOPBAR_WIDTH, type DataGridReloadIntent } from "@/lib/dataGrid/dataGridToolbar";import { getTableMetadataCapabilities } from "@/lib/table/tableMetadataCapabilities";import { getTableStructureCapabilities } from "@/lib/table/tableStructureCapabilities";import { supportsTableStructureEditing } from "@/lib/database/databaseCapabilities";@@ -280,7 +281,6 @@ const dataGridElapsed = () => `${Math.round(performance.now() - dataGridCreatedAconst isMac = isMacOS();const shortcutMod = isMac ? "Cmd" : "Ctrl";const saveShortcutLabel = computed(() => formatShortcut(settingsStore.editorSettings.shortcuts.saveSql));-const DATA_GRID_COMPACT_TOPBAR_WIDTH = 900;const AUTO_REFRESH_INTERVAL_OPTIONS = [5, 10, 30, 60, 300];function logDataGridTiming(message: string, payload?: Record<string, unknown>) {@@ -288,7 +288,7 @@ function logDataGridTiming(message: string, payload?: Record<string, unknown>) {}const emit = defineEmits<{- reload: [sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number];+ reload: [sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number, intent?: DataGridReloadIntent];paginate: [offset: number, limit: number, whereInput?: string, orderBy?: string];sort: [column: string, columnIndex: number, direction: "asc" | "desc" | null, whereInput?: string, mode?: DataGridSortMode];"update:whereInput": [value: string];@@ -4063,6 +4063,8 @@ const saveToolbarState = computed(() =>}),);const hasSearchBarSlot = computed(() => !!slots["search-bar"]);+const hasResultToolbarLeadingSlot = computed(() => !!slots["result-toolbar-leading"]);+const hasResultToolbarActionsSlot = computed(() => !!slots["result-toolbar-actions"]);const quickEntryEnabled = computed(() => settingsStore.editorSettings.dataGridQuickEntry);const showQuickEntryDraftRow = computed(() =>shouldShowQuickEntryDraftRow({@@ -4079,6 +4081,8 @@ const showDataGridTopbar = computed(hasLocalColumnFilters.value ||canShowWhereSearch.value ||hasSearchBarSlot.value ||+ hasResultToolbarLeadingSlot.value ||+ hasResultToolbarActionsSlot.value ||showQueryEditReadOnlyBadge.value ||props.context !== "results" ||(!!props.editable && hasDataGridSaveTarget.value) ||@@ -4236,7 +4240,7 @@ async function onToolbarRefresh() {}preserveTransposeOnNextResult.value = showTranspose.value;isRefreshingData.value = true;- emit("reload", props.sql, searchText.value, currentWhereInput(), currentOrderBy(), pageSize.value, (currentPage.value - 1) * pageSize.value);+ emit("reload", props.sql, searchText.value, currentWhereInput(), currentOrderBy(), pageSize.value, (currentPage.value - 1) * pageSize.value, "refresh");}function stopAutoRefreshTimer() {@@ -8731,6 +8735,9 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {<div v-if="hasData || canShowWhereSearch" class="flex-1 flex flex-col overflow-hidden" @contextmenu="onContextMenu"><!-- Search bar --><div ref="dataGridTopbarRef" v-if="showDataGridTopbar" class="data-grid-topbar-shell shrink-0 flex min-w-0 border-b bg-muted/20">+ <div v-if="hasResultToolbarLeadingSlot" class="flex shrink-0 items-center border-r">+ <slot name="result-toolbar-leading" :compact="compactDataGridToolbar" />+ </div><divclass="data-grid-topbar-scroll min-w-0 flex-1 overflow-x-hidden"@scroll="@@ -9159,6 +9166,7 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {</div><div class="flex shrink-0 items-center gap-1 px-1 ml-auto" @wheel="onDataGridTopbarFixedActionWheel">+ <slot v-if="hasResultToolbarActionsSlot" name="result-toolbar-actions" :compact="compactDataGridToolbar" /><Tooltip v-if="showQueryEditReadOnlyBadge"><TooltipTrigger as-child><div class="flex h-5 items-center gap-1 rounded border border-muted-foreground/30 bg-muted/60 px-1.5 text-xs font-medium text-muted-foreground">@@ -11460,9 +11468,12 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {}.data-grid-topbar-action-button {+ align-items: center;+ justify-content: center;max-width: 9rem;min-width: 1.25rem;gap: 0;+ line-height: 1;overflow: hidden;transition:max-width var(--data-grid-topbar-transition-duration) var(--data-grid-topbar-transition-easing),@@ -11484,6 +11495,8 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {}.data-grid-topbar-action-icon {+ display: block;+ align-self: center;flex-shrink: 0;transition:margin-inline-end var(--data-grid-topbar-transition-duration) var(--data-grid-topbar-transition-easing),@@ -11507,10 +11520,13 @@ const gridContextMenuItems = computed<ContextMenuItem[]>(() => {}.data-grid-topbar-action-label {- display: inline-block;+ display: inline-flex;+ align-items: center;+ height: 1rem;max-width: 8rem;overflow: hidden;white-space: nowrap;+ line-height: 1;opacity: 1;transform: translateX(0);transition:diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vueindex 28d8af1d4a..bc433bd459 100644--- a/apps/desktop/src/components/layout/ContentArea.vue+++ b/apps/desktop/src/components/layout/ContentArea.vue@@ -5,7 +5,7 @@ import { appendDebugLog, isDebugLoggingEnabled } from "@/lib/backend/debugLog";import { canReloadUnavailableDataTab } from "@/lib/table/tableDataRefresh";import type { CSSProperties } from "vue";import { useI18n } from "vue-i18n";-import { Check, Columns3, Columns3Cog, EyeOff, Loader2, Search, GitBranch, BarChart3, TableProperties, ChevronDown, ChevronUp, Inbox, RefreshCcw, Timer, Wrench, Toolbox, ListChecks, Database, Download, Upload, X, Pin, Rows3, SquareDashed, Minus, Plus } from "@lucide/vue";+import { Check, Columns3, Columns3Cog, EyeOff, Loader2, Search, TableProperties, ChevronDown, ChevronUp, Inbox, RefreshCcw, Wrench, Toolbox, Database, Download, Upload, X, Pin, Rows3, SquareDashed, Minus, Plus } from "@lucide/vue";import { Splitpanes, Pane } from "splitpanes";import "splitpanes/dist/splitpanes.css";import { Button } from "@/components/ui/button";@@ -17,6 +17,8 @@ import QueryEditor from "@/components/editor/QueryEditor.vue";import ColumnInfoPanel from "@/components/editor/ColumnInfoPanel.vue";import QueryLoadingState from "@/components/common/QueryLoadingState.vue";import QueryErrorActions from "@/components/common/QueryErrorActions.vue";+import QueryResultToolbarActions from "@/components/layout/QueryResultToolbarActions.vue";+import QueryResultViewSwitcher from "@/components/layout/QueryResultViewSwitcher.vue";import type { ColumnInfo } from "@/components/editor/ColumnInfoPanel.vue";let dataGridComponentPromise: Promise<typeof import("@/components/grid/DataGrid.vue")> | undefined;function loadDataGridComponent() {@@ -59,7 +61,7 @@ import { useConnectionStore } from "@/stores/connectionStore";import { TABLE_FONT_SIZE_MAX, TABLE_FONT_SIZE_MIN, useSettingsStore, type DataGridSearchMode } from "@/stores/settingsStore";import { useToast } from "@/composables/useToast";import { canCancelQueryExecution, queryExecutionLabelKey } from "@/lib/sql/queryExecutionState";-import { databaseDisplayNameForTab, executionSummaryItems, nextExecutionSummaryView, resultGridCacheKey, resultRunItems, resultSqlForGrid, tabularResultItems } from "@/lib/tabs/tabPresentation";+import { databaseDisplayNameForTab, executionSummaryItems, resultGridCacheKey, resultRunItems, resultSqlForGrid, tabularResultItems } from "@/lib/tabs/tabPresentation";import { defaultQueryResultArchiveFileName } from "@/lib/query/queryResultArchive";import { saveQueryResultArchiveFile } from "@/lib/query/queryResultArchiveFile";import { isTableDataEditable } from "@/lib/table/tableEditing";@@ -72,8 +74,8 @@ import * as api from "@/lib/backend/api";import { applyMongoGridChangesToDocument, buildMongoUpdateDocument, formatMongoShellLiteral, type MongoInputValue } from "@/lib/mongo/mongoDocumentValues";import type { SqlExecutionOverride } from "@/lib/sql/sqlExecutionTarget";import type { DataGridSortMode } from "@/lib/dataGrid/dataGridSort";+import { DATA_GRID_COMPACT_TOPBAR_WIDTH, type DataGridReloadIntent } from "@/lib/dataGrid/dataGridToolbar";import { useTabScroll } from "@/composables/useTabScroll";-import { nextResultToolbarLayout } from "@/lib/tabs/resultToolbarLayout";import { formatElapsedSeconds } from "@/lib/common/elapsedTime";import type { CustomSaveHandler } from "@/composables/useDataGridEditor";import type { QueryTab, ConnectionConfig, TableInfoTab, TreeNode, VectorCollectionMeta, ObjectBrowserViewport } from "@/types/database";@@ -137,7 +139,7 @@ const emit = defineEmits<{editorViewportChange: [tabId: string, viewport: { scrollTop: number; scrollLeft: number }];editorSelectionStateChange: [tabId: string, selection: { anchor: number; head: number }];formatError: [];- reload: [sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number];+ reload: [sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number, intent?: DataGridReloadIntent];paginate: [offset: number, limit: number, whereInput?: string, orderBy?: string];sort: [column: string, columnIndex: number, direction: "asc" | "desc" | null, whereInput?: string, mode?: DataGridSortMode];executeSql: [sql: string];@@ -154,7 +156,7 @@ const emit = defineEmits<{openConnectionSettings: [connectionId: string, initialTab: "advanced"];}>();-const { t, locale } = useI18n();+const { t } = useI18n();const queryStore = useQueryStore();const connectionStore = useConnectionStore();const settingsStore = useSettingsStore();@@ -186,7 +188,8 @@ const columnInfoLoading = ref(false);const columnInfoError = ref<string | undefined>(undefined);const dataGridRef = ref<DataGridHandle>();const queryEditorRef = ref<InstanceType<typeof QueryEditor>>();-const resultToolbarRef = ref<HTMLElement | null>(null);+const standaloneResultToolbarRef = ref<HTMLElement | null>(null);+const standaloneResultToolbarWidth = ref(0);const resultTabsScrollerRef = ref<HTMLElement | null>(null);const columnVisibilitySearch = ref("");const columnVisibilityOptions = computed(() => dataGridRef.value?.filteredColumnVisibilityOptions(columnVisibilitySearch.value) ?? []);@@ -313,11 +316,7 @@ const activeResultSql = computed(() => resultSqlForGrid(props.activeTab));const resultArchiveExporting = ref(false);const canExportResultArchive = computed(() => props.activeTab.mode === "query" && (!!props.activeTab.result || !!props.activeTab.results?.length || !!props.activeTab.resultRuns?.length));const resultAutoSave = computed(() => props.activeTab.resultAutoSave === true);-const QUERY_RESULT_AUTO_REFRESH_INTERVAL_OPTIONS = [5, 10, 30, 60, 300];-const queryResultAutoRefreshIntervalSeconds = ref(10);-const queryResultAutoRefreshEnabled = ref(false);-let queryResultAutoRefreshTimer: ReturnType<typeof setInterval> | undefined;-const queryResultAutoRefreshLabel = computed(() => (queryResultAutoRefreshEnabled.value ? t("tabs.autoRefreshEvery", { seconds: queryResultAutoRefreshIntervalSeconds.value }) : t("tabs.autoRefresh")));+const showResultRunSelector = computed(() => resultAutoSave.value && resultRuns.value.length > 0);watch(() => visibleResultItems.value.map((item) => item.index).join(","),() => {@@ -331,80 +330,25 @@ const hasTabularResult = computed(() => {return visibleResultItems.value.length > 0;});const canShowResultOutput = computed(() => hasTabularResult.value || props.activeTab.isExecuting);-const resultToolbarCompact = ref(false);-const resultToolbarExpandedRequiredWidth = ref<number>();-let resultToolbarResizeObserver: ResizeObserver | undefined;-let resultToolbarLayoutFrame = 0;--function updateResultToolbarLayout() {- const toolbar = resultToolbarRef.value;- const tabs = resultTabsScrollerRef.value;- if (!toolbar || !tabs) return;-- const next = nextResultToolbarLayout({- resultCount: visibleResultItems.value.length,- compact: resultToolbarCompact.value,- expandedRequiredWidth: resultToolbarExpandedRequiredWidth.value,- toolbarWidth: toolbar.clientWidth,- tabsViewportWidth: tabs.clientWidth,- tabsContentWidth: tabs.scrollWidth,- });- const compactChanged = next.compact !== resultToolbarCompact.value;- resultToolbarCompact.value = next.compact;- resultToolbarExpandedRequiredWidth.value = next.expandedRequiredWidth;- if (compactChanged) {- nextTick(() => {- updateResultTabsScrollbar();- scheduleResultToolbarLayout();+const canShowExplainOutput = computed(() => !!props.activeTab.explainPlan || !!props.activeTab.explainError || !!props.activeTab.explainTableResult || !!props.activeTab.explainTableError || props.activeTab.isExplaining === true);+const showStandaloneResultToolbar = computed(() => props.activeOutputView !== "result" || !props.activeTab.result || !hasTabularResult.value);+const standaloneResultToolbarCompact = computed(() => standaloneResultToolbarWidth.value > 0 && standaloneResultToolbarWidth.value < DATA_GRID_COMPACT_TOPBAR_WIDTH);+let standaloneResultToolbarResizeObserver: ResizeObserver | undefined;++function observeStandaloneResultToolbar() {+ standaloneResultToolbarResizeObserver?.disconnect();+ standaloneResultToolbarResizeObserver = undefined;+ const toolbar = standaloneResultToolbarRef.value;+ standaloneResultToolbarWidth.value = toolbar?.clientWidth ?? 0;+ if (toolbar && typeof ResizeObserver !== "undefined") {+ standaloneResultToolbarResizeObserver = new ResizeObserver(() => {+ standaloneResultToolbarWidth.value = toolbar.clientWidth;});+ standaloneResultToolbarResizeObserver.observe(toolbar);}}-function scheduleResultToolbarLayout() {- if (resultToolbarLayoutFrame) return;- resultToolbarLayoutFrame = window.requestAnimationFrame(() => {- resultToolbarLayoutFrame = 0;- updateResultToolbarLayout();- });-}--function resetResultToolbarLayout() {- resultToolbarCompact.value = false;- resultToolbarExpandedRequiredWidth.value = undefined;- nextTick(() => {- updateResultTabsScrollbar();- scheduleResultToolbarLayout();- });-}--function observeResultToolbarLayout() {- resultToolbarResizeObserver?.disconnect();- resultToolbarResizeObserver = undefined;- const toolbar = resultToolbarRef.value;- const tabs = resultTabsScrollerRef.value;- if (typeof ResizeObserver !== "undefined" && toolbar && tabs) {- resultToolbarResizeObserver = new ResizeObserver(scheduleResultToolbarLayout);- resultToolbarResizeObserver.observe(toolbar);- resultToolbarResizeObserver.observe(tabs);- }- scheduleResultToolbarLayout();-}--const resultToolbarLayoutSignature = computed(() =>- JSON.stringify({- locale: locale.value,- results: visibleResultItems.value.map((item) => [item.index, item.label, item.n]),- outputView: props.activeOutputView,- canExportResultArchive: canExportResultArchive.value,- hasResult: !!props.activeTab.result,- hasTabularResult: hasTabularResult.value,- autoRefreshEnabled: queryResultAutoRefreshEnabled.value,- autoRefreshInterval: queryResultAutoRefreshIntervalSeconds.value,- }),-);--watch([resultToolbarRef, resultTabsScrollerRef], observeResultToolbarLayout, { flush: "post" });-watch(resultToolbarLayoutSignature, resetResultToolbarLayout, { flush: "post" });+watch(standaloneResultToolbarRef, observeStandaloneResultToolbar, { flush: "post" });type MongoQueryGridChanges = {dirtyRows: Map<number, Map<number, MongoInputValue>>;deletedRows: Set<number>;@@ -482,7 +426,6 @@ const resultsPaneOpen = ref(false);const resultsPaneSize = ref(Number(safeLocalStorageGet("dbx-results-pane-size")) || DEFAULT_QUERY_RESULTS_PANE_SIZE);const editorPaneSize = computed(() => (resultsPaneOpen.value ? 100 - resultsPaneSize.value : 100));const queryRunningElapsed = ref(0);-const canAutoRefreshQueryResult = computed(() => props.activeTab.mode === "query" && props.activeOutputView === "result" && resultsPaneOpen.value && hasTabularResult.value && !props.activeTab.isExecuting);function onResultsResized(payload: { panes: { size: number }[] }) {const resultsPane = payload.panes[1];@@ -524,31 +467,10 @@ watch(() => [props.activeTab.id, props.activeTab.isExecuting, props.activeTab.quonUnmounted(() => {stopQueryRunningElapsedTimer();- stopQueryResultAutoRefreshTimer();- resultToolbarResizeObserver?.disconnect();- if (resultToolbarLayoutFrame) window.cancelAnimationFrame(resultToolbarLayoutFrame);+ standaloneResultToolbarResizeObserver?.disconnect();window.removeEventListener("dbx-refresh-active-kv-browser", onRefreshActiveKvBrowser);});-watch(() => props.activeTab.id, stopQueryResultAutoRefresh);--watch(- () => [props.activeOutputView, resultsPaneOpen.value] as const,- ([outputView, paneOpen]) => {- if (outputView !== "result" || !paneOpen) stopQueryResultAutoRefresh();- },-);--watch(canAutoRefreshQueryResult, (canRefresh) => {- if (!queryResultAutoRefreshEnabled.value) return;- if (canRefresh) restartQueryResultAutoRefreshTimer();- else stopQueryResultAutoRefreshTimer();-});--watch(activeQueryError, (message) => {- if (message && queryResultAutoRefreshEnabled.value) stopQueryResultAutoRefresh();-});-watch(hasQueryOutput,(hasOutput) => {@@ -734,37 +656,6 @@ function focusSearch(): boolean {return dataGridRef.value?.focusSearch() ?? false;}-function stopQueryResultAutoRefreshTimer() {- clearInterval(queryResultAutoRefreshTimer);- queryResultAutoRefreshTimer = undefined;-}--function runQueryResultAutoRefreshTick() {- if (!queryResultAutoRefreshEnabled.value || !canAutoRefreshQueryResult.value) return;- refreshData();-}--function restartQueryResultAutoRefreshTimer() {- stopQueryResultAutoRefreshTimer();- if (!queryResultAutoRefreshEnabled.value || !canAutoRefreshQueryResult.value) return;- queryResultAutoRefreshTimer = setInterval(runQueryResultAutoRefreshTick, queryResultAutoRefreshIntervalSeconds.value * 1000);-}--function setQueryResultAutoRefreshInterval(seconds: number) {- queryResultAutoRefreshIntervalSeconds.value = seconds;- if (queryResultAutoRefreshEnabled.value) restartQueryResultAutoRefreshTimer();-}--function toggleQueryResultAutoRefresh() {- queryResultAutoRefreshEnabled.value = !queryResultAutoRefreshEnabled.value;- restartQueryResultAutoRefreshTimer();-}--function stopQueryResultAutoRefresh() {- queryResultAutoRefreshEnabled.value = false;- stopQueryResultAutoRefreshTimer();-}-function refreshData(): boolean {if (props.activeTab.mode === "etcd") return etcdKeyBrowserRef.value?.refresh?.() ?? false;if (props.activeTab.mode === "zookeeper") return zookeeperKeyBrowserRef.value?.refresh?.() ?? false;@@ -802,10 +693,6 @@ async function exportResultArchive() {}}-function toggleExecutionSummary() {- emit("update:activeOutputView", nextExecutionSummaryView(props.activeOutputView, canShowResultOutput.value));-}-async function removeResultRun(runId: string) {const removedActiveRun = props.activeTab.activeResultRunId === runId;const removed = await queryStore.removeResultRun(props.activeTab.id, runId);@@ -891,18 +778,13 @@ defineExpose({ focusSearch, refreshData, handleModRTarget, requestQueryEditorExe</Pane><Pane v-if="resultsPaneOpen" class="min-h-0" :size="resultsPaneSize" :min-size="20"><div class="h-full flex flex-col">- <div v-if="hasQueryOutput" ref="resultToolbarRef" class="flex h-10 shrink-0 items-center gap-1 border-b bg-muted/20 px-2">- <div class="flex shrink-0 items-center gap-1">- <Button size="sm" :variant="activeOutputView === 'result' ? 'secondary' : 'ghost'" class="h-6 px-2 text-xs" :disabled="!hasTabularResult && !activeTab.isExecuting" @click="emit('update:activeOutputView', 'result')">- {{ t("tabs.tableData") }}- </Button>- </div>+ <div v-if="hasQueryOutput" class="flex h-10 shrink-0 items-center gap-1 border-b bg-muted/20 px-2"><Buttonv-if="activeTab.mode === 'query' && activeTab.result"variant="ghost"size="icon"- class="h-6 w-7 shrink-0 text-muted-foreground hover:text-foreground"- :class="{ 'text-primary': resultAutoSave }"+ class="h-6 w-7 shrink-0"+ :class="resultAutoSave ? 'bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary' : 'text-muted-foreground hover:bg-accent hover:text-foreground'":title="resultAutoSave ? t('tabs.autoKeepResultsEnabled') : t('tabs.autoKeepResults')":aria-label="resultAutoSave ? t('tabs.autoKeepResultsEnabled') : t('tabs.autoKeepResults')":aria-pressed="resultAutoSave"@@ -910,7 +792,7 @@ defineExpose({ focusSearch, refreshData, handleModRTarget, requestQueryEditorExe><Pin class="h-3.5 w-3.5" :class="{ 'fill-current': resultAutoSave }" /></Button>- <template v-if="resultRuns.length > 0">+ <template v-if="showResultRunSelector"><span class="mx-1 h-4 w-px shrink-0 bg-border" /><DropdownMenu><DropdownMenuTrigger as-child>@@ -961,71 +843,8 @@ defineExpose({ focusSearch, refreshData, handleModRTarget, requestQueryEditorExe</div></div></template>- <div class="ml-auto flex shrink-0 items-center gap-1" :data-compact="resultToolbarCompact || undefined">- <LightTooltip :text="t('tabs.executionSummary')" :disabled="!resultToolbarCompact" side="bottom" :delay="0" :close-delay="0" nowrap>- <Button- size="sm"- :variant="activeOutputView === 'summary' ? 'secondary' : 'ghost'"- class="h-6 text-xs"- :class="resultToolbarCompact ? 'w-7 gap-0 px-0' : 'gap-1 px-2'"- :title="t('tabs.executionSummary')"- :aria-label="t('tabs.executionSummary')"- :disabled="!hasExecutionSummary"- @click="toggleExecutionSummary"- >- <ListChecks class="h-3.5 w-3.5" />- <span v-if="!resultToolbarCompact">{{ t("tabs.executionSummary") }}</span>- </Button>- </LightTooltip>- <LightTooltip :text="t('chart.title')" :disabled="!resultToolbarCompact" side="bottom" :delay="0" :close-delay="0" nowrap>- <Button- size="sm"- :variant="activeOutputView === 'chart' ? 'secondary' : 'ghost'"- class="h-6 text-xs"- :class="resultToolbarCompact ? 'w-7 gap-0 px-0' : 'gap-1 px-2'"- :title="t('chart.title')"- :aria-label="t('chart.title')"- :disabled="!hasNumericData"- @click="emit('update:activeOutputView', 'chart')"- >- <BarChart3 class="h-3.5 w-3.5" />- <span v-if="!resultToolbarCompact">{{ t("chart.title") }}</span>- </Button>- </LightTooltip>- <span class="mx-1 h-4 w-px shrink-0 bg-border" />- <LightTooltip :text="t('explain.title')" :disabled="!resultToolbarCompact" side="bottom" :delay="0" :close-delay="0" nowrap>- <Button- size="sm"- :variant="activeOutputView === 'explain' ? 'secondary' : 'ghost'"- class="h-6 text-xs"- :class="resultToolbarCompact ? 'w-7 gap-0 px-0' : 'gap-1 px-2'"- :title="t('explain.title')"- :aria-label="t('explain.title')"- :disabled="!activeTab.explainPlan && !activeTab.explainError && !activeTab.explainTableResult && !activeTab.explainTableError && !activeTab.isExplaining"- @click="emit('update:activeOutputView', 'explain')"- >- <GitBranch class="h-3.5 w-3.5" />- <span v-if="!resultToolbarCompact">{{ t("explain.title") }}</span>- </Button>- </LightTooltip>- <LightTooltip v-if="canExportResultArchive" :text="t('tabs.exportResultArchive')" :disabled="!resultToolbarCompact" side="bottom" :delay="0" :close-delay="0" nowrap>- <Button- variant="ghost"- size="sm"- class="h-6 shrink-0 text-xs text-muted-foreground hover:text-foreground"- :class="resultToolbarCompact ? 'w-7 gap-0 px-0' : 'gap-1 px-2'"- :title="t('tabs.exportResultArchive')"- :aria-label="t('tabs.exportResultArchive')"- :aria-busy="resultArchiveExporting"- :disabled="resultArchiveExporting"- @click="exportResultArchive"- >- <Loader2 v-if="resultArchiveExporting" class="h-3.5 w-3.5 animate-spin" />- <Upload v-else class="h-3.5 w-3.5" />- <span v-if="!resultToolbarCompact">{{ t("tabs.exportResultArchive") }}</span>- </Button>- </LightTooltip>- <Popover v-if="activeOutputView === 'result' && activeTab.result">+ <div class="ml-auto flex shrink-0 items-center gap-1">+ <Popover v-if="activeOutputView === 'result' && activeTab.result && hasTabularResult"><PopoverTrigger as-child><Button variant="ghost" size="icon" class="h-6 w-7 shrink-0 text-foreground hover:bg-accent" :title="t('grid.viewOptions')" :aria-label="t('grid.viewOptions')"><Wrench class="h-4 w-4" />@@ -1168,72 +987,28 @@ defineExpose({ focusSearch, refreshData, handleModRTarget, requestQueryEditorExe</div></PopoverContent></Popover>- <div v-if="activeOutputView === 'result' && hasTabularResult" class="flex h-6 shrink-0 items-center">- <LightTooltip :text="t('grid.refresh')" :disabled="!resultToolbarCompact" side="bottom" :delay="0" :close-delay="0" nowrap>- <Button- variant="ghost"- size="sm"- class="h-6 rounded-r-none text-xs text-muted-foreground hover:text-foreground"- :class="resultToolbarCompact ? 'w-7 gap-0 px-0' : 'gap-1 px-2'"- :title="t('grid.refresh')"- :aria-label="t('grid.refresh')"- :aria-busy="activeTab.isExecuting"- :disabled="activeTab.isExecuting"- @click="refreshData"- >- <Loader2 v-if="activeTab.isExecuting" class="h-3.5 w-3.5 animate-spin" />- <RefreshCcw v-else class="h-3.5 w-3.5" />- <span v-if="!resultToolbarCompact">{{ t("grid.refresh") }}</span>- </Button>- </LightTooltip>- <LightTooltip :text="queryResultAutoRefreshLabel" :disabled="!resultToolbarCompact" side="bottom" :delay="0" :close-delay="0" nowrap>- <DropdownMenu>- <DropdownMenuTrigger as-child>- <Button- variant="ghost"- size="sm"- class="h-6 rounded-l-none border-l border-border/60 text-xs"- :class="[resultToolbarCompact ? 'w-7 gap-0 px-0' : 'px-1.5', queryResultAutoRefreshEnabled ? 'bg-primary/10 text-primary hover:bg-primary/15' : 'text-muted-foreground hover:text-foreground']"- :title="queryResultAutoRefreshLabel"- :aria-label="queryResultAutoRefreshLabel"- :aria-pressed="queryResultAutoRefreshEnabled"- >- <Timer class="h-3.5 w-3.5" />- <span v-if="!resultToolbarCompact" class="tabular-nums">{{ queryResultAutoRefreshEnabled ? `${queryResultAutoRefreshIntervalSeconds}s` : t("tabs.autoRefreshShort") }}</span>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" class="w-40">- <DropdownMenuItem class="gap-2" @select="toggleQueryResultAutoRefresh">- <Check v-if="queryResultAutoRefreshEnabled" class="h-3.5 w-3.5" />- <span v-else class="h-3.5 w-3.5" />- {{ queryResultAutoRefreshEnabled ? t("tabs.stopAutoRefresh") : t("tabs.startAutoRefresh") }}- </DropdownMenuItem>- <DropdownMenuItem v-for="seconds in QUERY_RESULT_AUTO_REFRESH_INTERVAL_OPTIONS" :key="seconds" class="gap-2" @select="setQueryResultAutoRefreshInterval(seconds)">- <Check v-if="queryResultAutoRefreshIntervalSeconds === seconds" class="h-3.5 w-3.5" />- <span v-else class="h-3.5 w-3.5" />- {{ t("tabs.autoRefreshEvery", { seconds }) }}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </LightTooltip>- </div>- <LightTooltip :text="t('editor.hideResultsPane')" :disabled="!resultToolbarCompact" side="bottom" :delay="0" :close-delay="0" nowrap>- <Button- variant="ghost"- size="sm"- class="h-6 shrink-0 text-xs text-muted-foreground hover:text-foreground"- :class="resultToolbarCompact ? 'w-7 gap-0 px-0' : 'gap-1 px-2'"- :title="t('editor.hideResultsPane')"- :aria-label="t('editor.hideResultsPane')"- @click="resultsPaneOpen = false"- >+ <LightTooltip :text="t('editor.hideResultsPane')" side="bottom" :delay="0" :close-delay="0" nowrap>+ <Button variant="ghost" size="icon" class="h-6 w-7 shrink-0 text-muted-foreground hover:text-foreground" :title="t('editor.hideResultsPane')" :aria-label="t('editor.hideResultsPane')" @click="resultsPaneOpen = false"><ChevronDown class="h-3.5 w-3.5" />- <span v-if="!resultToolbarCompact">{{ t("editor.hideResultsPane") }}</span></Button></LightTooltip></div></div>+ <div v-if="hasQueryOutput && showStandaloneResultToolbar" ref="standaloneResultToolbarRef" class="flex min-h-7 shrink-0 items-center border-b bg-muted/20">+ <QueryResultViewSwitcher :active-view="activeOutputView" :can-show-result="canShowResultOutput" :can-show-summary="hasExecutionSummary" :can-show-chart="hasNumericData" :compact="standaloneResultToolbarCompact" @select-view="emit('update:activeOutputView', $event)" />+ <QueryResultToolbarActions+ class="ml-auto"+ :active-view="activeOutputView"+ :can-show-explain="canShowExplainOutput"+ :can-export-archive="canExportResultArchive"+ :archive-exporting="resultArchiveExporting"+ :compact="standaloneResultToolbarCompact"+ @select-explain="emit('update:activeOutputView', 'explain')"+ @export-archive="exportResultArchive"+ />+ </div>+<ExplainPlanViewerv-if="activeOutputView === 'explain'"class="flex-1 min-h-0"@@ -1322,10 +1097,24 @@ defineExpose({ focusSearch, refreshData, handleModRTarget, requestQueryEditorExe:all-export-results="allResultExportSheets":export-file-base-name="activeTab.title"@update:order-by-input="(v: string) => (activeTab.orderByInput = v)"- @reload="(sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number) => emit('reload', sql, searchText, whereInput, orderBy, limit, offset)"+ @reload="(sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number, intent?: DataGridReloadIntent) => emit('reload', sql, searchText, whereInput, orderBy, limit, offset, intent)"@paginate="(offset: number, limit: number, whereInput?: string, orderBy?: string) => emit('paginate', offset, limit, whereInput, orderBy)"@sort="(column: string, columnIndex: number, direction: 'asc' | 'desc' | null, whereInput?: string, mode?: DataGridSortMode) => emit('sort', column, columnIndex, direction, whereInput, mode)">+ <template #result-toolbar-leading="{ compact }">+ <QueryResultViewSwitcher :active-view="activeOutputView" :can-show-result="canShowResultOutput" :can-show-summary="hasExecutionSummary" :can-show-chart="hasNumericData" :compact="compact" @select-view="emit('update:activeOutputView', $event)" />+ </template>+ <template #result-toolbar-actions="{ compact }">+ <QueryResultToolbarActions+ :active-view="activeOutputView"+ :can-show-explain="canShowExplainOutput"+ :can-export-archive="canExportResultArchive"+ :archive-exporting="resultArchiveExporting"+ :compact="compact"+ @select-explain="emit('update:activeOutputView', 'explain')"+ @export-archive="exportResultArchive"+ />+ </template><template v-if="activeTab.result?.columns.includes('Error')" #error-actions="{ errorMessage }"><QueryErrorActions :error-message="String(errorMessage)" :connection-id="activeTab.connectionId" @change-query-timeout="activeTab.connectionId && emit('openConnectionSettings', activeTab.connectionId, 'advanced')" @fix-with-ai="(message) => emit('fixWithAi', message)" /></template>@@ -1623,7 +1412,7 @@ defineExpose({ focusSearch, refreshData, handleModRTarget, requestQueryEditorExe:export-file-base-name="activeTab.title"@update:where-input="(v: string) => (activeTab.whereInput = v)"@update:order-by-input="(v: string) => (activeTab.orderByInput = v)"- @reload="(sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number) => emit('reload', sql, searchText, whereInput, orderBy, limit, offset)"+ @reload="(sql?: string, searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number, intent?: DataGridReloadIntent) => emit('reload', sql, searchText, whereInput, orderBy, limit, offset, intent)"@paginate="(offset: number, limit: number, whereInput?: string, orderBy?: string) => emit('paginate', offset, limit, whereInput, orderBy)"@sort="(column: string, columnIndex: number, direction: 'asc' | 'desc' | null, whereInput?: string, mode?: DataGridSortMode) => emit('sort', column, columnIndex, direction, whereInput, mode)">diff --git a/apps/desktop/src/components/layout/QueryResultToolbarActions.vue b/apps/desktop/src/components/layout/QueryResultToolbarActions.vuenew file mode 100644index 0000000000..caa264b4b4--- /dev/null+++ b/apps/desktop/src/components/layout/QueryResultToolbarActions.vue@@ -0,0 +1,65 @@+<script setup lang="ts">+import { GitBranch, Loader2, Upload } from "@lucide/vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import LightTooltip from "@/components/ui/LightTooltip.vue";++type OutputView = "result" | "summary" | "explain" | "chart";++withDefaults(+ defineProps<{+ activeView: OutputView;+ canShowExplain: boolean;+ canExportArchive: boolean;+ archiveExporting: boolean;+ compact?: boolean;+ }>(),+ { compact: false },+);++const emit = defineEmits<{+ selectExplain: [];+ exportArchive: [];+}>();++const { t } = useI18n();+</script>++<template>+ <div data-query-result-toolbar-actions class="flex shrink-0 items-center gap-1 border-r px-1">+ <LightTooltip :text="t('explain.title')" :disabled="!compact" side="bottom" :delay="0" :close-delay="0" nowrap>+ <Button+ size="sm"+ :variant="activeView === 'explain' ? 'secondary' : 'ghost'"+ class="h-5 shrink-0 text-xs leading-none"+ :class="compact ? 'w-6 gap-0 px-0' : 'gap-1 px-2'"+ :title="t('explain.title')"+ :aria-label="t('explain.title')"+ :aria-pressed="activeView === 'explain'"+ :disabled="!canShowExplain"+ @click="emit('selectExplain')"+ >+ <GitBranch class="block h-3.5 w-3.5 self-center" />+ <span v-if="!compact" class="inline-flex h-4 items-center leading-none">{{ t("explain.title") }}</span>+ </Button>+ </LightTooltip>++ <LightTooltip v-if="canExportArchive" :text="t('tabs.exportResultArchive')" :disabled="!compact" side="bottom" :delay="0" :close-delay="0" nowrap>+ <Button+ variant="ghost"+ size="sm"+ class="h-5 shrink-0 text-xs leading-none text-muted-foreground hover:text-foreground"+ :class="compact ? 'w-6 gap-0 px-0' : 'gap-1 px-2'"+ :title="t('tabs.exportResultArchive')"+ :aria-label="t('tabs.exportResultArchive')"+ :aria-busy="archiveExporting"+ :disabled="archiveExporting"+ @click="emit('exportArchive')"+ >+ <Loader2 v-if="archiveExporting" class="block h-3.5 w-3.5 self-center animate-spin" />+ <Upload v-else class="block h-3.5 w-3.5 self-center" />+ <span v-if="!compact" class="inline-flex h-4 items-center leading-none">{{ t("tabs.exportResultArchive") }}</span>+ </Button>+ </LightTooltip>+ </div>+</template>diff --git a/apps/desktop/src/components/layout/QueryResultViewSwitcher.vue b/apps/desktop/src/components/layout/QueryResultViewSwitcher.vuenew file mode 100644index 0000000000..e90347c2a9--- /dev/null+++ b/apps/desktop/src/components/layout/QueryResultViewSwitcher.vue@@ -0,0 +1,73 @@+<script setup lang="ts">+import { BarChart3, ListChecks } from "@lucide/vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import LightTooltip from "@/components/ui/LightTooltip.vue";++type OutputView = "result" | "summary" | "explain" | "chart";+type PrimaryResultView = Exclude<OutputView, "explain">;++const props = withDefaults(+ defineProps<{+ activeView: OutputView;+ canShowResult: boolean;+ canShowSummary: boolean;+ canShowChart: boolean;+ compact?: boolean;+ }>(),+ { compact: false },+);++const emit = defineEmits<{+ selectView: [view: PrimaryResultView];+}>();++const { t } = useI18n();++function selectView(view: PrimaryResultView) {+ if (props.activeView === view) return;+ emit("selectView", view);+}+</script>++<template>+ <div data-query-result-view-switcher class="flex shrink-0 items-center gap-1 px-1">+ <Button size="sm" :variant="activeView === 'result' ? 'secondary' : 'ghost'" class="h-5 shrink-0 px-2 text-xs leading-none" :disabled="!canShowResult" :aria-pressed="activeView === 'result'" @click="selectView('result')">+ <span class="inline-flex h-4 items-center leading-none">{{ t("tabs.tableData") }}</span>+ </Button>++ <LightTooltip :text="t('tabs.executionSummary')" :disabled="!compact" side="bottom" :delay="0" :close-delay="0" nowrap>+ <Button+ size="sm"+ :variant="activeView === 'summary' ? 'secondary' : 'ghost'"+ class="h-5 shrink-0 text-xs leading-none"+ :class="compact ? 'w-6 gap-0 px-0' : 'gap-1 px-2'"+ :title="t('tabs.executionSummary')"+ :aria-label="t('tabs.executionSummary')"+ :aria-pressed="activeView === 'summary'"+ :disabled="!canShowSummary"+ @click="selectView('summary')"+ >+ <ListChecks class="block h-3.5 w-3.5 self-center" />+ <span v-if="!compact" class="inline-flex h-4 items-center leading-none">{{ t("tabs.executionSummary") }}</span>+ </Button>+ </LightTooltip>++ <LightTooltip :text="t('chart.title')" :disabled="!compact" side="bottom" :delay="0" :close-delay="0" nowrap>+ <Button+ size="sm"+ :variant="activeView === 'chart' ? 'secondary' : 'ghost'"+ class="h-5 shrink-0 text-xs leading-none"+ :class="compact ? 'w-6 gap-0 px-0' : 'gap-1 px-2'"+ :title="t('chart.title')"+ :aria-label="t('chart.title')"+ :aria-pressed="activeView === 'chart'"+ :disabled="!canShowChart"+ @click="selectView('chart')"+ >+ <BarChart3 class="block h-3.5 w-3.5 self-center" />+ <span v-if="!compact" class="inline-flex h-4 items-center leading-none">{{ t("chart.title") }}</span>+ </Button>+ </LightTooltip>+ </div>+</template>diff --git a/apps/desktop/src/composables/useDataGridActions.ts b/apps/desktop/src/composables/useDataGridActions.tsindex 1db1f2421b..dd9960c9f4 100644--- a/apps/desktop/src/composables/useDataGridActions.ts+++ b/apps/desktop/src/composables/useDataGridActions.ts@@ -13,6 +13,7 @@ import { effectiveDatabaseTypeForConnection, metadataSchemaForConnection } fromimport { applyMongoFindSort } from "@/lib/mongo/mongoShellCommand";import { uuid } from "@/lib/common/utils";import type { DataGridSortMode } from "@/lib/dataGrid/dataGridSort";+import type { DataGridReloadIntent } from "@/lib/dataGrid/dataGridToolbar";import { queryResultBaseSql, queryResultExecutionSql } from "@/lib/tabs/tabPresentation";const DATA_TAB_METADATA_TTL_MS = 30_000;@@ -109,7 +110,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)await queryStore.executeTabSql(tab.id, sql, { preserveResultDuringExecution: true });}- async function onReloadData(sql?: string, _searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number) {+ async function onReloadData(sql?: string, _searchText?: string, whereInput?: string, orderBy?: string, limit?: number, offset?: number, intent?: DataGridReloadIntent) {const tab = activeTab.value;if (!tab) return;const traceId = uuid().slice(0, 8);@@ -162,6 +163,22 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)}return;}+ if (intent === "refresh" && tab.mode === "query" && (tab.results?.length ?? 0) > 1) {+ const resultGroupSql = tab.resultBaseSql || tab.lastExecutedSql || tab.sql;+ if (!resultGroupSql.trim()) return;+ tab.resultSortColumn = undefined;+ tab.resultSortColumnIndex = undefined;+ tab.resultSortDirection = undefined;+ tab.resultSortMode = undefined;+ tab.resultSortedSql = undefined;+ await queryStore.executeTabSql(tab.id, resultGroupSql, {+ resultBaseSql: resultGroupSql,+ resultSortedSql: undefined,+ preserveResultDuringExecution: true,+ preserveActiveResultIndex: true,+ });+ return;+ }if (tab.resultSortedSql) {const sortColumns = visibleQuerySortColumns(tab.result?.columns ?? [], tab.result?.hidden_column_indexes, tab.resultSortColumnIndex ?? -1);const rebuildHiddenKeySort = !!tab.result?.hidden_column_indexes?.length && tab.resultSortMode === "database" && !!tab.resultSortDirection && !!tab.resultSortColumn && !!sortColumns;diff --git a/apps/desktop/src/lib/__tests__/tabs/resultToolbarLayout.spec.ts b/apps/desktop/src/lib/__tests__/tabs/resultToolbarLayout.spec.tsdeleted file mode 100644index c25aa7e90f..0000000000--- a/apps/desktop/src/lib/__tests__/tabs/resultToolbarLayout.spec.ts+++ /dev/null@@ -1,25 +0,0 @@-import { describe, expect, it } from "vitest";-import { nextResultToolbarLayout } from "@/lib/tabs/resultToolbarLayout";--describe("nextResultToolbarLayout", () => {- it("never compacts fewer than two results", () => {- expect(nextResultToolbarLayout({ resultCount: 1, compact: true, expandedRequiredWidth: 900, toolbarWidth: 700, tabsViewportWidth: 100, tabsContentWidth: 300 })).toEqual({ compact: false });- });-- it("keeps the expanded layout when tabs fit", () => {- expect(nextResultToolbarLayout({ resultCount: 2, compact: false, toolbarWidth: 800, tabsViewportWidth: 300, tabsContentWidth: 300 })).toEqual({ compact: false });- });-- it("compacts on overflow and records the expanded width requirement", () => {- expect(nextResultToolbarLayout({ resultCount: 3, compact: false, toolbarWidth: 800, tabsViewportWidth: 240, tabsContentWidth: 300 })).toEqual({ compact: true, expandedRequiredWidth: 860 });- });-- it("stays compact after compact controls remove the current overflow", () => {- expect(nextResultToolbarLayout({ resultCount: 3, compact: true, expandedRequiredWidth: 860, toolbarWidth: 850, tabsViewportWidth: 320, tabsContentWidth: 300 })).toEqual({ compact: true, expandedRequiredWidth: 860 });- });-- it("expands only after the required width and hysteresis are available", () => {- expect(nextResultToolbarLayout({ resultCount: 3, compact: true, expandedRequiredWidth: 860, toolbarWidth: 867, tabsViewportWidth: 337, tabsContentWidth: 300 })).toEqual({ compact: true, expandedRequiredWidth: 860 });- expect(nextResultToolbarLayout({ resultCount: 3, compact: true, expandedRequiredWidth: 860, toolbarWidth: 868, tabsViewportWidth: 338, tabsContentWidth: 300 })).toEqual({ compact: false });- });-});diff --git a/apps/desktop/src/lib/dataGrid/dataGridToolbar.ts b/apps/desktop/src/lib/dataGrid/dataGridToolbar.tsnew file mode 100644index 0000000000..3dd1173193--- /dev/null+++ b/apps/desktop/src/lib/dataGrid/dataGridToolbar.ts@@ -0,0 +1,3 @@+export const DATA_GRID_COMPACT_TOPBAR_WIDTH = 900;++export type DataGridReloadIntent = "refresh";diff --git a/apps/desktop/src/lib/tabs/resultToolbarLayout.ts b/apps/desktop/src/lib/tabs/resultToolbarLayout.tsdeleted file mode 100644index 2b1156693e..0000000000--- a/apps/desktop/src/lib/tabs/resultToolbarLayout.ts+++ /dev/null@@ -1,35 +0,0 @@-const OVERFLOW_TOLERANCE_PX = 1;-const EXPAND_HYSTERESIS_PX = 8;--export interface ResultToolbarLayoutState {- compact: boolean;- expandedRequiredWidth?: number;-}--export interface ResultToolbarLayoutInput extends ResultToolbarLayoutState {- resultCount: number;- toolbarWidth: number;- tabsViewportWidth: number;- tabsContentWidth: number;-}--export function nextResultToolbarLayout(input: ResultToolbarLayoutInput): ResultToolbarLayoutState {- if (input.resultCount < 2) return { compact: false };- if (input.toolbarWidth <= 0 || input.tabsViewportWidth <= 0) {- return { compact: input.compact, expandedRequiredWidth: input.expandedRequiredWidth };- }-- if (input.compact) {- if (input.expandedRequiredWidth === undefined || input.toolbarWidth >= input.expandedRequiredWidth + EXPAND_HYSTERESIS_PX) {- return { compact: false };- }- return { compact: true, expandedRequiredWidth: input.expandedRequiredWidth };- }-- const overflowWidth = input.tabsContentWidth - input.tabsViewportWidth;- if (overflowWidth <= OVERFLOW_TOLERANCE_PX) return { compact: false };- return {- compact: true,- expandedRequiredWidth: input.toolbarWidth + overflowWidth,- };-}diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.tsindex 5bfdcbbf06..8127893e17 100644--- a/apps/desktop/src/stores/queryStore.ts+++ b/apps/desktop/src/stores/queryStore.ts@@ -131,6 +131,11 @@ function markQueryResultRunsRowsRaw(resultRuns: NonNullable<QueryTab["resultRunsreturn resultRuns;}+function preservedResultIndex(results: QueryResult[], currentIndex: number | undefined, preserve: boolean | undefined): number | undefined {+ if (preserve !== true || typeof currentIndex !== "number" || currentIndex < 0 || currentIndex >= results.length) return undefined;+ return currentIndex;+}+function annotateQueryResultSources(results: QueryResult[], sql: string, database: string | undefined, databaseType?: DatabaseType): QueryResult[] {const statements = splitSqlStatementRanges(sql, databaseType);let statementIndex = 0;@@ -2403,6 +2408,7 @@ export const useQueryStore = defineStore("query", () => {mongoSafety?: MongoAggregateSafetyOptions;preserveResultDuringExecution?: boolean;preserveTotalRowCountDuringExecution?: boolean;+ preserveActiveResultIndex?: boolean;replaceActiveResultInGroup?: boolean;skipRedisSafetyCheck?: boolean;sourceTraceId?: string;@@ -2522,7 +2528,7 @@ export const useQueryStore = defineStore("query", () => {if (current?.executionId === executionId) {if (allResults.length > 1) {const activeResultIndex = allResults.findIndex((r) => !r.columns.includes("Error"));- const resultIndex = activeResultIndex >= 0 ? activeResultIndex : 0;+ const resultIndex = preservedResultIndex(allResults, current.activeResultIndex, options?.preserveActiveResultIndex) ?? (activeResultIndex >= 0 ? activeResultIndex : 0);current.results = allResults;current.activeResultIndex = resultIndex;current.result = allResults[resultIndex];@@ -2568,12 +2574,19 @@ export const useQueryStore = defineStore("query", () => {const mongoCommand = parsedCommand.command;const sourceStatement = parsedCommand.text;const commandStartedAt = performance.now();+ const annotateMongoResult = (result: QueryResult): QueryResult => {+ const annotated = annotateQueryResultSource(result, sourceStatement);+ if ("collection" in mongoCommand) {+ annotated.sourceLabel = currentDatabase ? `${currentDatabase}.${mongoCommand.collection}` : mongoCommand.collection;+ }+ return annotated;+ };try {switch (mongoCommand.kind) {case "find": {console.info("[DBX][executeTabSql:mongo-find:start]", { traceId, collection: mongoCommand.collection, database: currentDatabase });const result = await api.mongoFindDocuments(tab.connectionId, currentDatabase, mongoCommand.collection, mongoCommand.skip, mongoCommand.limit, mongoCommand.filter, mongoCommand.projection, mongoCommand.sort, executionId);- const queryResult = markQueryResultRowsRaw(annotateQueryResultSource(mongoDocumentsToQueryResult(result.documents, performance.now() - commandStartedAt, result.total), sourceStatement));+ const queryResult = markQueryResultRowsRaw(annotateMongoResult(mongoDocumentsToQueryResult(result.documents, performance.now() - commandStartedAt, result.total)));allResults.push(queryResult);mongoEditTarget = mongoCommands.length === 1 && queryResult.columns.includes("_id") ? { collection: mongoCommand.collection, idColumn: "_id" } : undefined;console.info("[DBX][executeTabSql:mongo-find:done]", {@@ -2589,7 +2602,7 @@ export const useQueryStore = defineStore("query", () => {case "version": {console.info("[DBX][executeTabSql:mongo-version:start]", { traceId, database: currentDatabase });const version = await api.mongoServerVersion(tab.connectionId, currentDatabase, executionId);- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoVersionToQueryResult(version, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoVersionToQueryResult(version, performance.now() - commandStartedAt))));mongoEditTarget = undefined;console.info("[DBX][executeTabSql:mongo-version:done]", {traceId,@@ -2602,7 +2615,7 @@ export const useQueryStore = defineStore("query", () => {case "countDocuments": {console.info("[DBX][executeTabSql:mongo-count:start]", { traceId, collection: mongoCommand.collection, database: currentDatabase });const result = await api.mongoFindDocuments(tab.connectionId, currentDatabase, mongoCommand.collection, 0, 1, mongoCommand.filter, undefined, undefined, executionId);- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoCountToQueryResult(result.total, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoCountToQueryResult(result.total, performance.now() - commandStartedAt))));mongoEditTarget = undefined;console.info("[DBX][executeTabSql:mongo-count:done]", {traceId,@@ -2621,7 +2634,7 @@ export const useQueryStore = defineStore("query", () => {console.info("[DBX][executeTabSql:mongo-aggregate:start]", { traceId, collection: mongoCommand.collection, database: currentDatabase });const aggregateMaxRows = normalizeResultPageSize(pageLimit ?? options?.pagination?.limit ?? settingsStore.editorSettings.pageSize);const result = await api.mongoAggregateDocuments(tab.connectionId, currentDatabase, mongoCommand.collection, mongoCommand.pipeline, aggregateMaxRows, executionId);- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoDocumentsToQueryResult(result.documents, performance.now() - commandStartedAt, result.total), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoDocumentsToQueryResult(result.documents, performance.now() - commandStartedAt, result.total))));mongoEditTarget = undefined;console.info("[DBX][executeTabSql:mongo-aggregate:done]", {traceId,@@ -2636,7 +2649,7 @@ export const useQueryStore = defineStore("query", () => {case "getIndexes": {console.info("[DBX][executeTabSql:mongo-indexes:start]", { traceId, collection: mongoCommand.collection, database: currentDatabase });const indexes = await api.listIndexes(tab.connectionId, currentDatabase, "", mongoCommand.collection);- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoIndexesToQueryResult(indexes, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoIndexesToQueryResult(indexes, performance.now() - commandStartedAt))));mongoEditTarget = undefined;console.info("[DBX][executeTabSql:mongo-indexes:done]", {traceId,@@ -2655,7 +2668,7 @@ export const useQueryStore = defineStore("query", () => {database: currentDatabase,});const stats = await api.mongoCollectionStats(tab.connectionId, currentDatabase, mongoCommand.collection, mongoCommand.scale, executionId);- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoCollectionStatsToQueryResult(mongoCommand.metric, stats as unknown as Record<string, unknown>, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoCollectionStatsToQueryResult(mongoCommand.metric, stats as unknown as Record<string, unknown>, performance.now() - commandStartedAt))));mongoEditTarget = undefined;console.info("[DBX][executeTabSql:mongo-collection-stats:done]", {traceId,@@ -2686,22 +2699,22 @@ export const useQueryStore = defineStore("query", () => {mongoEditTarget = undefined;if (mongoCommand.kind === "insert") {const result = await api.mongoInsertDocuments(tab.connectionId, currentDatabase, mongoCommand.collection, mongoCommand.docsJson);- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoWriteToQueryResult(result.affected_rows, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoWriteToQueryResult(result.affected_rows, performance.now() - commandStartedAt))));} else if (mongoCommand.kind === "update") {const result = await api.mongoUpdateDocuments(tab.connectionId, currentDatabase, mongoCommand.collection, mongoCommand.filter, mongoCommand.update, mongoCommand.many);- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoWriteToQueryResult(result.affected_rows, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoWriteToQueryResult(result.affected_rows, performance.now() - commandStartedAt))));} else if (mongoCommand.kind === "createIndex") {const result = await api.mongoCreateIndex(tab.connectionId, currentDatabase, mongoCommand.collection, mongoCommand.keys, mongoCommand.options);- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoCreateIndexToQueryResult(result.name, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoCreateIndexToQueryResult(result.name, performance.now() - commandStartedAt))));} else if (mongoCommand.kind === "dropIndex" || mongoCommand.kind === "dropIndexes") {const result = await api.mongoDropIndexes(tab.connectionId, currentDatabase, mongoCommand.collection, mongoCommand.kind === "dropIndex" ? mongoCommand.index : mongoCommand.indexes, mongoCommand.kind === "dropIndex");- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoDroppedIndexesToQueryResult(result.dropped_names, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoDroppedIndexesToQueryResult(result.dropped_names, performance.now() - commandStartedAt))));} else if (mongoCommand.kind === "dropCollection") {await api.mongoDropCollection(tab.connectionId, currentDatabase, mongoCommand.collection);- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoWriteToQueryResult(1, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoWriteToQueryResult(1, performance.now() - commandStartedAt))));} else {const result = await api.mongoDeleteDocuments(tab.connectionId, currentDatabase, mongoCommand.collection, mongoCommand.filter, mongoCommand.many);- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoWriteToQueryResult(result.affected_rows, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoWriteToQueryResult(result.affected_rows, performance.now() - commandStartedAt))));}console.info("[DBX][executeTabSql:mongo-write:done]", {traceId,@@ -2714,7 +2727,7 @@ export const useQueryStore = defineStore("query", () => {}case "use": {currentDatabase = mongoCommand.database;- allResults.push(markQueryResultRowsRaw(annotateQueryResultSource(mongoUseToQueryResult(currentDatabase, performance.now() - commandStartedAt), sourceStatement)));+ allResults.push(markQueryResultRowsRaw(annotateMongoResult(mongoUseToQueryResult(currentDatabase, performance.now() - commandStartedAt))));mongoEditTarget = undefined;console.info("[DBX][executeTabSql:mongo-use:done]", {traceId,@@ -2727,7 +2740,7 @@ export const useQueryStore = defineStore("query", () => {} catch (error: any) {// Surface per-command failures inline and continue collecting results// for the rest of the batch, matching the grouped-result UX.- allResults.push(annotateQueryResultSource(toErrorResult(error), sourceStatement));+ allResults.push(annotateMongoResult(toErrorResult(error)));mongoEditTarget = undefined;}}@@ -2741,11 +2754,18 @@ export const useQueryStore = defineStore("query", () => {const current = tabs.value.find((t) => t.id === id);if (current?.executionId === executionId) {- if (allResults.length > 1) {+ const activeGroupIndex = current.activeResultIndex;+ const activeGroupResults = current.results;+ const shouldReplaceActiveResultInGroup = options?.replaceActiveResultInGroup === true && allResults.length === 1 && Array.isArray(activeGroupResults) && typeof activeGroupIndex === "number" && activeGroupIndex >= 0 && activeGroupIndex < activeGroupResults.length;+ if (shouldReplaceActiveResultInGroup) {+ current.results = activeGroupResults.slice();+ current.results[activeGroupIndex] = allResults[0];+ current.result = allResults[0];+ } else if (allResults.length > 1) {// Open grouped output on the first non-error result when possible so// mixed success/error batches land on the most useful table first.const activeResultIndex = allResults.findIndex((result) => !result.columns.includes("Error"));- const resultIndex = activeResultIndex >= 0 ? activeResultIndex : 0;+ const resultIndex = preservedResultIndex(allResults, current.activeResultIndex, options?.preserveActiveResultIndex) ?? (activeResultIndex >= 0 ? activeResultIndex : 0);current.results = allResults;current.activeResultIndex = resultIndex;current.result = allResults[resultIndex];@@ -2760,9 +2780,9 @@ export const useQueryStore = defineStore("query", () => {current.queryEditabilityReason = undefined;current.mongoEditTarget = mongoCommands.length === 1 ? mongoEditTarget : undefined;current.tableMeta = undefined;- current.resultBaseSql = options?.resultBaseSql ?? sql;+ current.resultBaseSql = shouldReplaceActiveResultInGroup ? (current.resultBaseSql ?? options?.resultBaseSql ?? sql) : (options?.resultBaseSql ?? sql);current.resultSortedSql = options?.resultSortedSql;- syncDisplayedResultRun(current, options?.resultBaseSql ?? sql);+ syncDisplayedResultRun(current, current.resultBaseSql ?? options?.resultBaseSql ?? sql);if (current.database !== currentDatabase) current.database = currentDatabase;}return;@@ -2872,7 +2892,7 @@ export const useQueryStore = defineStore("query", () => {current.result = results[0];} else if (results.length > 1) {const activeResultIndex = results.findIndex((result) => result.columns.length > 0);- const resultIndex = activeResultIndex >= 0 ? activeResultIndex : 0;+ const resultIndex = preservedResultIndex(results, current.activeResultIndex, options?.preserveActiveResultIndex) ?? (activeResultIndex >= 0 ? activeResultIndex : 0);current.results = results;current.activeResultIndex = resultIndex;current.result = results[resultIndex];@@ -2881,7 +2901,7 @@ export const useQueryStore = defineStore("query", () => {current.activeResultIndex = undefined;current.result = results[0];}- current.resultBaseSql = queryBaseSql;+ current.resultBaseSql = shouldReplaceActiveResultInGroup ? (current.resultBaseSql ?? queryBaseSql) : queryBaseSql;current.resultSortedSql = resultSortedSql;current.resultPageSql = pageSql;current.resultPageLimit = pageLimit;@@ -2967,7 +2987,7 @@ export const useQueryStore = defineStore("query", () => {current.queryEditabilityReason = undefined;current.mongoEditTarget = undefined;if (current.mode !== "data") current.tableMeta = undefined;- current.resultBaseSql = queryBaseSql;+ current.resultBaseSql = shouldReplaceActiveResultInGroup ? (current.resultBaseSql ?? queryBaseSql) : queryBaseSql;current.resultSortedSql = resultSortedSql;current.resultPageSql = pageSql;current.resultPageLimit = pageLimit;diff --git a/packages/app-tests/queryResultToolbar.test.ts b/packages/app-tests/queryResultToolbar.test.tsnew file mode 100644index 0000000000..b237bb8891--- /dev/null+++ b/packages/app-tests/queryResultToolbar.test.ts@@ -0,0 +1,89 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { test } from "vitest";+import { compileScript, compileTemplate, parse } from "vue/compiler-sfc";++const contentAreaPath = "apps/desktop/src/components/layout/ContentArea.vue";+const dataGridPath = "apps/desktop/src/components/grid/DataGrid.vue";+const viewSwitcherPath = "apps/desktop/src/components/layout/QueryResultViewSwitcher.vue";+const toolbarActionsPath = "apps/desktop/src/components/layout/QueryResultToolbarActions.vue";++function source(path: string): string {+ return readFileSync(path, "utf8");+}++function assertSfcCompiles(path: string): void {+ const { descriptor, errors } = parse(source(path), { filename: path });+ assert.deepEqual(errors, [], `${path} should parse without SFC errors`);+ assert.ok(descriptor.scriptSetup, `${path} should have a script setup block`);+ compileScript(descriptor, { id: path });+ if (descriptor.template) {+ const result = compileTemplate({ id: path, filename: path, source: descriptor.template.content });+ assert.deepEqual(result.errors, [], `${path} template should compile`);+ }+}++test("query result toolbar SFCs compile", () => {+ for (const path of [contentAreaPath, dataGridPath, viewSwitcherPath, toolbarActionsPath]) assertSfcCompiles(path);+});++test("query result toolbar reuses the production icon contract", () => {+ const contentArea = source(contentAreaPath);+ const viewSwitcher = source(viewSwitcherPath);+ const toolbarActions = source(toolbarActionsPath);++ assert.match(contentArea, /<Pin class="h-3\.5 w-3\.5"/);+ assert.match(contentArea, /<Wrench class="h-4 w-4"/);+ assert.match(contentArea, /<ChevronDown class="h-3\.5 w-3\.5"/);+ assert.match(viewSwitcher, /import \{ BarChart3, ListChecks \} from "@lucide\/vue"/);+ assert.match(toolbarActions, /import \{ GitBranch, Loader2, Upload \} from "@lucide\/vue"/);+ assert.match(viewSwitcher, /inline-flex h-4 items-center leading-none/);+ assert.match(toolbarActions, /block h-3\.5 w-3\.5 self-center/);+ assert.doesNotMatch(viewSwitcher + toolbarActions, /<svg\b|<symbol\b|<use\b/);+});++test("ContentArea keeps result history conditional and removes duplicate refresh state", () => {+ const contentArea = source(contentAreaPath);++ assert.match(contentArea, /showResultRunSelector = computed\(\(\) => resultAutoSave\.value && resultRuns\.value\.length > 0\)/);+ assert.match(contentArea, /<template v-if="showResultRunSelector">/);+ assert.match(contentArea, /resultAutoSave \? 'bg-primary\/10 text-primary[\s\S]*: 'text-muted-foreground hover:bg-accent hover:text-foreground'/);+ assert.doesNotMatch(contentArea, /queryResultAutoRefresh|QUERY_RESULT_AUTO_REFRESH|nextResultToolbarLayout/);+ assert.equal((contentArea.match(/<QueryResultViewSwitcher\b/g) ?? []).length, 2);+ assert.equal((contentArea.match(/<QueryResultToolbarActions\b/g) ?? []).length, 2);+});++test("ContentArea keeps MySQL standard explain results available in the shared toolbar", () => {+ const contentArea = source(contentAreaPath);++ assert.match(contentArea, /canShowExplainOutput = computed\([\s\S]*explainTableResult[\s\S]*explainTableError/);+ assert.match(contentArea, /:table-result="activeTab\.explainTableResult"/);+ assert.match(contentArea, /:table-error="activeTab\.explainTableError"/);+});++test("DataGrid exposes persistent result toolbar slots", () => {+ const dataGrid = source(dataGridPath);++ assert.match(dataGrid, /slots\["result-toolbar-leading"\]/);+ assert.match(dataGrid, /slots\["result-toolbar-actions"\]/);+ assert.match(dataGrid, /<slot name="result-toolbar-leading" :compact="compactDataGridToolbar"/);+ assert.match(dataGrid, /<slot v-if="hasResultToolbarActionsSlot" name="result-toolbar-actions" :compact="compactDataGridToolbar"/);+ assert.match(dataGrid, /hasResultToolbarLeadingSlot\.value \|\|[\s\S]*hasResultToolbarActionsSlot\.value/);+});++test("standalone result views use the same compact toolbar breakpoint", () => {+ const contentArea = source(contentAreaPath);+ const dataGrid = source(dataGridPath);++ assert.match(contentArea, /ref="standaloneResultToolbarRef"/);+ assert.match(contentArea, /standaloneResultToolbarWidth\.value < DATA_GRID_COMPACT_TOPBAR_WIDTH/);+ assert.equal((contentArea.match(/:compact="standaloneResultToolbarCompact"/g) ?? []).length, 2);+ assert.match(dataGrid, /dataGridTopbarWidth\.value < DATA_GRID_COMPACT_TOPBAR_WIDTH/);+});++test("DataGrid marks toolbar refresh separately from current-result reloads", () => {+ const dataGrid = source(dataGridPath);++ assert.match(dataGrid, /emit\("reload", props\.sql,[^;]+"refresh"\);/);+ assert.match(dataGrid, /function onToolbarRollback\(\)[\s\S]*?emit\("reload", props\.sql,[^;]+\);/);+});diff --git a/packages/app-tests/queryStore.test.ts b/packages/app-tests/queryStore.test.tsindex b4ad12ecbd..ca3ffe44b4 100644--- a/packages/app-tests/queryStore.test.ts+++ b/packages/app-tests/queryStore.test.ts@@ -2852,6 +2852,148 @@ test("mongo aggregate execution uses editor page size when pagination plan has nassert.equal(aggregateBody.collection, "accounting_reconciliations");assert.equal(tab?.result?.rows.length, 811);assert.equal(tab?.result?.truncated, false);+ assert.equal(tab?.result?.sourceLabel, "accounting.accounting_reconciliations");+ } finally {+ globalThis.fetch = originalFetch;+ restoreStorage();+ }+});++test("mongo multi-find results use database and collection source labels", async () => {+ const restoreStorage = installMemoryStorage();+ setActivePinia(createPinia());+ const connectionStore = useConnectionStore();+ const store = useQueryStore();+ const originalFetch = globalThis.fetch;+ const collections: string[] = [];++ connectionStore.addEphemeralConnection({+ ...conn("mongo-1"),+ db_type: "mongodb",+ port: 27017,+ });++ globalThis.fetch = withConnectionHealthMock(async (input, init) => {+ const url = String(input);+ if (url === "/api/query/prepare-pagination-plan") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ return new Response(JSON.stringify({ sqlToExecute: body.options.sql, useAgentResultSession: false }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/document-store/find-documents") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ collections.push(body.collection);+ return new Response(JSON.stringify({ documents: [{ _id: `${body.collection}-1` }], total: 1 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ return new Response("unexpected request", { status: 500 });+ });++ try {+ const tabId = store.createTab("mongo-1", "cmdb", "Query", "query", "");+ const groupedSql = "db.model_field_group.find({})\n\ndb.model_field_info.find({})";+ await store.executeTabSql(tabId, groupedSql);+ const tab = store.tabs.find((item) => item.id === tabId);++ assert.deepEqual(collections, ["model_field_group", "model_field_info"]);+ assert.deepEqual(+ tab?.results?.map((result) => result.sourceLabel),+ ["cmdb.model_field_group", "cmdb.model_field_info"],+ );++ assert.ok(tab);+ store.setActiveResultIndex(tabId, 1);+ const sortedSql = "db.model_field_info.find({}).sort({ name: 1 })";+ await store.executeTabSql(tabId, sortedSql, {+ resultBaseSql: "db.model_field_info.find({})",+ resultSortedSql: sortedSql,+ preserveResultDuringExecution: true,+ replaceActiveResultInGroup: true,+ });++ assert.deepEqual(collections, ["model_field_group", "model_field_info", "model_field_info"]);+ assert.equal(tab.results?.length, 2);+ assert.equal(tab.activeResultIndex, 1);+ assert.equal(tab.resultBaseSql, groupedSql);+ assert.deepEqual(+ tab.results?.map((result) => result.sourceLabel),+ ["cmdb.model_field_group", "cmdb.model_field_info"],+ );+ } finally {+ globalThis.fetch = originalFetch;+ restoreStorage();+ }+});++test("replacing one paginated SQL result preserves the grouped refresh SQL", async () => {+ const restoreStorage = installMemoryStorage();+ setActivePinia(createPinia());+ const connectionStore = useConnectionStore();+ const store = useQueryStore();+ const originalFetch = globalThis.fetch;++ connectionStore.addEphemeralConnection(conn("conn-1"));+ globalThis.fetch = withConnectionHealthMock(async (input, init) => {+ const url = String(input);+ if (url === "/api/query/prepare-pagination-plan") {+ const body = JSON.parse(String(init?.body ?? "{}"));+ return new Response(+ JSON.stringify({+ sqlToExecute: body.options.sql,+ pageSql: body.options.sql,+ pageLimit: 100,+ pageOffset: 100,+ useAgentResultSession: false,+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ );+ }+ if (url === "/api/query/execute-multi") {+ return new Response(JSON.stringify([{ columns: ["id"], rows: [[202]], affected_rows: 0, execution_time_ms: 1 }]), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ if (url === "/api/query/analyze-editability") {+ return new Response(JSON.stringify({ editable: false, reason: "complex-source" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+ }+ return new Response("unexpected request", { status: 500 });+ });++ try {+ const tabId = store.createTab("conn-1", "app", "Query", "query");+ const tab = store.tabs.find((item) => item.id === tabId);+ assert.ok(tab);+ const groupedSql = "select * from users; select * from orders";+ const activeSql = "select * from orders";+ tab.resultBaseSql = groupedSql;+ tab.results = [+ { columns: ["id"], rows: [[1]], affected_rows: 0, execution_time_ms: 1, sourceStatement: "select * from users" },+ { columns: ["id"], rows: [[2]], affected_rows: 0, execution_time_ms: 1, sourceStatement: activeSql },+ ];+ tab.activeResultIndex = 1;+ tab.result = tab.results[1];++ await store.executeTabSql(tabId, activeSql, {+ resultBaseSql: activeSql,+ pagination: { limit: 100, offset: 100 },+ preserveResultDuringExecution: true,+ preserveTotalRowCountDuringExecution: true,+ replaceActiveResultInGroup: true,+ });++ assert.equal(tab.results?.length, 2);+ assert.equal(tab.activeResultIndex, 1);+ assert.deepEqual(tab.result?.rows, [[202]]);+ assert.equal(tab.resultBaseSql, groupedSql);+ assert.equal(tab.result?.sourceStatement, activeSql);} finally {globalThis.fetch = originalFetch;restoreStorage();@@ -3068,6 +3210,10 @@ test("mongo multi-command execution runs writes sequentially and keeps grouped rtab?.results?.map((result) => result.sourceStatement),['db.users.insertOne({ name: "Ada" })', 'db.users.insertOne({ name: "Grace" })'],);+ assert.deepEqual(+ tab?.results?.map((result) => result.sourceLabel),+ ["accounting.users", "accounting.users"],+ );} finally {globalThis.fetch = originalFetch;restoreStorage();@@ -3254,6 +3400,8 @@ test("mongo multi-command execution applies use database before later commands",assert.equal(tab?.database, "archive");assert.equal(tab?.results?.length, 2);assert.deepEqual(tab?.results?.[0]?.rows, [["switched to db archive"]]);+ assert.equal(tab?.results?.[0]?.sourceLabel, undefined);+ assert.equal(tab?.results?.[1]?.sourceLabel, "archive.users");} finally {globalThis.fetch = originalFetch;restoreStorage();@@ -4225,6 +4373,15 @@ test("query results keep readable table source labels with active database contetab = store.tabs.find((item) => item.id === tabId);assert.equal(resultSqlForGrid(tab!), "select * from orders");+ await store.executeTabSql(tabId, "select * from users; select * from orders", {+ resultBaseSql: "select * from users; select * from orders",+ preserveResultDuringExecution: true,+ preserveActiveResultIndex: true,+ });+ tab = store.tabs.find((item) => item.id === tabId);+ assert.equal(tab?.activeResultIndex, 1);+ assert.equal(resultSqlForGrid(tab!), "select * from orders");+await store.executeTabSql(defaultDatabaseTabId, "SELECT *\nFROM apis AS ap\nLIMIT 10;\n\nSELECT *\nFROM menus AS mn\nLIMIT 10;");tab = store.tabs.find((item) => item.id === defaultDatabaseTabId);assert.deepEqual(diff --git a/packages/app-tests/useDataGridActions.test.ts b/packages/app-tests/useDataGridActions.test.tsindex 0669cd4b87..fdcb712b70 100644--- a/packages/app-tests/useDataGridActions.test.ts+++ b/packages/app-tests/useDataGridActions.test.ts@@ -170,3 +170,64 @@ test("data reload preserves current page offset instead of resetting to page 1",restoreStorage();}});++test("query toolbar refresh reruns the complete multi-result SQL and keeps the active result", async () => {+ const restoreStorage = installMemoryStorage();+ const { useDataGridActions } = await import("../../apps/desktop/src/composables/useDataGridActions.ts");++ try {+ setActivePinia(createPinia());+ const queryStore = useQueryStore();+ const tabId = queryStore.createTab("mysql-1", "app", "query", "query");+ const tab = queryStore.tabs.find((item) => item.id === tabId);+ assert.ok(tab);++ const batchSql = "select * from users; select * from orders";+ const refreshedResults = [+ { columns: ["id"], rows: [[11]], affected_rows: 0, execution_time_ms: 1, sourceStatement: "select * from users" },+ { columns: ["id"], rows: [[22]], affected_rows: 0, execution_time_ms: 1, sourceStatement: "select * from orders" },+ ];+ tab.sql = batchSql;+ tab.lastExecutedSql = batchSql;+ tab.resultBaseSql = batchSql;+ tab.results = refreshedResults.map((result) => ({ ...result, rows: result.rows.map((row) => [...row]) }));+ tab.activeResultIndex = 1;+ tab.result = tab.results[1];+ tab.resultSortColumn = "id";+ tab.resultSortColumnIndex = 0;+ tab.resultSortDirection = "desc";+ tab.resultSortMode = "database";+ tab.resultSortedSql = "select * from orders order by id desc";++ const executeTabSql = vi.spyOn(queryStore, "executeTabSql").mockImplementation(async (_tabId, _sql, options) => {+ assert.equal(tab.resultSortColumn, undefined);+ assert.equal(tab.resultSortColumnIndex, undefined);+ assert.equal(tab.resultSortDirection, undefined);+ assert.equal(tab.resultSortMode, undefined);+ assert.equal(tab.resultSortedSql, undefined);+ tab.results = refreshedResults;+ if (!options?.preserveActiveResultIndex) tab.activeResultIndex = 0;+ tab.result = refreshedResults[tab.activeResultIndex ?? 0];+ });+ const actions = useDataGridActions(computed(() => tab));++ await actions.onReloadData("select * from orders", undefined, undefined, undefined, 100, 0, "refresh");+ await actions.onReloadData("select * from orders", undefined, undefined, undefined, 100, 0, "refresh");++ assert.equal(executeTabSql.mock.calls.length, 2);+ for (const call of executeTabSql.mock.calls) {+ assert.equal(call[1], batchSql);+ assert.deepEqual(call[2], {+ resultBaseSql: batchSql,+ resultSortedSql: undefined,+ preserveResultDuringExecution: true,+ preserveActiveResultIndex: true,+ });+ }+ assert.equal(tab.results?.length, 2);+ assert.equal(tab.activeResultIndex, 1);+ assert.deepEqual(tab.result, refreshedResults[1]);+ } finally {+ restoreStorage();+ }+});