From e749bdd42c28213f0f35450c76074af305399d8c Mon Sep 17 00:00:00 2001 From: Yy-702 <1243389905@qq.com> Date: Wed, 5 Aug 2026 23:57:50 +0800 Subject: [PATCH] =?UTF-8?q?feat(oracle):=20Ctrl/Cmd+click=20=E6=89=93?= =?UTF-8?q?=E5=BC=80=E5=AD=98=E5=82=A8=E8=BF=87=E7=A8=8B=E6=BA=90=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(oracle): open procedure source via Ctrl/Cmd+click in SQL editor Allow navigating from SQL identifiers to routine source like DataGrip/DBeaver. Call sites open immediately without a global ALL_OBJECTS scan, and query-tab views wrap bare Oracle ALL_SOURCE as CREATE OR REPLACE for editable DDL. Close #5290 * fix(oracle): harden Ctrl/Cmd+click navigation identity model Address review feedback on routine navigation correctness: - Distinguish relation column lists (INSERT INTO t(...)) from routine calls - Resolve schema.routine vs package.member before optimistic open - Preserve quoted mixed-case identities for Oracle ALL_SOURCE lookup - Try exact then uppercase name candidates in the Oracle Go agent --- agents/drivers/oracle-go/main.go | 55 ++- agents/drivers/oracle-go/main_test.go | 12 + apps/desktop/src/App.vue | 99 ++++- .../src/components/editor/QueryEditor.vue | 125 +++++- .../components/objects/ObjectSourceDialog.vue | 10 +- .../sidebar/SidebarTreeRuntimeHost.vue | 28 +- apps/desktop/src/composables/useQuickOpen.ts | 3 +- .../lib/__tests__/sql/sqlNavigation.spec.ts | 173 ++++++++ apps/desktop/src/lib/sql/sqlNavigation.ts | 412 +++++++++++++++++- .../table/__tests__/objectSourceLoad.spec.ts | 56 +++ .../desktop/src/lib/table/objectSourceLoad.ts | 78 ++++ 11 files changed, 1005 insertions(+), 46 deletions(-) create mode 100644 apps/desktop/src/lib/table/__tests__/objectSourceLoad.spec.ts create mode 100644 apps/desktop/src/lib/table/objectSourceLoad.ts diff --git a/agents/drivers/oracle-go/main.go b/agents/drivers/oracle-go/main.go index 39d24ef5e0..cf6d230466 100644 --- a/agents/drivers/oracle-go/main.go +++ b/agents/drivers/oracle-go/main.go @@ -2293,7 +2293,7 @@ func oracleTriggerBody(source, description string) (string, bool) { func (s *server) getObjectSource(schema, name, objectType string) (map[string]any, error) { var err error - schema, err = s.normalizeSchema(schema) + schema, err = s.normalizeSchemaForIdentity(schema) if err != nil { return nil, err } @@ -2306,24 +2306,69 @@ func (s *server) getObjectSource(schema, name, objectType string) (map[string]an return map[string]any{"name": name, "object_type": objectType, "schema": schema, "source": source}, nil } + // Unquoted Oracle identifiers are stored uppercase; quoted mixed-case names must stay exact. + // Try caller-provided identity first, then uppercase fallback (same pattern as column metadata). + for _, candidate := range oracleObjectIdentityNameCandidates(name) { + source, found, queryErr := s.loadObjectSourceText(schema, candidate, upperType) + if queryErr != nil { + return nil, queryErr + } + if found { + return map[string]any{"name": candidate, "object_type": objectType, "schema": schema, "source": source}, nil + } + } + return map[string]any{"name": name, "object_type": objectType, "schema": schema, "source": ""}, nil +} + +func (s *server) loadObjectSourceText(schema, name, objectType string) (string, bool, error) { rows, err := s.queryRows(` SELECT TEXT FROM ALL_SOURCE WHERE OWNER = :1 AND NAME = :2 AND TYPE = :3 -ORDER BY LINE`, []any{schema, strings.ToUpper(name), upperType}) +ORDER BY LINE`, []any{schema, name, objectType}) if err != nil { - return nil, err + return "", false, err } defer s.closeRows(rows) var builder strings.Builder + var anyLine bool for rows.Next() { var line string if err := rows.Scan(&line); err != nil { - return nil, err + return "", false, err } builder.WriteString(line) + anyLine = true } - return map[string]any{"name": name, "object_type": objectType, "schema": schema, "source": builder.String()}, rows.Err() + if err := rows.Err(); err != nil { + return "", false, err + } + return builder.String(), anyLine, nil +} + +// oracleObjectIdentityNameCandidates returns ALL_SOURCE name variants. +// Exact form first (quoted mixed-case), then uppercase for unquoted identifiers. +func oracleObjectIdentityNameCandidates(name string) []string { + trimmed := strings.TrimSpace(name) + if trimmed == "" { + return nil + } + upper := strings.ToUpper(trimmed) + if trimmed == upper { + return []string{upper} + } + return []string{trimmed, upper} +} + +// normalizeSchemaForIdentity preserves mixed-case schema owners (quoted identities) +// and uppercases already-uppercase / empty-resolved session schemas. +func (s *server) normalizeSchemaForIdentity(schema string) (string, error) { + trimmed := strings.TrimSpace(schema) + if trimmed != "" && trimmed != strings.ToUpper(trimmed) { + // Mixed or lower case from a quoted click-site identity — keep exact OWNER. + return trimmed, nil + } + return s.normalizeSchema(schema) } func (s *server) getTableDDL(schema, table, objectType string) (string, error) { diff --git a/agents/drivers/oracle-go/main_test.go b/agents/drivers/oracle-go/main_test.go index a0dec1a160..be5f14aa95 100644 --- a/agents/drivers/oracle-go/main_test.go +++ b/agents/drivers/oracle-go/main_test.go @@ -1762,6 +1762,18 @@ func TestGetObjectSourceRejectsMissingViewSource(t *testing.T) { } } +func TestOracleObjectIdentityNameCandidates(t *testing.T) { + if got := oracleObjectIdentityNameCandidates("MIXEDPROC"); len(got) != 1 || got[0] != "MIXEDPROC" { + t.Fatalf("uppercase identity should be single candidate, got %#v", got) + } + if got := oracleObjectIdentityNameCandidates("MiXeDProc"); len(got) != 2 || got[0] != "MiXeDProc" || got[1] != "MIXEDPROC" { + t.Fatalf("mixed-case identity should try exact then upper, got %#v", got) + } + if got := oracleObjectIdentityNameCandidates(" "); got != nil { + t.Fatalf("blank name should yield no candidates, got %#v", got) + } +} + func contains(values []string, target string) bool { for _, value := range values { if value == target { diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue index a7f848de82..ce64706ce8 100644 --- a/apps/desktop/src/App.vue +++ b/apps/desktop/src/App.vue @@ -44,8 +44,9 @@ import { quickConnectionOpenTarget } from "@/lib/connection/connectionOpenTarget import { resolveDefaultDatabase } from "@/lib/database/defaultDatabase"; import { normalizeSqliteNamespace } from "@/lib/database/sqliteNamespace"; import { findTreeNodeById, resolveNewQueryTarget, resolveNewQueryInitialSql } from "@/lib/sql/newQueryContext"; -import { sqlObjectNavigationSourceKind, sqlObjectNavigationTableType, type SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation"; -import { buildExecutableObjectSourceStatements, executeObjectSourceSave } from "@/lib/table/objectSourceEditor"; +import { isSqlObjectNavigationRoutineType, normalizeOracleNavigationTarget, sqlObjectNavigationSourceKind, sqlObjectNavigationSourceName, sqlObjectNavigationSourceSchema, sqlObjectNavigationTableType, type SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation"; +import { buildEditableObjectSource, buildExecutableObjectSourceStatements, executeObjectSourceSave } from "@/lib/table/objectSourceEditor"; +import { loadEditableObjectSourceForEditor } from "@/lib/table/objectSourceLoad"; import { schemaAfterConnectionSwitch } from "@/lib/schema/connectionSchemaInitialization"; import { resolveHistorySqlRestoreTarget } from "@/lib/history/historyRestoreTarget"; import { resolveExecutableSql, resolveExecutableSqlWithBackend, type SqlExecutionSnapshot } from "@/lib/sql/sqlExecutionTarget"; @@ -222,7 +223,16 @@ const compressSqlRequest = ref<{ id: number; tabId: string } | null>(null); const activeOutputView = ref<"result" | "summary" | "explain" | "chart">("result"); const newQueryContextSource = ref<"tab" | "sidebar">("tab"); const queryEditorDdlTarget = ref<{ connectionId: string; database: string; catalog?: string; schema?: string; tableName: string; objectType?: ObjectSourceKind } | null>(null); -const queryEditorObjectSourceTarget = ref<{ connectionId: string; database: string; schema?: string; name: string; objectType: ObjectSourceKind; initialEditing: boolean } | null>(null); +const queryEditorObjectSourceTarget = ref<{ + connectionId: string; + database: string; + schema?: string; + name: string; + objectType: ObjectSourceKind; + initialEditing: boolean; + signature?: string; + relationName?: string; +} | null>(null); const showSaveSqlDialog = ref(false); const saveSqlName = ref(""); const ROOT_SAVED_SQL_FOLDER = "__root__"; @@ -1480,6 +1490,11 @@ function tableTargetFromActiveTab(table: string | SqlObjectNavigationTarget) { } async function onClickTable(table: SqlObjectNavigationTarget) { + // Procedures/functions/packages open source (same as sidebar view-source), not table data/DDL. + if (isSqlObjectNavigationRoutineType(table.type)) { + await onOpenObjectSource(table, false); + return; + } const target = tableTargetFromActiveTab(table); if (!target) return; const objectType = sqlObjectNavigationSourceKind(table); @@ -1525,13 +1540,62 @@ function onEditTableStructure(table: SqlObjectNavigationTarget) { } async function onOpenObjectSource(table: SqlObjectNavigationTarget, initialEditing: boolean) { - const target = tableTargetFromActiveTab(table); - const objectType = sqlObjectNavigationSourceKind(table); + const provisionalTarget = tableTargetFromActiveTab(table); + 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 objectType = sqlObjectNavigationSourceKind(navigation); if (!target || !objectType) return; + const sourceName = sqlObjectNavigationSourceName(navigation); + const sourceSchema = sqlObjectNavigationSourceSchema(navigation, target.schema || target.database); try { await connectionStore.ensureConnected(target.connectionId); connectionStore.activeConnectionId = target.connectionId; - queryEditorObjectSourceTarget.value = { connectionId: target.connectionId, database: target.database, schema: target.schema, name: target.tableName, objectType, initialEditing }; + // Align Ctrl/Cmd+click with sidebar "view source" (dialog vs data tab). + if (settingsStore.editorSettings.routineSourceOpenMode === "query-tab") { + try { + const resolvedDatabaseType = effectiveDatabaseTypeForConnection(connectionStore.getConfig(target.connectionId)); + if (!resolvedDatabaseType) throw new Error("Connection type is unavailable."); + // Wrap Oracle bare ALL_SOURCE (`procedure name is ...`) as CREATE OR REPLACE for the editor. + const { + raw, + editableSource, + objectType: resolvedType, + } = await loadEditableObjectSourceForEditor(api.getObjectSource, buildEditableObjectSource, { + connectionId: target.connectionId, + database: target.database, + schema: sourceSchema || target.database, + name: sourceName, + objectType, + databaseType: resolvedDatabaseType, + signature: navigation.signature, + }); + const tabId = queryStore.createTab(target.connectionId, target.database, `Source - ${sourceName}`, "query", sourceSchema, editableSource, target.catalog, { forceNew: true }); + const sourceIsEditable = raw.editable !== false && !["SEQUENCE", "TRIGGER", "TYPE", "TYPE_BODY"].includes(resolvedType); + if (sourceIsEditable) { + queryStore.setObjectSource(tabId, { + schema: sourceSchema || target.database, + name: sourceName, + objectType: resolvedType, + signature: navigation.signature, + }); + } + } catch (e: any) { + toast(e?.message || String(e), 5000); + } + return; + } + queryEditorObjectSourceTarget.value = { + connectionId: target.connectionId, + database: target.database, + schema: sourceSchema, + name: sourceName, + objectType, + initialEditing, + signature: navigation.signature, + }; showQueryEditorObjectSourceDialog.value = true; } catch (e: any) { toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000); @@ -1853,14 +1917,25 @@ async function handleQuickOpenSelect(item: any) { const schema = item.schema || item.database; try { - const result = await api.getObjectSource(item.connectionId, item.database, schema, item.objectName || item.tableName, objectType, item.signature); - const tabId = queryStore.createTab(item.connectionId, item.database, `Source - ${item.objectName || item.tableName}`); - queryStore.updateSql(tabId, result.source); + const databaseType = effectiveDatabaseTypeForConnection(connectionStore.getConfig(item.connectionId)); + if (!databaseType) throw new Error("Connection type is unavailable."); + const objectName = item.objectName || item.tableName; + const { editableSource, objectType: resolvedType } = await loadEditableObjectSourceForEditor(api.getObjectSource, buildEditableObjectSource, { + connectionId: item.connectionId, + database: item.database, + schema, + name: objectName, + objectType, + databaseType, + signature: item.signature, + }); + const tabId = queryStore.createTab(item.connectionId, item.database, `Source - ${objectName}`); + queryStore.updateSql(tabId, editableSource); if (item.type !== "sequence" && item.type !== "trigger" && item.type !== "type" && item.type !== "type-body") { queryStore.setObjectSource(tabId, { schema, - name: item.objectName || item.tableName, - objectType, + name: objectName, + objectType: resolvedType, signature: item.signature, }); } @@ -2649,6 +2724,8 @@ onUnmounted(() => { :database="queryEditorObjectSourceTarget.database" :schema="queryEditorObjectSourceTarget.schema" :name="queryEditorObjectSourceTarget.name" + :signature="queryEditorObjectSourceTarget.signature" + :relation-name="queryEditorObjectSourceTarget.relationName" :object-type="queryEditorObjectSourceTarget.objectType" :initial-editing="queryEditorObjectSourceTarget.initialEditing" :database-type="queryEditorObjectSourceDatabaseType" diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue index e7260ec7b1..a00dcc3728 100644 --- a/apps/desktop/src/components/editor/QueryEditor.vue +++ b/apps/desktop/src/components/editor/QueryEditor.vue @@ -61,7 +61,21 @@ import { type SqlCompletionScope, } from "@/lib/sql/sqlCompletionLookupTarget"; import { usesOracleSessionCompletionColumns as shouldUseOracleSessionCompletionColumns } from "@/lib/sql/oracleCompletionSession"; -import { extractIdentifierDetailsAt, isSqlKeyword, matchTable, mergeSqlObjectNavigationType, splitQualifiedIdentifier, sqlObjectHoverDetail, sqlObjectNavigationSourceKind, sqlObjectNavigationTarget, type SqlObjectNavigationTarget } from "@/lib/sql/sqlNavigation"; +import { + extractIdentifierDetailsAt, + isSqlKeyword, + matchSqlObject, + matchTable, + mergeSqlObjectNavigationType, + resolveSqlObjectNavigationIdentity, + splitQualifiedIdentifier, + sqlObjectHoverDetail, + sqlObjectNavigationSourceKind, + sqlObjectNavigationTarget, + sqlObjectNavigationTargetFromIdentity, + sqlObjectNavigationTypeFromCompletionObjectType, + type SqlObjectNavigationTarget, +} from "@/lib/sql/sqlNavigation"; import { buildHoverTableSql, ddlForHoverPreview, hoverTableMatchesScope, quoteQualifiedName, reformatHoverDdl, scopeHoverTables, type HoverTableScope } from "@/lib/editor/hoverTableSql"; import { lineColumnToOffset, parseSqlErrorLocation } from "@/lib/sql/sqlDiagnostics"; import { @@ -4312,24 +4326,115 @@ onMounted(async () => { event.preventDefault(); setTimeout(async () => { try { - const identifierParts = splitQualifiedIdentifier(identifier); - const tableLookupFilter = identifierParts[identifierParts.length - 1] ?? identifier; + // Single identity model: quote flags + role (relation column list vs routine call vs unknown). + const identity = resolveSqlObjectNavigationIdentity(doc, pos); + if (!identity) return; - // Ensure table cache is populated + const identifierParts = identity.parts.map((part) => part.value); + const tableLookupFilter = identity.name; + const objectNameFilter = identity.name; + // 3-part schema.package.member; 2-part stays ambiguous until metadata resolves it. + const objectParentHint = identity.parts.length >= 3 ? identity.qualifier : undefined; + const objectSchemaHint = identity.parts.length >= 3 ? identity.schema : identity.parts.length === 1 ? props.schema : undefined; + const isRoutineCall = identity.role === "routine_call"; + const isRelationColumnList = identity.role === "relation_column_list"; + + // 1. Local table cache (sync). Relation column lists always prefer tables over routines. if (cachedTables.length === 0) { - // Some metadata providers only accept table-name masks, not schema.table masks. - cachedTables = usesLocalOnlyCompletionMetadata() - ? connectionStore.lookupLocalCompletionTables(props.connectionId!, props.database!, tableLookupFilter, MAX_COMPLETION_TABLES, props.schema, props.catalog) - : await connectionStore.listCompletionTables(props.connectionId!, props.database!, tableLookupFilter, MAX_COMPLETION_TABLES, props.schema, false, props.schema, props.catalog); + cachedTables = connectionStore.lookupLocalCompletionTables(props.connectionId!, props.database!, tableLookupFilter, MAX_COMPLETION_TABLES, props.schema, props.catalog); } - // 1. Check if it's a table name - const matchedTable = matchTable(identifier, cachedTables); + let matchedTable = matchTable(identifier, cachedTables); if (matchedTable) { emit("clickTable", sqlObjectNavigationTarget(matchedTable)); return; } + const preserveOracleStoreCase = (value?: string) => !!value && value !== value.toUpperCase(); + const openMatchedObject = (matchedObject: { name: string; schema?: string; type: string; signature?: string; parentName?: string; parentSchema?: string }) => { + const navigationType = sqlObjectNavigationTypeFromCompletionObjectType(matchedObject.type); + if (!navigationType) return false; + // Metadata names are store-correct; mark mixed-case (or click-quoted) so Oracle normalize won't force UPPER. + emit( + "openObjectSource", + sqlObjectNavigationTarget({ + name: matchedObject.name, + schema: matchedObject.schema, + type: navigationType, + signature: matchedObject.signature, + parentName: matchedObject.parentName, + parentSchema: matchedObject.parentSchema, + nameQuoted: identity.nameQuoted || preserveOracleStoreCase(matchedObject.name), + schemaQuoted: matchedObject.schema ? identity.schemaQuoted || identity.qualifierQuoted || preserveOracleStoreCase(matchedObject.schema) : undefined, + parentNameQuoted: matchedObject.parentName ? identity.qualifierQuoted || preserveOracleStoreCase(matchedObject.parentName) : undefined, + parentSchemaQuoted: matchedObject.parentSchema ? identity.schemaQuoted || preserveOracleStoreCase(matchedObject.parentSchema) : undefined, + }), + false, + ); + return true; + }; + + // 1b. Local routine cache — skip for pure relation column lists (INSERT INTO t(...)). + if (!isRelationColumnList) { + const localObjects = connectionStore.lookupLocalCompletionObjects(props.connectionId!, props.database!, objectNameFilter, MAX_COMPLETION_TABLES, props.schema); + let matchedObject = matchSqlObject(identifier, localObjects); + if (matchedObject && openMatchedObject(matchedObject)) return; + + if (!usesLocalOnlyCompletionMetadata()) { + // Disambiguate schema.routine vs package.member with small scoped lookups (no global scan). + if (identity.parts.length === 2 && identity.qualifier) { + // Prefer package.member under session schema (Oracle common: PKG.MEMBER()). + const packageObjects = await connectionStore.listCompletionObjects(props.connectionId!, props.database!, objectNameFilter, 20, props.schema, identity.qualifier, false, props.schema, ["routine"]); + matchedObject = matchSqlObject(identifier, packageObjects); + if (matchedObject && openMatchedObject(matchedObject)) return; + + // Then schema.routine with qualifier as owner. + const schemaObjects = await connectionStore.listCompletionObjects(props.connectionId!, props.database!, objectNameFilter, 20, identity.qualifier, undefined, false, props.schema, ["routine"]); + matchedObject = matchSqlObject(identifier, schemaObjects); + if (matchedObject && openMatchedObject(matchedObject)) return; + } else { + const scopedObjects = await connectionStore.listCompletionObjects(props.connectionId!, props.database!, objectNameFilter, 20, objectSchemaHint, objectParentHint, false, props.schema, ["routine"]); + matchedObject = matchSqlObject(identifier, scopedObjects); + if (matchedObject && openMatchedObject(matchedObject)) return; + } + } + } + + // 1c. Remote table metadata — never skip for relation column lists or unknown identifiers. + // Routine-call sites may still hit this when a table and procedure share a name and + // local caches were empty; table wins only if listed as a relation. + if (!usesLocalOnlyCompletionMetadata() && (!isRoutineCall || isRelationColumnList || identity.role === "unknown")) { + cachedTables = await connectionStore.listCompletionTables(props.connectionId!, props.database!, tableLookupFilter, MAX_COMPLETION_TABLES, props.schema, false, props.schema, props.catalog); + matchedTable = matchTable(identifier, cachedTables); + if (matchedTable) { + emit("clickTable", sqlObjectNavigationTarget(matchedTable)); + return; + } + } else if (!usesLocalOnlyCompletionMetadata() && isRoutineCall) { + // Lightweight table check so INSERT INTO ORDERS(…) is not the only guarded path — + // still avoid global scans: only session-scoped prefix lookup. + cachedTables = await connectionStore.listCompletionTables(props.connectionId!, props.database!, tableLookupFilter, 20, props.schema, false, props.schema, props.catalog); + matchedTable = matchTable(identifier, cachedTables); + if (matchedTable) { + emit("clickTable", sqlObjectNavigationTarget(matchedTable)); + return; + } + } + + // 1d. Optimistic routine open only for confirmed call sites after metadata + table checks. + if (isRoutineCall) { + const optimistic = sqlObjectNavigationTargetFromIdentity(identity, { + fallbackSchema: props.schema, + preferType: "procedure", + // 2-part: package.member under session schema (not schema.routine). + asPackageMember: identity.twoPartAmbiguous, + }); + if (optimistic) { + emit("openObjectSource", optimistic, false); + return; + } + } + // 2. Parse SQL at click position to get referenced tables const context = getSqlCompletionContext(doc, pos); let referencedTables: Array> = context.referencedTables; diff --git a/apps/desktop/src/components/objects/ObjectSourceDialog.vue b/apps/desktop/src/components/objects/ObjectSourceDialog.vue index 6cf5e4b526..9d79d23f57 100644 --- a/apps/desktop/src/components/objects/ObjectSourceDialog.vue +++ b/apps/desktop/src/components/objects/ObjectSourceDialog.vue @@ -8,6 +8,7 @@ import { useSettingsStore } from "@/stores/settingsStore"; import { copyToClipboard } from "@/lib/common/clipboard"; import { formatSqlForDisplay, type SqlFormatDialect } from "@/lib/sql/sqlFormatter"; import { buildEditableObjectSource, buildExecutableObjectSourceStatements, executeObjectSourceSave, formatObjectSourceSaveError } from "@/lib/table/objectSourceEditor"; +import { loadObjectSourceWithRoutineFallback } from "@/lib/table/objectSourceLoad"; import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard"; import * as api from "@/lib/backend/api"; import QueryEditor from "@/components/editor/QueryEditor.vue"; @@ -54,6 +55,8 @@ const editing = ref(false); const sourceEditable = ref(true); const error = ref(""); const saveError = ref(""); +/** May differ from props.objectType after PROCEDURE/FUNCTION/PACKAGE fallback resolution. */ +const resolvedObjectType = ref(props.objectType); let loadSerial = 0; const canEdit = computed(() => sourceEditable.value && props.objectType !== "SEQUENCE"); @@ -80,16 +83,17 @@ async function loadSource(nextEditing = props.initialEditing && canEdit.value) { try { if (!props.databaseType) throw new Error("Connection type is unavailable."); const schema = props.schema || props.database; - const result = await api.getObjectSource(props.connectionId, props.database, schema, props.name, props.objectType, props.signature, props.relationName); + const { source: result, objectType: resolvedType } = await loadObjectSourceWithRoutineFallback(api.getObjectSource, props.connectionId, props.database, schema, props.name, props.objectType, props.signature, props.relationName); const editableAllowed = result.editable !== false; const editable = await buildEditableObjectSource({ databaseType: props.databaseType, - objectType: props.objectType, + objectType: resolvedType, schema, name: props.name, source: result.source, }); if (serial !== loadSerial) return; + resolvedObjectType.value = resolvedType; sourceEditable.value = editableAllowed; const formatted = await formatSqlForDisplay(editable, props.formatDialect ?? props.dialect, settingsStore.editorSettings.sqlFormatter); editableText.value = editable; @@ -145,7 +149,7 @@ async function saveSource() { try { const statements = await buildExecutableObjectSourceStatements({ databaseType, - objectType: props.objectType, + objectType: resolvedObjectType.value, schema, name: props.name, source: draft.value, diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue index 552ce944e3..3bfe9fd3cc 100644 --- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue +++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue @@ -125,7 +125,8 @@ import { type TableChildObjectType, } from "@/lib/database/dbAdminSql"; import { buildRenameObjectSql, supportsObjectRename, type RenameableObjectType } from "@/lib/table/objectRenameSql"; -import { buildRoutineRenameObjectSourceStatements, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor"; +import { buildEditableObjectSource, buildRoutineRenameObjectSourceStatements, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor"; +import { loadEditableObjectSourceForEditor } from "@/lib/table/objectSourceLoad"; import { buildViewDdl } from "@/lib/table/viewDdl"; import { formatSqlForDisplay, sqlFormatDialectForDbType } from "@/lib/sql/sqlFormatter"; import { getTableStructureCapabilities } from "@/lib/table/tableStructureCapabilities"; @@ -1626,14 +1627,29 @@ function openObjectSourceDialog(initialEditing: boolean) { .then(async () => { connectionStore.activeConnectionId = connectionId; const schema = node.schema || database; - const result = await api.getObjectSource(connectionId, database, schema, node.objectName || node.label, objectType as any, node.signature); - const tabId = queryStore.createTab(connectionId, database, `Source - ${node.label}`, "query", schema, result.source, node.catalog, { forceNew: true }); - const sourceIsEditable = result.editable !== false && !["SEQUENCE", "TRIGGER", "TYPE", "TYPE_BODY"].includes(objectType); + const databaseType = effectiveDatabaseTypeForConnection(connectionStore.getConfig(connectionId)); + if (!databaseType) throw new Error("Connection type is unavailable."); + const objectName = node.objectName || node.label; + const { + raw, + editableSource, + objectType: resolvedType, + } = await loadEditableObjectSourceForEditor(api.getObjectSource, buildEditableObjectSource, { + connectionId, + database, + schema, + name: objectName, + objectType: objectType as any, + databaseType, + signature: node.signature, + }); + const tabId = queryStore.createTab(connectionId, database, `Source - ${node.label}`, "query", schema, editableSource, node.catalog, { forceNew: true }); + const sourceIsEditable = raw.editable !== false && !["SEQUENCE", "TRIGGER", "TYPE", "TYPE_BODY"].includes(resolvedType); if (sourceIsEditable) { queryStore.setObjectSource(tabId, { schema, - name: node.objectName || node.label, - objectType, + name: objectName, + objectType: resolvedType, signature: node.signature, }); } diff --git a/apps/desktop/src/composables/useQuickOpen.ts b/apps/desktop/src/composables/useQuickOpen.ts index 623486904c..066efca876 100644 --- a/apps/desktop/src/composables/useQuickOpen.ts +++ b/apps/desktop/src/composables/useQuickOpen.ts @@ -441,7 +441,8 @@ export function useQuickOpen() { } function remoteTableItem(table: SqlCompletionTable, conn: ConnectionConfig, database: string): QuickOpenItem { - const type = table.type ?? "table"; + // Completion "tables" may carry routine navigation types; quick-open relation entries only accept relation kinds. + const type = table.type === "view" || table.type === "materialized_view" ? table.type : "table"; const prefix = type === "materialized_view" ? "mview" : type; return { id: `${prefix}-${conn.id}-${database}-${table.schema || ""}-${table.name}`, diff --git a/apps/desktop/src/lib/__tests__/sql/sqlNavigation.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlNavigation.spec.ts index fa02aa336a..97c72a61ab 100644 --- a/apps/desktop/src/lib/__tests__/sql/sqlNavigation.spec.ts +++ b/apps/desktop/src/lib/__tests__/sql/sqlNavigation.spec.ts @@ -2,14 +2,27 @@ import { describe, expect, it } from "vitest"; import { extractIdentifierAt, extractIdentifierDetailsAt, + isSqlCallSiteIdentifierAt, isSqlKeyword, + isSqlObjectNavigationRoutineType, + isSqlRelationColumnListContext, + isSqlRoutineCallNavigationCandidate, + matchSqlObject, matchTable, mergeSqlObjectNavigationType, + normalizeOracleNavigationIdentityName, + normalizeOracleNavigationTarget, + resolveSqlObjectNavigationIdentity, splitQualifiedIdentifier, sqlObjectHoverDetail, sqlObjectNavigationSourceKind, + sqlObjectNavigationSourceName, + sqlObjectNavigationSourceSchema, sqlObjectNavigationTableType, sqlObjectNavigationTarget, + sqlObjectNavigationTargetFromIdentifier, + sqlObjectNavigationTargetFromIdentity, + sqlObjectNavigationTypeFromCompletionObjectType, sqlObjectNavigationTypeFromTableType, } from "@/lib/sql/sqlNavigation"; @@ -104,10 +117,32 @@ describe("SQL object navigation metadata", () => { }); }); + it("preserves procedure package-member metadata for command-click navigation", () => { + expect( + sqlObjectNavigationTarget({ + name: "CALC_TAX", + schema: "HR", + type: "procedure", + parentName: "PAYROLL", + parentSchema: "HR", + signature: "CALC_TAX(p NUMBER)", + }), + ).toEqual({ + name: "CALC_TAX", + schema: "HR", + type: "procedure", + parentName: "PAYROLL", + parentSchema: "HR", + signature: "CALC_TAX(p NUMBER)", + }); + }); + it("uses the object type in hover details", () => { expect(sqlObjectHoverDetail({ name: "active_users", schema: "dbo", type: "view" })).toBe("view in dbo"); expect(sqlObjectHoverDetail({ name: "active_users_mv", schema: "dbo", type: "materialized_view" })).toBe("materialized view in dbo"); expect(sqlObjectHoverDetail({ name: "users", schema: "dbo", type: "table" })).toBe("table in dbo"); + expect(sqlObjectHoverDetail({ name: "calc_tax", schema: "hr", type: "procedure" })).toBe("procedure in hr"); + expect(sqlObjectHoverDetail({ name: "calc_tax", type: "procedure", parentName: "payroll", parentSchema: "hr" })).toBe("procedure in hr.payroll"); }); it("maps navigation types to table metadata types", () => { @@ -117,13 +152,151 @@ describe("SQL object navigation metadata", () => { expect(sqlObjectNavigationSourceKind({ name: "active_users", type: "view" })).toBe("VIEW"); expect(sqlObjectNavigationSourceKind({ name: "active_users_mv", type: "materialized_view" })).toBe("MATERIALIZED_VIEW"); expect(sqlObjectNavigationSourceKind({ name: "users", type: "table" })).toBeUndefined(); + expect(sqlObjectNavigationSourceKind({ name: "calc_tax", type: "procedure" })).toBe("PROCEDURE"); + expect(sqlObjectNavigationSourceKind({ name: "get_version", type: "function" })).toBe("FUNCTION"); + expect(sqlObjectNavigationSourceKind({ name: "pkg_utils", type: "package" })).toBe("PACKAGE"); + // Package members open the owning package body source. + expect(sqlObjectNavigationSourceKind({ name: "calc_tax", type: "procedure", parentName: "payroll" })).toBe("PACKAGE_BODY"); + expect(sqlObjectNavigationSourceName({ name: "calc_tax", type: "procedure", parentName: "payroll" })).toBe("payroll"); + expect(sqlObjectNavigationSourceSchema({ name: "calc_tax", type: "procedure", parentName: "payroll", parentSchema: "hr" }, "app")).toBe("hr"); + expect(isSqlObjectNavigationRoutineType("procedure")).toBe(true); + expect(isSqlObjectNavigationRoutineType("table")).toBe(false); }); it("normalizes relation metadata without collapsing materialized views", () => { expect(sqlObjectNavigationTypeFromTableType("BASE TABLE")).toBe("table"); expect(sqlObjectNavigationTypeFromTableType("VIEW")).toBe("view"); expect(sqlObjectNavigationTypeFromTableType("materialized view")).toBe("materialized_view"); + expect(sqlObjectNavigationTypeFromTableType("PROCEDURE")).toBe("procedure"); + expect(sqlObjectNavigationTypeFromCompletionObjectType("function")).toBe("function"); expect(mergeSqlObjectNavigationType("view", "materialized_view")).toBe("materialized_view"); expect(mergeSqlObjectNavigationType("table", "view")).toBe("view"); + expect(mergeSqlObjectNavigationType("table", "procedure")).toBe("procedure"); + }); +}); + +describe("matchSqlObject", () => { + it("matches unqualified standalone procedures before package members", () => { + const standalone = { name: "CALC_TAX", schema: "HR", type: "procedure" as const }; + const packaged = { name: "CALC_TAX", schema: "HR", parentName: "PAYROLL", type: "procedure" as const }; + + expect(matchSqlObject("calc_tax", [packaged, standalone])).toBe(standalone); + }); + + it("matches schema-qualified procedures", () => { + const procedure = { name: "CALC_TAX", schema: "HR", type: "procedure" as const }; + expect(matchSqlObject("hr.calc_tax", [procedure])).toBe(procedure); + expect(matchSqlObject("other.calc_tax", [procedure])).toBeNull(); + }); + + it("matches package members as package.proc and schema.package.proc", () => { + const member = { name: "CALC_TAX", schema: "HR", parentName: "PAYROLL", parentSchema: "HR", type: "procedure" as const }; + expect(matchSqlObject("payroll.calc_tax", [member])).toBe(member); + expect(matchSqlObject("hr.payroll.calc_tax", [member])).toBe(member); + }); +}); + +describe("call-site navigation helpers", () => { + it("detects procedure call sites after the identifier", () => { + const sql = "BEGIN\n PROC_STATIC_DATA_IMPORT()\nEND;"; + const pos = sql.indexOf("PROC_STATIC_DATA_IMPORT") + 3; + expect(isSqlCallSiteIdentifierAt(sql, pos)).toBe(true); + expect(isSqlRoutineCallNavigationCandidate(sql, pos)).toBe(true); + expect(isSqlCallSiteIdentifierAt("SELECT * FROM users", "SELECT * FROM users".indexOf("users"))).toBe(false); + }); + + it("does not treat INSERT INTO relation(column list) as a routine call", () => { + const sql = "INSERT INTO ORDERS(ID, AMT) VALUES (1, 2);"; + const pos = sql.indexOf("ORDERS") + 2; + expect(isSqlCallSiteIdentifierAt(sql, pos)).toBe(true); + expect(isSqlRelationColumnListContext(sql.slice(0, sql.indexOf("ORDERS")))).toBe(true); + expect(isSqlRoutineCallNavigationCandidate(sql, pos)).toBe(false); + + const identity = resolveSqlObjectNavigationIdentity(sql, pos); + expect(identity?.role).toBe("relation_column_list"); + expect(identity?.name).toBe("ORDERS"); + }); + + it("does not treat CREATE TABLE column lists as routine calls", () => { + const sql = "CREATE TABLE ORDERS(id number);"; + const pos = sql.indexOf("ORDERS") + 1; + expect(isSqlRoutineCallNavigationCandidate(sql, pos)).toBe(false); + expect(resolveSqlObjectNavigationIdentity(sql, pos)?.role).toBe("relation_column_list"); + }); + + it("builds optimistic targets preferring package.member for ambiguous two-part calls", () => { + const sql = "BEGIN\n PAYROLL.CALC_TAX();\nEND;"; + const identity = resolveSqlObjectNavigationIdentity(sql, sql.indexOf("CALC_TAX")); + expect(identity?.role).toBe("routine_call"); + expect(identity?.twoPartAmbiguous).toBe(true); + expect(sqlObjectNavigationTargetFromIdentity(identity!, { fallbackSchema: "APP" })).toEqual({ + name: "CALC_TAX", + schema: "APP", + parentName: "PAYROLL", + parentSchema: "APP", + type: "procedure", + }); + // Metadata can force schema.routine when confirmed. + expect(sqlObjectNavigationTargetFromIdentity(identity!, { asSchemaRoutine: true })).toEqual({ + name: "CALC_TAX", + schema: "PAYROLL", + type: "procedure", + }); + }); + + it("builds three-part package member targets", () => { + const sql = "BEGIN\n HR.PAYROLL.CALC_TAX();\nEND;"; + const identity = resolveSqlObjectNavigationIdentity(sql, sql.indexOf("CALC_TAX")); + expect(sqlObjectNavigationTargetFromIdentity(identity!)).toEqual({ + name: "CALC_TAX", + schema: "HR", + parentName: "PAYROLL", + parentSchema: "HR", + type: "procedure", + }); + }); + + it("preserves quoted mixed-case identities for Oracle normalization", () => { + const sql = 'BEGIN\n "MiXeDProc"();\nEND;'; + const identity = resolveSqlObjectNavigationIdentity(sql, sql.indexOf("MiXeD") + 1); + expect(identity?.name).toBe("MiXeDProc"); + expect(identity?.nameQuoted).toBe(true); + expect(normalizeOracleNavigationIdentityName(identity!.name, identity!.nameQuoted)).toBe("MiXeDProc"); + expect(normalizeOracleNavigationIdentityName("mixedproc", false)).toBe("MIXEDPROC"); + + const target = sqlObjectNavigationTargetFromIdentity(identity!, { fallbackSchema: "APP" }); + expect(normalizeOracleNavigationTarget(target!)).toEqual({ + name: "MiXeDProc", + nameQuoted: true, + schema: "APP", + type: "procedure", + }); + }); + + it("preserves quoted package.member mixed-case identities", () => { + const sql = 'BEGIN\n "Pkg"."Member"();\nEND;'; + const identity = resolveSqlObjectNavigationIdentity(sql, sql.indexOf("Member")); + expect(identity?.name).toBe("Member"); + expect(identity?.nameQuoted).toBe(true); + expect(identity?.qualifier).toBe("Pkg"); + expect(identity?.qualifierQuoted).toBe(true); + const target = normalizeOracleNavigationTarget(sqlObjectNavigationTargetFromIdentity(identity!, { fallbackSchema: "APP", asPackageMember: true })!); + expect(target).toEqual({ + name: "Member", + nameQuoted: true, + schema: "APP", + parentName: "Pkg", + parentNameQuoted: true, + parentSchema: "APP", + type: "procedure", + }); + }); + + it("keeps legacy string helper for simple identifiers", () => { + expect(sqlObjectNavigationTargetFromIdentifier("PROC_STATIC_DATA_IMPORT", { fallbackSchema: "APP" })).toEqual({ + name: "PROC_STATIC_DATA_IMPORT", + schema: "APP", + type: "procedure", + }); }); }); diff --git a/apps/desktop/src/lib/sql/sqlNavigation.ts b/apps/desktop/src/lib/sql/sqlNavigation.ts index 13d0df2511..17a5c87b98 100644 --- a/apps/desktop/src/lib/sql/sqlNavigation.ts +++ b/apps/desktop/src/lib/sql/sqlNavigation.ts @@ -135,13 +135,60 @@ export interface ExtractedSqlIdentifierPart { quoted: boolean; } -export type SqlObjectNavigationType = "table" | "view" | "materialized_view"; +export type SqlObjectNavigationType = "table" | "view" | "materialized_view" | "procedure" | "function" | "package" | "trigger"; + +/** + * Semantic role of a Ctrl/Cmd+clicked identifier for navigation. + * + * - `relation_column_list`: name is a table/view followed by `(cols)` (INSERT INTO t(...), CREATE TABLE t(...), …) + * - `routine_call`: name is invoked as a call / PL/SQL unit (`proc(...)`, `pkg.member(...)`) + * - `unknown`: plain identifier; resolve via metadata (table first, then routine) + */ +export type SqlObjectNavigationRole = "relation_column_list" | "routine_call" | "unknown"; export interface SqlObjectNavigationTarget { name: string; database?: string; schema?: string; type?: SqlObjectNavigationType; + /** Overload signature used by Postgres/SQL Server routines. */ + signature?: string; + /** Owning package/type name for Oracle package members (or trigger parent table). */ + parentName?: string; + parentSchema?: string; + /** Quote metadata so Oracle keeps mixed-case identities (`"MiXeDProc"`). */ + nameQuoted?: boolean; + schemaQuoted?: boolean; + parentNameQuoted?: boolean; + parentSchemaQuoted?: boolean; +} + +/** + * Fully resolved click identity: parts, quotes, and navigation role. + * Built before any remote metadata call so call-site vs table and package vs schema + * decisions share one model instead of scattered if/else branches. + */ +export interface SqlObjectNavigationIdentity { + identifier: string; + parts: ExtractedSqlIdentifierPart[]; + start: number; + end: number; + name: string; + nameQuoted: boolean; + /** Leading qualifier for 2-part names (schema OR package — still ambiguous until metadata). */ + qualifier?: string; + qualifierQuoted?: boolean; + /** Owner/schema when 3-part (schema.package.member) or when metadata resolves schema.routine. */ + schema?: string; + schemaQuoted?: boolean; + role: SqlObjectNavigationRole; + /** + * Two-part `A.B(...)` is ambiguous between `schema.routine` and `package.member`. + * Optimistic open prefers package.member under the session schema (Oracle common case) + * only after metadata lookups fail. + */ + twoPartAmbiguous: boolean; + followedByParen: boolean; } export function sqlObjectNavigationTarget(table: SqlObjectNavigationTarget): SqlObjectNavigationTarget { @@ -150,11 +197,26 @@ export function sqlObjectNavigationTarget(table: SqlObjectNavigationTarget): Sql ...(table.database ? { database: table.database } : {}), ...(table.schema ? { schema: table.schema } : {}), ...(table.type ? { type: table.type } : {}), + ...(table.signature ? { signature: table.signature } : {}), + ...(table.parentName ? { parentName: table.parentName } : {}), + ...(table.parentSchema ? { parentSchema: table.parentSchema } : {}), + ...(table.nameQuoted ? { nameQuoted: true } : {}), + ...(table.schemaQuoted ? { schemaQuoted: true } : {}), + ...(table.parentNameQuoted ? { parentNameQuoted: true } : {}), + ...(table.parentSchemaQuoted ? { parentSchemaQuoted: true } : {}), }; } +export function isSqlObjectNavigationRoutineType(type?: SqlObjectNavigationType): boolean { + return type === "procedure" || type === "function" || type === "package" || type === "trigger"; +} + export function sqlObjectHoverDetail(table: SqlObjectNavigationTarget): string { - const objectType = table.type === "materialized_view" ? "materialized view" : table.type === "view" ? "view" : "table"; + 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"; + if (table.parentName) { + const owner = table.parentSchema ? `${table.parentSchema}.${table.parentName}` : table.parentName; + return `${objectType} in ${owner}`; + } return table.schema ? `${objectType} in ${table.schema}` : objectType; } @@ -163,9 +225,48 @@ export function sqlObjectNavigationTableType(table: SqlObjectNavigationTarget): return table.type === "view" ? "VIEW" : "TABLE"; } +/** + * Maps a navigation target to an object-source kind. + * + * Package members (procedure/function with parentName) resolve to PACKAGE_BODY so Oracle + * ALL_SOURCE can load the owning package body rather than a missing standalone routine. + */ export function sqlObjectNavigationSourceKind(table: SqlObjectNavigationTarget): ObjectSourceKind | undefined { - const type = sqlObjectNavigationTableType(table); - return type === "TABLE" ? undefined : type; + if (table.parentName && (table.type === "procedure" || table.type === "function")) { + return "PACKAGE_BODY"; + } + switch (table.type) { + case "view": + return "VIEW"; + case "materialized_view": + return "MATERIALIZED_VIEW"; + case "procedure": + return "PROCEDURE"; + case "function": + return "FUNCTION"; + case "package": + return "PACKAGE"; + case "trigger": + return "TRIGGER"; + default: + return undefined; + } +} + +/** Object name to pass to getObjectSource (package body uses the package name). */ +export function sqlObjectNavigationSourceName(table: SqlObjectNavigationTarget): string { + if (table.parentName && (table.type === "procedure" || table.type === "function")) { + return table.parentName; + } + return table.name; +} + +/** Schema/owner for getObjectSource. */ +export function sqlObjectNavigationSourceSchema(table: SqlObjectNavigationTarget, fallbackSchema?: string): string | undefined { + if (table.parentName && (table.type === "procedure" || table.type === "function")) { + return table.parentSchema || table.schema || fallbackSchema; + } + return table.schema || fallbackSchema; } export function sqlObjectNavigationTypeFromTableType(tableType: string | null | undefined): SqlObjectNavigationType { @@ -175,12 +276,33 @@ export function sqlObjectNavigationTypeFromTableType(tableType: string | null | .replace(/[\s-]+/g, "_"); if (normalized === "MATERIALIZED_VIEW") return "materialized_view"; if (normalized === "VIEW") return "view"; + if (normalized === "PROCEDURE") return "procedure"; + if (normalized === "FUNCTION") return "function"; + if (normalized === "PACKAGE" || normalized === "PACKAGE_BODY") return "package"; + if (normalized === "TRIGGER") return "trigger"; return "table"; } +export function sqlObjectNavigationTypeFromCompletionObjectType(type: string | null | undefined): SqlObjectNavigationType | undefined { + switch (type) { + case "procedure": + return "procedure"; + case "function": + return "function"; + case "package": + return "package"; + case "trigger": + return "trigger"; + default: + return undefined; + } +} + export function mergeSqlObjectNavigationType(left?: SqlObjectNavigationType, right?: SqlObjectNavigationType): SqlObjectNavigationType | undefined { if (left === "materialized_view" || right === "materialized_view") return "materialized_view"; if (left === "view" || right === "view") return "view"; + if (isSqlObjectNavigationRoutineType(left)) return left; + if (isSqlObjectNavigationRoutineType(right)) return right; return left ?? right; } @@ -246,12 +368,12 @@ function identifierSearchBounds(doc: string, pos: number): { start: number; end: return { start, end }; } -/** Extract qualified identifier parts and per-part quote metadata at position `pos`. */ -export function extractIdentifierPartsAt(doc: string, pos: number): ExtractedSqlIdentifierPart[] { - if (pos < 0 || pos > doc.length) return []; +/** Locate the qualified identifier covering `pos`, including quote flags and document range. */ +export function extractQualifiedIdentifierAt(doc: string, pos: number): { parts: ExtractedSqlIdentifierPart[]; start: number; end: number } | null { + if (pos < 0 || pos > doc.length) return null; const clickPos = pos === doc.length ? pos - 1 : pos; - if (clickPos < 0) return []; + if (clickPos < 0) return null; const bounds = identifierSearchBounds(doc, clickPos); let index = bounds.start; @@ -259,7 +381,11 @@ export function extractIdentifierPartsAt(doc: string, pos: number): ExtractedSql const parsed = parseQualifiedIdentifier(doc, index); if (parsed) { if (clickPos >= parsed.start && clickPos < parsed.end) { - return parsed.parts.map((part) => ({ value: part.value, quoted: part.quoted })); + return { + parts: parsed.parts.map((part) => ({ value: part.value, quoted: part.quoted })), + start: parsed.start, + end: parsed.end, + }; } index = Math.max(parsed.end, index + 1); continue; @@ -267,7 +393,12 @@ export function extractIdentifierPartsAt(doc: string, pos: number): ExtractedSql index += 1; } - return []; + return null; +} + +/** Extract qualified identifier parts and per-part quote metadata at position `pos`. */ +export function extractIdentifierPartsAt(doc: string, pos: number): ExtractedSqlIdentifierPart[] { + return extractQualifiedIdentifierAt(doc, pos)?.parts ?? []; } /** Extract identifier and quote metadata at position `pos` in the document. */ @@ -285,6 +416,218 @@ export function extractIdentifierAt(doc: string, pos: number): string | null { return extractIdentifierDetailsAt(doc, pos)?.identifier ?? null; } +/** + * True when the identifier at `pos` is immediately followed by `(` (after optional whitespace). + * Not sufficient alone for routine navigation — also see {@link isSqlRelationColumnListContext}. + */ +export function isSqlCallSiteIdentifierAt(doc: string, pos: number): boolean { + const located = extractQualifiedIdentifierAt(doc, pos); + if (!located) return false; + let cursor = located.end; + while (cursor < doc.length && /\s/.test(doc[cursor] ?? "")) cursor += 1; + return doc[cursor] === "("; +} + +/** + * True when `before` (text immediately before a qualified identifier) is a relation definition + * / DML target where a following `(` starts a column list, not a routine call. + * + * Examples: `INSERT INTO t(`, `CREATE TABLE t(`, `CREATE OR REPLACE VIEW v(`, `CREATE INDEX i ON t(`. + */ +export function isSqlRelationColumnListContext(beforeIdentifier: string): boolean { + const cleaned = beforeIdentifier + .replace(/--[^\n]*/g, " ") + .replace(/\/\*[\s\S]*?\*\//g, " ") + .replace(/\s+/g, " ") + .trimEnd(); + // Trailing space optional; match statement keywords that introduce a relation then `(`. + return /(?:^|[\s(])(?:insert\s+into|merge\s+into|update|create\s+(?:global\s+temporary\s+)?table|create\s+(?:or\s+replace\s+)?(?:(?:no)?force\s+)?(?:(?:non)?editionable\s+)?view|create\s+(?:unique\s+|bitmap\s+)?index(?:\s+(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|[A-Za-z_][\w$]*))?\s+on|alter\s+table)$/i.test( + cleaned, + ); +} + +/** + * True when the identifier is a routine-call navigation candidate (not a relation column list). + * `INSERT INTO ORDERS(ID)` → false; `BEGIN PROC_NAME()` → true. + */ +export function isSqlRoutineCallNavigationCandidate(doc: string, pos: number): boolean { + const located = extractQualifiedIdentifierAt(doc, pos); + if (!located) return false; + let cursor = located.end; + while (cursor < doc.length && /\s/.test(doc[cursor] ?? "")) cursor += 1; + if (doc[cursor] !== "(") return false; + return !isSqlRelationColumnListContext(doc.slice(0, located.start)); +} + +/** + * Resolve the full navigation identity at a click position (role + quote-aware parts). + */ +export function resolveSqlObjectNavigationIdentity(doc: string, pos: number): SqlObjectNavigationIdentity | null { + const located = extractQualifiedIdentifierAt(doc, pos); + if (!located || located.parts.length === 0) return null; + + const parts = located.parts; + const namePart = parts[parts.length - 1]; + if (!namePart) return null; + if (!namePart.quoted && isSqlKeyword(namePart.value)) return null; + + let cursor = located.end; + while (cursor < doc.length && /\s/.test(doc[cursor] ?? "")) cursor += 1; + const followedByParen = doc[cursor] === "("; + const relationColumnList = followedByParen && isSqlRelationColumnListContext(doc.slice(0, located.start)); + + let role: SqlObjectNavigationRole = "unknown"; + if (relationColumnList) role = "relation_column_list"; + else if (followedByParen) role = "routine_call"; + + const identity: SqlObjectNavigationIdentity = { + identifier: parts.map((part) => part.value).join("."), + parts, + start: located.start, + end: located.end, + name: namePart.value, + nameQuoted: namePart.quoted, + role, + twoPartAmbiguous: parts.length === 2 && role === "routine_call", + followedByParen, + }; + + if (parts.length >= 3) { + const schemaPart = parts[parts.length - 3]; + const packagePart = parts[parts.length - 2]; + if (schemaPart) { + identity.schema = schemaPart.value; + identity.schemaQuoted = schemaPart.quoted; + } + if (packagePart) { + identity.qualifier = packagePart.value; + identity.qualifierQuoted = packagePart.quoted; + } + } else if (parts.length === 2) { + const qualifierPart = parts[0]; + if (qualifierPart) { + identity.qualifier = qualifierPart.value; + identity.qualifierQuoted = qualifierPart.quoted; + } + } + + return identity; +} + +/** + * Build a navigation target from a resolved identity for optimistic routine open. + * + * - 1-part: session/fallback schema + procedure name + * - 2-part ambiguous: prefer package.member under fallback schema (not schema.routine) + * - 3-part: schema.package.member + */ +export function sqlObjectNavigationTargetFromIdentity( + identity: SqlObjectNavigationIdentity, + options?: { + fallbackSchema?: string; + preferType?: SqlObjectNavigationType; + /** Force schema.routine interpretation for 2-part names (metadata-confirmed). */ + asSchemaRoutine?: boolean; + /** Force package.member interpretation (default for ambiguous 2-part optimistic). */ + asPackageMember?: boolean; + signature?: string; + }, +): SqlObjectNavigationTarget | null { + if (!identity.name) return null; + const preferType = options?.preferType ?? "procedure"; + const type: SqlObjectNavigationType = preferType === "function" ? "function" : preferType === "package" ? "package" : "procedure"; + + if (identity.parts.length >= 3) { + return sqlObjectNavigationTarget({ + name: identity.name, + nameQuoted: identity.nameQuoted, + schema: identity.schema, + schemaQuoted: identity.schemaQuoted, + parentName: identity.qualifier, + parentNameQuoted: identity.qualifierQuoted, + parentSchema: identity.schema, + parentSchemaQuoted: identity.schemaQuoted, + type, + ...(options?.signature ? { signature: options.signature } : {}), + }); + } + + if (identity.parts.length === 2 && identity.qualifier) { + const asPackageMember = options?.asPackageMember ?? (!options?.asSchemaRoutine && identity.twoPartAmbiguous); + if (asPackageMember) { + return sqlObjectNavigationTarget({ + name: identity.name, + nameQuoted: identity.nameQuoted, + schema: options?.fallbackSchema, + parentName: identity.qualifier, + parentNameQuoted: identity.qualifierQuoted, + parentSchema: options?.fallbackSchema, + type, + ...(options?.signature ? { signature: options.signature } : {}), + }); + } + return sqlObjectNavigationTarget({ + name: identity.name, + nameQuoted: identity.nameQuoted, + schema: identity.qualifier, + schemaQuoted: identity.qualifierQuoted, + type, + ...(options?.signature ? { signature: options.signature } : {}), + }); + } + + return sqlObjectNavigationTarget({ + name: identity.name, + nameQuoted: identity.nameQuoted, + ...(options?.fallbackSchema ? { schema: options.fallbackSchema } : {}), + type, + ...(options?.signature ? { signature: options.signature } : {}), + }); +} + +/** + * @deprecated Prefer {@link sqlObjectNavigationTargetFromIdentity} so quote flags and package/schema + * ambiguity stay consistent with the click identity model. + */ +export function sqlObjectNavigationTargetFromIdentifier( + identifier: string, + options?: { + fallbackSchema?: string; + preferType?: SqlObjectNavigationType; + }, +): SqlObjectNavigationTarget | null { + // Synthesize an identity for string-only callers (tests / legacy). + const syntheticDoc = identifier; + const identity = resolveSqlObjectNavigationIdentity(syntheticDoc, Math.max(0, syntheticDoc.length - 1)); + if (!identity) return null; + // String-only path has no surrounding SQL; treat as routine when multi-part. + if (identity.parts.length >= 2) { + identity.role = "routine_call"; + identity.twoPartAmbiguous = identity.parts.length === 2; + identity.followedByParen = true; + } + return sqlObjectNavigationTargetFromIdentity(identity, options); +} + +/** + * Oracle stores unquoted identifiers as uppercase. Quoted identities keep their written case. + * Apply before getObjectSource so mixed-case `"MiXeDProc"` is not forced to `MIXEDPROC`. + */ +export function normalizeOracleNavigationIdentityName(name: string, quoted?: boolean): string { + return quoted ? name : name.toUpperCase(); +} + +/** Normalize schema/name/parent fields on a navigation target for Oracle metadata APIs. */ +export function normalizeOracleNavigationTarget(target: SqlObjectNavigationTarget): SqlObjectNavigationTarget { + return sqlObjectNavigationTarget({ + ...target, + name: normalizeOracleNavigationIdentityName(target.name, target.nameQuoted), + ...(target.schema != null ? { schema: normalizeOracleNavigationIdentityName(target.schema, target.schemaQuoted) } : {}), + ...(target.parentName != null ? { parentName: normalizeOracleNavigationIdentityName(target.parentName, target.parentNameQuoted) } : {}), + ...(target.parentSchema != null ? { parentSchema: normalizeOracleNavigationIdentityName(target.parentSchema, target.parentSchemaQuoted) } : {}), + }); +} + /** Check whether the identifier is a SQL keyword (not a table/column name). */ export function isSqlKeyword(identifier: string): boolean { return SQL_KEYWORDS_SET.has(identifier.toLowerCase()); @@ -318,3 +661,52 @@ export function matchTable(identifier: string, objects: readonly T[]): T | null { + const parts = splitQualifiedIdentifier(identifier); + if (parts.length === 0) return null; + + const name = parts[parts.length - 1].toLowerCase(); + const same = (left: string | undefined, right: string | undefined) => (left || "").toLowerCase() === (right || "").toLowerCase(); + + if (parts.length === 1) { + // Prefer standalone routines over package members when the identifier is unqualified. + return objects.find((object) => object.name.toLowerCase() === name && !object.parentName) ?? objects.find((object) => object.name.toLowerCase() === name) ?? null; + } + + if (parts.length === 2) { + const qualifier = parts[0].toLowerCase(); + // schema.object (standalone) + const bySchema = objects.find((object) => object.name.toLowerCase() === name && !object.parentName && object.schema?.toLowerCase() === qualifier) ?? objects.find((object) => object.name.toLowerCase() === name && object.schema?.toLowerCase() === qualifier && !object.parentName); + if (bySchema) return bySchema; + // package.member + const byPackage = objects.find((object) => object.name.toLowerCase() === name && object.parentName?.toLowerCase() === qualifier); + if (byPackage) return byPackage; + return null; + } + + // schema.package.member or catalog.schema.object — use the last three parts. + const owner = parts[parts.length - 3].toLowerCase(); + const middle = parts[parts.length - 2].toLowerCase(); + const packageMember = objects.find((object) => object.name.toLowerCase() === name && object.parentName?.toLowerCase() === middle && same(object.parentSchema || object.schema, owner)); + if (packageMember) return packageMember; + + // Fallback: schema.object ignoring extra leading catalog parts. + return objects.find((object) => object.name.toLowerCase() === name && !object.parentName && object.schema?.toLowerCase() === middle) ?? null; +} diff --git a/apps/desktop/src/lib/table/__tests__/objectSourceLoad.spec.ts b/apps/desktop/src/lib/table/__tests__/objectSourceLoad.spec.ts new file mode 100644 index 0000000000..db82b52375 --- /dev/null +++ b/apps/desktop/src/lib/table/__tests__/objectSourceLoad.spec.ts @@ -0,0 +1,56 @@ +import { describe, expect, it, vi } from "vitest"; +import { loadEditableObjectSourceForEditor, loadObjectSourceWithRoutineFallback } from "@/lib/table/objectSourceLoad"; +import type { ObjectSource } from "@/types/database"; + +function source(text: string): ObjectSource { + return { name: "x", object_type: "PROCEDURE", schema: "APP", source: text }; +} + +describe("loadObjectSourceWithRoutineFallback", () => { + it("returns the primary source when it has content", async () => { + const getObjectSource = vi.fn().mockResolvedValue(source("CREATE PROCEDURE ...")); + const result = await loadObjectSourceWithRoutineFallback(getObjectSource, "c1", "ORCL", "APP", "P1", "PROCEDURE"); + expect(result.objectType).toBe("PROCEDURE"); + expect(result.source.source).toContain("CREATE PROCEDURE"); + expect(getObjectSource).toHaveBeenCalledTimes(1); + }); + + it("falls back from PROCEDURE to FUNCTION when primary source is empty", async () => { + const getObjectSource = vi + .fn() + .mockResolvedValueOnce(source("")) + .mockResolvedValueOnce({ ...source("CREATE FUNCTION ..."), object_type: "FUNCTION" }); + const result = await loadObjectSourceWithRoutineFallback(getObjectSource, "c1", "ORCL", "APP", "F1", "PROCEDURE"); + expect(result.objectType).toBe("FUNCTION"); + expect(result.source.source).toContain("CREATE FUNCTION"); + expect(getObjectSource).toHaveBeenCalledTimes(2); + expect(getObjectSource.mock.calls[1][4]).toBe("FUNCTION"); + }); +}); + +describe("loadEditableObjectSourceForEditor", () => { + it("wraps bare Oracle procedure source for the editor", async () => { + const raw = "procedure BMS_SA_SETTOREC_PK is\nbegin\n null;\nend;"; + const getObjectSource = vi.fn().mockResolvedValue(source(raw)); + const buildEditableObjectSource = vi.fn().mockImplementation(async (input) => `CREATE OR REPLACE ${input.source}`); + + const result = await loadEditableObjectSourceForEditor(getObjectSource, buildEditableObjectSource, { + connectionId: "c1", + database: "ORCL", + schema: "APP", + name: "BMS_SA_SETTOREC_PK", + objectType: "PROCEDURE", + databaseType: "oracle", + }); + + expect(result.editableSource).toBe(`CREATE OR REPLACE ${raw}`); + expect(buildEditableObjectSource).toHaveBeenCalledWith( + expect.objectContaining({ + databaseType: "oracle", + objectType: "PROCEDURE", + name: "BMS_SA_SETTOREC_PK", + source: raw, + }), + ); + }); +}); diff --git a/apps/desktop/src/lib/table/objectSourceLoad.ts b/apps/desktop/src/lib/table/objectSourceLoad.ts new file mode 100644 index 0000000000..35fbd63f8b --- /dev/null +++ b/apps/desktop/src/lib/table/objectSourceLoad.ts @@ -0,0 +1,78 @@ +import type { DatabaseType, ObjectSource, ObjectSourceKind } from "@/types/database"; + +export type GetObjectSourceFn = (connectionId: string, database: string, schema: string, name: string, objectType: ObjectSourceKind, signature?: string, relationName?: string) => Promise; + +export type BuildEditableObjectSourceFn = (input: { databaseType: DatabaseType; objectType: ObjectSourceKind; schema?: string; name: string; source: string }) => Promise; + +/** + * Load object source, retrying common routine type mismatches. + * Optimistic Ctrl/Cmd+click often assumes PROCEDURE; Oracle functions and package bodies need a second try. + */ +export async function loadObjectSourceWithRoutineFallback( + getObjectSource: GetObjectSourceFn, + connectionId: string, + database: string, + schema: string, + name: string, + objectType: ObjectSourceKind, + signature?: string, + relationName?: string, +): Promise<{ source: ObjectSource; objectType: ObjectSourceKind }> { + const primary = await getObjectSource(connectionId, database, schema, name, objectType, signature, relationName); + if (primary.source?.trim()) { + return { source: primary, objectType }; + } + + const fallbacks: ObjectSourceKind[] = objectType === "PROCEDURE" ? ["FUNCTION"] : objectType === "FUNCTION" ? ["PROCEDURE"] : objectType === "PACKAGE" ? ["PACKAGE_BODY"] : objectType === "PACKAGE_BODY" ? ["PACKAGE"] : []; + + for (const fallbackType of fallbacks) { + try { + const alternate = await getObjectSource(connectionId, database, schema, name, fallbackType, signature, relationName); + if (alternate.source?.trim()) { + return { source: alternate, objectType: fallbackType }; + } + } catch { + // Keep trying remaining fallbacks; surface the primary empty/error state if none succeed. + } + } + + return { source: primary, objectType }; +} + +/** + * Load raw object source then convert it to the editable editor form. + * + * For Oracle, bare `ALL_SOURCE` text like `procedure name is ...` becomes + * `CREATE OR REPLACE procedure name is ...` so the query tab shows deployable DDL + * (same wrapping ObjectSourceDialog already applies). + */ +export async function loadEditableObjectSourceForEditor( + getObjectSource: GetObjectSourceFn, + buildEditableObjectSource: BuildEditableObjectSourceFn, + options: { + connectionId: string; + database: string; + schema: string; + name: string; + objectType: ObjectSourceKind; + databaseType: DatabaseType; + signature?: string; + relationName?: string; + }, +): Promise<{ raw: ObjectSource; editableSource: string; objectType: ObjectSourceKind }> { + const { source: raw, objectType: resolvedType } = await loadObjectSourceWithRoutineFallback(getObjectSource, options.connectionId, options.database, options.schema, options.name, options.objectType, options.signature, options.relationName); + + const editableSource = await buildEditableObjectSource({ + databaseType: options.databaseType, + objectType: resolvedType, + schema: options.schema, + name: options.name, + source: raw.source, + }); + + return { + raw, + editableSource: editableSource.trim() ? editableSource : raw.source, + objectType: resolvedType, + }; +}