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(sidebar): search all connected roots in global search (#13763)

雨下的樱花丷3021a95c26aa
diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vue
index b4058c61d3..7ee19401fd 100644
--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue
+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue
@@ -28,6 +28,7 @@ import { createSidebarLabelMatcher } from "@/lib/sidebar/sidebarSearch";
import { firstSidebarSearchMatchDataNode, hasActiveSidebarSearch } from "@/lib/sidebar/sidebarSearchEnter";
import { collectSidebarRegexIndexScopes } from "@/lib/sidebar/sidebarRegexSearchIndex";
import { collectSidebarGlobalSearchIndexes, sidebarIndexedObjectGroupTypes } from "@/lib/sidebar/sidebarGlobalSearchIndex";
+import { runSidebarSearchTasks } from "./sidebarSearchTaskRunner";
import { resolveSidebarSearchDatabaseScope } from "@/lib/sidebar/sidebarSearchDatabaseScope";
import { useSidebarSearchIndexes } from "@/composables/useSidebarSearchIndexes";
import { useSidebarRemoteSearch } from "@/composables/useSidebarRemoteSearch";
@@ -534,25 +535,31 @@ const localTableSearchResults = ref<Record<string, TableInfo[] | null>>({});
const localTableSearchRequestRevisions = new Map<string, number>();
type InvalidatedTableSearchScope = SidebarRegexScopeIdentity & { parentNodeId: string };
const pendingInvalidatedTableSearchScopes = new Map<string, InvalidatedTableSearchScope>();
+function globalSearchConnectionRoots() {
+ return [...store.connectedIds].flatMap((connectionId) => {
+ const path = findNodePathByIdentity(store.treeNodes, connectionId, { connectionId, database: "", nodeType: "connection" });
+ const root = path?.[path.length - 1];
+ return root ? [{ connectionId, root }] : [];
+ });
+}
+
const globalSearchContext = [
() => regexMode.value,
() => settingsStore.editorSettings.sidebarGlobalSearchLocal,
() => settingsStore.editorSettings.sidebarObjectDisplay,
() => settingsStore.editorSettings.sidebarSearchOpenedDatabasesOnly,
- () => store.activeConnectionId,
() => [...store.connectedIds].sort().join("\0"),
() => [...queryStore.openDatabaseKeys].sort().join("\0"),
() => {
if (!settingsStore.editorSettings.sidebarSearchOpenedDatabasesOnly) return "";
- const connectionId = store.activeConnectionId;
- if (!connectionId) return "";
- const rootPath = findNodePathByIdentity(store.treeNodes, connectionId, { connectionId, database: "", nodeType: "connection" });
- const root = rootPath?.[rootPath.length - 1];
- if (!root) return "";
- const scope = resolveSidebarSearchDatabaseScope(root, { enabled: true, isChildrenLoaded: store.isTreeNodeChildrenLoaded, openDatabaseKeys: queryStore.openDatabaseKeys });
// Tree-only opens do not change editor tab keys. Observe scope membership,
// not descendant metadata or expansion flags, to avoid restarting builds.
- return JSON.stringify([...(scope ?? [])].sort());
+ return JSON.stringify(
+ globalSearchConnectionRoots().map(({ connectionId, root }) => {
+ const scope = resolveSidebarSearchDatabaseScope(root, { enabled: true, isChildrenLoaded: store.isTreeNodeChildrenLoaded, openDatabaseKeys: queryStore.openDatabaseKeys });
+ return [connectionId, [...(scope ?? [])].sort()];
+ }),
+ );
},
() => store.sidebarTableSearchIndexInvalidation.revision,
() => selectedSearchScopes.value.join(","),
@@ -577,22 +584,24 @@ const {
const isSidebarSearchLoading = computed(() => isGlobalIndexLoading.value || isRemoteSearchLoading.value);
async function loadGlobalRemoteSearchResults(query: string, signal: AbortSignal, onProgress: (results: SidebarRemoteSearchResult[]) => void) {
- const connectionId = store.activeConnectionId;
- if (!connectionId || !store.connectedIds.has(connectionId) || signal.aborted) return [];
- const rootPath = findNodePathByIdentity(store.treeNodes, connectionId, { connectionId, database: "", nodeType: "connection" });
- const root = rootPath?.[rootPath.length - 1];
- if (!root) return [];
- return collectSidebarRemoteSearchResults({
- root,
- connectionId,
- databaseScope: resolveSidebarSearchDatabaseScope(root, { enabled: settingsStore.editorSettings.sidebarSearchOpenedDatabasesOnly, isChildrenLoaded: store.isTreeNodeChildrenLoaded, openDatabaseKeys: queryStore.openDatabaseKeys }),
- signal,
- isSimpleParent: (node) => !sidebarIndexedObjectGroupTypes.has(node.type) && isGlobalTableIndexParent(node),
- discover: discoverGlobalSearchChildren,
- search: (node, publish) => store.searchSidebarObjects(node, query, signal, publish),
- onProgress,
- onError: (error) => toast(error instanceof Error ? error.message : String(error), 5000),
- });
+ const results: SidebarRemoteSearchResult[][] = [];
+ await runSidebarSearchTasks(
+ globalSearchConnectionRoots().map(({ connectionId, root }, index) => async () => {
+ if (signal.aborted || !store.connectedIds.has(connectionId)) return;
+ results[index] = await collectSidebarRemoteSearchResults({
+ root,
+ connectionId,
+ databaseScope: resolveSidebarSearchDatabaseScope(root, { enabled: settingsStore.editorSettings.sidebarSearchOpenedDatabasesOnly, isChildrenLoaded: store.isTreeNodeChildrenLoaded, openDatabaseKeys: queryStore.openDatabaseKeys }),
+ signal,
+ isSimpleParent: (node) => !sidebarIndexedObjectGroupTypes.has(node.type) && isGlobalTableIndexParent(node),
+ discover: discoverGlobalSearchChildren,
+ search: (node, publish) => store.searchSidebarObjects(node, query, signal, publish),
+ onProgress,
+ onError: (error) => toast(error instanceof Error ? error.message : String(error), 5000),
+ });
+ }),
+ );
+ return results.flat();
}
function isGlobalTableIndexParent(node: TreeNode): boolean {
@@ -632,36 +641,45 @@ async function loadGlobalTableSearchIndexes(shouldCancel: () => boolean, onProgr
shouldCancel,
);
}
- const connectionId = store.activeConnectionId;
- if (!connectionId || !store.connectedIds.has(connectionId)) return [];
- const rootPath = findNodePathByIdentity(store.treeNodes, connectionId, { connectionId, database: "", nodeType: "connection" });
- const root = rootPath?.[rootPath.length - 1];
- if (!root) return [];
- const databaseScope = resolveSidebarSearchDatabaseScope(root, {
- enabled: settingsStore.editorSettings.sidebarSearchOpenedDatabasesOnly,
- isChildrenLoaded: store.isTreeNodeChildrenLoaded,
- openDatabaseKeys: queryStore.openDatabaseKeys,
- });
- return collectSidebarGlobalSearchIndexes(
- {
- loadCachedScopes: async () =>
- (await store.loadSidebarTableSearchIndexScopes((scope) => scope.connectionId === connectionId && (settingsStore.editorSettings.sidebarObjectDisplay === "simple" ? !scope.nodeType.startsWith("group-") : sidebarIndexedObjectGroupTypes.has(scope.nodeType as TreeNodeType)))).map(
- ({ scope, entries, stale }) => ({ ...scope, entries, stale }),
- ),
- isIndexParent: isGlobalTableIndexParent,
- discover: discoverGlobalSearchChildren,
- loadIndex: (node, options) => {
- if (shouldCancel() || !store.connectedIds.has(connectionId)) return Promise.resolve(null);
- return store.ensureSidebarTableSearchIndex(node.id, deferredSearchQuery.value, { connectionId, database: node.database ?? "", schema: node.schema, catalog: node.catalog, nodeType: node.type }, { connectedOnly: true, refresh: options?.refresh });
- },
- onError: (_node, error) => toast(error instanceof Error ? error.message : String(error), 5000),
- },
- [root],
- connectionId,
- databaseScope,
- shouldCancel,
- onProgress,
+ const results: SidebarRegexIndexScope[][] = [];
+ await runSidebarSearchTasks(
+ globalSearchConnectionRoots().map(({ connectionId, root }, index) => async () => {
+ if (shouldCancel() || !store.connectedIds.has(connectionId)) return;
+ const databaseScope = resolveSidebarSearchDatabaseScope(root, {
+ enabled: settingsStore.editorSettings.sidebarSearchOpenedDatabasesOnly,
+ isChildrenLoaded: store.isTreeNodeChildrenLoaded,
+ openDatabaseKeys: queryStore.openDatabaseKeys,
+ });
+ try {
+ results[index] = await collectSidebarGlobalSearchIndexes(
+ {
+ loadCachedScopes: async () =>
+ (await store.loadSidebarTableSearchIndexScopes((scope) => scope.connectionId === connectionId && (settingsStore.editorSettings.sidebarObjectDisplay === "simple" ? !scope.nodeType.startsWith("group-") : sidebarIndexedObjectGroupTypes.has(scope.nodeType as TreeNodeType)))).map(
+ ({ scope, entries, stale }) => ({ ...scope, entries, stale }),
+ ),
+ isIndexParent: isGlobalTableIndexParent,
+ discover: discoverGlobalSearchChildren,
+ loadIndex: (node, options) => {
+ if (shouldCancel() || !store.connectedIds.has(connectionId)) return Promise.resolve(null);
+ return store.ensureSidebarTableSearchIndex(node.id, deferredSearchQuery.value, { connectionId, database: node.database ?? "", schema: node.schema, catalog: node.catalog, nodeType: node.type }, { connectedOnly: true, refresh: options?.refresh });
+ },
+ onError: (_node, error) => toast(error instanceof Error ? error.message : String(error), 5000),
+ },
+ [root],
+ connectionId,
+ databaseScope,
+ shouldCancel,
+ (scopes) => {
+ results[index] = scopes;
+ onProgress(results.flat());
+ },
+ );
+ } catch (error) {
+ if (!shouldCancel()) toast(error instanceof Error ? error.message : String(error), 5000);
+ }
+ }),
);
+ return results.flat();
}
function filterGloballyIndexedTables(nodes: TreeNode[]): TreeNode[] {
diff --git a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.remoteSearch.spec.ts b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.remoteSearch.spec.ts
index 32d290885d..87738a5b59 100644
--- a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.remoteSearch.spec.ts
+++ b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.remoteSearch.spec.ts
@@ -7,9 +7,10 @@ import { findNodePathByIdentity } from "@/lib/sidebar/sidebarSearchTree";
import { sidebarIndexedObjectGroupTypes } from "@/lib/sidebar/sidebarGlobalSearchIndex";
import { resolveSidebarSearchDatabaseScope } from "@/lib/sidebar/sidebarSearchDatabaseScope";
import type { TreeNode } from "@/types/database";
+import { runSidebarSearchTasks } from "../sidebarSearchTaskRunner";
import { compileConnectionTreeTestScript } from "./connectionTreeTestScript";
-const compiled = compileConnectionTreeTestScript(["loadGlobalRemoteSearchResults", "isGlobalTableIndexParent", "discoverGlobalSearchChildren", "globalSearchContext", "remoteSearchResults"]);
+const compiled = compileConnectionTreeTestScript(["globalSearchConnectionRoots", "loadGlobalRemoteSearchResults", "isGlobalTableIndexParent", "discoverGlobalSearchChildren", "globalSearchContext", "remoteSearchResults"]);
const cleanups: Array<() => void> = [];
beforeEach(() => vi.useFakeTimers());
@@ -49,6 +50,7 @@ function mountSearch() {
selectedSearchScopes: ref([]),
searchableNodeTypes: ref(undefined),
useSidebarRemoteSearch,
+ runSidebarSearchTasks,
collectSidebarRemoteSearchResults,
findNodePathByIdentity,
sidebarIndexedObjectGroupTypes,
diff --git a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.searchScope.spec.ts b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.searchScope.spec.ts
index f1c46b7be4..4d93589e16 100644
--- a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.searchScope.spec.ts
+++ b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.searchScope.spec.ts
@@ -9,9 +9,10 @@ import { collectSidebarRemoteSearchResults, type SidebarRemoteSearchResult } fro
import { findNodePathByIdentity, type SidebarRegexIndexScope } from "@/lib/sidebar/sidebarSearchTree";
import { resolveSidebarSearchDatabaseScope } from "@/lib/sidebar/sidebarSearchDatabaseScope";
import type { TableInfo, TreeNode } from "@/types/database";
+import { runSidebarSearchTasks } from "../sidebarSearchTaskRunner";
import { compileConnectionTreeTestScript } from "./connectionTreeTestScript";
-const compiled = compileConnectionTreeTestScript(["globalSearchContext", "globalTableSearchScopes", "remoteSearchResults", "loadGlobalTableSearchIndexes", "loadGlobalRemoteSearchResults", "isGlobalTableIndexParent", "discoverGlobalSearchChildren"]);
+const compiled = compileConnectionTreeTestScript(["globalSearchConnectionRoots", "globalSearchContext", "globalTableSearchScopes", "remoteSearchResults", "loadGlobalTableSearchIndexes", "loadGlobalRemoteSearchResults", "isGlobalTableIndexParent", "discoverGlobalSearchChildren"]);
const cleanups: Array<() => void> = [];
beforeEach(() => vi.useFakeTimers());
@@ -38,7 +39,7 @@ function fixture(display: "grouped" | "simple" = "grouped") {
loadConnectedConnectionRootForSidebarSearch: vi.fn(),
loadTreeNodeChildren: vi.fn(async (node: TreeNode) => openDatabase(node)),
ensureSidebarTableSearchIndex: vi.fn(async (): Promise<TableInfo[]> => [{ name: "late_orders", table_type: "TABLE" }]),
- searchSidebarObjects: vi.fn(async (node: TreeNode): Promise<TreeNode[]> => [{ id: `${node.id}:routine`, label: "late_routine", type: "procedure", connectionId: "conn", database: node.database }]),
+ searchSidebarObjects: vi.fn(async (node: TreeNode): Promise<TreeNode[]> => [{ id: `${node.id}:routine`, label: "late_routine", type: "procedure", connectionId: node.connectionId, database: node.database }]),
});
const onError = vi.fn();
const bindings = {
@@ -54,6 +55,7 @@ function fixture(display: "grouped" | "simple" = "grouped") {
useSidebarSearchIndexes,
useSidebarRemoteSearch,
collectSidebarGlobalSearchIndexes,
+ runSidebarSearchTasks,
collectSidebarRemoteSearchResults,
findNodePathByIdentity,
sidebarIndexedObjectGroupTypes,
@@ -78,10 +80,10 @@ function fixture(display: "grouped" | "simple" = "grouped") {
node.children =
display === "grouped"
? [
- { id: `${node.id}:tables`, label: "Tables", type: "group-tables", connectionId: "conn", database: node.database, isExpanded: false, children: [] },
- { id: `${node.id}:procedures`, label: "Procedures", type: "group-procedures", connectionId: "conn", database: node.database, isExpanded: false, children: [] },
+ { id: `${node.id}:tables`, label: "Tables", type: "group-tables", connectionId: node.connectionId, database: node.database, isExpanded: false, children: [] },
+ { id: `${node.id}:procedures`, label: "Procedures", type: "group-procedures", connectionId: node.connectionId, database: node.database, isExpanded: false, children: [] },
]
- : [{ id: `${node.id}:first_page`, label: "first_page", type: "table", connectionId: "conn", database: node.database }];
+ : [{ id: `${node.id}:first_page`, label: "first_page", type: "table", connectionId: node.connectionId, database: node.database }];
node.isExpanded = true;
loadedIds.add(node.id);
}
@@ -89,6 +91,98 @@ function fixture(display: "grouped" | "simple" = "grouped") {
return { ...state, searchQuery, databases, store, settingsStore, queryStore, loadedIds, openDatabase, onError };
}
+function addConnection(view: ReturnType<typeof fixture>, connectionId: string, connected = true) {
+ const database = reactive<TreeNode>({ id: `${connectionId}:app`, label: "app", type: "database", connectionId, database: "app", children: [] });
+ view.store.treeNodes.push({ id: `folder:${connectionId}`, label: "Folder", type: "connection-group", children: [{ id: connectionId, label: connectionId, type: "connection", connectionId, children: [database] }] });
+ view.loadedIds.add(connectionId);
+ if (connected) view.store.connectedIds.add(connectionId);
+ return database;
+}
+
+test.each(["grouped", "simple"] as const)("aggregates same-name tables across connected roots in %s mode without an active connection", async (display) => {
+ const view = fixture(display);
+ view.openDatabase(view.databases[0]);
+ view.openDatabase(addConnection(view, "second"));
+ view.openDatabase(addConnection(view, "offline", false));
+ view.store.activeConnectionId = "";
+
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ view.searchQuery.value = "late";
+ await vi.advanceTimersByTimeAsync(350);
+ expect(view.globalTableSearchScopes.value.map((scope) => [scope.connectionId, scope.entries[0].name]).sort()).toEqual([
+ ["conn", "late_orders"],
+ ["second", "late_orders"],
+ ]);
+ expect(view.remoteSearchResults.value.map((scope) => scope.connectionId).sort()).toEqual(["conn", "second"]);
+ view.searchQuery.value = "";
+ await vi.advanceTimersByTimeAsync(350);
+ }
+ expect(view.store.loadTreeNodeChildren).not.toHaveBeenCalled();
+ expect(view.onError).not.toHaveBeenCalled();
+});
+
+test("opening a database on an inactive connection refreshes search without resetting on selection changes", async () => {
+ const view = fixture();
+ view.openDatabase(view.databases[0]);
+ const other = addConnection(view, "second");
+ view.searchQuery.value = "late";
+ await vi.advanceTimersByTimeAsync(350);
+ expect(view.globalTableSearchScopes.value.map((scope) => scope.connectionId)).toEqual(["conn"]);
+
+ view.openDatabase(other);
+ await vi.advanceTimersByTimeAsync(350);
+ expect(view.globalTableSearchScopes.value.map((scope) => scope.connectionId).sort()).toEqual(["conn", "second"]);
+ expect(view.remoteSearchResults.value.map((scope) => scope.connectionId).sort()).toEqual(["conn", "second"]);
+ const tableCalls = view.store.ensureSidebarTableSearchIndex.mock.calls.length;
+ const remoteCalls = view.store.searchSidebarObjects.mock.calls.length;
+ view.store.activeConnectionId = "second";
+ await vi.advanceTimersByTimeAsync(350);
+ expect(view.store.ensureSidebarTableSearchIndex).toHaveBeenCalledTimes(tableCalls);
+ expect(view.store.searchSidebarObjects).toHaveBeenCalledTimes(remoteCalls);
+ expect(view.store.loadTreeNodeChildren).not.toHaveBeenCalled();
+});
+
+test.each(["complete", "disconnect"])("publishes a second connection while the first is pending and handles its late %s", async (action) => {
+ const view = fixture();
+ view.openDatabase(view.databases[0]);
+ view.openDatabase(addConnection(view, "second"));
+ let finishIndex!: (entries: TableInfo[]) => void;
+ let finishRemote!: (nodes: TreeNode[]) => void;
+ view.store.ensureSidebarTableSearchIndex.mockImplementationOnce(() => new Promise((resolve) => (finishIndex = resolve)));
+ view.store.searchSidebarObjects.mockImplementationOnce(() => new Promise((resolve) => (finishRemote = resolve)));
+ view.searchQuery.value = "late";
+ await vi.advanceTimersByTimeAsync(350);
+
+ expect(view.globalTableSearchScopes.value.map((scope) => scope.connectionId)).toEqual(["second"]);
+ expect(view.remoteSearchResults.value.map((scope) => scope.connectionId)).toEqual(["second"]);
+ if (action === "disconnect") {
+ view.store.connectedIds.delete("conn");
+ await vi.advanceTimersByTimeAsync(350);
+ }
+ finishIndex([{ name: "late_orders", table_type: "TABLE" }]);
+ finishRemote([{ id: "conn:app:routine", label: "late_routine", type: "procedure", connectionId: "conn", database: "app" }]);
+ await vi.advanceTimersByTimeAsync(0);
+
+ const expected = action === "complete" ? ["conn", "second"] : ["second"];
+ expect(view.globalTableSearchScopes.value.map((scope) => scope.connectionId).sort()).toEqual(expected);
+ expect(view.remoteSearchResults.value.map((scope) => scope.connectionId).sort()).toEqual(expected);
+ expect(view.onError).not.toHaveBeenCalled();
+});
+
+test("keeps another connection's table and routine results when one connection fails", async () => {
+ const view = fixture();
+ view.openDatabase(view.databases[0]);
+ view.openDatabase(addConnection(view, "second"));
+ view.store.loadSidebarTableSearchIndexScopes.mockRejectedValueOnce(new Error("cache unavailable"));
+ view.store.searchSidebarObjects.mockRejectedValueOnce(new Error("metadata unavailable"));
+ view.searchQuery.value = "late";
+ await vi.advanceTimersByTimeAsync(350);
+
+ expect(view.globalTableSearchScopes.value.map((scope) => scope.connectionId)).toEqual(["second"]);
+ expect(view.remoteSearchResults.value.map((scope) => scope.connectionId)).toEqual(["second"]);
+ expect(view.onError).toHaveBeenCalledTimes(2);
+});
+
test.each(["grouped", "simple"] as const)("indexes a database opened during %s search without clearing the query", async (display) => {
const view = fixture(display);
view.searchQuery.value = "north";