feat(nebula): add NebulaGraph 3.x browser support

This commit is contained in:
Hand Sonic authored and GitHub committed 2026-09-29 21:03:12 +08:00
1 parent e59a8c1bd4
commit ef05a6a19b
69 files changed
+1737 -41

No files matched your search

@@ -151,7 +151,7 @@ import { resolveVisibleDatabaseSaveAction } from "@/components/sidebar/visibleDa
import { canSaveVisibleDatabaseSelection, connectionUsesVisibleSchemaFilter, filterDatabaseNamesForVisiblePicker, filterSchemaNamesForVisiblePicker, buildDraftVisibleSchemasConnectionId, normalizeVisibleSchemaSelection } from "@/lib/database/visibleDatabases";
import { isSchemaAware, isSingleDatabase, supportsDataDictionary } from "@/lib/database/databaseFeatureSupport";
import { normalizeConnectionScope, normalizeConnectionTimeouts } from "@/lib/connection/connectionSubmitNormalization";
import { databaseConnectionFormKind } from "@/lib/database/databaseDriverManifest";
import { databaseConnectionFormKind, databaseManifestEntry } from "@/lib/database/databaseDriverManifest";
import VisibleSchemasDialog from "@/components/sidebar/VisibleSchemasDialog.vue";
import CloudflareD1ConnectionFields from "@/components/connection/CloudflareD1ConnectionFields.vue";
import SpannerConnectionFields from "@/components/connection/SpannerConnectionFields.vue";
@@ -1184,6 +1184,8 @@ const driverProfiles: Record<string, ConnectionProfileDefinition> = {
...CONNECTION_PROFILES,
...jdbcProductDriverProfiles(),
};
const nebulaDriverProfiles = databaseManifestEntry("nebula")?.driverProfiles ?? [];
const nebulaDefaultDriverProfile = nebulaDriverProfiles[0]?.profile ?? "nebula";
function profileForConfig(config: ConnectionConfig) {
if (config.db_type === "plugin" && config.plugin_id && config.plugin_connection_provider) {
@@ -2804,7 +2806,7 @@ function applyProfile(val: string, preserveConnectionFields = false) {
const previousDatabaseType = form.value.db_type;
selectedType.value = val;
form.value.db_type = profile.type;
form.value.driver_profile = val;
form.value.driver_profile = val === "nebula" ? nebulaDefaultDriverProfile : val;
form.value.driver_label = isCustomCompatibleProfile() ? customDriverName.value.trim() || profile.label : profile.label;
const preserveMeilisearchConfig = preserveConnectionFields && previousDatabaseType === "meilisearch" && profile.type === "meilisearch";
if (profile.type !== "sqlserver" && !preserveMeilisearchConfig) {
@@ -3434,6 +3436,12 @@ function switchEtcdApiVersion(profile: "etcd" | "etcd-v2") {
resetTestState();
}
function switchNebulaDriverProfile(profile: unknown) {
if (typeof profile !== "string" || !nebulaDriverProfiles.some((entry) => entry.profile === profile)) return;
form.value.driver_profile = profile;
resetTestState();
}
function switchH2DriverProfile(profile: "h2" | "h2-v1" | "h2-v2" | "h2-v3" | "h2-custom") {
form.value.driver_profile = profile;
if (profile === "h2-custom") {
@@ -3650,11 +3658,12 @@ const tlsCapableDatabaseTypes = new Set<DatabaseType>([
"influxdb",
"victoriametrics",
"cassandra",
"nebula",
"zookeeper",
]);
const supportsTlsToggle = computed(() => tlsCapableDatabaseTypes.has(form.value.db_type) || supportsMysqlTlsTab(form.value.db_type, selectedType.value));
const supportsCaCertificatePath = computed(() => form.value.db_type === "clickhouse" || form.value.db_type === "victoriametrics");
const supportsGenericUrlParams = computed(() => form.value.db_type !== "manticoresearch" && form.value.db_type !== "hbase");
const supportsGenericUrlParams = computed(() => form.value.db_type !== "manticoresearch" && form.value.db_type !== "hbase" && form.value.db_type !== "nebula");
const showGenericUrlParamsHint = computed(() => form.value.db_type === "mysql" || form.value.db_type === "doris" || form.value.db_type === "starrocks");
const bareMysqlProfiles = new Set(["doris", "selectdb", "oceanbase"]);
const supportsMysqlTlsOptions = computed(() => mysqlTlsOptionsSupported(form.value.db_type, selectedType.value));
@@ -4628,6 +4637,9 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugi
} else {
config = { ...formValueForSubmit(), id } as LegacyConnectionConfig;
}
if (config.db_type === "nebula" && (!config.driver_profile || config.driver_profile === "nebula")) {
config.driver_profile = nebulaDefaultDriverProfile;
}
config.database_info = undefined;
config.database = normalizeStoredConnectionDatabase(config.db_type, config.database);
config.note = config.note?.trim() || undefined;
@@ -7031,6 +7043,20 @@ function openExternalUrl(url: string) {
</button>
</div>
<div v-if="form.db_type === 'nebula'" class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelClass">{{ t("connection.version") }}</Label>
<div class="col-span-3">
<Select :model-value="form.driver_profile === 'nebula' ? nebulaDefaultDriverProfile : form.driver_profile" @update:model-value="switchNebulaDriverProfile">
<SelectTrigger class="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem v-for="profile in nebulaDriverProfiles" :key="profile.profile" :value="profile.profile">{{ profile.label }}</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<!-- OceanBase mode toggle -->
<div v-if="selectedType === 'oceanbase'" class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelSmallClass">{{ t("connection.mode") }}</Label>
@@ -9322,7 +9348,7 @@ function openExternalUrl(url: string) {
</label>
</div>
<template v-if="form.db_type === 'etcd' || form.db_type === 'consul' || form.db_type === 'zookeeper' || form.db_type === 'elasticsearch' || form.db_type === 'easysearch'">
<template v-if="form.db_type === 'etcd' || form.db_type === 'consul' || form.db_type === 'zookeeper' || form.db_type === 'elasticsearch' || form.db_type === 'easysearch' || form.db_type === 'nebula'">
<div class="grid grid-cols-4 items-start gap-4">
<Label :class="connectionLabelSmallPaddedClass">
<span class="inline-flex items-center justify-end gap-1">
@@ -9375,7 +9401,7 @@ function openExternalUrl(url: string) {
<TooltipContent>{{ t("connection.etcdClientKeyBrowse") }}</TooltipContent>
</Tooltip>
</div>
<p class="text-[11px] leading-4 text-muted-foreground">
<p v-if="form.db_type !== 'nebula'" class="text-[11px] leading-4 text-muted-foreground">
{{ t("connection.etcdClientCertHint") }}
</p>
</div>
@@ -801,7 +801,7 @@ function sqlVariableSyntaxToggle(key: keyof SqlVariableSyntaxToggles): boolean {
function setSqlVariableSyntaxToggle(key: keyof SqlVariableSyntaxToggles, value: boolean) {
const dbType = editSqlVariableSyntaxDatabaseType.value;
if (dbType === "neo4j" && key === "named") return;
if ((dbType === "neo4j" || dbType === "nebula") && key === "named") return;
const merged: SqlVariableSyntaxToggles = {
...DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES,
...editSqlVariableSyntaxOverrides.value[dbType],
@@ -7002,7 +7002,7 @@ onUnmounted(() => {
<Switch
:id="`sql-var-syntax-${key}`"
:model-value="sqlVariableSyntaxToggle(key)"
:disabled="!editSqlVariableSubstitutionEnabled || (editSqlVariableSyntaxDatabaseType === 'neo4j' && key === 'named')"
:disabled="!editSqlVariableSubstitutionEnabled || (['neo4j', 'nebula'].includes(editSqlVariableSyntaxDatabaseType) && key === 'named')"
class="mt-0.5 shrink-0"
@update:model-value="(value) => setSqlVariableSyntaxToggle(key, value as boolean)"
/>
@@ -750,7 +750,7 @@ const resolvedDatabaseType = computed(() => props.databaseType ?? effectiveDatab
// editor and clipboard path must decode it whenever MongoDB values are on screen.
const usesMongoDocumentGridValues = computed(() => props.mongoCollectionGrid === true || resolvedDatabaseType.value === "mongodb");
const isResultsContext = computed(() => props.context === "results");
const canShowWhereSearch = computed(() => !!props.onExecuteSql && !isResultsContext.value && resolvedDatabaseType.value !== "victoriametrics");
const canShowWhereSearch = computed(() => !!props.onExecuteSql && !isResultsContext.value && resolvedDatabaseType.value !== "victoriametrics" && resolvedDatabaseType.value !== "nebula");
const canUseWhereSearch = computed(() => !!props.tableMeta && canShowWhereSearch.value);
const canUseServerColumnFilter = computed(() => canUseWhereSearch.value && !!props.connectionId && !!props.tableMeta);
const tableStructureCapabilities = computed(() => getTableStructureCapabilities(resolvedDatabaseType.value, resolvedConnectionConfig.value?.db_type));
@@ -87,6 +87,7 @@ const assetIcons: Record<string, string> = {
starrocks: "starrocks",
redshift: "redshift",
neo4j: "neo4j",
nebula: "nebula.png",
informix: "informix",
databricks: "databricks",
saphana: "saphana",
@@ -310,14 +310,12 @@ const effectiveDatabaseType = computed(() => effectiveDatabaseTypeForConnection(
const isGaussdbM = computed(() => effectiveDatabaseType.value === "gaussdb" && props.connection.driver_profile?.toLowerCase() === "gaussdb-m");
const isVictoriaMetrics = computed(() => effectiveDatabaseType.value === "victoriametrics");
const isMongodb = computed(() => props.connection.db_type === "mongodb");
// Victoria Metrics reports series instead of rows and has no byte size to show;
// every other engine (MongoDB collections included, via `collStats`) fills both
// the row and size columns.
const supportsObjectSizeStats = computed(() => !isVictoriaMetrics.value);
// Neither VictoriaMetrics series nor NebulaGraph tag/edge metadata has table byte-size stats.
const supportsObjectSizeStats = computed(() => !isVictoriaMetrics.value && effectiveDatabaseType.value !== "nebula");
// The batch table toolbar (export/copy/truncate/empty/drop selected) is SQL-only:
// MongoDB collections are not dropped or truncated through it.
const supportsBatchTableActions = computed(() => !isVictoriaMetrics.value && !isMongodb.value);
const showTableStatistics = computed(() => objectFilter.value === "all" || objectFilter.value === "tables");
const supportsBatchTableActions = computed(() => !isVictoriaMetrics.value && !isMongodb.value && effectiveDatabaseType.value !== "nebula");
const showTableStatistics = computed(() => effectiveDatabaseType.value !== "nebula" && (objectFilter.value === "all" || objectFilter.value === "tables"));
const showObjectRowStats = computed(() => showTableStatistics.value);
const showObjectSizeStats = computed(() => supportsObjectSizeStats.value && showTableStatistics.value);
const objectRowsLabel = computed(() => t(isVictoriaMetrics.value ? "objects.series" : "objects.rows"));
@@ -617,7 +615,7 @@ watch(
},
);
const showCheckboxColumn = computed(() => settingsStore.editorSettings.objectBrowserShowCheckbox || selectedTableCount.value > 0);
const showCheckboxColumn = computed(() => supportsBatchTableActions.value && (settingsStore.editorSettings.objectBrowserShowCheckbox || selectedTableCount.value > 0));
function toggleCheckboxColumn() {
const next = !settingsStore.editorSettings.objectBrowserShowCheckbox;
@@ -2576,7 +2574,7 @@ async function copySelectedTablesToClipboard() {
}
function canPasteTableClipboard(): boolean {
return !isVictoriaMetrics.value && !isMongodb.value && tableClipboardMatchesTarget(normalizedObjectBrowserTableClipboardEntries(), pasteTableTargetContext());
return supportsBatchTableActions.value && tableClipboardMatchesTarget(normalizedObjectBrowserTableClipboardEntries(), pasteTableTargetContext());
}
function normalizedObjectBrowserTableClipboardEntries() {
@@ -2668,7 +2666,7 @@ function openPasteTableDialog() {
}
function onObjectBrowserKeydown(event: KeyboardEvent) {
if (event.defaultPrevented) return;
if (event.defaultPrevented || !supportsBatchTableActions.value) return;
if (eventTargetAllowsAppClipboardShortcut(event, "c")) {
if (selectedTableCount.value === 0) return;
event.preventDefault();
@@ -3462,6 +3460,14 @@ function selectedBatchTableCountLabel(key: "batchDrop" | "batchTruncate" | "batc
}
function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
if (effectiveDatabaseType.value === "nebula") {
return [
{ label: t("contextMenu.viewData"), action: () => openViewData(item), icon: Table2 },
{ label: t("contextMenu.viewDdl"), action: () => openTableInfo(item, "ddl"), icon: FileCode },
{ label: "", separator: true },
{ label: t("contextMenu.copyName"), action: () => copyName(item), icon: Copy },
];
}
if (isVictoriaMetrics.value) {
return [
{ label: t("contextMenu.viewData"), action: () => openViewData(item), icon: Table2 },
@@ -3530,6 +3536,14 @@ function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
}
function getViewMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
if (effectiveDatabaseType.value === "nebula") {
return [
{ label: t("contextMenu.viewData"), action: () => openViewData(item), icon: Table2 },
{ label: t("contextMenu.viewDdl"), action: () => openTableInfo(item, "ddl"), icon: ScrollText },
{ label: "", separator: true },
{ label: t("contextMenu.copyName"), action: () => copyName(item), icon: Copy },
];
}
return [
{ label: t("contextMenu.viewData"), action: () => openViewData(item), icon: Table2 },
{ label: t("contextMenu.editView"), action: () => openSource(item), icon: PencilLine },
@@ -3709,7 +3723,7 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<LayoutGrid class="h-3.5 w-3.5" />
</button>
</div>
<Button v-if="showInlineCheckboxToggle" variant="ghost" size="icon" class="h-7 w-7" :class="{ 'text-primary': settingsStore.editorSettings.objectBrowserShowCheckbox }" :title="t('objects.toggleCheckbox')" @click="toggleCheckboxColumn">
<Button v-if="showInlineCheckboxToggle && supportsBatchTableActions" variant="ghost" size="icon" class="h-7 w-7" :class="{ 'text-primary': settingsStore.editorSettings.objectBrowserShowCheckbox }" :title="t('objects.toggleCheckbox')" @click="toggleCheckboxColumn">
<CheckSquare v-if="settingsStore.editorSettings.objectBrowserShowCheckbox" class="h-3.5 w-3.5" />
<Square v-else class="h-3.5 w-3.5" />
</Button>
@@ -3747,14 +3761,14 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {
<LayoutGrid class="h-3.5 w-3.5" />
{{ t("objects.viewGrid") }}
</DropdownMenuItem>
<DropdownMenuCheckboxItem :model-value="settingsStore.editorSettings.objectBrowserShowCheckbox" @select.prevent @update:model-value="toggleCheckboxColumn()">{{ t("objects.toggleCheckbox") }}</DropdownMenuCheckboxItem>
<DropdownMenuCheckboxItem v-if="supportsBatchTableActions" :model-value="settingsStore.editorSettings.objectBrowserShowCheckbox" @select.prevent @update:model-value="toggleCheckboxColumn()">{{ t("objects.toggleCheckbox") }}</DropdownMenuCheckboxItem>
<template v-if="showObjectFilter && toolbarTier >= 2">
<DropdownMenuSeparator />
<DropdownMenuCheckboxItem v-for="filter in objectFilters" :key="filter" :model-value="objectFilter === filter" @select.prevent @update:model-value="selectObjectFilter(filter)">{{ filterLabel(filter) }}</DropdownMenuCheckboxItem>
</template>
</ToolbarOverflowMenu>
</div>
<div v-if="selectedTableCount > 0" class="flex h-9 shrink-0 items-center gap-2 overflow-x-auto border-b bg-muted/30 px-3 text-xs">
<div v-if="selectedTableCount > 0 && supportsBatchTableActions" class="flex h-9 shrink-0 items-center gap-2 overflow-x-auto border-b bg-muted/30 px-3 text-xs">
<div class="min-w-0 flex-1 truncate text-muted-foreground">
{{ t("objects.selectedTables", { count: selectedTableCount }) }}
</div>
@@ -93,6 +93,7 @@ const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
beforeEach(() => {
vi.clearAllMocks();
connection.db_type = "mysql";
mocks.store.treeClipboard = null;
mocks.listObjects.mockResolvedValue([
{ name: "orders", object_type: "TABLE" },
@@ -154,4 +155,18 @@ describe("ObjectBrowser table copy", () => {
await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("grid.copyFailed", 5000));
expect(mocks.toast).not.toHaveBeenCalledWith("contextMenu.pasteTableClipboardUpdated", 2000);
});
it("does not expose relational table copy or batch actions for NebulaGraph", async () => {
connection.db_type = "nebula";
const host = await mountBrowser();
rowFor(host, "orders").dispatchEvent(new MouseEvent("click", { bubbles: true, ctrlKey: true }));
await nextTick();
expect(host.textContent).not.toContain("objects.exportSelected");
expect(host.textContent).not.toContain("objects.dropSelected");
expect(host.querySelector('[title="objects.toggleCheckbox"]')).toBeNull();
host.querySelector<HTMLElement>("[data-object-browser-root]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "c", ctrlKey: true, bubbles: true }));
expect(mocks.copyToClipboard).not.toHaveBeenCalled();
expect(mocks.store.treeClipboard).toBeNull();
});
});
@@ -2787,6 +2787,7 @@ function requestDropTableChildObject() {
}
function canDropTreeNode(node: TreeNode): boolean {
if (databaseTypeForNode(node) === "nebula") return false;
if (isSqlServerLinkedNode(node)) return false;
if (node.type === "table") return !!node.connectionId && !!node.database;
if (node.type === "view" || node.type === "materialized_view" || node.type === "procedure" || node.type === "function" || node.type === "event") {
@@ -3129,6 +3130,7 @@ function requestDropSelectedNodes(): boolean {
}
function requestDropSelectedNode(): boolean {
if (currentDatabaseType() === "nebula") return false;
if (activeNode.value.type === "table") {
dropTable();
return true;
@@ -4753,7 +4755,7 @@ const canOpenSqlFileExecution = computed(() => {
const canExportAllDatabases = computed(() => {
if (activeNode.value.type !== "connection" || !activeNode.value.connectionId) return false;
const dbType = connectionStore.getConfig(activeNode.value.connectionId)?.db_type;
return !["redis", "mongodb", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "plugin", "salesforce"].includes(dbType || "");
return !["redis", "mongodb", "dynamodb", "elasticsearch", "easysearch", "meilisearch", "solr", "qdrant", "milvus", "weaviate", "chromadb", "etcd", "zookeeper", "consul", "mq", "nacos", "plugin", "salesforce", "nebula"].includes(dbType || "");
});
const canOpenScheduledBackups = computed(() => {
@@ -5860,6 +5862,19 @@ function buildDatabaseSidebarMenu(context: SidebarMenuFactoryContext): boolean {
});
return true;
}
if (currentDatabaseType() === "nebula" && node.type === "database") {
if (canCloseDatabaseConnection.value) items.push({ label: t("contextMenu.closeDatabaseConnection"), action: closeDatabaseConnection, icon: Unplug });
items.push(copyNameMenuItem());
items.push({ label: "", separator: true });
if (canOpenObjectBrowser.value) items.push({ label: t("contextMenu.openObjectBrowser"), action: openObjectBrowser, icon: TableProperties });
items.push({ label: t("contextMenu.newQuery"), action: newQuery, icon: TerminalSquare });
const sqlHistoryMenu = savedSqlHistorySubmenu();
if (sqlHistoryMenu) items.push(sqlHistoryMenu);
items.push({ label: isNodeDefaultDatabase.value ? t("contextMenu.clearDefaultDatabase") : t("contextMenu.setDefaultDatabase"), action: isNodeDefaultDatabase.value ? clearNodeDefaultDatabase : setNodeAsDefaultDatabase, icon: Database });
items.push({ label: "", separator: true });
items.push({ label: t("contextMenu.refreshChildren"), action: refresh, icon: RefreshCw, shortcut: shortcutRefresh });
return true;
}
if (canCloseDatabaseConnection.value) {
items.unshift({ label: "", separator: true });
items.unshift({ label: t("contextMenu.closeDatabaseConnection"), action: closeDatabaseConnection, icon: Unplug });
@@ -6266,6 +6281,20 @@ function buildObjectSidebarMenu(context: SidebarMenuFactoryContext): boolean {
appendPluginTableMenuItems(items, node);
return true;
}
if (currentDatabaseType() === "nebula") {
items.push(copyNameMenuItem());
items.push({ label: t("contextMenu.newQuery"), action: newQuery, icon: TerminalSquare });
items.push({ label: "", separator: true });
items.push({ label: t("contextMenu.viewData"), action: openDataImmediately, icon: TableProperties });
items.push({ label: t("contextMenu.openInNewDataTab"), action: openDataInNewTabImmediately, icon: CopyPlus, shortcut: shortcutOpenDataInNewTab.value });
items.push({ label: t("contextMenu.viewDdl"), action: openDdl, icon: FileCode });
const sqlHistoryMenu = savedSqlHistorySubmenu();
if (sqlHistoryMenu) items.push(sqlHistoryMenu);
items.push({ label: "", separator: true });
items.push({ label: t("contextMenu.refreshChildren"), action: refresh, icon: RefreshCw, shortcut: shortcutRefresh });
appendPluginTableMenuItems(items, node);
return true;
}
const destructiveActions: ContextMenuItem[] = [];
items.push(copyNameMenuItem());
items.push({ label: t("contextMenu.newQuery"), action: newQuery, icon: TerminalSquare });
@@ -6618,7 +6647,7 @@ function buildObjectGroupSidebarMenu(context: SidebarMenuFactoryContext): boolea
const mysqlObjectTemplate = node.connectionId ? mysqlObjectTemplateForGroup(connectionStore.getConfig(node.connectionId), node) : null;
const hasMongoCreateIndexAction = node.type === "group-indexes" && canCreateMongoIndex.value;
const hasMongoDropAllIndexesAction = node.type === "group-indexes" && canDropAllMongoIndexes.value;
const hasGroupAction = (node.type === "group-tables" && canCreateTable.value) || (node.type === "group-views" && !!node.connectionId && !!node.database) || !!mysqlObjectTemplate || hasMongoCreateIndexAction || hasMongoDropAllIndexesAction;
const hasGroupAction = (node.type === "group-tables" && canCreateTable.value) || (node.type === "group-views" && !!node.connectionId && !!node.database && currentDatabaseType() !== "nebula") || !!mysqlObjectTemplate || hasMongoCreateIndexAction || hasMongoDropAllIndexesAction;
const canLoadAllObjectGroup = node.type === "group-tables" || node.type === "group-dolt-system-tables" || node.type === "group-views" || node.type === "group-materialized-views";
if (node.type === "group-tables" && canCreateTable.value) {
items.push({ label: t("contextMenu.createTable"), action: createTable, icon: Plus });
@@ -6629,7 +6658,7 @@ function buildObjectGroupSidebarMenu(context: SidebarMenuFactoryContext): boolea
items.push({ label: t("contextMenu.pasteTable"), action: openPasteTableDialog, icon: Clipboard });
}
}
if (node.type === "group-views" && node.connectionId && node.database) {
if (node.type === "group-views" && node.connectionId && node.database && currentDatabaseType() !== "nebula") {
items.push({ label: t("contextMenu.createView"), action: createView, icon: Plus });
}
if (node.type === "group-events" && node.connectionId && node.database) {
@@ -0,0 +1,80 @@
// @vitest-environment happy-dom
import { createApp, defineComponent, h, nextTick, ref, type App } from "vue";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
import type { TreeNode } from "@/types/database";
vi.mock("@/lib/backend/api", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/backend/api")>();
return { ...actual, listPlugins: vi.fn().mockResolvedValue([]) };
});
import SidebarTreeRuntimeHost from "@/components/sidebar/SidebarTreeRuntimeHost.vue";
import { useConnectionStore } from "@/stores/connectionStore";
const connection = { id: "nebula-1", name: "NebulaGraph", db_type: "nebula", driver_profile: "nebula", host: "localhost", port: 9669, username: "root", password: "" };
const node = (type: TreeNode["type"], label: string): TreeNode => ({ id: `nebula-1:space:${type}:${label}`, type, label, connectionId: connection.id, database: "space", tableName: label });
const mountedApps: App<Element>[] = [];
const labels = (items: ContextMenuItem[]): string[] => items.flatMap((item) => [...(item.label ? [item.label] : []), ...(item.children ? labels(item.children) : [])]);
const tr = (key: string) => i18n.global.t(key);
async function mountHost() {
const pinia = createPinia();
setActivePinia(pinia);
useConnectionStore().connections = [connection];
const host = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);
const root = defineComponent({ setup: () => () => h(SidebarTreeRuntimeHost, { ref: host, node: node("connection", connection.name), depth: 0 }) });
const container = document.createElement("div");
document.body.appendChild(container);
const app = createApp(root);
app.use(pinia);
app.use(i18n);
app.mount(container);
mountedApps.push(app);
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 0));
await nextTick();
return host.value as { buildContextMenu(node: TreeNode): ContextMenuItem[] };
}
describe("NebulaGraph sidebar context menus", () => {
afterEach(() => {
for (const app of mountedApps.splice(0)) app.unmount();
document.body.innerHTML = "";
});
it("keeps space browsing and queries without relational database operations", async () => {
const host = await mountHost();
const items = labels(host.buildContextMenu(node("database", "space")));
expect(items).toEqual(expect.arrayContaining([tr("contextMenu.copyName"), tr("contextMenu.newQuery"), tr("contextMenu.openObjectBrowser"), tr("contextMenu.refreshChildren")]));
for (const key of ["transfer.dataTransfer", "diff.title", "dataCompare.title", "contextMenu.exportDatabase", "dataDictionary.title", "sqlFile.title"]) {
expect(items).not.toContain(tr(key));
}
});
it.each(["table", "view"] as const)("keeps %s reads and DDL without SQL table mutations", async (type) => {
const host = await mountHost();
const items = labels(host.buildContextMenu(node(type, type === "table" ? "person" : "knows")));
expect(items).toEqual(expect.arrayContaining([tr("contextMenu.copyName"), tr("contextMenu.newQuery"), tr("contextMenu.viewData"), tr("contextMenu.viewDdl"), tr("contextMenu.refreshChildren")]));
for (const key of ["contextMenu.generateSql", "contextMenu.exportDatabase", "contextMenu.exportData", "contextMenu.editView", "contextMenu.dropView", "contextMenu.dropTable", "contextMenu.emptyTable", "contextMenu.duplicateStructure", "dataCompare.title"]) {
expect(items).not.toContain(tr(key));
}
});
it("does not offer SQL view creation on the edge group", async () => {
const host = await mountHost();
const items = labels(host.buildContextMenu(node("group-views", "Edges")));
expect(items).toContain(tr("contextMenu.refreshChildren"));
expect(items).not.toContain(tr("contextMenu.createView"));
});
it("does not offer SQL files or all-database export on the connection", async () => {
const host = await mountHost();
const items = labels(host.buildContextMenu(node("connection", connection.name)));
expect(items).toContain(tr("contextMenu.newQuery"));
expect(items).not.toContain(tr("sqlFile.title"));
expect(items).not.toContain(tr("contextMenu.exportAllDatabases"));
});
});