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): restore lazy database expansion while searching

onenewcode7fda083a6fe7
diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vue
index e91b7924f8..493e077f70 100644
--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue
+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue
@@ -523,6 +523,18 @@ const globalSearchContext = [
() => 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());
+ },
() => store.sidebarTableSearchIndexInvalidation.revision,
() => selectedSearchScopes.value.join(","),
];
@@ -2106,6 +2118,9 @@ function onSearchToggle(node: TreeNode) {
}
function onNodeToggled(node: TreeNode, expanded: boolean) {
+ // Explicit cached toggles may act on a search copy; synchronize only the
+ // expansion state, never replace the live subtree with projected children.
+ syncSidebarTreeNodeExpansion(store.treeNodes, node, expanded);
if (isTreeSearchFiltering.value) return;
sidebarLayoutMonitor.recordEvent({
type: "expand-toggle",
@@ -2114,7 +2129,6 @@ function onNodeToggled(node: TreeNode, expanded: boolean) {
nodeType: node.type,
expanded,
});
- syncSidebarTreeNodeExpansion(store.treeNodes, node, expanded);
}
let contextMenuRequest = 0;
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index cdb822a5de..0cae18cb03 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -288,7 +288,7 @@ import { buildXuguCompileSql } from "@/lib/database/xuguCompileSql";
import { buildDamengCompileViewSql } from "@/lib/database/damengCompileSql";
import { buildTriggerToggleSql, supportsTriggerToggle } from "@/lib/database/triggerToggleSql";
import type { SidebarDataOpenRequest } from "@/lib/sidebar/sidebarDataOpenCoordinator";
-import { createSidebarActionRequest, createSidebarActionTarget, findSidebarActionTarget, releaseRemovedSidebarActionTarget, type SidebarActionRequest, type SidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";
+import { createSidebarActionRequest, createSidebarActionTarget, findSidebarActionTarget, matchesSidebarActionTarget, releaseRemovedSidebarActionTarget, type SidebarActionRequest, type SidebarActionTarget } from "@/lib/sidebar/sidebarActionTarget";
import { collapseSubtreeDescendants } from "@/lib/sidebar/sidebarTreeCollapse";
import { createSidebarMenuContext, normalizeSidebarMenuDescriptors } from "@/lib/sidebar/sidebarTreeMenuDescriptors";
import { driverProfileDatabaseWorkspace } from "@/lib/database/driverProfileExtensions";
@@ -954,12 +954,17 @@ async function toggle(requestId = beginNavigationRequest()) {
emit("search-toggle", node);
const wasExpanded = !!node.isExpanded;
- // A search result is a projection over children that are already loaded for
- // the query. Expanding a collapsed result must only remove it from the
- // projection's collapsed set; entering the normal load path here can replace
- // the live subtree with the filtered projection and leave the sidebar blank.
- if (!wasExpanded && node.children?.length && sidebarTreeContext?.isSearchProjectionActive?.()) {
- return;
+ // Skip loading only when removing the collapsed marker actually expanded
+ // the projection. Descendants of a matching connection retain their live
+ // expansion state and still need the normal lazy-load path. A saved-SQL
+ // shortcut alone also does not mean a database's objects have been loaded.
+ if (!wasExpanded && node.children?.some((child) => child.type !== "saved-sql-root") && sidebarTreeContext?.isSearchProjectionActive?.()) {
+ const visible = sidebarTreeContext.getVisibleNodes();
+ const index = sidebarTreeContext.getVisibleNodeIndex(node.id);
+ const indexed = visible[index];
+ // Database names containing ':' can share an id with a schema in another database.
+ const projected = indexed && matchesSidebarActionTarget(indexed, node) ? indexed : visible.find((candidate) => matchesSidebarActionTarget(candidate, node));
+ if (projected?.isExpanded) return;
}
if (node.type === "connection-group") {
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 a22852e3b1..32d290885d 100644
--- a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.remoteSearch.spec.ts
+++ b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.remoteSearch.spec.ts
@@ -1,7 +1,4 @@
// @vitest-environment happy-dom
-import { readFileSync } from "node:fs";
-import ts from "typescript";
-import { parse } from "vue/compiler-sfc";
import { computed, createApp, defineComponent, h, nextTick, reactive, ref } from "vue";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { useSidebarRemoteSearch } from "@/composables/useSidebarRemoteSearch";
@@ -10,19 +7,9 @@ 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 { compileConnectionTreeTestScript } from "./connectionTreeTestScript";
-const source = parse(readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8")).descriptor.scriptSetup!.content;
-const script = ts.createSourceFile("ConnectionTree.ts", source, ts.ScriptTarget.Latest, true);
-const statements = script.statements.filter((statement) => {
- if (ts.isFunctionDeclaration(statement)) return ["loadGlobalRemoteSearchResults", "isGlobalTableIndexParent", "discoverGlobalSearchChildren"].includes(statement.name?.text ?? "");
- return (
- ts.isVariableStatement(statement) &&
- statement.declarationList.declarations.some((declaration) =>
- ts.isIdentifier(declaration.name) ? declaration.name.text === "globalSearchContext" : ts.isObjectBindingPattern(declaration.name) && declaration.name.elements.some((element) => ts.isIdentifier(element.name) && element.name.text === "remoteSearchResults"),
- )
- );
-});
-const compiled = ts.transpileModule(statements.map((statement) => statement.getText(script)).join("\n"), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+const compiled = compileConnectionTreeTestScript(["loadGlobalRemoteSearchResults", "isGlobalTableIndexParent", "discoverGlobalSearchChildren", "globalSearchContext", "remoteSearchResults"]);
const cleanups: Array<() => void> = [];
beforeEach(() => vi.useFakeTimers());
@@ -44,7 +31,7 @@ function mountSearch() {
treeNodes: [root],
sidebarTableSearchIndexInvalidation: { revision: 0 },
sidebarObjectSearchRevision: 0,
- isTreeNodeChildrenLoaded: vi.fn(() => true),
+ isTreeNodeChildrenLoaded: vi.fn((_nodeId: string) => true),
searchSidebarObjects: vi.fn(async (_node: TreeNode, _query: string, _signal: AbortSignal): Promise<TreeNode[]> => []),
loadTreeNodeChildren: vi.fn(),
loadConnectedConnectionRootForSidebarSearch: vi.fn(),
@@ -177,6 +164,37 @@ test.each(["local", "regex"])("%s search never dispatches remote object search o
expect(view.store.loadConnectedConnectionRootForSidebarSearch).not.toHaveBeenCalled();
});
+test("searching a connection name does not load unopened databases when none is opened", async () => {
+ const view = mountSearch();
+ view.settingsStore.editorSettings.sidebarSearchOpenedDatabasesOnly = true;
+ view.store.isTreeNodeChildrenLoaded.mockReturnValue(false);
+ const databases: TreeNode[] = ["app", "other"].map((database) => ({ id: `conn:${database}`, label: database, type: "database", connectionId: "conn", database, isExpanded: false, children: [] }));
+ view.store.treeNodes = [{ id: "conn", label: "north", type: "connection", connectionId: "conn", isExpanded: true, children: databases }];
+
+ view.type("north");
+ await vi.advanceTimersByTimeAsync(600);
+
+ expect(view.store.loadTreeNodeChildren).not.toHaveBeenCalled();
+ expect(view.store.searchSidebarObjects).not.toHaveBeenCalled();
+ expect(databases.every((node) => !node.isExpanded && node.children?.length === 0)).toBe(true);
+});
+
+test("searches objects only in databases already opened by the user", async () => {
+ const view = mountSearch();
+ view.settingsStore.editorSettings.sidebarSearchOpenedDatabasesOnly = true;
+ const procedures: TreeNode = { id: "conn:app:__procedures", label: "Procedures", type: "group-procedures", connectionId: "conn", database: "app", children: [] };
+ const opened: TreeNode = { id: "conn:app", label: "app", type: "database", connectionId: "conn", database: "app", isExpanded: false, children: [procedures] };
+ const unopened: TreeNode = { id: "conn:other", label: "other", type: "database", connectionId: "conn", database: "other", isExpanded: false, children: [] };
+ view.store.treeNodes = [{ id: "conn", label: "north", type: "connection", connectionId: "conn", children: [opened, unopened] }];
+ view.store.isTreeNodeChildrenLoaded.mockImplementation((nodeId: string) => nodeId !== unopened.id);
+
+ view.type("routine");
+ await vi.advanceTimersByTimeAsync(600);
+
+ expect(view.store.searchSidebarObjects).toHaveBeenCalledExactlyOnceWith(procedures, "routine", expect.any(AbortSignal), expect.any(Function));
+ expect(view.store.loadTreeNodeChildren).not.toHaveBeenCalled();
+});
+
test.each(["clear", "local", "regex", "disconnect", "refresh", "unmount"])("%s cancels a pending search and ignores its late failure", async (action) => {
const view = mountSearch();
let fail!: (error: Error) => void;
diff --git a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.searchScope.spec.ts b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.searchScope.spec.ts
new file mode 100644
index 0000000000..f1c46b7be4
--- /dev/null
+++ b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.searchScope.spec.ts
@@ -0,0 +1,152 @@
+import { computed, effectScope, nextTick, reactive, ref, type Ref } from "vue";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { useSidebarSearchIndexes } from "@/composables/useSidebarSearchIndexes";
+import { useSidebarRemoteSearch } from "@/composables/useSidebarRemoteSearch";
+import { connectionShouldDiscoverJdbcSchemas, connectionUsesDatabaseObjectTreeMode, effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
+import { usesTreeSchemaMode } from "@/lib/database/databaseFeatureSupport";
+import { collectSidebarGlobalSearchIndexes, sidebarIndexedObjectGroupTypes } from "@/lib/sidebar/sidebarGlobalSearchIndex";
+import { collectSidebarRemoteSearchResults, type SidebarRemoteSearchResult } from "@/lib/sidebar/sidebarRemoteSearch";
+import { findNodePathByIdentity, type SidebarRegexIndexScope } from "@/lib/sidebar/sidebarSearchTree";
+import { resolveSidebarSearchDatabaseScope } from "@/lib/sidebar/sidebarSearchDatabaseScope";
+import type { TableInfo, TreeNode } from "@/types/database";
+import { compileConnectionTreeTestScript } from "./connectionTreeTestScript";
+
+const compiled = compileConnectionTreeTestScript(["globalSearchContext", "globalTableSearchScopes", "remoteSearchResults", "loadGlobalTableSearchIndexes", "loadGlobalRemoteSearchResults", "isGlobalTableIndexParent", "discoverGlobalSearchChildren"]);
+const cleanups: Array<() => void> = [];
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) cleanup();
+ vi.useRealTimers();
+});
+
+function fixture(display: "grouped" | "simple" = "grouped") {
+ const searchQuery = ref("");
+ const loadedIds = reactive(new Set(["conn"]));
+ const databases = reactive<TreeNode[]>(["app", "other"].map((database) => ({ id: `conn:${database}`, label: database, type: "database", connectionId: "conn", database, isExpanded: false, children: [] })));
+ const settingsStore = reactive({ editorSettings: { sidebarGlobalSearchLocal: false, sidebarObjectDisplay: display, sidebarSearchOpenedDatabasesOnly: true } });
+ const queryStore = reactive({ openDatabaseKeys: new Set<string>() });
+ const store = reactive({
+ activeConnectionId: "conn",
+ connectedIds: new Set(["conn"]),
+ treeNodes: [{ id: "conn", label: "north", type: "connection", connectionId: "conn", isExpanded: true, children: databases }] as TreeNode[],
+ sidebarTableSearchIndexInvalidation: { revision: 0 },
+ sidebarObjectSearchRevision: 0,
+ isTreeNodeChildrenLoaded: (nodeId: string) => loadedIds.has(nodeId),
+ getConfig: () => ({ db_type: "mysql" as const }),
+ loadSidebarTableSearchIndexScopes: vi.fn(async () => []),
+ 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 }]),
+ });
+ const onError = vi.fn();
+ const bindings = {
+ computed,
+ searchQuery,
+ deferredSearchQuery: searchQuery,
+ regexMode: ref(false),
+ settingsStore,
+ queryStore,
+ store,
+ selectedSearchScopes: ref([]),
+ searchableNodeTypes: ref(undefined),
+ useSidebarSearchIndexes,
+ useSidebarRemoteSearch,
+ collectSidebarGlobalSearchIndexes,
+ collectSidebarRemoteSearchResults,
+ findNodePathByIdentity,
+ sidebarIndexedObjectGroupTypes,
+ resolveSidebarSearchDatabaseScope,
+ connectionShouldDiscoverJdbcSchemas,
+ connectionUsesDatabaseObjectTreeMode,
+ effectiveDatabaseTypeForConnection,
+ usesTreeSchemaMode,
+ toast: onError,
+ };
+ const scope = effectScope();
+ const state = scope.run(
+ () =>
+ new Function(...Object.keys(bindings), `${compiled}; return { globalTableSearchScopes, remoteSearchResults };`)(...Object.values(bindings)) as {
+ globalTableSearchScopes: Ref<SidebarRegexIndexScope[]>;
+ remoteSearchResults: Ref<SidebarRemoteSearchResult[]>;
+ },
+ )!;
+ cleanups.push(() => scope.stop());
+
+ function openDatabase(node: TreeNode) {
+ 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}:first_page`, label: "first_page", type: "table", connectionId: "conn", database: node.database }];
+ node.isExpanded = true;
+ loadedIds.add(node.id);
+ }
+
+ return { ...state, searchQuery, databases, store, settingsStore, queryStore, loadedIds, openDatabase, onError };
+}
+
+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";
+ await vi.advanceTimersByTimeAsync(350);
+ expect(view.store.ensureSidebarTableSearchIndex).not.toHaveBeenCalled();
+ expect(view.store.loadTreeNodeChildren).not.toHaveBeenCalled();
+
+ view.openDatabase(view.databases[0]);
+ await vi.advanceTimersByTimeAsync(350);
+ view.searchQuery.value = "late_orders";
+ await vi.advanceTimersByTimeAsync(350);
+
+ expect(view.store.ensureSidebarTableSearchIndex).toHaveBeenCalledOnce();
+ expect(view.globalTableSearchScopes.value.flatMap((scope) => scope.entries.map((entry) => entry.name))).toEqual(["late_orders"]);
+ expect(view.remoteSearchResults.value.every((scope) => scope.database === "app")).toBe(true);
+ expect(view.remoteSearchResults.value).not.toEqual([]);
+ expect(view.store.loadTreeNodeChildren).not.toHaveBeenCalled();
+ expect(view.loadedIds.has(view.databases[1].id)).toBe(false);
+ expect(view.onError).not.toHaveBeenCalled();
+
+ // Browsing within the opened database must not restart a complete index build.
+ view.databases[0].isExpanded = false;
+ view.databases[0].isExpanded = true;
+ view.databases[0].children?.push({ id: "metadata", label: "metadata", type: "table" });
+ await vi.advanceTimersByTimeAsync(350);
+ expect(view.store.ensureSidebarTableSearchIndex).toHaveBeenCalledOnce();
+});
+
+test("discards an in-flight index when the database is closed during search", async () => {
+ const view = fixture();
+ let finish!: (entries: TableInfo[]) => void;
+ view.store.ensureSidebarTableSearchIndex.mockImplementationOnce(() => new Promise((resolve) => (finish = resolve)));
+ view.searchQuery.value = "north";
+ await vi.advanceTimersByTimeAsync(350);
+ view.openDatabase(view.databases[0]);
+ await vi.advanceTimersByTimeAsync(350);
+ expect(view.store.ensureSidebarTableSearchIndex).toHaveBeenCalledOnce();
+
+ view.loadedIds.delete(view.databases[0].id);
+ await vi.advanceTimersByTimeAsync(350);
+ finish([{ name: "stale_orders", table_type: "TABLE" }]);
+ await nextTick();
+ await nextTick();
+
+ expect(view.globalTableSearchScopes.value).toEqual([]);
+ expect(view.remoteSearchResults.value).toEqual([]);
+ expect(view.onError).not.toHaveBeenCalled();
+});
+
+test("includes databases referenced by new editor tabs without opening other databases", async () => {
+ const view = fixture();
+ view.searchQuery.value = "north";
+ await vi.advanceTimersByTimeAsync(350);
+ view.queryStore.openDatabaseKeys.add("conn\x00other");
+ await vi.advanceTimersByTimeAsync(700);
+
+ expect(view.globalTableSearchScopes.value.map((scope) => scope.database)).toEqual(["other"]);
+ expect(view.store.ensureSidebarTableSearchIndex).toHaveBeenCalledOnce();
+ expect(view.loadedIds.has(view.databases[0].id)).toBe(false);
+ expect(view.onError).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.expansion.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.expansion.spec.ts
index 93b83c0575..46b9ad2ecc 100644
--- a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.expansion.spec.ts
+++ b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.expansion.spec.ts
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
-import { createApp, defineComponent, h, nextTick, provide, ref, type App } from "vue";
+import { computed, createApp, defineComponent, h, nextTick, provide, reactive, ref, type App } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
import type { TreeNode } from "@/types/database";
@@ -9,6 +9,7 @@ import { sidebarTreeContextKey } from "@/lib/sidebar/sidebarTreeContext";
import { filterSidebarTree } from "@/lib/sidebar/sidebarSearchTree";
import { OBJECT_BROWSER_SEARCH_FOCUS_EVENT } from "@/lib/tabs/objectBrowserSearchFocus";
import SidebarTreeRuntimeHost from "@/components/sidebar/SidebarTreeRuntimeHost.vue";
+import { compileConnectionTreeTestScript } from "./connectionTreeTestScript";
const connectionStore = {
treeNodes: [] as TreeNode[],
@@ -90,6 +91,15 @@ vi.mock("@/lib/backend/api", async (importOriginal) => {
});
const mountedApps: App[] = [];
+const compiledSearchHandlers = compileConnectionTreeTestScript(["onSearchToggle", "onNodeToggled"]);
+
+function searchHandlers(searchCollapsedIds: { value: Set<string> }) {
+ const bindings = { searchCollapsedIds, isTreeSearchFiltering: ref(true), store: connectionStore, syncSidebarTreeNodeExpansion, sidebarLayoutMonitor: { recordEvent: vi.fn() } };
+ return new Function(...Object.keys(bindings), `${compiledSearchHandlers}; return { onSearchToggle, onNodeToggled };`)(...Object.values(bindings)) as {
+ onSearchToggle: (node: TreeNode) => void;
+ onNodeToggled: (node: TreeNode, expanded: boolean) => void;
+ };
+}
afterEach(() => {
for (const app of mountedApps.splice(0)) app.unmount();
@@ -842,15 +852,18 @@ describe("SidebarTreeRuntimeHost expansion", () => {
children: [tableGroup],
};
connectionStore.sidebarSearchQuery = "json";
- const searchToggle = vi.fn();
- const nodeToggled = vi.fn();
+ const collapsedIds = ref(new Set([database.id]));
+ const projection = computed(() => filterSidebarTree([database], "json", collapsedIds.value));
+ const handlers = searchHandlers(collapsedIds);
+ const searchToggle = vi.fn(handlers.onSearchToggle);
+ const nodeToggled = vi.fn(handlers.onNodeToggled);
const host = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);
const app = createApp(
defineComponent({
setup() {
provide(sidebarTreeContextKey, {
- getVisibleNodes: () => [database],
+ getVisibleNodes: () => projection.value,
getVisibleNodeIndex: () => 0,
isSearchProjectionActive: () => true,
});
@@ -868,11 +881,171 @@ describe("SidebarTreeRuntimeHost expansion", () => {
await nextTick();
expect(searchToggle).toHaveBeenCalledWith(database);
+ expect(projection.value[0].isExpanded).toBe(true);
+ expect(database.isExpanded).toBe(false);
expect(nodeToggled).not.toHaveBeenCalled();
expect(connectionStore.loadTables).not.toHaveBeenCalled();
expect(connectionStore.releaseCollapsedTreeNodeChildren).not.toHaveBeenCalled();
});
+ it.each([
+ { loaded: false, query: "north" },
+ { loaded: true, query: "north" },
+ { loaded: false, query: "basic" },
+ ])("expands a database during search ($query, loaded: $loaded)", async ({ loaded, query }) => {
+ const tableGroup: TreeNode = {
+ id: "mysql:basic:__tables",
+ label: "tree.tables",
+ type: "group-tables",
+ connectionId: "mysql",
+ database: "basic",
+ isExpanded: false,
+ children: [
+ { id: "mysql:basic:orders", label: "orders", type: "table", connectionId: "mysql", database: "basic" },
+ { id: "mysql:basic:customers", label: "customers", type: "table", connectionId: "mysql", database: "basic" },
+ ],
+ };
+ const database = reactive<TreeNode>({
+ id: "mysql:basic",
+ label: "basic",
+ type: "database",
+ connectionId: "mysql",
+ database: "basic",
+ isExpanded: false,
+ // Unopened databases can already contain their saved-SQL shortcut.
+ children: loaded ? [tableGroup] : [{ id: "mysql:basic:queries", label: "tree.queries", type: "saved-sql-root", connectionId: "mysql", database: "basic", children: [] }],
+ });
+ const otherDatabase: TreeNode = { id: "mysql:other", label: "other", type: "database", connectionId: "mysql", database: "other", isExpanded: false, children: [] };
+ const root: TreeNode = { id: "mysql", label: "north", type: "connection", connectionId: "mysql", isExpanded: true, children: [database, otherDatabase] };
+ connectionStore.treeNodes = [root];
+ connectionStore.connectedIds.add("mysql");
+ connectionStore.loadTables.mockImplementation(async () => {
+ if (!loaded) database.children = [tableGroup];
+ database.isExpanded = true;
+ });
+ const collapsedIds = ref(new Set(query === "basic" ? [database.id] : []));
+ const projectedDatabase = computed(() => filterSidebarTree([root], query, collapsedIds.value)[0].children![0]);
+ const handlers = searchHandlers(collapsedIds);
+ const host = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);
+ const app = createApp(
+ defineComponent({
+ setup() {
+ provide(sidebarTreeContextKey, {
+ getVisibleNodes: () => [projectedDatabase.value],
+ getVisibleNodeIndex: () => 0,
+ isSearchProjectionActive: () => true,
+ getTreeLoadSearchOptions: () => ({ searchFilter: "", allowGlobalSearchMismatch: true, expectedSidebarSearchQuery: "" }),
+ });
+ return () => h(SidebarTreeRuntimeHost, { ref: host, node: projectedDatabase.value, depth: 1, onSearchToggle: handlers.onSearchToggle, onNodeToggled: handlers.onNodeToggled });
+ },
+ }),
+ );
+ mountedApps.push(app);
+ const container = document.createElement("div");
+ document.body.append(container);
+ app.use(i18n);
+ app.mount(container);
+
+ host.value!.toggleNode(projectedDatabase.value);
+ await vi.waitFor(() => expect(projectedDatabase.value.isExpanded).toBe(true));
+ expect(connectionStore.loadTables).toHaveBeenCalledExactlyOnceWith("mysql", "basic", undefined, { searchFilter: "", allowGlobalSearchMismatch: true, expectedSidebarSearchQuery: "" });
+ expect(database.children?.[0].children?.map((node) => node.label)).toEqual(["orders", "customers"]);
+ expect(otherDatabase.isExpanded).toBe(false);
+
+ host.value!.toggleNode(projectedDatabase.value);
+ await nextTick();
+ expect(projectedDatabase.value.isExpanded).toBe(false);
+ host.value!.toggleNode(projectedDatabase.value);
+ await vi.waitFor(() => expect(projectedDatabase.value.isExpanded).toBe(true));
+ expect(connectionStore.loadTables).toHaveBeenCalledTimes(query === "basic" ? 1 : 2);
+ expect(connectionStore.releaseCollapsedTreeNodeChildren).not.toHaveBeenCalled();
+ });
+
+ it("reopens a cached table group below a matching connection without replacing its children", async () => {
+ const group = reactive<TreeNode>({
+ id: "mysql:basic:__tables",
+ label: "tree.tables",
+ type: "group-tables",
+ connectionId: "mysql",
+ database: "basic",
+ isExpanded: true,
+ children: [
+ { id: "mysql:basic:orders", label: "orders", type: "table", connectionId: "mysql", database: "basic" },
+ { id: "mysql:basic:customers", label: "customers", type: "table", connectionId: "mysql", database: "basic" },
+ ],
+ });
+ const root: TreeNode = { id: "mysql", label: "north", type: "connection", connectionId: "mysql", isExpanded: true, children: [{ id: "mysql:basic", label: "basic", type: "database", connectionId: "mysql", database: "basic", isExpanded: true, children: [group] }] };
+ connectionStore.treeNodes = [root];
+ connectionStore.connectedIds.add("mysql");
+ const collapsedIds = ref(new Set<string>());
+ const projectedGroup = computed(() => filterSidebarTree([root], "north", collapsedIds.value)[0].children![0].children![0]);
+ const handlers = searchHandlers(collapsedIds);
+ const host = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);
+ const app = createApp(
+ defineComponent({
+ setup() {
+ provide(sidebarTreeContextKey, { getVisibleNodes: () => [projectedGroup.value], getVisibleNodeIndex: () => 0, isSearchProjectionActive: () => true });
+ return () => h(SidebarTreeRuntimeHost, { ref: host, node: projectedGroup.value, depth: 2, onSearchToggle: handlers.onSearchToggle, onNodeToggled: handlers.onNodeToggled });
+ },
+ }),
+ );
+ mountedApps.push(app);
+ const container = document.createElement("div");
+ document.body.append(container);
+ app.use(i18n);
+ app.mount(container);
+ const children = group.children;
+
+ for (let cycle = 0; cycle < 2; cycle++) {
+ host.value!.toggleNode(projectedGroup.value);
+ await nextTick();
+ expect(projectedGroup.value.isExpanded).toBe(false);
+ expect(collapsedIds.value.has("mysql:basic:orders")).toBe(true);
+ host.value!.toggleNode(projectedGroup.value);
+ await nextTick();
+ expect(projectedGroup.value.isExpanded).toBe(true);
+ expect(group.isExpanded).toBe(true);
+ expect(group.children).toBe(children);
+ }
+ expect(connectionStore.loadObjectGroupChildren).not.toHaveBeenCalled();
+ expect(connectionStore.releaseCollapsedTreeNodeChildren).not.toHaveBeenCalled();
+ });
+
+ it("does not skip schema expansion when another visible database has the same node id", async () => {
+ const schema = reactive<TreeNode>({ id: "pg:a:b", label: "b", type: "schema", connectionId: "pg", database: "a", schema: "b", isExpanded: false, children: [{ id: "pg:a:b:tables", label: "Tables", type: "group-tables", connectionId: "pg", database: "a", schema: "b", children: [] }] });
+ const otherDatabase: TreeNode = { id: "pg:a:b", label: "a:b", type: "database", connectionId: "pg", database: "a:b", isExpanded: true, children: [] };
+ const root: TreeNode = { id: "pg", label: "north", type: "connection", connectionId: "pg", isExpanded: true, children: [{ id: "pg:a", label: "a", type: "database", connectionId: "pg", database: "a", isExpanded: true, children: [schema] }, otherDatabase] };
+ connectionStore.treeNodes = [root];
+ connectionStore.connectedIds.add("pg");
+ connectionStore.getConfig.mockReturnValue({ db_type: "postgres", name: "north" });
+ connectionStore.loadTables.mockImplementation(async () => {
+ schema.isExpanded = true;
+ });
+ const collapsedIds = ref(new Set<string>());
+ const projection = computed(() => filterSidebarTree([root], "north", collapsedIds.value)[0]);
+ const visible = computed(() => [projection.value.children![0].children![0], projection.value.children![1]]);
+ const handlers = searchHandlers(collapsedIds);
+ const host = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);
+ const app = createApp(
+ defineComponent({
+ setup() {
+ provide(sidebarTreeContextKey, { getVisibleNodes: () => visible.value, getVisibleNodeIndex: () => 1, isSearchProjectionActive: () => true });
+ return () => h(SidebarTreeRuntimeHost, { ref: host, node: visible.value[0], depth: 2, onSearchToggle: handlers.onSearchToggle, onNodeToggled: handlers.onNodeToggled });
+ },
+ }),
+ );
+ mountedApps.push(app);
+ const container = document.createElement("div");
+ document.body.append(container);
+ app.use(i18n);
+ app.mount(container);
+
+ host.value!.toggleNode(visible.value[0]);
+ await vi.waitFor(() => expect(schema.isExpanded).toBe(true));
+ expect(connectionStore.loadTables).toHaveBeenCalledExactlyOnceWith("pg", "a", "b", undefined);
+ expect(otherDatabase.isExpanded).toBe(true);
+ });
+
it("expands an unloaded object group without leaking a matching connection name", async () => {
const group: TreeNode = {
id: "mysql:basic:__tables",
diff --git a/apps/desktop/src/components/sidebar/__tests__/connectionTreeTestScript.ts b/apps/desktop/src/components/sidebar/__tests__/connectionTreeTestScript.ts
new file mode 100644
index 0000000000..8340f4565f
--- /dev/null
+++ b/apps/desktop/src/components/sidebar/__tests__/connectionTreeTestScript.ts
@@ -0,0 +1,19 @@
+import { readFileSync } from "node:fs";
+import ts from "typescript";
+import { parse } from "vue/compiler-sfc";
+
+const source = parse(readFileSync("apps/desktop/src/components/sidebar/ConnectionTree.vue", "utf8")).descriptor.scriptSetup!.content;
+const script = ts.createSourceFile("ConnectionTree.ts", source, ts.ScriptTarget.Latest, true);
+
+export function compileConnectionTreeTestScript(names: readonly string[]): string {
+ const statements = script.statements.filter((statement) => {
+ if (ts.isFunctionDeclaration(statement)) return names.includes(statement.name?.text ?? "");
+ return (
+ ts.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some((declaration) =>
+ ts.isIdentifier(declaration.name) ? names.includes(declaration.name.text) : ts.isObjectBindingPattern(declaration.name) && declaration.name.elements.some((element) => ts.isIdentifier(element.name) && names.includes(element.name.text)),
+ )
+ );
+ });
+ return ts.transpileModule(statements.map((statement) => statement.getText(script)).join("\n"), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+}
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index fd4d33cda8..962b166746 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -10404,7 +10404,7 @@ export default {
sidebarTableSearchEnabled: "Enable table search inside databases",
sidebarTableSearchEnabledDescription: "Show a local table search box under expanded databases, schemas, or table groups so each scope can filter tables independently.",
sidebarSearchOpenedDatabasesOnly: "Search only opened databases",
- sidebarSearchOpenedDatabasesOnlyDescription: "The sidebar search loads only databases you have opened in the active connection (all of them when none is opened). Turn off to search every database of the connection.",
+ sidebarSearchOpenedDatabasesOnlyDescription: "The sidebar search loads only databases you have opened in the active connection. Turn off to search every database of the connection.",
sidebarObjectInfoMode: "Sidebar supplementary info",
sidebarObjectInfoModeDescription:
"Choose comments, object sizes, both, or no supplementary text after names. When both are enabled, the comment follows the name and the size is shown at the far right. Information with no corresponding data is hidden. Database totals currently support PostgreSQL; table sizes support MySQL, PostgreSQL, GaussDB, KingbaseES, GBase 8a, SQL Server, Oracle, Dameng, and ClickHouse.",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 1f1f3ac82b..ca5a22790b 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -10229,7 +10229,7 @@ export default withEnglishFallback({
supportInfoLocalDriverVersions: "Versiones de controladores locales",
supportInfoAiProviders: "Proveedores de IA",
sidebarSearchOpenedDatabasesOnly: "Buscar solo en bases de datos abiertas",
- sidebarSearchOpenedDatabasesOnlyDescription: "La búsqueda de la barra lateral solo carga las bases de datos abiertas en la conexión actual (si no hay ninguna abierta, busca en todas). Al desactivarla, se buscará en todas las bases de datos de esa conexión.",
+ sidebarSearchOpenedDatabasesOnlyDescription: "La búsqueda de la barra lateral solo carga las bases de datos abiertas en la conexión actual. Al desactivarla, se buscará en todas las bases de datos de esa conexión.",
shortcutSelectLineEnds: "Seleccionar finales de línea",
openQueryOnConnectionOpen: "Abrir la página de consulta al abrir la conexión",
openQueryOnConnectionOpenDescription: "Al abrir una conexión o base de datos, abre su consulta default.sql y guarda los cambios automáticamente.",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index a00fcf7747..21c6b86468 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -8715,7 +8715,7 @@ export default withEnglishFallback({
sidebarTableSearchEnabled: "Aktifkan pencarian tabel dalam database",
sidebarTableSearchEnabledDescription: "Tampilkan kotak pencarian tabel lokal di bawah database, skema, atau grup tabel yang diperluas sehingga setiap cakupan dapat memfilter tabelnya sendiri.",
sidebarSearchOpenedDatabasesOnly: "Cari hanya pada database yang terbuka",
- sidebarSearchOpenedDatabasesOnlyDescription: "Pencarian bilah sisi hanya memuat database yang sudah Anda buka pada koneksi aktif (semuanya jika tidak ada yang terbuka). Nonaktifkan untuk mencari semua database pada koneksi tersebut.",
+ sidebarSearchOpenedDatabasesOnlyDescription: "Pencarian bilah sisi hanya memuat database yang sudah Anda buka pada koneksi aktif. Nonaktifkan untuk mencari semua database pada koneksi tersebut.",
sidebarObjectInfoMode: "Info tambahan bilah sisi",
sidebarObjectInfoModeDescription:
"Pilih komentar, ukuran objek, keduanya, atau tanpa info tambahan. Jika keduanya dipilih, komentar tampil setelah nama dan ukuran di paling kanan. Informasi yang datanya tidak tersedia akan disembunyikan. Total database saat ini mendukung PostgreSQL; ukuran tabel mendukung MySQL, PostgreSQL, GaussDB, KingbaseES, GBase 8a, SQL Server, Oracle, Dameng, dan ClickHouse.",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index d4e9563dc3..477a2923d1 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -9977,7 +9977,7 @@ export default withEnglishFallback({
supportInfoLocalDriverVersions: "Versioni dei driver locali",
supportInfoAiProviders: "Provider AI",
sidebarSearchOpenedDatabasesOnly: "Cerca solo nei database aperti",
- sidebarSearchOpenedDatabasesOnlyDescription: "La ricerca nella barra laterale carica solo i database aperti nella connessione corrente (se nessuno è aperto, cerca in tutti). Se disattivata, cerca in tutti i database della connessione.",
+ sidebarSearchOpenedDatabasesOnlyDescription: "La ricerca nella barra laterale carica solo i database aperti nella connessione corrente. Se disattivata, cerca in tutti i database della connessione.",
shortcutSelectLineEnds: "Seleziona fine riga",
openQueryOnConnectionOpen: "Apri la pagina Query all'apertura della connessione",
openQueryOnConnectionOpenDescription: "Apre la query default.sql quando si apre una connessione o un database e salva automaticamente le modifiche.",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index de6ad2491f..3c42c6e218 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -10006,7 +10006,7 @@ export default withEnglishFallback({
supportInfoLocalDriverVersions: "ローカルドライバーのバージョン",
supportInfoAiProviders: "AIプロバイダー",
sidebarSearchOpenedDatabasesOnly: "開いているデータベースのみを検索",
- sidebarSearchOpenedDatabasesOnlyDescription: "サイドバー検索は、現在の接続で開いているデータベースのみを読み込みます(1つも開いていない場合はすべてを検索します)。オフにすると、その接続のすべてのデータベースを検索します。",
+ sidebarSearchOpenedDatabasesOnlyDescription: "サイドバー検索は、現在の接続で開いているデータベースのみを読み込みます。オフにすると、その接続のすべてのデータベースを検索します。",
shortcutSelectLineEnds: "行末を選択",
openQueryOnConnectionOpen: "接続を開いたときにクエリページを開く",
openQueryOnConnectionOpenDescription: "有効にすると、接続またはデータベースを開いたときに default.sql を開き、変更を自動保存します。",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 6121df3daf..1953edd0ce 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -10074,7 +10074,7 @@ export default withEnglishFallback({
supportInfoLocalDriverVersions: "로컬 드라이버 버전",
supportInfoAiProviders: "AI 제공자",
sidebarSearchOpenedDatabasesOnly: "열려 있는 데이터베이스만 검색",
- sidebarSearchOpenedDatabasesOnlyDescription: "사이드바 검색은 현재 연결에서 열려 있는 데이터베이스만 로드합니다(열려 있는 데이터베이스가 하나도 없으면 전체를 검색). 끄면 해당 연결의 모든 데이터베이스를 검색합니다.",
+ sidebarSearchOpenedDatabasesOnlyDescription: "사이드바 검색은 현재 연결에서 열려 있는 데이터베이스만 로드합니다. 끄면 해당 연결의 모든 데이터베이스를 검색합니다.",
shortcutSelectLineEnds: "줄 끝 선택",
openQueryOnConnectionOpen: "연결을 열 때 쿼리 페이지로 이동",
openQueryOnConnectionOpenDescription: "활성화하면 연결 또는 데이터베이스를 열 때 default.sql 쿼리를 열고 변경 사항을 자동 저장합니다.",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index d0fab9f7a6..329ead1734 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -8787,7 +8787,7 @@ export default withEnglishFallback({
sidebarTableSearchEnabled: "Włącz wyszukiwanie tabel w bazach danych",
sidebarTableSearchEnabledDescription: "Wyświetlaj lokalne pole wyszukiwania tabel pod rozwiniętymi bazami danych, schematami lub grupami, aby każdy zakres mógł filtrować niezależnie.",
sidebarSearchOpenedDatabasesOnly: "Szukaj tylko w otwartych bazach danych",
- sidebarSearchOpenedDatabasesOnlyDescription: "Wyszukiwanie w pasku bocznym przeszukuje tylko bazy otwarte w aktywnym połączeniu (lub wszystkie, jeśli żadna nie jest otwarta). Wyłącz, aby przeszukiwać każdą bazę połączenia.",
+ sidebarSearchOpenedDatabasesOnlyDescription: "Wyszukiwanie w pasku bocznym przeszukuje tylko bazy otwarte w aktywnym połączeniu. Wyłącz, aby przeszukiwać każdą bazę połączenia.",
sidebarObjectInfoMode: "Informacje uzupełniające na pasku bocznym",
sidebarObjectInfoModeDescription:
"Choose comments, object sizes, or no supplementary text after names. Comments and sizes are mutually exclusive. Database totals currently support PostgreSQL; table sizes support MySQL, PostgreSQL, GaussDB, KingbaseES, GBase 8a, SQL Server, Oracle, Dameng, and ClickHouse.",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index ff7f75b5e5..ea300037fd 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -9974,7 +9974,7 @@ export default withEnglishFallback({
supportInfoLocalDriverVersions: "Versões de drivers locais",
supportInfoAiProviders: "Provedores de IA",
sidebarSearchOpenedDatabasesOnly: "Pesquisar apenas bancos de dados abertos",
- sidebarSearchOpenedDatabasesOnlyDescription: "A pesquisa da barra lateral carrega apenas os bancos de dados abertos na conexão atual (se nenhum estiver aberto, pesquisa todos). Quando desativada, pesquisará todos os bancos de dados da conexão.",
+ sidebarSearchOpenedDatabasesOnlyDescription: "A pesquisa da barra lateral carrega apenas os bancos de dados abertos na conexão atual. Quando desativada, pesquisará todos os bancos de dados da conexão.",
shortcutSelectLineEnds: "Selecionar fins de linha",
openQueryOnConnectionOpen: "Abrir consulta ao abrir a conexão",
openQueryOnConnectionOpenDescription: "Ao abrir uma conexão ou banco de dados, abre a consulta default.sql e salva as alterações automaticamente.",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index f2f8eb986c..ef6a129704 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -11551,7 +11551,7 @@ export default withEnglishFallback({
resultTabPreferComments: "Предпочитать комментарии SQL, если они есть",
resultTabPreferCommentsDescription: "Использовать комментарий над SQL-запросом; отключите, чтобы всегда отображать имя исходной таблицы.",
sidebarSearchOpenedDatabasesOnly: "Искать только в открытых базах данных",
- sidebarSearchOpenedDatabasesOnlyDescription: "Поиск на боковой панели загружает только открытые базы данных в текущем подключении (если ни одна не открыта, поиск выполняется по всем). Если отключить, поиск будет выполняться по всем базам данных этого подключения.",
+ sidebarSearchOpenedDatabasesOnlyDescription: "Поиск на боковой панели загружает только открытые базы данных в текущем подключении. Если отключить, поиск будет выполняться по всем базам данных этого подключения.",
shortcutSelectLineEnds: "Выделить концы строк",
openQueryOnConnectionOpen: "Открывать страницу запроса при открытии подключения",
openQueryOnConnectionOpenDescription: "При открытии подключения или базы данных открывается запрос default.sql. Изменения сохраняются автоматически.",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 427828f252..427a398114 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -10927,7 +10927,7 @@ export default withEnglishFallback({
sidebarTableSearchEnabled: "เปิดใช้การค้นหาตารางภายในฐานข้อมูล",
sidebarTableSearchEnabledDescription: "แสดงช่องค้นหาตารางเฉพาะที่ใต้ฐานข้อมูล Schema หรือกลุ่มตารางที่ขยาย เพื่อให้แต่ละขอบเขตกรองตารางได้อิสระ",
sidebarSearchOpenedDatabasesOnly: "ค้นหาเฉพาะฐานข้อมูลที่เปิด",
- sidebarSearchOpenedDatabasesOnlyDescription: "การค้นหา Sidebar จะโหลดเฉพาะฐานข้อมูลที่เปิดในการเชื่อมต่อปัจจุบัน (ทั้งหมดเมื่อยังไม่ได้เปิด) ปิดเพื่อค้นหาทุกฐานข้อมูลของการเชื่อมต่อ",
+ sidebarSearchOpenedDatabasesOnlyDescription: "การค้นหา Sidebar จะโหลดเฉพาะฐานข้อมูลที่เปิดในการเชื่อมต่อปัจจุบัน ปิดเพื่อค้นหาทุกฐานข้อมูลของการเชื่อมต่อ",
sidebarObjectInfoMode: "ข้อมูลเสริมของ Sidebar",
sidebarObjectInfoModeDescription:
"เลือกคอมเมนต์ ขนาดออบเจ็กต์ ทั้งสองอย่าง หรือไม่แสดงข้อมูลเสริม เมื่อแสดงทั้งสองอย่าง คอมเมนต์จะอยู่หลังชื่อและขนาดจะแสดงทางขวาสุด ข้อมูลที่ไม่มีจะถูกซ่อน ขณะนี้ยอดฐานข้อมูลรองรับ PostgreSQL ส่วนขนาดตารางรองรับ MySQL, PostgreSQL, GaussDB, KingbaseES, GBase 8a, SQL Server, Oracle, Dameng และ ClickHouse",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 45d14aabd1..bd29f73d47 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -10371,7 +10371,7 @@ export default withEnglishFallback({
sidebarTableSearchEnabled: "启用库下表搜索框",
sidebarTableSearchEnabledDescription: "在已展开的数据库、schema 或表分组下显示局部表搜索框,用于为不同库分别过滤表。",
sidebarSearchOpenedDatabasesOnly: "仅搜索已打开的数据库",
- sidebarSearchOpenedDatabasesOnlyDescription: "侧边栏搜索只加载当前连接中已打开的数据库(若一个都没打开则搜索全部)。关闭后会搜索该连接的全部数据库。",
+ sidebarSearchOpenedDatabasesOnlyDescription: "侧边栏搜索只加载当前连接中已打开的数据库。关闭后会搜索该连接的全部数据库。",
sidebarObjectInfoMode: "侧边栏附加信息",
sidebarObjectInfoModeDescription: "选择在名称后显示注释、对象大小、两者同时显示或不显示。组合模式下,注释跟随名称,大小显示在最右侧,缺少对应数据时自动隐藏。数据库总大小目前支持 PostgreSQL,表大小支持 MySQL、PostgreSQL、GaussDB、KingbaseES、GBase 8a、SQL Server、Oracle、达梦和 ClickHouse。",
sidebarObjectInfoModeCommentInline: "注释(紧跟名称)",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index aa3ae79760..fa2648d9a5 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -9104,7 +9104,7 @@ export default withEnglishFallback({
supportInfoLocalDriverVersions: "本機驅動程式版本",
supportInfoAiProviders: "AI 供應商",
sidebarSearchOpenedDatabasesOnly: "僅搜尋已開啟的資料庫",
- sidebarSearchOpenedDatabasesOnlyDescription: "側邊欄搜尋只載入目前連線中已開啟的資料庫(若一個都沒開啟則搜尋全部)。關閉後會搜尋該連線的全部資料庫。",
+ sidebarSearchOpenedDatabasesOnlyDescription: "側邊欄搜尋只載入目前連線中已開啟的資料庫。關閉後會搜尋該連線的全部資料庫。",
shortcutSelectLineEnds: "選取行尾",
openQueryOnConnectionOpen: "開啟連線時進入查詢頁",
openQueryOnConnectionOpenDescription: "啟用後,開啟連線或資料庫時進入對應的 default.sql 預設查詢,修改自動儲存。",
diff --git a/apps/desktop/src/lib/__tests__/sidebar/sidebarSearchDatabaseScope.spec.ts b/apps/desktop/src/lib/__tests__/sidebar/sidebarSearchDatabaseScope.spec.ts
index de810ffe43..71aac79d52 100644
--- a/apps/desktop/src/lib/__tests__/sidebar/sidebarSearchDatabaseScope.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sidebar/sidebarSearchDatabaseScope.spec.ts
@@ -17,12 +17,21 @@ function connectionNode(children: TreeNode[]): TreeNode {
}
describe("resolveSidebarSearchDatabaseScope", () => {
- it.each([
- ["disabled setting keeps the search unrestricted", { enabled: false }, null],
- ["no database opened falls back to every database", {}, null],
- ] as const)("returns null when %s", (_name, overrides, expected) => {
+ it("keeps the search unrestricted when the setting is disabled", () => {
const node = connectionNode([databaseNode("conn-1:a", "a"), databaseNode("conn-1:b", "b")]);
- expect(resolveSidebarSearchDatabaseScope(node, { ...OPTIONS, ...overrides })).toEqual(expected);
+ expect(resolveSidebarSearchDatabaseScope(node, { ...OPTIONS, enabled: false })).toBeNull();
+ });
+
+ it("does not open every database when none has been opened", () => {
+ const databases = [databaseNode("conn-1:a", "a"), databaseNode("conn-1:b", "b")];
+ const scope = resolveSidebarSearchDatabaseScope(connectionNode(databases), OPTIONS);
+ expect(scope).toEqual(new Set());
+ expect(databases.every((node) => isSidebarSearchPrunedDatabaseNode(node, scope))).toBe(true);
+ });
+
+ it("also restricts databases discovered after resolving an empty connection root", () => {
+ const scope = resolveSidebarSearchDatabaseScope(connectionNode([]), OPTIONS);
+ expect(isSidebarSearchPrunedDatabaseNode(databaseNode("conn-1:new", "new"), scope)).toBe(true);
});
it("keeps databases opened in the tree", () => {
@@ -44,9 +53,10 @@ describe("resolveSidebarSearchDatabaseScope", () => {
expect(resolveSidebarSearchDatabaseScope(node, OPTIONS)).toEqual(new Set(["conn-1:cat:nested:loaded"]));
});
- it("treats schema-mode trees without database nodes as unrestricted", () => {
+ it("keeps schema-mode trees searchable without database nodes", () => {
const schemaNode: TreeNode = { id: "conn-1:public", label: "public", type: "schema", connectionId: "conn-1", database: "main", isExpanded: false, children: [] };
- expect(resolveSidebarSearchDatabaseScope(connectionNode([schemaNode]), OPTIONS)).toEqual(null);
+ const scope = resolveSidebarSearchDatabaseScope(connectionNode([schemaNode]), OPTIONS);
+ expect(isSidebarSearchPrunedDatabaseNode(schemaNode, scope)).toBe(false);
});
});
@@ -54,6 +64,7 @@ describe("isSidebarSearchPrunedDatabaseNode", () => {
it.each([
["database outside the scope", databaseNode("conn-1:b", "b"), new Set(["conn-1:a"]), true],
["database inside the scope", databaseNode("conn-1:a", "a"), new Set(["conn-1:a"]), false],
+ ["database when none is opened", databaseNode("conn-1:a", "a"), new Set<string>(), true],
["unrestricted scope", databaseNode("conn-1:b", "b"), null, false],
["non-database container", { id: "conn-1", label: "prod", type: "connection", connectionId: "conn-1", isExpanded: true, children: [] } as TreeNode, new Set(["conn-1:a"]), false],
] as const)("returns %expected when the node is a %s", (_name, node, scope, expected) => {
diff --git a/apps/desktop/src/lib/sidebar/sidebarSearchDatabaseScope.ts b/apps/desktop/src/lib/sidebar/sidebarSearchDatabaseScope.ts
index 0dff397c73..426b110628 100644
--- a/apps/desktop/src/lib/sidebar/sidebarSearchDatabaseScope.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarSearchDatabaseScope.ts
@@ -30,19 +30,16 @@ function collectOpenedDatabaseNodeIds(node: TreeNode, opened: Set<string>, optio
/**
* Node ids of database-level nodes the sidebar search may load for one
- * connection, or null when the search must stay unrestricted.
- *
- * null means either the setting is off, the connection exposes no
- * database-level nodes (schema-mode trees such as Oracle, Redis, etc.), or
- * none of them is opened — in that case falling back to searching every
- * database keeps the box useful right after connecting, before the user
- * opens anything.
+ * connection, or null when the setting allows searching every database.
+ * An empty set must stay restricted: searching before opening a database
+ * must not load every database on the user's behalf. Schema-mode trees
+ * remain searchable because only database-level nodes are pruned.
*/
export function resolveSidebarSearchDatabaseScope(connectionNode: TreeNode, options: SidebarSearchDatabaseScopeOptions): ReadonlySet<string> | null {
if (!options.enabled) return null;
const opened = new Set<string>();
collectOpenedDatabaseNodeIds(connectionNode, opened, options);
- return opened.size > 0 ? opened : null;
+ return opened;
}
/**
diff --git a/docs/content/docs/schema-browser.mdx b/docs/content/docs/schema-browser.mdx
index 27bb588a98..f77e95cfca 100644
--- a/docs/content/docs/schema-browser.mdx
+++ b/docs/content/docs/schema-browser.mdx
@@ -61,7 +61,7 @@ Object-tree search can match:
- Object paths, column comments, and table comments
- Loaded metadata and complete cached table/view indexes
-The main sidebar search reuses table/view indexes from memory or the persisted schema cache. When an index is missing, the first search builds it for the eligible scopes in the active, connected datasource. Further edits filter the index locally without reloading the datasource tree. The “Search only opened databases” setting controls which databases are indexed; when none are open, all visible databases are eligible.
+The main sidebar search reuses table/view indexes from memory or the persisted schema cache. When an index is missing, the first search builds it for the eligible scopes in the active, connected datasource. Further edits filter the index locally without reloading the datasource tree. With “Search only opened databases” enabled, search does not load objects from unopened databases, even when none are open. Connection and database names remain searchable, and you can expand a database to load its objects. Turn the setting off to search every visible database in the active connection.
Other supported object types (including procedures, functions, triggers, sequences, and packages) use debounced, on-demand remote search, even when their group has never been expanded or the object is beyond its first page. Matching pages are cached in memory by keyword and full scope; filtered results are not treated as a complete schema index. Changing the input cancels the previous remote request and discards late results. Search results do not replace the loaded browsing tree.
diff --git a/packages/app-tests/sidebarGlobalSearchIndex.test.ts b/packages/app-tests/sidebarGlobalSearchIndex.test.ts
index 7b3180aab3..d9440abec8 100644
--- a/packages/app-tests/sidebarGlobalSearchIndex.test.ts
+++ b/packages/app-tests/sidebarGlobalSearchIndex.test.ts
@@ -1,6 +1,7 @@
import { expect, test, vi } from "vitest";
import { collectSidebarGlobalSearchIndexes, sidebarIndexedObjectGroupTypes, type SidebarGlobalSearchIndexLoader } from "../../apps/desktop/src/lib/sidebar/sidebarGlobalSearchIndex.ts";
import type { SidebarRegexIndexScope } from "../../apps/desktop/src/lib/sidebar/sidebarSearchTree.ts";
+import { resolveSidebarSearchDatabaseScope } from "../../apps/desktop/src/lib/sidebar/sidebarSearchDatabaseScope.ts";
import type { TreeNode } from "../../apps/desktop/src/types/database.ts";
function fixture() {
@@ -96,6 +97,18 @@ test("restricts cached and missing scopes to opened databases", async () => {
expect(loader.loadIndex).not.toHaveBeenCalled();
});
+test("does not discover or index unopened databases when none has been opened", async () => {
+ const { root, database, cached, loader, run } = fixture();
+ root.children?.push({ ...database, id: "conn:other", database: "other", children: [] });
+ loader.loadCachedScopes.mockResolvedValue([cached]);
+ const scope = resolveSidebarSearchDatabaseScope(root, { enabled: true, isChildrenLoaded: () => false, openDatabaseKeys: new Set() });
+
+ expect(await run(scope)).toEqual([]);
+ expect(loader.discover).toHaveBeenCalledExactlyOnceWith(root);
+ expect(loader.loadIndex).not.toHaveBeenCalled();
+ expect(root.children?.every((node) => !node.isExpanded)).toBe(true);
+});
+
test("discovers a missing namespace before indexing its tables", async () => {
const { database, schema, tables, loader, run } = fixture();
database.children = [];