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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(objects): allow editing procedures and routines from context menu (#12631)
lxk95544496cd07ee2
diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex 5d8697f1f4..c521d4e63f 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -4728,7 +4728,8 @@ function getProcFuncMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {return [...(item.type === "PROCEDURE" ? [{ label: t("contextMenu.executeProcedure"), action: () => openProcedureExecution(item), icon: Play }] : []),...(effectiveDatabaseType.value === "xugu" && buildXuguCompileSql({ objectType: item.type, schema: item.schema || selectedSchema.value, name: item.name }) ? [{ label: t("contextMenu.compileObject"), action: () => compileXuguObject(item), icon: Wrench }] : []),- { label: t("contextMenu.viewSource"), action: () => openSource(item), icon: Code2 },+ { sidebarActionId: "contextMenu.editObject", label: t("contextMenu.editObject"), action: () => openSource(item), icon: PencilLine },+ { sidebarActionId: "contextMenu.viewSource", label: t("contextMenu.viewSource"), action: () => openSource(item), icon: Code2 },...(canRename(item) ? [{ label: t("contextMenu.renameObject"), action: () => requestRename(item), icon: Pencil }] : []),{ label: "", separator: true },{@@ -4757,7 +4758,8 @@ function getPackageMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {return [...((effectiveDatabaseType.value === "oracle" || effectiveDatabaseType.value === "oceanbase-oracle") && (item.type === "PACKAGE" || item.type === "PACKAGE_BODY") ? [{ label: t("objects.packageSaveAsTitle"), action: () => requestPackageSaveAs(item), icon: CopyPlus }] : []),...(effectiveDatabaseType.value === "xugu" && buildXuguCompileSql({ objectType: item.type, schema: item.schema || selectedSchema.value, name: item.name }) ? [{ label: t("contextMenu.compileObject"), action: () => compileXuguObject(item), icon: Wrench }] : []),- { label: t("contextMenu.viewSource"), action: () => openSource(item), icon: Code2 },+ { sidebarActionId: "contextMenu.editObject", label: t("contextMenu.editObject"), action: () => openSource(item), icon: PencilLine },+ { sidebarActionId: "contextMenu.viewSource", label: t("contextMenu.viewSource"), action: () => openSource(item), icon: Code2 },{ label: "", separator: true },{ label: t("contextMenu.copyName"), action: () => copyName(item), icon: Copy },];diff --git a/apps/desktop/src/components/objects/ObjectSourceDialog.vue b/apps/desktop/src/components/objects/ObjectSourceDialog.vueindex c03581c908..451fbbf505 100644--- a/apps/desktop/src/components/objects/ObjectSourceDialog.vue+++ b/apps/desktop/src/components/objects/ObjectSourceDialog.vue@@ -87,7 +87,9 @@ onBeforeUnmount(() => {});const canEdit = computed(() => sourceEditable.value && (props.objectType !== "SEQUENCE" || props.databaseType === "oceanbase-oracle"));-const title = computed(() => `${editing.value ? t("contextMenu.editView") : t("contextMenu.viewSource")} - ${props.name}`);+const isViewLike = computed(() => props.objectType === "VIEW" || props.objectType === "MATERIALIZED_VIEW");+const editLabel = computed(() => (isViewLike.value ? t("contextMenu.editView") : t("contextMenu.editObject")));+const title = computed(() => `${editing.value ? editLabel.value : t("contextMenu.viewSource")} - ${props.name}`);const hasRoutineMetadata = computed(() => !!routineMetadata.value && (routineMetadata.value.parameters.length > 0 || !!routineMetadata.value.returnType));watch(@@ -329,7 +331,7 @@ function closeDialog() {</Button><Button v-if="!editing && canEdit && section === 'source'" variant="outline" :disabled="!editableText" @click="editSource"><PencilLine class="h-4 w-4" />- {{ t("contextMenu.editView") }}+ {{ editLabel }}</Button><Button v-if="editing && section === 'source'" variant="outline" :disabled="saving" @click="cancelEditSource">{{ t("objects.cancelEdit") }}diff --git a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.jdbcRoutineMetadata.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.jdbcRoutineMetadata.spec.tsindex 722585863c..54a9bc7090 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.jdbcRoutineMetadata.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.jdbcRoutineMetadata.spec.ts@@ -89,7 +89,7 @@ describe("ObjectSourceDialog generic JDBC routine metadata", () => {expect(document.querySelector("[data-query-editor-stub]")).toBeNull();expect(document.body.textContent).not.toContain("Object source is not supported");expect(mocks.getObjectSource).toHaveBeenCalledTimes(1);- expect([...document.querySelectorAll("button")].some((button) => button.textContent?.trim() === "contextMenu.editView")).toBe(false);+ expect([...document.querySelectorAll("button")].some((button) => button.textContent?.trim() === "contextMenu.editObject" || button.textContent?.trim() === "contextMenu.editView")).toBe(false);});it("keeps a legacy source payload without the optional field on the existing preview path", async () => {diff --git a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.tsindex bc9e78ecb1..2b94186fc8 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.ts@@ -120,7 +120,7 @@ describe("OceanBase sequence source through the shared Oracle object dialog", ()expect(editor()!.state.doc.toString()).toMatch(/CREATE\s+SEQUENCE/i);expect(editor()!.state.doc.toString()).toMatch(/START\s+WITH\s+40/i);expect(mocks.buildEditableObjectSource).toHaveBeenCalledWith({ databaseType: "oceanbase-oracle", objectType: "SEQUENCE", schema: "APP", name: "SEQ", source: ddl });- button("contextMenu.editView")!.click();+ button("contextMenu.editObject")!.click();await vi.waitFor(() => expect(editor()!.state.facet(EditorState.readOnly)).toBe(false));expect(editor()!.state.doc.toString()).toBe(alter);expect(editor()!.state.doc.toString()).not.toContain("START WITH");@@ -139,14 +139,14 @@ describe("OceanBase sequence source through the shared Oracle object dialog", ()await mount({ databaseType: "oracle", initialEditing });expect(editor()!.state.facet(EditorState.readOnly)).toBe(true);expect(editor()!.state.doc.toString()).toMatch(/CREATE\s+SEQUENCE/i);- expect(button("contextMenu.editView")).toBeUndefined();+ expect(button("contextMenu.editObject")).toBeUndefined();expect(button("objects.saveSource")).toBeUndefined();expect(mocks.executeQuery).not.toHaveBeenCalled();});it("honors a driver-declared read-only OceanBase object", async () => {await mount({ editable: false, initialEditing: true });expect(editor()!.state.facet(EditorState.readOnly)).toBe(true);- expect(button("contextMenu.editView")).toBeUndefined();+ expect(button("contextMenu.editObject")).toBeUndefined();expect(mocks.executeQuery).not.toHaveBeenCalled();});it("does not execute a sequence save after the selected connection changes during SQL generation", async () => {diff --git a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.routineTitle.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.routineTitle.spec.tsnew file mode 100644index 0000000000..d3336c941c--- /dev/null+++ b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.routineTitle.spec.ts@@ -0,0 +1,123 @@+// @vitest-environment happy-dom+import { createApp, h, type App } from "vue";+import { createPinia, setActivePinia } from "pinia";+import { createI18n } from "vue-i18n";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useConnectionStore } from "@/stores/connectionStore";+import type { ConnectionConfig, DatabaseType, ObjectSourceKind } from "@/types/database";+import ObjectSourceDialog from "../ObjectSourceDialog.vue";++const mocks = vi.hoisted(() => ({+ getObjectSource: vi.fn(),+ buildEditableObjectSource: vi.fn(),+ buildExecutableObjectSourceStatements: vi.fn(),+ executeQuery: vi.fn(),+}));++vi.mock("@/lib/backend/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/backend/api")>()),+ ...mocks,+}));++const mountedApps: Array<{ app: App; host: HTMLElement }> = [];++afterEach(() => {+ for (const { app, host } of mountedApps.splice(0)) {+ app.unmount();+ host.remove();+ }+ vi.restoreAllMocks();+ for (const mock of Object.values(mocks)) mock.mockReset();+});++function button(text: string) {+ return [...document.querySelectorAll<HTMLButtonElement>("button")].find((element) => element.textContent?.trim() === text);+}++async function mountDialog(options: { objectType: ObjectSourceKind; name: string; initialEditing?: boolean }) {+ const pinia = createPinia();+ setActivePinia(pinia);+ const store = useConnectionStore();+ vi.spyOn(store, "ensureConnected").mockResolvedValue(undefined as any);+ vi.spyOn(store, "getConfig").mockReturnValue({ id: "pg", name: "test", db_type: "postgres" } as ConnectionConfig);+ mocks.getObjectSource.mockResolvedValue({+ name: options.name,+ schema: "public",+ object_type: options.objectType,+ source: "CREATE OR REPLACE ...",+ editable: true,+ });+ mocks.buildEditableObjectSource.mockResolvedValue("CREATE OR REPLACE ...");++ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp({+ render: () =>+ h(ObjectSourceDialog, {+ open: true,+ connectionId: "pg",+ database: "testdb",+ schema: "public",+ name: options.name,+ objectType: options.objectType,+ databaseType: "postgres" as DatabaseType,+ dialect: "postgres",+ initialEditing: options.initialEditing ?? false,+ }),+ });+ app.use(pinia);+ app.use(+ createI18n({+ legacy: false,+ locale: "en",+ messages: {+ en: {+ contextMenu: {+ editView: "Edit View",+ editObject: "Edit Object",+ viewSource: "View Source",+ },+ common: {+ loading: "Loading...",+ close: "Close",+ },+ },+ },+ }),+ );+ app.mount(host);+ mountedApps.push({ app, host });+ await vi.waitFor(+ () => {+ const btn = button("Edit Object") || button("Edit View");+ expect(btn).toBeDefined();+ expect(btn?.disabled).toBe(false);+ },+ { timeout: 10_000 },+ );+ return host;+}++describe("ObjectSourceDialog dynamic edit label and title", () => {+ it("uses Edit Object for procedures in view mode and editing title", async () => {+ await mountDialog({ objectType: "PROCEDURE", name: "calculate_bonus" });+ const editBtn = button("Edit Object");+ expect(editBtn).toBeDefined();+ expect(button("Edit View")).toBeUndefined();+ expect(document.querySelector("[role='dialog']")?.textContent).toContain("View Source - calculate_bonus");++ editBtn!.click();+ await vi.waitFor(() => expect(document.querySelector("[role='dialog']")?.textContent).toContain("Edit Object - calculate_bonus"));+ });++ it("uses Edit View for views in view mode and editing title", async () => {+ await mountDialog({ objectType: "VIEW", name: "active_users" });+ const editBtn = button("Edit View");+ expect(editBtn).toBeDefined();+ expect(button("Edit Object")).toBeUndefined();+ expect(document.querySelector("[role='dialog']")?.textContent).toContain("View Source - active_users");++ editBtn!.click();+ await vi.waitFor(() => expect(document.querySelector("[role='dialog']")?.textContent).toContain("Edit View - active_users"));+ });+});diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vueindex 0b0906e07b..83d959c366 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue@@ -7717,7 +7717,10 @@ function buildObjectSidebarMenu(context: SidebarMenuFactoryContext): boolean {if (!isPackageMember && currentDatabaseType() === "xugu" && buildXuguCompileSql({ objectType: node.type, schema: node.schema, name: node.objectName || node.label })) {items.push({ label: t("contextMenu.compileObject"), action: compileXuguObject, icon: Wrench });}- items.push({ label: t("contextMenu.viewSource"), action: () => openObjectSourceDialog(false), icon: Code2 });+ if (!isPackageMember) {+ items.push({ sidebarActionId: "contextMenu.editObject", label: t("contextMenu.editObject"), action: () => openObjectSourceDialog(true), icon: Pencil });+ }+ items.push({ sidebarActionId: "contextMenu.viewSource", label: t("contextMenu.viewSource"), action: () => openObjectSourceDialog(false), icon: Code2 });if (!isPackageMember) {items.push({ label: t("diff.title"), action: openSchemaDiffForRoutine, icon: ArrowRightLeft });}@@ -7798,7 +7801,10 @@ function buildObjectSidebarMenu(context: SidebarMenuFactoryContext): boolean {if (currentDatabaseType() === "xugu" && buildXuguCompileSql({ objectType: node.type, schema: node.schema, name: node.objectName || node.label })) {items.push({ label: t("contextMenu.compileObject"), action: compileXuguObject, icon: Wrench });}- items.push({ label: t("contextMenu.viewSource"), action: () => openObjectSourceDialog(false), icon: Code2 });+ if (node.type === "package" || node.type === "package-body") {+ items.push({ sidebarActionId: "contextMenu.editObject", label: t("contextMenu.editObject"), action: () => openObjectSourceDialog(true), icon: Pencil });+ }+ items.push({ sidebarActionId: "contextMenu.viewSource", label: t("contextMenu.viewSource"), action: () => openObjectSourceDialog(false), icon: Code2 });if (canViewDatabaseObjectDependencies(currentDatabaseType(), node)) {items.push({ label: t("contextMenu.viewDependencies"), action: openDatabaseObjectDependencies, icon: Network });}diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.routineContextMenu.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.routineContextMenu.spec.tsnew file mode 100644index 0000000000..b1ec3b2d7d--- /dev/null+++ b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.routineContextMenu.spec.ts@@ -0,0 +1,129 @@+// @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 { DatabaseType, 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([]),+ executeQuery: vi.fn().mockResolvedValue({ success: true, columns: [], rows: [] }),+ };+});++import SidebarTreeRuntimeHost from "@/components/sidebar/SidebarTreeRuntimeHost.vue";+import { useConnectionStore } from "@/stores/connectionStore";+import { useQueryStore } from "@/stores/queryStore";++const node = (type: TreeNode["type"], label: string, extra?: Partial<TreeNode>): TreeNode => ({+ id: `test-conn:db:${type}:${label}`,+ type,+ label,+ objectName: label,+ connectionId: "test-conn",+ database: "testdb",+ schema: "public",+ ...extra,+});++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(dbType: DatabaseType = "postgres") {+ const pinia = createPinia();+ setActivePinia(pinia);+ const store = useConnectionStore();+ store.connections = [{ id: "test-conn", name: "TestDB", db_type: dbType, driver_profile: dbType, host: "localhost", port: 5432, username: "postgres", password: "password" }];+ vi.spyOn(store, "ensureConnected").mockResolvedValue(undefined as any);+ vi.spyOn(store, "refreshTreeNode").mockResolvedValue(undefined as any);+ const host = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);+ const root = defineComponent({ setup: () => () => h(SidebarTreeRuntimeHost, { ref: host, node: node("connection", "TestDB"), 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 any;+}++describe("Procedure and function sidebar context menu", () => {+ afterEach(() => {+ for (const app of mountedApps.splice(0)) app.unmount();+ document.body.innerHTML = "";+ });++ it("exposes editObject and viewSource for standalone procedures", async () => {+ const host = await mountHost("postgres");+ const procNode = node("procedure", "calculate_total");+ const menu = host.buildContextMenu(procNode);+ const itemLabels = labels(menu);+ expect(itemLabels).toContain(tr("contextMenu.editObject"));+ expect(itemLabels).toContain(tr("contextMenu.viewSource"));++ const editItem = menu.find((item: ContextMenuItem) => item.sidebarActionId === "contextMenu.editObject");+ expect(editItem).toBeDefined();++ const queryStore = useQueryStore();+ const openSpy = vi.spyOn(queryStore, "openObjectSourceTabPending");+ await editItem?.action?.();+ expect(openSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ initialEditing: true,+ request: expect.objectContaining({ name: "calculate_total", objectType: "PROCEDURE" }),+ }),+ );+ });++ it("exposes editObject and viewSource for standalone functions", async () => {+ const host = await mountHost("postgres");+ const funcNode = node("function", "get_status");+ const menu = host.buildContextMenu(funcNode);+ const itemLabels = labels(menu);+ expect(itemLabels).toContain(tr("contextMenu.editObject"));+ expect(itemLabels).toContain(tr("contextMenu.viewSource"));++ const editItem = menu.find((item: ContextMenuItem) => item.sidebarActionId === "contextMenu.editObject");+ expect(editItem).toBeDefined();++ const queryStore = useQueryStore();+ const openSpy = vi.spyOn(queryStore, "openObjectSourceTabPending");+ await editItem?.action?.();+ expect(openSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ initialEditing: true,+ request: expect.objectContaining({ name: "get_status", objectType: "FUNCTION" }),+ }),+ );+ });++ it("omits editObject for package members", async () => {+ const host = await mountHost("oracle");+ const memberNode = node("procedure", "pkg_member", {+ parentType: "package",+ parentName: "my_package",+ });+ const menu = host.buildContextMenu(memberNode);+ const itemLabels = labels(menu);+ expect(itemLabels).not.toContain(tr("contextMenu.editObject"));+ expect(itemLabels).toContain(tr("contextMenu.viewSource"));+ });++ it("exposes editObject and viewSource for package nodes", async () => {+ const host = await mountHost("oracle");+ const pkgNode = node("package", "user_management");+ const menu = host.buildContextMenu(pkgNode);+ const itemLabels = labels(menu);+ expect(itemLabels).toContain(tr("contextMenu.editObject"));+ expect(itemLabels).toContain(tr("contextMenu.viewSource"));+ });+});diff --git a/apps/desktop/src/lib/sidebar/__tests__/sidebarTreeCollapse.spec.ts b/apps/desktop/src/lib/sidebar/__tests__/sidebarTreeCollapse.spec.tsindex 5edeb1b15e..aa76806de5 100644--- a/apps/desktop/src/lib/sidebar/__tests__/sidebarTreeCollapse.spec.ts+++ b/apps/desktop/src/lib/sidebar/__tests__/sidebarTreeCollapse.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";import type { TreeNode } from "@/types/database";-import { collapseExpandedTreeNodes, collapseSubtreeDescendants } from "@/lib/sidebar/sidebarTreeCollapse";+import { collapseSubtreeDescendants } from "@/lib/sidebar/sidebarTreeCollapse";import { toggleGroupCollapsed, emptyLayout, createGroup } from "@/lib/sidebar/sidebarLayout";import { toggleTableVGroupCollapsed, emptyTableVGroupLayout, createTableVGroup } from "@/lib/table/tableVGroup";diff --git a/apps/desktop/src/lib/sidebar/sidebarMenuLayout.ts b/apps/desktop/src/lib/sidebar/sidebarMenuLayout.tsindex 3854e0d56e..6484c6d64a 100644--- a/apps/desktop/src/lib/sidebar/sidebarMenuLayout.ts+++ b/apps/desktop/src/lib/sidebar/sidebarMenuLayout.ts@@ -74,7 +74,20 @@ export function reorderSidebarMenuEntries(savedOrder: readonly string[], visibleconst groupActions: Partial<Record<MenuGroup, readonly string[]>> = {data: ["contextMenu.importData", "contextMenu.exportData", "contextMenu.exportDatabase", "contextMenu.exportAllDatabases", "transfer.dataTransfer", "dataCompare.title", "contextMenu.backupSqliteDatabase", "contextMenu.restoreSqliteDatabase", "databaseBackup.title", "databaseSearch.open"],sql: ["contextMenu.generateSql", "contextMenu.sqlHistory", "contextMenu.addToAi", "modelGeneration.title", "sqlFile.title"],- structure: ["contextMenu.viewDdl", "contextMenu.viewSource", "contextMenu.viewDependencies", "contextMenu.exportStructure", "contextMenu.duplicateStructure", "contextMenu.renameObject", "contextMenu.compileObject", "diagram.open", "docs.title", "diff.title", "dataDictionary.title"],+ structure: [+ "contextMenu.editObject",+ "contextMenu.viewDdl",+ "contextMenu.viewSource",+ "contextMenu.viewDependencies",+ "contextMenu.exportStructure",+ "contextMenu.duplicateStructure",+ "contextMenu.renameObject",+ "contextMenu.compileObject",+ "diagram.open",+ "docs.title",+ "diff.title",+ "dataDictionary.title",+ ],copy: ["contextMenu.copyName", "contextMenu.copyConnectionInfo", "contextMenu.copyStructureAs", "contextMenu.copyFinalProxyPort", "contextMenu.copyTable", "contextMenu.pasteTable"],organize: ["contextMenu.setDefaultDatabase",