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。

feat(database): 增加 Oracle 与 OceanBase Oracle 例程依赖明细 (#12770)

efeirec83fff2cb4b0
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index cac9f4de58..36e64120e5 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -90,7 +90,17 @@ import { parseRecentConnectionIds, rankRecentConnections, RECENT_CONNECTION_IDS_
import { resolveDefaultDatabase } from "@/lib/database/defaultDatabase";
import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace";
import { findTreeNodeById, resolveNewQueryTarget, resolveNewQueryInitialSql, type NewQueryContextSource } from "@/lib/sql/newQueryContext";
-import { isSqlObjectNavigationRoutineType, normalizeOracleNavigationTarget, sqlObjectNavigationSourceKind, sqlObjectNavigationSourceName, sqlObjectNavigationSourceSchema, sqlObjectNavigationTableType, type SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";
+import {
+ isSqlObjectNavigationRoutineType,
+ normalizeOracleNavigationTarget,
+ sqlObjectNavigationContextTarget,
+ sqlObjectNavigationSourceKind,
+ sqlObjectNavigationSourceName,
+ sqlObjectNavigationSourceSchema,
+ type SqlObjectNavigationContext,
+ type SqlObjectNavigationTarget,
+} from "@/lib/sql/sqlNavigation";
+import { isObjectDependencySection, type ObjectDependencyTarget } from "@/lib/database/objectDependencyDetails";
import { buildEditableObjectSource, buildExecutableObjectSourceStatements, executeObjectSourceSave } from "@/lib/table/objectSourceEditor";
import { assertSourceIdentity, beginSourceSave } from "@/lib/table/objectSourceIdentity";
import { loadEditableObjectSourceForEditor } from "@/lib/table/objectSourceLoad";
@@ -522,6 +532,7 @@ const queryEditorDdlTarget = ref<{ connectionId: string; database: string; catal
const queryEditorObjectSourceTarget = ref<{
connectionId: string;
database: string;
+ catalog?: string;
schema?: string;
name: string;
objectType: ObjectSourceKind;
@@ -2655,7 +2666,7 @@ async function handleSaveTab(tabId: string) {
async function openSaveSqlDialog(tabId?: string) {
const tab = tabId ? queryStore.tabs.find((candidate) => candidate.id === tabId) : activeTab.value;
- if (!tab || !canSaveSqlTab(tab)) return;
+ if (!tab || !canSaveSqlTab(tab) || isObjectDependencySection(tab)) return;
saveSqlDialogTabId.value = tab.id;
if (tab.objectSource) {
await saveActiveObjectSource(tab);
@@ -3416,21 +3427,14 @@ async function openSavedSqlFromWelcome(fileId: string) {
toast(t("welcome.fileOpened", { name: file.name }), 2000);
}
-function tableTargetFromActiveTab(table: string | SqlObjectNavigationTarget) {
- const tab = activeTab.value;
+function tableTargetFromActiveTab(table: string | SqlObjectNavigationTarget, context?: SqlObjectNavigationContext) {
+ const tab = context ?? activeTab.value;
if (!tab) return null;
const connectionId = tab.connectionId;
const catalog = tab.tableMeta?.catalog || tab.catalog;
if (typeof table !== "string") {
// Structured targets already separate qualifiers; reparsing would corrupt quoted object names that contain dots.
- return {
- connectionId,
- database: table.database || tab.database,
- catalog,
- schema: table.schema || tab.schema,
- tableName: table.name,
- tableType: table.type ? sqlObjectNavigationTableType(table) : undefined,
- };
+ return sqlObjectNavigationContextTarget(table, tab);
}
let database = tab.database;
@@ -3455,13 +3459,13 @@ function tableTargetFromActiveTab(table: string | SqlObjectNavigationTarget) {
return { connectionId, database, catalog, schema, tableName: rawTableName, tableType: undefined };
}
-async function onClickTable(table: SqlObjectNavigationTarget) {
+async function onClickTable(table: SqlObjectNavigationTarget, context?: SqlObjectNavigationContext) {
// Procedures/functions/packages open source (same as sidebar view-source), not table data/DDL.
if (isSqlObjectNavigationRoutineType(table.type)) {
- await onOpenObjectSource(table, false);
+ await onOpenObjectSource(table, false, context);
return;
}
- const target = tableTargetFromActiveTab(table);
+ const target = tableTargetFromActiveTab(table, context);
if (!target) return;
const objectType = sqlObjectNavigationSourceKind(table);
if (objectType) {
@@ -3505,13 +3509,17 @@ function onEditTableStructure(table: SqlObjectNavigationTarget) {
queryStore.openTableStructure(target.connectionId, target.database, target.schema, target.tableName, undefined, undefined, target.catalog);
}
-function onOpenObjectSource(table: SqlObjectNavigationTarget, initialEditing: boolean) {
- const provisionalTarget = tableTargetFromActiveTab(table);
+function onOpenDependencyObject(context: ObjectDependencyTarget, target: SqlObjectNavigationTarget) {
+ return onClickTable(target, context);
+}
+
+function onOpenObjectSource(table: SqlObjectNavigationTarget, initialEditing: boolean, context?: SqlObjectNavigationContext) {
+ const provisionalTarget = tableTargetFromActiveTab(table, context);
if (!provisionalTarget) return;
const databaseType = effectiveDatabaseTypeForConnection(connectionStore.getConfig(provisionalTarget.connectionId));
// Oracle-family: unquoted → UPPER; quoted mixed-case keeps written case for ALL_SOURCE lookup.
const navigation = databaseType === "oracle" || databaseType === "dameng" || databaseType === "oceanbase-oracle" || databaseType === "yashandb" || databaseType === "oscar" ? normalizeOracleNavigationTarget(table) : table;
- const target = tableTargetFromActiveTab(navigation);
+ const target = tableTargetFromActiveTab(navigation, context);
const objectType = sqlObjectNavigationSourceKind(navigation);
if (!target || !objectType) return;
const sourceName = sqlObjectNavigationSourceName(navigation);
@@ -3537,6 +3545,7 @@ function onOpenObjectSource(table: SqlObjectNavigationTarget, initialEditing: bo
queryEditorObjectSourceTarget.value = {
connectionId: target.connectionId,
database: target.database,
+ catalog: target.catalog,
schema: sourceSchema,
name: sourceName,
objectType,
@@ -5290,6 +5299,7 @@ onUnmounted(() => {
@collapse="setSidebarOpen(false)"
@open-settings="(initialTab) => openSettings(initialTab ?? 'appearance')"
@add-to-ai="addToAi"
+ @open-dependency-object="onOpenDependencyObject"
@mousedown="rememberSidebarSearchSurface"
@focusin="rememberSidebarSearchSurface"
/>
@@ -5491,6 +5501,7 @@ onUnmounted(() => {
@edit-table-structure="(_tabId: string, target: SqlObjectNavigationTarget) => onEditTableStructure(target)"
@view-table-ddl="(_tabId: string, target: SqlObjectNavigationTarget) => onViewTableDdl(target)"
@open-object-source="(_tabId: string, target: SqlObjectNavigationTarget, initialEditing: boolean) => onOpenObjectSource(target, initialEditing)"
+ @open-dependency-object="onOpenDependencyObject"
@open-object-table="
(tabId: string, target: { tableName: string; schema?: string; tableType?: string; catalog?: string; comment?: string | null }) => {
const tab = queryStore.tabs.find((candidate) => candidate.id === tabId) ?? activeTab;
@@ -5903,6 +5914,7 @@ onUnmounted(() => {
v-model:open="showQueryEditorObjectSourceDialog"
:connection-id="queryEditorObjectSourceTarget.connectionId"
:database="queryEditorObjectSourceTarget.database"
+ :catalog="queryEditorObjectSourceTarget.catalog"
:schema="queryEditorObjectSourceTarget.schema"
:name="queryEditorObjectSourceTarget.name"
:signature="queryEditorObjectSourceTarget.signature"
@@ -5913,6 +5925,7 @@ onUnmounted(() => {
:dialect="queryEditorObjectSourceDialect"
:format-dialect="queryEditorObjectSourceFormatDialect"
@saved="onQueryEditorObjectSourceSaved"
+ @open-object="onOpenDependencyObject"
/>
</TooltipProvider>
<div id="dbx-query-editor-tooltip-root" class="fixed left-0 top-0 z-[70] h-0 w-0 overflow-visible" :style="editorFontFamilyStyle" />
diff --git a/apps/desktop/src/components/layout/AppSidebar.vue b/apps/desktop/src/components/layout/AppSidebar.vue
index b91046ec38..bc90e9ea13 100644
--- a/apps/desktop/src/components/layout/AppSidebar.vue
+++ b/apps/desktop/src/components/layout/AppSidebar.vue
@@ -18,6 +18,8 @@ import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore";
import { useToast } from "@/composables/useToast";
import type { QueryTab, TreeNode } from "@/types/database";
+import type { ObjectDependencyTarget } from "@/lib/database/objectDependencyDetails";
+import type { SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";
defineProps<{
sidebarWidth: number;
@@ -31,6 +33,7 @@ const emit = defineEmits<{
collapse: [];
"open-settings": [initialTab: string];
"add-to-ai": [nodes: TreeNode | TreeNode[]];
+ "open-dependency-object": [context: ObjectDependencyTarget, target: SqlObjectNavigationTarget];
}>();
type ImportSource = "dbx" | "navicat" | "dbeaver" | "datagrip";
@@ -331,7 +334,7 @@ defineExpose({ focusSearch, locateTabInSidebar, disconnectAllActiveConnections,
</template>
</div>
<div data-sidebar-connection-tree class="flex-1 min-h-0">
- <ConnectionTree ref="connectionTreeRef" @open-settings="(initialTab) => emit('open-settings', initialTab)" @add-to-ai="(nodes) => emit('add-to-ai', nodes)" />
+ <ConnectionTree ref="connectionTreeRef" @open-settings="(initialTab) => emit('open-settings', initialTab)" @add-to-ai="(nodes) => emit('add-to-ai', nodes)" @open-dependency-object="(context, target) => emit('open-dependency-object', context, target)" />
</div>
<div v-if="activeConnectionEndpoint" data-sidebar-connection-endpoint class="flex shrink-0 items-center gap-1.5 border-t border-border/60 px-2.5 py-1.5 text-[11px] leading-none text-muted-foreground" :title="activeWindowConnection?.name">
<Server class="h-3 w-3 shrink-0" />
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index bf2b4e8908..9020964285 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -80,6 +80,8 @@ import QueryResultToolbarActions from "@/components/layout/QueryResultToolbarAct
import ResultSetNavigator from "@/components/layout/ResultSetNavigator.vue";
import QueryResultViewSwitcher from "@/components/layout/QueryResultViewSwitcher.vue";
import ProductionWatermark from "@/components/common/ProductionWatermark.vue";
+import ObjectDependenciesPanel from "@/components/objects/ObjectDependenciesPanel.vue";
+import { objectDependencyTarget, isObjectDependencySection, type ObjectDependencyTarget, type ObjectDetailsSection } from "@/lib/database/objectDependencyDetails";
import DataGridFreezeFirstColumnControl from "@/components/grid/DataGridFreezeFirstColumnControl.vue";
import DataGridStatusSqlControl from "@/components/grid/DataGridStatusSqlControl.vue";
import DataGridCopyFormatControl from "@/components/grid/DataGridCopyFormatControl.vue";
@@ -409,6 +411,20 @@ const activeResultDatabase = computed(() => activeResultExecutionTarget.value?.d
const activeResultSchema = computed(() => activeResultExecutionTarget.value?.schema ?? props.activeTab.schema);
const graphViewKey = computed(() => JSON.stringify([props.activeTab.id, props.activeTab.resultViewGeneration, props.activeTab.activeResultRunId, props.activeTab.activeResultIndex, activeResultConnectionId.value, activeResultDatabase.value]));
const activeEffectiveDatabaseType = computed(() => effectiveDatabaseTypeForConnection(activeResultConnection.value));
+const activeObjectDependencyTarget = computed(() => {
+ const tab = props.activeTab;
+ const details = tab.objectDetails;
+ if (!details || details.connectionId !== tab.connectionId || details.database !== tab.database || details.schema !== (tab.schema || tab.database) || (details.catalog || "") !== (tab.catalog || "")) return undefined;
+ return objectDependencyTarget(details, effectiveDatabaseTypeForConnection(connectionStore.getConfig(details.connectionId)));
+});
+const activeObjectSection = computed<ObjectDetailsSection>(() => (activeObjectDependencyTarget.value ? props.activeTab.objectDetails?.section || "source" : "source"));
+const sourceSectionActive = computed(() => !isObjectDependencySection(props.activeTab));
+function setObjectSection(section: ObjectDetailsSection) {
+ if (props.activeTab.objectDetails) props.activeTab.objectDetails.section = section;
+}
+function viewObjectDependencySql(context: ObjectDependencyTarget, sql: string) {
+ queryStore.createTab(context.connectionId, context.database, t("objectDependencies.viewSql"), "query", context.schema, sql, context.catalog, { forceNew: true });
+}
// 表数据工具箱的「导入数据」与侧边栏、对象浏览器共用同一条能力判断:未适配导入的引擎(如 HANA)不出现入口。
const canOpenTableImport = computed(() => supportsTableImport(activeEffectiveDatabaseType.value));
const activeVectorConnection = computed(() => connectionStore.getConfig(props.activeTab.connectionId) ?? props.activeConnection);
@@ -1797,22 +1813,27 @@ function handleModRTarget(target: Element): boolean {
}
function requestQueryEditorExecute() {
+ if (!sourceSectionActive.value) return false;
return queryEditorRef.value?.requestExecute();
}
function captureQueryEditorExecutionSnapshot() {
+ if (!sourceSectionActive.value) return;
return queryEditorRef.value?.captureExecutionSnapshot();
}
function requestQueryEditorExecuteInNewResultTab() {
+ if (!sourceSectionActive.value) return false;
return queryEditorRef.value?.requestExecuteInNewResultTab();
}
function requestQueryEditorPreviewChanges(stackSql?: string) {
+ if (!sourceSectionActive.value) return Promise.resolve(false);
return queryEditorRef.value?.requestPreviewChanges?.(stackSql);
}
function shouldBlockQueryEditorExecutionShortcut(event: KeyboardEvent) {
+ if (!sourceSectionActive.value) return true;
return queryEditorRef.value?.shouldBlockExecutionShortcut?.(event) ?? false;
}
@@ -2009,95 +2030,97 @@ defineExpose({
</Button>
</div>
<ProductionWatermark v-if="activeProductionContext.active" />
- <!-- issue #9035:源码 tab 先出现再加载。pending 期间不挂载编辑器
+ <ObjectDependenciesPanel :target="activeObjectDependencyTarget" :section="activeObjectSection" @update:section="setObjectSection" @view-sql="viewObjectDependencySql" @open-object="(context, target) => emit('openDependencyObject', context, target)">
+ <!-- issue #9035:源码 tab 先出现再加载。pending 期间不挂载编辑器
(还没有内容可编辑,也省下一次 Monaco 初始化),失败则就地重试。
issue #9387:DDL 新标签同样先出 tab 再加载,失败就地显示错误。 -->
- <QueryLoadingState v-if="activeTab.sourceLoad && !activeTab.sourceLoad.error" class="relative z-0 flex-1" :elapsed-seconds="sourceLoadElapsedSeconds" />
- <div v-else-if="activeTab.sourceLoad?.error" class="relative z-0 flex flex-1 min-h-0 flex-col items-center justify-center gap-3 px-6 text-sm" data-object-source-load-error>
- <p class="max-w-[80%] text-center break-words text-destructive">{{ activeTab.sourceLoad.error }}</p>
- <Button variant="outline" size="sm" class="gap-1.5" @click="queryStore.retryObjectSourceTab(activeTab.id)">
- <RotateCcw class="h-4 w-4" />
- {{ t("common.retry") }}
- </Button>
- </div>
- <QueryLoadingState v-else-if="activeTab.ddlLoad && !activeTab.ddlLoad.error" class="relative z-0 flex-1" :elapsed-seconds="ddlLoadElapsedSeconds" />
- <div v-else-if="activeTab.ddlLoad?.error" class="relative z-0 flex flex-1 min-h-0 flex-col items-center justify-center gap-3 px-6 text-sm" data-ddl-load-error>
- <p class="max-w-[80%] text-center break-words text-destructive">{{ t("contextMenu.ddlRefreshFailed", { message: activeTab.ddlLoad.error }) }}</p>
- <Button variant="outline" size="sm" class="gap-1.5" @click="queryStore.retryDdlViewerTab(activeTab.id)">
- <RotateCcw class="h-4 w-4" />
- {{ t("common.retry") }}
- </Button>
- </div>
- <QueryEditor
- v-else
- ref="queryEditorRef"
- class="relative z-0 flex-1"
- :auto-focus="autoFocus !== false"
- :model-value="activeTab.sql"
- :tab-id="activeTab.id"
- :connection-id="activeTab.connectionId"
- :catalog="activeTab.catalog"
- :database="activeTab.database"
- :schema="activeTab.schema"
- :client-session-id="activeTab.id"
- :completion-context-version="activeTab.completionContextVersion"
- :database-type="activeEffectiveDatabaseType"
- :dialect="editorDialect"
- :syntax-dialect="editorSyntaxDialect"
- :format-dialect="activeSqlFormatDialect"
- :format-request-id="formatSqlRequest?.tabId === activeTab.id ? formatSqlRequest.id : undefined"
- :compress-request-id="compressSqlRequest?.tabId === activeTab.id ? compressSqlRequest.id : undefined"
- :keyword-case-request-id="keywordCaseRequest?.tabId === activeTab.id ? keywordCaseRequest.id : undefined"
- :keyword-case-request-mode="keywordCaseRequest?.tabId === activeTab.id ? keywordCaseRequest.mode : undefined"
- :execution-error="activeQueryError"
- :execution-error-sql="activeTab.lastExecutedSql"
- :execution-error-result="activeQueryError ? activeTab.result : undefined"
- :result-columns="activeTab.result?.columns"
- :result-source-statement="activeTab.result?.sourceStatement"
- :result-source-from="activeTab.result?.sourceFrom"
- :result-source-to="activeTab.result?.sourceTo"
- :statement-execution-markers="activeStatementExecutionMarkers"
- :initial-viewport="activeTab.editorViewport"
- :initial-selection="activeTab.editorSelection"
- :reveal-request="activeTab.editorRevealRequest"
- :force-word-wrap="activeTab.forceWordWrap"
- :read-only="!!activeTab.ddlViewer"
- :hide-execution-controls="!!activeTab.ddlViewer"
- enable-explain-shortcut
- :can-explain="!activeTab.isExecuting && !activeTab.isExplaining && !!executableSql.trim()"
- :is-executing="activeTab.isExecuting"
- @update:model-value="emit('editorUpdate', activeTab.id, $event)"
- @selection-change="emit('editorSelectionChange', activeTab.id, $event)"
- @send-selection-to-ai="emit('sendSelectionToAi', activeTab.id, $event)"
- @cursor-change="emit('editorCursorChange', activeTab.id, $event)"
- @preview-changes-available="emit('previewChangesAvailable', activeTab.id, $event)"
- @viewport-change="(viewport, tabId) => emit('editorViewportChange', tabId ?? activeTab.id, viewport)"
- @selection-state-change="emit('editorSelectionStateChange', activeTab.id, $event)"
- @editor-state-flushed="emit('editorStateFlushed', activeTab.id)"
- @editor-reveal-consumed="clearEditorRevealRequest(activeTab)"
- @format-error="emit('formatError', activeTab.id)"
- @execute="emit('execute', activeTab.id, $event)"
- @execute-in-new-result-tab="emit('executeInNewResultTab', activeTab.id, $event)"
- @explain="emit('explain', activeTab.id)"
- @export-query="handleExportQuery"
- @save="emit('saveSql', props.activeTab.id)"
- @click-table="onHandleClickTable"
- @view-table-data="onHandleViewTableData"
- @edit-table-structure="onHandleEditTableStructure"
- @view-table-ddl="onHandleViewTableDdl"
- @open-object-source="onHandleOpenObjectSource"
- @click-column="onHandleClickColumn"
- @close-column-panel="onHandleCloseColumnPanel"
- />
- <ColumnInfoPanel
- v-if="showColumnInfo"
- :columns="columnInfoColumns"
- :loading="columnInfoLoading"
- :error="columnInfoError"
- :database-type="activeEffectiveDatabaseType"
- :is-gaussdb-m="activeEffectiveDatabaseType === 'gaussdb' && activeResultConnection?.driver_profile?.toLowerCase() === 'gaussdb-m'"
- @close="closeColumnInfo"
- />
+ <QueryLoadingState v-if="activeTab.sourceLoad && !activeTab.sourceLoad.error" class="relative z-0 flex-1" :elapsed-seconds="sourceLoadElapsedSeconds" />
+ <div v-else-if="activeTab.sourceLoad?.error" class="relative z-0 flex flex-1 min-h-0 flex-col items-center justify-center gap-3 px-6 text-sm" data-object-source-load-error>
+ <p class="max-w-[80%] text-center break-words text-destructive">{{ activeTab.sourceLoad.error }}</p>
+ <Button variant="outline" size="sm" class="gap-1.5" @click="queryStore.retryObjectSourceTab(activeTab.id)">
+ <RotateCcw class="h-4 w-4" />
+ {{ t("common.retry") }}
+ </Button>
+ </div>
+ <QueryLoadingState v-else-if="activeTab.ddlLoad && !activeTab.ddlLoad.error" class="relative z-0 flex-1" :elapsed-seconds="ddlLoadElapsedSeconds" />
+ <div v-else-if="activeTab.ddlLoad?.error" class="relative z-0 flex flex-1 min-h-0 flex-col items-center justify-center gap-3 px-6 text-sm" data-ddl-load-error>
+ <p class="max-w-[80%] text-center break-words text-destructive">{{ t("contextMenu.ddlRefreshFailed", { message: activeTab.ddlLoad.error }) }}</p>
+ <Button variant="outline" size="sm" class="gap-1.5" @click="queryStore.retryDdlViewerTab(activeTab.id)">
+ <RotateCcw class="h-4 w-4" />
+ {{ t("common.retry") }}
+ </Button>
+ </div>
+ <QueryEditor
+ v-else
+ ref="queryEditorRef"
+ class="relative z-0 flex-1"
+ :auto-focus="sourceSectionActive && autoFocus !== false"
+ :model-value="activeTab.sql"
+ :tab-id="activeTab.id"
+ :connection-id="activeTab.connectionId"
+ :catalog="activeTab.catalog"
+ :database="activeTab.database"
+ :schema="activeTab.schema"
+ :client-session-id="activeTab.id"
+ :completion-context-version="activeTab.completionContextVersion"
+ :database-type="activeEffectiveDatabaseType"
+ :dialect="editorDialect"
+ :syntax-dialect="editorSyntaxDialect"
+ :format-dialect="activeSqlFormatDialect"
+ :format-request-id="formatSqlRequest?.tabId === activeTab.id ? formatSqlRequest.id : undefined"
+ :compress-request-id="compressSqlRequest?.tabId === activeTab.id ? compressSqlRequest.id : undefined"
+ :keyword-case-request-id="keywordCaseRequest?.tabId === activeTab.id ? keywordCaseRequest.id : undefined"
+ :keyword-case-request-mode="keywordCaseRequest?.tabId === activeTab.id ? keywordCaseRequest.mode : undefined"
+ :execution-error="activeQueryError"
+ :execution-error-sql="activeTab.lastExecutedSql"
+ :execution-error-result="activeQueryError ? activeTab.result : undefined"
+ :result-columns="activeTab.result?.columns"
+ :result-source-statement="activeTab.result?.sourceStatement"
+ :result-source-from="activeTab.result?.sourceFrom"
+ :result-source-to="activeTab.result?.sourceTo"
+ :statement-execution-markers="activeStatementExecutionMarkers"
+ :initial-viewport="activeTab.editorViewport"
+ :initial-selection="activeTab.editorSelection"
+ :reveal-request="activeTab.editorRevealRequest"
+ :force-word-wrap="activeTab.forceWordWrap"
+ :read-only="!!activeTab.ddlViewer"
+ :hide-execution-controls="!!activeTab.ddlViewer"
+ enable-explain-shortcut
+ :can-explain="!activeTab.isExecuting && !activeTab.isExplaining && !!executableSql.trim()"
+ :is-executing="activeTab.isExecuting"
+ @update:model-value="emit('editorUpdate', activeTab.id, $event)"
+ @selection-change="emit('editorSelectionChange', activeTab.id, $event)"
+ @send-selection-to-ai="emit('sendSelectionToAi', activeTab.id, $event)"
+ @cursor-change="emit('editorCursorChange', activeTab.id, $event)"
+ @preview-changes-available="emit('previewChangesAvailable', activeTab.id, $event)"
+ @viewport-change="(viewport, tabId) => emit('editorViewportChange', tabId ?? activeTab.id, viewport)"
+ @selection-state-change="emit('editorSelectionStateChange', activeTab.id, $event)"
+ @editor-state-flushed="emit('editorStateFlushed', activeTab.id)"
+ @editor-reveal-consumed="clearEditorRevealRequest(activeTab)"
+ @format-error="emit('formatError', activeTab.id)"
+ @execute="sourceSectionActive && emit('execute', activeTab.id, $event)"
+ @execute-in-new-result-tab="sourceSectionActive && emit('executeInNewResultTab', activeTab.id, $event)"
+ @explain="sourceSectionActive && emit('explain', activeTab.id)"
+ @export-query="handleExportQuery"
+ @save="sourceSectionActive && emit('saveSql', props.activeTab.id)"
+ @click-table="onHandleClickTable"
+ @view-table-data="onHandleViewTableData"
+ @edit-table-structure="onHandleEditTableStructure"
+ @view-table-ddl="onHandleViewTableDdl"
+ @open-object-source="onHandleOpenObjectSource"
+ @click-column="onHandleClickColumn"
+ @close-column-panel="onHandleCloseColumnPanel"
+ />
+ <ColumnInfoPanel
+ v-if="showColumnInfo"
+ :columns="columnInfoColumns"
+ :loading="columnInfoLoading"
+ :error="columnInfoError"
+ :database-type="activeEffectiveDatabaseType"
+ :is-gaussdb-m="activeEffectiveDatabaseType === 'gaussdb' && activeResultConnection?.driver_profile?.toLowerCase() === 'gaussdb-m'"
+ @close="closeColumnInfo"
+ />
+ </ObjectDependenciesPanel>
<Button v-if="!editorOnly && hasQueryOutput && !resultsPaneOpen" variant="secondary" size="sm" class="absolute bottom-3 right-3 z-20 h-7 gap-1.5 rounded-full border bg-background/95 px-3 text-xs shadow-lg hover:bg-accent" @click="resultsPaneOpen = true">
<ChevronUp class="h-3.5 w-3.5" />
{{ t("editor.showResultsPane") }}
diff --git a/apps/desktop/src/components/layout/EditorToolbar.vue b/apps/desktop/src/components/layout/EditorToolbar.vue
index 0244e89f99..f782a980c7 100644
--- a/apps/desktop/src/components/layout/EditorToolbar.vue
+++ b/apps/desktop/src/components/layout/EditorToolbar.vue
@@ -59,6 +59,7 @@ import { canSaveSqlTab } from "@/lib/tabs/sqlTabSaveTarget";
import { looksLikeDmlStatement } from "@/lib/sql/dmlChangePreview";
import { canFormatSqlForDatabaseType } from "@/lib/sql/sqlFormatter";
import type { QueryTab, ConnectionConfig } from "@/types/database";
+import { isObjectDependencySection } from "@/lib/database/objectDependencyDetails";
const props = defineProps<{
activeTab: QueryTab;
@@ -567,7 +568,7 @@ defineExpose({
</script>
<template>
- <div ref="toolbarRootRef" class="app-editor-toolbar h-9 min-w-0 shrink-0 border-b bg-background/80 px-3 flex items-center gap-1 text-xs text-muted-foreground relative z-10 overflow-hidden" :style="toolbarStyle">
+ <div v-show="!isObjectDependencySection(activeTab)" ref="toolbarRootRef" class="app-editor-toolbar h-9 min-w-0 shrink-0 border-b bg-background/80 px-3 flex items-center gap-1 text-xs text-muted-foreground relative z-10 overflow-hidden" :style="toolbarStyle">
<div ref="toolbarActionsRef" class="min-w-0 flex flex-1 items-center gap-0.5 overflow-hidden">
<Tooltip>
<TooltipTrigger as-child>
diff --git a/apps/desktop/src/components/layout/SqlEditorWorkspace.vue b/apps/desktop/src/components/layout/SqlEditorWorkspace.vue
index 0ea93b11f4..1b0d19da7e 100644
--- a/apps/desktop/src/components/layout/SqlEditorWorkspace.vue
+++ b/apps/desktop/src/components/layout/SqlEditorWorkspace.vue
@@ -17,6 +17,7 @@ import { createContentSurfaceEventForwarders } from "@/lib/tabs/contentSurfaceEv
import type { ContentAreaSurfaceEmits, ContentAreaSurfaceProps, StatementRange } from "./querySurfaces";
import type { QueryTab, TableInfoTab } from "@/types/database";
import type { AiConversationBinding } from "@/lib/ai/aiConversationBinding";
+import { isObjectDependencySection } from "@/lib/database/objectDependencyDetails";
defineOptions({ inheritAttrs: false });
@@ -161,7 +162,7 @@ const showResultPane = computed({
if (tab?.mode === "query") queryStore.updateTabUiState(tab.id, { resultPaneOpen: open });
},
});
-const isResultPaneVisible = computed(() => hasSharedOutput.value && showResultPane.value);
+const isResultPaneVisible = computed(() => hasSharedOutput.value && showResultPane.value && !isObjectDependencySection(activeQueryTab.value!));
// Keep the pane mounted, but apply its target size immediately so available
// results never wait for an expansion animation before becoming visible.
const resultPaneTargetSize = computed(() => (isResultPaneVisible.value ? resultPaneSize.value : 0));
diff --git a/apps/desktop/src/components/layout/querySurfaces.ts b/apps/desktop/src/components/layout/querySurfaces.ts
index be939420d6..7567d8c207 100644
--- a/apps/desktop/src/components/layout/querySurfaces.ts
+++ b/apps/desktop/src/components/layout/querySurfaces.ts
@@ -5,6 +5,7 @@ import type { DataGridSortMode } from "@/lib/dataGrid/dataGridSort";
import type { SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";
import type { SqlExecutionOverride, SqlExecutionSnapshot } from "@/lib/sql/sqlExecutionTarget";
import type { AiConversationBinding } from "@/lib/ai/aiConversationBinding";
+import type { ObjectDependencyTarget } from "@/lib/database/objectDependencyDetails";
export interface StatementRange {
from: number;
@@ -107,6 +108,7 @@ export interface ContentAreaSurfaceEmits {
viewTableDdl: [tabId: string, target: SqlObjectNavigationTarget];
editTableStructure: [tabId: string, target: SqlObjectNavigationTarget];
openObjectSource: [tabId: string, target: SqlObjectNavigationTarget, initialEditing: boolean];
+ openDependencyObject: [context: ObjectDependencyTarget, target: SqlObjectNavigationTarget];
openObjectTable: [tabId: string, target: { tableName: string; schema?: string; tableType?: string; catalog?: string; comment?: string | null }];
openDatabaseSearchTarget: [tabId: string, target: NavigationTarget];
objectSchemaChange: [tabId: string, schema: string | undefined];
diff --git a/apps/desktop/src/components/objects/ObjectDependenciesPanel.vue b/apps/desktop/src/components/objects/ObjectDependenciesPanel.vue
new file mode 100644
index 0000000000..3cf8f8231e
--- /dev/null
+++ b/apps/desktop/src/components/objects/ObjectDependenciesPanel.vue
@@ -0,0 +1,150 @@
+<script setup lang="ts">
+import { computed, nextTick, ref, toRef, useId, watch } from "vue";
+import { useI18n } from "vue-i18n";
+import { Copy, RefreshCw, Code } from "@lucide/vue";
+import { Button } from "@/components/ui/button";
+import { useObjectDependencies } from "@/composables/useObjectDependencies";
+import { useToast } from "@/composables/useToast";
+import { copyToClipboard } from "@/lib/common/clipboard";
+import { objectDependencyNavigation, objectDependencySql, type ObjectDependencyTarget, type ObjectDependencyRow, type ObjectDetailsSection } from "@/lib/database/objectDependencyDetails";
+import type { SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";
+
+const props = defineProps<{ target?: ObjectDependencyTarget; section: ObjectDetailsSection; open?: boolean }>();
+const emit = defineEmits<{
+ "update:section": [section: ObjectDetailsSection];
+ "open-object": [context: ObjectDependencyTarget, target: SqlObjectNavigationTarget];
+ "view-sql": [context: ObjectDependencyTarget, sql: string];
+}>();
+const { t } = useI18n();
+const { toast } = useToast();
+const id = useId();
+const target = computed(() => (props.open === false ? undefined : props.target));
+const enabled = computed(() => !!target.value && props.section !== "source");
+const { rows, loading, error, loaded, truncated, refresh } = useObjectDependencies(target, enabled);
+const sourceVisited = ref(props.section === "source");
+watch(toRef(props, "section"), (section) => {
+ if (section === "source") sourceVisited.value = true;
+});
+const sections = ["source", "dependencies", "dependents"] as const;
+const directions = ["dependencies", "dependents"] as const;
+const hasLinks = computed(() => rows.value.some((row) => !!row.link));
+const label = (section: ObjectDetailsSection) => t(section === "source" ? "objects.source" : `objectDependencies.${section}`);
+const rowsFor = (section: ObjectDetailsSection) => rows.value.filter((row) => row.direction === (section === "dependencies" ? "DEPENDS_ON" : "REFERENCED_BY"));
+
+async function switchSection(event: KeyboardEvent, current: number) {
+ let index: number;
+ if (event.key === "ArrowRight") index = (current + 1) % sections.length;
+ else if (event.key === "ArrowLeft") index = (current + sections.length - 1) % sections.length;
+ else if (event.key === "Home") index = 0;
+ else if (event.key === "End") index = sections.length - 1;
+ else return;
+ event.preventDefault();
+ const parent = (event.currentTarget as HTMLElement).parentElement;
+ emit("update:section", sections[index]!);
+ await nextTick();
+ parent?.querySelector<HTMLButtonElement>(`[data-object-section="${sections[index]}"]`)?.focus();
+}
+
+function openObject(row: ObjectDependencyRow) {
+ const navigation = objectDependencyNavigation(row);
+ if (target.value && navigation) emit("open-object", { ...target.value }, navigation);
+}
+
+async function copyName(row: ObjectDependencyRow) {
+ try {
+ await copyToClipboard(`${row.schema}.${row.name}${row.link ? `@${row.link}` : ""}`);
+ toast(t("grid.copied"));
+ } catch (e: unknown) {
+ toast(t("grid.copyFailed", { message: e instanceof Error ? e.message : String(e) }), 5000);
+ }
+}
+</script>
+
+<template>
+ <div v-if="target" class="flex min-h-0 flex-1 flex-col overflow-hidden" data-object-details>
+ <div role="tablist" :aria-label="t('contextMenu.viewDependencies')" class="flex shrink-0 gap-1 border-b px-3 pt-1">
+ <button
+ v-for="(section, index) in sections"
+ :id="`${id}-${section}-tab`"
+ :key="section"
+ type="button"
+ role="tab"
+ :aria-selected="props.section === section"
+ :aria-controls="`${id}-${section}-panel`"
+ :tabindex="props.section === section ? 0 : -1"
+ :data-object-section="section"
+ class="border-b-2 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ :class="props.section === section ? 'border-primary font-medium text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'"
+ @click="emit('update:section', section)"
+ @keydown="switchSection($event, index)"
+ >
+ {{ label(section) }}
+ </button>
+ </div>
+ <div v-if="sourceVisited" v-show="props.section === 'source'" :id="`${id}-source-panel`" role="tabpanel" :aria-labelledby="`${id}-source-tab`" class="relative flex min-h-0 flex-1 flex-col overflow-hidden">
+ <slot />
+ </div>
+ <section v-for="section in directions" v-show="props.section === section" :id="`${id}-${section}-panel`" :key="section" role="tabpanel" :aria-labelledby="`${id}-${section}-tab`" :aria-busy="loading" class="flex min-h-0 flex-1 flex-col overflow-hidden">
+ <div class="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b px-4 py-3">
+ <div class="min-w-0">
+ <h3 class="text-sm font-medium">
+ {{ label(section) }} <span v-if="loaded" class="ml-1 text-muted-foreground">({{ rowsFor(section).length }})</span>
+ </h3>
+ <p class="mt-1 break-all font-mono text-sm text-muted-foreground">{{ target.schema }}.{{ target.name }}</p>
+ </div>
+ <div class="flex items-center gap-2">
+ <Button variant="outline" size="sm" :disabled="loading" @click="refresh"><RefreshCw class="h-4 w-4" :class="loading ? 'animate-spin' : ''" />{{ t("common.refresh") }}</Button>
+ <Button variant="ghost" size="sm" @click="emit('view-sql', { ...target }, objectDependencySql(target))"><Code class="h-4 w-4" />{{ t("objectDependencies.viewSql") }}</Button>
+ </div>
+ </div>
+ <div class="shrink-0 space-y-1 px-4 py-2 text-sm text-muted-foreground">
+ <p>{{ t("objectDependencies.visibility") }}</p>
+ <p v-if="target.objectType === 'PACKAGE'">{{ t("objectDependencies.packageScope") }}</p>
+ <p v-if="truncated" class="text-amber-700 dark:text-amber-400">{{ t("objectDependencies.partial") }}</p>
+ </div>
+ <div v-if="error" role="alert" class="mx-4 mb-3 flex shrink-0 flex-wrap items-center gap-2 rounded border border-destructive/30 px-3 py-2 text-sm">
+ <div class="min-w-0 flex-1 whitespace-pre-wrap break-words text-destructive">
+ {{ error }}
+ <p v-if="loaded" class="mt-1 text-muted-foreground">{{ t("objectDependencies.notUpdated") }}</p>
+ </div>
+ <Button variant="outline" size="sm" :disabled="loading" @click="refresh">{{ t("common.retry") }}</Button>
+ </div>
+ <div v-if="loading && !loaded" role="status" class="flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground"><RefreshCw class="h-4 w-4 animate-spin" />{{ t("common.loading") }}</div>
+ <div v-else-if="loaded && !rowsFor(section).length" class="flex flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">{{ t("objectDependencies.empty") }}</div>
+ <div v-else-if="loaded" class="min-h-0 flex-1 overflow-auto border-t">
+ <table class="w-full text-left text-sm">
+ <thead class="sticky top-0 z-10 bg-muted">
+ <tr class="border-b">
+ <th class="px-4 py-2 font-medium">{{ t("objects.name") }}</th>
+ <th class="px-4 py-2 font-medium">{{ t("objects.type") }}</th>
+ <th class="px-4 py-2 font-medium">{{ t("objects.schema") }}</th>
+ <th class="px-4 py-2 font-medium">{{ t("objectDependencies.dependencyType") }}</th>
+ <th v-if="target.objectType === 'PACKAGE'" class="px-4 py-2 font-medium">{{ t("objectDependencies.sourceType") }}</th>
+ <th v-if="hasLinks" class="px-4 py-2 font-medium">{{ t("objectDependencies.link") }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="(row, index) in rowsFor(section)" :key="index" class="border-b align-top hover:bg-muted/40">
+ <td class="px-4 py-2">
+ <button v-if="objectDependencyNavigation(row)" type="button" class="break-all text-left font-mono text-primary underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" @click="openObject(row)">{{ row.name }}</button>
+ <template v-else
+ ><div class="flex items-start gap-2">
+ <span class="break-all font-mono">{{ row.name }}</span
+ ><button type="button" class="rounded p-1 text-muted-foreground hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring" :aria-label="t('contextMenu.copyName')" @click="copyName(row)"><Copy class="h-3.5 w-3.5" /></button>
+ </div>
+ <p class="mt-1 text-muted-foreground">{{ t(row.link ? "objectDependencies.remoteObject" : "objectDependencies.unsupportedObject") }}</p></template
+ >
+ </td>
+ <td class="whitespace-nowrap px-4 py-2">{{ row.type }}</td>
+ <td class="px-4 py-2 font-mono">{{ row.schema }}</td>
+ <td class="px-4 py-2">{{ row.dependencyType }}</td>
+ <td v-if="target.objectType === 'PACKAGE'" class="whitespace-nowrap px-4 py-2">{{ row.sourceType }}</td>
+ <td v-if="hasLinks" class="px-4 py-2 font-mono">{{ row.link }}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </section>
+ </div>
+ <slot v-else />
+</template>
diff --git a/apps/desktop/src/components/objects/ObjectSourceDialog.vue b/apps/desktop/src/components/objects/ObjectSourceDialog.vue
index 12c1bb90f7..c03581c908 100644
--- a/apps/desktop/src/components/objects/ObjectSourceDialog.vue
+++ b/apps/desktop/src/components/objects/ObjectSourceDialog.vue
@@ -15,6 +15,10 @@ import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutio
import * as api from "@/lib/backend/api";
import QueryEditor from "@/components/editor/QueryEditor.vue";
import RoutineMetadataPanel from "@/components/objects/RoutineMetadataPanel.vue";
+import ObjectDependenciesPanel from "@/components/objects/ObjectDependenciesPanel.vue";
+import { objectDependencyTarget, type ObjectDependencyTarget, type ObjectDetailsSection } from "@/lib/database/objectDependencyDetails";
+import { useQueryStore } from "@/stores/queryStore";
+import type { SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import type { DatabaseType, ObjectSourceKind } from "@/types/database";
@@ -25,6 +29,7 @@ const props = withDefaults(
connectionId: string;
database: string;
schema?: string;
+ catalog?: string;
name: string;
relationName?: string;
signature?: string;
@@ -33,6 +38,7 @@ const props = withDefaults(
dialect: "mysql" | "postgres" | "sqlserver";
formatDialect?: SqlFormatDialect;
initialEditing?: boolean;
+ initialSection?: ObjectDetailsSection;
}>(),
{
initialEditing: false,
@@ -42,12 +48,25 @@ const props = withDefaults(
const emit = defineEmits<{
"update:open": [value: boolean];
saved: [];
+ "open-object": [context: ObjectDependencyTarget, target: SqlObjectNavigationTarget];
}>();
const { t } = useI18n();
const { toast } = useToast();
const connectionStore = useConnectionStore();
const settingsStore = useSettingsStore();
+const queryStore = useQueryStore();
+const section = ref<ObjectDetailsSection>(props.initialSection || "source");
+const dependencyTarget = computed(() => objectDependencyTarget({ connectionId: props.connectionId, database: props.database, schema: props.schema || props.database, catalog: props.catalog, name: props.name, objectType: resolvedObjectType.value, section: section.value }, props.databaseType));
+function viewDependencySql(context: ObjectDependencyTarget, sql: string) {
+ queryStore.createTab(context.connectionId, context.database, t("objectDependencies.viewSql"), "query", context.schema, sql, context.catalog, { forceNew: true });
+}
+function openDependencyObject(context: ObjectDependencyTarget, target: SqlObjectNavigationTarget) {
+ const dirty = editing.value && draft.value !== resolveObjectSourceEditDraft(props.databaseType, resolvedObjectType.value, content.value, editableText.value);
+ if (dirty && !window.confirm(t("objectDependencies.navigateDiscardConfirm"))) return;
+ emit("update:open", false);
+ emit("open-object", context, target);
+}
const content = ref("");
const editableText = ref("");
@@ -72,10 +91,12 @@ const title = computed(() => `${editing.value ? t("contextMenu.editView") : t("c
const hasRoutineMetadata = computed(() => !!routineMetadata.value && (routineMetadata.value.parameters.length > 0 || !!routineMetadata.value.returnType));
watch(
- () => [props.open, props.connectionId, props.database, props.schema, props.name, props.relationName, props.signature, props.objectType, props.databaseType, props.initialEditing] as const,
+ () => [props.open, props.connectionId, props.database, props.schema, props.catalog, props.name, props.relationName, props.signature, props.objectType, props.databaseType, props.initialEditing, props.initialSection] as const,
() => {
- if (props.open) void loadSource();
- else ++loadSerial;
+ if (props.open) {
+ section.value = props.initialSection || "source";
+ void loadSource();
+ } else ++loadSerial;
},
{ immediate: true, flush: "sync" },
);
@@ -83,6 +104,7 @@ watch(
async function loadSource(nextEditing = props.initialEditing && canEdit.value) {
const serial = ++loadSerial;
const target = { ...props };
+ resolvedObjectType.value = target.objectType;
const identity = captureSourceIdentity({ ...target, schema: target.schema || target.database });
sourceIdentity = undefined;
saving.value = false;
@@ -244,73 +266,75 @@ function closeDialog() {
<DialogTitle>{{ title }}</DialogTitle>
</DialogHeader>
- <div v-if="loading" class="flex min-h-0 items-center justify-center gap-2 text-sm text-muted-foreground">
- <Loader2 class="h-4 w-4 animate-spin" />
- <span>{{ t("common.loading") }}</span>
- </div>
- <div v-else-if="error" class="flex min-h-0 flex-col items-center justify-center gap-3 text-sm">
- <p class="text-destructive">{{ error }}</p>
- <Button variant="outline" size="sm" @click="loadSource()">
- <RefreshCw class="h-4 w-4" />
- {{ t("common.retry") }}
- </Button>
- </div>
- <div v-else-if="editing" class="object-source-dialog-editor flex min-h-0 flex-col overflow-hidden rounded border" data-object-source-editor>
- <QueryEditor
- v-model="draft"
- class="min-h-0 flex-1"
- :connection-id="props.connectionId"
- :database="props.database"
- :schema="props.schema || props.database"
- :database-type="props.databaseType"
- :dialect="props.dialect"
- :format-dialect="props.formatDialect"
- force-word-wrap
- hide-execution-controls
- @save="saveSource"
- />
- <div v-if="saveError" class="shrink-0 whitespace-pre-wrap break-words border-t px-3 py-2 text-xs text-destructive">
- {{ saveError }}
+ <ObjectDependenciesPanel :target="dependencyTarget" v-model:section="section" :open="props.open" @view-sql="viewDependencySql" @open-object="openDependencyObject">
+ <div v-if="loading" class="flex min-h-0 flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">
+ <Loader2 class="h-4 w-4 animate-spin" />
+ <span>{{ t("common.loading") }}</span>
+ </div>
+ <div v-else-if="error" class="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-sm">
+ <p class="text-destructive">{{ error }}</p>
+ <Button variant="outline" size="sm" @click="loadSource()">
+ <RefreshCw class="h-4 w-4" />
+ {{ t("common.retry") }}
+ </Button>
+ </div>
+ <div v-else-if="editing" class="object-source-dialog-editor flex min-h-0 flex-1 flex-col overflow-hidden rounded border" data-object-source-editor>
+ <QueryEditor
+ v-model="draft"
+ class="min-h-0 flex-1"
+ :connection-id="props.connectionId"
+ :database="props.database"
+ :schema="props.schema || props.database"
+ :database-type="props.databaseType"
+ :dialect="props.dialect"
+ :format-dialect="props.formatDialect"
+ force-word-wrap
+ hide-execution-controls
+ @save="section === 'source' && saveSource()"
+ />
+ <div v-if="saveError" class="shrink-0 whitespace-pre-wrap break-words border-t px-3 py-2 text-xs text-destructive">
+ {{ saveError }}
+ </div>
+ </div>
+ <div v-else class="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden">
+ <RoutineMetadataPanel v-if="hasRoutineMetadata && routineMetadata" :parameters="routineMetadata.parameters" :return-type="routineMetadata.returnType" />
+ <QueryEditor
+ v-if="content || !hasRoutineMetadata"
+ :key="`${props.connectionId}:${props.database}:${props.schema || ''}:${props.name}:${props.objectType}`"
+ :model-value="content"
+ class="object-source-dialog-editor min-h-0 flex-1 overflow-hidden rounded border"
+ :connection-id="props.connectionId"
+ :database="props.database"
+ :schema="props.schema || props.database"
+ :database-type="props.databaseType"
+ :dialect="props.dialect"
+ :format-dialect="props.formatDialect"
+ force-word-wrap
+ read-only
+ hide-execution-controls
+ data-object-source-preview
+ />
</div>
- </div>
- <div v-else class="flex min-h-0 flex-col gap-3 overflow-hidden">
- <RoutineMetadataPanel v-if="hasRoutineMetadata && routineMetadata" :parameters="routineMetadata.parameters" :return-type="routineMetadata.returnType" />
- <QueryEditor
- v-if="content || !hasRoutineMetadata"
- :key="`${props.connectionId}:${props.database}:${props.schema || ''}:${props.name}:${props.objectType}`"
- :model-value="content"
- class="object-source-dialog-editor min-h-0 flex-1 overflow-hidden rounded border"
- :connection-id="props.connectionId"
- :database="props.database"
- :schema="props.schema || props.database"
- :database-type="props.databaseType"
- :dialect="props.dialect"
- :format-dialect="props.formatDialect"
- force-word-wrap
- read-only
- hide-execution-controls
- data-object-source-preview
- />
- </div>
+ </ObjectDependenciesPanel>
<DialogFooter>
<Button variant="outline" @click="closeDialog">{{ t("common.close") }}</Button>
- <Button variant="outline" :disabled="loading || saving" :title="t('structureEditor.refresh')" @click="refreshSource">
+ <Button v-show="section === 'source'" variant="outline" :disabled="loading || saving" :title="t('structureEditor.refresh')" @click="refreshSource">
<RefreshCw class="h-4 w-4" />
{{ t("structureEditor.refresh") }}
</Button>
- <Button v-if="!editing" variant="outline" :disabled="!content" @click="copySource">
+ <Button v-if="!editing && section === 'source'" variant="outline" :disabled="!content" @click="copySource">
<Clipboard class="h-4 w-4" />
{{ t("grid.copy") }}
</Button>
- <Button v-if="!editing && canEdit" variant="outline" :disabled="!editableText" @click="editSource">
+ <Button v-if="!editing && canEdit && section === 'source'" variant="outline" :disabled="!editableText" @click="editSource">
<PencilLine class="h-4 w-4" />
{{ t("contextMenu.editView") }}
</Button>
- <Button v-if="editing" variant="outline" :disabled="saving" @click="cancelEditSource">
+ <Button v-if="editing && section === 'source'" variant="outline" :disabled="saving" @click="cancelEditSource">
{{ t("objects.cancelEdit") }}
</Button>
- <Button v-if="editing" :disabled="saving || !draft.trim()" @click="saveSource">
+ <Button v-if="editing && section === 'source'" :disabled="saving || !draft.trim()" @click="saveSource">
<Loader2 v-if="saving" class="h-4 w-4 animate-spin" />
{{ t("objects.saveSource") }}
</Button>
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectDependenciesPanel.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectDependenciesPanel.spec.ts
new file mode 100644
index 0000000000..fb4a2105ed
--- /dev/null
+++ b/apps/desktop/src/components/objects/__tests__/ObjectDependenciesPanel.spec.ts
@@ -0,0 +1,112 @@
+// @vitest-environment happy-dom
+import { createApp, h, nextTick, ref, type App } from "vue";
+import { createPinia, disposePinia, type Pinia } from "pinia";
+import { createI18n } from "vue-i18n";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import ObjectDependenciesPanel from "../ObjectDependenciesPanel.vue";
+import { useConnectionStore } from "@/stores/connectionStore";
+import type { ObjectDetailsSection } from "@/lib/database/objectDependencyDetails";
+
+const backend = vi.hoisted(() => ({ executeQuery: vi.fn(), cancelQuery: vi.fn(async () => true), checkConnectionHealth: vi.fn(async () => undefined) }));
+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...backend }));
+const target = { connectionId: "source-connection", database: "ORCL", schema: "Original.Owner", name: "P", objectType: "PROCEDURE" as const };
+const mounted: Array<{ app: App; host: HTMLElement; pinia: Pinia }> = [];
+function mountPanel(initial: ObjectDetailsSection = "source") {
+ const pinia = createPinia();
+ const connections = useConnectionStore(pinia);
+ connections.connectedIds.add(target.connectionId);
+ const section = ref(initial),
+ open = ref(true);
+ const onOpenObject = vi.fn(),
+ onViewSql = vi.fn();
+ const app = createApp({
+ render: () =>
+ h(
+ ObjectDependenciesPanel,
+ {
+ target,
+ section: section.value,
+ open: open.value,
+ "onUpdate:section": (value: ObjectDetailsSection) => {
+ section.value = value;
+ },
+ onOpenObject,
+ onViewSql,
+ },
+ { default: () => h("textarea", { "data-source-draft": "", defaultValue: "draft" }) },
+ ),
+ });
+ app.use(pinia);
+ app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
+ const host = document.createElement("div");
+ document.body.append(host);
+ app.mount(host);
+ mounted.push({ app, host, pinia });
+ return { host, section, open, onOpenObject, onViewSql };
+}
+function button(host: HTMLElement, text: string) {
+ return [...host.querySelectorAll("button")].find((node) => node.textContent?.trim() === text)!;
+}
+beforeEach(() => {
+ vi.clearAllMocks();
+ backend.executeQuery.mockResolvedValue({
+ columns: ["DIRECTION", "OBJECT_OWNER", "OBJECT_NAME", "OBJECT_TYPE", "REFERENCED_OWNER", "REFERENCED_NAME", "REFERENCED_TYPE", "DEPENDENCY_TYPE", "REFERENCED_LINK_NAME"],
+ rows: [
+ ["DEPENDS_ON", "Original.Owner", "P", "PROCEDURE", "Other.Owner", "Mixed.Table", "TABLE", "HARD", null],
+ ["REFERENCED_BY", "Caller", "Call.P", "FUNCTION", "Original.Owner", "P", "PROCEDURE", "HARD", null],
+ ["DEPENDS_ON", "Original.Owner", "P", "PROCEDURE", "Remote", "T", "TABLE", "HARD", "REMOTE_DB"],
+ ["DEPENDS_ON", "Original.Owner", "P", "PROCEDURE", "Other.Owner", "Kind", "TYPE", "HARD", null],
+ ],
+ affected_rows: 0,
+ execution_time_ms: 1,
+ });
+});
+afterEach(() => {
+ for (const item of mounted.splice(0)) {
+ item.app.unmount();
+ item.host.remove();
+ disposePinia(item.pinia);
+ }
+});
+
+describe("object details shared sections", () => {
+ it("preserves the source element, draft and selection while switching and refreshing dependencies", async () => {
+ const { host, section } = mountPanel();
+ expect(backend.executeQuery).not.toHaveBeenCalled();
+ const editor = host.querySelector<HTMLTextAreaElement>("textarea")!;
+ editor.value = "changed source draft";
+ editor.setSelectionRange(2, 8);
+ button(host, "objectDependencies.dependencies").click();
+ await vi.waitFor(() => expect(host.textContent).toContain("Mixed.Table"));
+ expect(section.value).toBe("dependencies");
+ button(host, "common.refresh").click();
+ await vi.waitFor(() => expect(backend.executeQuery).toHaveBeenCalledTimes(2));
+ button(host, "objects.source").click();
+ await nextTick();
+ expect(host.querySelector("textarea")).toBe(editor);
+ expect(editor.value).toBe("changed source draft");
+ expect([editor.selectionStart, editor.selectionEnd]).toEqual([2, 8]);
+ });
+
+ it("renders directions separately and forwards a captured origin with exact object identity", async () => {
+ const { host, section, onOpenObject, onViewSql } = mountPanel("dependencies");
+ await vi.waitFor(() => expect(host.textContent).toContain("Mixed.Table"));
+ button(host, "Mixed.Table").click();
+ expect(onOpenObject).toHaveBeenCalledWith(target, { name: "Mixed.Table", schema: "Other.Owner", type: "table", nameQuoted: true, schemaQuoted: true });
+ expect([...host.querySelectorAll("button")].some((node) => node.textContent?.trim() === "Kind")).toBe(false);
+ expect(host.textContent).toContain("objectDependencies.remoteObject");
+ expect(host.textContent).toContain("objectDependencies.unsupportedObject");
+ button(host, "objectDependencies.viewSql").click();
+ expect(onViewSql).toHaveBeenCalledWith(target, expect.stringContaining("ALL_DEPENDENCIES"));
+ expect(backend.executeQuery).toHaveBeenCalledTimes(1);
+ const tab = host.querySelector<HTMLButtonElement>('[data-object-section="dependencies"]')!;
+ tab.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
+ await nextTick();
+ expect(section.value).toBe("dependents");
+ expect(document.activeElement?.getAttribute("data-object-section")).toBe("dependents");
+ const visiblePanel = host.querySelector<HTMLElement>('[role="tabpanel"][aria-labelledby$="dependents-tab"]')!;
+ expect(visiblePanel.textContent).toContain("Call.P");
+ expect(visiblePanel.textContent).not.toContain("Mixed.Table");
+ expect(host.querySelector("textarea")).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.ts
new file mode 100644
index 0000000000..21d9b5bef1
--- /dev/null
+++ b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.dependencies.spec.ts
@@ -0,0 +1,139 @@
+// @vitest-environment happy-dom
+import { createApp, h, nextTick, ref, type App } from "vue";
+import { createPinia, disposePinia, type Pinia } from "pinia";
+import { createI18n } from "vue-i18n";
+import { EditorView } from "@codemirror/view";
+import { undo, undoDepth } from "@codemirror/commands";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import ObjectSourceDialog from "../ObjectSourceDialog.vue";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useQueryStore } from "@/stores/queryStore";
+
+const backend = vi.hoisted(() => ({
+ getObjectSource: vi.fn(),
+ buildEditableObjectSource: vi.fn(async (input: { source: string }) => input.source),
+ executeQuery: vi.fn(),
+ cancelQuery: vi.fn(async () => true),
+ checkConnectionHealth: vi.fn(async () => undefined),
+ listCompletionObjects: vi.fn(async () => []),
+ listPlugins: vi.fn(async () => []),
+}));
+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...backend }));
+const mounted: Array<{ app: App; host: HTMLElement; pinia: Pinia }> = [];
+const source = "CREATE OR REPLACE PROCEDURE P AS BEGIN NULL; END;";
+function button(text: string) {
+ return [...document.querySelectorAll("button")].find((node) => node.textContent?.trim() === text)!;
+}
+function mountDialog(initialSection: "source" | "dependencies" = "source") {
+ const pinia = createPinia();
+ const connections = useConnectionStore(pinia);
+ connections.connectedIds.add("original");
+ connections.connections = [{ id: "original", name: "original", db_type: "oracle", host: "localhost", port: 1521, username: "test", password: "" }];
+ const open = ref(true),
+ onOpenObject = vi.fn();
+ const app = createApp({
+ render: () =>
+ h(ObjectSourceDialog, {
+ open: open.value,
+ connectionId: "original",
+ database: "ORCL",
+ schema: "APP",
+ name: "P",
+ objectType: "PROCEDURE",
+ databaseType: "oracle",
+ dialect: "mysql",
+ initialSection,
+ onOpenObject,
+ "onUpdate:open": (value: boolean) => {
+ open.value = value;
+ },
+ }),
+ });
+ app.use(pinia);
+ app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
+ const host = document.createElement("div");
+ document.body.append(host);
+ app.mount(host);
+ mounted.push({ app, host, pinia });
+ return { open, onOpenObject };
+}
+beforeEach(() => {
+ vi.clearAllMocks();
+ backend.getObjectSource.mockResolvedValue({ name: "P", object_type: "PROCEDURE", source });
+ backend.executeQuery.mockResolvedValue({
+ columns: ["DIRECTION", "OBJECT_OWNER", "OBJECT_NAME", "OBJECT_TYPE", "REFERENCED_OWNER", "REFERENCED_NAME", "REFERENCED_TYPE", "DEPENDENCY_TYPE", "REFERENCED_LINK_NAME"],
+ rows: [["DEPENDS_ON", "APP", "P", "PROCEDURE", "Other.Owner", "Mixed.Table", "TABLE", "HARD", null]],
+ affected_rows: 0,
+ execution_time_ms: 1,
+ });
+});
+afterEach(() => {
+ for (const item of mounted.splice(0)) {
+ item.app.unmount();
+ item.host.remove();
+ disposePinia(item.pinia);
+ }
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe("source dialog dependency integration", () => {
+ it("keeps the real CodeMirror draft, undo history and selection through dependency refresh", async () => {
+ const { open, onOpenObject } = mountDialog();
+ await vi.waitFor(() => expect(button("contextMenu.editView")?.disabled).toBe(false));
+ button("contextMenu.editView").click();
+ await vi.waitFor(() => expect(document.querySelector("[data-object-source-editor] .cm-editor")).not.toBeNull());
+ const editor = document.querySelector<HTMLElement>("[data-object-source-editor] .cm-editor")!;
+ const view = EditorView.findFromDOM(editor)!;
+ const original = view.state.doc.toString();
+ view.dispatch({ changes: { from: original.length, insert: "\n-- my draft" }, selection: { anchor: 2, head: 8 } });
+ await nextTick();
+ const draft = view.state.doc.toString();
+ button("objectDependencies.dependencies").click();
+ await vi.waitFor(() => expect(button("Mixed.Table")).toBeTruthy());
+ button("common.refresh").click();
+ await vi.waitFor(() => expect(backend.executeQuery).toHaveBeenCalledTimes(2));
+ button("objectDependencies.viewSql").click();
+ await nextTick();
+ const queries = useQueryStore();
+ expect(queries.tabs.at(-1)?.sql).toContain("ALL_DEPENDENCIES");
+ expect(queries.tabs.at(-1)?.lastExecutedSql).toBeUndefined();
+ expect(backend.executeQuery).toHaveBeenCalledTimes(2);
+ queries.createTab("other-connection", "other-database", "Other query");
+ button("objects.source").click();
+ await nextTick();
+ expect(document.querySelector("[data-object-source-editor] .cm-editor")).toBe(editor);
+ expect(view.state.doc.toString()).toBe(draft);
+ expect([view.state.selection.main.anchor, view.state.selection.main.head]).toEqual([2, 8]);
+ expect(undoDepth(view.state)).toBeGreaterThan(0);
+ expect(undo(view)).toBe(true);
+ expect(view.state.doc.toString()).toBe(original);
+ view.dispatch({ changes: { from: original.length, insert: "\n-- keep me" } });
+ await nextTick();
+ button("objectDependencies.dependencies").click();
+ await nextTick();
+ const confirm = vi.fn(() => false);
+ vi.stubGlobal("confirm", confirm);
+ button("Mixed.Table").click();
+ expect(confirm).toHaveBeenCalled();
+ expect(open.value).toBe(true);
+ expect(onOpenObject).not.toHaveBeenCalled();
+ confirm.mockReturnValue(true);
+ button("Mixed.Table").click();
+ expect(open.value).toBe(false);
+ expect(onOpenObject).toHaveBeenCalledWith(expect.objectContaining({ connectionId: "original", database: "ORCL", schema: "APP" }), expect.objectContaining({ name: "Mixed.Table", schema: "Other.Owner", type: "table" }));
+ expect(backend.executeQuery.mock.calls.every((call) => String(call[2]).includes("ALL_DEPENDENCIES"))).toBe(true);
+ });
+
+ it("loads dependencies even when source loading fails", async () => {
+ backend.getObjectSource.mockRejectedValue(new Error("source denied"));
+ mountDialog("dependencies");
+ await vi.waitFor(() => expect(button("Mixed.Table")).toBeTruthy());
+ const selected = document.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]')!;
+ expect(selected.textContent).toBe("objectDependencies.dependencies");
+ expect(backend.executeQuery).toHaveBeenCalledTimes(1);
+ button("objects.source").click();
+ await nextTick();
+ expect(document.body.textContent).toContain("source denied");
+ });
+});
diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vue
index dac547a005..fa42050f63 100644
--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue
+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue
@@ -103,6 +103,8 @@ import { sidebarScrollbarGeometry as calculateSidebarScrollbarGeometry } from "@
import { createSidebarLayoutMonitor, type SidebarExpandedConnectionInfo } from "@/lib/sidebar/sidebarLayoutMonitor";
import { disconnectSidebarConnections } from "@/lib/sidebar/sidebarConnectionDisconnect";
import { compileSearchRegex } from "@/lib/common/searchPattern";
+import type { ObjectDependencyTarget, ObjectDetailsSection } from "@/lib/database/objectDependencyDetails";
+import type { SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation";
const { t, locale } = useI18n();
const store = useConnectionStore();
@@ -136,6 +138,7 @@ const { presentMenu, SidebarMenuPreferencesDialog, sidebarMenuPreferencesOpen, s
const emit = defineEmits<{
"open-settings": [initialTab: string];
"add-to-ai": [nodes: TreeNode | TreeNode[]];
+ "open-dependency-object": [context: ObjectDependencyTarget, target: SqlObjectNavigationTarget];
}>();
const sidebarContextMenuTarget = ref<SidebarActionTarget | null>(null);
@@ -153,7 +156,7 @@ const sidebarDdlTarget = ref<TreeNode | null>(null);
const sidebarDdlOpen = ref(false);
const sidebarElasticsearchIndexMetadataTarget = ref<{ node: TreeNode; kind: ElasticsearchIndexMetadataKind } | null>(null);
const sidebarElasticsearchIndexMetadataOpen = ref(false);
-const sidebarObjectSourceTarget = ref<{ node: TreeNode; initialEditing: boolean } | null>(null);
+const sidebarObjectSourceTarget = ref<{ node: TreeNode; initialEditing: boolean; initialSection?: ObjectDetailsSection } | null>(null);
const sidebarObjectSourceOpen = ref(false);
const sidebarProcedureTarget = ref<TreeNode | null>(null);
const sidebarProcedureOpen = ref(false);
@@ -2254,7 +2257,7 @@ function openSidebarElasticsearchIndexMetadata(node: TreeNode, kind: Elasticsear
sidebarElasticsearchIndexMetadataOpen.value = true;
}
-function openSidebarObjectSource(node: TreeNode, initialEditing: boolean) {
+function openSidebarObjectSource(node: TreeNode, initialEditing: boolean, initialSection?: ObjectDetailsSection) {
if (!node.connectionId || !hasTreeNodeDatabaseContext(node) || !objectSourceTargetForTreeNode(node)) return;
// TYPE/TYPE_BODY only have a source implementation on Xugu; PostgreSQL-family
// connections list user-defined types without a CREATE TYPE getter this cycle.
@@ -2263,7 +2266,7 @@ function openSidebarObjectSource(node: TreeNode, initialEditing: boolean) {
beginSidebarAction();
// issue #9035:弹窗立即挂载。此前先 await ensureConnected 再开弹窗,这段时间
// 界面上没有任何反馈;现在连接与取源都在弹窗自身的加载态之内完成。
- sidebarObjectSourceTarget.value = { node: target, initialEditing };
+ sidebarObjectSourceTarget.value = { node: target, initialEditing, initialSection };
sidebarObjectSourceOpen.value = true;
}
@@ -3035,6 +3038,7 @@ defineExpose({
v-model:open="sidebarObjectSourceOpen"
:connection-id="sidebarObjectSourceTarget.node.connectionId!"
:database="sidebarObjectSourceTarget.node.database!"
+ :catalog="sidebarObjectSourceTarget.node.catalog"
:schema="sidebarObjectSourceResolvedTarget?.schema"
:name="sidebarObjectSourceResolvedTarget!.name"
:relation-name="sidebarObjectSourceTarget.node.tableName"
@@ -3044,6 +3048,8 @@ defineExpose({
:dialect="sidebarObjectSourceDialect"
:format-dialect="sidebarObjectSourceFormatDialect"
:initial-editing="sidebarObjectSourceTarget.initialEditing"
+ :initial-section="sidebarObjectSourceTarget.initialSection"
+ @open-object="(context: ObjectDependencyTarget, target: SqlObjectNavigationTarget) => emit('open-dependency-object', context, target)"
@saved="refreshSidebarActionTarget"
/>
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index 40b975f2c5..249911608a 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -117,6 +117,8 @@ import { isXuguTypeMemberContainer } from "@/lib/sidebar/xuguTypeMembers";
import { isXuguSyntheticTreeNode } from "@/lib/sidebar/xuguPublicSynonyms";
import { buildXuguSchedulerJobSql, type XuguSchedulerJobAction } from "@/lib/database/xuguSchedulerJobSql";
import { canViewDatabaseObjectDependencies, databaseDependencyProviderFor } from "@/lib/database/databaseObjectDependencies";
+import { oracleTarget } from "@/lib/database/oracleObjectDependencies";
+import type { ObjectDetailsSection } from "@/lib/database/objectDependencyDetails";
import { elasticsearchClearIndexPreview, isElasticsearchClearConfirmed, isElasticsearchIndexPattern } from "@/lib/sidebar/elasticsearchIndexActions";
import { sidebarObjectTemplateForGroup } from "@/lib/sidebar/databaseObjectTemplates";
import { buildTableDeleteTemplate, buildTableInsertTemplate, buildTableSelectTemplate, buildTableUpdateTemplate, insertTemplatePrimaryKeyConflicts } from "@/lib/table/tableSqlTemplates";
@@ -540,7 +542,7 @@ const emit = defineEmits<{
"context-menu": [event: MouseEvent, node: TreeNode, items: ContextMenuItem[]];
"open-ddl": [node: TreeNode];
"open-elasticsearch-index-metadata": [node: TreeNode, kind: ElasticsearchIndexMetadataKind];
- "open-object-source": [node: TreeNode, initialEditing: boolean];
+ "open-object-source": [node: TreeNode, initialEditing: boolean, initialSection?: ObjectDetailsSection];
"open-procedure": [node: TreeNode];
"open-settings": [initialTab: string];
"open-data": [node: TreeNode, requireSelection: boolean, openMode: DataTabOpenMode, runner: (node: TreeNode, request: SidebarDataOpenRequest) => Promise<void>];
@@ -2966,8 +2968,9 @@ async function refreshDropTableChildObjectPreviewSql() {
dropTableChildObjectPreviewSql.value = options ? await buildDropTableChildObjectSql(options).catch(() => "") : "";
}
-function openObjectSourceDialog(initialEditing: boolean, viewPackageBody = false) {
- const node = activeNode.value;
+function openObjectSourceDialog(initialEditing: boolean, viewPackageBody = false, dependencyNode?: TreeNode) {
+ const node = dependencyNode || activeNode.value;
+ const initialSection = dependencyNode ? "dependencies" : undefined;
if (!node.connectionId || !node.database) return;
if (viewPackageBody && (node.type !== "package" || node.xuguPackageBodyAvailable !== true || currentDatabaseType() !== "xugu")) return;
const sourceNode: TreeNode = viewPackageBody ? { ...node, type: "package-body" } : node;
@@ -2990,11 +2993,12 @@ function openObjectSourceDialog(initialEditing: boolean, viewPackageBody = false
schema,
catalog: node.catalog,
initialEditing,
+ initialSection,
request: { name: sourceTarget.name, objectType: sourceTarget.objectType, signature: sourceNode.signature },
});
return;
}
- emit("open-object-source", sourceNode, initialEditing);
+ emit("open-object-source", sourceNode, initialEditing, initialSection);
}
function openProcedureExecution() {
@@ -3007,13 +3011,20 @@ async function openDatabaseObjectDependencies() {
const node = activeNode.value;
const provider = databaseDependencyProviderFor(currentDatabaseType());
if (!provider || !node.connectionId || !node.database || !provider.supports(node)) return;
+ if (currentDatabaseType() === "oracle" || currentDatabaseType() === "oceanbase-oracle") {
+ const target = oracleTarget(node);
+ if (!target) return;
+ openObjectSourceDialog(false, false, { ...node, type: target.type.toLowerCase() as "procedure" | "function" | "package", schema: target.schema, objectName: target.name, label: target.name, parentType: undefined, parentName: undefined, parentSchema: undefined });
+ return;
+ }
const sql = provider.buildQuery(node);
if (!sql) return;
try {
await connectionStore.ensureConnected(node.connectionId);
connectionStore.activeConnectionId = node.connectionId;
- const objectName = node.objectName || node.label;
+ const target = provider.targetLabel?.(node);
+ const objectName = target ? `${target.packageScope ? `${t("common.package")} ` : ""}${target.name}` : node.objectName || node.label;
const tabId = queryStore.createTab(node.connectionId, node.database, `${t("contextMenu.viewDependencies")} - ${objectName}`, "query", node.schema, undefined, node.catalog, { forceNew: true });
queryStore.updateSql(tabId, sql);
await queryStore.executeTabSql(tabId, sql);
@@ -7682,7 +7693,7 @@ function buildObjectSidebarMenu(context: SidebarMenuFactoryContext): boolean {
if (!isPackageMember) {
items.push({ label: t("diff.title"), action: openSchemaDiffForRoutine, icon: ArrowRightLeft });
}
- if (!isPackageMember && canViewDatabaseObjectDependencies(currentDatabaseType(), node)) {
+ if (canViewDatabaseObjectDependencies(currentDatabaseType(), node)) {
items.push({ label: t("contextMenu.viewDependencies"), action: openDatabaseObjectDependencies, icon: Network });
}
items.push(copyNameMenuItem());
diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.databaseDependencies.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.databaseDependencies.spec.ts
new file mode 100644
index 0000000000..2e358691d3
--- /dev/null
+++ b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.databaseDependencies.spec.ts
@@ -0,0 +1,141 @@
+// @vitest-environment happy-dom
+import { createApp, defineComponent, h, nextTick, ref, type App } from "vue";
+import { createPinia, disposePinia, setActivePinia, type Pinia } from "pinia";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import type { DatabaseType, TreeNode } from "@/types/database";
+import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
+
+const backend = vi.hoisted(() => ({
+ executeMulti: vi.fn().mockResolvedValue([{ columns: ["DIRECTION"], rows: [["DEPENDS_ON"]], affected_rows: 0, execution_time_ms: 3 }]),
+ prepareQueryPaginationExecutionPlan: vi.fn(async ({ sql }: { sql: string }) => ({ sqlToExecute: sql, pageSql: sql, pageLimit: 100, useAgentResultSession: false })),
+ checkConnectionHealth: vi.fn(async () => undefined),
+ getObjectSource: vi.fn(async () => ({ name: "BATCH_API", object_type: "PACKAGE", source: "package source", editable: false })),
+ buildEditableObjectSource: vi.fn(async (input: { source: string }) => input.source),
+ analyzeEditableQueryEditability: vi.fn(async () => ({ editable: false, reason: "set-operation" })),
+}));
+
+vi.mock("@/lib/backend/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/backend/api")>()),
+ ...backend,
+ listPlugins: vi.fn().mockResolvedValue([]),
+}));
+vi.mock("@/lib/backend/http", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/backend/http")>()),
+ ...backend,
+}));
+
+import SidebarTreeRuntimeHost from "@/components/sidebar/SidebarTreeRuntimeHost.vue";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useQueryStore } from "@/stores/queryStore";
+import { useSettingsStore } from "@/stores/settingsStore";
+
+const mounted: { app: App; container: HTMLElement; pinia: Pinia }[] = [];
+
+async function mountContextMenu(databaseType: DatabaseType, mode: "query-tab" | "dialog" = "query-tab") {
+ const pinia = createPinia();
+ setActivePinia(pinia);
+ const connections = useConnectionStore();
+ connections.addEphemeralConnection({ id: "dependency-test", name: "Test", db_type: databaseType, driver_profile: databaseType, host: "localhost", port: 1, username: "test", password: "" });
+ connections.connectedIds.add("dependency-test");
+ useSettingsStore().editorSettings.routineSourceOpenMode = mode;
+ const queries = useQueryStore();
+ const onOpenObjectSource = vi.fn();
+
+ const host = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);
+ const rootNode: TreeNode = { id: "dependency-test", type: "connection", label: "Test", connectionId: "dependency-test", database: "APP" };
+ const root = defineComponent({ setup: () => () => h(SidebarTreeRuntimeHost, { ref: host, node: rootNode, depth: 0, onOpenObjectSource }) });
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const app = createApp(root);
+ app.use(pinia);
+ app.use(i18n);
+ app.mount(container);
+ mounted.push({ app, container, pinia });
+ await nextTick();
+
+ return { host: host.value as unknown as { buildContextMenu(node: TreeNode): ContextMenuItem[] }, queries, onOpenObjectSource };
+}
+
+describe("routine dependency context-menu action", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ for (const { app, container, pinia } of mounted.splice(0)) {
+ app.unmount();
+ container.remove();
+ disposePinia(pinia);
+ }
+ setActivePinia(undefined);
+ });
+
+ it.each(["oracle", "oceanbase-oracle"] as const)("opens object dependencies from an Oracle package member in %s", async (databaseType) => {
+ const { host, queries } = await mountContextMenu(databaseType);
+ const member: TreeNode = {
+ id: "dependency-test:package-member",
+ type: "procedure",
+ label: "RUN_JOB",
+ objectName: "RUN_JOB",
+ parentType: "package",
+ parentName: "BATCH_API",
+ parentSchema: "APP",
+ schema: "APP",
+ connectionId: "dependency-test",
+ database: "APP",
+ };
+ const menu = host.buildContextMenu(member);
+ const action = menu.find((item) => item.label === i18n.global.t("contextMenu.viewDependencies"))?.action;
+ expect(action).toBeDefined();
+
+ await action?.();
+
+ const queryTab = queries.tabs.find((tab) => tab.mode === "query");
+ expect(queryTab?.title).toBe("Source - BATCH_API");
+ expect(queryTab?.objectDetails).toMatchObject({ connectionId: "dependency-test", database: "APP", schema: "APP", name: "BATCH_API", objectType: "PACKAGE", section: "dependencies" });
+ expect(backend.executeMulti).not.toHaveBeenCalled();
+ expect(queryTab?.result).toBeUndefined();
+ });
+
+ it("preserves the existing dialog preference and forwards its initial section", async () => {
+ const { host, queries, onOpenObjectSource } = await mountContextMenu("oracle", "dialog");
+ const node: TreeNode = { id: "P", type: "procedure", label: "P", schema: "APP", connectionId: "dependency-test", database: "APP" };
+ await host
+ .buildContextMenu(node)
+ .find((item) => item.label === i18n.global.t("contextMenu.viewDependencies"))
+ ?.action?.();
+ expect(onOpenObjectSource).toHaveBeenCalledWith(expect.objectContaining({ type: "procedure", schema: "APP", label: "P" }), false, "dependencies");
+ expect(queries.tabs).toHaveLength(0);
+ });
+
+ it("keeps the Xugu standalone dependency query path", async () => {
+ const { host, queries } = await mountContextMenu("xugu");
+ const node: TreeNode = { id: "P", type: "procedure", label: "P", schema: "APP", connectionId: "dependency-test", database: "APP" };
+ await host
+ .buildContextMenu(node)
+ .find((item) => item.label === i18n.global.t("contextMenu.viewDependencies"))
+ ?.action?.();
+ expect(queries.tabs[0]?.objectDetails).toBeUndefined();
+ expect(backend.executeMulti).toHaveBeenCalledTimes(1);
+ expect(queries.tabs[0]?.result).toMatchObject({ columns: ["DIRECTION"], rows: [["DEPENDS_ON"]] });
+ await vi.waitFor(() => expect(queries.tabs[0]?.queryEditabilityReason).toBe("set-operation"));
+ });
+
+ it("keeps package-member dependency action hidden for Xugu", async () => {
+ const { host } = await mountContextMenu("xugu");
+ const member: TreeNode = {
+ id: "dependency-test:package-member",
+ type: "procedure",
+ label: "RUN_JOB",
+ objectName: "RUN_JOB",
+ parentType: "package",
+ parentName: "BATCH_API",
+ parentSchema: "APP",
+ schema: "APP",
+ connectionId: "dependency-test",
+ database: "APP",
+ };
+ expect(host.buildContextMenu(member).map((item) => item.label)).not.toContain(i18n.global.t("contextMenu.viewDependencies"));
+ });
+});
diff --git a/apps/desktop/src/composables/__tests__/useObjectDependencies.spec.ts b/apps/desktop/src/composables/__tests__/useObjectDependencies.spec.ts
new file mode 100644
index 0000000000..d8d1774271
--- /dev/null
+++ b/apps/desktop/src/composables/__tests__/useObjectDependencies.spec.ts
@@ -0,0 +1,133 @@
+// @vitest-environment happy-dom
+import { createApp, defineComponent, h, nextTick, ref, type App } from "vue";
+import { createPinia, disposePinia, type Pinia } from "pinia";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useObjectDependencies } from "@/composables/useObjectDependencies";
+import { useConnectionStore } from "@/stores/connectionStore";
+import type { ObjectDependencyTarget } from "@/lib/database/objectDependencyDetails";
+import type { QueryResult } from "@/types/database";
+
+const backend = vi.hoisted(() => ({ executeQuery: vi.fn(), cancelQuery: vi.fn(async () => true), checkConnectionHealth: vi.fn(async () => undefined) }));
+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...backend }));
+const mounted: Array<{ app: App; host: HTMLElement; pinia: Pinia }> = [];
+const identity: ObjectDependencyTarget = { connectionId: "original", database: "ORCL", schema: "APP", name: "P", objectType: "PROCEDURE" };
+const result = (name = "T"): QueryResult => ({
+ columns: ["DIRECTION", "OBJECT_OWNER", "OBJECT_NAME", "OBJECT_TYPE", "REFERENCED_OWNER", "REFERENCED_NAME", "REFERENCED_TYPE", "DEPENDENCY_TYPE", "REFERENCED_LINK_NAME"],
+ rows: [["DEPENDS_ON", "APP", "P", "PROCEDURE", "OTHER", name, "TABLE", "HARD", null]],
+ affected_rows: 0,
+ execution_time_ms: 1,
+});
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+function mountLoader(enabled = true) {
+ const target = ref<ObjectDependencyTarget | undefined>({ ...identity });
+ const active = ref(enabled);
+ const pinia = createPinia();
+ const connections = useConnectionStore(pinia);
+ connections.connections = [{ id: "original", name: "original", db_type: "oracle", host: "localhost", port: 1521, username: "test", password: "" }];
+ connections.connectedIds.add("original");
+ let loader!: ReturnType<typeof useObjectDependencies>;
+ const app = createApp(
+ defineComponent({
+ setup() {
+ loader = useObjectDependencies(target, active);
+ return () => h("div");
+ },
+ }),
+ );
+ app.use(pinia);
+ const host = document.createElement("div");
+ document.body.append(host);
+ app.mount(host);
+ mounted.push({ app, host, pinia });
+ return { loader, target, active, app };
+}
+beforeEach(() => {
+ vi.clearAllMocks();
+ backend.executeQuery.mockReset();
+});
+afterEach(() => {
+ for (const item of mounted.splice(0)) {
+ item.app.unmount();
+ item.host.remove();
+ disposePinia(item.pinia);
+ }
+});
+
+describe("independent object dependency lifecycle", () => {
+ it("loads lazily without a query session and keeps previous rows on refresh failure", async () => {
+ backend.executeQuery.mockResolvedValue(result());
+ const { loader, active } = mountLoader(false);
+ await nextTick();
+ expect(backend.executeQuery).not.toHaveBeenCalled();
+ active.value = true;
+ await vi.waitFor(() => expect(loader.loaded.value).toBe(true));
+ expect(backend.executeQuery.mock.calls[0]).toEqual(["original", "ORCL", expect.stringContaining("ALL_DEPENDENCIES"), "APP", expect.stringContaining("object-dependencies-"), { catalog: undefined }]);
+ expect(loader.rows.value[0]?.name).toBe("T");
+ backend.executeQuery.mockRejectedValueOnce(new Error("permission denied"));
+ await loader.refresh();
+ expect(loader.error.value).toBe("permission denied");
+ expect(loader.rows.value[0]?.name).toBe("T");
+ expect(loader.loaded.value).toBe(true);
+ backend.executeQuery.mockResolvedValueOnce({ ...result(), rows: [], truncated: true });
+ await loader.refresh();
+ expect(loader.error.value).toBe("");
+ expect(loader.rows.value).toEqual([]);
+ expect(loader.truncated.value).toBe(true);
+ });
+
+ it("rejects stale refresh responses and cancels only its own execution id", async () => {
+ const first = deferred<QueryResult>(),
+ second = deferred<QueryResult>();
+ backend.executeQuery.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
+ const { loader } = mountLoader();
+ await vi.waitFor(() => expect(backend.executeQuery).toHaveBeenCalledTimes(1));
+ const refresh = loader.refresh();
+ await vi.waitFor(() => expect(backend.executeQuery).toHaveBeenCalledTimes(2));
+ expect(backend.cancelQuery).toHaveBeenCalledWith(backend.executeQuery.mock.calls[0]![4]);
+ second.resolve(result("CURRENT"));
+ await refresh;
+ first.resolve(result("OLD"));
+ await nextTick();
+ expect(loader.rows.value[0]?.name).toBe("CURRENT");
+ });
+
+ it("distinguishes A→B→A generations even when the final identity is equal", async () => {
+ const a = deferred<QueryResult>(),
+ b = deferred<QueryResult>(),
+ a2 = deferred<QueryResult>();
+ backend.executeQuery.mockReturnValueOnce(a.promise).mockReturnValueOnce(b.promise).mockReturnValueOnce(a2.promise);
+ const { target, loader } = mountLoader();
+ await vi.waitFor(() => expect(backend.executeQuery).toHaveBeenCalledTimes(1));
+ target.value = { ...identity, name: "B", schema: "OTHER" };
+ await vi.waitFor(() => expect(backend.executeQuery).toHaveBeenCalledTimes(2));
+ target.value = { ...identity };
+ await vi.waitFor(() => expect(backend.executeQuery).toHaveBeenCalledTimes(3));
+ a2.resolve(result("CURRENT"));
+ await vi.waitFor(() => expect(loader.loaded.value).toBe(true));
+ a.resolve(result("OLD_A"));
+ b.resolve(result("OLD_B"));
+ await nextTick();
+ expect(loader.rows.value[0]?.name).toBe("CURRENT");
+ });
+
+ it("invalidates close and context changes; a late response cannot refill closed content", async () => {
+ const pending = deferred<QueryResult>();
+ backend.executeQuery.mockReturnValue(pending.promise);
+ const { target, loader } = mountLoader();
+ await vi.waitFor(() => expect(backend.executeQuery).toHaveBeenCalledTimes(1));
+ target.value = undefined;
+ pending.resolve(result());
+ await nextTick();
+ expect(loader.rows.value).toEqual([]);
+ expect(loader.loaded.value).toBe(false);
+ expect(loader.loading.value).toBe(false);
+ expect(backend.cancelQuery).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/composables/useObjectDependencies.ts b/apps/desktop/src/composables/useObjectDependencies.ts
new file mode 100644
index 0000000000..c904f74dc5
--- /dev/null
+++ b/apps/desktop/src/composables/useObjectDependencies.ts
@@ -0,0 +1,74 @@
+import { computed, onBeforeUnmount, ref, watch, type Ref } from "vue";
+import * as api from "@/lib/backend/api";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { uuid } from "@/lib/common/utils";
+import { objectDependencyRows, objectDependencySql, type ObjectDependencyRow, type ObjectDependencyTarget } from "@/lib/database/objectDependencyDetails";
+
+export function useObjectDependencies(target: Readonly<Ref<ObjectDependencyTarget | undefined>>, enabled: Readonly<Ref<boolean>>) {
+ const connectionStore = useConnectionStore();
+ const rows = ref<ObjectDependencyRow[]>([]);
+ const loading = ref(false);
+ const error = ref("");
+ const loaded = ref(false);
+ const truncated = ref(false);
+ const key = computed(() => (target.value ? JSON.stringify(target.value) : ""));
+ let generation = 0;
+ let executionId: string | undefined;
+
+ function invalidate() {
+ ++generation;
+ if (executionId) void api.cancelQuery(executionId).catch(() => false);
+ executionId = undefined;
+ }
+
+ async function refresh() {
+ const identity = target.value;
+ if (!identity) return;
+ invalidate();
+ const serial = generation;
+ const requestKey = key.value;
+ const id = `object-dependencies-${uuid()}`;
+ executionId = id;
+ loading.value = true;
+ error.value = "";
+ try {
+ await connectionStore.ensureConnected(identity.connectionId);
+ if (serial !== generation || requestKey !== key.value) return;
+ const result = await api.executeQuery(identity.connectionId, identity.database, objectDependencySql(identity), identity.schema, id, { catalog: identity.catalog });
+ if (serial !== generation || requestKey !== key.value) return;
+ rows.value = objectDependencyRows(result);
+ truncated.value = !!(result.truncated || result.has_more);
+ loaded.value = true;
+ } catch (e: unknown) {
+ if (serial === generation && requestKey === key.value) error.value = e instanceof Error ? e.message : String(e);
+ } finally {
+ if (serial === generation) {
+ loading.value = false;
+ executionId = undefined;
+ }
+ }
+ }
+
+ watch(
+ key,
+ () => {
+ invalidate();
+ rows.value = [];
+ error.value = "";
+ loaded.value = false;
+ truncated.value = false;
+ loading.value = false;
+ if (enabled.value && target.value) void refresh();
+ },
+ { flush: "sync" },
+ );
+ watch(
+ enabled,
+ (value) => {
+ if (value && !loaded.value && !loading.value && target.value) void refresh();
+ },
+ { immediate: true },
+ );
+ onBeforeUnmount(invalidate);
+ return { rows, loading, error, loaded, truncated, refresh };
+}
diff --git a/apps/desktop/src/composables/useSqlExecution.ts b/apps/desktop/src/composables/useSqlExecution.ts
index 0278807b78..2f4e127bfd 100644
--- a/apps/desktop/src/composables/useSqlExecution.ts
+++ b/apps/desktop/src/composables/useSqlExecution.ts
@@ -36,6 +36,7 @@ import type { SqlExecutionTargetContext } from "@/lib/database/sqlExecutionTarge
import { MULTI_SOURCE_MAX_ROWS_PER_SOURCE } from "@/lib/query/multiSourceResult";
import { translateBackendError } from "@/i18n/backend-errors";
import type { SqlExecutionDeferredReason, SqlExecutionNotStartedReason, SqlExecutionOutcome } from "@/lib/sql/sqlExecutionOutcome";
+import { isObjectDependencySection } from "@/lib/database/objectDependencyDetails";
const DANGER_RE = /^\s*(DROP|DELETE|TRUNCATE|ALTER|UPDATE|MERGE|REPLACE)\b/i;
@@ -290,6 +291,11 @@ export function useSqlExecution(deps: {
}
async function tryExecute(sqlOverride?: SqlExecutionOverride, options: SqlExecutionOptions = {}): Promise<SqlExecutionOutcome> {
+ const sourceTab = resolveExecutionTab(options.tabId);
+ if (sourceTab && isObjectDependencySection(sourceTab)) {
+ cancelEditorViewportRequest(options.editorViewportRequestId);
+ return notStarted("blocked", sourceTab.id);
+ }
const context = captureExecutionContext(options.tabId);
if (!context) {
cancelEditorViewportRequest(options.editorViewportRequestId);
@@ -948,6 +954,8 @@ export function useSqlExecution(deps: {
}
async function tryExplain(sqlOverride?: SqlExecutionOverride, options: SqlExecutionOptions = {}) {
+ const sourceTab = resolveExecutionTab(options.tabId);
+ if (sourceTab && isObjectDependencySection(sourceTab)) return;
const context = captureExecutionContext(options.tabId);
if (!context) {
return;
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 63ed734b6d..27286a99b9 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -61,6 +61,22 @@ const consul = {
};
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "Asılılıqlar",
+ dependents: "Asılı obyektlər",
+ viewSql: "SQL-ə bax",
+ visibility: "ALL_DEPENDENCIES-də cari hesaba görünən birbaşa asılılıqları göstərir.",
+ packageScope: "Paketin spesifikasiyası və gövdəsi birlikdə göstərilir; ayrı-ayrı üzvlər fərqləndirilmir.",
+ partial: "Nəticələr kəsilib; siyahı natamam ola bilər.",
+ notUpdated: "Yenilənmə alınmadı. Əvvəlki nəticələr göstərilir.",
+ empty: "Cari hesaba görünən birbaşa asılılıq tapılmadı.",
+ dependencyType: "Asılılıq növü",
+ sourceType: "Mənbə növü",
+ link: "Verilənlər bazası bağlantısı",
+ remoteObject: "Uzaq obyekt: adı kopyalana bilər, lakin açılması hələ dəstəklənmir.",
+ unsupportedObject: "Bu obyekt növünün açılması hələ dəstəklənmir. Adını kopyalaya bilərsiniz.",
+ navigateDiscardConfirm: "Mənbədə saxlanılmamış dəyişikliklər var. Onları ləğv edib əlaqəli obyekti açasınız?",
+ },
sidebarMenu,
oracleIndex: { mixedDraft: "Oracle indeks dəyişikliklərini digər cədvəl quruluşu dəyişikliklərindən ayrıca tətbiq edin." },
pluginPlatform: {
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index e0245f64a2..434a5ac38a 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -64,6 +64,22 @@ const consul = {
};
export default {
+ objectDependencies: {
+ dependencies: "Dependencies",
+ dependents: "Dependents",
+ viewSql: "View SQL",
+ visibility: "Shows direct dependencies visible to the current account in ALL_DEPENDENCIES.",
+ packageScope: "Package specification and body are combined; individual members are not distinguished.",
+ partial: "Results were truncated; the list may be incomplete.",
+ notUpdated: "Refresh failed. The previous results are still shown.",
+ empty: "No direct dependencies visible to the current account were found.",
+ dependencyType: "Dependency type",
+ sourceType: "Source type",
+ link: "Database link",
+ remoteObject: "Remote object: copy its name; opening is not supported yet.",
+ unsupportedObject: "Opening this object type is not supported yet. You can copy its name.",
+ navigateDiscardConfirm: "The source has unsaved changes. Discard them and open the related object?",
+ },
oracleSecurity: {
directSqlNotice: "Visible direct grants only, not effective session permissions or a complete replay script. Inheritance and grantors are in the source details.",
searchOwner: "Search owner/schema",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index ae2e6273f7..89d0e2f630 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -66,6 +66,22 @@ const consul = {
};
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "Dependencias",
+ dependents: "Objetos dependientes",
+ viewSql: "Ver SQL",
+ visibility: "Muestra las dependencias directas visibles para la cuenta actual en ALL_DEPENDENCIES.",
+ packageScope: "La especificación y el cuerpo del paquete se combinan; no se distinguen sus miembros.",
+ partial: "Los resultados se truncaron; la lista puede estar incompleta.",
+ notUpdated: "La actualización falló. Se muestran los resultados anteriores.",
+ empty: "No se encontraron dependencias directas visibles para la cuenta actual.",
+ dependencyType: "Tipo de dependencia",
+ sourceType: "Tipo de origen",
+ link: "Enlace de base de datos",
+ remoteObject: "Objeto remoto: puede copiar su nombre; aún no se puede abrir.",
+ unsupportedObject: "Aún no se puede abrir este tipo de objeto. Puede copiar su nombre.",
+ navigateDiscardConfirm: "El código tiene cambios sin guardar. ¿Descartarlos y abrir el objeto relacionado?",
+ },
oracleSecurity: {
directSqlNotice: "Solo concesiones directas visibles, no permisos efectivos de sesión ni un script completo para reproducirlas. La herencia y los otorgantes están en los detalles de origen.",
searchOwner: "Buscar owner/schema",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 3496638ce4..c12dde5546 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -7,6 +7,22 @@ import { sqlServerTraceMessages as sqlServerTrace } from "./sqlServerTraceMessag
import { meilisearchManagementId } from "./meilisearchManagement";
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "Dependensi",
+ dependents: "Objek yang bergantung",
+ viewSql: "Lihat SQL",
+ visibility: "Menampilkan dependensi langsung yang terlihat oleh akun saat ini di ALL_DEPENDENCIES.",
+ packageScope: "Spesifikasi dan isi paket digabung; anggota individual tidak dibedakan.",
+ partial: "Hasil terpotong; daftar mungkin tidak lengkap.",
+ notUpdated: "Penyegaran gagal. Hasil sebelumnya tetap ditampilkan.",
+ empty: "Tidak ditemukan dependensi langsung yang terlihat oleh akun saat ini.",
+ dependencyType: "Jenis dependensi",
+ sourceType: "Jenis sumber",
+ link: "Tautan basis data",
+ remoteObject: "Objek jarak jauh: namanya dapat disalin, tetapi belum dapat dibuka.",
+ unsupportedObject: "Jenis objek ini belum dapat dibuka. Anda dapat menyalin namanya.",
+ navigateDiscardConfirm: "Sumber memiliki perubahan yang belum disimpan. Buang perubahan dan buka objek terkait?",
+ },
sidebarMenu,
oracleIndex: { mixedDraft: "Terapkan perubahan indeks Oracle secara terpisah dari perubahan struktur tabel lainnya." },
cellTransform: {
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 430056df20..098ec5af09 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -64,6 +64,22 @@ const consul = {
};
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "Dipendenze",
+ dependents: "Oggetti dipendenti",
+ viewSql: "Mostra SQL",
+ visibility: "Mostra le dipendenze dirette visibili all'account corrente in ALL_DEPENDENCIES.",
+ packageScope: "Specifica e corpo del package sono combinati; i singoli membri non sono distinti.",
+ partial: "I risultati sono stati troncati; l'elenco potrebbe essere incompleto.",
+ notUpdated: "Aggiornamento non riuscito. Sono mostrati i risultati precedenti.",
+ empty: "Nessuna dipendenza diretta visibile all'account corrente.",
+ dependencyType: "Tipo di dipendenza",
+ sourceType: "Tipo di origine",
+ link: "Collegamento al database",
+ remoteObject: "Oggetto remoto: è possibile copiarne il nome, ma non ancora aprirlo.",
+ unsupportedObject: "L'apertura di questo tipo di oggetto non è ancora supportata. È possibile copiarne il nome.",
+ navigateDiscardConfirm: "Il codice contiene modifiche non salvate. Ignorarle e aprire l'oggetto correlato?",
+ },
oracleSecurity: {
directSqlNotice: "Solo concessioni dirette visibili, non privilegi effettivi della sessione né uno script completo da rieseguire. Eredità e concedenti sono nei dettagli delle origini.",
searchOwner: "Cerca owner/schema",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 06cfd2b443..5c866a4cb1 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -65,6 +65,22 @@ const consul = {
};
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "依存先",
+ dependents: "依存元",
+ viewSql: "SQL を表示",
+ visibility: "ALL_DEPENDENCIES で現在のアカウントから参照できる直接の依存関係を表示します。",
+ packageScope: "パッケージ仕様部と本体をまとめて表示します。個々のメンバーは区別しません。",
+ partial: "結果が切り詰められたため、一覧が不完全な可能性があります。",
+ notUpdated: "更新に失敗しました。前回の結果を表示しています。",
+ empty: "現在のアカウントから参照できる直接の依存関係はありません。",
+ dependencyType: "依存関係の種類",
+ sourceType: "参照元の種類",
+ link: "データベースリンク",
+ remoteObject: "リモートオブジェクトは名前をコピーできますが、まだ開けません。",
+ unsupportedObject: "この種類のオブジェクトはまだ開けません。名前をコピーできます。",
+ navigateDiscardConfirm: "ソースに未保存の変更があります。破棄して関連オブジェクトを開きますか?",
+ },
oracleSecurity: {
directSqlNotice: "参照できる直接付与のみを表示します。セッションの有効な権限や完全な再実行スクリプトではありません。継承と付与者は付与元の詳細を参照してください。",
searchOwner: "owner/schema を検索",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index ac01c579fb..bf05830101 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -64,6 +64,22 @@ const consul = {
};
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "의존하는 객체",
+ dependents: "의존받는 객체",
+ viewSql: "SQL 보기",
+ visibility: "ALL_DEPENDENCIES에서 현재 계정에 보이는 직접 의존 관계를 표시합니다.",
+ packageScope: "패키지 명세와 본문을 합쳐 표시하며 개별 멤버는 구분하지 않습니다.",
+ partial: "결과가 잘려 목록이 불완전할 수 있습니다.",
+ notUpdated: "새로 고침에 실패했습니다. 이전 결과를 표시합니다.",
+ empty: "현재 계정에 보이는 직접 의존 관계가 없습니다.",
+ dependencyType: "의존 관계 유형",
+ sourceType: "원본 유형",
+ link: "데이터베이스 링크",
+ remoteObject: "원격 객체는 이름을 복사할 수 있지만 아직 열 수 없습니다.",
+ unsupportedObject: "이 객체 유형은 아직 열 수 없습니다. 이름을 복사할 수 있습니다.",
+ navigateDiscardConfirm: "소스에 저장하지 않은 변경 사항이 있습니다. 변경 사항을 버리고 관련 객체를 여시겠습니까?",
+ },
oracleSecurity: {
directSqlNotice: "조회 가능한 직접 부여만 표시하며 세션의 유효 권한이나 완전한 재실행 스크립트가 아닙니다. 상속과 부여자는 출처 상세 정보에 표시됩니다.",
searchOwner: "owner/schema 검색",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index 7c9eed1fe0..d517a78282 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -62,6 +62,22 @@ const consul = {
};
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "Zależności",
+ dependents: "Obiekty zależne",
+ viewSql: "Pokaż SQL",
+ visibility: "Pokazuje bezpośrednie zależności widoczne dla bieżącego konta w ALL_DEPENDENCIES.",
+ packageScope: "Specyfikacja i treść pakietu są połączone; poszczególne elementy nie są rozróżniane.",
+ partial: "Wyniki zostały obcięte; lista może być niepełna.",
+ notUpdated: "Odświeżenie nie powiodło się. Pokazane są poprzednie wyniki.",
+ empty: "Nie znaleziono bezpośrednich zależności widocznych dla bieżącego konta.",
+ dependencyType: "Typ zależności",
+ sourceType: "Typ źródła",
+ link: "Łącze bazy danych",
+ remoteObject: "Obiekt zdalny: można skopiować nazwę, ale otwieranie nie jest jeszcze obsługiwane.",
+ unsupportedObject: "Otwieranie tego typu obiektu nie jest jeszcze obsługiwane. Można skopiować nazwę.",
+ navigateDiscardConfirm: "Kod źródłowy zawiera niezapisane zmiany. Odrzucić je i otworzyć powiązany obiekt?",
+ },
modelGeneration: {
title: "Generuj model",
editTemplate: "Edytuj szablon",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 47228b672a..9536ef6e59 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -65,6 +65,22 @@ const consul = {
};
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "Dependências",
+ dependents: "Objetos dependentes",
+ viewSql: "Ver SQL",
+ visibility: "Mostra as dependências diretas visíveis para a conta atual em ALL_DEPENDENCIES.",
+ packageScope: "A especificação e o corpo do pacote são combinados; os membros individuais não são diferenciados.",
+ partial: "Os resultados foram truncados; a lista pode estar incompleta.",
+ notUpdated: "Falha ao atualizar. Os resultados anteriores continuam sendo exibidos.",
+ empty: "Nenhuma dependência direta visível para a conta atual foi encontrada.",
+ dependencyType: "Tipo de dependência",
+ sourceType: "Tipo de origem",
+ link: "Link de banco de dados",
+ remoteObject: "Objeto remoto: é possível copiar o nome, mas ainda não abri-lo.",
+ unsupportedObject: "Ainda não é possível abrir este tipo de objeto. Você pode copiar o nome.",
+ navigateDiscardConfirm: "O código tem alterações não salvas. Descartá-las e abrir o objeto relacionado?",
+ },
oracleSecurity: {
directSqlNotice: "Apenas concessões diretas visíveis, não permissões efetivas da sessão nem um script completo para reprodução. Herança e concedentes estão nos detalhes de origem.",
searchOwner: "Pesquisar owner/schema",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index f2d3236821..baef966cf5 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -7,6 +7,22 @@ import { meilisearchManagementRu } from "./meilisearchManagement";
// Russian locale. Entries omitted here fall back to English at runtime.
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "Зависимости",
+ dependents: "Зависимые объекты",
+ viewSql: "Показать SQL",
+ visibility: "Показаны прямые зависимости, доступные текущей учётной записи в ALL_DEPENDENCIES.",
+ packageScope: "Спецификация и тело пакета объединены; отдельные элементы не различаются.",
+ partial: "Результаты усечены; список может быть неполным.",
+ notUpdated: "Не удалось обновить. Показаны предыдущие результаты.",
+ empty: "Прямые зависимости, доступные текущей учётной записи, не найдены.",
+ dependencyType: "Тип зависимости",
+ sourceType: "Тип источника",
+ link: "Связь с базой данных",
+ remoteObject: "Удалённый объект: можно скопировать имя, но открыть пока нельзя.",
+ unsupportedObject: "Открытие объектов этого типа пока не поддерживается. Можно скопировать имя.",
+ navigateDiscardConfirm: "В исходном коде есть несохранённые изменения. Отменить их и открыть связанный объект?",
+ },
oracleSecurity: {
directSqlNotice: "Только видимые прямые назначения, а не действующие права сеанса или полный скрипт для повторного выполнения. Наследование и выдавшие права указаны в подробностях источников.",
searchOwner: "Поиск owner/schema",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index fc36b65afe..e375c67c82 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -49,6 +49,22 @@ const damengDump = {
};
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "วัตถุที่พึ่งพา",
+ dependents: "วัตถุที่อ้างอิงวัตถุนี้",
+ viewSql: "ดู SQL",
+ visibility: "แสดงความสัมพันธ์โดยตรงที่บัญชีปัจจุบันมองเห็นใน ALL_DEPENDENCIES",
+ packageScope: "แสดงข้อกำหนดและเนื้อหาแพ็กเกจรวมกัน โดยไม่แยกสมาชิกแต่ละรายการ",
+ partial: "ผลลัพธ์ถูกตัดทอน รายการอาจไม่ครบถ้วน",
+ notUpdated: "รีเฟรชไม่สำเร็จ ยังคงแสดงผลลัพธ์ก่อนหน้า",
+ empty: "ไม่พบความสัมพันธ์โดยตรงที่บัญชีปัจจุบันมองเห็น",
+ dependencyType: "ประเภทความสัมพันธ์",
+ sourceType: "ประเภทต้นทาง",
+ link: "ลิงก์ฐานข้อมูล",
+ remoteObject: "วัตถุระยะไกล: คัดลอกชื่อได้ แต่ยังไม่รองรับการเปิด",
+ unsupportedObject: "ยังไม่รองรับการเปิดวัตถุประเภทนี้ คุณสามารถคัดลอกชื่อได้",
+ navigateDiscardConfirm: "ซอร์สมีการเปลี่ยนแปลงที่ยังไม่บันทึก ต้องการละทิ้งและเปิดวัตถุที่เกี่ยวข้องหรือไม่",
+ },
oracleForeignKey: {
resultTitle: "ผลลัพธ์การดำเนินการ Foreign Key",
executionFailed: "การดำเนินการ Foreign Key ไม่ได้เสร็จสมบูรณ์ กรุณาตรวจสอบผลลัพธ์แต่ละรายการและสถานะฐานข้อมูล",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 05491a2edb..80cd0b211b 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -61,6 +61,22 @@ const consul = {
};
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "Bağımlılıklar",
+ dependents: "Bağımlı nesneler",
+ viewSql: "SQL'i göster",
+ visibility: "ALL_DEPENDENCIES içinde geçerli hesabın görebildiği doğrudan bağımlılıkları gösterir.",
+ packageScope: "Paket bildirimi ve gövdesi birlikte gösterilir; tek tek üyeler ayrılmaz.",
+ partial: "Sonuçlar kesildi; liste eksik olabilir.",
+ notUpdated: "Yenileme başarısız. Önceki sonuçlar gösteriliyor.",
+ empty: "Geçerli hesabın görebildiği doğrudan bağımlılık bulunamadı.",
+ dependencyType: "Bağımlılık türü",
+ sourceType: "Kaynak türü",
+ link: "Veritabanı bağlantısı",
+ remoteObject: "Uzak nesne: adı kopyalanabilir, ancak henüz açılamaz.",
+ unsupportedObject: "Bu nesne türü henüz açılamaz. Adını kopyalayabilirsiniz.",
+ navigateDiscardConfirm: "Kaynakta kaydedilmemiş değişiklikler var. Değişiklikler atılıp ilgili nesne açılsın mı?",
+ },
sidebarMenu,
oracleIndex: { mixedDraft: "Oracle indeks değişikliklerini diğer tablo yapısı değişikliklerinden ayrı uygulayın." },
pluginPlatform: {
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index d61c1f3ef3..3f8fa725ae 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -10,6 +10,22 @@ import { mongodbDatabaseDumpZhCN as mongoDump } from "./mongodbDatabaseDump";
import { damengDumpZhCN as damengDump } from "./damengDump";
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "依赖对象",
+ dependents: "被依赖对象",
+ viewSql: "查看 SQL",
+ visibility: "仅显示 ALL_DEPENDENCIES 中当前账号可见的直接依赖。",
+ packageScope: "包规范与包体合并显示;不区分包内成员。",
+ partial: "结果已截断,列表可能不完整。",
+ notUpdated: "刷新失败,仍显示上次结果。",
+ empty: "未找到当前账号可见的直接依赖。",
+ dependencyType: "依赖类型",
+ sourceType: "来源类型",
+ link: "数据库链接",
+ remoteObject: "远程对象:可复制名称,暂不支持打开。",
+ unsupportedObject: "此对象类型暂不支持打开,可复制名称。",
+ navigateDiscardConfirm: "当前源码有未保存的修改。放弃修改并打开关联对象?",
+ },
oracleSecurity: {
directSqlNotice: "仅显示可见的直接授权,不代表会话有效权限,也不是完整重放脚本。继承及授予者见来源详情。",
searchOwner: "搜索 owner/schema",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 31f1c1f12d..8e56939993 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -66,6 +66,22 @@ const consul = {
};
export default withEnglishFallback({
+ objectDependencies: {
+ dependencies: "依賴物件",
+ dependents: "被依賴物件",
+ viewSql: "檢視 SQL",
+ visibility: "僅顯示 ALL_DEPENDENCIES 中目前帳號可見的直接依賴。",
+ packageScope: "套件規格與本體合併顯示;不區分套件內成員。",
+ partial: "結果已截斷,清單可能不完整。",
+ notUpdated: "重新整理失敗,仍顯示上次結果。",
+ empty: "找不到目前帳號可見的直接依賴。",
+ dependencyType: "依賴類型",
+ sourceType: "來源類型",
+ link: "資料庫連結",
+ remoteObject: "遠端物件:可複製名稱,尚不支援開啟。",
+ unsupportedObject: "尚不支援開啟此物件類型,可複製名稱。",
+ navigateDiscardConfirm: "原始碼有未儲存的變更。要捨棄變更並開啟相關物件嗎?",
+ },
oracleSecurity: {
directSqlNotice: "僅顯示可見的直接授權,不代表工作階段有效權限,也不是完整重播指令碼。繼承及授予者請見來源詳情。",
searchOwner: "搜尋 owner/schema",
diff --git a/apps/desktop/src/lib/__tests__/database/databaseObjectDependencies.spec.ts b/apps/desktop/src/lib/__tests__/database/databaseObjectDependencies.spec.ts
index e11edcbfce..429cea6f66 100644
--- a/apps/desktop/src/lib/__tests__/database/databaseObjectDependencies.spec.ts
+++ b/apps/desktop/src/lib/__tests__/database/databaseObjectDependencies.spec.ts
@@ -12,12 +12,16 @@ const node = (overrides: Record<string, unknown> = {}) => ({
describe("database dependency providers", () => {
it("resolves only providers registered for the requested database", () => {
expect(databaseDependencyProviderFor("xugu")?.databaseType).toBe("xugu");
+ expect(databaseDependencyProviderFor("oracle")?.databaseType).toBe("oracle");
+ expect(databaseDependencyProviderFor("oceanbase-oracle")?.databaseType).toBe("oracle");
expect(databaseDependencyProviderFor("postgres")).toBeNull();
expect(databaseDependencyProviderFor(undefined)).toBeNull();
});
it("keeps the UI capability check database-agnostic", () => {
expect(canViewDatabaseObjectDependencies("xugu", node())).toBe(true);
+ expect(canViewDatabaseObjectDependencies("oracle", node({ type: "procedure" }))).toBe(true);
+ expect(canViewDatabaseObjectDependencies("oceanbase-oracle", node({ type: "package" }))).toBe(true);
expect(canViewDatabaseObjectDependencies("postgres", node())).toBe(false);
});
diff --git a/apps/desktop/src/lib/__tests__/database/objectDependencyDetails.spec.ts b/apps/desktop/src/lib/__tests__/database/objectDependencyDetails.spec.ts
new file mode 100644
index 0000000000..b3fa989076
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/database/objectDependencyDetails.spec.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+import { isObjectDependencySection, objectDependencyNavigation, objectDependencyRows, objectDependencySql, objectDependencyTarget, type ObjectDependencyRow } from "@/lib/database/objectDependencyDetails";
+import { oracleObjectDependenciesSql } from "@/lib/database/oracleObjectDependencies";
+import { normalizeOracleNavigationTarget, sqlObjectNavigationContextTarget, sqlObjectNavigationSourceKind } from "@/lib/sql/sqlNavigation";
+import type { QueryResult, QueryTab } from "@/types/database";
+
+const details = { connectionId: "original", database: "ORCL", schema: "Mixed.Schema", name: "Mixed.P", objectType: "PROCEDURE" as const, section: "dependencies" as const };
+const row: ObjectDependencyRow = { direction: "DEPENDS_ON", name: "Mixed.Table", schema: "Other.Schema", type: "TABLE", dependencyType: "HARD", link: "", sourceType: "PROCEDURE" };
+
+describe("object dependency details", () => {
+ it("keeps captured identity and reuses the provider SQL without changing quoting or package scope", () => {
+ const target = objectDependencyTarget(details, "oceanbase-oracle")!;
+ expect(target).toEqual({ connectionId: "original", database: "ORCL", schema: "Mixed.Schema", name: "Mixed.P", objectType: "PROCEDURE" });
+ expect(objectDependencySql(target)).toBe(oracleObjectDependenciesSql({ schema: details.schema, objectName: details.name, objectType: "PROCEDURE" }));
+ expect(objectDependencyTarget({ ...details, objectType: "PACKAGE_BODY" }, "oracle")?.objectType).toBe("PACKAGE");
+ expect(objectDependencyTarget(details, "xugu")).toBeUndefined();
+ expect(objectDependencyTarget({ ...details, objectType: "TYPE" }, "oracle")).toBeUndefined();
+ });
+
+ it("maps both directions from column names, retaining package body origin and nullable links", () => {
+ const result: QueryResult = {
+ columns: ["referenced_name", "direction", "object_owner", "object_name", "object_type", "referenced_owner", "referenced_type", "dependency_type", "referenced_link_name"],
+ rows: [
+ ["Mixed.Table", "DEPENDS_ON", "APP", "PK", "PACKAGE BODY", "Other.Schema", "TABLE", "HARD", null],
+ ["PK", "REFERENCED_BY", "CALLER", "Use.PK", "FUNCTION", "APP", "PACKAGE", "REF", null],
+ ],
+ affected_rows: 0,
+ execution_time_ms: 1,
+ };
+ expect(objectDependencyRows(result)).toEqual([
+ { ...row, sourceType: "PACKAGE BODY" },
+ { direction: "REFERENCED_BY", name: "Use.PK", schema: "CALLER", type: "FUNCTION", dependencyType: "REF", sourceType: "FUNCTION", link: "" },
+ ]);
+ expect(() => objectDependencyRows({ ...result, columns: [] })).toThrow("column layout");
+ expect(() => objectDependencyRows({ ...result, rows: [["x", "OTHER"]] })).toThrow("direction");
+ });
+
+ it.each(["TYPE", "TYPE BODY", "NON-EXISTENT", "UNKNOWN"])("preserves %s without incorrectly opening a table", (type) => {
+ expect(objectDependencyNavigation({ ...row, type })).toBeUndefined();
+ });
+
+ it("does not open DBLink objects locally and preserves exact quoted names for supported source kinds", () => {
+ expect(objectDependencyNavigation({ ...row, link: "REMOTE" })).toBeUndefined();
+ expect(objectDependencyNavigation(row)).toEqual({ name: row.name, schema: row.schema, type: "table", nameQuoted: true, schemaQuoted: true });
+ expect(sqlObjectNavigationContextTarget(objectDependencyNavigation(row)!, { ...details, catalog: "Original.Catalog" })).toEqual({ connectionId: "original", database: "ORCL", catalog: "Original.Catalog", schema: "Other.Schema", tableName: "Mixed.Table", tableType: "TABLE" });
+ for (const [type, sourceKind] of [
+ ["PACKAGE", "PACKAGE"],
+ ["PACKAGE BODY", "PACKAGE_BODY"],
+ ["SEQUENCE", "SEQUENCE"],
+ ["PROCEDURE", "PROCEDURE"],
+ ["FUNCTION", "FUNCTION"],
+ ["TRIGGER", "TRIGGER"],
+ ["VIEW", "VIEW"],
+ ["MATERIALIZED VIEW", "MATERIALIZED_VIEW"],
+ ] as const) {
+ const navigation = normalizeOracleNavigationTarget(objectDependencyNavigation({ ...row, type })!);
+ expect(sqlObjectNavigationSourceKind(navigation)).toBe(sourceKind);
+ expect(navigation.name).toBe(row.name);
+ expect(navigation.schema).toBe(row.schema);
+ }
+ });
+
+ it("blocks hidden-source execution only while the captured context still matches", () => {
+ const tab = { ...details, id: "source", title: "source", sql: "draft", mode: "query", isExecuting: false, isExplaining: false, isCancelling: false, objectDetails: { ...details } } as QueryTab;
+ expect(isObjectDependencySection(tab)).toBe(true);
+ expect(isObjectDependencySection({ ...tab, schema: "DIFFERENT" })).toBe(false);
+ expect(isObjectDependencySection({ ...tab, connectionId: "new" })).toBe(false);
+ expect(isObjectDependencySection({ ...tab, objectDetails: { ...details, section: "source" } })).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/database/oracleObjectDependencies.spec.ts b/apps/desktop/src/lib/__tests__/database/oracleObjectDependencies.spec.ts
new file mode 100644
index 0000000000..6cb32952bc
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/database/oracleObjectDependencies.spec.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+import { oracleDependencyProvider, oracleObjectDependenciesSql } from "@/lib/database/oracleObjectDependencies";
+
+const node = (overrides: Record<string, unknown> = {}) => ({ type: "procedure" as const, schema: "APP", objectName: "RUN_JOB", label: "RUN_JOB", ...overrides });
+
+describe("Oracle object dependencies", () => {
+ it("queries both direct directions and preserves raw dictionary details", () => {
+ const sql = oracleDependencyProvider.buildQuery(node());
+ expect(sql).toContain("'DEPENDS_ON' AS DIRECTION");
+ expect(sql).toContain("'REFERENCED_BY' AS DIRECTION");
+ expect(sql).toContain("d.TYPE = 'PROCEDURE'");
+ expect(sql).toContain("d.REFERENCED_TYPE = 'PROCEDURE'");
+ for (const column of ["OBJECT_OWNER", "OBJECT_NAME", "OBJECT_TYPE", "REFERENCED_OWNER", "REFERENCED_NAME", "REFERENCED_TYPE", "DEPENDENCY_TYPE", "REFERENCED_LINK_NAME"]) {
+ expect(sql).toContain(column);
+ }
+ expect(sql).toContain("FROM ALL_DEPENDENCIES d");
+ expect(sql).not.toContain("DBA_DEPENDENCIES");
+ expect(sql).not.toContain("Package/body scope");
+ });
+
+ it("matches local reverse references without hiding remote outbound dependencies", () => {
+ const sql = oracleDependencyProvider.buildQuery(node())!;
+ const [dependsOn, referencedBy] = sql.split("UNION ALL");
+ expect(dependsOn).not.toContain("REFERENCED_LINK_NAME IS NULL");
+ expect(dependsOn).toContain("d.REFERENCED_LINK_NAME");
+ expect(referencedBy).toContain("d.REFERENCED_LINK_NAME IS NULL");
+ });
+
+ it("uses the owning package scope for members and exposes it in the title", () => {
+ const member = node({ type: "function", objectName: "CALC", parentType: "package", parentName: "PAYROLL", parentSchema: "HR" });
+ expect(oracleDependencyProvider.targetLabel?.(member)).toEqual({ name: "HR.PAYROLL", packageScope: true });
+ const sql = oracleDependencyProvider.buildQuery(member)!;
+ expect(sql).toContain("'PAYROLL' AS TARGET_NAME");
+ expect(sql).toContain("d.TYPE IN ('PACKAGE', 'PACKAGE BODY')");
+ expect(sql).not.toContain("'CALC' AS TARGET_NAME");
+ expect(sql).toContain("Package/body scope, not member-level dependencies");
+ });
+
+ it("keeps package and body types distinct in package-scoped results", () => {
+ const sql = oracleObjectDependenciesSql({ schema: "HR", objectName: "PAYROLL", objectType: "PACKAGE" });
+ expect(sql).toContain("d.TYPE IN ('PACKAGE', 'PACKAGE BODY')");
+ expect(sql).toContain("d.REFERENCED_TYPE IN ('PACKAGE', 'PACKAGE BODY')");
+ expect(sql).toContain("d.TYPE AS OBJECT_TYPE");
+ });
+
+ it("escapes literals and rejects incomplete or unsupported tree nodes", () => {
+ expect(oracleObjectDependenciesSql({ schema: "O'BRIEN", objectName: "R'UN", objectType: "FUNCTION" })).toContain("'O''BRIEN'");
+ expect(oracleDependencyProvider.buildQuery(node({ schema: undefined }))).toBeNull();
+ expect(oracleDependencyProvider.supports(node({ type: "procedure", parentType: "package", parentName: "PKG" }))).toBe(false);
+ expect(oracleDependencyProvider.supports(node({ type: "procedure", parentType: "package", parentName: "PKG", parentSchema: undefined }))).toBe(false);
+ expect(oracleDependencyProvider.supports(node({ type: "trigger" }))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/lib/app/openTabsPersistence.ts b/apps/desktop/src/lib/app/openTabsPersistence.ts
index 5258bad2f5..bc49e723e9 100644
--- a/apps/desktop/src/lib/app/openTabsPersistence.ts
+++ b/apps/desktop/src/lib/app/openTabsPersistence.ts
@@ -72,6 +72,7 @@ export interface SavedOpenTab {
databaseSearchState?: QueryTab["databaseSearchState"];
objectBrowser?: QueryTab["objectBrowser"];
objectSource?: QueryTab["objectSource"];
+ objectDetails?: QueryTab["objectDetails"];
sourceView?: boolean;
ddlViewer?: QueryTab["ddlViewer"];
tableComment?: QueryTab["tableComment"];
@@ -222,6 +223,7 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
...(tab.databaseSearchState ? { databaseSearchState: tab.databaseSearchState } : {}),
objectBrowser: tab.objectBrowser,
objectSource: tab.objectSource,
+ ...(tab.objectDetails ? { objectDetails: { ...tab.objectDetails } } : {}),
...(tab.sourceView ? { sourceView: true } : {}),
...(tab.ddlViewer ? { ddlViewer: { ...tab.ddlViewer } } : {}),
...(tab.tableComment !== undefined ? { tableComment: tab.tableComment } : {}),
diff --git a/apps/desktop/src/lib/database/databaseObjectDependencies.ts b/apps/desktop/src/lib/database/databaseObjectDependencies.ts
index 8c84486fa0..72b71b1f1c 100644
--- a/apps/desktop/src/lib/database/databaseObjectDependencies.ts
+++ b/apps/desktop/src/lib/database/databaseObjectDependencies.ts
@@ -1,12 +1,13 @@
import type { DatabaseType, TreeNode } from "@/types/database";
import { xuguDependencyProvider } from "@/lib/database/xuguObjectDependencies";
+import { oracleDependencyProvider } from "@/lib/database/oracleObjectDependencies";
/**
* The subset of a sidebar node needed by a database dependency provider.
* Keeping this contract small lets providers remain independent of Vue state
* and makes it possible to test them without constructing a full tree node.
*/
-export type DependencyTreeNode = Pick<TreeNode, "type" | "schema" | "objectName" | "label" | "parentType" | "parentName">;
+export type DependencyTreeNode = Pick<TreeNode, "type" | "schema" | "objectName" | "label" | "parentType" | "parentName" | "parentSchema">;
/**
* Database-specific dependency inspection contract.
@@ -18,10 +19,13 @@ export interface DatabaseDependencyProvider {
readonly databaseType: DatabaseType;
supports(node: DependencyTreeNode): boolean;
buildQuery(node: DependencyTreeNode): string | null;
+ targetLabel?(node: DependencyTreeNode): { name: string; packageScope?: boolean } | null;
}
const PROVIDERS: Partial<Record<DatabaseType, DatabaseDependencyProvider>> = {
xugu: xuguDependencyProvider,
+ oracle: oracleDependencyProvider,
+ "oceanbase-oracle": oracleDependencyProvider,
};
export function databaseDependencyProviderFor(databaseType?: DatabaseType): DatabaseDependencyProvider | null {
diff --git a/apps/desktop/src/lib/database/objectDependencyDetails.ts b/apps/desktop/src/lib/database/objectDependencyDetails.ts
new file mode 100644
index 0000000000..d7706268a6
--- /dev/null
+++ b/apps/desktop/src/lib/database/objectDependencyDetails.ts
@@ -0,0 +1,75 @@
+import type { DatabaseType, QueryResult, QueryTab } from "@/types/database";
+import type { SqlObjectNavigationTarget, SqlObjectNavigationType } from "@/lib/sql/sqlNavigation";
+import { oracleObjectDependenciesSql, type OracleDependencyObjectType } from "@/lib/database/oracleObjectDependencies";
+
+export type ObjectDetails = NonNullable<QueryTab["objectDetails"]>;
+export type ObjectDetailsSection = ObjectDetails["section"];
+export function isObjectDependencySection(tab: QueryTab): boolean {
+ const details = tab.objectDetails;
+ return !!details && details.section !== "source" && details.connectionId === tab.connectionId && details.database === tab.database && details.schema === (tab.schema || tab.database) && (details.catalog || "") === (tab.catalog || "");
+}
+export interface ObjectDependencyTarget extends Omit<ObjectDetails, "section" | "objectType"> {
+ objectType: OracleDependencyObjectType;
+}
+
+export interface ObjectDependencyRow {
+ direction: "DEPENDS_ON" | "REFERENCED_BY";
+ name: string;
+ schema: string;
+ type: string;
+ dependencyType: string;
+ link: string;
+ sourceType: string;
+}
+
+export function objectDependencyTarget(details: QueryTab["objectDetails"], databaseType?: DatabaseType): ObjectDependencyTarget | undefined {
+ if (!details || (databaseType !== "oracle" && databaseType !== "oceanbase-oracle")) return;
+ const type = details.objectType === "PACKAGE_BODY" ? "PACKAGE" : details.objectType;
+ if (type !== "PROCEDURE" && type !== "FUNCTION" && type !== "PACKAGE") return;
+ const { section: _section, ...identity } = details;
+ return { ...identity, objectType: type };
+}
+
+export function objectDependencySql(target: ObjectDependencyTarget): string {
+ return oracleObjectDependenciesSql({ schema: target.schema, objectName: target.name, objectType: target.objectType });
+}
+
+export function objectDependencyRows(result: QueryResult): ObjectDependencyRow[] {
+ const indexes = new Map(result.columns.map((name, index) => [name.toUpperCase(), index]));
+ const required = ["DIRECTION", "OBJECT_OWNER", "OBJECT_NAME", "OBJECT_TYPE", "REFERENCED_OWNER", "REFERENCED_NAME", "REFERENCED_TYPE", "DEPENDENCY_TYPE", "REFERENCED_LINK_NAME"];
+ if (required.some((name) => !indexes.has(name))) throw new Error("The dependency query returned an unexpected column layout.");
+ return result.rows.map((row) => {
+ const value = (name: string) => String(row[indexes.get(name)!] ?? "");
+ const direction = value("DIRECTION");
+ if (direction !== "DEPENDS_ON" && direction !== "REFERENCED_BY") throw new Error("The dependency query returned an unknown direction.");
+ const prefix = direction === "DEPENDS_ON" ? "REFERENCED_" : "OBJECT_";
+ return {
+ direction,
+ name: value(prefix + "NAME"),
+ schema: value(prefix + "OWNER"),
+ type: value(prefix + "TYPE"),
+ dependencyType: value("DEPENDENCY_TYPE"),
+ link: value("REFERENCED_LINK_NAME"),
+ sourceType: value("OBJECT_TYPE"),
+ };
+ });
+}
+
+/** Strict dictionary mapping: unknown/remote objects must never fall back to TABLE. */
+export function objectDependencyNavigation(row: ObjectDependencyRow): SqlObjectNavigationTarget | undefined {
+ if (row.link || !row.name || !row.schema) return;
+ const types: Partial<Record<string, SqlObjectNavigationType>> = {
+ TABLE: "table",
+ VIEW: "view",
+ "MATERIALIZED VIEW": "materialized_view",
+ PROCEDURE: "procedure",
+ FUNCTION: "function",
+ PACKAGE: "package",
+ "PACKAGE BODY": "package_body",
+ SEQUENCE: "sequence",
+ TRIGGER: "trigger",
+ };
+ const type = types[row.type];
+ if (!type) return;
+ return { name: row.name, schema: row.schema, type, nameQuoted: true, schemaQuoted: true };
+}
diff --git a/apps/desktop/src/lib/database/oracleObjectDependencies.ts b/apps/desktop/src/lib/database/oracleObjectDependencies.ts
new file mode 100644
index 0000000000..bcb8ca4da6
--- /dev/null
+++ b/apps/desktop/src/lib/database/oracleObjectDependencies.ts
@@ -0,0 +1,84 @@
+import type { TreeNodeType } from "@/types/database";
+import type { DatabaseDependencyProvider, DependencyTreeNode } from "@/lib/database/databaseObjectDependencies";
+
+export type OracleDependencyObjectType = "PROCEDURE" | "FUNCTION" | "PACKAGE";
+
+/** Direct Oracle dictionary dependency rows, visible to the current account. */
+export function oracleObjectDependenciesSql(options: { schema: string; objectName: string; objectType: OracleDependencyObjectType }): string {
+ const owner = quoteSqlString(options.schema);
+ const name = quoteSqlString(options.objectName);
+ const typeFilter = options.objectType === "PACKAGE" ? "d.TYPE IN ('PACKAGE', 'PACKAGE BODY')" : `d.TYPE = '${options.objectType}'`;
+ const referenceTypeFilter = options.objectType === "PACKAGE" ? "d.REFERENCED_TYPE IN ('PACKAGE', 'PACKAGE BODY')" : `d.REFERENCED_TYPE = '${options.objectType}'`;
+ const scopeNote = options.objectType === "PACKAGE" ? " Package/body scope, not member-level dependencies." : "";
+ return `-- Direct dependencies and reverse references visible to the current account via ALL_DEPENDENCIES. Dynamic SQL references may be absent.${scopeNote}
+SELECT 'DEPENDS_ON' AS DIRECTION,
+ ${owner} AS TARGET_OWNER,
+ ${name} AS TARGET_NAME,
+ '${options.objectType}' AS TARGET_TYPE,
+ d.OWNER AS OBJECT_OWNER,
+ d.NAME AS OBJECT_NAME,
+ d.TYPE AS OBJECT_TYPE,
+ d.REFERENCED_OWNER,
+ d.REFERENCED_NAME,
+ d.REFERENCED_TYPE,
+ d.DEPENDENCY_TYPE,
+ d.REFERENCED_LINK_NAME
+FROM ALL_DEPENDENCIES d
+WHERE d.OWNER = ${owner}
+ AND d.NAME = ${name}
+ AND ${typeFilter}
+UNION ALL
+SELECT 'REFERENCED_BY' AS DIRECTION,
+ ${owner} AS TARGET_OWNER,
+ ${name} AS TARGET_NAME,
+ '${options.objectType}' AS TARGET_TYPE,
+ d.OWNER AS OBJECT_OWNER,
+ d.NAME AS OBJECT_NAME,
+ d.TYPE AS OBJECT_TYPE,
+ d.REFERENCED_OWNER,
+ d.REFERENCED_NAME,
+ d.REFERENCED_TYPE,
+ d.DEPENDENCY_TYPE,
+ d.REFERENCED_LINK_NAME
+FROM ALL_DEPENDENCIES d
+WHERE d.REFERENCED_OWNER = ${owner}
+ AND d.REFERENCED_NAME = ${name}
+ AND ${referenceTypeFilter}
+ AND d.REFERENCED_LINK_NAME IS NULL
+ORDER BY 1, 5, 6, 7`;
+}
+
+export function oracleTarget(node: DependencyTreeNode): { schema: string; name: string; type: OracleDependencyObjectType; packaged: boolean } | null {
+ const member = node.parentType === "package" && (node.type === "procedure" || node.type === "function");
+ const type = member || node.type === "package" ? "PACKAGE" : oracleTypeForTreeNode(node.type);
+ const schema = member ? node.parentSchema : node.schema;
+ const name = member ? node.parentName : node.objectName || node.label;
+ if (!schema || !name || !type) return null;
+ return { schema, name, type, packaged: member || type === "PACKAGE" };
+}
+
+function oracleTypeForTreeNode(type: TreeNodeType): OracleDependencyObjectType | null {
+ if (type === "procedure") return "PROCEDURE";
+ if (type === "function") return "FUNCTION";
+ if (type === "package") return "PACKAGE";
+ return null;
+}
+
+export const oracleDependencyProvider: DatabaseDependencyProvider = {
+ databaseType: "oracle",
+ supports(node) {
+ return oracleTarget(node) !== null;
+ },
+ buildQuery(node) {
+ const target = oracleTarget(node);
+ return target ? oracleObjectDependenciesSql({ schema: target.schema, objectName: target.name, objectType: target.type }) : null;
+ },
+ targetLabel(node) {
+ const target = oracleTarget(node);
+ return target ? { name: `${target.schema}.${target.name}`, packageScope: target.packaged } : null;
+ },
+};
+
+function quoteSqlString(value: string): string {
+ return `'${value.replaceAll("'", "''")}'`;
+}
diff --git a/apps/desktop/src/lib/sql/sqlNavigation.ts b/apps/desktop/src/lib/sql/sqlNavigation.ts
index d5078187f0..fe8dc9bacc 100644
--- a/apps/desktop/src/lib/sql/sqlNavigation.ts
+++ b/apps/desktop/src/lib/sql/sqlNavigation.ts
@@ -2,7 +2,7 @@
* Utilities for SQL identifier navigation (Ctrl/Cmd + click on table/column names).
*/
-import type { ObjectSourceKind } from "@/types/database";
+import type { ObjectSourceKind, QueryTab } from "@/types/database";
const SQL_KEYWORDS_SET = new Set([
"select",
@@ -135,7 +135,7 @@ export interface ExtractedSqlIdentifierPart {
quoted: boolean;
}
-export type SqlObjectNavigationType = "table" | "view" | "materialized_view" | "procedure" | "function" | "package" | "trigger";
+export type SqlObjectNavigationType = "table" | "view" | "materialized_view" | "procedure" | "function" | "package" | "package_body" | "sequence" | "trigger";
/**
* Semantic role of a Ctrl/Cmd+clicked identifier for navigation.
@@ -163,6 +163,20 @@ export interface SqlObjectNavigationTarget {
parentSchemaQuoted?: boolean;
}
+export type SqlObjectNavigationContext = Pick<QueryTab, "connectionId" | "database" | "schema" | "catalog" | "tableMeta">;
+
+/** Resolve a structured object against its captured origin, without reparsing quoted dots. */
+export function sqlObjectNavigationContextTarget(table: SqlObjectNavigationTarget, context: SqlObjectNavigationContext) {
+ return {
+ connectionId: context.connectionId,
+ database: table.database || context.database,
+ catalog: context.tableMeta?.catalog || context.catalog,
+ schema: table.schema || context.schema,
+ tableName: table.name,
+ tableType: table.type ? sqlObjectNavigationTableType(table) : undefined,
+ };
+}
+
/**
* Fully resolved click identity: parts, quotes, and navigation role.
* Built before any remote metadata call so call-site vs table and package vs schema
@@ -208,11 +222,11 @@ export function sqlObjectNavigationTarget(table: SqlObjectNavigationTarget): Sql
}
export function isSqlObjectNavigationRoutineType(type?: SqlObjectNavigationType): boolean {
- return type === "procedure" || type === "function" || type === "package" || type === "trigger";
+ return type === "procedure" || type === "function" || type === "package" || type === "package_body" || type === "sequence" || type === "trigger";
}
export function sqlObjectHoverDetail(table: SqlObjectNavigationTarget): string {
- const objectType = table.type === "materialized_view" ? "materialized view" : table.type === "view" ? "view" : table.type === "procedure" ? "procedure" : table.type === "function" ? "function" : table.type === "package" ? "package" : table.type === "trigger" ? "trigger" : "table";
+ const objectType = table.type === "materialized_view" ? "materialized view" : table.type === "package_body" ? "package body" : (table.type ?? "table");
if (table.parentName) {
const owner = table.parentSchema ? `${table.parentSchema}.${table.parentName}` : table.parentName;
return `${objectType} in ${owner}`;
@@ -246,6 +260,10 @@ export function sqlObjectNavigationSourceKind(table: SqlObjectNavigationTarget):
return "FUNCTION";
case "package":
return "PACKAGE";
+ case "package_body":
+ return "PACKAGE_BODY";
+ case "sequence":
+ return "SEQUENCE";
case "trigger":
return "TRIGGER";
default:
diff --git a/apps/desktop/src/lib/tabs/contentSurfaceEvents.ts b/apps/desktop/src/lib/tabs/contentSurfaceEvents.ts
index 332f64e36c..40b6d9af2e 100644
--- a/apps/desktop/src/lib/tabs/contentSurfaceEvents.ts
+++ b/apps/desktop/src/lib/tabs/contentSurfaceEvents.ts
@@ -34,6 +34,7 @@ export const contentSurfaceEventNames = [
"viewTableDdl",
"editTableStructure",
"openObjectSource",
+ "openDependencyObject",
"openObjectTable",
"openDatabaseSearchTarget",
"objectSchemaChange",
diff --git a/apps/desktop/src/stores/__tests__/queryStore.objectDetails.spec.ts b/apps/desktop/src/stores/__tests__/queryStore.objectDetails.spec.ts
new file mode 100644
index 0000000000..63f6d9ce7e
--- /dev/null
+++ b/apps/desktop/src/stores/__tests__/queryStore.objectDetails.spec.ts
@@ -0,0 +1,109 @@
+import { computed, ref } from "vue";
+import { createPinia, disposePinia, setActivePinia, type Pinia } from "pinia";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useConnectionStore } from "@/stores/connectionStore";
+import { useQueryStore } from "@/stores/queryStore";
+import { useSettingsStore } from "@/stores/settingsStore";
+import { useSqlExecution } from "@/composables/useSqlExecution";
+import { serializeOpenTabs, restoreOpenTabsState } from "@/lib/app/openTabsPersistence";
+import type { TabOutputView } from "@/types/database";
+
+const backend = vi.hoisted(() => ({
+ getObjectSource: vi.fn(),
+ buildEditableObjectSource: vi.fn(async (input: { source: string }) => input.source),
+ executeQuery: vi.fn(),
+ executeMulti: vi.fn(),
+ prepareQueryPaginationExecutionPlan: vi.fn(async (input: { sql: string }) => ({ sqlToExecute: input.sql })),
+ checkConnectionHealth: vi.fn(async () => undefined),
+ saveOpenTabsState: vi.fn(async () => {}),
+ saveHistory: vi.fn(async () => {}),
+ saveEditorSettings: vi.fn(async () => {}),
+ closeQuerySession: vi.fn(async () => {}),
+ closeClientConnectionSession: vi.fn(async () => {}),
+}));
+vi.mock("@/lib/backend/api", async (original) => ({ ...(await original<typeof import("@/lib/backend/api")>()), ...backend }));
+vi.mock("vue-i18n", async (original) => ({ ...(await original<typeof import("vue-i18n")>()), useI18n: () => ({ t: (key: string) => key }) }));
+let pinia: Pinia;
+const options = { connectionId: "oracle-1", database: "ORCL", schema: "APP", catalog: "CAT", title: "Source - P", request: { name: "P", objectType: "PROCEDURE" as const } };
+beforeEach(() => {
+ vi.clearAllMocks();
+ backend.getObjectSource.mockReset();
+ pinia = createPinia();
+ setActivePinia(pinia);
+ const connections = useConnectionStore();
+ connections.connections = [{ id: "oracle-1", name: "oracle", db_type: "oracle", host: "localhost", port: 1521, username: "test", password: "" }];
+ connections.connectedIds.add("oracle-1");
+ backend.executeQuery.mockResolvedValue({ columns: [], rows: [], affected_rows: 0, execution_time_ms: 1 });
+ backend.executeMulti.mockResolvedValue([{ columns: ["N"], rows: [[1]], affected_rows: 0, execution_time_ms: 1 }]);
+});
+afterEach(() => {
+ disposePinia(pinia);
+ setActivePinia(undefined);
+});
+
+describe("object detail identity through the real source store", () => {
+ it("keeps read-only identity after sourceLoad is cleared, and persists only identity and section", async () => {
+ backend.getObjectSource.mockResolvedValue({ name: "P", object_type: "PROCEDURE", source: "read-only definition", editable: false });
+ const store = useQueryStore();
+ const id = store.openObjectSourceTabPending({ ...options, initialSection: "dependencies" });
+ const tab = store.tabs.find((item) => item.id === id)!;
+ expect(tab.objectDetails?.section).toBe("dependencies");
+ await vi.waitFor(() => expect(tab.sourceLoad).toBeUndefined());
+ expect(tab.objectSource).toBeUndefined();
+ expect(tab.objectDetails).toEqual({ connectionId: "oracle-1", database: "ORCL", schema: "APP", catalog: "CAT", name: "P", objectType: "PROCEDURE", section: "dependencies" });
+ const restored = restoreOpenTabsState(JSON.stringify(serializeOpenTabs([tab])), id).tabs[0]!;
+ expect(restored.objectDetails).toEqual(tab.objectDetails);
+ expect(restored.sourceLoad).toBeUndefined();
+ expect(restored.result).toBeUndefined();
+ store.duplicateTab(id);
+ const duplicate = store.tabs.find((item) => item.id !== id)!;
+ expect(duplicate.objectDetails).toEqual(tab.objectDetails);
+ duplicate.objectDetails!.section = "source";
+ expect(tab.objectDetails?.section).toBe("dependencies");
+ });
+
+ it("keeps a dirty resolved function when a procedure fallback merges into its tab", async () => {
+ const store = useQueryStore();
+ const id = store.openObjectSourceTab({ ...options, sql: "original", objectSource: { schema: "APP", name: "P", objectType: "FUNCTION" } });
+ store.updateSql(id, "dirty function draft");
+ backend.getObjectSource.mockImplementation(async (_connection, _database, _schema, _name, kind) => {
+ return { name: "P", object_type: kind, source: kind === "PROCEDURE" ? "" : "fresh function source" };
+ });
+ store.openObjectSourceTabPending({ ...options, initialSection: "dependents" });
+ await vi.waitFor(() => expect(store.tabs).toHaveLength(1));
+ expect(store.tabs[0]?.id).toBe(id);
+ expect(store.tabs[0]?.sql).toBe("dirty function draft");
+ expect(store.tabs[0]?.objectDetails).toMatchObject({ objectType: "FUNCTION", section: "dependents" });
+ });
+
+ it("retains identity on source failure and deduplicates requests without losing the selected section", async () => {
+ backend.getObjectSource.mockRejectedValue(new Error("source denied"));
+ const store = useQueryStore();
+ const id = store.openObjectSourceTabPending(options);
+ await vi.waitFor(() => expect(store.tabs[0]?.sourceLoad?.error).toBeTruthy());
+ expect(store.tabs[0]?.objectDetails?.section).toBe("source");
+ expect(store.openObjectSourceTabPending({ ...options, initialSection: "dependents" })).toBe(id);
+ expect(store.tabs).toHaveLength(1);
+ expect(store.tabs[0]?.objectDetails?.section).toBe("dependents");
+ });
+
+ it("blocks new execution/explain while source is hidden and resumes the normal pipeline on return", async () => {
+ const store = useQueryStore();
+ const connections = useConnectionStore();
+ const id = store.createTab("oracle-1", "ORCL", "Source - P", "query", "APP", "SELECT 1 FROM DUAL");
+ const tab = store.tabs.find((item) => item.id === id)!;
+ tab.objectDetails = { connectionId: tab.connectionId, database: tab.database, schema: "APP", name: "P", objectType: "PROCEDURE", section: "dependencies" };
+ useSettingsStore().editorSettings.confirmDangerousSqlExecution = false;
+ const execution = useSqlExecution({ activeTab: computed(() => tab), activeConnection: computed(() => connections.connections[0]), executableSql: computed(() => tab.sql), activeOutputView: ref<TabOutputView>("result") });
+ expect(await execution.tryExecute()).toMatchObject({ status: "not-started", reason: "blocked" });
+ expect(await execution.tryExecuteInNewResultTab()).toMatchObject({ status: "not-started", reason: "blocked" });
+ await execution.tryExplain();
+ expect(backend.executeQuery).not.toHaveBeenCalled();
+ expect(backend.executeMulti).not.toHaveBeenCalled();
+ expect(tab.result).toBeUndefined();
+ tab.objectDetails.section = "source";
+ const outcome = await execution.tryExecute();
+ expect(outcome, JSON.stringify(outcome)).toMatchObject({ status: "started", ok: true });
+ expect(backend.executeMulti).toHaveBeenCalledWith("oracle-1", "ORCL", "SELECT 1 FROM DUAL", "APP", expect.any(String), expect.any(Object));
+ });
+});
diff --git a/apps/desktop/src/stores/queryStore.ts b/apps/desktop/src/stores/queryStore.ts
index 011c062dba..0e55af651b 100644
--- a/apps/desktop/src/stores/queryStore.ts
+++ b/apps/desktop/src/stores/queryStore.ts
@@ -313,6 +313,7 @@ interface OpenPendingObjectSourceTabOptions {
schema?: string;
catalog?: string;
initialEditing?: boolean;
+ initialSection?: NonNullable<QueryTab["objectDetails"]>["section"];
request: ObjectSourceRequestIdentity;
}
@@ -2848,6 +2849,7 @@ export const useQueryStore = defineStore("query", () => {
objectBrowser: t.objectBrowser,
objectSource: t.objectSource,
sourceView: t.sourceView,
+ objectDetails: t.objectDetails,
tableMeta: t.tableMeta,
mongoEditTarget: t.mongoEditTarget,
resultEvicted: t.resultEvicted,
@@ -3129,6 +3131,7 @@ export const useQueryStore = defineStore("query", () => {
const existing = findMatchingObjectSourceTab(options);
if (existing) {
existing.sourceView = true;
+ existing.objectDetails = sourceDetails(options, options.objectSource);
switchTab(existing.id);
if (!isTabDirty(existing)) {
const snapshot = getObjectSourceIdentitySnapshot(existing);
@@ -3141,6 +3144,8 @@ export const useQueryStore = defineStore("query", () => {
const id = createTab(options.connectionId, options.database, options.title, "query", options.schema, options.sql, options.catalog, { forceNew: true, sourceView: true, schemaQualifiesSql: true });
setObjectSource(id, options.objectSource);
+ const tab = tabs.value.find((candidate) => candidate.id === id);
+ if (tab) tab.objectDetails = sourceDetails(options, options.objectSource);
return id;
}
@@ -3150,6 +3155,10 @@ export const useQueryStore = defineStore("query", () => {
*/
const sourceRevalidateInFlight = new Set<string>();
+ function sourceDetails(context: Pick<QueryTab, "connectionId" | "database" | "schema" | "catalog">, source: ObjectSourceRequestIdentity, section: NonNullable<QueryTab["objectDetails"]>["section"] = "source"): NonNullable<QueryTab["objectDetails"]> {
+ return { connectionId: context.connectionId, database: context.database, schema: context.schema || context.database, catalog: context.catalog, name: source.name, objectType: source.objectType, section };
+ }
+
function findPendingObjectSourceTab(options: OpenPendingObjectSourceTabOptions): QueryTab | undefined {
return tabs.value.find(
(tab) =>
@@ -3188,6 +3197,7 @@ export const useQueryStore = defineStore("query", () => {
});
if (loaded) {
loaded.sourceView = true;
+ loaded.objectDetails = sourceDetails(options, options.request, options.initialSection);
switchTab(loaded.id);
// 这条路径不经过 ensureConnected,但树上的动作会把该连接设为当前连接
useConnectionStore().activeConnectionId = options.connectionId;
@@ -3197,6 +3207,7 @@ export const useQueryStore = defineStore("query", () => {
const existing = findPendingObjectSourceTab(options);
if (existing) {
+ existing.objectDetails = sourceDetails(options, options.request, options.initialSection);
switchTab(existing.id);
// 再次点击同一对象 = 再试一次,不新开 tab、不重复占用一个 tab 位
if (existing.sourceLoad?.error) retryObjectSourceTab(existing.id);
@@ -3205,7 +3216,10 @@ export const useQueryStore = defineStore("query", () => {
const id = createTab(options.connectionId, options.database, options.title, "query", options.schema, "", options.catalog, { forceNew: true, sourceView: true, schemaQualifiesSql: true });
const tab = tabs.value.find((candidate) => candidate.id === id);
- if (tab) tab.sourceLoad = { startedAt: Date.now(), initialEditing: options.initialEditing, request: { ...options.request } };
+ if (tab) {
+ tab.sourceLoad = { startedAt: Date.now(), initialEditing: options.initialEditing, request: { ...options.request } };
+ tab.objectDetails = sourceDetails(options, options.request, options.initialSection);
+ }
void loadObjectSourceIntoTab(id);
return id;
}
@@ -3354,6 +3368,7 @@ export const useQueryStore = defineStore("query", () => {
// 加载期间 tab 被关掉(用户放弃)或连接被断开:静默丢弃,不重建、不写库
const tab = tabs.value.find((candidate) => candidate.id === id);
if (!tab?.sourceLoad) return;
+ const details = sourceDetails(loaded, { ...loaded.request, objectType: loaded.resolvedType }, tab.objectDetails?.section);
const sourceIsEditable = !isViewOnlySourceWithoutEditablePayload(loaded.initialEditing, loaded.resolvedType) && loaded.raw.editable !== false && (!OBJECT_SOURCE_READ_ONLY_TYPES.includes(loaded.resolvedType) || (loaded.databaseType === "oceanbase-oracle" && loaded.resolvedType === "SEQUENCE"));
if (sourceIsEditable) {
const options: OpenObjectSourceTabOptions = {
@@ -3374,6 +3389,7 @@ export const useQueryStore = defineStore("query", () => {
clearObjectSourceLoad(tab);
closeTab(id);
existing.sourceView = true;
+ existing.objectDetails = details;
switchTab(existing.id);
if (!isTabDirty(existing)) {
updateSql(existing.id, loaded.editableSource);
@@ -3387,6 +3403,7 @@ export const useQueryStore = defineStore("query", () => {
updateSql(id, loaded.raw.source);
}
tab.sourceView = true;
+ tab.objectDetails = details;
markTabClean(tab);
clearObjectSourceLoad(tab);
}
@@ -5186,6 +5203,7 @@ export const useQueryStore = defineStore("query", () => {
objectBrowser: original.objectBrowser ? { ...original.objectBrowser } : undefined,
objectSource: original.objectSource ? { ...original.objectSource } : undefined,
sourceView: original.sourceView,
+ objectDetails: original.objectDetails ? { ...original.objectDetails } : undefined,
tableMeta: original.tableMeta
? {
...original.tableMeta,
@@ -6458,7 +6476,10 @@ export const useQueryStore = defineStore("query", () => {
function setObjectSource(id: string, objectSource: NonNullable<QueryTab["objectSource"]>) {
const tab = tabs.value.find((t) => t.id === id);
- if (tab) tab.objectSource = objectSource;
+ if (tab) {
+ tab.objectSource = objectSource;
+ tab.objectDetails = sourceDetails(tab, objectSource, tab.objectDetails?.section);
+ }
}
function setExecuting(id: string, isExecuting: boolean) {
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index 1630f9a8b6..ecb245d4f4 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -2387,6 +2387,16 @@ export interface QueryTab {
};
/** Opened to view object source, including objects without editable source metadata. */
sourceView?: boolean;
+ /** Stable object identity and local section, independent of pending source loading. */
+ objectDetails?: {
+ connectionId: string;
+ database: string;
+ schema: string;
+ catalog?: string;
+ name: string;
+ objectType: ObjectSourceKind;
+ section: "source" | "dependencies" | "dependents";
+ };
ddlViewer?: {
schema?: string;
tableName: string;
diff --git a/docs/database-object-dependencies.md b/docs/database-object-dependencies.md
new file mode 100644
index 0000000000..ce1b639bb0
--- /dev/null
+++ b/docs/database-object-dependencies.md
@@ -0,0 +1,29 @@
+# 查看 Oracle 例程依赖
+
+在 Oracle 或 OceanBase Oracle 对象树中,右键过程、函数、程序包或程序包成员,选择「查看依赖关系」。DBX 会打开现有对象详情,直接显示依赖列表;显示为标签页还是弹窗,沿用源码打开方式设置。
+
+## 在对象详情中切换方向
+
+- **源码**:查看或编辑原有源码。
+- **依赖对象**:当前例程直接依赖的对象。
+- **被依赖对象**:直接引用当前例程的对象。
+
+列表显示名称、类型、Schema 和依赖类型;有远程引用时显示数据库链接。程序包合并显示规范与包体记录,并保留来源类型。包内成员按所属程序包查询,不代表成员级依赖。
+
+切换分区或刷新依赖不会重载源码,也不会清除源码草稿、选区或撤销历史。源码读取失败时,仍可切换到依赖列表独立查询。
+
+## 打开关联对象或查看查询
+
+点击对象名称,按原连接及对象所属 Schema 打开关联表或源码。数据库链接对象、未知类型及当前尚不支持的类型保留在列表中,可复制名称,不会误作本地表打开。
+
+在源码弹窗中打开关联对象前,如果有未保存的修改,DBX 会要求确认是否放弃;取消后保留草稿。
+
+「查看 SQL」在普通查询标签页中生成相应查询,不自动执行。依赖刷新使用独立只读查询,不覆盖源码标签页的 SQL、已有查询结果或手动事务。
+
+## 目录范围与查询状态
+
+列表来自 `ALL_DEPENDENCIES`,仅包含当前账户可见的直接目录记录,不递归展开依赖链。动态 SQL 中的引用可能缺失;空列表表示没有查到当前账户可见的直接记录。
+
+出向依赖保留远端对象及链接名;通过链接引用的远端同名对象不会计作本地目标的引用者。DBX 不提权补查,也不自动解析同义词或远端链接。
+
+加载、空结果、查询失败及结果截断分别显示。刷新失败时保留上次同一对象的成功结果,并可重试;截断提示表示列表可能不完整。
diff --git a/docs/images/oracle-package-dependencies.jpg b/docs/images/oracle-package-dependencies.jpg
new file mode 100644
index 0000000000..58f267601f
Binary files /dev/null and b/docs/images/oracle-package-dependencies.jpg differ
diff --git a/docs/images/oracle-routine-dependencies.jpg b/docs/images/oracle-routine-dependencies.jpg
new file mode 100644
index 0000000000..6d30307688
Binary files /dev/null and b/docs/images/oracle-routine-dependencies.jpg differ