fix(duckdb): restore parquet preview and reclaim connections

This commit is contained in:
Xinyu Kuo authored and GitHub committed 2026-08-15 14:41:16 +08:00
1 parent a407c77a16
commit 84f1498a4b
16 files changed
+470 -19

No files matched your search

@@ -0,0 +1,122 @@
import { createPinia, setActivePinia } from "pinia";
import { afterEach, 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 installApiMocks() {
vi.doMock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
vi.doMock("@/lib/backend/api", () => ({
checkConnectionHealth: vi.fn().mockResolvedValue(undefined),
connectDb: vi.fn().mockResolvedValue("preview-1"),
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),
listInstalledAgents: vi.fn().mockResolvedValue([]),
sessionCredentialStatus: vi.fn().mockResolvedValue(false),
forgetSessionCredential: vi.fn().mockResolvedValue(undefined),
}));
// Result-snapshot cleanup hits a relative URL, which node's fetch rejects outright.
// Unrelated to what these cases assert.
vi.doMock("@/lib/tabs/tabResultCache", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/tabs/tabResultCache")>();
return { ...actual, deleteTabResultSnapshotsForOwner: vi.fn().mockResolvedValue(undefined) };
});
}
function previewConnection(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {
return {
id: "preview-1",
name: "[Preview] sales.parquet",
db_type: "duckdb",
host: ":memory:",
port: 0,
username: "",
password: "",
one_time: true,
...overrides,
} as ConnectionConfig;
}
describe("connectionStore one_time runtime cleanup", () => {
beforeEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
installLocalStorage();
setActivePinia(createPinia());
});
afterEach(() => {
vi.restoreAllMocks();
});
// One-time connections are never persisted, so the backend's save_connections
// sync never reclaims them; disconnect_db is the only reclaim point, which makes
// an explicit disconnect on removal mandatory.
it("removeConnection disconnects a one_time connection so the backend can reclaim it", async () => {
installApiMocks();
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
store.connections = [previewConnection()];
await store.removeConnection("preview-1");
const { disconnectDb } = await import("@/lib/backend/api");
// No clientAttempt: removal is terminal, so a superseded attempt number must not
// skip the cleanup.
expect(disconnectDb).toHaveBeenCalledWith("preview-1");
});
it("removeConnection leaves saved connections to the save_connections sync", async () => {
installApiMocks();
const { useConnectionStore } = await import("@/stores/connectionStore");
const store = useConnectionStore();
store.connections = [previewConnection({ id: "saved-1", one_time: false })];
await store.removeConnection("saved-1");
const { disconnectDb } = await import("@/lib/backend/api");
expect(disconnectDb).not.toHaveBeenCalled();
});
// The connection is gone for good, so its tabs can never reconnect: executing in
// one would fail with "Connection config not found".
it("removeConnection closes the tabs of a one_time connection", async () => {
installApiMocks();
const { useConnectionStore } = await import("@/stores/connectionStore");
const { useQueryStore } = await import("@/stores/queryStore");
const store = useConnectionStore();
const queryStore = useQueryStore();
store.connections = [previewConnection()];
queryStore.createTab("preview-1", "", "sales.parquet", "query");
expect(queryStore.tabs.some((tab) => tab.connectionId === "preview-1")).toBe(true);
await store.removeConnection("preview-1");
expect(queryStore.tabs.some((tab) => tab.connectionId === "preview-1")).toBe(false);
});
it("removeConnection keeps the tabs of a saved connection for the disconnect handling mode", async () => {
installApiMocks();
const { useConnectionStore } = await import("@/stores/connectionStore");
const { useQueryStore } = await import("@/stores/queryStore");
const store = useConnectionStore();
const queryStore = useQueryStore();
store.connections = [previewConnection({ id: "saved-1", one_time: false })];
queryStore.createTab("saved-1", "", "query.sql", "query");
await store.removeConnection("saved-1");
expect(queryStore.tabs.some((tab) => tab.connectionId === "saved-1")).toBe(true);
});
});
@@ -711,6 +711,44 @@ export const useConnectionStore = defineStore("connection", () => {
return trackDisconnectRequest(connectionId, request, clientAttempt != null);
}
/**
* One-time connections are never persisted, so the backend's "not in the saved
* list, so reclaim it" branch in `sync_connection_configs` never fires for them
* (see dbx-core `should_retain_runtime_config`) and `disconnect_db` is the only
* reclaim point. Removing one must disconnect it explicitly, or its runtime
* config, pool, and tunnel live until the process exits.
*
* `clientAttempt` is deliberately omitted: removal is terminal, so a superseded
* attempt number must not skip the cleanup.
*/
function releaseOneTimeRuntimeConnections(connectionIds: string[]) {
for (const connectionId of connectionIds) {
let request: Promise<void>;
try {
request = api.disconnectDb(connectionId);
} catch (error) {
request = Promise.reject(error);
}
void trackDisconnectRequest(connectionId, request, false).catch(() => {});
}
}
/**
* A one-time connection is deleted outright rather than left behind for a
* reconnect, so its tabs have nothing to point at once it is gone: executing in
* one would fail with "Connection config not found". Close them regardless of
* `disconnectTabHandlingMode`, which only makes sense for connections that can
* still be reconnected.
*/
async function closeOneTimeConnectionTabs(connectionIds: string[]) {
if (!connectionIds.length) return;
const { useQueryStore } = await import("@/stores/queryStore");
const queryStore = useQueryStore();
for (const connectionId of connectionIds) {
queryStore.closeConnectionTabs(connectionId);
}
}
function cancelDisconnectKey(connectionId: string, attempt: number): string {
return `${connectionId}:${attempt}`;
}
@@ -2700,8 +2738,11 @@ export const useConnectionStore = defineStore("connection", () => {
if (!connectionIds.length) return;
const removedIds = new Set(connectionIds);
const oneTimeIds = connectionIds.filter((id) => getConfig(id)?.one_time === true);
const nextConnections = connections.value.filter((c) => !removedIds.has(c.id));
await persistConnections(nextConnections);
await closeOneTimeConnectionTabs(oneTimeIds);
releaseOneTimeRuntimeConnections(oneTimeIds);
await persistTimeoutInheritanceIds(
settingsStore.editorSettings.connectTimeoutInheritConnectionIds.filter((id) => !removedIds.has(id)),
settingsStore.editorSettings.queryTimeoutInheritConnectionIds.filter((id) => !removedIds.has(id)),