feat(query): add batch result actions

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-10-01 15:50:54 +08:00
1 parent e6c7baa2d9
commit 38a00c7cb7
18 files changed
+668 -18

No files matched your search

@@ -8109,6 +8109,7 @@ const {
exportCurrentPageXlsxWithSql,
exportAllResultsXlsx,
exportAllResultsXlsxWithSql,
exportResultSheetsXlsx,
exportSql,
exportCurrentPageSql,
exportTxt,
@@ -12145,6 +12146,7 @@ defineExpose({
exportJson,
exportSql,
exportXlsx,
exportResultSheetsXlsx,
openXlsx,
exportTxt,
defaultCopyPreference: selectedCopyPreference,
@@ -7,6 +7,7 @@ import { defaultViewForResult } from "@/lib/query/queryResultDefaultView";
import { queryResultMessages } from "@/lib/query/queryResultMessages";
import { isQueryExecutionErrorResult } from "@/lib/query/queryResultError";
import { hasQueryOutput as tabHasQueryOutput } from "@/lib/query/queryOutput";
import { batchResultInsertRequest } from "@/lib/query/queryResultBatchInsert";
import { batchSqlRecoveryState, type BatchSqlRecoveryAction } from "@/lib/query/batchSqlRecovery";
import type { CSSProperties } from "vue";
import { useI18n } from "vue-i18n";
@@ -190,7 +191,7 @@ import { loadObjectDdl } from "@/lib/metadata/objectDdlCache";
import { formatDdlForDisplay } from "@/lib/sql/ddlDisplay";
import { sqlObjectNavigationTypeFromTableType } from "@/lib/sql/sqlNavigation";
import type { CustomSaveHandler } from "@/composables/useDataGridEditor";
import type { QueryMessage, QueryTab, RedisResultViewMode, TableInfoTab, TreeNode, VectorCollectionMeta } from "@/types/database";
import type { QueryMessage, QueryResult, QueryTab, RedisResultViewMode, TableInfoTab, TreeNode, VectorCollectionMeta } from "@/types/database";
import type { SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";
import { sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import { productionContextForDatabase } from "@/lib/database/productionSafety";
@@ -221,6 +222,7 @@ type DataGridHandle = DataGridColumnLayoutHandle & {
exportJson: () => Promise<void>;
exportSql: () => Promise<void>;
exportXlsx: () => Promise<void>;
exportResultSheetsXlsx: (sheets: Array<{ sheetName: string; result: QueryResult; sql?: string }>) => Promise<void>;
openXlsx: () => Promise<void>;
};
@@ -515,6 +517,82 @@ const allResultExportSheets = computed(() =>
sql: item.index === props.activeTab.activeResultIndex ? queryResultExecutionSql(props.activeTab) : item.result.sourceStatement,
})),
);
type ResultSetItem = (typeof visibleResultItems.value)[number];
const resultBatchBusy = ref(false);
async function copySelectedResultSql(items: ResultSetItem[]) {
if (resultBatchBusy.value) return;
resultBatchBusy.value = true;
const tab = props.activeTab;
const generation = tab.resultViewGeneration;
const runId = tab.activeResultRunId;
const databaseType = activeEffectiveDatabaseType.value;
const identifierQuote = connectionStore.connectionIdentifierQuote(activeResultConnectionId.value);
const extractorOptions = JSON.parse(JSON.stringify(settingsStore.editorSettings.dataGridExtractorOptions));
extractorOptions.sql.includeDatabaseName = settingsStore.editorSettings.generateSqlIncludeDatabaseName;
const isCurrent = () => props.activeTab === tab && tab.activeResultRunId === runId && tab.resultViewGeneration === generation && items.every((item) => (tab.results ?? [tab.result]).includes(item.result));
try {
const sections: string[] = [];
let bytes = 0;
for (const item of items) {
const metadata = await queryStore.resolveResultMetadataForBatch(tab.id, item.result);
const request = batchResultInsertRequest(item.result, metadata, databaseType, identifierQuote, extractorOptions);
if (!request) throw new Error(t("tabs.batchCopyUnsupportedResult", { name: item.label || t("tabs.resultN", { n: item.n }) }));
if (!request.rows.length) continue;
const extraction = await api.extractDataGridSelection(request);
if (!extraction.text.trim()) throw new Error(t("tabs.batchCopyUnsupportedResult", { name: item.label || t("tabs.resultN", { n: item.n }) }));
const label = (item.label || t("tabs.resultN", { n: item.n })).replace(/[\r\n]/g, " ");
const section = `-- ${label}\n${extraction.text.trim()}`;
bytes += new TextEncoder().encode(section).length + 2;
if (bytes > 32 * 1024 * 1024) throw new Error(t("tabs.batchCopyTooLarge"));
sections.push(section);
}
if (!isCurrent()) throw new Error(t("tabs.batchResultsChanged"));
if (!sections.length) throw new Error(t("tabs.batchCopyNoCompatibleResults"));
await copyToClipboard(sections.join("\n\n"));
toast(t("grid.copied"));
} catch (error: any) {
toast(t("grid.copyFailed", { message: error?.message || String(error) }), 5000);
} finally {
resultBatchBusy.value = false;
}
}
async function exportSelectedResultSheets(items: ResultSetItem[]) {
if (resultBatchBusy.value) return;
const dataGrid = dataGridRef.value;
if (!dataGrid) return;
const sheets = items.filter((item) => !item.result.execution_error && !item.result.server_message).map((item) => ({ sheetName: item.label || t("tabs.resultN", { n: item.n }), result: item.result }));
if (!sheets.length) return;
resultBatchBusy.value = true;
try {
await dataGrid.exportResultSheetsXlsx(sheets);
} finally {
resultBatchBusy.value = false;
}
}
async function copySelectedResultQueries(items: ResultSetItem[]) {
const sections = items
.map((item) => {
const sql = item.result.sourceStatement?.trim();
const label = (item.label || t("tabs.resultN", { n: item.n })).replace(/[\r\n]/g, " ");
return sql ? `-- ${label}\n${sql.endsWith(";") ? sql : `${sql};`}` : "";
})
.filter(Boolean);
if (!sections.length) {
toast(t("tabs.batchCopyNoCompatibleResults"), 5000);
return;
}
try {
await copyToClipboard(sections.join("\n\n"));
toast(t("grid.copied"));
} catch (error: any) {
toast(t("grid.copyFailed", { message: error?.message || String(error) }), 5000);
}
}
// 结果标签优先显示来源(表名),历史批次缺少来源信息时按批次 SQL 重新解析
const resultRuns = computed(() =>
resultRunItems(props.activeTab, {
@@ -1877,7 +1955,19 @@ defineExpose({
</div>
<div v-else-if="resultRuns.length > 0" class="min-w-0 flex-1" />
<span v-if="resultRuns.length > 0 && visibleResultItems.length > 0" class="mx-1 h-4 w-px shrink-0 bg-border" />
<ResultSetNavigator v-if="visibleResultItems.length > 0" :key="`${activeTab.id}:${activeTab.activeResultRunId ?? 'current'}`" :items="visibleResultItems" :active-index="activeTab.activeResultIndex ?? 0" :active="activeOutputView === 'result'" @select="selectResultItem" />
<ResultSetNavigator
v-if="visibleResultItems.length > 0"
:key="`${activeTab.id}:${activeTab.activeResultRunId ?? 'current'}`"
:items="visibleResultItems"
:busy="resultBatchBusy"
:can-export-xlsx="activeOutputView === 'result' && redisResultViewMode === 'grid' && !!activeTab.result && hasTabularResult && !activeElasticsearchJsonResponse"
:active-index="activeTab.activeResultIndex ?? 0"
:active="activeOutputView === 'result'"
@select="selectResultItem"
@copy-sql="copySelectedResultSql"
@copy-query-sql="copySelectedResultQueries"
@export-xlsx="exportSelectedResultSheets"
/>
</template>
<div class="ml-auto flex shrink-0 items-center gap-1">
<Popover v-if="activeOutputView === 'result' && redisResultViewMode === 'grid' && activeTab.result && hasTabularResult && !activeElasticsearchJsonResponse" v-model:open="dataGridViewOptionsOpen">
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { Check, ChevronDown } from "@lucide/vue";
import { Check, ChevronDown, Copy, FileCode2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import LightTooltip from "@/components/ui/LightTooltip.vue";
@@ -9,23 +9,46 @@ import { useTabScroll } from "@/composables/useTabScroll";
import type { tabularResultItems } from "@/lib/tabs/tabPresentation";
type ResultItem = ReturnType<typeof tabularResultItems>[number];
const props = defineProps<{ items: ResultItem[]; activeIndex: number; active: boolean }>();
const emit = defineEmits<{ select: [item: ResultItem] }>();
const props = defineProps<{
items: ResultItem[];
activeIndex: number;
active: boolean;
busy?: boolean;
canExportXlsx?: boolean;
}>();
const emit = defineEmits<{
select: [item: ResultItem];
copySql: [items: ResultItem[]];
copyQuerySql: [items: ResultItem[]];
exportXlsx: [items: ResultItem[]];
}>();
const { t } = useI18n();
const scroller = ref<HTMLElement | null>(null);
const list = ref<HTMLElement | null>(null);
const searchInput = ref<HTMLInputElement | null>(null);
const batchSearchInput = ref<HTMLInputElement | null>(null);
const open = ref(false);
const search = ref("");
const batchOpen = ref(false);
const batchSearch = ref("");
const selectedIndexes = ref<Set<number>>(new Set());
const { hasTabOverflow, scrollThumbLeftPercent, scrollThumbWidthPercent, isScrollbarDragging, updateScrollButtons, onTabsWheel, startScrollbarDrag } = useTabScroll(scroller);
const thumbStyle = computed(() => ({ left: `${scrollThumbLeftPercent.value}%`, width: `${scrollThumbWidthPercent.value}%` }));
const filteredItems = computed(() => {
const query = search.value.trim().toLocaleLowerCase();
if (!query) return props.items;
function filterResultItems(items: ResultItem[], rawQuery: string) {
const query = rawQuery.trim().toLocaleLowerCase();
if (!query) return items;
// A number is an exact result ordinal, not a substring of every SQL statement.
if (/^\d+$/.test(query)) return props.items.filter((item) => item.n === Number(query));
return props.items.filter((item) => [item.label, item.title, item.result.sourceStatement, t("tabs.resultN", { n: item.n })].some((value) => value?.toLocaleLowerCase().includes(query)));
if (/^\d+$/.test(query)) return items.filter((item) => item.n === Number(query));
return items.filter((item) => [item.label, item.title, item.result.sourceName, item.result.sourceLabel, item.result.sourceStatement, t("tabs.resultN", { n: item.n })].some((value) => value?.toLocaleLowerCase().includes(query)));
}
const filteredItems = computed(() => {
return filterResultItems(props.items, search.value);
});
const filteredBatchItems = computed(() => {
return filterResultItems(props.items, batchSearch.value);
});
const selectedBatchItems = computed(() => props.items.filter((item) => selectedIndexes.value.has(item.index)));
function revealActive() {
const container = scroller.value;
@@ -54,6 +77,49 @@ function select(item: ResultItem) {
open.value = false;
}
function resetBatchSelection() {
selectedIndexes.value = new Set(props.items.map((item) => item.index));
}
function onBatchOpenAutoFocus() {
batchSearch.value = "";
resetBatchSelection();
batchSearchInput.value?.focus();
}
function setVisibleBatchSelection(selected: boolean) {
const next = new Set(selectedIndexes.value);
for (const item of filteredBatchItems.value) {
if (selected) next.add(item.index);
else next.delete(item.index);
}
selectedIndexes.value = next;
}
function toggleBatchItem(item: ResultItem) {
const next = new Set(selectedIndexes.value);
if (next.has(item.index)) next.delete(item.index);
else next.add(item.index);
selectedIndexes.value = next;
}
function emitBatch(action: "copySql" | "copyQuerySql" | "exportXlsx") {
const items = selectedBatchItems.value;
if (!items.length) return;
if (action === "copySql") emit("copySql", items);
else if (action === "copyQuerySql") emit("copyQuerySql", items);
else emit("exportXlsx", items);
batchOpen.value = false;
}
watch(
() => props.items,
() => {
resetBatchSelection();
},
{ immediate: true },
);
function focusListItem(index: number) {
const buttons = list.value?.querySelectorAll<HTMLButtonElement>("button");
if (!buttons?.length) return;
@@ -135,6 +201,48 @@ function onListKeydown(event: KeyboardEvent, index: number) {
</div>
</PopoverContent>
</Popover>
<Popover v-if="items.length > 1" v-model:open="batchOpen">
<PopoverTrigger as-child>
<Button variant="ghost" size="sm" class="h-6 shrink-0 gap-1 px-2 text-xs" :title="t('tabs.batchResultActions')">
<Copy class="h-3.5 w-3.5" />
<span class="hidden sm:inline">{{ t("tabs.batchResultActions") }}</span>
</Button>
</PopoverTrigger>
<PopoverContent align="end" class="w-[32rem] max-h-[var(--reka-popover-content-available-height)] max-w-[calc(100vw-2rem)] gap-2 p-2" @open-auto-focus.prevent="onBatchOpenAutoFocus">
<div class="flex items-center justify-between gap-2 border-b pb-2">
<span class="shrink-0 text-xs font-semibold">{{ t("tabs.batchResultActions") }}</span>
<input ref="batchSearchInput" v-model="batchSearch" type="search" class="min-w-0 flex-1 rounded-md border bg-background px-2 py-1 text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring" :placeholder="t('tabs.searchResults')" :aria-label="t('tabs.searchResults')" />
<span class="shrink-0 text-[11px] text-muted-foreground">{{ t("tabs.batchSelectedCount", { count: selectedBatchItems.length, total: items.length }) }}</span>
</div>
<div class="flex min-h-0 max-h-56 flex-col gap-1 overflow-y-auto py-1">
<label v-for="item in filteredBatchItems" :key="item.index" class="flex cursor-pointer items-center gap-2 rounded px-1.5 py-1 text-xs hover:bg-accent">
<input type="checkbox" :checked="selectedIndexes.has(item.index)" @change="toggleBatchItem(item)" />
<span class="min-w-0 flex-1 truncate">{{ item.displayLabel || item.label || t("tabs.resultN", { n: item.n }) }}</span>
<span class="shrink-0 text-[10px] text-muted-foreground tabular-nums"
>{{ item.result.rows.length }}<template v-if="item.result.has_more || item.result.truncated"> · {{ t("tabs.batchIncompleteResult") }}</template></span
>
</label>
<p v-if="!filteredBatchItems.length" role="status" class="p-4 text-center text-xs text-muted-foreground">{{ t("tabs.noMatchingResults") }}</p>
</div>
<p class="text-[11px] text-muted-foreground">{{ t("tabs.batchLoadedRowsOnly") }}</p>
<div class="flex flex-wrap items-center gap-1 border-t pt-2">
<Button variant="ghost" size="sm" class="h-6 px-2 text-xs" :disabled="!filteredBatchItems.length" @click="setVisibleBatchSelection(true)">{{ t("tabs.selectAllResults") }}</Button>
<Button variant="ghost" size="sm" class="h-6 px-2 text-xs" :disabled="!filteredBatchItems.length" @click="setVisibleBatchSelection(false)">{{ t("tabs.clearResultSelection") }}</Button>
<span class="flex-1" />
<Button variant="outline" size="sm" class="h-6 gap-1 px-2 text-xs" :disabled="busy || selectedBatchItems.length === 0" @click="emitBatch('copyQuerySql')">
<FileCode2 class="h-3.5 w-3.5" />
{{ t("tabs.copyResultQueries") }}
</Button>
<Button variant="outline" size="sm" class="h-6 gap-1 px-2 text-xs" :disabled="!canExportXlsx || busy || selectedBatchItems.length === 0" @click="emitBatch('exportXlsx')">
{{ t("tabs.exportSelectedResultsXlsx") }}
</Button>
<Button size="sm" class="h-6 gap-1 px-2 text-xs" :disabled="busy || selectedBatchItems.length === 0" @click="emitBatch('copySql')">
<Copy class="h-3.5 w-3.5" />
{{ t("tabs.copyResultAsSql") }}
</Button>
</div>
</PopoverContent>
</Popover>
</div>
</template>
@@ -12,17 +12,59 @@ afterEach(() => {
document.body.replaceChildren();
});
async function mountNavigator(inputResults?: QueryResult[]) {
async function mountNavigator(inputResults?: QueryResult[], canExportXlsx = true) {
// Include a non-tabular result so ordinal and storage index are different.
const results = inputResults ?? ([{ columns: [], rows: [] }, ...Array.from({ length: 100 }, (_, i) => ({ columns: ["value"], rows: [[i + 1]], sourceStatement: `SELECT ${i + 1} AS value` }))] as QueryResult[]);
const select = vi.fn();
const copySql = vi.fn();
const copyQuerySql = vi.fn();
const exportXlsx = vi.fn();
const container = document.createElement("div");
document.body.append(container);
app = createApp(ResultSetNavigator, { items: tabularResultItems(results), activeIndex: 1, active: true, onSelect: select });
app.use(createI18n({ legacy: false, locale: "en", messages: { en: { tabs: { resultN: "Result {n}", resultSets: "Result sets", allResults: "All results ({count})", searchResults: "Search", noMatchingResults: "No matches" } } } }));
app = createApp(ResultSetNavigator, { items: tabularResultItems(results), activeIndex: 1, active: true, canExportXlsx, onSelect: select, onCopySql: copySql, onCopyQuerySql: copyQuerySql, onExportXlsx: exportXlsx });
app.use(
createI18n({
legacy: false,
locale: "en",
messages: {
en: {
tabs: {
resultN: "Result {n}",
resultSets: "Result sets",
allResults: "All results ({count})",
searchResults: "Search",
noMatchingResults: "No matches",
batchResultActions: "Batch actions",
batchSelectedCount: "{count}/{total} selected",
selectAllResults: "Select all",
clearResultSelection: "Clear",
copyResultQueries: "Copy queries",
copyResultAsSql: "Copy as SQL",
exportSelectedResultsXlsx: "Export XLSX",
batchLoadedRowsOnly: "Uses loaded rows",
batchIncompleteResult: "Incomplete",
},
},
},
}),
);
app.mount(container);
await nextTick();
return { container, select };
return { container, select, copySql, copyQuerySql, exportXlsx };
}
async function openBatchMenu(container: HTMLElement) {
[...container.querySelectorAll("button")].find((button) => button.textContent?.includes("Batch actions"))!.click();
await nextTick();
await nextTick();
const popup = [...document.querySelectorAll<HTMLElement>('[data-slot="popover-content"]')].find((candidate) => candidate.textContent?.includes("Batch actions"))!;
const input = popup.querySelector<HTMLInputElement>('input[type="search"]')!;
const filter = async (query: string) => {
input.value = query;
input.dispatchEvent(new Event("input", { bubbles: true }));
await nextTick();
};
return { popup, input, filter };
}
describe("large result-set navigation", () => {
@@ -71,4 +113,80 @@ describe("large result-set navigation", () => {
expect(select).toHaveBeenCalledOnce();
expect(select.mock.calls[0]![0]).toMatchObject({ n: 8, index: 8 });
});
it("emits the selected result sets without changing the active result", async () => {
const { container, copySql } = await mountNavigator([
{ columns: ["id"], rows: [[1]], sourceName: "first", sourceStatement: "SELECT 1" },
{ columns: ["id"], rows: [[2]], sourceName: "second", sourceStatement: "SELECT 2" },
]);
const batchTrigger = [...container.querySelectorAll("button")].find((button) => button.textContent?.includes("Batch actions"))!;
batchTrigger.click();
await nextTick();
const action = [...document.querySelectorAll("button")].find((button) => button.textContent?.includes("Copy as SQL"))!;
action.click();
await nextTick();
expect(copySql).toHaveBeenCalledOnce();
expect(copySql.mock.calls[0]?.[0]).toHaveLength(2);
});
it.each([
["Copy as SQL", "copySql"],
["Copy queries", "copyQuerySql"],
["Export XLSX", "exportXlsx"],
] as const)("%s only includes selected results matching the batch search", async (action, event) => {
const mounted = await mountNavigator([
{ columns: [], rows: [] },
{ columns: ["id"], rows: [[1]], sourceLabel: "apis", sourceStatement: "SELECT * FROM apis" },
{ columns: ["id"], rows: [[2]], sourceLabel: "menus", sourceStatement: "SELECT * FROM menus WHERE enabled = true" },
]);
const { popup, filter } = await openBatchMenu(mounted.container);
await filter("APIS");
expect(popup.querySelectorAll('input[type="checkbox"]')).toHaveLength(1);
expect(popup.textContent).toContain("2/2 selected");
[...popup.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Clear")!.click();
await nextTick();
expect(popup.textContent).toContain("1/2 selected");
await filter("enabled");
expect(popup.querySelectorAll("label")[0]?.textContent).toContain("menus");
[...popup.querySelectorAll("button")].find((button) => button.textContent?.includes(action))!.click();
expect(mounted[event]).toHaveBeenCalledOnce();
expect(mounted[event].mock.calls[0]?.[0].map((item: { index: number }) => item.index)).toEqual([2]);
expect(mounted.select).not.toHaveBeenCalled();
});
it("disables XLSX export when the result view is inactive", async () => {
const mounted = await mountNavigator(
[
{ columns: ["id"], rows: [[1]], sourceStatement: "SELECT 1" },
{ columns: ["id"], rows: [[2]], sourceStatement: "SELECT 2" },
],
false,
);
const { popup } = await openBatchMenu(mounted.container);
const exportButton = [...popup.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("Export XLSX"));
expect(exportButton?.disabled).toBe(true);
});
it("selects and clears only visible results and restores hidden selections when the search is cleared", async () => {
const { container } = await mountNavigator();
const { popup, filter } = await openBatchMenu(container);
await filter("8");
expect(popup.querySelectorAll('input[type="checkbox"]')).toHaveLength(1);
const clear = [...popup.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Clear")!;
const selectAll = [...popup.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Select all")!;
clear.click();
await nextTick();
expect(popup.textContent).toContain("99/100 selected");
await filter("");
expect(popup.textContent).toContain("99/100 selected");
await filter("8");
selectAll.click();
await nextTick();
await filter("");
expect(popup.textContent).toContain("100/100 selected");
await filter("no matching result");
expect(popup.querySelector('[role="status"]')?.textContent).toBe("No matches");
expect([...popup.querySelectorAll("button")].filter((button) => button.textContent?.includes("Select all") || button.textContent?.includes("Clear")).every((button) => button.disabled)).toBe(true);
});
});