25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(oracle): strict routine compare, guarded deploy, trusted readback
efeire8762114741f5
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vueindex c6251da1fa..fbf3d13a9b 100644--- a/apps/desktop/src/App.vue+++ b/apps/desktop/src/App.vue@@ -101,8 +101,8 @@ import {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 { buildEditableObjectSource } from "@/lib/table/objectSourceEditor";+import { saveObjectSourceTab } from "@/lib/table/objectSourceTabSave";import { loadEditableObjectSourceForEditor } from "@/lib/table/objectSourceLoad";import { schemaAfterConnectionSwitch } from "@/lib/schema/connectionSchemaInitialization";import { canReuseTabForHistoryRestore, resolveHistorySqlRestoreTarget } from "@/lib/history/historyRestoreTarget";@@ -189,7 +189,6 @@ import { buildAppendedEditorSql, buildDeduplicatedAppendedEditorSql } from "@/liimport { resolveAiSqlTargetTabId, type AiSqlApplyTargetMode } from "@/lib/ai/aiSqlTargetTab";import { assessProductionSql } from "@/lib/database/productionSafety";import { normalizeSqlExecutionTarget, sqlExecutionTargetCapabilities } from "@/lib/database/sqlExecutionTargetCapabilities";-import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";import { buildHistoryAiAnalysisPrompt } from "@/lib/history/historyAiAnalysis";import { countAvailableAgentDriverUpdates } from "@/lib/connection/agentDriverUpdateBadge";import type { DriverStoreFocus, DriverStoreTab } from "@/lib/connection/agentDriverInstallHint";@@ -2734,54 +2733,7 @@ async function openSaveSqlDialog(tabId?: string) {}async function saveActiveObjectSource(tab: QueryTab): Promise<boolean> {- const connection = connectionStore.getConfig(tab.connectionId);- const source = tab.objectSource;- if (!connection || !source) return false;-- try {- const identity = queryStore.getObjectSourceIdentitySnapshot(tab)!;- assertSourceIdentity(identity);- const { connectionId, database } = tab;- const schema = source.schema || tab.schema || database;- const sql = tab.sql;- const databaseType = effectiveDatabaseTypeForConnection(connection) ?? connection.db_type;- const statements = await buildExecutableObjectSourceStatements({- databaseType,- objectType: source.objectType,- schema,- name: source.name,- source: sql,- });- const execute = async () => {- if (!queryStore.tabs.includes(tab) || tab.objectSource !== source || tab.connectionId !== connectionId || tab.database !== database || (source.schema || tab.schema || database) !== schema) return false;- const release = beginSourceSave(identity);- try {- await executeObjectSourceSave(connectionId, database, databaseType, statements, schema);- return true;- } finally {- release();- }- };- const executableSql = statements.filter((sql) => sql.trim()).join(";\n");- if (executableSql.trim()) {- const saved = await executeWithProductionSqlGuard({- connection,- database,- sql: executableSql,- source: t("production.sourceObjectSource"),- execute,- });- if (!saved) return false;- } else {- if (!(await execute())) return false;- }- if (tab.sql === sql) queryStore.markTabClean(tab);- toast(t("objects.sourceSaved"), 2000);- return true;- } catch (e: any) {- toast(t("objects.sourceSaveFailed", { message: e?.message || String(e) }), 5000);- return false;- }+ return saveObjectSourceTab(tab, { connection: connectionStore.getConfig(tab.connectionId), queryStore, t, toast });}function saveSqlFolderDisplayName(id: string) {diff --git a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vueindex 52f4049182..05fdaf61d6 100644--- a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue+++ b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue@@ -23,7 +23,8 @@ import {type SchemaDiffRoutineMatch,} from "@/lib/schema/schemaDiffRoutine";import { createSchemaDiffTableListCoordinator, reconcileSchemaDiffSelectedTables, shouldLoadSchemaDiffTableList, type SchemaDiffTableIdentity, type SchemaDiffTableListLoader, type SchemaDiffTableSide } from "@/lib/schema/schemaDiffTableList";-import { schemaDiffRoutineObjectTypes, schemaDiffRoutineObjectTypesIntersection, supportsSchemaDiffRoutines } from "@/lib/database/databaseObjectCapabilities";+import { schemaDiffRoutineObjectTypes, schemaDiffRoutineObjectTypesIntersection, supportsSchemaDiffRoutines, schemaDiffRoutineProductType } from "@/lib/database/databaseObjectCapabilities";+import { schemaDiffEngineDatabaseType } from "@/lib/schema/schemaDiff";import { useConnectionStore } from "@/stores/connectionStore";import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";import * as api from "@/lib/backend/api";@@ -266,7 +267,9 @@ const tableListCoordinator = createSchemaDiffTableListCoordinator({const canConfigureTableSelection = computed(() => isTableIdentityReady("source"));const tablesCompareEnabled = computed(() => !!props.options.tables);const routinesCompareEnabled = computed(() => !!props.options.functions);-const canEnableRoutinesCompare = computed(() => schemaDiffRoutineObjectTypesIntersection(sourceDbType.value as DatabaseType | undefined, targetDbType.value as DatabaseType | undefined).length > 0);+const sourceRoutineType = computed(() => schemaDiffRoutineProductType(sourceDbType.value, schemaDiffEngineDatabaseType(sourceConfig.value)));+const targetRoutineType = computed(() => schemaDiffRoutineProductType(targetDbType.value, schemaDiffEngineDatabaseType(targetConfig.value)));+const canEnableRoutinesCompare = computed(() => schemaDiffRoutineObjectTypesIntersection(sourceRoutineType.value, targetRoutineType.value).length > 0);/** User preference AND supported pair — drives compare/canCompare/Switch display. */const effectiveRoutinesEnabled = computed(() => routinesCompareEnabled.value && canEnableRoutinesCompare.value);@@ -296,7 +299,7 @@ const restrictRoutines = ref(false);const localSelectedRoutines = ref<string[]>([]);const loadingRoutines = ref(false);-const canConfigureRoutineSelection = computed(() => isTableIdentityReady("source") && supportsSchemaDiffRoutines(sourceDbType.value as DatabaseType));+const canConfigureRoutineSelection = computed(() => isTableIdentityReady("source") && supportsSchemaDiffRoutines(sourceRoutineType.value));const activeRoutineMappings = computed(() => identitySchemaDiffRoutineMappings(props.options?.routineMappings ?? []));const routineMatches = computed<SchemaDiffRoutineMatch[]>(() => buildSchemaDiffRoutineMatches(localSelectedRoutines.value, targetRoutineList.value, activeRoutineMappings.value));const matchedRoutineCount = computed(() => routineMatches.value.filter((match) => match.targetRoutine).length);@@ -367,7 +370,7 @@ async function loadRoutineList(side: "source" | "target") {const connectionId = side === "source" ? props.sourceConnectionId : props.targetConnectionId;const database = side === "source" ? props.sourceDatabase : props.targetDatabase;const schema = side === "source" ? props.sourceSchema : props.targetSchema;- const dbType = side === "source" ? sourceDbType.value : targetDbType.value;+ const dbType = side === "source" ? sourceRoutineType.value : targetRoutineType.value;if (!isTableIdentityReady(side) || !supportsSchemaDiffRoutines(dbType as DatabaseType)) {if (side === "source") sourceRoutineList.value = [];else {@@ -413,7 +416,7 @@ async function loadRoutineList(side: "source" | "target") {}watch(- () => [restrictRoutines.value, effectiveRoutinesEnabled.value, props.sourceConnectionId, props.sourceDatabase, props.sourceSchema, sourceDbType.value] as const,+ () => [restrictRoutines.value, effectiveRoutinesEnabled.value, props.sourceConnectionId, props.sourceDatabase, props.sourceSchema, sourceRoutineType.value] as const,([restrictEnabled, routinesEnabled]) => {if (!canConfigureRoutineSelection.value) {clearUnavailableRoutineSelection();@@ -426,9 +429,9 @@ watch();watch(- () => [restrictRoutines.value, localSelectedRoutines.value.length, props.targetConnectionId, props.targetDatabase, props.targetSchema, targetDbType.value] as const,+ () => [restrictRoutines.value, localSelectedRoutines.value.length, props.targetConnectionId, props.targetDatabase, props.targetSchema, targetRoutineType.value] as const,([enabled, selectedCount]) => {- if (!enabled || selectedCount === 0 || !isTableIdentityReady("target") || !supportsSchemaDiffRoutines(targetDbType.value as DatabaseType)) {+ if (!enabled || selectedCount === 0 || !isTableIdentityReady("target") || !supportsSchemaDiffRoutines(targetRoutineType.value)) {if (!enabled) {targetRoutineList.value = [];targetRoutineListLoaded.value = false;@@ -446,7 +449,7 @@ watch(selectedRoutines: props.selectedRoutines,}),(current, previous) => {- if (!isTableIdentityReady("source") || !supportsSchemaDiffRoutines(sourceDbType.value as DatabaseType)) {+ if (!isTableIdentityReady("source") || !supportsSchemaDiffRoutines(sourceRoutineType.value)) {clearUnavailableRoutineSelection();return;}diff --git a/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue b/apps/desktop/src/components/diff/SchemaDiffDeployStep.vueindex ecad0be1dc..b5e6676a9c 100644--- a/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue+++ b/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue@@ -9,6 +9,11 @@ import { useTheme } from "@/composables/useTheme";import { loadEditorTheme, editorFontTheme } from "@/lib/editor/editorThemes";import { createDbxCodeMirrorSqlDialect } from "@/lib/editor/codemirrorSqlDialect";import { Splitpanes, Pane } from "splitpanes";+import { oracleRoutineActiveStep, routineIdentityKey, type OracleRoutineDeployment } from "@/lib/schema/oracleRoutineDeploy";+import { oracleRoutineOperationVerified } from "@/lib/table/oracleRoutineWrite";+import { scalarPositionToUtf16Offset } from "@/lib/sql/errorPosition";+import type { OracleRoutineOperation } from "@/types/schemaDiff";+import type { DatabaseType } from "@/types/database";import {schemaDiffObjectSelectionState,schemaDiffReviewAlert,@@ -54,6 +59,8 @@ const props = defineProps<{showIgnoreForeignKeyChecks?: boolean;/** Skip failed statements and keep running the rest of the deploy script. */continueOnError?: boolean;+ databaseType?: DatabaseType;+ routineDeployment?: OracleRoutineDeployment | null;}>();const emit = defineEmits<{@@ -63,12 +70,69 @@ const emit = defineEmits<{"update:continueOnError": [enabled: boolean];back: [];deploy: [];+ "select-routine": [objectId: string];+ "validate-routines": [];+ "refresh-routines": [];+ "observe-routine": [operationId: string];+ "recover-routine": [operationId: string];}>();const editorContainer = ref<HTMLDivElement>();const editorView = shallowRef<any>(null);const isEditorReady = ref(false);const selectedObjectId = ref<string | null>(null);+let editorDisposed = false;+let readOnlyCompartment: any;+const routineDraft = computed(() => props.routineDeployment?.drafts.find((draft) => draft.objectId === props.routineDeployment?.selectedObjectId));+const routineStep = computed(() => (props.routineDeployment ? oracleRoutineActiveStep(props.routineDeployment) : undefined));+const routineRecord = computed(() => (props.routineDeployment?.recoveryPlan ? routineStep.value?.operation : routineDraft.value?.operation));+const routineHistory = computed(() => {+ const records = props.routineDeployment?.records.filter((record) => routineDraft.value && routineIdentityKey(record.identity) === routineIdentityKey(routineDraft.value.identity)) ?? [];+ return routineRecord.value && !records.some((record) => record.operationId === routineRecord.value?.operationId) ? [...records, routineRecord.value] : records;+});+const editorReadOnly = computed(() => !!props.routineDeployment && (props.executing || !!props.routineDeployment.recoveryPlan || (!!routineDraft.value?.operation && oracleRoutineOperationVerified(routineDraft.value.operation))));++function routineStatus(record?: OracleRoutineOperation | null, compact = false): string {+ if (!record) return t("diff.routineNeedsValidation");+ if (props.routineDeployment?.pendingOperationId === record.operationId || record.lifecycle === "running" || record.lifecycle === "unproven") return t("diff.routinePending");+ if (oracleRoutineOperationVerified(record)) return t("diff.routineVerified");+ if (record.lifecycle === "prepared") return t("diff.routinePrepared");+ if (record.readback?.state === "invalid") return t(compact ? "objects.invalid" : "objects.routineReadbackInvalid");+ return t("diff.routineUnverified");+}++async function locateOffset(offset: number) {+ if (!editorView.value) return;+ const { EditorView } = await import("@codemirror/view");+ if (!editorView.value || editorDisposed) return;+ editorView.value.dispatch({ selection: { anchor: offset }, effects: EditorView.scrollIntoView(offset, { y: "center" }) });+ editorView.value.focus();+}++function locateIssue(line: number, column: number) {+ void locateOffset(scalarPositionToUtf16Offset(effectiveSql.value, line, column));+}++function compilerOffset(line: number, column: number): number | undefined {+ if (line < 1 || column < 1) return;+ if (!routineStep.value || effectiveSql.value !== routineStep.value.sql || routineRecord.value?.readback?.definitionMatches !== true) return;+ const source = routineRecord.value.readback.source;+ if (!source) return;+ // ALL_ERRORS positions start at the stored FUNCTION/PROCEDURE unit, not CREATE.+ // Only map the known generated prefix; retain the database coordinates when a+ // more complicated representation cannot be aligned safely.+ const prefix = /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:NON)?EDITIONABLE\s+)?/i.exec(source);+ if (!prefix) return;+ const unit = source.slice(prefix[0].length).trimEnd();+ const terminated = unit.endsWith(";") ? unit : `${unit};`;+ const offset = scalarPositionToUtf16Offset(terminated, line, column);+ // The stored unit can omit the declaration's owner while the approved draft+ // includes it. Map only the unchanged suffix, never guess inside that header.+ let suffix = 0;+ while (suffix < Math.min(terminated.length, effectiveSql.value.length) && terminated[terminated.length - suffix - 1] === effectiveSql.value[effectiveSql.value.length - suffix - 1]) suffix++;+ if (offset < terminated.length - suffix) return;+ return effectiveSql.value.length - terminated.length + offset;+}// Parse object positions in deploySqlconst objectPositions = computed(() => {@@ -94,6 +158,10 @@ const objectPositions = computed(() => {});async function handleSelectObject(obj: SchemaDiffObject) {+ if (props.routineDeployment) {+ emit("select-routine", obj.id);+ return;+ }selectedObjectId.value = obj.id;if (editorView.value) {const pos = objectPositions.value.get(obj.id);@@ -156,9 +224,11 @@ async function initEditor() {if (!editorContainer.value) return;const [{ EditorView }, { EditorState, Compartment }, langSql, { basicSetup }] = await Promise.all([import("@codemirror/view"), import("@codemirror/state"), import("@codemirror/lang-sql"), import("codemirror")]);+ if (editorDisposed || !editorContainer.value) return;const themeComp = new Compartment();const fontComp = new Compartment();+ readOnlyCompartment = new Compartment();const editorTheme = settingsStore.editorSettings.theme;const appAppearance = isDark.value ? "dark" : "light";@@ -166,9 +236,10 @@ async function initEditor() {const fontFamily = settingsStore.editorSettings.fontFamily;const themeExt = await loadEditorTheme(editorTheme, appAppearance);+ if (editorDisposed || !editorContainer.value) return;const fontExt = editorFontTheme(EditorView, fontSize, fontFamily, { fixedHeight: true, scrollable: true });- const dialect = createDbxCodeMirrorSqlDialect(langSql, "postgres");+ const dialect = createDbxCodeMirrorSqlDialect(langSql, props.databaseType === "oracle" || props.databaseType === "oceanbase-oracle" ? "oracle" : "postgres");const state = EditorState.create({doc: effectiveSql.value,@@ -177,6 +248,7 @@ async function initEditor() {langSql.sql({ dialect }),themeComp.of(themeExt),fontComp.of(fontExt),+ readOnlyCompartment.of(EditorState.readOnly.of(editorReadOnly.value)),EditorView.updateListener.of((update: any) => {if (update.docChanged) {emit("update:deploySql", update.state.doc.toString());@@ -201,11 +273,19 @@ watch(},);+watch(editorReadOnly, async (readOnly) => {+ if (!editorView.value || !readOnlyCompartment) return;+ const { EditorState } = await import("@codemirror/state");+ if (!editorView.value || editorDisposed) return;+ editorView.value.dispatch({ effects: readOnlyCompartment.reconfigure(EditorState.readOnly.of(readOnly)) });+});+onMounted(() => {initEditor();});onUnmounted(() => {+ editorDisposed = true;editorView.value?.destroy();editorView.value = null;});@@ -355,7 +435,17 @@ function getObjectIconColor(kind: DiffObjectKind): string {<Splitpanes class="flex-1 min-h-0"><Pane size="30" min-size="20"><div class="h-full overflow-auto p-2 space-y-0.5">- <div v-for="obj in topLevelObjects" :key="obj.id" class="flex items-center gap-2 px-2 py-1.5 rounded text-xs hover:bg-accent/50 cursor-pointer" :class="{ 'bg-primary/10': selectedObjectId === obj.id }" @click="handleSelectObject(obj)">+ <div+ v-for="obj in topLevelObjects"+ :key="obj.id"+ role="button"+ tabindex="0"+ class="flex flex-wrap items-center gap-2 px-2 py-1.5 rounded text-xs hover:bg-accent/50 cursor-pointer focus-visible:ring-2 focus-visible:ring-ring"+ :class="{ 'bg-primary/10': (routineDeployment?.selectedObjectId ?? selectedObjectId) === obj.id }"+ @click="handleSelectObject(obj)"+ @keydown.enter.prevent="handleSelectObject(obj)"+ @keydown.space.prevent="handleSelectObject(obj)"+ ><component :is="operationIcons[obj.operationType]" class="w-3.5 h-3.5 shrink-0" :class="operationColors[obj.operationType]" /><component :is="getObjectIcon(obj.objectKind)" class="w-3.5 h-3.5 shrink-0" :class="getObjectIconColor(obj.objectKind)" /><span class="truncate">{{ obj.name }}</span>@@ -363,6 +453,7 @@ function getObjectIconColor(kind: DiffObjectKind): string {<span class="text-[10px] text-muted-foreground shrink-0 ml-auto">{{ getOperationLabel(obj.operationType) }}</span>+ <span v-if="routineDeployment" class="basis-full pl-5 text-xs text-muted-foreground">{{ routineStatus(routineDeployment.drafts.find((draft) => draft.objectId === obj.id)?.operation, true) }}</span></div><div v-if="topLevelObjects.length === 0" class="text-xs text-muted-foreground text-center py-4">{{ t("diff.noObjectsSelected") }}@@ -371,7 +462,57 @@ function getObjectIconColor(kind: DiffObjectKind): string {</Pane><Pane size="70" min-size="40">- <div ref="editorContainer" class="deploy-sql-editor h-full w-full" />+ <div class="flex h-full min-w-0 flex-col">+ <div v-if="routineDeployment" class="shrink-0 space-y-2 border-b px-3 py-2 text-xs">+ <div class="flex flex-wrap items-center gap-x-3 gap-y-1">+ <span v-if="routineDraft" class="break-all font-mono">{{ routineDraft.identity.owner }}.{{ routineDraft.identity.name }} · {{ routineDraft.identity.kind }}</span>+ <span class="ml-auto" aria-live="polite">{{ routineDeployment.validating ? t("diff.routineChecking") : routineStatus(routineRecord) }}</span>+ </div>+ <p v-if="routineDeployment.recoveryPlan" class="text-amber-700 dark:text-amber-300">{{ t("diff.routineRecoveryNote") }}</p>+ <p v-else-if="editorReadOnly && !executing" class="text-muted-foreground">{{ t("diff.routineReadOnlyCompleted") }}</p>+ <div v-if="routineDeployment.error || routineStep?.issues.length" role="alert" tabindex="-1" class="max-h-40 space-y-1 overflow-auto text-destructive">+ <p v-if="routineDeployment.error" class="whitespace-pre-wrap break-words">{{ routineDeployment.error }}</p>+ <button v-for="(issue, index) in routineStep?.issues ?? []" :key="index" type="button" class="block w-full text-left hover:underline focus-visible:ring-2 focus-visible:ring-ring" @click="locateIssue(issue.line, issue.column)">+ {{ issue.line }}:{{ issue.column }} — {{ issue.message }}+ </button>+ </div>+ <details v-if="routineStep?.targetOriginal" class="max-h-40 overflow-auto text-muted-foreground">+ <summary class="cursor-pointer">{{ t("diff.targetDdl") }}</summary>+ <pre class="mt-1 whitespace-pre-wrap break-words font-mono">{{ routineStep.targetOriginal }}</pre>+ <Button variant="ghost" size="sm" class="h-7 text-xs" @click="copyToClipboard(routineStep.targetOriginal)">{{ t("diff.copyTargetDdl") }}</Button>+ </details>+ <details v-if="routineStep?.incomingCallers.length" class="max-h-32 overflow-auto text-muted-foreground">+ <summary class="cursor-pointer">{{ t("diff.routineCallers") }} ({{ routineStep.incomingCallers.length }})</summary>+ <p v-for="(caller, index) in routineStep.incomingCallers" :key="index" class="mt-1 break-all font-mono">{{ caller.owner }}.{{ caller.name }} · {{ caller.kind }}</p>+ </details>+ <div v-if="routineRecord" class="max-h-56 space-y-1 overflow-auto break-words" aria-live="polite">+ <p v-if="routineRecord.dispatched">{{ routineRecord.acknowledged ? t("objects.routineWriteAcknowledged") : t("diff.routineDispatched") }}</p>+ <p v-if="routineRecord.error" class="whitespace-pre-wrap text-destructive">{{ routineRecord.error }}</p>+ <p v-for="(issue, index) in routineRecord.readback?.issues ?? []" :key="index" class="text-destructive">{{ issue.message }}</p>+ <button+ v-for="(message, index) in routineRecord.readback?.compilerMessages ?? []"+ :key="index"+ type="button"+ class="block w-full text-left"+ :class="message.attribute === 'ERROR' ? 'text-destructive' : 'text-amber-700 dark:text-amber-300'"+ :disabled="compilerOffset(message.line, message.position) === undefined"+ @click="locateOffset(compilerOffset(message.line, message.position)!)"+ >+ {{ message.attribute }} {{ message.line }}:{{ message.position }} — {{ message.text }}+ </button>+ <Button v-if="routineRecord.lifecycle !== 'prepared'" variant="outline" size="sm" class="h-7 text-xs" :disabled="executing || routineDeployment.validating" @click="emit('observe-routine', routineRecord.operationId)">{{ t("diff.routineObserve") }}</Button>+ <Button v-if="routineRecord.lifecycle === 'terminal' && routineRecord.dispatched" variant="ghost" size="sm" class="h-7 text-xs" :disabled="executing || routineDeployment.validating" @click="emit('recover-routine', routineRecord.operationId)">{{+ t("diff.routineRecoveryPreview")+ }}</Button>+ </div>+ <p v-if="routineDeployment.stopRequested" class="text-muted-foreground">{{ t("diff.routineStopped") }}</p>+ <details v-if="routineHistory.length" class="text-muted-foreground">+ <summary class="cursor-pointer">{{ t("diff.routineHistory", { count: routineHistory.length }) }}</summary>+ <p v-for="record in routineHistory" :key="record.operationId" class="mt-1 break-all font-mono">{{ record.operationId }} — {{ routineStatus(record, true) }}</p>+ </details>+ </div>+ <div ref="editorContainer" class="deploy-sql-editor min-h-0 w-full flex-1" />+ </div></Pane></Splitpanes>@@ -398,12 +539,14 @@ function getObjectIconColor(kind: DiffObjectKind): string {<input type="checkbox" class="accent-primary" :checked="ignoreForeignKeyChecks === true" :disabled="executing" @change="emit('update:ignoreForeignKeyChecks', ($event.target as HTMLInputElement).checked)" />{{ t("diff.ignoreForeignKeyChecks") }}</label>- <label class="flex items-center gap-1.5 text-xs" :class="executing ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'" :title="t('diff.continueOnErrorHint')">+ <label v-if="!routineDeployment" class="flex items-center gap-1.5 text-xs" :class="executing ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'" :title="t('diff.continueOnErrorHint')"><input type="checkbox" class="accent-primary" :checked="continueOnError === true" :disabled="executing" @change="emit('update:continueOnError', ($event.target as HTMLInputElement).checked)" />{{ t("diff.continueOnError") }}</label></div><div class="flex items-center gap-2">+ <Button v-if="routineDeployment" variant="outline" size="sm" class="h-7 text-xs" :disabled="executing || routineDeployment.validating" @click="emit('refresh-routines')">{{ t("diff.routineRefreshBaseline") }}</Button>+ <Button v-if="routineDeployment" variant="outline" size="sm" class="h-7 text-xs" :disabled="executing || routineDeployment.validating" @click="emit('validate-routines')">{{ t("diff.routineValidate") }}</Button><Button variant="ghost" size="sm" class="h-7 text-xs gap-1" @click="$emit('back')"><ArrowLeft class="w-3.5 h-3.5" />{{ t("diff.backToResult") }}diff --git a/apps/desktop/src/components/diff/SchemaDiffDialog.vue b/apps/desktop/src/components/diff/SchemaDiffDialog.vueindex f273f67c87..f144428f52 100644--- a/apps/desktop/src/components/diff/SchemaDiffDialog.vue+++ b/apps/desktop/src/components/diff/SchemaDiffDialog.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { computed, ref, watch, onBeforeUnmount, nextTick } from "vue";+import { computed, reactive, ref, watch, onBeforeUnmount, nextTick } from "vue";import { useI18n } from "vue-i18n";import { Dialog, DialogHeader, DialogTitle, DialogFooter, DialogContent } from "@/components/ui/dialog";import { Button } from "@/components/ui/button";@@ -27,10 +27,23 @@ import { buildContinueOnErrorDeployLog, buildDeployTxResult, type DeployTxResultimport { getSchemaDiffNextProgressStep, isSchemaDiffPostgresLike, shouldLoadSchemaDiffExtraObjectPhase, type SchemaDiffProgressPhase } from "@/lib/schema/schemaDiffProgress";import { createSchemaDiffTableListLoader } from "@/lib/schema/schemaDiffTableList";import { countSchemaDiffActionableObjects, partitionSchemaDiffObjectsByResultTab, swapSchemaDiffRoutineMappings } from "@/lib/schema/schemaDiffRoutine";-import { schemaDiffRoutineObjectTypesIntersection } from "@/lib/database/databaseObjectCapabilities";+import { schemaDiffRoutineObjectTypesIntersection, schemaDiffRoutineProductType } from "@/lib/database/databaseObjectCapabilities";import { loadObjectSourceWithRoutineFallback } from "@/lib/table/objectSourceLoad";import { copyToClipboard } from "@/lib/common/clipboard";import { normalizeSchemaDiffCompareOptions } from "@/types/schemaDiff";+import {+ createOracleRoutineDeployment,+ editOracleRoutineDraft,+ executeOracleRoutineDeployment,+ observeOracleRoutineDeployment,+ oracleRoutineActiveStep,+ oracleRoutinePlanSql,+ prepareOracleRoutineRecovery,+ refreshOracleRoutineDeployment,+ selectOracleRoutineDraft,+ synchronizeOracleRoutineSelection,+ validateOracleRoutineDeployment,+} from "@/lib/schema/oracleRoutineDeploy";import type { SchemaDiffCompareOptions, SchemaDiffConfig, FieldMappingEntry, SchemaDiffTableMapping, SchemaDiffRoutineMapping } from "@/types/schemaDiff";import { getSchemaDiffSession, schemaDiffSessionObjects, startSchemaDiffSession, type SchemaDiffSession } from "@/composables/useSchemaDiffSession";import type { DatabaseType, ObjectSourceKind } from "@/types/database";@@ -141,6 +154,7 @@ const activeSessionId = ref<string | null>(props.sessionId ?? null);let appliedSessionResult: SchemaDiffPreparation | null = null;let shownSessionError = "";let componentUnmounted = false;+let suppressTargetIdentityReset = false;const diffObjects = ref<SchemaDiffObject[]>([]);const tableDiffGroups = ref<OperationGroup[]>([]);const routineDiffGroups = ref<OperationGroup[]>([]);@@ -175,13 +189,78 @@ const tableActionableCount = computed(() => countSchemaDiffActionableObjects(tabconst routineActionableCount = computed(() => countSchemaDiffActionableObjects(routineDiffObjects.value));const tablesCompareEnabled = computed(() => !!schemaDiffPanelOptions.value.tables);const routinesCompareEnabled = computed(() => !!schemaDiffPanelOptions.value.functions);-const canEnableRoutinesCompare = computed(() => schemaDiffRoutineObjectTypesIntersection(sourceDbType.value as DatabaseType | undefined, targetDbType.value as DatabaseType | undefined).length > 0);+const canEnableRoutinesCompare = computed(() => schemaDiffRoutineObjectTypesIntersection(schemaDiffRoutineProductType(sourceDbType.value, sourceEngineDbType.value), schemaDiffRoutineProductType(targetDbType.value, targetEngineDbType.value)).length > 0);const effectiveRoutinesEnabled = computed(() => routinesCompareEnabled.value && canEnableRoutinesCompare.value);const showTableResultTab = computed(() => tablesCompareEnabled.value);const showRoutineResultTab = computed(() => effectiveRoutinesEnabled.value);const showResultTabList = computed(() => showTableResultTab.value && showRoutineResultTab.value);const showNoDifferences = computed(() => showTableResultTab.value && tableDiffObjects.value.length === 0);-const showRoutineNoDifferences = computed(() => showRoutineResultTab.value && routineDiffObjects.value.length === 0);+const routineInventoriesComplete = computed(() => !!comparisonSession.value?.routineSnapshots?.source?.enumerationComplete && !!comparisonSession.value?.routineSnapshots?.target?.enumerationComplete);+const showRoutineNoDifferences = computed(() => showRoutineResultTab.value && routineDiffObjects.value.length === 0 && (!isOracleRoutineComparison.value || routineInventoriesComplete.value));+const comparisonSession = computed(() => getSchemaDiffSession(activeSessionId.value));+const isOracleRoutineComparison = computed(() => {+ const snapshots = comparisonSession.value?.routineSnapshots;+ return !!snapshots?.source && !!snapshots.target && [snapshots.source.endpoint.databaseType, snapshots.target.endpoint.databaseType].every((type) => type === "oracle" || type === "oceanbase-oracle");+});+const isOracleRoutineDeploy = computed(() => resultTab.value === "routines" && isOracleRoutineComparison.value);+const routineDeployment = computed(() => comparisonSession.value?.routineDeployment);+const routineTargetIsCurrent = computed(() => {+ const snapshots = comparisonSession.value?.routineSnapshots;+ return (+ !!snapshots?.source &&+ !!snapshots.target &&+ snapshots.source.endpoint.databaseType === snapshots.target.endpoint.databaseType &&+ snapshots.source.endpoint.connectionId === sourceConnectionId.value &&+ snapshots.source.endpoint.database === sourceDatabase.value &&+ snapshots.source.endpoint.schema === sourceSchema.value &&+ snapshots.target.endpoint.connectionId === targetConnectionId.value &&+ snapshots.target.endpoint.database === targetDatabase.value &&+ snapshots.target.endpoint.schema === targetSchema.value &&+ sourceEngineDbType.value === snapshots.source.endpoint.databaseType &&+ targetEngineDbType.value === snapshots.target.endpoint.databaseType+ );+});+const deployIsBusy = computed(() => executing.value || !!routineDeployment.value?.executing || !!routineDeployment.value?.validating);+const routineReadIssues = computed(() => {+ if (!isOracleRoutineComparison.value) return [];+ return (["source", "target"] as const).flatMap((side) => {+ const snapshot = comparisonSession.value?.routineSnapshots?.[side];+ const object = snapshot?.objects.find((object) => object.version.identity.name === selectedObject.value?.name);+ return [...(snapshot?.issues ?? []), ...(object?.issues ?? [])].map((issue) => ({ side, message: issue.message }));+ });+});+const deployEditorSql = computed({+ get: () => {+ if (!isOracleRoutineDeploy.value || !routineDeployment.value) return selectedDeploySql.value;+ const state = routineDeployment.value;+ return state.recoveryPlan ? (oracleRoutineActiveStep(state)?.sql ?? "") : (state.drafts.find((draft) => draft.objectId === state.selectedObjectId)?.sql ?? "");+ },+ set: (sql: string) => {+ if (!isOracleRoutineDeploy.value || !routineDeployment.value) {+ selectedDeploySql.value = sql;+ return;+ }+ if (!routineDeployment.value.recoveryPlan && routineDeployment.value.selectedObjectId) editOracleRoutineDraft(routineDeployment.value, routineDeployment.value.selectedObjectId, sql);+ },+});+let routineConfirmRevision: number | null = null;++function ensureRoutineDeployment() {+ const session = comparisonSession.value;+ if (!isOracleRoutineComparison.value || !session?.routineSnapshots?.source || !session.routineSnapshots.target) return;+ session.routineDeployment ??= reactive(createOracleRoutineDeployment(session.routineSnapshots.source, session.routineSnapshots.target));+ synchronizeOracleRoutineSelection(session.routineDeployment, routineDiffObjects.value);+ return session.routineDeployment;+}++function leaveDeployReview() {+ const state = routineDeployment.value;+ if (state) {+ state.stopRequested = true;+ state.reviewOpen = false;+ }+ step.value = "result";+}// Phase 4 result fieldsconst rollbackSql = ref("");@@ -339,6 +418,7 @@ watch(onBeforeUnmount(() => {componentUnmounted = true;+ if (routineDeployment.value) routineDeployment.value.stopRequested = true;teardownResizeObserver();});@@ -363,7 +443,7 @@ const selectedTreeObject = computed(() => {return findSchemaDiffObject(diffObjects.value, selectedObjectId.value);});-const canDeployRoutines = computed(() => isSchemaDiffPostgresLike(targetDbType.value));+const canDeployRoutines = computed(() => (isOracleRoutineComparison.value ? routineTargetIsCurrent.value : isSchemaDiffPostgresLike(targetDbType.value)));const canDeploy = computed(() => {// MySQL/SQL Server routine sync is deferred (copy DDL only). Postgres-family@@ -470,12 +550,12 @@ function restoreSchemaDiffSession(session: SchemaDiffSession): void {targetSchema: config.targetSchema,});updateActiveConfigOptions(config.options);- schemaDiffHasExtraObjectPhase.value = shouldLoadSchemaDiffExtraObjectPhase(config.sourceDbType, config.targetDbType, config.options);+ schemaDiffHasExtraObjectPhase.value = shouldLoadSchemaDiffExtraObjectPhase(schemaDiffRoutineProductType(config.sourceDbType, config.sourceEngineDbType), schemaDiffRoutineProductType(config.targetDbType, config.targetEngineDbType), config.options);}function applySchemaDiffSession(session: SchemaDiffSession | undefined): void {if (!session) return;- schemaDiffHasExtraObjectPhase.value = shouldLoadSchemaDiffExtraObjectPhase(session.config.sourceDbType, session.config.targetDbType, session.config.options);+ schemaDiffHasExtraObjectPhase.value = shouldLoadSchemaDiffExtraObjectPhase(schemaDiffRoutineProductType(session.config.sourceDbType, session.config.sourceEngineDbType), schemaDiffRoutineProductType(session.config.targetDbType, session.config.targetEngineDbType), session.config.options);if (session.status === "running") {loading.value = true;step.value = "compare";@@ -506,6 +586,12 @@ function applySchemaDiffSession(session: SchemaDiffSession | undefined): void {permissionDiffs.value = session.result.permissionDiffs ?? [];dependencyGraph.value = normalizeSchemaDiffDependencyGraph(session.result.dependencyGraph);diffObjects.value = schemaDiffSessionObjects(session.result);+ if (session.routineDeployment) {+ for (const object of diffObjects.value) {+ const saved = session.routineDeployment.drafts.find((draft) => draft.objectId === object.id);+ if (saved) object.selected = saved.included;+ }+ }rebuildDiffGroups();const hasTableActions = showTableResultTab.value && countSchemaDiffActionableObjects(tableDiffObjects.value) > 0;const hasRoutineActions = showRoutineResultTab.value && countSchemaDiffActionableObjects(routineDiffObjects.value) > 0;@@ -530,6 +616,7 @@ function applySchemaDiffSession(session: SchemaDiffSession | undefined): void {deploySqlMode.value = "forward";void regenerateSelectedDeploySql();void regenerateFocusedDeploySql();+ if (session.routineDeployment?.reviewOpen) step.value = "deploy-review";}// A Compare session deliberately outlives this v-if-mounted dialog. Closing the@@ -537,7 +624,10 @@ function applySchemaDiffSession(session: SchemaDiffSession | undefined): void {watch([() => open.value, () => props.sessionId],([isOpen]) => {- if (!isOpen) return;+ if (!isOpen) {+ if (routineDeployment.value) routineDeployment.value.stopRequested = true;+ return;+ }const session = getSchemaDiffSession(props.sessionId);activeSessionId.value = session?.id ?? null;appliedSessionResult = null;@@ -593,9 +683,6 @@ watch([sourceConnectionId, sourceDatabase, sourceSchema, targetConnectionId, tar});});-/** Suppress target-identity resets while restoring session/history/swap. */-let suppressTargetIdentityReset = false;-function runWithoutTargetIdentityReset(action: () => void): void {suppressTargetIdentityReset = true;try {@@ -607,6 +694,10 @@ function runWithoutTargetIdentityReset(action: () => void): void {}}+watch([sourceConnectionId, sourceDatabase, sourceSchema, targetConnectionId, targetDatabase, targetSchema], () => {+ if (!suppressTargetIdentityReset && routineDeployment.value) routineDeployment.value.stopRequested = true;+});+function handleSourceConnectionChange(connectionId: string): void {if (connectionId === sourceConnectionId.value) return;sourceConnectionId.value = connectionId;@@ -765,7 +856,7 @@ function handleCompare(): void {appliedSessionResult = null;shownSessionError = "";resetComparisonResultState();- schemaDiffHasExtraObjectPhase.value = shouldLoadSchemaDiffExtraObjectPhase(sourceDbType, targetDbType, options);+ schemaDiffHasExtraObjectPhase.value = shouldLoadSchemaDiffExtraObjectPhase(schemaDiffRoutineProductType(sourceDbType, sourceEngineDbType.value), schemaDiffRoutineProductType(targetDbType, targetEngineDbType.value), options);const session = startSchemaDiffSession({sourceConnectionId: sourceConnectionId.value,@@ -875,6 +966,10 @@ async function regenerateSelectedDeploySql() {if (!result) {return;}+ if (isOracleRoutineDeploy.value) {+ ensureRoutineDeployment();+ return;+ }const options = normalizeSchemaDiffCompareOptions(activeConfig.value?.options, getDbType());const input = selectSchemaDiffInput(result, currentTabDiffObjects.value);@@ -901,6 +996,7 @@ async function regenerateFocusedDeploySql(objectId: string | null = selectedObjefocusedForwardDeploySql.value = "";focusedRollbackSql.value = "";focusedDeploySql.value = "";+ if (isOracleRoutineDeploy.value) return;if (!result || !objectId || !findSchemaDiffObject(diffObjects.value, objectId)) {return;}@@ -936,6 +1032,10 @@ function switchDeploySqlMode(mode: "forward" | "rollback") {}const canExecuteDeploy = computed(() => {+ if (isOracleRoutineDeploy.value) {+ const state = routineDeployment.value;+ return routineTargetIsCurrent.value && !!(state?.recoveryPlan ?? state?.plan)?.ready && !deployIsBusy.value;+ }if (deploySqlMode.value === "rollback" && rollbackCompleteness.value === "incomplete") {return false;}@@ -945,7 +1045,7 @@ const canExecuteDeploy = computed(() => {const destructiveStatements = computed(() => {const databaseType = store.getConfig(targetConnectionId.value)?.db_type;- return detectDestructiveSchemaDiffStatements(selectedDeploySql.value, databaseType);+ return detectDestructiveSchemaDiffStatements(isOracleRoutineDeploy.value && routineDeployment.value ? oracleRoutinePlanSql(routineDeployment.value) : selectedDeploySql.value, databaseType);});function applyRename(rc: RenameCandidate) {@@ -995,6 +1095,10 @@ function ignoreRename(index: number) {}async function handleExecuteScript() {+ if (isOracleRoutineDeploy.value) {+ await handleDeployReview();+ return;+ }if (!selectedDeploySql.value.trim() || selectedDeploySql.value.trim() === "-- No objects selected") {toast(t("diff.noObjectsSelected"), 3000);return;@@ -1008,6 +1112,20 @@ async function handleExecuteScript() {}async function executeDeploySql() {+ if (isOracleRoutineDeploy.value && routineDeployment.value) {+ const state = routineDeployment.value;+ if (!routineTargetIsCurrent.value) return;+ await executeOracleRoutineDeployment(state, (sql, execute) =>+ executeWithProductionSqlGuard({+ connection: store.getConfig(state.target.endpoint.connectionId),+ database: state.target.endpoint.database,+ sql,+ source: t("production.sourceSchemaDiff"),+ execute,+ }),+ );+ return;+ }executing.value = true;try {const targetConnection = store.getConfig(targetConnectionId.value);@@ -1079,6 +1197,9 @@ async function handleSelectObject(reviewObject: SchemaDiffObject) {}if (obj.objectKind !== "function") return;+ // Strict snapshots retain incomplete reads and their issues; an ordinary+ // fallback must not silently replace that evidence with an unverified source.+ if (isOracleRoutineComparison.value) return;const preferredKind: ObjectSourceKind = obj.routineType === "PROCEDURE" ? "PROCEDURE" : "FUNCTION";@@ -1262,7 +1383,7 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st}}-function handleDeployReview() {+async function handleDeployReview() {if (resultTab.value === "routines" && !canDeployRoutines.value) return;const selectedObjects = selectedSchemaDiffObjects(currentTabDiffObjects.value);if (selectedObjects.length === 0) {@@ -1270,10 +1391,21 @@ function handleDeployReview() {return;}step.value = "deploy-review";+ if (isOracleRoutineDeploy.value) {+ const state = ensureRoutineDeployment();+ if (state) {+ state.reviewOpen = true;+ if (!state.plan && !state.recoveryPlan && !state.executing) await validateOracleRoutineDeployment(state);+ }+ }fetchDbVersion(targetConnectionId.value, targetDatabase.value, targetSchema.value);}async function handleDeploy() {+ if (isOracleRoutineDeploy.value) {+ if (!canExecuteDeploy.value) return;+ routineConfirmRevision = routineDeployment.value?.revision ?? null;+ }if (deploySqlMode.value === "rollback" && rollbackCompleteness.value === "incomplete") {toast(t("diff.rollbackIncompleteBlocked"), 5000);return;@@ -1283,6 +1415,7 @@ async function handleDeploy() {async function onConfirmDeploy() {showConfirmDialog.value = false;+ if (isOracleRoutineDeploy.value && (routineConfirmRevision !== routineDeployment.value?.revision || !canExecuteDeploy.value)) return;if (deploySqlMode.value === "rollback" && rollbackCompleteness.value === "incomplete") {toast(t("diff.rollbackIncompleteBlocked"), 5000);return;@@ -1292,6 +1425,10 @@ async function onConfirmDeploy() {}const deployStats = computed(() => {+ if (isOracleRoutineDeploy.value && routineDeployment.value) {+ const steps = (routineDeployment.value.recoveryPlan ?? routineDeployment.value.plan)?.steps ?? [];+ return { create: steps.filter((step) => step.action === "create").length, modify: steps.filter((step) => step.action === "replace").length, delete: steps.filter((step) => step.action === "delete").length, total: steps.length };+ }const counts = summarizeSchemaDiffOperations(currentTabDiffObjects.value);return {create: counts.create,@@ -1493,13 +1630,24 @@ const targetConnectionInfo = computed(() => {</TabsContent><TabsContent v-if="showRoutineResultTab" value="routines" class="mt-0 flex min-h-0 flex-1 flex-col outline-none data-[state=inactive]:hidden">+ <div v-if="routineReadIssues.length || (selectedObject?.operationType === 'none' && selectedObject.changes?.length)" role="status" class="mx-3 mt-2 max-h-32 shrink-0 space-y-1 overflow-auto text-xs text-amber-700 dark:text-amber-300">+ <p v-for="(issue, index) in routineReadIssues" :key="index">{{ t(issue.side === "source" ? "diff.sourceObject" : "diff.targetObject") }} — {{ issue.message }}</p>+ <p v-for="(change, index) in selectedObject?.operationType === 'none' ? (selectedObject.changes ?? []) : []" :key="`change-${index}`">{{ change }}</p>+ </div><div v-if="showRoutineNoDifferences" class="mx-3 mt-2 shrink-0 rounded-md border border-dashed bg-muted/20 px-3 py-2 text-center text-xs text-muted-foreground">{{ t("diff.noDifferences") }}</div><Splitpanes horizontal class="min-h-0 flex-1" @resized="handleSplitpanesResized"><Pane :size="splitpanesSize" min-size="20"><div class="h-full overflow-auto">- <SchemaDiffRoutineList :objects="routineDiffObjects" :viewing-object-id="selectedRoutineObjectId" :selectable="canDeployRoutines" :empty-text="t('diff.noDifferences')" @toggle-selection="handleToggleObjectSelection" @view-diff="handleViewRoutineDiff" />+ <SchemaDiffRoutineList+ :objects="routineDiffObjects"+ :viewing-object-id="selectedRoutineObjectId"+ :selectable="canDeployRoutines"+ :empty-text="t(isOracleRoutineComparison && !routineInventoriesComplete ? 'diff.routineUnreadable' : 'diff.noDifferences')"+ @toggle-selection="handleToggleObjectSelection"+ @view-diff="handleViewRoutineDiff"+ /></div></Pane><Pane :size="100 - splitpanesSize" min-size="20">@@ -1533,7 +1681,7 @@ const targetConnectionInfo = computed(() => {<!-- Deploy Review Step --><template v-else-if="step === 'deploy-review'"><SchemaDiffDeployStep- v-model:deploy-sql="selectedDeploySql"+ v-model:deploy-sql="deployEditorSql"v-model:ignore-foreign-key-checks="ignoreForeignKeyChecks"v-model:continue-on-error="continueOnError":show-ignore-foreign-key-checks="isMysqlDeployTarget"@@ -1541,8 +1689,10 @@ const targetConnectionInfo = computed(() => {:target-connection-id="targetConnectionId":target-database="targetDatabase":target-schema="targetSchema"- :executing="executing"- :rollback-sql="rollbackSql"+ :executing="deployIsBusy"+ :database-type="targetEngineDbType"+ :routine-deployment="isOracleRoutineDeploy ? routineDeployment : null"+ :rollback-sql="isOracleRoutineDeploy ? undefined : rollbackSql":deploy-sql-mode="deploySqlMode":compatibility-warnings="selectedCompatibilityWarnings":rename-candidates="renameCandidates"@@ -1551,8 +1701,17 @@ const targetConnectionInfo = computed(() => {:can-execute="canExecuteDeploy":destructive-statement-count="destructiveStatements.length"@update:deploy-sql-mode="switchDeploySqlMode"- @back="step = 'result'"+ @back="leaveDeployReview"@deploy="handleDeploy"+ @select-routine="+ (id) => {+ if (routineDeployment) selectOracleRoutineDraft(routineDeployment, id);+ }+ "+ @validate-routines="routineDeployment && validateOracleRoutineDeployment(routineDeployment)"+ @refresh-routines="routineDeployment && refreshOracleRoutineDeployment(routineDeployment)"+ @observe-routine="(id) => routineDeployment && observeOracleRoutineDeployment(routineDeployment, id)"+ @recover-routine="(id) => routineDeployment && prepareOracleRoutineRecovery(routineDeployment, id)"/></template></div>@@ -1575,8 +1734,8 @@ const targetConnectionInfo = computed(() => {<p v-if="showRoutineDeployDeferredHint" class="max-w-md text-right text-[11px] text-muted-foreground">{{ t("diff.routineSyncDeferredHint") }}</p>- <Button v-else size="sm" :disabled="!canDeploy || executing" @click="handleDeployReview">- <Loader2 v-if="executing" class="w-3.5 h-3.5 mr-1 animate-spin" />+ <Button v-else size="sm" :disabled="!canDeploy || deployIsBusy" @click="handleDeployReview">+ <Loader2 v-if="deployIsBusy" class="w-3.5 h-3.5 mr-1 animate-spin" /><Play v-else class="w-3.5 h-3.5 mr-1" />{{ deployButtonLabel }}</Button>@@ -1625,7 +1784,7 @@ const targetConnectionInfo = computed(() => {</ul></div>- <label class="flex items-start gap-2 rounded border border-yellow-300 bg-yellow-50 p-3 text-xs text-yellow-800 dark:border-yellow-700 dark:bg-yellow-950/30 dark:text-yellow-200" :class="executing ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'">+ <label v-if="!isOracleRoutineDeploy" class="flex items-start gap-2 rounded border border-yellow-300 bg-yellow-50 p-3 text-xs text-yellow-800 dark:border-yellow-700 dark:bg-yellow-950/30 dark:text-yellow-200" :class="executing ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'"><input v-model="continueOnError" type="checkbox" class="mt-0.5 accent-primary" :disabled="executing" /><span><span class="font-medium">{{ t("diff.continueOnError") }}</span>@@ -1636,8 +1795,8 @@ const targetConnectionInfo = computed(() => {<DialogFooter><Button variant="outline" @click="showConfirmDialog = false">{{ t("diff.cancel") }}</Button>- <Button variant="destructive" :disabled="executing" @click="onConfirmDeploy">- <Loader2 v-if="executing" class="w-3.5 h-3.5 mr-1 animate-spin" />+ <Button variant="destructive" :disabled="deployIsBusy || (isOracleRoutineDeploy && !canExecuteDeploy)" @click="onConfirmDeploy">+ <Loader2 v-if="deployIsBusy" class="w-3.5 h-3.5 mr-1 animate-spin" />{{ t("diff.confirmDeploy") }}</Button></DialogFooter>diff --git a/apps/desktop/src/components/diff/SchemaDiffRoutineList.vue b/apps/desktop/src/components/diff/SchemaDiffRoutineList.vueindex d524a7159a..c1052195c1 100644--- a/apps/desktop/src/components/diff/SchemaDiffRoutineList.vue+++ b/apps/desktop/src/components/diff/SchemaDiffRoutineList.vue@@ -46,6 +46,7 @@ function hasStats(stats: SchemaDiffRoutineTextDiffStats): boolean {}function onCheckboxChange(object: SchemaDiffObject, event: Event) {+ if (object.operationType === "none") return;emit("toggle-selection", object, (event.target as HTMLInputElement).checked);}@@ -79,7 +80,17 @@ function onRowActivate(object: SchemaDiffObject) {@keydown.enter.prevent="onRowActivate(row.object)"@keydown.space.prevent="onRowActivate(row.object)">- <input v-if="showSelection" type="checkbox" class="accent-primary justify-self-center" :checked="row.selection.checked" :indeterminate="row.selection.indeterminate" @click.stop @change="onCheckboxChange(row.object, $event)" />+ <input+ v-if="showSelection"+ type="checkbox"+ class="accent-primary justify-self-center"+ :checked="row.selection.checked"+ :indeterminate="row.selection.indeterminate"+ :disabled="row.object.operationType === 'none'"+ :aria-label="displayName(row.object, 'source') || displayName(row.object, 'target')"+ @click.stop+ @change="onCheckboxChange(row.object, $event)"+ /><div class="min-w-0 truncate font-mono" :title="row.sourceLabel || undefined"><span v-if="row.sourceLabel" :class="row.object.operationType === 'create' ? 'text-green-600 dark:text-green-400' : ''">{{ row.sourceLabel }}</span><span v-else class="text-muted-foreground">—</span>@@ -89,7 +100,10 @@ function onRowActivate(object: SchemaDiffObject) {<span v-else class="text-muted-foreground">—</span></div><div class="min-w-0 truncate tabular-nums" :title="hasStats(row.stats) ? t('diff.routineDiffStats', { added: row.stats.added, removed: row.stats.removed, modified: row.stats.modified }) : undefined">- <template v-if="hasStats(row.stats)">+ <span v-if="row.object.routineComparisonState === 'equal'" class="text-muted-foreground">{{ t("diff.routineEqual") }}</span>+ <span v-else-if="row.object.routineComparisonState === 'unreadable'" class="text-amber-700 dark:text-amber-300">{{ t("diff.routineUnreadable") }}</span>+ <span v-else-if="row.object.routineComparisonState === 'conflict'" class="text-destructive">{{ t("diff.routineConflict") }}</span>+ <template v-else-if="hasStats(row.stats)"><span class="text-green-600 dark:text-green-400">+{{ row.stats.added }}</span><span class="text-muted-foreground"> </span><span class="text-red-500 dark:text-red-400">−{{ row.stats.removed }}</span>diff --git a/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.ts b/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.tsindex fef4a7c4d1..a8a72b27da 100644--- a/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.ts+++ b/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.ts@@ -3,8 +3,13 @@import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";import { afterEach, describe, expect, it, vi } from "vitest";import SchemaDiffDeployStep from "@/components/diff/SchemaDiffDeployStep.vue";+import { createOracleRoutineDeployment, synchronizeOracleRoutineSelection } from "@/lib/schema/oracleRoutineDeploy";+import type { OracleRoutineOperation } from "@/types/schemaDiff";++const editor = vi.hoisted(() => ({ focus: vi.fn(), dispatch: vi.fn(), readOnly: vi.fn((_value: boolean) => []), dialect: vi.fn((_language: unknown, _dialect: string) => undefined) }));vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("@/i18n", () => ({ default: { global: { t: (key: string) => key } } }));vi.mock("@/stores/settingsStore", () => ({useSettingsStore: () => ({ editorSettings: { theme: "default", fontSize: 12, fontFamily: "monospace" } }),@@ -19,7 +24,7 @@ vi.mock("@/lib/editor/editorThemes", () => ({editorFontTheme: () => [],}));-vi.mock("@/lib/editor/codemirrorSqlDialect", () => ({ createDbxCodeMirrorSqlDialect: () => undefined }));+vi.mock("@/lib/editor/codemirrorSqlDialect", () => ({ createDbxCodeMirrorSqlDialect: editor.dialect }));// The deploy script preview is a CodeMirror view; the option under test lives in// the footer, so the editor is replaced with the smallest view that still accepts@@ -32,19 +37,24 @@ vi.mock("@codemirror/view", () => ({constructor(config: { state: { doc: { toString: () => string; length: number } } }) {this.state = config.state;}- dispatch() {}+ dispatch = editor.dispatch;+ focus = editor.focus;destroy() {}},}));vi.mock("@codemirror/state", () => ({EditorState: {+ readOnly: { of: editor.readOnly },create: (config: { doc: string }) => ({ doc: { toString: () => config.doc, length: config.doc.length } }),},Compartment: class {of() {return [];}+ reconfigure() {+ return [];+ }},}));@@ -130,6 +140,104 @@ describe("SchemaDiffDeployStep continue-on-error option", () => {afterEach(() => {for (const app of mountedApps.splice(0)) app.unmount();document.body.innerHTML = "";+ vi.clearAllMocks();+});++function routineFixture() {+ const endpoint = { connectionId: "target", database: "tenant", schema: "Owner.With.Dot", databaseType: "oceanbase-oracle" as const, generation: 1 };+ const snapshot = { endpoint, state: "complete" as const, enumerationComplete: true, objects: [], issues: [] };+ const state = reactive(createOracleRoutineDeployment(snapshot, snapshot));+ const object = { id: "func-F", name: "F", routineType: "FUNCTION", objectKind: "function" as const, operationType: "create" as const, selected: true };+ synchronizeOracleRoutineSelection(state, [object]);+ const identity = state.drafts[0].identity;+ const sql = 'CREATE FUNCTION "Owner.With.Dot"."F" RETURN NUMBER AS BEGIN RETURN 1; END;';+ state.drafts[0].sql = sql;+ state.plan = {+ target: endpoint,+ ready: false,+ steps: [{ identity, action: "create", sql, sourceOriginal: "raw source", targetOriginal: null, recoverySql: null, recoveryComplete: true, references: [], incomingCallers: [], operation: null, issues: [{ code: "unsupported", message: "Use a static reference", line: 1, column: 5 }] }],+ };+ return { state, object, sql, endpoint, identity };+}++describe("SchemaDiffDeployStep Oracle routine review", () => {+ it("keeps the editable draft and positioned issues in the existing editor, with explicit revalidation", async () => {+ const { state, object, sql } = routineFixture();+ const validate = vi.fn();+ const update = vi.fn();+ const { container } = await mountDeployStep({ deploySql: sql, selectedObjects: [object], databaseType: "oceanbase-oracle", routineDeployment: state, canExecute: false, onValidateRoutines: validate, "onUpdate:deploySql": update });+ expect(editor.dialect.mock.calls[0]?.[1]).toBe("oracle");+ expect(continueOnErrorCheckbox(container)).toBeNull();+ const issue = [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("1:5 — Use a static reference"));+ expect(issue).toBeDefined();+ issue!.click();+ await nextTick();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(editor.dispatch).toHaveBeenCalledWith(expect.objectContaining({ selection: { anchor: 4 } }));+ expect(editor.focus).toHaveBeenCalled();+ const buttons = [...container.querySelectorAll<HTMLButtonElement>("button")];+ buttons.find((button) => button.textContent?.trim() === "diff.routineValidate")!.click();+ expect(validate).toHaveBeenCalledTimes(1);+ expect(buttons.find((button) => button.textContent?.trim() === "diff.deployToServer")!.disabled).toBe(true);+ expect(update).not.toHaveBeenCalled();+ });++ it("displays ACK and compiler evidence without a success label, and only locks verified definitions", async () => {+ const { state, object, sql, endpoint, identity } = routineFixture();+ const record: OracleRoutineOperation = {+ operationId: "original-invalid",+ target: endpoint,+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ error: null,+ readback: { identity, state: "invalid", exists: true, version: null, source: sql, definitionMatches: true, issues: [], compilerMessages: [{ attribute: "ERROR", line: 1, position: 20, text: "invalid identifier" }] },+ };+ state.drafts[0].operation = record;+ state.plan!.steps[0].operation = record;+ const observe = vi.fn();+ const { container } = await mountDeployStep({ deploySql: sql, selectedObjects: [object], databaseType: "oracle", routineDeployment: state, onObserveRoutine: observe });+ expect(container.textContent).toContain("objects.routineWriteAcknowledged");+ expect(container.textContent).toContain("ERROR 1:20 — invalid identifier");+ expect(container.textContent).not.toContain("diff.routineVerified");+ expect(editor.readOnly).toHaveBeenLastCalledWith(false);+ [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "diff.routineObserve")!.click();+ expect(observe).toHaveBeenCalledWith("original-invalid");+ state.drafts[0].operation = { ...record, readback: { ...record.readback!, state: "verified", compilerMessages: [] } };+ await nextTick();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(editor.readOnly).toHaveBeenLastCalledWith(true);+ expect(container.textContent).toContain("diff.routineReadOnlyCompleted");+ });++ it("maps a compiler position past an omitted stored owner to the same token in the target draft", async () => {+ const { state, object, sql, endpoint, identity } = routineFixture();+ const draftSql = sql.replace("RETURN 1;", "RETURN missing_identifier;");+ const storedUnit = 'FUNCTION "F" RETURN NUMBER AS BEGIN RETURN missing_identifier; END';+ const position = storedUnit.indexOf("missing_identifier") + 1;+ const record: OracleRoutineOperation = {+ operationId: "invalid-short-header",+ target: endpoint,+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ error: null,+ readback: { identity, state: "invalid", exists: true, version: null, source: `CREATE OR REPLACE ${storedUnit}`, definitionMatches: true, issues: [], compilerMessages: [{ attribute: "ERROR", line: 1, position, text: "unknown identifier" }] },+ };+ state.drafts[0].sql = draftSql;+ state.drafts[0].operation = record;+ state.plan!.steps[0].sql = draftSql;+ state.plan!.steps[0].operation = record;+ const { container } = await mountDeployStep({ deploySql: draftSql, selectedObjects: [object], databaseType: "oracle", routineDeployment: state });+ const message = [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("unknown identifier"))!;+ expect(message.disabled).toBe(false);+ message.click();+ await nextTick();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(editor.dispatch).toHaveBeenCalledWith(expect.objectContaining({ selection: { anchor: draftSql.indexOf("missing_identifier") } }));+ });});describe("SchemaDiffDeployStep foreign key check option", () => {diff --git a/apps/desktop/src/components/diff/__tests__/SchemaDiffDialog.oracleRoutine.spec.ts b/apps/desktop/src/components/diff/__tests__/SchemaDiffDialog.oracleRoutine.spec.tsnew file mode 100644index 0000000000..7f12dfeac5--- /dev/null+++ b/apps/desktop/src/components/diff/__tests__/SchemaDiffDialog.oracleRoutine.spec.ts@@ -0,0 +1,376 @@+// @vitest-environment happy-dom++import { createApp, h, nextTick, reactive, type App } from "vue";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import SchemaDiffDialog from "@/components/diff/SchemaDiffDialog.vue";+import { startSchemaDiffSession, removeSchemaDiffSession } from "@/composables/useSchemaDiffSession";+import type { OracleRoutineOperation, OracleRoutinePlanInput, OracleRoutineSnapshot } from "@/types/schemaDiff";++const calls = vi.hoisted(() => ({ load: vi.fn(), compare: vi.fn(), prepare: vi.fn(), execute: vi.fn(), observe: vi.fn(), genericPlan: vi.fn(), confirm: vi.fn(), copy: vi.fn(), transaction: vi.fn(), databaseType: "oceanbase-oracle" }));+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));+vi.mock("@/i18n", () => ({ default: { global: { t: (key: string) => key } } }));+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: vi.fn() }) }));+vi.mock("@/composables/useDialogSources", () => ({ openSchemaDiffSession: vi.fn() }));+vi.mock("@/composables/useExportTracker", () => ({ useExportTracker: () => ({ addSchemaDiffTask: vi.fn(), updateCompareTask: vi.fn() }) }));+vi.mock("@/stores/productionSafetyStore", () => ({ useProductionSafetyStore: () => ({ requestConfirmation: calls.confirm }) }));+vi.mock("@/stores/connectionStore", () => {+ const connections = () => ["source", "target"].map((id) => ({ id, name: id, db_type: calls.databaseType, is_production: id === "target", host: "localhost", port: 1 }));+ return {+ useConnectionStore: () => ({+ get connections() {+ return connections();+ },+ getConfig: (id: string) => connections().find((connection) => connection.id === id),+ ensureConnected: vi.fn().mockResolvedValue(undefined),+ }),+ };+});+vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { theme: "default", fontSize: 12, fontFamily: "monospace" } }) }));+vi.mock("@/composables/useTheme", () => ({ useTheme: () => ({ isDark: { value: false } }) }));+vi.mock("@/lib/editor/editorThemes", () => ({ loadEditorTheme: async () => [], editorFontTheme: () => [] }));+vi.mock("@/lib/editor/codemirrorSqlDialect", () => ({ createDbxCodeMirrorSqlDialect: () => undefined }));+vi.mock("@/lib/common/clipboard", () => ({ copyToClipboard: calls.copy }));+vi.mock("@/lib/metadata/objectDdlCache", () => ({ invalidateObjectDdlCache: vi.fn().mockResolvedValue(undefined) }));+vi.mock("@/lib/table/objectBrowserRowsCache", () => ({ invalidateObjectBrowserRowsCache: vi.fn() }));+vi.mock("@/lib/backend/api", () => ({+ loadSchemaDiffRoutines: calls.load,+ prepareSchemaDiff: calls.compare,+ prepareOracleRoutinePlan: calls.prepare,+ updateOracleRoutineOperationReferences: vi.fn(async () => {}),+ executeOracleRoutineOperation: calls.execute,+ observeOracleRoutineOperation: calls.observe,+ generateSchemaSyncPlan: calls.genericPlan,+ executeQuery: vi.fn().mockResolvedValue({ rows: [] }),+ listFunctions: vi.fn().mockResolvedValue([]),+ executeScriptWith2pc: calls.transaction,+}));++// Substitute only CodeMirror's DOM boundary. The production dialog, session,+// deployment controller, buttons and production guard run unchanged.+vi.mock("@codemirror/state", () => ({+ EditorState: { readOnly: { of: () => [] }, create: (config: any) => ({ ...config, doc: { toString: () => config.doc, length: config.doc.length } }) },+ Compartment: class {+ of() {+ return [];+ }+ reconfigure() {+ return [];+ }+ },+}));+vi.mock("@codemirror/view", () => ({+ EditorView: class {+ static updateListener = { of: (callback: unknown) => callback };+ static scrollIntoView = () => ({});+ state: any;+ input: HTMLTextAreaElement;+ listener: any;+ constructor(config: any) {+ this.state = config.state;+ this.listener = config.state.extensions.find((extension: unknown) => typeof extension === "function");+ this.input = document.createElement("textarea");+ this.input.value = this.state.doc.toString();+ this.input.addEventListener("input", () => this.setText(this.input.value));+ config.parent.append(this.input);+ }+ setText(text: string) {+ this.state.doc = { toString: () => text, length: text.length };+ this.input.value = text;+ this.listener?.({ docChanged: true, state: this.state });+ }+ dispatch(change: any) {+ if (change.changes) this.setText(change.changes.insert);+ }+ focus() {+ this.input.focus();+ }+ destroy() {+ this.input.remove();+ }+ },+}));+vi.mock("@codemirror/lang-sql", () => ({ sql: () => [] }));+vi.mock("codemirror", () => ({ basicSetup: [] }));++const apps: App[] = [];+const sessions: string[] = [];+const records = new Map<string, OracleRoutineOperation>();+function snapshot(connectionId: string): OracleRoutineSnapshot {+ const owner = connectionId === "source" ? "Source" : "Target";+ return { endpoint: { connectionId, database: "tenant", schema: owner, databaseType: calls.databaseType === "oracle" ? "oracle" : "oceanbase-oracle", generation: 1 }, state: "complete", enumerationComplete: true, objects: [], issues: [] };+}+const sourceSql = 'CREATE OR REPLACE FUNCTION "F" RETURN NUMBER AS BEGIN RETURN 1; END';+const sourceFunction = { name: "F", function_type: "FUNCTION", definition: sourceSql, arguments: "", data_type: "NUMBER" };++beforeEach(() => {+ vi.clearAllMocks();+ records.clear();+ calls.databaseType = "oceanbase-oracle";+ calls.load.mockImplementation(async (id: string) => snapshot(id));+ calls.compare.mockResolvedValue({ diffs: [], functionDiffs: [{ type: "added", name: "F", source: sourceFunction }], syncSql: "", renameCandidates: [] });+ calls.confirm.mockResolvedValue(true);+ calls.genericPlan.mockResolvedValue({ syncSql: "CREATE FUNCTION f() RETURNS int AS 'SELECT 1' LANGUAGE SQL;", rollbackCompleteness: "complete", missingRollbackObjects: [] });+ calls.transaction.mockResolvedValue({ status: "committed", executed_count: 1, statement_count: 1 });+ calls.prepare.mockImplementation(async (input: OracleRoutinePlanInput) => ({+ target: input.target.endpoint,+ ready: true,+ steps: input.drafts.map((draft) => {+ const operation: OracleRoutineOperation = { operationId: `approval-${calls.prepare.mock.calls.length}`, target: input.target.endpoint, identity: draft.identity, lifecycle: "prepared", dispatched: false, acknowledged: false, error: null, readback: null };+ records.set(operation.operationId, operation);+ return {+ identity: draft.identity,+ action: draft.action,+ sql: draft.sql ?? 'CREATE FUNCTION "Target"."F" RETURN NUMBER AS BEGIN RETURN 1; END;',+ sourceOriginal: sourceSql,+ targetOriginal: null,+ recoverySql: null,+ recoveryComplete: true,+ references: [],+ incomingCallers: [],+ issues: [],+ operation,+ };+ }),+ }));+ calls.observe.mockImplementation(async (id: string) => ({ operation: records.get(id), lifecycle: records.get(id)?.lifecycle, error: null }));+ calls.execute.mockImplementation(async (id: string) => {+ const operation: OracleRoutineOperation = {+ ...records.get(id)!,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ readback: { identity: records.get(id)!.identity, state: "invalid", exists: true, version: null, source: sourceSql, definitionMatches: true, issues: [], compilerMessages: [{ attribute: "ERROR", line: 1, position: 20, text: "invalid identifier" }] },+ };+ records.set(id, operation);+ return operation;+ });+});++async function flush() {+ for (let index = 0; index < 8; index++) {+ await nextTick();+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+}+function button(text: string) {+ const found = [...document.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === text);+ expect(found, text).toBeDefined();+ return found!;+}+async function mountComparison(databaseType: "oracle" | "oceanbase-oracle" | "postgres" | "mysql" | "sqlserver" = "oceanbase-oracle") {+ calls.databaseType = databaseType;+ const session = startSchemaDiffSession(+ {+ sourceConnectionId: "source",+ sourceDatabase: "tenant",+ sourceSchema: "Source",+ sourceDbType: databaseType,+ targetConnectionId: "target",+ targetDatabase: "tenant",+ targetSchema: "Target",+ targetDbType: databaseType,+ options: { tables: false, views: false, functions: true, sequences: false, rules: false, owners: false },+ ignoreComments: false,+ label: "test",+ },+ { tableListLoader: { load: vi.fn().mockResolvedValue([]) } },+ );+ sessions.push(session.id);+ await flush();+ expect(session.status).toBe("completed");+ const visible = reactive({ open: true });+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp({+ setup: () => () =>+ h(SchemaDiffDialog, {+ open: visible.open,+ sessionId: session.id,+ "onUpdate:open": (open: boolean) => {+ visible.open = open;+ },+ }),+ });+ apps.push(app);+ app.mount(host);+ await flush();+ return { session, visible };+}++afterEach(() => {+ apps.splice(0).forEach((app) => app.unmount());+ sessions.splice(0).forEach(removeSchemaDiffSession);+ document.body.innerHTML = "";+});++it("opens the real Oracle comparison, retains draft on both confirmations' cancellation, then displays INVALID and corrects only that step", async () => {+ const { session } = await mountComparison();+ button("diff.nextStepDeployRoutines").click();+ await flush();+ expect(calls.genericPlan).not.toHaveBeenCalled();+ expect(session.routineDeployment?.plan?.ready).toBe(true);+ expect(button("diff.deployToServer").disabled).toBe(false);+ button("diff.deployToServer").click();+ await flush();+ const cancel = [...document.querySelectorAll<HTMLButtonElement>("button")].filter((button) => button.textContent?.trim() === "diff.cancel").at(-1)!;+ cancel.click();+ await flush();+ expect(calls.execute).not.toHaveBeenCalled();+ expect(session.routineDeployment?.drafts[0].sql).toContain('"Target"."F"');+ calls.confirm.mockResolvedValueOnce(false);+ button("diff.deployToServer").click();+ await flush();+ button("diff.confirmDeploy").click();+ await flush();+ expect(calls.confirm).toHaveBeenCalledTimes(1);+ expect(calls.execute).not.toHaveBeenCalled();+ button("diff.deployToServer").click();+ await flush();+ button("diff.confirmDeploy").click();+ await flush();+ expect(calls.execute).toHaveBeenCalledTimes(1);+ expect(document.body.textContent).toContain("ERROR 1:20 — invalid identifier");+ expect(button("diff.deployToServer").disabled).toBe(true);+ const editor = document.querySelector<HTMLTextAreaElement>(".deploy-sql-editor textarea")!;+ editor.value = 'CREATE FUNCTION "Target"."F" RETURN NUMBER AS BEGIN RETURN 77; END;';+ editor.dispatchEvent(new Event("input"));+ await flush();+ button("diff.routineValidate").click();+ await flush();+ expect(calls.prepare.mock.calls.at(-1)![0].drafts[0]).toMatchObject({ action: "replace", baselineOperationId: "approval-1", sql: editor.value });+ expect(button("diff.deployToServer").disabled).toBe(false);+ calls.execute.mockImplementationOnce(async (id: string) => ({+ ...records.get(id)!,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ readback: { identity: records.get(id)!.identity, state: "verified", exists: true, version: null, source: editor.value, definitionMatches: true, compilerMessages: [], issues: [] },+ }));+ button("diff.deployToServer").click();+ await flush();+ button("diff.confirmDeploy").click();+ await flush();+ expect(calls.execute.mock.calls.map((call) => call[0])).toEqual(["approval-1", "approval-2"]);+ expect(session.routineDeployment?.records).toHaveLength(2);+ expect(document.body.textContent).toContain("diff.routineReadOnlyCompleted");+});++it("restores the same draft and operation after closing and reopening the actual dialog", async () => {+ const { session, visible } = await mountComparison();+ button("diff.nextStepDeployRoutines").click();+ await flush();+ const editor = document.querySelector<HTMLTextAreaElement>(".deploy-sql-editor textarea")!;+ editor.value = "retained manual draft";+ editor.dispatchEvent(new Event("input"));+ await flush();+ visible.open = false;+ await flush();+ visible.open = true;+ await flush();+ expect(document.querySelector<HTMLTextAreaElement>(".deploy-sql-editor textarea")?.value).toBe("retained manual draft");+ expect(session.routineDeployment?.records[0].operationId).toBe("approval-1");+ expect(calls.execute).not.toHaveBeenCalled();+});++it("retains a late unknown result across close/reopen and only observes its original request", async () => {+ const { session, visible } = await mountComparison();+ button("diff.nextStepDeployRoutines").click();+ await flush();+ let reject!: (error: Error) => void;+ calls.execute.mockReturnValueOnce(+ new Promise((_resolve, fail) => {+ reject = fail;+ }),+ );+ button("diff.deployToServer").click();+ await flush();+ button("diff.confirmDeploy").click();+ await flush();+ expect(calls.execute).toHaveBeenCalledTimes(1);+ visible.open = false;+ await flush();+ const unknown = { ...records.get("approval-1")!, lifecycle: "unproven" as const, dispatched: true };+ records.set("approval-1", unknown);+ reject(new Error("client response lost"));+ await flush();+ visible.open = true;+ await flush();+ expect(session.routineDeployment?.drafts[0].operation?.operationId).toBe("approval-1");+ expect(button("diff.deployToServer").disabled).toBe(true);+ button("diff.routineObserve").click();+ await flush();+ expect(calls.observe).toHaveBeenLastCalledWith("approval-1", true);+ button("diff.routineValidate").click();+ await flush();+ expect(calls.prepare).toHaveBeenCalledTimes(1);+ expect(calls.execute).toHaveBeenCalledTimes(1);+ expect(document.body.textContent).toContain("termination is not proven");+});++it("retains all four comparison states and copies an equal object's exact raw source", async () => {+ const raw = sourceSql.replace("RETURN 1", "RETURN 'two spaces'");+ calls.compare.mockResolvedValue({+ diffs: [],+ syncSql: "",+ functionDiffs: [+ { type: "added", name: "Added", source: { ...sourceFunction, name: "Added" } },+ { type: "modified", name: "Modified", source: { ...sourceFunction, name: "Modified" }, target: { ...sourceFunction, name: "Modified", definition: "old" } },+ { type: "removed", name: "Removed", target: { ...sourceFunction, name: "Removed" } },+ { type: "equal", name: "Equal", source: { ...sourceFunction, name: "Equal", definition: raw }, target: { ...sourceFunction, name: "Equal", definition: raw } },+ ],+ });+ await mountComparison();+ const rows = [...document.querySelectorAll<HTMLElement>('[role="button"]')].filter((row) => row.querySelector('input[type="checkbox"]'));+ expect(rows).toHaveLength(4);+ const equal = rows.find((row) => row.textContent?.includes("Equal"))!;+ expect(equal.textContent).toContain("diff.routineEqual");+ expect(equal.querySelector<HTMLInputElement>("input")?.disabled).toBe(true);+ equal.click();+ await flush();+ const copy = document.querySelector<HTMLButtonElement>('button[title="diff.copySourceDdl"]')!;+ expect(copy.disabled).toBe(false);+ copy.click();+ expect(calls.copy).toHaveBeenLastCalledWith(raw);+});++it.each(["mysql", "sqlserver"] as const)("keeps %s routine comparison copy-only", async (databaseType) => {+ await mountComparison(databaseType);+ expect(document.body.textContent).toContain("diff.routineSyncDeferredHint");+ expect(document.body.textContent).not.toContain("diff.nextStepDeployRoutines");+ expect(calls.prepare).not.toHaveBeenCalled();+ expect(calls.execute).not.toHaveBeenCalled();+});++it("keeps PostgreSQL's existing plan, confirmation and transactional execution path", async () => {+ await mountComparison("postgres");+ button("diff.nextStepDeployRoutines").click();+ await flush();+ expect(calls.genericPlan).toHaveBeenCalled();+ expect(calls.prepare).not.toHaveBeenCalled();+ button("diff.deployToServer").click();+ await flush();+ button("diff.confirmDeploy").click();+ await flush();+ expect(calls.transaction).toHaveBeenCalledWith("target", "tenant", ["CREATE FUNCTION f() RETURNS int AS 'SELECT 1' LANGUAGE SQL;"], "Target", false);+ expect(document.body.textContent).toContain("diff.deploySuccessMessage");+ expect(calls.execute).not.toHaveBeenCalled();+});++it("does not label two failed inventories as an equal empty comparison", async () => {+ calls.load.mockImplementation(async (id: string) => ({ ...snapshot(id), state: "permission-denied", enumerationComplete: false, issues: [{ stage: "inventory", code: "permission-denied", message: "Metadata visibility unavailable" }] }));+ calls.compare.mockResolvedValue({ diffs: [], functionDiffs: [], syncSql: "" });+ await mountComparison();+ expect(document.body.textContent).toContain("Metadata visibility unavailable");+ expect(document.body.textContent).toContain("diff.routineUnreadable");+ expect(document.body.textContent).not.toContain("diff.noDifferences");+ expect(button("diff.nextStepDeployRoutines").disabled).toBe(true);+});++it("opens a native Oracle target draft through the same controlled review", async () => {+ const { session } = await mountComparison("oracle");+ button("diff.nextStepDeployRoutines").click();+ await flush();+ expect(session.routineDeployment?.plan?.target.databaseType).toBe("oracle");+ expect(button("diff.deployToServer").disabled).toBe(false);+ expect(calls.genericPlan).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex 48d07fca53..38e11a0598 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -107,7 +107,7 @@ import type { DuplicateTableStructurePlan } from "@/lib/database/dbAdminSql";import { executeOceanbaseTableClone, executeOceanbaseTableCloneData, oceanbaseCloneDataPreparationError, OceanbaseTableCloneError, type OceanbaseTableClone } from "@/lib/database/oceanbaseTableClone";import { useOceanbaseCloneDialog } from "@/composables/useOceanbaseCloneDialog";import { useToast } from "@/composables/useToast";-import { buildExecutableObjectSourceStatements, buildRoutineRenameObjectSourceStatements, executeObjectSourceSave, formatObjectSourceSaveError, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor";+import { buildExecutableObjectSourceStatements, buildRoutineRenameObjectSourceStatements, prepareObjectSourceSave, objectSourceSaveSuccessMessage, formatObjectSourceSaveError, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor";import { assertSourceIdentity, beginSourceSave, captureSourceIdentity, freezeSourceIdentities, renewSourceIdentity, type SourceIdentitySnapshot } from "@/lib/table/objectSourceIdentity";import { buildRenameObjectSql, supportsObjectRename } from "@/lib/table/objectRenameSql";import { prepareOracleViewRename, executeOracleViewRename, OracleViewRenameFailure, type OracleViewRenamePlan } from "@/lib/table/oracleViewRename";@@ -4013,6 +4013,7 @@ async function saveSource() {const databaseType = effectiveDatabaseType.value;sourceSaving.value = true;sourceSaveError.value = "";+ let save: Awaited<ReturnType<typeof prepareObjectSourceSave>> | undefined;try {if (!sourceIdentity) return;const identity = sourceIdentity;@@ -4024,31 +4025,32 @@ async function saveSource() {name: row.name,source: sourceDraft.value,});+ save = await prepareObjectSourceSave(connectionId, database, databaseType, statements, schema, { objectType: row.type as ObjectSourceKind, name: row.name });+ const preparedSave = save;const execute = async () => {- if (sidePanelGuard.isStale(epoch) || sourceRow.value !== row) return false;+ if (sidePanelGuard.isStale(epoch) || sourceRow.value !== row) return;const release = beginSourceSave(identity);try {- await executeObjectSourceSave(connectionId, database, databaseType, statements, schema);- return true;+ return { operation: await preparedSave() };} finally {release();}};const executableSql = statements.filter((sql) => sql.trim()).join(";\n");+ let result;if (executableSql.trim()) {- const saved = await executeWithProductionSqlGuard({+ result = await executeWithProductionSqlGuard({connection,database,sql: executableSql,source: t("production.sourceObjectSource"),execute,});- if (!saved || sidePanelGuard.isStale(epoch)) return;} else {- if (!(await execute())) return;- if (sidePanelGuard.isStale(epoch)) return;+ result = await execute();}- toast(t("objects.sourceSaved"));+ if (!result || sidePanelGuard.isStale(epoch)) return;+ toast(objectSourceSaveSuccessMessage(t("objects.sourceSaved"), result.operation), result.operation?.readback?.compilerMessages.length ? 6000 : 2000);sourceEditing.value = false;sourceDraft.value = "";await openSource(row);@@ -4056,6 +4058,7 @@ async function saveSource() {if (sidePanelGuard.isStale(epoch)) return;sourceSaveError.value = formatObjectSourceSaveError(e, databaseType, row.type as ObjectSourceKind, t("objects.postgresViewColumnChangeHint"));} finally {+ await save?.dispose?.();if (sidePanelGuard.isFresh(epoch)) sourceSaving.value = false;}}diff --git a/apps/desktop/src/components/objects/ObjectSourceDialog.vue b/apps/desktop/src/components/objects/ObjectSourceDialog.vueindex 451fbbf505..a222ff6de0 100644--- a/apps/desktop/src/components/objects/ObjectSourceDialog.vue+++ b/apps/desktop/src/components/objects/ObjectSourceDialog.vue@@ -7,7 +7,7 @@ import { useConnectionStore } from "@/stores/connectionStore";import { useSettingsStore } from "@/stores/settingsStore";import { copyToClipboard } from "@/lib/common/clipboard";import { formatSqlForDisplay, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";-import { buildEditableObjectSource, buildExecutableObjectSourceStatements, executeObjectSourceSave, formatObjectSourceSaveError, resolveObjectSourceEditDraft } from "@/lib/table/objectSourceEditor";+import { buildEditableObjectSource, buildExecutableObjectSourceStatements, prepareObjectSourceSave, objectSourceSaveSuccessMessage, formatObjectSourceSaveError, resolveObjectSourceEditDraft } from "@/lib/table/objectSourceEditor";import { loadObjectSourceWithRoutineFallback } from "@/lib/table/objectSourceLoad";import { assertSourceIdentity, beginSourceSave, captureSourceIdentity, renewSourceIdentity, type SourceIdentitySnapshot } from "@/lib/table/objectSourceIdentity";import { jdbcRoutineMetadata, xuguRoutineMetadataFromDefinition, type RoutineMetadata } from "@/lib/table/routineParameters";@@ -210,6 +210,7 @@ async function saveSource() {const schema = props.schema || props.database;saving.value = true;saveError.value = "";+ let save: Awaited<ReturnType<typeof prepareObjectSourceSave>> | undefined;try {if (!sourceIdentity) return;const identity = sourceIdentity;@@ -222,36 +223,38 @@ async function saveSource() {source: draft.value,});if (serial !== loadSerial) return;+ save = await prepareObjectSourceSave(connectionId, database, databaseType, statements, schema, { objectType, name });+ const preparedSave = save;const executableSql = statements.filter((sql) => sql.trim()).join(";\n");const execute = async () => {- if (serial !== loadSerial || !props.open) return false;+ if (serial !== loadSerial || !props.open) return;const release = beginSourceSave(identity);try {- await executeObjectSourceSave(connectionId, database, databaseType, statements, schema);- return true;+ return { operation: await preparedSave() };} finally {release();}};+ let result;if (executableSql.trim()) {- const saved = await executeWithProductionSqlGuard({+ result = await executeWithProductionSqlGuard({connection: connectionStore.getConfig(connectionId),database,sql: executableSql,source: t("production.sourceObjectSource"),execute,});- if (!saved) return;} else {- if (!(await execute())) return;+ result = await execute();}- if (serial !== loadSerial) return;- toast(t("objects.sourceSaved"));+ if (!result || serial !== loadSerial) return;+ toast(objectSourceSaveSuccessMessage(t("objects.sourceSaved"), result.operation), result.operation?.readback?.compilerMessages.length ? 6000 : 2000);emit("saved");await loadSource(false);} catch (e: unknown) {if (serial === loadSerial) saveError.value = formatObjectSourceSaveError(e, databaseType, objectType, t("objects.postgresViewColumnChangeHint"));} finally {+ await save?.dispose?.();if (serial === loadSerial) saving.value = false;}}diff --git a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.tsindex e7613ab77f..fe908be3a9 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectBrowser.viewSourceSave.spec.ts@@ -2,10 +2,13 @@import { createApp, defineComponent, h, ref, nextTick, type App } from "vue";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createPinia, getActivePinia, setActivePinia } from "pinia";import ObjectBrowser from "@/components/objects/ObjectBrowser.vue";import { getCachedObjectBrowserRows, invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";import { freezeSourceIdentities } from "@/lib/table/objectSourceIdentity";import type { ConnectionConfig } from "@/types/database";+import type { OracleRoutineOperation } from "@/types/schemaDiff";+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";const mocks = vi.hoisted(() => ({listObjects: vi.fn(),@@ -14,6 +17,9 @@ const mocks = vi.hoisted(() => ({buildEditableObjectSource: vi.fn(),buildExecutableObjectSourceStatements: vi.fn(),executeQuery: vi.fn(),+ prepareOracleRoutineSave: vi.fn(),+ updateOracleRoutineOperationReferences: vi.fn(),+ executeOracleRoutineOperation: vi.fn(),ensureConnected: vi.fn(),toast: vi.fn(),sourceTabs: [] as Array<{ id: string; sourceLoad?: { error?: string }; objectSource?: unknown }>,@@ -36,11 +42,11 @@ vi.mock("@/lib/backend/api", () => ({buildEditableObjectSource: (...args: unknown[]) => mocks.buildEditableObjectSource(...args),buildExecutableObjectSourceStatements: (...args: unknown[]) => mocks.buildExecutableObjectSourceStatements(...args),executeQuery: (...args: unknown[]) => mocks.executeQuery(...args),+ prepareOracleRoutineSave: (...args: unknown[]) => mocks.prepareOracleRoutineSave(...args),+ updateOracleRoutineOperationReferences: (...args: unknown[]) => mocks.updateOracleRoutineOperationReferences(...args),+ executeOracleRoutineOperation: (...args: unknown[]) => mocks.executeOracleRoutineOperation(...args),deleteSchemaCachePrefix: (...args: unknown[]) => mocks.deleteSchemaCachePrefix(...args),}));-vi.mock("@/lib/database/productionExecutionGuard", () => ({- executeWithProductionSqlGuard: async ({ execute }: { execute: () => Promise<unknown> }) => execute(),-}));vi.mock("@/stores/connectionStore", () => ({useConnectionStore: () => ({treeClipboard: null,@@ -167,6 +173,7 @@ const mountedApps: Array<{ app: App; host: HTMLElement }> = [];beforeEach(() => {vi.clearAllMocks();+ setActivePinia(createPinia());mocks.sourceTabs.splice(0);mocks.sourceLoadFailure = "";mocks.deferSourceTabLoad = false;@@ -198,6 +205,7 @@ async function mountBrowser(browserConnection = connection, database = "app") {const host = document.createElement("div");document.body.append(host);const app = createApp({ setup: () => () => h(ObjectBrowser, { connection: browserConnection, database }) });+ app.use(getActivePinia()!);mountedApps.push({ app, host });app.mount(host);await vi.waitFor(() => expect(host.textContent).toContain(VIEW_NAME));@@ -209,6 +217,7 @@ async function mountOracleBrowserWithSchema() {const host = document.createElement("div");document.body.append(host);const app = createApp({ setup: () => () => h(ObjectBrowser, { connection: oracleConnection, database: "ORCL", schema: schema.value }) });+ app.use(getActivePinia()!);mountedApps.push({ app, host });app.mount(host);await vi.waitFor(() => expect(host.textContent).toContain(VIEW_NAME));@@ -245,6 +254,85 @@ async function clickRow(host: HTMLElement, name: string) {}describe("ObjectBrowser view source save", () => {+ it.each(["confirm", "cancel"] as const)("uses the real production guard before a routine source save (%s)", async (decision) => {+ const target = { ...oracleConnection, id: `browser-production-${decision}`, is_production: true };+ const source = 'CREATE OR REPLACE FUNCTION "APP"."v_demo" RETURN NUMBER AS BEGIN RETURN 1; END;';+ const identity = { owner: "APP", name: VIEW_NAME, kind: "FUNCTION" as const };+ const operation: OracleRoutineOperation = {+ operationId: `browser-production-${decision}`,+ target: { connectionId: target.id, database: "ORCL", schema: "APP", databaseType: "oracle", generation: 0 },+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ readback: { identity, state: "verified", exists: true, source, version: null, definitionMatches: true, compilerMessages: [], issues: [] },+ error: null,+ };+ mocks.listObjects.mockResolvedValue([{ name: VIEW_NAME, schema: "APP", object_type: "FUNCTION" }]);+ mocks.getObjectSource.mockResolvedValue({ name: VIEW_NAME, schema: "APP", object_type: "FUNCTION", source, editable: true });+ mocks.buildExecutableObjectSourceStatements.mockResolvedValue([source]);+ mocks.prepareOracleRoutineSave.mockResolvedValue({ ...operation, lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null });+ mocks.executeOracleRoutineOperation.mockResolvedValue(operation);+ const host = await mountBrowser(target, "ORCL");+ vi.useFakeTimers();+ await clickRow(host, VIEW_NAME);+ click(saveButton(host)!);+ await settle();+ const safety = useProductionSafetyStore();+ expect(safety.pending).toMatchObject({ connectionName: target.name, database: "ORCL", sql: source, source: "production.sourceObjectSource" });+ expect(mocks.prepareOracleRoutineSave).toHaveBeenCalledExactlyOnceWith({ connectionId: target.id, database: "ORCL", identity, sql: source });+ expect(mocks.executeOracleRoutineOperation).not.toHaveBeenCalled();+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ if (decision === "confirm") safety.confirm();+ else safety.cancel();+ await settle();+ if (decision === "confirm") {+ expect(mocks.executeOracleRoutineOperation).toHaveBeenCalledExactlyOnceWith(operation.operationId, source);+ expect(mocks.toast).toHaveBeenCalledWith("objects.sourceSaved", 2000);+ } else {+ expect(mocks.executeOracleRoutineOperation).not.toHaveBeenCalled();+ expect(mocks.toast).not.toHaveBeenCalled();+ expect(mocks.getObjectSource).toHaveBeenCalledTimes(1);+ expect(saveButton(host)).toBeDefined();+ }+ });++ it.each([false, true])("counts a routine save only after complete verification (valid=%s)", async (valid) => {+ const source = 'CREATE OR REPLACE FUNCTION "APP"."v_demo" RETURN NUMBER AS BEGIN RETURN 1; END;';+ const identity = { owner: "APP", name: VIEW_NAME, kind: "FUNCTION" as const };+ const operation: OracleRoutineOperation = {+ operationId: `browser-routine-${valid}`,+ target: { connectionId: oracleConnection.id, database: "ORCL", schema: "APP", databaseType: "oracle", generation: 0 },+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ readback: { identity, state: valid ? "verified" : "invalid", exists: true, source, version: null, definitionMatches: true, compilerMessages: valid ? [] : [{ attribute: "ERROR", line: 1, position: 72, text: "missing identifier" }], issues: [] },+ error: null,+ };+ mocks.listObjects.mockResolvedValue([{ name: VIEW_NAME, schema: "APP", object_type: "FUNCTION" }]);+ mocks.getObjectSource.mockResolvedValue({ name: VIEW_NAME, schema: "APP", object_type: "FUNCTION", source, editable: true });+ mocks.buildExecutableObjectSourceStatements.mockResolvedValue([source]);+ mocks.prepareOracleRoutineSave.mockResolvedValue({ ...operation, lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null });+ mocks.executeOracleRoutineOperation.mockResolvedValue(operation);+ const host = await mountBrowser(oracleConnection, "ORCL");+ vi.useFakeTimers();+ await clickRow(host, VIEW_NAME);+ click(saveButton(host)!);+ await settle();+ expect(mocks.prepareOracleRoutineSave).toHaveBeenCalledWith({ connectionId: oracleConnection.id, database: "ORCL", identity, sql: source });+ expect(mocks.executeOracleRoutineOperation).toHaveBeenCalledExactlyOnceWith(operation.operationId, source);+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ if (valid) {+ expect(mocks.toast).toHaveBeenCalledWith("objects.sourceSaved", 2000);+ expect(saveButton(host)).toBeUndefined();+ } else {+ expect(host.textContent).toContain("ERROR 1:72 missing identifier");+ expect(mocks.toast).not.toHaveBeenCalledWith("objects.sourceSaved", 2000);+ expect(mocks.getObjectSource).toHaveBeenCalledTimes(1);+ expect(saveButton(host)).toBeDefined();+ }+ });it("invalidates completed compile caches but does not refresh an unmounted browser", async () => {let release!: () => void;mocks.listSchemas.mockResolvedValue(["APP_A", "APP_B"]);@@ -440,7 +528,7 @@ describe("ObjectBrowser view source save", () => {click(save!);await settle();expect(mocks.executeQuery).toHaveBeenCalledWith("mysql-views", "app", ALTER_SQL, "app");- expect(mocks.toast).toHaveBeenCalledWith("objects.sourceSaved");+ expect(mocks.toast).toHaveBeenCalledWith("objects.sourceSaved", 2000);// The success path closes the panel (same row + source mode).expect(saveButton(host)).toBeUndefined();diff --git a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.tsindex 2b94186fc8..57d800f949 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.ts@@ -8,12 +8,22 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { useConnectionStore } from "@/stores/connectionStore";import { useProductionSafetyStore } from "@/stores/productionSafetyStore";import type { ConnectionConfig, DatabaseType, ObjectSourceKind } from "@/types/database";+import type { OracleRoutineOperation } from "@/types/schemaDiff";import ObjectSourceDialog from "../ObjectSourceDialog.vue";import { freezeSourceIdentities } from "@/lib/table/objectSourceIdentity";const ddl = 'CREATE SEQUENCE "APP"."SEQ" START WITH 40 INCREMENT BY 1 NOCACHE;';const alter = 'ALTER SEQUENCE "APP"."SEQ" INCREMENT BY 1 NOCACHE;';-const mocks = vi.hoisted(() => ({ getObjectSource: vi.fn(), buildEditableObjectSource: vi.fn(), buildExecutableObjectSourceStatements: vi.fn(), executeQuery: vi.fn() }));+const mocks = vi.hoisted(() => ({+ getObjectSource: vi.fn(),+ buildEditableObjectSource: vi.fn(),+ buildExecutableObjectSourceStatements: vi.fn(),+ executeQuery: vi.fn(),+ prepareOracleRoutineSave: vi.fn(),+ updateOracleRoutineOperationReferences: vi.fn(async () => {}),+ executeOracleRoutineOperation: vi.fn(),+ observeOracleRoutineOperation: vi.fn(),+}));// The Rust/backend boundary is mocked; the dialog, CodeMirror editor and shared// save/production-guard pipeline remain real. Rust builder tests cover the SQL.vi.mock("@/lib/backend/api", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/backend/api")>()), ...mocks }));@@ -60,6 +70,61 @@ async function mount(options: { databaseType?: DatabaseType; initialEditing?: bo}describe("OceanBase sequence source through the shared Oracle object dialog", () => {+ function routineOperation(source: string, valid: boolean): OracleRoutineOperation {+ const identity = { owner: "APP", name: "SEQ", kind: "FUNCTION" as const };+ return {+ operationId: "dialog-save-operation",+ target: { connectionId: "ob", database: "service", schema: "APP", databaseType: "oceanbase-oracle", generation: 0 },+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ readback: { identity, state: valid ? "verified" : "invalid", exists: true, version: null, source, definitionMatches: true, compilerMessages: valid ? [] : [{ attribute: "ERROR", line: 2, position: 17, text: "missing identifier" }], issues: [] },+ error: null,+ };+ }+ it("retains the routine editor and compiler position when acknowledged DDL is INVALID", async () => {+ const source = 'CREATE OR REPLACE FUNCTION "APP"."SEQ" RETURN NUMBER AS BEGIN RETURN missing_value; END;';+ const { saved } = await mount({ type: "FUNCTION", source, initialEditing: true });+ const operation = routineOperation(source, false);+ mocks.prepareOracleRoutineSave.mockResolvedValue({ ...operation, lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null });+ mocks.executeOracleRoutineOperation.mockResolvedValue(operation);+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(document.body.textContent).toContain("ERROR 2:17 missing identifier"));+ expect(mocks.prepareOracleRoutineSave).toHaveBeenCalledWith({ connectionId: "ob", database: "service", identity: operation.identity, sql: source });+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ expect(saved).not.toHaveBeenCalled();+ expect(mocks.getObjectSource).toHaveBeenCalledTimes(1);+ expect(editor()!.state.doc.toString()).toBe(source);+ expect(editor()!.state.facet(EditorState.readOnly)).toBe(false);+ });+ it("reloads a routine only after the shared operation has verified the final definition", async () => {+ const source = 'CREATE OR REPLACE FUNCTION "APP"."SEQ" RETURN NUMBER AS BEGIN RETURN 1; END;';+ const { saved } = await mount({ type: "FUNCTION", source, initialEditing: true });+ const operation = routineOperation(source, true);+ mocks.prepareOracleRoutineSave.mockResolvedValue({ ...operation, lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null });+ mocks.executeOracleRoutineOperation.mockResolvedValue(operation);+ button("objects.saveSource")!.click();+ await vi.waitFor(() => expect(saved).toHaveBeenCalledOnce());+ expect(mocks.executeOracleRoutineOperation).toHaveBeenCalledExactlyOnceWith(operation.operationId, source);+ expect(mocks.executeQuery).not.toHaveBeenCalled();+ await vi.waitFor(() => expect(mocks.getObjectSource).toHaveBeenCalledTimes(2));+ });+ it("prepares a routine before production confirmation but does not write after cancellation", async () => {+ const source = 'CREATE OR REPLACE FUNCTION "APP"."SEQ" RETURN NUMBER AS BEGIN RETURN 2; END;';+ const { saved } = await mount({ type: "FUNCTION", source, initialEditing: true, production: true });+ const operation = routineOperation(source, true);+ mocks.prepareOracleRoutineSave.mockResolvedValue({ ...operation, lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null });+ button("objects.saveSource")!.click();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending).toBeDefined());+ expect(mocks.prepareOracleRoutineSave).toHaveBeenCalledOnce();+ safety.cancel();+ await vi.waitFor(() => expect(button("objects.saveSource")!.disabled).toBe(false));+ expect(mocks.executeOracleRoutineOperation).not.toHaveBeenCalled();+ expect(saved).not.toHaveBeenCalled();+ expect(editor()!.state.doc.toString()).toBe(source);+ });it("rechecks identity after the real production confirmation waits", async () => {const source = 'CREATE OR REPLACE VIEW "APP"."SEQ" AS SELECT 3 FROM DUAL';const { saved } = await mount({ type: "VIEW", source, initialEditing: true, production: true });diff --git a/apps/desktop/src/composables/__tests__/useSchemaDiffSession.spec.ts b/apps/desktop/src/composables/__tests__/useSchemaDiffSession.spec.tsindex 9dd1dce346..3cd4900ecb 100644--- a/apps/desktop/src/composables/__tests__/useSchemaDiffSession.spec.ts+++ b/apps/desktop/src/composables/__tests__/useSchemaDiffSession.spec.ts@@ -8,6 +8,7 @@ const apiMock = vi.hoisted(() => ({listSequences: vi.fn(),listRules: vi.fn(),listOwners: vi.fn(),+ loadSchemaDiffRoutines: vi.fn().mockImplementation(async (connectionId: string, database: string, schema: string) => ({ endpoint: { connectionId, database, schema, databaseType: "oracle", generation: 1 }, state: "complete", enumerationComplete: true, objects: [], issues: [] })),}));const openMock = vi.hoisted(() => vi.fn());const trackerMock = vi.hoisted(() => ({@@ -475,3 +476,80 @@ test("resolves the JDBC engine dialect from the connection's product type", asyn// 部署脚本按目标产品类型(而不是 jdbc)生成。assert.equal(payload?.databaseType, "oracle");});++test.each(["oracle", "oceanbase-oracle"] as const)("loads %s strict snapshots through the actual session entry instead of ordinary listFunctions", async (databaseType) => {+ vi.clearAllMocks();+ const raw = 'CREATE OR REPLACE PROCEDURE "Quoted.Proc" AS BEGIN NULL; /* keep spaces 😀 */ END';+ apiMock.loadSchemaDiffRoutines.mockImplementation(async (connectionId: string, database: string, schema: string) => ({+ endpoint: { connectionId, database, schema, databaseType, generation: 4 },+ state: connectionId.endsWith("source") ? "partial" : "complete",+ enumerationComplete: true,+ objects: [+ {+ version: { identity: { owner: schema, name: "Quoted.Proc", kind: "PROCEDURE" }, objectId: "9007199254740993", status: "VALID", lastDdlTime: "2026-10-21T00:00:00" },+ source: raw,+ sourceComplete: !connectionId.endsWith("source"),+ dependenciesComplete: true,+ dependencies: [],+ issues: connectionId.endsWith("source") ? [{ stage: "source", code: "read-incomplete", message: "source limit" }] : [],+ },+ ],+ issues: [],+ }));+ apiMock.prepareSchemaDiff.mockResolvedValue({ diffs: [], functionDiffs: [], syncSql: "" });+ const session = startSchemaDiffSession(+ {+ sourceConnectionId: `${databaseType}-source`,+ sourceDatabase: "db",+ sourceSchema: "Source.With.Dot",+ targetConnectionId: `${databaseType}-target`,+ targetDatabase: "db",+ targetSchema: "Target",+ sourceDbType: databaseType,+ targetDbType: databaseType,+ options: { tables: false, views: false, functions: true, selectedRoutines: ["Quoted.Proc"] },+ ignoreComments: false,+ label: "strict routines",+ },+ { tableListLoader: { load: vi.fn().mockResolvedValue([]) } },+ );+ await waitForSession(session);+ assert.equal(session.status, "completed");+ assert.equal(apiMock.listFunctions.mock.calls.length, 0);+ assert.equal(apiMock.loadSchemaDiffRoutines.mock.calls.length, 2);+ assert.equal(apiMock.loadSchemaDiffRoutines.mock.calls[0].length, 4);+ assert.deepEqual(apiMock.loadSchemaDiffRoutines.mock.calls[0][3], ["Quoted.Proc"]);+ assert.deepEqual(apiMock.loadSchemaDiffRoutines.mock.calls[1][3], ["Quoted.Proc"]);+ const payload = apiMock.prepareSchemaDiff.mock.calls[0][0];+ assert.equal(payload.sourceFunctions[0].function_type, "PROCEDURE");+ assert.equal(payload.sourceFunctions[0].definition, raw);+ assert.deepEqual(payload.oracleRoutines.sourceIncompleteNames, ["Quoted.Proc"]);+ assert.equal(payload.oracleRoutines.sourceDatabaseType, databaseType);+ assert.equal(payload.oracleRoutines.targetDatabaseType, databaseType);+ assert.equal(session.routineSnapshots?.source?.objects[0].source, raw);+});++test("a strict-snapshot endpoint mismatch fails the session without generating a false comparison", async () => {+ vi.clearAllMocks();+ apiMock.loadSchemaDiffRoutines.mockImplementation(async (connectionId: string, database: string, schema: string) => ({ endpoint: { connectionId, database, schema: `${schema}-wrong`, databaseType: "oracle", generation: 1 }, state: "complete", enumerationComplete: true, objects: [], issues: [] }));+ const session = startSchemaDiffSession(+ {+ sourceConnectionId: "wrong-source",+ sourceDatabase: "db",+ sourceSchema: "SOURCE",+ targetConnectionId: "wrong-target",+ targetDatabase: "db",+ targetSchema: "TARGET",+ sourceDbType: "oracle",+ targetDbType: "oracle",+ options: { tables: false, functions: true },+ ignoreComments: false,+ label: "mismatch",+ },+ { tableListLoader: { load: vi.fn().mockResolvedValue([]) } },+ );+ await waitForSession(session);+ assert.equal(session.status, "failed");+ assert.match(session.error ?? "", /endpoint/);+ assert.equal(apiMock.prepareSchemaDiff.mock.calls.length, 0);+});diff --git a/apps/desktop/src/composables/useSchemaDiffSession.ts b/apps/desktop/src/composables/useSchemaDiffSession.tsindex 919ba3209c..b1a3378136 100644--- a/apps/desktop/src/composables/useSchemaDiffSession.ts+++ b/apps/desktop/src/composables/useSchemaDiffSession.ts@@ -10,11 +10,12 @@ import { loadSchemaDetails } from "@/lib/schema/schemaDiffMetadataLoad";import { registerSchemaDiffTask } from "@/lib/schema/schemaDiffCancellation";import type { SchemaDiffTableIdentity, SchemaDiffTableListLoader } from "@/lib/schema/schemaDiffTableList";import { getSchemaDiffNextProgressStep, isSchemaDiffPostgresLike, shouldLoadSchemaDiffExtraObjectPhase, shouldLoadSchemaDiffRoutines, type SchemaDiffProgressPhase } from "@/lib/schema/schemaDiffProgress";-import { schemaDiffRoutineObjectTypesIntersection } from "@/lib/database/databaseObjectCapabilities";+import { schemaDiffRoutineObjectTypesIntersection, schemaDiffRoutineProductType } from "@/lib/database/databaseObjectCapabilities";import { convertToSchemaDiffObjects, databaseTypeToDialectKind, normalizeDialectKind, schemaDiffDeployTargetSchema, type SchemaDiffObject } from "@/lib/schema/schemaDiff";-import { normalizeSchemaDiffCompareOptions, type SchemaDiffCompareOptions } from "@/types/schemaDiff";+import { normalizeSchemaDiffCompareOptions, type OracleRoutineCompareContext, type OracleRoutineSnapshot, type SchemaDiffCompareOptions } from "@/types/schemaDiff";import type { DatabaseType, FunctionInfo, TableInfo } from "@/types/database";import type { SchemaDiffPreparation } from "@/lib/schema/schemaDiff";+import { disposeOracleRoutineDeployment, type OracleRoutineDeployment } from "@/lib/schema/oracleRoutineDeploy";export interface SchemaDiffSessionProgress {phase: SchemaDiffProgressPhase;@@ -34,8 +35,8 @@ export interface SchemaDiffSessionConfig {targetDbType: DatabaseType;/*** Product type behind a JDBC `sourceDbType`/`targetDbType` (see- * `schemaDiffEngineDatabaseType`). Only the diff engine's dialect/profile decisions use- * it: metadata loading, progress phases and option defaults keep the raw db types.+ * `schemaDiffEngineDatabaseType`). The diff engine and strict Oracle routine+ * collector use the product; unrelated metadata and option defaults keep raw db types.*/sourceEngineDbType?: DatabaseType;targetEngineDbType?: DatabaseType;@@ -53,6 +54,9 @@ export interface SchemaDiffSession {config: SchemaDiffSessionConfig;progress: SchemaDiffSessionProgress | null;result: SchemaDiffPreparation | null;+ routineSnapshots?: { source?: OracleRoutineSnapshot; target?: OracleRoutineSnapshot };+ oracleRoutineContext?: OracleRoutineCompareContext;+ routineDeployment?: OracleRoutineDeployment;error: string | null;startedAt: number;finishedAt?: number;@@ -101,6 +105,26 @@ function filterFunctionsByRoutineKinds(functions: FunctionInfo[], kinds: Array<"});}+function isOracleRoutineEngine(databaseType: string): boolean {+ return databaseType === "oracle" || databaseType === "oceanbase-oracle";+}++async function loadSessionRoutines(session: SchemaDiffSession, side: "source" | "target", signal: AbortSignal): Promise<FunctionInfo[]> {+ const input = session.config;+ const connectionId = side === "source" ? input.sourceConnectionId : input.targetConnectionId;+ const database = side === "source" ? input.sourceDatabase : input.targetDatabase;+ const schema = side === "source" ? input.sourceSchema : input.targetSchema;+ const engine = side === "source" ? (input.sourceEngineDbType ?? input.sourceDbType) : (input.targetEngineDbType ?? input.targetDbType);+ if (!isOracleRoutineEngine(engine)) return api.listFunctions(connectionId, database, schema);+ const snapshot = await api.loadSchemaDiffRoutines(connectionId, database, schema, input.options?.selectedRoutines);+ signal.throwIfAborted();+ if (snapshot.endpoint.connectionId !== connectionId || snapshot.endpoint.database !== database || snapshot.endpoint.schema !== schema || snapshot.endpoint.databaseType !== engine) {+ throw new Error("Routine snapshot endpoint does not match this comparison");+ }+ session.routineSnapshots = { ...session.routineSnapshots, [side]: snapshot };+ return snapshot.objects.map((object) => ({ name: object.version.identity.name, function_type: object.version.identity.kind, data_type: "", arguments: "", definition: object.source ?? "" }));+}+function publishProgress(session: SchemaDiffSession, progress: SchemaDiffSessionProgress): void {session.version += 1;session.progress = progress;@@ -125,11 +149,13 @@ async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: Scconst input = session.config;const tracker = useExportTracker();const options = normalizeSchemaDiffCompareOptions(input.options, input.targetDbType);- const routineKinds = schemaDiffRoutineObjectTypesIntersection(input.sourceDbType as DatabaseType, input.targetDbType);- const loadRoutines = shouldLoadSchemaDiffRoutines(input.sourceDbType, input.targetDbType, options);+ const sourceRoutineType = schemaDiffRoutineProductType(input.sourceDbType, input.sourceEngineDbType);+ const targetRoutineType = schemaDiffRoutineProductType(input.targetDbType, input.targetEngineDbType);+ const routineKinds = schemaDiffRoutineObjectTypesIntersection(sourceRoutineType, targetRoutineType);+ const loadRoutines = shouldLoadSchemaDiffRoutines(sourceRoutineType, targetRoutineType, options);const sessionOptions = options;const isPostgresLike = isSchemaDiffPostgresLike(input.targetDbType);- const hasExtraObjectPhase = shouldLoadSchemaDiffExtraObjectPhase(input.sourceDbType, input.targetDbType, sessionOptions);+ const hasExtraObjectPhase = shouldLoadSchemaDiffExtraObjectPhase(sourceRoutineType, targetRoutineType, sessionOptions);const tableFilter = compileSchemaDiffTableFilter(sessionOptions);const loadTableMetadata = !!(sessionOptions.tables || sessionOptions.views);@@ -191,8 +217,8 @@ async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: Scsignal.throwIfAborted();const promises: Promise<unknown>[] = [];if (loadRoutines) {- promises.push(api.listFunctions(input.sourceConnectionId, input.sourceDatabase, input.sourceSchema));- promises.push(api.listFunctions(input.targetConnectionId, input.targetDatabase, input.targetSchema));+ promises.push(loadSessionRoutines(session, "source", signal));+ promises.push(loadSessionRoutines(session, "target", signal));}if (isPostgresLike && sessionOptions.sequences) {promises.push(api.listSequences(input.sourceConnectionId, input.sourceDatabase, input.sourceSchema, !!sessionOptions.sequenceLastValues));@@ -220,6 +246,20 @@ async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: Scconst targetRules = sessionOptions.rules && isPostgresLike ? (extraObjects[index++] as Awaited<ReturnType<typeof api.listRules>>) : [];const sourceOwners = sessionOptions.owners && isPostgresLike ? (extraObjects[index++] as Awaited<ReturnType<typeof api.listOwners>>) : [];const targetOwners = sessionOptions.owners && isPostgresLike ? (extraObjects[index++] as Awaited<ReturnType<typeof api.listOwners>>) : [];+ if (loadRoutines && (isOracleRoutineEngine(input.sourceEngineDbType ?? input.sourceDbType) || isOracleRoutineEngine(input.targetEngineDbType ?? input.targetDbType))) {+ const source = session.routineSnapshots?.source;+ const target = session.routineSnapshots?.target;+ session.oracleRoutineContext = {+ sourceDatabaseType: input.sourceEngineDbType ?? input.sourceDbType,+ targetDatabaseType: input.targetEngineDbType ?? input.targetDbType,+ sourceSchema: input.sourceSchema,+ targetSchema: input.targetSchema,+ sourceEnumerationComplete: source?.enumerationComplete ?? true,+ targetEnumerationComplete: target?.enumerationComplete ?? true,+ sourceIncompleteNames: source?.objects.filter((object) => !object.sourceComplete).map((object) => object.version.identity.name) ?? [],+ targetIncompleteNames: target?.objects.filter((object) => !object.sourceComplete).map((object) => object.version.identity.name) ?? [],+ };+ }publishProgress(session, { phase: "comparing" });const result = await api.prepareSchemaDiff({@@ -229,6 +269,7 @@ async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: SctargetDetails,sourceFunctions,targetFunctions,+ oracleRoutines: session.oracleRoutineContext,sourceSequences,targetSequences,sourceRules,@@ -331,11 +372,13 @@ export function getSchemaDiffSession(id: string | null | undefined): SchemaDiffSexport function removeSchemaDiffSession(id: string): boolean {const session = sessions.get(id);if (session?.status === "running") return false;+ if (session?.routineDeployment) void disposeOracleRoutineDeployment(session.routineDeployment);return sessions.delete(id);}export function schemaDiffSessionNextProgressStep(session: SchemaDiffSession): string | null {- return getSchemaDiffNextProgressStep(session.progress?.phase, shouldLoadSchemaDiffExtraObjectPhase(session.config.sourceDbType, session.config.targetDbType, session.config.options));+ const config = session.config;+ return getSchemaDiffNextProgressStep(session.progress?.phase, shouldLoadSchemaDiffExtraObjectPhase(schemaDiffRoutineProductType(config.sourceDbType, config.sourceEngineDbType), schemaDiffRoutineProductType(config.targetDbType, config.targetEngineDbType), config.options));}export function schemaDiffSessionObjects(result: SchemaDiffPreparation | null): SchemaDiffObject[] {diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 1cc5c2a422..410128cc4c 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -6079,6 +6079,14 @@ export default {cancelEdit: "Cancel",sourceSaved: "Source saved",sourceSaveFailed: "Failed to save source: {message}",+ routineWritePending: "The original request has not been confirmed as finished (operation {operationId}). The draft is preserved; saving again only checks the original request and does not resend it.",+ routineWriteUnverified: "The save has not been verified as successful (operation {operationId}). The draft is preserved; handle this according to the result below.",+ routineWriteDraftChanged: "The original request has been checked; the current draft has additional changes. Save again.",+ routineSaveSingleDefinition: "Saving a routine requires one complete definition. Check the target and source.",+ routineWriteAcknowledged: "The DDL was submitted; below is the readback result for the target object.",+ routineReadbackInvalid: "The target object is invalid (INVALID). Fix the compilation errors before saving again.",+ routineReadbackMissing: "The target object was not read back. Check the target and permissions, then verify again.",+ routineReadbackMismatch: "The target definition does not match the approved draft. Check the current definition to avoid overwriting other changes.",refreshDiscardConfirm: "Refreshing will discard unsaved source edits. Continue?",postgresViewColumnChangeHint:"PostgreSQL cannot use CREATE OR REPLACE VIEW to remove, reorder, rename, or change the type of existing view columns. Keep existing column count, order, names, and types unchanged; new columns can only be appended. Use ALTER VIEW ... RENAME COLUMN to rename a column. To remove a column, review dependencies and recreate the view manually.",@@ -8632,7 +8640,7 @@ export default {routineSelectionUnrestricted: "Comparing all functions and procedures. Choose specific routines to limit the comparison.",routineSelectionTooLarge: "This schema has {count} routines (limit {limit} for unrestricted compare). Choose specific routines before comparing.",routineSelectionNeedSource: "Select a source connection and database first to choose routines.",- routineSelectionUnsupported: "Procedure/function compare requires the same supported dialect on both sides (MySQL, SQL Server, or PostgreSQL-family).",+ routineSelectionUnsupported: "Procedure/function compare requires compatible supported database types and readable routine source on both sides.",routineSameNameMatchingOnly: "Routines are matched by the same name (and signature). Manual rename mapping is not available in this release.",sourceRoutines: "Source routines",noRoutines: "No routines found",@@ -8655,6 +8663,25 @@ export default {selectRoutineToCompare: "Select a routine to compare definitions",routinesNotCompared: "Routine compare is off. Turn on the routines switch and re-compare.",routineDdlCopied: "DDL copied",+ routineNeedsValidation: "Needs validation",+ routineChecking: "Validating…",+ routinePending: "Original request needs checking",+ routineVerified: "Verified",+ routineUnverified: "Unverified",+ routinePrepared: "Ready to execute",+ routineDispatched: "Dispatched; no success acknowledgment received",+ routineValidate: "Validate again",+ routineObserve: "Check original request",+ routineRecoveryPreview: "Preview recovery script",+ routineRecoveryNote: "The recovery script executes new DDL; it is not a transaction rollback.",+ routineReadOnlyCompleted: "Completed steps will not be resent. To modify this object, compare again or preview a recovery script.",+ routineStopped: "Stopped sending subsequent steps. This does not cancel requests already dispatched.",+ routineHistory: "{count} operation records",+ routineRefreshBaseline: "Refresh baseline, keep draft",+ routineEqual: "Same",+ routineUnreadable: "Read incomplete",+ routineConflict: "Kind conflict",+ routineCallers: "Affected callers",copySourceDdl: "Copy source DDL",copyTargetDdl: "Copy target DDL",autoMatchHint: "Target tables are matched by the same name.",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 37e6a22ed0..3309f99732 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -5278,6 +5278,14 @@ export default withEnglishFallback({cancelEdit: "Cancelar",sourceSaved: "Código fuente guardado",sourceSaveFailed: "Error al guardar el código fuente: {message}",+ routineWritePending: "Aún no se ha confirmado que la solicitud original haya terminado (operación {operationId}). Se conserva el borrador; volver a guardar solo comprueba la solicitud original, no la vuelve a enviar.",+ routineWriteUnverified: "Aún no se ha verificado que el guardado haya tenido éxito (operación {operationId}). Se conserva el borrador; actúe según el resultado que aparece a continuación.",+ routineWriteDraftChanged: "Se ha comprobado la solicitud original; el borrador actual tiene cambios adicionales. Vuelva a guardarlo.",+ routineSaveSingleDefinition: "Para guardar una rutina se necesita una definición completa. Compruebe el destino y el código fuente.",+ routineWriteAcknowledged: "Se envió el DDL; a continuación se muestra el resultado de lectura del objeto de destino.",+ routineReadbackInvalid: "El objeto de destino no es válido (INVALID). Corrija los errores de compilación antes de volver a guardar.",+ routineReadbackMissing: "No se pudo leer el objeto de destino. Compruebe el destino y los permisos, y vuelva a verificar.",+ routineReadbackMismatch: "La definición de destino no coincide con el borrador aprobado. Compruebe la definición actual para evitar sobrescribir otros cambios.",postgresViewColumnChangeHint:"PostgreSQL no permite usar CREATE OR REPLACE VIEW para eliminar, reordenar, renombrar o cambiar el tipo de las columnas existentes de una vista. Mantenga sin cambios la cantidad, el orden, los nombres y los tipos de las columnas existentes; las columnas nuevas solo se pueden agregar al final. Use ALTER VIEW ... RENAME COLUMN para renombrar una columna. Para eliminar una columna, revise las dependencias y vuelva a crear la vista manualmente.",comment: "Comentario",@@ -7649,7 +7657,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "Comparando todas las funciones y procedimientos. Elige rutinas específicas para limitar la comparación.",routineSelectionTooLarge: "Este esquema tiene {count} rutinas (límite {limit} sin selección). Elige rutinas específicas antes de comparar.",routineSelectionNeedSource: "Selecciona primero una conexión y base de datos de origen para elegir rutinas.",- routineSelectionUnsupported: "La comparación de procedimientos/funciones requiere el mismo dialecto admitido en ambos lados (MySQL, SQL Server o familia PostgreSQL).",+ routineSelectionUnsupported: "La comparación de procedimientos/funciones requiere tipos de base de datos compatibles y admitidos, y código fuente legible en ambos lados.",routineSameNameMatchingOnly: "Las rutinas se emparejan por el mismo nombre (y firma). El mapeo manual de renombres no está disponible en esta versión.",sourceRoutines: "Rutinas de origen",noRoutines: "No se encontraron rutinas",@@ -7671,6 +7679,25 @@ export default withEnglishFallback({selectRoutineToCompare: "Selecciona una rutina para comparar definiciones",routinesNotCompared: "La comparación de rutinas está desactivada. Activa el interruptor de rutinas y vuelve a comparar.",routineDdlCopied: "DDL copiado",+ routineNeedsValidation: "Pendiente de validar",+ routineChecking: "Validando…",+ routinePending: "Solicitud original pendiente de comprobación",+ routineVerified: "Verificado",+ routineUnverified: "Sin verificar",+ routinePrepared: "Listo para ejecutar",+ routineDispatched: "Enviado; no se recibió confirmación de éxito",+ routineValidate: "Validar de nuevo",+ routineObserve: "Comprobar solicitud original",+ routineRecoveryPreview: "Previsualizar script de recuperación",+ routineRecoveryNote: "El script de recuperación ejecuta DDL nuevo; no es una reversión de transacción.",+ routineReadOnlyCompleted: "Los pasos completados no se volverán a enviar. Para modificar este objeto, vuelva a comparar o previsualice un script de recuperación.",+ routineStopped: "Se detuvo el envío de los pasos siguientes. Esto no cancela las solicitudes ya enviadas.",+ routineHistory: "{count} registros de operaciones",+ routineRefreshBaseline: "Actualizar línea base y conservar el borrador",+ routineEqual: "Igual",+ routineUnreadable: "Lectura incompleta",+ routineConflict: "Conflicto de tipo",+ routineCallers: "Llamadores afectados",autoMatchHint: "Las tablas de destino se emparejan por el mismo nombre.",matchedTables: "{matched}/{total} tablas coinciden",missingTargetTables: "Faltan tablas de destino con el mismo nombre: {tables}",diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.tsindex 4bdeaa8b88..fe099ac0ae 100644--- a/apps/desktop/src/i18n/locales/id.ts+++ b/apps/desktop/src/i18n/locales/id.ts@@ -7735,7 +7735,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "Membandingkan semua fungsi dan prosedur. Pilih rutin tertentu untuk membatasi perbandingan.",routineSelectionTooLarge: "Skema ini memiliki {count} rutin (batas {limit} untuk perbandingan tanpa batasan). Pilih rutin tertentu sebelum membandingkan.",routineSelectionNeedSource: "Pilih koneksi dan database sumber terlebih dahulu untuk memilih rutin.",- routineSelectionUnsupported: "Perbandingan prosedur/fungsi memerlukan dialek yang sama dan didukung di kedua sisi (MySQL, SQL Server, atau keluarga PostgreSQL).",+ routineSelectionUnsupported: "Perbandingan prosedur/fungsi memerlukan jenis basis data yang didukung dan kompatibel serta kode sumber yang dapat dibaca di kedua sisi.",routineSameNameMatchingOnly: "Rutin dicocokkan berdasarkan nama yang sama (dan signature). Pemetaan ganti nama manual belum tersedia di rilis ini.",sourceRoutines: "Rutin sumber",noRoutines: "Tidak ditemukan rutin",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 9dbaed12d8..00982fcbf8 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -5098,6 +5098,14 @@ export default withEnglishFallback({cancelEdit: "Annulla",sourceSaved: "Sorgente salvato",sourceSaveFailed: "Impossibile salvare il sorgente: {message}",+ routineWritePending: "Non è ancora stato confermato che la richiesta originale sia terminata (operazione {operationId}). La bozza è conservata; salvando di nuovo si controlla solo la richiesta originale, senza reinviarla.",+ routineWriteUnverified: "Il salvataggio non è ancora stato verificato come riuscito (operazione {operationId}). La bozza è conservata; procedi in base al risultato qui sotto.",+ routineWriteDraftChanged: "La richiesta originale è stata verificata; la bozza attuale contiene altre modifiche. Salva di nuovo.",+ routineSaveSingleDefinition: "Per salvare una routine serve una definizione completa. Controlla la destinazione e il codice sorgente.",+ routineWriteAcknowledged: "Il DDL è stato inviato; di seguito è riportato il risultato della rilettura dell'oggetto di destinazione.",+ routineReadbackInvalid: "L'oggetto di destinazione non è valido (INVALID). Correggi gli errori di compilazione prima di salvare di nuovo.",+ routineReadbackMissing: "L'oggetto di destinazione non è stato riletto. Controlla la destinazione e i permessi, quindi verifica di nuovo.",+ routineReadbackMismatch: "La definizione di destinazione non corrisponde alla bozza approvata. Controlla la definizione attuale per evitare di sovrascrivere altre modifiche.",postgresViewColumnChangeHint:"PostgreSQL non consente di usare CREATE OR REPLACE VIEW per eliminare, riordinare, rinominare o cambiare il tipo delle colonne esistenti di una vista. Mantieni invariati il numero, l'ordine, i nomi e i tipi delle colonne esistenti; le nuove colonne possono essere aggiunte solo alla fine. Usa ALTER VIEW ... RENAME COLUMN per rinominare una colonna. Per eliminare una colonna, verifica le dipendenze e ricrea manualmente la vista.",comment: "Commento",@@ -7433,7 +7441,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "Confronto di tutte le funzioni e procedure. Scegli routine specifiche per limitare il confronto.",routineSelectionTooLarge: "Questo schema ha {count} routine (limite {limit} senza selezione). Scegli routine specifiche prima di confrontare.",routineSelectionNeedSource: "Seleziona prima una connessione e un database di origine per scegliere le routine.",- routineSelectionUnsupported: "Il confronto di procedure/funzioni richiede lo stesso dialetto supportato su entrambi i lati (MySQL, SQL Server o famiglia PostgreSQL).",+ routineSelectionUnsupported: "Il confronto di procedure/funzioni richiede tipi di database supportati e compatibili e codice sorgente leggibile su entrambi i lati.",routineSameNameMatchingOnly: "Le routine vengono abbinate per lo stesso nome (e firma). Il mapping manuale di rinomina non è disponibile in questa versione.",sourceRoutines: "Routine di origine",noRoutines: "Nessuna routine trovata",@@ -7455,6 +7463,25 @@ export default withEnglishFallback({selectRoutineToCompare: "Seleziona una routine per confrontare le definizioni",routinesNotCompared: "Il confronto delle routine è disattivato. Attiva l'interruttore e confronta di nuovo.",routineDdlCopied: "DDL copiato",+ routineNeedsValidation: "Da verificare",+ routineChecking: "Verifica in corso…",+ routinePending: "Richiesta originale da verificare",+ routineVerified: "Verificato",+ routineUnverified: "Non verificato",+ routinePrepared: "Pronto per l'esecuzione",+ routineDispatched: "Inviata; nessuna conferma di successo ricevuta",+ routineValidate: "Verifica di nuovo",+ routineObserve: "Verifica la richiesta originale",+ routineRecoveryPreview: "Anteprima dello script di ripristino",+ routineRecoveryNote: "Lo script di ripristino esegue nuovo DDL; non è un rollback della transazione.",+ routineReadOnlyCompleted: "I passaggi completati non verranno inviati di nuovo. Per modificare questo oggetto, confronta di nuovo o visualizza l'anteprima di uno script di ripristino.",+ routineStopped: "Invio dei passaggi successivi interrotto. Le richieste già inviate non vengono annullate.",+ routineHistory: "{count} registrazioni di operazioni",+ routineRefreshBaseline: "Aggiorna la baseline e conserva la bozza",+ routineEqual: "Uguale",+ routineUnreadable: "Lettura incompleta",+ routineConflict: "Conflitto di tipo",+ routineCallers: "Chiamanti interessati",autoMatchHint: "Le tabelle di destinazione vengono abbinate per nome.",matchedTables: "{matched}/{total} tabelle abbinate",missingTargetTables: "Tabelle di destinazione omonime mancanti: {tables}",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 15c7739a0b..8c63498499 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -5160,6 +5160,14 @@ export default withEnglishFallback({cancelEdit: "キャンセル",sourceSaved: "ソースを保存しました",sourceSaveFailed: "ソースの保存に失敗しました: {message}",+ routineWritePending: "元のリクエストの完了はまだ確認されていません(操作 {operationId})。下書きは保持されています。再度保存すると元のリクエストを確認するだけで、再送信はしません。",+ routineWriteUnverified: "保存の成功はまだ確認できていません(操作 {operationId})。下書きは保持されています。以下の結果に応じて対応してください。",+ routineWriteDraftChanged: "元のリクエストを確認しました。現在の下書きには追加の変更があります。もう一度保存してください。",+ routineSaveSingleDefinition: "ルーチンの保存には完全な定義が1つ必要です。対象とソースを確認してください。",+ routineWriteAcknowledged: "DDL は送信されました。以下は対象オブジェクトの読み戻し結果です。",+ routineReadbackInvalid: "対象オブジェクトは無効です(INVALID)。再度保存する前にコンパイルエラーを修正してください。",+ routineReadbackMissing: "対象オブジェクトを読み戻せませんでした。対象と権限を確認してから、もう一度照合してください。",+ routineReadbackMismatch: "対象の定義が承認済みの下書きと一致しません。他の変更を上書きしないよう、現在の定義を確認してください。",postgresViewColumnChangeHint:"PostgreSQL では CREATE OR REPLACE VIEW を使用して、既存のビュー列の削除、並べ替え、名前変更、または型変更を行うことはできません。既存列の数、順序、名前、型を維持してください。新しい列は末尾にのみ追加できます。列名の変更には ALTER VIEW ... RENAME COLUMN を使用してください。列を削除する場合は、依存関係を確認してビューを手動で再作成してください。",comment: "コメント",@@ -7517,7 +7525,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "すべての関数とプロシージャを比較します。特定のルーチンを選ぶと範囲を限定できます。",routineSelectionTooLarge: "このスキーマには {count} 件のルーチンがあります(未指定時の上限は {limit})。比較前にルーチンを選択してください。",routineSelectionNeedSource: "ルーチンを選ぶ前に、ソースの接続とデータベースを選択してください。",- routineSelectionUnsupported: "プロシージャ/関数の比較には、ソースとターゲットが同じ対応方言(MySQL、SQL Server、または PostgreSQL 系)である必要があります。",+ routineSelectionUnsupported: "プロシージャ/関数の比較には、両側が互換性のある対応データベース型で、ソースコードを読み取れる必要があります。",routineSameNameMatchingOnly: "ルーチンは同名(およびシグネチャ)で照合します。このリリースでは手動のリネーム対応付けは未対応です。",sourceRoutines: "ソースのルーチン",noRoutines: "ルーチンがありません",@@ -7539,6 +7547,25 @@ export default withEnglishFallback({selectRoutineToCompare: "定義を比較するルーチンを選択",routinesNotCompared: "ルーチン比較はオフです。スイッチをオンにして再比較してください。",routineDdlCopied: "DDL をコピーしました",+ routineNeedsValidation: "検証が必要です",+ routineChecking: "検証中…",+ routinePending: "元のリクエストの確認待ち",+ routineVerified: "検証済み",+ routineUnverified: "未検証",+ routinePrepared: "実行準備完了",+ routineDispatched: "送信済み(成功応答なし)",+ routineValidate: "再検証",+ routineObserve: "元のリクエストを確認",+ routineRecoveryPreview: "リカバリースクリプトをプレビュー",+ routineRecoveryNote: "リカバリースクリプトは新しい DDL を実行します。トランザクションのロールバックではありません。",+ routineReadOnlyCompleted: "完了した手順は再送信されません。このオブジェクトを変更するには、再比較するかリカバリースクリプトをプレビューしてください。",+ routineStopped: "後続手順の送信を停止しました。送信済みのリクエストはキャンセルされません。",+ routineHistory: "{count} 件の操作記録",+ routineRefreshBaseline: "下書きを保持して基準を更新",+ routineEqual: "同じ",+ routineUnreadable: "読み取り未完了",+ routineConflict: "種別の競合",+ routineCallers: "影響を受ける呼び出し元",autoMatchHint: "ターゲットテーブルは同じ名前でマッチングされます。",matchedTables: "{matched}/{total}テーブルがマッチしました",missingTargetTables: "同名のターゲットテーブルがありません: {tables}",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex e9a8bef6a0..5d9fbba351 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -5252,6 +5252,14 @@ export default withEnglishFallback({cancelEdit: "취소",sourceSaved: "소스를 저장했습니다",sourceSaveFailed: "소스 저장에 실패했습니다: {message}",+ routineWritePending: "원래 요청이 완료되었는지 아직 확인되지 않았습니다(작업 {operationId}). 초안은 보존됩니다. 다시 저장하면 원래 요청만 확인하며 재전송하지 않습니다.",+ routineWriteUnverified: "저장이 성공했는지 아직 확인되지 않았습니다(작업 {operationId}). 초안은 보존됩니다. 아래 결과에 따라 처리하세요.",+ routineWriteDraftChanged: "원래 요청을 확인했습니다. 현재 초안에 추가 변경 사항이 있습니다. 다시 저장하세요.",+ routineSaveSingleDefinition: "루틴을 저장하려면 완전한 정의 하나가 필요합니다. 대상과 소스를 확인하세요.",+ routineWriteAcknowledged: "DDL이 제출되었습니다. 아래는 대상 객체를 다시 읽은 결과입니다.",+ routineReadbackInvalid: "대상 객체가 유효하지 않습니다(INVALID). 다시 저장하기 전에 컴파일 오류를 수정하세요.",+ routineReadbackMissing: "대상 객체를 다시 읽지 못했습니다. 대상과 권한을 확인한 다음 다시 검증하세요.",+ routineReadbackMismatch: "대상 정의가 승인된 초안과 일치하지 않습니다. 다른 변경 사항을 덮어쓰지 않도록 현재 정의를 확인하세요.",postgresViewColumnChangeHint:"PostgreSQL은 CREATE OR REPLACE VIEW로 기존 뷰 컬럼을 제거, 재정렬, 이름 변경 또는 타입 변경할 수 없습니다. 기존 컬럼 수, 순서, 이름, 타입은 그대로 유지하고 새 컬럼은 끝에만 추가할 수 있습니다. 컬럼 이름을 바꾸려면 ALTER VIEW ... RENAME COLUMN을 사용하세요. 컬럼을 제거하려면 종속성을 검토하고 뷰를 수동으로 다시 만드세요.",sourceReadOnly: "이 소스는 읽기 전용이며 편집할 수 없습니다.",@@ -7553,7 +7561,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "모든 함수와 프로시저를 비교합니다. 특정 루틴을 선택하면 비교 범위를 제한할 수 있습니다.",routineSelectionTooLarge: "이 스키마에 루틴이 {count}개 있습니다(미선택 시 한도 {limit}). 비교 전에 루틴을 선택하세요.",routineSelectionNeedSource: "루틴을 선택하려면 먼저 소스 연결과 데이터베이스를 선택하세요.",- routineSelectionUnsupported: "프로시저/함수 비교는 양쪽이 같은 지원 방언(MySQL, SQL Server 또는 PostgreSQL 계열)이어야 합니다.",+ routineSelectionUnsupported: "프로시저/함수 비교에는 양쪽에 호환되는 지원 데이터베이스 유형과 읽을 수 있는 소스 코드가 필요합니다.",routineSameNameMatchingOnly: "루틴은 같은 이름(및 시그니처)으로 매칭됩니다. 이 버전에서는 수동 이름 변경 매핑을 사용할 수 없습니다.",sourceRoutines: "소스 루틴",noRoutines: "루틴 없음",@@ -7576,6 +7584,25 @@ export default withEnglishFallback({selectRoutineToCompare: "정의를 비교할 루틴을 선택하세요",routinesNotCompared: "루틴 비교가 꺼져 있습니다. 루틴 스위치를 켠 뒤 다시 비교하세요.",routineDdlCopied: "DDL을 복사했습니다",+ routineNeedsValidation: "검증 필요",+ routineChecking: "검증 중…",+ routinePending: "원래 요청 확인 대기 중",+ routineVerified: "검증됨",+ routineUnverified: "미검증",+ routinePrepared: "실행 준비됨",+ routineDispatched: "전송됨; 성공 확인 응답 없음",+ routineValidate: "다시 검증",+ routineObserve: "원래 요청 확인",+ routineRecoveryPreview: "복구 스크립트 미리보기",+ routineRecoveryNote: "복구 스크립트는 새 DDL을 실행하며 트랜잭션 롤백이 아닙니다.",+ routineReadOnlyCompleted: "완료된 단계는 다시 전송되지 않습니다. 이 객체를 수정하려면 다시 비교하거나 복구 스크립트를 미리 보세요.",+ routineStopped: "후속 단계 전송을 중지했습니다. 이미 전송된 요청은 취소되지 않습니다.",+ routineHistory: "작업 기록 {count}개",+ routineRefreshBaseline: "초안을 유지하며 기준 새로고침",+ routineEqual: "같음",+ routineUnreadable: "읽기 미완료",+ routineConflict: "종류 충돌",+ routineCallers: "영향받는 호출자",copySourceDdl: "소스 DDL 복사",copyTargetDdl: "대상 DDL 복사",},diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.tsindex 86350d3019..d952faedb9 100644--- a/apps/desktop/src/i18n/locales/pl.ts+++ b/apps/desktop/src/i18n/locales/pl.ts@@ -7798,7 +7798,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "Porównywanie wszystkich funkcji i procedur. Wybierz konkretne elementy, aby ograniczyć porównanie.",routineSelectionTooLarge: "Ten schemat ma {count} procedur i funkcji (limit dla nieograniczonego porównania wynosi {limit}). Wybierz konkretne elementy przed porównaniem.",routineSelectionNeedSource: "Najpierw wybierz źródłowe połączenie i bazę danych, aby wybrać procedury i funkcje.",- routineSelectionUnsupported: "Porównywanie procedur/funkcji wymaga tego samego obsługiwanego dialektu po obu stronach (MySQL, SQL Server lub rodzina PostgreSQL).",+ routineSelectionUnsupported: "Porównywanie procedur/funkcji wymaga zgodnych i obsługiwanych typów baz danych oraz dostępnego kodu źródłowego po obu stronach.",routineSameNameMatchingOnly: "Procedury i funkcje są dopasowywane według identycznej nazwy (i sygnatury). Ręczne mapowanie zmian nazw nie jest dostępne w tej wersji.",sourceRoutines: "Procedury i funkcje źródłowe",noRoutines: "Nie znaleziono procedur ani funkcji",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex bfb4158358..89ac88ef42 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -5098,6 +5098,14 @@ export default withEnglishFallback({cancelEdit: "Cancelar",sourceSaved: "Código-fonte salvo",sourceSaveFailed: "Falha ao salvar código-fonte: {message}",+ routineWritePending: "Ainda não foi confirmado que a solicitação original terminou (operação {operationId}). O rascunho foi preservado; salvar novamente apenas verifica a solicitação original, sem reenviá-la.",+ routineWriteUnverified: "Ainda não foi confirmado que o salvamento foi bem-sucedido (operação {operationId}). O rascunho foi preservado; aja conforme o resultado abaixo.",+ routineWriteDraftChanged: "A solicitação original foi verificada; o rascunho atual tem alterações adicionais. Salve novamente.",+ routineSaveSingleDefinition: "Para salvar uma rotina, é necessária uma definição completa. Verifique o destino e o código-fonte.",+ routineWriteAcknowledged: "O DDL foi enviado; abaixo está o resultado da leitura de retorno do objeto de destino.",+ routineReadbackInvalid: "O objeto de destino é inválido (INVALID). Corrija os erros de compilação antes de salvar novamente.",+ routineReadbackMissing: "O objeto de destino não foi lido de volta. Verifique o destino e as permissões e, em seguida, confira novamente.",+ routineReadbackMismatch: "A definição de destino não corresponde ao rascunho aprovado. Confira a definição atual para evitar sobrescrever outras alterações.",postgresViewColumnChangeHint:"O PostgreSQL não permite usar CREATE OR REPLACE VIEW para remover, reordenar, renomear ou alterar o tipo das colunas existentes de uma view. Mantenha inalterados a quantidade, a ordem, os nomes e os tipos das colunas existentes; novas colunas só podem ser adicionadas ao final. Use ALTER VIEW ... RENAME COLUMN para renomear uma coluna. Para remover uma coluna, revise as dependências e recrie a view manualmente.",comment: "Comentário",@@ -7432,7 +7440,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "Comparando todas as funções e procedimentos. Escolha rotinas específicas para limitar a comparação.",routineSelectionTooLarge: "Este schema tem {count} rotinas (limite {limit} sem seleção). Escolha rotinas específicas antes de comparar.",routineSelectionNeedSource: "Selecione primeiro uma conexão e um banco de origem para escolher rotinas.",- routineSelectionUnsupported: "A comparação de procedimentos/funções exige o mesmo dialeto suportado em ambos os lados (MySQL, SQL Server ou família PostgreSQL).",+ routineSelectionUnsupported: "A comparação de procedimentos/funções exige tipos de banco de dados compatíveis e suportados e código-fonte legível em ambos os lados.",routineSameNameMatchingOnly: "As rotinas são correspondidas pelo mesmo nome (e assinatura). O mapeamento manual de renomeação não está disponível nesta versão.",sourceRoutines: "Rotinas de origem",noRoutines: "Nenhuma rotina encontrada",@@ -7454,6 +7462,25 @@ export default withEnglishFallback({selectRoutineToCompare: "Selecione uma rotina para comparar definições",routinesNotCompared: "A comparação de rotinas está desativada. Ative o interruptor e compare novamente.",routineDdlCopied: "DDL copiado",+ routineNeedsValidation: "Aguardando validação",+ routineChecking: "Validando…",+ routinePending: "Solicitação original aguardando conferência",+ routineVerified: "Verificado",+ routineUnverified: "Não verificado",+ routinePrepared: "Pronto para executar",+ routineDispatched: "Enviado; nenhuma confirmação de sucesso recebida",+ routineValidate: "Validar novamente",+ routineObserve: "Conferir solicitação original",+ routineRecoveryPreview: "Visualizar script de recuperação",+ routineRecoveryNote: "O script de recuperação executa um novo DDL; não é uma reversão de transação.",+ routineReadOnlyCompleted: "As etapas concluídas não serão reenviadas. Para modificar este objeto, compare novamente ou visualize um script de recuperação.",+ routineStopped: "O envio das próximas etapas foi interrompido. Isso não cancela as solicitações já enviadas.",+ routineHistory: "{count} registros de operações",+ routineRefreshBaseline: "Atualizar linha de base e manter o rascunho",+ routineEqual: "Igual",+ routineUnreadable: "Leitura incompleta",+ routineConflict: "Conflito de tipo",+ routineCallers: "Chamadores afetados",autoMatchHint: "As tabelas de destino são correspondidas pelo mesmo nome.",matchedTables: "{matched}/{total} tabelas correspondidas",missingTargetTables: "Tabelas de destino com o mesmo nome ausentes: {tables}",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 24a57f7a2b..f12e0782cc 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -5727,6 +5727,14 @@ export default withEnglishFallback({cancelEdit: "Отмена",sourceSaved: "Исходный код сохранён",sourceSaveFailed: "Не удалось сохранить исходный код: {message}",+ routineWritePending: "Завершение исходного запроса ещё не подтверждено (операция {operationId}). Черновик сохранён; повторное сохранение только проверяет исходный запрос и не отправляет его повторно.",+ routineWriteUnverified: "Успешное сохранение ещё не подтверждено (операция {operationId}). Черновик сохранён; действуйте согласно результату ниже.",+ routineWriteDraftChanged: "Исходный запрос проверен; в текущем черновике есть дополнительные изменения. Сохраните его ещё раз.",+ routineSaveSingleDefinition: "Для сохранения подпрограммы требуется одно полное определение. Проверьте целевой объект и исходный код.",+ routineWriteAcknowledged: "DDL отправлен; ниже приведён результат чтения целевого объекта.",+ routineReadbackInvalid: "Целевой объект недействителен (INVALID). Исправьте ошибки компиляции перед повторным сохранением.",+ routineReadbackMissing: "Целевой объект не удалось прочитать. Проверьте объект и разрешения, затем выполните проверку ещё раз.",+ routineReadbackMismatch: "Определение целевого объекта не совпадает с утверждённым черновиком. Проверьте текущее определение, чтобы не перезаписать другие изменения.",refreshDiscardConfirm: "Обновление отменит несохранённые изменения исходного кода. Продолжить?",postgresViewColumnChangeHint:"PostgreSQL не позволяет с помощью CREATE OR REPLACE VIEW удалять, переупорядочивать, переименовывать столбцы существующего представления или изменять их типы. Сохраняйте количество, порядок, имена и типы существующих столбцов неизменными; новые столбцы можно только добавлять в конец. Для переименования столбца используйте ALTER VIEW ... RENAME COLUMN. Чтобы удалить столбец, проверьте зависимости и пересоздайте представление вручную.",@@ -8849,7 +8857,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "Сравниваются все функции и процедуры. Выберите конкретные процедуры, чтобы ограничить сравнение.",routineSelectionTooLarge: "В этой схеме {count} процедур (лимит {limit} для неограниченного сравнения). Выберите конкретные процедуры перед сравнением.",routineSelectionNeedSource: "Сначала выберите исходное подключение и базу данных, чтобы выбрать процедуры.",- routineSelectionUnsupported: "Для сравнения процедур и функций требуется один и тот же поддерживаемый диалект с обеих сторон (MySQL, SQL Server или семейство PostgreSQL).",+ routineSelectionUnsupported: "Для сравнения процедур и функций требуются совместимые поддерживаемые типы баз данных и доступный для чтения исходный код с обеих сторон.",routineSameNameMatchingOnly: "Процедуры сопоставляются по одинаковому имени (и сигнатуре). Сопоставление с переименованием вручную в этой версии недоступно.",sourceRoutines: "Процедуры источника",noRoutines: "Процедуры не найдены",@@ -8872,6 +8880,25 @@ export default withEnglishFallback({selectRoutineToCompare: "Выберите процедуру для сравнения определений",routinesNotCompared: "Сравнение процедур отключено. Включите переключатель процедур и повторите сравнение.",routineDdlCopied: "DDL скопирован",+ routineNeedsValidation: "Требуется проверка",+ routineChecking: "Проверка…",+ routinePending: "Исходный запрос требует проверки",+ routineVerified: "Проверено",+ routineUnverified: "Не проверено",+ routinePrepared: "Готово к выполнению",+ routineDispatched: "Отправлено; подтверждение успеха не получено",+ routineValidate: "Проверить ещё раз",+ routineObserve: "Проверить исходный запрос",+ routineRecoveryPreview: "Предпросмотр сценария восстановления",+ routineRecoveryNote: "Сценарий восстановления выполняет новый DDL, а не откатывает транзакцию.",+ routineReadOnlyCompleted: "Завершённые шаги не будут отправлены повторно. Чтобы изменить этот объект, сравните его заново или просмотрите сценарий восстановления.",+ routineStopped: "Отправка следующих шагов остановлена. Уже отправленные запросы это не отменяет.",+ routineHistory: "Записей операций: {count}",+ routineRefreshBaseline: "Обновить базовый снимок, сохранив черновик",+ routineEqual: "Совпадает",+ routineUnreadable: "Чтение не завершено",+ routineConflict: "Конфликт типов",+ routineCallers: "Затронутые вызывающие объекты",copySourceDdl: "Копировать DDL источника",copyTargetDdl: "Копировать DDL цели",autoMatchHint: "Целевые таблицы сопоставляются по одинаковому имени.",diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex 50ee564149..5e00133029 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -6049,6 +6049,14 @@ export default withEnglishFallback({cancelEdit: "ยกเลิก",sourceSaved: "บันทึก Source แล้ว",sourceSaveFailed: "บันทึก Source ไม่สำเร็จ: {message}",+ routineWritePending: "ยังไม่ยืนยันว่าคำขอเดิมเสร็จสิ้นแล้ว (การดำเนินการ {operationId}) เก็บฉบับร่างไว้แล้ว การบันทึกอีกครั้งจะตรวจสอบเฉพาะคำขอเดิมและจะไม่ส่งซ้ำ",+ routineWriteUnverified: "ยังไม่ได้ยืนยันว่าบันทึกสำเร็จ (การดำเนินการ {operationId}) เก็บฉบับร่างไว้แล้ว โปรดดำเนินการตามผลด้านล่าง",+ routineWriteDraftChanged: "ตรวจสอบคำขอเดิมแล้ว ฉบับร่างปัจจุบันมีการแก้ไขเพิ่มเติม โปรดบันทึกอีกครั้ง",+ routineSaveSingleDefinition: "การบันทึก Routine ต้องมีคำจำกัดความที่สมบูรณ์หนึ่งรายการ โปรดตรวจสอบเป้าหมายและ Source",+ routineWriteAcknowledged: "ส่ง DDL แล้ว ด้านล่างคือผลการอ่านกลับของออบเจ็กต์เป้าหมาย",+ routineReadbackInvalid: "ออบเจ็กต์เป้าหมายไม่ถูกต้อง (INVALID) โปรดแก้ข้อผิดพลาดในการคอมไพล์ก่อนบันทึกอีกครั้ง",+ routineReadbackMissing: "ไม่ได้อ่านออบเจ็กต์เป้าหมายกลับมา โปรดตรวจสอบเป้าหมายและสิทธิ์ แล้วตรวจสอบอีกครั้ง",+ routineReadbackMismatch: "คำจำกัดความของเป้าหมายไม่ตรงกับฉบับร่างที่อนุมัติ โปรดตรวจสอบคำจำกัดความปัจจุบันเพื่อหลีกเลี่ยงการเขียนทับการแก้ไขอื่น",refreshDiscardConfirm: "การรีเฟรชจะทิ้งการแก้ไข Source ที่ยังไม่บันทึก ดำเนินการต่อหรือไม่",postgresViewColumnChangeHint:"PostgreSQL ใช้ CREATE OR REPLACE VIEW เพื่อลบ เรียงใหม่ เปลี่ยนชื่อ หรือเปลี่ยน Type ของ Column View ที่มีอยู่ไม่ได้ คงจำนวน ลำดับ ชื่อ และ Type ของ Column เดิมไว้ Column ใหม่ต่อท้ายได้เท่านั้น ใช้ ALTER VIEW ... RENAME COLUMN เพื่อเปลี่ยนชื่อ Column หากต้องการลบ Column ให้ตรวจสอบ Dependencies และสร้าง View ใหม่ด้วยตนเอง",@@ -9275,7 +9283,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "กำลังเปรียบเทียบ Function และ Procedure ทั้งหมด เลือก Routine เฉพาะเพื่อจำกัดการเปรียบเทียบ",routineSelectionTooLarge: "Schema นี้มี {count} Routine (จำกัด {limit} สำหรับการเปรียบเทียบแบบไม่จำกัด) เลือก Routine เฉพาะก่อนเปรียบเทียบ",routineSelectionNeedSource: "เลือกการเชื่อมต่อและฐานข้อมูลต้นทางก่อนเพื่อเลือก Routine",- routineSelectionUnsupported: "การเปรียบเทียบ Procedure/Function ต้องใช้ dialect ที่รองรับเหมือนกันทั้งสองฝั่ง (MySQL, SQL Server หรือกลุ่ม PostgreSQL)",+ routineSelectionUnsupported: "การเปรียบเทียบ Procedure/Function ต้องใช้ชนิดฐานข้อมูลที่รองรับและเข้ากันได้ พร้อมอ่านซอร์สโค้ดได้ทั้งสองฝั่ง",routineSameNameMatchingOnly: "จับคู่ Routine ด้วยชื่อ (และ signature) เดียวกัน ไม่รองรับการกำหนดการจับคู่ชื่อใหม่ด้วยตนเองในรุ่นนี้",sourceRoutines: "Routine ต้นทาง",noRoutines: "ไม่พบ Routine",@@ -9298,6 +9306,25 @@ export default withEnglishFallback({selectRoutineToCompare: "เลือก Routine เพื่อเปรียบเทียบคำจำกัดความ",routinesNotCompared: "ปิดการเปรียบเทียบ Routine อยู่ เปิดสวิตช์ Routine แล้วเปรียบเทียบอีกครั้ง",routineDdlCopied: "คัดลอก DDL แล้ว",+ routineNeedsValidation: "รอตรวจสอบ",+ routineChecking: "กำลังตรวจสอบ…",+ routinePending: "รอตรวจสอบคำขอเดิม",+ routineVerified: "ตรวจสอบแล้ว",+ routineUnverified: "ยังไม่ได้ตรวจสอบ",+ routinePrepared: "พร้อมดำเนินการ",+ routineDispatched: "ส่งคำขอแล้ว แต่ไม่ได้รับการยืนยันความสำเร็จ",+ routineValidate: "ตรวจสอบอีกครั้ง",+ routineObserve: "ตรวจสอบคำขอเดิม",+ routineRecoveryPreview: "แสดงตัวอย่างสคริปต์กู้คืน",+ routineRecoveryNote: "สคริปต์กู้คืนจะเรียกใช้ DDL ใหม่ ไม่ใช่การย้อนกลับธุรกรรม",+ routineReadOnlyCompleted: "ขั้นตอนที่เสร็จแล้วจะไม่ถูกส่งซ้ำ หากต้องการแก้ไขออบเจ็กต์นี้ ให้เปรียบเทียบอีกครั้งหรือแสดงตัวอย่างสคริปต์กู้คืน",+ routineStopped: "หยุดส่งขั้นตอนถัดไปแล้ว แต่คำขอที่ส่งไปแล้วจะไม่ถูกยกเลิก",+ routineHistory: "บันทึกการดำเนินการ {count} รายการ",+ routineRefreshBaseline: "รีเฟรชค่าฐานและเก็บฉบับร่างไว้",+ routineEqual: "เหมือนกัน",+ routineUnreadable: "อ่านไม่เสร็จ",+ routineConflict: "ชนิดไม่ตรงกัน",+ routineCallers: "ผู้เรียกที่ได้รับผลกระทบ",copySourceDdl: "คัดลอก DDL ต้นทาง",copyTargetDdl: "คัดลอก DDL ปลายทาง",autoMatchHint: "จับคู่ตารางปลายทางด้วยชื่อเดียวกัน",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 3f96824b26..104d003242 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -6055,6 +6055,14 @@ export default withEnglishFallback({cancelEdit: "取消",sourceSaved: "源码已保存",sourceSaveFailed: "保存源码失败:{message}",+ routineWritePending: "原请求尚未确认结束(操作 {operationId})。草稿已保留;再次保存只核对原请求,不重发。",+ routineWriteUnverified: "尚未验证保存成功(操作 {operationId})。草稿已保留,请根据下方结果处理。",+ routineWriteDraftChanged: "原请求已核对;当前草稿另有修改,请重新保存。",+ routineSaveSingleDefinition: "保存例程需要一条完整定义,请检查目标和源码。",+ routineWriteAcknowledged: "DDL 已提交;以下为目标对象的读回结果。",+ routineReadbackInvalid: "目标对象无效(INVALID)。请修正编译错误后再保存。",+ routineReadbackMissing: "未读回目标对象。请检查目标和权限后重新核对。",+ routineReadbackMismatch: "目标定义与批准稿不符。请核对当前定义,避免覆盖其他修改。",refreshDiscardConfirm: "刷新将丢弃未保存的源码修改,是否继续?",postgresViewColumnChangeHint: "PostgreSQL 无法通过 CREATE OR REPLACE VIEW 删除、重排、重命名已有视图字段,或修改字段类型。请保持原字段的数量、顺序、名称和类型不变;新增字段只能追加在末尾。重命名字段请使用 ALTER VIEW ... RENAME COLUMN;删除字段前请检查依赖并手动重建视图。",sourceReadOnly: "该源码为只读,不能编辑。",@@ -8686,7 +8694,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "比较全部函数与存储过程。可指定对象来限定比较范围。",routineSelectionTooLarge: "当前库有 {count} 个例程(未指定时最多比较 {limit} 个)。请先指定要比较的存储过程/函数。",routineSelectionNeedSource: "请先选择源连接和数据库,再指定要比较的存储过程或函数。",- routineSelectionUnsupported: "源与目标需为同一受支持方言(MySQL、SQL Server 或 PostgreSQL 系),且能列出存储过程/函数源码,才能开启例程对比。",+ routineSelectionUnsupported: "源与目标需采用兼容的受支持数据库类型,且能读取存储过程/函数源码,才能开启例程对比。",routineSameNameMatchingOnly: "例程按同名(及签名)自动匹配。本版本暂不支持手动重命名映射。",sourceRoutines: "源对象",noRoutines: "未找到存储过程或函数",@@ -8709,6 +8717,25 @@ export default withEnglishFallback({selectRoutineToCompare: "选择一条存储过程以对比定义",routinesNotCompared: "未开启存储过程对比。请打开上方开关后重新比较。",routineDdlCopied: "已复制 DDL",+ routineNeedsValidation: "待校验",+ routineChecking: "正在校验…",+ routinePending: "原请求待核对",+ routineVerified: "已验证",+ routineUnverified: "未验证",+ routinePrepared: "待执行",+ routineDispatched: "已派发,未收到成功回执",+ routineValidate: "重新校验",+ routineObserve: "核对原请求",+ routineRecoveryPreview: "预览恢复脚本",+ routineRecoveryNote: "恢复脚本会执行新的 DDL,不是事务回滚。",+ routineReadOnlyCompleted: "已完成步骤不会重发。要修改该对象,请重新比较或预览恢复脚本。",+ routineStopped: "已停止发送后续步骤。已派发的请求不会因此取消。",+ routineHistory: "{count} 次操作记录",+ routineRefreshBaseline: "刷新基线,保留草稿",+ routineEqual: "相同",+ routineUnreadable: "读取未完成",+ routineConflict: "种类冲突",+ routineCallers: "受影响的调用方",copySourceDdl: "复制源 DDL",copyTargetDdl: "复制目标 DDL",autoMatchHint: "目标表按同名自动匹配。",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 8148e38e22..a07577c41d 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -4844,6 +4844,14 @@ export default withEnglishFallback({cancelEdit: "取消",sourceSaved: "原始碼已儲存",sourceSaveFailed: "儲存原始碼失敗:{message}",+ routineWritePending: "尚未確認原始請求已完成(作業 {operationId})。草稿已保留;再次儲存只會核對原始請求,不會重新送出。",+ routineWriteUnverified: "尚未驗證儲存成功(作業 {operationId})。草稿已保留,請依下方結果處理。",+ routineWriteDraftChanged: "已核對原始請求;目前草稿另有修改,請重新儲存。",+ routineSaveSingleDefinition: "儲存例程需要一份完整定義,請檢查目標與原始碼。",+ routineWriteAcknowledged: "DDL 已送出;以下是目標物件的讀回結果。",+ routineReadbackInvalid: "目標物件無效(INVALID)。請修正編譯錯誤後再儲存。",+ routineReadbackMissing: "未讀回目標物件。請檢查目標與權限後重新核對。",+ routineReadbackMismatch: "目標定義與核准的草稿不符。請核對目前定義,避免覆蓋其他修改。",postgresViewColumnChangeHint: "PostgreSQL 無法透過 CREATE OR REPLACE VIEW 刪除、重新排序、重新命名既有檢視欄位,或修改欄位型別。請保持原欄位的數量、順序、名稱和型別不變;新增欄位只能附加在末尾。重新命名欄位請使用 ALTER VIEW ... RENAME COLUMN;刪除欄位前請檢查相依性並手動重建檢視。",sourceReadOnly: "此原始碼為唯讀,不能編輯。",comment: "註解",@@ -6796,7 +6804,7 @@ export default withEnglishFallback({routineSelectionUnrestricted: "比較全部函數與預存程序。可指定物件來限定比較範圍。",routineSelectionTooLarge: "目前庫有 {count} 個例程(未指定時最多比較 {limit} 個)。請先指定要比較的預存程序/函數。",routineSelectionNeedSource: "請先選擇來源連線與資料庫,再指定要比較的預存程序或函數。",- routineSelectionUnsupported: "來源與目標需為同一受支援方言(MySQL、SQL Server 或 PostgreSQL 系),且能列出預存程序/函數原始碼,才能開啟例程對比。",+ routineSelectionUnsupported: "來源與目標需採用相容的受支援資料庫類型,且能讀取預存程序/函數原始碼,才能開啟例程比較。",routineSameNameMatchingOnly: "例程按同名(及簽章)自動匹配。本版本暫不支援手動重新命名對應。",sourceRoutines: "來源例程",noRoutines: "找不到例程",@@ -6818,6 +6826,25 @@ export default withEnglishFallback({selectRoutineToCompare: "選擇一條預存程序以對比定義",routinesNotCompared: "未開啟預存程序對比。請打開上方開關後重新比較。",routineDdlCopied: "已複製 DDL",+ routineNeedsValidation: "待驗證",+ routineChecking: "正在驗證……",+ routinePending: "原始請求待核對",+ routineVerified: "已驗證",+ routineUnverified: "未驗證",+ routinePrepared: "待執行",+ routineDispatched: "已送出,未收到成功回覆",+ routineValidate: "重新驗證",+ routineObserve: "核對原始請求",+ routineRecoveryPreview: "預覽復原指令碼",+ routineRecoveryNote: "復原指令碼會執行新的 DDL,並非交易回滾。",+ routineReadOnlyCompleted: "已完成的步驟不會重新送出。若要修改此物件,請重新比較或預覽復原指令碼。",+ routineStopped: "已停止送出後續步驟。已送出的請求不會因此取消。",+ routineHistory: "{count} 筆操作記錄",+ routineRefreshBaseline: "重新整理基線並保留草稿",+ routineEqual: "相同",+ routineUnreadable: "讀取未完成",+ routineConflict: "種類衝突",+ routineCallers: "受影響的呼叫方",autoMatchHint: "目標資料表會依相同名稱進行比對。",matchedTables: "已比對 {matched}/{total} 張資料表",missingTargetTables: "缺少同名的目標資料表:{tables}",diff --git a/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.ts b/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.tsindex 80507beb50..22b2f7afbe 100644--- a/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/databaseObjectCapabilities.spec.ts@@ -155,10 +155,10 @@ describe("databaseObjectCapabilities", () => {});it("opens schema diff routines only for same-dialect allowlisted databases", () => {- for (const dbType of ["postgres", "opengauss", "mysql", "sqlserver", "gaussdb", "kingbase"] as const) {+ for (const dbType of ["postgres", "opengauss", "mysql", "sqlserver", "gaussdb", "kingbase", "oracle", "oceanbase-oracle"] as const) {expect(supportsSchemaDiffRoutines(dbType), dbType).toBe(true);}- for (const dbType of ["oracle", "dameng", "hive", "sqlite", "doris", "databend", "manticoresearch"] as const) {+ for (const dbType of ["dameng", "hive", "sqlite", "doris", "databend", "manticoresearch"] as const) {expect(supportsSchemaDiffRoutines(dbType), dbType).toBe(false);}// Fallback ROUTINE_OBJECTS must not open schema-diff routine compare.@@ -166,7 +166,8 @@ describe("databaseObjectCapabilities", () => {expect(supportsSchemaDiffRoutines(undefined)).toBe(false);expect(schemaDiffRoutineObjectTypes("mysql")).toEqual(["PROCEDURE", "FUNCTION"]);expect(schemaDiffRoutineObjectTypes("sqlserver")).toEqual(["PROCEDURE", "FUNCTION"]);- expect(schemaDiffRoutineObjectTypes("oracle")).toEqual([]);+ expect(schemaDiffRoutineObjectTypes("oracle")).toEqual(["PROCEDURE", "FUNCTION"]);+ expect(schemaDiffRoutineObjectTypesIntersection("oracle", "oceanbase-oracle")).toEqual([]);expect(schemaDiffRoutineObjectTypesIntersection("mysql", "mysql")).toEqual(["PROCEDURE", "FUNCTION"]);expect(schemaDiffRoutineObjectTypesIntersection("mysql", "oracle")).toEqual([]);expect(schemaDiffRoutineObjectTypesIntersection("mysql", "sqlserver")).toEqual([]);diff --git a/apps/desktop/src/lib/__tests__/database/oracleRoutineCompare.spec.ts b/apps/desktop/src/lib/__tests__/database/oracleRoutineCompare.spec.tsnew file mode 100644index 0000000000..8b3b2a1d6e--- /dev/null+++ b/apps/desktop/src/lib/__tests__/database/oracleRoutineCompare.spec.ts@@ -0,0 +1,10 @@+import { describe, expect, it } from "vitest";+import { schemaDiffRoutineObjectTypes, schemaDiffRoutineObjectTypesIntersection, supportsSchemaDiffRoutines } from "@/lib/database/databaseObjectCapabilities";++describe("Oracle-family routine comparison workflow", () => {+ it.each(["oracle", "oceanbase-oracle"] as const)("offers standalone procedures and functions for a %s pair", (databaseType) => {+ expect(supportsSchemaDiffRoutines(databaseType)).toBe(true);+ expect(schemaDiffRoutineObjectTypes(databaseType)).toEqual(["PROCEDURE", "FUNCTION"]);+ expect(schemaDiffRoutineObjectTypesIntersection(databaseType, databaseType)).toEqual(["PROCEDURE", "FUNCTION"]);+ });+});diff --git a/apps/desktop/src/lib/__tests__/schema/oracleRoutineDeploy.spec.ts b/apps/desktop/src/lib/__tests__/schema/oracleRoutineDeploy.spec.tsnew file mode 100644index 0000000000..faa7ecd250--- /dev/null+++ b/apps/desktop/src/lib/__tests__/schema/oracleRoutineDeploy.spec.ts@@ -0,0 +1,423 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ createOracleRoutineDeployment,+ disposeOracleRoutineDeployment,+ editOracleRoutineDraft,+ executeOracleRoutineDeployment,+ observeOracleRoutineDeployment,+ prepareOracleRoutineRecovery,+ refreshOracleRoutineDeployment,+ selectOracleRoutineDraft,+ synchronizeOracleRoutineSelection,+ validateOracleRoutineDeployment,+} from "@/lib/schema/oracleRoutineDeploy";+import type { SchemaDiffObject } from "@/lib/schema/schemaDiff";+import type { OracleRoutineOperation, OracleRoutinePlan, OracleRoutineSnapshot } from "@/types/schemaDiff";++const calls = vi.hoisted(() => ({ prepare: vi.fn(), execute: vi.fn(), observe: vi.fn(), recovery: vi.fn(), load: vi.fn(), invalidate: vi.fn(), refs: vi.fn() }));+vi.mock("@/lib/backend/api", () => ({+ prepareOracleRoutinePlan: calls.prepare,+ executeOracleRoutineOperation: calls.execute,+ observeOracleRoutineOperation: calls.observe,+ prepareOracleRoutineRecovery: calls.recovery,+ loadSchemaDiffRoutines: calls.load,+ updateOracleRoutineOperationReferences: calls.refs,+}));+vi.mock("@/lib/metadata/objectDdlCache", () => ({ invalidateObjectDdlCache: calls.invalidate }));+vi.mock("@/lib/table/objectBrowserRowsCache", () => ({ invalidateObjectBrowserRowsCache: calls.invalidate }));++const endpoint = { connectionId: "target", database: "db", schema: "Target.With.Dot", databaseType: "oceanbase-oracle" as const, generation: 7 };+const snapshot: OracleRoutineSnapshot = { endpoint, state: "complete", enumerationComplete: true, objects: [], issues: [] };+function object(name: string): SchemaDiffObject {+ return { id: `func-${name}`, name, operationType: "create", objectKind: "function", routineType: "FUNCTION", selected: true };+}+function operation(name: string, id = `${name}-approved`): OracleRoutineOperation {+ return { operationId: id, target: endpoint, identity: { owner: endpoint.schema, name, kind: "FUNCTION" }, lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null, error: null };+}+function plan(...names: string[]): OracleRoutinePlan {+ return {+ target: endpoint,+ ready: true,+ steps: names.map((name) => ({+ identity: operation(name).identity,+ action: "create",+ sql: `CREATE FUNCTION "Target.With.Dot"."${name}" RETURN NUMBER AS BEGIN RETURN 1; END;`,+ sourceOriginal: `original ${name}`,+ targetOriginal: null,+ recoverySql: `DROP FUNCTION "Target.With.Dot"."${name}";`,+ recoveryComplete: true,+ references: [],+ incomingCallers: [],+ issues: [],+ operation: operation(name),+ })),+ };+}+function finished(name: string, state: "verified" | "invalid" = "verified"): OracleRoutineOperation {+ return {+ ...operation(name),+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ readback: { identity: operation(name).identity, state, exists: true, version: null, source: "recorded full source", definitionMatches: true, compilerMessages: state === "invalid" ? [{ attribute: "ERROR", line: 2, position: 3, text: "missing identifier" }] : [], issues: [] },+ };+}+function state(...names: string[]) {+ const state = createOracleRoutineDeployment({ ...snapshot, endpoint: { ...endpoint, connectionId: "source", schema: "Source" } }, snapshot);+ synchronizeOracleRoutineSelection(state, names.map(object));+ return state;+}+const authorize = async (_: string, run: () => Promise<void>) => run();++beforeEach(() => {+ vi.clearAllMocks();+ calls.invalidate.mockResolvedValue(undefined);+ calls.refs.mockResolvedValue(undefined);+ calls.observe.mockImplementation(async (id: string) => ({ operation: operation(id.replace(/-approved$/, ""), id), lifecycle: "prepared", error: null }));+});++describe("Oracle routine deployment in the existing comparison session", () => {+ it("preserves the existing approved plan when revalidation is rejected by capacity admission", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValueOnce(plan("F"));+ await validateOracleRoutineDeployment(session);+ const approved = session.plan;+ calls.prepare.mockRejectedValueOnce(new Error("Routine operation registry capacity exceeded"));+ await validateOracleRoutineDeployment(session);+ expect(session.plan).toBe(approved);+ expect(session.plan?.ready).toBe(true);+ expect(session.drafts[0].operation?.operationId).toBe("F-approved");+ expect(calls.refs).not.toHaveBeenCalledWith([], ["F-approved"]);+ });+ it("keeps approval ownership across a stopped view, releasing only when the session is removed", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValue(plan("F"));+ await validateOracleRoutineDeployment(session);+ expect(calls.refs).toHaveBeenCalledWith(["F-approved"], []);+ session.stopRequested = true;+ expect(calls.refs).not.toHaveBeenCalledWith([], ["F-approved"]);+ await disposeOracleRoutineDeployment(session);+ expect(calls.refs).toHaveBeenLastCalledWith([], ["F-approved"]);+ expect(session.retainedOperationIds).toEqual([]);+ await executeOracleRoutineDeployment(session, authorize);+ expect(calls.execute).not.toHaveBeenCalled();+ });++ it("releases a late plan instead of reviving a removed session", async () => {+ const session = state("F");+ let resolve!: (plan: OracleRoutinePlan) => void;+ calls.prepare.mockReturnValue(+ new Promise<OracleRoutinePlan>((done) => {+ resolve = done;+ }),+ );+ const pending = validateOracleRoutineDeployment(session);+ await vi.waitFor(() => expect(calls.prepare).toHaveBeenCalled());+ await disposeOracleRoutineDeployment(session);+ resolve(plan("F"));+ await pending;+ expect(session.plan).toBeNull();+ expect(session.retainedOperationIds).toEqual([]);+ expect(calls.refs).toHaveBeenLastCalledWith([], ["F-approved"]);+ });++ it("reclaims superseded unsubmitted approvals after the replacement has been retained", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValueOnce(plan("F"));+ await validateOracleRoutineDeployment(session);+ editOracleRoutineDraft(session, "func-F", "changed draft");+ const replacement = plan("F");+ replacement.steps[0].operation = operation("F", "replacement");+ calls.prepare.mockResolvedValueOnce(replacement);+ await validateOracleRoutineDeployment(session);+ expect(session.records.map((record) => record.operationId)).toEqual(["replacement"]);+ expect(session.retainedOperationIds).toEqual(["replacement"]);+ expect(calls.refs.mock.calls.slice(-2)).toEqual([+ [["replacement"], []],+ [[], ["F-approved"]],+ ]);+ });++ it("does not forget a submitted execute temporarily observed as Prepared during edit and refresh", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValue(plan("F"));+ await validateOracleRoutineDeployment(session);+ calls.execute.mockRejectedValue(new Error("response lost before arrival is known"));+ await executeOracleRoutineDeployment(session, authorize);+ expect(session.attemptedOperationIds).toEqual(["F-approved"]);+ editOracleRoutineDraft(session, "func-F", "new draft");+ calls.load.mockImplementation(async (id: string) => (id === "source" ? session.source : session.target));+ await refreshOracleRoutineDeployment(session);+ calls.prepare.mockRejectedValue(new Error("capacity exceeded"));+ await validateOracleRoutineDeployment(session);+ expect(session.retainedOperationIds).toContain("F-approved");+ expect(session.records.some((record) => record.operationId === "F-approved")).toBe(true);+ expect(calls.prepare.mock.calls.at(-1)![0].drafts[0].supersedesOperationId).toBe("F-approved");+ expect(calls.refs).not.toHaveBeenCalledWith([], ["F-approved"]);+ expect(calls.execute).toHaveBeenCalledTimes(1);+ });++ it("retains raw snapshots and drafts while final validation replaces only the approved plan", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValue(plan("F"));+ await validateOracleRoutineDeployment(session);+ const original = session.source;+ editOracleRoutineDraft(session, "func-F", "manual final definition");+ expect(session.plan).toBeNull();+ expect(session.source).toBe(original);+ await validateOracleRoutineDeployment(session);+ expect(calls.prepare.mock.calls[1][0].drafts[0]).toMatchObject({ sql: "manual final definition", supersedesOperationId: "F-approved" });+ });++ it("ignores a late validation after an edit without replacing the newer draft", async () => {+ const session = state("F");+ let resolve!: (value: OracleRoutinePlan) => void;+ calls.prepare.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const pending = validateOracleRoutineDeployment(session);+ editOracleRoutineDraft(session, "func-F", "newer final text");+ resolve(plan("F"));+ await pending;+ expect(session.plan).toBeNull();+ expect(session.drafts[0].sql).toBe("newer final text");+ });++ it("keeps object issues and corrected text available instead of discarding the entire preview", async () => {+ const session = state("F", "G");+ const response = plan("F", "G");+ response.ready = false;+ response.steps[0].issues = [{ code: "unresolved-reference", message: "qualify the reference", line: 4, column: 9 }];+ calls.prepare.mockResolvedValue(response);+ await validateOracleRoutineDeployment(session);+ expect(session.plan?.steps[0].issues[0]).toMatchObject({ line: 4, column: 9 });+ expect(session.drafts[1].sql).toContain('"G"');+ await executeOracleRoutineDeployment(session, authorize);+ expect(calls.execute).not.toHaveBeenCalled();+ });++ it("canceling production confirmation retains approval and drafts without dispatch", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValue(plan("F"));+ await validateOracleRoutineDeployment(session);+ const text = session.drafts[0].sql;+ await executeOracleRoutineDeployment(session, async () => undefined);+ expect(calls.execute).not.toHaveBeenCalled();+ expect(session.plan?.ready).toBe(true);+ expect(session.drafts[0].sql).toBe(text);+ });++ it("stops at the first INVALID result, retains the first success and only corrects the failed/remaining steps", async () => {+ const session = state("F", "G", "H");+ calls.prepare.mockResolvedValue(plan("F", "G", "H"));+ await validateOracleRoutineDeployment(session);+ calls.execute.mockResolvedValueOnce(finished("F")).mockResolvedValueOnce(finished("G", "invalid"));+ await executeOracleRoutineDeployment(session, authorize);+ expect(calls.execute.mock.calls.map((call) => call[0])).toEqual(["F-approved", "G-approved"]);+ expect(session.records.find((record) => record.operationId === "F-approved")?.readback?.state).toBe("verified");+ expect(session.plan?.ready).toBe(false);+ editOracleRoutineDraft(session, "func-G", "corrected G definition");+ calls.observe.mockImplementation(async (id: string) => ({ operation: id === "G-approved" ? finished("G", "invalid") : operation("H"), lifecycle: id === "G-approved" ? "terminal" : "prepared", error: null }));+ calls.prepare.mockResolvedValue(plan("G", "H"));+ await validateOracleRoutineDeployment(session);+ const input = calls.prepare.mock.calls.at(-1)![0];+ expect(input.drafts.map((draft: { identity: { name: string } }) => draft.identity.name)).toEqual(["G", "H"]);+ expect(input.drafts[0]).toMatchObject({ action: "replace", baselineOperationId: "G-approved", sql: "corrected G definition" });+ expect(input.drafts[1]).toMatchObject({ supersedesOperationId: "H-approved" });+ });++ it("closing during the current write only prevents the next step and keeps the late result on its original session", async () => {+ const original = state("F", "G");+ calls.prepare.mockResolvedValue(plan("F", "G"));+ await validateOracleRoutineDeployment(original);+ let resolve!: (value: OracleRoutineOperation) => void;+ calls.execute.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const pending = executeOracleRoutineDeployment(original, authorize);+ original.stopRequested = true;+ const other = state("Other");+ resolve(finished("F"));+ await pending;+ expect(calls.execute).toHaveBeenCalledTimes(1);+ expect(original.records.some((record) => record.readback?.state === "verified")).toBe(true);+ expect(other.records).toEqual([]);+ await executeOracleRoutineDeployment(original, authorize);+ expect(calls.execute).toHaveBeenCalledTimes(1);+ });++ it("duplicate clicks cannot dispatch a second request while the first is waiting", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValue(plan("F"));+ await validateOracleRoutineDeployment(session);+ let resolve!: (value: OracleRoutineOperation) => void;+ calls.execute.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ const first = executeOracleRoutineDeployment(session, authorize);+ await executeOracleRoutineDeployment(session, authorize);+ expect(calls.execute).toHaveBeenCalledTimes(1);+ resolve(finished("F"));+ await first;+ });++ it("a lost execute response retains its original ID and unknown only offers read-only observation", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValue(plan("F"));+ await validateOracleRoutineDeployment(session);+ calls.execute.mockRejectedValue(new Error("transport ended"));+ calls.observe.mockResolvedValue({ operation: { ...operation("F"), lifecycle: "unproven", dispatched: true }, lifecycle: "unproven", error: null });+ await executeOracleRoutineDeployment(session, authorize);+ await validateOracleRoutineDeployment(session);+ expect(calls.prepare).toHaveBeenCalledTimes(1);+ expect(calls.execute).toHaveBeenCalledTimes(1);+ expect(session.error).toContain("F-approved");+ await observeOracleRoutineDeployment(session, "F-approved");+ expect(calls.observe).toHaveBeenLastCalledWith("F-approved", true);+ expect(calls.execute).toHaveBeenCalledTimes(1);+ });++ it("a missing Core record cannot be treated as permission to prepare a new operation", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValue(plan("F"));+ await validateOracleRoutineDeployment(session);+ calls.execute.mockRejectedValue(new Error("lost"));+ calls.observe.mockResolvedValue({ operation: null, lifecycle: "unproven", error: "original record unavailable" });+ await executeOracleRoutineDeployment(session, authorize);+ await validateOracleRoutineDeployment(session);+ expect(calls.prepare).toHaveBeenCalledTimes(1);+ expect(session.error).toContain("original record unavailable");+ });++ it("selection changes retain manual drafts and completed history instead of rebuilding from raw source", () => {+ const session = state("F");+ editOracleRoutineDraft(session, "func-F", "manual F");+ synchronizeOracleRoutineSelection(session, [{ ...object("F"), selected: false }]);+ synchronizeOracleRoutineSelection(session, [object("F")]);+ expect(session.drafts).toHaveLength(1);+ expect(session.drafts[0].sql).toBe("manual F");+ });++ it("recovery preserves copyable SQL and blocks incomplete restoration instead of dispatching it", async () => {+ const session = state("F");+ const response = plan("F");+ response.ready = false;+ response.steps[0].recoveryComplete = false;+ response.steps[0].issues = [{ code: "plan-preflight", message: "deleted grants were not captured", line: 1, column: 1 }];+ calls.recovery.mockResolvedValue(response);+ await prepareOracleRoutineRecovery(session, "F-original");+ expect(calls.recovery).toHaveBeenCalledWith("F-original");+ expect(session.recoveryPlan?.steps[0].sql).toContain("CREATE FUNCTION");+ await executeOracleRoutineDeployment(session, authorize);+ expect(calls.execute).not.toHaveBeenCalled();+ });++ it("rejects a validation response bound to another target", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValue({ ...plan("F"), target: { ...endpoint, schema: "Other" } });+ await validateOracleRoutineDeployment(session);+ expect(session.plan).toBeNull();+ expect(session.error).toContain("another comparison target");+ });++ it("explicit baseline refresh retains manual text and history while adopting freshly read target existence", async () => {+ const session = state("F");+ editOracleRoutineDraft(session, "func-F", "manual corrected text");+ session.drafts[0].operation = finished("F", "invalid");+ session.records.push(finished("F", "invalid"));+ calls.observe.mockResolvedValue({ operation: finished("F", "invalid"), lifecycle: "terminal", error: null });+ calls.load.mockImplementation(async (connectionId: string) =>+ connectionId === "source" ? session.source : { ...snapshot, objects: [{ version: { identity: operation("F").identity, objectId: "1", status: "INVALID", lastDdlTime: "now" }, source: "current target source", sourceComplete: true, dependencies: [], dependenciesComplete: true, issues: [] }] },+ );+ await refreshOracleRoutineDeployment(session);+ expect(session.drafts[0]).toMatchObject({ sql: "manual corrected text", action: "replace" });+ expect(session.drafts[0].operation).toBeUndefined();+ expect(session.records).toHaveLength(1);+ expect(session.target.objects).toHaveLength(1);+ expect(calls.load).toHaveBeenCalledWith("source", session.source.endpoint.database, session.source.endpoint.schema, ["F"]);+ expect(calls.load).toHaveBeenCalledWith(snapshot.endpoint.connectionId, snapshot.endpoint.database, snapshot.endpoint.schema, ["F"]);+ });++ it("refresh verifies an acknowledged deletion by its original ID and resumes only unfinished steps", async () => {+ const session = state("F", "G");+ session.drafts[0].action = "delete";+ const approved = plan("F", "G");+ approved.steps[0].action = "delete";+ approved.steps[0].sql = 'DROP FUNCTION "Target.With.Dot"."F";';+ calls.prepare.mockResolvedValueOnce(approved).mockResolvedValueOnce(plan("G"));+ await validateOracleRoutineDeployment(session);+ const failedReadback = { ...finished("F"), readback: null, error: "Readback unavailable" };+ calls.execute.mockResolvedValueOnce(failedReadback).mockResolvedValueOnce(finished("G"));+ await executeOracleRoutineDeployment(session, authorize);+ const absent = finished("F");+ absent.readback = { ...absent.readback!, exists: false, source: null };+ calls.observe.mockImplementation(async (id: string, refresh: boolean) => ({ operation: id === "G-approved" ? operation("G") : refresh ? absent : failedReadback, lifecycle: id === "G-approved" ? "prepared" : "terminal", error: null }));+ calls.load.mockImplementation(async (id: string) => (id === "source" ? session.source : snapshot));+ await refreshOracleRoutineDeployment(session);+ expect(calls.observe).toHaveBeenCalledWith("F-approved", true);+ expect(session.drafts[0].operation).toMatchObject({ operationId: "F-approved", readback: { state: "verified", exists: false } });+ await validateOracleRoutineDeployment(session);+ expect(calls.prepare.mock.calls.at(-1)![0].drafts.map((draft: { identity: { name: string } }) => draft.identity.name)).toEqual(["G"]);+ await executeOracleRoutineDeployment(session, authorize);+ expect(calls.execute.mock.calls.map((call) => call[0])).toEqual(["F-approved", "G-approved"]);+ expect(session.records.find((record) => record.operationId === "F-approved")?.readback?.exists).toBe(false);+ });++ it.each(["unacknowledged", "readback-failed", "still-exists"] as const)("refresh retains the original deletion when completion is not proven (%s)", async (scenario) => {+ const session = state("F");+ session.drafts[0].action = "delete";+ const record = finished("F");+ if (scenario === "unacknowledged") {+ record.acknowledged = false;+ record.readback = { ...record.readback!, exists: false, source: null };+ } else if (scenario === "readback-failed") record.readback = null;+ else record.readback!.state = "invalid";+ session.drafts[0].operation = record;+ calls.observe.mockResolvedValue({ operation: record, lifecycle: "terminal", error: null });+ calls.load.mockImplementation(async (id: string) => (id === "source" ? session.source : snapshot));+ await refreshOracleRoutineDeployment(session);+ expect(session.drafts[0].operation).toEqual(record);+ calls.prepare.mockResolvedValue({ ...plan("F"), ready: false });+ await validateOracleRoutineDeployment(session);+ expect(calls.prepare.mock.calls.at(-1)![0].drafts).toHaveLength(1);+ expect(calls.prepare.mock.calls.at(-1)![0].drafts[0]).toMatchObject({ action: "delete", baselineOperationId: "F-approved" });+ expect(calls.execute).not.toHaveBeenCalled();+ });++ it("selects the recovery's own object and leaves recovery preview when another draft is selected", async () => {+ const session = state("F", "G");+ calls.recovery.mockResolvedValue(plan("G"));+ await prepareOracleRoutineRecovery(session, "G-original");+ expect(session.selectedObjectId).toBe("func-G");+ selectOracleRoutineDraft(session, "func-F");+ expect(session.recoveryPlan).toBeNull();+ expect(session.selectedObjectId).toBe("func-F");+ await executeOracleRoutineDeployment(session, authorize);+ expect(calls.execute).not.toHaveBeenCalled();+ });++ it("keeps a recovery's visible identity fixed during its confirmation and write", async () => {+ const session = state("F", "G");+ session.recoveryPlan = plan("F");+ session.executing = true;+ selectOracleRoutineDraft(session, "func-G");+ expect(session.selectedObjectId).toBe("func-F");+ expect(session.recoveryPlan).not.toBeNull();+ });++ it("baseline refresh cannot erase an unresolved operation to obtain a new write ID", async () => {+ const session = state("F");+ session.drafts[0].operation = { ...operation("F"), lifecycle: "unproven" };+ calls.observe.mockResolvedValue({ operation: session.drafts[0].operation, lifecycle: "unproven", error: null });+ await refreshOracleRoutineDeployment(session);+ expect(calls.load).not.toHaveBeenCalled();+ expect(session.error).toContain("termination");+ expect(session.drafts[0].operation.operationId).toBe("F-approved");+ });+});diff --git a/apps/desktop/src/lib/__tests__/schema/schemaDiffSelection.spec.ts b/apps/desktop/src/lib/__tests__/schema/schemaDiffSelection.spec.tsindex 26de04618a..d4be72546e 100644--- a/apps/desktop/src/lib/__tests__/schema/schemaDiffSelection.spec.ts+++ b/apps/desktop/src/lib/__tests__/schema/schemaDiffSelection.spec.ts@@ -50,6 +50,27 @@ function createDuplicateForeignKeyPreparation(): SchemaDiffPreparation {}describe("schema diff SQL selection projections", () => {+ it("retains equal and unreadable Oracle originals without selecting executable steps", () => {+ const functionDiffs = (["equal", "unreadable", "conflict"] as const).map((type) => ({+ type,+ name: `${type}.Proc`,+ source: { name: `${type}.Proc`, function_type: "PROCEDURE", data_type: "", arguments: "", definition: "retained source" },+ target: { name: `${type}.Proc`, function_type: "PROCEDURE", data_type: "", arguments: "", definition: "retained target" },+ changes: type === "equal" ? [] : ["read or kind issue"],+ }));+ const result: SchemaDiffPreparation = { diffs: [], functionDiffs, syncSql: "" };+ const objects = convertToSchemaDiffObjects([], functionDiffs);+ expect(objects.map((object) => [object.operationType, object.selected, object.routineType])).toEqual([+ ["none", false, "PROCEDURE"],+ ["none", false, "PROCEDURE"],+ ["none", false, "PROCEDURE"],+ ]);+ expect(objects[1]!.sourceDdl).toBe("retained source");+ expect(objects[1]!.targetDdl).toBe("retained target");+ objects.forEach((object) => setSchemaDiffObjectSelected(objects, object.id, true));+ expect(selectSchemaDiffInput(result, objects).functionDiffs).toEqual([]);+ });+it("keeps every composite foreign key column in the selection dependency closure", () => {const result = createPreparation();result.diffs[0]!.foreignKeys = [diff --git a/apps/desktop/src/lib/__tests__/table/objectSourceTabSave.spec.ts b/apps/desktop/src/lib/__tests__/table/objectSourceTabSave.spec.tsnew file mode 100644index 0000000000..f8a53839cb--- /dev/null+++ b/apps/desktop/src/lib/__tests__/table/objectSourceTabSave.spec.ts@@ -0,0 +1,144 @@+import { createPinia, setActivePinia } from "pinia";+import { beforeEach, describe, expect, it, vi } from "vitest";+import * as api from "@/lib/backend/api";+import { saveObjectSourceTab } from "@/lib/table/objectSourceTabSave";+import { useConnectionStore } from "@/stores/connectionStore";+import { useProductionSafetyStore } from "@/stores/productionSafetyStore";+import { useQueryStore } from "@/stores/queryStore";+import type { ConnectionConfig } from "@/types/database";+import type { OracleRoutineOperation, OracleRoutineSaveInput } from "@/types/schemaDiff";++vi.mock("@/i18n", () => ({ default: { global: { t: (key: string) => key, locale: { value: "en-US" } } } }));+vi.mock("@/lib/backend/api", () => ({+ buildExecutableObjectSourceStatements: vi.fn(),+ prepareOracleRoutineSave: vi.fn(),+ updateOracleRoutineOperationReferences: vi.fn(async () => {}),+ executeOracleRoutineOperation: vi.fn(),+ observeOracleRoutineOperation: vi.fn(),+ executeQuery: vi.fn(),+ saveOpenTabsState: vi.fn(async () => {}),+}));++function operation(input: OracleRoutineSaveInput): OracleRoutineOperation {+ return {+ operationId: `approval-${input.identity.name}`,+ target: { connectionId: input.connectionId, database: input.database, schema: input.identity.owner, databaseType: "oceanbase-oracle", generation: 0 },+ identity: input.identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ readback: { identity: input.identity, state: "verified", exists: true, source: input.sql, version: null, definitionMatches: true, compilerMessages: [], issues: [] },+ error: null,+ };+}++function openDraft(name: string) {+ const connection = { id: `source-tab-${name}`, name: "Routine target", db_type: "oceanbase-oracle", is_production: true } as ConnectionConfig;+ useConnectionStore().connections.push(connection);+ const queryStore = useQueryStore();+ const original = `CREATE OR REPLACE FUNCTION "APP"."${name}" RETURN NUMBER AS BEGIN RETURN 1; END;`;+ const sql = original.replace("RETURN 1", "RETURN 2");+ const id = queryStore.openObjectSourceTab({ connectionId: connection.id, database: "ORCL", schema: "APP", title: name, sql: original, objectSource: { name, schema: "APP", objectType: "FUNCTION" } });+ queryStore.updateSql(id, sql);+ const tab = queryStore.tabs.find((tab) => tab.id === id)!;+ const toast = vi.fn();+ const t = (key: string, values?: Record<string, unknown>) => `${key}${values ? `:${values.message}` : ""}`;+ return { connection, queryStore, tab, sql, original, toast, save: () => saveObjectSourceTab(tab, { connection, queryStore, t, toast }) };+}++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal("localStorage", { getItem: vi.fn(() => null), setItem: vi.fn(), removeItem: vi.fn() });+ setActivePinia(createPinia());+ vi.mocked(api.buildExecutableObjectSourceStatements).mockImplementation(async ({ source }) => [source]);+ vi.mocked(api.prepareOracleRoutineSave).mockImplementation(async (input) => ({ ...operation(input), lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null }));+ vi.mocked(api.executeOracleRoutineOperation).mockImplementation(async () => operation(vi.mocked(api.prepareOracleRoutineSave).mock.calls.at(-1)![0]));+});++describe("App object source tab Save handler", () => {+ it("waits for real production confirmation, then saves exactly the approved ID and SQL and marks the draft clean", async () => {+ const draft = openDraft("Confirmed");+ const pending = draft.save();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending).toMatchObject({ connectionName: draft.connection.name, database: "ORCL", sql: draft.sql, source: "production.sourceObjectSource" }));+ expect(api.prepareOracleRoutineSave).toHaveBeenCalledExactlyOnceWith({ connectionId: draft.connection.id, database: "ORCL", identity: { owner: "APP", name: "Confirmed", kind: "FUNCTION" }, sql: draft.sql });+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ expect(draft.queryStore.isTabDirty(draft.tab)).toBe(true);+ safety.confirm();+ await expect(pending).resolves.toBe(true);+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledExactlyOnceWith("approval-Confirmed", draft.sql);+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(draft.queryStore.isTabDirty(draft.tab)).toBe(false);+ expect(draft.toast).toHaveBeenCalledWith("objects.sourceSaved", 2000);+ });++ it("cancel preserves the actual dirty tab and dispatches nothing", async () => {+ const draft = openDraft("Canceled");+ const pending = draft.save();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending).toBeDefined());+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ safety.cancel();+ await expect(pending).resolves.toBe(false);+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(draft.tab.sql).toBe(draft.sql);+ expect(draft.tab.originalSql).toBe(draft.original);+ expect(draft.queryStore.isTabDirty(draft.tab)).toBe(true);+ expect(draft.toast).not.toHaveBeenCalled();+ });++ it("a target switch during confirmation prevents dispatch", async () => {+ const draft = openDraft("Retargeted");+ const pending = draft.save();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending).toBeDefined());+ draft.queryStore.updateDatabase(draft.tab.id, "OTHER");+ safety.confirm();+ await expect(pending).resolves.toBe(false);+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ expect(draft.queryStore.isTabDirty(draft.tab)).toBe(true);+ });++ it("does not mark a newer draft clean when the approved original finishes", async () => {+ const draft = openDraft("EditedWhileConfirming");+ const pending = draft.save();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending).toBeDefined());+ const newer = draft.sql.replace("RETURN 2", "RETURN 3");+ draft.queryStore.updateSql(draft.tab.id, newer);+ safety.confirm();+ await expect(pending).resolves.toBe(true);+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledExactlyOnceWith("approval-EditedWhileConfirming", draft.sql);+ expect(draft.tab.sql).toBe(newer);+ expect(draft.tab.originalSql).toBe(draft.original);+ expect(draft.queryStore.isTabDirty(draft.tab)).toBe(true);+ });++ it("INVALID readback retains the actual dirty tab and compiler location", async () => {+ const draft = openDraft("InvalidReadback");+ vi.mocked(api.executeOracleRoutineOperation).mockImplementationOnce(async () => {+ const result = operation(vi.mocked(api.prepareOracleRoutineSave).mock.calls.at(-1)![0]);+ result.readback!.state = "invalid";+ result.readback!.compilerMessages = [{ attribute: "ERROR", line: 3, position: 12, text: "missing identifier" }];+ return result;+ });+ const pending = draft.save();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending).toBeDefined());+ safety.confirm();+ await expect(pending).resolves.toBe(false);+ expect(draft.tab.sql).toBe(draft.sql);+ expect(draft.queryStore.isTabDirty(draft.tab)).toBe(true);+ expect(draft.toast).toHaveBeenCalledWith(expect.stringContaining("ERROR 3:12 missing identifier"), 5000);+ expect(draft.toast).not.toHaveBeenCalledWith("objects.sourceSaved", 2000);+ });++ it("preserves backend object-message errors", async () => {+ const draft = openDraft("BackendMessage");+ vi.mocked(api.buildExecutableObjectSourceStatements).mockRejectedValueOnce({ message: "Source validation failed" });+ await expect(draft.save()).resolves.toBe(false);+ expect(draft.toast).toHaveBeenCalledWith("objects.sourceSaveFailed:Source validation failed", 5000);+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/lib/__tests__/table/oracleRoutineWrite.spec.ts b/apps/desktop/src/lib/__tests__/table/oracleRoutineWrite.spec.tsnew file mode 100644index 0000000000..db6f5eb1c4--- /dev/null+++ b/apps/desktop/src/lib/__tests__/table/oracleRoutineWrite.spec.ts@@ -0,0 +1,166 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { createPinia, setActivePinia } from "pinia";+import type { OracleRoutineOperation, OracleRoutineSaveInput } from "@/types/schemaDiff";+import type { ConnectionConfig } from "@/types/database";+import * as api from "@/lib/backend/api";++vi.mock("@/i18n", () => ({ default: { global: { t: (key: string, values?: Record<string, unknown>) => `${key} ${values?.operationId ?? ""}` } } }));+vi.mock("@/lib/backend/api", () => ({ prepareOracleRoutineSave: vi.fn(), updateOracleRoutineOperationReferences: vi.fn(async () => {}), executeOracleRoutineOperation: vi.fn(), observeOracleRoutineOperation: vi.fn(), executeQuery: vi.fn(), executeScript: vi.fn(), executeInTransaction: vi.fn() }));++const input = (): OracleRoutineSaveInput => ({ connectionId: "target", database: "tenant", identity: { owner: "Owner.Mixed", name: "Mixed.Func", kind: "FUNCTION" }, sql: 'CREATE OR REPLACE FUNCTION "Owner.Mixed"."Mixed.Func" RETURN NUMBER AS BEGIN RETURN 1; END;' });+const record = (changes: Partial<OracleRoutineOperation> = {}): OracleRoutineOperation => ({+ operationId: "original-operation",+ target: { connectionId: "target", database: "tenant", schema: "Owner.Mixed", databaseType: "oceanbase-oracle", generation: 2 },+ identity: input().identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ readback: { identity: input().identity, state: "verified", exists: true, version: null, source: input().sql, definitionMatches: true, compilerMessages: [], issues: [] },+ error: null,+ ...changes,+});++beforeEach(() => {+ vi.resetModules();+ vi.resetAllMocks();+ vi.mocked(api.prepareOracleRoutineSave).mockResolvedValue(record({ lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null }));+ vi.mocked(api.executeOracleRoutineOperation).mockResolvedValue(record());+});++describe("Oracle routine source save", () => {+ it("prepares before the real production confirmation and dispatches only the exact approved SQL", async () => {+ const { prepareObjectSourceSave } = await import("@/lib/table/objectSourceEditor");+ const { executeWithProductionSqlGuard } = await import("@/lib/database/productionExecutionGuard");+ const { useProductionSafetyStore } = await import("@/stores/productionSafetyStore");+ setActivePinia(createPinia());+ const source = input();+ const execute = await prepareObjectSourceSave(source.connectionId, source.database, "oceanbase-oracle", [source.sql], source.identity.owner, { objectType: source.identity.kind, name: source.identity.name });+ expect(api.prepareOracleRoutineSave).toHaveBeenCalledWith(source);+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ const pending = executeWithProductionSqlGuard({ connection: { id: source.connectionId, name: "target", db_type: "oceanbase-oracle", is_production: true } as ConnectionConfig, database: source.database, sql: source.sql, source: "Object source", execute });+ await vi.waitFor(() => expect(useProductionSafetyStore().pending).toMatchObject({ sql: source.sql, database: source.database, source: "Object source" }));+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ useProductionSafetyStore().confirm();+ await expect(pending).resolves.toMatchObject({ operationId: "original-operation", lifecycle: "terminal" });+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledExactlyOnceWith("original-operation", source.sql);+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it("canceling the real production confirmation leaves the prepared save undispatched", async () => {+ const { prepareObjectSourceSave } = await import("@/lib/table/objectSourceEditor");+ const { executeWithProductionSqlGuard } = await import("@/lib/database/productionExecutionGuard");+ const { useProductionSafetyStore } = await import("@/stores/productionSafetyStore");+ setActivePinia(createPinia());+ const source = input();+ const execute = await prepareObjectSourceSave(source.connectionId, source.database, "oceanbase-oracle", [source.sql], source.identity.owner, { objectType: source.identity.kind, name: source.identity.name });+ const pending = executeWithProductionSqlGuard({ connection: { id: source.connectionId, name: "target", db_type: "oceanbase-oracle", is_production: true } as ConnectionConfig, database: source.database, sql: source.sql, source: "Object source", execute });+ await vi.waitFor(() => expect(useProductionSafetyStore().pending).toBeDefined());+ useProductionSafetyStore().cancel();+ await expect(pending).resolves.toBeUndefined();+ await execute.dispose?.();+ expect(api.updateOracleRoutineOperationReferences).toHaveBeenCalledWith(["original-operation"], []);+ expect(api.updateOracleRoutineOperationReferences).toHaveBeenLastCalledWith([], ["original-operation"]);+ expect(api.prepareOracleRoutineSave).toHaveBeenCalledExactlyOnceWith(source);+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it("rejects acknowledged INVALID without reporting a successful save", async () => {+ const { prepareOracleRoutineSourceSave } = await import("@/lib/table/oracleRoutineWrite");+ const operation = record();+ operation.readback!.state = "invalid";+ operation.readback!.compilerMessages = [{ attribute: "ERROR", line: 3, position: 12, text: "missing identifier" }];+ vi.mocked(api.executeOracleRoutineOperation).mockResolvedValue(operation);+ const execute = await prepareOracleRoutineSourceSave(input());+ await expect(execute()).rejects.toMatchObject({ operation, operationId: "original-operation", message: expect.stringContaining("ERROR 3:12 missing identifier") });+ });++ it("retains the original ID after a lost wait and does not dispatch a newer draft", async () => {+ const { prepareOracleRoutineSourceSave } = await import("@/lib/table/oracleRoutineWrite");+ vi.mocked(api.executeOracleRoutineOperation).mockRejectedValue(new Error("HTTP wait ended"));+ const unresolved = record({ lifecycle: "unproven", acknowledged: false });+ vi.mocked(api.observeOracleRoutineOperation).mockResolvedValue({ operation: unresolved, lifecycle: "unproven", error: null });+ const first = await prepareOracleRoutineSourceSave(input());+ await expect(first()).rejects.toMatchObject({ operationId: "original-operation" });+ await first.dispose?.();+ expect(api.updateOracleRoutineOperationReferences).not.toHaveBeenCalledWith([], ["original-operation"]);+ const edited = { ...input(), sql: input().sql.replace("RETURN 1", "RETURN 2") };+ await expect((await prepareOracleRoutineSourceSave(edited))()).rejects.toMatchObject({ operationId: "original-operation" });+ expect(api.prepareOracleRoutineSave).toHaveBeenCalledTimes(1);+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledTimes(1);+ expect(api.observeOracleRoutineOperation).toHaveBeenLastCalledWith("original-operation", true);+ // Matching readback is already present above, but cannot prove termination.+ vi.mocked(api.observeOracleRoutineOperation).mockResolvedValue({ operation: record(), lifecycle: "terminal", error: null });+ await expect((await prepareOracleRoutineSourceSave(edited))()).rejects.toThrow("objects.routineWriteDraftChanged");+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledTimes(1);+ });++ it("a missing backend record remains unproven rather than creating a replacement ID", async () => {+ const { prepareOracleRoutineSourceSave } = await import("@/lib/table/oracleRoutineWrite");+ vi.mocked(api.executeOracleRoutineOperation).mockRejectedValue(new Error("disconnected"));+ vi.mocked(api.observeOracleRoutineOperation).mockResolvedValue({ operation: null, lifecycle: "unproven", error: "record unavailable" });+ await expect((await prepareOracleRoutineSourceSave(input()))()).rejects.toMatchObject({ operationId: "original-operation" });+ await expect((await prepareOracleRoutineSourceSave(input()))()).rejects.toMatchObject({ operationId: "original-operation", operation: null });+ expect(api.prepareOracleRoutineSave).toHaveBeenCalledTimes(1);+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledTimes(1);+ });++ it("a second concurrently prepared editor cannot replace the pending ID", async () => {+ const { prepareOracleRoutineSourceSave } = await import("@/lib/table/oracleRoutineWrite");+ const first = await prepareOracleRoutineSourceSave(input());+ vi.mocked(api.prepareOracleRoutineSave).mockResolvedValue(record({ operationId: "second-operation", lifecycle: "prepared" }));+ const second = await prepareOracleRoutineSourceSave(input());+ vi.mocked(api.executeOracleRoutineOperation).mockResolvedValue(record({ lifecycle: "running", acknowledged: false, readback: null }));+ await expect(first()).rejects.toMatchObject({ operationId: "original-operation" });+ await expect(second()).rejects.toMatchObject({ operationId: "original-operation" });+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledTimes(1);+ });++ it("verification requires terminal lifecycle, write acknowledgement, and full readback", async () => {+ const { oracleRoutineOperationVerified } = await import("@/lib/table/oracleRoutineWrite");+ expect(oracleRoutineOperationVerified(record())).toBe(true);+ for (const changes of [{ lifecycle: "running" }, { lifecycle: "unproven" }, { acknowledged: false }, { dispatched: false }, { readback: null }] as const) expect(oracleRoutineOperationVerified(record(changes))).toBe(false);+ });++ it("atomically supersedes an observed unstarted approval rather than replaying old edited SQL", async () => {+ const { prepareOracleRoutineSourceSave } = await import("@/lib/table/oracleRoutineWrite");+ const original = record({ lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null });+ vi.mocked(api.executeOracleRoutineOperation).mockRejectedValueOnce(new Error("HTTP did not confirm arrival"));+ vi.mocked(api.observeOracleRoutineOperation).mockResolvedValue({ operation: original, lifecycle: "prepared", error: null });+ await expect((await prepareOracleRoutineSourceSave(input()))()).rejects.toMatchObject({ operationId: "original-operation" });+ const edited = { ...input(), sql: input().sql.replace("RETURN 1", "RETURN 2") };+ vi.mocked(api.prepareOracleRoutineSave).mockResolvedValue({ ...original, operationId: "new-approval" });+ vi.mocked(api.executeOracleRoutineOperation).mockResolvedValue(record({ operationId: "new-approval" }));+ const execute = await prepareOracleRoutineSourceSave(edited);+ expect(api.prepareOracleRoutineSave).toHaveBeenLastCalledWith({ ...edited, supersedesOperationId: "original-operation" });+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledTimes(1);+ expect(vi.mocked(api.updateOracleRoutineOperationReferences).mock.calls).toEqual([+ [["original-operation"], []],+ [["new-approval"], []],+ [[], ["original-operation"]],+ ]);+ await execute();+ expect(api.executeOracleRoutineOperation).toHaveBeenLastCalledWith("new-approval", edited.sql);+ });++ it("retains the original pending ID if replacement admission fails", async () => {+ const { prepareOracleRoutineSourceSave } = await import("@/lib/table/oracleRoutineWrite");+ const original = record({ lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null });+ vi.mocked(api.executeOracleRoutineOperation).mockRejectedValue(new Error("response lost"));+ vi.mocked(api.observeOracleRoutineOperation).mockResolvedValue({ operation: original, lifecycle: "prepared", error: null });+ const execute = await prepareOracleRoutineSourceSave(input());+ await expect(execute()).rejects.toMatchObject({ operationId: original.operationId });+ vi.mocked(api.prepareOracleRoutineSave).mockRejectedValue(new Error("registry capacity exceeded"));+ await expect(prepareOracleRoutineSourceSave({ ...input(), sql: input().sql.replace("RETURN 1", "RETURN 2") })).rejects.toMatchObject({ operationId: original.operationId });+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledTimes(1);+ expect(api.updateOracleRoutineOperationReferences).not.toHaveBeenCalledWith([], [original.operationId]);+ });++ it("preserves WARNING locations in a successful source-save message", async () => {+ const { objectSourceSaveSuccessMessage } = await import("@/lib/table/objectSourceEditor");+ const operation = record();+ operation.readback!.compilerMessages = [{ attribute: "WARNING", line: 4, position: 8, text: "unused variable" }];+ expect(objectSourceSaveSuccessMessage("saved", operation)).toBe("saved\nWARNING 4:8 unused variable");+ expect(objectSourceSaveSuccessMessage("saved")).toBe("saved");+ });+});diff --git a/apps/desktop/src/lib/backend/__tests__/functionInfoTransport.spec.ts b/apps/desktop/src/lib/backend/__tests__/functionInfoTransport.spec.tsnew file mode 100644index 0000000000..7002e33594--- /dev/null+++ b/apps/desktop/src/lib/backend/__tests__/functionInfoTransport.spec.ts@@ -0,0 +1,161 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { FunctionInfo } from "@/types/database";+import type { FunctionDiff, SchemaDiffPreparationOptions } from "@/lib/schema/schemaDiff";++const mocks = vi.hoisted(() => ({ invoke: vi.fn() }));+vi.mock("@tauri-apps/api/core", () => ({ invoke: mocks.invoke }));+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));++const wireProcedure = { name: "Mixed.Proc", functionType: "PROCEDURE", dataType: "", definition: 'CREATE PROCEDURE "Mixed.Proc" AS BEGIN NULL; END;', arguments: "" };+const procedure: FunctionInfo = { name: wireProcedure.name, function_type: "PROCEDURE", data_type: "", definition: wireProcedure.definition, arguments: "" };+const diff: FunctionDiff = { type: "modified", name: procedure.name, source: procedure, target: { ...procedure, definition: "old" } };++describe.each(["http", "tauri"] as const)("FunctionInfo %s transport", (transport) => {+ let backend: typeof import("@/lib/backend/http");+ let response: unknown;+ const fetchMock = vi.fn();++ beforeEach(async () => {+ vi.clearAllMocks();+ response = undefined;+ mocks.invoke.mockImplementation(async () => response);+ fetchMock.mockImplementation(async () => ({ ok: true, status: 200, json: async () => response }));+ vi.stubGlobal("fetch", fetchMock);+ backend = await import(transport === "http" ? "@/lib/backend/http" : "@/lib/backend/tauri");+ });++ afterEach(() => vi.unstubAllGlobals());++ function sent(): Record<string, unknown> {+ if (transport === "tauri") return mocks.invoke.mock.calls.at(-1)![1] as Record<string, unknown>;+ return JSON.parse(String((fetchMock.mock.calls.at(-1)![1] as RequestInit).body)) as Record<string, unknown>;+ }++ it("decodes the actual camelCase procedure list without treating it as a function", async () => {+ response = [wireProcedure];+ await expect(backend.listFunctions("connection", "database", "Owner.With.Dot")).resolves.toEqual([procedure]);+ });++ it("retains non-Oracle routine kinds and PostgreSQL overload arguments", async () => {+ response = [{ ...wireProcedure, functionType: "AGGREGATE", dataType: "integer", arguments: "integer, text" }];+ await expect(backend.listFunctions("pg", "db", "public")).resolves.toEqual([{ ...procedure, function_type: "AGGREGATE", data_type: "integer", arguments: "integer, text" }]);+ });++ it("continues accepting existing snake_case responses without mutating them", async () => {+ response = [procedure];+ await expect(backend.listFunctions("connection", "database", "APP")).resolves.toEqual([procedure]);+ expect(response).toEqual([procedure]);+ });++ it("retains a partial strict snapshot and its unread object instead of returning an empty list", async () => {+ response = {+ endpoint: { connectionId: "connection", database: "database", schema: "Owner.With.Dot", databaseType: "oceanbase-oracle", generation: 3 },+ state: "partial",+ enumerationComplete: true,+ objects: [+ {+ version: { identity: { owner: "Owner.With.Dot", name: "Mixed.Proc", kind: "PROCEDURE" }, objectId: "9007199254740993", status: "INVALID", lastDdlTime: "2026-10-21T08:30:00" },+ source: null,+ sourceComplete: false,+ dependencies: [],+ dependenciesComplete: true,+ issues: [{ stage: "source", code: "read-incomplete", message: "source read failed" }],+ },+ ],+ issues: [],+ };+ await expect(backend.loadSchemaDiffRoutines("connection", "database", "Owner.With.Dot")).resolves.toEqual(response);+ if (transport === "tauri") expect(mocks.invoke).toHaveBeenLastCalledWith("load_schema_diff_routines", { connectionId: "connection", database: "database", schema: "Owner.With.Dot" });+ else expect(String(fetchMock.mock.calls.at(-1)![0])).toContain("/api/schema/diff-routines?connection_id=connection&database=database&schema=Owner.With.Dot");+ });++ it("keeps confirmed empty strict snapshots distinct from permission failures", async () => {+ response = { endpoint: { connectionId: "connection", database: "database", schema: "Owner.With.Dot", databaseType: "oracle", generation: 3 }, state: "complete", enumerationComplete: true, objects: [], issues: [] };+ await expect(backend.loadSchemaDiffRoutines("connection", "database", "Owner.With.Dot")).resolves.toEqual(response);+ response = { ...(response as object), state: "permission-denied", enumerationComplete: false, issues: [{ stage: "visibility", code: "permission-denied", message: "ORA-00942" }] };+ await expect(backend.loadSchemaDiffRoutines("connection", "database", "Owner.With.Dot")).resolves.toEqual(response);+ });++ it.each([{ names: [] }, { names: ["Quoted.Proc", "Dot.Name,WithComma", "lowerCase"] }])("transports exact selected routine names without broadening the read: $names", async ({ names }) => {+ await backend.loadSchemaDiffRoutines("connection", "database", "Owner.With.Dot", names);+ if (transport === "tauri") expect(mocks.invoke).toHaveBeenLastCalledWith("load_schema_diff_routines", { connectionId: "connection", database: "database", schema: "Owner.With.Dot", selectedRoutines: names });+ else expect(JSON.parse(new URL(String(fetchMock.mock.calls.at(-1)![0]), "http://localhost").searchParams.get("selected_routines")!)).toEqual(names);+ });++ it("prepares the exact routine identity and SQL without dispatching it", async () => {+ const input = { connectionId: "connection", database: "database", identity: { owner: "Owner.With.Dot", name: "Mixed.Proc", kind: "PROCEDURE" as const }, sql: wireProcedure.definition };+ response = { operationId: "bound-operation", lifecycle: "prepared", dispatched: false };+ await expect(backend.prepareOracleRoutineSave(input)).resolves.toEqual(response);+ expect(transport === "tauri" ? sent().input : sent()).toEqual(input);+ if (transport === "tauri") expect(mocks.invoke).toHaveBeenLastCalledWith("prepare_oracle_routine_save", { input });+ });++ it("uses the original operation ID and approved SQL for execution", async () => {+ response = { operationId: "bound-operation", lifecycle: "running", dispatched: true };+ await expect(backend.executeOracleRoutineOperation("bound-operation", wireProcedure.definition)).resolves.toEqual(response);+ expect(sent()).toEqual({ operationId: "bound-operation", approvedSql: wireProcedure.definition });+ });++ it("retains complete snapshots and final per-object drafts in both controlled-plan transports", async () => {+ const snapshot = { endpoint: { connectionId: "target", database: "db", schema: "Owner.With.Dot", databaseType: "oceanbase-oracle" as const, generation: 7 }, state: "complete" as const, enumerationComplete: true, objects: [], issues: [] };+ const input = { source: snapshot, target: snapshot, drafts: [{ identity: { owner: "Owner.With.Dot", name: "Mixed.Proc", kind: "PROCEDURE" as const }, action: "replace" as const, sql: wireProcedure.definition, baselineOperationId: "failed-original", supersedesOperationId: "old-prepared" }] };+ response = { target: snapshot.endpoint, ready: false, steps: [{ sql: wireProcedure.definition, issues: [{ line: 4, column: 8, code: "unresolved-reference", message: "retain the final draft" }], operation: null }] };+ await expect(backend.prepareOracleRoutinePlan(input)).resolves.toEqual(response);+ expect(transport === "tauri" ? sent().input : sent()).toEqual(input);+ if (transport === "tauri") expect(mocks.invoke).toHaveBeenLastCalledWith("prepare_oracle_routine_plan", { input });+ });++ it("prepares recovery only from the original recorded operation", async () => {+ response = { ready: false, steps: [{ recoveryComplete: false, sql: wireProcedure.definition }] };+ await expect(backend.prepareOracleRoutineRecovery("original-operation")).resolves.toEqual(response);+ expect(sent()).toEqual({ operationId: "original-operation" });+ if (transport === "tauri") expect(mocks.invoke).toHaveBeenLastCalledWith("prepare_oracle_routine_recovery", { operationId: "original-operation" });+ });++ it("transports atomic operation retain and release through the same ownership boundary", async () => {+ await backend.updateOracleRoutineOperationReferences(["current"], ["abandoned"]);+ expect(sent()).toEqual({ retainOperationIds: ["current"], releaseOperationIds: ["abandoned"] });+ if (transport === "tauri") expect(mocks.invoke).toHaveBeenLastCalledWith("update_oracle_routine_operation_references", { retainOperationIds: ["current"], releaseOperationIds: ["abandoned"] });+ });++ it("retains unproven when the original backend operation record is missing", async () => {+ response = { operation: null, lifecycle: "unproven", error: "record unavailable" };+ await expect(backend.observeOracleRoutineOperation("old-operation", true)).resolves.toEqual(response);+ if (transport === "tauri") expect(mocks.invoke).toHaveBeenLastCalledWith("observe_oracle_routine_operation", { operationId: "old-operation", refreshReadback: true });+ else expect(String(fetchMock.mock.calls.at(-1)![0])).toContain("/api/schema/routine-operation?operation_id=old-operation&refresh_readback=true");+ });++ it("does not guess a kind when snake_case and camelCase disagree", async () => {+ response = [{ ...wireProcedure, function_type: "FUNCTION" }];+ await expect(backend.listFunctions("connection", "database", "APP")).rejects.toThrow(/conflict/i);+ });++ it("rejects contradictory return type fields", async () => {+ response = [{ ...wireProcedure, data_type: "NUMBER" }];+ await expect(backend.listFunctions("connection", "database", "APP")).rejects.toThrow(/conflict/i);+ });++ it("encodes both preparation inputs and decodes nested diff definitions", async () => {+ response = { diffs: [], syncSql: "", functionDiffs: [{ ...diff, source: wireProcedure, target: { ...wireProcedure, definition: "old" } }] };+ const options: SchemaDiffPreparationOptions = { sourceTables: [], targetTables: [], sourceDetails: [], targetDetails: [], sourceFunctions: [procedure], targetFunctions: [procedure], databaseType: "oceanbase-oracle" };+ const result = await backend.prepareSchemaDiff(options);+ const payload = transport === "tauri" ? sent().options : sent();+ expect(payload).toMatchObject({ sourceFunctions: [wireProcedure], targetFunctions: [wireProcedure] });+ expect((payload as SchemaDiffPreparationOptions).sourceFunctions![0]).not.toHaveProperty("function_type");+ expect(result.functionDiffs![0].source).toEqual(procedure);+ expect(result.functionDiffs![0].target).toEqual({ ...procedure, definition: "old" });+ });++ it("encodes nested source and target definitions in selected plan requests", async () => {+ response = { syncSql: "", rollbackCompleteness: "complete", missingRollbackObjects: [] };+ await backend.generateSchemaSyncPlan({ diffs: [], functionDiffs: [diff], sequenceDiffs: [], ruleDiffs: [], ownerDiffs: [] }, { databaseType: "oracle", targetSchema: "APP" });+ expect(sent()).toMatchObject({ functionDiffs: [{ source: wireProcedure, target: { ...wireProcedure, definition: "old" } }] });+ expect((sent().functionDiffs as FunctionDiff[])[0].source).not.toHaveProperty("function_type");+ });++ it("uses the same routine wire fields for the legacy SQL plan entry", async () => {+ response = "";+ await backend.generateSchemaSyncSql([], "oracle", "APP", [diff]);+ expect(sent()).toMatchObject({ functionDiffs: [{ source: wireProcedure, target: { ...wireProcedure, definition: "old" } }] });+ });+});diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex 4a40c98273..3f5f6d0a57 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -247,6 +247,13 @@ export const listSubpartitions = forward("listSubpartitions");export const getTableDdl = forward("getTableDdl");export const getTableDisplayDdl = forward("getTableDisplayDdl");export const listFunctions = forward("listFunctions");+export const loadSchemaDiffRoutines = forward("loadSchemaDiffRoutines");+export const updateOracleRoutineOperationReferences = forward("updateOracleRoutineOperationReferences");+export const prepareOracleRoutineSave = forward("prepareOracleRoutineSave");+export const prepareOracleRoutinePlan = forward("prepareOracleRoutinePlan");+export const prepareOracleRoutineRecovery = forward("prepareOracleRoutineRecovery");+export const executeOracleRoutineOperation = forward("executeOracleRoutineOperation");+export const observeOracleRoutineOperation = forward("observeOracleRoutineOperation");export const listSequences = forward("listSequences");export const listRules = forward("listRules");export const listOwners = forward("listOwners");diff --git a/apps/desktop/src/lib/backend/functionInfoTransport.ts b/apps/desktop/src/lib/backend/functionInfoTransport.tsnew file mode 100644index 0000000000..8c3db40632--- /dev/null+++ b/apps/desktop/src/lib/backend/functionInfoTransport.ts@@ -0,0 +1,39 @@+import type { FunctionInfo } from "@/types/database";+import type { FunctionDiff, SchemaDiffPreparation, SchemaDiffPreparationOptions } from "@/lib/schema/schemaDiff";++export type FunctionInfoWire = Omit<FunctionInfo, "function_type" | "data_type"> & { functionType: string; dataType: string };+type FunctionDiffWire = Omit<FunctionDiff, "source" | "target"> & { source?: FunctionInfoWire; target?: FunctionInfoWire };+export type SchemaDiffPreparationWire = Omit<SchemaDiffPreparation, "functionDiffs"> & { functionDiffs?: FunctionDiffWire[] };++function routineField(value: FunctionInfo | FunctionInfoWire, camel: "functionType" | "dataType", snake: "function_type" | "data_type"): string {+ const raw = value as unknown as Record<string, unknown>;+ if (raw[camel] !== undefined && raw[snake] !== undefined && raw[camel] !== raw[snake]) throw new Error(`Conflicting routine metadata: ${camel}`);+ const field = raw[camel] ?? raw[snake];+ if (typeof field !== "string") throw new Error(`Missing routine metadata: ${camel}`);+ return field;+}++/** FunctionInfo is snake_case in the UI and camelCase in Rust's serde contract. */+export function functionInfoFromWire(value: FunctionInfo | FunctionInfoWire): FunctionInfo {+ const { functionType: _functionType, function_type: _function_type, dataType: _dataType, data_type: _data_type, ...rest } = value as FunctionInfo & FunctionInfoWire;+ return { ...rest, function_type: routineField(value, "functionType", "function_type"), data_type: routineField(value, "dataType", "data_type") };+}++function functionInfoToWire(value: FunctionInfo): FunctionInfoWire {+ const { function_type, data_type, ...rest } = functionInfoFromWire(value);+ return { ...rest, functionType: function_type, dataType: data_type };+}++export function functionDiffsToWire(diffs: FunctionDiff[]): FunctionDiffWire[] {+ return diffs.map(({ source, target, ...diff }) => ({ ...diff, ...(source ? { source: functionInfoToWire(source) } : {}), ...(target ? { target: functionInfoToWire(target) } : {}) }));+}++export function schemaDiffPreparationToWire(options: SchemaDiffPreparationOptions) {+ const { sourceFunctions, targetFunctions, ...rest } = options;+ return { ...rest, ...(sourceFunctions ? { sourceFunctions: sourceFunctions.map(functionInfoToWire) } : {}), ...(targetFunctions ? { targetFunctions: targetFunctions.map(functionInfoToWire) } : {}) };+}++export function schemaDiffPreparationFromWire(value: SchemaDiffPreparationWire): SchemaDiffPreparation {+ const { functionDiffs, ...rest } = value;+ return { ...rest, ...(functionDiffs ? { functionDiffs: functionDiffs.map(({ source, target, ...diff }) => ({ ...diff, ...(source ? { source: functionInfoFromWire(source) } : {}), ...(target ? { target: functionInfoFromWire(target) } : {}) })) } : {}) };+}diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 39cb6451d6..2c6616744d 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -9,6 +9,8 @@ import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/liimport type { PluginUiStorageItemRef, SqlFileFailureLogExportPayload, SqlFileFailureLogInfo, SqlFileFailureLogKey, SqlFileFailureLogTextPayload, SyncCatalogItem, SyncSelection, SyncSnapshotCatalog } from "@/lib/backend/tauri";import { FAILURE_LOG_TEXT_TOO_LARGE } from "@/lib/export/failureLogExport";import { saveTextFile } from "@/lib/export/saveTextFile";+import { functionDiffsToWire, functionInfoFromWire, schemaDiffPreparationFromWire, schemaDiffPreparationToWire, type FunctionInfoWire, type SchemaDiffPreparationWire } from "./functionInfoTransport";+import type { OracleRoutineSnapshot, OracleRoutineOperation, OracleRoutineOperationObservation, OracleRoutineSaveInput, OracleRoutinePlanInput, OracleRoutinePlan } from "@/types/schemaDiff";export function databaseBackupCommand<T = unknown>(command: DatabaseBackupCommand): Promise<T> {return post("/api/database-backups", command);@@ -1362,7 +1364,7 @@ export async function getTableDisplayDdl(connectionId: string, database: string,}export async function prepareSchemaDiff(options: SchemaDiffPreparationOptions): Promise<SchemaDiffPreparation> {- return post("/api/schema-diff/prepare", options);+ return schemaDiffPreparationFromWire(await post<SchemaDiffPreparationWire>("/api/schema-diff/prepare", schemaDiffPreparationToWire(options)));}export async function generateSchemaSyncSql(diffs: TableDiff[], databaseType: DatabaseType, targetSchema?: string, functionDiffs?: FunctionDiff[], sequenceDiffs?: SequenceDiff[], ruleDiffs?: RuleDiff[], ownerDiffs?: OwnerDiff[], cascadeDelete?: boolean): Promise<string> {@@ -1370,7 +1372,7 @@ export async function generateSchemaSyncSql(diffs: TableDiff[], databaseType: Dadiffs,databaseType,targetSchema,- functionDiffs: functionDiffs ?? [],+ functionDiffs: functionDiffsToWire(functionDiffs ?? []),sequenceDiffs: sequenceDiffs ?? [],ruleDiffs: ruleDiffs ?? [],ownerDiffs: ownerDiffs ?? [],@@ -1382,11 +1384,40 @@ export async function generateSchemaSyncPlan(input: SelectedSchemaDiffInput, optreturn post("/api/schema-diff/generate-sync-plan", {...input,...options,+ functionDiffs: functionDiffsToWire(input.functionDiffs),});}export async function listFunctions(connectionId: string, database: string, schema: string): Promise<FunctionInfo[]> {- return get(`/api/schema/functions?${qs({ connection_id: connectionId, database, schema })}`);+ return (await get<FunctionInfoWire[]>(`/api/schema/functions?${qs({ connection_id: connectionId, database, schema })}`)).map(functionInfoFromWire);+}++export function loadSchemaDiffRoutines(connectionId: string, database: string, schema: string, selectedRoutines?: string[]): Promise<OracleRoutineSnapshot> {+ return get(`/api/schema/diff-routines?${qs({ connection_id: connectionId, database, schema, selected_routines: selectedRoutines === undefined ? undefined : JSON.stringify(selectedRoutines) })}`);+}++export function prepareOracleRoutineSave(input: OracleRoutineSaveInput): Promise<OracleRoutineOperation> {+ return post("/api/schema/routine-save", input);+}++export function prepareOracleRoutinePlan(input: OracleRoutinePlanInput): Promise<OracleRoutinePlan> {+ return post("/api/schema/routine-plan", input);+}++export function prepareOracleRoutineRecovery(operationId: string): Promise<OracleRoutinePlan> {+ return post("/api/schema/routine-recovery", { operationId });+}++export function executeOracleRoutineOperation(operationId: string, approvedSql: string): Promise<OracleRoutineOperation> {+ return post("/api/schema/routine-execute", { operationId, approvedSql });+}++export function observeOracleRoutineOperation(operationId: string, refreshReadback = false): Promise<OracleRoutineOperationObservation> {+ return get(`/api/schema/routine-operation?${qs({ operation_id: operationId, refresh_readback: refreshReadback })}`);+}++export function updateOracleRoutineOperationReferences(retainOperationIds: string[], releaseOperationIds: string[]): Promise<void> {+ return post("/api/schema/routine-operation-references", { retainOperationIds, releaseOperationIds });}export async function listSequences(connectionId: string, database: string, schema: string, withLastValues: boolean): Promise<SequenceInfo[]> {diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex 383be89f85..788c932c6c 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -7,6 +7,8 @@ import type { MongoRestoreUpload, MongoSourceReadOptions } from "./mongodbDumpTyimport type { DamengDumpKind, DamengDumpRequest, DamengDumpProgress } from "./damengDumpTypes";import type { UserSkillRootSettings, UserSkillsListResult, UserSkillsReadResult } from "@/types/userSkills";import type { DatabaseBackupCommand, DatabaseBackupBackgroundStatus } from "@/lib/backup/backgroundDatabaseBackup";+import { functionDiffsToWire, functionInfoFromWire, schemaDiffPreparationFromWire, schemaDiffPreparationToWire, type FunctionInfoWire, type SchemaDiffPreparationWire } from "./functionInfoTransport";+import type { OracleRoutineSnapshot, OracleRoutineOperation, OracleRoutineOperationObservation, OracleRoutineSaveInput, OracleRoutinePlanInput, OracleRoutinePlan } from "@/types/schemaDiff";export function databaseBackupCommand<T = unknown>(command: DatabaseBackupCommand): Promise<T> {return invoke("database_backup_command", { command });@@ -2778,7 +2780,7 @@ export async function getTableDisplayDdl(connectionId: string, database: string,}export async function prepareSchemaDiff(options: SchemaDiffPreparationOptions): Promise<SchemaDiffPreparation> {- return invoke("prepare_schema_diff", { options });+ return schemaDiffPreparationFromWire(await invoke<SchemaDiffPreparationWire>("prepare_schema_diff", { options: schemaDiffPreparationToWire(options) }));}export async function listDialectDataTypes(dialectName: string): Promise<string[]> {@@ -2790,7 +2792,7 @@ export async function generateSchemaSyncSql(diffs: TableDiff[], databaseType: Dadiffs,databaseType,targetSchema,- functionDiffs: functionDiffs ?? [],+ functionDiffs: functionDiffsToWire(functionDiffs ?? []),sequenceDiffs: sequenceDiffs ?? [],ruleDiffs: ruleDiffs ?? [],ownerDiffs: ownerDiffs ?? [],@@ -2802,11 +2804,40 @@ export async function generateSchemaSyncPlan(input: SelectedSchemaDiffInput, optreturn invoke("generate_schema_sync_plan", {...input,...options,+ functionDiffs: functionDiffsToWire(input.functionDiffs),});}export async function listFunctions(connectionId: string, database: string, schema: string): Promise<FunctionInfo[]> {- return invoke("list_functions", { connectionId, database, schema });+ return (await invoke<FunctionInfoWire[]>("list_functions", { connectionId, database, schema })).map(functionInfoFromWire);+}++export function loadSchemaDiffRoutines(connectionId: string, database: string, schema: string, selectedRoutines?: string[]): Promise<OracleRoutineSnapshot> {+ return invoke("load_schema_diff_routines", { connectionId, database, schema, ...(selectedRoutines === undefined ? {} : { selectedRoutines }) });+}++export function prepareOracleRoutineSave(input: OracleRoutineSaveInput): Promise<OracleRoutineOperation> {+ return invoke("prepare_oracle_routine_save", { input });+}++export function prepareOracleRoutinePlan(input: OracleRoutinePlanInput): Promise<OracleRoutinePlan> {+ return invoke("prepare_oracle_routine_plan", { input });+}++export function prepareOracleRoutineRecovery(operationId: string): Promise<OracleRoutinePlan> {+ return invoke("prepare_oracle_routine_recovery", { operationId });+}++export function executeOracleRoutineOperation(operationId: string, approvedSql: string): Promise<OracleRoutineOperation> {+ return invoke("execute_oracle_routine_operation", { operationId, approvedSql });+}++export function observeOracleRoutineOperation(operationId: string, refreshReadback = false): Promise<OracleRoutineOperationObservation> {+ return invoke("observe_oracle_routine_operation", { operationId, refreshReadback });+}++export function updateOracleRoutineOperationReferences(retainOperationIds: string[], releaseOperationIds: string[]): Promise<void> {+ return invoke("update_oracle_routine_operation_references", { retainOperationIds, releaseOperationIds });}export async function listSequences(connectionId: string, database: string, schema: string, withLastValues: boolean): Promise<SequenceInfo[]> {diff --git a/apps/desktop/src/lib/database/databaseObjectCapabilities.ts b/apps/desktop/src/lib/database/databaseObjectCapabilities.tsindex 30ffefe10b..3be3347f13 100644--- a/apps/desktop/src/lib/database/databaseObjectCapabilities.ts+++ b/apps/desktop/src/lib/database/databaseObjectCapabilities.ts@@ -137,7 +137,7 @@ export function databaseObjectCapabilities(dbType?: DatabaseType, compatibilityMconst SCHEMA_DIFF_ROUTINE_KINDS = ["PROCEDURE", "FUNCTION"] as const;/** Same-dialect families with verified list_objects + get_object_source (or PG catalog) paths. */-const SCHEMA_DIFF_ROUTINE_FAMILY = new Map<DatabaseType, "postgres" | "mysql" | "sqlserver">([+const SCHEMA_DIFF_ROUTINE_FAMILY = new Map<DatabaseType, "postgres" | "mysql" | "sqlserver" | "oracle" | "oceanbase-oracle">([["postgres", "postgres"],["opengauss", "postgres"],["gaussdb", "postgres"],@@ -149,8 +149,16 @@ const SCHEMA_DIFF_ROUTINE_FAMILY = new Map<DatabaseType, "postgres" | "mysql" |["redshift", "postgres"],["mysql", "mysql"],["sqlserver", "sqlserver"],+ ["oracle", "oracle"],+ ["oceanbase-oracle", "oceanbase-oracle"],]);+/** Only the new Oracle JDBC path consumes inferred product identity here; do+ * not broaden the existing generic-JDBC or other engine comparison contracts. */+export function schemaDiffRoutineProductType(rawType?: string, productType?: string): DatabaseType | undefined {+ return (rawType === "jdbc" && (productType === "oracle" || productType === "oceanbase-oracle") ? productType : rawType) as DatabaseType | undefined;+}+/*** Schema Diff routine compare is limited to an allowlist of same-dialect families.* Sidebar may list routines for more engines (oracle/hive/…); those stay out ofdiff --git a/apps/desktop/src/lib/schema/oracleRoutineDeploy.ts b/apps/desktop/src/lib/schema/oracleRoutineDeploy.tsnew file mode 100644index 0000000000..33500e826f--- /dev/null+++ b/apps/desktop/src/lib/schema/oracleRoutineDeploy.ts@@ -0,0 +1,388 @@+import * as api from "@/lib/backend/api";+import { oracleRoutineOperationVerified } from "@/lib/table/oracleRoutineWrite";+import { beginSourceSave, captureSourceIdentity } from "@/lib/table/objectSourceIdentity";+import { invalidateObjectDdlCache } from "@/lib/metadata/objectDdlCache";+import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";+import type { SchemaDiffObject } from "@/lib/schema/schemaDiff";+import type { OracleRoutineIdentity, OracleRoutineOperation, OracleRoutinePlan, OracleRoutinePlanDraft, OracleRoutinePlanStep, OracleRoutineSnapshot } from "@/types/schemaDiff";+import { releaseOracleRoutineOperations, retainOracleRoutineOperations } from "@/lib/table/oracleRoutineOperationReferences";++export interface OracleRoutineDeployDraft extends OracleRoutinePlanDraft {+ objectId: string;+ included: boolean;+ operation?: OracleRoutineOperation;+}++/** Owned by the existing comparison session, not the mounted dialog. */+export interface OracleRoutineDeployment {+ source: OracleRoutineSnapshot;+ target: OracleRoutineSnapshot;+ drafts: OracleRoutineDeployDraft[];+ selectedObjectId: string | null;+ revision: number;+ plan: OracleRoutinePlan | null;+ recoveryPlan: OracleRoutinePlan | null;+ records: OracleRoutineOperation[];+ validating: boolean;+ executing: boolean;+ pendingOperationId: string | null;+ stopRequested: boolean;+ reviewOpen: boolean;+ error: string | null;+ retainedOperationIds: string[];+ attemptedOperationIds: string[];+ disposed: boolean;+}++export function routineIdentityKey(identity: OracleRoutineIdentity): string {+ return JSON.stringify([identity.owner, identity.name, identity.kind]);+}++export function createOracleRoutineDeployment(source: OracleRoutineSnapshot, target: OracleRoutineSnapshot): OracleRoutineDeployment {+ return {+ source,+ target,+ drafts: [],+ selectedObjectId: null,+ revision: 0,+ plan: null,+ recoveryPlan: null,+ records: [],+ validating: false,+ executing: false,+ pendingOperationId: null,+ stopRequested: false,+ reviewOpen: false,+ error: null,+ retainedOperationIds: [],+ attemptedOperationIds: [],+ disposed: false,+ };+}++const referenceUpdates = new WeakMap<OracleRoutineDeployment, Promise<void>>();+function planOperationIds(plan: OracleRoutinePlan | null): string[] {+ return plan?.steps.flatMap((step) => (step.operation ? [step.operation.operationId] : [])) ?? [];+}++function pruneOperationReferences(state: OracleRoutineDeployment): Promise<void> {+ const update = (referenceUpdates.get(state) ?? Promise.resolve()).then(async () => {+ const used = new Set([...planOperationIds(state.plan), ...planOperationIds(state.recoveryPlan), ...state.drafts.flatMap((draft) => (draft.operation ? [draft.operation.operationId] : [])), ...state.attemptedOperationIds, ...(state.pendingOperationId ? [state.pendingOperationId] : [])]);+ state.records = state.records.filter((record) => record.dispatched || used.has(record.operationId));+ state.records.forEach((record) => used.add(record.operationId));+ const released = state.retainedOperationIds.filter((id) => state.disposed || !used.has(id));+ await releaseOracleRoutineOperations(released);+ state.retainedOperationIds = state.retainedOperationIds.filter((id) => !released.includes(id));+ });+ referenceUpdates.set(state, update);+ return update;+}++export function disposeOracleRoutineDeployment(state: OracleRoutineDeployment): Promise<void> {+ state.disposed = true;+ state.stopRequested = true;+ state.revision++;+ return pruneOperationReferences(state);+}++export function synchronizeOracleRoutineSelection(state: OracleRoutineDeployment, objects: SchemaDiffObject[]): void {+ if (state.disposed) return;+ let changed = false;+ for (const draft of state.drafts) {+ const included = objects.some((object) => object.id === draft.objectId && object.selected && object.operationType !== "none");+ if (draft.included !== included) {+ draft.included = included;+ changed = true;+ }+ }+ for (const object of objects) {+ if (!object.selected || object.operationType === "none" || state.drafts.some((draft) => draft.objectId === object.id)) continue;+ if (object.routineType !== "FUNCTION" && object.routineType !== "PROCEDURE") throw new Error("Routine selection has no exact function/procedure kind");+ state.drafts.push({+ objectId: object.id,+ identity: { owner: state.target.endpoint.schema, name: object.targetName ?? object.name, kind: object.routineType },+ action: object.operationType === "create" ? "create" : object.operationType === "delete" ? "delete" : "replace",+ sourceName: object.sourceName ?? object.name,+ included: true,+ });+ changed = true;+ }+ if (changed) {+ state.revision++;+ state.plan = null;+ state.recoveryPlan = null;+ for (const draft of state.drafts) {+ if (!draft.included && draft.operation?.lifecycle === "prepared" && !state.attemptedOperationIds.includes(draft.operation.operationId)) draft.operation = undefined;+ }+ void pruneOperationReferences(state);+ }+ if (!state.drafts.some((draft) => draft.objectId === state.selectedObjectId && draft.included)) {+ state.selectedObjectId = state.drafts.find((draft) => draft.included)?.objectId ?? null;+ }+}++export function editOracleRoutineDraft(state: OracleRoutineDeployment, objectId: string, sql: string): void {+ if (state.disposed) return;+ const draft = state.drafts.find((draft) => draft.objectId === objectId);+ if (!draft || draft.sql === sql || state.executing || (draft.operation && oracleRoutineOperationVerified(draft.operation))) return;+ draft.sql = sql;+ state.revision++;+ state.plan = null;+ state.recoveryPlan = null;+ state.error = null;+}++function errorText(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++export function selectOracleRoutineDraft(state: OracleRoutineDeployment, objectId: string): void {+ if (state.disposed) return;+ if (!state.drafts.some((draft) => draft.objectId === objectId && draft.included)) return;+ if (state.selectedObjectId !== objectId && state.recoveryPlan) {+ if (state.executing) return;+ state.recoveryPlan = null;+ state.revision++;+ void pruneOperationReferences(state);+ }+ state.selectedObjectId = objectId;+}+function sameTarget(left: OracleRoutinePlan["target"], right: OracleRoutinePlan["target"]): boolean {+ return left.connectionId === right.connectionId && left.database === right.database && left.schema === right.schema && left.databaseType === right.databaseType && left.generation === right.generation;+}++function remember(state: OracleRoutineDeployment, operation: OracleRoutineOperation): void {+ if (state.disposed) return;+ const index = state.records.findIndex((record) => record.operationId === operation.operationId);+ if (index < 0) state.records.push(operation);+ else state.records[index] = operation;+ const draft = state.drafts.find((draft) => routineIdentityKey(draft.identity) === routineIdentityKey(operation.identity));+ // An old response cannot replace a newer approval on the same target.+ if (draft && (!draft.operation || draft.operation.operationId === operation.operationId)) draft.operation = operation;+}++async function invalidateTarget(operation: OracleRoutineOperation): Promise<void> {+ if (!operation.dispatched && operation.lifecycle !== "unproven" && operation.lifecycle !== "running") return;+ const target = operation.target;+ invalidateObjectBrowserRowsCache({ connectionId: target.connectionId, database: target.database, schema: target.schema });+ await Promise.allSettled([invalidateObjectDdlCache({ connectionId: target.connectionId, database: target.database, schema: target.schema, tableName: operation.identity.name })]);+}++export async function observeOracleRoutineDeployment(state: OracleRoutineDeployment, operationId: string): Promise<void> {+ if (state.disposed) return;+ try {+ const observed = await api.observeOracleRoutineOperation(operationId, true);+ if (!observed.operation) {+ state.error = `${operationId}: ${observed.error ?? "Original request outcome is unproven"}`;+ return;+ }+ remember(state, observed.operation);+ await invalidateTarget(observed.operation);+ } catch (error) {+ state.error = `${operationId}: ${errorText(error)}`;+ }+}++/** Final text + exact identities are sent to Core; old database dependencies are+ * not reused as proof of a manually edited draft. */+export async function validateOracleRoutineDeployment(state: OracleRoutineDeployment): Promise<void> {+ if (state.disposed || state.validating || state.executing) return;+ const previousPlan = state.plan;+ let replacementPrepared = false;+ state.validating = true;+ state.error = null;+ state.recoveryPlan = null;+ const revision = state.revision;+ try {+ const drafts: OracleRoutinePlanDraft[] = [];+ for (const draft of state.drafts.filter((draft) => draft.included)) {+ if (draft.operation && oracleRoutineOperationVerified(draft.operation)) continue;+ let previous = draft.operation;+ if (previous) {+ const observed = await api.observeOracleRoutineOperation(previous.operationId, false);+ if (!observed.operation) throw new Error(`${previous.operationId}: ${observed.error ?? "Original operation is unavailable; do not replay"}`);+ remember(state, observed.operation);+ previous = observed.operation;+ if (previous.lifecycle === "running" || previous.lifecycle === "unproven") throw new Error(`${previous.operationId}: original request termination is not proven; observe this operation before any new write`);+ if (oracleRoutineOperationVerified(previous)) continue;+ }+ const baseline = previous?.lifecycle === "terminal" && previous.dispatched ? previous : undefined;+ const action = baseline && draft.action !== "delete" ? (baseline.readback?.exists === true ? "replace" : "create") : draft.action;+ drafts.push({ identity: { ...draft.identity }, action, sourceName: draft.sourceName, sql: draft.sql, baselineOperationId: baseline?.operationId, supersedesOperationId: previous?.lifecycle === "prepared" ? previous.operationId : undefined });+ }+ if (drafts.length === 0) {+ state.plan = null;+ return;+ }+ const plan = await api.prepareOracleRoutinePlan({ source: state.source, target: state.target, drafts });+ const ids = planOperationIds(plan);+ replacementPrepared = plan.ready && ids.length > 0;+ try {+ await retainOracleRoutineOperations(ids);+ if (revision !== state.revision || state.disposed) {+ await releaseOracleRoutineOperations(ids.filter((id) => !state.retainedOperationIds.includes(id)));+ return;+ }+ if (!sameTarget(plan.target, state.target.endpoint)) throw new Error("Routine plan belongs to another comparison target");+ if (plan.steps.some((step) => !state.drafts.some((draft) => routineIdentityKey(draft.identity) === routineIdentityKey(step.identity)))) throw new Error("Routine plan returned an unselected object");+ } catch (error) {+ await releaseOracleRoutineOperations(ids.filter((id) => !state.retainedOperationIds.includes(id)));+ throw error;+ }+ state.retainedOperationIds = [...new Set([...state.retainedOperationIds, ...ids])];+ state.plan = plan;+ for (const step of plan.steps) {+ const draft = state.drafts.find((draft) => routineIdentityKey(draft.identity) === routineIdentityKey(step.identity));+ if (!draft) throw new Error("Routine plan returned an unselected object");+ draft.sql = step.sql;+ if (step.operation) {+ draft.operation = step.operation;+ remember(state, step.operation);+ }+ }+ } catch (error) {+ if (revision === state.revision) {+ state.plan = previousPlan;+ if (replacementPrepared && previousPlan) previousPlan.ready = false;+ state.error = errorText(error);+ }+ } finally {+ state.validating = false;+ await pruneOperationReferences(state);+ }+}++/** Explicit refresh replaces only read baselines. Drafts and execution history+ * remain attached to the original session; unresolved writes cannot be erased. */+export async function refreshOracleRoutineDeployment(state: OracleRoutineDeployment): Promise<void> {+ if (state.disposed || state.validating || state.executing) return;+ state.validating = true;+ state.error = null;+ state.plan = null;+ state.recoveryPlan = null;+ const revision = ++state.revision;+ try {+ for (const draft of state.drafts) {+ if (!draft.operation || oracleRoutineOperationVerified(draft.operation)) continue;+ const observed = await api.observeOracleRoutineOperation(draft.operation.operationId, draft.action === "delete");+ if (!observed.operation || observed.lifecycle === "running" || observed.lifecycle === "unproven") throw new Error(`${draft.operation.operationId}: establish the original request's termination before refreshing this write baseline`);+ remember(state, observed.operation);+ }+ const sourceNames = [...new Set(state.drafts.map((draft) => draft.sourceName ?? draft.identity.name))];+ const targetNames = [...new Set(state.drafts.map((draft) => draft.identity.name))];+ const read = (snapshot: OracleRoutineSnapshot, names: string[]) => api.loadSchemaDiffRoutines(snapshot.endpoint.connectionId, snapshot.endpoint.database, snapshot.endpoint.schema, names);+ const [source, target] = await Promise.all([read(state.source, sourceNames), read(state.target, targetNames)]);+ if (revision !== state.revision || state.disposed) return;+ const sameReadTarget = (current: OracleRoutineSnapshot, before: OracleRoutineSnapshot) =>+ current.endpoint.connectionId === before.endpoint.connectionId && current.endpoint.database === before.endpoint.database && current.endpoint.schema === before.endpoint.schema && current.endpoint.databaseType === before.endpoint.databaseType;+ if (!sameReadTarget(source, state.source) || !sameReadTarget(target, state.target)) throw new Error("Refreshed snapshots do not match this comparison's original endpoints");+ state.source = source;+ state.target = target;+ for (const draft of state.drafts) {+ if (draft.operation && oracleRoutineOperationVerified(draft.operation)) continue;+ if (draft.operation?.lifecycle === "terminal" && draft.action !== "delete") draft.operation = undefined;+ if (draft.action !== "delete") draft.action = target.objects.some((object) => object.version.identity.owner === draft.identity.owner && object.version.identity.name === draft.identity.name) ? "replace" : "create";+ }+ } catch (error) {+ state.error = errorText(error);+ } finally {+ state.validating = false;+ await pruneOperationReferences(state);+ }+}++export function oracleRoutinePlanSql(state: OracleRoutineDeployment): string {+ return (state.recoveryPlan ?? state.plan)?.steps.map((step) => step.sql).join("\n/\n") ?? "";+}++export function oracleRoutineActiveStep(state: OracleRoutineDeployment): OracleRoutinePlanStep | undefined {+ const draft = state.drafts.find((draft) => draft.objectId === state.selectedObjectId);+ return (state.recoveryPlan ?? state.plan)?.steps.find((step) => draft && routineIdentityKey(step.identity) === routineIdentityKey(draft.identity));+}++export async function prepareOracleRoutineRecovery(state: OracleRoutineDeployment, operationId: string): Promise<void> {+ if (state.disposed || state.validating || state.executing) return;+ state.validating = true;+ state.error = null;+ const revision = state.revision;+ try {+ const plan = await api.prepareOracleRoutineRecovery(operationId);+ const ids = planOperationIds(plan);+ try {+ await retainOracleRoutineOperations(ids);+ if (revision !== state.revision || state.disposed) {+ await releaseOracleRoutineOperations(ids.filter((id) => !state.retainedOperationIds.includes(id)));+ return;+ }+ if (!sameTarget(plan.target, state.target.endpoint)) throw new Error("Recovery belongs to another target");+ if (!state.drafts.some((draft) => draft.included && plan.steps.some((step) => routineIdentityKey(step.identity) === routineIdentityKey(draft.identity)))) throw new Error("Recovery does not belong to an included routine");+ } catch (error) {+ await releaseOracleRoutineOperations(ids.filter((id) => !state.retainedOperationIds.includes(id)));+ throw error;+ }+ state.retainedOperationIds = [...new Set([...state.retainedOperationIds, ...ids])];+ const draft = state.drafts.find((draft) => draft.included && plan.steps.some((step) => routineIdentityKey(step.identity) === routineIdentityKey(draft.identity)));+ if (!draft) throw new Error("Recovery does not belong to an included routine");+ state.selectedObjectId = draft.objectId;+ state.recoveryPlan = plan;+ state.revision++;+ } catch (error) {+ state.error = errorText(error);+ } finally {+ state.validating = false;+ await pruneOperationReferences(state);+ }+}++/** authorize reuses the existing production guard. It may cancel without calling+ * run. Closing the view stops the NEXT step, never the server's current worker. */+export async function executeOracleRoutineDeployment(state: OracleRoutineDeployment, authorize: (sql: string, run: () => Promise<void>) => Promise<unknown>): Promise<void> {+ const plan = state.recoveryPlan ?? state.plan;+ if (state.disposed || state.executing || state.validating || !plan?.ready || !plan.steps.length) return;+ const revision = state.revision;+ state.executing = true;+ state.stopRequested = false;+ state.error = null;+ let attempted = false;+ try {+ await authorize(oracleRoutinePlanSql(state), async () => {+ if (state.disposed || revision !== state.revision || (state.recoveryPlan ?? state.plan) !== plan) throw new Error("Draft changed during confirmation; validate it again");+ for (const step of plan.steps) {+ if (state.stopRequested) break;+ const operation = step.operation;+ if (!operation) throw new Error("Routine step has no Core approval");+ if (state.records.some((record) => record.operationId === operation.operationId && (record.dispatched || record.lifecycle !== "prepared"))) {+ throw new Error(`${operation.operationId}: this approval has already been used; observe its original ID`);+ }+ const release = beginSourceSave(captureSourceIdentity({ connectionId: plan.target.connectionId, database: plan.target.database, schema: plan.target.schema, objectType: step.identity.kind, name: step.identity.name }));+ let result: OracleRoutineOperation;+ try {+ attempted = true;+ state.pendingOperationId = operation.operationId;+ if (!state.attemptedOperationIds.includes(operation.operationId)) state.attemptedOperationIds.push(operation.operationId);+ try {+ result = await api.executeOracleRoutineOperation(operation.operationId, step.sql);+ } catch (error) {+ // Never dispatch again after a lost response, including Prepared: a+ // late original execute must be superseded atomically by Core.+ const observed = await api.observeOracleRoutineOperation(operation.operationId, false).catch(() => null);+ result = observed?.operation ?? { ...operation, lifecycle: "unproven", error: errorText(error) };+ }+ if (!state.disposed) step.operation = result;+ remember(state, result);+ await invalidateTarget(result);+ } finally {+ state.pendingOperationId = null;+ release();+ }+ if (!oracleRoutineOperationVerified(result)) break;+ }+ });+ } catch (error) {+ state.error = errorText(error);+ } finally {+ state.executing = false;+ if (attempted) plan.ready = false;+ await pruneOperationReferences(state);+ }+}diff --git a/apps/desktop/src/lib/schema/schemaDiff.ts b/apps/desktop/src/lib/schema/schemaDiff.tsindex 66f04f56ba..8080246d56 100644--- a/apps/desktop/src/lib/schema/schemaDiff.ts+++ b/apps/desktop/src/lib/schema/schemaDiff.ts@@ -1,5 +1,5 @@import type { ColumnInfo, IndexInfo, ForeignKeyInfo, TriggerInfo, FunctionInfo, SequenceInfo, RuleInfo, OwnerInfo, DatabaseType, TableInfo, ConnectionConfig } from "@/types/database";-import type { SchemaDiffTableMapping } from "@/types/schemaDiff";+import type { OracleRoutineCompareContext, SchemaDiffTableMapping } from "@/types/schemaDiff";import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";import { splitSqlStatementRanges } from "@/lib/sql/sqlStatementRanges";@@ -171,7 +171,7 @@ export interface TriggerDiff {}export interface FunctionDiff {- type: "added" | "removed" | "modified";+ type: "added" | "removed" | "modified" | "equal" | "unreadable" | "conflict";name: string;source?: FunctionInfo;target?: FunctionInfo;@@ -241,6 +241,7 @@ export interface SchemaDiffPreparationOptions {targetDetails: TableSchemaDetail[];sourceFunctions?: FunctionInfo[];targetFunctions?: FunctionInfo[];+ oracleRoutines?: OracleRoutineCompareContext;sourceSequences?: SequenceInfo[];targetSequences?: SequenceInfo[];sourceRules?: RuleInfo[];@@ -423,6 +424,7 @@ export interface SchemaDiffObject {arguments?: string;/** PROCEDURE vs FUNCTION when objectKind is function (for getObjectSource). */routineType?: "PROCEDURE" | "FUNCTION";+ routineComparisonState?: FunctionDiff["type"];renameMetadata?: {confirmed: boolean;sourceName?: string;@@ -766,9 +768,10 @@ export function convertToSchemaDiffObjects(tableDiffs: TableDiff[], functionDiffname: diff.name,arguments: args,routineType,+ routineComparisonState: diff.type,sourceName: diff.type === "added" ? undefined : diff.name,targetName: diff.type === "removed" ? undefined : diff.name,- selected: true,+ selected: getOperationType(diff.type) !== "none",sourceDdl: diff.source?.definition,targetDdl: diff.target?.definition,changes: diff.changes,diff --git a/apps/desktop/src/lib/table/objectSourceEditor.ts b/apps/desktop/src/lib/table/objectSourceEditor.tsindex 97c5c65f2a..9e99fefcd6 100644--- a/apps/desktop/src/lib/table/objectSourceEditor.ts+++ b/apps/desktop/src/lib/table/objectSourceEditor.ts@@ -1,6 +1,9 @@import type { DatabaseType, ObjectSourceKind } from "@/types/database";import * as api from "@/lib/backend/api";import { beginSourceSave, type SourceIdentitySnapshot } from "@/lib/table/objectSourceIdentity";+import { prepareOracleRoutineSourceSave } from "@/lib/table/oracleRoutineWrite";+import i18n from "@/i18n";+import type { OracleRoutineOperation } from "@/types/schemaDiff";export type BuildEditableObjectSourceSqlInput = {databaseType: DatabaseType;@@ -108,6 +111,25 @@ export function objectSourceSaveExecutionMode(_databaseType: DatabaseType): Objereturn "single";}+export type PreparedObjectSourceSave = (() => Promise<OracleRoutineOperation | undefined>) & { dispose?: () => Promise<void> };++export async function prepareObjectSourceSave(connectionId: string, database: string, databaseType: DatabaseType, statements: string[], schema: string, identity: { objectType: ObjectSourceKind; name: string }): Promise<PreparedObjectSourceSave> {+ if ((databaseType === "oracle" || databaseType === "oceanbase-oracle") && (identity.objectType === "PROCEDURE" || identity.objectType === "FUNCTION")) {+ const nonEmpty = statements.filter((sql) => sql.trim());+ if (nonEmpty.length !== 1) throw new Error(i18n.global.t("objects.routineSaveSingleDefinition"));+ return prepareOracleRoutineSourceSave({ connectionId, database, identity: { owner: schema, name: identity.name, kind: identity.objectType }, sql: nonEmpty[0] });+ }+ return async () => {+ await executeObjectSourceSave(connectionId, database, databaseType, statements, schema);+ return undefined;+ };+}++export function objectSourceSaveSuccessMessage(message: string, operation?: OracleRoutineOperation): string {+ const warnings = operation?.readback?.compilerMessages.filter((message) => message.attribute === "WARNING") ?? [];+ return [message, ...warnings.map((warning) => `WARNING ${warning.line}:${warning.position} ${warning.text}`)].join("\n");+}+export async function executeObjectSourceSave(connectionId: string, database: string, databaseType: DatabaseType, statements: string[], schema?: string, timeoutSecs?: number): Promise<void> {const nonEmptyStatements = statements.filter((sql) => sql.trim().length > 0);if (nonEmptyStatements.length === 0) return;diff --git a/apps/desktop/src/lib/table/objectSourceTabSave.ts b/apps/desktop/src/lib/table/objectSourceTabSave.tsnew file mode 100644index 0000000000..17edafbc2c--- /dev/null+++ b/apps/desktop/src/lib/table/objectSourceTabSave.ts@@ -0,0 +1,56 @@+import type { ConnectionConfig, QueryTab } from "@/types/database";+import type { useQueryStore } from "@/stores/queryStore";+import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";+import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";+import { assertSourceIdentity, beginSourceSave } from "@/lib/table/objectSourceIdentity";+import { buildExecutableObjectSourceStatements, objectSourceSaveSuccessMessage, prepareObjectSourceSave } from "@/lib/table/objectSourceEditor";++interface ObjectSourceTabSaveContext {+ connection?: ConnectionConfig;+ queryStore: Pick<ReturnType<typeof useQueryStore>, "tabs" | "getObjectSourceIdentitySnapshot" | "markTabClean">;+ t: (key: string, values?: Record<string, unknown>) => string;+ toast: (message: string, duration?: number) => void;+}++/** App's source-tab Save/Save-and-close handler, including confirmation and clean timing. */+export async function saveObjectSourceTab(tab: QueryTab, { connection, queryStore, t, toast }: ObjectSourceTabSaveContext): Promise<boolean> {+ const source = tab.objectSource;+ if (!connection || !source) return false;+ let save: Awaited<ReturnType<typeof prepareObjectSourceSave>> | undefined;++ try {+ const identity = queryStore.getObjectSourceIdentitySnapshot(tab)!;+ assertSourceIdentity(identity);+ const { connectionId, database } = tab;+ const schema = source.schema || tab.schema || database;+ const sql = tab.sql;+ const databaseType = effectiveDatabaseTypeForConnection(connection) ?? connection.db_type;+ const statements = await buildExecutableObjectSourceStatements({ databaseType, objectType: source.objectType, schema, name: source.name, source: sql });+ save = await prepareObjectSourceSave(connectionId, database, databaseType, statements, schema, { objectType: source.objectType, name: source.name });+ const preparedSave = save;+ const targetIsCurrent = () => queryStore.tabs.includes(tab) && tab.objectSource === source && tab.connectionId === connectionId && tab.database === database && (source.schema || tab.schema || database) === schema;+ const execute = async () => {+ if (!targetIsCurrent()) return;+ const release = beginSourceSave(identity);+ try {+ return { operation: await preparedSave() };+ } finally {+ release();+ }+ };+ const executableSql = statements.filter((sql) => sql.trim()).join(";\n");+ let result;+ if (executableSql.trim()) result = await executeWithProductionSqlGuard({ connection, database, sql: executableSql, source: t("production.sourceObjectSource"), execute });+ else result = await execute();+ if (!result || !targetIsCurrent()) return false;+ if (tab.sql === sql) queryStore.markTabClean(tab);+ toast(objectSourceSaveSuccessMessage(t("objects.sourceSaved"), result.operation), result.operation?.readback?.compilerMessages.length ? 6000 : 2000);+ return true;+ } catch (error: unknown) {+ const message = error && typeof error === "object" && "message" in error ? error.message : undefined;+ toast(t("objects.sourceSaveFailed", { message: message || String(error) }), 5000);+ return false;+ } finally {+ await save?.dispose?.();+ }+}diff --git a/apps/desktop/src/lib/table/oracleRoutineOperationReferences.ts b/apps/desktop/src/lib/table/oracleRoutineOperationReferences.tsnew file mode 100644index 0000000000..0590b05b92--- /dev/null+++ b/apps/desktop/src/lib/table/oracleRoutineOperationReferences.ts@@ -0,0 +1,35 @@+import * as api from "@/lib/backend/api";++// Serialize ownership changes so a delayed release cannot undo a later retain.+let updates: Promise<void> = Promise.resolve();+const pendingReleases = new Set<string>();++function enqueue(update: () => Promise<void>): Promise<void> {+ const result = updates.then(update);+ updates = result.catch(() => {});+ return result;+}++async function flushReleases(): Promise<void> {+ while (pendingReleases.size) {+ const ids = [...pendingReleases].slice(0, 1024);+ await api.updateOracleRoutineOperationReferences([], ids);+ ids.forEach((id) => pendingReleases.delete(id));+ }+}++export function retainOracleRoutineOperations(ids: string[]): Promise<void> {+ return enqueue(async () => {+ ids.forEach((id) => pendingReleases.delete(id));+ // Failed cleanup is retried on normal lifecycle actions, never by a timer.+ await flushReleases().catch(() => {});+ if (ids.length) await api.updateOracleRoutineOperationReferences([...new Set(ids)], []);+ });+}++export function releaseOracleRoutineOperations(ids: string[]): Promise<void> {+ return enqueue(async () => {+ ids.forEach((id) => pendingReleases.add(id));+ await flushReleases();+ }).catch(() => {});+}diff --git a/apps/desktop/src/lib/table/oracleRoutineWrite.ts b/apps/desktop/src/lib/table/oracleRoutineWrite.tsnew file mode 100644index 0000000000..580844d1e1--- /dev/null+++ b/apps/desktop/src/lib/table/oracleRoutineWrite.ts@@ -0,0 +1,138 @@+import i18n from "@/i18n";+import * as api from "@/lib/backend/api";+import type { OracleRoutineOperation, OracleRoutineSaveInput } from "@/types/schemaDiff";+import { releaseOracleRoutineOperations, retainOracleRoutineOperations } from "./oracleRoutineOperationReferences";++export type PreparedOracleRoutineSave = (() => Promise<OracleRoutineOperation>) & { dispose?: () => Promise<void> };++// A lost client wait keeps its original ID, including after closing/reopening a+// source editor. Database readback alone must not release an unresolved write.+const pendingSaves = new Map<string, { input: OracleRoutineSaveInput; operation: OracleRoutineOperation }>();++export class OracleRoutineWriteError extends Error {+ constructor(+ public readonly operationId: string,+ public readonly operation: OracleRoutineOperation | null,+ message: string,+ ) {+ super(message);+ this.name = "OracleRoutineWriteError";+ }+}++export function oracleRoutineOperationVerified(operation: OracleRoutineOperation): boolean {+ return operation.lifecycle === "terminal" && operation.dispatched && operation.acknowledged && operation.readback?.state === "verified";+}++export function requireVerifiedOracleRoutine(operation: OracleRoutineOperation): void {+ if (oracleRoutineOperationVerified(operation)) return;+ const pending = operation.lifecycle === "running" || operation.lifecycle === "unproven";+ const stateKey = operation.readback?.state === "invalid" ? "objects.routineReadbackInvalid" : operation.readback?.state === "missing" ? "objects.routineReadbackMissing" : operation.readback?.state === "definition-mismatch" ? "objects.routineReadbackMismatch" : null;+ const details = [+ operation.dispatched && operation.acknowledged ? i18n.global.t("objects.routineWriteAcknowledged") : null,+ stateKey ? i18n.global.t(stateKey) : null,+ operation.error,+ ...(operation.readback?.issues.map((issue) => issue.message) ?? []),+ ...(operation.readback?.compilerMessages.map((message) => `${message.attribute} ${message.line}:${message.position} ${message.text}`) ?? []),+ ]+ .filter(Boolean)+ .join("\n");+ throw new OracleRoutineWriteError(operation.operationId, operation, `${i18n.global.t(pending ? "objects.routineWritePending" : "objects.routineWriteUnverified", { operationId: operation.operationId })}${details ? `\n${details}` : ""}`);+}++/** Prepare BEFORE production confirmation, execute the exact approved draft+ * afterwards. Keeping these phases separate binds confirmation to its endpoint. */+export async function prepareOracleRoutineSourceSave(input: OracleRoutineSaveInput): Promise<PreparedOracleRoutineSave> {+ input = { ...input, identity: { ...input.identity } };+ const key = JSON.stringify([input.connectionId, input.database, input.identity.owner, input.identity.name]);+ const pending = pendingSaves.get(key);+ let prepared: OracleRoutineOperation | undefined;+ if (pending) {+ let latest;+ try {+ latest = await api.observeOracleRoutineOperation(pending.operation.operationId, false);+ } catch {+ /* Retain the original ID below. */+ }+ if (latest?.operation?.lifecycle === "prepared") {+ // Core atomically supersedes Prepared, preventing its late execute from+ // racing the edited approval. Running/unproven cannot take this path.+ try {+ prepared = await api.prepareOracleRoutineSave({ ...input, supersedesOperationId: pending.operation.operationId });+ await retainOracleRoutineOperations([prepared.operationId]);+ } catch {+ if (prepared) await releaseOracleRoutineOperations([prepared.operationId]);+ throw new OracleRoutineWriteError(pending.operation.operationId, latest.operation, i18n.global.t("objects.routineWritePending", { operationId: pending.operation.operationId }));+ }+ if (pendingSaves.get(key) === pending) pendingSaves.delete(key);+ await releaseOracleRoutineOperations([pending.operation.operationId]);+ } else {+ // A new Save click is only a status check while an earlier write is pending.+ return async () => {+ let observed;+ try {+ observed = await api.observeOracleRoutineOperation(pending.operation.operationId, true);+ } catch {+ throw new OracleRoutineWriteError(pending.operation.operationId, pending.operation, i18n.global.t("objects.routineWritePending", { operationId: pending.operation.operationId }));+ }+ if (!observed.operation) throw new OracleRoutineWriteError(pending.operation.operationId, null, i18n.global.t("objects.routineWritePending", { operationId: pending.operation.operationId }));+ if (observed.operation.lifecycle === "terminal" && pendingSaves.get(key) === pending) {+ pendingSaves.delete(key);+ await releaseOracleRoutineOperations([pending.operation.operationId]);+ }+ requireVerifiedOracleRoutine(observed.operation);+ // Reconciliation of the previous SQL must never mark a newer draft clean.+ if (input.sql !== pending.input.sql || input.identity.kind !== pending.input.identity.kind) throw new OracleRoutineWriteError(pending.operation.operationId, observed.operation, i18n.global.t("objects.routineWriteDraftChanged"));+ return observed.operation;+ };+ }+ }+ const approval = prepared ?? (await api.prepareOracleRoutineSave(input));+ if (!prepared) {+ try {+ await retainOracleRoutineOperations([approval.operationId]);+ } catch (error) {+ await releaseOracleRoutineOperations([approval.operationId]);+ throw error;+ }+ }+ let transferred = false;+ let disposed = false;+ const execute = async () => {+ // Different source editors may have prepared concurrently. The Core target+ // hold is authoritative; this map also retains the first unresolved ID.+ const active = pendingSaves.get(key);+ if (active) throw new OracleRoutineWriteError(active.operation.operationId, active.operation, i18n.global.t("objects.routineWritePending", { operationId: active.operation.operationId }));+ if (disposed || transferred) throw new OracleRoutineWriteError(approval.operationId, approval, i18n.global.t("objects.routineWritePending", { operationId: approval.operationId }));+ transferred = true;+ pendingSaves.set(key, { input, operation: approval });+ let operation: OracleRoutineOperation;+ try {+ operation = await api.executeOracleRoutineOperation(approval.operationId, input.sql);+ } catch {+ // The execute request may have arrived. Never prepare a replacement ID.+ try {+ const observed = await api.observeOracleRoutineOperation(approval.operationId, false);+ if (!observed.operation) throw new Error("unavailable");+ operation = observed.operation;+ } catch {+ throw new OracleRoutineWriteError(approval.operationId, approval, i18n.global.t("objects.routineWritePending", { operationId: approval.operationId }));+ }+ }+ if (pendingSaves.get(key)?.operation.operationId === approval.operationId) {+ if (operation.lifecycle === "terminal") {+ pendingSaves.delete(key);+ await releaseOracleRoutineOperations([approval.operationId]);+ } else pendingSaves.set(key, { input, operation });+ }+ requireVerifiedOracleRoutine(operation);+ return operation;+ };+ return Object.assign(execute, {+ dispose: async () => {+ if (transferred || disposed) return;+ disposed = true;+ await releaseOracleRoutineOperations([approval.operationId]);+ },+ });+}diff --git a/apps/desktop/src/types/schemaDiff.ts b/apps/desktop/src/types/schemaDiff.tsindex 61c3df1d47..9e62afe008 100644--- a/apps/desktop/src/types/schemaDiff.ts+++ b/apps/desktop/src/types/schemaDiff.ts@@ -1,5 +1,141 @@export type SchemaDiffTableFilterPriority = "include" | "exclude";+export interface OracleRoutineEndpoint {+ connectionId: string;+ database: string;+ schema: string;+ databaseType: "oracle" | "oceanbase-oracle";+ generation: number;+}++export interface OracleRoutineIdentity {+ owner: string;+ name: string;+ kind: "PROCEDURE" | "FUNCTION";+}++export interface OracleRoutineVersion {+ identity: OracleRoutineIdentity;+ objectId: string;+ status: string;+ lastDdlTime: string;+}++export interface OracleRoutineReadIssue {+ stage: string;+ code: string;+ message: string;+}++export interface OracleRoutineDependency {+ owner: string;+ name: string;+ kind: string;+ databaseLink: string | null;+ dependencyType: string;+}++export interface OracleRoutineObjectSnapshot {+ version: OracleRoutineVersion;+ source: string | null;+ sourceComplete: boolean;+ dependencies: OracleRoutineDependency[];+ dependenciesComplete: boolean;+ issues: OracleRoutineReadIssue[];+}++export interface OracleRoutineSnapshot {+ endpoint: OracleRoutineEndpoint;+ state: "complete" | "partial" | "failed" | "permission-denied";+ enumerationComplete: boolean;+ objects: OracleRoutineObjectSnapshot[];+ issues: OracleRoutineReadIssue[];+}++export interface OracleRoutineCompareContext {+ sourceDatabaseType: string;+ targetDatabaseType: string;+ sourceSchema: string;+ targetSchema: string;+ sourceEnumerationComplete: boolean;+ targetEnumerationComplete: boolean;+ sourceIncompleteNames: string[];+ targetIncompleteNames: string[];+}++export interface OracleRoutineReadback {+ identity: OracleRoutineIdentity;+ state: "verified" | "invalid" | "missing" | "present" | "definition-mismatch" | "readback-failed";+ exists: boolean | null;+ version: OracleRoutineVersion | null;+ source: string | null;+ definitionMatches: boolean | null;+ compilerMessages: { attribute: string; line: number; position: number; text: string }[];+ issues: OracleRoutineReadIssue[];+}++export interface OracleRoutineOperation {+ operationId: string;+ target: OracleRoutineEndpoint;+ identity: OracleRoutineIdentity;+ lifecycle: "prepared" | "running" | "terminal" | "unproven";+ dispatched: boolean;+ acknowledged: boolean;+ readback: OracleRoutineReadback | null;+ error: string | null;+}++export interface OracleRoutineOperationObservation {+ operation: OracleRoutineOperation | null;+ lifecycle: OracleRoutineOperation["lifecycle"];+ error: string | null;+}++export interface OracleRoutineSaveInput {+ connectionId: string;+ database: string;+ identity: OracleRoutineIdentity;+ sql: string;+ supersedesOperationId?: string;+}++export type OracleRoutinePlanAction = "create" | "replace" | "delete";++export interface OracleRoutinePlanDraft {+ identity: OracleRoutineIdentity;+ action: OracleRoutinePlanAction;+ sourceName?: string;+ sql?: string;+ baselineOperationId?: string;+ supersedesOperationId?: string;+}++export interface OracleRoutinePlanInput {+ source: OracleRoutineSnapshot;+ target: OracleRoutineSnapshot;+ drafts: OracleRoutinePlanDraft[];+}++export interface OracleRoutinePlanStep {+ identity: OracleRoutineIdentity;+ action: OracleRoutinePlanAction;+ sql: string;+ sourceOriginal: string | null;+ targetOriginal: string | null;+ recoverySql: string | null;+ recoveryComplete: boolean;+ references: { owner: string; name: string; kind: string; member: string | null; selectedIndex: number | null; line: number; column: number }[];+ incomingCallers: OracleRoutineDependency[];+ issues: { code: string; message: string; line: number; column: number }[];+ operation: OracleRoutineOperation | null;+}++export interface OracleRoutinePlan {+ target: OracleRoutineEndpoint;+ steps: OracleRoutinePlanStep[];+ ready: boolean;+}+export interface SchemaDiffTableMapping {sourceTable: string;targetTable: string;diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rsindex bc91f48c8b..dea0c6a30d 100644--- a/crates/dbx-core/src/connection/mod.rs+++ b/crates/dbx-core/src/connection/mod.rs@@ -379,6 +379,10 @@ pub struct ConnectionLifecycleSnapshot {}impl ConnectionLifecycleSnapshot {+ pub fn generation(&self) -> u64 {+ self.generation+ }+pub fn cancellation(&self) -> &CancellationToken {&self.cancellation}@@ -422,6 +426,7 @@ pub struct AppState {shared_resource_budgets: std::sync::Mutex<HashMap<String, SharedResourceBudget>>,pub configs: RwLock<HashMap<String, ConnectionConfig>>,pub running_queries: RunningQueries,+ pub routine_operations: crate::schema::oracle_routines::RoutineOperationRegistry,pub tunnels: TunnelManager,pub proxy_tunnels: ProxyTunnelManager,pub http_tunnels: HttpTunnelManager,@@ -1781,6 +1786,7 @@ impl AppState {shared_resource_budgets: std::sync::Mutex::new(HashMap::new()),configs: RwLock::new(HashMap::new()),running_queries: RunningQueries::default(),+ routine_operations: crate::schema::oracle_routines::RoutineOperationRegistry::default(),tunnels: TunnelManager::new(data_dir),proxy_tunnels: ProxyTunnelManager::new(),http_tunnels: HttpTunnelManager::new(),diff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rsindex f710ff17af..c27180f1f0 100644--- a/crates/dbx-core/src/data/transfer.rs+++ b/crates/dbx-core/src/data/transfer.rs@@ -9652,6 +9652,37 @@ pub async fn transfer_schema_objects<F>(target_pool_key: &str,progress_callback: F,) -> Result<TransferObjectOutcome, String>+where+ F: FnMut(TransferProgress),+{+ if matches!(request.content, TransferContent::DataOnly) {+ return Ok(TransferObjectOutcome::default());+ }+ let routine_context = crate::schema::oracle_routines::capture_routine_transfer_context(+ state,+ &request.source_connection_id,+ &request.target_connection_id,+ )+ .await?;+ transfer_schema_objects_with_routine_context(+ state,+ request,+ source_pool_key,+ target_pool_key,+ routine_context.as_ref(),+ progress_callback,+ )+ .await+}++pub(crate) async fn transfer_schema_objects_with_routine_context<F>(+ state: &AppState,+ request: &TransferRequest,+ source_pool_key: &str,+ target_pool_key: &str,+ routine_context: Option<&crate::schema::oracle_routines::RoutineTransferContext>,+ progress_callback: F,+) -> Result<TransferObjectOutcome, String>whereF: FnMut(TransferProgress),{@@ -9704,6 +9735,7 @@ where&target_db_type,source_pool_key,target_pool_key,+ routine_context,progress_callback,).await@@ -9975,6 +10007,7 @@ async fn transfer_oracle_schema_objects<F>(target_db_type: &DatabaseType,source_pool_key: &str,target_pool_key: &str,+ routine_context: Option<&crate::schema::oracle_routines::RoutineTransferContext>,mut progress_callback: F,) -> Result<TransferObjectOutcome, String>where@@ -10013,6 +10046,47 @@ whereprogress(&mut outcome, TransferStatus::Running, None);continue;}+ if let Some(context) =+ routine_context.filter(|_| matches!(kind, TransferObjectKind::Procedure | TransferObjectKind::Function))+ {+ let identity = crate::schema::oracle_routines::RoutineIdentity {+ owner: source_schema.clone(),+ name: name.clone(),+ kind: if kind == TransferObjectKind::Procedure {+ db::ObjectSourceKind::Procedure+ } else {+ db::ObjectSourceKind::Function+ },+ };+ let result = crate::schema::oracle_routines::transfer_oracle_routine_core(+ state,+ context,+ crate::schema::oracle_routines::RoutineTransferInput {+ source_connection_id: request.source_connection_id.clone(),+ source_database: request.source_database.clone(),+ identity,+ target_connection_id: request.target_connection_id.clone(),+ target_database: request.target_database.clone(),+ target_owner: target_schema.clone(),+ },+ )+ .await;+ match result {+ Ok(operation) if operation.verified() => {+ outcome.transferred.push(format!("{kind:?}:{name}"));+ progress(&mut outcome, TransferStatus::Running, None);+ }+ result => {+ let error = match result {+ Ok(operation) => operation.failure_message(),+ Err(error) => error,+ };+ outcome.failed.push(format!("{kind:?}:{name}"));+ progress(&mut outcome, TransferStatus::Error, Some(error));+ }+ }+ continue;+ }let query = oracle_object_source_query(&kind, &source_schema, &name)?;let result = execute_on_pool(state, source_pool_key, &query).await?;// DBMS_METADATA.GET_DDL resolves against the session's currentdiff --git a/crates/dbx-core/src/data/transfer_runner.rs b/crates/dbx-core/src/data/transfer_runner.rsindex 5cac483422..e9a5600858 100644--- a/crates/dbx-core/src/data/transfer_runner.rs+++ b/crates/dbx-core/src/data/transfer_runner.rs@@ -82,6 +82,33 @@ wherelet total_tables = request.tables.len();let app = ProgressEmitter::new(progress_callback);+ let routine_context = match crate::schema::oracle_routines::capture_routine_transfer_context(+ &state,+ &request.source_connection_id,+ &request.target_connection_id,+ )+ .await+ {+ Ok(context) => context,+ Err(error) => {+ if let Some(journal) = history.as_ref() {+ journal.record_schema_objects_error(false).await;+ }+ super::transfer::clear_cancelled(&transfer_id).await;+ return TransferProgress {+ transfer_id,+ table: "schema objects".into(),+ table_index: 0,+ total_tables,+ rows_transferred: 0,+ total_rows: None,+ status: TransferStatus::Error,+ error: Some(error),+ terminal: true,+ };+ }+ };+super::transfer::with_transfer_operation_timeout(operation_timeout_secs, async {// Sort tables by FK dependency so referenced tables are transferred first,// and keep the foreign key metadata fetched along the way — MySQL-family@@ -475,11 +502,12 @@ where// transfers schema objects; PG→PG keeps the legacy empty-selection// default only when structure participates in the transfer.let mut object_outcome = super::transfer::TransferObjectOutcome::default();- match super::transfer::transfer_schema_objects(+ match super::transfer::transfer_schema_objects_with_routine_context(&state,&request,&source_pool_key,&target_pool_key,+ routine_context.as_ref(),|progress| emit_progress(&app, progress),).awaitdiff --git a/crates/dbx-core/src/query/query_cancel.rs b/crates/dbx-core/src/query/query_cancel.rsindex 59e0132931..cdf6003a7d 100644--- a/crates/dbx-core/src/query/query_cancel.rs+++ b/crates/dbx-core/src/query/query_cancel.rs@@ -119,7 +119,27 @@ impl RunningQueries {metadata: RunningTaskMetadata,remember_completion: bool,) -> RegisteredQuery {- let token = CancellationToken::new();+ self.register_task_with_token(execution_id, metadata, remember_completion, CancellationToken::new())+ }++ /// Bind a controlled write to its original connection lifecycle. Cancelling+ /// this child must never cancel other users of the connection's parent token.+ pub fn register_task_for_terminal_confirmation_with_parent(+ &self,+ execution_id: String,+ metadata: RunningTaskMetadata,+ parent: &CancellationToken,+ ) -> RegisteredQuery {+ self.register_task_with_token(execution_id, metadata, true, parent.child_token())+ }++ fn register_task_with_token(+ &self,+ execution_id: String,+ metadata: RunningTaskMetadata,+ remember_completion: bool,+ token: CancellationToken,+ ) -> RegisteredQuery {let registration_id = self.next_registration_id.fetch_add(1, Ordering::Relaxed) + 1;let (completion, _) = watch::channel(false);let previous = {@@ -428,6 +448,7 @@ impl Drop for RegisteredQuery {mod tests {use super::{RunningQueries, RunningTaskKind, RunningTaskMetadata, DETACHED_REGISTRATION_GRACE_PERIOD};use std::time::{Duration, Instant};+ use tokio_util::sync::CancellationToken;#[test]fn cancel_marks_registered_query_as_cancelled() {@@ -463,6 +484,21 @@ mod tests {assert!(!running.has("exec-1"));}+ #[test]+ fn connection_lifecycle_cancels_only_its_registered_children() {+ let running = RunningQueries::default();+ let parent = CancellationToken::new();+ let first =+ running.register_task_for_terminal_confirmation_with_parent("first".into(), Default::default(), &parent);+ running.cancel("first");+ assert!(first.token().is_cancelled());+ assert!(!parent.is_cancelled());+ let second =+ running.register_task_for_terminal_confirmation_with_parent("second".into(), Default::default(), &parent);+ parent.cancel();+ assert!(second.token().is_cancelled());+ }+#[tokio::test(start_paused = true)]async fn detached_registration_survives_and_stays_cancellable() {let running = RunningQueries::default();diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex 989e908ee2..c3dc4b368a 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -24,6 +24,7 @@ mod agent_pg_sequences;mod external_table_filter_tests;mod kingbase;mod mongodb_columns;+pub mod oracle_routines;pub mod plugin_metadata;#[cfg(test)]mod plugin_metadata_tests;@@ -11427,6 +11428,42 @@ fn finalize_object_source(mut source: db::ObjectSource) -> db::ObjectSource {source}+async fn managed_object_source<T: serde::de::DeserializeOwned + Send + 'static>(+ pool: &PoolKind,+ database: &str,+ schema: &str,+ name: &str,+ object_type: &db::ObjectSourceKind,+ relation_name: Option<&str>,+ timeout: Option<Duration>,+) -> Result<T, String> {+ match pool {+ PoolKind::Agent(client) => {+ client+ .lock()+ .await+ .get_object_source_for_relation(database, schema, name, object_type, relation_name, timeout)+ .await+ }+ PoolKind::ExternalDriver { config, session, .. } => {+ session+ .invoke_with_timeout(+ "getObjectSource",+ serde_json::json!({+ "connection": config.as_ref(),+ "database": database,+ "schema": schema,+ "name": name,+ "object_type": object_type,+ }),+ timeout,+ )+ .await+ }+ _ => Err("Managed object source is not supported for this connection".into()),+ }+}+async fn get_object_source_once(state: &AppState,connection_id: &str,@@ -11468,19 +11505,16 @@ async fn get_object_source_once(routine_parameters: None,});}- let result: db::ObjectSource = session- .invoke_with_timeout(- "getObjectSource",- serde_json::json!({- "connection": config.as_ref(),- "database": database,- "schema": schema,- "name": name,- "object_type": &object_type,- }),- agent_metadata_timeout(Some(config.as_ref())),- )- .await?;+ let result: db::ObjectSource = managed_object_source(+ pool_handle.as_ref().ok_or("Pool not found")?,+ database,+ schema,+ name,+ &object_type,+ None,+ agent_metadata_timeout(Some(config.as_ref())),+ )+ .await?;return Ok(result);}if let Some(client) = extract_pool!(pool_handle.as_ref(), SqlServer) {@@ -11530,17 +11564,16 @@ async fn get_object_source_once(None => String::new(),}} else {- let mut client = client.lock().await;- let result: db::ObjectSource = client- .get_object_source_for_relation(- database,- schema,- name,- &object_type,- relation_name,- agent_metadata_timeout(db_config.as_ref()),- )- .await?;+ let result: db::ObjectSource = managed_object_source(+ pool_handle.as_ref().ok_or("Pool not found")?,+ database,+ schema,+ name,+ &object_type,+ relation_name,+ agent_metadata_timeout(db_config.as_ref()),+ )+ .await?;return Ok(result);}} else {diff --git a/crates/dbx-core/src/schema/oracle_routines.rs b/crates/dbx-core/src/schema/oracle_routines.rsnew file mode 100644index 0000000000..0f905683c1--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines.rs@@ -0,0 +1,702 @@+//! Complete, identity-bound routine reads for schema comparison and write readback.+//! Ordinary object lists keep their existing visibility and source contracts.++use super::{agent_metadata_timeout, connection_config, is_oracle_external_driver_config, managed_object_source};+use crate::connection::{AppState, PoolKind};+use crate::db;+use crate::models::connection::{ConnectionConfig, DatabaseType};+use crate::query::{agent_execute_query_params, QueryExecutionOptions};+use dbx_sql::object_source_sql::{validate_oracle_executable_object_source, OracleObjectSourceValidationInput};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::BTreeMap;++const PAGE_SIZE: usize = 256;++mod execution;+mod transfer;+pub(crate) use transfer::{+ capture_routine_transfer_context, transfer_oracle_routine_core, RoutineTransferContext, RoutineTransferInput,+};+mod operations;+mod plan;+mod readback;+mod references;+pub use execution::{+ execute_oracle_routine_operation_core, observe_oracle_routine_operation_core, prepare_oracle_routine_save_core,+ OracleRoutineSaveInput,+};+pub use operations::{+ RoutineOperationLifecycle, RoutineOperationObservation, RoutineOperationRecord, RoutineOperationRegistry,+};+pub use plan::{+ prepare_oracle_routine_plan_core, prepare_oracle_routine_recovery_core, OracleRoutinePlan, OracleRoutinePlanInput,+ OracleRoutinePlanStep, RoutinePlanAction, RoutinePlanDraft,+};+pub use readback::{+ read_oracle_routine_core, RoutineCompilerMessage, RoutineReadback, RoutineReadbackGoal, RoutineReadbackState,+};++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineEndpoint {+ pub connection_id: String,+ pub database: String,+ pub schema: String,+ pub database_type: DatabaseType,+ pub generation: u64,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineIdentity {+ pub owner: String,+ pub name: String,+ pub kind: db::ObjectSourceKind,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineVersion {+ pub identity: RoutineIdentity,+ // Decimal strings preserve Oracle NUMBER identities across JS transports.+ pub object_id: String,+ pub status: String,+ pub last_ddl_time: String,+}++#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineDependency {+ pub owner: String,+ pub name: String,+ pub kind: String,+ pub database_link: Option<String>,+ pub dependency_type: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineReadIssue {+ pub stage: String,+ pub code: String,+ pub message: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum RoutineReadState {+ Complete,+ Partial,+ Failed,+ PermissionDenied,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineObjectSnapshot {+ pub version: RoutineVersion,+ pub source: Option<String>,+ pub source_complete: bool,+ pub dependencies: Vec<RoutineDependency>,+ pub dependencies_complete: bool,+ pub issues: Vec<RoutineReadIssue>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineSnapshot {+ pub endpoint: RoutineEndpoint,+ pub state: RoutineReadState,+ pub enumeration_complete: bool,+ pub objects: Vec<RoutineObjectSnapshot>,+ pub issues: Vec<RoutineReadIssue>,+}++#[derive(Debug, Default, Deserialize)]+struct ReadFlags {+ #[serde(default, alias = "executionError")]+ execution_error: bool,+ #[serde(default)]+ truncated: bool,+ #[serde(default, alias = "hasMore")]+ has_more: bool,+ #[serde(default, alias = "largeValueCells")]+ large_value_cells: Vec<Value>,+ #[serde(default)]+ messages: Vec<db::QueryMessage>,+}++impl ReadFlags {+ fn check(&self) -> Result<(), String> {+ if self.execution_error || self.messages.iter().any(|message| message.severity.eq_ignore_ascii_case("ERROR")) {+ return Err("Routine metadata query reported an execution error".into());+ }+ if self.truncated || self.has_more || !self.large_value_cells.is_empty() {+ return Err("Routine metadata response is incomplete (row or large-value limit)".into());+ }+ Ok(())+ }+}++#[derive(Debug, Deserialize)]+struct CatalogReply {+ columns: Vec<String>,+ rows: Vec<Vec<Value>>,+ #[serde(flatten)]+ flags: ReadFlags,+}++impl CatalogReply {+ fn cell<'a>(&self, row: &'a [Value], column: &str) -> Result<&'a Value, String> {+ let index = self+ .columns+ .iter()+ .position(|name| name.eq_ignore_ascii_case(column))+ .ok_or_else(|| format!("Routine metadata is missing column {column}"))?;+ row.get(index).ok_or_else(|| format!("Routine metadata row is missing {column}"))+ }++ fn text(&self, row: &[Value], column: &str) -> Result<String, String> {+ match self.cell(row, column)? {+ Value::String(value) if !value.is_empty() => Ok(value.clone()),+ Value::Number(value) => Ok(value.to_string()),+ _ => Err(format!("Routine metadata has no {column}")),+ }+ }++ fn integer(&self, row: &[Value], column: &str) -> Result<u64, String> {+ self.text(row, column)?.parse().map_err(|_| format!("Routine metadata has invalid {column}"))+ }+}++#[derive(Debug, Deserialize)]+struct SourceReply {+ #[serde(flatten)]+ object: db::ObjectSource,+ #[serde(flatten)]+ flags: ReadFlags,+}++#[derive(Clone, Copy)]+enum SourceOrigin {+ OracleDictionary,+ OceanBaseDictionary,+ OracleMetadata,+}++#[async_trait::async_trait]+trait RoutineCatalog: Sync {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String>;+ async fn source(&self, identity: &RoutineIdentity) -> Result<SourceReply, String>;+}++struct LiveCatalog<'a> {+ state: &'a AppState,+ endpoint: &'a RoutineEndpoint,+ config: &'a ConnectionConfig,+}++impl LiveCatalog<'_> {+ async fn check_endpoint(&self) -> Result<(), String> {+ let lifecycle = self.state.connection_lifecycle_snapshot(&self.endpoint.connection_id);+ let current = connection_config(self.state, &self.endpoint.connection_id)+ .await+ .ok_or("Original routine connection is unavailable")?;+ if lifecycle.generation() != self.endpoint.generation+ || lifecycle.cancellation().is_cancelled()+ || !crate::connection::connection_configs_session_credentials_compatible(¤t, self.config)+ {+ return Err("Original routine connection changed; read a new preview before writing".into());+ }+ Ok(())+ }+}++#[async_trait::async_trait]+impl RoutineCatalog for LiveCatalog<'_> {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ self.check_endpoint().await?;+ let key = self+ .state+ .get_or_create_metadata_pool_for_session(&self.endpoint.connection_id, Some(&self.endpoint.database), None)+ .await?;+ let pool = self.state.pool_handle(&key).await.ok_or("Pool not found")?;+ self.check_endpoint().await?;+ let mut params = agent_execute_query_params(+ sql,+ Some(&self.endpoint.database),+ Some(&self.endpoint.schema),+ QueryExecutionOptions { max_rows: Some(PAGE_SIZE + 1), ..Default::default() },+ );+ let timeout = agent_metadata_timeout(Some(self.config));+ match pool {+ PoolKind::Agent(client) => client.lock().await.execute_query_with_timeout(params, timeout).await,+ PoolKind::ExternalDriver { config, session, .. } => {+ params["connection"] = serde_json::to_value(config.as_ref()).map_err(|error| error.to_string())?;+ session.invoke_with_timeout("executeQuery", params, timeout).await+ }+ _ => Err("Oracle routine metadata requires its managed driver".into()),+ }+ }++ async fn source(&self, identity: &RoutineIdentity) -> Result<SourceReply, String> {+ self.check_endpoint().await?;+ let key = self+ .state+ .get_or_create_metadata_pool_for_session(&self.endpoint.connection_id, Some(&self.endpoint.database), None)+ .await?;+ let pool = self.state.pool_handle(&key).await.ok_or("Pool not found")?;+ self.check_endpoint().await?;+ managed_object_source(+ &pool,+ &self.endpoint.database,+ &identity.owner,+ &identity.name,+ &identity.kind,+ None,+ agent_metadata_timeout(Some(self.config)),+ )+ .await+ }+}++pub async fn load_schema_diff_routines_core(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+) -> Result<RoutineSnapshot, String> {+ load_selected_schema_diff_routines_core(state, connection_id, database, schema, None).await+}++pub async fn load_selected_schema_diff_routines_core(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ selected_routines: Option<&[String]>,+) -> Result<RoutineSnapshot, String> {+ if schema.is_empty() {+ return Err("Select an exact Oracle routine owner".into());+ }+ let config = connection_config(state, connection_id).await.ok_or("Connection not found")?;+ let (database_type, origin) = routine_source_origin(&config)?;+ let lifecycle = state.connection_lifecycle_snapshot(connection_id);+ let endpoint = RoutineEndpoint {+ connection_id: connection_id.into(),+ database: database.into(),+ schema: schema.into(),+ database_type,+ generation: lifecycle.generation(),+ };+ let catalog = LiveCatalog { state, endpoint: &endpoint, config: &config };+ let mut snapshot = collect_selected_snapshot(&catalog, endpoint.clone(), origin, selected_routines).await;+ if !state.connection_lifecycle_is_current(connection_id, &lifecycle) {+ invalidate_snapshot_endpoint(&mut snapshot);+ }+ Ok(snapshot)+}++fn invalidate_snapshot_endpoint(snapshot: &mut RoutineSnapshot) {+ snapshot.enumeration_complete = false;+ snapshot.state = RoutineReadState::Partial;+ snapshot.issues.push(issue("endpoint", "Connection changed while reading routine metadata"));+ for object in &mut snapshot.objects {+ object.source_complete = false;+ object.dependencies_complete = false;+ }+}++fn routine_source_origin(config: &ConnectionConfig) -> Result<(DatabaseType, SourceOrigin), String> {+ Ok(match config.db_type {+ DatabaseType::Oracle => (DatabaseType::Oracle, SourceOrigin::OracleDictionary),+ DatabaseType::OceanbaseOracle => (DatabaseType::OceanbaseOracle, SourceOrigin::OceanBaseDictionary),+ DatabaseType::Jdbc if is_oracle_external_driver_config(config) => {+ (DatabaseType::Oracle, SourceOrigin::OracleMetadata)+ }+ _ => return Err("Strict routine metadata requires Oracle or OceanBase Oracle".into()),+ })+}++fn literal(value: &str) -> String {+ format!("'{}'", value.replace('\'', "''"))+}++fn kind_name(kind: &db::ObjectSourceKind) -> &'static str {+ match kind {+ db::ObjectSourceKind::Procedure => "PROCEDURE",+ db::ObjectSourceKind::Function => "FUNCTION",+ _ => unreachable!("routine identities are validated on collection"),+ }+}++fn object_key(identity: &RoutineIdentity) -> (String, String, &'static str) {+ (identity.owner.clone(), identity.name.clone(), kind_name(&identity.kind))+}++fn issue(stage: &str, message: impl Into<String>) -> RoutineReadIssue {+ let message = message.into();+ let code = if message.contains("ORA-00942") || message.contains("ORA-01031") {+ "permission-denied"+ } else {+ "read-incomplete"+ };+ RoutineReadIssue { stage: stage.into(), code: code.into(), message }+}++fn inventory_sql(owner: &str, dba: bool, after_id: u64) -> String {+ let view = if dba { "SYS.DBA_OBJECTS" } else { "ALL_OBJECTS" };+ format!(+ "SELECT * FROM (SELECT OWNER, OBJECT_NAME, OBJECT_TYPE, OBJECT_ID, STATUS, \+ TO_CHAR(LAST_DDL_TIME, 'YYYY-MM-DD\"T\"HH24:MI:SS') LAST_DDL_TIME \+ FROM {view} WHERE OWNER = {} AND OBJECT_TYPE IN ('PROCEDURE', 'FUNCTION') \+ AND OBJECT_ID > {after_id} ORDER BY OBJECT_ID) WHERE ROWNUM <= {PAGE_SIZE}",+ literal(owner),+ )+}++struct InventoryRead {+ objects: Vec<RoutineVersion>,+ error: Option<String>,+}++async fn inventory(catalog: &impl RoutineCatalog, owner: &str, dba: bool) -> InventoryRead {+ let mut objects = Vec::new();+ let mut after_id = 0;+ let mut names = std::collections::BTreeSet::new();+ let read: Result<(), String> = async {+ loop {+ let reply = catalog.query(&inventory_sql(owner, dba, after_id)).await?;+ if reply.rows.len() > PAGE_SIZE {+ return Err("Routine inventory exceeded its page size".into());+ }+ for row in &reply.rows {+ let object_id = reply.integer(row, "OBJECT_ID")?;+ let kind = match reply.text(row, "OBJECT_TYPE")?.as_str() {+ "PROCEDURE" => db::ObjectSourceKind::Procedure,+ "FUNCTION" => db::ObjectSourceKind::Function,+ _ => return Err("Routine inventory returned a different object kind".into()),+ };+ let identity =+ RoutineIdentity { owner: reply.text(row, "OWNER")?, name: reply.text(row, "OBJECT_NAME")?, kind };+ if identity.owner != owner || object_id <= after_id || !names.insert(object_key(&identity)) {+ return Err("Routine inventory has duplicate, unordered or mismatched identities".into());+ }+ after_id = object_id;+ objects.push(RoutineVersion {+ identity,+ object_id: object_id.to_string(),+ status: reply.text(row, "STATUS")?,+ last_ddl_time: reply.text(row, "LAST_DDL_TIME")?,+ });+ }+ reply.flags.check()?;+ if reply.rows.len() < PAGE_SIZE {+ return Ok(());+ }+ }+ }+ .await;+ InventoryRead { objects, error: read.err() }+}++fn identity_filter(identity: &RoutineIdentity) -> String {+ format!(+ "OWNER = {} AND NAME = {} AND TYPE = {}",+ literal(&identity.owner),+ literal(&identity.name),+ literal(kind_name(&identity.kind))+ )+}++fn source_integrity_sql(identity: &RoutineIdentity, origin: SourceOrigin) -> String {+ if matches!(origin, SourceOrigin::OracleMetadata) {+ return format!(+ "SELECT LENGTH(DBMS_METADATA.GET_DDL({}, {}, {})) SOURCE_CHARS FROM DUAL",+ literal(kind_name(&identity.kind)),+ literal(&identity.name),+ literal(&identity.owner)+ );+ }+ // Native ALL_SOURCE.TEXT is VARCHAR2: LENGTH4 fixes the codepoint unit even+ // on legacy UTF8 databases. OB exposes CLOB here and LENGTH4 rejects CLOB.+ let length = if matches!(origin, SourceOrigin::OracleDictionary) { "LENGTH4" } else { "LENGTH" };+ let filter = identity_filter(identity);+ let whitespace = "CHR(9)||CHR(10)||CHR(11)||CHR(12)||CHR(13)||' '";+ format!(+ "SELECT COUNT(*) SOURCE_ROWS, MIN(LINE) FIRST_LINE, MAX(LINE) LAST_LINE, \+ SUM({length}(TEXT)) SOURCE_CHARS, \+ SUM(CASE WHEN LINE = 1 THEN {length}(TEXT)-NVL({length}(LTRIM(TEXT, {whitespace})),0) ELSE 0 END) HEAD_TRIM, \+ SUM(CASE WHEN LINE = (SELECT MAX(LINE) FROM ALL_SOURCE WHERE {filter}) \+ THEN {length}(TEXT)-NVL({length}(RTRIM(TEXT, {whitespace})),0) ELSE 0 END) TAIL_TRIM \+ , MAX(CASE WHEN LINE = 1 THEN CAST(SUBSTR(LTRIM(TEXT, {whitespace}), 1, 18) AS VARCHAR2(72)) END) SOURCE_HEAD \+ FROM ALL_SOURCE WHERE {filter}"+ )+}++async fn check_source(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ identity: &RoutineIdentity,+ reply: &SourceReply,+ origin: SourceOrigin,+) -> Result<(), String> {+ reply.flags.check()?;+ if reply.object.name != identity.name+ || reply.object.schema.as_deref() != Some(&identity.owner)+ || reply.object.object_type != identity.kind+ {+ return Err("Routine source returned a different owner, name or kind".into());+ }+ validate_oracle_executable_object_source(OracleObjectSourceValidationInput {+ database_type: endpoint.database_type,+ object_type: identity.kind.clone(),+ schema: Some(identity.owner.clone()),+ name: identity.name.clone(),+ source: reply.object.source.clone(),+ })?;+ let lengths = catalog.query(&source_integrity_sql(identity, origin)).await?;+ lengths.flags.check()?;+ if lengths.rows.len() != 1 {+ return Err("Routine source length is unavailable or ambiguous".into());+ }+ let row = &lengths.rows[0];+ let mut expected = lengths.integer(row, "SOURCE_CHARS")?;+ let actual = match origin {+ SourceOrigin::OracleMetadata => reply.object.source.encode_utf16().count() as u64,+ SourceOrigin::OracleDictionary => reply.object.source.chars().count() as u64,+ SourceOrigin::OceanBaseDictionary => {+ let head = lengths.integer(row, "HEAD_TRIM")?;+ let tail = lengths.integer(row, "TAIL_TRIM")?;+ expected = expected.checked_sub(head + tail).ok_or("Routine source trim length is inconsistent")?;+ let head = lengths.text(row, "SOURCE_HEAD")?;+ let body = if head.get(..7).is_some_and(|prefix| prefix.eq_ignore_ascii_case("CREATE ")) {+ reply.object.source.as_str()+ } else {+ reply+ .object+ .source+ .strip_prefix("CREATE OR REPLACE ")+ .ok_or("OceanBase routine source has an unverified dictionary representation")?+ };+ body.chars().count() as u64+ }+ };+ if !matches!(origin, SourceOrigin::OracleMetadata) {+ let count = lengths.integer(row, "SOURCE_ROWS")?;+ if count == 0 || lengths.integer(row, "FIRST_LINE")? != 1 || lengths.integer(row, "LAST_LINE")? != count {+ return Err("Routine dictionary source has missing or duplicate lines".into());+ }+ }+ if actual != expected || actual == 0 {+ return Err("Routine source does not match the complete source-origin character length".into());+ }+ Ok(())+}++async fn dependencies(+ catalog: &impl RoutineCatalog,+ identity: &RoutineIdentity,+) -> Result<Vec<RoutineDependency>, String> {+ let mut result = Vec::new();+ let mut offset = 0;+ loop {+ let sql = format!(+ "SELECT * FROM (SELECT REFERENCED_OWNER, REFERENCED_NAME, REFERENCED_TYPE, \+ REFERENCED_LINK_NAME, DEPENDENCY_TYPE, ROW_NUMBER() OVER (ORDER BY REFERENCED_OWNER, \+ REFERENCED_NAME, REFERENCED_TYPE, REFERENCED_LINK_NAME, DEPENDENCY_TYPE) RN \+ FROM ALL_DEPENDENCIES WHERE {}) WHERE RN > {offset} AND RN <= {} ORDER BY RN",+ identity_filter(identity),+ offset + PAGE_SIZE,+ );+ let reply = catalog.query(&sql).await?;+ reply.flags.check()?;+ if reply.rows.len() > PAGE_SIZE {+ return Err("Routine dependencies exceeded their page size".into());+ }+ for row in &reply.rows {+ if reply.integer(row, "RN")? != (result.len() + 1) as u64 {+ return Err("Routine dependency pagination is incomplete".into());+ }+ result.push(RoutineDependency {+ owner: reply.text(row, "REFERENCED_OWNER")?,+ name: reply.text(row, "REFERENCED_NAME")?,+ kind: reply.text(row, "REFERENCED_TYPE")?,+ database_link: match reply.cell(row, "REFERENCED_LINK_NAME")? {+ Value::Null => None,+ Value::String(value) if value.is_empty() => None,+ Value::String(value) => Some(value.clone()),+ _ => return Err("Routine dependency has an invalid database link".into()),+ },+ dependency_type: reply.text(row, "DEPENDENCY_TYPE")?,+ });+ }+ if reply.rows.len() < PAGE_SIZE {+ result.sort();+ return Ok(result);+ }+ offset += PAGE_SIZE;+ }+}++#[cfg(test)]+async fn collect_snapshot(+ catalog: &impl RoutineCatalog,+ endpoint: RoutineEndpoint,+ origin: SourceOrigin,+) -> RoutineSnapshot {+ collect_selected_snapshot(catalog, endpoint, origin, None).await+}++async fn collect_selected_snapshot(+ catalog: &impl RoutineCatalog,+ endpoint: RoutineEndpoint,+ origin: SourceOrigin,+ selected_routines: Option<&[String]>,+) -> RoutineSnapshot {+ let mut snapshot = RoutineSnapshot {+ endpoint,+ state: RoutineReadState::Failed,+ enumeration_complete: false,+ objects: Vec::new(),+ issues: Vec::new(),+ };+ let login = match catalog.query("SELECT USER AS LOGIN_OWNER FROM DUAL").await.and_then(|reply| {+ reply.flags.check()?;+ if reply.rows.len() != 1 {+ return Err("Routine owner visibility is unknown".into());+ }+ reply.text(&reply.rows[0], "LOGIN_OWNER")+ }) {+ Ok(login) => login,+ Err(error) => {+ snapshot.issues.push(issue("visibility", error));+ return snapshot;+ }+ };+ let mut dba = login != snapshot.endpoint.schema;+ let mut initial_read = inventory(catalog, &snapshot.endpoint.schema, dba).await;+ snapshot.enumeration_complete = initial_read.error.is_none();+ if let Some(error) = initial_read.error {+ snapshot.issues.push(issue(if dba { "visibility" } else { "inventory" }, error));+ if dba {+ dba = false;+ let visible = inventory(catalog, &snapshot.endpoint.schema, false).await;+ for object in visible.objects {+ if !initial_read.objects.iter().any(|known| object_key(&known.identity) == object_key(&object.identity))+ {+ initial_read.objects.push(object);+ }+ }+ if let Some(error) = visible.error {+ snapshot.issues.push(issue("inventory", error));+ }+ }+ }+ let initial = initial_read.objects;+ for version in initial.iter().cloned() {+ let mut object = RoutineObjectSnapshot {+ version,+ source: None,+ source_complete: false,+ dependencies: Vec::new(),+ dependencies_complete: false,+ issues: Vec::new(),+ };+ if selected_routines.is_some_and(|names| !names.contains(&object.version.identity.name)) {+ snapshot.objects.push(object);+ continue;+ }+ match catalog.source(&object.version.identity).await {+ Ok(reply) => {+ object.source = Some(reply.object.source.clone());+ match check_source(catalog, &snapshot.endpoint, &object.version.identity, &reply, origin).await {+ Ok(()) => {+ // A second full read also detects replacement within LAST_DDL_TIME's second.+ match catalog.source(&object.version.identity).await {+ Ok(second)+ if second.flags.check().is_ok()+ && second.object.name == reply.object.name+ && second.object.schema == reply.object.schema+ && second.object.object_type == reply.object.object_type+ && second.object.source == reply.object.source =>+ {+ object.source_complete = true+ }+ Ok(_) => object+ .issues+ .push(issue("source", "Routine source changed or became incomplete during collection")),+ Err(error) => object.issues.push(issue("source", error)),+ }+ }+ Err(error) => object.issues.push(issue("source", error)),+ }+ }+ Err(error) => object.issues.push(issue("source", error)),+ }+ match dependencies(catalog, &object.version.identity).await {+ Ok(values) => {+ object.dependencies = values;+ object.dependencies_complete = true;+ }+ Err(error) => object.issues.push(issue("dependencies", error)),+ }+ snapshot.objects.push(object);+ }+ let after_read = inventory(catalog, &snapshot.endpoint.schema, dba).await;+ if let Some(error) = after_read.error {+ snapshot.enumeration_complete = false;+ snapshot.issues.push(issue("inventory", error));+ } else {+ let after = after_read.objects;+ let after_by_name =+ after.iter().map(|version| (object_key(&version.identity), version)).collect::<BTreeMap<_, _>>();+ for object in &mut snapshot.objects {+ if after_by_name.get(&object_key(&object.version.identity)).copied() != Some(&object.version) {+ object.source_complete = false;+ object.dependencies_complete = false;+ object+ .issues+ .push(issue("version", "Routine identity, state or DDL version changed during collection"));+ }+ }+ if initial != after {+ snapshot.enumeration_complete = false;+ snapshot.issues.push(issue(+ "inventory",+ "Routine inventory changed during collection; refresh before inferring absence",+ ));+ for version in after {+ if !initial.iter().any(|before| object_key(&before.identity) == object_key(&version.identity)) {+ snapshot.objects.push(RoutineObjectSnapshot {+ version,+ source: None,+ source_complete: false,+ dependencies: Vec::new(),+ dependencies_complete: false,+ issues: vec![issue(+ "source",+ "Routine appeared after the initial inventory; refresh to read its definition",+ )],+ });+ }+ }+ }+ }+ snapshot.state = if snapshot.enumeration_complete+ && snapshot.objects.iter().all(|object| object.source_complete && object.dependencies_complete)+ {+ RoutineReadState::Complete+ } else if snapshot.objects.is_empty() && snapshot.issues.iter().any(|issue| issue.code == "permission-denied") {+ RoutineReadState::PermissionDenied+ } else if snapshot.objects.is_empty() && !snapshot.enumeration_complete {+ RoutineReadState::Failed+ } else {+ RoutineReadState::Partial+ };+ snapshot+}++#[cfg(test)]+mod tests;diff --git a/crates/dbx-core/src/schema/oracle_routines/execution.rs b/crates/dbx-core/src/schema/oracle_routines/execution.rsnew file mode 100644index 0000000000..6cc53d19d6--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/execution.rs@@ -0,0 +1,397 @@+use super::operations::{BeginRoutineOperation, RoutineWriteBinding};+use super::*;+use crate::connection::session_credentials::{current_credential_owner, with_credential_owner};+use crate::db::agent_driver::{AgentCallError, AgentErrorCategory, AgentErrorStage, AgentOperationOutcome};+use crate::query::query_cancel::RunningTaskMetadata;+use crate::query::{execute_sql_statement_with_options_typed, QueryExecutionError};+use dbx_sql::object_source_sql::{validate_oracle_routine_target_definition, EditableObjectSourceSqlInput};+use std::sync::Arc;+use tokio_util::sync::CancellationToken;++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleRoutineSaveInput {+ pub connection_id: String,+ pub database: String,+ pub identity: RoutineIdentity,+ pub sql: String,+ #[serde(default)]+ pub supersedes_operation_id: Option<String>,+}++/// Ordinary saves retain their existing permission contract. In particular this+/// path does not ask for global inbound-dependency visibility.+pub async fn prepare_oracle_routine_save_core(+ state: &AppState,+ input: OracleRoutineSaveInput,+) -> Result<RoutineOperationRecord, String> {+ prepare_definition(state, input, false).await+}++pub(super) fn prepare_bound_definition_pinned(+ state: &AppState,+ input: OracleRoutineSaveInput,+ config: ConnectionConfig,+ generation: u64,+ require_absent: bool,+) -> Result<(RoutineOperationRecord, operations::RoutineOperationPin<'_>), String> {+ let record = prepare_bound_definition_with_pins(state, input, config, generation, require_absent, 1)?;+ let pin = state.routine_operations.adopt_pin(&record.operation_id);+ Ok((record, pin))+}++pub(super) async fn prepare_definition(+ state: &AppState,+ input: OracleRoutineSaveInput,+ require_absent: bool,+) -> Result<RoutineOperationRecord, String> {+ let config = connection_config(state, &input.connection_id).await.ok_or("Connection not found")?;+ let generation = state.connection_lifecycle_snapshot(&input.connection_id).generation();+ prepare_bound_definition(state, input, config, generation, require_absent)+}++pub(super) fn prepare_bound_definition(+ state: &AppState,+ input: OracleRoutineSaveInput,+ config: ConnectionConfig,+ generation: u64,+ require_absent: bool,+) -> Result<RoutineOperationRecord, String> {+ prepare_bound_definition_with_pins(state, input, config, generation, require_absent, 0)+}++fn prepare_bound_definition_with_pins(+ state: &AppState,+ input: OracleRoutineSaveInput,+ config: ConnectionConfig,+ generation: u64,+ require_absent: bool,+ pins: usize,+) -> Result<RoutineOperationRecord, String> {+ let (database_type, _) = routine_source_origin(&config)?;+ if input.identity.owner.is_empty() || input.identity.name.is_empty() {+ return Err("A routine write requires its exact original owner and name".into());+ }+ validate_oracle_routine_target_definition(+ EditableObjectSourceSqlInput {+ database_type,+ object_type: input.identity.kind.clone(),+ schema: Some(input.identity.owner.clone()),+ name: input.identity.name.clone(),+ source: input.sql.clone(),+ },+ require_absent.then_some(false),+ )?;+ let target = RoutineEndpoint {+ connection_id: input.connection_id,+ database: input.database,+ schema: input.identity.owner.clone(),+ database_type,+ generation,+ };+ let mut records = state.routine_operations.prepare_batch(+ vec![operations::PreparedRoutineWrite {+ operation_id: uuid::Uuid::new_v4().to_string(),+ binding: RoutineWriteBinding {+ target,+ identity: input.identity,+ goal: RoutineReadbackGoal::Definition { sql: input.sql.clone() },+ sql: input.sql,+ expected_config: config,+ require_absent,+ compare: None,+ prerequisite_operation_ids: Vec::new(),+ },+ supersedes: input.supersedes_operation_id,+ }],+ pins,+ )?;+ Ok(records.remove(0))+}++/// The caller already knows operationId from preparation. Dropping its HTTP or+/// desktop wait cannot drop the spawned database operation or cause a replay.+pub async fn execute_oracle_routine_operation_core(+ state: Arc<AppState>,+ operation_id: String,+ approved_sql: String,+) -> Result<RoutineOperationRecord, String> {+ let binding = match state.routine_operations.begin(&operation_id, &approved_sql)? {+ BeginRoutineOperation::Existing(record) => return Ok(*record),+ BeginRoutineOperation::Dispatch(binding) => *binding,+ };+ let owner_scope = current_credential_owner();+ let _response_pin = state.routine_operations.adopt_pin(&operation_id);+ let app = state.clone();+ let id = operation_id.clone();+ let (tx, rx) = tokio::sync::oneshot::channel();+ tokio::spawn(with_credential_owner(owner_scope, async move {+ let _worker_pin = app.routine_operations.adopt_pin(&id);+ perform_write(&app, &id, binding).await;+ let _ = tx.send(());+ }));+ // This bounds only the response wait. The registry remains Running until+ // the original worker obtains its own result, even if the client times out.+ let _ = tokio::time::timeout(std::time::Duration::from_secs(30), rx).await;+ state+ .routine_operations+ .observe(&operation_id)+ .operation+ .ok_or_else(|| "Routine operation is unavailable; do not replay".into())+}++async fn perform_write(state: &AppState, id: &str, binding: RoutineWriteBinding) {+ let lifecycle = state.connection_lifecycle_snapshot(&binding.target.connection_id);+ let mut metadata =+ RunningTaskMetadata::query(binding.target.connection_id.clone(), binding.target.database.clone(), None);+ metadata.owner_scope = current_credential_owner();+ let registered = state.running_queries.register_task_for_terminal_confirmation_with_parent(+ id.into(),+ metadata,+ lifecycle.cancellation(),+ );+ let io = LiveWriter {+ catalog: LiveCatalog { state, endpoint: &binding.target, config: &binding.expected_config },+ cancellation: registered.token(),+ execution_id: id,+ };+ let (_, origin) =+ routine_source_origin(&binding.expected_config).expect("preparation accepted this routine engine");+ if let Some(compare) = &binding.compare {+ let mut guard = WriteGuard { registry: &state.routine_operations, id, complete: false };+ let source = compare.source.as_ref().map(|before| LiveCatalog {+ state,+ endpoint: &before.endpoint,+ config: &before.config,+ });+ let check = plan::verify_compare_preflight(source.as_ref(), &io, &binding.target, compare, origin).await;+ if let Err(error) = check {+ state.routine_operations.not_started(id, error);+ guard.complete = true;+ return;+ }+ guard.complete = true;+ }+ run_write(&state.routine_operations, id, &binding, &io, origin).await;+ drop(registered);+}++/// The transfer runner already owns a server-side task independent of the UI.+/// Reuse that lifetime instead of requiring Arc at the legacy Core entry point.+pub(super) async fn execute_prepared_inline(+ state: &AppState,+ operation_id: &str,+ approved_sql: &str,+) -> Result<RoutineOperationRecord, String> {+ let binding = match state.routine_operations.begin(operation_id, approved_sql)? {+ BeginRoutineOperation::Existing(record) => return Ok(*record),+ BeginRoutineOperation::Dispatch(binding) => *binding,+ };+ let _response_pin = state.routine_operations.adopt_pin(operation_id);+ let _worker_pin = state.routine_operations.adopt_pin(operation_id);+ perform_write(state, operation_id, binding).await;+ state+ .routine_operations+ .observe(operation_id)+ .operation+ .ok_or_else(|| "Original routine operation is unavailable; do not replay".into())+}++pub async fn observe_oracle_routine_operation_core(+ state: &AppState,+ operation_id: &str,+ refresh_readback: bool,+) -> RoutineOperationObservation {+ let _readback_pin = refresh_readback.then(|| state.routine_operations.pin(operation_id).ok()).flatten();+ if _readback_pin.is_some() {+ if let Ok(binding) = state.routine_operations.binding_for_readback(operation_id) {+ let catalog = LiveCatalog { state, endpoint: &binding.target, config: &binding.expected_config };+ if let Ok((_, origin)) = routine_source_origin(&binding.expected_config) {+ let current =+ readback::readback(&catalog, &binding.target, binding.identity.clone(), &binding.goal, origin)+ .await;+ // Updating current contents deliberately does not change lifecycle.+ state.routine_operations.update_readback(operation_id, current);+ }+ }+ }+ state.routine_operations.observe(operation_id)+}++#[async_trait::async_trait]+trait RoutineWriteIo: RoutineCatalog {+ async fn check_write(&self, sql: &str) -> Result<(), String>;+ async fn write(&self, sql: &str) -> Result<db::QueryResult, QueryExecutionError>;+}++struct LiveWriter<'a> {+ catalog: LiveCatalog<'a>,+ cancellation: CancellationToken,+ execution_id: &'a str,+}++#[async_trait::async_trait]+impl RoutineCatalog for LiveWriter<'_> {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ self.catalog.query(sql).await+ }+ async fn source(&self, identity: &RoutineIdentity) -> Result<SourceReply, String> {+ self.catalog.source(identity).await+ }+}++#[async_trait::async_trait]+impl RoutineWriteIo for LiveWriter<'_> {+ async fn check_write(&self, sql: &str) -> Result<(), String> {+ self.catalog.check_endpoint().await?;+ crate::query::check_read_only_for_connection(self.catalog.state, &self.catalog.endpoint.connection_id, sql)+ .await+ }+ async fn write(&self, sql: &str) -> Result<db::QueryResult, QueryExecutionError> {+ execute_sql_statement_with_options_typed(+ self.catalog.state,+ &self.catalog.endpoint.connection_id,+ &self.catalog.endpoint.database,+ sql,+ Some(&self.catalog.endpoint.schema),+ Some(self.cancellation.clone()),+ QueryExecutionOptions {+ timeout_secs: Some(0),+ await_cancel_completion: true,+ execution_id: Some(self.execution_id.into()),+ ..Default::default()+ },+ )+ .await+ }+}++struct WriteGuard<'a> {+ registry: &'a RoutineOperationRegistry,+ id: &'a str,+ complete: bool,+}+impl Drop for WriteGuard<'_> {+ fn drop(&mut self) {+ if !self.complete {+ self.registry.waiting_lost(+ self.id,+ "Original routine execution worker ended without terminal evidence; do not replay".into(),+ );+ }+ }+}++#[derive(Debug, PartialEq, Eq)]+enum WriteFailure {+ NotStarted,+ Terminal,+ Unproven,+}++fn classify_write_failure(error: &QueryExecutionError) -> WriteFailure {+ match error {+ QueryExecutionError::Agent(error) if error.operation_outcome() == AgentOperationOutcome::NotStarted => {+ WriteFailure::NotStarted+ }+ QueryExecutionError::Canceled { operation_outcome: AgentOperationOutcome::NotStarted, .. } => {+ WriteFailure::NotStarted+ }+ QueryExecutionError::Sql(_) | QueryExecutionError::SqlWithPosition { .. } => WriteFailure::Terminal,+ QueryExecutionError::Agent(AgentCallError::Structured { context, .. })+ if context.category == AgentErrorCategory::Sql+ && matches!(context.stage, AgentErrorStage::Execute | AgentErrorStage::Fetch) =>+ {+ WriteFailure::Terminal+ }+ _ => WriteFailure::Unproven,+ }+}++async fn run_write(+ registry: &RoutineOperationRegistry,+ id: &str,+ binding: &RoutineWriteBinding,+ io: &impl RoutineWriteIo,+ origin: SourceOrigin,+) {+ let mut guard = WriteGuard { registry, id, complete: false };+ let preflight: Result<(), String> = async {+ io.check_write(&binding.sql).await?;+ if binding.require_absent {+ let before = readback::readback(+ io,+ &binding.target,+ binding.identity.clone(),+ &RoutineReadbackGoal::Inspect,+ origin,+ )+ .await;+ if before.exists != Some(false) || !before.issues.is_empty() {+ return Err("Routine target is not confirmed absent; preserve the draft and read a new preview".into());+ }+ }+ for (prerequisite, before) in registry.prerequisites_for_write(id)? {+ let current = readback::readback(+ io,+ &prerequisite.target,+ prerequisite.identity.clone(),+ &prerequisite.goal,+ origin,+ ).await;+ if current.state != RoutineReadbackState::Verified+ || !current.issues.is_empty()+ || current.exists != before.exists+ || current.version != before.version+ || current.source != before.source+ || current.compiler_messages != before.compiler_messages+ {+ return Err(format!(+ "Prerequisite routine {}.{} changed since its verified deployment; refresh and validate the remaining draft without replaying completed steps",+ prerequisite.identity.owner, prerequisite.identity.name,+ ));+ }+ }+ io.check_write(&binding.sql).await?;+ Ok(())+ }+ .await;+ if let Err(error) = preflight {+ registry.not_started(id, error);+ guard.complete = true;+ return;+ }+ if let Err(error) = registry.mark_dispatched(id) {+ registry.waiting_lost(id, error);+ guard.complete = true;+ return;+ }+ let result = io.write(&binding.sql).await;+ let (acknowledged, error, failure) = match result {+ Ok(result) => {+ let error = result+ .messages+ .iter()+ .find(|message| message.severity.eq_ignore_ascii_case("ERROR"))+ .map(|message| message.message.clone());+ (error.is_none(), error, WriteFailure::Terminal)+ }+ Err(error) => (false, Some(error.to_string()), classify_write_failure(&error)),+ };+ match failure {+ WriteFailure::NotStarted => registry.not_started(id, error.expect("NotStarted is an error")),+ WriteFailure::Unproven => registry.waiting_lost(id, error.expect("Unproven is an error")),+ WriteFailure::Terminal => {+ // Receipt/terminal evidence belongs to the write itself. A later+ // metadata timeout or dropped readback must not erase that fact.+ registry.terminal(id, acknowledged, None, error.clone());+ let current =+ readback::readback(io, &binding.target, binding.identity.clone(), &binding.goal, origin).await;+ registry.terminal(id, acknowledged, Some(current), error);+ }+ }+ guard.complete = true;+}++#[cfg(test)]+mod tests;diff --git a/crates/dbx-core/src/schema/oracle_routines/execution/tests.rs b/crates/dbx-core/src/schema/oracle_routines/execution/tests.rsnew file mode 100644index 0000000000..03290eab25--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/execution/tests.rs@@ -0,0 +1,513 @@+use super::*;+use serde_json::json;+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::Mutex;++const SOURCE: &str = "CREATE OR REPLACE FUNCTION \"Read.Func\" RETURN NUMBER AS BEGIN RETURN 1; END";++#[tokio::test]+async fn actual_execute_entry_pins_terminal_readback_through_cancel_or_final_response() {+ use crate::db::agent_driver::{AgentDriverClient, AgentLaunchSpec, AgentRuntimeClient};+ struct RuntimeGuard(Arc<AgentRuntimeClient>);+ impl Drop for RuntimeGuard {+ fn drop(&mut self) {+ self.0.kill();+ }+ }+ async fn wait_for(path: &std::path::Path) {+ tokio::time::timeout(std::time::Duration::from_secs(10), async {+ while !path.exists() {+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ })+ .await+ .expect("fake Agent did not reach the controlled readback barrier");+ }+ for cancel_waiter in [false, true] {+ let dir = tempfile::tempdir().unwrap();+ let script = dir.path().join("routine-agent.py");+ let root = serde_json::to_string(&dir.path().to_string_lossy()).unwrap();+ let source = serde_json::to_string(SOURCE).unwrap();+ std::fs::write(&script, r#"import json, pathlib, sys, time+root = pathlib.Path(__ROOT__)+source = __SOURCE__+writes = 0+print(json.dumps({'ready': True}), flush=True)+for line in sys.stdin:+ req = json.loads(line)+ method = req['method']+ params = req.get('params', {})+ sql = params.get('sql', '')+ if method == 'handshake':+ result = {'protocolVersion': 2, 'agentProtocolVersion': 2, 'capabilities': ['multi_session']}+ elif method in ('validate_session', 'validate_connection', 'close_session', 'set_schema'):+ result = {}+ elif method.replace('_', '').lower() == 'getobjectsource':+ result = {'name': 'Read.Func', 'schema': 'OWNER', 'object_type': 'FUNCTION', 'source': source}+ elif sql:+ if sql.lstrip().upper().startswith('CREATE'):+ writes += 1+ (root / 'writes').write_text(str(writes))+ result = {'columns': [], 'rows': [], 'affected_rows': 0, 'execution_time_ms': 1}+ else:+ if writes and not (root / 'release').exists():+ (root / 'readback-entered').touch()+ while not (root / 'release').exists(): time.sleep(0.01)+ if 'LOGIN_OWNER' in sql:+ columns, rows = ['LOGIN_OWNER'], [['OWNER']]+ elif 'ALL_ERRORS' in sql:+ columns, rows = ['SEQUENCE', 'ATTRIBUTE', 'LINE', 'POSITION', 'TEXT'], []+ elif 'SOURCE_ROWS' in sql:+ columns = ['SOURCE_ROWS', 'FIRST_LINE', 'LAST_LINE', 'SOURCE_CHARS', 'HEAD_TRIM', 'TAIL_TRIM', 'SOURCE_HEAD']+ rows = [[1, 1, 1, len(source.removeprefix('CREATE OR REPLACE ')), 0, 0, 'FUNCTION']]+ elif 'ALL_OBJECTS' in sql:+ columns = ['OWNER', 'OBJECT_NAME', 'OBJECT_TYPE', 'OBJECT_ID', 'STATUS', 'LAST_DDL_TIME']+ rows = [['OWNER', 'Read.Func', 'FUNCTION', 12, 'VALID', '2026-10-21T08:30:00']]+ else:+ raise RuntimeError('unexpected fake metadata query')+ result = {'columns': columns, 'rows': rows}+ else:+ (root / 'unexpected-method').write_text(method)+ print(json.dumps({'jsonrpc': '2.0', 'id': req['id'], 'error': {'code': -1, 'message': 'unexpected fake Agent method'}}), flush=True)+ continue+ print(json.dumps({'jsonrpc': '2.0', 'id': req['id'], 'result': result}), flush=True)+"#.replace("__ROOT__", &root).replace("__SOURCE__", &source)).unwrap();+ let python = if cfg!(windows) { "python" } else { "python3" };+ let runtime = AgentRuntimeClient::spawn(+ AgentLaunchSpec::new(python).with_args([script.to_string_lossy().to_string()]),+ "test",+ )+ .await+ .unwrap();+ let _runtime_guard = RuntimeGuard(runtime.clone());+ let storage = crate::persistence::test_storage::open(&dir.path().join("storage.db")).await.unwrap();+ let state = Arc::new(AppState::new(storage));+ let bound = binding();+ state.configs.write().await.insert("target".into(), bound.expected_config);+ state+ .update_connection_pools(|pools| {+ for key in ["target:tenant", "target:tenant:role:metadata"] {+ runtime.increment_session_count();+ pools.insert(+ key.into(),+ PoolKind::agent(AgentDriverClient::shared_session(runtime.clone(), "routine-test".into())),+ );+ }+ })+ .await;+ let approval = prepare_oracle_routine_save_core(+ &state,+ OracleRoutineSaveInput {+ connection_id: "target".into(),+ database: "tenant".into(),+ identity: bound.identity,+ sql: SOURCE.into(),+ supersedes_operation_id: None,+ },+ )+ .await+ .unwrap();+ state.routine_operations.update_references(std::slice::from_ref(&approval.operation_id), &[]).unwrap();+ let waiter = tokio::spawn(execute_oracle_routine_operation_core(+ state.clone(),+ approval.operation_id.clone(),+ SOURCE.into(),+ ));+ wait_for(&dir.path().join("readback-entered")).await;+ let paused = state.routine_operations.observe(&approval.operation_id).operation.unwrap();+ assert_eq!(paused.lifecycle, RoutineOperationLifecycle::Terminal);+ assert!(paused.dispatched && paused.acknowledged && paused.readback.is_none());+ state.routine_operations.update_references(&[], std::slice::from_ref(&approval.operation_id)).unwrap();+ assert!(state.routine_operations.observe(&approval.operation_id).operation.is_some());+ let waiter = if cancel_waiter {+ waiter.abort();+ assert!(waiter.await.unwrap_err().is_cancelled());+ state.routine_operations.update_references(&[], &[]).unwrap();+ assert!(state.routine_operations.observe(&approval.operation_id).operation.is_some());+ None+ } else {+ Some(waiter)+ };+ std::fs::write(dir.path().join("release"), b"").unwrap();+ if let Some(waiter) = waiter {+ let final_record = waiter.await.unwrap().unwrap();+ assert!(final_record.verified());+ }+ tokio::time::timeout(std::time::Duration::from_secs(10), async {+ while state.routine_operations.observe(&approval.operation_id).operation.is_some() {+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ })+ .await+ .expect("operation was not reclaimed after the last worker/response pin");+ assert_eq!(std::fs::read_to_string(dir.path().join("writes")).unwrap(), "1");+ }+}++struct Io {+ name: String,+ source_text: String,+ object_id: u64,+ endpoint_current: bool,+ exists: AtomicBool,+ invalid: bool,+ failure: Option<QueryExecutionError>,+ writes: AtomicUsize,+ queries: Mutex<Vec<String>>,+ wait: bool,+ entered: tokio::sync::Notify,+ block_readback: bool,+ readback_entered: tokio::sync::Notify,+}++impl Default for Io {+ fn default() -> Self {+ Self {+ name: "Read.Func".into(),+ source_text: SOURCE.into(),+ object_id: 12,+ endpoint_current: true,+ exists: AtomicBool::new(true),+ invalid: false,+ failure: None,+ writes: AtomicUsize::new(0),+ queries: Mutex::new(Vec::new()),+ wait: false,+ entered: tokio::sync::Notify::new(),+ block_readback: false,+ readback_entered: tokio::sync::Notify::new(),+ }+ }+}++#[async_trait::async_trait]+impl RoutineCatalog for Io {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ if self.block_readback && self.writes.load(Ordering::SeqCst) > 0 {+ self.readback_entered.notify_one();+ std::future::pending::<()>().await;+ }+ self.queries.lock().unwrap().push(sql.into());+ let (columns, rows) = if sql.contains("LOGIN_OWNER") {+ (vec!["LOGIN_OWNER"], vec![vec![json!("OWNER")]])+ } else if sql.contains("ALL_ERRORS") {+ (+ vec!["SEQUENCE", "ATTRIBUTE", "LINE", "POSITION", "TEXT"],+ if self.invalid {+ vec![vec![json!(1), json!("ERROR"), json!(1), json!(72), json!("missing identifier")]]+ } else {+ vec![]+ },+ )+ } else if sql.contains("SOURCE_ROWS") {+ (+ vec!["SOURCE_ROWS", "FIRST_LINE", "LAST_LINE", "SOURCE_CHARS", "HEAD_TRIM", "TAIL_TRIM", "SOURCE_HEAD"],+ vec![vec![+ json!(1),+ json!(1),+ json!(1),+ json!(self.source_text.strip_prefix("CREATE OR REPLACE ").unwrap().chars().count()),+ json!(0),+ json!(0),+ json!("FUNCTION"),+ ]],+ )+ } else if sql.contains("ALL_OBJECTS") {+ (+ vec!["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "STATUS", "LAST_DDL_TIME"],+ if self.exists.load(Ordering::SeqCst) {+ vec![vec![+ json!("OWNER"),+ json!(self.name),+ json!("FUNCTION"),+ json!(self.object_id),+ json!(if self.invalid { "INVALID" } else { "VALID" }),+ json!("2026-10-21T08:30:00"),+ ]]+ } else {+ vec![]+ },+ )+ } else {+ panic!("unexpected query: {sql}")+ };+ Ok(serde_json::from_value(json!({"columns":columns,"rows":rows})).unwrap())+ }+ async fn source(&self, _: &RoutineIdentity) -> Result<SourceReply, String> {+ Ok(serde_json::from_value(+ json!({"name":self.name,"schema":"OWNER","object_type":"FUNCTION","source":self.source_text}),+ )+ .unwrap())+ }+}++#[async_trait::async_trait]+impl RoutineWriteIo for Io {+ async fn check_write(&self, _sql: &str) -> Result<(), String> {+ if self.endpoint_current {+ Ok(())+ } else {+ Err("endpoint changed".into())+ }+ }+ async fn write(&self, sql: &str) -> Result<db::QueryResult, QueryExecutionError> {+ self.writes.fetch_add(1, Ordering::SeqCst);+ self.entered.notify_one();+ if self.wait {+ std::future::pending::<()>().await;+ }+ if let Some(error) = &self.failure {+ return Err(error.clone());+ }+ self.exists.store(!sql.starts_with("DROP "), Ordering::SeqCst);+ Ok(serde_json::from_value(json!({"columns":[],"rows":[],"affected_rows":0,"execution_time_ms":1})).unwrap())+ }+}++fn binding() -> RoutineWriteBinding {+ RoutineWriteBinding {+ target: RoutineEndpoint { connection_id: "target".into(), database: "tenant".into(), schema: "OWNER".into(), database_type: DatabaseType::OceanbaseOracle, generation: 0 },+ identity: RoutineIdentity { owner: "OWNER".into(), name: "Read.Func".into(), kind: db::ObjectSourceKind::Function },+ sql: SOURCE.into(), goal: RoutineReadbackGoal::Definition { sql: SOURCE.into() }, require_absent: false,+ expected_config: serde_json::from_value(json!({"id":"target","name":"test","db_type":DatabaseType::OceanbaseOracle,"host":"localhost","port":2881,"username":"OWNER","password":"","database":null})).unwrap(),+ compare: None, prerequisite_operation_ids: Vec::new(),+ }+}++async fn run(io: &Io, binding: RoutineWriteBinding) -> RoutineOperationRecord {+ let registry = RoutineOperationRegistry::default();+ let operation = registry.prepare(binding.clone());+ registry.begin(&operation.operation_id, &binding.sql).unwrap();+ run_write(®istry, &operation.operation_id, &binding, io, SourceOrigin::OceanBaseDictionary).await;+ registry.observe(&operation.operation_id).operation.unwrap()+}++#[tokio::test]+async fn save_counts_only_valid_full_readback_and_does_not_require_global_dependencies() {+ let io = Io::default();+ assert!(run(&io, binding()).await.verified());+ assert_eq!(io.writes.load(Ordering::SeqCst), 1);+ assert!(!io.queries.lock().unwrap().iter().any(|sql| sql.contains("DBA_")));+ let io = Io { invalid: true, ..Default::default() };+ let operation = run(&io, binding()).await;+ assert!(operation.dispatched && operation.acknowledged);+ assert!(!operation.verified());+ let read = operation.readback.unwrap();+ assert_eq!(read.state, RoutineReadbackState::Invalid);+ assert_eq!(read.compiler_messages[0].position, 72);+}++#[tokio::test]+async fn endpoint_change_or_an_occupied_create_target_does_not_dispatch() {+ let io = Io { endpoint_current: false, ..Default::default() };+ let operation = run(&io, binding()).await;+ assert!(!operation.dispatched);+ assert_eq!(io.writes.load(Ordering::SeqCst), 0);+ let io = Io::default();+ let operation = run(&io, RoutineWriteBinding { require_absent: true, ..binding() }).await;+ assert!(!operation.dispatched);+ assert_eq!(io.writes.load(Ordering::SeqCst), 0);+ let io = Io { exists: AtomicBool::new(false), ..Default::default() };+ assert!(run(&io, RoutineWriteBinding { require_absent: true, ..binding() }).await.verified());+}++#[tokio::test]+async fn lost_transport_is_unproven_even_if_the_object_currently_matches() {+ let io = Io {+ failure: Some(QueryExecutionError::Agent(AgentCallError::Transport { message: "connection lost".into() })),+ ..Default::default()+ };+ let operation = run(&io, binding()).await;+ assert_eq!(operation.lifecycle, RoutineOperationLifecycle::Unproven);+ assert!(operation.dispatched && !operation.acknowledged);+ assert!(operation.readback.is_none());+ assert_eq!(io.writes.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn terminal_sql_error_and_known_not_started_are_distinct_from_unknown() {+ let io =+ Io { failure: Some(QueryExecutionError::Sql("ORA-00955: name is already used".into())), ..Default::default() };+ let operation = run(&io, binding()).await;+ assert_eq!(operation.lifecycle, RoutineOperationLifecycle::Terminal);+ assert!(operation.dispatched && !operation.acknowledged && !operation.verified());+ let io = Io {+ failure: Some(QueryExecutionError::Canceled {+ stage: AgentErrorStage::Checkout,+ operation_outcome: AgentOperationOutcome::NotStarted,+ }),+ ..Default::default()+ };+ let operation = run(&io, binding()).await;+ assert_eq!(operation.lifecycle, RoutineOperationLifecycle::Terminal);+ assert!(!operation.dispatched);+}++#[tokio::test]+async fn an_abandoned_worker_does_not_release_a_possibly_dispatched_target() {+ let io = Arc::new(Io { wait: true, ..Default::default() });+ let registry = Arc::new(RoutineOperationRegistry::default());+ let bound = binding();+ let operation = registry.prepare(bound.clone());+ registry.begin(&operation.operation_id, &bound.sql).unwrap();+ let worker = {+ let io = io.clone();+ let registry = registry.clone();+ let id = operation.operation_id.clone();+ tokio::spawn(+ async move { run_write(®istry, &id, &bound, io.as_ref(), SourceOrigin::OceanBaseDictionary).await },+ )+ };+ io.entered.notified().await;+ worker.abort();+ assert!(worker.await.unwrap_err().is_cancelled());+ assert_eq!(registry.observe(&operation.operation_id).lifecycle, RoutineOperationLifecycle::Unproven);+ let next = registry.prepare(binding());+ assert!(+ matches!(registry.begin(&next.operation_id, SOURCE).unwrap(), BeginRoutineOperation::Existing(record) if record.lifecycle == RoutineOperationLifecycle::Terminal && !record.dispatched)+ );+}++#[tokio::test]+async fn live_preflight_preserves_read_only_policy_and_rejects_a_changed_original_endpoint() {+ let dir = tempfile::tempdir().unwrap();+ let storage = crate::persistence::test_storage::open(&dir.path().join("storage.db")).await.unwrap();+ let state = AppState::new(storage);+ let bound = binding();+ state.configs.write().await.insert("target".into(), bound.expected_config.clone());+ let io = LiveWriter {+ catalog: LiveCatalog { state: &state, endpoint: &bound.target, config: &bound.expected_config },+ cancellation: CancellationToken::new(),+ execution_id: "policy-test",+ };+ assert!(io.check_write(&bound.sql).await.is_ok());+ state.configs.write().await.get_mut("target").unwrap().read_only = true;+ assert!(io.check_write(&bound.sql).await.is_err());+ state.configs.write().await.get_mut("target").unwrap().read_only = false;+ assert!(io.check_write(&bound.sql).await.is_ok());+ state.configs.write().await.get_mut("target").unwrap().host = "changed-endpoint".into();+ assert!(io.check_write(&bound.sql).await.unwrap_err().contains("changed"));+}++#[tokio::test]+async fn losing_only_the_readback_preserves_the_original_terminal_write_receipt() {+ let io = Arc::new(Io { block_readback: true, ..Default::default() });+ let registry = Arc::new(RoutineOperationRegistry::default());+ let bound = binding();+ let operation = registry.prepare(bound.clone());+ registry.begin(&operation.operation_id, &bound.sql).unwrap();+ let worker = {+ let io = io.clone();+ let registry = registry.clone();+ let id = operation.operation_id.clone();+ tokio::spawn(+ async move { run_write(®istry, &id, &bound, io.as_ref(), SourceOrigin::OceanBaseDictionary).await },+ )+ };+ io.readback_entered.notified().await;+ worker.abort();+ assert!(worker.await.unwrap_err().is_cancelled());+ let observed = registry.observe(&operation.operation_id).operation.unwrap();+ assert_eq!(observed.lifecycle, RoutineOperationLifecycle::Terminal);+ assert!(observed.dispatched && observed.acknowledged);+ assert!(!observed.verified());+ assert!(observed.readback.is_none());+}++struct PlanIo {+ prerequisite: Io,+ next: Io,+}++#[async_trait::async_trait]+impl RoutineCatalog for PlanIo {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ if sql.contains("'Read.Func'") {+ self.prerequisite.query(sql).await+ } else {+ self.next.query(sql).await+ }+ }+ async fn source(&self, identity: &RoutineIdentity) -> Result<SourceReply, String> {+ if identity.name == "Read.Func" {+ self.prerequisite.source(identity).await+ } else {+ self.next.source(identity).await+ }+ }+}++#[async_trait::async_trait]+impl RoutineWriteIo for PlanIo {+ async fn check_write(&self, sql: &str) -> Result<(), String> {+ self.next.check_write(sql).await+ }+ async fn write(&self, sql: &str) -> Result<db::QueryResult, QueryExecutionError> {+ self.next.write(sql).await+ }+}++#[tokio::test]+async fn review_regression_completed_prerequisite_is_rechecked_before_the_next_dispatch() {+ for change in ["unchanged", "body", "identity", "status", "deleted", "refreshed-identity", "reappeared"] {+ let registry = RoutineOperationRegistry::default();+ let mut previous = binding();+ if change == "reappeared" {+ previous.sql = "DROP FUNCTION \"OWNER\".\"Read.Func\"".into();+ previous.goal = RoutineReadbackGoal::Absent;+ }+ let first = registry.prepare(previous.clone());+ registry.begin(&first.operation_id, &previous.sql).unwrap();+ let original_io = Io::default();+ run_write(®istry, &first.operation_id, &previous, &original_io, SourceOrigin::OceanBaseDictionary).await;+ assert!(registry.observe(&first.operation_id).operation.unwrap().verified());++ let prerequisite = Io {+ source_text: if change == "body" { SOURCE.replace("RETURN 1", "RETURN 9") } else { SOURCE.into() },+ object_id: if matches!(change, "identity" | "refreshed-identity") { 99 } else { 12 },+ invalid: change == "status",+ exists: AtomicBool::new(change != "deleted"),+ ..Default::default()+ };+ if change == "refreshed-identity" {+ let current = readback::readback(+ &prerequisite,+ &previous.target,+ previous.identity.clone(),+ &previous.goal,+ SourceOrigin::OceanBaseDictionary,+ )+ .await;+ assert_eq!(current.state, RoutineReadbackState::Verified);+ registry.update_readback(&first.operation_id, current);+ }+ let next_source = SOURCE.replace("Read.Func", "Next.Func").replace("RETURN 1", "RETURN \"Read.Func\"");+ let next = RoutineWriteBinding {+ identity: RoutineIdentity { name: "Next.Func".into(), ..binding().identity },+ sql: next_source.clone(),+ goal: RoutineReadbackGoal::Definition { sql: next_source.clone() },+ prerequisite_operation_ids: vec![first.operation_id.clone()],+ ..binding()+ };+ let operation = registry.prepare(next.clone());+ assert!(matches!(+ registry.begin(&operation.operation_id, &next.sql).unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ let io = PlanIo {+ prerequisite,+ next: Io { name: "Next.Func".into(), source_text: next_source, ..Default::default() },+ };+ run_write(®istry, &operation.operation_id, &next, &io, SourceOrigin::OceanBaseDictionary).await;+ let result = registry.observe(&operation.operation_id).operation.unwrap();+ if change == "unchanged" {+ assert!(result.verified(), "{}", result.failure_message());+ assert_eq!(io.next.writes.load(Ordering::SeqCst), 1);+ } else {+ assert!(!result.dispatched, "{change}: the next routine was dispatched after the prerequisite changed");+ assert_eq!(result.lifecycle, RoutineOperationLifecycle::Terminal);+ assert_eq!(io.next.writes.load(Ordering::SeqCst), 0);+ }+ assert_eq!(original_io.writes.load(Ordering::SeqCst), 1, "completed work must not be replayed");+ }+}diff --git a/crates/dbx-core/src/schema/oracle_routines/operations.rs b/crates/dbx-core/src/schema/oracle_routines/operations.rsnew file mode 100644index 0000000000..47030e98a3--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/operations.rs@@ -0,0 +1,573 @@+use super::{RoutineEndpoint, RoutineIdentity, RoutineReadback, RoutineReadbackGoal, RoutineReadbackState};+use crate::connection::session_credentials::current_credential_owner;+use crate::models::connection::ConnectionConfig;+use serde::Serialize;+use std::collections::HashMap;+use std::sync::Mutex;+use std::time::Instant;++mod retention;+use retention::RegistryLimits;+pub(super) use retention::{PreparedRoutineWrite, RoutineOperationPin};++#[derive(Clone, Serialize)]+pub(super) struct RoutineWriteBinding {+ pub target: RoutineEndpoint,+ pub identity: RoutineIdentity,+ pub sql: String,+ pub goal: RoutineReadbackGoal,+ pub expected_config: ConnectionConfig,+ pub require_absent: bool,+ pub compare: Option<super::plan::ComparePreflight>,+ pub prerequisite_operation_ids: Vec<String>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "kebab-case")]+pub enum RoutineOperationLifecycle {+ Prepared,+ Running,+ Terminal,+ Unproven,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineOperationRecord {+ pub operation_id: String,+ pub target: RoutineEndpoint,+ pub identity: RoutineIdentity,+ pub lifecycle: RoutineOperationLifecycle,+ pub dispatched: bool,+ pub acknowledged: bool,+ pub readback: Option<RoutineReadback>,+ pub error: Option<String>,+}++impl RoutineOperationRecord {+ pub fn verified(&self) -> bool {+ self.lifecycle == RoutineOperationLifecycle::Terminal+ && self.dispatched+ && self.acknowledged+ && self.readback.as_ref().is_some_and(|readback| readback.state == RoutineReadbackState::Verified)+ }++ pub fn failure_message(&self) -> String {+ let mut details = vec![format!(+ "Routine {}.{} operation {}: {:?}",+ self.identity.owner, self.identity.name, self.operation_id, self.lifecycle+ )];+ if let Some(error) = &self.error {+ details.push(error.clone());+ }+ if let Some(readback) = &self.readback {+ details.push(format!("Target verification: {:?}", readback.state));+ details.extend(readback.compiler_messages.iter().map(|message| {+ format!("{} {}:{} {}", message.attribute, message.line, message.position, message.text)+ }));+ details.extend(readback.issues.iter().map(|issue| issue.message.clone()));+ }+ details.join("\n")+ }+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineOperationObservation {+ pub operation: Option<RoutineOperationRecord>,+ pub lifecycle: RoutineOperationLifecycle,+ pub error: Option<String>,+}++struct StoredOperation {+ binding: RoutineWriteBinding,+ record: RoutineOperationRecord,+ // Later observations may describe a different version of the same object.+ // Dependents remain bound to the first fully verified deployment result.+ verified_post_state: Option<RoutineReadback>,+ // Web session tokens remain private, in memory, and outside Debug/Serialize.+ owner_scope: Option<String>,+ client_retained: bool,+ unclaimed_until: Option<Instant>,+ inflight: usize,+ charge: usize,+ receipt_floor: usize,+}++pub struct RoutineOperationRegistry {+ operations: Mutex<HashMap<String, StoredOperation>>,+ limits: RegistryLimits,+}++impl Default for RoutineOperationRegistry {+ fn default() -> Self {+ Self { operations: Mutex::new(HashMap::new()), limits: RegistryLimits::default() }+ }+}++pub(super) enum BeginRoutineOperation {+ Dispatch(Box<RoutineWriteBinding>),+ Existing(Box<RoutineOperationRecord>),+}++fn same_namespace_target(left: &RoutineWriteBinding, right: &RoutineWriteBinding) -> bool {+ if left.target.database != right.target.database+ || left.identity.owner != right.identity.owner+ || left.identity.name != right.identity.name+ {+ return false;+ }+ if left.target.connection_id == right.target.connection_id {+ return true;+ }+ // Authentication does not create a separate target namespace. Keep routing+ // fields (including the OB tenant/cluster suffix), not the login account.+ let normalize = |config: &ConnectionConfig| {+ let mut config = config.clone();+ config.id.clear();+ config.password.clear();+ config.save_password = false;+ config.username = if config.db_type == crate::models::connection::DatabaseType::OceanbaseOracle {+ config.username.split_once('@').map(|(_, tenant)| format!("@{tenant}")).unwrap_or_default()+ } else {+ String::new()+ };+ config.sysdba = false;+ config+ };+ crate::connection::connection_configs_session_credentials_compatible(+ &normalize(&left.expected_config),+ &normalize(&right.expected_config),+ )+}++impl RoutineOperationRegistry {+ #[cfg(test)]+ pub(super) fn prepare(&self, binding: RoutineWriteBinding) -> RoutineOperationRecord {+ self.prepare_replacing(binding, None).expect("a new routine approval does not supersede another operation")+ }++ pub(super) fn prepare_replacing(+ &self,+ binding: RoutineWriteBinding,+ supersedes: Option<&str>,+ ) -> Result<RoutineOperationRecord, String> {+ let mut records = self.prepare_batch(+ vec![PreparedRoutineWrite {+ operation_id: uuid::Uuid::new_v4().to_string(),+ binding,+ supersedes: supersedes.map(str::to_owned),+ }],+ 0,+ )?;+ Ok(records.remove(0))+ }++ pub fn observe(&self, operation_id: &str) -> RoutineOperationObservation {+ match self.operations.lock().unwrap_or_else(|error| error.into_inner()).get(operation_id) {+ Some(operation) if operation.owner_scope == current_credential_owner() => RoutineOperationObservation {+ operation: Some(operation.record.clone()),+ lifecycle: operation.record.lifecycle,+ error: operation.record.error.clone(),+ },+ _ => RoutineOperationObservation {+ operation: None,+ lifecycle: RoutineOperationLifecycle::Unproven,+ error: Some("Original routine execution record is unavailable; do not replay the write".into()),+ },+ }+ }++ pub(super) fn begin(&self, operation_id: &str, approved_sql: &str) -> Result<BeginRoutineOperation, String> {+ let mut operations = self.operations.lock().unwrap_or_else(|error| error.into_inner());+ let operation =+ operations.get(operation_id).ok_or("Original routine operation is unavailable; its outcome is unproven")?;+ if operation.owner_scope != current_credential_owner() {+ return Err("Routine operation is unavailable in this authenticated session".into());+ }+ if operation.binding.sql != approved_sql {+ return Err("Routine approval does not match the edited SQL; validate a new draft".into());+ }+ if operation.record.lifecycle != RoutineOperationLifecycle::Prepared {+ return Ok(BeginRoutineOperation::Existing(Box::new(operation.record.clone())));+ }+ if operation.binding.prerequisite_operation_ids.iter().any(|id| {+ !operations.get(id).is_some_and(|prerequisite| {+ prerequisite.owner_scope == operation.owner_scope && prerequisite.record.verified()+ })+ }) {+ self.update_record_locked(&mut operations, operation_id, |record| {+ record.lifecycle = RoutineOperationLifecycle::Terminal;+ record.error = Some("A prerequisite routine step is not verified; validate the remaining draft without replaying completed steps".into());+ });+ return Ok(BeginRoutineOperation::Existing(Box::new(operations[operation_id].record.clone())));+ }+ if let Some(active) = operations.values().find(|other| {+ matches!(other.record.lifecycle, RoutineOperationLifecycle::Running | RoutineOperationLifecycle::Unproven)+ && same_namespace_target(&operation.binding, &other.binding)+ }) {+ let error = if active.owner_scope == operation.owner_scope {+ format!(+ "Routine target is held by operation {}; establish its termination before another write",+ active.record.operation_id+ )+ } else {+ "Routine target has an unresolved operation in another authenticated session".into()+ };+ self.update_record_locked(&mut operations, operation_id, |record| {+ record.lifecycle = RoutineOperationLifecycle::Terminal;+ record.error = Some(error);+ });+ return Ok(BeginRoutineOperation::Existing(Box::new(operations[operation_id].record.clone())));+ }+ let operation = operations.get_mut(operation_id).expect("operation was checked under this lock");+ // One pin belongs to the independent worker, one to its response waiter.+ operation.inflight = operation.inflight.checked_add(2).ok_or("Too many routine operation waiters")?;+ let binding = operation.binding.clone();+ self.update_record_locked(&mut operations, operation_id, |record| {+ record.lifecycle = RoutineOperationLifecycle::Running+ });+ Ok(BeginRoutineOperation::Dispatch(Box::new(binding)))+ }++ pub(super) fn binding_for_readback(&self, operation_id: &str) -> Result<RoutineWriteBinding, String> {+ self.operations+ .lock()+ .unwrap_or_else(|error| error.into_inner())+ .get(operation_id)+ .filter(|operation| operation.owner_scope == current_credential_owner())+ .map(|operation| operation.binding.clone())+ .ok_or_else(|| "Original routine operation is unavailable; do not replay the write".into())+ }++ pub(super) fn prerequisites_for_write(+ &self,+ operation_id: &str,+ ) -> Result<Vec<(RoutineWriteBinding, RoutineReadback)>, String> {+ let operations = self.operations.lock().unwrap_or_else(|error| error.into_inner());+ let operation = operations+ .get(operation_id)+ .filter(|operation| operation.owner_scope == current_credential_owner())+ .ok_or("Original routine operation is unavailable; do not replay the write")?;+ operation.binding.prerequisite_operation_ids.iter().map(|id| {+ let prerequisite = operations.get(id).filter(|prerequisite| {+ prerequisite.owner_scope == operation.owner_scope+ && prerequisite.record.verified()+ && prerequisite.binding.target == operation.binding.target+ && prerequisite.binding.expected_config == operation.binding.expected_config+ }).ok_or("A prerequisite routine has no verified result on the original target; validate the remaining draft")?;+ let before = prerequisite.verified_post_state.clone()+ .ok_or("The prerequisite's verified deployment snapshot is unavailable; do not replay completed steps")?;+ Ok((prerequisite.binding.clone(), before))+ }).collect()+ }++ pub(super) fn mark_dispatched(&self, operation_id: &str) -> Result<(), String> {+ let mut operations = self.operations.lock().unwrap_or_else(|error| error.into_inner());+ let operation = operations.get(operation_id).ok_or("Routine operation record is unavailable")?;+ if operation.record.lifecycle != RoutineOperationLifecycle::Running || operation.record.dispatched {+ return Err("Routine operation is not awaiting its first dispatch".into());+ }+ self.update_record_locked(&mut operations, operation_id, |record| record.dispatched = true);+ Ok(())+ }++ pub(super) fn terminal(+ &self,+ operation_id: &str,+ acknowledged: bool,+ readback: Option<RoutineReadback>,+ error: Option<String>,+ ) {+ self.update_record(operation_id, |record| {+ record.lifecycle = RoutineOperationLifecycle::Terminal;+ record.acknowledged = acknowledged;+ record.readback = readback;+ record.error = error;+ });+ }++ pub(super) fn not_started(&self, operation_id: &str, error: String) {+ self.update_record(operation_id, |record| {+ record.lifecycle = RoutineOperationLifecycle::Terminal;+ record.dispatched = false;+ record.error = Some(error);+ });+ }++ pub(super) fn waiting_lost(&self, operation_id: &str, error: String) {+ self.update_record(operation_id, |record| {+ if record.lifecycle != RoutineOperationLifecycle::Terminal {+ record.lifecycle = if record.dispatched {+ RoutineOperationLifecycle::Unproven+ } else {+ RoutineOperationLifecycle::Terminal+ };+ record.error = Some(error);+ }+ });+ }++ pub(super) fn update_readback(&self, operation_id: &str, readback: RoutineReadback) {+ self.update_record(operation_id, |record| {+ // Current object contents are not evidence that the original request ended.+ record.readback = Some(readback);+ });+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::db::ObjectSourceKind;+ use crate::models::connection::DatabaseType;++ pub(super) fn binding() -> RoutineWriteBinding {+ RoutineWriteBinding { target: RoutineEndpoint { connection_id: "target".into(), database: "tenant".into(), schema: "OWNER".into(), database_type: DatabaseType::OceanbaseOracle, generation: 1 },+ identity: RoutineIdentity { owner: "OWNER".into(), name: "Shared.Name".into(), kind: ObjectSourceKind::Function }, sql: "approved SQL".into(), goal: RoutineReadbackGoal::Inspect,+ expected_config: serde_json::from_value(serde_json::json!({"id":"target", "name":"test", "db_type": DatabaseType::OceanbaseOracle, "host":"localhost", "port":2881, "username":"OWNER", "password":"", "database":null})).unwrap(), require_absent: false, compare: None, prerequisite_operation_ids: Vec::new() }+ }++ pub(super) fn verified_readback() -> RoutineReadback {+ RoutineReadback {+ identity: binding().identity,+ state: RoutineReadbackState::Verified,+ exists: Some(true),+ version: None,+ source: Some("expected source".into()),+ definition_matches: Some(true),+ compiler_messages: Vec::new(),+ issues: Vec::new(),+ }+ }++ #[test]+ fn oversized_approval_is_rejected_without_retaining_its_payload() {+ let registry = RoutineOperationRegistry::default();+ let mut input = binding();+ input.sql = "x".repeat(16 * 1024 * 1024);+ assert!(registry.prepare_replacing(input, None).is_err());+ assert!(registry.operations.lock().unwrap().is_empty());+ }++ #[test]+ fn duplicate_id_returns_the_same_operation_without_a_second_dispatch() {+ let registry = RoutineOperationRegistry::default();+ let operation = registry.prepare(binding());+ assert!(matches!(+ registry.begin(&operation.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ registry.mark_dispatched(&operation.operation_id).unwrap();+ assert!(+ matches!(registry.begin(&operation.operation_id, "approved SQL").unwrap(), BeginRoutineOperation::Existing(record) if record.dispatched)+ );+ assert!(registry.mark_dispatched(&operation.operation_id).is_err());+ assert!(registry.begin(&operation.operation_id, "different SQL").is_err());+ }++ #[test]+ fn namespace_lock_ignores_kind_and_survives_unknown_readback() {+ let registry = RoutineOperationRegistry::default();+ let first = registry.prepare(binding());+ assert!(matches!(+ registry.begin(&first.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ registry.mark_dispatched(&first.operation_id).unwrap();+ registry.waiting_lost(&first.operation_id, "transport ended without terminal evidence".into());+ registry.update_readback(&first.operation_id, verified_readback());+ let other = RoutineWriteBinding {+ identity: RoutineIdentity { kind: ObjectSourceKind::Procedure, ..binding().identity },+ ..binding()+ };+ let second = registry.prepare(other);+ assert!(+ matches!(registry.begin(&second.operation_id, "approved SQL").unwrap(), BeginRoutineOperation::Existing(record) if record.lifecycle == RoutineOperationLifecycle::Terminal && !record.dispatched)+ );+ let observed = registry.observe(&first.operation_id);+ assert_eq!(observed.lifecycle, RoutineOperationLifecycle::Unproven);+ assert!(!observed.operation.unwrap().verified());+ registry.terminal(&first.operation_id, true, Some(verified_readback()), None);+ assert!(+ matches!(registry.begin(&second.operation_id, "approved SQL").unwrap(), BeginRoutineOperation::Existing(record) if !record.dispatched)+ );+ let third = registry.prepare(binding());+ assert!(matches!(+ registry.begin(&third.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ }++ #[test]+ fn lost_record_is_unproven_and_never_becomes_a_new_dispatch() {+ let registry = RoutineOperationRegistry::default();+ assert_eq!(registry.observe("old-operation-id").lifecycle, RoutineOperationLifecycle::Unproven);+ assert!(registry.begin("old-operation-id", "approved SQL").is_err());+ assert!(registry.operations.lock().unwrap().is_empty());+ }++ #[test]+ fn preflight_failure_has_no_dispatch_and_does_not_hold_the_target() {+ let registry = RoutineOperationRegistry::default();+ let first = registry.prepare(binding());+ registry.begin(&first.operation_id, "approved SQL").unwrap();+ registry.waiting_lost(&first.operation_id, "preflight failed before dispatch".into());+ let observed = registry.observe(&first.operation_id).operation.unwrap();+ assert!(!observed.dispatched && !observed.verified());+ assert_eq!(observed.lifecycle, RoutineOperationLifecycle::Terminal);+ let second = registry.prepare(binding());+ assert!(matches!(+ registry.begin(&second.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ }++ #[test]+ fn verified_object_without_write_acknowledgement_does_not_count_as_deployed() {+ let registry = RoutineOperationRegistry::default();+ let operation = registry.prepare(binding());+ registry.begin(&operation.operation_id, "approved SQL").unwrap();+ registry.mark_dispatched(&operation.operation_id).unwrap();+ registry.terminal(&operation.operation_id, false, Some(verified_readback()), Some("DDL was rejected".into()));+ assert!(!registry.observe(&operation.operation_id).operation.unwrap().verified());+ }++ #[tokio::test]+ async fn authenticated_sessions_cannot_observe_or_dispatch_each_others_operations() {+ use crate::connection::session_credentials::with_credential_owner;+ let registry = RoutineOperationRegistry::default();+ let first = with_credential_owner(Some("first-owner".into()), async { registry.prepare(binding()) }).await;+ with_credential_owner(Some("second-owner".into()), async {+ assert!(registry.observe(&first.operation_id).operation.is_none());+ assert!(registry.begin(&first.operation_id, "approved SQL").is_err());+ })+ .await;+ with_credential_owner(Some("first-owner".into()), async {+ assert!(registry.observe(&first.operation_id).operation.is_some());+ })+ .await;+ }++ #[test]+ fn saved_endpoint_aliases_cannot_bypass_an_unknown_namespace_hold() {+ let registry = RoutineOperationRegistry::default();+ let first = registry.prepare(binding());+ registry.begin(&first.operation_id, "approved SQL").unwrap();+ registry.mark_dispatched(&first.operation_id).unwrap();+ registry.waiting_lost(&first.operation_id, "original request is unresolved".into());+ let mut alias = binding();+ alias.target.connection_id = "another-saved-connection".into();+ alias.expected_config.id = alias.target.connection_id.clone();+ alias.expected_config.name = "Different display name".into();+ alias.expected_config.password = "new runtime password".into();+ let second = registry.prepare(alias.clone());+ assert!(+ matches!(registry.begin(&second.operation_id, "approved SQL").unwrap(), BeginRoutineOperation::Existing(record) if !record.dispatched)+ );+ alias.expected_config.host = "different-server".into();+ let separate = registry.prepare(alias);+ assert!(matches!(+ registry.begin(&separate.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ }++ #[test]+ fn review_regression_different_accounts_share_the_same_unknown_object_hold() {+ let registry = RoutineOperationRegistry::default();+ let mut original = binding();+ original.expected_config.username = "FIRST@oracletest".into();+ let first = registry.prepare(original);+ registry.begin(&first.operation_id, "approved SQL").unwrap();+ registry.mark_dispatched(&first.operation_id).unwrap();+ registry.waiting_lost(&first.operation_id, "original request is unresolved".into());++ let mut alias = binding();+ alias.target.connection_id = "other-account".into();+ alias.expected_config.id = alias.target.connection_id.clone();+ alias.expected_config.username = "SECOND@oracletest".into();+ let second = registry.prepare(alias.clone());+ assert!(matches!(+ registry.begin(&second.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Existing(record) if !record.dispatched && record.lifecycle == RoutineOperationLifecycle::Terminal+ ));+ alias.expected_config.host = "different-server".into();+ let separate = registry.prepare(alias.clone());+ assert!(matches!(+ registry.begin(&separate.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ alias.expected_config.host = "localhost".into();+ alias.target.connection_id = "other-tenant".into();+ alias.expected_config.id = alias.target.connection_id.clone();+ alias.expected_config.username = "SECOND@another-tenant".into();+ let other_tenant = registry.prepare(alias);+ assert!(matches!(+ registry.begin(&other_tenant.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ }++ #[test]+ fn review_regression_native_oracle_accounts_do_not_change_the_target_lock() {+ let registry = RoutineOperationRegistry::default();+ let mut original = binding();+ original.target.database_type = DatabaseType::Oracle;+ original.expected_config.db_type = DatabaseType::Oracle;+ original.expected_config.username = "FIRST".into();+ let first = registry.prepare(original.clone());+ registry.begin(&first.operation_id, "approved SQL").unwrap();+ registry.mark_dispatched(&first.operation_id).unwrap();+ registry.waiting_lost(&first.operation_id, "original request is unresolved".into());+ original.target.connection_id = "second-account".into();+ original.expected_config.id = original.target.connection_id.clone();+ original.expected_config.username = "SECOND".into();+ original.expected_config.sysdba = true;+ let second = registry.prepare(original);+ assert!(+ matches!(registry.begin(&second.operation_id, "approved SQL").unwrap(), BeginRoutineOperation::Existing(record) if !record.dispatched)+ );+ }++ #[test]+ fn replacing_an_unstarted_approval_atomically_disables_its_late_execute_request() {+ let registry = RoutineOperationRegistry::default();+ let first = registry.prepare(binding());+ let second = registry.prepare_replacing(binding(), Some(&first.operation_id)).unwrap();+ assert!(+ matches!(registry.begin(&first.operation_id, "approved SQL").unwrap(), BeginRoutineOperation::Existing(record) if !record.dispatched && record.lifecycle == RoutineOperationLifecycle::Terminal)+ );+ assert!(matches!(+ registry.begin(&second.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ registry.mark_dispatched(&second.operation_id).unwrap();+ registry.waiting_lost(&second.operation_id, "original request may still run".into());+ assert!(registry.prepare_replacing(binding(), Some(&second.operation_id)).is_err());+ }++ #[test]+ fn plan_prerequisites_are_enforced_by_core_not_frontend_order() {+ let registry = RoutineOperationRegistry::default();+ let first = registry.prepare(binding());+ let mut dependent = binding();+ dependent.identity.name = "Caller".into();+ dependent.prerequisite_operation_ids = vec![first.operation_id.clone()];+ let early = registry.prepare(dependent.clone());+ assert!(+ matches!(registry.begin(&early.operation_id, "approved SQL").unwrap(), BeginRoutineOperation::Existing(record) if !record.dispatched && record.lifecycle == RoutineOperationLifecycle::Terminal)+ );+ registry.begin(&first.operation_id, "approved SQL").unwrap();+ registry.mark_dispatched(&first.operation_id).unwrap();+ registry.terminal(&first.operation_id, true, Some(verified_readback()), None);+ let approved = registry.prepare(dependent);+ assert!(matches!(+ registry.begin(&approved.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ assert!(+ matches!(registry.begin(&early.operation_id, "approved SQL").unwrap(), BeginRoutineOperation::Existing(record) if !record.dispatched)+ );+ }+}diff --git a/crates/dbx-core/src/schema/oracle_routines/operations/retention.rs b/crates/dbx-core/src/schema/oracle_routines/operations/retention.rsnew file mode 100644index 0000000000..e72ab50e2f--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/operations/retention.rs@@ -0,0 +1,546 @@+use super::*;+use std::collections::HashSet;+use std::io::{self, Write};+use std::time::Duration;++const CAPACITY_ERROR: &str =+ "Routine operation registry capacity exceeded; release unused comparison tasks or reduce the selection";+const RESULT_CAPACITY_ERROR: &str =+ "Routine result exceeds registry capacity; execution facts are retained, read the original operation again";++pub(in crate::schema::oracle_routines) struct RegistryLimits {+ records: usize,+ total: usize,+ single: usize,+}++impl Default for RegistryLimits {+ fn default() -> Self {+ Self { records: 1024, total: 128 * 1024 * 1024, single: 16 * 1024 * 1024 }+ }+}++pub(in crate::schema::oracle_routines) struct PreparedRoutineWrite {+ pub operation_id: String,+ pub binding: RoutineWriteBinding,+ pub supersedes: Option<String>,+}++pub(in crate::schema::oracle_routines) struct RoutineOperationPin<'a> {+ registry: &'a RoutineOperationRegistry,+ operation_id: String,+}++impl Drop for RoutineOperationPin<'_> {+ fn drop(&mut self) {+ let mut operations = self.registry.operations.lock().unwrap_or_else(|error| error.into_inner());+ if let Some(operation) = operations.get_mut(&self.operation_id) {+ operation.inflight = operation.inflight.saturating_sub(1);+ }+ sweep(&mut operations, &HashSet::new());+ }+}++struct ByteCount {+ bytes: usize,+ limit: usize,+}++impl Write for ByteCount {+ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {+ let next = self+ .bytes+ .checked_add(bytes.len())+ .filter(|value| *value <= self.limit)+ .ok_or_else(|| io::Error::other("payload exceeds capacity"))?;+ self.bytes = next;+ Ok(bytes.len())+ }++ fn flush(&mut self) -> io::Result<()> {+ Ok(())+ }+}++fn json_bytes(value: &impl Serialize, limit: usize) -> Result<usize, String> {+ let mut counter = ByteCount { bytes: 0, limit };+ serde_json::to_writer(&mut counter, value).map_err(|_| CAPACITY_ERROR.to_owned())?;+ Ok(counter.bytes)+}++fn fallback_readback(identity: &RoutineIdentity) -> RoutineReadback {+ RoutineReadback {+ identity: identity.clone(),+ state: RoutineReadbackState::ReadbackFailed,+ exists: None,+ version: None,+ source: None,+ definition_matches: None,+ compiler_messages: Vec::new(),+ issues: vec![super::super::issue("capacity", RESULT_CAPACITY_ERROR)],+ }+}++fn charge(+ operation: &StoredOperation,+ record: &RoutineOperationRecord,+ verified: &Option<RoutineReadback>,+ limit: usize,+) -> Result<usize, String> {+ let parts = [+ 256,+ json_bytes(&record.operation_id, limit)?,+ json_bytes(&operation.owner_scope, limit)?,+ json_bytes(&operation.binding, limit)?,+ json_bytes(record, limit)?.max(operation.receipt_floor),+ json_bytes(verified, limit)?,+ ];+ parts.into_iter().try_fold(0usize, |total, value| {+ total.checked_add(value).filter(|total| *total <= limit).ok_or_else(|| CAPACITY_ERROR.into())+ })+}++fn sweep(operations: &mut HashMap<String, StoredOperation>, additional_roots: &HashSet<String>) {+ let now = Instant::now();+ let mut keep = additional_roots.clone();+ let mut pending = Vec::new();+ for (id, operation) in operations.iter() {+ if operation.client_retained+ || operation.inflight > 0+ || matches!(+ operation.record.lifecycle,+ RoutineOperationLifecycle::Running | RoutineOperationLifecycle::Unproven+ )+ || operation.unclaimed_until.is_some_and(|deadline| deadline > now)+ {+ keep.insert(id.clone());+ }+ }+ pending.extend(keep.iter().cloned());+ while let Some(id) = pending.pop() {+ if let Some(operation) = operations.get(&id) {+ for prerequisite in &operation.binding.prerequisite_operation_ids {+ if keep.insert(prerequisite.clone()) {+ pending.push(prerequisite.clone());+ }+ }+ }+ }+ operations.retain(|id, _| keep.contains(id));+}++impl RoutineOperationRegistry {+ pub(in crate::schema::oracle_routines) fn adopt_pin(&self, operation_id: &str) -> RoutineOperationPin<'_> {+ RoutineOperationPin { registry: self, operation_id: operation_id.into() }+ }++ pub(in crate::schema::oracle_routines) fn pin(+ &self,+ operation_id: &str,+ ) -> Result<RoutineOperationPin<'_>, String> {+ let mut operations = self.operations.lock().unwrap_or_else(|error| error.into_inner());+ let operation = operations+ .get_mut(operation_id)+ .filter(|operation| operation.owner_scope == current_credential_owner())+ .ok_or("Original routine operation is unavailable; do not replay the write")?;+ operation.inflight = operation.inflight.checked_add(1).ok_or("Too many routine operation waiters")?;+ Ok(self.adopt_pin(operation_id))+ }++ pub fn update_references(&self, retain: &[String], release: &[String]) -> Result<(), String> {+ if retain.len() > self.limits.records+ || release.len() > self.limits.records+ || retain.iter().chain(release).any(|id| id.len() > 128)+ {+ return Err(CAPACITY_ERROR.into());+ }+ let owner = current_credential_owner();+ let mut operations = self.operations.lock().unwrap_or_else(|error| error.into_inner());+ if retain.iter().any(|id| !operations.get(id).is_some_and(|operation| operation.owner_scope == owner)) {+ return Err("Routine approval is unavailable in this authenticated session".into());+ }+ for id in release {+ if let Some(operation) = operations.get_mut(id).filter(|operation| operation.owner_scope == owner) {+ operation.client_retained = false;+ operation.unclaimed_until = None;+ }+ }+ for id in retain {+ let operation = operations.get_mut(id).expect("validated under the same lock");+ operation.client_retained = true;+ operation.unclaimed_until = None;+ }+ sweep(&mut operations, &HashSet::new());+ Ok(())+ }++ pub(in crate::schema::oracle_routines) fn prepare_batch(+ &self,+ requests: Vec<PreparedRoutineWrite>,+ pins: usize,+ ) -> Result<Vec<RoutineOperationRecord>, String> {+ if requests.is_empty() || requests.len() > self.limits.records {+ return Err(CAPACITY_ERROR.into());+ }+ let owner_scope = current_credential_owner();+ let mut candidates = Vec::with_capacity(requests.len());+ let mut new_ids = HashSet::new();+ let mut supersedes_ids = HashSet::new();+ for request in requests {+ if request.operation_id.len() > 128 || !new_ids.insert(request.operation_id.clone()) {+ return Err("Duplicate or invalid routine approval ID".into());+ }+ if let Some(id) = &request.supersedes {+ if !supersedes_ids.insert(id.clone()) {+ return Err("A routine approval cannot be superseded twice in one plan".into());+ }+ }+ let record = RoutineOperationRecord {+ operation_id: request.operation_id,+ target: request.binding.target.clone(),+ identity: request.binding.identity.clone(),+ lifecycle: RoutineOperationLifecycle::Prepared,+ dispatched: false,+ acknowledged: false,+ readback: None,+ error: None,+ };+ let mut fallback = record.clone();+ fallback.readback = Some(fallback_readback(&record.identity));+ fallback.error = Some(RESULT_CAPACITY_ERROR.into());+ let floor = json_bytes(&record, self.limits.single)?+ .max(json_bytes(&fallback, self.limits.single)?)+ .checked_add(4096)+ .ok_or(CAPACITY_ERROR)?;+ let mut operation = StoredOperation {+ binding: request.binding,+ record,+ verified_post_state: None,+ owner_scope: owner_scope.clone(),+ client_retained: false,+ unclaimed_until: (pins == 0).then(|| Instant::now() + Duration::from_secs(60)),+ inflight: pins,+ charge: 0,+ receipt_floor: floor,+ };+ operation.charge = charge(&operation, &operation.record, &None, self.limits.single)?;+ candidates.push((operation, request.supersedes));+ }+ let mut operations = self.operations.lock().unwrap_or_else(|error| error.into_inner());+ let mut replacements = HashMap::new();+ for (operation, supersedes) in &candidates {+ if operations.contains_key(&operation.record.operation_id) {+ return Err("Routine approval ID already exists".into());+ }+ if let Some(id) = supersedes {+ let original = operations+ .get(id)+ .filter(|operation| operation.owner_scope == owner_scope)+ .ok_or("Original routine approval is unavailable; do not replace its ID")?;+ if !same_namespace_target(&operation.binding, &original.binding) {+ return Err("A new routine draft cannot supersede another target".into());+ }+ if matches!(+ original.record.lifecycle,+ RoutineOperationLifecycle::Running | RoutineOperationLifecycle::Unproven+ ) {+ return Err("Original routine request may still be running; only observe its original ID".into());+ }+ if original.record.lifecycle == RoutineOperationLifecycle::Prepared {+ let mut record = original.record.clone();+ record.lifecycle = RoutineOperationLifecycle::Terminal;+ record.error = Some("Approval was superseded before dispatch".into());+ let bytes = charge(original, &record, &original.verified_post_state, self.limits.single)?;+ replacements.insert(id.clone(), (record, bytes));+ }+ }+ for id in &operation.binding.prerequisite_operation_ids {+ if !new_ids.contains(id)+ && !operations.get(id).is_some_and(|operation| operation.owner_scope == owner_scope)+ {+ return Err("Routine prerequisite approval is unavailable".into());+ }+ }+ }+ // Preserve old inputs until admission succeeds; capacity failure must not+ // invalidate approvals which the caller can still use.+ let mut inputs = supersedes_ids;+ for (operation, _) in &candidates {+ inputs.extend(operation.binding.prerequisite_operation_ids.iter().cloned());+ }+ sweep(&mut operations, &inputs);+ let total = operations+ .iter()+ .map(|(id, operation)| replacements.get(id).map_or(operation.charge, |(_, bytes)| *bytes))+ .chain(candidates.iter().map(|(operation, _)| operation.charge))+ .try_fold(0usize, |total, bytes| {+ total.checked_add(bytes).filter(|total| *total <= self.limits.total).ok_or(CAPACITY_ERROR)+ })?;+ if operations.len() + candidates.len() > self.limits.records || total > self.limits.total {+ return Err(CAPACITY_ERROR.into());+ }+ let mut records = Vec::with_capacity(candidates.len());+ for (id, (record, bytes)) in replacements {+ let original = operations.get_mut(&id).expect("superseded input is protected under the lock");+ original.record = record;+ original.charge = bytes;+ }+ for (operation, _) in candidates {+ records.push(operation.record.clone());+ operations.insert(operation.record.operation_id.clone(), operation);+ }+ Ok(records)+ }++ pub(in crate::schema::oracle_routines) fn update_record(+ &self,+ id: &str,+ update: impl FnOnce(&mut RoutineOperationRecord),+ ) {+ let mut operations = self.operations.lock().unwrap_or_else(|error| error.into_inner());+ self.update_record_locked(&mut operations, id, update);+ }++ pub(super) fn update_record_locked(+ &self,+ operations: &mut HashMap<String, StoredOperation>,+ id: &str,+ update: impl FnOnce(&mut RoutineOperationRecord),+ ) {+ sweep(operations, &HashSet::from([id.to_owned()]));+ let other_bytes = operations+ .iter()+ .filter(|(key, _)| key.as_str() != id)+ .map(|(_, operation)| operation.charge)+ .sum::<usize>();+ let Some(operation) = operations.get_mut(id) else {+ return;+ };+ let mut record = operation.record.clone();+ update(&mut record);+ let verified = if operation.verified_post_state.is_none() && record.verified() {+ record.readback.clone()+ } else {+ operation.verified_post_state.clone()+ };+ let limit = self.limits.single.min(self.limits.total.saturating_sub(other_bytes));+ match charge(operation, &record, &verified, limit) {+ Ok(bytes) => {+ operation.record = record;+ operation.verified_post_state = verified;+ operation.charge = bytes;+ }+ Err(_) => {+ record.readback = Some(fallback_readback(&record.identity));+ record.error = Some(RESULT_CAPACITY_ERROR.into());+ // The prepared floor reserves this bounded result, including+ // immutable identity copies and the original verified snapshot.+ operation.charge = charge(operation, &record, &operation.verified_post_state, self.limits.single)+ .expect("bounded receipt fits the approval's reserved floor");+ operation.record = record;+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::super::tests::{binding, verified_readback};+ use super::*;++ fn request(id: &str, supersedes: Option<&str>) -> PreparedRoutineWrite {+ PreparedRoutineWrite { operation_id: id.into(), binding: binding(), supersedes: supersedes.map(str::to_owned) }+ }++ #[tokio::test]+ async fn reference_updates_are_owner_isolated_and_invalid_retains_are_atomic() {+ use crate::connection::session_credentials::with_credential_owner;+ let registry = RoutineOperationRegistry::default();+ let first = with_credential_owner(Some("first".into()), async {+ let record = registry.prepare(binding());+ registry.update_references(std::slice::from_ref(&record.operation_id), &[]).unwrap();+ record+ })+ .await;+ with_credential_owner(Some("second".into()), async {+ let second = registry.prepare(binding());+ let third = registry.prepare(binding());+ registry.update_references(std::slice::from_ref(&second.operation_id), &[]).unwrap();+ assert!(registry+ .update_references(+ &[third.operation_id.clone(), first.operation_id.clone()],+ std::slice::from_ref(&second.operation_id)+ )+ .is_err());+ assert!(registry+ .update_references(+ &[third.operation_id.clone(), "missing".into()],+ std::slice::from_ref(&second.operation_id)+ )+ .is_err());+ {+ let operations = registry.operations.lock().unwrap();+ assert!(operations[&second.operation_id].client_retained);+ assert!(!operations[&third.operation_id].client_retained);+ }+ registry.update_references(&[], std::slice::from_ref(&first.operation_id)).unwrap();+ assert!(registry.observe(&first.operation_id).operation.is_none());+ })+ .await;+ with_credential_owner(Some("first".into()), async {+ assert!(registry.observe(&first.operation_id).operation.is_some());+ assert!(registry.operations.lock().unwrap()[&first.operation_id].client_retained);+ })+ .await;+ }++ #[test]+ fn release_reclaims_unused_approval_and_missing_id_never_replays() {+ let registry = RoutineOperationRegistry::default();+ let record = registry.prepare(binding());+ registry.update_references(&[], std::slice::from_ref(&record.operation_id)).unwrap();+ assert!(registry.observe(&record.operation_id).operation.is_none());+ assert!(registry.begin(&record.operation_id, "approved SQL").is_err());+ }++ #[test]+ fn retained_approval_and_prerequisite_closure_survive_until_last_reference() {+ let registry = RoutineOperationRegistry::default();+ let first = registry.prepare(binding());+ let mut next = binding();+ next.prerequisite_operation_ids.push(first.operation_id.clone());+ let second = registry.prepare(next);+ registry+ .update_references(std::slice::from_ref(&second.operation_id), std::slice::from_ref(&first.operation_id))+ .unwrap();+ assert!(registry.observe(&first.operation_id).operation.is_some());+ registry.update_references(&[], std::slice::from_ref(&second.operation_id)).unwrap();+ assert!(registry.operations.lock().unwrap().is_empty());+ }++ #[test]+ fn unclaimed_grace_expires_but_client_reference_does_not() {+ let registry = RoutineOperationRegistry::default();+ let orphan = registry.prepare(binding());+ let retained = registry.prepare(binding());+ registry.update_references(std::slice::from_ref(&retained.operation_id), &[]).unwrap();+ {+ let mut operations = registry.operations.lock().unwrap();+ operations.get_mut(&orphan.operation_id).unwrap().unclaimed_until =+ Some(Instant::now() - Duration::from_secs(1));+ }+ registry.update_references(&[], &[]).unwrap();+ assert!(registry.observe(&orphan.operation_id).operation.is_none());+ assert!(registry.observe(&retained.operation_id).operation.is_some());+ }++ #[test]+ fn worker_and_response_pins_cover_terminal_readback_and_final_clone() {+ let registry = RoutineOperationRegistry::default();+ let record = registry.prepare(binding());+ assert!(matches!(+ registry.begin(&record.operation_id, "approved SQL").unwrap(),+ BeginRoutineOperation::Dispatch(_)+ ));+ let worker = registry.adopt_pin(&record.operation_id);+ let response = registry.adopt_pin(&record.operation_id);+ registry.mark_dispatched(&record.operation_id).unwrap();+ registry.terminal(&record.operation_id, true, None, None);+ registry.update_references(&[], std::slice::from_ref(&record.operation_id)).unwrap();+ assert!(registry.observe(&record.operation_id).operation.is_some());+ registry.update_readback(&record.operation_id, verified_readback());+ drop(worker);+ let final_record = registry.observe(&record.operation_id).operation.unwrap();+ assert!(final_record.verified());+ drop(response);+ assert!(registry.observe(&record.operation_id).operation.is_none());+ assert!(final_record.verified());+ }++ #[test]+ fn unproven_is_not_reclaimed_when_waiters_and_client_release() {+ let registry = RoutineOperationRegistry::default();+ let record = registry.prepare(binding());+ registry.begin(&record.operation_id, "approved SQL").unwrap();+ let worker = registry.adopt_pin(&record.operation_id);+ let response = registry.adopt_pin(&record.operation_id);+ registry.mark_dispatched(&record.operation_id).unwrap();+ registry.waiting_lost(&record.operation_id, "outcome unknown".into());+ registry.update_references(&[], std::slice::from_ref(&record.operation_id)).unwrap();+ drop(worker);+ drop(response);+ assert_eq!(registry.observe(&record.operation_id).lifecycle, RoutineOperationLifecycle::Unproven);+ }++ #[test]+ fn batch_capacity_failure_leaves_no_partial_insert_or_supersede() {+ let mut registry = RoutineOperationRegistry::default();+ registry.limits.records = 2;+ let original = registry.prepare(binding());+ assert!(registry+ .prepare_batch(vec![request("new-one", Some(&original.operation_id)), request("new-two", None)], 0)+ .is_err());+ assert_eq!(registry.operations.lock().unwrap().len(), 1);+ assert_eq!(registry.observe(&original.operation_id).lifecycle, RoutineOperationLifecycle::Prepared);+ assert!(registry.observe("new-one").operation.is_none());+ }++ #[test]+ fn ordinary_hundred_step_batch_does_not_reserve_sixteen_mib_per_step() {+ let registry = RoutineOperationRegistry::default();+ let records =+ registry.prepare_batch((0..100).map(|index| request(&format!("step-{index}"), None)).collect(), 0).unwrap();+ assert_eq!(records.len(), 100);+ let retained_bytes =+ registry.operations.lock().unwrap().values().map(|operation| operation.charge).sum::<usize>();+ assert!(retained_bytes < 2 * 1024 * 1024);+ }++ #[test]+ fn oversized_first_verified_readback_keeps_ack_without_claiming_verification() {+ let mut registry = RoutineOperationRegistry::default();+ let record = registry.prepare(binding());+ registry.begin(&record.operation_id, "approved SQL").unwrap();+ registry.mark_dispatched(&record.operation_id).unwrap();+ registry.limits.single = registry.operations.lock().unwrap()[&record.operation_id].charge + 1024;+ let mut readback = verified_readback();+ readback.source = Some("x".repeat(8192));+ registry.terminal(&record.operation_id, true, Some(readback), None);+ let observed = registry.observe(&record.operation_id).operation.unwrap();+ assert!(observed.acknowledged && observed.dispatched);+ assert_eq!(observed.lifecycle, RoutineOperationLifecycle::Terminal);+ assert!(!observed.verified());+ assert_eq!(observed.readback.unwrap().state, RoutineReadbackState::ReadbackFailed);+ assert!(registry.operations.lock().unwrap()[&record.operation_id].verified_post_state.is_none());+ }++ #[test]+ fn later_oversized_readback_preserves_first_verified_and_stays_within_old_charge() {+ let registry = RoutineOperationRegistry::default();+ let record = registry.prepare(binding());+ registry.begin(&record.operation_id, "approved SQL").unwrap();+ registry.mark_dispatched(&record.operation_id).unwrap();+ registry.terminal(&record.operation_id, true, Some(verified_readback()), None);+ let before = registry.operations.lock().unwrap()[&record.operation_id].charge;+ let mut readback = verified_readback();+ readback.source = Some("x".repeat(16 * 1024 * 1024));+ registry.update_readback(&record.operation_id, readback);+ let operations = registry.operations.lock().unwrap();+ let operation = &operations[&record.operation_id];+ assert!(!operation.record.verified());+ assert_eq!(operation.verified_post_state.as_ref().unwrap().source.as_deref(), Some("expected source"));+ assert!(operation.charge <= before);+ }++ #[test]+ fn private_binding_duplicates_and_nested_credentials_count_without_logging_them() {+ let registry = RoutineOperationRegistry::default();+ let first = registry.prepare(binding());+ let mut larger = binding();+ larger.expected_config.password = "p".repeat(1000);+ larger.goal = RoutineReadbackGoal::Definition { sql: "q".repeat(1000) };+ let second = registry.prepare(larger);+ let operations = registry.operations.lock().unwrap();+ assert!(operations[&second.operation_id].charge >= operations[&first.operation_id].charge + 2000);+ }+}diff --git a/crates/dbx-core/src/schema/oracle_routines/plan.rs b/crates/dbx-core/src/schema/oracle_routines/plan.rsnew file mode 100644index 0000000000..92e8adc9ec--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/plan.rs@@ -0,0 +1,599 @@+use super::operations::RoutineWriteBinding;+use super::references::{resolve_draft, CatalogReadProof, ResolvedRoutineReference, SelectedFinalDraft};+use super::*;+use dbx_sql::object_source_sql::{+ analyze_oracle_routine_draft, prepare_oracle_routine_definition, validate_oracle_routine_target_definition,+ EditableObjectSourceSqlInput, OracleDraftIssue, OracleRoutineDefinitionInput,+};+use std::collections::BTreeSet;++mod recovery;+pub use recovery::prepare_oracle_routine_recovery_core;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum RoutinePlanAction {+ Create,+ Replace,+ Delete,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutinePlanDraft {+ pub identity: RoutineIdentity,+ pub action: RoutinePlanAction,+ pub source_name: Option<String>,+ // None generates the initial declaration-only adaptation. Some is the+ // user's final draft and must validate before any normalization.+ pub sql: Option<String>,+ pub baseline_operation_id: Option<String>,+ pub supersedes_operation_id: Option<String>,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleRoutinePlanInput {+ pub source: RoutineSnapshot,+ pub target: RoutineSnapshot,+ pub drafts: Vec<RoutinePlanDraft>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleRoutinePlanStep {+ pub identity: RoutineIdentity,+ pub action: RoutinePlanAction,+ pub sql: String,+ pub source_original: Option<String>,+ pub target_original: Option<String>,+ pub recovery_sql: Option<String>,+ pub recovery_complete: bool,+ pub references: Vec<ResolvedRoutineReference>,+ pub incoming_callers: Vec<RoutineDependency>,+ pub issues: Vec<OracleDraftIssue>,+ pub operation: Option<RoutineOperationRecord>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleRoutinePlan {+ pub target: RoutineEndpoint,+ pub steps: Vec<OracleRoutinePlanStep>,+ pub ready: bool,+}++#[derive(Clone, Serialize)]+pub(super) enum ExpectedRoutine {+ Absent(RoutineIdentity),+ Present(RoutineObjectSnapshot),+}++impl ExpectedRoutine {+ fn identity(&self) -> &RoutineIdentity {+ match self {+ Self::Absent(identity) => identity,+ Self::Present(object) => &object.version.identity,+ }+ }+}++#[derive(Clone, Serialize)]+pub(super) struct SourcePreflight {+ pub endpoint: RoutineEndpoint,+ pub config: ConnectionConfig,+ pub expected: ExpectedRoutine,+}++#[derive(Clone, Serialize)]+pub(super) struct ComparePreflight {+ pub source: Option<SourcePreflight>,+ pub target: ExpectedRoutine,+ pub proofs: Vec<CatalogReadProof>,+ pub incoming: Option<Vec<RoutineDependency>>,+ pub selected: Vec<RoutineIdentity>,+}++fn problem(message: impl Into<String>) -> OracleDraftIssue {+ OracleDraftIssue { code: "plan-preflight".into(), message: message.into(), line: 1, column: 1 }+}+fn ddl_input(endpoint: &RoutineEndpoint, identity: &RoutineIdentity, sql: String) -> EditableObjectSourceSqlInput {+ EditableObjectSourceSqlInput {+ database_type: endpoint.database_type,+ object_type: identity.kind.clone(),+ schema: Some(identity.owner.clone()),+ name: identity.name.clone(),+ source: sql,+ }+}+fn drop_sql(identity: &RoutineIdentity) -> String {+ format!(+ "DROP {} \"{}\".\"{}\";",+ kind_name(&identity.kind),+ identity.owner.replace('"', "\"\""),+ identity.name.replace('"', "\"\"")+ )+}+fn adapted(+ endpoint: &RoutineEndpoint,+ identity: &RoutineIdentity,+ source_owner: &str,+ source: &str,+ replace: bool,+) -> Result<String, String> {+ prepare_oracle_routine_definition(OracleRoutineDefinitionInput {+ database_type: endpoint.database_type,+ object_type: identity.kind.clone(),+ source_owner: source_owner.into(),+ target_owner: identity.owner.clone(),+ name: identity.name.clone(),+ source: source.into(),+ replace,+ })+}++/// Complete incoming scope is specific to destructive comparison steps. It is+/// deliberately not used by ordinary saves or legacy structure transfer.+pub(super) async fn incoming_dependencies(+ catalog: &impl RoutineCatalog,+ identity: &RoutineIdentity,+) -> Result<Vec<RoutineDependency>, String> {+ let mut result = Vec::new();+ loop {+ let offset = result.len();+ let reply = catalog+ .query(&format!(+ "SELECT * FROM (SELECT OWNER, NAME, TYPE, REFERENCED_LINK_NAME, DEPENDENCY_TYPE, \+ ROW_NUMBER() OVER (ORDER BY OWNER, NAME, TYPE, REFERENCED_LINK_NAME, DEPENDENCY_TYPE) RN \+ FROM SYS.DBA_DEPENDENCIES WHERE REFERENCED_OWNER = {} AND REFERENCED_NAME = {} AND REFERENCED_TYPE = {}) \+ WHERE RN > {offset} AND RN <= {} ORDER BY RN",+ literal(&identity.owner),+ literal(&identity.name),+ literal(kind_name(&identity.kind)),+ offset + PAGE_SIZE,+ ))+ .await?;+ reply.flags.check()?;+ if reply.rows.len() > PAGE_SIZE {+ return Err("Incoming dependency metadata exceeded its page size".into());+ }+ for row in &reply.rows {+ if reply.integer(row, "RN")? != result.len() as u64 + 1 {+ return Err("Incoming dependency pagination is incomplete".into());+ }+ let link = match reply.cell(row, "REFERENCED_LINK_NAME")? {+ Value::Null => None,+ Value::String(value) if value.is_empty() => None,+ Value::String(value) => Some(value.clone()),+ _ => return Err("Incoming dependency link is unknown".into()),+ };+ result.push(RoutineDependency {+ owner: reply.text(row, "OWNER")?,+ name: reply.text(row, "NAME")?,+ kind: reply.text(row, "TYPE")?,+ database_link: link,+ dependency_type: reply.text(row, "DEPENDENCY_TYPE")?,+ });+ }+ if reply.rows.len() < PAGE_SIZE {+ result.sort();+ return Ok(result);+ }+ }+}++pub(super) async fn verify_expected(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ expected: &ExpectedRoutine,+ origin: SourceOrigin,+) -> Result<(), String> {+ let current =+ readback::readback(catalog, endpoint, expected.identity().clone(), &RoutineReadbackGoal::Inspect, origin).await;+ if !current.issues.is_empty() {+ return Err(current.issues.iter().map(|issue| issue.message.as_str()).collect::<Vec<_>>().join("\n"));+ }+ match expected {+ ExpectedRoutine::Absent(_) if current.exists == Some(false) => Ok(()),+ ExpectedRoutine::Present(before) if before.source_complete && current.version.as_ref() == Some(&before.version) && current.source == before.source => {+ if before.dependencies_complete && dependencies(catalog, &before.version.identity).await? != before.dependencies {+ return Err("Routine dependency snapshot changed; refresh and validate the preserved draft".into());+ }+ Ok(())+ }+ _ => Err("Routine identity, definition, status or namespace changed since preview; refresh and validate the preserved draft".into()),+ }+}++fn external_incoming(values: &[RoutineDependency], selected: &[RoutineIdentity]) -> Vec<RoutineDependency> {+ values+ .iter()+ .filter(|dependency| {+ !selected.iter().any(|identity| {+ identity.owner == dependency.owner+ && identity.name == dependency.name+ && kind_name(&identity.kind) == dependency.kind+ })+ })+ .cloned()+ .collect()+}++pub(super) async fn verify_compare_preflight(+ source: Option<&impl RoutineCatalog>,+ target: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ preflight: &ComparePreflight,+ target_origin: SourceOrigin,+) -> Result<(), String> {+ if let Some(before) = &preflight.source {+ let source = source.ok_or("Original source connection is unavailable")?;+ let (_, origin) = routine_source_origin(&before.config)?;+ verify_expected(source, &before.endpoint, &before.expected, origin).await?;+ }+ verify_expected(target, endpoint, &preflight.target, target_origin).await?;+ for proof in &preflight.proofs {+ proof.verify(target).await?;+ }+ if let Some(before) = &preflight.incoming {+ let current = incoming_dependencies(target, preflight.target.identity()).await?;+ if external_incoming(¤t, &preflight.selected) != external_incoming(before, &preflight.selected) {+ return Err("Incoming callers changed after preview; refresh the affected step before writing".into());+ }+ }+ Ok(())+}++async fn checked_endpoint(state: &AppState, endpoint: &RoutineEndpoint) -> Result<ConnectionConfig, String> {+ let config = connection_config(state, &endpoint.connection_id).await.ok_or("Original connection not found")?;+ let (actual, _) = routine_source_origin(&config)?;+ if actual != endpoint.database_type || endpoint.schema.is_empty() {+ return Err("Routine endpoint does not match its actual engine/schema".into());+ }+ LiveCatalog { state, endpoint, config: &config }.check_endpoint().await?;+ Ok(config)+}++fn snapshot_object(snapshot: &RoutineSnapshot, name: &str) -> Result<Option<RoutineObjectSnapshot>, String> {+ let objects: Vec<_> = snapshot+ .objects+ .iter()+ .filter(|object| {+ object.version.identity.name == name && object.version.identity.owner == snapshot.endpoint.schema+ })+ .collect();+ match objects.as_slice() {+ [] => Ok(None),+ [object] => Ok(Some((*object).clone())),+ _ => Err("Routine snapshot has conflicting namespace identities".into()),+ }+}++fn terminal_baseline(+ state: &AppState,+ id: &str,+ endpoint: &RoutineEndpoint,+ identity: &RoutineIdentity,+) -> Result<ExpectedRoutine, String> {+ let record = state+ .routine_operations+ .observe(id)+ .operation+ .ok_or("Original operation is unavailable; only observe its original ID")?;+ correction_baseline(record, endpoint, identity)+}++fn correction_baseline(+ record: RoutineOperationRecord,+ endpoint: &RoutineEndpoint,+ identity: &RoutineIdentity,+) -> Result<ExpectedRoutine, String> {+ if record.target != *endpoint+ || record.identity != *identity+ || record.lifecycle != RoutineOperationLifecycle::Terminal+ || !record.dispatched+ {+ return Err("Correction requires a terminal operation on the same original target".into());+ }+ let readback = record.readback.ok_or("Read the original operation's complete current result before correction")?;+ if !readback.issues.is_empty() {+ return Err("Original operation readback is incomplete; retain its draft and refresh the result".into());+ }+ if readback.exists == Some(true) && readback.definition_matches != Some(true) {+ return Err("Current definition does not match the original approved write; refresh and review the target baseline before replacing it".into());+ }+ match (readback.exists, readback.version, readback.source) {+ (Some(false), _, _) => Ok(ExpectedRoutine::Absent(identity.clone())),+ (Some(true), Some(version), Some(source)) => Ok(ExpectedRoutine::Present(RoutineObjectSnapshot {+ version,+ source: Some(source),+ source_complete: true,+ dependencies: Vec::new(),+ dependencies_complete: false,+ issues: Vec::new(),+ })),+ _ => Err("Original operation has no complete baseline for correction".into()),+ }+}++pub async fn prepare_oracle_routine_plan_core(+ state: &AppState,+ input: OracleRoutinePlanInput,+) -> Result<OracleRoutinePlan, String> {+ let _input_pins = input+ .drafts+ .iter()+ .flat_map(|draft| draft.baseline_operation_id.iter().chain(draft.supersedes_operation_id.iter()))+ .map(|id| state.routine_operations.pin(id))+ .collect::<Result<Vec<_>, _>>()?;+ if input.source.endpoint.database_type != input.target.endpoint.database_type {+ return Err("Cross-product Oracle routine conversion is read-only".into());+ }+ if input.drafts.is_empty() {+ return Err("Select at least one changed routine".into());+ }+ if input+ .drafts+ .iter()+ .any(|draft| !matches!(draft.identity.kind, db::ObjectSourceKind::Procedure | db::ObjectSourceKind::Function))+ {+ return Err("Routine plans accept only exact standalone procedure/function identities".into());+ }+ let source_config = checked_endpoint(state, &input.source.endpoint).await?;+ let target_config = checked_endpoint(state, &input.target.endpoint).await?;+ let source = LiveCatalog { state, endpoint: &input.source.endpoint, config: &source_config };+ let target = LiveCatalog { state, endpoint: &input.target.endpoint, config: &target_config };+ let (_, source_origin) = routine_source_origin(&source_config)?;+ let (_, target_origin) = routine_source_origin(&target_config)?;+ let mut built = build_plan(&source, &target, &input, source_origin, target_origin, |draft| {+ draft+ .baseline_operation_id+ .as_deref()+ .map(|id| terminal_baseline(state, id, &input.target.endpoint, &draft.identity))+ .transpose()+ })+ .await;+ if !built.plan.ready {+ return Ok(built.plan);+ }+ let mut operations: BTreeMap<usize, String> = BTreeMap::new();+ let mut requests = Vec::new();+ let mut indices = Vec::new();+ for index in built.order {+ let step = &mut built.plan.steps[index];+ let dependencies = built.dependencies[index]+ .iter()+ .map(|dependency| operations.get(dependency).cloned().ok_or("Routine plan order is incomplete"))+ .collect::<Result<Vec<_>, _>>()?;+ let preflight = built.preflights[index].take().ok_or("Routine preflight is unavailable")?;+ let source_preflight = SourcePreflight {+ endpoint: input.source.endpoint.clone(),+ config: source_config.clone(),+ expected: built.source_expected[index].clone().ok_or("Source snapshot is unavailable")?,+ };+ let operation_id = uuid::Uuid::new_v4().to_string();+ requests.push(super::operations::PreparedRoutineWrite {+ operation_id: operation_id.clone(),+ binding: RoutineWriteBinding {+ target: input.target.endpoint.clone(),+ identity: step.identity.clone(),+ sql: step.sql.clone(),+ goal: if step.action == RoutinePlanAction::Delete {+ RoutineReadbackGoal::Absent+ } else {+ RoutineReadbackGoal::Definition { sql: step.sql.clone() }+ },+ expected_config: target_config.clone(),+ require_absent: step.action == RoutinePlanAction::Create,+ compare: Some(ComparePreflight { source: Some(source_preflight), ..preflight }),+ prerequisite_operation_ids: dependencies,+ },+ supersedes: input.drafts[index].supersedes_operation_id.clone(),+ });+ operations.insert(index, operation_id);+ indices.push(index);+ }+ let prepared = state.routine_operations.prepare_batch(requests, 0)?;+ for (index, operation) in indices.into_iter().zip(prepared) {+ built.plan.steps[index].operation = Some(operation);+ }+ // Present the actual server-enforced order, not merely frontend sorting.+ built.plan.steps.sort_by_key(|step| {+ operations+ .iter()+ .find_map(|(index, id)| {+ step.operation+ .as_ref()+ .filter(|operation| operation.operation_id == *id)+ .map(|_| built.order_position[*index])+ })+ .unwrap_or(usize::MAX)+ });+ Ok(built.plan)+}++struct BuiltPlan {+ plan: OracleRoutinePlan,+ preflights: Vec<Option<ComparePreflight>>,+ source_expected: Vec<Option<ExpectedRoutine>>,+ dependencies: Vec<BTreeSet<usize>>,+ order: Vec<usize>,+ order_position: Vec<usize>,+}++async fn build_plan(+ source: &impl RoutineCatalog,+ target: &impl RoutineCatalog,+ input: &OracleRoutinePlanInput,+ source_origin: SourceOrigin,+ target_origin: SourceOrigin,+ baseline: impl Fn(&RoutinePlanDraft) -> Result<Option<ExpectedRoutine>, String>,+) -> BuiltPlan {+ let mut plan = OracleRoutinePlan { target: input.target.endpoint.clone(), steps: Vec::new(), ready: false };+ let mut selected = Vec::new();+ let mut preflights = Vec::new();+ let mut source_expected = Vec::new();+ let mut seen = BTreeSet::new();+ for draft in &input.drafts {+ let mut step = OracleRoutinePlanStep {+ identity: draft.identity.clone(),+ action: draft.action,+ sql: draft.sql.clone().unwrap_or_default(),+ source_original: None,+ target_original: None,+ recovery_sql: None,+ recovery_complete: draft.action != RoutinePlanAction::Delete,+ references: Vec::new(),+ incoming_callers: Vec::new(),+ issues: Vec::new(),+ operation: None,+ };+ let mut source_before = None;+ let mut before = None;+ let prepared: Result<(), String> = async {+ if draft.identity.owner != input.target.endpoint.schema || draft.identity.name.is_empty() || !matches!(draft.identity.kind, db::ObjectSourceKind::Function | db::ObjectSourceKind::Procedure) { return Err("Every step must retain its exact selected target identity".into()); }+ if !seen.insert((draft.identity.owner.clone(), draft.identity.name.clone())) { return Err("The same shared namespace target is selected more than once".into()); }+ let source_name = draft.source_name.as_deref().unwrap_or(&draft.identity.name);+ if source_name != draft.identity.name { return Err("Routine rename mappings require a separate reviewed lifecycle; keep this comparison's exact name".into()); }+ let source_object = snapshot_object(&input.source, source_name)?;+ let target_object = snapshot_object(&input.target, &draft.identity.name)?;+ step.source_original = source_object.as_ref().and_then(|object| object.source.clone());+ step.target_original = target_object.as_ref().and_then(|object| object.source.clone());+ source_before = Some(if draft.action == RoutinePlanAction::Delete {+ if !input.source.enumeration_complete || source_object.is_some() { return Err("Deletion requires complete source enumeration and a confirmed absent source identity".into()); }+ ExpectedRoutine::Absent(RoutineIdentity { owner: input.source.endpoint.schema.clone(), ..draft.identity.clone() })+ } else {+ let object = source_object.ok_or("Source routine is not present in the complete preview")?;+ if object.version.identity.kind != draft.identity.kind || !object.source_complete { return Err("Source kind or complete definition is not verified".into()); }+ ExpectedRoutine::Present(object)+ });+ let mut expected = match baseline(draft)? {+ Some(expected) => expected,+ None => match target_object {+ Some(object) => ExpectedRoutine::Present(object),+ None if input.target.enumeration_complete => ExpectedRoutine::Absent(draft.identity.clone()),+ None => return Err("Target absence is not proven by this preview".into()),+ },+ };+ match (&expected, draft.action) {+ (ExpectedRoutine::Absent(_), RoutinePlanAction::Create) => {}+ (ExpectedRoutine::Present(object), RoutinePlanAction::Replace | RoutinePlanAction::Delete) => {+ if object.version.identity != draft.identity || !object.source_complete { return Err("Target kind conflicts or its complete definition is unavailable".into()); }+ step.target_original = object.source.clone();+ }+ _ => return Err("The selected operation no longer matches the target's existence; refresh the plan without discarding the draft".into()),+ }+ if draft.action == RoutinePlanAction::Delete {+ let exact = drop_sql(&draft.identity);+ if draft.sql.as_ref().is_some_and(|sql| sql.trim() != exact) { return Err("A deletion must contain only the exact selected DROP statement".into()); }+ step.sql = exact;+ } else {+ let replace = draft.action == RoutinePlanAction::Replace;+ step.sql = if let Some(sql) = &draft.sql {+ validate_oracle_routine_target_definition(ddl_input(&input.target.endpoint, &draft.identity, sql.clone()), if replace { None } else { Some(false) })?;+ adapted(&input.target.endpoint, &draft.identity, &draft.identity.owner, sql, replace)?+ } else {+ adapted(&input.target.endpoint, &draft.identity, &input.source.endpoint.schema, step.source_original.as_deref().ok_or("Complete source is unavailable")?, replace)?+ };+ }+ step.recovery_sql = match &expected {+ ExpectedRoutine::Absent(_) => Some(drop_sql(&draft.identity)),+ ExpectedRoutine::Present(object) => Some(adapted(&input.target.endpoint, &draft.identity, &draft.identity.owner, object.source.as_deref().ok_or("Original target definition is unavailable")?, draft.action != RoutinePlanAction::Delete)?),+ };+ if matches!(&expected, ExpectedRoutine::Present(object) if !object.dependencies_complete) && draft.baseline_operation_id.is_none() { return Err("Target dependency snapshot is incomplete; refresh it before a destructive step".into()); }+ verify_expected(source, &input.source.endpoint, source_before.as_ref().unwrap(), source_origin).await?;+ verify_expected(target, &input.target.endpoint, &expected, target_origin).await?;+ if let ExpectedRoutine::Present(object) = &mut expected {+ if !object.dependencies_complete {+ object.dependencies = dependencies(target, &object.version.identity).await?;+ object.dependencies_complete = true;+ }+ }+ before = Some(expected);+ Ok(())+ }.await;+ if let Err(error) = prepared {+ step.issues.push(problem(error));+ }+ let analysis = if draft.action == RoutinePlanAction::Delete {+ None+ } else {+ let analysis =+ analyze_oracle_routine_draft(ddl_input(&input.target.endpoint, &draft.identity, step.sql.clone()));+ step.issues.extend(analysis.issues.clone());+ Some(analysis)+ };+ selected.push(SelectedFinalDraft { identity: draft.identity.clone(), analysis });+ preflights.push(before.map(|target| ComparePreflight {+ source: None,+ target,+ proofs: Vec::new(),+ incoming: None,+ selected: input.drafts.iter().map(|draft| draft.identity.clone()).collect(),+ }));+ source_expected.push(source_before);+ plan.steps.push(step);+ }+ let mut dependencies = vec![BTreeSet::new(); plan.steps.len()];+ for index in 0..plan.steps.len() {+ if !plan.steps[index].issues.is_empty() {+ continue;+ }+ if plan.steps[index].action != RoutinePlanAction::Delete {+ let resolution = resolve_draft(target, &input.target.endpoint, &selected, index).await;+ plan.steps[index].issues.extend(resolution.issues);+ plan.steps[index].references = resolution.references;+ dependencies[index] = resolution.selected_dependencies;+ preflights[index].as_mut().unwrap().proofs = resolution.proofs;+ }+ if plan.steps[index].action != RoutinePlanAction::Create {+ match incoming_dependencies(target, &plan.steps[index].identity).await {+ Ok(incoming) => {+ plan.steps[index].incoming_callers = incoming.clone();+ if plan.steps[index].action == RoutinePlanAction::Delete {+ for caller in &incoming {+ if caller.owner == plan.steps[index].identity.owner+ && caller.name == plan.steps[index].identity.name+ && caller.kind == kind_name(&plan.steps[index].identity.kind)+ {+ continue;+ }+ match input.drafts.iter().position(|draft| draft.identity.owner == caller.owner && draft.identity.name == caller.name && kind_name(&draft.identity.kind) == caller.kind) {+ Some(caller_index) => { dependencies[index].insert(caller_index); }+ None => plan.steps[index].issues.push(problem(format!("Caller {}.{} ({}) is outside the deletion/correction selection; remove its dependency first", caller.owner, caller.name, caller.kind))),+ }+ }+ }+ preflights[index].as_mut().unwrap().incoming = Some(incoming);+ }+ Err(error) => plan.steps[index].issues.push(problem(format!(+ "Complete incoming dependency visibility is required for this destructive step: {error}"+ ))),+ }+ }+ }+ let mut order = Vec::new();+ let mut remaining: BTreeSet<_> = (0..plan.steps.len()).collect();+ while let Some(next) = remaining+ .iter()+ .copied()+ .find(|index| dependencies[*index].iter().all(|dependency| !remaining.contains(dependency)))+ {+ remaining.remove(&next);+ order.push(next);+ }+ for index in remaining {+ plan.steps[index].issues.push(problem(+ "Selected final drafts have an unresolved dependency cycle; correct the draft or reduce the selection",+ ));+ }+ plan.ready = plan.steps.iter().all(|step| step.issues.is_empty()) && order.len() == plan.steps.len();+ let mut order_position = vec![usize::MAX; plan.steps.len()];+ for (position, index) in order.iter().enumerate() {+ order_position[*index] = position;+ }+ BuiltPlan { plan, preflights, source_expected, dependencies, order, order_position }+}++#[cfg(test)]+mod tests;diff --git a/crates/dbx-core/src/schema/oracle_routines/plan/recovery.rs b/crates/dbx-core/src/schema/oracle_routines/plan/recovery.rsnew file mode 100644index 0000000000..c319987abe--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/plan/recovery.rs@@ -0,0 +1,234 @@+use super::*;++/// Recovery is a new, explicitly approved DDL operation against the original+/// operation's recorded post-state. It never unlocks an unknown request.+pub async fn prepare_oracle_routine_recovery_core(+ state: &AppState,+ operation_id: &str,+) -> Result<OracleRoutinePlan, String> {+ let _original_pin = state.routine_operations.pin(operation_id)?;+ let original = state+ .routine_operations+ .observe(operation_id)+ .operation+ .ok_or("Original operation is unavailable; recovery cannot establish its termination")?;+ if original.lifecycle != RoutineOperationLifecycle::Terminal || !original.dispatched {+ return Err("Recovery requires the original write's terminal evidence; only observe its original ID".into());+ }+ let binding = state.routine_operations.binding_for_readback(operation_id)?;+ check_recovery_receipt(&original, &binding.goal)?;+ let before =+ binding.compare.as_ref().ok_or("This operation has no complete comparison recovery material")?.target.clone();+ let current = terminal_baseline(state, operation_id, &original.target, &original.identity)?;+ let config = checked_endpoint(state, &original.target).await?;+ let catalog = LiveCatalog { state, endpoint: &original.target, config: &config };+ let (_, origin) = routine_source_origin(&config)?;+ let mut result = recovery_plan(&catalog, &original.target, &original.identity, before, current, origin).await;+ if result.plan.ready {+ let step = &mut result.plan.steps[0];+ step.operation = Some(state.routine_operations.prepare_replacing(+ RoutineWriteBinding {+ target: original.target,+ identity: step.identity.clone(),+ sql: step.sql.clone(),+ goal: if step.action == RoutinePlanAction::Delete {+ RoutineReadbackGoal::Absent+ } else {+ RoutineReadbackGoal::Definition { sql: step.sql.clone() }+ },+ expected_config: config,+ require_absent: step.action == RoutinePlanAction::Create,+ compare: result.preflight.take(),+ prerequisite_operation_ids: Vec::new(),+ },+ None,+ )?);+ }+ Ok(result.plan)+}++fn check_recovery_receipt(original: &RoutineOperationRecord, goal: &RoutineReadbackGoal) -> Result<(), String> {+ let recorded_post_matches = original.readback.as_ref().is_some_and(|readback| match goal {+ RoutineReadbackGoal::Definition { .. } => readback.definition_matches == Some(true),+ RoutineReadbackGoal::Absent => {+ readback.state == RoutineReadbackState::Verified && readback.exists == Some(false)+ }+ RoutineReadbackGoal::Inspect => false,+ });+ if original.lifecycle != RoutineOperationLifecycle::Terminal+ || !original.dispatched+ || !original.acknowledged+ || !recorded_post_matches+ {+ return Err("Recovery cannot attribute the recorded contents to an acknowledged matching write; refresh and review the target instead".into());+ }+ Ok(())+}++struct RecoveryPlan {+ plan: OracleRoutinePlan,+ preflight: Option<ComparePreflight>,+}++async fn recovery_plan(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ identity: &RoutineIdentity,+ before: ExpectedRoutine,+ mut current: ExpectedRoutine,+ origin: SourceOrigin,+) -> RecoveryPlan {+ let action = match (&before, ¤t) {+ (ExpectedRoutine::Absent(_), _) => RoutinePlanAction::Delete,+ (ExpectedRoutine::Present(_), ExpectedRoutine::Absent(_)) => RoutinePlanAction::Create,+ _ => RoutinePlanAction::Replace,+ };+ let mut step = OracleRoutinePlanStep {+ identity: identity.clone(),+ action,+ sql: String::new(),+ source_original: match &before {+ ExpectedRoutine::Present(object) => object.source.clone(),+ _ => None,+ },+ target_original: match ¤t {+ ExpectedRoutine::Present(object) => object.source.clone(),+ _ => None,+ },+ recovery_sql: None,+ recovery_complete: action != RoutinePlanAction::Create,+ references: Vec::new(),+ incoming_callers: Vec::new(),+ issues: Vec::new(),+ operation: None,+ };+ let mut preflight = None;+ let prepared: Result<(), String> = async {+ step.sql = match &before {+ ExpectedRoutine::Absent(_) => drop_sql(identity),+ ExpectedRoutine::Present(object) => adapted(endpoint, identity, &identity.owner, object.source.as_deref().ok_or("Original complete definition is unavailable")?, action == RoutinePlanAction::Replace)?,+ };+ if action == RoutinePlanAction::Create {+ return Err("The deleted routine's definition is available to copy, but grants and other deleted state were not captured; complete one-click recovery is unavailable".into());+ }+ verify_expected(catalog, endpoint, ¤t, origin).await?;+ if let ExpectedRoutine::Present(object) = &mut current {+ object.dependencies = dependencies(catalog, identity).await?;+ object.dependencies_complete = true;+ }+ let incoming = incoming_dependencies(catalog, identity).await?;+ step.incoming_callers = incoming.clone();+ if action == RoutinePlanAction::Delete && incoming.iter().any(|caller| caller.owner != identity.owner || caller.name != identity.name || caller.kind != kind_name(&identity.kind)) {+ return Err("New callers depend on the deployed routine; remove those dependencies before recovery deletion".into());+ }+ let proofs = if action == RoutinePlanAction::Replace {+ let analysis = analyze_oracle_routine_draft(ddl_input(endpoint, identity, step.sql.clone()));+ if !analysis.complete { step.issues.extend(analysis.issues); return Ok(()); }+ let selected = vec![SelectedFinalDraft { identity: identity.clone(), analysis: Some(analysis) }];+ let resolution = resolve_draft(catalog, endpoint, &selected, 0).await;+ step.references = resolution.references;+ step.issues.extend(resolution.issues);+ resolution.proofs+ } else { Vec::new() };+ preflight = Some(ComparePreflight { source: None, target: current.clone(), proofs, incoming: Some(incoming), selected: vec![identity.clone()] });+ Ok(())+ }.await;+ if let Err(error) = prepared {+ step.issues.push(problem(error));+ }+ let ready = step.issues.is_empty() && preflight.is_some();+ RecoveryPlan { plan: OracleRoutinePlan { target: endpoint.clone(), steps: vec![step], ready }, preflight }+}++#[cfg(test)]+mod tests {+ use super::super::tests::{endpoint, object, Catalog};+ use super::*;++ #[tokio::test]+ async fn recovery_checks_the_recorded_post_state_and_refuses_third_party_source_changes() {+ let before = object("OWNER", "F", "1");+ let after = object("OWNER", "F", "2");+ let catalog = Catalog::new("OWNER", vec![after.clone()]);+ let result = recovery_plan(+ &catalog,+ &endpoint("OWNER"),+ &before.version.identity,+ ExpectedRoutine::Present(before.clone()),+ ExpectedRoutine::Present(after.clone()),+ SourceOrigin::OceanBaseDictionary,+ )+ .await;+ assert!(result.plan.ready);+ assert!(result.plan.steps[0].sql.contains("RETURN 1;"));+ catalog.changed_source.store(true, std::sync::atomic::Ordering::SeqCst);+ let result = recovery_plan(+ &catalog,+ &endpoint("OWNER"),+ &before.version.identity,+ ExpectedRoutine::Present(before.clone()),+ ExpectedRoutine::Present(after),+ SourceOrigin::OceanBaseDictionary,+ )+ .await;+ assert!(!result.plan.ready);+ assert!(!result.plan.steps[0].issues.is_empty());+ }++ #[tokio::test]+ async fn deleted_grants_are_not_invented_and_original_definition_stays_copyable() {+ let before = object("OWNER", "F", "1");+ let catalog = Catalog::new("OWNER", Vec::new());+ let result = recovery_plan(+ &catalog,+ &endpoint("OWNER"),+ &before.version.identity,+ ExpectedRoutine::Present(before.clone()),+ ExpectedRoutine::Absent(before.version.identity.clone()),+ SourceOrigin::OceanBaseDictionary,+ )+ .await;+ assert!(!result.plan.ready);+ assert!(!result.plan.steps[0].recovery_complete);+ validate_oracle_routine_target_definition(+ ddl_input(&endpoint("OWNER"), &before.version.identity, result.plan.steps[0].sql.clone()),+ Some(false),+ )+ .unwrap();+ assert!(result.plan.steps[0].issues[0].message.contains("grants"));+ }++ #[test]+ fn rejected_or_unknown_writes_cannot_claim_a_competing_object_for_recovery() {+ let identity = object("OWNER", "F", "1").version.identity;+ let goal = RoutineReadbackGoal::Definition { sql: "approved".into() };+ let mut original = RoutineOperationRecord {+ operation_id: "original".into(),+ target: endpoint("OWNER"),+ identity: identity.clone(),+ lifecycle: RoutineOperationLifecycle::Terminal,+ dispatched: true,+ acknowledged: true,+ error: None,+ readback: Some(RoutineReadback {+ identity,+ state: RoutineReadbackState::Invalid,+ exists: Some(true),+ version: None,+ source: Some("approved".into()),+ definition_matches: Some(true),+ compiler_messages: Vec::new(),+ issues: Vec::new(),+ }),+ };+ check_recovery_receipt(&original, &goal).unwrap();+ original.acknowledged = false;+ assert!(check_recovery_receipt(&original, &goal).is_err());+ original.acknowledged = true;+ original.lifecycle = RoutineOperationLifecycle::Unproven;+ assert!(check_recovery_receipt(&original, &goal).is_err());+ original.lifecycle = RoutineOperationLifecycle::Terminal;+ original.readback.as_mut().unwrap().definition_matches = Some(false);+ assert!(check_recovery_receipt(&original, &goal).is_err());+ }+}diff --git a/crates/dbx-core/src/schema/oracle_routines/plan/tests.rs b/crates/dbx-core/src/schema/oracle_routines/plan/tests.rsnew file mode 100644index 0000000000..225252066b--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/plan/tests.rs@@ -0,0 +1,458 @@+use super::*;+use serde_json::json;+use std::sync::atomic::{AtomicBool, Ordering};++pub(super) struct Catalog {+ owner: &'static str,+ objects: Vec<RoutineObjectSnapshot>,+ incoming: BTreeMap<String, Vec<RoutineDependency>>,+ deny_incoming: bool,+ pub(super) changed_source: AtomicBool,+}+impl Catalog {+ pub(super) fn new(owner: &'static str, objects: Vec<RoutineObjectSnapshot>) -> Self {+ Self { owner, objects, incoming: BTreeMap::new(), deny_incoming: false, changed_source: AtomicBool::new(false) }+ }+ fn source_text(&self, object: &RoutineObjectSnapshot) -> String {+ let source = object.source.as_ref().unwrap();+ if self.changed_source.load(Ordering::SeqCst) {+ format!("{source} -- concurrent edit")+ } else {+ source.clone()+ }+ }+}+fn reply(columns: &[&str], rows: Vec<Vec<Value>>) -> CatalogReply {+ serde_json::from_value(json!({"columns":columns,"rows":rows})).unwrap()+}+fn name_from(sql: &str, field: &str) -> String {+ sql.split(&format!("{field} = '")).nth(1).unwrap_or("").split('\'').next().unwrap_or("").into()+}++#[async_trait::async_trait]+impl RoutineCatalog for Catalog {+ async fn source(&self, identity: &RoutineIdentity) -> Result<SourceReply, String> {+ let object =+ self.objects.iter().find(|object| object.version.identity == *identity).ok_or("Source not found")?;+ Ok(serde_json::from_value(json!({"name":identity.name,"schema":identity.owner,"object_type":identity.kind,"source":self.source_text(object)})).unwrap())+ }+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ if sql.contains("LOGIN_OWNER") {+ return Ok(reply(&["LOGIN_OWNER"], vec![vec![json!(self.owner)]]));+ }+ if sql.contains("ALL_OBJECTS") || sql.contains("DBA_OBJECTS") {+ let owner = name_from(sql, "OWNER");+ let name = name_from(sql, "OBJECT_NAME");+ let rows = self+ .objects+ .iter()+ .filter(|object| object.version.identity.owner == owner && object.version.identity.name == name)+ .map(|object| {+ let version = &object.version;+ vec![+ json!(version.identity.owner),+ json!(version.identity.name),+ json!(kind_name(&version.identity.kind)),+ json!(version.object_id),+ json!(version.status),+ json!(version.last_ddl_time),+ ]+ })+ .collect();+ return Ok(reply(&["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "STATUS", "LAST_DDL_TIME"], rows));+ }+ if sql.contains("ALL_ERRORS") {+ return Ok(reply(&["SEQUENCE", "ATTRIBUTE", "LINE", "POSITION", "TEXT"], Vec::new()));+ }+ if sql.contains("SOURCE_ROWS") {+ let name = name_from(sql, "NAME");+ let object = self.objects.iter().find(|object| object.version.identity.name == name).unwrap();+ let source = self.source_text(object);+ let body = source.strip_prefix("CREATE OR REPLACE ").unwrap();+ return Ok(reply(+ &["SOURCE_ROWS", "FIRST_LINE", "LAST_LINE", "SOURCE_CHARS", "HEAD_TRIM", "TAIL_TRIM", "SOURCE_HEAD"],+ vec![vec![+ json!(1),+ json!(1),+ json!(1),+ json!(body.chars().count()),+ json!(0),+ json!(0),+ json!(kind_name(&object.version.identity.kind)),+ ]],+ ));+ }+ if sql.contains("DBA_DEPENDENCIES") {+ if self.deny_incoming {+ return Err("ORA-00942: no complete incoming visibility".into());+ }+ let name = name_from(sql, "REFERENCED_NAME");+ let rows = self+ .incoming+ .get(&name)+ .into_iter()+ .flatten()+ .enumerate()+ .map(|(index, caller)| {+ vec![+ json!(caller.owner),+ json!(caller.name),+ json!(caller.kind),+ json!(caller.database_link),+ json!(caller.dependency_type),+ json!(index + 1),+ ]+ })+ .collect();+ return Ok(reply(&["OWNER", "NAME", "TYPE", "REFERENCED_LINK_NAME", "DEPENDENCY_TYPE", "RN"], rows));+ }+ if sql.contains("ALL_DEPENDENCIES") {+ let name = name_from(sql, "NAME");+ let object = self.objects.iter().find(|object| object.version.identity.name == name).unwrap();+ let rows = object+ .dependencies+ .iter()+ .enumerate()+ .map(|(index, dependency)| {+ vec![+ json!(dependency.owner),+ json!(dependency.name),+ json!(dependency.kind),+ json!(dependency.database_link),+ json!(dependency.dependency_type),+ json!(index + 1),+ ]+ })+ .collect();+ return Ok(reply(+ &[+ "REFERENCED_OWNER",+ "REFERENCED_NAME",+ "REFERENCED_TYPE",+ "REFERENCED_LINK_NAME",+ "DEPENDENCY_TYPE",+ "RN",+ ],+ rows,+ ));+ }+ panic!("Unexpected metadata query: {sql}")+ }+}++pub(super) fn endpoint(owner: &str) -> RoutineEndpoint {+ RoutineEndpoint {+ connection_id: owner.into(),+ database: "tenant".into(),+ schema: owner.into(),+ database_type: DatabaseType::OceanbaseOracle,+ generation: 1,+ }+}+pub(super) fn object(owner: &str, name: &str, expression: &str) -> RoutineObjectSnapshot {+ RoutineObjectSnapshot {+ version: RoutineVersion {+ identity: RoutineIdentity { owner: owner.into(), name: name.into(), kind: db::ObjectSourceKind::Function },+ object_id: format!("{}", name.as_bytes()[0]),+ status: "VALID".into(),+ last_ddl_time: "2026-10-21T00:00:00".into(),+ },+ source: Some(format!("CREATE OR REPLACE FUNCTION \"{name}\" RETURN NUMBER AS BEGIN RETURN {expression}; END")),+ source_complete: true,+ dependencies: Vec::new(),+ dependencies_complete: true,+ issues: Vec::new(),+ }+}+fn snapshot(catalog: &Catalog) -> RoutineSnapshot {+ RoutineSnapshot {+ endpoint: endpoint(catalog.owner),+ state: RoutineReadState::Complete,+ enumeration_complete: true,+ objects: catalog.objects.clone(),+ issues: Vec::new(),+ }+}+fn draft(name: &str, action: RoutinePlanAction) -> RoutinePlanDraft {+ RoutinePlanDraft {+ identity: object("OWNER", name, "1").version.identity,+ action,+ source_name: None,+ sql: None,+ baseline_operation_id: None,+ supersedes_operation_id: None,+ }+}+fn input(source: &Catalog, target: &Catalog, drafts: Vec<RoutinePlanDraft>) -> OracleRoutinePlanInput {+ OracleRoutinePlanInput { source: snapshot(source), target: snapshot(target), drafts }+}+async fn build(source: &Catalog, target: &Catalog, input: &OracleRoutinePlanInput) -> BuiltPlan {+ build_plan(source, target, input, SourceOrigin::OceanBaseDictionary, SourceOrigin::OceanBaseDictionary, |_| {+ Ok(None)+ })+ .await+}++#[tokio::test]+async fn initial_plan_preserves_raw_text_and_creates_without_replace_in_server_dependency_order() {+ let source =+ Catalog::new("SOURCE", vec![object("SOURCE", "Caller", "\"Callee\""), object("SOURCE", "Callee", "1")]);+ let target = Catalog::new("OWNER", Vec::new());+ let input = input(+ &source,+ &target,+ vec![draft("Caller", RoutinePlanAction::Create), draft("Callee", RoutinePlanAction::Create)],+ );+ let result = build(&source, &target, &input).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert_eq!(result.order, vec![1, 0]);+ validate_oracle_routine_target_definition(+ ddl_input(&input.target.endpoint, &result.plan.steps[0].identity, result.plan.steps[0].sql.clone()),+ Some(false),+ )+ .unwrap();+ assert_eq!(result.plan.steps[0].source_original, source.objects[0].source);+ assert!(result.plan.steps[0].target_original.is_none());+ assert_eq!(result.plan.steps[0].recovery_sql.as_deref(), Some("DROP FUNCTION \"OWNER\".\"Caller\";"));+}++#[tokio::test]+async fn final_manual_draft_invalidates_old_edges_and_becomes_the_new_readback_expectation() {+ let source =+ Catalog::new("SOURCE", vec![object("SOURCE", "Caller", "\"Callee\""), object("SOURCE", "Callee", "1")]);+ let target = Catalog::new("OWNER", Vec::new());+ let mut input = input(+ &source,+ &target,+ vec![draft("Caller", RoutinePlanAction::Create), draft("Callee", RoutinePlanAction::Create)],+ );+ input.drafts[0].sql = Some("CREATE FUNCTION \"OWNER\".\"Caller\" RETURN NUMBER AS BEGIN RETURN 77; END;".into());+ let result = build(&source, &target, &input).await;+ assert!(result.plan.ready);+ assert_eq!(result.order, vec![0, 1]);+ assert!(result.dependencies[0].is_empty());+ assert!(result.plan.steps[0].sql.contains("RETURN 77;"));+ input.drafts[0].sql = Some("CREATE FUNCTION \"OWNER\".\"Other\" RETURN NUMBER AS BEGIN RETURN 77; END;".into());+ assert!(!build(&source, &target, &input).await.plan.ready);+ input.drafts[0].sql =+ Some("CREATE OR REPLACE FUNCTION \"OWNER\".\"Caller\" RETURN NUMBER AS BEGIN RETURN 77; END;".into());+ assert!(!build(&source, &target, &input).await.plan.ready);+}++#[tokio::test]+async fn cycles_are_localized_and_independent_valid_drafts_are_not_discarded() {+ let source = Catalog::new(+ "SOURCE",+ vec![object("SOURCE", "F", "\"G\""), object("SOURCE", "G", "\"F\""), object("SOURCE", "Independent", "7")],+ );+ let target = Catalog::new("OWNER", Vec::new());+ let input = input(+ &source,+ &target,+ vec![+ draft("F", RoutinePlanAction::Create),+ draft("G", RoutinePlanAction::Create),+ draft("Independent", RoutinePlanAction::Create),+ ],+ );+ let result = build(&source, &target, &input).await;+ assert!(!result.plan.ready);+ assert!(!result.plan.steps[0].issues.is_empty());+ assert!(result.plan.steps[2].issues.is_empty());+ assert!(result.plan.steps[2].sql.contains("RETURN 7;"));+}++#[tokio::test]+async fn destructive_visibility_failure_only_affects_that_step_not_ordinary_owner_creation() {+ let source = Catalog::new("SOURCE", vec![object("SOURCE", "F", "2"), object("SOURCE", "New", "3")]);+ let mut target = Catalog::new("OWNER", vec![object("OWNER", "F", "1")]);+ target.deny_incoming = true;+ let input =+ input(&source, &target, vec![draft("F", RoutinePlanAction::Replace), draft("New", RoutinePlanAction::Create)]);+ let result = build(&source, &target, &input).await;+ assert!(!result.plan.ready);+ assert!(result.plan.steps[0].issues[0].message.contains("incoming"));+ assert!(result.plan.steps[1].issues.is_empty());+ let input = OracleRoutinePlanInput { drafts: vec![input.drafts[1].clone()], ..input };+ assert!(build(&source, &target, &input).await.plan.ready);+}++fn caller(name: &str) -> RoutineDependency {+ RoutineDependency {+ owner: "OWNER".into(),+ name: name.into(),+ kind: "FUNCTION".into(),+ database_link: None,+ dependency_type: "HARD".into(),+ }+}++#[tokio::test]+async fn delete_checks_full_callers_and_reverses_the_selected_deletion_order_without_claiming_grant_recovery() {+ let source = Catalog::new("SOURCE", Vec::new());+ let mut target = Catalog::new("OWNER", vec![object("OWNER", "F", "1"), object("OWNER", "G", "\"F\"")]);+ target.incoming.insert("F".into(), vec![caller("G")]);+ let blocked = input(&source, &target, vec![draft("F", RoutinePlanAction::Delete)]);+ assert!(build(&source, &target, &blocked).await.plan.steps[0].issues[0].message.contains("outside"));+ let all =+ input(&source, &target, vec![draft("F", RoutinePlanAction::Delete), draft("G", RoutinePlanAction::Delete)]);+ let result = build(&source, &target, &all).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert_eq!(result.order, vec![1, 0]);+ assert_eq!(result.plan.steps[0].sql, "DROP FUNCTION \"OWNER\".\"F\";");+ assert!(!result.plan.steps[0].recovery_complete);+ validate_oracle_routine_target_definition(+ ddl_input(+ &all.target.endpoint,+ &result.plan.steps[0].identity,+ result.plan.steps[0].recovery_sql.clone().unwrap(),+ ),+ Some(false),+ )+ .unwrap();+}++#[tokio::test]+async fn same_second_source_target_and_incoming_changes_block_prepared_writes() {+ let source = Catalog::new("SOURCE", vec![object("SOURCE", "F", "2")]);+ let mut target = Catalog::new("OWNER", vec![object("OWNER", "F", "1")]);+ let input = input(&source, &target, vec![draft("F", RoutinePlanAction::Replace)]);+ let mut result = build(&source, &target, &input).await;+ assert!(result.plan.ready);+ let preflight = result.preflights[0].as_mut().unwrap();+ verify_compare_preflight(+ Some(&source),+ &target,+ &input.target.endpoint,+ preflight,+ SourceOrigin::OceanBaseDictionary,+ )+ .await+ .unwrap();+ target.changed_source.store(true, Ordering::SeqCst);+ assert!(verify_compare_preflight(+ Some(&source),+ &target,+ &input.target.endpoint,+ preflight,+ SourceOrigin::OceanBaseDictionary+ )+ .await+ .is_err());+ target.changed_source.store(false, Ordering::SeqCst);+ target.incoming.insert("F".into(), vec![caller("Outside")]);+ assert!(verify_compare_preflight(+ Some(&source),+ &target,+ &input.target.endpoint,+ preflight,+ SourceOrigin::OceanBaseDictionary+ )+ .await+ .is_err());+ source.changed_source.store(true, Ordering::SeqCst);+ assert!(verify_expected(+ &source,+ &input.source.endpoint,+ result.source_expected[0].as_ref().unwrap(),+ SourceOrigin::OceanBaseDictionary+ )+ .await+ .is_err());+}++#[tokio::test]+async fn occupied_new_namespace_incomplete_absence_and_extra_sql_cannot_produce_a_ready_plan() {+ let source = Catalog::new("SOURCE", vec![object("SOURCE", "F", "1")]);+ let target = Catalog::new("OWNER", Vec::new());+ let input = input(&source, &target, vec![draft("F", RoutinePlanAction::Create)]);+ let occupied = Catalog::new("OWNER", vec![object("OWNER", "F", "9")]);+ assert!(!build(&source, &occupied, &input).await.plan.ready);+ let mut missing_scope = input.clone();+ missing_scope.target.enumeration_complete = false;+ assert!(!build(&source, &target, &missing_scope).await.plan.ready);+ let mut extra = input;+ extra.drafts[0].sql =+ Some("CREATE FUNCTION \"OWNER\".\"F\" RETURN NUMBER AS BEGIN RETURN 1; END; DELETE FROM unrelated;".into());+ assert!(!build(&source, &target, &extra).await.plan.ready);+}++#[tokio::test]+async fn terminal_invalid_create_can_be_corrected_as_an_explicit_new_replace_approval() {+ let source = Catalog::new("SOURCE", vec![object("SOURCE", "F", "1")]);+ let target = Catalog::new("OWNER", vec![object("OWNER", "F", "1")]);+ let mut input = input(&source, &Catalog::new("OWNER", Vec::new()), vec![draft("F", RoutinePlanAction::Replace)]);+ input.drafts[0].baseline_operation_id = Some("original-invalid-create".into());+ input.drafts[0].sql = Some("CREATE FUNCTION \"OWNER\".\"F\" RETURN NUMBER AS BEGIN RETURN 77; END;".into());+ let result = build_plan(+ &source,+ &target,+ &input,+ SourceOrigin::OceanBaseDictionary,+ SourceOrigin::OceanBaseDictionary,+ |_| Ok(Some(ExpectedRoutine::Present(target.objects[0].clone()))),+ )+ .await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ validate_oracle_routine_target_definition(+ ddl_input(&input.target.endpoint, &result.plan.steps[0].identity, result.plan.steps[0].sql.clone()),+ Some(true),+ )+ .unwrap();+ assert!(result.plan.steps[0].sql.contains("RETURN 77;"));+}++fn correction_record() -> RoutineOperationRecord {+ let object = object("OWNER", "F", "1");+ RoutineOperationRecord {+ operation_id: "original".into(),+ target: endpoint("OWNER"),+ identity: object.version.identity.clone(),+ lifecycle: RoutineOperationLifecycle::Terminal,+ dispatched: true,+ acknowledged: true,+ error: None,+ readback: Some(RoutineReadback {+ identity: object.version.identity.clone(),+ state: RoutineReadbackState::Invalid,+ exists: Some(true),+ version: Some(object.version),+ source: object.source,+ definition_matches: Some(true),+ compiler_messages: Vec::new(),+ issues: Vec::new(),+ }),+ }+}++#[test]+fn correction_accepts_the_terminal_invalid_definition_but_not_a_competing_create() {+ let record = correction_record();+ let identity = record.identity.clone();+ assert!(matches!(+ correction_baseline(record.clone(), &endpoint("OWNER"), &identity).unwrap(),+ ExpectedRoutine::Present(_)+ ));+ let mut competing = record;+ competing.acknowledged = false;+ competing.readback.as_mut().unwrap().definition_matches = Some(false);+ let error = correction_baseline(competing, &endpoint("OWNER"), &identity).err().unwrap();+ assert!(error.contains("refresh and review"));+}++#[test]+fn matching_or_absent_readback_does_not_prove_an_unknown_request_has_terminated() {+ let mut record = correction_record();+ let identity = record.identity.clone();+ record.lifecycle = RoutineOperationLifecycle::Unproven;+ assert!(correction_baseline(record.clone(), &endpoint("OWNER"), &identity).is_err());+ let readback = record.readback.as_mut().unwrap();+ readback.state = RoutineReadbackState::Verified;+ readback.exists = Some(false);+ readback.version = None;+ readback.source = None;+ readback.definition_matches = None;+ assert!(correction_baseline(record.clone(), &endpoint("OWNER"), &identity).is_err());+ record.lifecycle = RoutineOperationLifecycle::Terminal;+ assert!(matches!(correction_baseline(record, &endpoint("OWNER"), &identity).unwrap(), ExpectedRoutine::Absent(_)));+}diff --git a/crates/dbx-core/src/schema/oracle_routines/readback.rs b/crates/dbx-core/src/schema/oracle_routines/readback.rsnew file mode 100644index 0000000000..5f71643483--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/readback.rs@@ -0,0 +1,504 @@+use super::*;+use dbx_sql::object_source_sql::{comparable_oracle_routine_definition, OracleRoutineDefinitionInput};++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct RoutineCompilerMessage {+ pub attribute: String,+ pub line: u64,+ pub position: u64,+ pub text: String,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+pub enum RoutineReadbackState {+ Verified,+ Invalid,+ Missing,+ Present,+ DefinitionMismatch,+ ReadbackFailed,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(tag = "kind", rename_all = "kebab-case")]+pub enum RoutineReadbackGoal {+ Definition { sql: String },+ Absent,+ Inspect,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineReadback {+ pub identity: RoutineIdentity,+ pub state: RoutineReadbackState,+ pub exists: Option<bool>,+ pub version: Option<RoutineVersion>,+ pub source: Option<String>,+ pub definition_matches: Option<bool>,+ pub compiler_messages: Vec<RoutineCompilerMessage>,+ pub issues: Vec<RoutineReadIssue>,+}++/// This reports only current object state. Callers must independently establish+/// the write request's terminal lifecycle before counting a verified deployment.+pub async fn read_oracle_routine_core(+ state: &AppState,+ connection_id: &str,+ database: &str,+ identity: RoutineIdentity,+ goal: RoutineReadbackGoal,+) -> Result<RoutineReadback, String> {+ if identity.owner.is_empty()+ || identity.name.is_empty()+ || !matches!(identity.kind, db::ObjectSourceKind::Procedure | db::ObjectSourceKind::Function)+ {+ return Err("Routine readback requires an exact standalone routine identity".into());+ }+ let config = connection_config(state, connection_id).await.ok_or("Connection not found")?;+ let (database_type, origin) = routine_source_origin(&config)?;+ let lifecycle = state.connection_lifecycle_snapshot(connection_id);+ let endpoint = RoutineEndpoint {+ connection_id: connection_id.into(),+ database: database.into(),+ schema: identity.owner.clone(),+ database_type,+ generation: lifecycle.generation(),+ };+ let catalog = LiveCatalog { state, endpoint: &endpoint, config: &config };+ let mut readback = readback(&catalog, &endpoint, identity, &goal, origin).await;+ if !state.connection_lifecycle_is_current(connection_id, &lifecycle) {+ readback.state = RoutineReadbackState::ReadbackFailed;+ readback.issues.push(issue("endpoint", "Connection changed during routine readback"));+ }+ Ok(readback)+}++pub(super) async fn read_namespace(+ catalog: &impl RoutineCatalog,+ identity: &RoutineIdentity,+ dba: bool,+) -> Result<CatalogReply, String> {+ let view = if dba { "SYS.DBA_OBJECTS" } else { "ALL_OBJECTS" };+ let reply = catalog.query(&format!(+ "SELECT OWNER, OBJECT_NAME, OBJECT_TYPE, OBJECT_ID, STATUS, \+ TO_CHAR(LAST_DDL_TIME, 'YYYY-MM-DD\"T\"HH24:MI:SS') LAST_DDL_TIME \+ FROM {view} WHERE OWNER = {} AND OBJECT_NAME = {} AND OBJECT_TYPE IN \+ ('TABLE','VIEW','SEQUENCE','PROCEDURE','FUNCTION','PACKAGE','MATERIALIZED VIEW','TYPE','SYNONYM') ORDER BY OBJECT_ID",+ literal(&identity.owner), literal(&identity.name),+ )).await?;+ reply.flags.check()?;+ Ok(reply)+}++pub(super) fn exact_version(reply: &CatalogReply, identity: &RoutineIdentity) -> Result<RoutineVersion, String> {+ if reply.rows.len() != 1 {+ return Err("Routine namespace is ambiguous or has a different object kind".into());+ }+ let row = &reply.rows[0];+ if reply.text(row, "OWNER")? != identity.owner+ || reply.text(row, "OBJECT_NAME")? != identity.name+ || reply.text(row, "OBJECT_TYPE")? != kind_name(&identity.kind)+ {+ return Err("Routine namespace contains a different owner, name or kind".into());+ }+ Ok(RoutineVersion {+ identity: identity.clone(),+ object_id: reply.integer(row, "OBJECT_ID")?.to_string(),+ status: reply.text(row, "STATUS")?,+ last_ddl_time: reply.text(row, "LAST_DDL_TIME")?,+ })+}++async fn compiler_messages(+ catalog: &impl RoutineCatalog,+ identity: &RoutineIdentity,+ messages: &mut Vec<RoutineCompilerMessage>,+) -> Result<(), String> {+ let mut sequence = None;+ loop {+ // OceanBase's first diagnostic can be SEQUENCE=0. The first page has+ // no lower bound; subsequent pages advance past the last actual row.+ let after = sequence.map(|sequence| format!(" AND SEQUENCE > {sequence}")).unwrap_or_default();+ let reply = catalog+ .query(&format!(+ "SELECT * FROM (SELECT SEQUENCE, ATTRIBUTE, LINE, POSITION, TEXT FROM ALL_ERRORS \+ WHERE {}{after} ORDER BY SEQUENCE) WHERE ROWNUM <= {PAGE_SIZE}",+ identity_filter(identity),+ ))+ .await?;+ if reply.rows.len() > PAGE_SIZE {+ return Err("Routine compiler diagnostics exceeded their page size".into());+ }+ for row in &reply.rows {+ let next = reply.integer(row, "SEQUENCE")?;+ if sequence.is_some_and(|sequence| next <= sequence) {+ return Err("Routine compiler diagnostic pagination is inconsistent".into());+ }+ sequence = Some(next);+ let attribute = reply.text(row, "ATTRIBUTE")?;+ if !matches!(attribute.as_str(), "ERROR" | "WARNING") {+ return Err("Routine compiler diagnostic severity is unknown".into());+ }+ messages.push(RoutineCompilerMessage {+ attribute,+ line: reply.integer(row, "LINE")?,+ position: reply.integer(row, "POSITION")?,+ text: reply.text(row, "TEXT")?,+ });+ }+ reply.flags.check()?;+ if reply.rows.len() < PAGE_SIZE {+ return Ok(());+ }+ }+}++fn comparable(source: String, endpoint: &RoutineEndpoint, identity: &RoutineIdentity) -> Result<String, String> {+ comparable_oracle_routine_definition(OracleRoutineDefinitionInput {+ database_type: endpoint.database_type,+ object_type: identity.kind.clone(),+ source_owner: identity.owner.clone(),+ target_owner: identity.owner.clone(),+ name: identity.name.clone(),+ source,+ replace: true,+ })+}++pub(super) async fn readback(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ identity: RoutineIdentity,+ goal: &RoutineReadbackGoal,+ origin: SourceOrigin,+) -> RoutineReadback {+ let mut result = RoutineReadback {+ identity,+ state: RoutineReadbackState::ReadbackFailed,+ exists: None,+ version: None,+ source: None,+ definition_matches: None,+ compiler_messages: Vec::new(),+ issues: Vec::new(),+ };+ let read: Result<(), String> = async {+ let login = catalog.query("SELECT USER AS LOGIN_OWNER FROM DUAL").await?;+ login.flags.check()?;+ if login.rows.len() != 1 {+ return Err("Routine namespace visibility is unknown".into());+ }+ let other_owner = login.text(&login.rows[0], "LOGIN_OWNER")? != result.identity.owner;+ let mut dba = false;+ let mut namespace = read_namespace(catalog, &result.identity, false).await?;+ // A positive exact ALL_OBJECTS identity is useful evidence for ordinary+ // saves to another owner. Only inferring absence requires full scope.+ if namespace.rows.is_empty() && other_owner {+ dba = true;+ namespace = read_namespace(catalog, &result.identity, true).await?;+ }+ result.exists = Some(!namespace.rows.is_empty());+ if namespace.rows.is_empty() {+ result.state = if *goal == RoutineReadbackGoal::Absent {+ RoutineReadbackState::Verified+ } else {+ RoutineReadbackState::Missing+ };+ return Ok(());+ }+ let version = exact_version(&namespace, &result.identity)?;+ result.version = Some(version.clone());+ let source = catalog.source(&result.identity).await?;+ result.source = Some(source.object.source.clone());+ check_source(catalog, endpoint, &result.identity, &source, origin).await?;+ compiler_messages(catalog, &result.identity, &mut result.compiler_messages).await?;+ let second = catalog.source(&result.identity).await?;+ second.flags.check()?;+ if second.object.name != source.object.name+ || second.object.schema != source.object.schema+ || second.object.object_type != source.object.object_type+ || second.object.source != source.object.source+ {+ return Err("Routine definition changed during readback".into());+ }+ let after = read_namespace(catalog, &result.identity, dba).await?;+ if exact_version(&after, &result.identity)? != version {+ return Err("Routine identity, status or DDL version changed during readback".into());+ }+ if let RoutineReadbackGoal::Definition { sql } = goal {+ result.definition_matches = Some(+ comparable(sql.clone(), endpoint, &result.identity)?+ == comparable(source.object.source.clone(), endpoint, &result.identity)?,+ );+ }+ result.state = if version.status != "VALID"+ || result.compiler_messages.iter().any(|message| message.attribute == "ERROR")+ {+ RoutineReadbackState::Invalid+ } else if result.definition_matches == Some(false) || *goal == RoutineReadbackGoal::Absent {+ RoutineReadbackState::DefinitionMismatch+ } else if result.definition_matches == Some(true) {+ RoutineReadbackState::Verified+ } else {+ RoutineReadbackState::Present+ };+ Ok(())+ }+ .await;+ if let Err(error) = read {+ result.state = RoutineReadbackState::ReadbackFailed;+ result.issues.push(issue("readback", error));+ }+ result+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;+ use std::sync::atomic::{AtomicUsize, Ordering};++ struct Catalog {+ login: &'static str,+ status: &'static str,+ messages: Vec<Vec<Value>>,+ exists: bool,+ fail: &'static str,+ wrong_kind: bool,+ source: String,+ incomplete_errors: bool,+ source_changes: bool,+ source_reads: AtomicUsize,+ }++ impl Default for Catalog {+ fn default() -> Self {+ Self {+ login: "OWNER",+ status: "VALID",+ messages: Vec::new(),+ exists: true,+ fail: "",+ wrong_kind: false,+ source: "CREATE OR REPLACE FUNCTION \"Read.Func\" RETURN NUMBER AS BEGIN RETURN 1; END".into(),+ incomplete_errors: false,+ source_changes: false,+ source_reads: AtomicUsize::new(0),+ }+ }+ }++ fn reply(columns: &[&str], rows: Vec<Vec<Value>>) -> CatalogReply {+ serde_json::from_value(json!({"columns":columns,"rows":rows})).unwrap()+ }++ #[async_trait::async_trait]+ impl RoutineCatalog for Catalog {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ if !self.fail.is_empty() && sql.contains(self.fail) {+ return Err("ORA-01031: insufficient privileges".into());+ }+ if sql.contains("LOGIN_OWNER") {+ return Ok(reply(&["LOGIN_OWNER"], vec![vec![json!(self.login)]]));+ }+ if sql.contains("ALL_ERRORS") {+ let after = sql+ .split_once("SEQUENCE > ")+ .map(|(_, rest)| rest.split_whitespace().next().unwrap().parse::<u64>().unwrap());+ let rows = self+ .messages+ .iter()+ .filter(|row| after.is_none_or(|sequence| row[0].as_u64().unwrap() > sequence))+ .take(PAGE_SIZE)+ .cloned()+ .collect();+ let mut reply = reply(&["SEQUENCE", "ATTRIBUTE", "LINE", "POSITION", "TEXT"], rows);+ reply.flags.truncated = self.incomplete_errors;+ return Ok(reply);+ }+ if sql.contains("SOURCE_ROWS") {+ let body = self.source.strip_prefix("CREATE OR REPLACE ").unwrap();+ return Ok(reply(+ &[+ "SOURCE_ROWS",+ "FIRST_LINE",+ "LAST_LINE",+ "SOURCE_CHARS",+ "HEAD_TRIM",+ "TAIL_TRIM",+ "SOURCE_HEAD",+ ],+ vec![vec![+ json!(1),+ json!(1),+ json!(1),+ json!(body.chars().count()),+ json!(0),+ json!(0),+ json!("FUNCTION"),+ ]],+ ));+ }+ Ok(reply(+ &["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "STATUS", "LAST_DDL_TIME"],+ if self.exists {+ vec![vec![+ json!("OWNER"),+ json!("Read.Func"),+ json!(if self.wrong_kind { "PACKAGE" } else { "FUNCTION" }),+ json!(12),+ json!(self.status),+ json!("2026-10-21T08:30:00"),+ ]]+ } else {+ vec![]+ },+ ))+ }+ async fn source(&self, _identity: &RoutineIdentity) -> Result<SourceReply, String> {+ let calls = self.source_reads.fetch_add(1, Ordering::SeqCst);+ let text = if self.source_changes && calls > 0 {+ self.source.replace("RETURN 1", "RETURN 3")+ } else {+ self.source.clone()+ };+ Ok(serde_json::from_value(+ json!({"name":"Read.Func","schema":"OWNER","object_type":"FUNCTION","source":text}),+ )+ .unwrap())+ }+ }++ async fn run(catalog: &Catalog, goal: RoutineReadbackGoal) -> RoutineReadback {+ let endpoint = RoutineEndpoint {+ connection_id: "target".into(),+ database: "tenant".into(),+ schema: "OWNER".into(),+ database_type: DatabaseType::OceanbaseOracle,+ generation: 1,+ };+ readback(+ catalog,+ &endpoint,+ RoutineIdentity { owner: "OWNER".into(), name: "Read.Func".into(), kind: db::ObjectSourceKind::Function },+ &goal,+ SourceOrigin::OceanBaseDictionary,+ )+ .await+ }++ fn expected() -> RoutineReadbackGoal {+ RoutineReadbackGoal::Definition {+ sql: "CREATE OR REPLACE FUNCTION \"OWNER\".\"Read.Func\" RETURN NUMBER AS BEGIN RETURN 1; END;".into(),+ }+ }++ #[tokio::test]+ async fn valid_complete_definition_is_verified_and_warning_remains_visible() {+ let catalog = Catalog {+ messages: vec![vec![json!(1), json!("WARNING"), json!(1), json!(12), json!("compiler warning")]],+ ..Default::default()+ };+ let result = run(&catalog, expected()).await;+ assert_eq!(result.state, RoutineReadbackState::Verified);+ assert_eq!(result.definition_matches, Some(true));+ assert_eq!(result.compiler_messages[0].attribute, "WARNING");+ }++ #[tokio::test]+ async fn invalid_or_error_is_not_a_successful_definition_readback() {+ let invalid = Catalog { status: "INVALID", ..Default::default() };+ assert_eq!(run(&invalid, expected()).await.state, RoutineReadbackState::Invalid);+ let error = Catalog {+ messages: vec![vec![json!(1), json!("ERROR"), json!(1), json!(72), json!("missing identifier")]],+ ..Default::default()+ };+ let result = run(&error, expected()).await;+ assert_eq!(result.state, RoutineReadbackState::Invalid);+ assert_eq!(result.compiler_messages[0].position, 72);+ }++ #[tokio::test]+ async fn zero_based_first_error_or_warning_is_not_dropped() {+ for (attribute, expected_state) in+ [("ERROR", RoutineReadbackState::Invalid), ("WARNING", RoutineReadbackState::Verified)]+ {+ let catalog = Catalog {+ messages: vec![vec![json!(0), json!(attribute), json!(1), json!(63), json!("first diagnostic")]],+ ..Default::default()+ };+ let result = run(&catalog, expected()).await;+ assert_eq!(result.state, expected_state);+ assert_eq!(result.compiler_messages.len(), 1);+ assert_eq!(result.compiler_messages[0].attribute, attribute);+ assert_eq!(result.compiler_messages[0].position, 63);+ }+ }++ #[tokio::test]+ async fn zero_based_diagnostics_continue_after_a_full_first_page_without_loss_or_duplicates() {+ let catalog = Catalog {+ messages: (0..300)+ .map(|sequence| {+ vec![json!(sequence), json!("WARNING"), json!(1), json!(sequence + 1), json!("warning")]+ })+ .collect(),+ ..Default::default()+ };+ let result = run(&catalog, expected()).await;+ assert_eq!(result.state, RoutineReadbackState::Verified);+ assert_eq!(result.compiler_messages.len(), 300);+ assert_eq!(result.compiler_messages[0].position, 1);+ assert_eq!(result.compiler_messages[299].position, 300);+ }++ #[tokio::test]+ async fn compiler_read_failure_retains_source_without_reporting_verified() {+ let catalog = Catalog { fail: "ALL_ERRORS", ..Default::default() };+ let result = run(&catalog, expected()).await;+ assert_eq!(result.state, RoutineReadbackState::ReadbackFailed);+ assert_eq!(result.source.as_deref(), Some(catalog.source.as_str()));+ assert_eq!(result.issues[0].code, "permission-denied");+ }++ #[tokio::test]+ async fn absence_is_verified_only_after_a_complete_namespace_read() {+ let catalog = Catalog { exists: false, ..Default::default() };+ assert_eq!(run(&catalog, RoutineReadbackGoal::Absent).await.state, RoutineReadbackState::Verified);+ assert_eq!(run(&catalog, expected()).await.state, RoutineReadbackState::Missing);+ let denied = Catalog { exists: false, fail: "ALL_OBJECTS", ..Default::default() };+ assert_eq!(run(&denied, RoutineReadbackGoal::Absent).await.state, RoutineReadbackState::ReadbackFailed);+ }++ #[tokio::test]+ async fn definition_mismatch_and_shared_namespace_collision_are_not_success() {+ let catalog =+ Catalog { source: Catalog::default().source.replace("RETURN 1", "RETURN 2"), ..Default::default() };+ assert_eq!(run(&catalog, expected()).await.state, RoutineReadbackState::DefinitionMismatch);+ let catalog = Catalog { wrong_kind: true, ..Default::default() };+ assert_eq!(run(&catalog, expected()).await.state, RoutineReadbackState::ReadbackFailed);+ }++ #[tokio::test]+ async fn incomplete_diagnostics_or_a_changed_readback_never_count_as_verified() {+ let catalog = Catalog { incomplete_errors: true, ..Default::default() };+ assert_eq!(run(&catalog, expected()).await.state, RoutineReadbackState::ReadbackFailed);+ let catalog = Catalog { source_changes: true, ..Default::default() };+ let result = run(&catalog, expected()).await;+ assert_eq!(result.state, RoutineReadbackState::ReadbackFailed);+ assert_eq!(result.source.as_deref(), Some(catalog.source.as_str()));+ }++ #[tokio::test]+ async fn positive_other_owner_readback_does_not_add_a_global_dictionary_permission() {+ let catalog = Catalog { login: "OTHER_LOGIN", fail: "SYS.DBA_OBJECTS", ..Default::default() };+ assert_eq!(run(&catalog, expected()).await.state, RoutineReadbackState::Verified);+ let catalog = Catalog { login: "OTHER_LOGIN", exists: false, fail: "SYS.DBA_OBJECTS", ..Default::default() };+ let result = run(&catalog, RoutineReadbackGoal::Absent).await;+ assert_eq!(result.state, RoutineReadbackState::ReadbackFailed);+ assert_eq!(result.exists, None);+ }+}diff --git a/crates/dbx-core/src/schema/oracle_routines/references.rs b/crates/dbx-core/src/schema/oracle_routines/references.rsnew file mode 100644index 0000000000..8b9c91fa12--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/references.rs@@ -0,0 +1,537 @@+//! Target-side binding for the closed static draft grammar. Every successful+//! catalog read is retained for the dispatch-time check; an empty visible subset+//! is never used as proof that a higher-priority name does not exist.+use super::*;+use dbx_sql::object_source_sql::{+ OracleDraftIssue, OracleDraftReference, OracleDraftReferenceRole, OracleRoutineDraftAnalysis,+};+use std::collections::BTreeSet;++#[derive(Clone, Serialize)]+pub(super) struct CatalogReadProof {+ pub sql: String,+ pub columns: Vec<String>,+ pub rows: Vec<Vec<Value>>,+}++impl CatalogReadProof {+ pub async fn verify(&self, catalog: &impl RoutineCatalog) -> Result<(), String> {+ let current = catalog.query(&self.sql).await?;+ current.flags.check()?;+ if current.columns != self.columns || current.rows != self.rows {+ return Err("Referenced object, name resolution, signature, columns or direct privileges changed; validate the draft again".into());+ }+ Ok(())+ }+}++#[derive(Clone)]+pub(super) struct SelectedFinalDraft {+ pub identity: RoutineIdentity,+ // None denotes an explicitly selected deletion, not an unreadable signature.+ pub analysis: Option<OracleRoutineDraftAnalysis>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ResolvedRoutineReference {+ pub owner: String,+ pub name: String,+ pub kind: String,+ pub member: Option<String>,+ pub selected_index: Option<usize>,+ pub line: u64,+ pub column: u64,+}++pub(super) struct DraftResolution {+ pub references: Vec<ResolvedRoutineReference>,+ pub selected_dependencies: BTreeSet<usize>,+ pub proofs: Vec<CatalogReadProof>,+ pub issues: Vec<OracleDraftIssue>,+}++#[derive(Clone)]+struct Object {+ owner: String,+ name: String,+ kind: String,+ object_id: String,+ status: String,+ selected: Option<usize>,+}++struct Resolver<'a, C> {+ catalog: &'a C,+ endpoint: &'a RoutineEndpoint,+ login: String,+ selected: &'a [SelectedFinalDraft],+ output: DraftResolution,+}++impl<C: RoutineCatalog> Resolver<'_, C> {+ async fn query(&mut self, sql: String) -> Result<CatalogReply, String> {+ let reply = self.catalog.query(&sql).await?;+ reply.flags.check()?;+ if reply.rows.len() > PAGE_SIZE {+ return Err("Dependency metadata exceeded its verified page size".into());+ }+ self.output.proofs.push(CatalogReadProof { sql, columns: reply.columns.clone(), rows: reply.rows.clone() });+ Ok(reply)+ }++ async fn rows(&mut self, projection: &str, from: &str, order: &str) -> Result<CatalogReply, String> {+ let mut columns = None;+ let mut rows = Vec::new();+ loop {+ let offset = rows.len();+ let reply = self+ .query(format!(+ "SELECT * FROM (SELECT {projection}, ROW_NUMBER() OVER (ORDER BY {order}) RN FROM {from}) \+ WHERE RN > {offset} AND RN <= {} ORDER BY RN",+ offset + PAGE_SIZE,+ ))+ .await?;+ if columns.as_ref().is_some_and(|known| known != &reply.columns) {+ return Err("Dependency metadata columns changed between pages".into());+ }+ for (index, row) in reply.rows.iter().enumerate() {+ if reply.integer(row, "RN")? != (offset + index + 1) as u64 {+ return Err("Dependency metadata pagination is incomplete".into());+ }+ }+ let finished = reply.rows.len() < PAGE_SIZE;+ columns = Some(reply.columns);+ rows.extend(reply.rows);+ if finished {+ return Ok(CatalogReply { columns: columns.unwrap(), rows, flags: ReadFlags::default() });+ }+ }+ }++ async fn namespace(&mut self, owner: &str, name: &str) -> Result<Option<Object>, String> {+ if let Some((index, selected)) = self+ .selected+ .iter()+ .enumerate()+ .find(|(_, draft)| draft.identity.owner == owner && draft.identity.name == name)+ {+ if selected.analysis.is_none() {+ return Err(format!("Reference {owner}.{name} is selected for deletion"));+ }+ return Ok(Some(Object {+ owner: owner.into(),+ name: name.into(),+ kind: kind_name(&selected.identity.kind).into(),+ object_id: String::new(),+ status: "VALID".into(),+ selected: Some(index),+ }));+ }+ let make_sql = |view: &str| {+ format!(+ "SELECT OWNER, OBJECT_NAME, OBJECT_TYPE, OBJECT_ID, STATUS, \+ TO_CHAR(LAST_DDL_TIME, 'YYYY-MM-DD\"T\"HH24:MI:SS') LAST_DDL_TIME FROM {view} \+ WHERE OWNER = {} AND OBJECT_NAME = {} AND OBJECT_TYPE IN \+ ('TABLE','VIEW','SEQUENCE','PROCEDURE','FUNCTION','PACKAGE','MATERIALIZED VIEW','TYPE','SYNONYM') ORDER BY OBJECT_ID",+ literal(owner), literal(name),+ )+ };+ let mut reply = self.query(make_sql("ALL_OBJECTS")).await?;+ if reply.rows.is_empty() && owner != self.login && owner != "PUBLIC" {+ // A positive ALL_OBJECTS match is sufficient. Absence in another+ // owner's namespace needs complete visibility, not an ALL_* fallback.+ reply = self.query(make_sql("SYS.DBA_OBJECTS")).await?;+ }+ if reply.rows.is_empty() {+ return Ok(None);+ }+ if reply.rows.len() != 1 {+ return Err(format!("Namespace {owner}.{name} is ambiguous"));+ }+ let row = &reply.rows[0];+ if reply.text(row, "OWNER")? != owner || reply.text(row, "OBJECT_NAME")? != name {+ return Err("Dependency metadata returned another identity".into());+ }+ Ok(Some(Object {+ owner: owner.into(),+ name: name.into(),+ kind: reply.text(row, "OBJECT_TYPE")?,+ object_id: reply.integer(row, "OBJECT_ID")?.to_string(),+ status: reply.text(row, "STATUS")?,+ selected: None,+ }))+ }++ async fn object(&mut self, owner: &str, name: &str, public_fallback: bool) -> Result<Option<Object>, String> {+ let mut object = self.namespace(owner, name).await?;+ if object.is_none() && public_fallback {+ object = self.namespace("PUBLIC", name).await?;+ }+ let mut visited = BTreeSet::new();+ for _ in 0..16 {+ let Some(current) = object else {+ return Ok(None);+ };+ if current.kind != "SYNONYM" {+ return Ok(Some(current));+ }+ if !visited.insert((current.owner.clone(), current.name.clone())) {+ return Err("Synonym cycle prevents complete dependency resolution".into());+ }+ let reply = self+ .query(format!(+ "SELECT OWNER, SYNONYM_NAME, TABLE_OWNER, TABLE_NAME, DB_LINK FROM ALL_SYNONYMS \+ WHERE OWNER = {} AND SYNONYM_NAME = {} ORDER BY OWNER, SYNONYM_NAME",+ literal(¤t.owner),+ literal(¤t.name),+ ))+ .await?;+ if reply.rows.len() != 1 {+ return Err("Synonym target is unavailable or ambiguous".into());+ }+ let row = &reply.rows[0];+ if !matches!(reply.cell(row, "DB_LINK")?, Value::Null) && reply.cell(row, "DB_LINK")? != "" {+ return Err("A database-link dependency must be removed from this static deployment plan".into());+ }+ object = self.namespace(&reply.text(row, "TABLE_OWNER")?, &reply.text(row, "TABLE_NAME")?).await?;+ }+ Err("Synonym resolution exceeded its verified depth".into())+ }++ async fn accessible(&mut self, object: &Object, relation: bool) -> Result<(), String> {+ if object.status != "VALID" {+ return Err(format!("Dependency {}.{} is not VALID", object.owner, object.name));+ }+ if object.owner == self.endpoint.schema {+ return Ok(());+ }+ let privileges = if relation { "'SELECT','READ'" } else { "'EXECUTE'" };+ let grants = self.rows("GRANTEE, PRIVILEGE", &format!(+ "SYS.ALL_TAB_PRIVS WHERE TABLE_SCHEMA = {} AND TABLE_NAME = {} AND GRANTEE IN ({}, 'PUBLIC') AND PRIVILEGE IN ({privileges})",+ literal(&object.owner), literal(&object.name), literal(&self.endpoint.schema),+ ), "GRANTEE, PRIVILEGE").await?;+ if !grants.rows.is_empty() {+ return Ok(());+ }+ // Stored AUTHID DEFINER code cannot borrow enabled roles. Query only+ // direct system grants to the defining owner, never SESSION_PRIVS.+ if object.owner != "SYS" {+ let privilege = if relation { "'SELECT ANY TABLE','READ ANY TABLE'" } else { "'EXECUTE ANY PROCEDURE'" };+ let from = if self.login == self.endpoint.schema {+ format!("USER_SYS_PRIVS WHERE PRIVILEGE IN ({privilege})")+ } else {+ format!(+ "SYS.DBA_SYS_PRIVS WHERE GRANTEE = {} AND PRIVILEGE IN ({privilege})",+ literal(&self.endpoint.schema)+ )+ };+ if !self.rows("PRIVILEGE", &from, "PRIVILEGE").await?.rows.is_empty() {+ return Ok(());+ }+ }+ Err(format!("Direct or PUBLIC privilege for {}.{} is not proven for {}; grant the required privilege and validate again", object.owner, object.name, self.endpoint.schema))+ }++ async fn columns(&mut self, object: &Object) -> Result<BTreeSet<String>, String> {+ self.accessible(object, true).await?;+ let reply = self+ .rows(+ "COLUMN_ID, COLUMN_NAME",+ &format!(+ "ALL_TAB_COLUMNS WHERE OWNER = {} AND TABLE_NAME = {}",+ literal(&object.owner),+ literal(&object.name),+ ),+ "COLUMN_ID, COLUMN_NAME",+ )+ .await?;+ if reply.rows.is_empty() {+ return Err("The relation's complete column list is unavailable".into());+ }+ reply.rows.iter().map(|row| reply.text(row, "COLUMN_NAME")).collect()+ }++ async fn call(+ &mut self,+ object: &Object,+ member: Option<&str>,+ reference: &OracleDraftReference,+ ) -> Result<(), String> {+ let expected = if reference.role == OracleDraftReferenceRole::Procedure { "PROCEDURE" } else { "FUNCTION" };+ if object.name == "DBMS_SQL" {+ return Err("DBMS_SQL execution cannot be proven by this static plan; use supported static SQL or deselect this object".into());+ }+ if let Some(index) = object.selected {+ if member.is_some() || object.kind != expected {+ return Err("Selected dependency has another routine kind".into());+ }+ let parameters =+ &self.selected[index].analysis.as_ref().ok_or("Selected dependency is deleted")?.parameters;+ return check_arguments(+ parameters.iter().map(|parameter| (parameter.mode.as_str(), parameter.has_default)),+ reference,+ );+ }+ if (member.is_some() && object.kind != "PACKAGE") || (member.is_none() && object.kind != expected) {+ return Err(format!("Dependency {}.{} is not an unambiguous {expected}", object.owner, object.name));+ }+ self.accessible(object, false).await?;+ let member_filter = member+ .map(|member| format!("PROCEDURE_NAME = {}", literal(member)))+ .unwrap_or_else(|| "PROCEDURE_NAME IS NULL".into());+ let procedures = self+ .rows(+ "OBJECT_ID, SUBPROGRAM_ID",+ &format!(+ "ALL_PROCEDURES WHERE OWNER = {} AND OBJECT_ID = {} AND {member_filter}",+ literal(&object.owner),+ object.object_id,+ ),+ "SUBPROGRAM_ID",+ )+ .await?;+ if procedures.rows.len() != 1 {+ return Err(+ "Routine member is missing, overloaded or not fully visible; use an unambiguous supported call".into(),+ );+ }+ let subprogram = procedures.integer(&procedures.rows[0], "SUBPROGRAM_ID")?;+ let arguments = self+ .rows(+ "POSITION, SEQUENCE, IN_OUT, DATA_TYPE, TYPE_OWNER, TYPE_NAME, TYPE_SUBNAME, DEFAULTED",+ &format!(+ "ALL_ARGUMENTS WHERE OWNER = {} AND OBJECT_ID = {} AND SUBPROGRAM_ID = {subprogram} AND DATA_LEVEL = 0",+ literal(&object.owner), object.object_id,+ ),+ "POSITION, SEQUENCE",+ )+ .await?;+ let mut parameters = Vec::new();+ let mut function = false;+ for row in &arguments.rows {+ if !matches!(arguments.cell(row, "TYPE_NAME")?, Value::Null)+ || !matches!(arguments.cell(row, "TYPE_SUBNAME")?, Value::Null)+ {+ return Err("A user-defined argument type requires manual correction or a smaller selection".into());+ }+ let data_type = arguments.text(row, "DATA_TYPE")?;+ if !scalar_argument_type(&data_type) {+ return Err(format!("Argument type {data_type} is outside this static plan"));+ }+ let position = arguments.integer(row, "POSITION")?;+ if position == 0 {+ if function {+ return Err("Routine return metadata is ambiguous".into());+ }+ function = true;+ } else {+ if position != parameters.len() as u64 + 1 {+ return Err("Routine argument metadata has a gap".into());+ }+ parameters.push((arguments.text(row, "IN_OUT")?, arguments.text(row, "DEFAULTED")? == "Y"));+ }+ }+ if function != (expected == "FUNCTION") {+ return Err("Routine member kind could not be confirmed".into());+ }+ check_arguments(parameters.iter().map(|(mode, default)| (mode.as_str(), *default)), reference)+ }++ async fn resolve_call(&mut self, reference: &OracleDraftReference) -> Result<(Object, Option<String>), String> {+ let parts: Vec<&str> = reference.parts.iter().map(|name| name.value.as_str()).collect();+ let owner = self.endpoint.schema.clone();+ let (object, member) = match parts.as_slice() {+ [name] => (self.object(&owner, name, true).await?, None),+ [first, second] => {+ let prefix = self.object(&owner, first, true).await?;+ let qualified = self.object(first, second, false).await?;+ match (prefix, qualified) {+ (Some(prefix), Some(_)) => return Err(format!("{}.{} has competing package/schema interpretations; qualify a package member with all three name parts", prefix.name, second)),+ (Some(prefix), None) if prefix.kind == "PACKAGE" => (Some(prefix), Some((*second).into())),+ (Some(_), None) => return Err("The first name is captured by a local object; qualify or rename this reference".into()),+ (None, qualified) => (qualified, None),+ }+ }+ [schema, package, member] => {+ if self.object(&owner, schema, true).await?.is_some() {+ return Err("The schema prefix is captured by a local object; use an unambiguous reference".into());+ }+ (self.object(schema, package, false).await?, Some((*member).into()))+ }+ _ => return Err("Reference needs one, two or three exact name parts".into()),+ };+ let object = object.ok_or("Referenced routine was not confirmed in the target namespace")?;+ self.call(&object, member.as_deref(), reference).await?;+ Ok((object, member))+ }+}++fn scalar_argument_type(value: &str) -> bool {+ matches!(+ value,+ "NUMBER"+ | "INTEGER"+ | "BINARY_INTEGER"+ | "PLS_INTEGER"+ | "BINARY_FLOAT"+ | "BINARY_DOUBLE"+ | "FLOAT"+ | "VARCHAR2"+ | "NVARCHAR2"+ | "CHAR"+ | "NCHAR"+ | "BOOLEAN"+ | "PL/SQL BOOLEAN"+ | "DATE"+ | "TIMESTAMP"+ | "RAW"+ )+}++fn check_arguments<'a>(+ parameters: impl Iterator<Item = (&'a str, bool)>,+ reference: &OracleDraftReference,+) -> Result<(), String> {+ let parameters: Vec<_> = parameters.collect();+ let supplied = reference.argument_writable.len();+ if supplied > parameters.len() || parameters.iter().skip(supplied).any(|(_, default)| !default) {+ return Err("Call argument count does not match the final signature/defaults".into());+ }+ for ((mode, _), writable) in parameters.iter().zip(&reference.argument_writable) {+ if !matches!(*mode, "IN" | "OUT" | "IN OUT" | "IN/OUT") || (*mode != "IN" && !writable) {+ return Err("OUT/IN OUT arguments must be writable local scalars".into());+ }+ }+ Ok(())+}++pub(super) async fn resolve_draft(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ selected: &[SelectedFinalDraft],+ index: usize,+) -> DraftResolution {+ let mut resolver = Resolver {+ catalog,+ endpoint,+ login: String::new(),+ selected,+ output: DraftResolution {+ references: Vec::new(),+ selected_dependencies: BTreeSet::new(),+ proofs: Vec::new(),+ issues: Vec::new(),+ },+ };+ let Some(analysis) = &selected[index].analysis else {+ return resolver.output;+ };+ if !analysis.complete {+ resolver.output.issues = analysis.issues.clone();+ return resolver.output;+ }+ let login = async {+ let reply = resolver.query("SELECT USER AS LOGIN_OWNER FROM DUAL".into()).await?;+ if reply.rows.len() != 1 {+ return Err("Target owner visibility is unknown".to_owned());+ }+ reply.text(&reply.rows[0], "LOGIN_OWNER")+ }+ .await;+ match login {+ Ok(login) => resolver.login = login,+ Err(error) => {+ resolver.output.issues.push(OracleDraftIssue {+ code: "target-visibility".into(),+ message: error,+ line: 1,+ column: 1,+ });+ return resolver.output;+ }+ }+ let mut relations: BTreeMap<usize, (Object, BTreeSet<String>)> = BTreeMap::new();+ for (reference_index, reference) in analysis.references.iter().enumerate() {+ let resolution: Result<Option<(Object, Option<String>)>, String> = async {+ if reference.role == OracleDraftReferenceRole::Relation {+ let parts: Vec<&str> = reference.parts.iter().map(|part| part.value.as_str()).collect();+ let object = match parts.as_slice() {+ [name] => resolver.object(&endpoint.schema, name, true).await?,+ [owner, name] => resolver.object(owner, name, false).await?,+ _ => return Err("A relation needs an exact local or owner.table name".into()),+ }+ .ok_or("Target relation is not confirmed")?;+ if !matches!(object.kind.as_str(), "TABLE" | "VIEW" | "MATERIALIZED VIEW") {+ return Err("FROM does not resolve to a table or view".into());+ }+ let columns = resolver.columns(&object).await?;+ relations.insert(reference_index, (object.clone(), columns));+ return Ok(Some((object, None)));+ }+ if let Some(query) = reference.query {+ let query = analysis.queries.get(query).ok_or("SQL reference has no verified query scope")?;+ let (relation, columns) =+ relations.get(&query.relation_reference).ok_or("SQL relation/columns are not verified")?;+ let values: Vec<&str> = reference.parts.iter().map(|part| part.value.as_str()).collect();+ if reference.role == OracleDraftReferenceRole::Value {+ match values.as_slice() {+ [column] if columns.contains(*column) => return Ok(None),+ [qualifier, column]+ if query.alias.as_ref().map(|alias| alias.value.as_str()).unwrap_or(&relation.name)+ == *qualifier =>+ {+ return if columns.contains(*column) {+ Ok(None)+ } else {+ Err("The qualified SQL column is not present in the complete column list".into())+ };+ }+ [_, _] if query.alias.as_ref().is_some_and(|alias| alias.value == reference.parts[0].value) => {+ return Err("SQL alias cannot be used as a schema/routine prefix".into())+ }+ _ => {}+ }+ } else if query.alias.as_ref().is_some_and(|alias| alias.value == reference.parts[0].value) {+ return Err("SQL alias shadows this routine prefix".into());+ }+ if reference.local_binding.is_some() {+ return if reference.role == OracleDraftReferenceRole::Value && reference.parts.len() == 1 {+ Ok(None)+ } else {+ Err("A local scalar shadows this routine prefix; calls or member access are not supported on scalar bindings".into())+ };+ }+ }+ resolver.resolve_call(reference).await.map(Some)+ }+ .await;+ match resolution {+ Ok(Some((object, member))) => {+ if let Some(dependency) = object.selected.filter(|dependency| *dependency != index) {+ resolver.output.selected_dependencies.insert(dependency);+ }+ resolver.output.references.push(ResolvedRoutineReference {+ owner: object.owner,+ name: object.name,+ kind: object.kind,+ member,+ selected_index: object.selected,+ line: reference.line,+ column: reference.column,+ });+ }+ Ok(None) => {}+ Err(message) => resolver.output.issues.push(OracleDraftIssue {+ code: "unresolved-reference".into(),+ message,+ line: reference.line,+ column: reference.column,+ }),+ }+ }+ resolver.output+}++#[cfg(test)]+mod tests;diff --git a/crates/dbx-core/src/schema/oracle_routines/references/tests.rs b/crates/dbx-core/src/schema/oracle_routines/references/tests.rsnew file mode 100644index 0000000000..609de39b62--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/references/tests.rs@@ -0,0 +1,379 @@+use super::*;+use dbx_sql::object_source_sql::{analyze_oracle_routine_draft, EditableObjectSourceSqlInput, OracleDraftParameter};+use serde_json::json;+use std::sync::atomic::{AtomicBool, Ordering};++#[derive(Clone)]+struct Entry {+ owner: &'static str,+ name: &'static str,+ kind: &'static str,+ columns: Vec<&'static str>,+ synonym: Option<(&'static str, &'static str, Option<&'static str>)>,+ member: Option<&'static str>,+ function: bool,+ parameters: Vec<(&'static str, bool)>,+ grant: bool,+}++impl Entry {+ fn object(owner: &'static str, name: &'static str, kind: &'static str) -> Self {+ Self {+ owner,+ name,+ kind,+ columns: vec!["N"],+ synonym: None,+ member: None,+ function: kind == "FUNCTION",+ parameters: Vec::new(),+ grant: false,+ }+ }+}++#[derive(Default)]+struct Catalog {+ entries: Vec<Entry>,+ dba_denied: bool,+ incomplete_columns: bool,+ changed: AtomicBool,+}++fn value_after(sql: &str, field: &str) -> String {+ sql.split(&format!("{field} = '")).nth(1).unwrap_or("").split('\'').next().unwrap_or("").into()+}+fn reply(columns: &[&str], rows: Vec<Vec<Value>>) -> CatalogReply {+ serde_json::from_value(json!({"columns":columns,"rows":rows})).unwrap()+}+fn page(columns: &[&str], mut rows: Vec<Vec<Value>>) -> CatalogReply {+ let mut columns = columns.to_vec();+ columns.push("RN");+ for (index, row) in rows.iter_mut().enumerate() {+ row.push(json!(index + 1));+ }+ reply(&columns, rows)+}++#[async_trait::async_trait]+impl RoutineCatalog for Catalog {+ async fn source(&self, _: &RoutineIdentity) -> Result<SourceReply, String> {+ panic!("Draft resolution must not execute or fetch an implementation body")+ }+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ if sql.contains("LOGIN_OWNER") {+ return Ok(reply(&["LOGIN_OWNER"], vec![vec![json!("OWNER")]]));+ }+ if sql.contains("DBA_OBJECTS") && self.dba_denied {+ return Err("ORA-00942: dictionary unavailable".into());+ }+ let owner = value_after(sql, "OWNER");+ let name = value_after(sql, "OBJECT_NAME");+ if sql.contains("ALL_OBJECTS") || sql.contains("DBA_OBJECTS") {+ let rows = self+ .entries+ .iter()+ .enumerate()+ .filter(|(_, entry)| entry.owner == owner && entry.name == name)+ .map(|(index, entry)| {+ vec![+ json!(entry.owner),+ json!(entry.name),+ json!(entry.kind),+ json!(index + 1),+ json!(if self.changed.load(Ordering::SeqCst) { "INVALID" } else { "VALID" }),+ json!("2026-10-21T00:00:00"),+ ]+ })+ .collect();+ return Ok(reply(&["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "STATUS", "LAST_DDL_TIME"], rows));+ }+ if sql.contains("ALL_SYNONYMS") {+ let name = value_after(sql, "SYNONYM_NAME");+ return Ok(reply(+ &["OWNER", "SYNONYM_NAME", "TABLE_OWNER", "TABLE_NAME", "DB_LINK"],+ self.entries+ .iter()+ .filter(|entry| entry.owner == owner && entry.name == name)+ .filter_map(|entry| {+ entry.synonym.map(|(target_owner, target_name, link)| {+ vec![json!(owner), json!(name), json!(target_owner), json!(target_name), json!(link)]+ })+ })+ .collect(),+ ));+ }+ if sql.contains("ALL_TAB_COLUMNS") {+ let name = value_after(sql, "TABLE_NAME");+ let rows = self+ .entries+ .iter()+ .find(|entry| entry.owner == owner && entry.name == name)+ .map(|entry| {+ entry.columns.iter().enumerate().map(|(index, name)| vec![json!(index + 1), json!(name)]).collect()+ })+ .unwrap_or_default();+ let mut result = page(&["COLUMN_ID", "COLUMN_NAME"], rows);+ result.flags.truncated = self.incomplete_columns;+ return Ok(result);+ }+ if sql.contains("ALL_TAB_PRIVS") {+ let owner = value_after(sql, "TABLE_SCHEMA");+ let name = value_after(sql, "TABLE_NAME");+ let entry = self.entries.iter().find(|entry| entry.owner == owner && entry.name == name);+ return Ok(page(+ &["GRANTEE", "PRIVILEGE"],+ entry+ .filter(|entry| entry.grant)+ .map(|entry| {+ vec![vec![json!("OWNER"), json!(if entry.kind == "TABLE" { "SELECT" } else { "EXECUTE" })]]+ })+ .unwrap_or_default(),+ ));+ }+ if sql.contains("SYS_PRIVS") {+ return Ok(page(&["PRIVILEGE"], Vec::new()));+ }+ if sql.contains("ALL_PROCEDURES") || sql.contains("ALL_ARGUMENTS") {+ let id =+ sql.split("OBJECT_ID = ").nth(1).unwrap().split_whitespace().next().unwrap().parse::<usize>().unwrap();+ let entry = &self.entries[id - 1];+ if sql.contains("ALL_PROCEDURES") {+ let member = value_after(sql, "PROCEDURE_NAME");+ return Ok(page(+ &["OBJECT_ID", "SUBPROGRAM_ID"],+ if entry.member.unwrap_or("") == member { vec![vec![json!(id), json!(1)]] } else { Vec::new() },+ ));+ }+ let mut rows = Vec::new();+ if entry.function {+ rows.push(vec![+ json!(0),+ json!(1),+ json!("OUT"),+ json!("NUMBER"),+ Value::Null,+ Value::Null,+ Value::Null,+ json!("N"),+ ]);+ }+ for (index, (mode, default)) in entry.parameters.iter().enumerate() {+ rows.push(vec![+ json!(index + 1),+ json!(rows.len() + 1),+ json!(mode),+ json!("NUMBER"),+ Value::Null,+ Value::Null,+ Value::Null,+ json!(if *default { "Y" } else { "N" }),+ ]);+ }+ return Ok(page(+ &[+ "POSITION",+ "SEQUENCE",+ "IN_OUT",+ "DATA_TYPE",+ "TYPE_OWNER",+ "TYPE_NAME",+ "TYPE_SUBNAME",+ "DEFAULTED",+ ],+ rows,+ ));+ }+ panic!("Unexpected metadata query: {sql}")+ }+}++fn endpoint() -> RoutineEndpoint {+ RoutineEndpoint {+ connection_id: "target".into(),+ database: "tenant".into(),+ schema: "OWNER".into(),+ database_type: DatabaseType::OceanbaseOracle,+ generation: 1,+ }+}+fn draft(name: &str, body: &str) -> SelectedFinalDraft {+ let identity = RoutineIdentity { owner: "OWNER".into(), name: name.into(), kind: db::ObjectSourceKind::Function };+ let analysis = analyze_oracle_routine_draft(EditableObjectSourceSqlInput {+ database_type: endpoint().database_type,+ object_type: identity.kind.clone(),+ schema: Some(identity.owner.clone()),+ name: identity.name.clone(),+ source: format!("CREATE FUNCTION \"OWNER\".\"{name}\" RETURN NUMBER AS {body}"),+ });+ assert!(analysis.complete, "{:?}", analysis.issues);+ SelectedFinalDraft { identity, analysis: Some(analysis) }+}++#[tokio::test]+async fn final_selected_signatures_resolve_zero_argument_values_before_creation_and_self_recursion_is_not_a_cycle() {+ let selected = vec![draft("Caller", "BEGIN RETURN \"Callee\"; END;"), draft("Callee", "BEGIN RETURN 1; END;")];+ let result = resolve_draft(&Catalog::default(), &endpoint(), &selected, 0).await;+ assert!(result.issues.is_empty(), "{:?}", result.issues);+ assert_eq!(result.selected_dependencies, BTreeSet::from([1]));+ let selected = vec![draft("Self", "BEGIN RETURN \"Self\"; END;")];+ let result = resolve_draft(&Catalog::default(), &endpoint(), &selected, 0).await;+ assert!(result.issues.is_empty());+ assert!(result.selected_dependencies.is_empty());+}++#[tokio::test]+async fn final_parameter_defaults_and_out_positions_are_checked_not_only_required_count() {+ let mut callee = draft("Callee", "BEGIN RETURN 1; END;");+ let parameter = |name: &str, mode: &str, has_default| OracleDraftParameter {+ name: dbx_sql::object_source_sql::OracleDraftName { value: name.into(), quoted: false },+ mode: mode.into(),+ data_type: "NUMBER".into(),+ has_default,+ };+ callee.analysis.as_mut().unwrap().parameters = vec![parameter("A", "OUT", false), parameter("B", "IN", true)];+ let selected = vec![draft("Caller", "BEGIN RETURN \"Callee\"(1); END;"), callee.clone()];+ let failed = resolve_draft(&Catalog::default(), &endpoint(), &selected, 0).await;+ assert!(failed.issues[0].message.contains("writable"));+ let selected = vec![draft("Caller", "n NUMBER; BEGIN RETURN \"Callee\"(n); END;"), callee];+ assert!(resolve_draft(&Catalog::default(), &endpoint(), &selected, 0).await.issues.is_empty());+}++#[tokio::test]+async fn sql_columns_bind_before_local_or_selected_function_names_and_aliases_do_not_become_calls() {+ let catalog = Catalog { entries: vec![Entry::object("OWNER", "Base.Table", "TABLE")], ..Default::default() };+ let selected = vec![+ draft(+ "Caller",+ "n NUMBER; BEGIN SELECT a.n INTO n FROM \"OWNER\".\"Base.Table\" a WHERE n = 1; RETURN n; END;",+ ),+ draft("N", "BEGIN RETURN 1; END;"),+ ];+ let result = resolve_draft(&catalog, &endpoint(), &selected, 0).await;+ assert!(result.issues.is_empty(), "{:?}", result.issues);+ assert!(result.selected_dependencies.is_empty());+ assert_eq!(result.references.len(), 1);+ let bad = vec![draft("Caller", "n NUMBER; BEGIN SELECT a.missing INTO n FROM \"Base.Table\" a; RETURN n; END;")];+ assert!(resolve_draft(&catalog, &endpoint(), &bad, 0).await.issues[0].message.contains("column"));+ let incomplete = Catalog { incomplete_columns: true, ..catalog };+ assert!(!resolve_draft(&incomplete, &endpoint(), &selected, 0).await.issues.is_empty());+}++#[tokio::test]+async fn review_regression_sql_scalar_binding_does_not_hide_calls_or_compound_references() {+ let catalog = Catalog { entries: vec![Entry::object("OWNER", "Base.Table", "TABLE")], ..Default::default() };+ for expression in ["f()", "f.member", "f.member()"] {+ let selected = vec![draft(+ "Caller",+ &format!("f NUMBER := 1; n NUMBER; BEGIN SELECT {expression} INTO n FROM \"Base.Table\"; RETURN n; END;"),+ )];+ let result = resolve_draft(&catalog, &endpoint(), &selected, 0).await;+ assert!(!result.issues.is_empty(), "SQL scalar {expression} was accepted as a call/compound reference");+ assert!(result.issues[0].column > 1);+ }+ let selected =+ vec![draft("Caller", "f NUMBER := 1; n NUMBER; BEGIN SELECT f INTO n FROM \"Base.Table\"; RETURN n; END;")];+ let result = resolve_draft(&catalog, &endpoint(), &selected, 0).await;+ assert!(result.issues.is_empty(), "{:?}", result.issues);+ assert!(result.selected_dependencies.is_empty());+}++#[tokio::test]+async fn two_part_package_schema_ambiguity_is_positioned_and_three_part_member_can_continue() {+ let mut package = Entry::object("OWNER", "PKG", "PACKAGE");+ package.member = Some("F");+ package.function = true;+ let mut external = Entry::object("PKG", "F", "FUNCTION");+ external.grant = true;+ let catalog = Catalog { entries: vec![package, external], ..Default::default() };+ let ambiguous = vec![draft("Caller", "BEGIN RETURN pkg.f; END;")];+ let result = resolve_draft(&catalog, &endpoint(), &ambiguous, 0).await;+ assert!(result.issues[0].message.contains("competing"));+ assert!(result.issues[0].column > 1);+ let explicit = vec![draft("Caller", "BEGIN RETURN \"OWNER\".pkg.f; END;")];+ let result = resolve_draft(&catalog, &endpoint(), &explicit, 0).await;+ assert!(result.issues.is_empty(), "{:?}", result.issues);+ assert_eq!(result.references[0].member.as_deref(), Some("F"));+}++#[tokio::test]+async fn private_then_public_synonyms_preserve_precedence_and_remote_cycles_are_blocked() {+ let mut private = Entry::object("OWNER", "S", "SYNONYM");+ private.synonym = Some(("OWNER", "F", None));+ let mut public = Entry::object("PUBLIC", "S", "SYNONYM");+ public.synonym = Some(("OWNER", "Other", None));+ let catalog = Catalog {+ entries: vec![+ private,+ public,+ Entry::object("OWNER", "F", "FUNCTION"),+ Entry::object("OWNER", "Other", "FUNCTION"),+ ],+ ..Default::default()+ };+ let selected = vec![draft("Caller", "BEGIN RETURN s; END;")];+ let result = resolve_draft(&catalog, &endpoint(), &selected, 0).await;+ assert!(result.issues.is_empty());+ assert_eq!(result.references[0].name, "F");+ let mut public_only = Catalog { entries: catalog.entries[1..].to_vec(), ..Default::default() };+ assert_eq!(resolve_draft(&public_only, &endpoint(), &selected, 0).await.references[0].name, "Other");+ public_only.entries[0].synonym = Some(("OWNER", "S", Some("REMOTE")));+ assert!(resolve_draft(&public_only, &endpoint(), &selected, 0).await.issues[0].message.contains("database-link"));+ public_only.entries[0].synonym = Some(("PUBLIC", "S", None));+ assert!(resolve_draft(&public_only, &endpoint(), &selected, 0).await.issues[0].message.contains("cycle"));+}++#[tokio::test]+async fn cross_owner_invisible_namespace_is_unknown_and_role_only_access_is_not_a_direct_grant() {+ let selected = vec![draft("Caller", "BEGIN RETURN other.f; END;")];+ let hidden = Catalog { dba_denied: true, ..Default::default() };+ assert!(resolve_draft(&hidden, &endpoint(), &selected, 0).await.issues[0].message.contains("ORA-00942"));+ let mut catalog = Catalog { entries: vec![Entry::object("OTHER", "F", "FUNCTION")], ..Default::default() };+ assert!(resolve_draft(&catalog, &endpoint(), &selected, 0).await.issues[0].message.contains("privilege"));+ catalog.entries[0].grant = true;+ assert!(resolve_draft(&catalog, &endpoint(), &selected, 0).await.issues.is_empty());+}++#[tokio::test]+async fn dbms_sql_is_blocked_after_synonym_resolution_but_ordinary_strings_are_not_references() {+ let mut alias = Entry::object("OWNER", "ALIAS", "SYNONYM");+ alias.synonym = Some(("OWNER", "DBMS_SQL", None));+ let mut package = Entry::object("OWNER", "DBMS_SQL", "PACKAGE");+ package.member = Some("EXECUTE");+ package.function = true;+ let catalog = Catalog { entries: vec![alias, package], ..Default::default() };+ let selected = vec![draft("Caller", "BEGIN RETURN alias.execute(1); END;")];+ assert!(resolve_draft(&catalog, &endpoint(), &selected, 0).await.issues[0].message.contains("DBMS_SQL"));+ let selected = vec![draft("Caller", "BEGIN RETURN 'EXECUTE IMMEDIATE DBMS_SQL'; END;")];+ assert!(resolve_draft(&catalog, &endpoint(), &selected, 0).await.issues.is_empty());+}++#[tokio::test]+async fn selected_deletion_is_unavailable_and_external_evidence_is_rechecked_before_dispatch() {+ let catalog = Catalog { entries: vec![Entry::object("OWNER", "F", "FUNCTION")], ..Default::default() };+ let selected = vec![draft("Caller", "BEGIN RETURN f; END;")];+ let result = resolve_draft(&catalog, &endpoint(), &selected, 0).await;+ assert!(result.issues.is_empty());+ for proof in &result.proofs {+ proof.verify(&catalog).await.unwrap();+ }+ catalog.changed.store(true, Ordering::SeqCst);+ assert!(result.proofs.iter().any(|proof| proof.sql.contains("ALL_OBJECTS")));+ let proof = result.proofs.iter().find(|proof| proof.sql.contains("ALL_OBJECTS")).unwrap();+ assert!(proof.verify(&catalog).await.is_err());+ let mut deleted = draft("F", "BEGIN RETURN 1; END;");+ deleted.analysis = None;+ let result = resolve_draft(&Catalog::default(), &endpoint(), &[selected[0].clone(), deleted], 0).await;+ assert!(result.issues[0].message.contains("deletion"));+}++#[tokio::test]+async fn dictionary_in_out_arguments_accept_only_writable_scalars() {+ let mut external = Entry::object("OWNER", "F", "FUNCTION");+ external.parameters = vec![("IN/OUT", false)];+ let catalog = Catalog { entries: vec![external], ..Default::default() };+ let selected = vec![draft("Caller", "n NUMBER; BEGIN RETURN f(n); END;")];+ assert!(resolve_draft(&catalog, &endpoint(), &selected, 0).await.issues.is_empty());+ let selected = vec![draft("Caller", "BEGIN RETURN f(1); END;")];+ assert!(resolve_draft(&catalog, &endpoint(), &selected, 0).await.issues[0].message.contains("writable"));+}diff --git a/crates/dbx-core/src/schema/oracle_routines/tests.rs b/crates/dbx-core/src/schema/oracle_routines/tests.rsnew file mode 100644index 0000000000..b0c8e0e668--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/tests.rs@@ -0,0 +1,371 @@+use super::*;+use serde_json::json;+use std::sync::{+ atomic::{AtomicUsize, Ordering},+ Mutex,+};++const BODY: &str = "FUNCTION \"Quoted.Func\" RETURN VARCHAR2 IS BEGIN RETURN 'a b'; END";++struct FakeCatalog {+ login: String,+ objects: Vec<Vec<Value>>,+ source: String,+ source_flags: Value,+ query_flags: Value,+ flag_stage: &'static str,+ source_error: bool,+ source_mismatch: bool,+ source_changes: bool,+ inventory_changes: bool,+ fail_second_page: bool,+ deny_dba: bool,+ length: u64,+ source_calls: AtomicUsize,+ inventory_calls: AtomicUsize,+ queries: Mutex<Vec<String>>,+}++impl Default for FakeCatalog {+ fn default() -> Self {+ Self {+ login: "Owner.Mixed".into(),+ objects: vec![object_row(1, "Quoted.Func", "FUNCTION")],+ source: format!("CREATE OR REPLACE {BODY}"),+ source_flags: json!({}),+ query_flags: json!({}),+ flag_stage: "",+ source_error: false,+ source_mismatch: false,+ source_changes: false,+ inventory_changes: false,+ fail_second_page: false,+ deny_dba: false,+ length: BODY.chars().count() as u64,+ source_calls: AtomicUsize::new(0),+ inventory_calls: AtomicUsize::new(0),+ queries: Mutex::new(Vec::new()),+ }+ }+}++fn object_row(id: u64, name: &str, kind: &str) -> Vec<Value> {+ vec![json!("Owner.Mixed"), json!(name), json!(kind), json!(id), json!("VALID"), json!("2026-10-21T08:30:00")]+}++fn reply(columns: &[&str], rows: Vec<Vec<Value>>, flags: &Value) -> CatalogReply {+ let mut value = flags.clone();+ value["columns"] = json!(columns);+ value["rows"] = json!(rows);+ serde_json::from_value(value).unwrap()+}++#[async_trait::async_trait]+impl RoutineCatalog for FakeCatalog {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ self.queries.lock().unwrap().push(sql.into());+ let (stage, columns, mut rows) = if sql.contains("LOGIN_OWNER") {+ ("visibility", vec!["LOGIN_OWNER"], vec![vec![json!(self.login)]])+ } else if sql.contains("OBJECT_ID >") {+ if sql.contains("SYS.DBA_OBJECTS") && self.deny_dba {+ return Err("ORA-00942: table or view does not exist".into());+ }+ let after = sql.split("OBJECT_ID > ").nth(1).unwrap().split(' ').next().unwrap().parse::<u64>().unwrap();+ if self.fail_second_page && after > 0 {+ return Err("metadata connection lost on next page".into());+ }+ let call = self.inventory_calls.fetch_add(1, Ordering::SeqCst);+ let mut all = self.objects.clone();+ if self.inventory_changes && call > 0 {+ all.push(object_row(2, "Appeared.Proc", "PROCEDURE"));+ }+ let rows = all.into_iter().filter(|row| row[3].as_u64().unwrap() > after).take(PAGE_SIZE).collect();+ ("inventory", vec!["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "STATUS", "LAST_DDL_TIME"], rows)+ } else if sql.contains("SOURCE_ROWS") {+ (+ "length",+ vec!["SOURCE_ROWS", "FIRST_LINE", "LAST_LINE", "SOURCE_CHARS", "HEAD_TRIM", "TAIL_TRIM", "SOURCE_HEAD"],+ vec![vec![+ json!(1),+ json!(1),+ json!(1),+ json!(self.length),+ json!(0),+ json!(0),+ json!(BODY.chars().take(18).collect::<String>()),+ ]],+ )+ } else if sql.contains("DBMS_METADATA.GET_DDL") {+ ("length", vec!["SOURCE_CHARS"], vec![vec![json!(self.length)]])+ } else if sql.contains("ALL_DEPENDENCIES") {+ (+ "dependencies",+ vec![+ "REFERENCED_OWNER",+ "REFERENCED_NAME",+ "REFERENCED_TYPE",+ "REFERENCED_LINK_NAME",+ "DEPENDENCY_TYPE",+ "RN",+ ],+ vec![],+ )+ } else {+ panic!("unexpected catalog query");+ };+ let empty_flags = json!({});+ let flags = if stage == self.flag_stage { &self.query_flags } else { &empty_flags };+ // A managed error can have no metadata-shaped rows; consumers must not+ // turn that response into a successful empty catalog.+ if flags.get("execution_error") == Some(&json!(true)) {+ rows.clear();+ }+ Ok(reply(&columns, rows, flags))+ }++ async fn source(&self, identity: &RoutineIdentity) -> Result<SourceReply, String> {+ let call = self.source_calls.fetch_add(1, Ordering::SeqCst);+ if self.source_error {+ return Err("source read denied".into());+ }+ let mut value = self.source_flags.clone();+ value["name"] = json!(if self.source_mismatch { "Other.Func" } else { &identity.name });+ value["schema"] = json!(identity.owner);+ value["object_type"] = json!(identity.kind);+ let text = if self.objects.len() > 1 {+ format!("CREATE OR REPLACE FUNCTION \"{}\" RETURN NUMBER IS BEGIN RETURN 1; END", identity.name)+ } else if self.source_changes && call > 0 {+ self.source.replace("a b", "changed")+ } else {+ self.source.clone()+ };+ value["source"] = json!(text);+ Ok(serde_json::from_value(value).unwrap())+ }+}++fn endpoint() -> RoutineEndpoint {+ RoutineEndpoint {+ connection_id: "test-source".into(),+ database: "tenant".into(),+ schema: "Owner.Mixed".into(),+ database_type: DatabaseType::OceanbaseOracle,+ generation: 7,+ }+}++async fn collect(catalog: &FakeCatalog) -> RoutineSnapshot {+ collect_snapshot(catalog, endpoint(), SourceOrigin::OceanBaseDictionary).await+}++#[tokio::test]+async fn explicit_selection_enriches_only_exact_names_and_retains_complete_paged_inventory() {+ let name = "lower.Dot,Name";+ let source = format!("CREATE OR REPLACE FUNCTION \"{name}\" RETURN NUMBER IS BEGIN RETURN 1; END");+ let mut objects = (1..=600).map(|id| object_row(id, &format!("Other{id}"), "FUNCTION")).collect::<Vec<_>>();+ objects.push(object_row(601, name, "FUNCTION"));+ let catalog = FakeCatalog { objects, length: source.encode_utf16().count() as u64, ..Default::default() };+ let snapshot =+ collect_selected_snapshot(&catalog, endpoint(), SourceOrigin::OracleMetadata, Some(&[name.into()])).await;+ assert!(snapshot.enumeration_complete);+ assert_eq!(snapshot.objects.len(), 601);+ assert_eq!(catalog.inventory_calls.load(Ordering::SeqCst), 6);+ assert_eq!(catalog.source_calls.load(Ordering::SeqCst), 2);+ assert_eq!(+ snapshot.objects.iter().filter(|object| object.source_complete && object.dependencies_complete).count(),+ 1+ );+ let selected = snapshot.objects.iter().find(|object| object.version.identity.name == name).unwrap();+ assert_eq!(selected.source.as_deref(), Some(source.as_str()));+ let queries = catalog.queries.lock().unwrap();+ assert_eq!(queries.iter().filter(|sql| sql.contains("DBMS_METADATA.GET_DDL")).count(), 1);+ assert_eq!(queries.iter().filter(|sql| sql.contains("ALL_DEPENDENCIES")).count(), 1);+ assert_eq!(snapshot.state, RoutineReadState::Partial);+}++#[tokio::test]+async fn empty_or_absent_selection_keeps_inventory_without_reading_definitions() {+ for names in [Vec::new(), vec!["quoted.func".into()], vec!["Missing".into()]] {+ let catalog = FakeCatalog::default();+ let snapshot =+ collect_selected_snapshot(&catalog, endpoint(), SourceOrigin::OceanBaseDictionary, Some(&names)).await;+ assert!(snapshot.enumeration_complete);+ assert_eq!(snapshot.objects.len(), 1);+ assert_eq!(snapshot.objects[0].version.identity.name, "Quoted.Func");+ assert!(!snapshot.objects[0].source_complete);+ assert_eq!(catalog.source_calls.load(Ordering::SeqCst), 0);+ assert_eq!(catalog.queries.lock().unwrap().len(), 3);+ }+}++#[tokio::test]+async fn scoped_reads_do_not_turn_failed_inventory_pagination_into_absence() {+ let catalog = FakeCatalog {+ objects: (1..=PAGE_SIZE as u64).map(|id| object_row(id, &format!("Other{id}"), "PROCEDURE")).collect(),+ fail_second_page: true,+ ..Default::default()+ };+ let snapshot =+ collect_selected_snapshot(&catalog, endpoint(), SourceOrigin::OceanBaseDictionary, Some(&["Missing".into()]))+ .await;+ assert!(!snapshot.enumeration_complete);+ assert_eq!(snapshot.objects.len(), PAGE_SIZE);+ assert_eq!(catalog.source_calls.load(Ordering::SeqCst), 0);+ assert_eq!(snapshot.state, RoutineReadState::Partial);+}++#[tokio::test]+async fn exact_quoted_identity_keeps_raw_body_and_validates_without_final_semicolon() {+ let catalog = FakeCatalog::default();+ let snapshot = collect(&catalog).await;+ assert_eq!(snapshot.state, RoutineReadState::Complete);+ assert!(snapshot.enumeration_complete);+ assert_eq!(snapshot.objects[0].version.identity.name, "Quoted.Func");+ assert_eq!(snapshot.objects[0].source.as_deref(), Some(catalog.source.as_str()));+ assert!(!snapshot.objects[0].source.as_ref().unwrap().ends_with(';'));+ assert!(snapshot.objects[0].dependencies_complete);+ assert!(!catalog.queries.lock().unwrap().iter().any(|sql| sql.contains("DBA_")));+}++#[tokio::test]+async fn failed_source_keeps_the_inventory_object_instead_of_implying_deletion() {+ let catalog = FakeCatalog { source_error: true, ..Default::default() };+ let snapshot = collect(&catalog).await;+ assert_eq!(snapshot.state, RoutineReadState::Partial);+ assert!(snapshot.enumeration_complete);+ assert_eq!(snapshot.objects.len(), 1);+ assert!(snapshot.objects[0].source.is_none());+ assert!(!snapshot.objects[0].source_complete);+ assert_eq!(snapshot.objects[0].issues[0].message, "source read denied");+}++#[tokio::test]+async fn partial_response_flags_are_not_successful_empty_results() {+ for flag in [+ json!({"execution_error":true}),+ json!({"truncated":true}),+ json!({"hasMore":true}),+ json!({"largeValueCells":[{"row_index":0}]}),+ json!({"messages":[{"severity":"ERROR","message":"denied"}]}),+ ] {+ let catalog = FakeCatalog { flag_stage: "inventory", query_flags: flag, ..Default::default() };+ let snapshot = collect(&catalog).await;+ assert_ne!(snapshot.state, RoutineReadState::Complete);+ assert!(!snapshot.enumeration_complete);+ assert!(!snapshot.issues.is_empty());+ }+}++#[tokio::test]+async fn source_flags_or_wrong_identity_keep_read_text_but_do_not_verify_it() {+ for flag in [+ json!({"executionError":true}),+ json!({"truncated":true}),+ json!({"has_more":true}),+ json!({"large_value_cells":[{}]}),+ ] {+ let catalog = FakeCatalog { source_flags: flag, ..Default::default() };+ let snapshot = collect(&catalog).await;+ assert_eq!(snapshot.objects[0].source.as_deref(), Some(catalog.source.as_str()));+ assert!(!snapshot.objects[0].source_complete);+ }+ let catalog = FakeCatalog { source_mismatch: true, ..Default::default() };+ assert!(!collect(&catalog).await.objects[0].source_complete);+}++#[tokio::test]+async fn unicode_length_uses_the_actual_source_origin_not_utf8_bytes_or_ob_utf16_units() {+ let body = BODY.replace("a b", "中文🧪 文本");+ let catalog = FakeCatalog {+ source: format!("CREATE OR REPLACE {body}"),+ length: body.chars().count() as u64,+ ..Default::default()+ };+ assert_eq!(collect(&catalog).await.state, RoutineReadState::Complete);+ let wrong = FakeCatalog { length: body.encode_utf16().count() as u64, ..catalog };+ assert!(!collect(&wrong).await.objects[0].source_complete);+}++#[tokio::test]+async fn native_dictionary_and_jdbc_metadata_use_distinct_character_units() {+ let body = BODY.replace("a b", "中文🧪");+ let mut ep = endpoint();+ ep.database_type = DatabaseType::Oracle;+ let native = FakeCatalog { source: body.clone(), length: body.chars().count() as u64, ..Default::default() };+ assert_eq!(+ collect_snapshot(&native, ep.clone(), SourceOrigin::OracleDictionary).await.state,+ RoutineReadState::Complete+ );+ assert!(native.queries.lock().unwrap().iter().any(|sql| sql.contains("SUM(LENGTH4(TEXT))")));+ let source = format!("CREATE OR REPLACE {body}");+ let jdbc =+ FakeCatalog { source: source.clone(), length: source.encode_utf16().count() as u64, ..Default::default() };+ assert_eq!(collect_snapshot(&jdbc, ep, SourceOrigin::OracleMetadata).await.state, RoutineReadState::Complete);+ assert!(!jdbc.queries.lock().unwrap().iter().any(|sql| sql.contains("ALL_SOURCE")));+}++#[tokio::test]+async fn same_second_source_replacement_is_not_a_complete_snapshot() {+ let catalog = FakeCatalog { source_changes: true, ..Default::default() };+ let snapshot = collect(&catalog).await;+ assert_eq!(snapshot.objects[0].source.as_deref(), Some(catalog.source.as_str()));+ assert!(!snapshot.objects[0].source_complete);+ assert!(snapshot.objects[0].issues.iter().any(|issue| issue.message.contains("changed")));+}++#[tokio::test]+async fn inventory_change_preserves_new_and_old_objects_without_inferring_absence() {+ let catalog = FakeCatalog { inventory_changes: true, ..Default::default() };+ let snapshot = collect(&catalog).await;+ assert!(!snapshot.enumeration_complete);+ assert_eq!(snapshot.objects.len(), 2);+ assert_eq!(snapshot.objects[1].version.identity.kind, db::ObjectSourceKind::Procedure);+ assert!(!snapshot.objects[1].source_complete);+}++#[tokio::test]+async fn other_owner_visible_subset_never_claims_complete_namespace() {+ let catalog = FakeCatalog { login: "OTHER_OWNER".into(), deny_dba: true, ..Default::default() };+ let snapshot = collect(&catalog).await;+ assert_eq!(snapshot.objects.len(), 1);+ assert!(snapshot.objects[0].source_complete);+ assert!(!snapshot.enumeration_complete);+ assert_eq!(snapshot.issues[0].code, "permission-denied");+}++#[tokio::test]+async fn inventory_pages_by_object_id_and_retains_previous_page_on_failure() {+ let objects = (1..=PAGE_SIZE as u64 + 1).map(|id| object_row(id, &format!("F{id:03}"), "FUNCTION")).collect();+ let catalog = FakeCatalog { objects, source_error: true, ..Default::default() };+ let snapshot = collect(&catalog).await;+ assert!(snapshot.enumeration_complete);+ assert_eq!(snapshot.objects.len(), PAGE_SIZE + 1);+ assert!(catalog.queries.lock().unwrap().iter().any(|sql| sql.contains("OBJECT_ID > 256")));+ let partial = FakeCatalog { fail_second_page: true, ..catalog };+ let snapshot = collect(&partial).await;+ assert!(!snapshot.enumeration_complete);+ assert_eq!(snapshot.objects.len(), PAGE_SIZE);+}++#[tokio::test]+async fn successful_empty_owner_catalog_is_distinct_from_query_error() {+ let empty = FakeCatalog { objects: vec![], ..Default::default() };+ let snapshot = collect(&empty).await;+ assert_eq!(snapshot.state, RoutineReadState::Complete);+ assert!(snapshot.enumeration_complete && snapshot.objects.is_empty());+ let denied =+ FakeCatalog { flag_stage: "inventory", query_flags: json!({"execution_error":true}), ..Default::default() };+ let snapshot = collect(&denied).await;+ assert!(!snapshot.enumeration_complete && snapshot.objects.is_empty());+ assert_ne!(snapshot.state, RoutineReadState::Complete);+}++#[tokio::test]+async fn endpoint_change_invalidates_each_definition_as_well_as_absence_inference() {+ let catalog = FakeCatalog::default();+ let mut snapshot = collect(&catalog).await;+ invalidate_snapshot_endpoint(&mut snapshot);+ assert!(!snapshot.enumeration_complete);+ assert!(!snapshot.objects[0].source_complete && !snapshot.objects[0].dependencies_complete);+ assert_eq!(snapshot.objects[0].source.as_deref(), Some(catalog.source.as_str()));+}diff --git a/crates/dbx-core/src/schema/oracle_routines/transfer.rs b/crates/dbx-core/src/schema/oracle_routines/transfer.rsnew file mode 100644index 0000000000..76a00d27f2--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/transfer.rs@@ -0,0 +1,212 @@+use super::*;+use crate::data::transfer::{oracle_object_source_query, rewrite_oracle_schema_qualifier, TransferObjectKind};+use dbx_sql::object_source_sql::{prepare_oracle_routine_definition, OracleRoutineDefinitionInput};++pub(crate) struct RoutineTransferInput {+ pub source_connection_id: String,+ pub source_database: String,+ pub identity: RoutineIdentity,+ pub target_connection_id: String,+ pub target_database: String,+ pub target_owner: String,+}++pub(crate) struct RoutineTransferContext {+ source_config: ConnectionConfig,+ target_config: ConnectionConfig,+ source_generation: u64,+ target_generation: u64,+}++pub(crate) async fn capture_routine_transfer_context(+ state: &AppState,+ source_id: &str,+ target_id: &str,+) -> Result<Option<RoutineTransferContext>, String> {+ let source_generation = state.connection_lifecycle_snapshot(source_id).generation();+ let target_generation = state.connection_lifecycle_snapshot(target_id).generation();+ let configs = state.configs.read().await;+ let source_config = configs.get(source_id).ok_or("Source connection not found")?.clone();+ let target_config = configs.get(target_id).ok_or("Target connection not found")?.clone();+ if routine_source_origin(&source_config).is_err() || routine_source_origin(&target_config).is_err() {+ return Ok(None);+ }+ Ok(Some(RoutineTransferContext { source_config, target_config, source_generation, target_generation }))+}++/// Keep the transfer's existing GET_DDL and schema adaptation contracts. The+/// length proof is for that CLOB, not for the different ordinary-source getter.+async fn transfer_definition(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ identity: &RoutineIdentity,+) -> Result<String, String> {+ let kind = match identity.kind {+ db::ObjectSourceKind::Function => TransferObjectKind::Function,+ db::ObjectSourceKind::Procedure => TransferObjectKind::Procedure,+ _ => return Err("Routine transfer requires a standalone function or procedure".into()),+ };+ let before = readback::exact_version(&readback::read_namespace(catalog, identity, false).await?, identity)?;+ let original_query = oracle_object_source_query(&kind, &identity.owner, &identity.name)?;+ let query = format!("WITH ROUTINE_DEFINITION(SOURCE_DDL) AS ({original_query}) SELECT SOURCE_DDL, LENGTH(SOURCE_DDL) SOURCE_CHARS FROM ROUTINE_DEFINITION");+ let read = |reply: CatalogReply| -> Result<String, String> {+ reply.flags.check()?;+ if reply.rows.len() != 1 {+ return Err("Routine transfer source is not a unique complete definition".into());+ }+ let source = reply.text(&reply.rows[0], "SOURCE_DDL")?;+ let length = reply.integer(&reply.rows[0], "SOURCE_CHARS")?;+ let actual = if endpoint.database_type == DatabaseType::OceanbaseOracle {+ source.chars().count()+ } else {+ source.encode_utf16().count()+ };+ if actual as u64 != length {+ return Err("Routine GET_DDL CLOB is incomplete; transfer has not been dispatched".into());+ }+ validate_oracle_executable_object_source(OracleObjectSourceValidationInput {+ database_type: endpoint.database_type,+ object_type: identity.kind.clone(),+ schema: Some(identity.owner.clone()),+ name: identity.name.clone(),+ source: source.clone(),+ })?;+ Ok(source)+ };+ let source = read(catalog.query(&query).await?)?;+ let second = read(catalog.query(&query).await?)?;+ let after = readback::exact_version(&readback::read_namespace(catalog, identity, false).await?, identity)?;+ if source != second || before != after {+ return Err("Routine transfer source changed during its read; refresh before continuing".into());+ }+ Ok(source)+}++pub(crate) async fn transfer_oracle_routine_core(+ state: &AppState,+ context: &RoutineTransferContext,+ input: RoutineTransferInput,+) -> Result<RoutineOperationRecord, String> {+ let (source_type, _) = routine_source_origin(&context.source_config)?;+ let (target_type, _) = routine_source_origin(&context.target_config)?;+ let source_endpoint = RoutineEndpoint {+ connection_id: input.source_connection_id,+ database: input.source_database,+ schema: input.identity.owner.clone(),+ database_type: source_type,+ generation: context.source_generation,+ };+ let target_endpoint = RoutineEndpoint {+ connection_id: input.target_connection_id.clone(),+ database: input.target_database.clone(),+ schema: input.target_owner.clone(),+ database_type: target_type,+ generation: context.target_generation,+ };+ LiveCatalog { state, endpoint: &target_endpoint, config: &context.target_config }.check_endpoint().await?;+ let catalog = LiveCatalog { state, endpoint: &source_endpoint, config: &context.source_config };+ let source = transfer_definition(&catalog, &source_endpoint, &input.identity).await?;+ catalog.check_endpoint().await?;+ // Existing transfer rewrites schema-qualified code, including body refs,+ // unlike the comparison path's declaration-only adaptation.+ let adapted = rewrite_oracle_schema_qualifier(&source, &input.identity.owner, &input.target_owner);+ let sql = prepare_oracle_routine_definition(OracleRoutineDefinitionInput {+ database_type: target_type,+ object_type: input.identity.kind.clone(),+ source_owner: input.target_owner.clone(),+ target_owner: input.target_owner.clone(),+ name: input.identity.name.clone(),+ source: adapted,+ replace: false,+ })?;+ let (prepared, _transfer_pin) = execution::prepare_bound_definition_pinned(+ state,+ OracleRoutineSaveInput {+ connection_id: input.target_connection_id,+ database: input.target_database,+ identity: RoutineIdentity { owner: input.target_owner, ..input.identity },+ sql: sql.clone(),+ supersedes_operation_id: None,+ },+ context.target_config.clone(),+ context.target_generation,+ false,+ )?;+ // CREATE itself protects the race without adding global dictionary grants+ // to the old transfer entry. The existing skip check remains with its caller.+ execution::execute_prepared_inline(state, &prepared.operation_id, &sql).await+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;+ use std::sync::atomic::{AtomicUsize, Ordering};++ struct Catalog {+ database_type: DatabaseType,+ incomplete: bool,+ changed: bool,+ reads: AtomicUsize,+ }+ const SOURCE: &str =+ "CREATE OR REPLACE FUNCTION \"OWNER\".\"Mixed.Func\" RETURN VARCHAR2 AS BEGIN RETURN '🙂 OWNER.Table'; END";+ #[async_trait::async_trait]+ impl RoutineCatalog for Catalog {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ if sql.contains("SOURCE_DDL") {+ let call = self.reads.fetch_add(1, Ordering::SeqCst);+ let source =+ if self.changed && call > 0 { SOURCE.replace("OWNER.Table", "OTHER.Table") } else { SOURCE.into() };+ let length = if self.database_type == DatabaseType::OceanbaseOracle {+ source.chars().count()+ } else {+ source.encode_utf16().count()+ };+ Ok(serde_json::from_value(json!({"columns":["SOURCE_DDL","SOURCE_CHARS"],"rows":[[source,length]],"truncated":self.incomplete})).unwrap())+ } else {+ Ok(serde_json::from_value(json!({"columns":["OWNER","OBJECT_NAME","OBJECT_TYPE","OBJECT_ID","STATUS","LAST_DDL_TIME"],"rows":[["OWNER","Mixed.Func","FUNCTION",12,"VALID","2026-10-21T08:30:00"]]})).unwrap())+ }+ }+ async fn source(&self, _: &RoutineIdentity) -> Result<SourceReply, String> {+ panic!("transfer keeps its metadata source, not the ordinary getter")+ }+ }+ fn endpoint(database_type: DatabaseType) -> RoutineEndpoint {+ RoutineEndpoint {+ connection_id: "source".into(),+ database: "tenant".into(),+ schema: "OWNER".into(),+ database_type,+ generation: 0,+ }+ }+ fn identity() -> RoutineIdentity {+ RoutineIdentity { owner: "OWNER".into(), name: "Mixed.Func".into(), kind: db::ObjectSourceKind::Function }+ }+ #[tokio::test]+ async fn complete_metadata_uses_product_specific_clob_units_and_keeps_literals() {+ for database_type in [DatabaseType::Oracle, DatabaseType::OceanbaseOracle] {+ let catalog = Catalog { database_type, incomplete: false, changed: false, reads: AtomicUsize::new(0) };+ let source = transfer_definition(&catalog, &endpoint(database_type), &identity()).await.unwrap();+ assert_eq!(source, SOURCE);+ let adapted = rewrite_oracle_schema_qualifier(&source, "OWNER", "TARGET");+ assert!(adapted.contains("'🙂 OWNER.Table'"));+ assert!(adapted.contains("\"TARGET\".\"Mixed.Func\""));+ }+ }+ #[tokio::test]+ async fn incomplete_or_changed_metadata_never_reaches_a_transfer_write() {+ for (incomplete, changed) in [(true, false), (false, true)] {+ let catalog = Catalog {+ database_type: DatabaseType::OceanbaseOracle,+ incomplete,+ changed,+ reads: AtomicUsize::new(0),+ };+ assert!(transfer_definition(&catalog, &endpoint(DatabaseType::OceanbaseOracle), &identity())+ .await+ .is_err());+ }+ }+}diff --git a/crates/dbx-core/tests/api_contract_verification.rs b/crates/dbx-core/tests/api_contract_verification.rsindex ec4c95606a..8263415c04 100644--- a/crates/dbx-core/tests/api_contract_verification.rs+++ b/crates/dbx-core/tests/api_contract_verification.rs@@ -40,6 +40,7 @@ fn prepare_schema_diff_function_signature() {target_details: vec![],source_functions: vec![],target_functions: vec![],+ oracle_routines: None,source_sequences: vec![],target_sequences: vec![],source_rules: vec![],@@ -80,6 +81,7 @@ fn schema_diff_case_options_are_backward_compatible_and_use_camel_case() {.unwrap();assert!(!legacy.ignore_table_name_case);assert!(!legacy.ignore_column_name_case);+ assert!(legacy.oracle_routines.is_none());let mut options = legacy;options.ignore_table_name_case = true;@@ -89,6 +91,7 @@ fn schema_diff_case_options_are_backward_compatible_and_use_camel_case() {assert_eq!(json["ignoreColumnNameCase"], true);assert!(json.get("ignore_table_name_case").is_none());assert!(json.get("ignore_column_name_case").is_none());+ assert!(json.get("oracleRoutines").is_none());}/// Verify generate_schema_sync_sql accepts all arg types@@ -142,6 +145,7 @@ fn schema_diff_preparation_field_names() {target_details: vec![],source_functions: vec![],target_functions: vec![],+ oracle_routines: None,source_sequences: vec![],target_sequences: vec![],source_rules: vec![],diff --git a/crates/dbx-sql-core/src/object_source_sql.rs b/crates/dbx-sql-core/src/object_source_sql.rsindex 665850bea6..3a833dd158 100644--- a/crates/dbx-sql-core/src/object_source_sql.rs+++ b/crates/dbx-sql-core/src/object_source_sql.rs@@ -8,6 +8,14 @@ use crate::models::connection::DatabaseType;use crate::sql::split_sql_statements_for_database;use crate::types::ObjectSourceKind;+mod oracle_routines;+pub use oracle_routines::{+ analyze_oracle_routine_draft, comparable_oracle_routine_definition, prepare_oracle_routine_definition,+ validate_oracle_routine_target_definition, OracleDraftIssue, OracleDraftName, OracleDraftParameter,+ OracleDraftQuery, OracleDraftReference, OracleDraftReferenceRole, OracleRoutineDefinitionInput,+ OracleRoutineDraftAnalysis,+};+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct EditableObjectSourceSqlInput {diff --git a/crates/dbx-sql-core/src/object_source_sql/oracle_routines.rs b/crates/dbx-sql-core/src/object_source_sql/oracle_routines.rsnew file mode 100644index 0000000000..c874327841--- /dev/null+++ b/crates/dbx-sql-core/src/object_source_sql/oracle_routines.rs@@ -0,0 +1,295 @@+use super::*;++mod analysis;+pub use analysis::{+ analyze_oracle_routine_draft, OracleDraftIssue, OracleDraftName, OracleDraftParameter, OracleDraftQuery,+ OracleDraftReference, OracleDraftReferenceRole, OracleRoutineDraftAnalysis,+};++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleRoutineDefinitionInput {+ pub database_type: DatabaseType,+ pub object_type: ObjectSourceKind,+ pub source_owner: String,+ pub target_owner: String,+ pub name: String,+ pub source: String,+ pub replace: bool,+}++pub fn validate_oracle_routine_target_definition(+ input: EditableObjectSourceSqlInput,+ require_replace: Option<bool>,+) -> Result<(), String> {+ if !matches!(input.object_type, ObjectSourceKind::Procedure | ObjectSourceKind::Function) {+ return Err("The approved statement must define one standalone routine".into());+ }+ validate_oracle_executable_object_source(OracleObjectSourceValidationInput {+ database_type: input.database_type,+ object_type: input.object_type,+ schema: input.schema,+ name: input.name,+ source: input.source.clone(),+ })?;+ let tokens = Tokenizer::new(&OracleDialect {}, &input.source).tokenize().map_err(|error| error.to_string())?;+ let significant =+ tokens.iter().filter(|token| !matches!(token, Token::Whitespace(_) | Token::EOF)).collect::<Vec<_>>();+ if !significant.first().is_some_and(|token| token_unquoted_word_is(token, "CREATE")) {+ return Err("The approved routine statement must begin with CREATE".into());+ }+ let replaces = significant.get(1).is_some_and(|token| token_unquoted_word_is(token, "OR"));+ if require_replace.is_some_and(|required| required != replaces) {+ return Err(if replaces {+ "A newly created routine cannot use OR REPLACE"+ } else {+ "A routine replacement requires OR REPLACE"+ }+ .into());+ }+ Ok(())+}++/// Adapt only the declaration and client delimiter. The stored original remains+/// separate from this executable target draft.+pub fn prepare_oracle_routine_definition(input: OracleRoutineDefinitionInput) -> Result<String, String> {+ if !matches!(input.database_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle)+ || !matches!(input.object_type, ObjectSourceKind::Procedure | ObjectSourceKind::Function)+ {+ return Err("Oracle routine adaptation requires a standalone procedure or function".into());+ }+ if input.source_owner.is_empty() || input.target_owner.is_empty() || input.name.is_empty() {+ return Err("Oracle routine adaptation requires an exact owner and name".into());+ }+ let mut source = strip_client_delimiter(&input.source)?;+ let tokens = Tokenizer::new(&OracleDialect {}, &source).tokenize().map_err(|error| error.to_string())?;+ if !tokens+ .iter()+ .find(|token| !matches!(token, Token::Whitespace(_)))+ .is_some_and(|token| token_unquoted_word_is(token, "CREATE"))+ {+ source = format!("CREATE OR REPLACE {source}");+ }+ validate_oracle_object_source(+ input.database_type,+ &input.object_type,+ Some(&input.source_owner),+ &input.name,+ &source,+ )?;+ let tokens =+ Tokenizer::new(&OracleDialect {}, &source).tokenize_with_location().map_err(|error| error.to_string())?;+ let significant =+ tokens.iter().filter(|token| !matches!(token.token, Token::Whitespace(_) | Token::EOF)).collect::<Vec<_>>();+ let token_at = |position: usize| significant.get(position).map(|token| &token.token);+ let mut edits = Vec::new();+ let mut position = 1;+ if token_at(position).is_some_and(|token| token_unquoted_word_is(token, "OR")) {+ edits.push((significant[position].span, String::new()));+ edits.push((significant[position + 1].span, String::new()));+ position += 2;+ }+ edits.push((significant[0].span, if input.replace { "CREATE OR REPLACE".into() } else { "CREATE".into() }));+ if token_at(position).is_some_and(|token| {+ token_unquoted_word_is(token, "EDITIONABLE") || token_unquoted_word_is(token, "NONEDITIONABLE")+ }) {+ position += 1;+ }+ if !token_at(position).is_some_and(|token| token_unquoted_word_is(token, object_type_keyword(&input.object_type))) {+ return Err("Routine declaration kind must be an unquoted PROCEDURE or FUNCTION keyword".into());+ }+ edits.push((significant[position].span, object_type_keyword(&input.object_type).to_string()));+ position += 1;+ if token_at(position + 1) == Some(&Token::Period) {+ edits.push((significant[position].span, quote_postgres_identifier(&input.target_owner)));+ edits.push((significant[position + 2].span, quote_postgres_identifier(&input.name)));+ } else {+ edits.push((+ significant[position].span,+ format!("{}.{}", quote_postgres_identifier(&input.target_owner), quote_postgres_identifier(&input.name)),+ ));+ }+ let mut ranges = edits+ .into_iter()+ .map(|(span, replacement)| {+ let start = routine_location_to_byte_offset(&source, span.start)+ .ok_or("Cannot locate routine declaration token")?;+ let end =+ routine_location_to_byte_offset(&source, span.end).ok_or("Cannot locate routine declaration token")?;+ Ok((start, end, replacement))+ })+ .collect::<Result<Vec<_>, String>>()?;+ ranges.sort_by_key(|(start, _, _)| *start);+ for (start, end, replacement) in ranges.into_iter().rev() {+ source.replace_range(start..end, &replacement);+ }+ let sql = ensure_oracle_ddl_terminated(&source);+ validate_oracle_object_source(+ input.database_type,+ &input.object_type,+ Some(&input.target_owner),+ &input.name,+ &sql,+ )?;+ Ok(sql)+}++pub fn comparable_oracle_routine_definition(mut input: OracleRoutineDefinitionInput) -> Result<String, String> {+ input.replace = true;+ let database_type = input.database_type;+ let object_type = input.object_type.clone();+ let schema = input.target_owner.clone();+ let name = input.name.clone();+ let source = prepare_oracle_routine_definition(input)?;+ fingerprint_oracle_routine_object_source(EditableObjectSourceSqlInput {+ database_type,+ object_type,+ schema: Some(schema),+ name,+ source,+ })+}++fn strip_client_delimiter(source: &str) -> Result<String, String> {+ let tokens =+ Tokenizer::new(&OracleDialect {}, source).tokenize_with_location().map_err(|error| error.to_string())?;+ let Some(last) = tokens.iter().rev().find(|token| !matches!(token.token, Token::Whitespace(_) | Token::EOF)) else {+ return Err("Routine definition is empty".into());+ };+ if last.token != Token::Div {+ return Ok(source.into());+ }+ let start =+ routine_location_to_byte_offset(source, last.span.start).ok_or("Cannot locate Oracle client delimiter")?;+ let end = routine_location_to_byte_offset(source, last.span.end).ok_or("Cannot locate Oracle client delimiter")?;+ let line_start = source[..start].rfind('\n').map_or(0, |index| index + 1);+ let line_end = source[end..].find('\n').map_or(source.len(), |index| end + index);+ if source[line_start..line_end].trim() != "/" {+ return Err("An Oracle client slash delimiter must be on a separate line".into());+ }+ let mut result = source.to_string();+ result.replace_range(start..end, "");+ Ok(result)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn input(source: &str) -> OracleRoutineDefinitionInput {+ OracleRoutineDefinitionInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: ObjectSourceKind::Function,+ source_owner: "Source.Owner".into(),+ target_owner: "Target.Owner".into(),+ name: "Mixed.Func".into(),+ source: source.into(),+ replace: false,+ }+ }++ #[test]+ fn adapts_only_declaration_and_keeps_literals_comments_and_raw_input() {+ let source = r#"-- Source.Owner.Mixed.Func remains here+CREATE OR REPLACE NONEDITIONABLE FUNCTION "Source.Owner"."Mixed.Func" RETURN VARCHAR2 AS+BEGIN RETURN q'[Source.Owner.Mixed.Func text]'; END;+/+"#;+ let original = input(source);+ let sql = prepare_oracle_routine_definition(original.clone()).unwrap();+ assert!(sql.contains("CREATE NONEDITIONABLE FUNCTION \"Target.Owner\".\"Mixed.Func\""));+ assert!(sql.contains("-- Source.Owner.Mixed.Func remains here"));+ assert!(sql.contains("q'[Source.Owner.Mixed.Func text]'"));+ assert!(!sql.lines().any(|line| line.trim() == "/"));+ assert_eq!(original.source, source);+ }++ #[test]+ fn bare_source_gets_an_exact_create_without_replace() {+ let sql =+ prepare_oracle_routine_definition(input(r#"FUNCTION "Mixed.Func" RETURN NUMBER AS BEGIN RETURN 1; END"#))+ .unwrap();+ assert!(sql.starts_with("CREATE FUNCTION \"Target.Owner\".\"Mixed.Func\""));+ assert!(!sql.contains("OR REPLACE"));+ assert!(sql.ends_with(';'));+ }++ #[test]+ fn replacement_preserves_declaration_comments() {+ let mut definition = input(+ r#"CREATE /* create */ OR /* or */ REPLACE FUNCTION "Mixed.Func" RETURN NUMBER AS BEGIN RETURN 1; END;"#,+ );+ definition.replace = true;+ let sql = prepare_oracle_routine_definition(definition).unwrap();+ assert!(sql.starts_with("CREATE OR REPLACE /* create */ /* or */ FUNCTION"));+ }++ #[test]+ fn comparison_maps_only_declaration_and_outer_representation() {+ let left = input(r#"FUNCTION "Source.Owner"."Mixed.Func" RETURN VARCHAR2 AS BEGIN RETURN 'a b'; END"#);+ let mut right = input("CREATE OR REPLACE FUNCTION \"Target.Owner\".\"Mixed.Func\" RETURN VARCHAR2 AS\nBEGIN RETURN 'a b'; END;\n/");+ right.source_owner = "Target.Owner".into();+ assert_eq!(+ comparable_oracle_routine_definition(left.clone()).unwrap(),+ comparable_oracle_routine_definition(right.clone()).unwrap()+ );+ right.source = right.source.replace("a b", "a b");+ assert_ne!(+ comparable_oracle_routine_definition(left).unwrap(),+ comparable_oracle_routine_definition(right).unwrap()+ );+ }++ #[test]+ fn edition_and_body_comments_are_not_normalized_away() {+ let base =+ input(r#"CREATE EDITIONABLE FUNCTION "Mixed.Func" RETURN NUMBER AS BEGIN /* keep */ RETURN 1; END;"#);+ let other = OracleRoutineDefinitionInput {+ source: base.source.replace("EDITIONABLE", "NONEDITIONABLE"),+ ..base.clone()+ };+ assert_ne!(+ comparable_oracle_routine_definition(base.clone()).unwrap(),+ comparable_oracle_routine_definition(other).unwrap()+ );+ let other =+ OracleRoutineDefinitionInput { source: base.source.replace("/* keep */", "/* changed */"), ..base.clone() };+ assert_ne!(+ comparable_oracle_routine_definition(base).unwrap(),+ comparable_oracle_routine_definition(other).unwrap()+ );+ }++ #[test]+ fn rejects_wrong_identity_kind_or_extra_statements() {+ for source in [+ r#"CREATE FUNCTION "Wrong.Owner"."Mixed.Func" RETURN NUMBER AS BEGIN RETURN 1; END;"#,+ r#"CREATE FUNCTION "Other.Func" RETURN NUMBER AS BEGIN RETURN 1; END;"#,+ r#"CREATE PROCEDURE "Mixed.Func" AS BEGIN NULL; END;"#,+ r#"CREATE FUNCTION "Mixed.Func" RETURN NUMBER AS BEGIN RETURN 1; END; DELETE FROM ACCOUNTS;"#,+ ] {+ assert!(prepare_oracle_routine_definition(input(source)).is_err(), "{source}");+ }+ }++ #[test]+ fn target_validation_does_not_execute_a_bare_body_or_widen_create_to_replace() {+ let check = |source: &str, replace| {+ validate_oracle_routine_target_definition(+ EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: ObjectSourceKind::Function,+ schema: Some("Target.Owner".into()),+ name: "Mixed.Func".into(),+ source: source.into(),+ },+ replace,+ )+ };+ let create = r#"CREATE FUNCTION "Target.Owner"."Mixed.Func" RETURN NUMBER AS BEGIN RETURN 1; END;"#;+ assert!(check(create, Some(false)).is_ok());+ assert!(check(&create.replacen("CREATE", "CREATE OR REPLACE", 1), Some(false)).is_err());+ assert!(check(create.strip_prefix("CREATE ").unwrap(), None).is_err());+ assert!(check(&create.replacen("CREATE", "CREATE OR REPLACE", 1), None).is_ok());+ }+}diff --git a/crates/dbx-sql-core/src/object_source_sql/oracle_routines/analysis.rs b/crates/dbx-sql-core/src/object_source_sql/oracle_routines/analysis.rsnew file mode 100644index 0000000000..7bb4444dbe--- /dev/null+++ b/crates/dbx-sql-core/src/object_source_sql/oracle_routines/analysis.rs@@ -0,0 +1,715 @@+//! Fail-closed analysis of the small static PL/SQL subset used by comparison+//! deployment. Ordinary source saves and transfers do not use this restriction.+use super::*;+use sqlparser::ast::{+ Expr, FunctionArg, FunctionArgExpr, FunctionArguments, GroupByExpr, Ident, ObjectName, SelectFlavor, SelectItem,+ SetExpr, Statement, TableFactor,+};+use sqlparser::parser::Parser;+use sqlparser::tokenizer::{Location, TokenWithSpan};+use std::collections::BTreeMap;++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct OracleDraftName {+ pub value: String,+ pub quoted: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct OracleDraftParameter {+ pub name: OracleDraftName,+ pub mode: String,+ pub data_type: String,+ pub has_default: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+pub enum OracleDraftReferenceRole {+ Relation,+ Value,+ Function,+ Procedure,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleDraftReference {+ pub parts: Vec<OracleDraftName>,+ pub role: OracleDraftReferenceRole,+ pub argument_writable: Vec<bool>,+ pub query: Option<usize>,+ pub local_binding: Option<bool>,+ pub line: u64,+ pub column: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleDraftQuery {+ pub relation_reference: usize,+ pub alias: Option<OracleDraftName>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleDraftIssue {+ pub code: String,+ pub message: String,+ pub line: u64,+ pub column: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub struct OracleRoutineDraftAnalysis {+ pub complete: bool,+ pub parameters: Vec<OracleDraftParameter>,+ pub references: Vec<OracleDraftReference>,+ pub queries: Vec<OracleDraftQuery>,+ pub issues: Vec<OracleDraftIssue>,+}++fn canonical(ident: &Ident) -> String {+ if ident.quote_style.is_some() {+ ident.value.clone()+ } else {+ ident.value.to_uppercase()+ }+}+fn name(ident: &Ident) -> OracleDraftName {+ OracleDraftName { value: canonical(ident), quoted: ident.quote_style.is_some() }+}+fn object_parts(value: &ObjectName) -> Result<Vec<Ident>, String> {+ value+ .0+ .iter()+ .map(|part| part.as_ident().cloned().ok_or_else(|| "Computed object names require manual correction".into()))+ .collect()+}++struct Analysis<'a> {+ input: &'a EditableObjectSourceSqlInput,+ tokens: Vec<TokenWithSpan>,+ pos: usize,+ bindings: BTreeMap<String, bool>,+ output: OracleRoutineDraftAnalysis,+ issue_position: Option<Location>,+}++impl Analysis<'_> {+ fn current(&self) -> Option<&TokenWithSpan> {+ self.tokens.get(self.pos)+ }+ fn word(&self, value: &str) -> bool {+ self.current().is_some_and(|token| token_unquoted_word_is(&token.token, value))+ }+ fn consume_word(&mut self, value: &str) -> bool {+ if self.word(value) {+ self.pos += 1;+ true+ } else {+ false+ }+ }+ fn consume(&mut self, value: Token) -> bool {+ if self.current().is_some_and(|token| token.token == value) {+ self.pos += 1;+ true+ } else {+ false+ }+ }+ fn expect_word(&mut self, value: &str) -> Result<(), String> {+ if self.consume_word(value) {+ Ok(())+ } else {+ Err(format!("Expected {value}; edit this draft to the supported static form"))+ }+ }+ fn expect(&mut self, value: Token) -> Result<(), String> {+ if self.consume(value.clone()) {+ Ok(())+ } else {+ Err(format!("Expected {value} in the static routine draft"))+ }+ }+ fn ident(&mut self) -> Result<Ident, String> {+ let token = self.current().ok_or("Routine draft ended unexpectedly")?;+ let Token::Word(word) = &token.token else {+ return Err("Expected an exact identifier".into());+ };+ let ident = Ident { value: word.value.clone(), quote_style: word.quote_style, span: token.span };+ self.pos += 1;+ Ok(ident)+ }+ fn parts(&mut self) -> Result<Vec<Ident>, String> {+ let mut result = vec![self.ident()?];+ while self.consume(Token::Period) {+ result.push(self.ident()?);+ }+ if result.len() > 3 {+ return Err("Only a local object, owner.object or owner.package.member can be resolved".into());+ }+ Ok(result)+ }+ fn scalar_type(&mut self) -> Result<String, String> {+ let token = self.current().ok_or("A scalar type is required")?;+ let Token::Word(word) = &token.token else {+ return Err("A built-in scalar type is required".into());+ };+ let data_type = word.value.to_uppercase();+ if word.quote_style.is_some()+ || !matches!(+ data_type.as_str(),+ "NUMBER"+ | "NUMERIC"+ | "DECIMAL"+ | "INTEGER"+ | "INT"+ | "SMALLINT"+ | "PLS_INTEGER"+ | "BINARY_INTEGER"+ | "SIMPLE_INTEGER"+ | "VARCHAR2"+ | "VARCHAR"+ | "NVARCHAR2"+ | "CHAR"+ | "NCHAR"+ | "BOOLEAN"+ | "DATE"+ | "TIMESTAMP"+ | "RAW"+ | "FLOAT"+ | "BINARY_FLOAT"+ | "BINARY_DOUBLE"+ )+ {+ return Err("This automatic plan supports built-in scalar declarations; keep this draft for manual correction or deselect the object".into());+ }+ self.pos += 1;+ if self.consume(Token::LParen) {+ for index in 0..2 {+ let _ = self.consume(Token::Minus);+ if !self.current().is_some_and(+ |token| matches!(&token.token, Token::Number(number, _) if number.parse::<u32>().is_ok()),+ ) {+ return Err("Only literal numeric precision or length is supported".into());+ }+ self.pos += 1;+ if index == 0 && self.consume(Token::Comma) {+ continue;+ }+ break;+ }+ let _ = self.consume_word("CHAR") || self.consume_word("BYTE");+ self.expect(Token::RParen)?;+ }+ Ok(data_type)+ }+ fn expression_tokens_until(&mut self, terminators: &[Token]) -> Result<Vec<TokenWithSpan>, String> {+ let start = self.pos;+ let mut depth = 0usize;+ while let Some(token) = self.current() {+ if depth == 0 && terminators.contains(&token.token) {+ break;+ }+ match token.token {+ Token::LParen => depth += 1,+ Token::RParen if depth > 0 => depth -= 1,+ Token::EOF => break,+ _ => {}+ }+ self.pos += 1;+ }+ if depth != 0 || start == self.pos {+ return Err("A complete scalar expression is required".into());+ }+ Ok(self.tokens[start..self.pos].to_vec())+ }+ fn expression(&mut self, tokens: Vec<TokenWithSpan>, query: Option<usize>) -> Result<Expr, String> {+ let position = tokens.first().map(|token| token.span.start);+ let result = (|| {+ let mut parser = Parser::new(&OracleDialect {}).with_tokens_with_locations(tokens);+ let expr =+ parser.parse_expr().map_err(|error| format!("Cannot analyze this scalar expression: {error}"))?;+ if parser.peek_token_ref().token != Token::EOF {+ return Err("Expression has unsupported trailing syntax".into());+ }+ self.visit_expr(&expr, query)?;+ Ok(expr)+ })();+ if result.is_err() {+ self.issue_position = position;+ }+ result+ }+ fn reference(+ &mut self,+ parts: &[Ident],+ role: OracleDraftReferenceRole,+ arguments: Vec<bool>,+ query: Option<usize>,+ ) -> Result<(), String> {+ if parts.is_empty() || parts.len() > 3 {+ return Err("Reference does not have an exact supported identity".into());+ }+ let local = self.bindings.get(&canonical(&parts[0])).copied();+ if query.is_none() && local.is_some() {+ if parts.len() == 1 && role == OracleDraftReferenceRole::Value {+ return Ok(());+ }+ return Err("A local scalar shadows this call or qualifier; use an unambiguous static target name".into());+ }+ self.output.references.push(OracleDraftReference {+ parts: parts.iter().map(name).collect(),+ role,+ argument_writable: arguments,+ query,+ local_binding: local,+ line: parts[0].span.start.line,+ column: parts[0].span.start.column,+ });+ Ok(())+ }+ fn writable(&self, expr: &Expr) -> bool {+ matches!(expr, Expr::Identifier(ident) if self.bindings.get(&canonical(ident)) == Some(&true))+ }+ fn call(+ &mut self,+ function: &sqlparser::ast::Function,+ query: Option<usize>,+ procedure: bool,+ ) -> Result<(), String> {+ if function.uses_odbc_syntax+ || function.parameters != FunctionArguments::None+ || function.filter.is_some()+ || function.null_treatment.is_some()+ || function.over.is_some()+ || !function.within_group.is_empty()+ {+ return Err("Call modifiers require manual correction before automatic deployment".into());+ }+ let parts = object_parts(&function.name)?;+ let args = match &function.args {+ FunctionArguments::None => &[][..],+ FunctionArguments::List(list) if list.duplicate_treatment.is_none() && list.clauses.is_empty() => {+ list.args.as_slice()+ }+ _ => return Err("Only positional scalar call arguments are supported".into()),+ };+ // COUNT(*) has a closed SQL aggregate meaning, not a guessed unresolved+ // routine. Other calls go through the Core name/argument resolver.+ if query.is_some()+ && !procedure+ && parts.len() == 1+ && parts[0].quote_style.is_none()+ && parts[0].value.eq_ignore_ascii_case("COUNT")+ && matches!(args, [FunctionArg::Unnamed(FunctionArgExpr::Wildcard)])+ {+ return Ok(());+ }+ let mut writable = Vec::new();+ for arg in args {+ let FunctionArg::Unnamed(FunctionArgExpr::Expr(expr)) = arg else {+ return Err("Named, wildcard or query call arguments are not supported by this automatic plan".into());+ };+ self.visit_expr(expr, query)?;+ writable.push(query.is_none() && self.writable(expr));+ }+ self.reference(+ &parts,+ if procedure { OracleDraftReferenceRole::Procedure } else { OracleDraftReferenceRole::Function },+ writable,+ query,+ )+ }+ fn visit_expr(&mut self, expr: &Expr, query: Option<usize>) -> Result<(), String> {+ match expr {+ Expr::Value(value) if matches!(value.value, sqlparser::ast::Value::Number(_, _) | sqlparser::ast::Value::SingleQuotedString(_) | sqlparser::ast::Value::NationalStringLiteral(_) | sqlparser::ast::Value::QuoteDelimitedStringLiteral(_) | sqlparser::ast::Value::NationalQuoteDelimitedStringLiteral(_) | sqlparser::ast::Value::Boolean(_) | sqlparser::ast::Value::Null) => Ok(()),+ Expr::Identifier(ident) => self.reference(std::slice::from_ref(ident), OracleDraftReferenceRole::Value, Vec::new(), query),+ Expr::CompoundIdentifier(parts) => self.reference(parts, OracleDraftReferenceRole::Value, Vec::new(), query),+ Expr::Nested(expr) | Expr::IsNull(expr) | Expr::IsNotNull(expr) => self.visit_expr(expr, query),+ Expr::UnaryOp { op, expr } if matches!(op.to_string().as_str(), "+" | "-" | "NOT") => self.visit_expr(expr, query),+ Expr::BinaryOp { left, op, right } if matches!(op.to_string().as_str(), "+" | "-" | "*" | "/" | "%" | "||" | "AND" | "OR" | "=" | "<>" | "!=" | "<" | ">" | "<=" | ">=") => { self.visit_expr(left, query)?; self.visit_expr(right, query) },+ Expr::Function(function) => self.call(function, query, false),+ _ => Err("This expression needs a supported static form before automatic deployment; nested queries, methods and extra scopes are not inferred".into()),+ }+ }+ fn declare_binding(&mut self, ident: &Ident, writable: bool) -> Result<(), String> {+ if self.bindings.insert(canonical(ident), writable).is_some() {+ return Err("Duplicate or shadowed local declarations require manual correction".into());+ }+ Ok(())+ }+ fn parse(&mut self) -> Result<(), String> {+ self.expect_word("CREATE")?;+ if self.consume_word("OR") {+ self.expect_word("REPLACE")?;+ }+ let _ = self.consume_word("EDITIONABLE") || self.consume_word("NONEDITIONABLE");+ self.expect_word(object_type_keyword(&self.input.object_type))?;+ self.parts()?; // Existing identity validator checked owner/name/kind.+ if self.consume(Token::LParen) && !self.consume(Token::RParen) {+ loop {+ let ident = self.ident()?;+ let mode = if self.consume_word("IN") {+ if self.consume_word("OUT") {+ "IN OUT"+ } else {+ "IN"+ }+ } else if self.consume_word("OUT") {+ "OUT"+ } else {+ "IN"+ };+ let data_type = self.scalar_type()?;+ let has_default = self.consume_word("DEFAULT") || self.consume(Token::Assignment);+ if has_default {+ if mode != "IN" {+ return Err("Only IN parameters can have a default in this automatic plan".into());+ }+ let tokens = self.expression_tokens_until(&[Token::Comma, Token::RParen])?;+ self.expression(tokens, None)?;+ }+ self.declare_binding(&ident, mode != "IN")?;+ self.output.parameters.push(OracleDraftParameter {+ name: name(&ident),+ mode: mode.into(),+ data_type,+ has_default,+ });+ if self.consume(Token::RParen) {+ break;+ }+ self.expect(Token::Comma)?;+ }+ }+ if self.input.object_type == ObjectSourceKind::Function {+ self.expect_word("RETURN")?;+ self.scalar_type()?;+ }+ if self.consume_word("AUTHID") {+ self.expect_word("DEFINER")?;+ }+ if !self.consume_word("AS") && !self.consume_word("IS") {+ return Err(+ "Unknown routine header option; only a static AUTHID DEFINER scalar routine is supported".into()+ );+ }+ while !self.word("BEGIN") {+ if self.current().is_none()+ || self.word("FUNCTION")+ || self.word("PROCEDURE")+ || self.word("DECLARE")+ || self.word("CURSOR")+ || self.word("TYPE")+ {+ return Err("Local routines, cursors and additional declaration scopes need manual correction or removal from this plan".into());+ }+ let ident = self.ident()?;+ let constant = self.consume_word("CONSTANT");+ self.scalar_type()?;+ if self.consume_word("NOT") {+ self.expect_word("NULL")?;+ }+ let initialized = self.consume(Token::Assignment) || self.consume_word("DEFAULT");+ if initialized {+ let tokens = self.expression_tokens_until(&[Token::SemiColon])?;+ self.expression(tokens, None)?;+ } else if constant {+ return Err("A scalar constant needs a complete initializer".into());+ }+ self.expect(Token::SemiColon)?;+ self.declare_binding(&ident, !constant)?;+ }+ self.expect_word("BEGIN")?;+ while !self.word("END") {+ let start = self.pos;+ let tokens = self.expression_tokens_until(&[Token::SemiColon])?;+ self.expect(Token::SemiColon)?;+ if let Err(error) = self.statement(tokens) {+ if self.issue_position.is_none() {+ self.issue_position = self.tokens.get(start).map(|token| token.span.start);+ }+ return Err(error);+ }+ }+ self.expect_word("END")?;+ if !self.current().is_some_and(|token| token.token == Token::SemiColon) {+ let end_name = self.ident()?;+ if canonical(&end_name) != self.input.name {+ return Err("The outer END name does not match the selected routine".into());+ }+ }+ self.expect(Token::SemiColon)?;+ if self.pos != self.tokens.len() {+ return Err("Extra statements or unsupported trailing routine syntax are not approved".into());+ }+ for reference in &self.output.references {+ if reference.query.is_none()+ && reference.local_binding.is_none()+ && reference.parts.len() == 1+ && self.bindings.contains_key(&reference.parts[0].value)+ {+ return Err(format!("Forward or self declaration can shadow reference {} at {}:{}; qualify the intended external routine", reference.parts[0].value, reference.line, reference.column));+ }+ }+ Ok(())+ }+ fn statement(&mut self, tokens: Vec<TokenWithSpan>) -> Result<(), String> {+ let is_word =+ |index: usize, value| tokens.get(index).is_some_and(|token| token_unquoted_word_is(&token.token, value));+ if tokens.len() == 1 && is_word(0, "NULL") {+ return Ok(());+ }+ if is_word(0, "RETURN") {+ if tokens.len() == 1 {+ return if self.input.object_type == ObjectSourceKind::Procedure {+ Ok(())+ } else {+ Err("A scalar function RETURN needs an expression".into())+ };+ }+ if self.input.object_type != ObjectSourceKind::Function {+ return Err("A procedure RETURN cannot return a value".into());+ }+ self.expression(tokens[1..].to_vec(), None)?;+ return Ok(());+ }+ if is_word(0, "SELECT") {+ return self.select(tokens);+ }+ if [+ "IF",+ "LOOP",+ "WHILE",+ "FOR",+ "BEGIN",+ "DECLARE",+ "EXCEPTION",+ "EXECUTE",+ "OPEN",+ "CLOSE",+ "FETCH",+ "RAISE",+ "INSERT",+ "UPDATE",+ "DELETE",+ "MERGE",+ ]+ .iter()+ .any(|word| is_word(0, word))+ {+ return Err("This automatic plan supports NULL, RETURN, scalar assignment, static calls and single-relation SELECT INTO; correct or deselect this object".into());+ }+ if tokens.get(1).is_some_and(|token| token.token == Token::Assignment) {+ let Token::Word(word) = &tokens[0].token else {+ return Err("Assignment needs a local scalar target".into());+ };+ let ident = Ident { value: word.value.clone(), quote_style: word.quote_style, span: tokens[0].span };+ if self.bindings.get(&canonical(&ident)) != Some(&true) {+ return Err("Assignment target is not a writable local scalar".into());+ }+ self.expression(tokens[2..].to_vec(), None)?;+ return Ok(());+ }+ let mut parser = Parser::new(&OracleDialect {}).with_tokens_with_locations(tokens);+ let expr = parser.parse_expr().map_err(|error| error.to_string())?;+ if parser.peek_token_ref().token != Token::EOF {+ return Err("Statement is not a complete static procedure call".into());+ }+ match expr {+ Expr::Function(function) => self.call(&function, None, true),+ Expr::Identifier(ident) => self.reference(&[ident], OracleDraftReferenceRole::Procedure, Vec::new(), None),+ Expr::CompoundIdentifier(parts) => {+ self.reference(&parts, OracleDraftReferenceRole::Procedure, Vec::new(), None)+ }+ _ => Err("Only a complete static procedure call is supported in this statement position".into()),+ }+ }+ fn select(&mut self, tokens: Vec<TokenWithSpan>) -> Result<(), String> {+ let mut depth = 0isize;+ let mut into = None;+ let mut from = None;+ for (index, token) in tokens.iter().enumerate() {+ match token.token {+ Token::LParen => depth += 1,+ Token::RParen => depth -= 1,+ _ => {}+ }+ if depth == 0 && token_unquoted_word_is(&token.token, "INTO") && into.replace(index).is_some() {+ return Err("SELECT has more than one INTO scope".into());+ }+ if depth == 0 && token_unquoted_word_is(&token.token, "FROM") && from.replace(index).is_some() {+ return Err("SELECT has more than one FROM scope".into());+ }+ }+ let (into, from) = into+ .zip(from)+ .filter(|(into, from)| into < from)+ .ok_or("A single SELECT INTO ... FROM relation is required")?;+ let targets = &tokens[into + 1..from];+ if targets.is_empty() {+ return Err("SELECT INTO needs local scalar targets".into());+ }+ let mut count = 0;+ for (index, token) in targets.iter().enumerate() {+ if index % 2 == 1 {+ if token.token != Token::Comma {+ return Err("INTO targets must be a simple scalar list".into());+ }+ continue;+ }+ let Token::Word(word) = &token.token else {+ return Err("INTO targets must be local scalar identifiers".into());+ };+ let ident = Ident { value: word.value.clone(), quote_style: word.quote_style, span: token.span };+ if self.bindings.get(&canonical(&ident)) != Some(&true) {+ return Err("INTO target is not a writable local scalar".into());+ }+ count += 1;+ }+ if targets.len().is_multiple_of(2) {+ return Err("SELECT INTO target list is incomplete".into());+ }+ let query_tokens = tokens[..into].iter().chain(&tokens[from..]).cloned().collect();+ let statements = Parser::new(&OracleDialect {})+ .with_tokens_with_locations(query_tokens)+ .parse_statements()+ .map_err(|error| error.to_string())?;+ let [Statement::Query(query)] = statements.as_slice() else {+ return Err("A complete single SELECT is required".into());+ };+ if query.with.is_some()+ || query.order_by.is_some()+ || query.limit_clause.is_some()+ || query.fetch.is_some()+ || !query.locks.is_empty()+ || query.for_clause.is_some()+ || query.settings.is_some()+ || query.format_clause.is_some()+ || !query.pipe_operators.is_empty()+ {+ return Err("Additional SELECT query scopes or clauses need manual correction".into());+ }+ let SetExpr::Select(select) = query.body.as_ref() else {+ return Err("Set operations or nested SELECT bodies are not supported".into());+ };+ if !select.optimizer_hints.is_empty()+ || select.distinct.is_some()+ || select.select_modifiers.is_some()+ || select.top.is_some()+ || select.exclude.is_some()+ || select.into.is_some()+ || !select.lateral_views.is_empty()+ || select.prewhere.is_some()+ || !select.connect_by.is_empty()+ || !matches!(&select.group_by, GroupByExpr::Expressions(values, modifiers) if values.is_empty() && modifiers.is_empty())+ || !select.cluster_by.is_empty()+ || !select.distribute_by.is_empty()+ || !select.sort_by.is_empty()+ || select.having.is_some()+ || !select.named_window.is_empty()+ || select.qualify.is_some()+ || select.value_table_mode.is_some()+ || select.flavor != SelectFlavor::Standard+ {+ return Err("Only a plain single-relation SELECT with optional WHERE is supported".into());+ }+ if select.projection.len() != count || select.from.len() != 1 || !select.from[0].joins.is_empty() {+ return Err("SELECT projection and scalar INTO targets must match; joins require manual correction".into());+ }+ let TableFactor::Table {+ name: relation,+ alias,+ args,+ with_hints,+ version,+ with_ordinality,+ partitions,+ json_path,+ sample,+ index_hints,+ } = &select.from[0].relation+ else {+ return Err("SELECT requires one ordinary table or view".into());+ };+ if args.is_some()+ || !with_hints.is_empty()+ || version.is_some()+ || *with_ordinality+ || !partitions.is_empty()+ || json_path.is_some()+ || sample.is_some()+ || !index_hints.is_empty()+ || alias.as_ref().is_some_and(|alias| !alias.columns.is_empty())+ {+ return Err("Table functions, derived names and relation modifiers are not supported".into());+ }+ let parts = object_parts(relation)?;+ if parts.len() > 2 {+ return Err("A relation must be name or owner.name without a database link".into());+ }+ let query_index = self.output.queries.len();+ let relation_reference = self.output.references.len();+ self.reference(&parts, OracleDraftReferenceRole::Relation, Vec::new(), Some(query_index))?;+ self.output+ .queries+ .push(OracleDraftQuery { relation_reference, alias: alias.as_ref().map(|alias| name(&alias.name)) });+ for item in &select.projection {+ match item {+ SelectItem::UnnamedExpr(expr) | SelectItem::ExprWithAlias { expr, .. } => {+ self.visit_expr(expr, Some(query_index))?+ }+ _ => return Err("Project scalar expressions explicitly rather than SELECT *".into()),+ }+ }+ if let Some(expr) = &select.selection {+ self.visit_expr(expr, Some(query_index))?;+ }+ Ok(())+ }+}++pub fn analyze_oracle_routine_draft(input: EditableObjectSourceSqlInput) -> OracleRoutineDraftAnalysis {+ let mut analysis = Analysis {+ input: &input,+ tokens: Vec::new(),+ pos: 0,+ bindings: BTreeMap::new(),+ output: OracleRoutineDraftAnalysis::default(),+ issue_position: None,+ };+ let parsed: Result<(), String> = (|| {+ validate_oracle_routine_target_definition(input.clone(), None)?;+ analysis.tokens = Tokenizer::new(&OracleDialect {}, &input.source)+ .tokenize_with_location()+ .map_err(|error| error.to_string())?+ .into_iter()+ .filter(|token| !matches!(token.token, Token::Whitespace(_) | Token::EOF))+ .collect();+ analysis.parse()+ })();+ match parsed {+ Ok(()) => analysis.output.complete = true,+ Err(message) => {+ let position = analysis+ .issue_position+ .or_else(|| analysis.current().or_else(|| analysis.tokens.last()).map(|token| token.span.start));+ analysis.output.issues.push(OracleDraftIssue {+ code: "manual-static-correction".into(),+ message,+ line: position.map_or(1, |position| position.line),+ column: position.map_or(1, |position| position.column),+ });+ }+ }+ analysis.output+}++#[cfg(test)]+mod tests;diff --git a/crates/dbx-sql-core/src/object_source_sql/oracle_routines/analysis/tests.rs b/crates/dbx-sql-core/src/object_source_sql/oracle_routines/analysis/tests.rsnew file mode 100644index 0000000000..3dffbafb44--- /dev/null+++ b/crates/dbx-sql-core/src/object_source_sql/oracle_routines/analysis/tests.rs@@ -0,0 +1,165 @@+use super::*;++fn analyze(body: &str) -> OracleRoutineDraftAnalysis {+ analyze_oracle_routine_draft(EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: ObjectSourceKind::Function,+ schema: Some("Owner.Mixed".into()),+ name: "Mixed.Func".into(),+ source: format!("CREATE OR REPLACE FUNCTION \"Owner.Mixed\".\"Mixed.Func\" RETURN NUMBER AS {body}"),+ })+}+fn function(source: &str) -> OracleRoutineDraftAnalysis {+ analyze_oracle_routine_draft(EditableObjectSourceSqlInput {+ database_type: DatabaseType::Oracle,+ object_type: ObjectSourceKind::Function,+ schema: Some("OWNER".into()),+ name: "F".into(),+ source: source.into(),+ })+}++#[test]+fn constant_and_unicode_comment_bodies_are_fully_consumed_without_changing_the_source() {+ let comment = "-- 原文🙂 Source.Owner.f; EXECUTE IMMEDIATE\n".repeat(140);+ let input = EditableObjectSourceSqlInput { database_type: DatabaseType::OceanbaseOracle, object_type: ObjectSourceKind::Function, schema: Some("Owner.Mixed".into()), name: "Mixed.Func".into(), source: format!("CREATE OR REPLACE FUNCTION \"Owner.Mixed\".\"Mixed.Func\" RETURN VARCHAR2 AS\n{comment}BEGIN RETURN q'[Source.Owner.f; 保留🙂]'; END;") };+ let original = input.source.clone();+ let result = analyze_oracle_routine_draft(input.clone());+ assert!(result.complete, "{:?}", result.issues);+ assert!(result.references.is_empty());+ assert_eq!(input.source, original);+}++#[test]+fn scalar_parameters_locals_and_initializers_keep_scope_and_call_dependencies_separate() {+ let result = function("CREATE FUNCTION \"OWNER\".F(a IN NUMBER DEFAULT \"OWNER\".base(), b OUT NUMBER) RETURN NUMBER AUTHID DEFINER AS n NUMBER := \"OWNER\".initial(); c CONSTANT NUMBER := 1; BEGIN n := a + \"OWNER\".other(c); b := n; RETURN n; END F;");+ assert!(result.complete, "{:?}", result.issues);+ assert_eq!(result.parameters.len(), 2);+ assert!(result.parameters[0].has_default);+ assert_eq!(result.parameters[1].mode, "OUT");+ assert_eq!(+ result.references.iter().map(|reference| reference.parts.last().unwrap().value.as_str()).collect::<Vec<_>>(),+ vec!["BASE", "INITIAL", "OTHER"]+ );+ let shadowed = function("CREATE FUNCTION \"OWNER\".F(other NUMBER) RETURN NUMBER AS BEGIN RETURN other; END;");+ assert!(shadowed.complete);+ assert!(shadowed.references.is_empty());+}++#[test]+fn no_parentheses_function_values_and_package_calls_keep_exact_name_parts() {+ let result = analyze("BEGIN RETURN \"Owner.With.Dot\".\"Other.Func\" + \"OWNER\".PKG.member(1); END;");+ assert!(result.complete, "{:?}", result.issues);+ assert_eq!(result.references[0].role, OracleDraftReferenceRole::Value);+ assert_eq!(+ result.references[0].parts,+ vec![+ OracleDraftName { value: "Owner.With.Dot".into(), quoted: true },+ OracleDraftName { value: "Other.Func".into(), quoted: true }+ ]+ );+ assert_eq!(result.references[1].parts.len(), 3);+ assert_eq!(result.references[1].argument_writable, vec![false]);+}++#[test]+fn standalone_procedure_calls_include_no_argument_calls_and_writable_scalar_arguments() {+ let result = analyze_oracle_routine_draft(EditableObjectSourceSqlInput {+ database_type: DatabaseType::Oracle,+ object_type: ObjectSourceKind::Procedure,+ schema: Some("OWNER".into()),+ name: "P".into(),+ source:+ "CREATE PROCEDURE \"OWNER\".P(a IN OUT NUMBER) AS BEGIN \"OWNER\".ready; \"OWNER\".update_value(a, a+1); RETURN; END P;"+ .into(),+ });+ assert!(result.complete, "{:?}", result.issues);+ assert!(result.references.iter().all(|reference| reference.role == OracleDraftReferenceRole::Procedure));+ assert_eq!(result.references[1].argument_writable, vec![true, false]);+}++#[test]+fn a_single_table_select_keeps_columns_and_aliases_for_target_column_binding() {+ let result = analyze("n NUMBER; BEGIN SELECT COUNT(*) INTO n FROM \"Owner.Mixed\".\"Base.Table\"; RETURN n; END;");+ assert!(result.complete, "{:?}", result.issues);+ assert_eq!(result.references.len(), 1);+ assert_eq!(result.references[0].role, OracleDraftReferenceRole::Relation);+ let result = function("CREATE FUNCTION \"OWNER\".F(a NUMBER) RETURN NUMBER AS n NUMBER; BEGIN SELECT a, t.a INTO n, a FROM \"OWNER\".T t WHERE t.a > \"OWNER\".threshold; RETURN n; END;");+ assert!(!result.complete, "IN parameter is not writable INTO");+ let result = function("CREATE FUNCTION \"OWNER\".F(a NUMBER) RETURN NUMBER AS n NUMBER; BEGIN SELECT t.a AS selected_value INTO n FROM \"OWNER\".T t WHERE a > \"OWNER\".threshold; RETURN n; END;");+ assert!(result.complete, "{:?}", result.issues);+ assert_eq!(result.queries[0].alias.as_ref().unwrap().value, "T");+ assert!(result.references.iter().all(|reference| reference.query == Some(0)));+ assert_eq!(+ result.references.iter().find(|reference| reference.parts[0].value == "A").unwrap().local_binding,+ Some(false)+ );+ assert!(!result+ .references+ .iter()+ .any(|reference| reference.parts.iter().any(|part| part.value == "SELECTED_VALUE")));+}++#[test]+fn edited_drafts_produce_new_reference_sets_including_zero_argument_functions() {+ let old = analyze("BEGIN RETURN old_func; END;");+ let edited = analyze("BEGIN RETURN new_func(); END;");+ assert!(old.complete && edited.complete);+ assert_eq!(old.references[0].parts[0].value, "OLD_FUNC");+ assert_eq!(edited.references[0].parts[0].value, "NEW_FUNC");+ assert_eq!(edited.references[0].role, OracleDraftReferenceRole::Function);+}++#[test]+fn unsupported_scopes_dynamic_sql_and_unconsumed_clauses_are_positioned_not_ignored() {+ for body in [+ "BEGIN\nIF 1=1 THEN RETURN 1; END IF; END;",+ "FUNCTION local_f RETURN NUMBER AS BEGIN RETURN 1; END; BEGIN RETURN local_f; END;",+ "BEGIN EXECUTE IMMEDIATE 'SELECT 1 FROM DUAL'; RETURN 1; END;",+ "n NUMBER; BEGIN SELECT COUNT(*) INTO n FROM \"OWNER\".T JOIN \"OWNER\".U ON T.ID=U.ID; RETURN n; END;",+ "BEGIN RETURN (SELECT 1 FROM DUAL); END;",+ "n \"OWNER\".T%TYPE; BEGIN RETURN 1; END;",+ "BEGIN RETURN 1; EXCEPTION WHEN OTHERS THEN RETURN 0; END;",+ ] {+ let result = analyze(body);+ assert!(!result.complete, "unsupported body was accepted: {body}");+ assert!(!result.issues.is_empty());+ assert!(result.issues[0].line >= 1 && result.issues[0].column >= 1);+ }+ assert!(+ !function("CREATE FUNCTION \"OWNER\".F RETURN NUMBER AUTHID CURRENT_USER AS BEGIN RETURN 1; END;").complete+ );+}++#[test]+fn local_calls_forward_bindings_and_bind_placeholders_cannot_hide_dependencies() {+ for source in [+ "CREATE FUNCTION \"OWNER\".F(other NUMBER) RETURN NUMBER AS BEGIN RETURN other(1); END;",+ "CREATE FUNCTION \"OWNER\".F RETURN NUMBER AS n NUMBER := n; BEGIN RETURN n; END;",+ "CREATE FUNCTION \"OWNER\".F RETURN NUMBER AS BEGIN RETURN ?; END;",+ "CREATE FUNCTION \"OWNER\".F RETURN NUMBER PARALLEL_ENABLE AS BEGIN RETURN 1; END;",+ ] {+ assert!(!function(source).complete, "{source}");+ }+}++#[test]+fn quoted_keyword_names_are_identifiers_and_unicode_reference_spans_point_to_original_tokens() {+ let result =+ analyze("\"BEGIN\" NUMBER := 1; BEGIN\n-- 🙂 注释\nRETURN \"Other.Schema\".\"Other.Func\" + \"BEGIN\"; END;");+ assert!(result.complete, "{:?}", result.issues);+ assert_eq!(result.references.len(), 1);+ assert_eq!(result.references[0].line, 3);+ assert_eq!(result.references[0].column, 8);+}++#[test]+fn extra_statements_and_wrong_identity_never_enter_a_complete_plan() {+ for source in [+ "CREATE FUNCTION \"OWNER\".F RETURN NUMBER AS BEGIN RETURN 1; END; DELETE FROM \"OWNER\".T;",+ "CREATE FUNCTION \"OWNER\".OTHER RETURN NUMBER AS BEGIN RETURN 1; END;",+ "CREATE PROCEDURE \"OWNER\".F AS BEGIN NULL; END;",+ ] {+ assert!(!function(source).complete);+ }+}diff --git a/crates/dbx-sql-schema/src/schema_diff.rs b/crates/dbx-sql-schema/src/schema_diff.rsindex 53510621fc..d14c210efc 100644--- a/crates/dbx-sql-schema/src/schema_diff.rs+++ b/crates/dbx-sql-schema/src/schema_diff.rs@@ -23,7 +23,9 @@ use crate::types::{ColumnInfo, ForeignKeyInfo, FunctionInfo, IndexInfo, OwnerInfo, RuleInfo, SequenceInfo, TableInfo, TriggerInfo,};+mod oracle_routines;mod sqlserver_dependencies;+pub use oracle_routines::{diff_oracle_routines, oracle_routine_diff_sql, OracleRoutineCompareContext};use sqlserver_dependencies::build_dependency_aware_alter_column_batch;@@ -498,6 +500,8 @@ pub struct SchemaDiffPreparationOptions {pub source_functions: Vec<FunctionInfo>,#[serde(default)]pub target_functions: Vec<FunctionInfo>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub oracle_routines: Option<OracleRoutineCompareContext>,#[serde(default)]pub source_sequences: Vec<SequenceInfo>,#[serde(default)]@@ -1989,6 +1993,7 @@ impl Default for SchemaDiffPreparationOptions {target_details: Vec::new(),source_functions: Vec::new(),target_functions: Vec::new(),+ oracle_routines: None,source_sequences: Vec::new(),target_sequences: Vec::new(),source_rules: Vec::new(),@@ -2191,7 +2196,10 @@ pub fn prepare_schema_diff(options: SchemaDiffPreparationOptions) -> SchemaDiffPNone};- let function_diffs = diff_functions(&options.source_functions, &options.target_functions);+ let function_diffs = match &options.oracle_routines {+ Some(context) => diff_oracle_routines(&options.source_functions, &options.target_functions, context),+ None => diff_functions(&options.source_functions, &options.target_functions),+ };let sequence_diffs = diff_sequences(&options.source_sequences, &options.target_sequences);let rule_diffs = diff_rules(&options.source_rules, &options.target_rules);let owner_diffs = diff_owners(&options.source_owners, &options.target_owners);@@ -2214,9 +2222,9 @@ pub fn prepare_schema_diff(options: SchemaDiffPreparationOptions) -> SchemaDiffP}}- let (sync_sql, _) = generate_schema_sync_sql_inner(+ let (mut sync_sql, _) = generate_schema_sync_sql_inner(&diffs,- &function_diffs,+ if options.oracle_routines.is_some() { &[] } else { &function_diffs },&sequence_diffs,&rule_diffs,&owner_diffs,@@ -2226,6 +2234,18 @@ pub fn prepare_schema_diff(options: SchemaDiffPreparationOptions) -> SchemaDiffPoptions.source_dialect,&options.field_mappings,);+ if let Some(context) = &options.oracle_routines {+ for diff in &function_diffs {+ if let Ok(sql) = oracle_routine_diff_sql(diff, context) {+ if !sql.is_empty() {+ if !sync_sql.is_empty() {+ sync_sql.push_str("\n\n");+ }+ sync_sql.push_str(&sql);+ }+ }+ }+ }let (rollback_sync_sql, missing_rollback_objects) = match &rollback_graph {Some(graph) => {@@ -13953,6 +13973,7 @@ mod tests {target_details: vec![],source_functions: vec![],target_functions: vec![],+ oracle_routines: None,source_sequences: vec![],target_sequences: vec![],source_rules: vec![],diff --git a/crates/dbx-sql-schema/src/schema_diff/oracle_routines.rs b/crates/dbx-sql-schema/src/schema_diff/oracle_routines.rsnew file mode 100644index 0000000000..a9c1830bd7--- /dev/null+++ b/crates/dbx-sql-schema/src/schema_diff/oracle_routines.rs@@ -0,0 +1,303 @@+use super::{DatabaseType, FunctionDiff, FunctionInfo};+use dbx_sql_core::object_source_sql::{+ comparable_oracle_routine_definition, prepare_oracle_routine_definition, OracleRoutineDefinitionInput,+};+use dbx_sql_core::types::ObjectSourceKind;+use serde::{Deserialize, Serialize};+use std::collections::{BTreeMap, BTreeSet};++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleRoutineCompareContext {+ pub source_database_type: DatabaseType,+ pub target_database_type: DatabaseType,+ pub source_schema: String,+ pub target_schema: String,+ pub source_enumeration_complete: bool,+ pub target_enumeration_complete: bool,+ pub source_incomplete_names: Vec<String>,+ pub target_incomplete_names: Vec<String>,+}++impl OracleRoutineCompareContext {+ fn supported(&self) -> bool {+ self.source_database_type == self.target_database_type+ && matches!(self.source_database_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle)+ && !self.source_schema.is_empty()+ && !self.target_schema.is_empty()+ }+}++fn kind(function: &FunctionInfo) -> Result<ObjectSourceKind, String> {+ match function.function_type.as_str() {+ "PROCEDURE" => Ok(ObjectSourceKind::Procedure),+ "FUNCTION" => Ok(ObjectSourceKind::Function),+ _ => Err("Routine kind must be exactly PROCEDURE or FUNCTION".into()),+ }+}++fn definition_input(+ function: &FunctionInfo,+ context: &OracleRoutineCompareContext,+ source: bool,+ replace: bool,+) -> Result<OracleRoutineDefinitionInput, String> {+ Ok(OracleRoutineDefinitionInput {+ database_type: if source { context.source_database_type } else { context.target_database_type },+ object_type: kind(function)?,+ source_owner: if source { &context.source_schema } else { &context.target_schema }.clone(),+ target_owner: context.target_schema.clone(),+ name: function.name.clone(),+ source: function.definition.clone(),+ replace,+ })+}++/// Keep equal and unreadable rows for the existing side-by-side source viewer.+/// Absence is actionable only when the opposite inventory is complete.+pub fn diff_oracle_routines(+ source: &[FunctionInfo],+ target: &[FunctionInfo],+ context: &OracleRoutineCompareContext,+) -> Vec<FunctionDiff> {+ let source_map = source.iter().map(|function| (function.name.as_str(), function)).collect::<BTreeMap<_, _>>();+ let target_map = target.iter().map(|function| (function.name.as_str(), function)).collect::<BTreeMap<_, _>>();+ let names = source_map.keys().chain(target_map.keys()).copied().collect::<BTreeSet<_>>();+ names+ .into_iter()+ .map(|name| {+ let source = source_map.get(name).copied();+ let target = target_map.get(name).copied();+ let mut diff = FunctionDiff {+ diff_type: "unreadable".into(),+ name: name.into(),+ source: source.cloned(),+ target: target.cloned(),+ changes: Vec::new(),+ };+ let compared = (|| {+ if !context.supported() {+ return Err(+ "Automatic routine comparison requires the same Oracle product type and exact owners".into()+ );+ }+ if source.is_some() && context.source_incomplete_names.iter().any(|candidate| candidate == name) {+ return Err("Source routine definition is incomplete; readable original text is retained".into());+ }+ if target.is_some() && context.target_incomplete_names.iter().any(|candidate| candidate == name) {+ return Err("Target routine definition is incomplete; readable original text is retained".into());+ }+ if source.is_none() && !context.source_enumeration_complete {+ return Err("Source inventory is incomplete; absence and deletion are not established".into());+ }+ if target.is_none() && !context.target_enumeration_complete {+ return Err("Target inventory is incomplete; absence and creation are not established".into());+ }+ match (source, target) {+ (Some(source), Some(target)) => {+ if kind(source)? != kind(target)? {+ return Ok("conflict");+ }+ let source =+ comparable_oracle_routine_definition(definition_input(source, context, true, true)?)?;+ let target =+ comparable_oracle_routine_definition(definition_input(target, context, false, true)?)?;+ Ok(if source == target { "equal" } else { "modified" })+ }+ (Some(source), None) => {+ prepare_oracle_routine_definition(definition_input(source, context, true, false)?)?;+ Ok("added")+ }+ (None, Some(target)) => {+ comparable_oracle_routine_definition(definition_input(target, context, false, true)?)?;+ Ok("removed")+ }+ _ => unreachable!("names are collected from the two inventories"),+ }+ })();+ match compared {+ Ok(state) => {+ diff.diff_type = state.into();+ if state == "conflict" {+ diff.changes.push(+ "Routine kind conflict: review an explicit drop/create plan; no implicit replacement"+ .into(),+ );+ }+ if state == "modified" {+ diff.changes.push("definition changed".into());+ }+ }+ Err(error) => diff.changes.push(error),+ }+ diff+ })+ .collect()+}++pub fn oracle_routine_diff_sql(diff: &FunctionDiff, context: &OracleRoutineCompareContext) -> Result<String, String> {+ if !context.supported() {+ return Err("Oracle routine target adaptation requires the same product type".into());+ }+ match diff.diff_type.as_str() {+ "added" | "modified" => {+ let source = diff.source.as_ref().ok_or("Routine source is unavailable")?;+ if diff.diff_type == "modified"+ && kind(source)? != kind(diff.target.as_ref().ok_or("Routine target is unavailable")?)?+ {+ return Err("A routine kind conflict cannot be replaced".into());+ }+ prepare_oracle_routine_definition(definition_input(source, context, true, diff.diff_type == "modified")?)+ }+ "removed" => {+ let target = diff.target.as_ref().ok_or("Routine target is unavailable")?;+ let keyword = match kind(target)? {+ ObjectSourceKind::Procedure => "PROCEDURE",+ _ => "FUNCTION",+ };+ Ok(format!(+ "DROP {keyword} \"{}\".\"{}\";",+ context.target_schema.replace('"', "\"\""),+ target.name.replace('"', "\"\"")+ ))+ }+ "equal" => Ok(String::new()),+ _ => Err("Routine comparison is unresolved; keep the draft and resolve its issues before deployment".into()),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::schema_diff::{prepare_schema_diff, SchemaDiffPreparationOptions};++ fn context() -> OracleRoutineCompareContext {+ OracleRoutineCompareContext {+ source_database_type: DatabaseType::OceanbaseOracle,+ target_database_type: DatabaseType::OceanbaseOracle,+ source_schema: "Source.Owner".into(),+ target_schema: "Target.Owner".into(),+ source_enumeration_complete: true,+ target_enumeration_complete: true,+ source_incomplete_names: Vec::new(),+ target_incomplete_names: Vec::new(),+ }+ }++ fn function(name: &str, value: &str) -> FunctionInfo {+ FunctionInfo {+ name: name.into(),+ function_type: "FUNCTION".into(),+ data_type: String::new(),+ arguments: String::new(),+ definition: format!(+ "FUNCTION \"{}\" RETURN VARCHAR2 AS BEGIN RETURN '{}'; END",+ name.replace('"', "\"\""),+ value+ ),+ }+ }++ #[test]+ fn real_preparation_keeps_all_four_states_and_kind() {+ let source = vec![+ function("Added.Func", "new"),+ function("Changed.Func", "two spaces"),+ function("Equal.Func", "same"),+ ];+ let target = vec![+ function("Removed.Func", "old"),+ function("Changed.Func", "two spaces"),+ function("Equal.Func", "same"),+ ];+ let prepared = prepare_schema_diff(SchemaDiffPreparationOptions {+ source_functions: source,+ target_functions: target,+ database_type: DatabaseType::OceanbaseOracle,+ oracle_routines: Some(context()),+ ..Default::default()+ });+ assert_eq!(+ prepared+ .function_diffs+ .iter()+ .map(|diff| (diff.name.as_str(), diff.diff_type.as_str()))+ .collect::<Vec<_>>(),+ vec![+ ("Added.Func", "added"),+ ("Changed.Func", "modified"),+ ("Equal.Func", "equal"),+ ("Removed.Func", "removed")+ ]+ );+ assert!(prepared.sync_sql.contains("DROP FUNCTION \"Target.Owner\".\"Removed.Func\";"));+ assert!(!prepared.sync_sql.contains("DROP PROCEDURE"));+ }++ #[test]+ fn incomplete_inventory_does_not_create_a_false_deletion_or_addition() {+ let mut context = context();+ context.source_enumeration_complete = false;+ let diffs = diff_oracle_routines(&[], &[function("Kept.Func", "v")], &context);+ assert_eq!(diffs[0].diff_type, "unreadable");+ assert!(oracle_routine_diff_sql(&diffs[0], &context).is_err());+ context.source_enumeration_complete = true;+ context.target_enumeration_complete = false;+ assert_eq!(diff_oracle_routines(&[function("Kept.Func", "v")], &[], &context)[0].diff_type, "unreadable");+ }++ #[test]+ fn per_object_failure_retains_raw_text_and_other_actionable_rows() {+ let mut context = context();+ context.source_incomplete_names.push("Unread.Func".into());+ let source = vec![function("Unread.Func", "retained"), function("Good.Func", "new")];+ let diffs = diff_oracle_routines(&source, &[function("Unread.Func", "old")], &context);+ assert_eq!(diffs[0].diff_type, "added");+ assert_eq!(diffs[1].diff_type, "unreadable");+ assert_eq!(diffs[1].source.as_ref().unwrap().definition, source[0].definition);+ }++ #[test]+ fn kind_conflict_is_not_a_replace_or_implicit_drop() {+ let source = FunctionInfo {+ function_type: "PROCEDURE".into(),+ definition: "PROCEDURE \"Kind.Mixed\" AS BEGIN NULL; END".into(),+ ..function("Kind.Mixed", "")+ };+ let diffs = diff_oracle_routines(&[source], &[function("Kind.Mixed", "v")], &context());+ assert_eq!(diffs[0].diff_type, "conflict");+ assert!(oracle_routine_diff_sql(&diffs[0], &context()).is_err());+ }++ #[test]+ fn product_types_do_not_collapse_to_the_oracle_dialect() {+ let mut context = context();+ context.source_database_type = DatabaseType::Oracle;+ let diffs = diff_oracle_routines(&[function("Mixed.Func", "v")], &[], &context);+ assert_eq!(diffs[0].diff_type, "unreadable");+ assert!(oracle_routine_diff_sql(&diffs[0], &context).is_err());+ }++ #[test]+ fn new_create_cannot_replace_a_concurrent_object_and_does_not_rewrite_body_literals() {+ let source = function("New.Func", "Source.Owner text");+ let diffs = diff_oracle_routines(&[source], &[], &context());+ let sql = oracle_routine_diff_sql(&diffs[0], &context()).unwrap();+ assert!(sql.contains("FUNCTION \"Target.Owner\".\"New.Func\""));+ assert!(!sql.contains("OR REPLACE"));+ assert!(sql.contains("'Source.Owner text'"));+ }++ #[test]+ fn quoted_owner_mapping_is_confined_to_the_declaration() {+ let mut source = function("Mixed.Func", "same");+ source.definition = source.definition.replacen("FUNCTION ", "CREATE FUNCTION \"Source.Owner\".", 1);+ let mut target = function("Mixed.Func", "same");+ target.definition = format!("CREATE OR REPLACE {};\n/", target.definition).replacen(+ "FUNCTION ",+ "FUNCTION \"Target.Owner\".",+ 1,+ );+ assert_eq!(diff_oracle_routines(&[source], &[target], &context())[0].diff_type, "equal");+ }+}diff --git a/crates/dbx-tauri-schema/src/commands.rs b/crates/dbx-tauri-schema/src/commands.rsindex 7156503f9c..b365b73369 100644--- a/crates/dbx-tauri-schema/src/commands.rs+++ b/crates/dbx-tauri-schema/src/commands.rs@@ -662,6 +662,85 @@ pub async fn list_functions(dbx_core::schema::list_functions_core(&state, &connection_id, &database, &schema).await}+#[tauri::command]+pub async fn load_schema_diff_routines(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ database: String,+ schema: String,+ selected_routines: Option<Vec<String>>,+) -> Result<dbx_core::schema::oracle_routines::RoutineSnapshot, String> {+ dbx_core::schema::oracle_routines::load_selected_schema_diff_routines_core(+ &state,+ &connection_id,+ &database,+ &schema,+ selected_routines.as_deref(),+ )+ .await+}++#[tauri::command]+pub async fn prepare_oracle_routine_save(+ state: State<'_, Arc<AppState>>,+ input: dbx_core::schema::oracle_routines::OracleRoutineSaveInput,+) -> Result<dbx_core::schema::oracle_routines::RoutineOperationRecord, String> {+ dbx_core::schema::oracle_routines::prepare_oracle_routine_save_core(&state, input).await+}++#[tauri::command]+pub async fn prepare_oracle_routine_plan(+ state: State<'_, Arc<AppState>>,+ input: dbx_core::schema::oracle_routines::OracleRoutinePlanInput,+) -> Result<dbx_core::schema::oracle_routines::OracleRoutinePlan, String> {+ dbx_core::schema::oracle_routines::prepare_oracle_routine_plan_core(&state, input).await+}++#[tauri::command]+pub async fn prepare_oracle_routine_recovery(+ state: State<'_, Arc<AppState>>,+ operation_id: String,+) -> Result<dbx_core::schema::oracle_routines::OracleRoutinePlan, String> {+ dbx_core::schema::oracle_routines::prepare_oracle_routine_recovery_core(&state, &operation_id).await+}++#[tauri::command]+pub async fn execute_oracle_routine_operation(+ state: State<'_, Arc<AppState>>,+ operation_id: String,+ approved_sql: String,+) -> Result<dbx_core::schema::oracle_routines::RoutineOperationRecord, String> {+ dbx_core::schema::oracle_routines::execute_oracle_routine_operation_core(+ state.inner().clone(),+ operation_id,+ approved_sql,+ )+ .await+}++#[tauri::command]+pub async fn observe_oracle_routine_operation(+ state: State<'_, Arc<AppState>>,+ operation_id: String,+ refresh_readback: Option<bool>,+) -> Result<dbx_core::schema::oracle_routines::RoutineOperationObservation, String> {+ Ok(dbx_core::schema::oracle_routines::observe_oracle_routine_operation_core(+ &state,+ &operation_id,+ refresh_readback.unwrap_or(false),+ )+ .await)+}++#[tauri::command]+pub fn update_oracle_routine_operation_references(+ state: State<'_, Arc<AppState>>,+ retain_operation_ids: Vec<String>,+ release_operation_ids: Vec<String>,+) -> Result<(), String> {+ state.routine_operations.update_references(&retain_operation_ids, &release_operation_ids)+}+#[tauri::command]pub async fn list_sequences(state: State<'_, Arc<AppState>>,diff --git a/crates/dbx-tauri-schema/src/lib.rs b/crates/dbx-tauri-schema/src/lib.rsindex b6ecef3734..0962014ebd 100644--- a/crates/dbx-tauri-schema/src/lib.rs+++ b/crates/dbx-tauri-schema/src/lib.rs@@ -53,6 +53,13 @@ define_registry![list_subpartitions,get_table_ddl,list_functions,+ load_schema_diff_routines,+ prepare_oracle_routine_save,+ prepare_oracle_routine_plan,+ prepare_oracle_routine_recovery,+ execute_oracle_routine_operation,+ observe_oracle_routine_operation,+ update_oracle_routine_operation_references,list_sequences,list_rules,list_owners,@@ -85,8 +92,15 @@ mod tests {#[test]fn handles_only_schema_commands() {- assert_eq!(COMMANDS.len(), 49);+ assert_eq!(COMMANDS.len(), 56);assert!(handles("list_databases"));+ assert!(handles("load_schema_diff_routines"));+ assert!(handles("prepare_oracle_routine_save"));+ assert!(handles("prepare_oracle_routine_plan"));+ assert!(handles("prepare_oracle_routine_recovery"));+ assert!(handles("execute_oracle_routine_operation"));+ assert!(handles("observe_oracle_routine_operation"));+ assert!(handles("update_oracle_routine_operation_references"));assert!(handles("list_event_triggers"));assert!(!handles("prepare_schema_diff"));assert!(!handles("load_connections"));diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex 3c1e99398e..bc2183dfa2 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -813,6 +813,13 @@ async fn serve() -> Result<(), String> {.route("/schema/invalid-indexes", get(routes::schema::list_invalid_indexes)).route("/schema/subpartitions", get(routes::schema::list_subpartitions)).route("/schema/functions", get(routes::schema::list_functions))+ .route("/schema/diff-routines", get(routes::schema::load_schema_diff_routines))+ .route("/schema/routine-save", post(routes::schema::prepare_oracle_routine_save))+ .route("/schema/routine-plan", post(routes::schema::prepare_oracle_routine_plan))+ .route("/schema/routine-recovery", post(routes::schema::prepare_oracle_routine_recovery))+ .route("/schema/routine-execute", post(routes::schema::execute_oracle_routine_operation))+ .route("/schema/routine-operation", get(routes::schema::observe_oracle_routine_operation))+ .route("/schema/routine-operation-references", post(routes::schema::update_oracle_routine_operation_references)).route("/schema/sequences", get(routes::schema::list_sequences)).route("/schema/rules", get(routes::schema::list_rules)).route("/schema/owners", get(routes::schema::list_owners))diff --git a/crates/dbx-web/src/routes/schema.rs b/crates/dbx-web/src/routes/schema.rsindex f25c6b28ed..3610a3beb2 100644--- a/crates/dbx-web/src/routes/schema.rs+++ b/crates/dbx-web/src/routes/schema.rs@@ -4,6 +4,7 @@ use std::sync::Arc;use crate::error::AppError;use crate::state::WebState;use axum::extract::{Query, State};+use axum::http::HeaderMap;use axum::Json;use dbx_core::connection::AppState;use serde::de::DeserializeOwned;@@ -847,6 +848,152 @@ pub async fn list_functions(Ok(Json(serde_json::to_value(result).map_err(|e| AppError::from(e.to_string()))?))}+#[derive(Deserialize)]+pub struct RoutineSnapshotQuery {+ #[serde(flatten)]+ scope: SchemaQuery,+ selected_routines: Option<String>,+}++pub async fn load_schema_diff_routines(+ State(state): State<Arc<WebState>>,+ Query(query): Query<RoutineSnapshotQuery>,+) -> Result<Json<dbx_core::schema::oracle_routines::RoutineSnapshot>, AppError> {+ let selected_routines = query+ .selected_routines+ .as_deref()+ .map(serde_json::from_str::<Vec<String>>)+ .transpose()+ .map_err(|error| AppError::from(format!("Invalid selected routine names: {error}")))?;+ let q = query.scope;+ let snapshot = dbx_core::schema::oracle_routines::load_selected_schema_diff_routines_core(+ &state.app,+ &q.connection_id,+ q.database.as_deref().unwrap_or(""),+ q.schema.as_deref().unwrap_or(""),+ selected_routines.as_deref(),+ )+ .await+ .map_err(AppError::from)?;+ Ok(Json(snapshot))+}++pub async fn prepare_oracle_routine_save(+ State(state): State<Arc<WebState>>,+ Json(input): Json<dbx_core::schema::oracle_routines::OracleRoutineSaveInput>,+) -> Result<Json<dbx_core::schema::oracle_routines::RoutineOperationRecord>, AppError> {+ dbx_core::schema::oracle_routines::prepare_oracle_routine_save_core(&state.app, input)+ .await+ .map(Json)+ .map_err(AppError::from)+}++pub async fn prepare_oracle_routine_plan(+ State(state): State<Arc<WebState>>,+ Json(input): Json<dbx_core::schema::oracle_routines::OracleRoutinePlanInput>,+) -> Result<Json<dbx_core::schema::oracle_routines::OracleRoutinePlan>, AppError> {+ dbx_core::schema::oracle_routines::prepare_oracle_routine_plan_core(&state.app, input)+ .await+ .map(Json)+ .map_err(AppError::from)+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineRecoveryRequest {+ operation_id: String,+}++pub async fn prepare_oracle_routine_recovery(+ State(state): State<Arc<WebState>>,+ Json(request): Json<RoutineRecoveryRequest>,+) -> Result<Json<dbx_core::schema::oracle_routines::OracleRoutinePlan>, AppError> {+ dbx_core::schema::oracle_routines::prepare_oracle_routine_recovery_core(&state.app, &request.operation_id)+ .await+ .map(Json)+ .map_err(AppError::from)+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ExecuteRoutineOperationRequest {+ operation_id: String,+ approved_sql: String,+}++pub async fn execute_oracle_routine_operation(+ State(state): State<Arc<WebState>>,+ headers: HeaderMap,+ Json(request): Json<ExecuteRoutineOperationRequest>,+) -> Result<Json<dbx_core::schema::oracle_routines::RoutineOperationRecord>, AppError> {+ let original = state+ .app+ .routine_operations+ .observe(&request.operation_id)+ .operation+ .ok_or_else(|| AppError::from("Original routine operation is unavailable; do not replay"))?;+ let database = super::mcp_policy::ensure_sql(+ &state,+ &headers,+ &original.target.connection_id,+ &original.target.database,+ &request.approved_sql,+ false,+ )+ .await?;+ if database != original.target.database {+ return Err(AppError::from("Routine operation cannot switch its approved target database"));+ }+ dbx_core::schema::oracle_routines::execute_oracle_routine_operation_core(+ state.app.clone(),+ request.operation_id,+ request.approved_sql,+ )+ .await+ .map(Json)+ .map_err(AppError::from)+}++#[derive(Deserialize)]+pub struct RoutineOperationQuery {+ operation_id: String,+ #[serde(default)]+ refresh_readback: bool,+}++pub async fn observe_oracle_routine_operation(+ State(state): State<Arc<WebState>>,+ Query(query): Query<RoutineOperationQuery>,+) -> Json<dbx_core::schema::oracle_routines::RoutineOperationObservation> {+ Json(+ dbx_core::schema::oracle_routines::observe_oracle_routine_operation_core(+ &state.app,+ &query.operation_id,+ query.refresh_readback,+ )+ .await,+ )+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineOperationReferences {+ retain_operation_ids: Vec<String>,+ release_operation_ids: Vec<String>,+}++pub async fn update_oracle_routine_operation_references(+ State(state): State<Arc<WebState>>,+ Json(input): Json<RoutineOperationReferences>,+) -> Result<Json<()>, AppError> {+ state+ .app+ .routine_operations+ .update_references(&input.retain_operation_ids, &input.release_operation_ids)+ .map_err(AppError::from)?;+ Ok(Json(()))+}+#[derive(Deserialize)]pub struct SequenceQuery {pub connection_id: String,diff --git a/docs/content/docs/data-transfer.cn.mdx b/docs/content/docs/data-transfer.cn.mdxindex 61b682a3fc..73e67f764d 100644--- a/docs/content/docs/data-transfer.cn.mdx+++ b/docs/content/docs/data-transfer.cn.mdx@@ -135,6 +135,8 @@ PostgreSQL 到 PostgreSQL 且启用创建表时,DBX 会在能力允许时处因此“任务完成”不代表所有表都成功;应检查最终状态、失败列表、目标行数和关键字段。+Oracle/OceanBase Oracle 独立过程和函数传输后还会读回精确对象、完整定义和编译结果。DDL 返回成功但对象为 `INVALID`,或读回失败、定义不符时,均不计为传输成功;错误中保留编译位置或核对失败原因。已有目标仍跳过,新建不使用 `OR REPLACE` 覆盖同名对象。+## 数据库覆盖范围DBX 按驱动能力清单过滤源和目标连接。当前实现同时包含 SQL 到 SQL、MongoDB 到 MongoDB,以及部分 MongoDB 与 SQL 之间的转换路径;并非所有已支持连接都提供数据传输。diff --git a/docs/content/docs/data-transfer.mdx b/docs/content/docs/data-transfer.mdxindex 29dabd9ba8..8c395a762d 100644--- a/docs/content/docs/data-transfer.mdx+++ b/docs/content/docs/data-transfer.mdx@@ -135,6 +135,8 @@ A multi-table task does not discard the entire queue after the first table failuAs a result, a finished task does not necessarily mean every table succeeded. Check the terminal state, failure list, target row counts, and key fields.+Oracle and OceanBase Oracle standalone routine transfers also read back the exact object, full definition, and compiler result. An acknowledged DDL with an `INVALID` object, failed readback, or mismatched definition does not count as a successful transfer. Errors retain compiler coordinates or the verification failure. Existing targets are still skipped; new routines do not use `OR REPLACE` to overwrite a competing name.+## Database CoverageDBX filters source and target connections through the driver capability manifest. The implementation includes SQL-to-SQL, MongoDB-to-MongoDB, and selected MongoDB/SQL conversion paths. Not every connectable database supports Data Transfer.diff --git a/docs/content/docs/schema-diff.cn.mdx b/docs/content/docs/schema-diff.cn.mdxindex ae6bd43cb7..c1502cbf2f 100644--- a/docs/content/docs/schema-diff.cn.mdx+++ b/docs/content/docs/schema-diff.cn.mdx@@ -85,7 +85,7 @@ DBX 提供两类对比工作流:- 批次模式和表名模式- 是否显示系统对象-过滤用于控制比较范围,不等于数据库权限。当前账号无法读取的对象不会出现在结果中。+过滤用于控制比较范围,不增加数据库权限。Oracle 例程读取不完整时会保留已识别对象和问题;未列出的对象不能据此认定不存在。其他对象也受账号的元数据可见范围限制。### 重命名检测@@ -119,6 +119,20 @@ DBX 提供两类对比工作流:<Callout type="info">“在事务中执行”只在目标数据库和语句支持事务 DDL 时提供真正的整体回滚。MySQL 等数据库的 DDL 可能隐式提交。</Callout>+### Oracle 独立过程和函数++Oracle 与 OceanBase Oracle 的独立 `PROCEDURE`、`FUNCTION` 使用专用读取和部署流程。两端必须是同一产品类型;Oracle 与 OceanBase Oracle 之间不自动转换。包、TYPE、同义词和 DBLink 不在此流程的迁移范围内。++在例程列表查看新增、修改、删除和相同对象,点击任一行比较或复制两侧原文。读取不完整、种类冲突的对象保留原文及原因,不生成可执行操作,也不会把读取失败当成对象不存在。++选择对象进入部署审核后,在原编辑器逐个修改目标草稿,再点击 **重新校验**。自动适配只调整声明中的目标 Schema 和外层分隔符,不改正文中的 Schema 引用。校验会根据最终稿重新解析引用、检查目标目录并安排顺序;新建使用 `CREATE`,不会自动覆盖同名对象。替换和删除还需要完整的调用方可见性,权限不足会阻止相应步骤。预览后内容变化时,用 **刷新基线,保留草稿** 保留草稿并重新校验。++自动依赖分析目前接受标量声明、`NULL`、返回、赋值、可解析的过程/函数调用及单表静态 `SELECT ... INTO`。动态 SQL、循环、异常块等超出当前分析范围的语法会显示行列位置。可在原草稿修正或移出本次选择;原文查看、复制及日常源码编辑不受此分析范围限制。++执行按对象记录回执和读回结果。只有请求已终结、定义匹配、对象为 `VALID` 且没有编译错误时才显示验证通过;`WARNING` 单列显示。已提交但 `INVALID` 会保留编译位置并停止后续步骤,修正后只重新批准未完成步骤,已完成对象不会重放。++关闭审核页只停止发送下一步,不表示当前数据库请求已停止。应用进程内重开同一比较任务可恢复草稿和记录。结果未知时,使用 **核对原请求** 查询原操作 ID,不换 ID 重试;必须先确认原请求终结才能继续写入。**预览恢复脚本** 是新的、需确认的 DDL,不是事务回滚:目标已被第三方修改时拒绝覆盖,删除前未保存的授权等材料会使恢复仅可复制、不可一键执行。+## 方言语义DBX 会尽量保留数据库专属语义,而不是把所有 DDL 转成通用格式,例如:@@ -190,7 +204,7 @@ DBX 会尽量保留数据库专属语义,而不是把所有 DDL 转成通用## 已知边界-- 动态 SQL、存储过程内部行为、应用代码和外部 ETL 不在 Schema 对比范围内+- Schema 对比不验证动态 SQL、例程运行行为、应用代码和外部 ETL 的等价性- 重命名检测是相似度建议,不是确定结论- DDL 格式差异可能产生语义相同但文本不同的结果- 数据对比需要把选定范围读入比较流程,不适合无过滤地处理超大表diff --git a/docs/content/docs/schema-diff.mdx b/docs/content/docs/schema-diff.mdxindex 7506dd7cfb..70184459f1 100644--- a/docs/content/docs/schema-diff.mdx+++ b/docs/content/docs/schema-diff.mdx@@ -85,7 +85,7 @@ Options load dialect-specific defaults. Objects without reliable metadata or syn- Batch mode and table-name patterns- System-object visibility-Filtering controls comparison scope, not permissions. Objects the current account cannot read do not appear.+Filtering controls scope without granting permissions. Incomplete Oracle routine reads retain identified objects and issues; an unlisted object is not proven absent. Other metadata also remains limited by the account's visibility.### Rename Detection@@ -119,6 +119,20 @@ When the target is MySQL, deployment review also offers **Ignore foreign key che<Callout type="info">Run in transaction provides full rollback only when the target database and statements support transactional DDL. MySQL and other databases can implicitly commit DDL.</Callout>+### Oracle Standalone Procedures and Functions++Standalone `PROCEDURE` and `FUNCTION` objects on Oracle and OceanBase Oracle use a dedicated read and deployment path. Both endpoints must use the same product; Oracle-to-OceanBase conversion is not automatic. Packages, types, synonyms, and database links are outside this migration path.++The routine list retains added, modified, removed, and equal objects. Select a row to compare or copy its original source. Incomplete reads and kind conflicts retain the readable text and reason without generating an executable operation. A failed read never establishes absence.++In deployment review, edit each target draft in the existing editor and choose **Validate again**. Automatic adaptation changes only the declaration's target schema and outer delimiters, not schema references in the body. Validation resolves references from the final text against the target catalog and recalculates execution order. New objects use `CREATE` without replacing a competing name. Replacement and deletion also require complete incoming-caller visibility. **Refresh baseline, keep draft** retains drafts when the catalog has changed, so they can be reviewed and validated again.++Automatic dependency analysis currently accepts scalar declarations, `NULL`, returns, assignments, resolvable routine calls, and single-table static `SELECT ... INTO`. Dynamic SQL, loops, exception blocks, and other unsupported syntax produce positioned issues. Correct the draft or remove the object from this selection; original-source viewing, copying, and ordinary source editing remain available.++Execution records acknowledgment and readback separately for each object. Verification requires a terminal request, a matching definition, `VALID` status, and no compilation errors. Warnings remain visible. An acknowledged but `INVALID` object stops later steps and retains compiler coordinates. Correcting it creates a new approval for unfinished steps without replaying completed objects.++Closing review stops only the next dispatch, not the current database request. Reopening the same comparison within the application process restores its drafts and records. For an unknown outcome, choose **Check original request** rather than retrying under a new ID; establish termination before another write. **Preview recovery script** prepares a separately confirmed DDL operation, not a transaction rollback. It rejects intervening target changes. Missing deleted grants or other recovery material leave the available definition copyable but block one-click restoration.+## Dialect SemanticsDBX attempts to preserve database-specific semantics rather than normalizing everything to generic DDL, including:@@ -190,7 +204,7 @@ Delete synchronization is the highest-risk option. If target-local data is allow## Known Boundaries-- Dynamic SQL, procedure behavior, application code, and external ETL are outside schema comparison+- Schema comparison does not establish equivalent dynamic SQL, routine runtime behavior, application code, or external ETL- Rename detection is a similarity suggestion, not a confirmed conclusion- Formatting differences can produce text changes with equivalent semantics- Data compare reads the selected scope and is not suitable for unfiltered huge tablesdiff --git a/docs/images/oracle-routine-deploy-readback.jpg b/docs/images/oracle-routine-deploy-readback.jpgnew file mode 100644index 0000000000..ca4363fe07Binary files /dev/null and b/docs/images/oracle-routine-deploy-readback.jpg differdiff --git a/docs/images/oracle-routine-save-readback.jpg b/docs/images/oracle-routine-save-readback.jpgnew file mode 100644index 0000000000..38510237a1Binary files /dev/null and b/docs/images/oracle-routine-save-readback.jpg differdiff --git a/packages/app-tests/productionGuardEntrypoints.test.ts b/packages/app-tests/productionGuardEntrypoints.test.tsindex cbcc25a88a..8453c258dd 100644--- a/packages/app-tests/productionGuardEntrypoints.test.ts+++ b/packages/app-tests/productionGuardEntrypoints.test.ts@@ -48,21 +48,9 @@ test("secondary write entrypoints use the shared production SQL guard", () => {executor: "api.executeQuery",sourceKey: "production.sourceSidebar",},- {- path: "apps/desktop/src/App.vue",- executor: "executeObjectSourceSave",- sourceKey: "production.sourceObjectSource",- },- {- path: "apps/desktop/src/components/objects/ObjectSourceDialog.vue",- executor: "executeObjectSourceSave",- sourceKey: "production.sourceObjectSource",- },- {- path: "apps/desktop/src/components/objects/ObjectBrowser.vue",- executor: "executeObjectSourceSave",- sourceKey: "production.sourceObjectSource",- },+ // Source saves select a prepared executor by engine. Their confirmation and+ // dispatch behavior is exercised by objectSourceTabSave.spec.ts and the real+ // ObjectSourceDialog/ObjectBrowser component tests, not a callee-name match.{path: "apps/desktop/src/components/objects/ObjectBrowser.vue",executor: "api.executeQuery",