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(sql-file): preserve target database when selecting SQL file
lxk955c2d9610d1c29
diff --git a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.retry.spec.ts b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.retry.spec.tsindex 006cc86054..52f69ccede 100644--- a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.retry.spec.ts+++ b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.retry.spec.ts@@ -148,8 +148,21 @@ vi.mock("@/components/ui/select", () => ({Select: defineComponent({inheritAttrs: false,props: ["modelValue"],- setup(props, { attrs, slots }) {- return () => h("div", { ...attrs, "data-select-value": props.modelValue ?? "" }, slots.default?.());+ emits: ["update:modelValue"],+ setup(props, { attrs, slots, emit }) {+ return () =>+ h(+ "div",+ {+ ...attrs,+ "data-select-value": props.modelValue ?? "",+ onClick: (e: MouseEvent) => {+ const target = (e.target as HTMLElement)?.closest?.("[data-select-item]") as HTMLElement | null;+ if (target?.dataset?.selectItem) emit("update:modelValue", target.dataset.selectItem);+ },+ },+ slots.default?.(),+ );},}),SelectContent: passthrough("div"),@@ -167,7 +180,7 @@ vi.mock("@/components/icons/DatabaseIcon.vue", () => ({ default: passthrough("spvi.mock("@/components/connection/ConnectionGroupBadge.vue", () => ({ default: passthrough("span") }));import SqlFileExecutionDialog from "./SqlFileExecutionDialog.vue";-import { rememberExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";+import { rememberExternalSqlFileTarget, resolveExternalSqlFileTarget, unassociatedExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";let app: ReturnType<typeof createApp> | undefined;let root: HTMLDivElement | undefined;@@ -1036,3 +1049,95 @@ describe("SqlFileExecutionDialog selected-table restore", () => {expect(input.value).toBe("/tmp/missing.sql");});});++describe("SqlFileExecutionDialog target preservation (#4844)", () => {+ it("preserves prefilled database when browsing for a new unassociated SQL file", async () => {+ mocks.connections = [{ id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "" }];+ mocks.queryStore.tabs = [{ id: "tab-1", connectionId: "mysql-1", database: "first_db" }];+ mocks.queryStore.activeTabId = "tab-1";+ mocks.fetchSqlFileTargetOptions.mockResolvedValue(["first_db", "target_db"]);+ mocks.openFileDialog.mockResolvedValueOnce(["/tmp/unassociated.sql"]);++ root = document.createElement("div");+ document.body.append(root);+ app = createApp(SqlFileExecutionDialog, { open: true, prefillConnectionId: "mysql-1", prefillDatabase: "target_db" });+ app.mount(root);++ await vi.waitFor(() => expect(mocks.fetchSqlFileTargetOptions).toHaveBeenCalledWith("mysql-1", expect.anything()));+ expect(root.querySelector('[data-select-value="target_db"]')).not.toBeNull();++ findButton("sqlFile.browse").click();+ await vi.waitFor(() => expect(mocks.previewSqlFile).toHaveBeenCalledWith("/tmp/unassociated.sql"));++ // Target database MUST NOT have been overwritten by activeTab database ("first_db")+ expect(root.querySelector('[data-select-value="target_db"]')).not.toBeNull();++ mocks.executeSqlFiles.mockImplementationOnce(async (request) => {+ mocks.progressHandler?.(progress(request.executionId, "done"));+ });+ findButton("sqlFile.execute").click();++ await vi.waitFor(() => expect(mocks.executeSqlFiles).toHaveBeenCalledWith(expect.objectContaining({ connectionId: "mysql-1", database: "target_db" }), ["/tmp/unassociated.sql"]));+ expect(resolveExternalSqlFileTarget("/tmp/unassociated.sql", () => true, unassociatedExternalSqlFileTarget())).toMatchObject({+ connectionId: "mysql-1",+ database: "target_db",+ });+ });++ it("does not overwrite prefilled connection and database even if the selected file has a saved target", async () => {+ mocks.connections = [+ { id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "" },+ { id: "mysql-2", name: "MySQL 2", db_type: "mysql", driver_profile: "mysql", database: "" },+ ];+ rememberExternalSqlFileTarget("/tmp/saved_other.sql", { connectionId: "mysql-2", database: "other_db" });+ mocks.fetchSqlFileTargetOptions.mockResolvedValue(["first_db", "explicit_prefill_db"]);+ mocks.openFileDialog.mockResolvedValueOnce(["/tmp/saved_other.sql"]);++ root = document.createElement("div");+ document.body.append(root);+ app = createApp(SqlFileExecutionDialog, { open: true, prefillConnectionId: "mysql-1", prefillDatabase: "explicit_prefill_db" });+ app.mount(root);++ await vi.waitFor(() => expect(mocks.fetchSqlFileTargetOptions).toHaveBeenCalledWith("mysql-1", expect.anything()));+ findButton("sqlFile.browse").click();+ await vi.waitFor(() => expect(mocks.previewSqlFile).toHaveBeenCalledWith("/tmp/saved_other.sql"));++ expect(root.querySelector('[data-select-value="mysql-1"]')).not.toBeNull();+ expect(root.querySelector('[data-select-value="explicit_prefill_db"]')).not.toBeNull();+ });++ it("preserves user-selected database in the dialog when browsing an unassociated file", async () => {+ mocks.connections = [{ id: "mysql-1", name: "MySQL", db_type: "mysql", driver_profile: "mysql", database: "" }];+ mocks.queryStore.tabs = [{ id: "tab-1", connectionId: "mysql-1", database: "first_db" }];+ mocks.queryStore.activeTabId = "tab-1";+ mocks.fetchSqlFileTargetOptions.mockResolvedValue(["first_db", "second_db", "chosen_db"]);+ mocks.openFileDialog.mockResolvedValueOnce(["/tmp/brand_new.sql"]);++ root = document.createElement("div");+ document.body.append(root);+ app = createApp(SqlFileExecutionDialog, { open: true });+ app.mount(root);++ await vi.waitFor(() => expect(mocks.fetchSqlFileTargetOptions).toHaveBeenCalledWith("mysql-1", expect.anything()));++ // User selects "chosen_db" from the database dropdown+ const chosenDbItem = root.querySelector('[data-select-item="chosen_db"]') as HTMLElement;+ expect(chosenDbItem).not.toBeNull();+ chosenDbItem.click();+ await nextTick();+ expect(root.querySelector('[data-select-value="chosen_db"]')).not.toBeNull();++ findButton("sqlFile.browse").click();+ await vi.waitFor(() => expect(mocks.previewSqlFile).toHaveBeenCalledWith("/tmp/brand_new.sql"));++ // Selection MUST be preserved, not overwritten with "first_db" from activeTab+ expect(root.querySelector('[data-select-value="chosen_db"]')).not.toBeNull();++ mocks.executeSqlFiles.mockImplementationOnce(async (request) => {+ mocks.progressHandler?.(progress(request.executionId, "done"));+ });+ findButton("sqlFile.execute").click();++ await vi.waitFor(() => expect(mocks.executeSqlFiles).toHaveBeenCalledWith(expect.objectContaining({ connectionId: "mysql-1", database: "chosen_db" }), ["/tmp/brand_new.sql"]));+ });+});diff --git a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vueindex 2c829c11b3..a1551eb0b0 100644--- a/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue+++ b/apps/desktop/src/components/sql-file/SqlFileExecutionDialog.vue@@ -24,7 +24,7 @@ import { formatError, isManualTransactionSessionExpired } from "@/lib/backend/erimport { fetchSqlFileTargetOptions, namespaceOptionsAreSchemas } from "@/composables/useDatabaseOptions";import { requiresSqlFileTargetDatabaseSelection, supportsConnectionLevelDatabaseBootstrap } from "@/lib/connection/connectionLevelDatabaseBootstrap";import { beginManualTransaction, commitManualTransaction, rollbackManualTransaction, cancelSqlFileExecution, executeSqlFiles, inspectSqlFileTables, listenSqlFileProgress, previewSqlFile, type SqlFilePreview, type SqlFileProgress, type SqlFileStatus, type SqlFileTable } from "@/lib/backend/api";-import { activeTabExternalSqlFileTarget, resolveExternalSqlFileTargetForActiveTab, type ExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";+import { activeTabExternalSqlFileTarget, rememberExternalSqlFileTarget, resolveExternalSqlFileTarget, unassociatedExternalSqlFileTarget, type ExternalSqlFileTarget } from "@/lib/sql/externalSqlFileTarget";import { isSqlFilePath } from "@/lib/sql/sqlFileOpen";import { buildDisplayFileNames, tooltipText as computeTooltipText } from "./sqlFilePreviewLabel";import { parseSqlFilePathInput } from "./sqlFilePathInput";@@ -427,6 +427,8 @@ function chooseNamespace(names: string[], id: string) {const preferred = preferredTarget.value?.connectionId === id ? preferredTarget.value : undefined;const preferredNamespace = preferred ? (optionsAreSchemas ? preferred.schema : preferred.database) : optionsAreSchemas ? (id === props.prefillConnectionId ? props.prefillSchema : undefined) : props.prefillDatabase;const configuredNamespace = optionsAreSchemas ? (connection?.default_schema ?? "") : (connection?.database ?? "");+ const currentNamespace = targetNamespace.value.trim();+ if (currentNamespace && connectionId.value === id && names.includes(currentNamespace)) return currentNamespace;if (names.length > 0) {if (preferredNamespace && names.includes(preferredNamespace)) return preferredNamespace;if (configuredNamespace && names.includes(configuredNamespace)) return configuredNamespace;@@ -435,6 +437,17 @@ function chooseNamespace(names: string[], id: string) {return preferredNamespace ?? configuredNamespace;}+watch(targetNamespace, (namespace) => {+ if (!connectionId.value) return;+ const connection = store.getConfig(connectionId.value);+ const optionsAreSchemas = namespaceOptionsAreSchemas(connection);+ preferredTarget.value = {+ connectionId: connectionId.value,+ database: optionsAreSchemas ? connection?.database?.trim() || "" : namespace.trim(),+ ...(optionsAreSchemas ? { schema: namespace.trim() } : {}),+ };+});+function sqlFileExecutionTarget(): SqlFileExecutionTarget {const namespace = targetNamespace.value.trim();const connection = store.getConfig(connectionId.value);@@ -534,10 +547,14 @@ async function loadPreviews(filesOrPaths: Array<string | File>, resolveSelectedFnextPreviews.push(await previewSelectedSqlFile(fileOrPath));}previews.value = nextPreviews;- if (resolveSelectedFileTarget) {+ if (resolveSelectedFileTarget && !props.prefillConnectionId) {const firstPath = typeof filesOrPaths[0] === "string" && isSqlFilePath(filesOrPaths[0]) ? filesOrPaths[0] : undefined;- const target = firstPath ? resolveExternalSqlFileTargetForActiveTab(firstPath, queryStore.tabs, queryStore.activeTabId, (connectionId) => store.getConfig(connectionId)) : activeTabExternalSqlFileTarget(queryStore.tabs, queryStore.activeTabId, (connectionId) => store.getConfig(connectionId));- applyTarget(target);+ const remembered = firstPath ? resolveExternalSqlFileTarget(firstPath, (id) => sqlConnections.value.some((c) => c.id === id), unassociatedExternalSqlFileTarget()) : undefined;+ if (remembered?.connectionId) {+ applyTarget(remembered);+ } else if (!connectionId.value) {+ applyTarget(activeTabExternalSqlFileTarget(queryStore.tabs, queryStore.activeTabId, (connectionId) => store.getConfig(connectionId)));+ }}} catch (e: any) {toast(e?.message || String(e), 5000);@@ -771,7 +788,20 @@ async function startExecution() {unlisten();}- if (completedSuccessfully && !txnSessionId.value) await refreshTargetAfterImport(target);+ if (completedSuccessfully) {+ if (isDesktopRuntime) {+ for (const item of previews.value) {+ if (item.filePath) {+ rememberExternalSqlFileTarget(item.filePath, {+ connectionId: connectionId.value,+ database: target.database,+ schema: target.schema,+ });+ }+ }+ }+ if (!txnSessionId.value) await refreshTargetAfterImport(target);+ }} catch (e: any) {terminalStatus.value = cancelRequested.value ? "cancelled" : "error";terminalError.value = e?.message || String(e);