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
fix(editor): export only the statement under the context menu
t8y20329294d73a3
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vueindex dbe2c3b2ff..7a74be5ea6 100644--- a/apps/desktop/src/components/editor/QueryEditor.vue+++ b/apps/desktop/src/components/editor/QueryEditor.vue@@ -65,6 +65,7 @@ import QueryEditorContextMenu, { type QueryEditorContextMenuState, type QueryEdiimport { clipboardLineEndings, copyToClipboard, readTextFromClipboard } from "@/lib/common/clipboard";import { resolveExecutableSql, type SqlExecutionOverride } from "@/lib/sql/sqlExecutionTarget";+import { resolveContextMenuExportSql } from "@/lib/sql/contextMenuExportSql";import { supportsExecutionTargetPicker, type SqlTextRange } from "@/lib/sql/sqlStatementRanges";import { executableStatementRangeAtCursor, executableStatementRangeCacheForDoc, executableStatementRangeStartingAt as executableStatementRangeStartingAtLine, type ExecutableStatementRangeCache } from "@/lib/sql/executableStatementRangeCache";import { statementNavigationTarget, type StatementNavigationDirection } from "@/lib/sql/statementNavigation";@@ -301,6 +302,8 @@ const gotoLinePanelRef = ref<InstanceType<typeof EditorGotoLinePanel>>();const { intentionPopup, closeIntentionPopup, executeIntentionAction, handleSqlIntentionActions } = useQueryEditorIntentions({ props, view, sqlBehaviorDialect, focusEditor });const selectedSql = ref("");+// 右键菜单打开处的文档位置:导出只取该处的单条语句,避免把多语句整篇文档交给后端。+const contextMenuPosition = ref<number | null>(null);const {delimitedListOpen,delimitedListSelectedText,@@ -932,6 +935,7 @@ function selectStarExpansionTargetForView(currentView: EditorViewType, position?function syncContextMenuStateAtEvent(currentView: EditorViewType, event: MouseEvent) {const pos = currentView.posAtCoords({ x: event.clientX, y: event.clientY });+ contextMenuPosition.value = pos ?? currentView.state.selection.main.head;clearScheduledPreviewContextRefresh();// 预览按“右键点击处”解析当前语句(执行按光标处),右键处与光标一致时才直觉一致。syncContextMenuState(currentView, pos ?? undefined, pos ?? undefined);@@ -1009,8 +1013,23 @@ function explainFromContextMenu() {focusEditor();}-function exportQueryFromContextMenu(format: "csv" | "xlsx" | "txt") {- const sql = executableSql.value;+// 右键导出与「执行」「预览变更」保持同一语句范围:选区优先,否则只导出右键处的单条语句。+// 把整篇多语句文档交给导出后端会被判定为不可流式导出(#1894)。+async function contextMenuExportSql(): Promise<string> {+ const currentView = view.value;+ const position = contextMenuPosition.value ?? currentView?.state.selection.main.head ?? null;+ return resolveContextMenuExportSql({+ selectedSql: selectedSql.value,+ position,+ documentSql: currentView ? currentEditorDocText(currentView) : executableSql.value,+ databaseType: props.databaseType,+ findStatementAtPosition: (sql, cursorPos, databaseType) => api.findStatementAtCursor(sql, cursorPos, databaseType),+ statementAtPosition: (cursorPos) => (currentView ? (executableStatementRangeAtPosition(currentView, cursorPos)?.sql ?? null) : null),+ });+}++async function exportQueryFromContextMenu(format: "csv" | "xlsx" | "txt") {+ const sql = await contextMenuExportSql();if (!sql.trim()) return;emit("exportQuery", { sql, format, columnComments: undefined });}diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditor.contextMenuExport.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditor.contextMenuExport.integration.spec.tsnew file mode 100644index 0000000000..c6e6b52c7d--- /dev/null+++ b/apps/desktop/src/components/editor/__tests__/QueryEditor.contextMenuExport.integration.spec.ts@@ -0,0 +1,93 @@+// @vitest-environment happy-dom++import { createApp, h, nextTick, reactive, shallowRef } from "vue";+import { createPinia, setActivePinia } from "pinia";+import { createI18n } from "vue-i18n";+import { EditorView } from "@codemirror/view";+import { afterEach, describe, expect, it, vi } from "vitest";+import QueryEditor from "../QueryEditor.vue";+import { useConnectionStore } from "@/stores/connectionStore";+import { useSettingsStore } from "@/stores/settingsStore";+import type { QueryEditorProps } from "../queryEditorTypes";++const apiMocks = vi.hoisted(() => ({ findStatementAtCursor: vi.fn() }));++vi.mock("@/lib/backend/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/backend/api")>()),+ findStatementAtCursor: apiMocks.findStatementAtCursor,+}));++vi.mock("@/lib/common/clipboard", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/common/clipboard")>()),+ copyToClipboard: vi.fn().mockResolvedValue(undefined),+ readTextFromClipboard: vi.fn().mockResolvedValue(""),+}));++const DOCUMENT = ["CREATE TABLE t (id Int64) ENGINE = Memory;", "WITH 1 AS min_id SELECT * FROM t WHERE id >= min_id;", "SELECT 2;"].join("\n");+const WITH_STATEMENT = "WITH 1 AS min_id SELECT * FROM t WHERE id >= min_id;";+const cleanups: Array<() => void> = [];++afterEach(() => {+ for (const cleanup of cleanups.splice(0).reverse()) cleanup();+ vi.restoreAllMocks();+ apiMocks.findStatementAtCursor.mockReset();+});++async function mountEditor(overrides: Partial<QueryEditorProps> = {}) {+ const pinia = createPinia();+ setActivePinia(pinia);+ const settingsStore = useSettingsStore();+ settingsStore.editorSettings.sidebarMenuLayout = "full";+ useConnectionStore();+ const props = reactive<QueryEditorProps>({ modelValue: "", tabId: "context-menu-export", databaseType: "clickhouse", dialect: "clickhouse", autoFocus: false, ...overrides });+ const editor = shallowRef<InstanceType<typeof QueryEditor>>();+ const emitted: Array<{ sql: string; format: string }> = [];+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp({+ render: () =>+ h(QueryEditor, {+ ...props,+ ref: editor,+ onExportQuery: (payload: { sql: string; format: string }) => emitted.push(payload),+ }),+ });+ app.use(pinia);+ app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));+ app.mount(host);+ cleanups.push(() => {+ app.unmount();+ host.remove();+ });+ await vi.waitFor(() => expect(host.querySelector(".cm-editor")).not.toBeNull(), { timeout: 5000 });+ const view = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;+ return { view, host, emitted };+}++function menuButton(labelFragment: string) {+ const found = [...document.querySelectorAll<HTMLButtonElement>("[data-dbx-context-menu] button")].find((candidate) => candidate.textContent?.includes(labelFragment));+ expect(found, labelFragment).toBeDefined();+ return found!;+}++describe("QueryEditor context-menu query export", () => {+ it("exports only the statement at the right-click position instead of the whole document", async () => {+ apiMocks.findStatementAtCursor.mockResolvedValue(WITH_STATEMENT);+ const { view, host, emitted } = await mountEditor({ modelValue: DOCUMENT });+ // happy-dom has no layout, so the click position resolves to the caret.+ vi.spyOn(EditorView.prototype, "posAtCoords").mockReturnValue(null);+ const caret = DOCUMENT.indexOf("min_id");+ view.dispatch({ selection: { anchor: caret } });+ await nextTick();++ host.querySelector("[data-query-editor-root]")!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 12, clientY: 12 }));+ await nextTick();+ menuButton("editor.contextMenu.export").click();+ await nextTick();+ menuButton("editor.contextMenu.exportQueryResultTo").click();++ await vi.waitFor(() => expect(emitted).toHaveLength(1));+ expect(apiMocks.findStatementAtCursor).toHaveBeenCalledExactlyOnceWith(DOCUMENT, caret, "clickhouse");+ expect(emitted[0]).toEqual({ sql: WITH_STATEMENT, format: "csv" });+ });+});diff --git a/apps/desktop/src/lib/sql/__tests__/contextMenuExportSql.spec.ts b/apps/desktop/src/lib/sql/__tests__/contextMenuExportSql.spec.tsnew file mode 100644index 0000000000..363544aacf--- /dev/null+++ b/apps/desktop/src/lib/sql/__tests__/contextMenuExportSql.spec.ts@@ -0,0 +1,65 @@+import { describe, expect, it, vi } from "vitest";+import { resolveContextMenuExportSql } from "../contextMenuExportSql";++const DOCUMENT = ["CREATE TABLE t (id Int64);", "WITH 1 AS min_id SELECT * FROM t WHERE id >= min_id;", "SELECT 2;"].join("\n");+const WITH_STATEMENT = "WITH 1 AS min_id SELECT * FROM t WHERE id >= min_id;";++function sources(overrides: Partial<Parameters<typeof resolveContextMenuExportSql>[0]> = {}) {+ return {+ selectedSql: "",+ position: DOCUMENT.indexOf("WITH"),+ documentSql: DOCUMENT,+ databaseType: "clickhouse" as const,+ findStatementAtPosition: vi.fn(async () => WITH_STATEMENT),+ statementAtPosition: vi.fn(() => null),+ ...overrides,+ };+}++describe("resolveContextMenuExportSql", () => {+ it("exports the selection as-is without asking the backend", async () => {+ const options = sources({ selectedSql: " SELECT 1 " });++ await expect(resolveContextMenuExportSql(options)).resolves.toBe("SELECT 1");+ expect(options.findStatementAtPosition).not.toHaveBeenCalled();+ expect(options.statementAtPosition).not.toHaveBeenCalled();+ });++ it("exports only the statement at the right-click position in a multi-statement document", async () => {+ const options = sources();++ await expect(resolveContextMenuExportSql(options)).resolves.toBe(WITH_STATEMENT);+ expect(options.findStatementAtPosition).toHaveBeenCalledExactlyOnceWith(DOCUMENT, DOCUMENT.indexOf("WITH"), "clickhouse");+ });++ it("falls back to the whole document when the position is unknown", async () => {+ const options = sources({ position: null });++ await expect(resolveContextMenuExportSql(options)).resolves.toBe(DOCUMENT);+ expect(options.findStatementAtPosition).not.toHaveBeenCalled();+ });++ it("falls back to the front-end statement range when the backend splitter fails", async () => {+ const options = sources({+ findStatementAtPosition: vi.fn(async () => {+ throw new Error("backend unavailable");+ }),+ statementAtPosition: vi.fn(() => WITH_STATEMENT),+ });++ await expect(resolveContextMenuExportSql(options)).resolves.toBe(WITH_STATEMENT);+ expect(options.statementAtPosition).toHaveBeenCalledExactlyOnceWith(DOCUMENT.indexOf("WITH"));+ });++ it("falls back to the front-end statement range when the backend returns only whitespace", async () => {+ const options = sources({ findStatementAtPosition: vi.fn(async () => " \n "), statementAtPosition: vi.fn(() => WITH_STATEMENT) });++ await expect(resolveContextMenuExportSql(options)).resolves.toBe(WITH_STATEMENT);+ });++ it("exports the whole document when no statement can be resolved at all", async () => {+ const options = sources({ findStatementAtPosition: vi.fn(async () => ""), statementAtPosition: vi.fn(() => null) });++ await expect(resolveContextMenuExportSql(options)).resolves.toBe(DOCUMENT);+ });+});diff --git a/apps/desktop/src/lib/sql/contextMenuExportSql.ts b/apps/desktop/src/lib/sql/contextMenuExportSql.tsnew file mode 100644index 0000000000..d767007ff4--- /dev/null+++ b/apps/desktop/src/lib/sql/contextMenuExportSql.ts@@ -0,0 +1,39 @@+import type { DatabaseType } from "@/types/database";++export interface ContextMenuExportSqlOptions {+ /** Text the user selected in the editor; an explicit selection always wins. */+ selectedSql: string;+ /** CodeMirror position of the context-menu invocation, or null when unknown. */+ position: number | null;+ /** Whole-document SQL used only when no statement can be resolved. */+ documentSql: string;+ /** Dialect used to parse the document (passed through to the backend splitter). */+ databaseType?: DatabaseType;+ /** Resolve the statement at a position with the backend statement splitter. */+ findStatementAtPosition: (sql: string, position: number, databaseType?: DatabaseType) => Promise<string>;+ /** Front-end statement range fallback for when the backend splitter is unavailable. */+ statementAtPosition: (position: number) => string | null;+}++/**+ * SQL for the editor context-menu "export current query result set" action.+ *+ * The action must export the statement the user right-clicked, mirroring the+ * execute action's statement scope (#1894): handing the backend the whole+ * editor document makes a multi-statement document look like a single+ * unsupported query, so the export is rejected before it starts.+ */+export async function resolveContextMenuExportSql(options: ContextMenuExportSqlOptions): Promise<string> {+ const selectedSql = options.selectedSql.trim();+ if (selectedSql) return selectedSql;+ if (options.position === null) return options.documentSql.trim();++ try {+ const resolved = (await options.findStatementAtPosition(options.documentSql, options.position, options.databaseType)).trim();+ if (resolved) return resolved;+ } catch {+ // The backend splitter is best-effort here; the front-end range keeps export usable offline.+ }++ return (options.statementAtPosition(options.position) ?? options.documentSql).trim();+}