fix(query): sync open executors after default database edit

This commit is contained in:
Melody Ruch authored and GitHub committed 2026-09-29 21:26:17 +08:00
1 parent c8aed1b6e5
commit edd2592869
3 files changed
+108

No files matched your search

@@ -0,0 +1,87 @@
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ConnectionConfig } from "@/types/database";
function installLocalStorage() {
const data = new Map<string, string>();
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => data.get(key) ?? null),
setItem: vi.fn((key: string, value: string) => data.set(key, value)),
removeItem: vi.fn((key: string) => data.delete(key)),
});
}
function postgresConnection(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {
return {
id: "pg-1",
name: "Reporting",
db_type: "postgres",
host: "127.0.0.1",
port: 5432,
username: "postgres",
password: "secret",
database: "testdb",
read_only: false,
...overrides,
} as ConnectionConfig;
}
async function createStores() {
vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
vi.doMock("@/lib/backend/api", () => ({
checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
disconnectDb: vi.fn().mockResolvedValue(undefined),
deleteSchemaCachePrefix: vi.fn().mockResolvedValue(undefined),
loadSchemaCache: vi.fn().mockResolvedValue(null),
saveConnections: vi.fn().mockResolvedValue(undefined),
saveSidebarLayout: vi.fn().mockResolvedValue(undefined),
connectionDatabaseInfo: vi.fn().mockResolvedValue(undefined),
}));
const { useConnectionStore } = await import("@/stores/connectionStore");
const { useQueryStore } = await import("@/stores/queryStore");
return { connectionStore: useConnectionStore(), queryStore: useQueryStore() };
}
describe("connectionStore updateConnection re-syncs open query tabs' database", () => {
beforeEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
installLocalStorage();
setActivePinia(createPinia());
});
it("re-points a tab still on the connection's old default database, but leaves a tab the user pointed elsewhere alone", async () => {
const { connectionStore, queryStore } = await createStores();
const connection = postgresConnection();
connectionStore.connections = [connection];
// Opened before the edit, still on the connection's original default database (#7905 repro).
const staleTabId = queryStore.createTab("pg-1", "testdb", "stale query");
queryStore.setTableMeta(staleTabId, { schema: "public", database: "testdb", tableName: "users", tableType: "TABLE", columns: [], primaryKeys: [] });
// A tab the user explicitly pointed at a different database via the tab's own
// connection/database switcher — must not be silently reassigned.
const explicitTabId = queryStore.createTab("pg-1", "reporting_archive", "explicit query", "query", undefined, undefined, undefined, { forceNew: true });
await connectionStore.updateConnection({ ...connection, database: "hive313" });
expect(connectionStore.getConfig("pg-1")?.database).toBe("hive313");
const staleTab = queryStore.tabs.find((tab) => tab.id === staleTabId);
expect(staleTab?.database).toBe("hive313");
// The stale snapshot's cached metadata/result state must not survive the switch.
expect(staleTab?.tableMeta).toBeUndefined();
const explicitTab = queryStore.tabs.find((tab) => tab.id === explicitTabId);
expect(explicitTab?.database).toBe("reporting_archive");
});
it("does nothing to open tabs when the edited connection's database is unchanged", async () => {
const { connectionStore, queryStore } = await createStores();
const connection = postgresConnection();
connectionStore.connections = [connection];
const tabId = queryStore.createTab("pg-1", "testdb", "unaffected query");
await connectionStore.updateConnection({ ...connection, host: "new-host.internal" });
expect(queryStore.tabs.find((tab) => tab.id === tabId)?.database).toBe("testdb");
});
});
@@ -4051,6 +4051,7 @@ export const useConnectionStore = defineStore("connection", () => {
const idx = connections.value.findIndex((c) => c.id === config.id); const idx = connections.value.findIndex((c) => c.id === config.id);
if (idx < 0) return; if (idx < 0) return;
const previousConfig = normalizeConnection(connections.value[idx]); const previousConfig = normalizeConnection(connections.value[idx]);
const previousDatabase = previousConfig.database ?? "";
const runtimeConfigChanged = connectionConfigFingerprint(previousConfig) !== connectionConfigFingerprint(config); const runtimeConfigChanged = connectionConfigFingerprint(previousConfig) !== connectionConfigFingerprint(config);
const shouldReconnectPlugin = runtimeConfigChanged && previousConfig.db_type === "plugin" && config.db_type === "plugin" && connectedIds.value.has(config.id); const shouldReconnectPlugin = runtimeConfigChanged && previousConfig.db_type === "plugin" && config.db_type === "plugin" && connectedIds.value.has(config.id);
const nextConnections = [...connections.value]; const nextConnections = [...connections.value];
@@ -4062,6 +4063,11 @@ export const useConnectionStore = defineStore("connection", () => {
rebuildTreeNodes(); rebuildTreeNodes();
if (!runtimeConfigChanged) return; if (!runtimeConfigChanged) return;
clearEtcdAccessCapabilities(config.id); clearEtcdAccessCapabilities(config.id);
// Tabs opened before this edit keep whatever database they were created
// with (queryStore snapshots it onto the tab); re-point the ones still on
// the old default so their query executor stops running against it (#7905).
const { useQueryStore } = await import("@/stores/queryStore");
useQueryStore().syncTabsDatabaseForConnectionEdit(config.id, previousDatabase, config.database ?? "");
clearPrimaryVisibleObjectNames(config.id); clearPrimaryVisibleObjectNames(config.id);
connectedIds.value.delete(config.id); connectedIds.value.delete(config.id);
clearSidebarStorageCaches(config.id); clearSidebarStorageCaches(config.id);
+15
View File
@@ -5537,6 +5537,20 @@ export const useQueryStore = defineStore("query", () => {
persistSavedSqlExecutionTarget(tab, options); persistSavedSqlExecutionTarget(tab, options);
} }
/**
* Editing a saved connection's default database (Connection dialog Save) only
* updates the connection record — tabs opened before the edit keep whatever
* database was snapshotted onto them at creation time (issue #7905). Re-point
* every open tab that was still on the connection's old default over to the
* new one, same as if the tab had just been created fresh.
*/
function syncTabsDatabaseForConnectionEdit(connectionId: string, previousDatabase: string, nextDatabase: string) {
if (previousDatabase === nextDatabase) return;
for (const tab of tabs.value) {
if (tab.connectionId === connectionId && tab.database === previousDatabase) updateDatabase(tab.id, nextDatabase);
}
}
function updateCatalog(id: string, catalog: string | undefined, database: string, options: UpdateExecutionTargetOptions = {}) { function updateCatalog(id: string, catalog: string | undefined, database: string, options: UpdateExecutionTargetOptions = {}) {
const tab = tabs.value.find((candidate) => candidate.id === id); const tab = tabs.value.find((candidate) => candidate.id === id);
if (!tab || (tab.catalog === catalog && tab.database === database)) return; if (!tab || (tab.catalog === catalog && tab.database === database)) return;
@@ -9489,6 +9503,7 @@ export const useQueryStore = defineStore("query", () => {
reorderTab, reorderTab,
createExecutionTargetGuard, createExecutionTargetGuard,
updateDatabase, updateDatabase,
syncTabsDatabaseForConnectionEdit,
updateCatalog, updateCatalog,
updateSchema, updateSchema,
updateConnection, updateConnection,