Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

fix(history): open new query tab when restoring history SQL instead of overwriting active editor (#12979)

lxk955eeab128d738e
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index 27a8bc8e0b..aa29029a82 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -105,7 +105,7 @@ import { buildEditableObjectSource, buildExecutableObjectSourceStatements, execu
import { assertSourceIdentity, beginSourceSave } from "@/lib/table/objectSourceIdentity";
import { loadEditableObjectSourceForEditor } from "@/lib/table/objectSourceLoad";
import { schemaAfterConnectionSwitch } from "@/lib/schema/connectionSchemaInitialization";
-import { resolveHistorySqlRestoreTarget } from "@/lib/history/historyRestoreTarget";
+import { canReuseTabForHistoryRestore, resolveHistorySqlRestoreTarget } from "@/lib/history/historyRestoreTarget";
import { resolveExecutableSql, resolveExecutableSqlWithBackend, type SqlExecutionOverride, type SqlExecutionSnapshot } from "@/lib/sql/sqlExecutionTarget";
import { uuid } from "@/lib/common/utils";
import { getPlatform, isMacOS, isWindows } from "@/lib/backend/platform";
@@ -990,21 +990,26 @@ async function refreshAgentDriverUpdateCount() {
}
function restoreHistorySql(sql: string, entry: HistoryEntry) {
- const tab = activeTab.value;
- if (tab?.mode === "query") {
- queryStore.updateSql(tab.id, sql);
- return;
- }
-
const target = resolveHistorySqlRestoreTarget({
entry,
- activeTab: tab,
+ activeTab: activeTab.value,
firstConnectionId: connectionStore.connections[0]?.id,
+ connections: connectionStore.connections,
getConfig: (connectionId) => connectionStore.getConfig(connectionId),
});
if (!target) return;
- const tabId = queryStore.createTab(target.connectionId, target.database, t("tabs.sql"), "query", target.schema);
- queryStore.updateSql(tabId, sql);
+
+ const tab = activeTab.value;
+ if (tab && canReuseTabForHistoryRestore(tab, target)) {
+ queryStore.updateSql(tab.id, sql);
+ } else {
+ queryStore.createTab(target.connectionId, target.database, undefined, "query", target.schema, sql, undefined, { forceNew: true });
+ }
+
+ if (target.connectionId) {
+ connectionStore.activeConnectionId = target.connectionId;
+ connectionStore.ensureConnected(target.connectionId).catch(() => {});
+ }
}
const executableSql = computed(() => {
diff --git a/apps/desktop/src/lib/history/__tests__/historyRestoreTarget.spec.ts b/apps/desktop/src/lib/history/__tests__/historyRestoreTarget.spec.ts
new file mode 100644
index 0000000000..1bcf45f503
--- /dev/null
+++ b/apps/desktop/src/lib/history/__tests__/historyRestoreTarget.spec.ts
@@ -0,0 +1,309 @@
+import { describe, expect, it } from "vitest";
+import type { HistoryEntry } from "@/lib/backend/api";
+import type { ConnectionConfig, QueryTab } from "@/types/database";
+import { canReuseTabForHistoryRestore, resolveHistorySqlRestoreTarget } from "../historyRestoreTarget";
+
+describe("resolveHistorySqlRestoreTarget", () => {
+ const pgConfig: ConnectionConfig = {
+ id: "pg-1",
+ name: "PostgreSQL Local",
+ db_type: "postgresql",
+ host: "localhost",
+ port: 5432,
+ username: "postgres",
+ password: "",
+ database: "postgres",
+ default_schema: "public",
+ };
+
+ const mysqlConfig: ConnectionConfig = {
+ id: "mysql-1",
+ name: "MySQL Prod",
+ db_type: "mysql",
+ host: "localhost",
+ port: 3306,
+ username: "root",
+ password: "",
+ database: "ecommerce",
+ };
+
+ const sqliteConfig: ConnectionConfig = {
+ id: "sqlite-1",
+ name: "SQLite Main",
+ db_type: "sqlite",
+ database: "/path/to/db.sqlite",
+ };
+
+ const configs: Record<string, ConnectionConfig> = {
+ "pg-1": pgConfig,
+ "mysql-1": mysqlConfig,
+ "sqlite-1": sqliteConfig,
+ };
+
+ const getConfig = (id: string) => configs[id];
+ const connections = [pgConfig, mysqlConfig, sqliteConfig];
+
+ const baseEntry: HistoryEntry = {
+ id: "entry-1",
+ connection_id: "pg-1",
+ connection_name: "PostgreSQL Local",
+ database: "analytics",
+ sql: "SELECT * FROM page_views;",
+ executed_at: "2026-10-21T00:00:00Z",
+ execution_time_ms: 42,
+ success: true,
+ };
+
+ it("resolves target directly from history entry connection_id and database", () => {
+ const target = resolveHistorySqlRestoreTarget({
+ entry: baseEntry,
+ getConfig,
+ connections,
+ });
+
+ expect(target).toEqual({
+ connectionId: "pg-1",
+ database: "analytics",
+ schema: "public",
+ });
+ });
+
+ it("resolves connection by connection_name if connection_id was deleted or unknown", () => {
+ const entry: HistoryEntry = {
+ ...baseEntry,
+ connection_id: "old-deleted-id",
+ connection_name: "MySQL Prod",
+ database: "ecommerce",
+ };
+
+ const target = resolveHistorySqlRestoreTarget({
+ entry,
+ getConfig,
+ connections,
+ });
+
+ expect(target).toEqual({
+ connectionId: "mysql-1",
+ database: "ecommerce",
+ schema: undefined,
+ });
+ });
+
+ it("extracts schema from details_json when available", () => {
+ const entry: HistoryEntry = {
+ ...baseEntry,
+ details_json: JSON.stringify({ schema: "custom_schema", table: "users" }),
+ };
+
+ const target = resolveHistorySqlRestoreTarget({
+ entry,
+ getConfig,
+ connections,
+ });
+
+ expect(target).toEqual({
+ connectionId: "pg-1",
+ database: "analytics",
+ schema: "custom_schema",
+ });
+ });
+
+ it("does not choose an arbitrary connection when a deleted connection name is ambiguous", () => {
+ const duplicate = { ...mysqlConfig, id: "mysql-2", host: "another-host" };
+ const target = resolveHistorySqlRestoreTarget({
+ entry: { ...baseEntry, connection_id: "deleted-id", connection_name: mysqlConfig.name },
+ getConfig,
+ connections: [...connections, duplicate],
+ firstConnectionId: "mysql-1",
+ });
+
+ expect(target).toBeNull();
+ });
+
+ it("falls back to active tab schema when active tab shares the same connection and database", () => {
+ const activeTab = {
+ id: "tab-1",
+ connectionId: "pg-1",
+ database: "analytics",
+ schema: "tenant_42",
+ mode: "query",
+ sql: "",
+ } as QueryTab;
+
+ const target = resolveHistorySqlRestoreTarget({
+ entry: baseEntry,
+ activeTab,
+ getConfig,
+ connections,
+ });
+
+ expect(target).toEqual({
+ connectionId: "pg-1",
+ database: "analytics",
+ schema: "tenant_42",
+ });
+ });
+
+ it("normalizes sqlite namespace when connection is sqlite", () => {
+ const entry: HistoryEntry = {
+ ...baseEntry,
+ connection_id: "sqlite-1",
+ connection_name: "SQLite Main",
+ database: "main",
+ };
+
+ const target = resolveHistorySqlRestoreTarget({
+ entry,
+ getConfig,
+ connections,
+ });
+
+ expect(target).toEqual({
+ connectionId: "sqlite-1",
+ database: "main",
+ schema: undefined,
+ });
+ });
+
+ it("falls back to active tab or first connection when entry connection fields are absent", () => {
+ const emptyEntry: HistoryEntry = {
+ ...baseEntry,
+ connection_id: undefined,
+ connection_name: "",
+ database: "",
+ };
+
+ const activeTab = {
+ id: "tab-2",
+ connectionId: "mysql-1",
+ database: "billing",
+ mode: "query",
+ sql: "SELECT 1;",
+ } as QueryTab;
+
+ const target = resolveHistorySqlRestoreTarget({
+ entry: emptyEntry,
+ activeTab,
+ firstConnectionId: "pg-1",
+ getConfig,
+ connections,
+ });
+
+ expect(target).toEqual({
+ connectionId: "mysql-1",
+ database: "billing",
+ schema: undefined,
+ });
+ });
+
+ it("returns null when no connection can be determined", () => {
+ const emptyEntry: HistoryEntry = {
+ ...baseEntry,
+ connection_id: undefined,
+ connection_name: "",
+ database: "",
+ };
+
+ const target = resolveHistorySqlRestoreTarget({
+ entry: emptyEntry,
+ getConfig: () => undefined,
+ connections: [],
+ });
+
+ expect(target).toBeNull();
+ });
+});
+
+describe("canReuseTabForHistoryRestore", () => {
+ const target = {
+ connectionId: "pg-1",
+ database: "analytics",
+ schema: "public",
+ };
+
+ const createCleanTab = (overrides: Partial<QueryTab> = {}): QueryTab =>
+ ({
+ id: "tab-1",
+ title: "query_1",
+ connectionId: "pg-1",
+ database: "analytics",
+ schema: "public",
+ mode: "query",
+ sql: "",
+ isExecuting: false,
+ isCancelling: false,
+ isExplaining: false,
+ ...overrides,
+ }) as QueryTab;
+
+ it("allows reusing an active query tab that is blank and on the same connection, database, and schema", () => {
+ const tab = createCleanTab();
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(true);
+ });
+
+ it("treats whitespace-only SQL as empty and allows reusing", () => {
+ const tab = createCleanTab({ sql: " \n\t " });
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(true);
+ });
+
+ it("rejects when tab has existing SQL to prevent clearing user work", () => {
+ const tab = createCleanTab({ sql: "SELECT * FROM users WHERE active = true;" });
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(false);
+ });
+
+ it("rejects when tab is on a different connection", () => {
+ const tab = createCleanTab({ connectionId: "mysql-1" });
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(false);
+ });
+
+ it("rejects when tab is on a different database", () => {
+ const tab = createCleanTab({ database: "production" });
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(false);
+ });
+
+ it("rejects when tab is on a different schema", () => {
+ const tab = createCleanTab({ schema: "archive" });
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(false);
+ });
+
+ it("rejects non-query tabs (e.g. data grid)", () => {
+ const tab = createCleanTab({ mode: "data" });
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(false);
+ });
+
+ it("rejects tabs linked to external SQL files", () => {
+ const tab = createCleanTab({ externalSqlPath: "/path/to/script.sql" });
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(false);
+ });
+
+ it("rejects tabs linked to saved SQL in library", () => {
+ const tab = createCleanTab({ savedSqlId: "saved-sql-123" });
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(false);
+ });
+
+ it("rejects tabs displaying object source views", () => {
+ const tab = createCleanTab({ objectSource: { schema: "public", name: "v_stats", objectType: "view" } });
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(false);
+ });
+
+ it("rejects tabs that are currently executing queries", () => {
+ const tab = createCleanTab({ isExecuting: true });
+ expect(canReuseTabForHistoryRestore(tab, target)).toBe(false);
+ });
+
+ it("rejects tabs that contain active query results", () => {
+ const tabWithResult = createCleanTab({
+ result: { columns: ["id"], rows: [[1]], execution_time_ms: 10, affected_rows: null },
+ });
+ expect(canReuseTabForHistoryRestore(tabWithResult, target)).toBe(false);
+
+ const tabWithResults = createCleanTab({
+ results: [{ columns: ["id"], rows: [[1]], execution_time_ms: 10, affected_rows: null }],
+ });
+ expect(canReuseTabForHistoryRestore(tabWithResults, target)).toBe(false);
+ });
+
+ it("rejects when tab is undefined", () => {
+ expect(canReuseTabForHistoryRestore(undefined, target)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/lib/history/historyRestoreTarget.ts b/apps/desktop/src/lib/history/historyRestoreTarget.ts
index e7d7ab8a4d..d8ad754bb1 100644
--- a/apps/desktop/src/lib/history/historyRestoreTarget.ts
+++ b/apps/desktop/src/lib/history/historyRestoreTarget.ts
@@ -9,13 +9,61 @@ export interface HistorySqlRestoreTarget {
schema?: string;
}
-export function resolveHistorySqlRestoreTarget(options: { entry: HistoryEntry; activeTab?: QueryTab; firstConnectionId?: string; getConfig: (connectionId: string) => ConnectionConfig | undefined }): HistorySqlRestoreTarget | null {
- const { entry, activeTab, firstConnectionId, getConfig } = options;
- const connectionId = entry.connection_id || activeTab?.connectionId || firstConnectionId;
+export function resolveHistorySqlRestoreTarget(options: { entry: HistoryEntry; activeTab?: QueryTab; firstConnectionId?: string; connections?: ConnectionConfig[]; getConfig: (connectionId: string) => ConnectionConfig | undefined }): HistorySqlRestoreTarget | null {
+ const { entry, activeTab, firstConnectionId, connections, getConfig } = options;
+ let connectionId: string | undefined;
+ if (entry.connection_id && getConfig(entry.connection_id)) {
+ connectionId = entry.connection_id;
+ } else if (entry.connection_name && connections) {
+ const matches = connections.filter((connection) => connection.name === entry.connection_name);
+ if (matches.length > 1) return null;
+ connectionId = matches[0]?.id;
+ }
+ if (!connectionId && entry.connection_id) {
+ connectionId = entry.connection_id;
+ }
+ connectionId = connectionId || activeTab?.connectionId || firstConnectionId;
if (!connectionId) return null;
+
const config = getConfig(connectionId);
- const storedDatabase = entry.database || activeTab?.database || (config ? resolveDefaultDatabase(config, []) : "");
+ const storedDatabase = entry.database || (activeTab?.connectionId === connectionId ? activeTab.database : "") || (config ? resolveDefaultDatabase(config, []) : "");
const database = config?.db_type === "sqlite" ? normalizeSqliteNamespace(storedDatabase, config) : storedDatabase;
- const schema = activeTab?.connectionId === connectionId && activeTab.database === database ? activeTab.schema : undefined;
+
+ let schema: string | undefined;
+ if (entry.details_json) {
+ try {
+ const details = JSON.parse(entry.details_json);
+ if (typeof details?.schema === "string" && details.schema) {
+ schema = details.schema;
+ }
+ } catch {}
+ }
+ if (!schema && activeTab?.connectionId === connectionId && activeTab.database === database) {
+ schema = activeTab.schema;
+ }
+ if (!schema && config?.default_schema) {
+ schema = config.default_schema;
+ }
+
return { connectionId, database: database || "", schema };
}
+
+/**
+ * Determines whether an existing active tab can be safely reused for restoring history SQL.
+ * To avoid clearing or overwriting user's active work, a tab is only reusable if:
+ * 1. It is a query tab (not a data grid, structure editor, etc.)
+ * 2. It has no user-typed or existing SQL (empty / whitespace-only)
+ * 3. It is not an external file, saved SQL document, or object source view
+ * 4. It is not currently executing and has no active results
+ * 5. Its connection, database, and schema match the restore target
+ */
+export function canReuseTabForHistoryRestore(tab: QueryTab | undefined, target: HistorySqlRestoreTarget): boolean {
+ if (!tab || tab.mode !== "query") return false;
+ if (tab.sql.trim().length > 0) return false;
+ if (tab.savedSqlId || tab.externalSqlPath || tab.objectSource) return false;
+ if (tab.isExecuting || tab.result || (tab.results && tab.results.length > 0)) return false;
+ if (tab.connectionId !== target.connectionId) return false;
+ if ((tab.database || "") !== (target.database || "")) return false;
+ if ((tab.schema || "") !== (target.schema || "")) return false;
+ return true;
+}