feat(mongo): open object browser from database tree nodes

This commit is contained in:
高瑞强 authored and GitHub committed 2026-08-25 22:15:40 +08:00
1 parent 46111850db
commit bfd7c7def2
29 files changed
+354 -61

No files matched your search

@@ -9,6 +9,8 @@ import {
supportsConnectionDatabaseBrowser,
supportsDatabaseNameCompletion,
supportsDatabaseSchemaQualifier,
supportsObjectBrowser,
supportsObjectBrowserTreeNode,
supportsQueryTargetDatabaseListing,
supportsQueryEditorBlockComments,
supportsSqlInListPaste,
@@ -50,6 +52,17 @@ describe("connection database browser", () => {
it("follows object browser support without enabling unsupported connection types", () => {
expect(supportsConnectionDatabaseBrowser("postgres")).toBe(true);
expect(supportsConnectionDatabaseBrowser("redis")).toBe(false);
expect(supportsConnectionDatabaseBrowser("mongodb")).toBe(false);
});
});
describe("object browser tree nodes", () => {
it("opens MongoDB object browser from mongo-db nodes without the SQL database list", () => {
expect(supportsObjectBrowser("mongodb")).toBe(true);
expect(supportsObjectBrowserTreeNode("mongodb", "mongo-db")).toBe(true);
expect(supportsObjectBrowserTreeNode("mongodb", "database")).toBe(false);
expect(supportsObjectBrowserTreeNode("mysql", "database")).toBe(true);
expect(supportsObjectBrowserTreeNode("mysql", "mongo-db")).toBe(false);
});
});
@@ -127,6 +127,14 @@ describe("treeNodeClick", () => {
expect(shouldOpenObjectBrowserOnSingleClick("table", true)).toBe(false);
expect(shouldOpenObjectBrowserOnSingleClick("database", true)).toBe(true);
expect(shouldOpenObjectBrowserOnSingleClick("database", false)).toBe(false);
expect(shouldOpenObjectBrowserOnSingleClick("mongo-db", true)).toBe(true);
expect(shouldOpenObjectBrowserOnSingleClick("mongo-db", false)).toBe(false);
});
it("opens the MongoDB object browser from mongo-db nodes like SQL databases", () => {
expect(treeNodeRowAction("mongo-db", true, "single", "mongodb", true, true)).toBe("open-object-browser-and-expand");
expect(treeNodeRowAction("mongo-db", true, "single", "mongodb", false, true)).toBe("toggle");
expect(treeNodeRowDoubleClickAction("mongo-db", true, "single", true, "mongodb")).toBe("open-object-browser");
});
it("expands package containers while preserving source behavior for leaf packages", () => {
@@ -18,6 +18,12 @@ describe("ObjectBrowser context watcher", () => {
expect(watcher).toContain("reload({ allowCachedObjects: true, contextEpoch })");
});
it("loads MongoDB collections through the existing objects view", () => {
expect(objectBrowserSource).toContain("api.mongoListCollections");
expect(objectBrowserSource).toContain("buildMongoObjectBrowserRows");
expect(objectBrowserSource).toContain("objects.searchCollections");
});
it("ignores connection object replacement when the context values stay unchanged", async () => {
const connection = ref({ id: "connection-1" });
const database = ref("database-1");
@@ -177,6 +177,14 @@ describe("shouldDeferSingleClick", () => {
expect(shouldDeferSingleClick(tableRow, "open-table")).toBe(false);
});
it("opens MongoDB collections instead of SQL table-info", () => {
expect(singleClickRowAction(tableRow, "mongodb")).toBe("open-table");
expect(doubleClickRowAction(tableRow, "mongodb")).toBe("open-table");
expect(singleClickRowAction(viewRow, "mongodb")).toBe("open-table");
expect(doubleClickRowAction(viewRow, "mongodb")).toBe("open-table");
expect(shouldDeferSingleClick(tableRow, "open-table", "mongodb")).toBe(false);
});
it("handles null/undefined row", () => {
expect(shouldDeferSingleClick(null, "table-info")).toBe(false);
expect(shouldDeferSingleClick(undefined, "open-source")).toBe(false);
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { orderItemsByPinnedTreeNodeOrder, removePinnedTreeNodesFromOrder, treeNodePinIdentity, treeNodePinKey } from "@/lib/app/pinnedItems";
import { buildObjectBrowserRows, canonicalizeObjectBrowserPinnedTreeNodeIdentity, objectBrowserRowLegacyPinnedTreeNodeIds, objectBrowserRowMatchesPinnedTreeNode, sortObjectBrowserRows, type ObjectBrowserRow } from "@/lib/table/objectBrowserRows";
import { buildMongoObjectBrowserRows, buildObjectBrowserRows, canonicalizeObjectBrowserPinnedTreeNodeIdentity, objectBrowserRowLegacyPinnedTreeNodeIds, objectBrowserRowMatchesPinnedTreeNode, sortObjectBrowserRows, type ObjectBrowserRow } from "@/lib/table/objectBrowserRows";
import type { TreeNode } from "@/types/database";
describe("buildObjectBrowserRows", () => {
@@ -119,3 +119,32 @@ describe("Object Browser pinned ordering", () => {
expect(objectBrowserRowMatchesPinnedTreeNode(routineRow, treeNodePinIdentity({ ...routineNode, id: "conn:app:public:functions:run:integer", label: "run(integer)", signature: "integer" }), context)).toBe(true);
});
});
describe("buildMongoObjectBrowserRows", () => {
it("maps collection kinds and keeps collection names searchable", () => {
const rows = buildMongoObjectBrowserRows({
collections: [
{ name: "users", kind: "collection" },
{ name: "active_users", kind: "view" },
{ name: "metrics", kind: "timeseries" },
],
database: "app",
});
expect(rows.map((row) => ({ name: row.name, type: row.type, collectionKind: row.collectionKind }))).toEqual([
{ name: "users", type: "TABLE", collectionKind: "collection" },
{ name: "active_users", type: "VIEW", collectionKind: "view" },
{ name: "metrics", type: "TABLE", collectionKind: "timeseries" },
]);
});
it("preserves distinct MongoDB collection identifiers verbatim", () => {
const rows = buildMongoObjectBrowserRows({
collections: [{ name: " users " }, { name: "users" }, { name: " " }, { name: "" }],
database: "app",
});
expect(rows.map((row) => row.name)).toEqual([" users ", "users", " "]);
expect(new Set(rows.map((row) => row.id))).toHaveLength(3);
});
});
@@ -216,11 +216,13 @@ export function supportsObjectBrowser(dbType?: DatabaseType): boolean {
}
export function supportsConnectionDatabaseBrowser(dbType?: DatabaseType): boolean {
return supportsObjectBrowser(dbType);
// MongoDB reuses the object browser for collections, not the SQL database list.
return supportsObjectBrowser(dbType) && dbType !== "mongodb";
}
export function supportsObjectBrowserTreeNode(dbType: DatabaseType | undefined, nodeType: TreeNodeType): boolean {
if (!supportsObjectBrowser(dbType)) return false;
if (dbType === "mongodb") return nodeType === "mongo-db";
if (nodeType === "database" && usesDatabaseObjectTreeMode(dbType)) return true;
if (nodeType === "database" && isSchemaAware(dbType) && dbType !== "sqlserver") return false;
return nodeType === "database" || nodeType === "schema" || nodeType === "object-browser";
@@ -22,6 +22,7 @@ import {
snapshotMongoIndexSpec,
toMongoCollectionKind,
toMongoIndexRow,
visibleMongoCollections,
type MongoCreateIndexForm,
type MongoIndexSpecSource,
} from "../mongoCollectionMutation";
@@ -94,6 +95,20 @@ describe("toMongoCollectionKind", () => {
});
});
describe("visibleMongoCollections", () => {
it("hides GridFS buckets and their backing collections", () => {
expect(
visibleMongoCollections([
{ name: "users", kind: "collection" },
{ name: "fs", kind: "bucket", bucketName: "fs" },
{ name: "fs.files", kind: "collection" },
{ name: "fs.chunks", kind: "collection" },
{ name: "reports", kind: "view" },
]).map((collection) => collection.name),
).toEqual(["users", "reports"]);
});
});
describe("isProtectedMongoIndex", () => {
it("protects the default index by name or primary metadata", () => {
expect(isProtectedMongoIndex({ name: "_id_", is_primary: false })).toBe(true);
@@ -34,8 +34,8 @@ export function dataTabOpenModeFromTreeClick(type: TreeNodeType, event: Omit<Sho
return matchesModifierOnlyShortcut(event, shortcut) ? "new-tab" : "default";
}
function isSameDatabase(tab: DataTabLike, target: Pick<DataTabTarget, "connectionId" | "database">): boolean {
return tab.mode === "data" && tab.connectionId === target.connectionId && tab.database === target.database;
function isSameDatabase(tab: DataTabLike, target: Pick<DataTabTarget, "connectionId" | "database">, mode: "data" | "mongo" = "data"): boolean {
return tab.mode === mode && tab.connectionId === target.connectionId && tab.database === target.database;
}
function dataTabCatalog(tab: DataTabLike): string {
@@ -47,8 +47,16 @@ function isSameTable(tab: DataTabLike, target: DataTabTarget): boolean {
return isSameDatabase(tab, target) && dataTabCatalog(tab) === (target.catalog || "") && tabSchema === (target.schema || "") && (tab.tableMeta?.tableName || tab.title) === target.tableName;
}
function canReuseActiveTableTab(tab: DataTabLike | undefined, target: DataTabTarget, mode: "data" | "mongo"): boolean {
return tab !== undefined && isSameDatabase(tab, target, mode) && dataTabCatalog(tab) === (target.catalog || "") && !tab.pinned && !tab.isExecuting && !tab.isCancelling && !tab.isExplaining && !tab.txnSessionId && !tab.pendingDataChangeCount && !tab.hasPendingDataEditorDraft;
}
export function canReuseActiveDataTab(tab: DataTabLike | undefined, target: DataTabTarget): boolean {
return tab !== undefined && isSameDatabase(tab, target) && dataTabCatalog(tab) === (target.catalog || "") && !tab.pinned && !tab.isExecuting && !tab.isCancelling && !tab.isExplaining && !tab.txnSessionId && !tab.pendingDataChangeCount && !tab.hasPendingDataEditorDraft;
return canReuseActiveTableTab(tab, target, "data");
}
export function canReuseActiveMongoTab(tab: DataTabLike | undefined, target: DataTabTarget): boolean {
return canReuseActiveTableTab(tab, target, "mongo");
}
export function canApplyDataTabMetadata(tab: DataTabLike | undefined, target: DataTabTarget, signal?: AbortSignal): boolean {
@@ -73,6 +73,13 @@ export function toMongoCollectionKind(kind?: string | null): MongoCollectionKind
return "collection";
}
/** Drop GridFS buckets and their backing `.files` / `.chunks` collections from object lists. */
export function visibleMongoCollections<T extends { name: string; kind?: string | null; bucketName?: string }>(collections: readonly T[]): T[] {
const bucketNames = new Set(collections.filter((collection) => collection.kind === "bucket" && collection.bucketName).map((collection) => collection.bucketName as string));
const hiddenCollectionNames = new Set([...bucketNames].flatMap((bucketName) => [`${bucketName}.files`, `${bucketName}.chunks`]));
return collections.filter((collection) => collection.kind !== "bucket" && !hiddenCollectionNames.has(collection.name));
}
export function mongoRenameCollectionPreview(database: string, oldName: string, newName: string): string {
return `db.getSiblingDB(${JSON.stringify(database)}).getCollection(${JSON.stringify(oldName)}).renameCollection(${JSON.stringify(newName)})`;
}
@@ -49,7 +49,7 @@ export function isRepeatableNavigationTreeNode(type: TreeNodeType): boolean {
export function shouldActivateTreeNodeOnSingleClick(type: TreeNodeType, activation: SidebarActivation = "single"): boolean {
return activation !== "double" || isDirectNavigationTreeNode(type);
}
const objectBrowserNodeTypes = new Set<TreeNodeType>(["database", "schema", "object-browser"]);
const objectBrowserNodeTypes = new Set<TreeNodeType>(["database", "schema", "object-browser", "mongo-db"]);
/** 开关“单击数据库同时打开数据库项目”命中时,单击数据库类节点直接打开对象浏览器标签页。 */
export function shouldOpenObjectBrowserOnSingleClick(type: TreeNodeType, enabled: boolean): boolean {
@@ -16,6 +16,7 @@ export type ObjectBrowserRowAction = "table-info" | "type-info" | "open-table" |
*/
export function singleClickRowAction(row: ObjectBrowserRow | null | undefined, dbType?: DatabaseType): ObjectBrowserRowAction {
if (!row) return "none";
if (dbType === "mongodb") return mongoObjectBrowserRowAction(row);
if (row.type === "TABLE") return "table-info";
if (row.type === "EVENT") return "none";
if (row.type === "TYPE" && customTypeCapabilities(dbType).details) return "type-info";
@@ -31,6 +32,7 @@ export function singleClickRowAction(row: ObjectBrowserRow | null | undefined, d
*/
export function doubleClickRowAction(row: ObjectBrowserRow | null | undefined, dbType?: DatabaseType): ObjectBrowserRowAction {
if (!row) return "none";
if (dbType === "mongodb") return mongoObjectBrowserRowAction(row);
if (row.type === "TABLE") return "open-table";
if (row.type === "EVENT") return "open-source";
if (row.type === "TYPE" && customTypeCapabilities(dbType).details) return "type-info";
@@ -65,10 +67,10 @@ export function resolveRowClickAction(row: ObjectBrowserRow | null | undefined,
* open-table). For rows whose single and double actions are identical
* (e.g. VIEW → open-source both), no deferral is needed.
*/
export function shouldDeferSingleClick(row: ObjectBrowserRow | null | undefined, action: ObjectBrowserRowAction): boolean {
export function shouldDeferSingleClick(row: ObjectBrowserRow | null | undefined, action: ObjectBrowserRowAction, dbType?: DatabaseType): boolean {
if (action === "none") return false;
const single = singleClickRowAction(row);
const double = doubleClickRowAction(row);
const single = singleClickRowAction(row, dbType);
const double = doubleClickRowAction(row, dbType);
return single !== double && action === single;
}
@@ -80,6 +82,10 @@ export function isSourceOnlyObjectBrowserRow(row: ObjectBrowserRow): boolean {
return row.type === "TRIGGER" || row.type === "SEQUENCE" || row.type === "PACKAGE" || row.type === "PACKAGE_BODY" || row.type === "TYPE" || row.type === "TYPE_BODY";
}
function mongoObjectBrowserRowAction(row: ObjectBrowserRow): ObjectBrowserRowAction {
return row.type === "TABLE" || row.type === "VIEW" ? "open-table" : "none";
}
function canOpenSource(row: ObjectBrowserRow, dbType?: DatabaseType): boolean {
// Verified PG-family TYPE rows open the read-only details panel instead;
// Xugu keeps its source editor entry through supportsTypeObjectSource below.
@@ -1,5 +1,6 @@
import type { ObjectInfo, TreeNode, TreeNodeType } from "@/types/database";
import type { MongoCollectionKind, ObjectInfo, TreeNode, TreeNodeType } from "@/types/database";
import { pinnedTreeNodeIdentityMatches, type PinnedTreeNodeIdentity } from "@/lib/app/pinnedItems";
import { toMongoCollectionKind } from "@/lib/sidebar/mongoCollectionMutation";
import { buildGroupedObjectTreeNodes, buildSimpleObjectTreeNodes, buildTableTreeNodes, compareDatabaseObjectNames, normalizeDatabaseObjectName } from "@/lib/table/tableTree";
import { parseSlashDelimitedRegexQuery } from "@/lib/common/searchPattern";
@@ -9,6 +10,7 @@ export type ObjectBrowserRow = {
displayName: string;
schema?: string;
type: "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "EVENT" | "SEQUENCE" | "PACKAGE" | "PACKAGE_BODY" | "TYPE" | "TYPE_BODY";
collectionKind?: MongoCollectionKind;
valid?: boolean | null;
signature?: string | null;
comment?: string | null;
@@ -189,6 +191,28 @@ export function buildObjectBrowserRows(options: { objects: ObjectInfo[]; databas
return rows;
}
export function buildMongoObjectBrowserRows(options: { collections: Array<{ name: string; kind?: string | null }>; database: string }): ObjectBrowserRow[] {
const seen = new Map<string, number>();
return options.collections.flatMap((collection) => {
const name = collection.name;
if (!name) return [];
const collectionKind = toMongoCollectionKind(collection.kind);
const type: ObjectBrowserRow["type"] = collectionKind === "view" ? "VIEW" : "TABLE";
const baseId = `${options.database}:${name}:${type}:${collectionKind}`;
const index = seen.get(baseId) ?? 0;
seen.set(baseId, index + 1);
return [
{
id: `${baseId}:${index}`,
name,
displayName: name,
type,
collectionKind,
},
];
});
}
function routineSignatureForDisplay(type: ObjectBrowserRow["type"], signature: string | null | undefined): string | undefined {
if (type !== "PROCEDURE" && type !== "FUNCTION") return undefined;
if (signature == null) return undefined;