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): support controlled package spec and body migration
efeiredb606123add4
diff --git a/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java b/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.javaindex a8681117e1..761ca63821 100644--- a/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java+++ b/agents/common/src/main/java/com/dbx/agent/DatabaseAgent.java@@ -104,6 +104,10 @@ public interface DatabaseAgent {throw new UnsupportedOperationException("Object source is not supported");}+ default ObjectSource getObjectSourceWithOrigin(String schema, String name, String objectType) {+ return getObjectSource(schema, name, objectType);+ }+default String getTableDdl(String schema, String table) {List<IndexInfo> indexes;try {diff --git a/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java b/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.javaindex f49ede4a18..36603560e6 100644--- a/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java+++ b/agents/common/src/main/java/com/dbx/agent/JsonRpcServer.java@@ -265,11 +265,21 @@ public final class JsonRpcServer {}if (AgentProtocol.METHOD_GET_OBJECT_SOURCE.equals(method)) {switchCatalog(params);- return agent.getObjectSource(- params.get("schema").getAsString(),- params.get("name").getAsString(),- params.get("object_type").getAsString()- );+ boolean includeOrigin = params.has("include_source_origin") && params.get("include_source_origin").getAsBoolean();+ String schema = params.get("schema").getAsString();+ String name = params.get("name").getAsString();+ String objectType = params.get("object_type").getAsString();+ ObjectSource source = includeOrigin+ ? agent.getObjectSourceWithOrigin(schema, name, objectType)+ : agent.getObjectSource(schema, name, objectType);+ if (includeOrigin) {+ JsonObject result = gson.toJsonTree(source).getAsJsonObject();+ if (source.getSourceOrigin() != null) {+ result.addProperty("source_origin", source.getSourceOrigin());+ }+ return result;+ }+ return source;}if (AgentProtocol.METHOD_GET_TABLE_DDL.equals(method)) {switchCatalog(params);diff --git a/agents/common/src/main/java/com/dbx/agent/ObjectSource.java b/agents/common/src/main/java/com/dbx/agent/ObjectSource.javaindex 13e9d2590b..3aaba3a05d 100644--- a/agents/common/src/main/java/com/dbx/agent/ObjectSource.java+++ b/agents/common/src/main/java/com/dbx/agent/ObjectSource.java@@ -8,6 +8,7 @@ public final class ObjectSource {private String schema;private String source;private boolean editable;+ private transient String sourceOrigin;public ObjectSource() {this("", "", null, "", true);@@ -49,6 +50,14 @@ public final class ObjectSource {return editable;}+ public String getSourceOrigin() {+ return sourceOrigin;+ }++ public void setSourceOrigin(String sourceOrigin) {+ this.sourceOrigin = sourceOrigin;+ }+public void setName(String name) {this.name = name;}diff --git a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.javaindex 07d04757ac..a4c8f92d7d 100644--- a/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java+++ b/agents/drivers/oceanbase-oracle/src/main/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgent.java@@ -1318,12 +1318,21 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {@Overridepublic ObjectSource getObjectSource(String schema, String name, String objectType) {+ return getObjectSource(schema, name, objectType, false);+ }++ @Override+ public ObjectSource getObjectSourceWithOrigin(String schema, String name, String objectType) {+ return getObjectSource(schema, name, objectType, true);+ }++ private ObjectSource getObjectSource(String schema, String name, String objectType, boolean exactMetadataKind) {return unchecked(() -> {String owner = normalizeSchema(schema);String objectName = normalizeObjectName(name);String normalizedType = normalizeObjectSourceType(objectType);if (prefersDictionarySource(normalizedType)) {- return getDictionaryFirstObjectSource(owner, objectName, normalizedType);+ return getDictionaryFirstObjectSource(owner, objectName, normalizedType, exactMetadataKind);}String source;SQLException metadataError = null;@@ -1354,8 +1363,9 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {});}- private ObjectSource getDictionaryFirstObjectSource(String owner, String name, String objectType) throws SQLException {+ private ObjectSource getDictionaryFirstObjectSource(String owner, String name, String objectType, boolean exactMetadataKind) throws SQLException {String source;+ String origin = "oceanbase-dictionary";SQLException dictionaryError = null;try {source = queryDictionarySource(owner, name, objectType);@@ -1366,7 +1376,9 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {if (source == null || source.trim().isEmpty()) {try {- source = queryDbmsMetadataSource(owner, name, objectType);+ source = queryDbmsMetadataSource(owner, name,+ exactMetadataKind && "PACKAGE".equals(objectType) ? "PACKAGE_SPEC" : objectType);+ origin = "oracle-metadata";} catch (SQLException metadataError) {if (dictionaryError != null) {dictionaryError.addSuppressed(metadataError);@@ -1381,7 +1393,9 @@ public final class OceanBaseOracleAgent extends ConfiguredJdbcAgent {}return new ObjectSource(name, objectType, owner, source, false);}- return new ObjectSource(name, objectType, owner, source == null ? "" : source);+ ObjectSource result = new ObjectSource(name, objectType, owner, source == null ? "" : source);+ result.setSourceOrigin(origin);+ return result;}private String queryDbmsMetadataSource(String owner, String name, String objectType) throws SQLException {diff --git a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.javaindex 45b0915d7c..c19bd3708c 100644--- a/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java+++ b/agents/drivers/oceanbase-oracle/src/test/java/com/dbx/agent/oceanbaseoracle/OceanBaseOracleAgentTest.java@@ -11,6 +11,9 @@ import com.dbx.agent.ExecuteQueryOptions;import com.dbx.agent.MetadataListConstraints;import com.dbx.agent.ObjectInfo;import com.dbx.agent.ObjectSource;+import com.dbx.agent.JsonRpcServer;+import com.google.gson.JsonObject;+import com.google.gson.JsonParser;import com.dbx.agent.QueryPageOptions;import com.dbx.agent.QueryPageResult;import com.dbx.agent.QueryResult;@@ -1276,6 +1279,50 @@ class OceanBaseOracleAgentTest {Assertions.assertEquals(List.of("APP", "P1", "PROCEDURE", "PROCEDURE", "P1", "APP"), params);}+ @Test+ void strictPackageSourceReportsActualFallbackOriginWithoutChangingOrdinaryResponses() throws Exception {+ Method request = JsonRpcServer.class.getDeclaredMethod("handleRequest", String.class);+ request.setAccessible(true);+ for (boolean fallback : new boolean[]{false, true}) {+ for (boolean strict : new boolean[]{false, true}) {+ OceanBaseOracleAgent agent = new OceanBaseOracleAgent();+ ResultSet rows = resultSet(new String[]{fallback ? "DDL" : "TEXT"}, new Object[][]{+ {fallback ? "CREATE OR REPLACE PACKAGE BODY APP.P AS END;" : "PACKAGE BODY P AS END;"}+ });+ TestSupport.setPrivateConnection(agent, fallback+ ? objectSourceFallbackConnection(new ArrayList<>(), new ArrayList<>(), rows)+ : objectSourceConnection(new ArrayList<>(), new ArrayList<>(), rows));+ String response = (String) request.invoke(new JsonRpcServer(agent),+ "{\"id\":1,\"method\":\"get_object_source\",\"params\":{\"schema\":\"APP\",\"name\":\"P\",\"object_type\":\"PACKAGE_BODY\",\"include_source_origin\":" + strict + "}}");+ JsonObject envelope = JsonParser.parseString(response).getAsJsonObject();+ Assertions.assertFalse(envelope.has("error"), response);+ JsonObject result = envelope.getAsJsonObject("result");+ if (strict) {+ Assertions.assertTrue(result.has("source_origin"), response);+ Assertions.assertEquals(fallback ? "oracle-metadata" : "oceanbase-dictionary", result.get("source_origin").getAsString());+ } else {+ Assertions.assertFalse(result.has("source_origin"), response);+ }+ }+ }+ }++ @Test+ void strictSpecificationMetadataFallbackRequestsOnlyTheSpecification() throws Exception {+ Method request = JsonRpcServer.class.getDeclaredMethod("handleRequest", String.class);+ request.setAccessible(true);+ for (boolean strict : new boolean[]{false, true}) {+ List<String> params = new ArrayList<>();+ OceanBaseOracleAgent agent = new OceanBaseOracleAgent();+ TestSupport.setPrivateConnection(agent, objectSourceFallbackConnection(new ArrayList<>(), params,+ resultSet(new String[]{"DDL"}, new Object[][]{{"CREATE OR REPLACE PACKAGE APP.P AS END;"}})));+ String response = (String) request.invoke(new JsonRpcServer(agent),+ "{\"id\":1,\"method\":\"get_object_source\",\"params\":{\"schema\":\"APP\",\"name\":\"P\",\"object_type\":\"PACKAGE\",\"include_source_origin\":" + strict + "}}");+ Assertions.assertFalse(JsonParser.parseString(response).getAsJsonObject().has("error"), response);+ Assertions.assertEquals(List.of("APP", "P", "PACKAGE", strict ? "PACKAGE_SPEC" : "PACKAGE", "P", "APP"), params);+ }+ }+@Testvoid synonymSourcePreservesOwnersQuotedNamesAndRemoteLinkDomains() {for (String owner : List.of("Mixed.Owner", "PUBLIC")) {diff --git a/agents/drivers/oracle-go/main.go b/agents/drivers/oracle-go/main.goindex c01aefa66d..e21ba9aba9 100644--- a/agents/drivers/oracle-go/main.go+++ b/agents/drivers/oracle-go/main.go@@ -992,6 +992,12 @@ func (s *server) dispatch(method string, params map[string]json.RawMessage) (anyname := stringParam(params, "name")objectType := stringParam(params, "object_type")source, err := s.getObjectSource(schema, name, objectType)+ if err == nil && boolParam(params, "include_source_origin") {+ switch strings.ToUpper(objectType) {+ case "PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY":+ source["source_origin"] = "oracle-dictionary"+ }+ }return source, false, errcase "get_table_ddl":schema := stringParam(params, "schema")@@ -3444,8 +3450,12 @@ func (s *server) getObjectSource(schema, name, objectType string) (map[string]an// Unquoted Oracle identifiers are stored uppercase; quoted mixed-case names must stay exact.// Try caller-provided identity first, then uppercase fallback (same pattern as column metadata).+ dictionaryType := upperType+ if dictionaryType == "PACKAGE_BODY" {+ dictionaryType = "PACKAGE BODY"+ }for _, candidate := range oracleObjectIdentityNameCandidates(name) {- source, found, queryErr := s.loadObjectSourceText(schema, candidate, upperType)+ source, found, queryErr := s.loadObjectSourceText(schema, candidate, dictionaryType)if queryErr != nil {return nil, queryErr}diff --git a/agents/drivers/oracle-go/main_test.go b/agents/drivers/oracle-go/main_test.goindex aabfa7ed7b..b1d2ba601d 100644--- a/agents/drivers/oracle-go/main_test.go+++ b/agents/drivers/oracle-go/main_test.go@@ -3668,6 +3668,39 @@ func TestGetObjectSourceAggregatesProcedureSourceInOracle(t *testing.T) {}}+func TestStrictPackageSourceReportsDictionaryOriginAndUsesExactDictionaryKind(t *testing.T) {+ for _, kind := range []string{"PACKAGE", "PACKAGE_BODY"} {+ for _, strict := range []bool{false, true} {+ t.Run(fmt.Sprintf("%s/strict=%t", kind, strict), func(t *testing.T) {+ dictionaryKind := strings.ReplaceAll(kind, "_", " ")+ source := dictionaryKind + " \"Pkg.With.Dot\" AS END;"+ db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{+ queryContains: "DBMS_XMLGEN.CONVERT",+ args: []driver.Value{"DBX_TEST", "Pkg.With.Dot", dictionaryKind},+ rows: [][]driver.Value{{source}},+ }})+ s := newServer()+ s.db = db+ response, shutdown := s.handleLine(fmt.Sprintf(`{"id":1,"method":"get_object_source","params":{"schema":"DBX_TEST","name":"Pkg.With.Dot","object_type":%q,"include_source_origin":%t}}`, kind, strict))+ if shutdown || response.Error != nil {+ t.Fatalf("unexpected source response: %#v", response)+ }+ result := response.Result.(map[string]any)+ if result["source"] != source || result["object_type"] != kind {+ t.Fatalf("wrong exact source: %#v", result)+ }+ origin, exists := result["source_origin"]+ if exists != strict || (strict && origin != "oracle-dictionary") {+ t.Fatalf("wrong source provenance: %#v", result)+ }+ if scripted.next != len(scripted.steps) {+ t.Fatalf("unexpected queries: %d", scripted.next)+ }+ })+ }+ }+}+func TestGetObjectSourceReturnsEmptyWhenAggregatedSourceIsNull(t *testing.T) {db, scripted := openOracleViewSourceTestDB(t, []oracleViewSourceQueryStep{{diff --git a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vueindex 05fdaf61d6..419406440a 100644--- a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue+++ b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue@@ -19,6 +19,7 @@ import {reconcileSchemaDiffRoutineMappings,reconcileSchemaDiffSelectedRoutines,schemaDiffRoutineKey,+ schemaDiffRoutineKeyFromFunction,SCHEMA_DIFF_UNRESTRICTED_ROUTINE_LIMIT,type SchemaDiffRoutineMatch,} from "@/lib/schema/schemaDiffRoutine";@@ -31,7 +32,7 @@ import * as api from "@/lib/backend/api";import { isSchemaAware } from "@/lib/database/databaseCapabilities";import { fetchNamespaceOptionsForConnection } from "@/composables/useDatabaseOptions";import { ArrowLeftRight, GitCompareArrows, Save, FolderOpen, Settings, Trash2, X } from "@lucide/vue";-import type { SchemaDiffConfig, SchemaDiffCompareOptions, FieldMappingEntry, SchemaDiffTableMapping, SchemaDiffRoutineMapping } from "@/types/schemaDiff";+import type { SchemaDiffConfig, SchemaDiffCompareOptions, FieldMappingEntry, SchemaDiffTableMapping, SchemaDiffRoutineMapping, OracleRoutineKind, OracleRoutineIdentity } from "@/types/schemaDiff";import type { DatabaseType } from "@/types/database";const { t } = useI18n();@@ -76,6 +77,7 @@ const emit = defineEmits<{(e: "deleteHistoryConfig", configId: string): void;(e: "update:selectedTables", value?: string[]): void;(e: "update:selectedRoutines", value?: string[]): void;+ (e: "update:routineSelection", value: { objectKinds: OracleRoutineKind[]; selectedObjects?: Pick<OracleRoutineIdentity, "name" | "kind">[] }): void;(e: "update:compareScope", value: { tables?: boolean; views?: boolean; functions?: boolean }): void;}>();@@ -269,7 +271,10 @@ const tablesCompareEnabled = computed(() => !!props.options.tables);const routinesCompareEnabled = computed(() => !!props.options.functions);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);+const availableRoutineKinds = computed(() => schemaDiffRoutineObjectTypesIntersection(sourceRoutineType.value, targetRoutineType.value, ["PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY"]));+const routineKinds = computed(() => props.options.routineObjectKinds ?? schemaDiffRoutineObjectTypesIntersection(sourceRoutineType.value, targetRoutineType.value));+const typedRoutines = computed(() => props.options.routineObjectKinds !== undefined);+const canEnableRoutinesCompare = computed(() => availableRoutineKinds.value.length > 0);/** User preference AND supported pair — drives compare/canCompare/Switch display. */const effectiveRoutinesEnabled = computed(() => routinesCompareEnabled.value && canEnableRoutinesCompare.value);@@ -298,6 +303,57 @@ const targetRoutineListLoaded = ref(false);const restrictRoutines = ref(false);const localSelectedRoutines = ref<string[]>([]);const loadingRoutines = ref(false);+type ProgramSelection = Pick<OracleRoutineIdentity, "name" | "kind">;+const routineIdentities = { source: ref<Record<string, ProgramSelection>>({}), target: ref<Record<string, ProgramSelection>>({}) };+const routineRequests = { source: 0, target: 0 };+for (const side of ["source", "target"] as const) {+ watch(+ () => [side === "source" ? props.sourceConnectionId : props.targetConnectionId, side === "source" ? props.sourceDatabase : props.targetDatabase, side === "source" ? props.sourceSchema : props.targetSchema, JSON.stringify(props.options.routineObjectKinds)],+ () => {+ routineRequests[side]++;+ routineIdentities[side].value = {};+ if (side === "source") sourceRoutineList.value = [];+ else {+ targetRoutineList.value = [];+ targetRoutineListLoaded.value = false;+ }+ },+ { flush: "sync" },+ );+}+const exactRoutineKey = (identity: ProgramSelection) => schemaDiffRoutineKeyFromFunction({ name: identity.name, function_type: identity.kind, arguments: "" }, true);+const selectedRoutineKeys = computed(() => (typedRoutines.value ? props.options.selectedRoutineObjects?.map(exactRoutineKey) : props.selectedRoutines));+const routineLabels = computed<Record<string, string>>(() => {+ if (!typedRoutines.value) return {};+ const identities = { ...routineIdentities.target.value, ...routineIdentities.source.value };+ for (const identity of props.options.selectedRoutineObjects ?? []) identities[exactRoutineKey(identity)] = identity;+ return Object.fromEntries(Object.entries(identities).map(([key, identity]) => [key, `${identity.kind.replaceAll("_", " ")} ${identity.name}`]));+});++function emitRoutineSelection(keys: string[] | undefined) {+ if (!typedRoutines.value) {+ emit("update:selectedRoutines", keys);+ return;+ }+ emit("update:routineSelection", {+ objectKinds: [...routineKinds.value],+ selectedObjects: keys?.flatMap((key) => {+ const identity = routineIdentities.source.value[key];+ return identity ? [{ ...identity }] : [];+ }),+ });+}++function toggleRoutineKind(kind: OracleRoutineKind, enabled: boolean) {+ const kinds = availableRoutineKinds.value.filter((candidate) => (candidate === kind ? enabled : routineKinds.value.includes(candidate)));+ const selectedObjects = restrictRoutines.value+ ? localSelectedRoutines.value.flatMap((key) => {+ const identity = routineIdentities.source.value[key];+ return identity && kinds.includes(identity.kind) ? [{ ...identity }] : [];+ })+ : undefined;+ emit("update:routineSelection", { objectKinds: kinds, selectedObjects });+}const canConfigureRoutineSelection = computed(() => isTableIdentityReady("source") && supportsSchemaDiffRoutines(sourceRoutineType.value));const activeRoutineMappings = computed(() => identitySchemaDiffRoutineMappings(props.options?.routineMappings ?? []));@@ -316,7 +372,7 @@ function reconcileRoutineMappings(selectedRoutines: string[], targetRoutines = t}watch(- () => props.selectedRoutines,+ () => selectedRoutineKeys.value,(value) => {restrictRoutines.value = Array.isArray(value);localSelectedRoutines.value = value && Array.isArray(value) ? [...value] : [];@@ -336,7 +392,7 @@ watch(function handleToggleRestrictRoutines(enabled: boolean) {restrictRoutines.value = enabled;- emit("update:selectedRoutines", enabled ? [...localSelectedRoutines.value] : undefined);+ emitRoutineSelection(enabled ? [...localSelectedRoutines.value] : undefined);if (!enabled) emitRoutineMappings([]);else reconcileRoutineMappings(localSelectedRoutines.value);}@@ -344,7 +400,7 @@ function handleToggleRestrictRoutines(enabled: boolean) {function handleUpdateSelectedRoutines(value: string[]) {localSelectedRoutines.value = value;if (!restrictRoutines.value) return;- emit("update:selectedRoutines", [...value]);+ emitRoutineSelection([...value]);reconcileRoutineMappings(value);}@@ -353,20 +409,27 @@ function handleRemoveSelectedRoutine(sourceRoutine: string) {}function clearUnavailableRoutineSelection() {+ routineRequests.source++;+ routineRequests.target++;+ routineIdentities.source.value = {};+ routineIdentities.target.value = {};sourceRoutineList.value = [];targetRoutineList.value = [];targetRoutineListLoaded.value = false;- if (props.selectedRoutines === undefined && !restrictRoutines.value && localSelectedRoutines.value.length === 0) {+ if (selectedRoutineKeys.value === undefined && !restrictRoutines.value && localSelectedRoutines.value.length === 0) {emitRoutineMappings([]);return;}restrictRoutines.value = false;localSelectedRoutines.value = [];- emit("update:selectedRoutines", undefined);+ emitRoutineSelection(undefined);emitRoutineMappings([]);}async function loadRoutineList(side: "source" | "target") {+ const request = ++routineRequests[side];+ const exactKinds = typedRoutines.value;+ const requestedKinds = exactKinds ? [...routineKinds.value] : undefined;const connectionId = side === "source" ? props.sourceConnectionId : props.targetConnectionId;const database = side === "source" ? props.sourceDatabase : props.targetDatabase;const schema = side === "source" ? props.sourceSchema : props.targetSchema;@@ -379,23 +442,32 @@ async function loadRoutineList(side: "source" | "target") {}return;}- const isCurrent = metadataRequestIsCurrent(side);+ const endpointIsCurrent = metadataRequestIsCurrent(side);+ const isCurrent = () => endpointIsCurrent() && request === routineRequests[side] && JSON.stringify(requestedKinds) === JSON.stringify(typedRoutines.value ? routineKinds.value : undefined);try {loadingRoutines.value = true;await store.ensureConnected(connectionId);if (!isCurrent()) return;// Names/signatures only — avoid listFunctions N+1 source fetch on the config step.- const kinds = schemaDiffRoutineObjectTypes(dbType as DatabaseType);+ const kinds = schemaDiffRoutineObjectTypes(dbType as DatabaseType, requestedKinds);const objects = kinds.length === 0 ? [] : await api.listObjects(connectionId, database, schema, kinds);if (!isCurrent()) return;- const keys = objects.map((object) => schemaDiffRoutineKey(object.name, object.signature ?? ""));+ const identities: Record<string, ProgramSelection> = {};+ const keys = objects.map((object) => {+ const kind = (object.object_type ?? "").replaceAll(" ", "_").toUpperCase() as OracleRoutineKind;+ if (exactKinds && !kinds.includes(kind)) throw new Error("Program listing returned an unexpected object kind");+ const key = exactKinds ? exactRoutineKey({ name: object.name, kind }) : schemaDiffRoutineKey(object.name, object.signature ?? "");+ if (kinds.includes(kind)) identities[key] = { name: object.name, kind };+ return key;+ });+ routineIdentities[side].value = identities;if (side === "source") {sourceRoutineList.value = keys;if (restrictRoutines.value) {const next = reconcileSchemaDiffSelectedRoutines(localSelectedRoutines.value, keys);if (next.length !== localSelectedRoutines.value.length || next.some((key, index) => key !== localSelectedRoutines.value[index])) {localSelectedRoutines.value = next;- emit("update:selectedRoutines", [...next]);+ emitRoutineSelection([...next]);}}} else {@@ -416,7 +488,7 @@ async function loadRoutineList(side: "source" | "target") {}watch(- () => [restrictRoutines.value, effectiveRoutinesEnabled.value, props.sourceConnectionId, props.sourceDatabase, props.sourceSchema, sourceRoutineType.value] as const,+ () => [restrictRoutines.value, effectiveRoutinesEnabled.value, props.sourceConnectionId, props.sourceDatabase, props.sourceSchema, sourceRoutineType.value, JSON.stringify(props.options.routineObjectKinds)] as const,([restrictEnabled, routinesEnabled]) => {if (!canConfigureRoutineSelection.value) {clearUnavailableRoutineSelection();@@ -429,7 +501,7 @@ watch();watch(- () => [restrictRoutines.value, localSelectedRoutines.value.length, props.targetConnectionId, props.targetDatabase, props.targetSchema, targetRoutineType.value] as const,+ () => [restrictRoutines.value, localSelectedRoutines.value.length, props.targetConnectionId, props.targetDatabase, props.targetSchema, targetRoutineType.value, JSON.stringify(props.options.routineObjectKinds)] as const,([enabled, selectedCount]) => {if (!enabled || selectedCount === 0 || !isTableIdentityReady("target") || !supportsSchemaDiffRoutines(targetRoutineType.value)) {if (!enabled) {@@ -446,7 +518,7 @@ watch(watch(() => ({source: [props.sourceConnectionId, props.sourceDatabase, props.sourceSchema] as const,- selectedRoutines: props.selectedRoutines,+ selectedRoutines: selectedRoutineKeys.value,}),(current, previous) => {if (!isTableIdentityReady("source") || !supportsSchemaDiffRoutines(sourceRoutineType.value)) {@@ -474,7 +546,7 @@ function handleRoutinesCompareEnabled(enabled: boolean) {const unrestrictedRoutineLoadTooLarge = computed(() => {if (!effectiveRoutinesEnabled.value || restrictRoutines.value) return false;- return isSchemaDiffUnrestrictedRoutineLoadTooLarge(sourceRoutineList.value.length, props.selectedRoutines);+ return isSchemaDiffUnrestrictedRoutineLoadTooLarge(sourceRoutineList.value.length, selectedRoutineKeys.value);});const canCompare = computed(() => {@@ -483,7 +555,7 @@ const canCompare = computed(() => {if (!tablesEnabled && !routinesEnabled) return false;if (unrestrictedRoutineLoadTooLarge.value) return false;const hasSelectedTables = !tablesEnabled || props.selectedTables === undefined || props.selectedTables.length > 0;- const hasSelectedRoutines = !routinesEnabled || props.selectedRoutines === undefined || props.selectedRoutines.length > 0;+ const hasSelectedRoutines = !routinesEnabled || (routineKinds.value.length > 0 && (selectedRoutineKeys.value === undefined || selectedRoutineKeys.value.length > 0));// Unmapped source tables are not a blocker: they flow through the comparison as// source-only tables (CREATE TABLE in the target), matching the pre-mapping behavior.const hasValidTableMappings = !tablesEnabled || !restrictTables.value || localSelectedTables.value.length === 0 || isTableIdentityReady("target");@@ -948,7 +1020,13 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st<div class="space-y-1.5 border-t border-border/60 pt-3"><div class="flex items-center justify-between gap-2"><div class="flex min-w-0 items-center gap-2">- <Switch size="sm" :model-value="effectiveRoutinesEnabled" :disabled="!canEnableRoutinesCompare" :aria-label="t('diff.compareRoutinesSwitch')" @update:model-value="handleRoutinesCompareEnabled(Boolean($event))" />+ <Switch+ size="sm"+ :model-value="typedRoutines ? routinesCompareEnabled : effectiveRoutinesEnabled"+ :disabled="!canEnableRoutinesCompare && !(typedRoutines && routinesCompareEnabled)"+ :aria-label="t('diff.compareRoutinesSwitch')"+ @update:model-value="handleRoutinesCompareEnabled(Boolean($event))"+ /><Label class="text-xs font-medium" :class="!canEnableRoutinesCompare ? 'text-muted-foreground' : ''">{{ t("diff.routineSelection") }}</Label></div><Button v-if="effectiveRoutinesEnabled && (restrictRoutines || canConfigureRoutineSelection)" variant="ghost" size="sm" class="h-6 px-2 text-xs" :disabled="loadingRoutines" @click="handleToggleRestrictRoutines(!restrictRoutines)">@@ -962,6 +1040,12 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st{{ t("diff.routineCompareDisabled") }}</div><template v-else>+ <div v-if="availableRoutineKinds.includes('PACKAGE')" class="flex flex-wrap gap-x-4 gap-y-2">+ <label v-for="kind in availableRoutineKinds" :key="kind" class="flex items-center gap-2 text-xs">+ <input type="checkbox" class="accent-primary" :data-program-kind="kind" :checked="routineKinds.includes(kind)" :disabled="loadingRoutines" @change="toggleRoutineKind(kind, ($event.target as HTMLInputElement).checked)" />+ {{ kind.replaceAll("_", " ") }}+ </label>+ </div><div v-if="!restrictRoutines" class="text-[11px] text-muted-foreground">{{ !isTableIdentityReady("source") ? t("diff.routineSelectionNeedSource") : t("diff.routineSelectionUnrestricted") }}</div>@@ -974,6 +1058,8 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st:model-value="localSelectedRoutines"@update:model-value="handleUpdateSelectedRoutines":tables="sourceRoutineList"+ :disabled="loadingRoutines"+ :labels="typedRoutines ? routineLabels : undefined":title="t('diff.sourceRoutines')":search-placeholder="t('diff.searchSourceRoutines')":empty-text="t('diff.noRoutines')"@@ -1001,9 +1087,9 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st</thead><tbody><tr v-for="match in routineMatches" :key="match.sourceRoutine" class="border-b last:border-b-0">- <td class="max-w-[220px] truncate px-2 py-1.5 font-mono" :title="match.sourceRoutine">{{ match.sourceRoutine }}</td>- <td class="max-w-[220px] truncate px-2 py-1.5 font-mono" :title="match.targetRoutine || undefined">- <span v-if="match.targetRoutine">{{ match.targetRoutine }}</span>+ <td class="max-w-[220px] truncate px-2 py-1.5 font-mono" :title="routineLabels[match.sourceRoutine] ?? match.sourceRoutine">{{ routineLabels[match.sourceRoutine] ?? match.sourceRoutine }}</td>+ <td class="max-w-[220px] truncate px-2 py-1.5 font-mono" :title="match.targetRoutine ? (routineLabels[match.targetRoutine] ?? match.targetRoutine) : undefined">+ <span v-if="match.targetRoutine">{{ routineLabels[match.targetRoutine] ?? match.targetRoutine }}</span><span v-else class="text-muted-foreground">—</span></td><td class="px-2 py-1.5" :class="matchStatusClass(match.kind)">diff --git a/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue b/apps/desktop/src/components/diff/SchemaDiffDeployStep.vueindex b5e6676a9c..befa6e069b 100644--- a/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue+++ b/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue@@ -9,10 +9,10 @@ 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 { oracleRoutineActiveStep, oracleRoutineDeploymentEntries, 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 { OracleRoutineOperation, OracleRoutinePlanDraft } from "@/types/schemaDiff";import type { DatabaseType } from "@/types/database";import {schemaDiffObjectSelectionState,@@ -61,6 +61,7 @@ const props = defineProps<{continueOnError?: boolean;databaseType?: DatabaseType;routineDeployment?: OracleRoutineDeployment | null;+ packageTransfer?: boolean;}>();const emit = defineEmits<{@@ -75,6 +76,9 @@ const emit = defineEmits<{"refresh-routines": [];"observe-routine": [operationId: string];"recover-routine": [operationId: string];+ "include-package-companion": [objectId: string, source: "source" | "target"];+ "update-package-options": [objectId: string, options: Pick<OracleRoutinePlanDraft, "packageBodySource" | "packageContract" | "confirmPackagePair">];+ "review-package-target": [objectId: string];}>();const editorContainer = ref<HTMLDivElement>();@@ -85,7 +89,39 @@ 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 routineEntries = computed(() => (props.routineDeployment ? oracleRoutineDeploymentEntries(props.routineDeployment) : []));+const routineIdentity = computed(() => routineStep.value?.identity ?? routineDraft.value?.identity);+const routineOriginals = computed(() => {+ if (routineStep.value) return { source: routineStep.value.sourceOriginal, target: routineStep.value.targetOriginal };+ const draft = routineDraft.value;+ const source = props.routineDeployment?.source;+ const target = props.routineDeployment?.target;+ return {+ source: source?.objects.find((object) => object.version.identity.owner === source.endpoint.schema && object.version.identity.name === (draft?.sourceName ?? draft?.identity.name) && object.version.identity.kind === draft?.identity.kind)?.source,+ target: target?.objects.find((object) => draft && routineIdentityKey(object.version.identity) === routineIdentityKey(draft.identity))?.source,+ };+});+const packageDraft = computed(() => (!props.routineDeployment?.recoveryPlan && !editorReadOnly.value && (routineDraft.value?.identity.kind === "PACKAGE" || routineDraft.value?.identity.kind === "PACKAGE_BODY") ? routineDraft.value : undefined));+const packagePeer = computed(() =>+ props.routineDeployment?.drafts.find(+ (draft) => draft.included && draft.identity.owner === packageDraft.value?.identity.owner && draft.identity.name === packageDraft.value?.identity.name && draft.identity.kind !== packageDraft.value?.identity.kind && (draft.identity.kind === "PACKAGE" || draft.identity.kind === "PACKAGE_BODY"),+ ),+);+function packageMaterial(source: "source" | "target", kind: "PACKAGE" | "PACKAGE_BODY") {+ const snapshot = props.routineDeployment?.[source];+ const name = source === "source" ? (packageDraft.value?.sourceName ?? packageDraft.value?.identity.name) : packageDraft.value?.identity.name;+ return snapshot?.objects.find((object) => object.version.identity.owner === snapshot.endpoint.schema && object.version.identity.name === name && object.version.identity.kind === kind && object.sourceComplete && object.source);+}const routineRecord = computed(() => (props.routineDeployment?.recoveryPlan ? routineStep.value?.operation : routineDraft.value?.operation));+const routineCompanion = computed(() => routineRecord.value?.readback?.packageCompanion);+const routineCompanionStatus = computed(() => {+ const companion = routineCompanion.value;+ if (!companion) return "";+ if (companion.exists === false) return t("objects.routineReadbackMissing");+ if (companion.state === "invalid") return t("objects.invalid");+ if (companion.issues.length || (companion.state !== "present" && companion.state !== "verified")) return t("diff.routineUnverified");+ return companion.version?.status ?? t("diff.routineUnverified");+});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;@@ -118,7 +154,7 @@ function compilerOffset(line: number, column: number): number | undefined {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.+ // ALL_ERRORS positions start at the stored program 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);@@ -176,6 +212,7 @@ async function handleSelectObject(obj: SchemaDiffObject) {// Filter top-level selected objects (exclude children and none)const topLevelObjects = computed(() => {+ if (props.routineDeployment) return routineEntries.value.map((entry): SchemaDiffObject => ({ id: entry.objectId, name: entry.identity.name, routineType: entry.identity.kind, objectKind: "function", operationType: entry.action === "replace" ? "modify" : entry.action, selected: true }));const operationOrder: Record<DiffOperationType, number> = { create: 0, modify: 1, delete: 2, none: 3 };return props.selectedObjects.filter((o) => {@@ -186,10 +223,10 @@ const topLevelObjects = computed(() => {});const operationCounts = computed(() => {- return summarizeSchemaDiffOperations(props.selectedObjects);+ return summarizeSchemaDiffOperations(props.routineDeployment ? topLevelObjects.value : props.selectedObjects);});-const selectedObjectCount = computed(() => selectedSchemaDiffObjects(props.selectedObjects).length);+const selectedObjectCount = computed(() => (props.routineDeployment ? topLevelObjects.value.length : selectedSchemaDiffObjects(props.selectedObjects).length));const compatibilityWarningCount = computed(() => props.compatibilityWarnings?.length ?? 0);const reviewAlert = computed(() => schemaDiffReviewAlert(props.destructiveStatementCount ?? 0, compatibilityWarningCount.value));@@ -220,6 +257,7 @@ const operationColors: Record<DiffOperationType, string> = {};// Initialize CodeMirror editor+let syncingEditorSql = false;async function initEditor() {if (!editorContainer.value) return;@@ -250,7 +288,7 @@ async function initEditor() {fontComp.of(fontExt),readOnlyCompartment.of(EditorState.readOnly.of(editorReadOnly.value)),EditorView.updateListener.of((update: any) => {- if (update.docChanged) {+ if (update.docChanged && !syncingEditorSql) {emit("update:deploySql", update.state.doc.toString());}}),@@ -266,9 +304,14 @@ watch(() => effectiveSql.value,(newVal) => {if (editorView.value && editorView.value.state.doc.toString() !== newVal) {- editorView.value.dispatch({- changes: { from: 0, to: editorView.value.state.doc.length, insert: newVal },- });+ syncingEditorSql = true;+ try {+ editorView.value.dispatch({+ changes: { from: 0, to: editorView.value.state.doc.length, insert: newVal },+ });+ } finally {+ syncingEditorSql = false;+ }}},);@@ -394,7 +437,7 @@ function getObjectIconColor(kind: DiffObjectKind): string {<!-- Header --><div class="flex items-center justify-between px-3 py-2 border-b shrink-0"><div class="flex items-center gap-2">- <Button variant="ghost" size="sm" class="h-7 px-2 text-xs gap-1" @click="$emit('back')">+ <Button v-if="!packageTransfer" variant="ghost" size="sm" class="h-7 px-2 text-xs gap-1" @click="$emit('back')"><ArrowLeft class="w-3.5 h-3.5" />{{ t("diff.backToResult") }}</Button>@@ -449,11 +492,12 @@ function getObjectIconColor(kind: DiffObjectKind): string {<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>+ <span v-if="obj.routineType === 'PACKAGE' || obj.routineType === 'PACKAGE_BODY'" class="text-muted-foreground">{{ obj.routineType.replaceAll("_", " ") }}</span><span v-if="obj.children?.length" class="text-[10px] text-muted-foreground shrink-0">{{ schemaDiffSelectionTargets(obj).filter((child) => child.selected).length }}/{{ schemaDiffSelectionTargets(obj).length }}</span><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>+ <span v-if="routineDeployment" class="basis-full pl-5 text-xs text-muted-foreground">{{ routineStatus(routineEntries.find((entry) => entry.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") }}@@ -463,23 +507,67 @@ function getObjectIconColor(kind: DiffObjectKind): string {<Pane size="70" min-size="40"><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 v-if="routineDeployment" class="max-h-[50%] shrink-0 space-y-2 overflow-y-auto 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 v-if="routineIdentity" class="break-all font-mono">{{ routineIdentity.owner }}.{{ routineIdentity.name }} · {{ routineIdentity.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="packageDraft" class="space-y-2">+ <div v-if="routineDeployment && routineDeployment.source.endpoint.databaseType !== routineDeployment.target.endpoint.databaseType" class="space-y-1 text-amber-700 dark:text-amber-300">+ <p>{{ routineDeployment.source.endpoint.databaseType }} → {{ routineDeployment.target.endpoint.databaseType }} · {{ t("diff.packageCrossProduct") }}</p>+ <Button v-if="!packageDraft.reviewedTargetDraft && packageDraft.sql?.trim()" variant="outline" size="sm" :disabled="executing" @click="emit('review-package-target', packageDraft.objectId)">{{ t("diff.packageReviewTarget") }}</Button>+ </div>+ <div v-if="packageDraft.identity.kind === 'PACKAGE' && packageDraft.action !== 'delete'" class="flex flex-wrap gap-2">+ <Button v-if="packageMaterial('source', 'PACKAGE_BODY') && (!packageTransfer || !packageMaterial('target', 'PACKAGE_BODY'))" variant="outline" size="sm" :disabled="executing" @click="emit('include-package-companion', packageDraft.objectId, 'source')">{{+ t("diff.packageUseSourceBody")+ }}</Button>+ <Button v-if="!packageTransfer && packageMaterial('target', 'PACKAGE_BODY')" variant="outline" size="sm" :disabled="executing" @click="emit('include-package-companion', packageDraft.objectId, 'target')">{{ t("diff.packageRebuildTargetBody") }}</Button>+ </div>+ <div v-if="packageDraft.identity.kind === 'PACKAGE_BODY'" class="space-y-2">+ <Button+ v-if="!packagePeer && packageMaterial(packageDraft.action === 'delete' ? 'target' : 'source', 'PACKAGE') && (!packageTransfer || !packageMaterial('target', 'PACKAGE'))"+ variant="outline"+ size="sm"+ :disabled="executing"+ @click="emit('include-package-companion', packageDraft.objectId, 'source')"+ >{{ t(packageDraft.action === "delete" ? "diff.packageDeleteWhole" : "diff.packageAddSpecification") }}</Button+ >+ <div v-if="packageDraft.action !== 'delete'" class="flex flex-wrap gap-3" role="radiogroup" :aria-label="t('diff.packageContract')">+ <label v-for="contract in ['source', 'target'] as const" :key="contract" class="flex items-center gap-1.5">+ <input type="radio" name="package-contract" :value="contract" :checked="(packageDraft.packageContract ?? 'source') === contract" :disabled="executing" @change="emit('update-package-options', packageDraft.objectId, { packageContract: contract })" />+ {{ t(contract === "source" ? "diff.packageSourceContract" : "diff.packageTargetContract") }}+ </label>+ </div>+ </div>+ <label v-if="packageDraft.identity.kind === 'PACKAGE' && (packageDraft.action !== 'create' || packageMaterial('target', 'PACKAGE_BODY') || routineStep?.packageImpact?.bodyPending)" class="flex items-start gap-2 text-amber-700 dark:text-amber-300">+ <input type="checkbox" class="mt-0.5" :checked="packageDraft.confirmPackagePair ?? false" :disabled="executing" @change="emit('update-package-options', packageDraft.objectId, { confirmPackagePair: ($event.target as HTMLInputElement).checked })" />+ {{ t(packageDraft.action === "delete" ? "diff.packageConfirmDrop" : "diff.packageConfirmImpact") }}+ </label>+ </div>+ <p v-if="routineStep?.packageImpact?.bodyPending" class="text-amber-700 dark:text-amber-300">{{ t("diff.packageSpecificationOnly") }}</p>+ <p v-if="routineStep?.packageImpact?.mayInitialize" class="text-muted-foreground">{{ t("diff.packageInitialization") }}</p>+ <details v-if="routineStep?.packageImpact?.grants" class="max-h-32 overflow-auto text-muted-foreground">+ <summary class="cursor-pointer">{{ t("diff.packageGrantBackup") }}</summary>+ <p v-if="!routineStep.packageImpact.grants.complete" class="text-amber-700 dark:text-amber-300">{{ routineStep.packageImpact.grants.issue }}</p>+ <p v-for="(grant, index) in routineStep.packageImpact.grants.grants" :key="index" class="mt-1 break-all font-mono">{{ grant.grantor }} → {{ grant.grantee }} · {{ grant.privilege }} · GRANTABLE={{ grant.grantable }}</p>+ </details><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">+ <details v-if="routineOriginals.source" class="max-h-40 overflow-auto text-muted-foreground">+ <summary class="cursor-pointer">{{ t("diff.sourceDdl") }}</summary>+ <Button variant="ghost" size="sm" class="h-7 text-xs" @click="copyToClipboard(routineOriginals.source)">{{ t("diff.copySourceDdl") }}</Button>+ <pre class="mt-1 whitespace-pre-wrap break-words font-mono">{{ routineOriginals.source }}</pre>+ </details>+ <details v-if="routineOriginals.target" 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>+ <Button variant="ghost" size="sm" class="h-7 text-xs" @click="copyToClipboard(routineOriginals.target)">{{ t("diff.copyTargetDdl") }}</Button>+ <pre class="mt-1 whitespace-pre-wrap break-words font-mono">{{ routineOriginals.target }}</pre></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>@@ -500,6 +588,21 @@ function getObjectIconColor(kind: DiffObjectKind): string {>{{ message.attribute }} {{ message.line }}:{{ message.position }} — {{ message.text }}</button>+ <details v-if="routineRecord.readback?.source" class="max-h-40 overflow-auto text-muted-foreground">+ <summary class="cursor-pointer">{{ t("diff.targetDdl") }} · {{ routineRecord.identity.kind.replaceAll("_", " ") }}</summary>+ <Button variant="ghost" size="sm" class="h-7 text-xs" @click="copyToClipboard(routineRecord.readback.source)">{{ t("diff.copyTargetDdl") }}</Button>+ <pre class="mt-1 whitespace-pre-wrap break-words font-mono">{{ routineRecord.readback.source }}</pre>+ </details>+ <div v-if="routineCompanion" class="space-y-1 border-t pt-2">+ <p class="break-all font-mono">{{ routineCompanion.identity.kind.replaceAll("_", " ") }} {{ routineCompanion.identity.name }} · {{ routineCompanionStatus }}</p>+ <p v-for="(issue, index) in routineCompanion.issues" :key="index" class="text-destructive">{{ issue.message }}</p>+ <p v-for="(message, index) in routineCompanion.compilerMessages" :key="index" :class="message.attribute === 'ERROR' ? 'text-destructive' : 'text-amber-700 dark:text-amber-300'">{{ message.attribute }} {{ message.line }}:{{ message.position }} — {{ message.text }}</p>+ <details v-if="routineCompanion.source" class="max-h-40 overflow-auto text-muted-foreground">+ <summary class="cursor-pointer">{{ t("diff.targetDdl") }} · {{ routineCompanion.identity.kind.replaceAll("_", " ") }}</summary>+ <Button variant="ghost" size="sm" class="h-7 text-xs" @click="copyToClipboard(routineCompanion.source)">{{ t("diff.copyTargetDdl") }}</Button>+ <pre class="mt-1 whitespace-pre-wrap break-words font-mono">{{ routineCompanion.source }}</pre>+ </details>+ </div><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")@@ -547,14 +650,14 @@ function getObjectIconColor(kind: DiffObjectKind): string {<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')">+ <Button v-if="!packageTransfer" 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") }}</Button>- <Button variant="ghost" size="sm" class="h-7 text-xs" @click="$emit('back')">+ <Button v-if="!packageTransfer" variant="ghost" size="sm" class="h-7 text-xs" @click="$emit('back')">{{ t("diff.cancel") }}</Button>- <Button size="sm" class="h-7 text-xs gap-1" :disabled="topLevelObjects.length === 0 || executing || canExecute === false" @click="handleDeploy">+ <Button v-if="!packageTransfer" size="sm" class="h-7 text-xs gap-1" :disabled="topLevelObjects.length === 0 || executing || canExecute === false" @click="handleDeploy"><Loader2 v-if="executing" class="w-3.5 h-3.5 animate-spin" /><Play v-else class="w-3.5 h-3.5" />{{ t("diff.deployToServer") }}diff --git a/apps/desktop/src/components/diff/SchemaDiffDialog.vue b/apps/desktop/src/components/diff/SchemaDiffDialog.vueindex f144428f52..cb777eeb86 100644--- a/apps/desktop/src/components/diff/SchemaDiffDialog.vue+++ b/apps/desktop/src/components/diff/SchemaDiffDialog.vue@@ -34,6 +34,9 @@ import { normalizeSchemaDiffCompareOptions } from "@/types/schemaDiff";import {createOracleRoutineDeployment,editOracleRoutineDraft,+ editOraclePackageOptions,+ includeOraclePackageCompanion,+ reviewOraclePackageTargetDraft,executeOracleRoutineDeployment,observeOracleRoutineDeployment,oracleRoutineActiveStep,@@ -44,7 +47,7 @@ import {synchronizeOracleRoutineSelection,validateOracleRoutineDeployment,} from "@/lib/schema/oracleRoutineDeploy";-import type { SchemaDiffCompareOptions, SchemaDiffConfig, FieldMappingEntry, SchemaDiffTableMapping, SchemaDiffRoutineMapping } from "@/types/schemaDiff";+import type { SchemaDiffCompareOptions, SchemaDiffConfig, FieldMappingEntry, SchemaDiffTableMapping, SchemaDiffRoutineMapping, OracleRoutineKind, OracleRoutineIdentity } from "@/types/schemaDiff";import { getSchemaDiffSession, schemaDiffSessionObjects, startSchemaDiffSession, type SchemaDiffSession } from "@/composables/useSchemaDiffSession";import type { DatabaseType, ObjectSourceKind } from "@/types/database";import {@@ -189,7 +192,9 @@ 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(schemaDiffRoutineProductType(sourceDbType.value, sourceEngineDbType.value), schemaDiffRoutineProductType(targetDbType.value, targetEngineDbType.value)).length > 0);+const canEnableRoutinesCompare = computed(+ () => schemaDiffRoutineObjectTypesIntersection(schemaDiffRoutineProductType(sourceDbType.value, sourceEngineDbType.value), schemaDiffRoutineProductType(targetDbType.value, targetEngineDbType.value), schemaDiffPanelOptions.value.routineObjectKinds).length > 0,+);const effectiveRoutinesEnabled = computed(() => routinesCompareEnabled.value && canEnableRoutinesCompare.value);const showTableResultTab = computed(() => tablesCompareEnabled.value);const showRoutineResultTab = computed(() => effectiveRoutinesEnabled.value);@@ -209,7 +214,6 @@ const routineTargetIsCurrent = computed(() => {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 &&@@ -225,7 +229,9 @@ 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);+ const selected = selectedObject.value;+ const name = side === "source" ? (selected?.sourceName ?? selected?.name) : (selected?.targetName ?? selected?.name);+ const object = snapshot?.objects.find((object) => object.version.identity.name === name && object.version.identity.kind === selected?.routineType);return [...(snapshot?.issues ?? []), ...(object?.issues ?? [])].map((issue) => ({ side, message: issue.message }));});});@@ -339,8 +345,8 @@ const dialogStyle = computed(() => {}if (step.value === "result") {return {- width: savedSize?.width || "1100px",- height: savedSize?.height || "820px",+ width: parseFloat(savedSize?.width) > 0 ? savedSize.width : "1100px",+ height: parseFloat(savedSize?.height) > 0 ? savedSize.height : "820px",maxWidth: "calc(100vw - 2rem)",maxHeight: "calc(100vh - 2rem)",};@@ -380,6 +386,7 @@ function setupResizeObserver() {resizeObserver = new ResizeObserver((entries) => {for (const entry of entries) {const { width, height } = entry.contentRect;+ if (width <= 0 || height <= 0) continue;if (saveTimeout) clearTimeout(saveTimeout);saveTimeout = window.setTimeout(() => {localStorage.setItem(@@ -443,7 +450,14 @@ const selectedTreeObject = computed(() => {return findSchemaDiffObject(diffObjects.value, selectedObjectId.value);});-const canDeployRoutines = computed(() => (isOracleRoutineComparison.value ? routineTargetIsCurrent.value : isSchemaDiffPostgresLike(targetDbType.value)));+const canDeployRoutines = computed(() => {+ if (!isOracleRoutineComparison.value) return isSchemaDiffPostgresLike(targetDbType.value);+ if (!routineTargetIsCurrent.value) return false;+ const snapshots = comparisonSession.value!.routineSnapshots!;+ if (snapshots.source!.endpoint.databaseType === snapshots.target!.endpoint.databaseType) return true;+ const kinds = comparisonSession.value!.config.options.routineObjectKinds;+ return !!kinds?.length && kinds.every((kind) => kind === "PACKAGE" || kind === "PACKAGE_BODY") && routineDiffObjects.value.every((object) => object.routineType === "PACKAGE" || object.routineType === "PACKAGE_BODY");+});const canDeploy = computed(() => {// MySQL/SQL Server routine sync is deferred (copy DDL only). Postgres-family@@ -585,7 +599,7 @@ function applySchemaDiffSession(session: SchemaDiffSession | undefined): void {compatibilityWarnings.value = session.result.compatibilityWarnings ?? [];permissionDiffs.value = session.result.permissionDiffs ?? [];dependencyGraph.value = normalizeSchemaDiffDependencyGraph(session.result.dependencyGraph);- diffObjects.value = schemaDiffSessionObjects(session.result);+ diffObjects.value = schemaDiffSessionObjects(session.result, session.routineDeployment);if (session.routineDeployment) {for (const object of diffObjects.value) {const saved = session.routineDeployment.drafts.find((draft) => draft.objectId === object.id);@@ -818,6 +832,12 @@ function handleSelectedRoutinesUpdate(value?: string[]) {}}+function handleRoutineSelectionUpdate(value: { objectKinds: OracleRoutineKind[]; selectedObjects?: Pick<OracleRoutineIdentity, "name" | "kind">[] }) {+ if (activeConfig.value) {+ updateActiveConfigOptions(normalizeSchemaDiffCompareOptions({ ...activeConfig.value.options, routineObjectKinds: value.objectKinds, selectedRoutineObjects: value.selectedObjects, selectedRoutines: undefined, routineMappings: [] }, getDbType()));+ }+}+function handleCompareScopeUpdate(value: { tables?: boolean; views?: boolean; functions?: boolean }) {if (activeConfig.value) {const next = { ...activeConfig.value.options, ...value };@@ -1201,7 +1221,7 @@ async function handleSelectObject(reviewObject: SchemaDiffObject) {// fallback must not silently replace that evidence with an unverified source.if (isOracleRoutineComparison.value) return;- const preferredKind: ObjectSourceKind = obj.routineType === "PROCEDURE" ? "PROCEDURE" : "FUNCTION";+ const preferredKind: ObjectSourceKind = obj.routineType ?? "FUNCTION";async function fetchRoutineDdl(connectionId: string, database: string, schema: string, name: string): Promise<string | undefined> {try {@@ -1510,6 +1530,7 @@ const targetConnectionInfo = computed(() => {@update:routine-mappings="handleRoutineMappingsUpdate"@update:selected-tables="handleSelectedTablesUpdate"@update:selected-routines="handleSelectedRoutinesUpdate"+ @update:routine-selection="handleRoutineSelectionUpdate"@update:compare-scope="handleCompareScopeUpdate"@open-field-mapping="showFieldMappingDialog = true"/>@@ -1709,6 +1730,9 @@ const targetConnectionInfo = computed(() => {}"@validate-routines="routineDeployment && validateOracleRoutineDeployment(routineDeployment)"+ @include-package-companion="(id, source) => routineDeployment && includeOraclePackageCompanion(routineDeployment, id, source)"+ @update-package-options="(id, options) => routineDeployment && editOraclePackageOptions(routineDeployment, id, options)"+ @review-package-target="(id) => routineDeployment && reviewOraclePackageTargetDraft(routineDeployment, id)"@refresh-routines="routineDeployment && refreshOracleRoutineDeployment(routineDeployment)"@observe-routine="(id) => routineDeployment && observeOracleRoutineDeployment(routineDeployment, id)"@recover-routine="(id) => routineDeployment && prepareOracleRoutineRecovery(routineDeployment, id)"diff --git a/apps/desktop/src/components/diff/SchemaDiffObjectTree.vue b/apps/desktop/src/components/diff/SchemaDiffObjectTree.vueindex 6f68f4d04f..00296b2e01 100644--- a/apps/desktop/src/components/diff/SchemaDiffObjectTree.vue+++ b/apps/desktop/src/components/diff/SchemaDiffObjectTree.vue@@ -137,11 +137,15 @@ function displayObjectName(object: SchemaDiffObject): string {}function sourceObjectName(object: SchemaDiffObject): string {- return object.sourceName ?? displayObjectName(object);+ const name = object.sourceName ?? displayObjectName(object);+ if (object.routineType === "PACKAGE" || object.routineType === "PACKAGE_BODY") return `${object.routineType.replaceAll("_", " ")} ${name}`;+ return name;}function targetObjectName(object: SchemaDiffObject): string {- return object.targetName ?? displayObjectName(object);+ const name = object.targetName ?? displayObjectName(object);+ if (object.routineType === "PACKAGE" || object.routineType === "PACKAGE_BODY") return `${object.routineType.replaceAll("_", " ")} ${name}`;+ return name;}</script>diff --git a/apps/desktop/src/components/diff/SchemaDiffRoutineList.vue b/apps/desktop/src/components/diff/SchemaDiffRoutineList.vueindex c1052195c1..f20955478d 100644--- a/apps/desktop/src/components/diff/SchemaDiffRoutineList.vue+++ b/apps/desktop/src/components/diff/SchemaDiffRoutineList.vue@@ -38,6 +38,7 @@ const rows = computed(() =>function displayName(object: SchemaDiffObject, side: "source" | "target"): string {const name = side === "source" ? (object.sourceName ?? object.name) : (object.targetName ?? object.name);+ if (object.routineType === "PACKAGE" || object.routineType === "PACKAGE_BODY") return `${object.routineType.replaceAll("_", " ")} ${name}`;return schemaDiffRoutineKey(name, object.arguments ?? "");}diff --git a/apps/desktop/src/components/diff/__tests__/SchemaDiffConfigStep.programs.spec.ts b/apps/desktop/src/components/diff/__tests__/SchemaDiffConfigStep.programs.spec.tsnew file mode 100644index 0000000000..a325b0ebbf--- /dev/null+++ b/apps/desktop/src/components/diff/__tests__/SchemaDiffConfigStep.programs.spec.ts@@ -0,0 +1,146 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, reactive, type App } from "vue";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import i18n from "@/i18n";+import { getDefaultOptionsForDbType, normalizeSchemaDiffCompareOptions, type OracleRoutineKind, type OracleRoutineIdentity, type SchemaDiffCompareOptions } from "@/types/schemaDiff";+import SchemaDiffConfigStep from "@/components/diff/SchemaDiffConfigStep.vue";++const backend = vi.hoisted(() => ({ listObjects: vi.fn(), loadSchemaDiffRoutines: vi.fn() }));+vi.mock("@/stores/connectionStore", () => {+ const connections = [+ { id: "source", name: "Source", db_type: "oceanbase-oracle" },+ { id: "target", name: "Target", db_type: "oceanbase-oracle" },+ { id: "mysql", name: "MySQL", db_type: "mysql" },+ ];+ return { useConnectionStore: () => ({ connections, sidebarLayout: { groups: [], order: [] }, getConfig: (id: string) => connections.find((connection) => connection.id === id), ensureConnected: vi.fn().mockResolvedValue(undefined) }) };+});+vi.mock("@/lib/backend/api", () => ({ ...backend, listDatabases: vi.fn().mockResolvedValue(["S", "T"]), listSchemas: vi.fn().mockResolvedValue(["S", "T"]), executeQuery: vi.fn().mockResolvedValue({ rows: [] }) }));++const name = 'Pkg.With.Dot,"中文😀';+const rows = (kinds: string[]) => kinds.map((object_type) => ({ name: object_type.startsWith("PACKAGE") ? name : object_type === "FUNCTION" ? "F" : "P", object_type }));+const apps: App[] = [];+beforeEach(() => {+ vi.clearAllMocks();+ backend.listObjects.mockImplementation(async (_id, _db, _schema, kinds: string[]) => rows(kinds));+});+afterEach(() => {+ apps.splice(0).forEach((app) => app.unmount());+ document.body.textContent = "";+});+async function flush() {+ for (let index = 0; index < 8; index++) {+ await nextTick();+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+}+function mountConfig(options: Partial<SchemaDiffCompareOptions> = {}, targetConnectionId = "target") {+ const state = reactive({ options: { ...getDefaultOptionsForDbType("oceanbase-oracle"), tables: false, views: false, functions: true, ...options } });+ const container = document.createElement("div");+ document.body.append(container);+ const app = createApp({+ setup: () => () =>+ h(SchemaDiffConfigStep, {+ sourceConnectionId: "source",+ sourceDatabase: "S",+ sourceSchema: "S",+ targetConnectionId,+ targetDatabase: "T",+ targetSchema: "T",+ configs: [],+ activeConfigId: "",+ ignoreComments: false,+ options: state.options,+ selectedRoutines: state.options.selectedRoutines,+ loading: false,+ recentConfigs: [],+ tableListLoader: { load: vi.fn().mockResolvedValue([]) },+ "onUpdate:routineSelection": (selection: { objectKinds: OracleRoutineKind[]; selectedObjects?: Pick<OracleRoutineIdentity, "name" | "kind">[] }) => {+ state.options = normalizeSchemaDiffCompareOptions({ ...state.options, routineObjectKinds: selection.objectKinds, selectedRoutineObjects: selection.selectedObjects, selectedRoutines: undefined, routineMappings: [] });+ },+ "onUpdate:selectedRoutines": (selectedRoutines?: string[]) => {+ state.options = { ...state.options, selectedRoutines };+ },+ "onUpdate:compareScope": (scope: { functions?: boolean }) => {+ state.options = { ...state.options, ...scope };+ },+ }),+ });+ apps.push(app);+ app.use(i18n);+ app.mount(container);+ return { state, container };+}++it("keeps the legacy listing request unchanged and lets BODY-only selection use an opaque kind key with a readable label", async () => {+ const { state, container } = mountConfig();+ await flush();+ expect(backend.listObjects).toHaveBeenCalledWith("source", "S", "S", ["PROCEDURE", "FUNCTION"]);+ expect(state.options.routineObjectKinds).toBeUndefined();+ container.querySelector<HTMLInputElement>('[data-program-kind="PACKAGE_BODY"]')!.click();+ await flush();+ expect(state.options.routineObjectKinds).toEqual(["PROCEDURE", "FUNCTION", "PACKAGE_BODY"]);+ [...container.querySelectorAll("button")].find((button) => button.textContent?.trim() === i18n.global.t("diff.chooseRoutines"))!.click();+ await flush();+ const key = JSON.stringify(["PACKAGE_BODY", name, ""]);+ const body = [...container.querySelectorAll<HTMLButtonElement>("[data-table-name]")].find((button) => button.dataset.tableName === key)!;+ expect(body.textContent).toContain(`PACKAGE BODY ${name}`);+ expect(body.textContent).not.toContain('["PACKAGE_BODY"');+ body.click();+ await flush();+ expect(state.options.selectedRoutineObjects).toEqual([{ name, kind: "PACKAGE_BODY" }]);+ expect(state.options.selectedRoutines).toBeUndefined();+ container.querySelector<HTMLInputElement>('[data-program-kind="PACKAGE"]')!.click();+ await flush();+ expect(state.options.selectedRoutineObjects).toEqual([{ name, kind: "PACKAGE_BODY" }]);+ [...container.querySelectorAll<HTMLButtonElement>("[data-table-name]")].find((button) => button.dataset.tableName === JSON.stringify(["PACKAGE", name, ""]))!.click();+ await flush();+ expect(state.options.selectedRoutineObjects).toEqual([+ { name, kind: "PACKAGE_BODY" },+ { name, kind: "PACKAGE" },+ ]);+ expect(backend.loadSchemaDiffRoutines).not.toHaveBeenCalled();+});++it("does not let an older kind-list response remove a newer restored package selection", async () => {+ const { state, container } = mountConfig();+ await flush();+ let resolveOld!: (value: ReturnType<typeof rows>) => void;+ backend.listObjects.mockImplementation(async (_id, _db, _schema, kinds: string[]) =>+ kinds.includes("PACKAGE_BODY")+ ? new Promise((resolve) => {+ resolveOld = resolve;+ })+ : rows(kinds),+ );+ container.querySelector<HTMLInputElement>('[data-program-kind="PACKAGE_BODY"]')!.click();+ await vi.waitFor(() => expect(resolveOld).toBeTypeOf("function"));+ state.options = normalizeSchemaDiffCompareOptions({ ...state.options, routineObjectKinds: ["PACKAGE"], selectedRoutineObjects: [{ name, kind: "PACKAGE" }], selectedRoutines: undefined });+ await flush();+ resolveOld(rows(["PACKAGE_BODY"]));+ await flush();+ expect(state.options.selectedRoutineObjects).toEqual([{ name, kind: "PACKAGE" }]);+ expect([...container.querySelectorAll<HTMLButtonElement>("[data-table-name]")].map((button) => button.dataset.tableName)).toContain(JSON.stringify(["PACKAGE", name, ""]));+ expect(container.querySelector<HTMLInputElement>('[data-program-kind="PACKAGE_BODY"]')!.checked).toBe(false);+});++it("retains an explicit legacy function selection when package kinds are enabled", async () => {+ const { state, container } = mountConfig({ selectedRoutines: ["F"] });+ await flush();+ container.querySelector<HTMLInputElement>('[data-program-kind="PACKAGE"]')!.click();+ await flush();+ expect(state.options.selectedRoutineObjects).toEqual([{ name: "F", kind: "FUNCTION" }]);+ expect(state.options.selectedRoutines).toBeUndefined();+});++it("lets an unsupported restored package scope be turned off explicitly without silently filtering it", async () => {+ const { state, container } = mountConfig({ tables: true, routineObjectKinds: ["PACKAGE"] }, "mysql");+ await flush();+ const toggle = [...container.querySelectorAll<HTMLButtonElement>('[role="switch"]')].find((button) => button.getAttribute("aria-label") === i18n.global.t("diff.compareRoutinesSwitch"))!;+ expect(toggle.getAttribute("aria-checked")).toBe("true");+ expect(toggle.disabled).toBe(false);+ toggle.click();+ await flush();+ expect(state.options.functions).toBe(false);+ expect(state.options.routineObjectKinds).toEqual(["PACKAGE"]);+ expect(backend.loadSchemaDiffRoutines).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.ts b/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.tsindex a8a72b27da..dd19d1d2bc 100644--- a/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.ts+++ b/apps/desktop/src/components/diff/__tests__/SchemaDiffDeployStep.spec.ts@@ -3,10 +3,11 @@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";+import { createOracleRoutineDeployment, editOraclePackageOptions, includeOraclePackageCompanion, reviewOraclePackageTargetDraft, selectOracleRoutineDraft, synchronizeOracleRoutineSelection } from "@/lib/schema/oracleRoutineDeploy";+import type { OracleRoutineOperation, OracleRoutineKind } 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) }));+const editor = vi.hoisted(() => ({ focus: vi.fn(), dispatch: vi.fn(), readOnly: vi.fn((_value: boolean) => []), dialect: vi.fn((_language: unknown, _dialect: string) => undefined), copy: vi.fn() }));+vi.mock("@/lib/common/clipboard", () => ({ copyToClipboard: editor.copy }));vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));vi.mock("@/i18n", () => ({ default: { global: { t: (key: string) => key } } }));@@ -143,14 +144,14 @@ afterEach(() => {vi.clearAllMocks();});-function routineFixture() {+function routineFixture(kind: OracleRoutineKind = "FUNCTION") {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 };+ const object = { id: "func-F", name: "F", routineType: kind, 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;';+ const sql = kind === "FUNCTION" ? 'CREATE FUNCTION "Owner.With.Dot"."F" RETURN NUMBER AS BEGIN RETURN 1; END;' : `CREATE ${kind.replaceAll("_", " ")} "Owner.With.Dot"."F" AS END;`;state.drafts[0].sql = sql;state.plan = {target: endpoint,@@ -161,6 +162,229 @@ function routineFixture() {}describe("SchemaDiffDeployStep Oracle routine review", () => {+ it("reuses package editing and validation for transfer without offering a second execution or replacement of skipped kinds", async () => {+ const { state, object, sql, identity } = routineFixture("PACKAGE_BODY");+ const spec = { ...identity, kind: "PACKAGE" as const };+ const material = { version: { identity: spec, objectId: "spec", status: "VALID", lastDdlTime: "1" }, source: "complete specification", sourceComplete: true, dependencies: [], dependenciesComplete: true, issues: [] };+ state.source = { ...state.source, objects: [material] };+ state.target = { ...state.target, objects: [material] };+ const validate = vi.fn();+ const { container } = await mountDeployStep({ deploySql: sql, selectedObjects: [object], databaseType: "oracle", routineDeployment: state, packageTransfer: true, onValidateRoutines: validate });+ expect(container.textContent).not.toContain("diff.deployToServer");+ expect(container.textContent).not.toContain("diff.backToResult");+ expect(container.textContent).not.toContain("diff.packageAddSpecification");+ const buttons = [...container.querySelectorAll<HTMLButtonElement>("button")];+ buttons.find((button) => button.textContent?.trim() === "diff.routineValidate")!.click();+ expect(validate).toHaveBeenCalledOnce();+ expect(container.querySelector('input[type="radio"][value="target"]')).not.toBeNull();+ state.target = { ...state.target, objects: [] };+ await nextTick();+ expect(container.textContent).toContain("diff.packageAddSpecification");+ });++ it("offers an explicit manual target-draft review for cross-product packages without enabling deployment", async () => {+ const { state, object, sql } = routineFixture("PACKAGE");+ state.source = { ...state.source, endpoint: { ...state.source.endpoint, databaseType: "oracle" } };+ const { container } = await mountDeployStep({ deploySql: sql, selectedObjects: [object], databaseType: "oceanbase-oracle", routineDeployment: state, canExecute: false, onReviewPackageTarget: (id: string) => reviewOraclePackageTargetDraft(state, id) });+ expect(container.textContent).toContain("oracle → oceanbase-oracle");+ expect(container.textContent).toContain("diff.packageCrossProduct");+ const review = [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("diff.packageReviewTarget"))!;+ expect(state.drafts[0].reviewedTargetDraft).not.toBe(true);+ review.click();+ await nextTick();+ expect(state.drafts[0].reviewedTargetDraft).toBe(true);+ expect(state.plan).toBeNull();+ const deploy = [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("diff.deployToServer"))!;+ expect(deploy.disabled).toBe(true);+ });++ it("requires an explicit body choice, retains target body as a draft, and invalidates confirmation when its contract changes", async () => {+ const { state, object, sql, identity } = routineFixture("PACKAGE");+ const bodyIdentity = { ...identity, kind: "PACKAGE_BODY" as const };+ state.drafts[0].action = "replace";+ state.target = { ...state.target, objects: [{ version: { identity: bodyIdentity, objectId: "2", status: "VALID", lastDdlTime: "1" }, source: "complete target body", sourceComplete: true, dependencies: [], dependenciesComplete: true, issues: [] }] };+ const { container } = await mountDeployStep({+ deploySql: sql,+ selectedObjects: [object],+ databaseType: "oceanbase-oracle",+ routineDeployment: state,+ onIncludePackageCompanion: (id: string, source: "source" | "target") => includeOraclePackageCompanion(state, id, source),+ onUpdatePackageOptions: (id: string, options: Parameters<typeof editOraclePackageOptions>[2]) => editOraclePackageOptions(state, id, options),+ });+ expect(state.drafts).toHaveLength(1);+ const confirm = [...container.querySelectorAll<HTMLLabelElement>("label")].find((label) => label.textContent?.includes("diff.packageConfirmImpact"))!.querySelector<HTMLInputElement>("input")!;+ expect(confirm.checked).toBe(false);+ confirm.checked = true;+ confirm.dispatchEvent(new Event("change"));+ await nextTick();+ expect(state.drafts[0].confirmPackagePair).toBe(true);+ const retain = [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("diff.packageRebuildTargetBody"))!;+ retain.click();+ await nextTick();+ expect(state.drafts).toHaveLength(2);+ expect(state.drafts[1]).toMatchObject({ identity: bodyIdentity, packageBodySource: "target", action: "replace" });+ expect(state.drafts[0].confirmPackagePair).toBe(false);+ expect(state.plan).toBeNull();+ const original = [...container.querySelectorAll("details")].find((detail) => detail.querySelector("summary")?.textContent === "diff.targetDdl")!;+ expect(original.querySelector("pre")?.textContent).toBe("complete target body");+ original.querySelector("button")!.click();+ expect(editor.copy).toHaveBeenCalledWith("complete target body");+ const targetContract = container.querySelector<HTMLInputElement>('input[type="radio"][value="target"]')!;+ targetContract.checked = true;+ targetContract.dispatchEvent(new Event("change"));+ await nextTick();+ expect(state.drafts[1].packageContract).toBe("target");+ });++ it("renders the Core package order and exposes recovery-only body source in the same review", async () => {+ const { state, object, sql, identity } = routineFixture("PACKAGE");+ const bodyIdentity = { ...identity, kind: "PACKAGE_BODY" as const };+ const specification = state.plan!.steps[0];+ const body = { ...specification, identity: bodyIdentity, action: "delete" as const, sql: 'DROP PACKAGE BODY "Owner.With.Dot"."F"', sourceOriginal: "complete original body" };+ state.recoveryPlan = { ...state.plan!, steps: [body, specification] };+ const { container } = await mountDeployStep({ deploySql: sql, selectedObjects: [object], databaseType: "oceanbase-oracle", routineDeployment: state, onSelectRoutine: (id: string) => selectOracleRoutineDraft(state, id) });+ const rows = [...container.querySelectorAll<HTMLElement>('[role="button"]')];+ expect(rows).toHaveLength(2);+ expect(rows[0].textContent).toContain("PACKAGE BODY");+ expect(rows[1].textContent).not.toContain("PACKAGE BODY");+ rows[0].click();+ await nextTick();+ expect(state.recoveryPlan).not.toBeNull();+ expect(state.drafts).toHaveLength(1);+ expect(container.textContent).toContain("Owner.With.Dot.F · PACKAGE_BODY");+ const source = [...container.querySelectorAll("details")].find((detail) => detail.querySelector("summary")?.textContent === "diff.sourceDdl")!;+ expect(source.querySelector("pre")?.textContent).toBe("complete original body");+ source.querySelector("button")!.click();+ expect(editor.copy).toHaveBeenCalledWith("complete original body");+ });++ it("shows specification success separately from an invalid body, preserves its full readback, and does not locate body errors in the specification editor", async () => {+ const { state, object, sql, endpoint, identity } = routineFixture("PACKAGE");+ const bodyIdentity = { ...identity, kind: "PACKAGE_BODY" as const };+ const body = 'CREATE OR REPLACE PACKAGE BODY "Owner.With.Dot"."F" AS -- 中文😀\nEND;';+ const record: OracleRoutineOperation = {+ operationId: "spec-success",+ target: endpoint,+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ error: null,+ readback: {+ identity,+ state: "verified",+ exists: true,+ version: null,+ source: sql,+ definitionMatches: true,+ issues: [],+ compilerMessages: [],+ packageCompanion: {+ identity: bodyIdentity,+ state: "invalid",+ exists: true,+ version: { identity: bodyIdentity, objectId: "12", status: "INVALID", lastDdlTime: "1" },+ source: body,+ definitionMatches: null,+ issues: [],+ compilerMessages: [+ { attribute: "ERROR", line: 3, position: 12, text: "PLS-00323" },+ { attribute: "WARNING", line: 4, position: 2, text: "unused package state" },+ ],+ },+ },+ };+ state.drafts[0].operation = record;+ state.plan!.steps[0].operation = record;+ state.plan!.steps[0].issues = [];+ const { container } = await mountDeployStep({ deploySql: sql, selectedObjects: [object], databaseType: "oceanbase-oracle", routineDeployment: state, canExecute: false });+ expect(container.textContent).toContain("diff.routineVerified");+ expect(container.textContent).toContain("PACKAGE BODY F · objects.invalid");+ expect(container.textContent).toContain("ERROR 3:12 — PLS-00323");+ expect(container.textContent).toContain("WARNING 4:2 — unused package state");+ expect([...container.querySelectorAll("button")].some((button) => button.textContent?.includes("PLS-00323"))).toBe(false);+ const details = [...container.querySelectorAll("details")].find((detail) => detail.querySelector("summary")?.textContent === "diff.targetDdl · PACKAGE BODY")!;+ expect(details.querySelector("pre")?.textContent).toBe(body);+ details.querySelector("button")!.click();+ expect(editor.copy).toHaveBeenCalledWith(body);+ state.drafts[0].operation!.readback!.packageCompanion = { ...record.readback!.packageCompanion!, state: "missing", exists: false, version: null, source: null, compilerMessages: [] };+ await nextTick();+ expect(container.textContent).toContain("PACKAGE BODY F · objects.routineReadbackMissing");+ });++ it("does not present a VALID catalog status as complete companion verification when its source readback failed", async () => {+ const { state, object, sql, endpoint, identity } = routineFixture("PACKAGE");+ const companion = { ...identity, kind: "PACKAGE_BODY" as const };+ state.drafts[0].operation = {+ operationId: "pair-read-failed",+ target: endpoint,+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ error: null,+ readback: {+ identity,+ state: "readback-failed",+ exists: true,+ source: sql,+ version: null,+ definitionMatches: true,+ compilerMessages: [],+ issues: [],+ packageCompanion: {+ identity: companion,+ state: "readback-failed",+ exists: true,+ version: { identity: companion, objectId: "12", status: "VALID", lastDdlTime: "1" },+ source: null,+ definitionMatches: null,+ compilerMessages: [],+ issues: [{ stage: "source", code: "incomplete", message: "companion source incomplete" }],+ },+ },+ };+ const { container } = await mountDeployStep({ deploySql: sql, selectedObjects: [object], routineDeployment: state });+ expect(container.textContent).toContain("PACKAGE BODY F · diff.routineUnverified");+ expect(container.textContent).toContain("companion source incomplete");+ expect(container.textContent).not.toContain("PACKAGE BODY F · VALID");+ });++ it("locates a package-body compiler position after Unicode and an omitted stored owner in the body editor", async () => {+ const { state, object, endpoint, identity } = routineFixture("PACKAGE_BODY");+ const stored = "PACKAGE BODY \"F\" AS FUNCTION f RETURN NUMBER IS BEGIN RETURN '😀' + missing_identifier; END f; END;";+ const sql = `CREATE OR REPLACE ${stored.replace('"F"', '"Owner.With.Dot"."F"')}`;+ state.drafts[0].sql = sql;+ state.plan!.steps[0].sql = sql;+ state.plan!.steps[0].issues = [];+ state.drafts[0].operation = {+ operationId: "invalid-body",+ target: endpoint,+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ error: null,+ readback: {+ identity,+ state: "invalid",+ exists: true,+ source: `CREATE OR REPLACE ${stored}`,+ version: null,+ definitionMatches: true,+ issues: [],+ compilerMessages: [{ attribute: "ERROR", line: 1, position: Array.from(stored.slice(0, stored.indexOf("missing_identifier"))).length + 1, text: "package member missing" }],+ },+ };+ const { container } = await mountDeployStep({ deploySql: sql, selectedObjects: [object], routineDeployment: state, databaseType: "oceanbase-oracle" });+ const message = [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.includes("package member missing"))!;+ expect(message.disabled).toBe(false);+ message.click();+ await nextTick();+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(editor.dispatch).toHaveBeenCalledWith(expect.objectContaining({ selection: { anchor: sql.indexOf("missing_identifier") } }));+ });+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();diff --git a/apps/desktop/src/components/diff/__tests__/SchemaDiffDialog.oracleRoutine.spec.ts b/apps/desktop/src/components/diff/__tests__/SchemaDiffDialog.oracleRoutine.spec.tsindex 7f12dfeac5..6f26447847 100644--- a/apps/desktop/src/components/diff/__tests__/SchemaDiffDialog.oracleRoutine.spec.ts+++ b/apps/desktop/src/components/diff/__tests__/SchemaDiffDialog.oracleRoutine.spec.ts@@ -3,10 +3,11 @@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 SchemaDiffDeployStep from "@/components/diff/SchemaDiffDeployStep.vue";import { startSchemaDiffSession, removeSchemaDiffSession } from "@/composables/useSchemaDiffSession";-import type { OracleRoutineOperation, OracleRoutinePlanInput, OracleRoutineSnapshot } from "@/types/schemaDiff";+import type { OracleRoutineKind, 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" }));+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", sourceDatabaseType: "" }));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() }) }));@@ -14,7 +15,7 @@ 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 }));+ const connections = () => ["source", "target"].map((id) => ({ id, name: id, db_type: id === "source" ? calls.sourceDatabaseType || calls.databaseType : calls.databaseType, is_production: id === "target", host: "localhost", port: 1 }));return {useConnectionStore: () => ({get connections() {@@ -97,7 +98,8 @@ 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 product = connectionId === "source" ? calls.sourceDatabaseType || calls.databaseType : calls.databaseType;+ return { endpoint: { connectionId, database: "tenant", schema: owner, databaseType: product === "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" };@@ -106,6 +108,7 @@ beforeEach(() => {vi.clearAllMocks();records.clear();calls.databaseType = "oceanbase-oracle";+ calls.sourceDatabaseType = "";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);@@ -157,19 +160,20 @@ function button(text: string) {expect(found, text).toBeDefined();return found!;}-async function mountComparison(databaseType: "oracle" | "oceanbase-oracle" | "postgres" | "mysql" | "sqlserver" = "oceanbase-oracle") {+async function mountComparison(databaseType: "oracle" | "oceanbase-oracle" | "postgres" | "mysql" | "sqlserver" = "oceanbase-oracle", sourceType = databaseType, kinds?: OracleRoutineKind[]) {calls.databaseType = databaseType;+ calls.sourceDatabaseType = sourceType;const session = startSchemaDiffSession({sourceConnectionId: "source",sourceDatabase: "tenant",sourceSchema: "Source",- sourceDbType: databaseType,+ sourceDbType: sourceType,targetConnectionId: "target",targetDatabase: "tenant",targetSchema: "Target",targetDbType: databaseType,- options: { tables: false, views: false, functions: true, sequences: false, rules: false, owners: false },+ options: { tables: false, views: false, functions: true, sequences: false, rules: false, owners: false, ...(kinds ? { routineObjectKinds: kinds } : {}) },ignoreComments: false,label: "test",},@@ -201,6 +205,86 @@ afterEach(() => {apps.splice(0).forEach((app) => app.unmount());sessions.splice(0).forEach(removeSchemaDiffSession);document.body.innerHTML = "";+ localStorage.removeItem("dbx-schema-diff-size");+});++it("keeps external SQL and rollback previews separate from actual user edits, including clearing", async () => {+ const state = reactive({ sql: "original specification", mode: "forward" });+ const edits: string[] = [];+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp({+ setup: () => () =>+ h(SchemaDiffDeployStep, {+ deploySql: state.sql,+ deploySqlMode: state.mode as "forward" | "rollback",+ rollbackSql: "original recovery",+ selectedObjects: [],+ targetConnectionId: "target",+ targetDatabase: "tenant",+ targetSchema: "Target",+ executing: false,+ "onUpdate:deploySql": (sql: string) => edits.push(sql),+ }),+ });+ apps.push(app);+ app.mount(host);+ await flush();+ const input = host.querySelector<HTMLTextAreaElement>("textarea")!;+ state.sql = "";+ await flush();+ expect(input.value).toBe("");+ state.sql = "prepared target body";+ await flush();+ state.mode = "rollback";+ await flush();+ expect(input.value).toBe("original recovery");+ state.mode = "forward";+ await flush();+ expect(input.value).toBe("prepared target body");+ expect(edits).toEqual([]);+ input.value = "manual body";+ input.dispatchEvent(new Event("input"));+ input.value = "";+ input.dispatchEvent(new Event("input"));+ expect(edits).toEqual(["manual body", ""]);+});++it.each([+ [{ width: "0px", height: "0px" }, "1100px", "820px"],+ [{ width: "1120px", height: "840px" }, "1120px", "840px"],+])("opens readable results while preserving a positive saved dialog size: %j", async (saved, width, height) => {+ localStorage.setItem("dbx-schema-diff-size", JSON.stringify(saved));+ await mountComparison();+ const dialog = document.querySelector<HTMLElement>('[role="dialog"]')!;+ expect(dialog.style.width).toBe(width);+ expect(dialog.style.height).toBe(height);+});++it("does not persist a hidden dialog's zero-sized resize observation", async () => {+ let resize: ResizeObserverCallback | undefined;+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(private callback: ResizeObserverCallback) {}+ observe(target: Element) {+ if (target.matches(".dbx-schema-diff-dialog")) resize = this.callback;+ }+ unobserve() {}+ disconnect() {}+ },+ );+ try {+ await mountComparison();+ await vi.waitFor(() => expect(resize).toBeDefined());+ resize!([{ contentRect: { width: 1120, height: 840 } } as ResizeObserverEntry], {} as ResizeObserver);+ await vi.waitFor(() => expect(JSON.parse(localStorage.getItem("dbx-schema-diff-size")!)).toEqual({ width: "1120px", height: "840px" }));+ resize!([{ contentRect: { width: 0, height: 0 } } as ResizeObserverEntry], {} as ResizeObserver);+ await new Promise((resolve) => setTimeout(resolve, 550));+ expect(JSON.parse(localStorage.getItem("dbx-schema-diff-size")!)).toEqual({ width: "1120px", height: "840px" });+ } finally {+ vi.unstubAllGlobals();+ }});it("opens the real Oracle comparison, retains draft on both confirmations' cancellation, then displays INVALID and corrects only that step", async () => {@@ -255,6 +339,48 @@ it("opens the real Oracle comparison, retains draft on both confirmations' canceexpect(document.body.textContent).toContain("diff.routineReadOnlyCompleted");});+it("keeps a newly included target body automatic until the user actually edits it", async () => {+ calls.load.mockImplementation(async (id: string) => {+ const result = snapshot(id);+ result.objects = (["PACKAGE", "PACKAGE_BODY"] as const).map((kind) => ({+ version: { identity: { owner: result.endpoint.schema!, name: "P", kind }, objectId: `${id}-${kind}`, status: "VALID", lastDdlTime: "1" },+ source: kind === "PACKAGE" ? 'CREATE PACKAGE "P" AS FUNCTION f RETURN NUMBER; END;' : 'CREATE PACKAGE BODY "P" AS FUNCTION f RETURN NUMBER IS BEGIN RETURN 1; END; END;',+ sourceComplete: true,+ dependencies: [],+ dependenciesComplete: true,+ issues: [],+ }));+ return result;+ });+ const spec = { ...sourceFunction, name: "P", function_type: "PACKAGE", definition: 'CREATE PACKAGE "P" AS g NUMBER; FUNCTION f RETURN NUMBER; END;' };+ calls.compare.mockResolvedValue({ diffs: [], functionDiffs: [{ type: "modified", name: "P", programKind: "PACKAGE", source: spec, target: { ...spec, definition: spec.definition.replace("g NUMBER; ", "") } }], syncSql: "", renameCandidates: [] });+ const ordinaryPrepare = calls.prepare.getMockImplementation()!;+ calls.prepare.mockImplementation(async (input: OracleRoutinePlanInput) => {+ const plan = await ordinaryPrepare(input);+ for (const step of plan.steps) step.sql = input.drafts.find((draft) => draft.identity.kind === step.identity.kind)?.sql ?? (step.identity.kind === "PACKAGE" ? spec.definition : 'CREATE PACKAGE BODY "Target"."P" AS FUNCTION f RETURN NUMBER IS BEGIN RETURN 1; END; END;');+ return plan;+ });+ const { session } = await mountComparison("oceanbase-oracle", "oceanbase-oracle", ["PACKAGE"]);+ button("diff.nextStepDeployRoutines").click();+ await flush();+ button("diff.packageRebuildTargetBody").click();+ await flush();+ const body = session.routineDeployment!.drafts.find((draft) => draft.identity.kind === "PACKAGE_BODY")!;+ expect(body.packageBodySource).toBe("target");+ expect(body.sql).toBeUndefined();+ button("diff.routineValidate").click();+ await flush();+ const request = calls.prepare.mock.calls.at(-1)![0] as OracleRoutinePlanInput;+ expect(request.drafts.find((draft) => draft.identity.kind === "PACKAGE_BODY")).toMatchObject({ packageBodySource: "target", sql: undefined });+ expect(body.sql).toContain('PACKAGE BODY "Target"."P"');+ const input = document.querySelector<HTMLTextAreaElement>(".deploy-sql-editor textarea")!;+ input.value = "";+ input.dispatchEvent(new Event("input"));+ await flush();+ expect(body.sql).toBe("");+ expect(session.routineDeployment!.plan).toBeNull();+});+it("restores the same draft and operation after closing and reopening the actual dialog", async () => {const { session, visible } = await mountComparison();button("diff.nextStepDeployRoutines").click();@@ -374,3 +500,55 @@ it("opens a native Oracle target draft through the same controlled review", asynexpect(button("diff.deployToServer").disabled).toBe(false);expect(calls.genericPlan).not.toHaveBeenCalled();});++it("keeps the old cross-product function selection outside the package deployment path", async () => {+ const session = startSchemaDiffSession(+ {+ sourceConnectionId: "source",+ sourceDatabase: "tenant",+ sourceSchema: "Source",+ sourceDbType: "oracle",+ targetConnectionId: "target",+ targetDatabase: "tenant",+ targetSchema: "Target",+ targetDbType: "oceanbase-oracle",+ options: { tables: false, views: false, functions: true, sequences: false, rules: false, owners: false, routineObjectKinds: ["FUNCTION"] },+ ignoreComments: false,+ label: "cross-product function",+ },+ { tableListLoader: { load: vi.fn() } },+ );+ sessions.push(session.id);+ await flush();+ expect(session.status).toBe("failed");+ expect(session.error).toContain("cross-product comparison supports explicit package kinds only");+ expect(calls.prepare).not.toHaveBeenCalled();+ expect(calls.execute).not.toHaveBeenCalled();+});++it("opens a cross-product package in the actual review and requires explicit target-draft review before approval", async () => {+ calls.compare.mockResolvedValue({ diffs: [], functionDiffs: [{ type: "added", name: "P", programKind: "PACKAGE", source: { ...sourceFunction, name: "P", function_type: "PACKAGE", definition: 'CREATE PACKAGE "P" AS n NUMBER; END;' } }], syncSql: "", renameCandidates: [] });+ const ordinaryPrepare = calls.prepare.getMockImplementation()!;+ calls.prepare.mockImplementation(async (input: OracleRoutinePlanInput) => {+ const plan = await ordinaryPrepare(input);+ plan.steps[0].sql = input.drafts[0].sql ?? 'CREATE PACKAGE "Target"."P" AS n NUMBER; END;';+ if (!input.drafts[0].sql) {+ plan.ready = false;+ plan.steps[0].operation = null;+ plan.steps[0].issues = [{ code: "review-required", message: "Review target draft", line: 1, column: 1 }];+ }+ return plan;+ });+ const { session } = await mountComparison("oceanbase-oracle", "oracle", ["PACKAGE"]);+ button("diff.nextStepDeployRoutines").click();+ await flush();+ expect(session.routineDeployment?.plan?.ready).toBe(false);+ expect(button("diff.deployToServer").disabled).toBe(true);+ button("diff.packageReviewTarget").click();+ await flush();+ button("diff.routineValidate").click();+ await flush();+ expect(calls.prepare.mock.calls.at(-1)![0].drafts[0].sql).toContain('PACKAGE "Target"."P"');+ expect(button("diff.deployToServer").disabled).toBe(false);+ expect(calls.execute).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/components/diff/__tests__/SchemaDiffRoutineList.spec.ts b/apps/desktop/src/components/diff/__tests__/SchemaDiffRoutineList.spec.tsnew file mode 100644index 0000000000..b6b1de92f8--- /dev/null+++ b/apps/desktop/src/components/diff/__tests__/SchemaDiffRoutineList.spec.ts@@ -0,0 +1,45 @@+// @vitest-environment happy-dom++import { createApp } from "vue";+import { expect, it, vi } from "vitest";+import type { SchemaDiffObject } from "@/lib/schema/schemaDiff";+import SchemaDiffRoutineList from "../SchemaDiffRoutineList.vue";+import SchemaDiffObjectTree from "../SchemaDiffObjectTree.vue";+import { groupDiffObjects } from "@/lib/schema/schemaDiff";++vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));++it("distinguishes same-name package kinds without changing overload labels or selection identity", () => {+ const objects = ["PACKAGE", "PACKAGE_BODY", "FUNCTION"].map((routineType, index) => ({+ id: String(index),+ name: "P",+ sourceName: "P",+ targetName: "P",+ objectKind: "function",+ routineType,+ arguments: routineType === "FUNCTION" ? "integer" : "",+ operationType: "modify",+ selected: true,+ })) as SchemaDiffObject[];+ const selections: SchemaDiffObject[] = [];+ const host = document.createElement("div");+ const app = createApp(SchemaDiffRoutineList, { objects, selectable: true, onToggleSelection: (object: SchemaDiffObject) => selections.push(object) });+ app.mount(host);+ try {+ const checkboxes = Array.from(host.querySelectorAll("input"));+ expect(checkboxes.map((input) => input.getAttribute("aria-label"))).toEqual(["PACKAGE P", "PACKAGE BODY P", "P(integer)"]);+ expect(host.textContent).toContain("PACKAGE BODY P");+ for (const input of checkboxes) input.dispatchEvent(new Event("change"));+ expect(selections).toEqual(objects);+ } finally {+ app.unmount();+ }+ const tree = createApp(SchemaDiffObjectTree, { groups: groupDiffObjects(objects) });+ tree.mount(host);+ try {+ expect(host.textContent).toContain("PACKAGE P");+ expect(host.textContent).toContain("PACKAGE BODY P");+ } finally {+ tree.unmount();+ }+});diff --git a/apps/desktop/src/components/editor/DangerConfirmDialog.vue b/apps/desktop/src/components/editor/DangerConfirmDialog.vueindex 03cb544cbb..0e02392a06 100644--- a/apps/desktop/src/components/editor/DangerConfirmDialog.vue+++ b/apps/desktop/src/components/editor/DangerConfirmDialog.vue@@ -131,7 +131,7 @@ async function copyFullCode() {<template><Dialog v-model:open="dialogOpen">- <DialogContent class="sm:max-w-[480px]" @open-auto-focus="onDangerDialogOpenAutoFocus" @close-auto-focus="onDangerDialogCloseAutoFocus">+ <DialogContent :class="$slots.preview ? 'flex h-[85vh] min-h-0 flex-col sm:max-w-[1120px]' : 'sm:max-w-[480px]'" @open-auto-focus="onDangerDialogOpenAutoFocus" @close-auto-focus="onDangerDialogCloseAutoFocus"><DialogHeader><DialogTitle class="flex items-center gap-2 text-destructive"><AlertTriangle class="h-5 w-5" />@@ -139,29 +139,31 @@ async function copyFullCode() {</DialogTitle></DialogHeader>- <div class="py-4 min-w-0">+ <div class="py-4 min-w-0" :class="{ 'flex min-h-0 flex-1 flex-col': $slots.preview }"><p class="text-sm text-muted-foreground mb-3">{{ message || t("dangerDialog.message") }}</p><p v-if="detailsText" class="text-xs text-muted-foreground mb-3 whitespace-pre-line max-h-40 overflow-auto">{{ detailsText }}</p><slot name="options" />- <component :is="detailsLabel ? 'details' : 'div'" v-if="code" data-testid="danger-code-container" class="min-w-0">- <summary v-if="detailsLabel" class="mb-2 cursor-pointer text-sm text-muted-foreground">{{ detailsLabel }}</summary>- <div data-testid="danger-code-actions" class="mb-1 flex items-center justify-end gap-0.5">- <Button variant="ghost" size="icon-xs" class="h-6 w-6 text-muted-foreground" :title="t('dangerDialog.copyFullText')" @click="copyFullCode">- <Check v-if="copied" class="h-3.5 w-3.5 text-emerald-600" />- <Copy v-else class="h-3.5 w-3.5" />- </Button>- <Button variant="ghost" size="icon-xs" class="h-6 w-6" :class="wrap ? 'text-foreground bg-accent' : 'text-muted-foreground'" :title="t('dangerDialog.wrapLines')" @click="wrap = !wrap">- <TextWrap class="h-3.5 w-3.5" />- </Button>- </div>- <div data-native-clipboard data-testid="danger-code-preview" class="max-h-40 min-w-0 overflow-auto rounded bg-muted px-3 py-3 text-xs font-mono">- <pre class="font-inherit" :class="wrap ? 'w-full whitespace-pre-wrap break-all' : 'w-max min-w-full whitespace-pre'" v-html="highlightedHead" />- <div v-if="preview.truncated" data-testid="danger-preview-truncated" class="my-2 rounded border border-border/70 bg-background/70 px-2 py-1.5 text-center text-[11px] leading-4 text-muted-foreground whitespace-normal">- {{ t("dangerDialog.previewTruncated", { lines: preview.omittedLines.toLocaleString(), characters: preview.omittedCharacters.toLocaleString() }) }}+ <slot name="preview">+ <component :is="detailsLabel ? 'details' : 'div'" v-if="code" data-testid="danger-code-container" class="min-w-0">+ <summary v-if="detailsLabel" class="mb-2 cursor-pointer text-sm text-muted-foreground">{{ detailsLabel }}</summary>+ <div data-testid="danger-code-actions" class="mb-1 flex items-center justify-end gap-0.5">+ <Button variant="ghost" size="icon-xs" class="h-6 w-6 text-muted-foreground" :title="t('dangerDialog.copyFullText')" @click="copyFullCode">+ <Check v-if="copied" class="h-3.5 w-3.5 text-emerald-600" />+ <Copy v-else class="h-3.5 w-3.5" />+ </Button>+ <Button variant="ghost" size="icon-xs" class="h-6 w-6" :class="wrap ? 'text-foreground bg-accent' : 'text-muted-foreground'" :title="t('dangerDialog.wrapLines')" @click="wrap = !wrap">+ <TextWrap class="h-3.5 w-3.5" />+ </Button></div>- <pre v-if="preview.tail" class="font-inherit" :class="wrap ? 'w-full whitespace-pre-wrap break-all' : 'w-max min-w-full whitespace-pre'" v-html="highlightedTail" />- </div>- </component>+ <div data-native-clipboard data-testid="danger-code-preview" class="max-h-40 min-w-0 overflow-auto rounded bg-muted px-3 py-3 text-xs font-mono">+ <pre class="font-inherit" :class="wrap ? 'w-full whitespace-pre-wrap break-all' : 'w-max min-w-full whitespace-pre'" v-html="highlightedHead" />+ <div v-if="preview.truncated" data-testid="danger-preview-truncated" class="my-2 rounded border border-border/70 bg-background/70 px-2 py-1.5 text-center text-[11px] leading-4 text-muted-foreground whitespace-normal">+ {{ t("dangerDialog.previewTruncated", { lines: preview.omittedLines.toLocaleString(), characters: preview.omittedCharacters.toLocaleString() }) }}+ </div>+ <pre v-if="preview.tail" class="font-inherit" :class="wrap ? 'w-full whitespace-pre-wrap break-all' : 'w-max min-w-full whitespace-pre'" v-html="highlightedTail" />+ </div>+ </component>+ </slot><div v-if="showSuppressToggle" class="mt-3 flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2"><Label for="danger-confirm-suppress" class="text-sm leading-5">{{ suppressToggleLabel || t("dangerDialog.suppressFuturePrompts") }}</Label><Switch id="danger-confirm-suppress" v-model="suppressFuturePrompts" />diff --git a/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts b/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.tsindex a54762d51b..6a9d60ab06 100644--- a/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts+++ b/apps/desktop/src/components/editor/__tests__/DangerConfirmDialog.spec.ts@@ -31,22 +31,26 @@ vi.mock("@/lib/common/clipboard", () => ({const mountedApps: App[] = [];-async function mountDialog(sql: string, extraProps: Record<string, unknown> = {}, listeners: Record<string, (...args: any[]) => void> = {}) {+async function mountDialog(sql: string, extraProps: Record<string, unknown> = {}, listeners: Record<string, (...args: any[]) => void> = {}, previewSlot?: () => ReturnType<typeof h>) {const state = reactive({ open: true });const container = document.createElement("div");document.body.append(container);const app = createApp(defineComponent({setup: () => () =>- h(DangerConfirmDialog, {- open: state.open,- sql,- ...extraProps,- ...listeners,- "onUpdate:open": (value: boolean) => {- state.open = value;+ h(+ DangerConfirmDialog,+ {+ open: state.open,+ sql,+ ...extraProps,+ ...listeners,+ "onUpdate:open": (value: boolean) => {+ state.open = value;+ },},- }),+ previewSlot ? { preview: previewSlot } : undefined,+ ),}),);mountedApps.push(app);@@ -66,6 +70,29 @@ afterEach(() => {});describe("DangerConfirmDialog SQL preview", () => {+ it("hosts editable review in the existing confirmation and keeps its final action disabled until validation", async () => {+ const confirmed = vi.fn();+ const draft = reactive({ sql: "CREATE PACKAGE P AS END;" });+ await mountDialog(draft.sql, { confirmDisabled: true, closeOnConfirm: false, confirmLabel: "Start reviewed transfer" }, { onConfirm: confirmed }, () =>+ h("textarea", {+ value: draft.sql,+ onInput: (event: Event) => {+ draft.sql = (event.target as HTMLTextAreaElement).value;+ },+ }),+ );+ expect(document.body.querySelector('[data-testid="danger-code-preview"]')).toBeNull();+ const input = document.body.querySelector("textarea")!;+ input.value = "CREATE PACKAGE P AS n NUMBER; END;";+ input.dispatchEvent(new Event("input"));+ await nextTick();+ expect(draft.sql).toContain("n NUMBER");+ const confirm = [...document.body.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Start reviewed transfer")!;+ expect(confirm.disabled).toBe(true);+ confirm.click();+ expect(confirmed).not.toHaveBeenCalled();+ });+it("starts optional details collapsed and keeps the complete SQL available to copy", async () => {const sql = "CREATE TABLE target (id NUMBER);";await mountDialog(sql, { detailsLabel: "View SQL" });diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex 9186588f09..cede7f9c12 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -122,7 +122,7 @@ import OracleTableRenamePreview from "@/components/objects/OracleTableRenamePrevimport OracleRoutineRenamePreview from "@/components/objects/OracleRoutineRenamePreview.vue";import OraclePackageSaveAsDialog from "@/components/objects/OraclePackageSaveAsDialog.vue";import OracleInvalidObjectsDialog from "@/components/objects/OracleInvalidObjectsDialog.vue";-import { executeOraclePackageSaveAs, OraclePackageSaveAsFailure, prepareOraclePackageSaveAs, type OraclePackageSaveAsPlan } from "@/lib/table/oraclePackageSaveAs";+import { prepareOraclePackageSaveAsExecution, OraclePackageSaveAsFailure, prepareOraclePackageSaveAs, type OraclePackageSaveAsPlan } from "@/lib/table/oraclePackageSaveAs";import { isTauriRuntime } from "@/lib/backend/tauriRuntime";import { autoRevealExportedPathIfConfigured, promptExportSavePath } from "@/lib/export/exportPath";import { generateDatabaseExportId } from "@/lib/export/databaseExport";@@ -2366,18 +2366,12 @@ async function confirmPackageSaveAs() {packageSaveAsName.value.trim() === plan.target.newName);};+ let prepared: Awaited<ReturnType<typeof prepareOraclePackageSaveAsExecution>> | undefined;try {+ prepared = await prepareOraclePackageSaveAsExecution(plan, isCurrentPlan);+ const execute = prepared;const executed = await executeObjectBrowserSqlWithProductionGuard(plan.statements.join("\n\n"), async () => {- await executeOraclePackageSaveAs(- plan,- () =>- packageSaveAsPlan.value === plan &&- packageSaveAsOpen.value &&- packageSaveAsTarget.value?.name === plan.target.oldName &&- props.connection.id === plan.target.connectionId &&- props.database === plan.target.database &&- (row.schema || selectedSchema.value || props.database) === plan.target.schema,- );+ await execute();return true;});if (!executed) return;@@ -2400,6 +2394,7 @@ async function confirmPackageSaveAs() {}}} finally {+ await prepared?.dispose();packageSaveAsExecuting.value = false;}}diff --git a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.ts b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.tsindex 6befe6c953..11715055fb 100644--- a/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/ObjectSourceDialog.oceanbaseSequence.spec.ts@@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => ({loadTunnelProfiles: vi.fn(),loadTableVGroups: vi.fn(),loadSidebarLayout: vi.fn(),+ listInstalledAgents: vi.fn(),prepareOracleRoutineSave: vi.fn(),updateOracleRoutineOperationReferences: vi.fn(async () => {}),executeOracleRoutineOperation: vi.fn(),@@ -44,8 +45,9 @@ beforeEach(() => {throw new Error(`Unexpected HTTP boundary: ${String(input)}`);});});-afterEach(() => {+afterEach(async () => {for (const cleanup of cleanups.splice(0)) cleanup();+ await vi.dynamicImportSettled();vi.restoreAllMocks();for (const mock of Object.values(mocks)) mock.mockReset();expect(unexpectedHttp).toEqual([]);@@ -74,6 +76,7 @@ async function mount(options: { databaseType?: DatabaseType; initialEditing?: bomocks.loadTunnelProfiles.mockResolvedValue([]);mocks.loadTableVGroups.mockResolvedValue({});mocks.loadSidebarLayout.mockResolvedValue(null);+ mocks.listInstalledAgents.mockResolvedValue([]);mocks.getObjectSource.mockResolvedValue({ name: "SEQ", schema: "APP", object_type: objectType, source, editable: options.editable !== false });mocks.buildEditableObjectSource.mockResolvedValue(objectType === "SEQUENCE" && databaseType === "oceanbase-oracle" ? alter : source);mocks.buildExecutableObjectSourceStatements.mockResolvedValue([objectType === "SEQUENCE" ? alter : source]);diff --git a/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts b/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.tsindex 6bf4836cb8..1d69b8ef0c 100644--- a/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts+++ b/apps/desktop/src/components/objects/__tests__/OceanbaseClone.entrypoints.spec.ts@@ -13,7 +13,7 @@ import * as api from "@/lib/backend/api";import { OraclePackageSaveAsFailure, type OraclePackageSaveAsPlan } from "@/lib/table/oraclePackageSaveAs";const backend = vi.hoisted(() => ({ executeQuery: vi.fn(), buildCreateTableSql: vi.fn(), buildCopyTableDataSql: vi.fn() }));-const packageSaveAs = vi.hoisted(() => ({ prepare: vi.fn(), execute: vi.fn() }));+const packageSaveAs = vi.hoisted(() => ({ prepare: vi.fn(), prepareExecution: vi.fn(), execute: vi.fn(), dispose: vi.fn() }));vi.mock("@/lib/backend/api", async (importOriginal) => ({...(await importOriginal<typeof import("@/lib/backend/api")>()),...backend,@@ -34,7 +34,7 @@ vi.mock("@/lib/backend/api", async (importOriginal) => ({}));vi.mock("@/lib/table/oraclePackageSaveAs", async (importOriginal) => {const actual = await importOriginal<typeof import("@/lib/table/oraclePackageSaveAs")>();- return { ...actual, prepareOraclePackageSaveAs: (...args: unknown[]) => packageSaveAs.prepare(...args), executeOraclePackageSaveAs: (...args: unknown[]) => packageSaveAs.execute(...args) };+ return { ...actual, prepareOraclePackageSaveAs: (...args: unknown[]) => packageSaveAs.prepare(...args), prepareOraclePackageSaveAsExecution: (...args: unknown[]) => packageSaveAs.prepareExecution(...args) };});const result = (rows: unknown[][] = []) => ({ columns: [], rows, affected_rows: 0, execution_time_ms: 0 });@@ -63,6 +63,8 @@ beforeEach(() => {backend.buildCopyTableDataSql.mockResolvedValue('INSERT INTO "APP"."MixedCopy" SELECT * FROM "APP"."SOURCE"');packageSaveAs.prepare.mockReset();packageSaveAs.execute.mockReset();+ packageSaveAs.dispose.mockReset().mockResolvedValue(undefined);+ packageSaveAs.prepareExecution.mockReset().mockImplementation(async (...args: unknown[]) => Object.assign(() => packageSaveAs.execute(...args), { dispose: packageSaveAs.dispose }));backend.executeQuery.mockImplementation(async (_id, _db, sql: string) => {if (sql.includes("ALL_TAB_COMMENTS")) return result([["source comment"]]);if (sql.includes("ALL_TABLES")) return result([["NO", "N"]]);@@ -533,6 +535,21 @@ async function beginPackageSaveAs(surface: "sidebar" | "objects") {}describe.each(["sidebar", "objects"] as const)("%s Oracle package Save As failure refresh", (surface) => {+ it("binds the execution before production confirmation and releases the unused approval on cancel", async () => {+ connection.is_production = true;+ const { controller, plan } = await beginPackageSaveAs(surface);+ const pending = controller.confirmPackageSaveAs();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending).toMatchObject({ sql: plan.statements.join("\n\n") }));+ expect(packageSaveAs.prepareExecution).toHaveBeenCalledExactlyOnceWith(plan, expect.any(Function));+ expect(packageSaveAs.execute).not.toHaveBeenCalled();+ safety.cancel();+ await pending;+ expect(packageSaveAs.execute).not.toHaveBeenCalled();+ expect(packageSaveAs.dispose).toHaveBeenCalledOnce();+ expect(controller.packageSaveAsOpen).toBe(true);+ });+it("refreshes the target tree and keeps the failed plan editable for recovery", async () => {const { controller, refresh, plan } = await beginPackageSaveAs(surface);packageSaveAs.execute.mockRejectedValue(new OraclePackageSaveAsFailure(plan, ["PACKAGE P_NEW"], "PACKAGE BODY P_NEW", new Error("body failed"), true));diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vueindex 469faabc87..ce8e8f95bf 100644--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue@@ -208,7 +208,7 @@ import { buildRenameObjectSql, buildRenameDatabaseSql, buildRenameDatabasePrefliimport { prepareOracleViewRename, executeOracleViewRename, OracleViewRenameFailure, type OracleViewRenamePlan } from "@/lib/table/oracleViewRename";import { prepareOracleRoutineRename, executeOracleRoutineRename, OracleRoutineRenameFailure, type OracleRoutineRenamePlan } from "@/lib/table/oracleRoutineRename";import { prepareOracleTableRename, executeOracleTableRename, OracleTableRenameFailure, type OracleTableRenamePlan } from "@/lib/table/oracleTableRename";-import { executeOraclePackageSaveAs, OraclePackageSaveAsFailure, prepareOraclePackageSaveAs, type OraclePackageSaveAsPlan } from "@/lib/table/oraclePackageSaveAs";+import { prepareOraclePackageSaveAsExecution, OraclePackageSaveAsFailure, prepareOraclePackageSaveAs, type OraclePackageSaveAsPlan } from "@/lib/table/oraclePackageSaveAs";import { buildRoutineRenameObjectSourceStatements, executeObjectSourceSave, supportsSourceBackedRoutineRename } from "@/lib/table/objectSourceEditor";import { freezeSourceIdentities } from "@/lib/table/objectSourceIdentity";import { buildViewDdl } from "@/lib/table/viewDdl";@@ -4136,24 +4136,14 @@ async function confirmPackageSaveAs() {packageSaveAsName.value.trim() === plan.target.newName);};+ let prepared: Awaited<ReturnType<typeof prepareOraclePackageSaveAsExecution>> | undefined;try {await connectionStore.ensureConnected(target.connectionId);+ prepared = await prepareOraclePackageSaveAsExecution(plan, isCurrentPlan);+ const execute = prepared;const executed = await executeTreeNodeSqlWithProductionGuard(target, plan.statements.join("\n\n"), {execute: async () => {- await executeOraclePackageSaveAs(plan, () => {- const current = packageSaveAsTarget.value;- return (- packageSaveAsPlan.value === plan &&- packageSaveAsOpen.value &&- !!current &&- current.connectionId === plan.target.connectionId &&- current.database === plan.target.database &&- (current.schema || current.database) === plan.target.schema &&- (current.objectName || current.label) === plan.target.oldName &&- packageSaveAsName.value.trim() === plan.target.newName &&- databaseTypeForNode(current) === plan.target.databaseType- );- });+ await execute();return { columns: [], rows: [], affected_rows: 0, execution_time_ms: 0 };},});@@ -4175,6 +4165,7 @@ async function confirmPackageSaveAs() {}}} finally {+ await prepared?.dispose();packageSaveAsExecuting.value = false;}}diff --git a/apps/desktop/src/components/transfer/DataTransferDialog.vue b/apps/desktop/src/components/transfer/DataTransferDialog.vueindex bbadd579fe..68e4930dc4 100644--- a/apps/desktop/src/components/transfer/DataTransferDialog.vue+++ b/apps/desktop/src/components/transfer/DataTransferDialog.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { computed, onBeforeUnmount, ref, shallowRef, watch } from "vue";+import { computed, onBeforeUnmount, reactive, ref, shallowRef, watch } from "vue";import { uuid } from "@/lib/common/utils";import { useI18n } from "vue-i18n";import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";@@ -19,10 +19,12 @@ import {transferStrategyOptions,TRANSFER_STRUCTURE_PREVIEW_UNAVAILABLE,type TransferStrategy,+ type TransferPackageConfirmation,} from "./transferStrategy";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { Switch } from "@/components/ui/switch";import SearchableSelect from "@/components/ui/searchable-select/SearchableSelect.vue";import ConnectionTreeSelect from "@/components/connection/ConnectionTreeSelect.vue";@@ -36,8 +38,24 @@ import ObjectSelectionTree from "@/components/transfer/ObjectSelectionTree.vue";import TransferTaskTree from "@/components/transfer/TransferTaskTree.vue";import DataTransferProgressDialog from "@/components/transfer/DataTransferProgressDialog.vue";import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";+import SqlPreviewPanel from "@/components/editor/SqlPreviewPanel.vue";+import SchemaDiffDeployStep from "@/components/diff/SchemaDiffDeployStep.vue";+import {+ createOracleRoutineDeployment,+ oraclePackageTransferPendingReady,+ disposeOracleRoutineDeployment,+ editOracleRoutineDraft,+ editOraclePackageOptions,+ includeOraclePackageCompanion,+ refreshOracleRoutineDeployment,+ reviewOraclePackageTargetDraft,+ selectOracleRoutineDraft,+ validateOracleRoutineDeployment,+ type OracleRoutineDeployment,+} from "@/lib/schema/oracleRoutineDeploy";+import { normalizeSchemaDiffCompareOptions, type OracleRoutinePlanInput } from "@/types/schemaDiff";import type { DatabaseType } from "@/types/database";-import type { TransferTask, TransferTaskConfig } from "@/types/database";+import type { TransferPackageDraft, TransferTask, TransferTaskConfig } from "@/types/database";import { isSchemaAware, supportsTransfer } from "@/lib/database/databaseCapabilities";import { transferDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";import { isDorisFamilyCatalogCapable } from "@/lib/database/databaseFeatureSupport";@@ -46,7 +64,9 @@ import { formatDatabaseLabel } from "@/lib/database/defaultDatabase";import { DEFAULT_QUERY_TIMEOUT_SECS, MAX_QUERY_TIMEOUT_SECS } from "@/lib/connection/timeoutLimits";import { databaseOptionsForConnection, fetchCatalogNamespaceOptions, fetchNamespaceOptionsForConnection, namespaceOptionsAreSchemas } from "@/composables/useDatabaseOptions";import { useExportTracker } from "@/composables/useExportTracker";-import { openDataTransferTask } from "@/composables/useDialogSources";+import { openDataTransferTask, openSchemaDiffSession } from "@/composables/useDialogSources";+import { startSchemaDiffSession } from "@/composables/useSchemaDiffSession";+import { createSchemaDiffTableListLoader } from "@/lib/schema/schemaDiffTableList";import { useTransferTaskStore, TransferTaskNameConflictError, nextTransferTaskCopyName } from "@/stores/transferTaskStore";import { useToast } from "@/composables/useToast";import type { CatalogInfo } from "@/types/database";@@ -125,6 +145,7 @@ const OBJECT_KIND_LABEL_KEY: Record<TransferObjectKind, string> = {SEQUENCE: "transfer.objectTypeSequence",EVENT: "transfer.objectTypeEvent",PACKAGE: "tree.packages",+ PACKAGE_BODY: "objects.packageBody",SYNONYM: "tree.synonyms",};@@ -237,6 +258,19 @@ const pendingTransferId = ref<string | null>(null);const showStartConfirm = ref(false);const confirmationRequest = shallowRef<api.TransferRequest | null>(null);const confirmationPreview = shallowRef<api.TransferOwnershipPreview | null>(null);+const packageDeployment = shallowRef<OracleRoutineDeployment | null>(null);+const packagePreparedInput = shallowRef<OracleRoutinePlanInput | null>(null);+const packageComparisonLoading = ref(false);+const packagePreviewTab = ref("routines");+const packageTableName = ref("");+const packageTablePreview = computed(() => confirmationPreview.value?.structure?.tables.find((table) => table.sourceTable === packageTableName.value) ?? confirmationPreview.value?.structure?.tables[0]);+const savedPackageDrafts = shallowRef<{ context: string; drafts: TransferPackageDraft[] } | null>(null);+const packageDraftSql = computed(() => packageDeployment.value?.drafts.find((draft) => draft.objectId === packageDeployment.value?.selectedObjectId)?.sql ?? "");+const packageReady = computed(() => {+ const state = packageDeployment.value;+ const preview = confirmationPreview.value?.oraclePackages;+ return !packageComparisonLoading.value && (!state || (!state.disposed && !state.validating && !state.error && (!!state.plan?.ready || (!!preview && oraclePackageTransferPendingReady(state, preview)))));+});let resolveTransferConfirmation: ((confirmed: boolean) => void) | undefined;const ownershipDialogOpen = ref(false);const ownershipMissingOwners = ref<string[]>([]);@@ -773,45 +807,64 @@ watch(targetDatabase, async (db) => {}});+async function applyTransferPrefill() {+ resetState();+ pendingSourceSchemaPrefill.value = props.prefillSchema ?? "";+ pendingSelectedTablesPrefill.value = props.prefillTables?.length ? [...props.prefillTables] : null;+ pendingTargetSchemaPrefill.value = props.prefillTargetSchema ?? "";+ if (props.prefillConnectionId) {+ skipSourceWatch.value = true;+ sourceConnectionId.value = props.prefillConnectionId;+ if (isCatalogCapable(props.prefillConnectionId)) {+ await loadCatalogs(props.prefillConnectionId, "source");+ if (props.prefillCatalog) {+ sourceCatalog.value = props.prefillCatalog;+ }+ if (sourceCatalog.value) {+ await loadDatabasesForCatalog(props.prefillConnectionId, sourceCatalog.value, "source");+ }+ } else {+ await loadDatabases(props.prefillConnectionId, "source");+ }+ if (props.prefillDatabase !== undefined) sourceDatabase.value = encodedDatabase(props.prefillConnectionId, props.prefillDatabase);+ }+ if (props.prefillTargetConnectionId) {+ skipTargetWatch.value = true;+ targetConnectionId.value = props.prefillTargetConnectionId;+ if (isCatalogCapable(props.prefillTargetConnectionId)) {+ await loadCatalogs(props.prefillTargetConnectionId, "target");+ if (targetCatalog.value) {+ await loadDatabasesForCatalog(props.prefillTargetConnectionId, targetCatalog.value, "target");+ }+ } else {+ await loadDatabases(props.prefillTargetConnectionId, "target");+ }+ if (props.prefillTargetDatabase !== undefined) targetDatabase.value = encodedDatabase(props.prefillTargetConnectionId, props.prefillTargetDatabase);+ }+}+watch([open, () => props.taskId],async ([val, taskId]) => {- if (val && !taskId) {- void taskStore.initFromStorage();- resetState();- pendingSourceSchemaPrefill.value = props.prefillSchema ?? "";- pendingSelectedTablesPrefill.value = props.prefillTables?.length ? [...props.prefillTables] : null;- pendingTargetSchemaPrefill.value = props.prefillTargetSchema ?? "";- if (props.prefillConnectionId) {- skipSourceWatch.value = true;- sourceConnectionId.value = props.prefillConnectionId;- if (isCatalogCapable(props.prefillConnectionId)) {- await loadCatalogs(props.prefillConnectionId, "source");- if (props.prefillCatalog) {- sourceCatalog.value = props.prefillCatalog;- }- if (sourceCatalog.value) {- await loadDatabasesForCatalog(props.prefillConnectionId, sourceCatalog.value, "source");- }- } else {- await loadDatabases(props.prefillConnectionId, "source");- }- if (props.prefillDatabase !== undefined) sourceDatabase.value = encodedDatabase(props.prefillConnectionId, props.prefillDatabase);- }- if (props.prefillTargetConnectionId) {- skipTargetWatch.value = true;- targetConnectionId.value = props.prefillTargetConnectionId;- if (isCatalogCapable(props.prefillTargetConnectionId)) {- await loadCatalogs(props.prefillTargetConnectionId, "target");- if (targetCatalog.value) {- await loadDatabasesForCatalog(props.prefillTargetConnectionId, targetCatalog.value, "target");- }- } else {- await loadDatabases(props.prefillTargetConnectionId, "target");- }- if (props.prefillTargetDatabase !== undefined) targetDatabase.value = encodedDatabase(props.prefillTargetConnectionId, props.prefillTargetDatabase);- }+ if (!val || taskId) return;+ void taskStore.initFromStorage();+ if (currentConfig().oraclePackageDrafts?.length) {+ const sameContext = [+ [props.prefillConnectionId, sourceConnectionId.value],+ [props.prefillDatabase, sourceDatabaseName.value],+ [props.prefillCatalog, sourceCatalog.value],+ [props.prefillSchema, sourceSchema.value || sourceDatabaseName.value],+ [props.prefillTargetConnectionId, targetConnectionId.value],+ [props.prefillTargetDatabase, targetDatabaseName.value],+ [props.prefillTargetSchema, targetSchema.value || targetDatabaseName.value],+ ].every(([requested, current]) => !requested || requested === current);+ if (sameContext && !props.prefillTables?.length) return;+ requestDiscardableAction(() => {+ void applyTransferPrefill();+ });+ return;}+ await applyTransferPrefill();},{ immediate: true },);@@ -819,6 +872,8 @@ watch(function resetState(cancelTaskLoad = true) {if (cancelTaskLoad) taskLoadTracker.cancel();cancelPendingTransfer();+ packageDeployment.value = null;+ savedPackageDrafts.value = null;sourceConnectionId.value = "";sourceCatalog.value = "";sourceCatalogs.value = [];@@ -974,6 +1029,15 @@ async function requestStartTransfer() {tableFilters: requestedTableFilters(),dropTargetConfirmed: false,};+ if (request.content !== "dataOnly") {+ for (const kind of ["PACKAGE", "PACKAGE_BODY"] as const) {+ const names = currentConfig().objects[kind];+ if (!names?.length) continue;+ const selection = request.objects.find((selection) => selection.objectType === kind);+ if (selection) selection.names = [...names];+ else request.objects.push({ objectType: kind, names: [...names] });+ }+ }pendingTransferId.value = request.transferId;try {await transferSubmission.start(request);@@ -990,7 +1054,15 @@ async function requestStartTransfer() {function runTransfer(request: api.TransferRequest, shouldRefreshTargetTree: boolean) {isSubmitting.value = true;+ rememberTransferPackageDrafts();+ const deployment = packageDeployment.value;startDataTransferTask(request, `${request.sourceDatabase} → ${request.targetDatabase}`, {+ oracleRoutineDeployment: deployment ?? undefined,+ onRemove: deployment+ ? () => {+ void disposeOracleRoutineDeployment(deployment);+ }+ : undefined,formatOverlapError: (tables) => t("transfer.targetTableBusy", { tables: tables.join(", ") }),onStarted: () => toast(t("transfer.backgroundStarted")),onOpen: () => openDataTransferTask(request.transferId),@@ -1000,6 +1072,9 @@ function runTransfer(request: api.TransferRequest, shouldRefreshTargetTree: bool}},});+ // The background task now owns the same retained approvals and editable+ // results; closing this form must not release them before the server claims.+ packageDeployment.value = null;open.value = false;resetState();}@@ -1033,12 +1108,12 @@ function getConnectionName(id: string) {const activeTaskName = computed(() => (activeTaskId.value ? (taskStore.getTask(activeTaskId.value)?.name ?? "") : ""));/** Builds a serializable config from the current form state. */-function currentConfig(): TransferTaskConfig {+function currentConfig(includePackageDrafts = true): TransferTaskConfig {const objects: TransferTaskConfig["objects"] = {};for (const [kind, names] of Object.entries(selectedObjects.value)) {if (names && names.size > 0) objects[kind as TransferObjectKind] = [...names];}- return {+ const config: TransferTaskConfig = {sourceConnectionId: sourceConnectionId.value,sourceCatalog: normalizeTransferCatalog(sourceCatalog.value, sourceCatalogs.value) || undefined,sourceDatabase: sourceDatabaseName.value,@@ -1058,6 +1133,16 @@ function currentConfig(): TransferTaskConfig {tableFilters: requestedTableFilters(),dropTargetConfirmed: false,};+ if (includePackageDrafts) {+ const state = packageDeployment.value;+ const context = packageDraftContext(config);+ const drafts = state && !state.disposed && confirmationRequest.value && packageDraftContext(confirmationRequest.value) === context ? transferPackageDrafts(state) : savedPackageDrafts.value?.context === context ? savedPackageDrafts.value.drafts : undefined;+ const selectedDrafts = drafts?.filter((draft) => (draft.identity.kind === "PACKAGE" || draft.identity.kind === "PACKAGE_BODY") && config.objects[draft.identity.kind]?.includes(draft.sourceName ?? draft.identity.name));+ if (selectedDrafts?.length) {+ config.oraclePackageDrafts = selectedDrafts;+ }+ }+ return config;}/** Canonical serialization (sorted kinds/names) for stable dirty comparison. */@@ -1077,7 +1162,14 @@ const canSaveConfig = computed(() => !!sourceConnectionId.value && isTransferDat// Invalidate before asynchronous callbacks can publish a preview for an old form,// including a task switch whose new values happen to equal the previous task.-watch(() => configSnapshot(currentConfig()), cancelPendingTransfer, { flush: "sync" });+let addingPackageCompanion = false;+watch(+ () => configSnapshot(currentConfig(false)),+ () => {+ if (!addingPackageCompanion) cancelPendingTransfer();+ },+ { flush: "sync" },+);watch(activeTaskId, cancelPendingTransfer, { flush: "sync" });watch(open,@@ -1185,6 +1277,7 @@ async function loadTaskIntoForm(task: TransferTask) {}if (isTaskLoadStale()) return;+ savedPackageDrafts.value = config.oraclePackageDrafts?.length ? { context: packageDraftContext(config), drafts: JSON.parse(JSON.stringify(config.oraclePackageDrafts)) } : null;savedConfigSnapshot.value = configSnapshot(currentConfig());}@@ -1315,13 +1408,195 @@ function transferPreviewFailureMessage(message: string): string {return t("transfer.previewFailed", { message });}-function requestTransferConfirmation(request: api.TransferRequest, preview: api.TransferOwnershipPreview): Promise<boolean> {+function packageDraftContext(config: Pick<TransferTaskConfig, "sourceConnectionId" | "sourceDatabase" | "sourceSchema" | "sourceCatalog" | "targetConnectionId" | "targetDatabase" | "targetSchema" | "targetCatalog">): string {+ return JSON.stringify([config.sourceConnectionId, config.sourceCatalog ?? "", config.sourceDatabase, config.sourceSchema || config.sourceDatabase, config.targetConnectionId, config.targetCatalog ?? "", config.targetDatabase, config.targetSchema || config.targetDatabase]);+}++function transferPackageDrafts(state: OracleRoutineDeployment): TransferPackageDraft[] {+ return state.drafts+ .filter((draft) => draft.included)+ .map((draft) => ({+ identity: { ...draft.identity },+ sourceName: draft.sourceName,+ sql: draft.sql,+ packageBodySource: draft.packageBodySource,+ packageContract: draft.packageContract,+ confirmPackagePair: draft.confirmPackagePair,+ reviewedTargetDraft: draft.reviewedTargetDraft,+ }));+}++function includeTransferPackageCompanion(objectId: string, source: "source" | "target") {+ const state = packageDeployment.value;+ if (!state) return;+ const draft = includeOraclePackageCompanion(state, objectId, source);+ if (!draft || (draft.identity.kind !== "PACKAGE" && draft.identity.kind !== "PACKAGE_BODY")) return;+ addingPackageCompanion = true;+ try {+ const names = new Set(selectedObjects.value[draft.identity.kind] ?? []);+ names.add(draft.sourceName ?? draft.identity.name);+ selectedObjects.value = { ...selectedObjects.value, [draft.identity.kind]: names };+ } finally {+ addingPackageCompanion = false;+ }+}++function rememberTransferPackageDrafts() {+ const state = packageDeployment.value;+ const request = confirmationRequest.value;+ if (state && request && !state.disposed) savedPackageDrafts.value = { context: packageDraftContext(request), drafts: transferPackageDrafts(state) };+}++function packageTransferObjects(request: api.TransferRequest): api.TransferRequest["objects"] {+ const objects = request.objects.map((selection) => ({ ...selection, names: [...selection.names] }));+ for (const draft of packageDeployment.value?.drafts.filter((draft) => draft.included) ?? []) {+ const kind = draft.identity.kind;+ if (kind !== "PACKAGE" && kind !== "PACKAGE_BODY") continue;+ let selection = objects.find((selection) => selection.objectType === kind);+ if (!selection) objects.push((selection = { objectType: kind, names: [] }));+ const name = draft.sourceName ?? draft.identity.name;+ if (!selection.names.includes(name)) selection.names.push(name);+ }+ return objects;+}++async function compareTransferPackages() {+ const request = confirmationRequest.value;+ const packages = confirmationPreview.value?.oraclePackages;+ const state = packageDeployment.value;+ if (!request || !packages || packageComparisonLoading.value || state?.validating || state?.executing) return;+ const source = store.getConfig(request.sourceConnectionId);+ const target = store.getConfig(request.targetConnectionId);+ if (!source || !target) return;+ packageComparisonLoading.value = true;+ try {+ const selected = packageTransferObjects(request).flatMap((selection) => (selection.objectType === "PACKAGE" || selection.objectType === "PACKAGE_BODY" ? selection.names.map((name) => ({ name, kind: selection.objectType as "PACKAGE" | "PACKAGE_BODY" })) : []));+ const session = startSchemaDiffSession(+ {+ sourceConnectionId: request.sourceConnectionId,+ sourceDatabase: request.sourceDatabase,+ sourceSchema: request.sourceSchema,+ targetConnectionId: request.targetConnectionId,+ targetDatabase: request.targetDatabase,+ targetSchema: request.targetSchema,+ sourceDbType: source.db_type,+ targetDbType: target.db_type,+ sourceEngineDbType: packages.input.source.endpoint.databaseType,+ targetEngineDbType: packages.input.target.endpoint.databaseType,+ options: normalizeSchemaDiffCompareOptions({ tables: false, views: false, functions: true, sequences: false, rules: false, owners: false, routineObjectKinds: [...new Set(selected.map((object) => object.kind))], selectedRoutineObjects: selected }, packages.input.target.endpoint.databaseType),+ ignoreComments: false,+ label: `${getConnectionName(request.sourceConnectionId)} → ${getConnectionName(request.targetConnectionId)}`,+ },+ { tableListLoader: createSchemaDiffTableListLoader({ ensureConnected: (id) => store.ensureConnected(id), listTables: (id, database, schema) => api.listTables(id, database, schema) }) },+ {+ source: packages.input.source.endpoint,+ target: packages.input.target.endpoint,+ drafts: state ? transferPackageDrafts(state) : savedPackageDrafts.value?.context === packageDraftContext(request) ? savedPackageDrafts.value.drafts : [],+ },+ );+ if (session.status === "running")+ await new Promise<void>((resolve) => {+ const stop = watch(+ () => session.status,+ (status) => {+ if (status !== "running") {+ stop();+ resolve();+ }+ },+ );+ });+ if (confirmationRequest.value !== request) return;+ if (session.status === "failed") {+ toast(session.error ?? t("transfer.previewFailed", { message: "" }), 5000);+ return;+ }+ resolveStartDecision(false);+ openSchemaDiffSession(session.id);+ open.value = false;+ } finally {+ packageComparisonLoading.value = false;+ }+}++async function validateTransferPackages() {+ const state = packageDeployment.value;+ const request = confirmationRequest.value;+ if (!state || !request) return;+ const revision = state.revision;+ await validateOracleRoutineDeployment(state, async (input) => {+ const preview = await api.previewTransferOwnership({ ...request, objects: packageTransferObjects(request), oraclePackages: { input, operationIds: [] } });+ if (!preview.oraclePackages) throw new Error(TRANSFER_STRUCTURE_PREVIEW_UNAVAILABLE);+ if (packageDeployment.value === state && confirmationRequest.value === request && state.revision === revision && !state.disposed) {+ if (preview.oraclePackages.pendingTables) {+ if (state.drafts.some((draft) => draft.operation && (draft.operation.lifecycle !== "prepared" || draft.operation.dispatched || state.attemptedOperationIds.includes(draft.operation.operationId))))+ throw new Error("Establish the original package request's termination before changing this transfer preview");+ for (const draft of state.drafts) {+ draft.operation = undefined;+ draft.supersedesOperationId = undefined;+ }+ if (!confirmationPreview.value?.oraclePackages?.pendingTables) packagePreviewTab.value = "tables";+ }+ confirmationPreview.value = preview;+ packagePreparedInput.value = preview.oraclePackages.input;+ }+ return preview.oraclePackages.plan;+ });+}++async function refreshTransferPackages() {+ const state = packageDeployment.value;+ if (!state) return;+ await refreshOracleRoutineDeployment(state);+ if (!state.error && packageDeployment.value === state) await validateTransferPackages();+}++async function requestTransferConfirmation(request: api.TransferRequest, preview: api.TransferOwnershipPreview): Promise<boolean | TransferPackageConfirmation> {+ rememberTransferPackageDrafts();+ if (packageDeployment.value) await disposeOracleRoutineDeployment(packageDeployment.value);+ packageDeployment.value = null;+ packagePreparedInput.value = null;confirmationRequest.value = request;confirmationPreview.value = preview;+ packagePreviewTab.value = preview.structure?.tables.length ? "tables" : "routines";+ packageTableName.value = "";+ const packages = preview.oraclePackages;+ if (packages?.input.drafts.length) {+ const state = reactive(createOracleRoutineDeployment(packages.input.source, packages.input.target));+ const saved = savedPackageDrafts.value?.context === packageDraftContext(request) ? savedPackageDrafts.value.drafts : [];+ state.drafts = packages.input.drafts.map((draft, index) => ({ ...draft, ...saved.find((item) => item.identity.owner === draft.identity.owner && item.identity.name === draft.identity.name && item.identity.kind === draft.identity.kind), objectId: `transfer-package:${index}`, included: true }));+ state.selectedObjectId = state.drafts[0]?.objectId ?? null;+ packageDeployment.value = state;+ packagePreparedInput.value = packages.input;+ if (saved.length) await validateTransferPackages();+ else await validateOracleRoutineDeployment(state, async () => packages.plan);+ if (confirmationRequest.value !== request || state.disposed) return false;+ const accepted = await new Promise<boolean>((resolve) => {+ resolveTransferConfirmation = resolve;+ showSqlPreviewConfirm.value = true;+ });+ if (!accepted || !packageReady.value || packageDeployment.value !== state || !packagePreparedInput.value) return false;+ const revision = state.revision;+ const finalPreview = confirmationPreview.value!;+ const decision: TransferPackageConfirmation = JSON.parse(+ JSON.stringify({+ objects: packageTransferObjects(request),+ oraclePackages: { input: packagePreparedInput.value, operationIds: state.plan!.steps.flatMap((step) => (step.operation ? [step.operation.operationId] : [])), pendingTables: finalPreview.oraclePackages?.pendingTables },+ }),+ );+ const authorized = await confirmTransferWithProductionSafety({+ request,+ connection: store.getConfig(request.targetConnectionId),+ reviewText: transferPlanReviewText(confirmationStrategy.value, confirmationDetails.value, finalPreview),+ source: t("transfer.title"),+ confirm: async () => true,+ });+ return authorized && state.revision === revision && packageReady.value ? decision : false;+ }const reviewText = hasTransferSqlPreview(preview)? transferPlanReviewText(confirmationStrategy.value, confirmationDetails.value, preview): [confirmationSummary.value, `${t("transfer.targetTableHandling")}: ${confirmationStrategy.value}`, ...request.objects.map((selection) => selection.names.join(", "))].join("\n");- return confirmTransferWithProductionSafety({+ const accepted = await confirmTransferWithProductionSafety({request,connection: store.getConfig(request.targetConnectionId),reviewText,@@ -1333,9 +1608,12 @@ function requestTransferConfirmation(request: api.TransferRequest, preview: api.else showStartConfirm.value = true;}),});+ return accepted && packages ? { objects: request.objects, oraclePackages: { input: packages.input, operationIds: [] } } : accepted;}function resolveStartDecision(confirmed: boolean) {+ if (confirmed && !packageReady.value) return;+ rememberTransferPackageDrafts();const resolve = resolveTransferConfirmation;resolveTransferConfirmation = undefined;showStartConfirm.value = false;@@ -1345,6 +1623,8 @@ function resolveStartDecision(confirmed: boolean) {function cancelPendingTransfer() {transferSubmission.cancel();+ rememberTransferPackageDrafts();+ if (packageDeployment.value) void disposeOracleRoutineDeployment(packageDeployment.value);const scopeId = pendingTransferId.value;pendingTransferId.value = null;if (scopeId) productionSafetyStore.cancelScope(scopeId);@@ -1753,7 +2033,64 @@ async function saveConfigTask() {</DialogContent></Dialog>- <DangerConfirmDialog v-model:open="showSqlPreviewConfirm" :sql="confirmationSql" :title="confirmationTitle" :message="confirmationDangerMessage" :details-text="confirmationDetails" :confirm-label="t('transfer.start')" :close-on-confirm="false" @confirm="resolveStartDecision(true)" />+ <DangerConfirmDialog+ v-model:open="showSqlPreviewConfirm"+ :sql="confirmationSql"+ :title="confirmationTitle"+ :message="confirmationDangerMessage"+ :details-text="confirmationDetails"+ :confirm-label="t('transfer.start')"+ :confirm-disabled="!packageReady"+ :initial-focus="packageDeployment ? 'default' : 'confirm'"+ :close-on-confirm="false"+ @confirm="resolveStartDecision(true)"+ >+ <template v-if="confirmationPreview?.oraclePackages" #options>+ <div class="mb-3 space-y-2">+ <p v-if="confirmationPreview.oraclePackages.skipped.length" class="max-h-24 overflow-auto text-sm text-muted-foreground">+ {{ t("transfer.structurePlanSkipped") }}: {{ confirmationPreview.oraclePackages.skipped.map((identity) => `${identity.kind.replaceAll("_", " ")} ${identity.owner}.${identity.name}`).join("; ") }}+ </p>+ <Button variant="outline" size="sm" :disabled="packageComparisonLoading || packageDeployment?.validating" @click="compareTransferPackages"><Loader2 v-if="packageComparisonLoading" class="mr-1 h-3.5 w-3.5 animate-spin" />{{ t("diff.title") }}</Button>+ </div>+ </template>+ <template v-if="packageDeployment" #preview>+ <Tabs v-model="packagePreviewTab" class="flex min-h-0 flex-1 flex-col">+ <TabsList v-if="confirmationPreview?.structure?.tables.length" class="shrink-0 self-start">+ <TabsTrigger value="tables">{{ t("diff.tableSelection") }}</TabsTrigger>+ <TabsTrigger value="routines">{{ t("diff.routineSelection") }}</TabsTrigger>+ </TabsList>+ <TabsContent v-if="packageTablePreview" value="tables" class="flex min-h-0 flex-1 flex-col overflow-hidden">+ <Select :model-value="packageTablePreview.sourceTable" @update:model-value="packageTableName = String($event)">+ <SelectTrigger class="mb-2 w-full sm:max-w-sm" :aria-label="t('diff.tableSelection')"><SelectValue /></SelectTrigger>+ <SelectContent+ ><SelectItem v-for="table in confirmationPreview?.structure?.tables" :key="table.sourceTable" :value="table.sourceTable">{{ table.sourceTable }} → {{ table.targetTable }}</SelectItem></SelectContent+ >+ </Select>+ <div class="min-h-0 flex-1 overflow-hidden rounded border" data-testid="transfer-table-sql"><SqlPreviewPanel :sql="packageTablePreview.sql" sql-format-dialect="oracle" @close="packagePreviewTab = 'routines'" /></div>+ </TabsContent>+ <TabsContent value="routines" class="min-h-0 flex-1 overflow-hidden rounded border">+ <SchemaDiffDeployStep+ :deploy-sql="packageDraftSql"+ :selected-objects="[]"+ :target-connection-id="packageDeployment.target.endpoint.connectionId"+ :target-database="packageDeployment.target.endpoint.database"+ :target-schema="packageDeployment.target.endpoint.schema"+ :database-type="packageDeployment.target.endpoint.databaseType"+ :executing="packageComparisonLoading"+ :routine-deployment="packageDeployment"+ package-transfer+ @update:deploy-sql="editOracleRoutineDraft(packageDeployment, packageDeployment.selectedObjectId!, $event)"+ @select-routine="selectOracleRoutineDraft(packageDeployment, $event)"+ @validate-routines="validateTransferPackages"+ @refresh-routines="refreshTransferPackages"+ @include-package-companion="includeTransferPackageCompanion"+ @update-package-options="(id, options) => editOraclePackageOptions(packageDeployment!, id, options)"+ @review-package-target="reviewOraclePackageTargetDraft(packageDeployment, $event)"+ />+ </TabsContent>+ </Tabs>+ </template>+ </DangerConfirmDialog><Dialog v-model:open="ownershipDialogOpen"><DialogContent class="sm:max-w-[520px]" @interact-outside.prevent>diff --git a/apps/desktop/src/components/transfer/DataTransferProgressDialog.vue b/apps/desktop/src/components/transfer/DataTransferProgressDialog.vueindex 175d43c855..5b26070a87 100644--- a/apps/desktop/src/components/transfer/DataTransferProgressDialog.vue+++ b/apps/desktop/src/components/transfer/DataTransferProgressDialog.vue@@ -1,15 +1,38 @@<script setup lang="ts">-import { computed, onBeforeUnmount, onMounted, ref } from "vue";+import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";import { useI18n } from "vue-i18n";import { AlertCircle, ArrowRightLeft, CheckCircle2, Loader2, Minimize2, X, XCircle } from "@lucide/vue";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { formatDataTransferDuration, useExportTracker, type ExportTask } from "@/composables/useExportTracker";import { translateBackendError } from "@/i18n/backend-errors";+import SchemaDiffDeployStep from "@/components/diff/SchemaDiffDeployStep.vue";+import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";+import {+ editOracleRoutineDraft,+ editOraclePackageOptions,+ executeOracleRoutineDeployment,+ includeOraclePackageCompanion,+ observeOracleRoutineDeployment,+ prepareOracleRoutineRecovery,+ refreshOracleRoutineDeployment,+ reviewOraclePackageTargetDraft,+ selectOracleRoutineDraft,+ validateOracleRoutineDeployment,+} from "@/lib/schema/oracleRoutineDeploy";+import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";+import { useConnectionStore } from "@/stores/connectionStore";const { t } = useI18n();const open = defineModel<boolean>("open", { default: false });const props = defineProps<{ task: ExportTask }>();+const connectionStore = useConnectionStore();+const packageDeployment = computed(() => props.task.oracleRoutineDeployment);+const showPackageReview = ref(true);+const packageDraftSql = computed(() => packageDeployment.value?.drafts.find((draft) => draft.objectId === packageDeployment.value?.selectedObjectId)?.sql ?? "");+const packageConfirmOpen = ref(false);+const packageConfirmSql = ref("");+let resolvePackageConfirmation: ((confirmed: boolean) => void) | undefined;const { cancelTask } = useExportTracker();const currentTime = ref(Date.now());let elapsedTimer: ReturnType<typeof setInterval> | undefined;@@ -32,6 +55,42 @@ const statusText = computed(() => {return t("exportProgress.compareRunning");});+function settlePackageConfirmation(confirmed: boolean) {+ const resolve = resolvePackageConfirmation;+ resolvePackageConfirmation = undefined;+ packageConfirmOpen.value = false;+ resolve?.(confirmed);+}++async function executePackageRepair() {+ const state = packageDeployment.value;+ if (!state || isActive.value) return;+ await executeOracleRoutineDeployment(state, async (sql, run) => {+ packageConfirmSql.value = sql;+ const confirmed = await new Promise<boolean>((resolve) => {+ resolvePackageConfirmation = resolve;+ packageConfirmOpen.value = true;+ });+ if (!confirmed) return;+ await executeWithProductionSqlGuard({ connection: connectionStore.getConfig(state.target.endpoint.connectionId), database: state.target.endpoint.database, sql, source: t("transfer.title"), execute: run });+ });+}++async function refreshPackageResults() {+ const state = packageDeployment.value;+ if (state) await refreshOracleRoutineDeployment(state, { source: state.source.endpoint, target: state.target.endpoint });+}++watch(packageConfirmOpen, (isOpen) => {+ if (!isOpen) settlePackageConfirmation(false);+});+watch(open, (isOpen) => {+ if (!isOpen) {+ settlePackageConfirmation(false);+ if (packageDeployment.value) packageDeployment.value.stopRequested = true;+ }+});+onMounted(() => {elapsedTimer = setInterval(() => {currentTime.value = Date.now();@@ -40,12 +99,14 @@ onMounted(() => {onBeforeUnmount(() => {if (elapsedTimer) clearInterval(elapsedTimer);+ settlePackageConfirmation(false);+ if (packageDeployment.value) packageDeployment.value.stopRequested = true;});</script><template><Dialog :open="open" @update:open="open = $event">- <DialogContent class="sm:max-w-lg" data-transfer-progress-dialog @interact-outside.prevent>+ <DialogContent :class="packageDeployment && showPackageReview ? 'flex h-[85vh] min-h-0 flex-col sm:max-w-[1120px]' : 'sm:max-w-lg'" data-transfer-progress-dialog @interact-outside.prevent><DialogHeader><DialogTitle class="flex items-center gap-2"><ArrowRightLeft class="h-4 w-4" />@@ -69,7 +130,7 @@ onBeforeUnmount(() => {</div><div class="flex items-center justify-between gap-3 text-xs text-muted-foreground"><span class="truncate">{{ task.currentTable || task.tableName }}</span>- <span class="shrink-0 tabular-nums">{{ task.tableIndex ?? 0 }} / {{ task.totalTables ?? 0 }} · {{ task.rowsExported.toLocaleString() }} {{ t("exportProgress.rowsShort") }}</span>+ <span v-if="!packageDeployment || task.totalTables" class="shrink-0 tabular-nums">{{ task.tableIndex ?? 0 }} / {{ task.totalTables ?? 0 }} · {{ task.rowsExported.toLocaleString() }} {{ t("exportProgress.rowsShort") }}</span></div><div class="text-xs text-muted-foreground">{{ t("exportProgress.elapsed", { duration: elapsed }) }}</div></div>@@ -79,7 +140,33 @@ onBeforeUnmount(() => {</div></div>+ <div v-if="packageDeployment && showPackageReview" class="min-h-0 flex-1 overflow-hidden rounded border">+ <SchemaDiffDeployStep+ :deploy-sql="packageDraftSql"+ :selected-objects="[]"+ :target-connection-id="packageDeployment.target.endpoint.connectionId"+ :target-database="packageDeployment.target.endpoint.database"+ :target-schema="packageDeployment.target.endpoint.schema"+ :database-type="packageDeployment.target.endpoint.databaseType"+ :routine-deployment="packageDeployment"+ :executing="isActive || packageDeployment.executing"+ :can-execute="!isActive && (packageDeployment.recoveryPlan ?? packageDeployment.plan)?.ready === true"+ @back="showPackageReview = false"+ @select-routine="selectOracleRoutineDraft(packageDeployment, $event)"+ @update:deploy-sql="editOracleRoutineDraft(packageDeployment, packageDeployment.selectedObjectId!, $event)"+ @validate-routines="validateOracleRoutineDeployment(packageDeployment)"+ @refresh-routines="refreshPackageResults"+ @observe-routine="observeOracleRoutineDeployment(packageDeployment, $event)"+ @recover-routine="prepareOracleRoutineRecovery(packageDeployment, $event)"+ @include-package-companion="(id, source) => includeOraclePackageCompanion(packageDeployment!, id, source)"+ @update-package-options="(id, options) => editOraclePackageOptions(packageDeployment!, id, options)"+ @review-package-target="reviewOraclePackageTargetDraft(packageDeployment, $event)"+ @deploy="executePackageRepair"+ />+ </div>+<DialogFooter>+ <Button v-if="packageDeployment && !showPackageReview" variant="outline" size="sm" @click="showPackageReview = true">{{ t("diff.deployReview") }}</Button><template v-if="isActive"><Button variant="ghost" size="sm" @click="open = false"><Minimize2 class="mr-1 h-3.5 w-3.5" />@@ -95,6 +182,7 @@ onBeforeUnmount(() => {</DialogFooter></DialogContent></Dialog>+ <DangerConfirmDialog v-if="packageDeployment" v-model:open="packageConfirmOpen" :sql="packageConfirmSql" :close-on-confirm="false" @confirm="settlePackageConfirmation(true)" /></template><style scoped>diff --git a/apps/desktop/src/components/transfer/__tests__/DataTransferDialog.packages.spec.ts b/apps/desktop/src/components/transfer/__tests__/DataTransferDialog.packages.spec.tsnew file mode 100644index 0000000000..95cdb42e7c--- /dev/null+++ b/apps/desktop/src/components/transfer/__tests__/DataTransferDialog.packages.spec.ts@@ -0,0 +1,562 @@+// @vitest-environment happy-dom+import { createApp, defineComponent, h, nextTick, reactive, type App } from "vue";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import i18n from "@/i18n";+import { TooltipProvider } from "@/components/ui/tooltip";+import type { OracleRoutineOperation, OracleRoutinePlanInput, OracleRoutineSnapshot } from "@/types/schemaDiff";+import type { TransferRequest, TransferProgress, OraclePackageTransferPreview } from "@/lib/backend/api";+import type { TransferTask } from "@/types/database";++const calls = vi.hoisted(() => ({ preview: vi.fn(), start: vi.fn(), refs: vi.fn(), observe: vi.fn(), confirm: vi.fn(), cancelScope: vi.fn(), writable: vi.fn(), save: vi.fn(), toast: vi.fn(), load: vi.fn(), compare: vi.fn(), openComparison: vi.fn(), tables: vi.fn() }));+const savedTask = {+ id: "saved-package",+ name: "Package transfer",+ orderIndex: 0,+ createdAt: "",+ updatedAt: "",+ config: {+ sourceConnectionId: "source",+ sourceDatabase: "S",+ sourceSchema: "S",+ targetConnectionId: "target",+ targetDatabase: "T",+ targetSchema: "T",+ objects: { PACKAGE_BODY: ["P"] },+ content: "structureOnly",+ mode: "append",+ targetTableNameCase: "preserve",+ quoteTargetColumnNames: true,+ batchSize: 100,+ },+} as TransferTask;++vi.mock("@/lib/backend/api", () => ({+ previewTransferOwnership: calls.preview,+ startTransfer: calls.start,+ updateOracleRoutineOperationReferences: calls.refs,+ observeOracleRoutineOperation: calls.observe,+ listSchemas: vi.fn(async (id: string) => [id === "source" ? "S" : id === "replacement" ? "U" : "T"]),+ listTables: calls.tables,+ listObjects: vi.fn(async (_id: string, _db: string, _schema: string, kinds: string[]) => (kinds.some((kind) => kind === "PACKAGE" || kind === "PACKAGE_BODY") ? [{ name: "P" }] : [])),+ cancelTransfer: vi.fn(),+ loadSchemaDiffRoutines: calls.load,+ prepareSchemaDiff: calls.compare,+}));+vi.mock("@/stores/connectionStore", () => {+ const connections = [+ { id: "source", name: "Source", db_type: "oracle", database: "tenant" },+ { id: "target", name: "Target", db_type: "oceanbase-oracle", database: "tenant" },+ { id: "replacement", name: "Replacement", db_type: "oceanbase-oracle", database: "tenant" },+ ];+ return { useConnectionStore: () => ({ connections, sidebarLayout: { groups: [], order: [] }, getConfig: (id: string) => connections.find((config) => config.id === id), ensureConnected: async () => {}, refreshObjectListTreeNode: vi.fn() }) };+});+vi.mock("@/stores/transferTaskStore", () => ({+ useTransferTaskStore: () => ({ initFromStorage: async () => {}, getTask: (id: string) => (id === savedTask.id ? savedTask : undefined), listTasks: () => [savedTask], saveTask: calls.save }),+ TransferTaskNameConflictError: class extends Error {},+ nextTransferTaskCopyName: (name: string) => name,+}));+vi.mock("@/components/transfer/TransferTaskTree.vue", () => ({+ default: defineComponent({+ emits: ["select"],+ setup(_props, { emit }) {+ return () => h("button", { onClick: () => emit("select", savedTask) }, "Load saved package");+ },+ }),+}));+vi.mock("@/components/connection/ConnectionTreeSelect.vue", () => ({+ default: defineComponent({+ props: ["modelValue", "connections"],+ emits: ["update:modelValue"],+ setup(props, { emit }) {+ return () =>+ h(+ "select",+ { "data-testid": "transfer-connection", value: props.modelValue, onChange: (event: Event) => emit("update:modelValue", (event.target as HTMLSelectElement).value) },+ props.connections.map((connection: { id: string }) => h("option", { value: connection.id }, connection.id)),+ );+ },+ }),+}));+vi.mock("@/composables/useDialogSources", () => ({ openDataTransferTask: vi.fn(), openSchemaDiffSession: calls.openComparison }));+vi.mock("@/lib/database/readOnlyWriteAccess", () => ({ ensureReadOnlyWriteAccess: calls.writable }));+vi.mock("@/stores/productionSafetyStore", () => ({ useProductionSafetyStore: () => ({ requestConfirmation: calls.confirm, cancelScope: calls.cancelScope }) }));+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: calls.toast }) }));+vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { theme: "default", fontSize: 12, fontFamily: "monospace" } }) }));+vi.mock("@/composables/useTheme", () => ({ useTheme: () => ({ isDark: { value: false } }) }));+vi.mock("@/composables/useSqlHighlighter", () => ({ useSqlHighlighter: () => ({ highlight: (text: string) => text }) }));+vi.mock("@/lib/editor/editorThemes", () => ({ loadEditorTheme: async () => [], editorFontTheme: () => [] }));+vi.mock("@/lib/editor/codemirrorSqlDialect", () => ({ createDbxCodeMirrorSqlDialect: () => undefined }));+vi.mock("@/lib/metadata/objectDdlCache", () => ({ invalidateObjectDdlCache: vi.fn() }));+vi.mock("@/lib/sql/sqlHighlighter", () => ({ createShikiSqlHighlighter: async () => (sql: string) => sql.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">") }));+vi.mock("@/lib/table/objectBrowserRowsCache", () => ({ invalidateObjectBrowserRowsCache: vi.fn() }));+vi.mock("@codemirror/view", () => ({+ EditorView: class {+ static updateListener = { of: (listener: unknown) => ({ listener }) };+ static scrollIntoView = () => ({});+ state: any;+ input = document.createElement("textarea");+ constructor({ state, parent }: any) {+ this.state = state;+ this.input.dataset.testid = "package-editor";+ this.input.value = state.doc.toString();+ parent.append(this.input);+ this.input.addEventListener("input", () => {+ const text = this.input.value;+ this.state.doc = { toString: () => text, length: text.length };+ state.extensions.find((extension: any) => extension?.listener)?.listener({ docChanged: true, state: this.state });+ });+ }+ dispatch(update: any) {+ if (update.changes) {+ const text = update.changes.insert;+ this.state.doc = { toString: () => text, length: text.length };+ this.input.value = text;+ }+ }+ focus() {+ this.input.focus();+ }+ destroy() {+ this.input.remove();+ }+ },+}));+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/lang-sql", () => ({ sql: () => [] }));+vi.mock("codemirror", () => ({ basicSetup: [] }));++import DataTransferDialog from "@/components/transfer/DataTransferDialog.vue";+import { useExportTracker } from "@/composables/useExportTracker";+import { getSchemaDiffSession, schemaDiffSessionObjects } from "@/composables/useSchemaDiffSession";++const apps: App[] = [];+const records = new Map<string, OracleRoutineOperation>();+const generated = 'CREATE PACKAGE BODY "T"."P" AS -- 原始😀\nEND;';+const corrected = generated.replace("原始", "人工复核");++beforeEach(() => {+ vi.clearAllMocks();+ records.clear();+ savedTask.config.objects = { PACKAGE_BODY: ["P"] };+ calls.tables.mockResolvedValue([]);+ i18n.global.locale.value = "en";+ calls.refs.mockResolvedValue(undefined);+ calls.writable.mockResolvedValue(true);+ calls.confirm.mockResolvedValue(true);+ calls.observe.mockImplementation(async (id: string) => ({ operation: records.get(id), lifecycle: records.get(id)?.lifecycle, error: null }));+ calls.preview.mockImplementation(async (request: TransferRequest) => {+ const snapshot = (source: boolean): OracleRoutineSnapshot => ({+ endpoint: { connectionId: source ? request.sourceConnectionId : request.targetConnectionId, database: source ? request.sourceDatabase : request.targetDatabase, schema: source ? request.sourceSchema : request.targetSchema, databaseType: source ? "oracle" : "oceanbase-oracle", generation: 1 },+ state: "complete",+ enumerationComplete: true,+ objects: [],+ issues: [],+ });+ const identity = { owner: request.targetSchema, name: "P", kind: "PACKAGE_BODY" as const };+ const input: OracleRoutinePlanInput = request.oraclePackages?.input ?? { source: snapshot(true), target: snapshot(false), drafts: [{ identity, sourceName: "P", action: "create" }] };+ const sql = input.drafts[0].sql ?? generated;+ const ready = input.drafts[0].sql === corrected;+ const operation: OracleRoutineOperation = { operationId: `original-body-${request.transferId}-${calls.preview.mock.calls.length}`, target: input.target.endpoint, identity, lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null, error: null };+ if (ready) records.set(operation.operationId, operation);+ return {+ missingOwners: [],+ targetOwner: "T",+ structure: { sql, tables: [], operations: [], schemaObjectsExpanded: true },+ oraclePackages: {+ input,+ skipped: [],+ plan: {+ target: input.target.endpoint,+ ready,+ steps: [+ {+ identity,+ action: "create",+ sql,+ sourceOriginal: 'CREATE PACKAGE BODY "S"."P" AS -- 原始😀\nEND;',+ targetOriginal: null,+ recoverySql: null,+ recoveryComplete: true,+ references: [],+ incomingCallers: [],+ issues: ready ? [] : [{ code: "review-required", message: "Review the target draft", line: 1, column: 1 }],+ operation: ready ? operation : null,+ },+ ],+ },+ },+ };+ });+ calls.start.mockImplementation(async (request, progress, started) => {+ started?.();+ progress({ transferId: request.transferId, table: "", tableIndex: 0, totalTables: 0, rowsTransferred: 0, totalRows: null, status: "done", terminal: true, error: null });+ });+ calls.load.mockImplementation(async (id: string, database: string, schema: string): Promise<OracleRoutineSnapshot> => ({+ endpoint: { connectionId: id, database, schema, databaseType: id === "source" ? "oracle" : "oceanbase-oracle", generation: 1 },+ state: "complete",+ enumerationComplete: true,+ objects: [{ version: { identity: { owner: schema, name: "P", kind: "PACKAGE_BODY" }, objectId: `${id}-body`, status: "VALID", lastDdlTime: "1" }, source: generated.replace('"T"', `"${schema}"`), sourceComplete: true, dependencies: [], dependenciesComplete: true, issues: [] }],+ issues: [],+ }));+ calls.compare.mockResolvedValue({+ diffs: [],+ functionDiffs: [{ type: "modified", name: "P", programKind: "PACKAGE_BODY", source: { name: "P", arguments: "", function_type: "PACKAGE_BODY", definition: generated }, target: { name: "P", arguments: "", function_type: "PACKAGE_BODY", definition: "old target body" } }],+ syncSql: "",+ });+});+afterEach(async () => {+ apps.splice(0).forEach((app) => app.unmount());+ const tracker = useExportTracker();+ tracker.clearFinished();+ await nextTick();+ document.body.innerHTML = "";+});++function button(label: string, enabled = true) {+ const found = [...document.body.querySelectorAll<HTMLButtonElement>("button")].filter((button) => button.textContent?.trim() === label && (!enabled || !button.disabled)).at(-1);+ expect(found, label).toBeDefined();+ return found!;+}+async function openPreview(expectEditor: boolean | "table" = true) {+ const visible = reactive({ open: true, prefillTarget: undefined as string | undefined });+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp({+ render: () =>+ h(TooltipProvider, {}, () =>+ h(DataTransferDialog, {+ open: visible.open,+ prefillTargetConnectionId: visible.prefillTarget,+ "onUpdate:open": (value: boolean) => {+ visible.open = value;+ },+ }),+ ),+ });+ apps.push(app);+ app.use(i18n);+ app.mount(host);+ await nextTick();+ button("Load saved package").click();+ await vi.waitFor(() => expect(button(i18n.global.t("transfer.start")).disabled).toBe(false));+ button(i18n.global.t("transfer.start")).click();+ await vi.waitFor(() => expect(document.querySelector(expectEditor === "table" ? '[data-testid="transfer-table-sql"]' : expectEditor ? '[data-testid="package-editor"]' : '[data-testid="danger-code-preview"]')).not.toBeNull());+ return visible;+}+async function editTargetDraft() {+ const editor = document.querySelector<HTMLTextAreaElement>('[data-testid="package-editor"]')!;+ editor.value = corrected;+ editor.dispatchEvent(new Event("input"));+ await nextTick();+}++it.each(["PACKAGE", "PACKAGE_BODY"] as const)("does not restore a deselected same-name %s from retained package drafts", async (removed) => {+ savedTask.config.objects = { PACKAGE: ["P"], PACKAGE_BODY: ["P"] };+ const basePreview = calls.preview.getMockImplementation()!;+ calls.preview.mockImplementation(async (request: TransferRequest) => {+ const result = await basePreview(request);+ const identities = request.objects.flatMap((selection) => (selection.objectType === "PACKAGE" || selection.objectType === "PACKAGE_BODY" ? selection.names.map((name) => ({ owner: "T", name, kind: selection.objectType })) : []));+ result.oraclePackages.input.drafts = identities.map((identity) => ({ identity, sourceName: identity.name, action: "create", sql: `CREATE ${identity.kind === "PACKAGE" ? "PACKAGE" : "PACKAGE BODY"} "T"."P" AS END;` }));+ result.oraclePackages.plan.steps = result.oraclePackages.input.drafts.map((draft) => ({ ...result.oraclePackages.plan.steps[0], identity: draft.identity, sql: draft.sql, operation: null }));+ return result;+ });+ await openPreview();+ button(i18n.global.t("common.cancel")).click();+ await nextTick();+ const toggle = document.querySelector<HTMLButtonElement>(`[data-test="group-${removed}"] [data-test="group-toggle"]`)!;+ expect(toggle).not.toBeNull();+ toggle.click();+ await nextTick();+ button(i18n.global.t("transfer.saveConfig")).click();+ await vi.waitFor(() => expect(calls.save).toHaveBeenCalledOnce());+ const config = calls.save.mock.calls[0][0].config;+ expect(config.objects[removed]).toBeUndefined();+ expect(config.oraclePackageDrafts.map((draft: any) => draft.identity.kind)).toEqual([removed === "PACKAGE" ? "PACKAGE_BODY" : "PACKAGE"]);+ button(i18n.global.t("transfer.start")).click();+ await vi.waitFor(() => expect(calls.preview.mock.calls.length).toBeGreaterThan(1));+ expect(calls.preview.mock.calls.at(-1)![0].objects).toEqual([{ objectType: removed === "PACKAGE" ? "PACKAGE_BODY" : "PACKAGE", names: ["P"] }]);+ expect(calls.start).not.toHaveBeenCalled();+});++it("keeps an explicitly added companion in the source selection without cancelling the open preview", async () => {+ const basePreview = calls.preview.getMockImplementation()!;+ calls.preview.mockImplementation(async (request: TransferRequest) => {+ const result = await basePreview(request);+ result.oraclePackages.input.source.objects.push({+ version: { identity: { owner: "S", name: "P", kind: "PACKAGE" }, objectId: "source-spec", status: "VALID", lastDdlTime: "1" },+ source: 'CREATE PACKAGE "S"."P" AS END;',+ sourceComplete: true,+ dependencies: [],+ dependenciesComplete: true,+ issues: [],+ });+ return result;+ });+ await openPreview();+ button(i18n.global.t("diff.packageAddSpecification")).click();+ await nextTick();+ expect(document.querySelector('[data-testid="package-editor"]')).not.toBeNull();+ expect(document.querySelector('[data-test="group-PACKAGE"] [data-test="group-toggle"]')?.getAttribute("data-state")).toBe("all");+ expect(calls.start).not.toHaveBeenCalled();+ button(i18n.global.t("common.cancel")).click();+ await nextTick();+ await vi.waitFor(() => expect(button(i18n.global.t("transfer.saveConfig"), false).disabled).toBe(false));+ button(i18n.global.t("transfer.saveConfig")).click();+ await vi.waitFor(() => expect(calls.save).toHaveBeenCalledOnce());+ expect(calls.save.mock.calls[0][0].config.objects).toEqual({ PACKAGE_BODY: ["P"], PACKAGE: ["P"] });+ expect(calls.save.mock.calls[0][0].config.oraclePackageDrafts.map((draft: any) => draft.identity.kind)).toEqual(["PACKAGE_BODY", "PACKAGE"]);+});++it("replaces an unused Prepared preview with a reviewed mixed-table plan and adopts only its post-table IDs", async () => {+ savedTask.config.objects.TABLE = ["SOURCE"];+ calls.tables.mockImplementation(async (id: string) => (id === "source" ? [{ name: "SOURCE", schema: "S", table_type: "TABLE" }] : []));+ calls.refs.mockImplementation(async (_retain: string[], release: string[]) => {+ release.forEach((id) => records.delete(id));+ });+ const basePreview = calls.preview.getMockImplementation()!;+ const mixedSql = `${corrected}\n-- mixed table dependency`;+ let latest: OraclePackageTransferPreview | undefined;+ calls.preview.mockImplementation(async (request: TransferRequest) => {+ const result = await basePreview(request);+ const mixed = request.oraclePackages?.input?.drafts[0].sql === mixedSql;+ const ddl = `CREATE TABLE "T"."SOURCE"(V VARCHAR2(20${mixed ? " CHAR" : ""}))`;+ result.structure.tables = [{ sourceTable: "SOURCE", targetTable: "SOURCE", preexisting: false, sql: ddl }];+ result.structure.sql = `${ddl};\n${result.structure.sql}`;+ if (mixed) {+ expect(request.oraclePackages!.input!.drafts[0].supersedesOperationId).toMatch(/^original-body-/);+ result.oraclePackages.input = JSON.parse(JSON.stringify(request.oraclePackages!.input!));+ result.oraclePackages.input.drafts[0].supersedesOperationId = undefined;+ result.oraclePackages.plan.ready = false;+ result.oraclePackages.plan.steps[0] = { ...result.oraclePackages.plan.steps[0], sql: mixedSql, issues: [], operation: null };+ result.oraclePackages.pendingTables = {+ source: result.oraclePackages.input.source.endpoint,+ target: result.oraclePackages.input.target.endpoint,+ tables: [{ sourceTable: "SOURCE", finalDdl: ddl }],+ dependencyManifest: { order: [0], steps: [] },+ tableEvidence: [{ sourceTable: "SOURCE", targetTable: "SOURCE", sql: ddl }],+ };+ latest = result.oraclePackages;+ }+ return result;+ });+ calls.start.mockImplementation(async (request: TransferRequest, publish: (event: TransferProgress) => void, started?: () => void) => {+ started?.();+ const input = request.oraclePackages!.input!;+ const operation: OracleRoutineOperation = { operationId: `after-table-${request.transferId}`, target: input.target.endpoint, identity: input.drafts[0].identity, lifecycle: "prepared", dispatched: false, acknowledged: false, error: null, readback: null };+ records.set(operation.operationId, operation);+ const base: TransferProgress = { transferId: request.transferId, table: "SOURCE", tableIndex: 1, totalTables: 1, rowsTransferred: 7, totalRows: 7, status: "tableDone", terminal: false, error: null };+ publish(base);+ publish({ ...base, table: "package objects", rowsTransferred: 0, status: "running", oraclePackageApproval: { input, skipped: [], plan: { ...latest!.plan, ready: true, steps: latest!.plan.steps.map((step) => ({ ...step, operation })) } } });+ const terminal: OracleRoutineOperation = { ...operation, lifecycle: "terminal", dispatched: true, acknowledged: true, readback: { identity: operation.identity, state: "verified", exists: true, version: null, source: mixedSql, definitionMatches: true, compilerMessages: [], issues: [] } };+ records.set(operation.operationId, terminal);+ publish({ ...base, table: "PackageBody:P", rowsTransferred: 0, oracleRoutineOperation: terminal });+ publish({ ...base, table: "", status: "done", terminal: true });+ });+ await openPreview("table");+ button(i18n.global.t("diff.routineSelection")).dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await vi.waitFor(() => expect(document.querySelector('[data-testid="package-editor"]')).not.toBeNull());+ await editTargetDraft();+ button(i18n.global.t("diff.routineValidate")).click();+ await vi.waitFor(() => expect(records.size).toBe(1));+ await vi.waitFor(() => expect(button(i18n.global.t("transfer.start")).disabled).toBe(false));+ const oldId = [...records.keys()][0];+ const editor = document.querySelector<HTMLTextAreaElement>('[data-testid="package-editor"]')!;+ editor.value = mixedSql;+ editor.dispatchEvent(new Event("input"));+ await nextTick();+ button(i18n.global.t("diff.routineValidate")).click();+ await vi.waitFor(() => expect(document.querySelector('[data-testid="transfer-table-sql"]')?.textContent).toContain("VARCHAR2(20 CHAR)"));+ await vi.waitFor(() => expect(calls.refs.mock.calls.some((call) => call[1]?.includes(oldId))).toBe(true));+ expect(records.size).toBe(0);+ await vi.waitFor(() => expect(button(i18n.global.t("transfer.start")).disabled).toBe(false));+ button(i18n.global.t("transfer.start")).click();+ await vi.waitFor(() => expect(calls.start).toHaveBeenCalledOnce());+ const request = calls.start.mock.calls[0][0] as TransferRequest;+ expect(request.tables).toEqual(["SOURCE"]);+ expect(request.oraclePackages?.operationIds).toEqual([]);+ expect(request.oraclePackages?.pendingTables).toEqual(latest!.pendingTables);+ const task = useExportTracker().tasks.value.find((task) => task.exportId === request.transferId)!;+ await vi.waitFor(() => expect(task.oracleRoutineDeployment?.drafts[0].operation?.lifecycle).toBe("terminal"));+ expect(task.oracleRoutineDeployment?.records.map((record) => record.operationId)).toEqual([`after-table-${request.transferId}`]);+ expect(task.rowsExported).toBe(7);+ expect(task.status).toBe("Done");+});++it("loads the saved BODY-only task, edits and validates in the real preview, then hands off exact SQL and original approval ID", async () => {+ const visible = await openPreview();+ expect(calls.start).not.toHaveBeenCalled();+ expect(calls.preview.mock.calls[0][0].objects).toEqual([{ objectType: "PACKAGE_BODY", names: ["P"] }]);+ await editTargetDraft();+ expect(calls.start).not.toHaveBeenCalled();+ button(i18n.global.t("diff.routineValidate")).click();+ await vi.waitFor(() => expect(records.size).toBe(1));+ await nextTick();+ expect(calls.preview.mock.calls.at(-1)![0].oraclePackages.input.drafts[0].sql).toBe(corrected);+ await vi.waitFor(() => expect(button(i18n.global.t("transfer.start")).disabled).toBe(false));+ button(i18n.global.t("transfer.start")).click();+ await vi.waitFor(() => expect(calls.start).toHaveBeenCalledOnce());+ const request = calls.start.mock.calls[0][0];+ const originalId = [...records.keys()][0];+ expect(request.oraclePackages.operationIds).toEqual([originalId]);+ expect(request.oraclePackages.input.drafts[0].sql).toBe(corrected);+ expect(request.objects).toEqual([{ objectType: "PACKAGE_BODY", names: ["P"] }]);+ expect(request.targetConnectionId).toBe("target");+ expect(visible.open).toBe(false);+ expect(useExportTracker().tasks.value[0].oracleRoutineDeployment?.retainedOperationIds).toContain(originalId);+ expect(calls.refs.mock.calls.some((call) => call[1]?.includes(originalId))).toBe(false);+});++it("cancels without dispatch and reopens with the manual draft but fresh source reads and approvals", async () => {+ await openPreview();+ await editTargetDraft();+ button(i18n.global.t("dangerDialog.cancel")).click();+ await vi.waitFor(() => expect(document.querySelector('[data-testid="package-editor"]')).toBeNull());+ await vi.waitFor(() => expect(button(i18n.global.t("transfer.start")).disabled).toBe(false));+ button(i18n.global.t("transfer.start")).click();+ await vi.waitFor(() => expect(records.size).toBe(1));+ expect(calls.preview.mock.calls[1][0].oraclePackages).toBeUndefined();+ expect(calls.preview.mock.calls.at(-1)![0].oraclePackages.input.drafts[0].sql).toBe(corrected);+ expect(document.querySelector<HTMLTextAreaElement>('[data-testid="package-editor"]')!.value).toBe(corrected);+ expect(calls.start).not.toHaveBeenCalled();+ button(i18n.global.t("dangerDialog.cancel")).click();+});++it("keeps the original package target and manual draft when the whole transfer dialog closes and reopens", async () => {+ const visible = await openPreview();+ await editTargetDraft();+ visible.open = false;+ await nextTick();+ visible.open = true;+ await nextTick();+ await vi.waitFor(() => expect(button(i18n.global.t("transfer.start")).disabled).toBe(false));+ button(i18n.global.t("transfer.start")).click();+ await vi.waitFor(() => expect(records.size).toBe(1));+ const request = calls.preview.mock.calls.at(-1)![0];+ expect(request.targetConnectionId).toBe("target");+ expect(request.targetSchema).toBe("T");+ expect(request.oraclePackages.input.drafts[0].sql).toBe(corrected);+ expect(calls.start).not.toHaveBeenCalled();+ button(i18n.global.t("dangerDialog.cancel")).click();+});++it("uses the existing unsaved-change decision before a new prefill can replace a retained package target", async () => {+ const visible = await openPreview();+ await editTargetDraft();+ visible.open = false;+ await nextTick();+ visible.prefillTarget = "replacement";+ visible.open = true;+ await nextTick();+ await vi.waitFor(() => expect(button(i18n.global.t("transfer.unsavedDiscard"))).toBeDefined());+ button(i18n.global.t("transfer.cancel")).click();+ await nextTick();+ const target = () => document.querySelectorAll<HTMLSelectElement>('[data-testid="transfer-connection"]')[1];+ expect(target().value).toBe("target");+ visible.open = false;+ await nextTick();+ visible.open = true;+ await nextTick();+ button(i18n.global.t("transfer.unsavedDiscard")).click();+ await vi.waitFor(() => expect(target().value).toBe("replacement"));+ expect(button(i18n.global.t("transfer.start"), false).disabled).toBe(true);+ expect(calls.preview).toHaveBeenCalledOnce();+ expect(calls.start).not.toHaveBeenCalled();+});++it("opens the existing comparison for the same package and target, preserving manual SQL but no transfer approvals", async () => {+ const visible = await openPreview();+ await editTargetDraft();+ button(i18n.global.t("diff.routineValidate")).click();+ await vi.waitFor(() => expect(records.size).toBe(1));+ await vi.waitFor(() => expect(button(i18n.global.t("diff.title"))).toBeDefined());+ button(i18n.global.t("diff.title")).click();+ await vi.waitFor(() => expect(calls.openComparison).toHaveBeenCalledOnce());+ const session = getSchemaDiffSession(calls.openComparison.mock.calls[0][0])!;+ expect(session.status).toBe("completed");+ expect(session.config.options.selectedRoutineObjects).toEqual([{ name: "P", kind: "PACKAGE_BODY" }]);+ expect(session.routineDeployment?.target.endpoint.connectionId).toBe("target");+ expect(session.routineDeployment?.drafts[0]).toMatchObject({ sql: corrected, action: "replace", confirmPackagePair: false });+ expect(session.routineDeployment?.retainedOperationIds).toEqual([]);+ expect(session.routineDeployment?.plan).toBeNull();+ expect(visible.open).toBe(false);+ expect(calls.start).not.toHaveBeenCalled();+});++it("keeps a reviewed manual target draft actionable even when the fresh original sources compare equal", async () => {+ calls.compare.mockResolvedValue({+ diffs: [],+ functionDiffs: [{ type: "equal", name: "P", programKind: "PACKAGE_BODY", source: { name: "P", arguments: "", function_type: "PACKAGE_BODY", definition: generated }, target: { name: "P", arguments: "", function_type: "PACKAGE_BODY", definition: generated } }],+ syncSql: "",+ });+ await openPreview();+ await editTargetDraft();+ button(i18n.global.t("diff.title")).click();+ await vi.waitFor(() => expect(calls.openComparison).toHaveBeenCalledOnce());+ const session = getSchemaDiffSession(calls.openComparison.mock.calls[0][0])!;+ expect(schemaDiffSessionObjects(session.result, session.routineDeployment)[0]).toMatchObject({ operationType: "modify", routineType: "PACKAGE_BODY" });+ expect(session.routineDeployment?.drafts[0]).toMatchObject({ sql: corrected, included: true, action: "replace", reviewedTargetDraft: true });+ expect(calls.start).not.toHaveBeenCalled();+});++it("retains the original preview when a connection generation changes during comparison handoff", async () => {+ const load = calls.load.getMockImplementation()!;+ calls.load.mockImplementation(async (...args) => {+ const snapshot = await load(...args);+ return args[0] === "target" ? { ...snapshot, endpoint: { ...snapshot.endpoint, generation: 2 } } : snapshot;+ });+ const visible = await openPreview();+ await editTargetDraft();+ button(i18n.global.t("diff.title")).click();+ await vi.waitFor(() => expect(calls.toast).toHaveBeenCalledWith(expect.stringContaining("endpoint changed"), 5000));+ expect(visible.open).toBe(true);+ expect(document.querySelector<HTMLTextAreaElement>('[data-testid="package-editor"]')!.value).toBe(corrected);+ expect(calls.openComparison).not.toHaveBeenCalled();+ expect(calls.start).not.toHaveBeenCalled();+});++it("offers comparison when all selected package kinds are skipped without preparing or dispatching a replacement", async () => {+ const preview = calls.preview.getMockImplementation()!;+ calls.preview.mockImplementation(async (request: TransferRequest) => {+ const result = await preview(request);+ result.oraclePackages.input.drafts = [];+ result.oraclePackages.plan.steps = [];+ result.oraclePackages.plan.ready = true;+ result.oraclePackages.skipped = [{ owner: "T", name: "P", kind: "PACKAGE_BODY" }];+ result.structure.sql = "-- Existing PACKAGE BODY T.P is skipped";+ return result;+ });+ await openPreview(false);+ expect(document.body.textContent).toContain("PACKAGE BODY T.P");+ expect(document.body.textContent).toContain(`${i18n.global.t("transfer.structurePlanSkipped")}: PACKAGE BODY T.P`);+ button(i18n.global.t("diff.title")).click();+ await vi.waitFor(() => expect(calls.openComparison).toHaveBeenCalledOnce());+ const session = getSchemaDiffSession(calls.openComparison.mock.calls[0][0])!;+ expect(session.routineDeployment?.drafts[0]).toMatchObject({ action: "replace", identity: { owner: "T", name: "P", kind: "PACKAGE_BODY" } });+ expect(session.routineDeployment?.plan).toBeNull();+ expect(session.routineDeployment?.retainedOperationIds).toEqual([]);+ expect(calls.start).not.toHaveBeenCalled();+});++it("retains the editable transfer draft if its object disappears from the fresh comparison", async () => {+ const load = calls.load.getMockImplementation()!;+ calls.load.mockImplementation(async (...args) => ({ ...(await load(...args)), objects: [] }));+ calls.compare.mockResolvedValue({ diffs: [], functionDiffs: [], syncSql: "" });+ const visible = await openPreview();+ await editTargetDraft();+ button(i18n.global.t("diff.title")).click();+ await vi.waitFor(() => expect(calls.toast).toHaveBeenCalledWith(expect.stringContaining("unavailable in the fresh comparison"), 5000));+ expect(visible.open).toBe(true);+ expect(document.querySelector<HTMLTextAreaElement>('[data-testid="package-editor"]')!.value).toBe(corrected);+ expect(calls.openComparison).not.toHaveBeenCalled();+ expect(calls.start).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/components/transfer/__tests__/DataTransferProgressDialog.spec.ts b/apps/desktop/src/components/transfer/__tests__/DataTransferProgressDialog.spec.tsindex 5fdf1ae9e4..76d86922e4 100644--- a/apps/desktop/src/components/transfer/__tests__/DataTransferProgressDialog.spec.ts+++ b/apps/desktop/src/components/transfer/__tests__/DataTransferProgressDialog.spec.ts@@ -1,11 +1,18 @@// @vitest-environment happy-dom-import { createApp, defineComponent, h, nextTick, ref, type App, type Ref } from "vue";+import { createApp, defineComponent, h, nextTick, reactive, ref, type App, type Ref } from "vue";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import i18n from "@/i18n";+import { createOracleRoutineDeployment } from "@/lib/schema/oracleRoutineDeploy";+import type { OracleRoutineOperation } from "@/types/schemaDiff";const mocks = vi.hoisted(() => ({cancelTransfer: vi.fn(),+ prepare: vi.fn(),+ observe: vi.fn(),+ execute: vi.fn(),+ refs: vi.fn(),+ guard: vi.fn(),}));vi.mock("@/lib/backend/api", () => ({@@ -14,13 +21,73 @@ vi.mock("@/lib/backend/api", () => ({cancelTableExport: vi.fn(),cancelTransfer: mocks.cancelTransfer,startTransfer: vi.fn(),+ prepareOracleRoutinePlan: mocks.prepare,+ observeOracleRoutineOperation: mocks.observe,+ executeOracleRoutineOperation: mocks.execute,+ updateOracleRoutineOperationReferences: mocks.refs,}));+vi.mock("@/stores/connectionStore", () => ({ useConnectionStore: () => ({ getConfig: () => undefined }) }));+vi.mock("@/lib/database/productionExecutionGuard", () => ({ executeWithProductionSqlGuard: mocks.guard }));+vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { theme: "default", fontSize: 12, fontFamily: "monospace" } }) }));+vi.mock("@/composables/useTheme", () => ({ useTheme: () => ({ isDark: { value: false } }) }));+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: vi.fn() }) }));+vi.mock("@/composables/useSqlHighlighter", () => ({ useSqlHighlighter: () => ({ highlight: (text: string) => text }) }));+vi.mock("@/lib/editor/editorThemes", () => ({ loadEditorTheme: async () => [], editorFontTheme: () => [] }));+vi.mock("@/lib/editor/codemirrorSqlDialect", () => ({ createDbxCodeMirrorSqlDialect: () => undefined }));+vi.mock("@/lib/metadata/objectDdlCache", () => ({ invalidateObjectDdlCache: vi.fn() }));+vi.mock("@/lib/table/objectBrowserRowsCache", () => ({ invalidateObjectBrowserRowsCache: vi.fn() }));+vi.mock("@codemirror/view", () => ({+ EditorView: class {+ static updateListener = { of: (listener: unknown) => ({ listener }) };+ static scrollIntoView = () => ({});+ state: any;+ input = document.createElement("textarea");+ constructor({ state, parent }: any) {+ this.state = state;+ this.input.dataset.testid = "package-editor";+ this.input.value = state.doc.toString();+ parent.append(this.input);+ this.input.addEventListener("input", () => {+ const text = this.input.value;+ this.state.doc = { toString: () => text, length: text.length };+ state.extensions.find((extension: any) => extension?.listener)?.listener({ docChanged: true, state: this.state });+ });+ }+ dispatch(update: any) {+ if (update.changes) {+ const text = update.changes.insert;+ this.state.doc = { toString: () => text, length: text.length };+ this.input.value = text;+ }+ }+ focus() {+ this.input.focus();+ }+ destroy() {+ this.input.remove();+ }+ },+}));+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/lang-sql", () => ({ sql: () => [] }));+vi.mock("codemirror", () => ({ basicSetup: [] }));vi.mock("@/components/ui/dialog", async () => {const { defineComponent, h } = await import("vue");const passthrough = defineComponent({- setup(_props, { slots }) {- return () => h("div", slots.default?.());+ props: { open: { type: Boolean, default: undefined } },+ setup(props, { slots }) {+ return () => (props.open === false ? null : h("div", slots.default?.()));},});return { Dialog: passthrough, DialogContent: passthrough, DialogFooter: passthrough, DialogHeader: passthrough, DialogTitle: passthrough };@@ -49,6 +116,8 @@ function resetTracker() {beforeEach(() => {vi.clearAllMocks();+ mocks.refs.mockResolvedValue(undefined);+ mocks.guard.mockImplementation(async (options: { execute: () => Promise<void> }) => options.execute());resetTracker();i18n.global.locale.value = "en";});@@ -60,6 +129,68 @@ afterEach(() => {});describe("DataTransferProgressDialog", () => {+ it("reopens the original package result, edits an invalid body and deploys only its newly validated correction", async () => {+ const endpoint = { connectionId: "target", database: "tenant", schema: "T", databaseType: "oceanbase-oracle" as const, generation: 1 };+ const target = { endpoint, state: "complete" as const, enumerationComplete: true, objects: [], issues: [] };+ const state = reactive(createOracleRoutineDeployment({ ...target, endpoint: { ...endpoint, connectionId: "source", schema: "S" } }, target));+ const record = (kind: "PACKAGE" | "PACKAGE_BODY", id: string, invalid = false): OracleRoutineOperation => {+ const identity = { owner: "T", name: "P", kind };+ return {+ operationId: id,+ target: endpoint,+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ error: null,+ readback: { identity, state: invalid ? "invalid" : "verified", exists: true, version: null, source: "original full definition", definitionMatches: true, issues: [], compilerMessages: invalid ? [{ attribute: "ERROR", line: 2, position: 3, text: "PLS-00323" }] : [] },+ };+ };+ const specification = record("PACKAGE", "original-spec");+ const body = record("PACKAGE_BODY", "original-body", true);+ state.records = [specification, body];+ state.drafts = [specification, body].map((operation, index) => ({ identity: operation.identity, action: "create", sourceName: "P", sql: index ? 'CREATE PACKAGE BODY "T"."P" AS END;' : 'CREATE PACKAGE "T"."P" AS END;', objectId: `package-${index}`, included: true, operation }));+ state.selectedObjectId = "package-1";+ const tracker = useExportTracker();+ const task = tracker.addDataTransferTask("original-package-failure", "source → target", 0);+ task.status = "Error";+ task.oracleRoutineDeployment = state;+ const container = document.createElement("div");+ document.body.append(container);+ const app = createApp({ render: () => h(DataTransferProgressDialog, { open: true, task }) });+ mountedApps.push(app);+ app.use(i18n);+ app.mount(container);+ await vi.waitFor(() => expect(container.querySelector('[data-testid="package-editor"]')).not.toBeNull());+ expect(container.textContent).toContain("PLS-00323");+ expect(container.textContent).not.toContain("0 / 0");+ const corrected = 'CREATE OR REPLACE PACKAGE BODY "T"."P" AS -- corrected 中文😀\nEND;';+ const editor = container.querySelector<HTMLTextAreaElement>('[data-testid="package-editor"]')!;+ editor.value = corrected;+ editor.dispatchEvent(new Event("input"));+ await nextTick();+ mocks.observe.mockResolvedValue({ operation: body, lifecycle: "terminal", error: null });+ const prepared = { ...body, operationId: "new-body", lifecycle: "prepared" as const, dispatched: false, acknowledged: false, readback: null };+ mocks.prepare.mockResolvedValue({+ target: endpoint,+ ready: true,+ steps: [{ identity: body.identity, action: "replace", sql: corrected, sourceOriginal: "complete source body", targetOriginal: "original full definition", recoverySql: null, recoveryComplete: true, references: [], incomingCallers: [], issues: [], operation: prepared }],+ });+ const click = (label: string) => [...document.body.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === label)!.click();+ click(i18n.global.t("diff.routineValidate"));+ await vi.waitFor(() => expect(state.plan?.ready).toBe(true));+ expect(mocks.prepare.mock.calls[0][0].drafts).toEqual([expect.objectContaining({ identity: body.identity, action: "replace", sql: corrected, baselineOperationId: "original-body" })]);+ mocks.execute.mockResolvedValue({ ...record("PACKAGE_BODY", "new-body"), readback: { ...record("PACKAGE_BODY", "new-body").readback!, source: corrected } });+ click(i18n.global.t("diff.deployToServer"));+ await nextTick();+ expect(mocks.execute).not.toHaveBeenCalled();+ click(i18n.global.t("dangerDialog.confirm"));+ await vi.waitFor(() => expect(mocks.execute).toHaveBeenCalledWith("new-body", corrected));+ expect(mocks.execute).toHaveBeenCalledOnce();+ expect(state.drafts[0].operation?.operationId).toBe("original-spec");+ expect(task.status).toBe("Error");+ });+it("minimizes without cancelling and keeps the explicit cancel action", async () => {const tracker = useExportTracker();const task = tracker.addDataTransferTask("transfer-progress", "source → target", 2);diff --git a/apps/desktop/src/components/transfer/__tests__/transferSelections.spec.ts b/apps/desktop/src/components/transfer/__tests__/transferSelections.spec.tsindex 5c4260ec9d..dd2bdd4354 100644--- a/apps/desktop/src/components/transfer/__tests__/transferSelections.spec.ts+++ b/apps/desktop/src/components/transfer/__tests__/transferSelections.spec.ts@@ -24,6 +24,19 @@ describe("countTransferObjects", () => {});describe("buildTransferObjectSelections", () => {+ it("retains separate same-name package selections and omits them only from a data-only request", () => {+ const selected = { TABLE: setOf(["orders"]), PACKAGE: setOf(["Pkg.With.Dot😀"]), PACKAGE_BODY: setOf(["Pkg.With.Dot😀"]) };+ const fields = buildTransferObjectSelectionField(selected, []);+ expect(fields.objects).toEqual([+ { objectType: "PACKAGE", names: ["Pkg.With.Dot😀"] },+ { objectType: "PACKAGE_BODY", names: ["Pkg.With.Dot😀"] },+ ]);+ expect(countTransferObjects({ tables: ["orders"], ...fields })).toBe(3);+ expect(buildTransferObjectSelectionField(selected, ["PACKAGE", "PACKAGE_BODY"]).objects).toEqual([]);+ expect(buildTransferObjectSelectionField(selected, []).objects).toEqual(fields.objects);+ expect(buildTransferObjectSelectionField({ PACKAGE_BODY: selected.PACKAGE_BODY }, []).objects).toEqual([{ objectType: "PACKAGE_BODY", names: ["Pkg.With.Dot😀"] }]);+ });+it("serializes non-table selections in request order", () => {const result = buildTransferObjectSelections({diff --git a/apps/desktop/src/components/transfer/__tests__/transferStrategy.spec.ts b/apps/desktop/src/components/transfer/__tests__/transferStrategy.spec.tsindex 7bfc78fbae..07a8a4b669 100644--- a/apps/desktop/src/components/transfer/__tests__/transferStrategy.spec.ts+++ b/apps/desktop/src/components/transfer/__tests__/transferStrategy.spec.ts@@ -1,9 +1,9 @@import { createPinia, setActivePinia } from "pinia";import { beforeEach, describe, expect, it, vi } from "vitest";-import type { TransferOwnershipPreview, TransferRequest } from "@/lib/backend/api";+import type { TransferOwnershipPreview, TransferRequest, OraclePackageTransferRequest } from "@/lib/backend/api";import type { ConnectionConfig } from "@/types/database";import { useProductionSafetyStore } from "@/stores/productionSafetyStore";-import { confirmTransferWithProductionSafety, createTransferSubmission, rebuildUnavailableReason, resolveTransferStrategy, supportsTransferUpsert, transferStrategyOptions } from "../transferStrategy";+import { confirmTransferWithProductionSafety, createTransferSubmission, rebuildUnavailableReason, resolveTransferStrategy, supportsTransferUpsert, transferStrategyOptions, type TransferPackageConfirmation } from "../transferStrategy";function deferred<T>() {let resolve!: (value: T) => void;@@ -92,6 +92,79 @@ describe("transfer strategies", () => {});describe("transfer submission", () => {+ function packageOptions(): OraclePackageTransferRequest {+ const endpoint = { connectionId: "source", database: "tenant", schema: "Source", databaseType: "oracle" as const, generation: 1 };+ return {+ input: {+ source: { endpoint, state: "complete", enumerationComplete: true, objects: [], issues: [] },+ target: { endpoint: { ...endpoint, connectionId: "target", schema: "Target" }, state: "complete", enumerationComplete: true, objects: [], issues: [] },+ drafts: [{ identity: { owner: "Target", name: "Pkg.With.Dot😀", kind: "PACKAGE_BODY" }, action: "create", sql: "original target draft" }],+ },+ operationIds: ["original-id"],+ };+ }++ it("freezes nested package drafts and original IDs before asynchronous preview", async () => {+ const gate = deferred<TransferOwnershipPreview>();+ let captured: TransferRequest | undefined;+ const execute = vi.fn();+ const submission = createTransferSubmission({+ preview: async (value) => {+ captured = value;+ return gate.promise;+ },+ confirmOwnership: async () => "preserve",+ confirm: async () => false,+ execute,+ });+ const input = request({ oraclePackages: packageOptions() });+ const pending = submission.start(input);+ input.oraclePackages!.input!.drafts[0].sql = "late unreviewed text";+ input.oraclePackages!.operationIds!.push("late-id");+ expect(captured!.oraclePackages!.input!.drafts[0].sql).toBe("original target draft");+ expect(captured!.oraclePackages!.operationIds).toEqual(["original-id"]);+ expect(() => {+ captured!.oraclePackages!.input!.drafts[0].sql = "mutation";+ }).toThrow();+ gate.resolve(preview());+ await expect(pending).resolves.toBe(false);+ expect(execute).not.toHaveBeenCalled();+ });++ it("accepts only explicit same-package companion selection and freezes the final reviewed approval", async () => {+ const decision = deferred<TransferPackageConfirmation>();+ const execute = vi.fn();+ const initial = request({ objects: [{ objectType: "PACKAGE_BODY", names: ["Pkg.With.Dot😀"] }], oraclePackages: packageOptions() });+ const confirm = vi.fn(() => decision.promise);+ const submission = createTransferSubmission({ preview: async () => preview(), confirmOwnership: async () => "preserve", confirm, execute });+ const pending = submission.start(initial);+ await vi.waitFor(() => expect(confirm).toHaveBeenCalledOnce());+ const reviewed = { objects: [...initial.objects, { objectType: "PACKAGE" as const, names: ["Pkg.With.Dot😀"] }], oraclePackages: { ...packageOptions(), operationIds: ["reviewed-body", "reviewed-spec"] } };+ decision.resolve(reviewed);+ await expect(pending).resolves.toBe(true);+ reviewed.oraclePackages.operationIds.push("late-unapproved-id");+ expect(execute).toHaveBeenCalledOnce();+ const final = execute.mock.calls[0][0] as TransferRequest;+ expect(final.targetConnectionId).toBe(initial.targetConnectionId);+ expect(final.tables).toEqual(initial.tables);+ expect(final.objects).toEqual(reviewed.objects);+ expect(final.oraclePackages?.operationIds).toEqual(["reviewed-body", "reviewed-spec"]);+ });++ it.each([+ [{ objectType: "PACKAGE_BODY" as const, names: ["Different"] }],+ [{ objectType: "PACKAGE" as const, names: ["Pkg.With.Dot😀"] }],+ [+ { objectType: "PACKAGE_BODY" as const, names: ["Pkg.With.Dot😀"] },+ { objectType: "VIEW" as const, names: ["unreviewed"] },+ ],+ ])("rejects package review that changes or omits the original scope: %j", async (...objects) => {+ const execute = vi.fn();+ const submission = createTransferSubmission({ preview: async () => preview(), confirmOwnership: async () => "preserve", confirm: async () => ({ objects, oraclePackages: packageOptions() }), execute });+ await expect(submission.start(request({ objects: [{ objectType: "PACKAGE_BODY", names: ["Pkg.With.Dot😀"] }] }))).rejects.toThrow("TRANSFER_PACKAGE_REVIEW_SCOPE_CHANGED");+ expect(execute).not.toHaveBeenCalled();+ });+it("reviews backend SQL and executes the frozen request only after confirmation", async () => {const decision = deferred<boolean>();const reviewed: Array<{ request: TransferRequest; preview: TransferOwnershipPreview }> = [];diff --git a/apps/desktop/src/components/transfer/transferStrategy.ts b/apps/desktop/src/components/transfer/transferStrategy.tsindex 3e54297ce8..e672185e5e 100644--- a/apps/desktop/src/components/transfer/transferStrategy.ts+++ b/apps/desktop/src/components/transfer/transferStrategy.ts@@ -1,4 +1,4 @@-import type { TransferContent, TransferMode, TransferOwnershipPolicy, TransferOwnershipPreview, TransferRequest } from "@/lib/backend/api";+import type { TransferContent, TransferMode, TransferOwnershipPolicy, TransferOwnershipPreview, TransferRequest, OraclePackageTransferRequest } from "@/lib/backend/api";import type { ConnectionConfig, DatabaseType } from "@/types/database";import { productionContextForDatabase } from "@/lib/database/productionSafety";import { useProductionSafetyStore } from "@/stores/productionSafetyStore";@@ -29,12 +29,20 @@ export function rebuildUnavailableReason(content: TransferContent, targetType: D/** Snapshot the complete selection before any asynchronous preview or confirmation. */function freezeTransferRequest(request: TransferRequest): TransferRequest {+ const oraclePackages: OraclePackageTransferRequest | undefined = request.oraclePackages && JSON.parse(JSON.stringify(request.oraclePackages));+ const freezePackage = (value: unknown): void => {+ if (!value || typeof value !== "object") return;+ for (const child of Object.values(value)) freezePackage(child);+ Object.freeze(value);+ };+ freezePackage(oraclePackages);const snapshot = {...request,...transferStrategyOptions(resolveTransferStrategy(request)),tables: [...request.tables],objects: request.objects.map((selection) => ({ ...selection, names: [...selection.names] })),dropTargetConfirmed: false,+ ...(oraclePackages ? { oraclePackages } : {}),};Object.freeze(snapshot.tables);for (const selection of snapshot.objects) {@@ -70,11 +78,16 @@ export function hasTransferSqlPreview(preview: TransferOwnershipPreview): booleareturn Boolean(preview.rebuild || preview.structure);}+export interface TransferPackageConfirmation {+ objects: TransferRequest["objects"];+ oraclePackages: OraclePackageTransferRequest;+}+interface TransferSubmissionOptions {ensureWritable?: (request: TransferRequest) => Promise<boolean>;preview: (request: TransferRequest) => Promise<TransferOwnershipPreview>;confirmOwnership: (preview: TransferOwnershipPreview) => Promise<TransferOwnershipPolicy | null>;- confirm: (request: TransferRequest, preview: TransferOwnershipPreview) => Promise<boolean>;+ confirm: (request: TransferRequest, preview: TransferOwnershipPreview) => Promise<boolean | TransferPackageConfirmation>;execute: (request: TransferRequest) => void;}@@ -106,7 +119,23 @@ export function createTransferSubmission(options: TransferSubmissionOptions) {// A structure-only transfer changes the target schema; never fall back to the plain// start confirmation when the backend did not say what it is going to run.if (request.content === "structureOnly" && !preview.structure) throw new Error(TRANSFER_STRUCTURE_PREVIEW_UNAVAILABLE);- if (!(await options.confirm(request, preview)) || !isCurrent()) return false;+ const decision = await options.confirm(request, preview);+ if (!decision || !isCurrent()) return false;+ if (typeof decision !== "boolean") {+ const isPackage = (selection: TransferRequest["objects"][number]) => selection.objectType === "PACKAGE" || selection.objectType === "PACKAGE_BODY";+ const original = request.objects.filter(isPackage);+ const names = new Set(original.flatMap((selection) => selection.names));+ const other = (objects: TransferRequest["objects"]) => objects.filter((selection) => !isPackage(selection)).map((selection) => [selection.objectType, selection.names]);+ if (+ original.length === 0 ||+ JSON.stringify(other(request.objects)) !== JSON.stringify(other(decision.objects)) ||+ decision.objects.filter(isPackage).some((selection) => selection.names.some((name) => !names.has(name))) ||+ original.some((selection) => selection.names.some((name) => !decision.objects.some((next) => next.objectType === selection.objectType && next.names.includes(name))))+ ) {+ throw new Error("TRANSFER_PACKAGE_REVIEW_SCOPE_CHANGED");+ }+ request = freezeTransferRequest({ ...request, objects: decision.objects, oraclePackages: decision.oraclePackages });+ }options.execute(Object.freeze({ ...request, dropTargetConfirmed: request.dropTargetBeforeCreate }));return true;} catch (error) {diff --git a/apps/desktop/src/composables/__tests__/useExportTracker.spec.ts b/apps/desktop/src/composables/__tests__/useExportTracker.spec.tsindex d1311cef85..6d805cfb22 100644--- a/apps/desktop/src/composables/__tests__/useExportTracker.spec.ts+++ b/apps/desktop/src/composables/__tests__/useExportTracker.spec.ts@@ -1,5 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { SqlFileProgress, TransferProgress, TransferRequest } from "@/lib/backend/api";+import { reactive } from "vue";+import { createOracleRoutineDeployment, disposeOracleRoutineDeployment } from "@/lib/schema/oracleRoutineDeploy";vi.mock("@/lib/backend/api", () => ({startTransfer: vi.fn(),@@ -7,12 +9,15 @@ vi.mock("@/lib/backend/api", () => ({cancelDatabaseExport: vi.fn(),cancelSqlFileExecution: vi.fn(),cancelTableExport: vi.fn(),+ updateOracleRoutineOperationReferences: vi.fn().mockResolvedValue(undefined),}));const mockAutoRevealExportedPathIfConfigured = vi.fn();vi.mock("@/lib/export/exportPath", () => ({autoRevealExportedPathIfConfigured: (...args: unknown[]) => mockAutoRevealExportedPathIfConfigured(...args),}));+vi.mock("@/lib/metadata/objectDdlCache", () => ({ invalidateObjectDdlCache: vi.fn() }));+vi.mock("@/lib/table/objectBrowserRowsCache", () => ({ invalidateObjectBrowserRowsCache: vi.fn() }));import * as api from "@/lib/backend/api";import {@@ -98,6 +103,87 @@ afterEach(() => {});describe("data transfer task duration", () => {+ it("ignores a progress packet from another transfer before changing task state", () => {+ const tracker = useExportTracker();+ const task = tracker.addDataTransferTask("bound-transfer", "users", 1);+ tracker.updateDataTransferTask(task.exportId, transferProgress(task.exportId, "running", false));+ tracker.updateDataTransferTask(task.exportId, { ...transferProgress("different-transfer", "done"), rowsTransferred: 99 });+ expect(task.status).toBe("Running");+ expect(task.rowsExported).toBe(10);+ expect(task.finishedAt).toBeUndefined();+ });++ it.each(["oraclePackageApproval", "oraclePackagePreflight"] as const)("keeps completed table rows when receiving %s", (field) => {+ const tracker = useExportTracker();+ const task = tracker.addDataTransferTask(`rows-${field}`, "users and packages", 1);+ tracker.updateDataTransferTask(task.exportId, transferProgress(task.exportId, "tableDone", false));+ const endpoint = { connectionId: "target", database: "tenant", schema: "T", databaseType: "oceanbase-oracle" as const, generation: 1 };+ const snapshot = { endpoint, state: "complete" as const, enumerationComplete: true, objects: [], issues: [] };+ tracker.updateDataTransferTask(task.exportId, {+ ...transferProgress(task.exportId, field === "oraclePackagePreflight" ? "error" : "running", false),+ table: "package objects",+ rowsTransferred: 0,+ totalRows: null,+ [field]: { input: { source: snapshot, target: snapshot, drafts: [] }, skipped: [], plan: { target: endpoint, ready: false, steps: [] } },+ });+ expect(task.rowsExported).toBe(10);+ expect(task.totalRows).toBe(10);+ expect(task.finishedAt).toBeUndefined();+ tracker.updateDataTransferTask(task.exportId, { ...transferProgress(task.exportId, "error"), table: "" });+ expect(task.rowsExported).toBe(10);+ expect(task.status).toBe("Error");+ });++ it("keeps the original package approvals owned by the background task until its result is removed", async () => {+ const endpoint = { connectionId: "target", database: "tenant", schema: "T", databaseType: "oceanbase-oracle" as const, generation: 1 };+ const snapshot = { endpoint, state: "complete" as const, enumerationComplete: true, objects: [], issues: [] };+ const deployment = reactive(createOracleRoutineDeployment(snapshot, snapshot));+ deployment.retainedOperationIds = ["original-package-operation"];+ const identity = { owner: "T", name: "P", kind: "PACKAGE_BODY" as const };+ const prepared = { operationId: "original-package-operation", target: endpoint, identity, lifecycle: "prepared" as const, dispatched: false, acknowledged: false, readback: null, error: null };+ deployment.records = [prepared];+ deployment.drafts = [{ identity, action: "create", objectId: "body", included: true, operation: prepared }];+ let finish!: () => void;+ let publish!: (progress: TransferProgress) => void;+ vi.mocked(api.startTransfer).mockImplementationOnce(+ (request, progress) =>+ new Promise<void>((resolve) => {+ publish = progress;+ finish = () => {+ progress(transferProgress(request.transferId, "error"));+ resolve();+ };+ }),+ );+ const tracker = useExportTracker();+ const cleanup = vi.fn(() => {+ void disposeOracleRoutineDeployment(deployment);+ });+ const task = tracker.startDataTransferTask(transferRequest("package-reference-owner", []), "package", { oracleRoutineDeployment: deployment, onRemove: cleanup });+ expect(task.oracleRoutineDeployment).toBe(deployment);+ expect(deployment.executing).toBe(true);+ expect(api.updateOracleRoutineOperationReferences).not.toHaveBeenCalled();+ const bodyResult = {+ ...prepared,+ lifecycle: "terminal" as const,+ dispatched: true,+ acknowledged: true,+ readback: { identity, state: "invalid" as const, exists: true, version: null, source: "full original body 中文😀", definitionMatches: true, issues: [], compilerMessages: [{ attribute: "ERROR" as const, line: 2, position: 3, text: "PLS-00323" }] },+ };+ publish({ ...transferProgress(task.exportId, "error", false), oracleRoutineOperation: bodyResult });+ expect(task.status).toBe("Running");+ expect(deployment.drafts[0].operation).toEqual(bodyResult);+ expect(deployment.records[0].operationId).toBe("original-package-operation");+ finish();+ await vi.waitFor(() => expect(deployment.executing).toBe(false));+ expect(task.status).toBe("Error");+ expect(deployment.retainedOperationIds).toEqual(["original-package-operation"]);+ expect(cleanup).not.toHaveBeenCalled();+ tracker.removeTask(task.exportId);+ await vi.waitFor(() => expect(api.updateOracleRoutineOperationReferences).toHaveBeenCalledWith([], ["original-package-operation"]));+ expect(cleanup).toHaveBeenCalledOnce();+ });+it("freezes the first successful terminal duration", () => {const tracker = useExportTracker();now = 1_000;diff --git a/apps/desktop/src/composables/__tests__/useSchemaDiffSession.spec.ts b/apps/desktop/src/composables/__tests__/useSchemaDiffSession.spec.tsindex 3cd4900ecb..46a6505d3b 100644--- a/apps/desktop/src/composables/__tests__/useSchemaDiffSession.spec.ts+++ b/apps/desktop/src/composables/__tests__/useSchemaDiffSession.spec.ts@@ -553,3 +553,196 @@ test("a strict-snapshot endpoint mismatch fails the session without generating aassert.match(session.error ?? "", /endpoint/);assert.equal(apiMock.prepareSchemaDiff.mock.calls.length, 0);});++test("carries immutable BODY-only selection and kind-scoped evidence through the real comparison session", async () => {+ vi.clearAllMocks();+ apiMock.loadSchemaDiffRoutines.mockImplementation(async (connectionId: string, database: string, schema: string) => ({+ endpoint: { connectionId, database, schema, databaseType: "oceanbase-oracle", generation: 6 },+ state: connectionId.endsWith("source") ? "partial" : "complete",+ enumerationComplete: true,+ issues: [],+ objects: (["PACKAGE", "PACKAGE_BODY"] as const).map((kind, index) => ({+ version: { identity: { owner: schema, name: "Pkg.With.Dot", kind }, objectId: String(12 + index), status: "VALID", lastDdlTime: "2026-10-23T01:00:00" },+ source: `CREATE OR REPLACE ${kind.replace("_", " ")} "${schema}"."Pkg.With.Dot" AS END;`,+ sourceOrigin: "oceanbase-dictionary",+ sourceComplete: !(connectionId.endsWith("source") && kind === "PACKAGE_BODY"),+ dependenciesComplete: true,+ dependencies: [],+ issues: [],+ })),+ }));+ apiMock.prepareSchemaDiff.mockResolvedValue({ diffs: [], functionDiffs: [], syncSql: "" });+ const routineObjectKinds: Array<"PACKAGE_BODY" | "PACKAGE"> = ["PACKAGE_BODY"];+ const selectedRoutineObjects = [{ name: "Pkg.With.Dot", kind: "PACKAGE_BODY" as const }];+ const session = startSchemaDiffSession(+ {+ sourceConnectionId: "package-source",+ sourceDatabase: "db",+ sourceSchema: "S",+ targetConnectionId: "package-target",+ targetDatabase: "db",+ targetSchema: "T",+ sourceDbType: "oceanbase-oracle",+ targetDbType: "oceanbase-oracle",+ options: { tables: false, functions: true, routineObjectKinds, selectedRoutineObjects },+ ignoreComments: false,+ label: "body only",+ },+ { tableListLoader: { load: vi.fn().mockResolvedValue([]) } },+ );+ routineObjectKinds.push("PACKAGE");+ selectedRoutineObjects[0]!.name = "changed outside the session";+ await waitForSession(session);+ assert.equal(session.status, "completed", session.error ?? "");+ assert.equal(apiMock.listFunctions.mock.calls.length, 0);+ for (const call of apiMock.loadSchemaDiffRoutines.mock.calls) {+ assert.equal(call[3], undefined);+ assert.deepEqual(call[4], { objectKinds: ["PACKAGE_BODY"], selectedObjects: [{ name: "Pkg.With.Dot", kind: "PACKAGE_BODY" }] });+ }+ assert.equal(session.routineSnapshots?.source?.objects.length, 2, "keep the specification as read-only evidence");+ assert.equal(session.routineSnapshots?.source?.objects[0]?.sourceOrigin, "oceanbase-dictionary");+ assert.equal(session.routineSnapshots?.target?.objects[1]?.sourceOrigin, "oceanbase-dictionary");+ const payload = apiMock.prepareSchemaDiff.mock.calls[0][0];+ assert.deepEqual(+ payload.sourceFunctions.map((object: { function_type: string }) => object.function_type),+ ["PACKAGE_BODY"],+ );+ assert.deepEqual(+ payload.targetFunctions.map((object: { function_type: string }) => object.function_type),+ ["PACKAGE_BODY"],+ );+ assert.deepEqual(payload.oracleRoutines.objectKinds, ["PACKAGE_BODY"]);+ assert.deepEqual(payload.oracleRoutines.sourceIncompleteObjects, [{ name: "Pkg.With.Dot", kind: "PACKAGE_BODY" }]);+ assert.deepEqual(payload.oracleRoutines.targetIncompleteObjects, []);+});++test("rejects package comparison on unsupported products instead of silently comparing empty lists", async () => {+ vi.clearAllMocks();+ apiMock.listFunctions.mockResolvedValue([]);+ const session = startSchemaDiffSession(+ {+ sourceConnectionId: "unsupported-source",+ sourceDatabase: "db",+ sourceSchema: "S",+ targetConnectionId: "unsupported-target",+ targetDatabase: "db",+ targetSchema: "T",+ sourceDbType: "mysql",+ targetDbType: "mysql",+ options: { tables: false, functions: true, routineObjectKinds: ["PACKAGE_BODY"] },+ ignoreComments: false,+ label: "unsupported",+ },+ { tableListLoader: { load: vi.fn().mockResolvedValue([]) } },+ );+ await waitForSession(session);+ assert.equal(session.status, "failed");+ assert.match(session.error ?? "", /Oracle product/);+ assert.equal(apiMock.listFunctions.mock.calls.length, 0);+ assert.equal(apiMock.prepareSchemaDiff.mock.calls.length, 0);+});++test.each([+ ["oracle", "oceanbase-oracle"],+ ["oceanbase-oracle", "oracle"],+] as const)("loads exact package evidence for a read-only %s to %s comparison", async (sourceType, targetType) => {+ vi.clearAllMocks();+ apiMock.loadSchemaDiffRoutines.mockImplementation(async (connectionId: string, database: string, schema: string) => {+ const databaseType = connectionId.endsWith("source") ? sourceType : targetType;+ return {+ endpoint: { connectionId, database, schema, databaseType, generation: 1 },+ state: "complete",+ enumerationComplete: true,+ issues: [],+ objects: ["PACKAGE", "PACKAGE_BODY"].map((kind, index) => ({+ version: { identity: { owner: schema, name: "Pkg.With.Dot", kind }, objectId: String(10 + index), status: "VALID", lastDdlTime: "1" },+ source: `CREATE OR REPLACE ${kind.replace("_", " ")} "${schema}"."Pkg.With.Dot" AS END;`,+ sourceOrigin: databaseType === "oracle" ? "oracle-metadata" : "oceanbase-dictionary",+ sourceComplete: true,+ dependenciesComplete: true,+ dependencies: [],+ issues: [],+ })),+ };+ });+ apiMock.prepareSchemaDiff.mockResolvedValue({ diffs: [], functionDiffs: [], syncSql: "" });+ const session = startSchemaDiffSession(+ {+ sourceConnectionId: "cross-package-source",+ sourceDatabase: "db",+ sourceSchema: "S",+ targetConnectionId: "cross-package-target",+ targetDatabase: "db",+ targetSchema: "T",+ sourceDbType: sourceType,+ targetDbType: targetType,+ options: { tables: false, functions: true, routineObjectKinds: ["PACKAGE_BODY"], selectedRoutineObjects: [{ name: "Pkg.With.Dot", kind: "PACKAGE_BODY" }] },+ ignoreComments: false,+ label: "cross-product package",+ },+ { tableListLoader: { load: vi.fn().mockResolvedValue([]) } },+ );+ await waitForSession(session);+ assert.equal(session.status, "completed", session.error ?? "");+ assert.equal(apiMock.loadSchemaDiffRoutines.mock.calls.length, 2);+ const payload = apiMock.prepareSchemaDiff.mock.calls[0][0];+ assert.deepEqual(+ payload.sourceFunctions.map((object: { function_type: string }) => object.function_type),+ ["PACKAGE_BODY"],+ );+ assert.deepEqual(+ payload.targetFunctions.map((object: { function_type: string }) => object.function_type),+ ["PACKAGE_BODY"],+ );+ assert.equal(payload.oracleRoutines.sourceDatabaseType, sourceType);+ assert.equal(payload.oracleRoutines.targetDatabaseType, targetType);+ assert.equal(session.routineSnapshots?.source?.objects.length, 2);+});++test("rejects explicitly selected standalone kinds in a cross-product package comparison before metadata requests", async () => {+ vi.clearAllMocks();+ const session = startSchemaDiffSession(+ {+ sourceConnectionId: "cross-pf-source",+ sourceDatabase: "db",+ sourceSchema: "S",+ targetConnectionId: "cross-pf-target",+ targetDatabase: "db",+ targetSchema: "T",+ sourceDbType: "oracle",+ targetDbType: "oceanbase-oracle",+ options: { tables: false, functions: true, routineObjectKinds: ["FUNCTION", "PACKAGE_BODY"] },+ ignoreComments: false,+ label: "unsupported mixed kinds",+ },+ { tableListLoader: { load: vi.fn().mockResolvedValue([]) } },+ );+ await waitForSession(session);+ assert.equal(session.status, "failed");+ assert.equal(apiMock.loadSchemaDiffRoutines.mock.calls.length, 0);+ assert.equal(apiMock.prepareSchemaDiff.mock.calls.length, 0);+});++test.each([{ routineObjectKinds: ["PACKAGE_BODY"], selectedRoutines: ["P"] }, { selectedRoutineObjects: [{ name: "P", kind: "PACKAGE_BODY" }] }])("rejects ambiguous typed selection before issuing metadata requests: %j", async (selection) => {+ vi.clearAllMocks();+ const session = startSchemaDiffSession(+ {+ sourceConnectionId: "ambiguous-source",+ sourceDatabase: "db",+ sourceSchema: "S",+ targetConnectionId: "ambiguous-target",+ targetDatabase: "db",+ targetSchema: "T",+ sourceDbType: "oceanbase-oracle",+ targetDbType: "oceanbase-oracle",+ options: { tables: false, functions: true, ...selection },+ ignoreComments: false,+ label: "ambiguous",+ },+ { tableListLoader: { load: vi.fn().mockResolvedValue([]) } },+ );+ await waitForSession(session);+ assert.equal(session.status, "failed");+ assert.equal(apiMock.loadSchemaDiffRoutines.mock.calls.length, 0);+ assert.equal(apiMock.prepareSchemaDiff.mock.calls.length, 0);+});diff --git a/apps/desktop/src/composables/useExportTracker.ts b/apps/desktop/src/composables/useExportTracker.tsindex c302c6dac4..d54dfb91ac 100644--- a/apps/desktop/src/composables/useExportTracker.ts+++ b/apps/desktop/src/composables/useExportTracker.ts@@ -4,6 +4,7 @@ import { isTerminalTransferProgress } from "@/lib/backend/transferProgress";import { uuid } from "@/lib/common/utils";import { formatQueryDuration } from "@/lib/format/duration";import { autoRevealExportedPathIfConfigured } from "@/lib/export/exportPath";+import { acceptOraclePackageTransferApproval, acceptOraclePackageTransferPreflight, acceptOracleRoutineDeploymentOperation, type OracleRoutineDeployment } from "@/lib/schema/oracleRoutineDeploy";export type BackgroundTaskKind = "table-export" | "database-export" | "data-dictionary" | "sql-file" | "data-transfer" | "data-generation" | "multi-db-execution" | "schema-diff" | "data-compare";export type BackgroundTaskStatus = "Running" | "Writing" | "Cancelling" | "Done" | "Error" | "Cancelled";@@ -66,6 +67,7 @@ export interface ExportTask {targetTables?: string[];transferFailures?: DataTransferFailure[];transferFailuresOmitted?: number;+ oracleRoutineDeployment?: OracleRoutineDeployment;sqlFileFailures?: SqlFileFailure[];sqlFileFailuresOmitted?: number;multiDbSourceTabId?: string;@@ -167,6 +169,7 @@ interface SqlFileFailureState {const taskMap = reactive<Map<string, ExportTask>>(new Map());const activeTransferRuns = new Set<string>();+const packageTransferConfirmations = new WeakMap<ExportTask, api.OraclePackageTransferRequest>();const taskCancelHandlers = new Map<string, () => void | Promise<void>>();const transferFailureStates = new Map<string, TransferFailureState>();const sqlFileFailureStates = new Map<string, SqlFileFailureState>();@@ -622,6 +625,8 @@ export function useExportTracker() {onStarted?: () => void;onDone?: () => void | Promise<void>;onOpen?: () => void;+ onRemove?: () => void;+ oracleRoutineDeployment?: OracleRoutineDeployment;formatOverlapError?: (tables: string[]) => string;} = {},): ExportTask {@@ -635,6 +640,10 @@ export function useExportTracker() {task.targetSchema = request.targetSchema;task.targetTables = request.tables.map((table) => targetTableName(table, request.targetTableNameCase));if (activeTransferRuns.has(request.transferId)) return task;+ task.onRemove = options.onRemove;+ task.oracleRoutineDeployment = options.oracleRoutineDeployment;+ if (request.oraclePackages?.pendingTables) packageTransferConfirmations.set(task, JSON.parse(JSON.stringify(request.oraclePackages)));+ else packageTransferConfirmations.delete(task);const overlappingTables = findActiveOverlappingTransfer(request);if (overlappingTables.length > 0) {@@ -646,6 +655,7 @@ export function useExportTracker() {}activeTransferRuns.add(request.transferId);+ if (task.oracleRoutineDeployment) task.oracleRoutineDeployment.executing = true;let terminalStatus: api.TransferProgress["status"] | null = null;let startAcknowledged = false;const acknowledgeStart = () => {@@ -681,6 +691,10 @@ export function useExportTracker() {terminal: true,});} finally {+ if (task.oracleRoutineDeployment) {+ task.oracleRoutineDeployment.executing = false;+ if (task.oracleRoutineDeployment.plan) task.oracleRoutineDeployment.plan.ready = false;+ }activeTransferRuns.delete(request.transferId);}})();@@ -757,7 +771,17 @@ export function useExportTracker() {function updateDataTransferTask(transferId: string, progress: api.TransferProgress) {const task = taskMap.get(transferId);- if (!task) return;+ if (!task || progress.transferId !== transferId) return;+ const pendingConfirmation = packageTransferConfirmations.get(task);+ if (progress.oraclePackagePreflight && !progress.oraclePackageApproval && !progress.oracleRoutineOperation && pendingConfirmation && task.oracleRoutineDeployment) {+ acceptOraclePackageTransferPreflight(task.oracleRoutineDeployment, pendingConfirmation, progress.oraclePackagePreflight);+ }+ if (progress.oraclePackageApproval && !progress.oraclePackagePreflight && !progress.oracleRoutineOperation && pendingConfirmation && task.oracleRoutineDeployment) {+ void acceptOraclePackageTransferApproval(task.oracleRoutineDeployment, pendingConfirmation, progress.oraclePackageApproval);+ }+ if (progress.oracleRoutineOperation && task.oracleRoutineDeployment) {+ acceptOracleRoutineDeploymentOperation(task.oracleRoutineDeployment, progress.oracleRoutineOperation);+ }if (progress.transferFailuresOmitted !== undefined) {const state = getTransferFailureState(task);state.replayOmittedCount = Math.max(state.replayOmittedCount, progress.transferFailuresOmitted);@@ -774,7 +798,8 @@ export function useExportTracker() {task.tableIndex = progress.tableIndex;task.totalTables = progress.totalTables;task.currentTable = progress.table || task.currentTable;- if (progress.table || progress.rowsTransferred > 0 || task.rowsExported === 0) {+ const packageEvent = progress.oraclePackageApproval || progress.oraclePackagePreflight || progress.oracleRoutineOperation;+ if (!packageEvent && (progress.table || progress.rowsTransferred > 0 || task.rowsExported === 0)) {task.rowsExported = progress.rowsTransferred;}task.totalRows = progress.totalRows ?? task.totalRows;diff --git a/apps/desktop/src/composables/useSchemaDiffSession.ts b/apps/desktop/src/composables/useSchemaDiffSession.tsindex b1a3378136..bac6e82587 100644--- a/apps/desktop/src/composables/useSchemaDiffSession.ts+++ b/apps/desktop/src/composables/useSchemaDiffSession.ts@@ -5,17 +5,17 @@ import { openSchemaDiffSession } from "@/composables/useDialogSources";import { useExportTracker } from "@/composables/useExportTracker";import { filterSchemaDiffTables } from "@/lib/schema/schemaDiffTableFilter";import { compileSchemaDiffTableFilter } from "@/lib/schema/schemaDiffTableFilter";-import { filterSchemaDiffFunctions } from "@/lib/schema/schemaDiffRoutine";+import { filterSchemaDiffFunctions, schemaDiffRoutineKeyFromFunction } from "@/lib/schema/schemaDiffRoutine";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, schemaDiffRoutineProductType } from "@/lib/database/databaseObjectCapabilities";import { convertToSchemaDiffObjects, databaseTypeToDialectKind, normalizeDialectKind, schemaDiffDeployTargetSchema, type SchemaDiffObject } from "@/lib/schema/schemaDiff";-import { normalizeSchemaDiffCompareOptions, type OracleRoutineCompareContext, type OracleRoutineSnapshot, type SchemaDiffCompareOptions } from "@/types/schemaDiff";-import type { DatabaseType, FunctionInfo, TableInfo } from "@/types/database";+import { normalizeSchemaDiffCompareOptions, type OracleRoutineCompareContext, type OracleRoutineKind, type OracleRoutineSnapshot, type SchemaDiffCompareOptions } from "@/types/schemaDiff";+import type { DatabaseType, FunctionInfo, TableInfo, TransferPackageDraft } from "@/types/database";import type { SchemaDiffPreparation } from "@/lib/schema/schemaDiff";-import { disposeOracleRoutineDeployment, type OracleRoutineDeployment } from "@/lib/schema/oracleRoutineDeploy";+import { createOracleRoutineDeployment, disposeOracleRoutineDeployment, synchronizeOracleRoutineSelection, type OracleRoutineDeployment } from "@/lib/schema/oracleRoutineDeploy";export interface SchemaDiffSessionProgress {phase: SchemaDiffProgressPhase;@@ -66,6 +66,12 @@ export interface SchemaDiffSessionDependencies {tableListLoader: SchemaDiffTableListLoader;}+export interface OraclePackageComparisonHandoff {+ source: OracleRoutineSnapshot["endpoint"];+ target: OracleRoutineSnapshot["endpoint"];+ drafts: readonly TransferPackageDraft[];+}+const sessions = reactive(new Map<string, SchemaDiffSession>());function schemaDiffDialect(dbType: DatabaseType | string | undefined, explicit: string | undefined): string | undefined {@@ -79,6 +85,8 @@ function cloneOptions(options: SchemaDiffCompareOptions): SchemaDiffCompareOptioselectedTables: options.selectedTables ? [...options.selectedTables] : options.selectedTables,tableMappings: options.tableMappings?.map((mapping) => ({ ...mapping })),selectedRoutines: options.selectedRoutines ? [...options.selectedRoutines] : options.selectedRoutines,+ ...(options.routineObjectKinds === undefined ? {} : { routineObjectKinds: [...options.routineObjectKinds] }),+ ...(options.selectedRoutineObjects === undefined ? {} : { selectedRoutineObjects: options.selectedRoutineObjects.map((object) => ({ ...object })) }),routineMappings: options.routineMappings?.map((mapping) => ({ ...mapping })),fieldMappings: options.fieldMappings?.map((mapping) => ({ ...mapping })),};@@ -92,8 +100,12 @@ function sessionError(error: unknown): string {return error instanceof Error ? error.message : (error as { message?: string } | null)?.message || String(error);}-function filterFunctionsByRoutineKinds(functions: FunctionInfo[], kinds: Array<"PROCEDURE" | "FUNCTION">): FunctionInfo[] {+function filterFunctionsByRoutineKinds(functions: FunctionInfo[], kinds: OracleRoutineKind[], exactKind = false): FunctionInfo[] {if (kinds.length === 0) return [];+ if (exactKind) {+ const allowed = new Set<string>(kinds);+ return functions.filter((fn) => allowed.has(fn.function_type));+ }if (kinds.length === 2) return functions;const allowProcedure = kinds.includes("PROCEDURE");const allowFunction = kinds.includes("FUNCTION");@@ -116,7 +128,10 @@ async function loadSessionRoutines(session: SchemaDiffSession, side: "source" |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);+ const snapshot =+ input.options.routineObjectKinds === undefined+ ? await api.loadSchemaDiffRoutines(connectionId, database, schema, input.options?.selectedRoutines)+ : await api.loadSchemaDiffRoutines(connectionId, database, schema, undefined, { objectKinds: input.options.routineObjectKinds, ...(input.options.selectedRoutineObjects === undefined ? {} : { selectedObjects: input.options.selectedRoutineObjects }) });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");@@ -145,13 +160,14 @@ async function settleRequests<T>(requests: Promise<T>[]): Promise<T[]> {});}-async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: SchemaDiffSessionDependencies, signal: AbortSignal): Promise<void> {+async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: SchemaDiffSessionDependencies, signal: AbortSignal, handoff?: OraclePackageComparisonHandoff): Promise<void> {const input = session.config;const tracker = useExportTracker();const options = normalizeSchemaDiffCompareOptions(input.options, input.targetDbType);const sourceRoutineType = schemaDiffRoutineProductType(input.sourceDbType, input.sourceEngineDbType);const targetRoutineType = schemaDiffRoutineProductType(input.targetDbType, input.targetEngineDbType);- const routineKinds = schemaDiffRoutineObjectTypesIntersection(sourceRoutineType, targetRoutineType);+ const routineKinds = options.routineObjectKinds ?? schemaDiffRoutineObjectTypesIntersection(sourceRoutineType, targetRoutineType);+ const typedRoutines = options.routineObjectKinds !== undefined;const loadRoutines = shouldLoadSchemaDiffRoutines(sourceRoutineType, targetRoutineType, options);const sessionOptions = options;const isPostgresLike = isSchemaDiffPostgresLike(input.targetDbType);@@ -160,6 +176,12 @@ async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: Scconst loadTableMetadata = !!(sessionOptions.tables || sessionOptions.views);try {+ if (sessionOptions.functions && (typedRoutines || sessionOptions.selectedRoutineObjects !== undefined)) {+ if (!isOracleRoutineEngine(sourceRoutineType ?? "") || !isOracleRoutineEngine(targetRoutineType ?? "")) throw new Error("Typed program comparison requires two Oracle product endpoints");+ if (!typedRoutines || sessionOptions.selectedRoutines !== undefined) throw new Error("Typed program selection requires explicit kinds and cannot use legacy routine names");+ const supported = new Set(schemaDiffRoutineObjectTypesIntersection(sourceRoutineType, targetRoutineType, routineKinds));+ if (!routineKinds.length || routineKinds.some((kind) => !supported.has(kind))) throw new Error("The selected program kinds are not supported for this exact product pair; cross-product comparison supports explicit package kinds only");+ }publishProgress(session, { phase: "loading-table-lists" });let sourceTables: TableInfo[] = [];@@ -237,9 +259,10 @@ async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: Scconst extraObjects = await settleRequests(promises);signal.throwIfAborted();let index = 0;- const listedSourceFunctions = loadRoutines ? filterFunctionsByRoutineKinds(extraObjects[index++] as FunctionInfo[], routineKinds) : [];- const listedTargetFunctions = loadRoutines ? filterFunctionsByRoutineKinds(extraObjects[index++] as FunctionInfo[], routineKinds) : [];- const { sourceFunctions, targetFunctions } = filterSchemaDiffFunctions(listedSourceFunctions, listedTargetFunctions, sessionOptions.selectedRoutines, sessionOptions.routineMappings ?? []);+ const listedSourceFunctions = loadRoutines ? filterFunctionsByRoutineKinds(extraObjects[index++] as FunctionInfo[], routineKinds, typedRoutines) : [];+ const listedTargetFunctions = loadRoutines ? filterFunctionsByRoutineKinds(extraObjects[index++] as FunctionInfo[], routineKinds, typedRoutines) : [];+ const selectedRoutineKeys = typedRoutines ? sessionOptions.selectedRoutineObjects?.map((object) => schemaDiffRoutineKeyFromFunction({ name: object.name, function_type: object.kind, arguments: "" }, true)) : sessionOptions.selectedRoutines;+ const { sourceFunctions, targetFunctions } = filterSchemaDiffFunctions(listedSourceFunctions, listedTargetFunctions, selectedRoutineKeys, sessionOptions.routineMappings ?? [], typedRoutines);const sourceSequences = sessionOptions.sequences && isPostgresLike ? (extraObjects[index++] as Awaited<ReturnType<typeof api.listSequences>>) : [];const targetSequences = sessionOptions.sequences && isPostgresLike ? (extraObjects[index++] as Awaited<ReturnType<typeof api.listSequences>>) : [];const sourceRules = sessionOptions.rules && isPostgresLike ? (extraObjects[index++] as Awaited<ReturnType<typeof api.listRules>>) : [];@@ -258,6 +281,13 @@ async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: SctargetEnumerationComplete: 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) ?? [],+ ...(typedRoutines+ ? {+ objectKinds: sessionOptions.routineObjectKinds,+ sourceIncompleteObjects: source?.objects.filter((object) => !object.sourceComplete).map((object) => ({ name: object.version.identity.name, kind: object.version.identity.kind })) ?? [],+ targetIncompleteObjects: target?.objects.filter((object) => !object.sourceComplete).map((object) => ({ name: object.version.identity.name, kind: object.version.identity.kind })) ?? [],+ }+ : {}),};}@@ -309,6 +339,30 @@ async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: Scsignal.throwIfAborted();publishProgress(session, { phase: "generating" });+ if (handoff) {+ const snapshots = session.routineSnapshots;+ if (!snapshots?.source || !snapshots.target) throw new Error("Transferred package drafts require the original strict comparison endpoints");+ for (const side of ["source", "target"] as const) {+ if ((["connectionId", "database", "schema", "databaseType", "generation"] as const).some((key) => snapshots[side]!.endpoint[key] !== handoff[side][key])) throw new Error("The package comparison endpoint changed during handoff; retain the transfer draft and refresh its original identities");+ }+ const state = reactive(createOracleRoutineDeployment(snapshots.source, snapshots.target));+ const objects = schemaDiffSessionObjects(result);+ for (const saved of handoff.drafts) {+ if ((saved.identity.kind !== "PACKAGE" && saved.identity.kind !== "PACKAGE_BODY") || saved.identity.owner !== snapshots.target.endpoint.schema) throw new Error("Transferred drafts must retain their exact package target identities");+ const object = objects.find((object) => object.name === saved.identity.name && object.routineType === saved.identity.kind);+ if (!object) throw new Error(`Package ${saved.identity.kind} ${saved.identity.name} is unavailable in the fresh comparison; retain its draft in the transfer preview`);+ if (object && saved.sql?.trim() && (object.operationType === "delete" || (object.operationType === "none" && saved.reviewedTargetDraft))) {+ object.operationType = snapshots.target.objects.some((target) => target.version.identity.owner === saved.identity.owner && target.version.identity.name === saved.identity.name && target.version.identity.kind === saved.identity.kind) ? "modify" : "create";+ object.selected = true;+ }+ }+ synchronizeOracleRoutineSelection(state, objects);+ for (const draft of state.drafts) {+ const saved = handoff.drafts.find((saved) => saved.identity.owner === draft.identity.owner && saved.identity.name === draft.identity.name && saved.identity.kind === draft.identity.kind);+ if (saved) Object.assign(draft, saved, { identity: { ...saved.identity }, confirmPackagePair: false });+ }+ session.routineDeployment = state;+ }session.result = result;session.progress = { phase: "complete" };session.version += 1;@@ -335,7 +389,7 @@ async function runSchemaDiffSession(session: SchemaDiffSession, dependencies: Sc}}-export function startSchemaDiffSession(input: Omit<SchemaDiffSessionConfig, "options"> & { options: SchemaDiffCompareOptions }, dependencies: SchemaDiffSessionDependencies): SchemaDiffSession {+export function startSchemaDiffSession(input: Omit<SchemaDiffSessionConfig, "options"> & { options: SchemaDiffCompareOptions }, dependencies: SchemaDiffSessionDependencies, handoff?: OraclePackageComparisonHandoff): SchemaDiffSession {const id = uuid();const session = shallowReactive<SchemaDiffSession>({id,@@ -360,7 +414,12 @@ export function startSchemaDiffSession(input: Omit<SchemaDiffSessionConfig, "opt() => removeSchemaDiffSession(id),);const controller = new AbortController();- const settled = runSchemaDiffSession(session, dependencies, controller.signal);+ const frozenHandoff = handoff && {+ source: { ...handoff.source },+ target: { ...handoff.target },+ drafts: handoff.drafts.map(({ identity, sourceName, sql, packageBodySource, packageContract, reviewedTargetDraft }) => ({ identity: { ...identity }, sourceName, sql, packageBodySource, packageContract, reviewedTargetDraft })),+ };+ const settled = runSchemaDiffSession(session, dependencies, controller.signal, frozenHandoff);registerSchemaDiffTask([input.sourceConnectionId, input.targetConnectionId], controller, settled);return session;}@@ -381,7 +440,14 @@ export function schemaDiffSessionNextProgressStep(session: SchemaDiffSession): sreturn getSchemaDiffNextProgressStep(session.progress?.phase, shouldLoadSchemaDiffExtraObjectPhase(schemaDiffRoutineProductType(config.sourceDbType, config.sourceEngineDbType), schemaDiffRoutineProductType(config.targetDbType, config.targetEngineDbType), config.options));}-export function schemaDiffSessionObjects(result: SchemaDiffPreparation | null): SchemaDiffObject[] {+export function schemaDiffSessionObjects(result: SchemaDiffPreparation | null, deployment?: OracleRoutineDeployment): SchemaDiffObject[] {if (!result) return [];- return convertToSchemaDiffObjects(result.diffs, result.functionDiffs, result.sequenceDiffs, result.ruleDiffs, result.ownerDiffs, result.renameCandidates);+ const objects = convertToSchemaDiffObjects(result.diffs, result.functionDiffs, result.sequenceDiffs, result.ruleDiffs, result.ownerDiffs, result.renameCandidates);+ for (const object of objects) {+ const draft = deployment?.drafts.find((draft) => draft.objectId === object.id);+ if (draft?.sql?.trim() && draft.action !== "delete" && (object.operationType === "delete" || (object.operationType === "none" && draft.reviewedTargetDraft))) {+ object.operationType = draft.action === "replace" ? "modify" : "create";+ }+ }+ return objects;}diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 5d51c80923..19255d877d 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -8957,6 +8957,20 @@ export default {routineObserve: "Check original request",routineRecoveryPreview: "Preview recovery script",routineRecoveryNote: "The recovery script executes new DDL; it is not a transaction rollback.",+ packageAddSpecification: "Add specification to plan",+ packageCrossProduct: "Cross-product drafts require manual review of target semantics before full validation.",+ packageReviewTarget: "Reviewed: use as manual target draft",+ packageUseSourceBody: "Use source body",+ packageRebuildTargetBody: "Retain and rebuild target body",+ packageDeleteWhole: "Delete the whole package instead",+ packageContract: "Specification used to validate body",+ packageSourceContract: "Validate against source specification",+ packageTargetContract: "Validate against target specification",+ packageConfirmDrop: "Confirm deletion of the whole package and its existing body; old grants are not restored automatically",+ packageConfirmImpact: "I have reviewed specification, body, caller impacts and recovery limitations",+ packageSpecificationOnly: "Specification only: the body or member implementations have not been migrated.",+ packageInitialization: "First use may execute package initialization; validation and readback do not call the package.",+ packageGrantBackup: "Original target grants backup",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",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 3065d453f3..b0555e5ad6 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -7813,6 +7813,20 @@ export default withEnglishFallback({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.",+ packageAddSpecification: "Añadir especificación al plan",+ packageCrossProduct: "Los borradores entre productos requieren revisar la semántica de destino antes de la validación completa.",+ packageReviewTarget: "Revisado: usar como borrador manual de destino",+ packageUseSourceBody: "Usar cuerpo de origen",+ packageRebuildTargetBody: "Conservar y reconstruir cuerpo de destino",+ packageDeleteWhole: "Eliminar todo el paquete",+ packageContract: "Especificación para validar el cuerpo",+ packageSourceContract: "Validar con la especificación de origen",+ packageTargetContract: "Validar con la especificación de destino",+ packageConfirmDrop: "Confirmo eliminar el paquete y su cuerpo existente; los permisos anteriores no se restauran automáticamente",+ packageConfirmImpact: "He revisado el impacto en la especificación, el cuerpo y los llamadores, y las limitaciones de recuperación",+ packageSpecificationOnly: "Solo especificación: el cuerpo o las implementaciones de miembros no se han migrado.",+ packageInitialization: "El primer uso puede ejecutar la inicialización; la validación y la lectura posterior no llaman al paquete.",+ packageGrantBackup: "Copia de permisos originales del destino",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",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 1477b49d48..97a99e333a 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -7597,6 +7597,20 @@ export default withEnglishFallback({routineObserve: "Verifica la richiesta originale",routineRecoveryPreview: "Anteprima dello script di ripristino",routineRecoveryNote: "Lo script di ripristino esegue nuovo DDL; non è un rollback della transazione.",+ packageAddSpecification: "Aggiungi specifica al piano",+ packageCrossProduct: "Le bozze tra prodotti richiedono una revisione manuale della semantica di destinazione prima della convalida completa.",+ packageReviewTarget: "Revisionata: usa come bozza manuale di destinazione",+ packageUseSourceBody: "Usa corpo sorgente",+ packageRebuildTargetBody: "Mantieni e ricrea corpo di destinazione",+ packageDeleteWhole: "Elimina invece l'intero pacchetto",+ packageContract: "Specifica per convalidare il corpo",+ packageSourceContract: "Convalida con la specifica sorgente",+ packageTargetContract: "Convalida con la specifica di destinazione",+ packageConfirmDrop: "Confermo l'eliminazione dell'intero pacchetto e del corpo esistente; i privilegi precedenti non vengono ripristinati automaticamente",+ packageConfirmImpact: "Ho esaminato gli effetti su specifica, corpo e chiamanti e i limiti del ripristino",+ packageSpecificationOnly: "Solo specifica: il corpo o le implementazioni dei membri non sono stati migrati.",+ packageInitialization: "Il primo utilizzo può eseguire l'inizializzazione; la convalida e la rilettura non chiamano il pacchetto.",+ packageGrantBackup: "Backup dei privilegi originali della destinazione",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",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 0aa390844c..98de2da17a 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -7681,6 +7681,20 @@ export default withEnglishFallback({routineObserve: "元のリクエストを確認",routineRecoveryPreview: "リカバリースクリプトをプレビュー",routineRecoveryNote: "リカバリースクリプトは新しい DDL を実行します。トランザクションのロールバックではありません。",+ packageAddSpecification: "仕様を計画に追加",+ packageCrossProduct: "異なる製品間のドラフトは、ターゲットの意味を手動で確認してから完全検証してください。",+ packageReviewTarget: "確認済み:手動ターゲット稿として使用",+ packageUseSourceBody: "ソースの本体を移行",+ packageRebuildTargetBody: "ターゲットの本体を保持して再作成",+ packageDeleteWhole: "パッケージ全体を削除",+ packageContract: "本体の検証に使用する仕様",+ packageSourceContract: "ソースの仕様で検証",+ packageTargetContract: "ターゲットの仕様で検証",+ packageConfirmDrop: "パッケージ全体と既存の本体の削除を確認しました。元の権限は自動復元されません",+ packageConfirmImpact: "仕様・本体・呼び出し元への影響と復元の制限を確認しました",+ packageSpecificationOnly: "仕様のみです。本体またはメンバーの実装はまだ移行されていません。",+ packageInitialization: "初回使用時に初期化が実行される場合があります。今回の検証と再読み取りではパッケージを呼び出しません。",+ packageGrantBackup: "ターゲットの元の権限のバックアップ",routineReadOnlyCompleted: "完了した手順は再送信されません。このオブジェクトを変更するには、再比較するかリカバリースクリプトをプレビューしてください。",routineStopped: "後続手順の送信を停止しました。送信済みのリクエストはキャンセルされません。",routineHistory: "{count} 件の操作記録",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 054abc4a85..dba914caa3 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -7878,6 +7878,20 @@ export default withEnglishFallback({routineObserve: "원래 요청 확인",routineRecoveryPreview: "복구 스크립트 미리보기",routineRecoveryNote: "복구 스크립트는 새 DDL을 실행하며 트랜잭션 롤백이 아닙니다.",+ packageAddSpecification: "명세를 계획에 추가",+ packageCrossProduct: "제품 간 초안은 대상 의미를 직접 검토한 후 전체 검증을 진행해야 합니다.",+ packageReviewTarget: "검토 완료: 수동 대상 초안으로 사용",+ packageUseSourceBody: "소스 본문 사용",+ packageRebuildTargetBody: "대상 본문 유지 및 재생성",+ packageDeleteWhole: "패키지 전체 삭제로 변경",+ packageContract: "본문 검증에 사용할 명세",+ packageSourceContract: "소스 명세로 검증",+ packageTargetContract: "대상 명세로 검증",+ packageConfirmDrop: "패키지 전체와 기존 본문 삭제를 확인합니다. 이전 권한은 자동 복원되지 않습니다",+ packageConfirmImpact: "명세, 본문, 호출자에 미치는 영향과 복구 제한을 검토했습니다",+ packageSpecificationOnly: "명세만 이전합니다. 본문 또는 멤버 구현은 아직 이전되지 않았습니다.",+ packageInitialization: "최초 사용 시 초기화가 실행될 수 있습니다. 이번 검증과 읽기 확인은 패키지를 호출하지 않습니다.",+ packageGrantBackup: "대상의 기존 권한 백업",routineReadOnlyCompleted: "완료된 단계는 다시 전송되지 않습니다. 이 객체를 수정하려면 다시 비교하거나 복구 스크립트를 미리 보세요.",routineStopped: "후속 단계 전송을 중지했습니다. 이미 전송된 요청은 취소되지 않습니다.",routineHistory: "작업 기록 {count}개",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex f3f74ec4ef..682db63d4d 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -7596,6 +7596,20 @@ export default withEnglishFallback({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.",+ packageAddSpecification: "Adicionar especificação ao plano",+ packageCrossProduct: "Rascunhos entre produtos exigem revisão manual da semântica de destino antes da validação completa.",+ packageReviewTarget: "Revisado: usar como rascunho manual de destino",+ packageUseSourceBody: "Usar corpo de origem",+ packageRebuildTargetBody: "Manter e recriar corpo de destino",+ packageDeleteWhole: "Excluir o pacote inteiro",+ packageContract: "Especificação para validar o corpo",+ packageSourceContract: "Validar com a especificação de origem",+ packageTargetContract: "Validar com a especificação de destino",+ packageConfirmDrop: "Confirmo a exclusão do pacote inteiro e do corpo existente; as permissões anteriores não são restauradas automaticamente",+ packageConfirmImpact: "Revisei os impactos na especificação, no corpo e nos chamadores e os limites da recuperação",+ packageSpecificationOnly: "Somente especificação: o corpo ou as implementações dos membros ainda não foram migrados.",+ packageInitialization: "O primeiro uso pode executar a inicialização; a validação e a releitura não chamam o pacote.",+ packageGrantBackup: "Backup das permissões originais do destino",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",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 987b860417..e0ebea50b7 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -9174,6 +9174,20 @@ export default withEnglishFallback({routineObserve: "Проверить исходный запрос",routineRecoveryPreview: "Предпросмотр сценария восстановления",routineRecoveryNote: "Сценарий восстановления выполняет новый DDL, а не откатывает транзакцию.",+ packageAddSpecification: "Добавить спецификацию в план",+ packageCrossProduct: "Для переноса между продуктами вручную проверьте семантику целевого черновика перед полной проверкой.",+ packageReviewTarget: "Проверено: использовать как ручной целевой черновик",+ packageUseSourceBody: "Использовать исходное тело",+ packageRebuildTargetBody: "Сохранить и пересоздать целевое тело",+ packageDeleteWhole: "Удалить весь пакет",+ packageContract: "Спецификация для проверки тела",+ packageSourceContract: "Проверить по исходной спецификации",+ packageTargetContract: "Проверить по целевой спецификации",+ packageConfirmDrop: "Подтверждаю удаление всего пакета и существующего тела; прежние права не восстанавливаются автоматически",+ packageConfirmImpact: "Проверены последствия для спецификации, тела и вызывающих объектов, а также ограничения восстановления",+ packageSpecificationOnly: "Только спецификация: тело или реализации членов ещё не перенесены.",+ packageInitialization: "Первое использование может выполнить инициализацию; проверка и чтение результата не вызывают пакет.",+ packageGrantBackup: "Резервная копия исходных прав целевого пакета",routineReadOnlyCompleted: "Завершённые шаги не будут отправлены повторно. Чтобы изменить этот объект, сравните его заново или просмотрите сценарий восстановления.",routineStopped: "Отправка следующих шагов остановлена. Уже отправленные запросы это не отменяет.",routineHistory: "Записей операций: {count}",diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.tsindex d44686ee76..429fe959be 100644--- a/apps/desktop/src/i18n/locales/th.ts+++ b/apps/desktop/src/i18n/locales/th.ts@@ -9563,6 +9563,20 @@ export default withEnglishFallback({routineObserve: "ตรวจสอบคำขอเดิม",routineRecoveryPreview: "แสดงตัวอย่างสคริปต์กู้คืน",routineRecoveryNote: "สคริปต์กู้คืนจะเรียกใช้ DDL ใหม่ ไม่ใช่การย้อนกลับธุรกรรม",+ packageAddSpecification: "เพิ่มข้อกำหนดแพ็กเกจในแผน",+ packageCrossProduct: "ร่างข้ามผลิตภัณฑ์ต้องตรวจสอบความหมายของปลายทางด้วยตนเองก่อนตรวจสอบทั้งหมด",+ packageReviewTarget: "ตรวจสอบแล้ว ใช้เป็นร่างปลายทางที่ตรวจเอง",+ packageUseSourceBody: "ใช้ส่วนเนื้อหาต้นทาง",+ packageRebuildTargetBody: "เก็บและสร้างส่วนเนื้อหาปลายทางใหม่",+ packageDeleteWhole: "เปลี่ยนเป็นลบทั้งแพ็กเกจ",+ packageContract: "ข้อกำหนดที่ใช้ตรวจสอบส่วนเนื้อหา",+ packageSourceContract: "ตรวจสอบกับข้อกำหนดต้นทาง",+ packageTargetContract: "ตรวจสอบกับข้อกำหนดปลายทาง",+ packageConfirmDrop: "ยืนยันการลบทั้งแพ็กเกจและส่วนเนื้อหาที่มีอยู่ สิทธิ์เดิมจะไม่ถูกกู้คืนโดยอัตโนมัติ",+ packageConfirmImpact: "ตรวจสอบผลกระทบต่อข้อกำหนด ส่วนเนื้อหา ผู้เรียกใช้ และข้อจำกัดการกู้คืนแล้ว",+ packageSpecificationOnly: "ย้ายเฉพาะข้อกำหนด ยังไม่ได้ย้ายส่วนเนื้อหาหรือการทำงานของสมาชิก",+ packageInitialization: "การใช้งานครั้งแรกอาจเรียกการเริ่มต้นแพ็กเกจ การตรวจสอบและอ่านผลครั้งนี้จะไม่เรียกใช้แพ็กเกจ",+ packageGrantBackup: "สำรองสิทธิ์เดิมของแพ็กเกจปลายทาง",routineReadOnlyCompleted: "ขั้นตอนที่เสร็จแล้วจะไม่ถูกส่งซ้ำ หากต้องการแก้ไขออบเจ็กต์นี้ ให้เปรียบเทียบอีกครั้งหรือแสดงตัวอย่างสคริปต์กู้คืน",routineStopped: "หยุดส่งขั้นตอนถัดไปแล้ว แต่คำขอที่ส่งไปแล้วจะไม่ถูกยกเลิก",routineHistory: "บันทึกการดำเนินการ {count} รายการ",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 989947e5d9..8fffe2bc53 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -9011,6 +9011,20 @@ export default withEnglishFallback({routineObserve: "核对原请求",routineRecoveryPreview: "预览恢复脚本",routineRecoveryNote: "恢复脚本会执行新的 DDL,不是事务回滚。",+ packageAddSpecification: "将规格加入计划",+ packageCrossProduct: "跨产品草稿需人工复核目标语义,再执行完整校验。",+ packageReviewTarget: "已复核,作为人工目标稿",+ packageUseSourceBody: "迁入源包体",+ packageRebuildTargetBody: "保留并重建目标包体",+ packageDeleteWhole: "改为删除整个包",+ packageContract: "包体校验所用规格",+ packageSourceContract: "按源规格校验",+ packageTargetContract: "按目标规格校验",+ packageConfirmDrop: "确认删除整个包及现有包体;旧授权不会自动恢复",+ packageConfirmImpact: "已审阅规格、包体、调用方影响及恢复限制",+ packageSpecificationOnly: "仅迁移规格,包体或成员实现尚未迁移。",+ packageInitialization: "首次使用包时可能执行初始化;本次校验和读回不会调用包。",+ packageGrantBackup: "目标原授权备份",routineReadOnlyCompleted: "已完成步骤不会重发。要修改该对象,请重新比较或预览恢复脚本。",routineStopped: "已停止发送后续步骤。已派发的请求不会因此取消。",routineHistory: "{count} 次操作记录",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 08ba442111..e993ceecc0 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -6960,6 +6960,20 @@ export default withEnglishFallback({routineObserve: "核對原始請求",routineRecoveryPreview: "預覽復原指令碼",routineRecoveryNote: "復原指令碼會執行新的 DDL,並非交易回滾。",+ packageAddSpecification: "將規格加入計畫",+ packageCrossProduct: "跨產品草稿須人工複核目標語意,再執行完整驗證。",+ packageReviewTarget: "已複核,作為人工目標稿",+ packageUseSourceBody: "移入來源套件主體",+ packageRebuildTargetBody: "保留並重建目標套件主體",+ packageDeleteWhole: "改為刪除整個套件",+ packageContract: "主體驗證所用規格",+ packageSourceContract: "依來源規格驗證",+ packageTargetContract: "依目標規格驗證",+ packageConfirmDrop: "確認刪除整個套件及現有主體;原授權不會自動復原",+ packageConfirmImpact: "已檢閱規格、主體、呼叫端影響及復原限制",+ packageSpecificationOnly: "僅移轉規格,主體或成員實作尚未移轉。",+ packageInitialization: "首次使用套件時可能執行初始化;本次驗證及讀回不會呼叫套件。",+ packageGrantBackup: "目標原授權備份",routineReadOnlyCompleted: "已完成的步驟不會重新送出。若要修改此物件,請重新比較或預覽復原指令碼。",routineStopped: "已停止送出後續步驟。已送出的請求不會因此取消。",routineHistory: "{count} 筆操作記錄",diff --git a/apps/desktop/src/lib/__tests__/database/oracleRoutineCompare.spec.ts b/apps/desktop/src/lib/__tests__/database/oracleRoutineCompare.spec.tsindex 8b3b2a1d6e..1485342366 100644--- a/apps/desktop/src/lib/__tests__/database/oracleRoutineCompare.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/oracleRoutineCompare.spec.ts@@ -7,4 +7,22 @@ describe("Oracle-family routine comparison workflow", () => {expect(schemaDiffRoutineObjectTypes(databaseType)).toEqual(["PROCEDURE", "FUNCTION"]);expect(schemaDiffRoutineObjectTypesIntersection(databaseType, databaseType)).toEqual(["PROCEDURE", "FUNCTION"]);});++ it.each(["oracle", "oceanbase-oracle"] as const)("only adds explicitly requested package kinds for %s", (databaseType) => {+ expect(schemaDiffRoutineObjectTypes(databaseType, ["PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY"])).toEqual(["PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY"]);+ expect(schemaDiffRoutineObjectTypesIntersection(databaseType, databaseType, ["PACKAGE_BODY"])).toEqual(["PACKAGE_BODY"]);+ });++ it.each([+ ["oracle", "oceanbase-oracle"],+ ["oceanbase-oracle", "oracle"],+ ] as const)("permits exact package comparison from %s to %s without broadening standalone conversion", (source, target) => {+ expect(schemaDiffRoutineObjectTypesIntersection(source, target)).toEqual([]);+ expect(schemaDiffRoutineObjectTypesIntersection(source, target, ["PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY"])).toEqual(["PACKAGE", "PACKAGE_BODY"]);+ });++ it.each(["dameng", "xugu", "mysql", "postgres"] as const)("does not inherit package comparison from the %s sidebar", (databaseType) => {+ expect(schemaDiffRoutineObjectTypes(databaseType, ["PACKAGE", "PACKAGE_BODY"])).toEqual([]);+ expect(schemaDiffRoutineObjectTypesIntersection("oracle", databaseType, ["PACKAGE", "PACKAGE_BODY"])).toEqual([]);+ });});diff --git a/apps/desktop/src/lib/__tests__/schema/oraclePackageTransferApproval.spec.ts b/apps/desktop/src/lib/__tests__/schema/oraclePackageTransferApproval.spec.tsnew file mode 100644index 0000000000..2a6778b012--- /dev/null+++ b/apps/desktop/src/lib/__tests__/schema/oraclePackageTransferApproval.spec.ts@@ -0,0 +1,191 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { reactive } from "vue";+import type { OraclePackageTransferPreview, OraclePackageTransferRequest } from "@/lib/backend/api";+import { acceptOraclePackageTransferApproval, acceptOraclePackageTransferPreflight, acceptOracleRoutineDeploymentOperation, createOracleRoutineDeployment, disposeOracleRoutineDeployment, oraclePackageTransferPendingReady, refreshOracleRoutineDeployment } from "@/lib/schema/oracleRoutineDeploy";++const refs = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const load = vi.hoisted(() => vi.fn());+vi.mock("@/lib/backend/api", () => ({ updateOracleRoutineOperationReferences: refs, loadSchemaDiffRoutines: load }));+vi.mock("@/lib/metadata/objectDdlCache", () => ({ invalidateObjectDdlCache: vi.fn() }));+vi.mock("@/lib/table/objectBrowserRowsCache", () => ({ invalidateObjectBrowserRowsCache: vi.fn() }));++function fixture() {+ const endpoint = { connectionId: "T", database: "tenant", schema: "T", databaseType: "oceanbase-oracle" as const, generation: 1 };+ const source = { endpoint: { ...endpoint, connectionId: "S", schema: "S" }, state: "complete" as const, enumerationComplete: true, objects: [], issues: [] };+ const target = { ...source, endpoint };+ const drafts = (["PACKAGE", "PACKAGE_BODY"] as const).map((kind) => ({ identity: { owner: "T", name: "P", kind }, action: "create" as const, sourceName: "P", sql: `CREATE ${kind.replace("_", " ")} "T".P AS END;` }));+ const state = reactive(createOracleRoutineDeployment(source, target));+ state.drafts = drafts.map((draft) => ({ ...draft, objectId: draft.identity.kind, included: true }));+ state.executing = true;+ const steps = drafts.map((draft) => ({ ...draft, sourceOriginal: "完整原文 中文😀", targetOriginal: null, recoverySql: null, recoveryComplete: true, references: [], incomingCallers: [], issues: [], operation: null }));+ state.plan = { target: endpoint, steps, ready: false };+ const frozen: OraclePackageTransferRequest = { input: { source, target, drafts }, operationIds: [], pendingTables: { source: source.endpoint, target: endpoint, tables: [{ sourceTable: "SOURCE" }], dependencyManifest: {}, tableEvidence: [{ sourceTable: "SOURCE" }] } };+ const approval: OraclePackageTransferPreview = {+ input: frozen.input!,+ skipped: [],+ plan: { target: endpoint, ready: true, steps: steps.map((step, index) => ({ ...step, operation: { operationId: `operation-${index}`, target: endpoint, identity: step.identity, lifecycle: "prepared", dispatched: false, acknowledged: false, error: null, readback: null } })) },+ };+ return { state, frozen: structuredClone(frozen), approval: structuredClone(approval) };+}++beforeEach(() => {+ refs.mockReset();+ refs.mockResolvedValue(undefined);+});++describe("mixed package transfer approval handoff", () => {+ it("enables only the transfer confirmation layer for a matching pending plan, never ordinary deployment", () => {+ const { state, frozen, approval } = fixture();+ state.executing = false;+ const preview = { ...approval, pendingTables: frozen.pendingTables, plan: { ...approval.plan, ready: false, steps: approval.plan.steps.map((step) => ({ ...step, operation: null })) } };+ expect(oraclePackageTransferPendingReady(state, preview)).toBe(true);+ expect(state.plan?.ready).toBe(false);+ state.drafts[0].sql += " -- edited after validation";+ expect(oraclePackageTransferPendingReady(state, preview)).toBe(false);+ state.drafts[0].sql = frozen.input!.drafts[0].sql;+ preview.plan.steps[0].issues = [{ code: "missing-reference", message: "missing", line: 1, column: 1 }];+ expect(oraclePackageTransferPendingReady(state, preview)).toBe(false);+ });++ it("keeps post-table preflight issues in the original draft editor without adopting IDs or replaying tables", async () => {+ const { state, frozen, approval } = fixture();+ const preview = structuredClone(approval);+ preview.plan.ready = false;+ preview.plan.steps.forEach((step) => {+ step.operation = null;+ });+ preview.plan.steps[1].issues = [{ code: "missing-reference", message: "Missing column 中文😀", line: 3, column: 7 }];+ expect(acceptOraclePackageTransferPreflight(state, frozen, preview)).toBe(true);+ expect(state.plan?.steps[1].issues[0].column).toBe(7);+ expect(state.drafts[1].sql).toBe(frozen.input!.drafts[1].sql);+ expect(state.records).toEqual([]);+ await expect(acceptOraclePackageTransferApproval(state, frozen, approval)).resolves.toBe(false);+ const original = fixture();+ await acceptOraclePackageTransferApproval(original.state, original.frozen, original.approval);+ expect(acceptOraclePackageTransferPreflight(original.state, original.frozen, preview)).toBe(false);+ expect(original.state.records).toHaveLength(2);+ await disposeOracleRoutineDeployment(original.state);+ });++ it("freezes transfer refresh generations while preserving the ordinary explicit-refresh contract", async () => {+ const { state } = fixture();+ state.executing = false;+ const fixed = { source: { ...state.source.endpoint }, target: { ...state.target.endpoint } };+ load.mockImplementation(async (id: string, database: string, schema: string) => ({+ state: "complete",+ enumerationComplete: true,+ objects: [],+ issues: [],+ endpoint: { ...fixed.target, connectionId: id, database, schema, generation: 2 },+ }));+ await refreshOracleRoutineDeployment(state, fixed);+ expect(state.error).toContain("generation changed");+ expect(state.source.endpoint).toEqual(fixed.source);+ expect(state.target.endpoint).toEqual(fixed.target);+ const ordinary = fixture().state;+ ordinary.executing = false;+ await refreshOracleRoutineDeployment(ordinary);+ expect(ordinary.error).toBeNull();+ expect(ordinary.target.endpoint.generation).toBe(2);+ });++ it("installs only the exact ordered batch before a result can arrive and retains it for the task", async () => {+ const { state, frozen, approval } = fixture();+ let finish!: () => void;+ refs.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );+ const accepting = acceptOraclePackageTransferApproval(state, frozen, approval);+ expect(state.records.map((record) => record.operationId)).toEqual(["operation-0", "operation-1"]);+ const result = { ...approval.plan.steps[1].operation!, lifecycle: "terminal" as const, dispatched: true, acknowledged: true, error: "body invalid" };+ expect(acceptOracleRoutineDeploymentOperation(state, result)).toBe(true);+ expect(state.drafts[1].operation).toEqual(result);+ expect(acceptOracleRoutineDeploymentOperation(state, { ...result, operationId: "unrelated" })).toBe(false);+ await vi.waitFor(() => expect(refs).toHaveBeenCalledWith(["operation-0", "operation-1"], []));+ finish();+ await expect(accepting).resolves.toBe(true);+ await expect(acceptOraclePackageTransferApproval(state, frozen, approval)).resolves.toBe(false);+ await disposeOracleRoutineDeployment(state);+ expect(refs).toHaveBeenLastCalledWith([], ["operation-0", "operation-1"]);+ });++ it("rejects changed source/target generations, final SQL, order, selection and unfamiliar execution state", async () => {+ for (let change = 0; change < 12; change++) {+ const { state, frozen, approval } = fixture();+ switch (change) {+ case 0:+ approval.input.source.endpoint.generation++;+ break;+ case 1:+ approval.plan.target = { ...approval.plan.target, connectionId: "another-target" };+ break;+ case 2:+ approval.plan.steps[1].sql += " -- changed";+ break;+ case 3:+ approval.plan.steps.reverse();+ break;+ case 4:+ approval.plan.steps.pop();+ break;+ case 5:+ approval.plan.steps[1].operation!.operationId = "operation-0";+ break;+ case 6:+ approval.plan.steps[0].operation!.dispatched = true;+ break;+ case 7:+ state.plan = null;+ break;+ case 8:+ state.executing = false;+ break;+ case 9:+ frozen.pendingTables = undefined;+ break;+ case 10:+ approval.input.drafts[0].sql += " -- changed";+ break;+ default:+ for (const identity of [state.drafts[0].identity, state.plan!.steps[0].identity, frozen.input!.drafts[0].identity, approval.input.drafts[0].identity, approval.plan.steps[0].identity, approval.plan.steps[0].operation!.identity]) identity.kind = "PROCEDURE";+ }+ await expect(acceptOraclePackageTransferApproval(state, frozen, approval)).resolves.toBe(false);+ expect(state.records).toEqual([]);+ expect(state.retainedOperationIds).toEqual([]);+ }+ expect(refs).not.toHaveBeenCalled();+ });++ it("releases a batch when its task is removed while the retain RPC is still pending", async () => {+ const { state, frozen, approval } = fixture();+ let finish!: () => void;+ refs.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );+ const accepting = acceptOraclePackageTransferApproval(state, frozen, approval);+ await vi.waitFor(() => expect(refs).toHaveBeenCalledOnce());+ const disposing = disposeOracleRoutineDeployment(state);+ finish();+ await expect(accepting).resolves.toBe(false);+ await disposing;+ expect(refs).toHaveBeenLastCalledWith([], ["operation-0", "operation-1"]);+ expect(state.retainedOperationIds).toEqual([]);+ });++ it("keeps known IDs and the retain failure visible until normal task cleanup", async () => {+ const { state, frozen, approval } = fixture();+ refs.mockRejectedValueOnce(new Error("reference update unavailable"));+ await expect(acceptOraclePackageTransferApproval(state, frozen, approval)).resolves.toBe(false);+ expect(state.error).toBe("reference update unavailable");+ expect(state.records).toHaveLength(2);+ expect(state.retainedOperationIds).toEqual(["operation-0", "operation-1"]);+ await disposeOracleRoutineDeployment(state);+ expect(refs).toHaveBeenLastCalledWith([], ["operation-0", "operation-1"]);+ });+});diff --git a/apps/desktop/src/lib/__tests__/schema/oracleRoutineDeploy.spec.ts b/apps/desktop/src/lib/__tests__/schema/oracleRoutineDeploy.spec.tsindex faa7ecd250..f3454f0687 100644--- a/apps/desktop/src/lib/__tests__/schema/oracleRoutineDeploy.spec.ts+++ b/apps/desktop/src/lib/__tests__/schema/oracleRoutineDeploy.spec.ts@@ -1,12 +1,18 @@import { beforeEach, describe, expect, it, vi } from "vitest";import {createOracleRoutineDeployment,+ acceptOracleRoutineDeploymentOperation,disposeOracleRoutineDeployment,editOracleRoutineDraft,+ editOraclePackageOptions,+ includeOraclePackageCompanion,executeOracleRoutineDeployment,observeOracleRoutineDeployment,+ oracleRoutineActiveStep,+ oracleRoutineDeploymentEntries,prepareOracleRoutineRecovery,refreshOracleRoutineDeployment,+ reviewOraclePackageTargetDraft,selectOracleRoutineDraft,synchronizeOracleRoutineSelection,validateOracleRoutineDeployment,@@ -77,6 +83,254 @@ beforeEach(() => {});describe("Oracle routine deployment in the existing comparison session", () => {+ it("adopts original background operation results without enabling replay or overwriting a newer approval", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValue(plan("F"));+ await validateOracleRoutineDeployment(session);+ const invalid = finished("F", "invalid");+ expect(acceptOracleRoutineDeploymentOperation(session, invalid)).toBe(true);+ expect(session.drafts[0].operation).toBe(invalid);+ expect(session.plan?.steps[0].operation).toBe(invalid);+ expect(session.plan?.ready).toBe(false);+ expect(session.attemptedOperationIds).toEqual([invalid.operationId]);+ expect(acceptOracleRoutineDeploymentOperation(session, operation("F"))).toBe(false);+ expect(session.drafts[0].operation).toBe(invalid);+ session.drafts[0].operation = operation("F", "newer-body-approval");+ expect(acceptOracleRoutineDeploymentOperation(session, finished("F"))).toBe(true);+ expect(session.drafts[0].operation.operationId).toBe("newer-body-approval");+ });++ it("rejects background records from another target, generation, identity or unknown operation ID", async () => {+ const session = state("F");+ calls.prepare.mockResolvedValue(plan("F"));+ await validateOracleRoutineDeployment(session);+ const original = session.drafts[0].operation;+ for (const record of [+ { ...finished("F"), target: { ...endpoint, connectionId: "another-target" } },+ { ...finished("F"), target: { ...endpoint, generation: endpoint.generation + 1 } },+ { ...finished("F"), identity: { ...operation("F").identity, kind: "PACKAGE_BODY" as const } },+ { ...finished("F"), operationId: "unknown-original-id" },+ ])+ expect(acceptOracleRoutineDeploymentOperation(session, record)).toBe(false);+ expect(session.drafts[0].operation).toBe(original);+ expect(session.plan?.ready).toBe(true);+ });++ it("uses a transfer-bound preparation callback without bypassing the existing target and selection checks", async () => {+ const session = state("F");+ const prepare = vi.fn().mockResolvedValue(plan("F"));+ await validateOracleRoutineDeployment(session, prepare);+ expect(calls.prepare).not.toHaveBeenCalled();+ expect(prepare.mock.calls[0][0].source).toBe(session.source);+ expect(prepare.mock.calls[0][0].target).toBe(session.target);+ expect(session.plan?.ready).toBe(true);+ const wrong = plan("G");+ prepare.mockResolvedValue(wrong);+ await validateOracleRoutineDeployment(session, prepare);+ expect(session.error).toContain("unselected object");+ expect(session.plan?.steps[0].identity.name).toBe("F");+ });++ it("does not call a transfer-bound preparer while an original package write is unproven", async () => {+ const session = state();+ synchronizeOracleRoutineSelection(session, [{ ...object("P"), id: "body", routineType: "PACKAGE_BODY" }]);+ const original = { ...operation("P", "original-body"), identity: session.drafts[0].identity, lifecycle: "unproven" as const, dispatched: true };+ session.drafts[0].operation = original;+ calls.observe.mockResolvedValue({ operation: original, lifecycle: "unproven", error: null });+ const prepare = vi.fn();+ await validateOracleRoutineDeployment(session, prepare);+ expect(prepare).not.toHaveBeenCalled();+ expect(calls.prepare).not.toHaveBeenCalled();+ expect(session.error).toContain("termination is not proven");+ expect(session.drafts[0].operation?.operationId).toBe("original-body");+ });++ it("does not turn generated cross-product previews into final target drafts merely by revalidating", async () => {+ const session = state();+ session.source = { ...session.source, endpoint: { ...session.source.endpoint, databaseType: "oracle" } };+ synchronizeOracleRoutineSelection(session, [+ { ...object("Pkg.With.Dot"), id: "spec", routineType: "PACKAGE" },+ { ...object("Pkg.With.Dot"), id: "body", routineType: "PACKAGE_BODY" },+ ]);+ const response = plan("Pkg.With.Dot", "Pkg.With.Dot");+ response.ready = false;+ response.steps.forEach((step, index) => {+ step.identity = session.drafts[index].identity;+ step.operation = null;+ step.sql = `generated target ${step.identity.kind}`;+ });+ calls.prepare.mockResolvedValue(response);+ await validateOracleRoutineDeployment(session);+ await validateOracleRoutineDeployment(session);+ expect(calls.prepare.mock.calls[1][0].drafts.map((draft: { sql?: string }) => draft.sql)).toEqual([undefined, undefined]);+ reviewOraclePackageTargetDraft(session, "spec");+ expect(session.plan).toBeNull();+ await validateOracleRoutineDeployment(session);+ expect(calls.prepare.mock.calls[2][0].drafts.map((draft: { sql?: string }) => draft.sql)).toEqual(["generated target PACKAGE", undefined]);+ editOracleRoutineDraft(session, "body", "manually edited target body");+ await validateOracleRoutineDeployment(session);+ expect(calls.prepare.mock.calls[3][0].drafts[1].sql).toBe("manually edited target body");+ await executeOracleRoutineDeployment(session, authorize);+ expect(calls.execute).not.toHaveBeenCalled();+ });++ it("requires a new target-draft review after changing the selected body source", () => {+ const session = state();+ synchronizeOracleRoutineSelection(session, [{ ...object("Pkg.With.Dot"), id: "body", routineType: "PACKAGE_BODY" }]);+ editOracleRoutineDraft(session, "body", "reviewed source body");+ expect(session.drafts[0].reviewedTargetDraft).toBe(true);+ editOraclePackageOptions(session, "body", { packageBodySource: "target" });+ expect(session.drafts[0].reviewedTargetDraft).toBe(false);+ reviewOraclePackageTargetDraft(session, "body");+ expect(session.drafts[0].reviewedTargetDraft).toBe(false);+ editOraclePackageOptions(session, "body", { packageBodySource: "source" });+ expect(session.drafts[0].sql).toBe("reviewed source body");+ reviewOraclePackageTargetDraft(session, "body");+ expect(session.drafts[0].reviewedTargetDraft).toBe(true);+ });++ it("adds a whole-package deletion only explicitly from a body deletion, using target material", () => {+ const session = state();+ const selected = { ...object("Pkg.With.Dot"), id: "body", routineType: "PACKAGE_BODY" as const, operationType: "delete" as const };+ session.target = {+ ...session.target,+ objects: [{ version: { identity: { owner: endpoint.schema, name: selected.name, kind: "PACKAGE" }, objectId: "1", status: "VALID", lastDdlTime: "1" }, source: "complete target specification", sourceComplete: true, dependencies: [], dependenciesComplete: true, issues: [] }],+ };+ synchronizeOracleRoutineSelection(session, [selected]);+ expect(session.drafts).toHaveLength(1);+ const spec = includeOraclePackageCompanion(session, "body");+ expect(spec).toMatchObject({ identity: { kind: "PACKAGE" }, action: "delete", confirmPackagePair: false });+ expect(includeOraclePackageCompanion(session, spec!.objectId)).toBeUndefined();+ expect(session.drafts).toHaveLength(2);+ });++ it("projects normalized Core steps in execution order rather than sorting deletes last", async () => {+ const session = state();+ synchronizeOracleRoutineSelection(session, [+ { ...object("Pkg.With.Dot"), id: "spec", routineType: "PACKAGE", operationType: "modify" },+ { ...object("Pkg.With.Dot"), id: "body", routineType: "PACKAGE_BODY", operationType: "delete" },+ ]);+ const response = plan("Pkg.With.Dot", "Pkg.With.Dot");+ response.steps[0].identity = { ...session.drafts[1].identity };+ response.steps[0].action = "delete";+ response.steps[1].identity = { ...session.drafts[0].identity };+ response.steps[1].action = "replace";+ calls.prepare.mockResolvedValue(response);+ await validateOracleRoutineDeployment(session);+ expect(oracleRoutineDeploymentEntries(session).map((entry) => entry.objectId)).toEqual(["body", "spec"]);+ const normalized = { ...response, steps: [response.steps[1]] };+ calls.prepare.mockResolvedValue(normalized);+ session.selectedObjectId = "body";+ await validateOracleRoutineDeployment(session);+ expect(oracleRoutineDeploymentEntries(session).map((entry) => entry.objectId)).toEqual(["spec"]);+ expect(session.selectedObjectId).toBe("spec");+ });++ it("allows inspecting recovery-only companion definitions without adding them to the write selection", async () => {+ const session = state();+ synchronizeOracleRoutineSelection(session, [{ ...object("Pkg.With.Dot"), id: "spec", routineType: "PACKAGE", operationType: "modify" }]);+ const response = plan("Pkg.With.Dot", "Pkg.With.Dot");+ response.ready = false;+ response.steps[0].identity = { ...session.drafts[0].identity };+ response.steps[1].identity = { ...session.drafts[0].identity, kind: "PACKAGE_BODY" };+ response.steps[1].sourceOriginal = "original orphan body";+ response.steps.forEach((step) => {+ step.operation = null;+ step.recoveryComplete = false;+ });+ calls.recovery.mockResolvedValue(response);+ await prepareOracleRoutineRecovery(session, "original-spec");+ const entries = oracleRoutineDeploymentEntries(session);+ expect(entries).toHaveLength(2);+ selectOracleRoutineDraft(session, entries[1].objectId);+ expect(session.recoveryPlan).toBe(response);+ expect(oracleRoutineActiveStep(session)?.sourceOriginal).toBe("original orphan body");+ expect(session.drafts).toHaveLength(1);+ session.executing = true;+ selectOracleRoutineDraft(session, entries[0].objectId);+ expect(session.selectedObjectId).toBe(entries[1].objectId);+ });++ it("adds a completely read companion only after explicit selection and retains it with its parent", () => {+ const session = state();+ const selected = { ...object("Pkg.With.Dot"), id: "body", routineType: "PACKAGE_BODY" as const };+ session.source.objects = [{ version: { identity: { owner: "Source", name: selected.name, kind: "PACKAGE" }, objectId: "1", status: "VALID", lastDdlTime: "1" }, source: "complete source specification", sourceComplete: true, dependencies: [], dependenciesComplete: true, issues: [] }];+ synchronizeOracleRoutineSelection(session, [selected]);+ expect(session.drafts).toHaveLength(1);+ const specification = includeOraclePackageCompanion(session, "body");+ expect(specification).toMatchObject({ identity: { owner: endpoint.schema, name: selected.name, kind: "PACKAGE" }, action: "create", companionFor: "body", included: true });+ synchronizeOracleRoutineSelection(session, [selected]);+ expect(session.drafts.filter((draft) => draft.included)).toHaveLength(2);+ expect(includeOraclePackageCompanion(session, "body")).toBe(specification);+ expect(session.drafts).toHaveLength(2);+ synchronizeOracleRoutineSelection(session, [{ ...selected, selected: false }]);+ expect(session.drafts.some((draft) => draft.included)).toBe(false);+ });++ it("keeps the edited body when a companion is incomplete instead of inventing a write", () => {+ const session = state();+ synchronizeOracleRoutineSelection(session, [{ ...object("Pkg.With.Dot"), id: "body", routineType: "PACKAGE_BODY" }]);+ editOracleRoutineDraft(session, "body", "retained body draft");+ expect(includeOraclePackageCompanion(session, "body")).toBeUndefined();+ expect(session.drafts).toHaveLength(1);+ expect(session.drafts[0].sql).toBe("retained body draft");+ expect(session.error).toContain("Completely read");+ });++ it("keeps same-name specification and body drafts separate and preserves edited source variants when package choices change", () => {+ const session = state();+ synchronizeOracleRoutineSelection(session, [+ { ...object("Pkg.With.Dot"), id: "spec", routineType: "PACKAGE" },+ { ...object("Pkg.With.Dot"), id: "body", routineType: "PACKAGE_BODY" },+ ]);+ expect(session.drafts.map((draft) => draft.identity.kind)).toEqual(["PACKAGE", "PACKAGE_BODY"]);+ editOracleRoutineDraft(session, "body", "manually edited source body");+ editOraclePackageOptions(session, "spec", { confirmPackagePair: true });+ editOraclePackageOptions(session, "body", { packageBodySource: "target", packageContract: "target" });+ expect(session.drafts[0].confirmPackagePair).toBe(false);+ expect(session.drafts[1].sql).toBeUndefined();+ editOracleRoutineDraft(session, "body", "manually edited target body");+ editOraclePackageOptions(session, "body", { packageBodySource: "source" });+ expect(session.drafts[1].sql).toBe("manually edited source body");+ editOraclePackageOptions(session, "body", { packageBodySource: "target" });+ expect(session.drafts[1].sql).toBe("manually edited target body");+ editOraclePackageOptions(session, "spec", { confirmPackagePair: true });+ editOracleRoutineDraft(session, "body", "changed final body");+ expect(session.drafts[0].confirmPackagePair).toBe(false);+ });++ it("forwards reviewed package body source, target contract and pair confirmation without adding a specification write", async () => {+ const session = state();+ synchronizeOracleRoutineSelection(session, [{ ...object("Pkg.With.Dot"), id: "body", routineType: "PACKAGE_BODY" }]);+ editOraclePackageOptions(session, "body", { packageBodySource: "target", packageContract: "target", confirmPackagePair: true });+ const response = plan("Pkg.With.Dot");+ response.steps[0].identity.kind = "PACKAGE_BODY";+ response.steps[0].operation!.identity.kind = "PACKAGE_BODY";+ calls.prepare.mockResolvedValue(response);+ await validateOracleRoutineDeployment(session);+ expect(session.error).toBeNull();+ expect(calls.prepare.mock.calls[0][0].drafts).toHaveLength(1);+ expect(calls.prepare.mock.calls[0][0].drafts[0]).toMatchObject({ identity: { kind: "PACKAGE_BODY", name: "Pkg.With.Dot" }, packageBodySource: "target", packageContract: "target", confirmPackagePair: true });+ });++ it("refreshes packages with typed selection and does not treat a same-name specification as an existing body", async () => {+ const session = state();+ synchronizeOracleRoutineSelection(session, [{ ...object("Pkg.With.Dot"), id: "body", routineType: "PACKAGE_BODY", operationType: "modify" }]);+ calls.load.mockImplementation(async (id: string) =>+ id === "source"+ ? session.source+ : { ...snapshot, objects: [{ version: { identity: { owner: endpoint.schema, name: "Pkg.With.Dot", kind: "PACKAGE" }, objectId: "11", status: "VALID", lastDdlTime: "1" }, source: "complete specification", sourceComplete: true, dependencies: [], dependenciesComplete: true, issues: [] }] },+ );+ await refreshOracleRoutineDeployment(session);+ expect(session.error).toBeNull();+ expect(session.drafts[0].action).toBe("create");+ for (const call of calls.load.mock.calls) {+ expect(call[3]).toBeUndefined();+ expect(call[4]).toEqual({ objectKinds: ["PACKAGE_BODY"], selectedObjects: [{ name: "Pkg.With.Dot", kind: "PACKAGE_BODY" }] });+ }+ expect(session.target.objects[0].version.identity.kind).toBe("PACKAGE");+ });+it("preserves the existing approved plan when revalidation is rejected by capacity admission", async () => {const session = state("F");calls.prepare.mockResolvedValueOnce(plan("F"));diff --git a/apps/desktop/src/lib/__tests__/schema/schemaDiffRoutine.spec.ts b/apps/desktop/src/lib/__tests__/schema/schemaDiffRoutine.spec.tsindex 231d3cdf26..89bb1877ad 100644--- a/apps/desktop/src/lib/__tests__/schema/schemaDiffRoutine.spec.ts+++ b/apps/desktop/src/lib/__tests__/schema/schemaDiffRoutine.spec.ts@@ -30,6 +30,61 @@ describe("schemaDiffRoutine", () => {expect(schemaDiffRoutineKeyFromFunction(fn("add", "integer, text"))).toBe("add(integer, text)");});+ it("keeps a package specification and its same-name body as separate identities", () => {+ const specification = { ...fn("Pkg.With.Dot"), function_type: "PACKAGE" };+ const body = { ...fn("Pkg.With.Dot"), function_type: "PACKAGE_BODY" };+ expect(schemaDiffRoutineKeyFromFunction(specification)).not.toBe(schemaDiffRoutineKeyFromFunction(body));+ });++ it("does not include a package specification when only its body is selected", () => {+ const specification = { ...fn("Pkg.With.Dot"), function_type: "PACKAGE" };+ const body = { ...fn("Pkg.With.Dot"), function_type: "PACKAGE_BODY" };+ const selected = schemaDiffRoutineKeyFromFunction(body);+ const filtered = filterSchemaDiffFunctions([specification, body], [specification, body], [selected]);+ expect(filtered.sourceFunctions).toEqual([body]);+ expect(filtered.targetFunctions).toEqual([body]);+ });++ it("does not confuse a quoted function name with a serialized package key", () => {+ const body = { ...fn("Pkg.With.Dot"), function_type: "PACKAGE_BODY" };+ const selected = schemaDiffRoutineKeyFromFunction(body);+ const quotedFunction = fn(selected);+ expect(schemaDiffRoutineKeyFromFunction(quotedFunction)).toBe(selected);+ const filtered = filterSchemaDiffFunctions([body, quotedFunction], [body, quotedFunction], [selected]);+ expect(filtered.sourceFunctions).toEqual([body]);+ expect(filtered.targetFunctions).toEqual([body]);+ });++ it("uses exact kinds only when the caller selects the typed program contract", () => {+ const routine = fn("same", "");+ const key = schemaDiffRoutineKeyFromFunction(routine, true);+ expect(key).not.toBe(schemaDiffRoutineKeyFromFunction(routine));+ expect(filterSchemaDiffFunctions([routine], [routine], [key], [], true)).toEqual({ sourceFunctions: [routine], targetFunctions: [routine] });+ expect(() => schemaDiffRoutineKeyFromFunction({ name: "same", arguments: "" }, true)).toThrow("object kind");+ });++ it("retains the opposite standalone kind so typed selection still reports a procedure/function conflict", () => {+ const procedure = { ...fn("same"), function_type: "PROCEDURE" };+ const target = fn("same");+ const filtered = filterSchemaDiffFunctions([procedure], [target], [schemaDiffRoutineKeyFromFunction(procedure, true)], [], true);+ expect(filtered.sourceFunctions).toEqual([procedure]);+ expect(filtered.targetFunctions).toEqual([target]);+ expect(filterSchemaDiffFunctions([procedure], [fn("same", "integer")], [schemaDiffRoutineKeyFromFunction(procedure, true)], [], true).targetFunctions).toEqual([]);+ });++ it("can select a target-only body without selecting its specification", () => {+ const specification = { ...fn("P"), function_type: "PACKAGE" };+ const body = { ...fn("P"), function_type: "PACKAGE_BODY" };+ expect(filterSchemaDiffFunctions([], [specification, body], [schemaDiffRoutineKeyFromFunction(body)], [], true)).toEqual({ sourceFunctions: [], targetFunctions: [body] });+ });++ it("retains a same-name foreign namespace kind as conflict evidence, not a package counterpart write", () => {+ const body = { ...fn("P"), function_type: "PACKAGE_BODY" };+ const target = fn("P");+ const filtered = filterSchemaDiffFunctions([body], [target], [schemaDiffRoutineKeyFromFunction(body)], [], true);+ expect(filtered.targetFunctions).toEqual([target]);+ });+it("blocks unrestricted compare when routine count exceeds the soft limit", () => {expect(SCHEMA_DIFF_UNRESTRICTED_ROUTINE_LIMIT).toBe(200);expect(isSchemaDiffUnrestrictedRoutineLoadTooLarge(200, undefined)).toBe(false);diff --git a/apps/desktop/src/lib/__tests__/schema/schemaDiffSelection.spec.ts b/apps/desktop/src/lib/__tests__/schema/schemaDiffSelection.spec.tsindex d4be72546e..45e02621f9 100644--- a/apps/desktop/src/lib/__tests__/schema/schemaDiffSelection.spec.ts+++ b/apps/desktop/src/lib/__tests__/schema/schemaDiffSelection.spec.ts@@ -50,6 +50,37 @@ function createDuplicateForeignKeyPreparation(): SchemaDiffPreparation {}describe("schema diff SQL selection projections", () => {+ it("keeps explicit same-name package specification and body identities separate through projection", () => {+ const functionDiffs = (["PACKAGE", "PACKAGE_BODY"] as const).map((programKind) => ({+ type: "modified" as const,+ name: 'Pkg.With.Dot,"中文😀',+ programKind,+ source: { name: 'Pkg.With.Dot,"中文😀', function_type: programKind, data_type: "", arguments: "", definition: `${programKind} original` },+ }));+ const result: SchemaDiffPreparation = { diffs: [], functionDiffs, syncSql: "" };+ const objects = convertToSchemaDiffObjects([], functionDiffs);+ expect(new Set(objects.map((object) => object.id)).size).toBe(2);+ expect(objects.map((object) => object.routineType)).toEqual(["PACKAGE", "PACKAGE_BODY"]);+ setSchemaDiffObjectSelected(objects, objects[0]!.id, false);+ expect(selectSchemaDiffInput(result, objects).functionDiffs).toEqual([functionDiffs[1]]);+ expect(selectSchemaDiffInputForObject(result, objects, objects[1]!.id).functionDiffs).toEqual([functionDiffs[1]]);+ });++ it("does not guess a package identity from an arbitrary source or target definition", () => {+ const source = { name: "P", function_type: "PACKAGE_BODY", data_type: "", arguments: "", definition: "retained body" };+ expect(() => convertToSchemaDiffObjects([], [{ type: "added", name: "P", source }])).toThrow("explicit program kind");+ expect(() => convertToSchemaDiffObjects([], [{ type: "removed", name: "P", target: source }])).toThrow("explicit program kind");+ expect(() => convertToSchemaDiffObjects([], [{ type: "conflict", name: "P", source: { ...source, function_type: "FUNCTION" }, target: source }])).toThrow("explicit program kind");+ });++ it("preserves legacy PostgreSQL overload IDs and selection", () => {+ const functionDiffs = ["integer", "text"].map((arguments_) => ({ type: "added" as const, name: "f", source: { name: "f", function_type: "FUNCTION", data_type: "", arguments: arguments_, definition: "original" } }));+ const objects = convertToSchemaDiffObjects([], functionDiffs);+ expect(objects.map((object) => object.id)).toEqual(["func-f-integer", "func-f-text"]);+ setSchemaDiffObjectSelected(objects, "func-f-text", false);+ expect(selectSchemaDiffInput({ diffs: [], functionDiffs, syncSql: "" }, objects).functionDiffs).toEqual([functionDiffs[0]]);+ });+it("retains equal and unreadable Oracle originals without selecting executable steps", () => {const functionDiffs = (["equal", "unreadable", "conflict"] as const).map((type) => ({type,diff --git a/apps/desktop/src/lib/__tests__/table/objectSourceTabSave.spec.ts b/apps/desktop/src/lib/__tests__/table/objectSourceTabSave.spec.tsindex f8a53839cb..1ff50ef518 100644--- a/apps/desktop/src/lib/__tests__/table/objectSourceTabSave.spec.ts+++ b/apps/desktop/src/lib/__tests__/table/objectSourceTabSave.spec.ts@@ -32,13 +32,13 @@ function operation(input: OracleRoutineSaveInput): OracleRoutineOperation {};}-function openDraft(name: string) {+function openDraft(name: string, kind: "FUNCTION" | "PACKAGE" | "PACKAGE_BODY" = "FUNCTION") {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" } });+ const original = kind === "FUNCTION" ? `CREATE OR REPLACE FUNCTION "APP"."${name}" RETURN NUMBER AS BEGIN RETURN 1; END;` : `CREATE OR REPLACE ${kind.replaceAll("_", " ")} "APP"."${name}" AS g NUMBER := 1; END "${name}";`;+ const sql = original.replace("RETURN 1", "RETURN 2").replace(":= 1", ":= 2");+ const id = queryStore.openObjectSourceTab({ connectionId: connection.id, database: "ORCL", schema: "APP", title: name, sql: original, objectSource: { name, schema: "APP", objectType: kind } });queryStore.updateSql(id, sql);const tab = queryStore.tabs.find((tab) => tab.id === id)!;const toast = vi.fn();@@ -56,6 +56,20 @@ beforeEach(() => {});describe("App object source tab Save handler", () => {+ it.each(["PACKAGE", "PACKAGE_BODY"] as const)("prepares %s before confirmation and saves only its approved draft", async (kind) => {+ const draft = openDraft(`Confirmed${kind}`, kind);+ const pending = draft.save();+ const safety = useProductionSafetyStore();+ await vi.waitFor(() => expect(safety.pending).toMatchObject({ sql: draft.sql }));+ expect(api.prepareOracleRoutineSave).toHaveBeenCalledExactlyOnceWith({ connectionId: draft.connection.id, database: "ORCL", identity: { owner: "APP", name: draft.tab.objectSource!.name, kind }, sql: draft.sql });+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ safety.confirm();+ await expect(pending).resolves.toBe(true);+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledExactlyOnceWith(`approval-Confirmed${kind}`, draft.sql);+ expect(draft.queryStore.isTabDirty(draft.tab)).toBe(false);+ });+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();@@ -115,8 +129,8 @@ describe("App object source tab Save handler", () => {expect(draft.queryStore.isTabDirty(draft.tab)).toBe(true);});- it("INVALID readback retains the actual dirty tab and compiler location", async () => {- const draft = openDraft("InvalidReadback");+ it.each(["FUNCTION", "PACKAGE", "PACKAGE_BODY"] as const)("INVALID %s readback retains the actual dirty tab and compiler location", async (kind) => {+ const draft = openDraft(`InvalidReadback${kind}`, kind);vi.mocked(api.executeOracleRoutineOperation).mockImplementationOnce(async () => {const result = operation(vi.mocked(api.prepareOracleRoutineSave).mock.calls.at(-1)![0]);result.readback!.state = "invalid";diff --git a/apps/desktop/src/lib/__tests__/table/oraclePackageSaveAs.spec.ts b/apps/desktop/src/lib/__tests__/table/oraclePackageSaveAs.spec.tsindex cd25bbdc37..043ae3fb01 100644--- a/apps/desktop/src/lib/__tests__/table/oraclePackageSaveAs.spec.ts+++ b/apps/desktop/src/lib/__tests__/table/oraclePackageSaveAs.spec.ts@@ -1,10 +1,19 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { beginSourceSave, captureSourceIdentity } from "@/lib/table/objectSourceIdentity";-import { executeOraclePackageSaveAs, prepareOraclePackageSaveAs } from "@/lib/table/oraclePackageSaveAs";+import { executeOraclePackageSaveAs, prepareOraclePackageSaveAs, prepareOraclePackageSaveAsExecution } from "@/lib/table/oraclePackageSaveAs";+import type { OracleRoutineOperation, OracleRoutineSaveInput } from "@/types/schemaDiff";import { invalidateObjectDdlCache } from "@/lib/metadata/objectDdlCache";import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";-const api = vi.hoisted(() => ({ executeQuery: vi.fn(), parseOracleObjectName: vi.fn(), buildExecutableObjectSourceStatements: vi.fn() }));+const api = vi.hoisted(() => ({+ executeQuery: vi.fn(),+ parseOracleObjectName: vi.fn(),+ buildExecutableObjectSourceStatements: vi.fn(),+ prepareOracleRoutineSave: vi.fn(),+ executeOracleRoutineOperation: vi.fn(),+ observeOracleRoutineOperation: vi.fn(),+ updateOracleRoutineOperationReferences: vi.fn(),+}));vi.mock("@/lib/backend/api", () => api);vi.mock("@/lib/metadata/objectDdlCache", () => ({ invalidateObjectDdlCache: vi.fn().mockResolvedValue(undefined) }));vi.mock("@/lib/table/objectBrowserRowsCache", () => ({ invalidateObjectBrowserRowsCache: vi.fn() }));@@ -24,6 +33,7 @@ let tamperSpecId: boolean;let operatorTargetConflict: boolean;let newSpecReads: number;let grants: Map<string, unknown[][]>;+let approvals: Map<string, { input: OracleRoutineSaveInput; record: OracleRoutineOperation }>;function key(name: string, type: string) {return `${name}:${type}`;@@ -52,6 +62,39 @@ beforeEach(() => {operatorTargetConflict = false;newSpecReads = 0;grants = new Map([["P_OLD", []]]);+ approvals = new Map();+ api.updateOracleRoutineOperationReferences.mockResolvedValue(undefined);+ api.prepareOracleRoutineSave.mockImplementation(async (input: OracleRoutineSaveInput) => {+ const operationId = `package-approval-${approvals.size}`;+ const record: OracleRoutineOperation = {+ operationId,+ identity: input.identity,+ target: { connectionId: input.connectionId, database: input.database, schema: input.identity.owner, databaseType: "oracle", generation: 1 },+ lifecycle: "prepared",+ acknowledged: false,+ dispatched: false,+ readback: null,+ error: null,+ };+ approvals.set(operationId, { input, record });+ return record;+ });+ api.executeOracleRoutineOperation.mockImplementation(async (id: string, sql: string) => {+ const approval = approvals.get(id)!;+ expect(sql).toBe(approval.input.sql);+ const record = approval.record;+ record.dispatched = true;+ record.lifecycle = "terminal";+ try {+ await api.executeQuery(approval.input.connectionId, approval.input.database, sql, approval.input.identity.owner);+ record.acknowledged = true;+ record.readback = { identity: record.identity, state: "verified", exists: true, version: null, source: sql, definitionMatches: true, compilerMessages: [], issues: [] };+ } catch (error) {+ record.error = error instanceof Error ? error.message : String(error);+ }+ return record;+ });+ api.observeOracleRoutineOperation.mockImplementation(async (id: string) => ({ operation: approvals.get(id)?.record ?? null, lifecycle: approvals.get(id)?.record.lifecycle ?? "unproven", error: null }));api.parseOracleObjectName.mockImplementation(async (name) => name.toUpperCase());api.buildExecutableObjectSourceStatements.mockImplementation(async ({ source }: { source: string }) => [source]);api.executeQuery.mockImplementation(async (_connection: string, _database: string, sql: string) => {@@ -111,6 +154,78 @@ beforeEach(() => {afterEach(() => vi.clearAllMocks());describe("Oracle package Save As plan and execution", () => {+ it("prepares the exact new specification with absence protection before confirmation and releases it without writing on cancel", async () => {+ const plan = await prepareOraclePackageSaveAs(target);+ const execute = await prepareOraclePackageSaveAsExecution(plan);+ expect(api.prepareOracleRoutineSave).toHaveBeenCalledExactlyOnceWith({ connectionId: target.connectionId, database: target.database, identity: { owner: "APP", name: "P_NEW", kind: "PACKAGE" }, sql: plan.specSource, requireAbsent: true });+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ await execute.dispose();+ expect(api.updateOracleRoutineOperationReferences).toHaveBeenLastCalledWith([], ["package-approval-0"]);+ expect(states.has(key("P_NEW", "PACKAGE"))).toBe(false);+ });++ it("uses controlled specification and body operations while freezing both old and new package identities", async () => {+ const plan = await prepareOraclePackageSaveAs(target);+ const dispatch = api.executeOracleRoutineOperation.getMockImplementation()!;+ api.executeOracleRoutineOperation.mockImplementation(async (...args) => {+ for (const name of ["P_OLD", "P_NEW"])+ for (const objectType of ["PACKAGE", "PACKAGE_BODY"]) {+ const identity = captureSourceIdentity({ connectionId: target.connectionId, database: target.database, schema: "APP", objectType, name });+ expect(() => beginSourceSave(identity)).toThrow();+ }+ return dispatch(...args);+ });+ await executeOraclePackageSaveAs(plan);+ expect(api.executeOracleRoutineOperation.mock.calls.map(([id, sql]) => [id, sql])).toEqual([+ ["package-approval-0", plan.specSource],+ ["package-approval-1", plan.bodySource],+ ]);+ expect(api.prepareOracleRoutineSave.mock.calls[1]![0]).toMatchObject({ requireAbsent: true, prerequisiteOperationId: "package-approval-0", identity: { kind: "PACKAGE_BODY", name: "P_NEW" } });+ expect(api.updateOracleRoutineOperationReferences.mock.calls).toEqual([+ [["package-approval-0"], []],+ [["package-approval-1"], []],+ [[], ["package-approval-1"]],+ [[], ["package-approval-0"]],+ ]);+ for (const name of ["P_OLD", "P_NEW"])+ for (const objectType of ["PACKAGE", "PACKAGE_BODY"]) {+ const release = beginSourceSave(captureSourceIdentity({ connectionId: target.connectionId, database: target.database, schema: "APP", objectType, name }));+ release();+ }+ });++ it("does not prepare a body against a different connection generation after specification success", async () => {+ const plan = await prepareOraclePackageSaveAs(target);+ const prepare = api.prepareOracleRoutineSave.getMockImplementation()!;+ api.prepareOracleRoutineSave.mockImplementation(async (input: OracleRoutineSaveInput) => {+ if (input.identity.kind === "PACKAGE_BODY") throw new Error("Package target changed before body preparation");+ return prepare(input);+ });+ await expect(executeOraclePackageSaveAs(plan)).rejects.toMatchObject({ completed: ["PACKAGE P_NEW"], uncertain: "PACKAGE BODY P_NEW", message: expect.stringContaining("target changed") });+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledTimes(1);+ expect(states.has(key("P_NEW", "PACKAGE BODY"))).toBe(false);+ expect(api.prepareOracleRoutineSave).toHaveBeenLastCalledWith(expect.objectContaining({ prerequisiteOperationId: "package-approval-0" }));+ });++ it("keeps the original unknown body operation even when its current definition is present", async () => {+ const plan = await prepareOraclePackageSaveAs({ ...target, connectionId: "package-save-as-unknown-body" });+ const dispatch = api.executeOracleRoutineOperation.getMockImplementation()!;+ api.executeOracleRoutineOperation.mockImplementation(async (id: string, sql: string) => {+ const record = await dispatch(id, sql);+ if (record.identity.kind === "PACKAGE_BODY") {+ record.lifecycle = "unproven";+ record.acknowledged = false;+ }+ return record;+ });+ await expect(executeOraclePackageSaveAs(plan)).rejects.toMatchObject({ completed: ["PACKAGE P_NEW"], uncertain: "PACKAGE BODY P_NEW", message: expect.stringContaining("package-approval-1") });+ expect(states.has(key("P_NEW", "PACKAGE BODY"))).toBe(true);+ await expect(executeOraclePackageSaveAs(plan)).rejects.toThrow();+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledTimes(2);+ expect(api.prepareOracleRoutineSave).toHaveBeenCalledTimes(2);+ expect(api.updateOracleRoutineOperationReferences).not.toHaveBeenCalledWith([], ["package-approval-1"]);+ });+it("validates generated spec and body against the executable Oracle source parser", async () => {const plan = await prepareOraclePackageSaveAs(target);diff --git a/apps/desktop/src/lib/__tests__/table/oracleRoutineWrite.spec.ts b/apps/desktop/src/lib/__tests__/table/oracleRoutineWrite.spec.tsindex db6f5eb1c4..412eaea4cc 100644--- a/apps/desktop/src/lib/__tests__/table/oracleRoutineWrite.spec.ts+++ b/apps/desktop/src/lib/__tests__/table/oracleRoutineWrite.spec.ts@@ -28,6 +28,50 @@ beforeEach(() => {});describe("Oracle routine source save", () => {+ it.each(["PACKAGE", "PACKAGE_BODY"] as const)("routes ordinary %s saves through the same prepared operation instead of direct SQL", async (kind) => {+ const { prepareObjectSourceSave } = await import("@/lib/table/objectSourceEditor");+ const source = { ...input(), identity: { ...input().identity, kind }, sql: `CREATE OR REPLACE ${kind.replaceAll("_", " ")} "Owner.Mixed"."Mixed.Func" AS END "Mixed.Func";` };+ const operation = record({ identity: source.identity });+ operation.readback = { ...operation.readback!, identity: source.identity, source: source.sql };+ vi.mocked(api.prepareOracleRoutineSave).mockResolvedValue({ ...operation, lifecycle: "prepared", dispatched: false, acknowledged: false, readback: null });+ vi.mocked(api.executeOracleRoutineOperation).mockResolvedValue(operation);+ const save = await prepareObjectSourceSave(source.connectionId, source.database, "oceanbase-oracle", [source.sql], source.identity.owner, { objectType: kind, name: source.identity.name });+ expect(api.prepareOracleRoutineSave).toHaveBeenCalledExactlyOnceWith(source);+ expect(api.executeOracleRoutineOperation).not.toHaveBeenCalled();+ await expect(save()).resolves.toEqual(operation);+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledExactlyOnceWith(operation.operationId, source.sql);+ expect(api.executeQuery).not.toHaveBeenCalled();+ expect(api.executeScript).not.toHaveBeenCalled();+ });++ it("does not prepare or dispatch a specification while its body has an unknown original save", async () => {+ const { prepareObjectSourceSave } = await import("@/lib/table/objectSourceEditor");+ const source = input();+ const unknown = record({ identity: { ...source.identity, kind: "PACKAGE_BODY" }, lifecycle: "unproven", acknowledged: false });+ vi.mocked(api.executeOracleRoutineOperation).mockResolvedValue(unknown);+ vi.mocked(api.observeOracleRoutineOperation).mockResolvedValue({ operation: unknown, lifecycle: "unproven", error: null });+ const body = await prepareObjectSourceSave(source.connectionId, source.database, "oracle", ["body draft"], source.identity.owner, { objectType: "PACKAGE_BODY", name: source.identity.name });+ await expect(body()).rejects.toMatchObject({ operationId: unknown.operationId });+ const spec = await prepareObjectSourceSave(source.connectionId, source.database, "oracle", ["new specification draft"], source.identity.owner, { objectType: "PACKAGE", name: source.identity.name });+ await expect(spec()).rejects.toMatchObject({ operationId: unknown.operationId });+ expect(api.prepareOracleRoutineSave).toHaveBeenCalledTimes(1);+ expect(api.executeOracleRoutineOperation).toHaveBeenCalledTimes(1);+ expect(api.executeQuery).not.toHaveBeenCalled();+ });++ it("keeps specification success separate from its invalid companion body and includes the actual compiler error", async () => {+ const { objectSourceSaveSuccessMessage } = await import("@/lib/table/objectSourceEditor");+ const operation = record();+ operation.readback!.packageCompanion = {+ ...operation.readback!,+ identity: { ...operation.identity, kind: "PACKAGE_BODY" },+ state: "invalid",+ version: { identity: { ...operation.identity, kind: "PACKAGE_BODY" }, status: "INVALID", objectId: "2", lastDdlTime: "1" },+ compilerMessages: [{ attribute: "ERROR", line: 8, position: 4, text: "PLS-00323" }],+ };+ expect(objectSourceSaveSuccessMessage("saved", operation)).toBe("saved\nPACKAGE BODY: INVALID\nERROR 8:4 PLS-00323");+ });+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");diff --git a/apps/desktop/src/lib/backend/__tests__/functionInfoTransport.spec.ts b/apps/desktop/src/lib/backend/__tests__/functionInfoTransport.spec.tsindex 7002e33594..d25d374dc8 100644--- a/apps/desktop/src/lib/backend/__tests__/functionInfoTransport.spec.ts+++ b/apps/desktop/src/lib/backend/__tests__/functionInfoTransport.spec.ts@@ -90,12 +90,62 @@ describe.each(["http", "tauri"] as const)("FunctionInfo %s transport", (transporif (transport === "tauri") expect(mocks.invoke).toHaveBeenLastCalledWith("prepare_oracle_routine_save", { input });});+ it("transports package kinds and typed selection without turning BODY-only into a legacy name selection", async () => {+ const options = { objectKinds: ["PACKAGE", "PACKAGE_BODY"] as Array<"PACKAGE" | "PACKAGE_BODY">, selectedObjects: [{ name: 'Pkg.With.Dot,"中文😀', kind: "PACKAGE_BODY" as const }] };+ response = {+ endpoint: { connectionId: "connection", database: "database", schema: "Owner.With.Dot", databaseType: "oceanbase-oracle", generation: 3 },+ state: "partial",+ enumerationComplete: true,+ issues: [],+ objects: [+ {+ version: { identity: { owner: "Owner.With.Dot", ...options.selectedObjects[0] }, objectId: "9007199254740993", status: "INVALID", lastDdlTime: "2026-10-23T01:00:00" },+ source: null,+ sourceComplete: false,+ dependencies: [],+ dependenciesComplete: true,+ issues: [{ stage: "source", code: "permission-denied", message: "ORA-01031" }],+ },+ ],+ };+ await expect(backend.loadSchemaDiffRoutines("connection", "database", "Owner.With.Dot", undefined, options)).resolves.toEqual(response);+ if (transport === "tauri") {+ expect(mocks.invoke).toHaveBeenLastCalledWith("load_schema_diff_routines", { connectionId: "connection", database: "database", schema: "Owner.With.Dot", ...options });+ } else {+ const params = new URL(String(fetchMock.mock.calls.at(-1)![0]), "http://localhost").searchParams;+ expect(JSON.parse(params.get("object_kinds")!)).toEqual(options.objectKinds);+ expect(JSON.parse(params.get("selected_objects")!)).toEqual(options.selectedObjects);+ expect(params.has("selected_routines")).toBe(false);+ }+ });+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("preserves explicit new-package absence protection in controlled save requests", async () => {+ const input = { connectionId: "target", database: "tenant", identity: { owner: "Owner.With.Dot", name: "Pkg.With.Dot", kind: "PACKAGE" as const }, sql: 'CREATE PACKAGE "Owner.With.Dot"."Pkg.With.Dot" AS g NUMBER; END;', requireAbsent: true };+ response = { operationId: "package-save", identity: input.identity, lifecycle: "prepared" };+ await expect(backend.prepareOracleRoutineSave(input)).resolves.toEqual(response);+ expect(transport === "tauri" ? sent().input : sent()).toEqual(input);+ });++ it("binds a Save As body request to its original verified specification operation", async () => {+ const input = {+ connectionId: "target",+ database: "tenant",+ identity: { owner: "Owner.With.Dot", name: "Pkg.With.Dot", kind: "PACKAGE_BODY" as const },+ sql: 'CREATE PACKAGE BODY "Owner.With.Dot"."Pkg.With.Dot" AS END;',+ requireAbsent: true,+ prerequisiteOperationId: "verified-new-specification",+ };+ response = { operationId: "package-body-save", identity: input.identity, lifecycle: "prepared" };+ await expect(backend.prepareOracleRoutineSave(input)).resolves.toEqual(response);+ expect(transport === "tauri" ? sent().input : sent()).toEqual(input);+ });+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" }] };@@ -112,6 +162,28 @@ describe.each(["http", "tauri"] as const)("FunctionInfo %s transport", (transporif (transport === "tauri") expect(mocks.invoke).toHaveBeenLastCalledWith("prepare_oracle_routine_recovery", { operationId: "original-operation" });});+ it("preserves explicit retained-body and target-contract choices instead of broadening package selection", 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 identity = { owner: "Owner.With.Dot", name: "Pkg.With.Dot", kind: "PACKAGE_BODY" as const };+ const input = { source: snapshot, target: snapshot, drafts: [{ identity, action: "replace" as const, packageBodySource: "target" as const, packageContract: "target" as const, confirmPackagePair: true, sql: "retained body draft" }] };+ response = {+ target: snapshot.endpoint,+ ready: false,+ steps: [+ {+ identity,+ sql: input.drafts[0].sql,+ packageImpact: { companion: { ...identity, kind: "PACKAGE" }, companionAction: null, implicitCompanionDelete: false, retainsTargetBody: true, bodyPending: false, mayInitialize: true, grants: null },+ issues: [{ code: "plan-preflight", message: "Refresh the complete target pair", line: 1, column: 1 }],+ },+ ],+ };+ const result = await backend.prepareOracleRoutinePlan(input);+ expect(result).toEqual(response);+ expect(transport === "tauri" ? sent().input : sent()).toEqual(input);+ expect(result.steps[0]?.packageImpact?.retainsTargetBody).toBe(true);+ });+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"] });@@ -125,6 +197,38 @@ describe.each(["http", "tauri"] as const)("FunctionInfo %s transport", (transporelse expect(String(fetchMock.mock.calls.at(-1)![0])).toContain("/api/schema/routine-operation?operation_id=old-operation&refresh_readback=true");});+ it("retains the independently identified package companion and exact source origins in operation readback", async () => {+ const identity = { owner: "Owner.With.Dot", name: "Pkg.With.Dot", kind: "PACKAGE" as const };+ const companion = {+ identity: { ...identity, kind: "PACKAGE_BODY" as const },+ state: "invalid" as const,+ exists: true,+ version: null,+ source: "CREATE PACKAGE BODY ...",+ sourceOrigin: "oceanbase-dictionary" as const,+ definitionMatches: null,+ compilerMessages: [{ attribute: "ERROR", line: 1, position: 0, text: "PLS-00323" }],+ issues: [],+ };+ response = {+ operation: {+ operationId: "package-spec",+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ error: null,+ readback: { identity, state: "verified", exists: true, version: null, source: "CREATE PACKAGE ...", sourceOrigin: "oracle-metadata", packageCompanion: companion, definitionMatches: true, compilerMessages: [], issues: [] },+ },+ lifecycle: "terminal",+ error: null,+ };+ const observed = await backend.observeOracleRoutineOperation("package-spec", true);+ expect(observed).toEqual(response);+ expect(observed.operation?.readback?.packageCompanion).toEqual(companion);+ expect(observed.operation?.readback?.sourceOrigin).toBe("oracle-metadata");+ });+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);@@ -153,6 +257,34 @@ describe.each(["http", "tauri"] as const)("FunctionInfo %s transport", (transporexpect((sent().functionDiffs as FunctionDiff[])[0].source).not.toHaveProperty("function_type");});+ it("retains explicit package diff identity and kind-scoped read issues through preparation and selected SQL requests", async () => {+ const body = { ...procedure, name: "Pkg.With.Dot", function_type: "PACKAGE_BODY", definition: 'CREATE OR REPLACE PACKAGE BODY "S"."Pkg.With.Dot" AS END;' };+ const targetBody = { ...body, definition: body.definition.replace('"S".', '"T".') };+ const wireBody = { ...wireProcedure, name: body.name, functionType: "PACKAGE_BODY", definition: body.definition };+ const wireTarget = { ...wireBody, definition: targetBody.definition };+ const packageDiff: FunctionDiff = { type: "unreadable", name: body.name, programKind: "PACKAGE_BODY", source: body, target: targetBody };+ const oracleRoutines = {+ sourceDatabaseType: "oceanbase-oracle",+ targetDatabaseType: "oceanbase-oracle",+ sourceSchema: "S",+ targetSchema: "T",+ sourceEnumerationComplete: true,+ targetEnumerationComplete: true,+ sourceIncompleteNames: [body.name],+ targetIncompleteNames: [],+ objectKinds: ["PACKAGE", "PACKAGE_BODY"] as Array<"PACKAGE" | "PACKAGE_BODY">,+ sourceIncompleteObjects: [{ name: body.name, kind: "PACKAGE_BODY" as const }],+ targetIncompleteObjects: [],+ };+ response = { diffs: [], syncSql: "", functionDiffs: [{ ...packageDiff, source: wireBody, target: wireTarget }] };+ const result = await backend.prepareSchemaDiff({ sourceTables: [], targetTables: [], sourceDetails: [], targetDetails: [], sourceFunctions: [body], targetFunctions: [targetBody], databaseType: "oceanbase-oracle", oracleRoutines });+ expect(result.functionDiffs).toEqual([packageDiff]);+ expect(transport === "tauri" ? sent().options : sent()).toMatchObject({ oracleRoutines });+ response = { syncSql: "", rollbackCompleteness: "complete", missingRollbackObjects: [] };+ await backend.generateSchemaSyncPlan({ diffs: [], functionDiffs: result.functionDiffs!, sequenceDiffs: [], ruleDiffs: [], ownerDiffs: [] }, { databaseType: "oceanbase-oracle", targetSchema: "T" });+ expect(sent()).toMatchObject({ functionDiffs: [{ programKind: "PACKAGE_BODY", source: wireBody, target: wireTarget }] });+ });+it("uses the same routine wire fields for the legacy SQL plan entry", async () => {response = "";await backend.generateSchemaSyncSql([], "oracle", "APP", [diff]);diff --git a/apps/desktop/src/lib/backend/__tests__/packageTransferTransport.spec.ts b/apps/desktop/src/lib/backend/__tests__/packageTransferTransport.spec.tsnew file mode 100644index 0000000000..487607e134--- /dev/null+++ b/apps/desktop/src/lib/backend/__tests__/packageTransferTransport.spec.ts@@ -0,0 +1,232 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { TransferContent, TransferProgress, TransferRequest, OraclePackageTransferRequest } from "@/lib/backend/tauri";++function reviewedPackage(): OraclePackageTransferRequest {+ const source = { connectionId: "source", database: "tenant", schema: "Source.With.Dot", databaseType: "oracle" as const, generation: 1 };+ const target = { ...source, connectionId: "target", schema: "Target.With.Dot", databaseType: "oceanbase-oracle" as const };+ return {+ input: {+ source: { endpoint: source, state: "complete", enumerationComplete: true, objects: [], issues: [] },+ target: { endpoint: target, state: "complete", enumerationComplete: true, objects: [], issues: [] },+ drafts: [{ identity: { owner: target.schema, name: 'Pkg.With.Dot,"中文😀', kind: "PACKAGE_BODY" }, action: "create", sql: 'CREATE PACKAGE BODY "Target.With.Dot"."Pkg.With.Dot,""中文😀" AS END;', packageContract: "target", confirmPackagePair: false }],+ },+ operationIds: ["original-approved-body-id"],+ };+}++const native = vi.hoisted(() => ({ invoke: vi.fn(), listen: vi.fn() }));+vi.mock("@tauri-apps/api/core", () => ({ invoke: native.invoke }));+vi.mock("@tauri-apps/api/event", () => ({ listen: native.listen }));++describe.each(["http", "tauri"] as const)("package transfer %s transport", (transport) => {+ let backend: typeof import("@/lib/backend/http");+ let deliver: (progress: TransferProgress) => void;+ const fetchMock = vi.fn();+ const unlisten = vi.fn();++ beforeEach(async () => {+ vi.clearAllMocks();+ native.invoke.mockResolvedValue(undefined);+ native.listen.mockImplementation(async (_event: string, handler: (event: { payload: TransferProgress }) => void) => {+ deliver = (progress) => handler({ payload: progress });+ return unlisten;+ });+ fetchMock.mockResolvedValue({ ok: true });+ vi.stubGlobal("fetch", fetchMock);+ class Stream {+ onmessage: ((event: { data: string }) => void) | null = null;+ onerror: (() => void) | null = null;+ close = unlisten;+ constructor() {+ deliver = (progress) => this.onmessage?.({ data: JSON.stringify(progress) });+ }+ }+ vi.stubGlobal("EventSource", Stream);+ backend = await import(transport === "http" ? "@/lib/backend/http" : "@/lib/backend/tauri");+ });+ afterEach(() => vi.unstubAllGlobals());++ it.each(["structureOnly", "structureAndData", "dataOnly"] satisfies TransferContent[])("retains explicit spec/body identity in %s without broadening BODY-only", async (content) => {+ const request: TransferRequest = {+ transferId: "package-transfer",+ sourceConnectionId: "source",+ sourceDatabase: "tenant",+ sourceSchema: "Source.With.Dot",+ targetConnectionId: "target",+ targetDatabase: "tenant",+ targetSchema: "Target.With.Dot",+ tables: content === "structureAndData" ? ["orders"] : [],+ createTable: content !== "dataOnly",+ content,+ objects: [{ objectType: "PACKAGE_BODY", names: ['Pkg.With.Dot,"中文😀'] }],+ mode: "append",+ targetTableNameCase: "preserve",+ quoteTargetColumnNames: true,+ batchSize: 100,+ dropTargetBeforeCreate: false,+ dropTargetConfirmed: false,+ oraclePackages: reviewedPackage(),+ };+ const progress = vi.fn();+ const started = vi.fn();+ const pending = backend.startTransfer(request, progress, started);+ await vi.waitFor(() => expect(started).toHaveBeenCalledOnce());+ const sent = transport === "http" ? JSON.parse(String(fetchMock.mock.calls[0][1].body)) : native.invoke.mock.calls[0][1];+ expect(sent.request).toEqual(request);+ expect(sent.request.objects).toEqual([{ objectType: "PACKAGE_BODY", names: ['Pkg.With.Dot,"中文😀'] }]);+ expect(sent.request.oraclePackages).toEqual(reviewedPackage());+ const input = request.oraclePackages!.input!;+ const identity = input.drafts[0].identity;+ const operation: TransferProgress = {+ transferId: request.transferId,+ table: `PackageBody:${identity.name}`,+ tableIndex: 0,+ totalTables: request.tables.length,+ rowsTransferred: 0,+ totalRows: null,+ status: "error",+ terminal: false,+ error: "Package body is INVALID",+ oracleRoutineOperation: {+ operationId: "original-approved-body-id",+ target: input.target.endpoint,+ identity,+ lifecycle: "terminal",+ dispatched: true,+ acknowledged: true,+ error: null,+ readback: { identity, state: "invalid", exists: true, version: null, source: input.drafts[0].sql!, definitionMatches: true, issues: [], compilerMessages: [{ attribute: "ERROR", line: 2, position: 3, text: "PLS-00323 中文😀" }] },+ },+ };+ deliver(operation);+ expect(progress).toHaveBeenCalledWith(operation);+ expect(unlisten).not.toHaveBeenCalled();+ const terminal: TransferProgress = { transferId: request.transferId, table: "", tableIndex: request.tables.length, totalTables: request.tables.length, rowsTransferred: 0, totalRows: null, status: "done", terminal: true, error: null };+ deliver(terminal);+ await expect(pending).resolves.toBeUndefined();+ expect(progress).toHaveBeenCalledWith(terminal);+ expect(unlisten).toHaveBeenCalledOnce();+ });++ it("preserves frozen pending-table evidence and the ordered nonterminal approval event", async () => {+ const packages = reviewedPackage();+ packages.operationIds = [];+ packages.pendingTables = {+ source: packages.input!.source.endpoint,+ target: packages.input!.target.endpoint,+ tables: [{ sourceTable: "SOURCE", finalDdl: 'CREATE TABLE "Target.With.Dot".FINAL("中文😀" VARCHAR2(20 CHAR))' }],+ dependencyManifest: { proofGroups: [{ use: "external-source", source: "完整原文 中文😀" }] },+ tableEvidence: [{ sourceTable: "SOURCE", targetTable: "FINAL", namespaceRows: [] }],+ };+ const request: TransferRequest = {+ transferId: "pending-tables",+ sourceConnectionId: "source",+ sourceDatabase: "tenant",+ sourceSchema: "Source.With.Dot",+ targetConnectionId: "target",+ targetDatabase: "tenant",+ targetSchema: "Target.With.Dot",+ tables: ["SOURCE"],+ createTable: true,+ content: "structureAndData",+ objects: [{ objectType: "PACKAGE_BODY", names: [packages.input!.drafts[0].identity.name] }],+ mode: "append",+ targetTableNameCase: "preserve",+ quoteTargetColumnNames: true,+ batchSize: 100,+ dropTargetBeforeCreate: false,+ dropTargetConfirmed: false,+ oraclePackages: packages,+ };+ const progress = vi.fn();+ const started = vi.fn();+ const pending = backend.startTransfer(request, progress, started);+ await vi.waitFor(() => expect(started).toHaveBeenCalledOnce());+ const sent = transport === "http" ? JSON.parse(String(fetchMock.mock.calls[0][1].body)) : native.invoke.mock.calls[0][1];+ expect(sent.request.oraclePackages).toEqual(packages);+ const approval: TransferProgress = {+ transferId: request.transferId,+ table: "package objects",+ tableIndex: 1,+ totalTables: 1,+ rowsTransferred: 0,+ totalRows: null,+ status: "running",+ terminal: false,+ error: null,+ oraclePackageApproval: { input: packages.input!, skipped: [], plan: { target: packages.input!.target.endpoint, ready: true, steps: [] } },+ };+ deliver(approval);+ expect(progress).toHaveBeenNthCalledWith(1, approval);+ expect(unlisten).not.toHaveBeenCalled();+ deliver({ ...approval, oraclePackageApproval: undefined, status: "done", terminal: true });+ await expect(pending).resolves.toBeUndefined();+ expect(unlisten).toHaveBeenCalledOnce();+ });++ it("returns structured preflight issues and full drafts without any dispatched operation", async () => {+ const request: TransferRequest = {+ transferId: "blocked-package-transfer",+ sourceConnectionId: "source",+ sourceDatabase: "tenant",+ sourceSchema: "Source.With.Dot",+ targetConnectionId: "target",+ targetDatabase: "tenant",+ targetSchema: "Target.With.Dot",+ tables: ["not_written"],+ createTable: true,+ content: "structureAndData",+ mode: "append",+ targetTableNameCase: "preserve",+ quoteTargetColumnNames: true,+ batchSize: 100,+ dropTargetBeforeCreate: false,+ dropTargetConfirmed: false,+ objects: [{ objectType: "PACKAGE_BODY", names: ['Pkg.With.Dot,"中文😀'] }],+ };+ const progress = vi.fn();+ const started = vi.fn();+ const pending = backend.startTransfer(request, progress, started);+ await vi.waitFor(() => expect(started).toHaveBeenCalledOnce());+ const input = reviewedPackage().input!;+ const identity = input.drafts[0].identity;+ const terminal: TransferProgress = {+ transferId: request.transferId,+ table: "schema objects",+ tableIndex: 0,+ totalTables: request.tables.length,+ rowsTransferred: 0,+ totalRows: null,+ status: "error",+ terminal: true,+ error: "Target draft requires correction",+ oraclePackagePreflight: {+ input,+ skipped: [],+ plan: {+ target: input.target.endpoint,+ ready: false,+ steps: [+ {+ identity,+ action: "create",+ sql: input.drafts[0].sql!,+ sourceOriginal: "Full body 中文😀",+ targetOriginal: null,+ recoverySql: null,+ recoveryComplete: false,+ references: [],+ incomingCallers: [],+ operation: null,+ issues: [{ code: "missing-reference", message: "Missing column 中文😀", line: 3, column: 7 }],+ },+ ],+ },+ },+ };+ deliver(terminal);+ await expect(pending).resolves.toBeUndefined();+ expect(progress).toHaveBeenCalledWith(terminal);+ expect(unlisten).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex f755999906..e01631962d 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -1169,6 +1169,9 @@ export type {SqlFileTable,SqlFileProgress,TransferRequest,+ OraclePackageTransferRequest,+ OraclePackageTransferPreview,+ OraclePackagePendingTables,TransferProgress,TransferMode,TransferContent,diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 735e96da2e..dff8c270a5 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -10,7 +10,7 @@ import type { PluginUiStorageItemRef, SqlFileFailureLogExportPayload, SqlFileFaiimport { 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";+import type { OracleRoutineSnapshot, OracleRoutineOperation, OracleRoutineOperationObservation, OracleRoutineSaveInput, OracleRoutinePlanInput, OracleRoutinePlan, OracleRoutineReadOptions } from "@/types/schemaDiff";export function databaseBackupCommand<T = unknown>(command: DatabaseBackupCommand): Promise<T> {return post("/api/database-backups", command);@@ -1436,8 +1436,10 @@ export async function listFunctions(connectionId: string, database: string, schereturn (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 loadSchemaDiffRoutines(connectionId: string, database: string, schema: string, selectedRoutines?: string[], options?: OracleRoutineReadOptions): Promise<OracleRoutineSnapshot> {+ return get(+ `/api/schema/diff-routines?${qs({ connection_id: connectionId, database, schema, selected_routines: selectedRoutines === undefined ? undefined : JSON.stringify(selectedRoutines), object_kinds: options?.objectKinds === undefined ? undefined : JSON.stringify(options.objectKinds), selected_objects: options?.selectedObjects === undefined ? undefined : JSON.stringify(options.selectedObjects) })}`,+ );}export function prepareOracleRoutineSave(input: OracleRoutineSaveInput): Promise<OracleRoutineOperation> {diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex 98498f0fa7..9a3ea633f1 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -8,7 +8,7 @@ import type { DamengDumpKind, DamengDumpRequest, DamengDumpProgress } from "./daimport 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";+import type { OracleRoutineSnapshot, OracleRoutineOperation, OracleRoutineOperationObservation, OracleRoutineSaveInput, OracleRoutinePlanInput, OracleRoutinePlan, OracleRoutineReadOptions, OracleRoutineIdentity } from "@/types/schemaDiff";export function databaseBackupCommand<T = unknown>(command: DatabaseBackupCommand): Promise<T> {return invoke("database_backup_command", { command });@@ -2883,8 +2883,8 @@ export async function listFunctions(connectionId: string, database: string, schereturn (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 loadSchemaDiffRoutines(connectionId: string, database: string, schema: string, selectedRoutines?: string[], options?: OracleRoutineReadOptions): Promise<OracleRoutineSnapshot> {+ return invoke("load_schema_diff_routines", { connectionId, database, schema, ...(selectedRoutines === undefined ? {} : { selectedRoutines }), ...options });}export function prepareOracleRoutineSave(input: OracleRoutineSaveInput): Promise<OracleRoutineOperation> {@@ -5686,7 +5686,7 @@ export interface HistoryConnectionOption extends HistoryConnectionFilter {export type TaskType = "transfer";export type TaskLifecycleOwner = "tauri" | "web";export type TaskRunStatus = "running" | "succeeded" | "partial_failed" | "failed" | "cancelled";-export type TaskItemKind = "table" | "view" | "materialized_view" | "procedure" | "function" | "trigger" | "sequence" | "event" | "object";+export type TaskItemKind = "table" | "view" | "materialized_view" | "procedure" | "function" | "package" | "package_body" | "trigger" | "sequence" | "event" | "object";export type TaskItemStatus = "pending" | "running" | "succeeded" | "skipped" | "failed" | "cancelled" | "not_started" | "incomplete";export type TaskRowCountState = "not_applicable" | "known" | "unknown" | "incomplete";export type TransferRunContent = "structure_and_data" | "structure_only" | "data_only";@@ -5968,7 +5968,7 @@ export type TransferTableNameCase = "preserve" | "lower" | "upper";export type TransferColumnNameCase = "preserve" | "lower" | "upper";export type TransferOwnershipPolicy = "preserve" | "skip" | "reassignMissing";export type TransferContent = "structureAndData" | "structureOnly" | "dataOnly";-export type TransferObjectKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "SEQUENCE" | "EVENT" | "PACKAGE" | "SYNONYM";+export type TransferObjectKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "SEQUENCE" | "EVENT" | "PACKAGE" | "PACKAGE_BODY" | "SYNONYM";export interface TransferObjectSelection {objectType: TransferObjectKind;@@ -6006,6 +6006,28 @@ export interface TransferRequest {tableFilters?: Record<string, string>;dropTargetBeforeCreate: boolean;dropTargetConfirmed: boolean;+ oraclePackages?: OraclePackageTransferRequest;+}++export interface OraclePackageTransferRequest {+ input?: OracleRoutinePlanInput;+ operationIds?: string[];+ pendingTables?: OraclePackagePendingTables;+}++export interface OraclePackagePendingTables {+ source: OracleRoutinePlanInput["source"]["endpoint"];+ target: OracleRoutinePlanInput["target"]["endpoint"];+ tables: unknown[];+ dependencyManifest: unknown;+ tableEvidence: unknown[];+}++export interface OraclePackageTransferPreview {+ input: OracleRoutinePlanInput;+ plan: OracleRoutinePlan;+ skipped: OracleRoutineIdentity[];+ pendingTables?: OraclePackagePendingTables;}export interface TransferStructurePreviewTable {@@ -6046,9 +6068,13 @@ export interface TransferOwnershipPreview {};/** Structure-plan preview: present for structure-only transfers. */structure?: TransferStructurePreview;+ oraclePackages?: OraclePackageTransferPreview;}export interface TransferProgress {+ oraclePackageApproval?: OraclePackageTransferPreview;+ oraclePackagePreflight?: OraclePackageTransferPreview;+ oracleRoutineOperation?: OracleRoutineOperation;transferId: string;table: string;tableIndex: number;diff --git a/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts b/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.tsindex bc6dbc4d1a..9538b3b360 100644--- a/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts+++ b/apps/desktop/src/lib/database/__tests__/transferObjectKinds.spec.ts@@ -14,6 +14,18 @@ describe("transferObjectKinds", () => {expect(transferSchemasForDatabase("postgres", schemas)).toBe(schemas);expect(transferSchemasForDatabase("mysql", schemas)).toBe(schemas);});+ it("offers exact package kinds only when both actual products support them", () => {+ for (const source of ["oracle", "oceanbase-oracle"] as const) {+ expect(transferObjectKindsForDatabase(source)).toEqual(expect.arrayContaining(["PACKAGE", "PACKAGE_BODY"]));+ for (const target of ["oracle", "oceanbase-oracle"] as const) expect(crossFamilyTransferableKinds(source, target)).toEqual(expect.arrayContaining(["PACKAGE", "PACKAGE_BODY"]));+ for (const target of ["dameng", "xugu", "mysql", "postgres"] as const) {+ expect(crossFamilyTransferableKinds(source, target)).not.toContain("PACKAGE");+ expect(crossFamilyTransferableKinds(target, source)).not.toContain("PACKAGE_BODY");+ }+ }+ expect(transferObjectKindsForDatabase("dameng")).not.toContain("PACKAGE");+ });+it("groups databases into transfer families", () => {expect(transferObjectFamily("mysql")).toBe(TransferObjectFamily.Mysql);expect(transferObjectFamily("kingbase")).toBe(TransferObjectFamily.Postgres);@@ -25,7 +37,7 @@ describe("transferObjectKinds", () => {it("returns per-family object kinds", () => {expect(transferObjectKindsForDatabase("mysql")).toEqual(["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT"]);expect(transferObjectKindsForDatabase("postgres")).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"]);- expect(transferObjectKindsForDatabase("oracle")).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"]);+ expect(transferObjectKindsForDatabase("oracle")).toEqual(["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE", "PACKAGE", "PACKAGE_BODY"]);expect(transferObjectKindsForDatabase("sqlserver")).toEqual(["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"]);});@@ -60,14 +72,16 @@ describe("transferObjectKinds", () => {expect(isTransferPairSupported(undefined, "xugu")).toBe(true);});- it("exposes native Xugu schema objects without enabling them for other engines", () => {+ it("keeps native Xugu schema objects and engine-pair boundaries intact", () => {const kinds = ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE", "PACKAGE", "SYNONYM"];expect(transferObjectKindsForDatabase("xugu")).toEqual(kinds);expect(crossFamilyTransferableKinds("xugu", "xugu")).toEqual(kinds);+ expect(transferObjectKindsForDatabase("xugu")).not.toContain("PACKAGE_BODY");for (const engine of ["postgres", "mysql", "oracle", "dameng", "sqlserver"] as const) {expect(crossFamilyTransferableKinds("xugu", engine)).toEqual([]);expect(crossFamilyTransferableKinds(engine, "xugu")).toEqual([]);- expect(transferObjectKindsForDatabase(engine)).not.toContain("PACKAGE");+ if (engine === "oracle") expect(transferObjectKindsForDatabase(engine)).toContain("PACKAGE");+ else expect(transferObjectKindsForDatabase(engine)).not.toContain("PACKAGE");expect(transferObjectKindsForDatabase(engine)).not.toContain("SYNONYM");}});diff --git a/apps/desktop/src/lib/database/databaseObjectCapabilities.ts b/apps/desktop/src/lib/database/databaseObjectCapabilities.tsindex 17407af8a3..4b7f7729b2 100644--- a/apps/desktop/src/lib/database/databaseObjectCapabilities.ts+++ b/apps/desktop/src/lib/database/databaseObjectCapabilities.ts@@ -1,4 +1,5 @@import type { DatabaseType } from "@/types/database";+import type { OracleRoutineKind } from "@/types/schemaDiff";export type SidebarObjectKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "FUNCTION_INTERNAL" | "FUNCTION_UDF" | "TRIGGER" | "EVENT" | "SEQUENCE" | "INDEX" | "SYNONYM" | "JOB" | "PACKAGE" | "PACKAGE_BODY" | "TYPE" | "TYPE_BODY";@@ -174,19 +175,23 @@ export function supportsSchemaDiffRoutines(dbType?: DatabaseType): boolean {return SCHEMA_DIFF_ROUTINE_KINDS.some((kind) => sidebarObjects.includes(kind) && sourceReadable.includes(kind));}-export function schemaDiffRoutineObjectTypes(dbType?: DatabaseType): Array<"PROCEDURE" | "FUNCTION"> {+export function schemaDiffRoutineObjectTypes(dbType?: DatabaseType, requestedKinds: readonly OracleRoutineKind[] = SCHEMA_DIFF_ROUTINE_KINDS): OracleRoutineKind[] {if (!supportsSchemaDiffRoutines(dbType)) return [];const { sidebarObjects, sourceReadable } = databaseObjectCapabilities(dbType);- return SCHEMA_DIFF_ROUTINE_KINDS.filter((kind) => sidebarObjects.includes(kind) && sourceReadable.includes(kind));+ const kinds: OracleRoutineKind[] = dbType === "oracle" || dbType === "oceanbase-oracle" ? [...SCHEMA_DIFF_ROUTINE_KINDS, "PACKAGE", "PACKAGE_BODY"] : [...SCHEMA_DIFF_ROUTINE_KINDS];+ return kinds.filter((kind) => requestedKinds.includes(kind) && sidebarObjects.includes(kind) && sourceReadable.includes(kind));}-export function schemaDiffRoutineObjectTypesIntersection(sourceDbType?: DatabaseType, targetDbType?: DatabaseType): Array<"PROCEDURE" | "FUNCTION"> {+export function schemaDiffRoutineObjectTypesIntersection(sourceDbType?: DatabaseType, targetDbType?: DatabaseType, requestedKinds?: readonly OracleRoutineKind[]): OracleRoutineKind[] {if (!sourceDbType || !targetDbType) return [];const sourceFamily = SCHEMA_DIFF_ROUTINE_FAMILY.get(sourceDbType);const targetFamily = SCHEMA_DIFF_ROUTINE_FAMILY.get(targetDbType);- if (!sourceFamily || sourceFamily !== targetFamily) return [];- const sourceTypes = new Set(schemaDiffRoutineObjectTypes(sourceDbType));- return schemaDiffRoutineObjectTypes(targetDbType).filter((kind) => sourceTypes.has(kind));+ if (!sourceFamily || !targetFamily) return [];+ const sourceTypes = new Set(schemaDiffRoutineObjectTypes(sourceDbType, requestedKinds));+ const shared = schemaDiffRoutineObjectTypes(targetDbType, requestedKinds).filter((kind) => sourceTypes.has(kind));+ if (sourceFamily === targetFamily) return shared;+ if ((sourceFamily === "oracle" || sourceFamily === "oceanbase-oracle") && (targetFamily === "oracle" || targetFamily === "oceanbase-oracle")) return shared.filter((kind) => kind === "PACKAGE" || kind === "PACKAGE_BODY");+ return [];}export function sidebarObjectKindsForDatabase(dbType?: DatabaseType, compatibilityMode?: string): SidebarObjectKind[] {diff --git a/apps/desktop/src/lib/database/transferObjectKinds.ts b/apps/desktop/src/lib/database/transferObjectKinds.tsindex f9c5bdd170..66bcff6a66 100644--- a/apps/desktop/src/lib/database/transferObjectKinds.ts+++ b/apps/desktop/src/lib/database/transferObjectKinds.ts@@ -14,7 +14,7 @@ export enum TransferObjectFamily {SqlServer = "sqlserver",}-export type TransferObjectKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "SEQUENCE" | "EVENT" | "PACKAGE" | "SYNONYM";+export type TransferObjectKind = "TABLE" | "VIEW" | "MATERIALIZED_VIEW" | "PROCEDURE" | "FUNCTION" | "TRIGGER" | "SEQUENCE" | "EVENT" | "PACKAGE" | "PACKAGE_BODY" | "SYNONYM";const MYSQL_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "EVENT"];const POSTGRES_KINDS: TransferObjectKind[] = ["TABLE", "VIEW", "MATERIALIZED_VIEW", "PROCEDURE", "FUNCTION", "TRIGGER", "SEQUENCE"];@@ -46,7 +46,7 @@ export function transferObjectKindsForDatabase(dbType?: DatabaseType): TransferOcase TransferObjectFamily.Postgres:return [...POSTGRES_KINDS];case TransferObjectFamily.Oracle:- return [...ORACLE_KINDS];+ return dbType === "oracle" || dbType === "oceanbase-oracle" ? [...ORACLE_KINDS, "PACKAGE", "PACKAGE_BODY"] : [...ORACLE_KINDS];case TransferObjectFamily.SqlServer:return [...SQLSERVER_KINDS];default:@@ -66,7 +66,7 @@ export function transferObjectKindsForDatabase(dbType?: DatabaseType): TransferOexport function crossFamilyTransferableKinds(a?: DatabaseType, b?: DatabaseType): TransferObjectKind[] {if (a === "xugu" || b === "xugu") return a === "xugu" && b === "xugu" ? transferObjectKindsForDatabase("xugu") : [];if (isSameTransferFamily(a, b)) {- return transferObjectKindsForDatabase(a);+ return transferObjectKindsForDatabase(a).filter((kind) => transferObjectKindsForDatabase(b).includes(kind));}const aFam = transferObjectFamily(a);const bFam = transferObjectFamily(b);diff --git a/apps/desktop/src/lib/schema/oracleRoutineDeploy.ts b/apps/desktop/src/lib/schema/oracleRoutineDeploy.tsindex 33500e826f..41a0e5d3fa 100644--- a/apps/desktop/src/lib/schema/oracleRoutineDeploy.ts+++ b/apps/desktop/src/lib/schema/oracleRoutineDeploy.ts@@ -4,13 +4,16 @@ import { beginSourceSave, captureSourceIdentity } from "@/lib/table/objectSourceimport { 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 type { OracleRoutineIdentity, OracleRoutineOperation, OracleRoutinePlan, OracleRoutinePlanDraft, OracleRoutinePlanStep, OracleRoutineSnapshot, OracleRoutinePlanInput } from "@/types/schemaDiff";import { releaseOracleRoutineOperations, retainOracleRoutineOperations } from "@/lib/table/oracleRoutineOperationReferences";export interface OracleRoutineDeployDraft extends OracleRoutinePlanDraft {objectId: string;included: boolean;operation?: OracleRoutineOperation;+ packageBodyDrafts?: Partial<Record<"source" | "target", string>>;+ companionFor?: string;+ reviewedTargetDraft?: boolean;}/** Owned by the existing comparison session, not the mounted dialog. */@@ -89,7 +92,7 @@ export function synchronizeOracleRoutineSelection(state: OracleRoutineDeploymentif (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");+ const included = objects.some((object) => (object.id === draft.objectId || object.id === draft.companionFor) && object.selected && object.operationType !== "none");if (draft.included !== included) {draft.included = included;changed = true;@@ -97,7 +100,7 @@ export function synchronizeOracleRoutineSelection(state: OracleRoutineDeployment}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");+ if (object.routineType !== "FUNCTION" && object.routineType !== "PROCEDURE" && object.routineType !== "PACKAGE" && object.routineType !== "PACKAGE_BODY") throw new Error("Program selection has no exact supported kind");state.drafts.push({objectId: object.id,identity: { owner: state.target.endpoint.schema, name: object.targetName ?? object.name, kind: object.routineType },@@ -121,11 +124,84 @@ export function synchronizeOracleRoutineSelection(state: OracleRoutineDeployment}}+export function includeOraclePackageCompanion(state: OracleRoutineDeployment, objectId: string, bodySource: "source" | "target" = "source"): OracleRoutineDeployDraft | undefined {+ const current = state.drafts.find((draft) => draft.objectId === objectId && draft.included);+ if (state.disposed || state.executing || !current || (current.identity.kind !== "PACKAGE" && current.identity.kind !== "PACKAGE_BODY")) return;+ if (current.identity.kind === "PACKAGE" && current.action === "delete") return;+ const kind = current.identity.kind === "PACKAGE" ? "PACKAGE_BODY" : "PACKAGE";+ const identity: OracleRoutineIdentity = { ...current.identity, kind };+ const existing = state.drafts.find((draft) => routineIdentityKey(draft.identity) === routineIdentityKey(identity));+ if (existing?.included && (kind !== "PACKAGE_BODY" || (existing.operation && oracleRoutineOperationVerified(existing.operation)))) {+ state.selectedObjectId = existing.objectId;+ return existing;+ }+ const material = current.action === "delete" || (kind === "PACKAGE_BODY" && bodySource === "target") ? state.target : state.source;+ const name = material === state.source ? (current.sourceName ?? current.identity.name) : current.identity.name;+ const original = material.objects.find((object) => object.version.identity.owner === material.endpoint.schema && object.version.identity.name === name && object.version.identity.kind === kind);+ if (!original?.sourceComplete || !original.source) {+ state.error = "Completely read the selected package companion before adding its write; refresh the comparison without discarding the draft";+ return;+ }+ const target = state.target.objects.find((object) => routineIdentityKey(object.version.identity) === routineIdentityKey(identity));+ const draft: OracleRoutineDeployDraft = existing ?? { objectId: `package-companion:${routineIdentityKey(identity)}`, identity, action: current.action === "delete" ? "delete" : target ? "replace" : "create", sourceName: current.sourceName ?? current.identity.name, included: true };+ if (!existing) state.drafts.push(draft);+ const action = current.action === "delete" ? "delete" : target ? "replace" : "create";+ if (draft.action !== action) {+ draft.action = action;+ draft.sql = undefined;+ draft.reviewedTargetDraft = false;+ }+ draft.included = true;+ draft.companionFor = current.objectId;+ if (kind === "PACKAGE_BODY") editOraclePackageOptions(state, draft.objectId, { packageBodySource: bodySource });+ for (const peer of state.drafts) if (peer.identity.owner === identity.owner && peer.identity.name === identity.name) peer.confirmPackagePair = false;+ state.selectedObjectId = draft.objectId;+ state.revision++;+ state.plan = null;+ state.recoveryPlan = null;+ state.error = null;+ return draft;+}+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;+ draft.reviewedTargetDraft = true;+ if (draft.identity.kind === "PACKAGE" || draft.identity.kind === "PACKAGE_BODY") {+ for (const peer of state.drafts) if (peer.identity.owner === draft.identity.owner && peer.identity.name === draft.identity.name) peer.confirmPackagePair = false;+ }+ state.revision++;+ state.plan = null;+ state.recoveryPlan = null;+ state.error = null;+}++export function editOraclePackageOptions(state: OracleRoutineDeployment, objectId: string, options: Pick<OracleRoutinePlanDraft, "packageBodySource" | "packageContract" | "confirmPackagePair">): void {+ const draft = state.drafts.find((draft) => draft.objectId === objectId);+ if (state.disposed || state.executing || !draft || (draft.operation && oracleRoutineOperationVerified(draft.operation)) || (draft.identity.kind !== "PACKAGE" && draft.identity.kind !== "PACKAGE_BODY")) return;+ const next = { ...draft, ...options };+ if (next.packageBodySource === draft.packageBodySource && next.packageContract === draft.packageContract && next.confirmPackagePair === draft.confirmPackagePair) return;+ if (next.packageBodySource !== draft.packageBodySource) {+ draft.packageBodyDrafts = { ...draft.packageBodyDrafts, [draft.packageBodySource ?? "source"]: draft.sql };+ draft.sql = draft.packageBodyDrafts[next.packageBodySource ?? "source"];+ draft.reviewedTargetDraft = false;+ }+ if (next.packageBodySource !== draft.packageBodySource || next.packageContract !== draft.packageContract) {+ for (const peer of state.drafts) if (peer.identity.owner === draft.identity.owner && peer.identity.name === draft.identity.name) peer.confirmPackagePair = false;+ }+ Object.assign(draft, options);+ state.revision++;+ state.plan = null;+ state.recoveryPlan = null;+ state.error = null;+}++export function reviewOraclePackageTargetDraft(state: OracleRoutineDeployment, objectId: string): void {+ const draft = state.drafts.find((draft) => draft.objectId === objectId && draft.included);+ if (state.disposed || state.executing || !draft || !draft.sql?.trim() || draft.reviewedTargetDraft || (draft.operation && oracleRoutineOperationVerified(draft.operation)) || (draft.identity.kind !== "PACKAGE" && draft.identity.kind !== "PACKAGE_BODY")) return;+ draft.reviewedTargetDraft = true;state.revision++;state.plan = null;state.recoveryPlan = null;@@ -138,6 +214,10 @@ function errorText(error: unknown): string {export function selectOracleRoutineDraft(state: OracleRoutineDeployment, objectId: string): void {if (state.disposed) return;+ if (state.recoveryPlan && oracleRoutineDeploymentEntries(state).some((entry) => entry.objectId === objectId)) {+ if (!state.executing) state.selectedObjectId = objectId;+ return;+ }if (!state.drafts.some((draft) => draft.objectId === objectId && draft.included)) return;if (state.selectedObjectId !== objectId && state.recoveryPlan) {if (state.executing) return;@@ -161,6 +241,191 @@ function remember(state: OracleRoutineDeployment, operation: OracleRoutineOperatif (draft && (!draft.operation || draft.operation.operationId === operation.operationId)) draft.operation = operation;}+export function acceptOracleRoutineDeploymentOperation(state: OracleRoutineDeployment, operation: OracleRoutineOperation): boolean {+ if (state.disposed || !sameTarget(operation.target, state.target.endpoint)) return false;+ const previous = state.records.find((record) => record.operationId === operation.operationId) ?? state.drafts.find((draft) => draft.operation?.operationId === operation.operationId)?.operation;+ if (+ !previous ||+ routineIdentityKey(previous.identity) !== routineIdentityKey(operation.identity) ||+ (previous.dispatched && !operation.dispatched) ||+ (previous.lifecycle === "terminal" && operation.lifecycle !== "terminal") ||+ (previous.lifecycle === "unproven" && operation.lifecycle === "prepared")+ )+ return false;+ remember(state, operation);+ for (const plan of [state.plan, state.recoveryPlan]) {+ const step = plan?.steps.find((step) => step.operation?.operationId === operation.operationId);+ if (step) {+ step.operation = operation;+ if (operation.dispatched || operation.lifecycle !== "prepared") plan!.ready = false;+ }+ }+ if (operation.dispatched && !state.attemptedOperationIds.includes(operation.operationId)) state.attemptedOperationIds.push(operation.operationId);+ void invalidateTarget(operation);+ return true;+}++function sameTransferDraft(left: OracleRoutinePlanDraft, right: OracleRoutinePlanDraft): boolean {+ return (+ routineIdentityKey(left.identity) === routineIdentityKey(right.identity) &&+ left.action === "create" &&+ right.action === "create" &&+ !!left.sql &&+ left.sql === right.sql &&+ (left.sourceName ?? null) === (right.sourceName ?? null) &&+ (left.packageBodySource ?? null) === (right.packageBodySource ?? null) &&+ (left.packageContract ?? null) === (right.packageContract ?? null) &&+ !!left.confirmPackagePair === !!right.confirmPackagePair &&+ !left.baselineOperationId &&+ !left.supersedesOperationId &&+ !right.baselineOperationId &&+ !right.supersedesOperationId+ );+}++function matchesPendingTransferInput(state: OracleRoutineDeployment, frozen: api.OraclePackageTransferRequest, returned: OracleRoutinePlanInput): boolean {+ const input = frozen.input;+ const pending = frozen.pendingTables;+ if (!input || !pending?.tables.length || !pending.dependencyManifest || pending.tableEvidence.length !== pending.tables.length || frozen.operationIds?.length || state.pendingOperationId || state.attemptedOperationIds.length || state.drafts.some((draft) => draft.operation)) return false;+ if (![input.source.endpoint.databaseType, input.target.endpoint.databaseType].every((type) => type === "oracle" || type === "oceanbase-oracle")) return false;+ if (+ !sameTarget(input.source.endpoint, state.source.endpoint) ||+ !sameTarget(input.target.endpoint, state.target.endpoint) ||+ !sameTarget(pending.source, input.source.endpoint) ||+ !sameTarget(pending.target, input.target.endpoint) ||+ !sameTarget(returned.source.endpoint, input.source.endpoint) ||+ !sameTarget(returned.target.endpoint, input.target.endpoint)+ )+ return false;+ const selected = state.drafts.filter((draft) => draft.included);+ if (+ !selected.length ||+ selected.some((draft) => draft.identity.kind !== "PACKAGE" && draft.identity.kind !== "PACKAGE_BODY") ||+ input.drafts.length !== selected.length ||+ returned.drafts.length !== selected.length ||+ new Set(selected.map((draft) => routineIdentityKey(draft.identity))).size !== selected.length+ )+ return false;+ return !selected.some((draft) => {+ const expected = input.drafts.find((item) => routineIdentityKey(item.identity) === routineIdentityKey(draft.identity));+ const actual = returned.drafts.find((item) => routineIdentityKey(item.identity) === routineIdentityKey(draft.identity));+ return !expected || !actual || !sameTransferDraft(draft, expected) || !sameTransferDraft(expected, actual);+ });+}++export function oraclePackageTransferPendingReady(state: OracleRoutineDeployment, preview: api.OraclePackageTransferPreview): boolean {+ if (+ state.disposed ||+ state.executing ||+ state.validating ||+ state.error ||+ !state.plan ||+ state.plan.ready ||+ preview.plan.ready ||+ !sameTarget(preview.plan.target, state.target.endpoint) ||+ !matchesPendingTransferInput(state, { input: preview.input, pendingTables: preview.pendingTables }, preview.input)+ )+ return false;+ return (+ new Set(state.plan.steps.map((step) => routineIdentityKey(step.identity))).size === state.plan.steps.length &&+ state.plan.steps.length === preview.input.drafts.length &&+ preview.plan.steps.length === state.plan.steps.length &&+ state.plan.steps.every((step, index) => {+ const returned = preview.plan.steps[index];+ const draft = preview.input.drafts.find((draft) => routineIdentityKey(draft.identity) === routineIdentityKey(step.identity));+ return (+ !!draft &&+ !step.operation &&+ !returned.operation &&+ !step.issues.length &&+ !returned.issues.length &&+ step.action === "create" &&+ returned.action === "create" &&+ routineIdentityKey(step.identity) === routineIdentityKey(returned.identity) &&+ step.sql === returned.sql &&+ step.sql === draft.sql+ );+ })+ );+}++export function acceptOraclePackageTransferPreflight(state: OracleRoutineDeployment, frozen: api.OraclePackageTransferRequest, preview: api.OraclePackageTransferPreview): boolean {+ if (state.disposed || !state.executing || state.validating || !state.plan || state.plan.ready || preview.plan.ready || !sameTarget(preview.plan.target, state.target.endpoint) || !matchesPendingTransferInput(state, frozen, preview.input) || preview.plan.steps.length !== frozen.input!.drafts.length)+ return false;+ if (+ new Set(preview.plan.steps.map((step) => routineIdentityKey(step.identity))).size !== preview.plan.steps.length ||+ preview.plan.steps.some((step) => step.operation || step.action !== "create" || !frozen.input!.drafts.some((draft) => routineIdentityKey(draft.identity) === routineIdentityKey(step.identity) && draft.sql === step.sql))+ )+ return false;+ state.plan = preview.plan;+ return true;+}++export async function acceptOraclePackageTransferApproval(state: OracleRoutineDeployment, frozen: api.OraclePackageTransferRequest, approval: api.OraclePackageTransferPreview): Promise<boolean> {+ const input = frozen.input;+ const before = state.plan;+ if (+ !input ||+ state.disposed ||+ !state.executing ||+ state.validating ||+ state.error ||+ !before ||+ before.ready ||+ !sameTarget(approval.plan.target, input.target.endpoint) ||+ !matchesPendingTransferInput(state, frozen, approval.input) ||+ before.steps.length !== input.drafts.length ||+ approval.plan.steps.length !== input.drafts.length ||+ approval.pendingTables ||+ !approval.plan.ready+ )+ return false;+ if (new Set(approval.plan.steps.map((step) => routineIdentityKey(step.identity))).size !== approval.plan.steps.length) return false;+ const ids: string[] = [];+ for (const [index, step] of approval.plan.steps.entries()) {+ const expected = before.steps[index];+ const draft = input.drafts.find((draft) => routineIdentityKey(draft.identity) === routineIdentityKey(step.identity));+ const operation = step.operation;+ if (+ !draft ||+ !operation ||+ !sameTarget(operation.target, input.target.endpoint) ||+ operation.lifecycle !== "prepared" ||+ operation.dispatched ||+ operation.acknowledged ||+ operation.error ||+ operation.readback ||+ !operation.operationId ||+ ids.includes(operation.operationId) ||+ state.records.some((record) => record.operationId === operation.operationId) ||+ routineIdentityKey(operation.identity) !== routineIdentityKey(step.identity) ||+ routineIdentityKey(expected.identity) !== routineIdentityKey(step.identity) ||+ expected.action !== "create" ||+ step.action !== "create" ||+ draft.sql !== step.sql ||+ expected.sql !== step.sql ||+ (expected.sourceOriginal ?? null) !== (step.sourceOriginal ?? null) ||+ (expected.targetOriginal ?? null) !== (step.targetOriginal ?? null) ||+ expected.operation ||+ expected.issues.length ||+ step.issues.length+ )+ return false;+ ids.push(operation.operationId);+ }+ // Install IDs synchronously: the next stream event may already be a result.+ state.plan = approval.plan;+ for (const step of approval.plan.steps) remember(state, step.operation!);+ state.retainedOperationIds = [...new Set([...state.retainedOperationIds, ...ids])];+ try {+ await retainOracleRoutineOperations(ids);+ return !state.disposed;+ } catch (error) {+ if (!state.disposed) state.error = errorText(error);+ return false;+ }+}+async function invalidateTarget(operation: OracleRoutineOperation): Promise<void> {if (!operation.dispatched && operation.lifecycle !== "unproven" && operation.lifecycle !== "running") return;const target = operation.target;@@ -185,7 +450,7 @@ export async function observeOracleRoutineDeployment(state: OracleRoutineDeploym/** 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> {+export async function validateOracleRoutineDeployment(state: OracleRoutineDeployment, prepare: (input: OracleRoutinePlanInput) => Promise<OracleRoutinePlan> = api.prepareOracleRoutinePlan): Promise<void> {if (state.disposed || state.validating || state.executing) return;const previousPlan = state.plan;let replacementPrepared = false;@@ -208,13 +473,23 @@ export async function validateOracleRoutineDeployment(state: OracleRoutineDeploy}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 });+ drafts.push({+ identity: { ...draft.identity },+ action,+ sourceName: draft.sourceName,+ sql: state.source.endpoint.databaseType === state.target.endpoint.databaseType || draft.reviewedTargetDraft ? draft.sql : undefined,+ baselineOperationId: baseline?.operationId,+ supersedesOperationId: previous?.lifecycle === "prepared" ? previous.operationId : undefined,+ ...(draft.packageBodySource === undefined ? {} : { packageBodySource: draft.packageBodySource }),+ ...(draft.packageContract === undefined ? {} : { packageContract: draft.packageContract }),+ ...(draft.confirmPackagePair === undefined ? {} : { confirmPackagePair: draft.confirmPackagePair }),+ });}if (drafts.length === 0) {state.plan = null;return;}- const plan = await api.prepareOracleRoutinePlan({ source: state.source, target: state.target, drafts });+ const plan = await prepare({ source: state.source, target: state.target, drafts });const ids = planOperationIds(plan);replacementPrepared = plan.ready && ids.length > 0;try {@@ -240,6 +515,7 @@ export async function validateOracleRoutineDeployment(state: OracleRoutineDeployremember(state, step.operation);}}+ if (!oracleRoutineActiveStep(state) && plan.steps.length) state.selectedObjectId = oracleRoutineDeploymentEntries(state).find((entry) => routineIdentityKey(entry.identity) === routineIdentityKey(plan.steps[0].identity))!.objectId;} catch (error) {if (revision === state.revision) {state.plan = previousPlan;@@ -254,7 +530,7 @@ export async function validateOracleRoutineDeployment(state: OracleRoutineDeploy/** 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> {+export async function refreshOracleRoutineDeployment(state: OracleRoutineDeployment, fixedEndpoints?: { source: OracleRoutineSnapshot["endpoint"]; target: OracleRoutineSnapshot["endpoint"] }): Promise<void> {if (state.disposed || state.validating || state.executing) return;state.validating = true;state.error = null;@@ -270,18 +546,27 @@ export async function refreshOracleRoutineDeployment(state: OracleRoutineDeploym}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)]);+ const typed = state.drafts.some((draft) => draft.identity.kind === "PACKAGE" || draft.identity.kind === "PACKAGE_BODY");+ const objectKinds = [...new Set(state.drafts.map((draft) => draft.identity.kind))];+ const read = (snapshot: OracleRoutineSnapshot, names: string[], source: boolean) =>+ typed+ ? api.loadSchemaDiffRoutines(snapshot.endpoint.connectionId, snapshot.endpoint.database, snapshot.endpoint.schema, undefined, {+ objectKinds,+ selectedObjects: state.drafts.map((draft) => ({ name: source ? (draft.sourceName ?? draft.identity.name) : draft.identity.name, kind: draft.identity.kind })),+ })+ : api.loadSchemaDiffRoutines(snapshot.endpoint.connectionId, snapshot.endpoint.database, snapshot.endpoint.schema, names);+ const [source, target] = await Promise.all([read(state.source, sourceNames, true), read(state.target, targetNames, false)]);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");+ if (fixedEndpoints && (!sameTarget(source.endpoint, fixedEndpoints.source) || !sameTarget(target.endpoint, fixedEndpoints.target))) throw new Error("The original transfer connection generation changed; preserve its results and open a new comparison for the current connection");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";+ if (draft.action !== "delete") draft.action = target.objects.some((object) => object.version.identity.owner === draft.identity.owner && object.version.identity.name === draft.identity.name && object.version.identity.kind === draft.identity.kind) ? "replace" : "create";}} catch (error) {state.error = errorText(error);@@ -296,8 +581,18 @@ export function oracleRoutinePlanSql(state: OracleRoutineDeployment): string {}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));+ const entry = oracleRoutineDeploymentEntries(state).find((entry) => entry.objectId === state.selectedObjectId);+ return (state.recoveryPlan ?? state.plan)?.steps.find((step) => entry && routineIdentityKey(step.identity) === routineIdentityKey(entry.identity));+}++export function oracleRoutineDeploymentEntries(state: OracleRoutineDeployment): Pick<OracleRoutineDeployDraft, "objectId" | "identity" | "action" | "operation">[] {+ const plan = state.recoveryPlan ?? state.plan;+ if (!plan) return state.drafts.filter((draft) => draft.included);+ const entries = plan.steps.map((step) => {+ const draft = state.drafts.find((draft) => routineIdentityKey(draft.identity) === routineIdentityKey(step.identity));+ return { objectId: draft?.objectId ?? `recovery:${routineIdentityKey(step.identity)}`, identity: step.identity, action: step.action, operation: state.recoveryPlan ? (step.operation ?? undefined) : (draft?.operation ?? step.operation ?? undefined) };+ });+ return state.recoveryPlan ? entries : [...state.drafts.filter((draft) => draft.included && draft.operation && oracleRoutineOperationVerified(draft.operation) && !entries.some((entry) => entry.objectId === draft.objectId)), ...entries];}export async function prepareOracleRoutineRecovery(state: OracleRoutineDeployment, operationId: string): Promise<void> {diff --git a/apps/desktop/src/lib/schema/schemaDiff.ts b/apps/desktop/src/lib/schema/schemaDiff.tsindex 8080246d56..1b4615819f 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 { OracleRoutineCompareContext, SchemaDiffTableMapping } from "@/types/schemaDiff";+import type { OracleRoutineCompareContext, OracleRoutineKind, SchemaDiffTableMapping } from "@/types/schemaDiff";import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";import { splitSqlStatementRanges } from "@/lib/sql/sqlStatementRanges";@@ -173,6 +173,7 @@ export interface TriggerDiff {export interface FunctionDiff {type: "added" | "removed" | "modified" | "equal" | "unreadable" | "conflict";name: string;+ programKind?: OracleRoutineKind;source?: FunctionInfo;target?: FunctionInfo;changes?: string[];@@ -423,7 +424,7 @@ export interface SchemaDiffObject {/** Function arguments signature (for PostgreSQL overloaded functions) */arguments?: string;/** PROCEDURE vs FUNCTION when objectKind is function (for getObjectSource). */- routineType?: "PROCEDURE" | "FUNCTION";+ routineType?: OracleRoutineKind;routineComparisonState?: FunctionDiff["type"];renameMetadata?: {confirmed: boolean;@@ -657,6 +658,17 @@ function buildSequenceDdl(seq: SequenceInfo): string {return parts.join("\n");}+function functionDiffIdentity(diff: FunctionDiff): { id: string; kind: OracleRoutineKind } {+ const args = diff.source?.arguments || diff.target?.arguments || "";+ if (diff.programKind) {+ if (!["PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY"].includes(diff.programKind)) throw new Error("Unsupported explicit program kind");+ return { id: `program-${JSON.stringify([diff.programKind, diff.name, args])}`, kind: diff.programKind };+ }+ const functionType = (diff.source?.function_type || diff.target?.function_type || "").toUpperCase();+ if ([diff.source?.function_type, diff.target?.function_type].some((kind) => ["PACKAGE", "PACKAGE_BODY", "PACKAGE BODY"].includes((kind ?? "").toUpperCase()))) throw new Error("Package comparison requires an explicit program kind");+ return { id: `func-${diff.name}-${args}`, kind: functionType.includes("PROC") ? "PROCEDURE" : "FUNCTION" };+}+export function convertToSchemaDiffObjects(tableDiffs: TableDiff[], functionDiffs: FunctionDiff[] = [], sequenceDiffs: SequenceDiff[] = [], ruleDiffs: RuleDiff[] = [], ownerDiffs: OwnerDiff[] = [], renameCandidates?: RenameCandidate[]): SchemaDiffObject[] {const objects: SchemaDiffObject[] = [];@@ -759,15 +771,14 @@ export function convertToSchemaDiffObjects(tableDiffs: TableDiff[], functionDifffor (const diff of functionDiffs) {const args = diff.source?.arguments || diff.target?.arguments || "";- const functionType = (diff.source?.function_type || diff.target?.function_type || "").toUpperCase();- const routineType: "PROCEDURE" | "FUNCTION" = functionType.includes("PROC") ? "PROCEDURE" : "FUNCTION";+ const identity = functionDiffIdentity(diff);objects.push({- id: `func-${diff.name}-${args}`,+ id: identity.id,operationType: getOperationType(diff.type),objectKind: "function",name: diff.name,arguments: args,- routineType,+ routineType: identity.kind,routineComparisonState: diff.type,sourceName: diff.type === "added" ? undefined : diff.name,targetName: diff.type === "removed" ? undefined : diff.name,@@ -891,7 +902,7 @@ export function selectSchemaDiffInput(result: SchemaDiffPreparation, objects: Screturn {diffs,- functionDiffs: (result.functionDiffs ?? []).filter((diff) => selectedIds.has(`func-${diff.name}-${diff.source?.arguments || diff.target?.arguments || ""}`)),+ functionDiffs: (result.functionDiffs ?? []).filter((diff) => selectedIds.has(functionDiffIdentity(diff).id)),sequenceDiffs: (result.sequenceDiffs ?? []).filter((diff) => selectedIds.has(`seq-${diff.name}`)),ruleDiffs: (result.ruleDiffs ?? []).filter((diff) => selectedIds.has(`rule-${diff.name}`)),ownerDiffs: (result.ownerDiffs ?? []).filter((diff) => selectedIds.has(`owner-${diff.objectName}`)),diff --git a/apps/desktop/src/lib/schema/schemaDiffProgress.ts b/apps/desktop/src/lib/schema/schemaDiffProgress.tsindex b93c022d18..a262f1d95e 100644--- a/apps/desktop/src/lib/schema/schemaDiffProgress.ts+++ b/apps/desktop/src/lib/schema/schemaDiffProgress.ts@@ -17,13 +17,13 @@ export function shouldLoadSchemaDiffExtraObjects(dbType: string | null | undefin}/** True when session will load routines via listFunctions for a supported source/target pair. */-export function shouldLoadSchemaDiffRoutines(sourceDbType: string | null | undefined, targetDbType: string | null | undefined, options: Pick<SchemaDiffCompareOptions, "functions">): boolean {+export function shouldLoadSchemaDiffRoutines(sourceDbType: string | null | undefined, targetDbType: string | null | undefined, options: Pick<SchemaDiffCompareOptions, "functions"> & Partial<Pick<SchemaDiffCompareOptions, "routineObjectKinds">>): boolean {if (!options.functions) return false;- return schemaDiffRoutineObjectTypesIntersection(sourceDbType as DatabaseType | undefined, targetDbType as DatabaseType | undefined).length > 0;+ return schemaDiffRoutineObjectTypesIntersection(sourceDbType as DatabaseType | undefined, targetDbType as DatabaseType | undefined, options.routineObjectKinds).length > 0;}/** Unified extra-object progress phase used by session + dialog next-step hints. */-export function shouldLoadSchemaDiffExtraObjectPhase(sourceDbType: string | null | undefined, targetDbType: string | null | undefined, options: Pick<SchemaDiffCompareOptions, "functions" | "sequences" | "rules" | "owners">): boolean {+export function shouldLoadSchemaDiffExtraObjectPhase(sourceDbType: string | null | undefined, targetDbType: string | null | undefined, options: Pick<SchemaDiffCompareOptions, "functions" | "sequences" | "rules" | "owners"> & Partial<Pick<SchemaDiffCompareOptions, "routineObjectKinds">>): boolean {return shouldLoadSchemaDiffExtraObjects(targetDbType, options) || shouldLoadSchemaDiffRoutines(sourceDbType, targetDbType, options);}diff --git a/apps/desktop/src/lib/schema/schemaDiffRoutine.ts b/apps/desktop/src/lib/schema/schemaDiffRoutine.tsindex a1977ae7cd..3b50bff842 100644--- a/apps/desktop/src/lib/schema/schemaDiffRoutine.ts+++ b/apps/desktop/src/lib/schema/schemaDiffRoutine.ts@@ -69,7 +69,11 @@ export function schemaDiffRoutineKey(name: string, args = ""): string {return trimmedArgs ? `${name}(${trimmedArgs})` : name;}-export function schemaDiffRoutineKeyFromFunction(fn: Pick<FunctionInfo, "name" | "arguments">): string {+export function schemaDiffRoutineKeyFromFunction(fn: Pick<FunctionInfo, "name" | "arguments"> & Partial<Pick<FunctionInfo, "function_type">>, exactKind = false): string {+ if (exactKind || fn.function_type === "PACKAGE" || fn.function_type === "PACKAGE_BODY") {+ if (!["PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY"].includes(fn.function_type ?? "")) throw new Error("An exact program key requires its supported object kind");+ return JSON.stringify([fn.function_type, fn.name, fn.arguments.trim()]);+ }return schemaDiffRoutineKey(fn.name, fn.arguments);}@@ -167,24 +171,35 @@ export interface FilteredSchemaDiffFunctions {* When `selectedRoutines` is undefined, both sides keep all listed functions.* Non-identity (rename) mappings are ignored until backend rematch lands.*/-export function filterSchemaDiffFunctions(sourceFunctions: FunctionInfo[], targetFunctions: FunctionInfo[], selectedRoutines: string[] | undefined, routineMappings: SchemaDiffRoutineMapping[] = []): FilteredSchemaDiffFunctions {+export function filterSchemaDiffFunctions(sourceFunctions: FunctionInfo[], targetFunctions: FunctionInfo[], selectedRoutines: string[] | undefined, routineMappings: SchemaDiffRoutineMapping[] = [], exactKind = false): FilteredSchemaDiffFunctions {if (selectedRoutines === undefined) {return { sourceFunctions, targetFunctions };}const selectedSet = new Set(selectedRoutines);- const filteredSource = sourceFunctions.filter((fn) => selectedSet.has(schemaDiffRoutineKeyFromFunction(fn)));- const targetByKey = new Map(targetFunctions.map((fn) => [schemaDiffRoutineKeyFromFunction(fn), fn]));+ const typed = exactKind || [...sourceFunctions, ...targetFunctions].some((fn) => fn.function_type === "PACKAGE" || fn.function_type === "PACKAGE_BODY");+ const key = (fn: FunctionInfo) => schemaDiffRoutineKeyFromFunction(fn, typed);+ const filteredSource = sourceFunctions.filter((fn) => selectedSet.has(key(fn)));+ const targetByKey = new Map(targetFunctions.map((fn) => [key(fn), fn]));const targetKeys = [...targetByKey.keys()];- const mappings = reconcileSchemaDiffRoutineMappings(- filteredSource.map((fn) => schemaDiffRoutineKeyFromFunction(fn)),- targetKeys,- identitySchemaDiffRoutineMappings(routineMappings),- );+ const mappings = reconcileSchemaDiffRoutineMappings(filteredSource.map(key), targetKeys, identitySchemaDiffRoutineMappings(routineMappings));const selectedTargetKeys = new Set(mappings.map((mapping) => mapping.targetRoutine));+ if (typed) {+ for (const target of targetFunctions) {+ const targetPackage = target.function_type === "PACKAGE" || target.function_type === "PACKAGE_BODY";+ if (+ selectedSet.has(key(target)) ||+ filteredSource.some((source) => {+ const sourcePackage = source.function_type === "PACKAGE" || source.function_type === "PACKAGE_BODY";+ return source.name === target.name && source.arguments.trim() === target.arguments.trim() && source.function_type !== target.function_type && !(sourcePackage && targetPackage);+ })+ )+ selectedTargetKeys.add(key(target));+ }+ }return {sourceFunctions: filteredSource,- targetFunctions: targetFunctions.filter((fn) => selectedTargetKeys.has(schemaDiffRoutineKeyFromFunction(fn))),+ targetFunctions: targetFunctions.filter((fn) => selectedTargetKeys.has(key(fn))),};}diff --git a/apps/desktop/src/lib/table/objectSourceEditor.ts b/apps/desktop/src/lib/table/objectSourceEditor.tsindex 9e99fefcd6..f05ecc2df8 100644--- a/apps/desktop/src/lib/table/objectSourceEditor.ts+++ b/apps/desktop/src/lib/table/objectSourceEditor.ts@@ -114,7 +114,7 @@ export function objectSourceSaveExecutionMode(_databaseType: DatabaseType): Objeexport 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")) {+ if ((databaseType === "oracle" || databaseType === "oceanbase-oracle") && (identity.objectType === "PROCEDURE" || identity.objectType === "FUNCTION" || identity.objectType === "PACKAGE" || identity.objectType === "PACKAGE_BODY")) {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] });@@ -127,7 +127,12 @@ export async function prepareObjectSourceSave(connectionId: string, database: stexport 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");+ const companion = operation?.readback?.packageCompanion;+ const companionIssues =+ companion && companion.exists !== false && companion.state !== "present" && companion.state !== "verified"+ ? [`${companion.identity.kind.replaceAll("_", " ")}: ${companion.version?.status ?? companion.state}`, ...companion.issues.map((issue) => issue.message), ...companion.compilerMessages.map((message) => `${message.attribute} ${message.line}:${message.position} ${message.text}`)]+ : [];+ return [message, ...warnings.map((warning) => `WARNING ${warning.line}:${warning.position} ${warning.text}`), ...companionIssues].join("\n");}export async function executeObjectSourceSave(connectionId: string, database: string, databaseType: DatabaseType, statements: string[], schema?: string, timeoutSecs?: number): Promise<void> {diff --git a/apps/desktop/src/lib/table/oraclePackageSaveAs.ts b/apps/desktop/src/lib/table/oraclePackageSaveAs.tsindex 2dab548a85..935a580762 100644--- a/apps/desktop/src/lib/table/oraclePackageSaveAs.ts+++ b/apps/desktop/src/lib/table/oraclePackageSaveAs.ts@@ -5,6 +5,7 @@ import { invalidateObjectDdlCache } from "@/lib/metadata/objectDdlCache";import { invalidateObjectBrowserRowsCache } from "@/lib/table/objectBrowserRowsCache";import type { DatabaseType, QueryResult } from "@/types/database";import { oraclePackageCatalogSource, rewriteOraclePackageSource } from "@/lib/table/oraclePackageSource";+import { prepareOracleRoutineSourceSave, type PreparedOracleRoutineSave } from "@/lib/table/oracleRoutineWrite";export interface OraclePackageSaveAsTarget {connectionId: string;@@ -251,13 +252,33 @@ async function verifyCreatedPackage(target: OraclePackageSaveAsTarget, expected:return snapshot;}+export async function prepareOraclePackageSaveAsExecution(plan: OraclePackageSaveAsPlan, isCurrent: () => boolean = () => true) {+ if (!isCurrent()) throw new Error("The package Save As target changed. Refresh the preview.");+ if (!plan.executable || !plan.snapshot) throw new Error("Resolve the package Save As preview issues before execution.");+ const specification = await prepareOracleRoutineSourceSave({ connectionId: plan.target.connectionId, database: plan.target.database, identity: { owner: plan.target.schema, name: plan.canonicalNewName, kind: "PACKAGE" }, sql: plan.specSource, requireAbsent: true }, { retainTerminalResult: true });+ return Object.assign(() => executePreparedOraclePackageSaveAs(plan, isCurrent, specification), {+ dispose: async () => {+ await specification.dispose?.();+ },+ });+}+export async function executeOraclePackageSaveAs(plan: OraclePackageSaveAsPlan, isCurrent: () => boolean = () => true): Promise<void> {+ const execute = await prepareOraclePackageSaveAsExecution(plan, isCurrent);+ try {+ await execute();+ } finally {+ await execute.dispose();+ }+}++async function executePreparedOraclePackageSaveAs(plan: OraclePackageSaveAsPlan, isCurrent: () => boolean, specification: PreparedOracleRoutineSave): Promise<void> {if (!isCurrent()) throw new Error("The package Save As target changed. Refresh the preview.");if (!plan.executable || !plan.snapshot) throw new Error("Resolve the package Save As preview issues before execution.");const current = await prepareOraclePackageSaveAs(plan.target, packageDrafts(plan));if (!current.executable || planIdentity(current) !== planIdentity(plan)) throw new Error("The package or its members changed. Refresh the Save As preview.");- const lock = freezeSourceIdentities(["PACKAGE", "PACKAGE_BODY"].map((objectType) => ({ connectionId: plan.target.connectionId, database: plan.target.database, schema: plan.target.schema, objectType, name: plan.target.oldName })));+ const lock = freezeSourceIdentities([plan.target.oldName, plan.canonicalNewName].flatMap((name) => ["PACKAGE", "PACKAGE_BODY"].map((objectType) => ({ connectionId: plan.target.connectionId, database: plan.target.database, schema: plan.target.schema, objectType, name }))));const completed: string[] = [];let dispatched = false;let active = `PACKAGE ${plan.canonicalNewName}`;@@ -271,7 +292,7 @@ export async function executeOraclePackageSaveAs(plan: OraclePackageSaveAsPlan,if (!isCurrent()) throw new Error("The Save As dialog changed before package creation.");active = `PACKAGE ${plan.canonicalNewName}`;dispatched = true;- await query(plan.target, plan.specSource);+ const specificationResult = await specification();const specState = (await objectStates(plan.target, plan.canonicalNewName, ["PACKAGE"])).filter((row) => row[0] === plan.canonicalNewName && row[1] === "PACKAGE");const specSource = await readSource(plan.target, plan.canonicalNewName, "PACKAGE");if (specState.length !== 1 || oraclePackageCatalogSource(specSource) !== oraclePackageCatalogSource(plan.specSource)) throw new Error(`Created package ${plan.canonicalNewName} specification did not match the preview.`);@@ -286,7 +307,19 @@ export async function executeOraclePackageSaveAs(plan: OraclePackageSaveAsPlan,if (!isCurrent()) throw new Error("The Save As dialog changed before package body creation.");if (currentSpec.length !== 1 || String(currentSpec[0]![2]) !== createdSpecId || oraclePackageCatalogSource(currentSource) !== oraclePackageCatalogSource(plan.specSource)) throw new Error("The new package specification identity or definition changed before body creation.");active = `PACKAGE BODY ${plan.canonicalNewName}`;- await query(plan.target, plan.bodySource);+ const body = await prepareOracleRoutineSourceSave({+ connectionId: plan.target.connectionId,+ database: plan.target.database,+ identity: { owner: plan.target.schema, name: plan.canonicalNewName, kind: "PACKAGE_BODY" },+ sql: plan.bodySource,+ requireAbsent: true,+ prerequisiteOperationId: specificationResult.operationId,+ });+ try {+ await body();+ } finally {+ await body.dispose?.();+ }const bodyState = (await objectStates(plan.target, plan.canonicalNewName, ["PACKAGE BODY"])).filter((row) => row[0] === plan.canonicalNewName && row[1] === "PACKAGE BODY");const bodySource = await readSource(plan.target, plan.canonicalNewName, "PACKAGE BODY");if (bodyState.length !== 1 || oraclePackageCatalogSource(bodySource) !== oraclePackageCatalogSource(plan.bodySource)) throw new Error(`Created package body ${plan.canonicalNewName} did not match the preview.`);diff --git a/apps/desktop/src/lib/table/oracleRoutineWrite.ts b/apps/desktop/src/lib/table/oracleRoutineWrite.tsindex 580844d1e1..b99f365623 100644--- a/apps/desktop/src/lib/table/oracleRoutineWrite.ts+++ b/apps/desktop/src/lib/table/oracleRoutineWrite.ts@@ -28,12 +28,16 @@ export function requireVerifiedOracleRoutine(operation: OracleRoutineOperation):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 companion = operation.readback?.packageCompanion;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}`) ?? []),+ ...(companion+ ? [`${companion.identity.kind.replaceAll("_", " ")}: ${companion.version?.status ?? companion.state}`, ...companion.issues.map((issue) => issue.message), ...companion.compilerMessages.map((message) => `${message.attribute} ${message.line}:${message.position} ${message.text}`)]+ : []),].filter(Boolean).join("\n");@@ -42,7 +46,7 @@ export function requireVerifiedOracleRoutine(operation: OracleRoutineOperation):/** 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> {+export async function prepareOracleRoutineSourceSave(input: OracleRoutineSaveInput, { retainTerminalResult = false }: { retainTerminalResult?: boolean } = {}): 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);@@ -98,6 +102,7 @@ export async function prepareOracleRoutineSourceSave(input: OracleRoutineSaveInp}let transferred = false;let disposed = false;+ let retainedTerminal = 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.@@ -122,7 +127,8 @@ export async function prepareOracleRoutineSourceSave(input: OracleRoutineSaveInpif (pendingSaves.get(key)?.operation.operationId === approval.operationId) {if (operation.lifecycle === "terminal") {pendingSaves.delete(key);- await releaseOracleRoutineOperations([approval.operationId]);+ if (retainTerminalResult) retainedTerminal = true;+ else await releaseOracleRoutineOperations([approval.operationId]);} else pendingSaves.set(key, { input, operation });}requireVerifiedOracleRoutine(operation);@@ -130,7 +136,7 @@ export async function prepareOracleRoutineSourceSave(input: OracleRoutineSaveInp};return Object.assign(execute, {dispose: async () => {- if (transferred || disposed) return;+ if ((transferred && !retainedTerminal) || disposed) return;disposed = true;await releaseOracleRoutineOperations([approval.operationId]);},diff --git a/apps/desktop/src/stores/__tests__/transferTaskStore.spec.ts b/apps/desktop/src/stores/__tests__/transferTaskStore.spec.tsindex 8871a226ab..2ccda0c683 100644--- a/apps/desktop/src/stores/__tests__/transferTaskStore.spec.ts+++ b/apps/desktop/src/stores/__tests__/transferTaskStore.spec.ts@@ -82,6 +82,44 @@ describe("transferTaskStore", () => {expect(store.getTask("legacy-selection")?.config.objects).toEqual({});});+ it.each([+ ["source", "source"],+ ["target", "target"],+ [undefined, undefined],+ ["invalid", undefined],+ ] as const)("round-trips package body choice %s without retaining approvals or operation records", async (bodySource, expectedSource) => {+ const sql = 'CREATE PACKAGE BODY "T"."Pkg.With.Dot" AS -- 中文😀\nEND;';+ const config = makeConfig({+ objects: { PACKAGE_BODY: ["Pkg.With.Dot"] },+ oraclePackageDrafts: [+ {+ identity: { owner: "T", name: "Pkg.With.Dot", kind: "PACKAGE_BODY" },+ sql,+ packageBodySource: bodySource,+ packageContract: "target",+ reviewedTargetDraft: true,+ operation: { operationId: "old-operation" },+ baselineOperationId: "old-operation",+ supersedesOperationId: "old-preparation",+ } as never,+ ],+ });+ const store = useTransferTaskStore();+ const saved = await store.saveTask({ name: "package-body-draft", config });+ expect(saved.config.oraclePackageDrafts?.[0].packageBodySource).toBe(expectedSource);+ const persisted = vi.mocked(api.saveTransferTaskLibrary).mock.calls.at(-1)![0];+ expect(JSON.stringify(persisted)).not.toContain("old-operation");+ expect(JSON.stringify(persisted)).not.toContain("old-preparation");+ vi.mocked(api.loadTransferTaskLibrary).mockResolvedValue(persisted);+ setActivePinia(createPinia());+ const reloaded = useTransferTaskStore();+ await reloaded.initFromStorage();+ expect(reloaded.getTask(saved.id)?.config.objects).toEqual({ PACKAGE_BODY: ["Pkg.With.Dot"] });+ expect(reloaded.getTask(saved.id)?.config.oraclePackageDrafts).toEqual([expect.objectContaining({ identity: { owner: "T", name: "Pkg.With.Dot", kind: "PACKAGE_BODY" }, sql, packageContract: "target", reviewedTargetDraft: true })]);+ expect(reloaded.getTask(saved.id)?.config.oraclePackageDrafts?.[0].packageBodySource).toBe(expectedSource);+ expect(reloaded.getTask(saved.id)?.config.dropTargetConfirmed).toBe(false);+ });+it("round-trips TABLE-only and TABLE + VIEW task selections", async () => {const store = useTransferTaskStore();const tableOnly = await store.saveTask({ name: "table-only", config: makeConfig({ objects: { TABLE: ["orders"] } }) });diff --git a/apps/desktop/src/stores/transferTaskStore.ts b/apps/desktop/src/stores/transferTaskStore.tsindex 58cbcb2ba0..161a4a235c 100644--- a/apps/desktop/src/stores/transferTaskStore.ts+++ b/apps/desktop/src/stores/transferTaskStore.ts@@ -2,7 +2,7 @@ import { computed, ref } from "vue";import { defineStore } from "pinia";import { uuid } from "@/lib/common/utils";import * as api from "@/lib/backend/api";-import type { TransferTask, TransferTaskConfig, TransferTaskFolder, TransferTaskLibrary } from "@/types/database";+import type { TransferPackageDraft, TransferTask, TransferTaskConfig, TransferTaskFolder, TransferTaskLibrary } from "@/types/database";import { resolveTransferStrategy, transferStrategyOptions } from "@/components/transfer/transferStrategy";import { MAX_QUERY_TIMEOUT_SECS } from "@/lib/connection/timeoutLimits";@@ -76,6 +76,25 @@ function normalizeTransferOperationTimeoutSecs(raw: unknown): number | undefinedreturn raw;}+function normalizePackageDrafts(raw: unknown): TransferPackageDraft[] | undefined {+ if (!Array.isArray(raw)) return undefined;+ const drafts: TransferPackageDraft[] = [];+ for (const value of raw) {+ const identity = value?.identity;+ if (!identity || typeof identity.owner !== "string" || typeof identity.name !== "string" || (identity.kind !== "PACKAGE" && identity.kind !== "PACKAGE_BODY")) continue;+ drafts.push({+ identity: { owner: identity.owner, name: identity.name, kind: identity.kind },+ sourceName: typeof value.sourceName === "string" ? value.sourceName : undefined,+ sql: typeof value.sql === "string" ? value.sql : undefined,+ packageBodySource: value.packageBodySource === "source" || value.packageBodySource === "target" ? value.packageBodySource : undefined,+ packageContract: value.packageContract === "source" || value.packageContract === "target" ? value.packageContract : undefined,+ confirmPackagePair: value.confirmPackagePair === true,+ reviewedTargetDraft: value.reviewedTargetDraft === true,+ });+ }+ return drafts.length ? drafts : undefined;+}+function normalizeTask(raw: unknown): TransferTask | null {if (!raw || typeof raw !== "object") return null;const candidate = raw as Partial<TransferTask>;@@ -103,6 +122,7 @@ function normalizeTask(raw: unknown): TransferTask | null {targetDatabase: String(config.targetDatabase),targetSchema: config.targetSchema || undefined,objects,+ oraclePackageDrafts: normalizePackageDrafts(config.oraclePackageDrafts),content: config.content ?? "structureAndData",...transferStrategyOptions(resolveTransferStrategy(config)),targetTableNameCase: config.targetTableNameCase ?? "preserve",@@ -306,6 +326,7 @@ export const useTransferTaskStore = defineStore("transferTasks", () => {...input.config,...transferStrategyOptions(resolveTransferStrategy(input.config)),operationTimeoutSecs: normalizeTransferOperationTimeoutSecs(input.config.operationTimeoutSecs),+ oraclePackageDrafts: normalizePackageDrafts(input.config.oraclePackageDrafts),dropTargetConfirmed: false,};const task: TransferTask = existingdiff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex c9dfc6bc22..b5fcbdb5f3 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -5,6 +5,7 @@ import type { MultiDbExecutionTarget, MultiDbResultRunExecution } from "@/types/import type { DatabaseType } from "@/types/generated/databaseTypes";import type { PluginAiRecommendation } from "@/types/pluginAiRecommendations";import type { GraphResult } from "@/lib/graph/graphResult";+import type { OracleRoutinePlanDraft } from "@/types/schemaDiff";export type { DatabaseType } from "@/types/generated/databaseTypes";@@ -2973,6 +2974,8 @@ export interface SavedSqlLibrary {}/** Serializable configuration of a saved data-transfer task. */+export type TransferPackageDraft = Pick<OracleRoutinePlanDraft, "identity" | "sourceName" | "sql" | "packageBodySource" | "packageContract" | "confirmPackagePair"> & { reviewedTargetDraft?: boolean };+export interface TransferTaskConfig {sourceConnectionId: string;/** Undefined means the connection's built-in/default catalog. */@@ -2985,6 +2988,7 @@ export interface TransferTaskConfig {targetSchema?: string;/** Selected object names grouped by object kind (TABLE, VIEW, ...). */objects: Partial<Record<TransferObjectKind, string[]>>;+ oraclePackageDrafts?: TransferPackageDraft[];content: TransferContent;mode: TransferMode;targetTableNameCase: TransferTableNameCase;diff --git a/apps/desktop/src/types/schemaDiff.ts b/apps/desktop/src/types/schemaDiff.tsindex 9e62afe008..0de95f1d83 100644--- a/apps/desktop/src/types/schemaDiff.ts+++ b/apps/desktop/src/types/schemaDiff.ts@@ -8,10 +8,17 @@ export interface OracleRoutineEndpoint {generation: number;}+export type OracleRoutineKind = "PROCEDURE" | "FUNCTION" | "PACKAGE" | "PACKAGE_BODY";+export interface OracleRoutineIdentity {owner: string;name: string;- kind: "PROCEDURE" | "FUNCTION";+ kind: OracleRoutineKind;+}++export interface OracleRoutineReadOptions {+ objectKinds?: OracleRoutineKind[];+ selectedObjects?: Pick<OracleRoutineIdentity, "name" | "kind">[];}export interface OracleRoutineVersion {@@ -38,6 +45,7 @@ export interface OracleRoutineDependency {export interface OracleRoutineObjectSnapshot {version: OracleRoutineVersion;source: string | null;+ sourceOrigin?: "oracle-dictionary" | "oceanbase-dictionary" | "oracle-metadata";sourceComplete: boolean;dependencies: OracleRoutineDependency[];dependenciesComplete: boolean;@@ -61,6 +69,9 @@ export interface OracleRoutineCompareContext {targetEnumerationComplete: boolean;sourceIncompleteNames: string[];targetIncompleteNames: string[];+ objectKinds?: OracleRoutineKind[];+ sourceIncompleteObjects?: Pick<OracleRoutineIdentity, "name" | "kind">[];+ targetIncompleteObjects?: Pick<OracleRoutineIdentity, "name" | "kind">[];}export interface OracleRoutineReadback {@@ -70,6 +81,8 @@ export interface OracleRoutineReadback {version: OracleRoutineVersion | null;source: string | null;definitionMatches: boolean | null;+ sourceOrigin?: "oracle-dictionary" | "oceanbase-dictionary" | "oracle-metadata";+ packageCompanion?: OracleRoutineReadback;compilerMessages: { attribute: string; line: number; position: number; text: string }[];issues: OracleRoutineReadIssue[];}@@ -96,6 +109,8 @@ export interface OracleRoutineSaveInput {database: string;identity: OracleRoutineIdentity;sql: string;+ requireAbsent?: boolean;+ prerequisiteOperationId?: string;supersedesOperationId?: string;}@@ -108,6 +123,9 @@ export interface OracleRoutinePlanDraft {sql?: string;baselineOperationId?: string;supersedesOperationId?: string;+ packageBodySource?: "source" | "target";+ packageContract?: "source" | "target";+ confirmPackagePair?: boolean;}export interface OracleRoutinePlanInput {@@ -128,6 +146,17 @@ export interface OracleRoutinePlanStep {incomingCallers: OracleRoutineDependency[];issues: { code: string; message: string; line: number; column: number }[];operation: OracleRoutineOperation | null;+ packageImpact?: OraclePackagePlanImpact;+}++export interface OraclePackagePlanImpact {+ companion: OracleRoutineIdentity;+ companionAction: OracleRoutinePlanAction | null;+ implicitCompanionDelete: boolean;+ retainsTargetBody: boolean;+ bodyPending: boolean;+ mayInitialize: boolean;+ grants: { grants: { grantor: string; grantee: string; privilege: string; grantable: boolean }[]; complete: boolean; issue: string | null } | null;}export interface OracleRoutinePlan {@@ -186,6 +215,8 @@ export interface SchemaDiffCompareOptions {* `[]` means restriction enabled with nothing selected.*/selectedRoutines: string[] | undefined;+ routineObjectKinds?: OracleRoutineKind[];+ selectedRoutineObjects?: Pick<OracleRoutineIdentity, "name" | "kind">[];routineMappings?: SchemaDiffRoutineMapping[];detectRenames: boolean;renameThreshold: number;@@ -325,6 +356,8 @@ export function normalizeSchemaDiffCompareOptions(options: Partial<SchemaDiffComtableMappings: Array.isArray(options?.tableMappings) ? options.tableMappings.map((mapping) => ({ ...mapping })) : defaults.tableMappings,routineMappings: Array.isArray(options?.routineMappings) ? options.routineMappings.map((mapping) => ({ ...mapping })) : defaults.routineMappings,selectedRoutines: options?.selectedRoutines === undefined ? defaults.selectedRoutines : options.selectedRoutines ? [...options.selectedRoutines] : options.selectedRoutines,+ ...(options?.routineObjectKinds === undefined ? {} : { routineObjectKinds: [...options.routineObjectKinds] }),+ ...(options?.selectedRoutineObjects === undefined ? {} : { selectedRoutineObjects: options.selectedRoutineObjects.map((object) => ({ ...object })) }),};// Table compare owns views; turning tables off must not leave views loading metadata alone.if (!normalized.tables) normalized.views = false;diff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rsindex c43e27b6a1..277485d850 100644--- a/crates/dbx-core/src/data/transfer.rs+++ b/crates/dbx-core/src/data/transfer.rs@@ -24,6 +24,7 @@ mod iris_tests;mod db2;mod ddl_plan;+pub(crate) mod oracle_table_contract;mod overwrite_clear;mod structure_plan;pub(crate) mod xugu_objects;@@ -266,10 +267,11 @@ pub enum TransferObjectKind {MaterializedView,Procedure,Function,+ Package,+ PackageBody,Trigger,Sequence,Event,- Package,Synonym,}@@ -312,10 +314,14 @@ pub fn transfer_object_kinds(db_type: &DatabaseType) -> Vec<TransferObjectKind>if *db_type == DatabaseType::Xugu {return xugu_objects::supported_kinds();}- match transfer_object_family(db_type) {+ let mut kinds = match transfer_object_family(db_type) {Some(family) => transfer_object_kinds_for_family(&family),None => Vec::new(),+ };+ if matches!(db_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle) {+ kinds.extend([TransferObjectKind::Package, TransferObjectKind::PackageBody]);}+ kinds}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -365,6 +371,8 @@ pub struct TransferRequest {/// Production database confirmation for drop_target_before_create.#[serde(default)]pub drop_target_confirmed: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub oracle_packages: Option<crate::schema::oracle_routines::OraclePackageTransferRequest>,}fn default_quote_target_column_names() -> bool {@@ -383,6 +391,8 @@ pub struct TransferOwnershipPreview {/// re-reads source and target metadata before executing.#[serde(skip_serializing_if = "Option::is_none")]pub structure: Option<TransferStructurePreview>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub oracle_packages: Option<crate::schema::oracle_routines::OraclePackageTransferPreview>,}/// SQL plan preview for a `drop_target_before_create` (rebuild) transfer.@@ -493,6 +503,8 @@ impl TransferStructureOperation {#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct TransferStructurePreviewTable {+ #[serde(skip)]+ pub(crate) oracle_plan: Option<ddl_plan::PreparedTableDdl>,pub source_table: String,pub target_table: String,/// The target table already exists and this transfer plans no structure DDL for it,@@ -532,6 +544,15 @@ impl<'a> TransferObjectSelectionMode<'a> {}impl TransferRequest {+ pub(crate) fn has_package_selection(&self) -> bool {+ self.objects.as_ref().is_some_and(|objects| {+ objects.iter().any(|selection| {+ matches!(selection.object_type, TransferObjectKind::Package | TransferObjectKind::PackageBody)+ && !selection.names.is_empty()+ })+ })+ }+fn object_selection_mode(&self) -> TransferObjectSelectionMode<'_> {match self.objects.as_deref() {Some(selections) => TransferObjectSelectionMode::Explicit(selections),@@ -576,6 +597,12 @@ pub struct TransferTableResult {#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]pub struct TransferProgress {+ #[serde(skip_serializing_if = "Option::is_none")]+ pub oracle_package_approval: Option<crate::schema::oracle_routines::OraclePackageTransferPreview>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub oracle_package_preflight: Option<crate::schema::oracle_routines::OraclePackageTransferPreview>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub oracle_routine_operation: Option<crate::schema::oracle_routines::RoutineOperationRecord>,pub transfer_id: String,pub table: String,pub table_index: usize,@@ -1121,6 +1148,15 @@ pub fn validate_transfer_database_pair(source_db_type: &DatabaseType,target_db_type: &DatabaseType,) -> Result<(), String> {+ if request.has_package_selection()+ && !(matches!((source_db_type, target_db_type), (DatabaseType::Xugu, DatabaseType::Xugu))+ && request.oracle_packages.is_none())+ && ![source_db_type, target_db_type]+ .into_iter()+ .all(|product| matches!(product, DatabaseType::Oracle | DatabaseType::OceanbaseOracle))+ {+ return Err("Package transfer requires actual Oracle or OceanBase Oracle endpoints; the Oracle family alone does not establish package support".into());+ }if transfer_support_level(source_db_type).is_none() {return Err(format!("{} 暂未声明数据传输兼容级别", source_db_type.as_str()));}@@ -1382,6 +1418,11 @@ pub fn target_object_exists_sql(name: &str,kind: &TransferObjectKind,) -> Result<String, String> {+ if matches!(kind, TransferObjectKind::Package | TransferObjectKind::PackageBody)+ && !matches!(db_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle)+ {+ return Err("Package existence requires actual Oracle or OceanBase Oracle".into());+ }let schema = quote_string_literal(schema);let name = quote_string_literal(name);let q = |literal: &str| literal.to_string();@@ -1434,6 +1475,8 @@ pub fn target_object_exists_sql(| TransferObjectKind::MaterializedView| TransferObjectKind::Procedure| TransferObjectKind::Function+ | TransferObjectKind::Package+ | TransferObjectKind::PackageBody| TransferObjectKind::Trigger| TransferObjectKind::Sequence,) => format!(@@ -1443,6 +1486,8 @@ pub fn target_object_exists_sql(TransferObjectKind::MaterializedView => "'MATERIALIZED VIEW'",TransferObjectKind::Procedure => "'PROCEDURE'",TransferObjectKind::Function => "'FUNCTION'",+ TransferObjectKind::Package => "'PACKAGE'",+ TransferObjectKind::PackageBody => "'PACKAGE BODY'",TransferObjectKind::Trigger => "'TRIGGER'",_ => "'SEQUENCE'",})@@ -9545,12 +9590,13 @@ pub fn ordered_transfer_object_kinds(kinds: Vec<TransferObjectKind>) -> Vec<TranTransferObjectKind::Sequence => 1,TransferObjectKind::View => 2,TransferObjectKind::MaterializedView => 2,- TransferObjectKind::Function => 3,- TransferObjectKind::Procedure => 4,- TransferObjectKind::Trigger => 5,- TransferObjectKind::Event => 6,TransferObjectKind::Package => 3,TransferObjectKind::Synonym => 4,+ TransferObjectKind::Function => 3,+ TransferObjectKind::Procedure => 4,+ TransferObjectKind::PackageBody => 5,+ TransferObjectKind::Trigger => 6,+ TransferObjectKind::Event => 7,};let mut kinds = kinds;kinds.sort_by_key(rank);@@ -9590,6 +9636,9 @@ pub fn object_kind_selected_or_defaulted(selections: Option<&[TransferObjectSelection]>,kind: &TransferObjectKind,) -> bool {+ if selections.is_none() && matches!(kind, TransferObjectKind::Package | TransferObjectKind::PackageBody) {+ return false;+ }selections.is_none_or(|selections| !selected_object_names(selections, kind).is_empty())}@@ -9686,11 +9735,25 @@ pub async fn transfer_schema_objects<F>(request: &TransferRequest,source_pool_key: &str,target_pool_key: &str,- progress_callback: F,+ mut progress_callback: F,) -> Result<TransferObjectOutcome, String>whereF: FnMut(TransferProgress),{+ if request.has_package_selection() {+ let source_db_type = get_db_type(state, &request.source_connection_id).await?;+ let target_db_type = get_db_type(state, &request.target_connection_id).await?;+ validate_transfer_database_pair(request, &source_db_type, &target_db_type)?;+ }+ let packages = match crate::schema::oracle_routines::claim_transfer_packages(state, request, None).await {+ Ok(packages) => packages,+ Err(error) => {+ let progress = error.into_progress(request);+ let message = progress.error.clone().unwrap();+ progress_callback(progress);+ return Err(message);+ }+ };if matches!(request.content, TransferContent::DataOnly) {return Ok(TransferObjectOutcome::default());}@@ -9700,15 +9763,29 @@ where&request.target_connection_id,).await?;- transfer_schema_objects_with_routine_context(+ let mut outcome = transfer_schema_objects_with_routine_context(state,request,source_pool_key,target_pool_key,routine_context.as_ref(),- progress_callback,+ &mut progress_callback,)- .await+ .await?;+ if let Some(packages) = packages {+ let (package_outcome, cancelled, preflight_error) =+ packages.run(state, request, outcome.failed.is_empty(), progress_callback).await;+ outcome.transferred.extend(package_outcome.transferred);+ outcome.skipped.extend(package_outcome.skipped);+ outcome.failed.extend(package_outcome.failed);+ if cancelled {+ return Err("Cancelled".into());+ }+ if let Some(error) = preflight_error {+ return Err(error);+ }+ }+ Ok(outcome)}pub(crate) async fn transfer_schema_objects_with_routine_context<F>(@@ -9722,11 +9799,17 @@ pub(crate) async fn transfer_schema_objects_with_routine_context<F>(whereF: FnMut(TransferProgress),{- if matches!(request.content, TransferContent::DataOnly) {+ if matches!(request.content, TransferContent::DataOnly) && !request.has_package_selection() {return Ok(TransferObjectOutcome::default());}let source_db_type = get_db_type(state, &request.source_connection_id).await?;let target_db_type = get_db_type(state, &request.target_connection_id).await?;+ if request.has_package_selection() {+ validate_transfer_database_pair(request, &source_db_type, &target_db_type)?;+ }+ if matches!(request.content, TransferContent::DataOnly) {+ return Ok(TransferObjectOutcome::default());+ }if !should_transfer_schema_objects(&source_db_type, &target_db_type, request) {return Ok(TransferObjectOutcome::default());}@@ -9821,6 +9904,9 @@ wherelet table = format!("schema object: {name}");let mut progress = |outcome: &mut TransferObjectOutcome, status: TransferStatus, error: Option<String>| {progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: table.clone(),table_index: request.tables.len(),@@ -10066,6 +10152,9 @@ wherelet table = format!("schema object: {name}");let mut progress = |outcome: &mut TransferObjectOutcome, status: TransferStatus, error: Option<String>| {progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: table.clone(),table_index: request.tables.len(),@@ -10212,6 +10301,9 @@ wherelet table = format!("schema object: {name}");let mut progress = |outcome: &mut TransferObjectOutcome, status: TransferStatus, error: Option<String>| {progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: table.clone(),table_index: request.tables.len(),@@ -10306,6 +10398,9 @@ wherelet table = format!("schema object: {name}");let mut progress = |outcome: &mut TransferObjectOutcome, status: TransferStatus, error: Option<String>| {progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: table.clone(),table_index: request.tables.len(),@@ -11112,6 +11207,25 @@ async fn build_rebuild_preview(Ok(TransferRebuildPreview { sql: phases.join("\n\n"), tables, backup_sql, cleanup_sql })}+pub(crate) async fn build_package_transfer_structure(+ state: &Arc<AppState>,+ request: &TransferRequest,+ source_db_type: &DatabaseType,+ target_db_type: &DatabaseType,+ source_pool_key: &str,+ target_pool_key: &str,+) -> Result<TransferStructurePreview, String> {+ structure_plan::build_structure_preview(+ state,+ request,+ source_db_type,+ target_db_type,+ source_pool_key,+ target_pool_key,+ )+ .await+}+pub async fn preview_transfer_ownership(state: &Arc<AppState>,request: &TransferRequest,@@ -11120,6 +11234,9 @@ pub async fn preview_transfer_ownership(source_pool_key: &str,target_pool_key: &str,) -> Result<TransferOwnershipPreview, String> {+ if request.has_package_selection() {+ validate_transfer_request(request)?;+ }validate_transfer_database_pair(request, source_db_type, target_db_type)?;// PostgreSQL-compatible transfers report role ownership gaps for the confirmation flow.let (missing_owners, target_owner) =@@ -11151,7 +11268,10 @@ pub async fn preview_transfer_ownership(// Structure-only transfers expose the statements their create pass will run. The other// content modes keep their existing previews: data-only runs no DDL, and// structure-and-data is deliberately unchanged here.- let structure = if matches!(request.content, TransferContent::StructureOnly) {+ let mut structure = if matches!(request.content, TransferContent::StructureOnly)+ || (request.has_package_selection()+ && matches!(source_db_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle))+ {Some(structure_plan::build_structure_preview(state,@@ -11167,7 +11287,30 @@ pub async fn preview_transfer_ownership(None};- Ok(TransferOwnershipPreview { missing_owners, target_owner, rebuild, structure })+ let oracle_packages =+ crate::schema::oracle_routines::prepare_transfer_packages(state, request, structure.as_mut()).await?;+ if let (Some(packages), Some(structure)) = (&oracle_packages, &mut structure) {+ let sql = packages+ .plan+ .steps+ .iter()+ .filter(|step| !step.sql.trim().is_empty())+ .map(|step| step.sql.as_str())+ .collect::<Vec<_>>()+ .join("\n/\n");+ if !sql.is_empty() {+ structure.sql.push_str("\n\n");+ structure.sql.push_str(&sql);+ }+ structure.schema_objects_expanded = request.objects.iter().flatten().all(|selection| {+ selection.names.is_empty()+ || matches!(+ selection.object_type,+ TransferObjectKind::Table | TransferObjectKind::Package | TransferObjectKind::PackageBody+ )+ });+ }+ Ok(TransferOwnershipPreview { missing_owners, target_owner, rebuild, structure, oracle_packages })}fn postgres_transfer_grant_statements_sql(@@ -11748,6 +11891,9 @@ whereoffset += row_count as u64;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: table.to_string(),table_index,@@ -12238,6 +12384,9 @@ where}progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: format!("rename: {table}"),table_index: i,@@ -12511,7 +12660,7 @@ async fn create_transfer_target_table(// confirmation dialog and the actual creation can never disagree on the DDL// or the names inside it. Rebuild mode additionally fails closed here when// source metadata cannot be trusted.- let prepared = ddl_plan::prepare_table_ddl(+ let mut prepared = ddl_plan::prepare_table_ddl(state,request,table,@@ -12524,6 +12673,21 @@ async fn create_transfer_target_table(known_foreign_keys,).await?;+ if let Some(frozen) = request+ .oracle_packages+ .as_ref()+ .and_then(|packages| packages.pending_tables.as_ref())+ .and_then(|pending| pending.tables.iter().find(|frozen| frozen.source_table() == table))+ {+ let regenerated = frozen.verify_server_plan(+ table,+ &request.target_schema,+ target_table,+ &prepared.ddl,+ prepared.source_evidence.clone().ok_or("The original table evidence is unavailable before CREATE")?,+ )?;+ prepared.ddl = regenerated.final_ddl().to_owned();+ }let reused_source_ddl = prepared.reused_source_ddl;let ddl = prepared.ddl;let ddl = if pg_compat_transfer && !owned_sequences.is_empty() {@@ -13099,6 +13263,9 @@ where.map_err(|error| format!("Native Inceptor transfer failed for '{table}': {error}"))?;let copied = total_rows.expect("complex transfer count validated");progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: table.to_string(),table_index,@@ -13153,6 +13320,9 @@ wherebatch_size as u64,&mut |rows| {progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: table.to_string(),table_index,@@ -13172,6 +13342,9 @@ wheretotal_transferred = rows;log::info!("[transfer] {table}: COPY fast path moved {rows} rows in {:?}", started.elapsed());progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: table.to_string(),table_index,@@ -13444,6 +13617,9 @@ whereoffset += row_count as u64;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: table.to_string(),table_index,@@ -14066,6 +14242,9 @@ where}completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: format!("extension: {}", extension.extension_name),table_index,@@ -14087,6 +14266,9 @@ where}completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: format!("enum: {}", enum_type.type_name),table_index,@@ -14108,6 +14290,9 @@ where}completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: format!("domain: {}", domain.domain_name),table_index,@@ -14134,6 +14319,9 @@ where}completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: format!("sequence: {}", sequence.name),table_index,@@ -14269,6 +14457,9 @@ where}completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: format!("schema object: {}", object.name),table_index,@@ -14329,6 +14520,9 @@ where}completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: format!("materialized view: {}", view.view_name),table_index,@@ -14363,6 +14557,9 @@ where}completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: format!("trigger: {}", trigger.trigger_name),table_index,@@ -14383,6 +14580,9 @@ where.map_err(|e| format!("Failed to drop PostgreSQL trigger {}: {e}", trigger.trigger_name))?;completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: format!("trigger: {}", trigger.trigger_name),table_index,@@ -14411,6 +14611,9 @@ where}completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: "row security policies".to_string(),table_index,@@ -14432,6 +14635,9 @@ where}completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: "ownership".to_string(),table_index,@@ -14463,6 +14669,9 @@ where}completed_steps += 1;progress_callback(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: "grants".to_string(),table_index,@@ -15503,6 +15712,7 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;batch_size: 1000,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,};let json = serde_json::to_value(&request).unwrap();assert_eq!(json["content"], "structureOnly");@@ -15542,6 +15752,33 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;let dm = transfer_object_kinds(&DatabaseType::Dameng);assert!(dm.contains(&TransferObjectKind::Trigger));assert!(dm.contains(&TransferObjectKind::Sequence));+ assert!(!dm.contains(&TransferObjectKind::Package));+ for product in [DatabaseType::Oracle, DatabaseType::OceanbaseOracle] {+ let kinds = transfer_object_kinds(&product);+ assert!(kinds.contains(&TransferObjectKind::Package));+ assert!(kinds.contains(&TransferObjectKind::PackageBody));+ assert!(target_object_exists_sql(+ &product,+ "Owner.With.Dot",+ "Pkg.With.Dot😀",+ &TransferObjectKind::Package+ )+ .unwrap()+ .contains("OBJECT_TYPE = 'PACKAGE'"));+ assert!(target_object_exists_sql(+ &product,+ "Owner.With.Dot",+ "Pkg.With.Dot😀",+ &TransferObjectKind::PackageBody+ )+ .unwrap()+ .contains("OBJECT_TYPE = 'PACKAGE BODY'"));+ }+ assert!(+ target_object_exists_sql(&DatabaseType::Dameng, "OWNER", "PKG", &TransferObjectKind::Package).is_err()+ );+ assert!(!object_kind_selected_or_defaulted(None, &TransferObjectKind::Package));+ assert!(!object_kind_selected_or_defaulted(None, &TransferObjectKind::PackageBody));let sqlserver = transfer_object_kinds(&DatabaseType::SqlServer);assert!(sqlserver.contains(&TransferObjectKind::View));assert!(sqlserver.contains(&TransferObjectKind::Procedure));@@ -15592,6 +15829,7 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;table_filters: std::collections::HashMap::new(),drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,}}@@ -15620,6 +15858,44 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;assert!(validate_transfer_database_pair(&rebuild, &DatabaseType::Xugu, &DatabaseType::Xugu).is_err());}+ #[test]+ fn explicit_package_requests_round_trip_and_reject_unsupported_products_before_filtering() {+ let request = TransferRequest {+ objects: Some(vec![+ TransferObjectSelection {+ object_type: TransferObjectKind::Package,+ names: vec!["Pkg.With.Dot:😀".into()],+ },+ TransferObjectSelection {+ object_type: TransferObjectKind::PackageBody,+ names: vec!["Pkg.With.Dot:😀".into()],+ },+ ]),+ ..base_request()+ };+ let wire = serde_json::to_value(&request).unwrap();+ assert_eq!(wire["objects"][0]["objectType"], "PACKAGE");+ assert_eq!(wire["objects"][1]["objectType"], "PACKAGE_BODY");+ let restored: TransferRequest = serde_json::from_value(wire).unwrap();+ assert_eq!(restored.objects, request.objects);+ for source in [DatabaseType::Oracle, DatabaseType::OceanbaseOracle] {+ for target in [DatabaseType::Oracle, DatabaseType::OceanbaseOracle] {+ assert!(validate_transfer_database_pair(&restored, &source, &target).is_ok());+ }+ for target in [DatabaseType::Dameng, DatabaseType::Mysql, DatabaseType::Postgres, DatabaseType::Xugu] {+ assert!(validate_transfer_database_pair(&restored, &source, &target)+ .unwrap_err()+ .contains("actual Oracle"));+ assert!(validate_transfer_database_pair(&restored, &target, &source)+ .unwrap_err()+ .contains("actual Oracle"));+ }+ }+ let legacy = TransferRequest { objects: None, ..restored };+ assert!(!legacy.has_package_selection());+ assert!(validate_transfer_database_pair(&legacy, &DatabaseType::Dameng, &DatabaseType::Oracle).is_ok());+ }+#[test]fn transfer_pair_requires_declared_endpoint_compatibility() {let request = base_request();@@ -15716,6 +15992,7 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;objects: Some(Vec::new()),drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,};assert!(validate_transfer_request(&base).is_ok());@@ -15758,6 +16035,7 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;objects: Some(Vec::new()),drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,};// drop_target_before_create=false → valid@@ -17085,6 +17363,7 @@ CREATE TABLE "Other"."prefix""Source"."NAME" ("ID" INT);"#;batch_size: 1000,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,}}@@ -24441,6 +24720,9 @@ CREATE INDEX items_name_idx ON public.items (id);"#;try_send_transfer_progress(&sender,TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: "transfer".to_string(),table: "table".to_string(),table_index: 0,diff --git a/crates/dbx-core/src/data/transfer/ddl_plan.rs b/crates/dbx-core/src/data/transfer/ddl_plan.rsindex aea9a9623a..76a13249ca 100644--- a/crates/dbx-core/src/data/transfer/ddl_plan.rs+++ b/crates/dbx-core/src/data/transfer/ddl_plan.rs@@ -13,11 +13,13 @@ fn xugu_table_ddl_is_unavailable(sql: &str) -> bool {}#[derive(Debug, Clone, Serialize, Deserialize)]-pub(super) struct PreparedTableDdl {+pub(crate) struct PreparedTableDdl {pub ddl: String,pub reused_source_ddl: bool,pub deferred_fk_alters: Vec<String>,pub deferred_fk_names: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub source_evidence: Option<serde_json::Value>,}#[allow(clippy::too_many_arguments)]@@ -33,6 +35,11 @@ pub(super) async fn prepare_table_ddl(table_comment: Option<&str>,known_foreign_keys: &HashMap<String, Vec<db::ForeignKeyInfo>>,) -> Result<PreparedTableDdl, String> {+ let source_columns = if request.has_package_selection() {+ Some(serde_json::to_value(columns).map_err(|error| error.to_string())?)+ } else {+ None+ };let rebuild = request.drop_target_before_create;// Every column reference below (CREATE TABLE, keys) uses the target-side names.let target_columns = request.target_columns(columns);@@ -108,6 +115,7 @@ pub(super) async fn prepare_table_ddl(}let mut reused_source_ddl = false;+ let mut source_definition = None;let ddl = if can_reuse {let (source_ddl, source_ddl_was_read) = if let Some(catalog) =resolve_external_transfer_catalog(request.source_catalog.as_deref(), source_db_type)@@ -191,6 +199,9 @@ pub(super) async fn prepare_table_ddl(),}};+ if source_columns.is_some() && source_ddl_was_read {+ source_definition = Some(source_ddl.clone());+ }if contains_oceanbase_mysql_table_options(&source_ddl)&& !db::oceanbase_mysql::is_profile(target_db_type, target_driver_profile.as_deref()){@@ -272,7 +283,17 @@ pub(super) async fn prepare_table_ddl(generate_mysql_foreign_key_alter_statements(&foreign_keys, request, target_table, target_db_type);}- Ok(PreparedTableDdl { ddl, reused_source_ddl, deferred_fk_alters, deferred_fk_names })+ let source_evidence = source_columns.map(|columns| {+ serde_json::json!({+ "columns": columns,+ "tableComment": table_comment,+ "foreignKeys": foreign_keys,+ "sourceDdl": source_definition,+ "sourceDriverProfile": source_driver_profile,+ "targetDriverProfile": target_driver_profile,+ })+ });+ Ok(PreparedTableDdl { ddl, reused_source_ddl, deferred_fk_alters, deferred_fk_names, source_evidence })}#[cfg(test)]@@ -311,6 +332,67 @@ mod tests {]}+ #[tokio::test]+ async fn package_table_plans_keep_generation_inputs_without_changing_legacy_payloads() {+ let (state, _directory) = state_fixture().await;+ let mut request = request(false);+ let source_columns = columns();+ let known = HashMap::from([("child".into(), Vec::new())]);+ let ordinary = prepare_table_ddl(+ &state,+ &request,+ "child",+ "renamed",+ &DatabaseType::Oracle,+ &DatabaseType::OceanbaseOracle,+ "unused-source-pool",+ &source_columns,+ Some("source comment"),+ &known,+ )+ .await+ .unwrap();+ assert!(ordinary.source_evidence.is_none());+ assert!(serde_json::to_value(&ordinary).unwrap().get("source_evidence").is_none());+ request.objects =+ Some(vec![TransferObjectSelection { object_type: TransferObjectKind::Package, names: vec!["P".into()] }]);+ let reviewed = prepare_table_ddl(+ &state,+ &request,+ "child",+ "renamed",+ &DatabaseType::Oracle,+ &DatabaseType::OceanbaseOracle,+ "unused-source-pool",+ &source_columns,+ Some("source comment"),+ &known,+ )+ .await+ .unwrap();+ assert_eq!(reviewed.ddl, ordinary.ddl);+ assert!(!reviewed.reused_source_ddl);+ let evidence = reviewed.source_evidence.unwrap();+ assert_eq!(evidence["columns"], serde_json::to_value(&source_columns).unwrap());+ assert_eq!(evidence["tableComment"], "source comment");+ assert!(evidence["sourceDdl"].is_null());+ let changed = prepare_table_ddl(+ &state,+ &request,+ "child",+ "renamed",+ &DatabaseType::Oracle,+ &DatabaseType::OceanbaseOracle,+ "unused-source-pool",+ &source_columns,+ Some("changed comment"),+ &known,+ )+ .await+ .unwrap();+ assert_ne!(changed.source_evidence.unwrap(), evidence);+ }+#[tokio::test]async fn prepared_sqlite_ddl_preserves_source_foreign_keys_without_mutating_source() {let (state, directory) = state_fixture().await;diff --git a/crates/dbx-core/src/data/transfer/oracle_table_contract.rs b/crates/dbx-core/src/data/transfer/oracle_table_contract.rsnew file mode 100644index 0000000000..91c73c910e--- /dev/null+++ b/crates/dbx-core/src/data/transfer/oracle_table_contract.rs@@ -0,0 +1,607 @@+use sqlparser::{+ ast::{CreateTable, Statement},+ dialect::OracleDialect,+ parser::Parser,+ tokenizer::{Token, TokenWithSpan, Tokenizer},+};+use std::collections::BTreeSet;++#[path = "oracle_table_contract/types.rs"]+mod types;+pub(crate) use types::LengthSemantics;+#[path = "oracle_table_contract/frozen.rs"]+mod frozen;+pub use frozen::FrozenTableDdl;+#[path = "oracle_table_contract/length.rs"]+mod length;++pub(crate) struct CatalogTableColumn {+ pub id: u64,+ pub name: String,+ pub data_type: String,+ pub data_type_owner: Option<String>,+ pub data_length: u64,+ pub char_length: u64,+ pub char_used: Option<String>,+ pub precision: Option<u64>,+ pub scale: Option<i64>,+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub(super) struct TableShape {+ owner: String,+ name: String,+ columns: Vec<(String, types::ColumnType)>,+}++pub(crate) fn planned_columns(sql: &str, owner: &str, name: &str) -> Result<BTreeSet<String>, String> {+ let table = parse_create_table(sql)?;+ let effective = |identifier: &sqlparser::ast::Ident| {+ if identifier.quote_style.is_some() {+ identifier.value.clone()+ } else {+ identifier.value.to_uppercase()+ }+ };+ let parts = table+ .name+ .0+ .iter()+ .map(|part| part.as_ident().map(&effective).ok_or("The table target is not an exact identifier"))+ .collect::<Result<Vec<_>, _>>()?;+ if !matches!(parts.as_slice(), [table] if table == name)+ && !matches!(parts.as_slice(), [schema, table] if schema == owner && table == name)+ {+ return Err("The final table DDL belongs to another target identity".into());+ }+ let columns = table.columns.iter().map(|column| effective(&column.name)).collect::<BTreeSet<_>>();+ if columns.len() != table.columns.len() {+ return Err("The final table has duplicate effective column names".into());+ }+ Ok(columns)+}++pub(crate) fn needs_length_choice(sql: &str) -> Result<bool, String> {+ parse_create_table(sql)?;+ Ok(character_lengths(&table_tokens(sql)?)?.iter().any(|column| column.semantics.is_none()))+}++pub(super) fn table_shape(+ sql: &str,+ owner: &str,+ name: &str,+ default_length: Option<LengthSemantics>,+) -> Result<TableShape, String> {+ let table = parse_create_table(sql)?;+ let effective = |identifier: &sqlparser::ast::Ident| {+ if identifier.quote_style.is_some() {+ identifier.value.clone()+ } else {+ identifier.value.to_uppercase()+ }+ };+ let parts = table+ .name+ .0+ .iter()+ .map(|part| part.as_ident().map(&effective).ok_or("The table target is not an exact identifier"))+ .collect::<Result<Vec<_>, _>>()?;+ let matches = match parts.as_slice() {+ [table] => table == name,+ [schema, table] => schema == owner && table == name,+ _ => false,+ };+ if !matches {+ return Err("The final table DDL belongs to another target identity".into());+ }+ let mut columns = Vec::new();+ let mut names = BTreeSet::new();+ for column in table.columns {+ let name = effective(&column.name);+ if !names.insert(name.clone()) {+ return Err("The final table has duplicate effective column names".into());+ }+ if column.options.iter().any(|option| {+ matches!(+ option.option,+ sqlparser::ast::ColumnOption::Generated { generation_expr: Some(_), .. }+ | sqlparser::ast::ColumnOption::Materialized(_)+ | sqlparser::ast::ColumnOption::Alias(_)+ | sqlparser::ast::ColumnOption::Ephemeral(_)+ )+ }) {+ return Err(format!("Column {name} has an unverified generated shape; retain its complete table draft"));+ }+ let data_type =+ types::from_ast(&column.data_type, default_length).map_err(|error| format!("Column {name}: {error}"))?;+ columns.push((name, data_type));+ }+ Ok(TableShape { owner: owner.into(), name: name.into(), columns })+}++pub(super) fn parse_create_table(sql: &str) -> Result<CreateTable, String> {+ let dialect = OracleDialect {};+ let mut tokens = table_tokens(sql)?;+ let (_, close) = column_bounds(&tokens)?;+ check_physical_options(&tokens[close + 1..])?;+ for column in character_lengths(&tokens)? {+ if column.kind == "CHAR" && column.semantics.is_some() {+ if let Token::Word(word) = &mut tokens[column.type_index].token {+ word.keyword = sqlparser::keywords::Keyword::NoKeyword;+ }+ }+ }+ let mut statements = Parser::new(&dialect)+ .with_tokens_with_locations(tokens[..=close].to_vec())+ .parse_statements()+ .map_err(|error| error.to_string())?;+ if statements.len() != 1 {+ return Err("Expected one complete CREATE TABLE definition".into());+ }+ match statements.remove(0) {+ Statement::CreateTable(table)+ if !table.columns.is_empty()+ && !table.or_replace+ && !table.temporary+ && !table.external+ && table.global.is_none()+ && !table.if_not_exists+ && table.query.is_none()+ && table.like.is_none()+ && table.clone.is_none() =>+ {+ Ok(table)+ }+ _ => Err("Expected a CREATE TABLE definition".into()),+ }+}++fn table_tokens(sql: &str) -> Result<Vec<TokenWithSpan>, String> {+ let mut tokens =+ Tokenizer::new(&OracleDialect {}, sql).tokenize_with_location().map_err(|error| error.to_string())?;+ tokens.retain(|token| !matches!(token.token, Token::Whitespace(_)));+ if tokens.last().is_some_and(|token| token.token == Token::SemiColon) {+ tokens.pop();+ }+ Ok(tokens)+}++fn column_bounds(tokens: &[TokenWithSpan]) -> Result<(usize, usize), String> {+ let open = tokens+ .iter()+ .position(|token| token.token == Token::LParen)+ .ok_or("Expected an explicit complete table column list")?;+ let mut depth = 0;+ let close = tokens+ .iter()+ .enumerate()+ .skip(open)+ .find_map(|(index, token)| {+ match token.token {+ Token::LParen => depth += 1,+ Token::RParen => depth -= 1,+ _ => (),+ }+ (depth == 0).then_some(index)+ })+ .ok_or("The table column list is incomplete")?;+ Ok((open, close))+}++struct CharacterLengthColumn {+ column: String,+ kind: String,+ length: u64,+ semantics: Option<LengthSemantics>,+ type_index: usize,+ close_index: usize,+}++fn character_lengths(tokens: &[TokenWithSpan]) -> Result<Vec<CharacterLengthColumn>, String> {+ let (open, close) = column_bounds(tokens)?;+ let mut start = open + 1;+ let mut depth = 0;+ let mut output = Vec::new();+ for index in open + 1..=close {+ match tokens[index].token {+ Token::LParen => depth += 1,+ Token::RParen if depth > 0 => depth -= 1,+ _ => (),+ }+ if index != close && !(depth == 0 && tokens[index].token == Token::Comma) {+ continue;+ }+ let segment = &tokens[start..index];+ if let [column, data_type, ..] = segment {+ let is_character = word(Some(data_type), "CHAR") || word(Some(data_type), "VARCHAR2");+ if is_character {+ let Token::Word(column) = &column.token else {+ return Err("The character column has no exact identity".into());+ };+ let name =+ if column.quote_style.is_some() { column.value.clone() } else { column.value.to_uppercase() };+ if segment.get(2).map(|token| &token.token) != Some(&Token::LParen) {+ return Err(format!("Column {name} requires an explicit character length"));+ }+ let Some(Token::Number(length, false)) = segment.get(3).map(|token| &token.token) else {+ return Err(format!("Column {name} has an unverified character length"));+ };+ let length =+ length.parse::<u64>().ok().filter(|length| *length > 0).ok_or("The character length is invalid")?;+ let (semantics, end) = if segment.get(4).map(|token| &token.token) == Some(&Token::RParen) {+ (None, 4)+ } else if word(segment.get(4), "BYTE") {+ (Some(LengthSemantics::Bytes), 5)+ } else if word(segment.get(4), "CHAR") {+ (Some(LengthSemantics::Characters), 5)+ } else {+ return Err(format!("Column {name} has an unverified length unit"));+ };+ if segment.get(end).map(|token| &token.token) != Some(&Token::RParen) {+ return Err(format!("Column {name} has incomplete length parameters"));+ }+ output.push(CharacterLengthColumn {+ column: name,+ kind: if word(Some(data_type), "CHAR") { "CHAR" } else { "VARCHAR2" }.into(),+ length,+ semantics,+ type_index: start + 1,+ close_index: start + end,+ });+ }+ }+ start = index + 1;+ }+ Ok(output)+}++fn word(token: Option<&TokenWithSpan>, expected: &str) -> bool {+ matches!(token.map(|token| &token.token), Some(Token::Word(word))+ if word.quote_style.is_none() && word.value.eq_ignore_ascii_case(expected))+}++fn check_physical_options(tokens: &[TokenWithSpan]) -> Result<(), String> {+ let mut index = 0;+ let mut seen = BTreeSet::new();+ while let Some(token) = tokens.get(index) {+ let fail = || {+ format!(+ "Unverified table storage clause at line {}, column {}",+ token.span.start.line, token.span.start.column+ )+ };+ let Token::Word(option) = &token.token else {+ return Err(fail());+ };+ if option.quote_style.is_some() {+ return Err(fail());+ }+ let option = option.value.to_ascii_uppercase();+ if !seen.insert(option.clone()) {+ return Err(fail());+ }+ if option == "COMPRESS" {+ if !word(tokens.get(index + 1), "FOR") || !word(tokens.get(index + 2), "ARCHIVE") {+ return Err(fail());+ }+ index += 3;+ continue;+ }+ if !matches!(option.as_str(), "REPLICA_NUM" | "BLOCK_SIZE" | "USE_BLOOM_FILTER" | "TABLET_SIZE" | "PCTFREE")+ || tokens.get(index + 1).map(|token| &token.token) != Some(&Token::Eq)+ {+ return Err(fail());+ }+ let value = tokens.get(index + 2);+ if option == "USE_BLOOM_FILTER" {+ if !word(value, "TRUE") && !word(value, "FALSE") {+ return Err(fail());+ }+ } else {+ let Some(Token::Number(number, false)) = value.map(|token| &token.token) else {+ return Err(fail());+ };+ let number = number.parse::<u64>().map_err(|_| fail())?;+ if (option == "PCTFREE" && number > 99) || (option != "PCTFREE" && number == 0) {+ return Err(fail());+ }+ }+ index += 3;+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::types::{from_ast, from_catalog, CatalogColumnType, ColumnType, LengthSemantics};+ use super::*;++ const OB_DDL: &str = "CREATE TABLE \"PKG_MIXED_TYPE_PROBE\" (\n \"N\" NUMBER(12,3),\n \"V\" VARCHAR2(20 CHAR),\n \"B\" VARCHAR2(20),\n \"D\" VARCHAR2(20),\n \"T\" TIMESTAMP(6),\n \"Z\" TIMESTAMP(3) WITH TIME ZONE,\n \"Mixed列\" RAW(16)\n) COMPRESS FOR ARCHIVE REPLICA_NUM = 1 BLOCK_SIZE = 16384 USE_BLOOM_FILTER = FALSE TABLET_SIZE = 134217728 PCTFREE = 0";++ #[test]+ fn complete_ob_metadata_ddl_retains_all_column_types() {+ let table = parse_create_table(OB_DDL).unwrap();+ assert_eq!(table.name.to_string(), "\"PKG_MIXED_TYPE_PROBE\"");+ assert_eq!(table.columns.len(), 7);+ let sqlparser::ast::DataType::Custom(name, parameters) = &table.columns[0].data_type else {+ panic!("Expected Oracle NUMBER parameters");+ };+ assert_eq!(name.to_string(), "NUMBER");+ assert_eq!(parameters, &["12", "3"]);+ let sqlparser::ast::DataType::Custom(name, parameters) = &table.columns[1].data_type else {+ panic!("Expected Oracle VARCHAR2 length semantics");+ };+ assert_eq!(name.to_string(), "VARCHAR2");+ assert_eq!(parameters, &["20", "CHAR"]);+ assert_eq!(table.columns[5].data_type.to_string(), "TIMESTAMP(3) WITH TIME ZONE");+ assert_eq!(table.columns[6].name.value, "Mixed列");+ }++ #[test]+ fn unknown_duplicate_or_malformed_tail_and_additional_statements_are_not_ignored() {+ for suffix in [+ "UNKNOWN_OPTION = 1",+ "COMPRESS FOR QUERY",+ "REPLICA_NUM = 0",+ "BLOCK_SIZE = -1",+ "TABLET_SIZE = 1.5",+ "PCTFREE = 100",+ "USE_BLOOM_FILTER = MAYBE",+ "REPLICA_NUM = 1 REPLICA_NUM = 2",+ "COMPRESS FOR ARCHIVE COMPRESS FOR ARCHIVE",+ "PCTFREE = 1e2",+ "REPLICA_NUM =",+ "; ALTER TABLE T ADD X NUMBER",+ "; CREATE TABLE OTHER (X NUMBER)",+ ] {+ assert!(parse_create_table(&format!("CREATE TABLE T (N NUMBER) {suffix}")).is_err(), "{suffix}");+ }+ }++ #[test]+ fn column_parentheses_quotes_and_comments_do_not_end_the_definition_early() {+ let sql = "CREATE TABLE \"T.With.Dot\" (\"Mixed列\" VARCHAR2(20 CHAR) DEFAULT q'[); COMPRESS]', N NUMBER(12,3) CHECK (N >= 0)) /* ) */ COMPRESS FOR ARCHIVE PCTFREE = 0; -- trailing";+ let table = parse_create_table(sql).unwrap();+ assert_eq!(table.name.to_string(), "\"T.With.Dot\"");+ assert_eq!(table.columns.len(), 2);+ }++ #[test]+ fn ctas_incomplete_and_nonpermanent_definitions_are_not_typed_tables() {+ for sql in [+ "CREATE TABLE T AS SELECT 1 N FROM DUAL",+ "CREATE TABLE T (N NUMBER",+ "CREATE GLOBAL TEMPORARY TABLE T (N NUMBER)",+ "CREATE TABLE IF NOT EXISTS T (N NUMBER)",+ "SELECT F(N) FROM T",+ ] {+ assert!(parse_create_table(sql).is_err(), "{sql}");+ }+ assert!(parse_create_table("CREATE TABLE T (N NUMBER, V VARCHAR2(20 BYTE));").is_ok());+ }++ #[test]+ fn actual_ob_catalog_types_match_final_ddl_semantics_not_display_strings() {+ let table = parse_create_table(OB_DDL).unwrap();+ let observed = [+ ("NUMBER", 22, 0, None, Some(12), Some(3)),+ ("VARCHAR2", 80, 20, Some("C"), None, None),+ ("VARCHAR2", 20, 20, Some("B"), None, None),+ ("VARCHAR2", 20, 20, Some("B"), None, None),+ ("TIMESTAMP(6)", 11, 0, None, None, Some(6)),+ ("TIMESTAMP(3) WITH TIME ZONE", 13, 0, None, None, Some(3)),+ ("RAW", 16, 0, None, None, Some(-1)),+ ];+ for (column, (data_type, data_length, char_length, char_used, precision, scale)) in+ table.columns.iter().zip(observed)+ {+ let actual = from_catalog(CatalogColumnType {+ data_type,+ data_type_owner: None,+ data_length,+ char_length,+ char_used,+ precision,+ scale,+ })+ .unwrap();+ assert_eq!(from_ast(&column.data_type, Some(LengthSemantics::Bytes)).unwrap(), actual, "{}", column.name);+ }+ assert!(from_ast(&table.columns[2].data_type, None).is_err());+ assert!(matches!(+ from_ast(&table.columns[1].data_type, None).unwrap(),+ ColumnType::Character { semantics: LengthSemantics::Characters, length: 20, .. }+ ));+ }++ #[test]+ fn changed_types_or_incomplete_catalog_fields_do_not_become_equivalent() {+ let table =+ parse_create_table("CREATE TABLE T (N NUMBER(12,3), R RAW(16), S TIMESTAMP(3) WITH TIME ZONE)").unwrap();+ assert_ne!(+ from_ast(&table.columns[0].data_type, None).unwrap(),+ from_catalog(CatalogColumnType {+ data_type: "NUMBER",+ data_type_owner: None,+ data_length: 22,+ char_length: 0,+ char_used: None,+ precision: Some(12),+ scale: Some(0)+ })+ .unwrap()+ );+ assert_ne!(+ from_ast(&table.columns[1].data_type, None).unwrap(),+ from_catalog(CatalogColumnType {+ data_type: "RAW",+ data_type_owner: None,+ data_length: 8,+ char_length: 0,+ char_used: None,+ precision: None,+ scale: Some(-1)+ })+ .unwrap()+ );+ assert!(from_catalog(CatalogColumnType {+ data_type: "VARCHAR2",+ data_type_owner: None,+ data_length: 20,+ char_length: 20,+ char_used: None,+ precision: None,+ scale: None+ })+ .is_err());+ assert!(from_catalog(CatalogColumnType {+ data_type: "TIMESTAMP(3) WITH TIME ZONE",+ data_type_owner: None,+ data_length: 13,+ char_length: 0,+ char_used: None,+ precision: None,+ scale: Some(6)+ })+ .is_err());+ assert_ne!(+ from_ast(&table.columns[0].data_type, None).unwrap(),+ from_catalog(CatalogColumnType {+ data_type: "NUMBER",+ data_type_owner: Some("OTHER"),+ data_length: 22,+ char_length: 0,+ char_used: None,+ precision: Some(12),+ scale: Some(3)+ })+ .unwrap()+ );+ }++ #[test]+ fn external_column_types_keep_exact_qualified_identity_not_unverified_local_aliases() {+ let frozen = FrozenTableDdl::from_server_plan(+ "S",+ "T",+ "FINAL",+ "CREATE TABLE FINAL (A ext.shape, B \"Owner.With.Dot\".\"Mixed列\")",+ serde_json::json!({}),+ None,+ )+ .unwrap();+ assert_eq!(+ frozen.external_types(),+ BTreeSet::from([("EXT".into(), "SHAPE".into()), ("Owner.With.Dot".into(), "Mixed列".into())])+ );+ for sql in ["CREATE TABLE FINAL(A SHAPE)", "CREATE TABLE FINAL(A ext.shape(12))", "CREATE TABLE FINAL(A LONG)"]+ {+ assert!(+ FrozenTableDdl::from_server_plan("S", "T", "FINAL", sql, serde_json::json!({}), None).is_err(),+ "{sql}"+ );+ }+ frozen+ .verify_catalog_columns(&[+ CatalogTableColumn {+ id: 16,+ name: "A".into(),+ data_type: "SHAPE".into(),+ data_type_owner: Some("EXT".into()),+ data_length: 0,+ char_length: 0,+ char_used: None,+ precision: None,+ scale: None,+ },+ CatalogTableColumn {+ id: 17,+ name: "B".into(),+ data_type: "Mixed列".into(),+ data_type_owner: Some("Owner.With.Dot".into()),+ data_length: 0,+ char_length: 0,+ char_used: None,+ precision: None,+ scale: None,+ },+ ])+ .unwrap();+ }++ #[test]+ fn final_target_and_effective_column_names_are_exact_and_ordered() {+ let shape = table_shape(+ "CREATE TABLE \"Target.With.Dot\".\"T\" (source_name NUMBER(12,3), \"Mixed列\" RAW(16))",+ "Target.With.Dot",+ "T",+ None,+ )+ .unwrap();+ assert_eq!(shape.columns.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), ["SOURCE_NAME", "Mixed列"]);+ assert!(table_shape("CREATE TABLE \"Other\".T(N NUMBER)", "Target.With.Dot", "T", None).is_err());+ assert!(table_shape("CREATE TABLE T(N NUMBER, \"N\" NUMBER)", "Target.With.Dot", "T", None).is_err());+ assert!(table_shape(+ "CREATE TABLE T(N NUMBER, X NUMBER GENERATED ALWAYS AS (N+1) VIRTUAL)",+ "Target.With.Dot",+ "T",+ None+ )+ .is_err());+ let reordered = table_shape(+ "CREATE TABLE \"Target.With.Dot\".T(\"Mixed列\" RAW(16), source_name NUMBER(12,3))",+ "Target.With.Dot",+ "T",+ None,+ )+ .unwrap();+ assert_ne!(shape, reordered);+ }++ #[test]+ fn native_ast_variants_preserve_character_lob_and_binary_float_precision() {+ let sql = "CREATE TABLE T (C CHAR(10), D DATE, L CLOB, B BLOB, N NCHAR(10), V NVARCHAR2(12), F FLOAT(8))";+ let shape = table_shape(sql, "OWNER", "T", Some(LengthSemantics::Bytes)).unwrap();+ assert_eq!(+ shape.columns.iter().map(|(_, kind)| kind.clone()).collect::<Vec<_>>(),+ [+ ColumnType::Character { kind: "CHAR".into(), length: 10, semantics: LengthSemantics::Bytes },+ ColumnType::Date,+ ColumnType::Clob,+ ColumnType::Blob,+ ColumnType::Character { kind: "NCHAR".into(), length: 10, semantics: LengthSemantics::Characters },+ ColumnType::Character { kind: "NVARCHAR2".into(), length: 12, semantics: LengthSemantics::Characters },+ ColumnType::Float(8),+ ]+ );+ assert!(table_shape(sql, "OWNER", "T", None).is_err());+ assert_eq!(+ from_catalog(CatalogColumnType {+ data_type: "FLOAT",+ data_type_owner: None,+ data_length: 22,+ char_length: 0,+ char_used: None,+ precision: Some(8),+ scale: None+ })+ .unwrap(),+ ColumnType::Float(8)+ );+ assert!(from_catalog(CatalogColumnType {+ data_type: "FLOAT",+ data_type_owner: None,+ data_length: 22,+ char_length: 0,+ char_used: None,+ precision: None,+ scale: None+ })+ .is_err());+ assert_eq!(+ table_shape("CREATE TABLE T (V OTHER.EXTERNAL_TYPE)", "OWNER", "T", None).unwrap().columns[0].1,+ ColumnType::External { owner: "OTHER".into(), name: "EXTERNAL_TYPE".into() }+ );+ }+}diff --git a/crates/dbx-core/src/data/transfer/oracle_table_contract/frozen.rs b/crates/dbx-core/src/data/transfer/oracle_table_contract/frozen.rsnew file mode 100644index 0000000000..3402b2af6b--- /dev/null+++ b/crates/dbx-core/src/data/transfer/oracle_table_contract/frozen.rs@@ -0,0 +1,164 @@+use super::{+ length::{finalize_length_semantics, InsertedLengthUnit},+ LengthSemantics, TableShape,+};++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FrozenTableDdl {+ source_table: String,+ base_ddl: String,+ final_ddl: String,+ source_evidence: serde_json::Value,+ length_semantics_choice: Option<LengthSemantics>,+ inserted_units: Vec<InsertedLengthUnit>,+ shape: TableShape,+}++impl FrozenTableDdl {+ pub(crate) fn external_types(&self) -> std::collections::BTreeSet<(String, String)> {+ self.shape+ .columns+ .iter()+ .filter_map(|(_, kind)| match kind {+ super::types::ColumnType::External { owner, name } => Some((owner.clone(), name.clone())),+ _ => None,+ })+ .collect()+ }++ pub(crate) fn verify_catalog_columns(&self, columns: &[super::CatalogTableColumn]) -> Result<(), String> {+ let mut previous = None;+ let mut names = std::collections::BTreeSet::new();+ let mut actual = Vec::new();+ for column in columns {+ if column.id == 0 || previous.is_some_and(|id| column.id <= id) || !names.insert(&column.name) {+ return Err("The actual table column identities or order are incomplete".into());+ }+ previous = Some(column.id);+ actual.push((+ column.name.clone(),+ super::types::from_catalog(super::types::CatalogColumnType {+ data_type: &column.data_type,+ data_type_owner: column.data_type_owner.as_deref(),+ data_length: column.data_length,+ char_length: column.char_length,+ char_used: column.char_used.as_deref(),+ precision: column.precision,+ scale: column.scale,+ })?,+ ));+ }+ if actual != self.shape.columns {+ return Err(format!("The actual table {}.{} does not match the confirmed ordered column types; retain the completed table and package drafts", self.owner(), self.name()));+ }+ Ok(())+ }++ pub(crate) fn source_table(&self) -> &str {+ &self.source_table+ }+ pub(crate) fn owner(&self) -> &str {+ &self.shape.owner+ }+ pub(crate) fn name(&self) -> &str {+ &self.shape.name+ }+ pub(crate) fn columns(&self) -> std::collections::BTreeSet<String> {+ self.shape.columns.iter().map(|(name, _)| name.clone()).collect()+ }+ pub(crate) fn length_choice(&self) -> Option<LengthSemantics> {+ self.length_semantics_choice+ }++ pub(crate) fn final_ddl(&self) -> &str {+ &self.final_ddl+ }++ pub(crate) fn from_server_plan(+ source_table: &str,+ owner: &str,+ target_table: &str,+ base_ddl: &str,+ source_evidence: serde_json::Value,+ choice: Option<LengthSemantics>,+ ) -> Result<Self, String> {+ let finalized = finalize_length_semantics(base_ddl, owner, target_table, choice)?;+ let length_semantics_choice = (!finalized.inserted_units.is_empty()).then_some(choice).flatten();+ Ok(Self {+ source_table: source_table.into(),+ base_ddl: base_ddl.into(),+ final_ddl: finalized.sql,+ source_evidence,+ length_semantics_choice,+ inserted_units: finalized.inserted_units,+ shape: finalized.shape,+ })+ }++ pub(crate) fn verify_server_plan(+ &self,+ source_table: &str,+ owner: &str,+ target_table: &str,+ base_ddl: &str,+ source_evidence: serde_json::Value,+ ) -> Result<Self, String> {+ let current = Self::from_server_plan(+ source_table,+ owner,+ target_table,+ base_ddl,+ source_evidence,+ self.length_semantics_choice,+ )?;+ if *self != current {+ return Err("The table source, final SQL or typed structure changed after confirmation; retain the package drafts and refresh before writing".into());+ }+ Ok(current)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn a_confirmed_unit_is_reapplied_to_server_sql_not_to_client_create_text() {+ let sql = "CREATE TABLE \"OWNER\".T(V VARCHAR2(20))";+ let evidence =+ json!({"columns":[{"name":"V","dataType":"VARCHAR2(20)"}],"sourceDdl":"full original definition"});+ let frozen =+ FrozenTableDdl::from_server_plan("S", "OWNER", "T", sql, evidence.clone(), Some(LengthSemantics::Bytes))+ .unwrap();+ assert_eq!(frozen.final_ddl, "CREATE TABLE \"OWNER\".T(V VARCHAR2(20 BYTE))");+ let encoded = serde_json::to_value(&frozen).unwrap();+ assert_eq!(serde_json::from_value::<FrozenTableDdl>(encoded.clone()).unwrap(), frozen);+ assert_eq!(frozen.verify_server_plan("S", "OWNER", "T", sql, evidence.clone()).unwrap(), frozen);+ for key in ["sourceTable", "baseDdl", "finalDdl"] {+ let mut changed = encoded.clone();+ changed[key] = json!("CREATE TABLE OTHER(X NUMBER)");+ let changed: FrozenTableDdl = serde_json::from_value(changed).unwrap();+ assert!(changed.verify_server_plan("S", "OWNER", "T", sql, evidence.clone()).is_err(), "{key}");+ }+ let changed_evidence = json!({"columns":[{"name":"V","dataType":"VARCHAR2(20)"}],"sourceDdl":"a different original owner or source comment"});+ assert!(frozen.verify_server_plan("S", "OWNER", "T", sql, changed_evidence).is_err());+ assert!(frozen+ .verify_server_plan("S", "OWNER", "T", "CREATE TABLE \"OWNER\".T(V VARCHAR2(21))", evidence.clone())+ .is_err());+ assert!(frozen.verify_server_plan("OtherSource", "OWNER", "T", sql, evidence.clone()).is_err());+ assert!(frozen.verify_server_plan("S", "OTHER", "T", sql, evidence).is_err());+ }++ #[test]+ fn explicit_or_national_columns_do_not_retain_an_unused_default_choice() {+ let sql = "CREATE TABLE T(V VARCHAR2(20 CHAR), N NVARCHAR2(10))";+ let frozen =+ FrozenTableDdl::from_server_plan("S", "OWNER", "T", sql, json!({}), Some(LengthSemantics::Bytes)).unwrap();+ assert!(frozen.length_semantics_choice.is_none());+ assert!(frozen.inserted_units.is_empty());+ assert_eq!(frozen.final_ddl, sql);+ assert_eq!(frozen.verify_server_plan("S", "OWNER", "T", sql, json!({})).unwrap(), frozen);+ }+}diff --git a/crates/dbx-core/src/data/transfer/oracle_table_contract/length.rs b/crates/dbx-core/src/data/transfer/oracle_table_contract/length.rsnew file mode 100644index 0000000000..51f412e7cb--- /dev/null+++ b/crates/dbx-core/src/data/transfer/oracle_table_contract/length.rs@@ -0,0 +1,142 @@+use super::{character_lengths, parse_create_table, table_shape, table_tokens, LengthSemantics, TableShape};++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub(super) struct InsertedLengthUnit {+ pub column: String,+ pub kind: String,+ pub length: u64,+ pub semantics: LengthSemantics,+}++pub(super) struct FinalTableDdl {+ pub sql: String,+ pub shape: TableShape,+ pub inserted_units: Vec<InsertedLengthUnit>,+}++pub(super) fn finalize_length_semantics(+ sql: &str,+ owner: &str,+ name: &str,+ choice: Option<LengthSemantics>,+) -> Result<FinalTableDdl, String> {+ parse_create_table(sql)?;+ let tokens = table_tokens(sql)?;+ let missing =+ character_lengths(&tokens)?.into_iter().filter(|column| column.semantics.is_none()).collect::<Vec<_>>();+ let mut final_sql = sql.to_owned();+ let mut inserted_units = Vec::new();+ if !missing.is_empty() {+ let choice =+ choice.ok_or("Read and review the target character length unit before confirming this table draft")?;+ let text = match choice {+ LengthSemantics::Bytes => " BYTE",+ LengthSemantics::Characters => " CHAR",+ };+ let mut offsets = Vec::new();+ for column in missing {+ let location = tokens[column.close_index].span.start;+ let offset = byte_offset(sql, location)?;+ if !sql[offset..].starts_with(')') {+ return Err("The character length token no longer matches the complete table draft".into());+ }+ offsets.push(offset);+ inserted_units.push(InsertedLengthUnit {+ column: column.column,+ kind: column.kind,+ length: column.length,+ semantics: choice,+ });+ }+ for offset in offsets.into_iter().rev() {+ final_sql.insert_str(offset, text);+ }+ }+ let shape = table_shape(&final_sql, owner, name, None)?;+ Ok(FinalTableDdl { sql: final_sql, shape, inserted_units })+}++fn byte_offset(sql: &str, location: sqlparser::tokenizer::Location) -> Result<usize, String> {+ let (mut line, mut column) = (1, 1);+ for (offset, value) in sql.char_indices() {+ if line == location.line && column == location.column {+ return Ok(offset);+ }+ if value == '\n' {+ line += 1;+ column = 1;+ } else {+ column += 1;+ }+ }+ Err("The character length location is outside the original UTF-8 table draft".into())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn explicit_length_units_preserve_every_other_byte_and_are_idempotent() {+ let sql = "CREATE TABLE \"T.With.Dot\" (\r\n \"混合😀\" VARCHAR2 /* 中文 */ (20),\r\n C CHAR(3), V VARCHAR2(7 CHAR), N NVARCHAR2(12), X RAW(4) DEFAULT q'[CHAR(3); 😀)]'\r\n) COMPRESS FOR ARCHIVE PCTFREE = 0; -- CHAR(3)";+ let expected = "CREATE TABLE \"T.With.Dot\" (\r\n \"混合😀\" VARCHAR2 /* 中文 */ (20 BYTE),\r\n C CHAR(3 BYTE), V VARCHAR2(7 CHAR), N NVARCHAR2(12), X RAW(4) DEFAULT q'[CHAR(3); 😀)]'\r\n) COMPRESS FOR ARCHIVE PCTFREE = 0; -- CHAR(3)";+ let result = finalize_length_semantics(sql, "OWNER", "T.With.Dot", Some(LengthSemantics::Bytes)).unwrap();+ assert_eq!(result.sql, expected);+ assert_eq!(result.inserted_units.len(), 2);+ assert_eq!(result.inserted_units[0].column, "混合😀");+ assert_eq!(result.inserted_units[1].column, "C");+ assert_eq!(table_shape(expected, "OWNER", "T.With.Dot", None).unwrap(), result.shape);+ let again = finalize_length_semantics(expected, "OWNER", "T.With.Dot", None).unwrap();+ assert_eq!(again.sql, expected);+ assert!(again.inserted_units.is_empty());+ }++ #[test]+ fn an_unconfirmed_choice_or_wrong_target_cannot_produce_a_final_table() {+ assert!(finalize_length_semantics("CREATE TABLE T(V VARCHAR2(20))", "OWNER", "T", None).is_err());+ assert!(finalize_length_semantics(+ "CREATE TABLE OTHER.T(V VARCHAR2(20))",+ "OWNER",+ "T",+ Some(LengthSemantics::Bytes)+ )+ .is_err());+ let result = finalize_length_semantics(+ "CREATE TABLE T(C CHAR(3), V VARCHAR2(20 BYTE), N NCHAR(3))",+ "OWNER",+ "T",+ Some(LengthSemantics::Characters),+ )+ .unwrap();+ assert_eq!(result.sql, "CREATE TABLE T(C CHAR(3 CHAR), V VARCHAR2(20 BYTE), N NCHAR(3))");+ assert_eq!(+ result.inserted_units,+ [InsertedLengthUnit {+ column: "C".into(),+ kind: "CHAR".into(),+ length: 3,+ semantics: LengthSemantics::Characters+ }]+ );+ let explicit =+ finalize_length_semantics("CREATE TABLE T(C CHAR(3 CHAR), V VARCHAR2(20 BYTE))", "OWNER", "T", None)+ .unwrap();+ assert!(explicit.inserted_units.is_empty());+ assert_eq!(explicit.sql, "CREATE TABLE T(C CHAR(3 CHAR), V VARCHAR2(20 BYTE))");+ }++ #[test]+ fn malformed_character_units_do_not_get_reinterpreted_by_the_generic_parser() {+ for sql in [+ "CREATE TABLE T(V VARCHAR2(20,CHAR))",+ "CREATE TABLE T(V VARCHAR2(20 CHAR BYTE))",+ "CREATE TABLE T(V VARCHAR2(20 UNKNOWN))",+ "CREATE TABLE T(V VARCHAR2(0))",+ "CREATE TABLE T(V VARCHAR2(20)) UNKNOWN_STORAGE = 1",+ "CREATE TABLE T(V VARCHAR2(20)); DROP TABLE OTHER",+ ] {+ assert!(finalize_length_semantics(sql, "OWNER", "T", Some(LengthSemantics::Bytes)).is_err(), "{sql}");+ }+ }+}diff --git a/crates/dbx-core/src/data/transfer/oracle_table_contract/types.rs b/crates/dbx-core/src/data/transfer/oracle_table_contract/types.rsnew file mode 100644index 0000000000..c59460c4dd--- /dev/null+++ b/crates/dbx-core/src/data/transfer/oracle_table_contract/types.rs@@ -0,0 +1,208 @@+use sqlparser::ast::{CharLengthUnits, CharacterLength, DataType, ExactNumberInfo, TimezoneInfo};++#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) enum LengthSemantics {+ Bytes,+ Characters,+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+#[serde(tag = "kind", content = "parameters", rename_all = "camelCase")]+pub(super) enum ColumnType {+ Number { precision: Option<u64>, scale: Option<i64> },+ Float(u64),+ Character { kind: String, length: u64, semantics: LengthSemantics },+ Raw(u64),+ Timestamp { precision: u64, with_time_zone: bool },+ Date,+ BinaryFloat,+ BinaryDouble,+ Clob,+ Nclob,+ Blob,+ External { owner: String, name: String },+}++pub(super) fn from_ast(data_type: &DataType, default_length: Option<LengthSemantics>) -> Result<ColumnType, String> {+ match data_type {+ DataType::Char(length) | DataType::Character(length) | DataType::Varchar(length) => {+ let (length, explicit) = match length {+ None => (1, None),+ Some(CharacterLength::IntegerLength { length, unit }) => (+ *length,+ match unit {+ None => None,+ Some(CharLengthUnits::Characters) => Some(LengthSemantics::Characters),+ Some(CharLengthUnits::Octets) => Some(LengthSemantics::Bytes),+ },+ ),+ _ => return Err("The character column length is not a bounded integer".into()),+ };+ if length == 0 {+ return Err("The character column length is invalid".into());+ }+ let semantics = explicit.or(default_length).ok_or("The target execution session's default character length semantics are not verified; retain the table draft")?;+ Ok(ColumnType::Character {+ kind: if matches!(data_type, DataType::Varchar(_)) { "VARCHAR2" } else { "CHAR" }.into(),+ length,+ semantics,+ })+ }+ DataType::Float(info) => match info {+ ExactNumberInfo::None => Ok(ColumnType::Float(126)),+ ExactNumberInfo::Precision(precision) if (1..=126).contains(precision) => Ok(ColumnType::Float(*precision)),+ _ => Err("The Oracle FLOAT binary precision is not verified".into()),+ },+ DataType::Clob(None) => Ok(ColumnType::Clob),+ DataType::Blob(None) => Ok(ColumnType::Blob),+ DataType::Timestamp(precision, zone) => {+ let precision = precision.unwrap_or(6);+ if precision > 9 || !matches!(zone, TimezoneInfo::None | TimezoneInfo::WithTimeZone) {+ return Err("The table timestamp precision or time-zone semantics are not verified".into());+ }+ Ok(ColumnType::Timestamp { precision, with_time_zone: *zone == TimezoneInfo::WithTimeZone })+ }+ DataType::Date => Ok(ColumnType::Date),+ DataType::Custom(name, parameters) => {+ if let [owner, name] = name.0.as_slice() {+ let effective = |part: &sqlparser::ast::ObjectNamePart| -> Result<String, String> {+ let ident = part.as_ident().ok_or("The external type identity is not a plain identifier")?;+ Ok(if ident.quote_style.is_some() { ident.value.clone() } else { ident.value.to_uppercase() })+ };+ if !parameters.is_empty() {+ return Err("An external column type cannot have unverified parameters".into());+ }+ return Ok(ColumnType::External { owner: effective(owner)?, name: effective(name)? });+ }+ let [part] = name.0.as_slice() else {+ return Err("An external table-column type requires its exact target type evidence".into());+ };+ let identifier = part.as_ident().ok_or("The table-column type identity is not a plain identifier")?;+ if identifier.quote_style.is_some() {+ return Err("A quoted table-column type requires its exact target type evidence".into());+ }+ let kind = identifier.value.to_ascii_uppercase();+ match kind.as_str() {+ "NUMBER" => {+ let (precision, scale) = match parameters.as_slice() {+ [] => (None, None),+ [precision] => (Some(positive(precision)?), Some(0)),+ [precision, scale] => (+ if precision == "*" { None } else { Some(positive(precision)?) },+ Some(scale.parse::<i64>().map_err(|_| "The NUMBER scale is incomplete")?),+ ),+ _ => return Err("The NUMBER parameters are incomplete".into()),+ };+ number(precision, scale)+ }+ "VARCHAR2" | "NVARCHAR2" | "CHAR" | "NCHAR" => {+ let (length, explicit) = match parameters.as_slice() {+ [length] => (positive(length)?, None),+ [length, unit] if unit.eq_ignore_ascii_case("BYTE") => {+ (positive(length)?, Some(LengthSemantics::Bytes))+ }+ [length, unit] if unit.eq_ignore_ascii_case("CHAR") => {+ (positive(length)?, Some(LengthSemantics::Characters))+ }+ _ => return Err("The character column length or unit is incomplete".into()),+ };+ let national = kind == "NCHAR" || kind == "NVARCHAR2";+ if national && explicit == Some(LengthSemantics::Bytes) {+ return Err("A national character column cannot use BYTE semantics".into());+ }+ let semantics = if national {+ LengthSemantics::Characters+ } else {+ explicit.or(default_length).ok_or("The target execution session's default character length semantics are not verified; retain the table draft")?+ };+ Ok(ColumnType::Character { kind, length, semantics })+ }+ "RAW" if parameters.len() == 1 => Ok(ColumnType::Raw(positive(¶meters[0])?)),+ "BINARY_FLOAT" if parameters.is_empty() => Ok(ColumnType::BinaryFloat),+ "BINARY_DOUBLE" if parameters.is_empty() => Ok(ColumnType::BinaryDouble),+ "CLOB" if parameters.is_empty() => Ok(ColumnType::Clob),+ "NCLOB" if parameters.is_empty() => Ok(ColumnType::Nclob),+ "BLOB" if parameters.is_empty() => Ok(ColumnType::Blob),+ _ => Err(format!("Table-column type {kind} requires verified target type semantics")),+ }+ }+ _ => Err("The final table-column type requires verified Oracle type semantics".into()),+ }+}++fn positive(text: &str) -> Result<u64, String> {+ text.parse::<u64>().ok().filter(|value| *value > 0).ok_or_else(|| "The type length or precision is invalid".into())+}++fn number(precision: Option<u64>, scale: Option<i64>) -> Result<ColumnType, String> {+ if precision.is_some_and(|precision| !(1..=38).contains(&precision))+ || scale.is_some_and(|scale| !(-84..=127).contains(&scale))+ {+ return Err("The NUMBER precision or scale is outside the verified Oracle range".into());+ }+ Ok(ColumnType::Number { precision, scale })+}++pub(super) struct CatalogColumnType<'a> {+ pub data_type: &'a str,+ pub data_type_owner: Option<&'a str>,+ pub data_length: u64,+ pub char_length: u64,+ pub char_used: Option<&'a str>,+ pub precision: Option<u64>,+ pub scale: Option<i64>,+}++pub(super) fn from_catalog(column: CatalogColumnType<'_>) -> Result<ColumnType, String> {+ if let Some(owner) = column.data_type_owner {+ if owner.is_empty() || column.data_type.is_empty() {+ return Err("The external catalog type identity is incomplete".into());+ }+ return Ok(ColumnType::External { owner: owner.into(), name: column.data_type.into() });+ }+ match column.data_type {+ "NUMBER" => number(column.precision, column.scale),+ "FLOAT" if column.scale.is_none() => match column.precision {+ Some(precision) if (1..=126).contains(&precision) => Ok(ColumnType::Float(precision)),+ _ => Err("The catalog FLOAT binary precision is incomplete".into()),+ },+ "VARCHAR2" | "CHAR" | "NVARCHAR2" | "NCHAR" => {+ let semantics = match column.char_used {+ Some("B") => LengthSemantics::Bytes,+ Some("C") => LengthSemantics::Characters,+ _ => return Err("The catalog character length semantics are incomplete".into()),+ };+ let length = if semantics == LengthSemantics::Bytes { column.data_length } else { column.char_length };+ if matches!(column.data_type, "NCHAR" | "NVARCHAR2") && semantics != LengthSemantics::Characters {+ return Err("The national character column has inconsistent length semantics".into());+ }+ if length == 0 {+ return Err("The catalog character length is incomplete".into());+ }+ Ok(ColumnType::Character { kind: column.data_type.into(), length, semantics })+ }+ "RAW" if column.data_length > 0 => Ok(ColumnType::Raw(column.data_length)),+ "DATE" => Ok(ColumnType::Date),+ "BINARY_FLOAT" => Ok(ColumnType::BinaryFloat),+ "BINARY_DOUBLE" => Ok(ColumnType::BinaryDouble),+ "CLOB" => Ok(ColumnType::Clob),+ "NCLOB" => Ok(ColumnType::Nclob),+ "BLOB" => Ok(ColumnType::Blob),+ data_type if data_type.starts_with("TIMESTAMP") => {+ let dialect = sqlparser::dialect::OracleDialect {};+ let mut parser =+ sqlparser::parser::Parser::new(&dialect).try_with_sql(data_type).map_err(|error| error.to_string())?;+ let data_type = parser.parse_data_type().map_err(|error| error.to_string())?;+ if parser.peek_token().token != sqlparser::tokenizer::Token::EOF {+ return Err("The catalog timestamp type has unverified trailing text".into());+ }+ let result = from_ast(&data_type, None)?;+ if !matches!(&result, ColumnType::Timestamp { precision, .. } if Some(*precision as i64) == column.scale) {+ return Err("The catalog timestamp precision fields disagree".into());+ }+ Ok(result)+ }+ _ => Err("The catalog table-column type is not completely verified".into()),+ }+}diff --git a/crates/dbx-core/src/data/transfer/overwrite_clear.rs b/crates/dbx-core/src/data/transfer/overwrite_clear.rsindex 4c41b85ca5..b933f8f492 100644--- a/crates/dbx-core/src/data/transfer/overwrite_clear.rs+++ b/crates/dbx-core/src/data/transfer/overwrite_clear.rs@@ -193,6 +193,7 @@ mod tests {table_filters: HashMap::new(),drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,}}diff --git a/crates/dbx-core/src/data/transfer/structure_plan.rs b/crates/dbx-core/src/data/transfer/structure_plan.rsindex 8e367ffbdf..99db627926 100644--- a/crates/dbx-core/src/data/transfer/structure_plan.rs+++ b/crates/dbx-core/src/data/transfer/structure_plan.rs@@ -71,7 +71,13 @@ pub(super) async fn build_structure_preview(.await?};if !request.create_table {- let mut sections = vec![CREATE_TABLE_DISABLED_NOTE.to_string()];+ let mut sections = vec![if request.has_package_selection()+ && matches!(source_db_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle)+ {+ "-- Table creation is disabled; selected package definitions are reviewed separately.".into()+ } else {+ CREATE_TABLE_DISABLED_NOTE.to_string()+ }];if let Some(plan) = &xugu_plan {sections.push(plan.preview_before_tables());}@@ -146,6 +152,7 @@ pub(super) async fn build_structure_preview(DDL for it");planned_tables.push(TransferStructurePreviewTable {+ oracle_plan: None,source_table: table.clone(),target_table,preexisting: true,@@ -176,6 +183,7 @@ pub(super) async fn build_structure_preview(let section = format!("-- {} -> {}\n{}", table, target_table, statement_block(&planned.statements));planned_tables.push(TransferStructurePreviewTable {+ oracle_plan: planned.oracle_plan,source_table: table.clone(),target_table,preexisting: false,@@ -290,6 +298,7 @@ async fn mysql_schema_object_preview_sql(}struct PlannedTableStructure {+ oracle_plan: Option<ddl_plan::PreparedTableDdl>,statements: Vec<String>,operations: Vec<TransferStructureOperation>,deferred_fk_alters: Vec<String>,@@ -417,6 +426,7 @@ async fn plan_table_structure(known_foreign_keys,).await?;+ let oracle_plan = request.has_package_selection().then(|| prepared.clone());let ddl = if pg_compat_transfer && !owned_sequences.owned_sequences.is_empty() {rewrite_postgres_serial_columns_for_transfer(&prepared.ddl,@@ -516,6 +526,7 @@ async fn plan_table_structure(}Ok(PlannedTableStructure {+ oracle_plan,statements,operations,deferred_fk_alters: prepared.deferred_fk_alters,@@ -638,11 +649,18 @@ fn unexpanded_schema_object_notes(TransferObjectSelectionMode::LegacyUnspecified => return vec![UNEXPANDED_OBJECTS_NOTE.to_string()],TransferObjectSelectionMode::Explicit(selections) => selections,};- let mut notes = vec![UNEXPANDED_OBJECTS_NOTE.to_string()];+ let mut notes = Vec::new();for selection in selections {- if selection.object_type == TransferObjectKind::Table || selection.names.is_empty() {+ if matches!(+ selection.object_type,+ TransferObjectKind::Table | TransferObjectKind::Package | TransferObjectKind::PackageBody+ ) || selection.names.is_empty()+ {continue;}+ if notes.is_empty() {+ notes.push(UNEXPANDED_OBJECTS_NOTE.to_string());+ }notes.push(format!("-- {}: {}", preview_object_kind_label(&selection.object_type), selection.names.join(", ")));}notes@@ -655,10 +673,11 @@ fn preview_object_kind_label(kind: &TransferObjectKind) -> &'static str {TransferObjectKind::MaterializedView => "Materialized views",TransferObjectKind::Procedure => "Procedures",TransferObjectKind::Function => "Functions",+ TransferObjectKind::Package => "Packages",+ TransferObjectKind::PackageBody => "Package bodies",TransferObjectKind::Trigger => "Triggers",TransferObjectKind::Sequence => "Sequences",TransferObjectKind::Event => "Events",- TransferObjectKind::Package => "Packages",TransferObjectKind::Synonym => "Synonyms",}}@@ -677,6 +696,34 @@ mod tests {use super::*;use serde_json::json;+ #[test]+ fn internal_table_provenance_is_not_part_of_the_legacy_structure_payload() {+ let table = TransferStructurePreviewTable {+ source_table: "source".into(),+ target_table: "target".into(),+ preexisting: false,+ sql: "CREATE TABLE target (N NUMBER)".into(),+ oracle_plan: Some(ddl_plan::PreparedTableDdl {+ ddl: "CREATE TABLE target (N NUMBER)".into(),+ reused_source_ddl: true,+ deferred_fk_alters: Vec::new(),+ deferred_fk_names: Vec::new(),+ source_evidence: Some(json!({"sourceDdl":"full original input"})),+ }),+ };+ assert_eq!(+ table.oracle_plan.as_ref().unwrap().source_evidence.as_ref().unwrap()["sourceDdl"],+ "full original input"+ );+ assert_eq!(+ serde_json::to_value(&table).unwrap(),+ json!({+ "sourceTable":"source", "targetTable":"target", "preexisting":false,+ "sql":"CREATE TABLE target (N NUMBER)",+ })+ );+ }+#[test]fn structured_ddl_metadata_produces_operation_dtos() {let index = db::IndexInfo {diff --git a/crates/dbx-core/src/data/transfer/xugu_objects.rs b/crates/dbx-core/src/data/transfer/xugu_objects.rsindex b25f56b010..7f7fe9047f 100644--- a/crates/dbx-core/src/data/transfer/xugu_objects.rs+++ b/crates/dbx-core/src/data/transfer/xugu_objects.rs@@ -733,6 +733,9 @@ impl Plan {outcome.transferred.push(label.clone());}progress(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: format!("schema object: {label}"),table_index: request.tables.len(),diff --git a/crates/dbx-core/src/data/transfer_runner.rs b/crates/dbx-core/src/data/transfer_runner.rsindex b538acd808..0e484ac570 100644--- a/crates/dbx-core/src/data/transfer_runner.rs+++ b/crates/dbx-core/src/data/transfer_runner.rs@@ -32,6 +32,9 @@ wherefn take_terminal(&self, transfer_id: &str, total_tables: usize) -> TransferProgress {self.terminal.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take().unwrap_or_else(|| {TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.to_string(),table: String::new(),table_index: total_tables,@@ -82,11 +85,34 @@ 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,- )+ let (routine_context, package_transfer) = match async {+ super::transfer::validate_transfer_database_pair(&request, &source_db_type, &target_db_type)?;+ let routine = crate::schema::oracle_routines::capture_routine_transfer_context(+ &state,+ &request.source_connection_id,+ &request.target_connection_id,+ )+ .await?;+ let mut table_structure =+ if request.oracle_packages.as_ref().is_some_and(|packages| packages.pending_tables.is_some()) {+ Some(+ super::transfer::build_package_transfer_structure(+ &state,+ &request,+ &source_db_type,+ &target_db_type,+ &source_pool_key,+ &target_pool_key,+ )+ .await?,+ )+ } else {+ None+ };+ let packages =+ crate::schema::oracle_routines::claim_transfer_packages(&state, &request, table_structure.as_mut()).await?;+ Ok::<_, crate::schema::oracle_routines::PackageTransferPreflightError>((routine, packages))+ }.await{Ok(context) => context,@@ -95,17 +121,7 @@ wherejournal.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,- };+ return error.into_progress(&request);}};@@ -175,6 +191,9 @@ where&app,history.as_ref(),TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: "schema objects".into(),table_index: 0,@@ -244,6 +263,9 @@ where&app,history.as_ref(),TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: "rename pre-pass".to_string(),table_index: 0,@@ -264,6 +286,9 @@ where&app,history.as_ref(),TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: "rename pre-pass".to_string(),table_index: 0,@@ -304,6 +329,9 @@ where&app,history.as_ref(),TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: "schema dependencies".to_string(),table_index: 0,@@ -324,6 +352,9 @@ where&app,history.as_ref(),TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: "schema dependencies".to_string(),table_index: 0,@@ -358,6 +389,9 @@ where&app,history.as_ref(),TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: "overwrite pre-pass".to_string(),table_index: 0,@@ -381,6 +415,9 @@ where&app,history.as_ref(),TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: table.clone(),table_index: i,@@ -452,6 +489,9 @@ whereemit_progress(&app,TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: table.clone(),table_index: i,@@ -480,6 +520,9 @@ where&app,history.as_ref(),TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: table.clone(),table_index: i,@@ -504,6 +547,9 @@ whereemit_progress(&app,TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: table.clone(),table_index: i,@@ -581,6 +627,9 @@ where&app,history.as_ref(),TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: "schema objects".to_string(),table_index: total_tables,@@ -604,6 +653,9 @@ whereemit_progress(&app,TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: "schema objects".to_string(),table_index: total_tables,@@ -621,6 +673,52 @@ wherefailed_tables.push(format!("schema objects ({})", object_outcome.failed.len()));}+ if let Some(packages) = &package_transfer {+ // A failed prerequisite leaves its actual table/object results intact;+ // no package step is sent, and unsent steps are not counted as writes.+ let (outcome, package_cancelled, preflight_error) = packages+ .run(&state, &request, failed_tables.is_empty(), |progress| emit_progress(&app, progress))+ .await;+ if let Some(error) = preflight_error {+ failed_tables.push(format!("package preflight: {error}"));+ }+ if !outcome.failed.is_empty() {+ failed_tables.push("package objects".into());+ }+ if let Some(journal) = history.as_ref() {+ journal.record_object_outcome(&outcome).await;+ }+ object_outcome.transferred.extend(outcome.transferred);+ object_outcome.skipped.extend(outcome.skipped);+ object_outcome.failed.extend(outcome.failed);+ if package_cancelled {+ if let Some(journal) = history.as_ref() {+ journal.record_schema_objects_error(true).await;+ }+ emit_terminal_progress(+ &app,+ history.as_ref(),+ TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,+ transfer_id: transfer_id.clone(),+ table: "package objects".into(),+ table_index: total_tables,+ total_tables,+ rows_transferred: last_rows_transferred,+ total_rows: last_total_rows,+ status: TransferStatus::Cancelled,+ error: None,+ terminal: true,+ },+ )+ .await;+ super::transfer::clear_cancelled(&transfer_id).await;+ return;+ }+ }+// The rename pre-pass left one backup per rebuilt table. Drop them only now that// every table, every deferred foreign key and every selected schema object has// succeeded — a failure anywhere above keeps the originals recoverable under@@ -659,6 +757,9 @@ where&app,history.as_ref(),TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: transfer_id.clone(),table: String::new(),table_index: total_tables,@@ -698,6 +799,38 @@ mod tests {use crate::models::connection::ConnectionConfig;use serde_json::json;+ #[tokio::test]+ async fn unsupported_package_requests_stop_before_connection_capture_or_any_table_work() {+ let directory = tempfile::tempdir().unwrap();+ let storage = crate::persistence::test_storage::open(&directory.path().join("storage.db")).await.unwrap();+ let state = Arc::new(AppState::new_with_plugin_dir(storage, directory.path().join("plugins")));+ for content in ["structureOnly", "structureAndData", "dataOnly"] {+ let request: TransferRequest = serde_json::from_value(json!({+ "transferId": uuid::Uuid::new_v4().to_string(), "sourceConnectionId": "unconfigured-source",+ "sourceDatabase": "tenant", "sourceSchema": "SOURCE", "targetConnectionId": "unconfigured-target",+ "targetDatabase": "tenant", "targetSchema": "TARGET", "tables": ["must-not-write"],+ "createTable": true, "content": content,+ "objects": [{"objectType":"PACKAGE_BODY", "names":["Pkg.With.Dot😀"]}], "batchSize": 100,+ }))+ .unwrap();+ let terminal = run_transfer(+ state.clone(),+ request,+ DatabaseType::Dameng,+ DatabaseType::Oracle,+ "not-a-source-pool".into(),+ "not-a-target-pool".into(),+ None,+ None,+ |_| panic!("Unsupported package request must stop before progress or writes"),+ )+ .await;+ assert!(terminal.terminal);+ assert!(matches!(terminal.status, TransferStatus::Error));+ assert!(terminal.error.unwrap().contains("actual Oracle or OceanBase Oracle"));+ }+ }+#[tokio::test]async fn empty_data_only_transfer_completes_without_schema_object_progress() {let directory = tempfile::tempdir().unwrap();diff --git a/crates/dbx-core/src/persistence/task_history.rs b/crates/dbx-core/src/persistence/task_history.rsindex 63b1f4c42e..34b71c9b02 100644--- a/crates/dbx-core/src/persistence/task_history.rs+++ b/crates/dbx-core/src/persistence/task_history.rs@@ -292,6 +292,8 @@ pub enum TaskItemKind {MaterializedView,Procedure,Function,+ Package,+ PackageBody,Trigger,Sequence,Event,@@ -306,6 +308,8 @@ impl TaskItemKind {Self::MaterializedView => "materialized_view",Self::Procedure => "procedure",Self::Function => "function",+ Self::Package => "package",+ Self::PackageBody => "package_body",Self::Trigger => "trigger",Self::Sequence => "sequence",Self::Event => "event",@@ -320,6 +324,8 @@ impl TaskItemKind {"materialized_view" => Some(Self::MaterializedView),"procedure" => Some(Self::Procedure),"function" => Some(Self::Function),+ "package" => Some(Self::Package),+ "package_body" => Some(Self::PackageBody),"trigger" => Some(Self::Trigger),"sequence" => Some(Self::Sequence),"event" => Some(Self::Event),@@ -338,6 +344,8 @@ impl TaskItemKind {"MaterializedView" => Self::MaterializedView,"Procedure" => Self::Procedure,"Function" => Self::Function,+ "Package" => Self::Package,+ "PackageBody" => Self::PackageBody,"Trigger" => Self::Trigger,"Sequence" => Self::Sequence,"Event" => Self::Event,@@ -931,6 +939,17 @@ fn to_sqlite_count(value: u64) -> Option<i64> {#[cfg(test)]mod tests {use super::*;++ #[test]+ fn package_history_keeps_the_exact_kind_and_entire_quoted_name() {+ for (kind, name) in [(TaskItemKind::Package, "Package"), (TaskItemKind::PackageBody, "PackageBody")] {+ let actual = TaskItemKind::from_transfer(&format!("{name}:Pkg.With.Dot:😀"));+ assert_eq!(actual, (kind, "Pkg.With.Dot:😀".into()));+ assert_eq!(TaskItemKind::from_storage(kind.as_storage_str()), Some(kind));+ let wire = serde_json::to_string(&kind).unwrap();+ assert_eq!(serde_json::from_str::<TaskItemKind>(&wire).unwrap(), kind);+ }+ }use crate::data::transfer::{TransferColumnNameCase, TransferMode, TransferObjectSelection, TransferOwnershipPolicy, TransferTableNameCase,};@@ -969,6 +988,7 @@ mod tests {]),drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,};let journal =TransferTaskJournal::accept(&storage, &app, &request, TaskLifecycleOwner::Web).await.unwrap().unwrap();@@ -983,6 +1003,9 @@ mod tests {journal.finish_table(0, TaskItemStatus::Failed, None, None).await;journal.finish(&TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: request.transfer_id.clone(),table: "orders".to_string(),table_index: 0,diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex 21c8d0cffc..65e48d703e 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -11989,15 +11989,37 @@ async fn managed_object_source<T: serde::de::DeserializeOwned + Send + 'static>(object_type: &db::ObjectSourceKind,signature: Option<&str>,relation_name: Option<&str>,+ include_source_origin: bool,timeout: Option<Duration>,) -> Result<T, String> {match pool {PoolKind::Agent(client) => {- client- .lock()- .await- .get_object_source_with_identity(database, schema, name, object_type, signature, relation_name, timeout)- .await+ let mut client = client.lock().await;+ if include_source_origin {+ client+ .get_object_source_with_origin(+ database,+ schema,+ name,+ object_type,+ signature,+ relation_name,+ timeout,+ )+ .await+ } else {+ client+ .get_object_source_with_identity(+ database,+ schema,+ name,+ object_type,+ signature,+ relation_name,+ timeout,+ )+ .await+ }}PoolKind::ExternalDriver { config, session, .. } => {let mut params = serde_json::json!({@@ -12011,6 +12033,9 @@ async fn managed_object_source<T: serde::de::DeserializeOwned + Send + 'static>(if let Some(signature) = signature {params["signature"] = serde_json::Value::String(signature.to_string());}+ if include_source_origin {+ params["include_source_origin"] = serde_json::json!(true);+ }session.invoke_with_timeout("getObjectSource", params, timeout).await}_ => Err("Managed object source is not supported for this connection".into()),@@ -12066,6 +12091,7 @@ async fn get_object_source_once(&object_type,signature,None,+ false,agent_metadata_timeout(Some(config.as_ref())),).await?;@@ -12126,6 +12152,7 @@ async fn get_object_source_once(&object_type,signature,relation_name,+ false,agent_metadata_timeout(db_config.as_ref()),).await?;diff --git a/crates/dbx-core/src/schema/oracle_routines.rs b/crates/dbx-core/src/schema/oracle_routines.rsindex 01200695d1..b9459d989c 100644--- a/crates/dbx-core/src/schema/oracle_routines.rs+++ b/crates/dbx-core/src/schema/oracle_routines.rs@@ -16,8 +16,10 @@ const PAGE_SIZE: usize = 256;mod execution;mod transfer;pub(crate) use transfer::{- capture_routine_transfer_context, transfer_oracle_routine_core, RoutineTransferContext, RoutineTransferInput,+ capture_routine_transfer_context, claim_transfer_packages, prepare_transfer_packages, transfer_oracle_routine_core,+ PackageTransferPreflightError, RoutineTransferContext, RoutineTransferInput,};+pub use transfer::{OraclePackageTransferPreview, OraclePackageTransferRequest};mod operations;mod plan;mod readback;@@ -31,7 +33,8 @@ pub use operations::{};pub use plan::{prepare_oracle_routine_plan_core, prepare_oracle_routine_recovery_core, OracleRoutinePlan, OracleRoutinePlanInput,- OracleRoutinePlanStep, RoutinePlanAction, RoutinePlanDraft,+ OracleRoutinePlanStep, PackageBodySource, PackageContractChoice, PackageGrant, PackageGrantSnapshot,+ PackagePlanImpact, RoutinePlanAction, RoutinePlanDraft,};pub use readback::{read_oracle_routine_core, RoutineCompilerMessage, RoutineReadback, RoutineReadbackGoal, RoutineReadbackState,@@ -55,6 +58,75 @@ pub struct RoutineIdentity {pub kind: db::ObjectSourceKind,}+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineSelection {+ pub name: String,+ pub kind: db::ObjectSourceKind,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RoutineReadOptions {+ pub object_kinds: Option<Vec<db::ObjectSourceKind>>,+ pub selected_objects: Option<Vec<RoutineSelection>>,+ pub selected_routines: Option<Vec<String>>,+}++impl RoutineReadOptions {+ fn kinds(&self) -> &[db::ObjectSourceKind] {+ self.object_kinds.as_deref().unwrap_or(&[db::ObjectSourceKind::Procedure, db::ObjectSourceKind::Function])+ }++ fn inventory_kinds(&self) -> Vec<db::ObjectSourceKind> {+ let mut kinds = self.kinds().to_vec();+ if kinds.iter().any(|kind| matches!(kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody)) {+ for kind in [db::ObjectSourceKind::Package, db::ObjectSourceKind::PackageBody] {+ if !kinds.contains(&kind) {+ kinds.push(kind);+ }+ }+ }+ kinds+ }++ fn validate(&self) -> Result<(), String> {+ if self.kinds().iter().any(|kind| {+ !matches!(+ kind,+ db::ObjectSourceKind::Procedure+ | db::ObjectSourceKind::Function+ | db::ObjectSourceKind::Package+ | db::ObjectSourceKind::PackageBody+ )+ }) {+ return Err("Strict program inventory supports only procedures, functions and packages".into());+ }+ if self.selected_routines.is_some()+ && (self.selected_objects.is_some()+ || self+ .kinds()+ .iter()+ .any(|kind| matches!(kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody)))+ {+ return Err("Package selection requires exact selected objects instead of legacy routine names".into());+ }+ if self.selected_objects.as_ref().is_some_and(|objects| {+ objects.iter().any(|object| object.name.is_empty() || !self.kinds().contains(&object.kind))+ }) {+ return Err("Selected program identities must belong to the requested object kinds".into());+ }+ Ok(())+ }++ fn reads(&self, identity: &RoutineIdentity) -> bool {+ if let Some(objects) = &self.selected_objects {+ return objects.iter().any(|object| object.name == identity.name);+ }+ self.selected_routines.as_ref().is_none_or(|names| names.contains(&identity.name))+ }+}+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct RoutineVersion {@@ -97,6 +169,8 @@ pub enum RoutineReadState {pub struct RoutineObjectSnapshot {pub version: RoutineVersion,pub source: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub source_origin: Option<SourceOrigin>,pub source_complete: bool,pub dependencies: Vec<RoutineDependency>,pub dependencies_complete: bool,@@ -176,11 +250,15 @@ struct SourceReply {object: db::ObjectSource,#[serde(flatten)]flags: ReadFlags,+ #[serde(default, alias = "sourceOrigin")]+ source_origin: Option<SourceOrigin>,}-#[derive(Clone, Copy)]-enum SourceOrigin {+#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+pub enum SourceOrigin {OracleDictionary,+ #[serde(rename = "oceanbase-dictionary")]OceanBaseDictionary,OracleMetadata,}@@ -256,6 +334,7 @@ impl RoutineCatalog for LiveCatalog<'_> {&identity.kind,None,None,+ true,agent_metadata_timeout(Some(self.config)),).await@@ -278,6 +357,24 @@ pub async fn load_selected_schema_diff_routines_core(schema: &str,selected_routines: Option<&[String]>,) -> Result<RoutineSnapshot, String> {+ load_schema_diff_routines_with_options_core(+ state,+ connection_id,+ database,+ schema,+ RoutineReadOptions { selected_routines: selected_routines.map(<[String]>::to_vec), ..Default::default() },+ )+ .await+}++pub async fn load_schema_diff_routines_with_options_core(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ options: RoutineReadOptions,+) -> Result<RoutineSnapshot, String> {+ options.validate()?;if schema.is_empty() {return Err("Select an exact Oracle routine owner".into());}@@ -292,7 +389,7 @@ pub async fn load_selected_schema_diff_routines_core(generation: lifecycle.generation(),};let catalog = LiveCatalog { state, endpoint: &endpoint, config: &config };- let mut snapshot = collect_selected_snapshot(&catalog, endpoint.clone(), origin, selected_routines).await;+ let mut snapshot = collect_snapshot_with_options(&catalog, endpoint.clone(), origin, &options).await;if !state.connection_lifecycle_is_current(connection_id, &lifecycle) {invalidate_snapshot_endpoint(&mut snapshot);}@@ -328,6 +425,8 @@ fn kind_name(kind: &db::ObjectSourceKind) -> &'static str {match kind {db::ObjectSourceKind::Procedure => "PROCEDURE",db::ObjectSourceKind::Function => "FUNCTION",+ db::ObjectSourceKind::Package => "PACKAGE",+ db::ObjectSourceKind::PackageBody => "PACKAGE BODY",_ => unreachable!("routine identities are validated on collection"),}}@@ -346,12 +445,13 @@ fn issue(stage: &str, message: impl Into<String>) -> RoutineReadIssue {RoutineReadIssue { stage: stage.into(), code: code.into(), message }}-fn inventory_sql(owner: &str, dba: bool, after_id: u64) -> String {+fn inventory_sql(owner: &str, dba: bool, after_id: u64, kinds: &[db::ObjectSourceKind]) -> String {let view = if dba { "SYS.DBA_OBJECTS" } else { "ALL_OBJECTS" };+ let kinds = kinds.iter().map(|kind| literal(kind_name(kind))).collect::<Vec<_>>().join(", ");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') \+ FROM {view} WHERE OWNER = {} AND OBJECT_TYPE IN ({kinds}) \AND OBJECT_ID > {after_id} ORDER BY OBJECT_ID) WHERE ROWNUM <= {PAGE_SIZE}",literal(owner),)@@ -362,13 +462,21 @@ struct InventoryRead {error: Option<String>,}-async fn inventory(catalog: &impl RoutineCatalog, owner: &str, dba: bool) -> InventoryRead {+async fn inventory(+ catalog: &impl RoutineCatalog,+ owner: &str,+ dba: bool,+ kinds: &[db::ObjectSourceKind],+) -> InventoryRead {+ if kinds.is_empty() {+ return InventoryRead { objects: Vec::new(), error: None };+ }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?;+ let reply = catalog.query(&inventory_sql(owner, dba, after_id, kinds)).await?;if reply.rows.len() > PAGE_SIZE {return Err("Routine inventory exceeded its page size".into());}@@ -377,11 +485,17 @@ async fn inventory(catalog: &impl RoutineCatalog, owner: &str, dba: bool) -> Invlet kind = match reply.text(row, "OBJECT_TYPE")?.as_str() {"PROCEDURE" => db::ObjectSourceKind::Procedure,"FUNCTION" => db::ObjectSourceKind::Function,+ "PACKAGE" => db::ObjectSourceKind::Package,+ "PACKAGE BODY" => db::ObjectSourceKind::PackageBody,_ => 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)) {+ if !kinds.contains(&identity.kind)+ || 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;@@ -413,9 +527,13 @@ fn identity_filter(identity: &RoutineIdentity) -> String {fn source_integrity_sql(identity: &RoutineIdentity, origin: SourceOrigin) -> String {if matches!(origin, SourceOrigin::OracleMetadata) {+ let metadata_kind = match identity.kind {+ db::ObjectSourceKind::Package => "PACKAGE_SPEC".into(),+ _ => kind_name(&identity.kind).replace(' ', "_"),+ };return format!("SELECT LENGTH(DBMS_METADATA.GET_DDL({}, {}, {})) SOURCE_CHARS FROM DUAL",- literal(kind_name(&identity.kind)),+ literal(&metadata_kind),literal(&identity.name),literal(&identity.owner));@@ -444,6 +562,19 @@ async fn check_source(origin: SourceOrigin,) -> Result<(), String> {reply.flags.check()?;+ let origin = match reply.source_origin {+ Some(SourceOrigin::OracleDictionary) if endpoint.database_type != DatabaseType::Oracle => {+ return Err("Routine source origin does not match the database product".into());+ }+ Some(SourceOrigin::OceanBaseDictionary) if endpoint.database_type != DatabaseType::OceanbaseOracle => {+ return Err("Routine source origin does not match the database product".into());+ }+ Some(actual) => actual,+ None if matches!(identity.kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody) => {+ return Err("Strict package source requires the getter's actual source origin".into());+ }+ None => origin,+ };if reply.object.name != identity.name|| reply.object.schema.as_deref() != Some(&identity.owner)|| reply.object.object_type != identity.kind@@ -465,6 +596,9 @@ async fn check_source(let row = &lengths.rows[0];let mut expected = lengths.integer(row, "SOURCE_CHARS")?;let actual = match origin {+ SourceOrigin::OracleMetadata if endpoint.database_type == DatabaseType::OceanbaseOracle => {+ reply.object.source.chars().count() as u64+ }SourceOrigin::OracleMetadata => reply.object.source.encode_utf16().count() as u64,SourceOrigin::OracleDictionary => reply.object.source.chars().count() as u64,SourceOrigin::OceanBaseDictionary => {@@ -541,6 +675,7 @@ async fn dependencies(}}+#[cfg(test)]#[cfg(test)]async fn collect_snapshot(catalog: &impl RoutineCatalog,@@ -550,12 +685,29 @@ async fn collect_snapshot(collect_selected_snapshot(catalog, endpoint, origin, None).await}+#[cfg(test)]async fn collect_selected_snapshot(catalog: &impl RoutineCatalog,endpoint: RoutineEndpoint,origin: SourceOrigin,selected_routines: Option<&[String]>,) -> RoutineSnapshot {+ collect_snapshot_with_options(+ catalog,+ endpoint,+ origin,+ &RoutineReadOptions { selected_routines: selected_routines.map(<[String]>::to_vec), ..Default::default() },+ )+ .await+}++async fn collect_snapshot_with_options(+ catalog: &impl RoutineCatalog,+ endpoint: RoutineEndpoint,+ origin: SourceOrigin,+ options: &RoutineReadOptions,+) -> RoutineSnapshot {+ let kinds = options.inventory_kinds();let mut snapshot = RoutineSnapshot {endpoint,state: RoutineReadState::Failed,@@ -577,13 +729,13 @@ async fn collect_selected_snapshot(}};let mut dba = login != snapshot.endpoint.schema;- let mut initial_read = inventory(catalog, &snapshot.endpoint.schema, dba).await;+ let mut initial_read = inventory(catalog, &snapshot.endpoint.schema, dba, &kinds).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;+ let visible = inventory(catalog, &snapshot.endpoint.schema, false, &kinds).await;for object in visible.objects {if !initial_read.objects.iter().any(|known| object_key(&known.identity) == object_key(&object.identity)){@@ -600,19 +752,34 @@ async fn collect_selected_snapshot(let mut object = RoutineObjectSnapshot {version,source: None,+ source_origin: 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)) {+ if !options.reads(&object.version.identity) {snapshot.objects.push(object);continue;}match catalog.source(&object.version.identity).await {Ok(reply) => {object.source = Some(reply.object.source.clone());+ if matches!(+ object.version.identity.kind,+ db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody+ ) {+ object.source_origin = reply.source_origin;+ }match check_source(catalog, &snapshot.endpoint, &object.version.identity, &reply, origin).await {+ Ok(())+ if matches!(+ object.version.identity.kind,+ db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody+ ) =>+ {+ object.source_complete = true;+ }Ok(()) => {// A second full read also detects replacement within LAST_DDL_TIME's second.match catalog.source(&object.version.identity).await {@@ -621,6 +788,7 @@ async fn collect_selected_snapshot(&& second.object.name == reply.object.name&& second.object.schema == reply.object.schema&& second.object.object_type == reply.object.object_type+ && second.source_origin == reply.source_origin&& second.object.source == reply.object.source =>{object.source_complete = true@@ -645,7 +813,36 @@ async fn collect_selected_snapshot(}snapshot.objects.push(object);}- let after_read = inventory(catalog, &snapshot.endpoint.schema, dba).await;+ for object in &mut snapshot.objects {+ if !object.source_complete+ || !matches!(+ object.version.identity.kind,+ db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody+ )+ {+ continue;+ }+ match catalog.source(&object.version.identity).await {+ Ok(second)+ if second.flags.check().is_ok()+ && second.object.name == object.version.identity.name+ && second.object.schema.as_deref() == Some(object.version.identity.owner.as_str())+ && second.object.object_type == object.version.identity.kind+ && second.source_origin == object.source_origin+ && object.source.as_deref() == Some(second.object.source.as_str()) => {}+ Ok(_) => {+ object.source_complete = false;+ object+ .issues+ .push(issue("source", "Package source changed or became incomplete while collecting its pair"));+ }+ Err(error) => {+ object.source_complete = false;+ object.issues.push(issue("source", error));+ }+ }+ }+ let after_read = inventory(catalog, &snapshot.endpoint.schema, dba, &kinds).await;if let Some(error) = after_read.error {snapshot.enumeration_complete = false;snapshot.issues.push(issue("inventory", error));@@ -673,6 +870,7 @@ async fn collect_selected_snapshot(snapshot.objects.push(RoutineObjectSnapshot {version,source: None,+ source_origin: None,source_complete: false,dependencies: Vec::new(),dependencies_complete: false,diff --git a/crates/dbx-core/src/schema/oracle_routines/execution.rs b/crates/dbx-core/src/schema/oracle_routines/execution.rsindex 6cc53d19d6..6675b84b97 100644--- a/crates/dbx-core/src/schema/oracle_routines/execution.rs+++ b/crates/dbx-core/src/schema/oracle_routines/execution.rs@@ -16,6 +16,9 @@ pub struct OracleRoutineSaveInput {pub identity: RoutineIdentity,pub sql: String,#[serde(default)]+ pub require_absent: bool,+ pub prerequisite_operation_id: Option<String>,+ #[serde(default)]pub supersedes_operation_id: Option<String>,}@@ -47,9 +50,101 @@ pub(super) async fn prepare_definition() -> 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();+ let require_absent = require_absent || input.require_absent;+ if matches!(input.identity.kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody) {+ let (database_type, _) = routine_source_origin(&config)?;+ let target = RoutineEndpoint {+ connection_id: input.connection_id.clone(),+ database: input.database.clone(),+ schema: input.identity.owner.clone(),+ database_type,+ generation,+ };+ let catalog = LiveCatalog { state, endpoint: &target, config: &config };+ return prepare_package_definition(+ &state.routine_operations,+ &catalog,+ input,+ &target,+ &config,+ require_absent,+ )+ .await;+ }prepare_bound_definition(state, input, config, generation, require_absent)}+async fn prepare_package_definition(+ registry: &RoutineOperationRegistry,+ catalog: &impl RoutineCatalog,+ input: OracleRoutineSaveInput,+ target: &RoutineEndpoint,+ config: &ConnectionConfig,+ require_absent: bool,+) -> Result<RoutineOperationRecord, String> {+ let (database_type, origin) = routine_source_origin(config)?;+ if input.identity.owner.is_empty()+ || input.identity.name.is_empty()+ || target.schema != input.identity.owner+ || target.connection_id != input.connection_id+ || target.database != input.database+ {+ return Err("A package save requires its exact original target, 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),+ )?;+ if let Some(id) = &input.prerequisite_operation_id {+ let specification = registry.binding_for_readback(id)?;+ if input.identity.kind != db::ObjectSourceKind::PackageBody+ || specification.identity.kind != db::ObjectSourceKind::Package+ || specification.identity.owner != input.identity.owner+ || specification.identity.name != input.identity.name+ || specification.target != *target+ || specification.expected_config != *config+ || !registry.observe(id).operation.is_some_and(|record| record.verified())+ {+ return Err(+ "The new package body requires its original verified specification operation on the same target".into(),+ );+ }+ }+ let compare = plan::package_save_preflight(catalog, target, &input.identity, origin).await?;+ if require_absent {+ if !matches!(&compare.target, plan::ExpectedRoutine::Absent(_)) {+ return Err("The new package save target already exists; refresh without overwriting it".into());+ }+ if input.identity.kind == db::ObjectSourceKind::Package+ && !matches!(&compare.package.as_ref().unwrap().pair.body, plan::ExpectedRoutine::Absent(_))+ {+ return Err(+ "The new package name has a residual body; refresh without overwriting that package pair".into()+ );+ }+ }+ registry.prepare_replacing(+ RoutineWriteBinding {+ target: target.clone(),+ identity: input.identity,+ goal: RoutineReadbackGoal::Definition { sql: input.sql.clone() },+ sql: input.sql,+ expected_config: config.clone(),+ require_absent,+ compare: Some(compare),+ prerequisite_operation_ids: input.prerequisite_operation_id.into_iter().collect(),+ package_effect_operation_ids: Vec::new(),+ },+ input.supersedes_operation_id.as_deref(),+ )+}+pub(super) fn prepare_bound_definition(state: &AppState,input: OracleRoutineSaveInput,@@ -68,7 +163,14 @@ fn prepare_bound_definition_with_pins(require_absent: bool,pins: usize,) -> Result<RoutineOperationRecord, String> {+ let require_absent = require_absent || input.require_absent;+ if input.prerequisite_operation_id.is_some() {+ return Err("A package specification prerequisite applies only to controlled package-body saves".into());+ }let (database_type, _) = routine_source_origin(&config)?;+ if !matches!(input.identity.kind, db::ObjectSourceKind::Procedure | db::ObjectSourceKind::Function) {+ return Err("Standalone routine saves require an exact procedure/function identity".into());+ }if input.identity.owner.is_empty() || input.identity.name.is_empty() {return Err("A routine write requires its exact original owner and name".into());}@@ -101,6 +203,7 @@ fn prepare_bound_definition_with_pins(require_absent,compare: None,prerequisite_operation_ids: Vec::new(),+ package_effect_operation_ids: Vec::new(),},supersedes: input.supersedes_operation_id,}],@@ -157,22 +260,12 @@ async fn perform_write(state: &AppState, id: &str, binding: RoutineWriteBinding)};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;+ let source = binding.compare.as_ref().and_then(|compare| compare.source.as_ref()).map(|before| LiveCatalog {+ state,+ endpoint: &before.endpoint,+ config: &before.config,+ });+ run_write(&state.routine_operations, id, &binding, &io, source.as_ref(), origin).await;drop(registered);}@@ -208,8 +301,7 @@ pub async fn observe_oracle_routine_operation_core(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;+ current_readback(&state.routine_operations, operation_id, &binding, &catalog, origin).await;// Updating current contents deliberately does not change lifecycle.state.routine_operations.update_readback(operation_id, current);}@@ -218,6 +310,30 @@ pub async fn observe_oracle_routine_operation_core(state.routine_operations.observe(operation_id)}+async fn current_readback(+ registry: &RoutineOperationRegistry,+ id: &str,+ binding: &RoutineWriteBinding,+ catalog: &impl RoutineCatalog,+ origin: SourceOrigin,+) -> RoutineReadback {+ let mut current =+ readback::readback(catalog, &binding.target, binding.identity.clone(), &binding.goal, origin).await;+ if binding.identity.kind == db::ObjectSourceKind::PackageBody {+ match registry+ .package_effects_for_write(id)+ .and_then(|effects| plan::observed_body_preflight(binding, &effects))+ {+ Ok(compare) => plan::validate_post_state(binding, compare.as_ref(), &mut current),+ Err(error) => {+ current.state = RoutineReadbackState::ReadbackFailed;+ current.issues.push(issue("package-contract", error));+ }+ }+ }+ current+}+#[async_trait::async_trait]trait RoutineWriteIo: RoutineCatalog {async fn check_write(&self, sql: &str) -> Result<(), String>;@@ -313,11 +429,19 @@ async fn run_write(id: &str,binding: &RoutineWriteBinding,io: &impl RoutineWriteIo,+ source: Option<&impl RoutineCatalog>,origin: SourceOrigin,) {let mut guard = WriteGuard { registry, id, complete: false };+ let mut effective_compare = None;let preflight: Result<(), String> = async {io.check_write(&binding.sql).await?;+ let effects=registry.package_effects_for_write(id)?;+ effective_compare=plan::effective_preflight(binding,&effects)?;+ if matches!(binding.identity.kind,db::ObjectSourceKind::Package|db::ObjectSourceKind::PackageBody) && !effective_compare.as_ref().is_some_and(|compare|compare.package.is_some()) {+ return Err("Package dispatch requires its frozen pair approval".into());+ }+ if let Some(compare)=&effective_compare {plan::verify_compare_preflight(source,io,&binding.target,compare,origin).await?;}if binding.require_absent {let before = readback::readback(io,@@ -332,6 +456,7 @@ async fn run_write(}}for (prerequisite, before) in registry.prerequisites_for_write(id)? {+ let before=plan::effective_prerequisite(&prerequisite,&before,&effects)?;let current = readback::readback(io,&prerequisite.target,@@ -341,10 +466,7 @@ async fn run_write().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+ || !plan::same_observation(¤t,&before){return Err(format!("Prerequisite routine {}.{} changed since its verified deployment; refresh and validate the remaining draft without replaying completed steps",@@ -385,13 +507,16 @@ async fn run_write(// 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 =+ let mut current =readback::readback(io, &binding.target, binding.identity.clone(), &binding.goal, origin).await;+ plan::validate_post_state(binding, effective_compare.as_ref(), &mut current);registry.terminal(id, acknowledged, Some(current), error);}}guard.complete = true;}+#[cfg(test)]+mod package_tests;#[cfg(test)]mod tests;diff --git a/crates/dbx-core/src/schema/oracle_routines/execution/package_tests.rs b/crates/dbx-core/src/schema/oracle_routines/execution/package_tests.rsnew file mode 100644index 0000000000..b96578380b--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/execution/package_tests.rs@@ -0,0 +1,1025 @@+use super::super::plan;+use super::*;+use serde_json::json;+use std::sync::Mutex;++#[derive(Clone)]+struct Program {+ source: String,+ id: u64,+ time: u64,+ invalid: bool,+}+struct PackageIo {+ owner: &'static str,+ database_type: DatabaseType,+ programs: Mutex<BTreeMap<String, Program>>,+ writes: Mutex<Vec<String>>,+ invalidate_old_body: bool,+ fail_body: Mutex<bool>,+ unknown_body: bool,+ change_spec_during_body: bool,+ grants: Mutex<Vec<plan::PackageGrant>>,+ forbid_global_incoming: bool,+}++impl PackageIo {+ fn new(owner: &'static str, present: bool) -> Self {+ let mut programs = BTreeMap::new();+ if present {+ programs.insert("PACKAGE".into(),Program {source:format!("CREATE OR REPLACE PACKAGE \"{owner}\".PKG AS g NUMBER := 1; FUNCTION f(p NUMBER) RETURN NUMBER; END PKG;"),id:11,time:1,invalid:false});+ programs.insert("PACKAGE BODY".into(),Program {source:format!("CREATE OR REPLACE PACKAGE BODY \"{owner}\".PKG AS FUNCTION f(p NUMBER) RETURN NUMBER IS BEGIN RETURN p + g; END f; END PKG;"),id:12,time:1,invalid:false});+ }+ Self {+ owner,+ database_type: DatabaseType::OceanbaseOracle,+ programs: Mutex::new(programs),+ writes: Mutex::new(Vec::new()),+ invalidate_old_body: false,+ fail_body: Mutex::new(false),+ unknown_body: false,+ change_spec_during_body: false,+ grants: Mutex::new(Vec::new()),+ forbid_global_incoming: false,+ }+ }++ fn endpoint(&self) -> RoutineEndpoint {+ RoutineEndpoint {+ connection_id: self.owner.into(),+ database: "tenant".into(),+ schema: self.owner.into(),+ database_type: self.database_type,+ generation: 1,+ }+ }+ fn config(&self) -> ConnectionConfig {+ let mut config: ConnectionConfig = serde_json::from_value(json!({"id":self.owner,"name":"fixture","db_type":"oceanbase-oracle","host":"localhost","port":2881,"username":self.owner,"password":"","database":null})).unwrap();+ config.db_type = self.database_type;+ config+ }+ fn origin(&self) -> SourceOrigin {+ if self.database_type == DatabaseType::Oracle {+ SourceOrigin::OracleDictionary+ } else {+ SourceOrigin::OceanBaseDictionary+ }+ }+ fn snapshot(&self) -> RoutineSnapshot {+ RoutineSnapshot {+ endpoint: self.endpoint(),+ state: RoutineReadState::Complete,+ enumeration_complete: true,+ issues: Vec::new(),+ objects: self+ .programs+ .lock()+ .unwrap()+ .iter()+ .map(|(kind, program)| RoutineObjectSnapshot {+ version: RoutineVersion {+ identity: RoutineIdentity {+ owner: self.owner.into(),+ name: "PKG".into(),+ kind: if kind == "PACKAGE" {+ db::ObjectSourceKind::Package+ } else {+ db::ObjectSourceKind::PackageBody+ },+ },+ object_id: program.id.to_string(),+ status: if program.invalid { "INVALID" } else { "VALID" }.into(),+ last_ddl_time: program.time.to_string(),+ },+ source: Some(program.source.clone()),+ source_origin: Some(self.origin()),+ source_complete: true,+ dependencies: Vec::new(),+ dependencies_complete: true,+ issues: Vec::new(),+ })+ .collect(),+ }+ }+}++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 PackageIo {+ async fn source(&self, identity: &RoutineIdentity) -> Result<SourceReply, String> {+ assert_eq!(identity.owner, self.owner);+ assert_eq!(identity.name, "PKG");+ let programs = self.programs.lock().unwrap();+ let program = programs.get(kind_name(&identity.kind)).ok_or("Source not found")?;+ Ok(serde_json::from_value(json!({"name":identity.name,"schema":identity.owner,"object_type":identity.kind,"source":program.source,"source_origin":self.origin()})).unwrap())+ }+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ assert!(sql.starts_with("SELECT "));+ if sql.contains("LOGIN_OWNER") {+ return Ok(reply(&["LOGIN_OWNER"], vec![vec![json!(self.owner)]]));+ }+ let programs = self.programs.lock().unwrap();+ if sql.contains("OBJECTS") {+ return Ok(reply(+ &["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "STATUS", "LAST_DDL_TIME"],+ programs+ .iter()+ .map(|(kind, program)| {+ vec![+ json!(self.owner),+ json!("PKG"),+ json!(kind),+ json!(program.id),+ json!(if program.invalid { "INVALID" } else { "VALID" }),+ json!(program.time.to_string()),+ ]+ })+ .collect(),+ ));+ }+ let kind = if sql.contains("TYPE = 'PACKAGE BODY'") { "PACKAGE BODY" } else { "PACKAGE" };+ if sql.contains("SOURCE_ROWS") {+ let source = &programs.get(kind).unwrap().source;+ 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!(source.chars().count()),+ json!(0),+ json!(0),+ json!("CREATE PACKAGE"),+ ]],+ ));+ }+ if sql.contains("ALL_ERRORS") {+ return Ok(reply(+ &["SEQUENCE", "ATTRIBUTE", "LINE", "POSITION", "TEXT"],+ if programs.get(kind).is_some_and(|program| program.invalid) {+ vec![vec![+ json!(0),+ json!("ERROR"),+ json!(1),+ json!(0),+ json!("PLS-00382: simulated compiler boundary failure"),+ ]]+ } else {+ Vec::new()+ },+ ));+ }+ if sql.contains("DBA_DEPENDENCIES") {+ assert!(!self.forbid_global_incoming, "Ordinary package saving must not require global caller visibility");+ return Ok(reply(&["OWNER", "NAME", "TYPE", "REFERENCED_LINK_NAME", "DEPENDENCY_TYPE", "RN"], Vec::new()));+ }+ if sql.contains("ALL_DEPENDENCIES") {+ return Ok(reply(+ &[+ "REFERENCED_OWNER",+ "REFERENCED_NAME",+ "REFERENCED_TYPE",+ "REFERENCED_LINK_NAME",+ "DEPENDENCY_TYPE",+ "RN",+ ],+ Vec::new(),+ ));+ }+ if sql.contains("ALL_TAB_PRIVS") {+ return Ok(reply(+ &["GRANTOR", "GRANTEE", "PRIVILEGE", "GRANTABLE", "RN"],+ self.grants+ .lock()+ .unwrap()+ .iter()+ .enumerate()+ .map(|(index, grant)| {+ vec![+ json!(grant.grantor),+ json!(grant.grantee),+ json!(grant.privilege),+ json!(if grant.grantable { "YES" } else { "NO" }),+ json!(index + 1),+ ]+ })+ .collect(),+ ));+ }+ panic!("Unexpected package query: {sql}")+ }+}++#[async_trait::async_trait]+impl RoutineWriteIo for PackageIo {+ async fn check_write(&self, _: &str) -> Result<(), String> {+ Ok(())+ }+ async fn write(&self, sql: &str) -> Result<db::QueryResult, QueryExecutionError> {+ self.writes.lock().unwrap().push(sql.into());+ let body = sql.contains("PACKAGE BODY");+ let kind = if body { "PACKAGE BODY" } else { "PACKAGE" };+ let mut programs = self.programs.lock().unwrap();+ if sql.starts_with("DROP ") {+ programs.remove(kind);+ if !body {+ programs.remove("PACKAGE BODY");+ self.grants.lock().unwrap().clear();+ }+ } else {+ let previous = programs.get(kind).cloned();+ programs.insert(+ kind.into(),+ Program {+ source: sql.into(),+ id: previous.as_ref().map_or(if body { 12 } else { 11 }, |program| program.id),+ time: previous.map_or(1, |program| program.time + 1),+ invalid: body && *self.fail_body.lock().unwrap(),+ },+ );+ if !body && self.invalidate_old_body {+ if let Some(body) = programs.get_mut("PACKAGE BODY") {+ body.invalid = true;+ body.time += 1;+ }+ }+ if body && self.change_spec_during_body {+ if let Some(spec) = programs.get_mut("PACKAGE") {+ spec.source = spec.source.replace("g NUMBER := 1", "g NUMBER := 9");+ spec.time += 1;+ }+ }+ }+ if body && self.unknown_body {+ return Err(QueryExecutionError::Agent(AgentCallError::Transport {+ message: "package response lost after dispatch".into(),+ }));+ }+ Ok(serde_json::from_value(json!({"columns":[],"rows":[],"affected_rows":0,"execution_time_ms":1})).unwrap())+ }+}++fn drafts(action: RoutinePlanAction) -> Vec<RoutinePlanDraft> {+ [db::ObjectSourceKind::Package, db::ObjectSourceKind::PackageBody]+ .into_iter()+ .map(|kind| RoutinePlanDraft {+ identity: RoutineIdentity { owner: "OWNER".into(), name: "PKG".into(), kind },+ action,+ source_name: None,+ sql: None,+ baseline_operation_id: None,+ supersedes_operation_id: None,+ package_body_source: None,+ package_contract: None,+ confirm_package_pair: true,+ })+ .collect()+}++async fn prepare(+ registry: &RoutineOperationRegistry,+ source: &PackageIo,+ target: &PackageIo,+ input: OracleRoutinePlanInput,+) -> OracleRoutinePlan {+ plan::prepare_with_catalogs(registry, source, target, input, &source.config(), &target.config()).await.unwrap()+}+async fn execute(+ registry: &RoutineOperationRegistry,+ source: &PackageIo,+ target: &PackageIo,+ step: &OracleRoutinePlanStep,+) -> RoutineOperationRecord {+ execute_approval(registry, Some(source), target, step.operation.as_ref().unwrap(), &step.sql).await+}++async fn execute_approval(+ registry: &RoutineOperationRegistry,+ source: Option<&PackageIo>,+ target: &PackageIo,+ approval: &RoutineOperationRecord,+ sql: &str,+) -> RoutineOperationRecord {+ let id = &approval.operation_id;+ match registry.begin(id, sql).unwrap() {+ BeginRoutineOperation::Dispatch(binding) => {+ run_write(registry, id, &binding, target, source, target.origin()).await+ }+ BeginRoutineOperation::Existing(_) => {}+ }+ registry.observe(id).operation.unwrap()+}++async fn save_approval(+ registry: &RoutineOperationRegistry,+ target: &PackageIo,+ kind: db::ObjectSourceKind,+ sql: &str,+ require_absent: bool,+) -> Result<RoutineOperationRecord, String> {+ prepare_package_definition(+ registry,+ target,+ OracleRoutineSaveInput {+ connection_id: target.owner.into(),+ database: "tenant".into(),+ identity: RoutineIdentity { owner: target.owner.into(), name: "PKG".into(), kind },+ sql: sql.into(),+ require_absent,+ prerequisite_operation_id: None,+ supersedes_operation_id: None,+ },+ &target.endpoint(),+ &target.config(),+ require_absent,+ )+ .await+}++#[tokio::test]+async fn ordinary_package_save_uses_pair_freeze_without_static_comparison_or_global_caller_requirements() {+ let mut target = PackageIo::new("OWNER", true);+ target.forbid_global_incoming = true;+ let registry = RoutineOperationRegistry::default();+ let sql = "CREATE OR REPLACE PACKAGE BODY \"OWNER\".PKG AS FUNCTION f(p NUMBER) RETURN NUMBER IS BEGIN EXECUTE IMMEDIATE 'SELECT 1 FROM DUAL'; RETURN p; END f; END PKG;";+ let approval = save_approval(®istry, &target, db::ObjectSourceKind::PackageBody, sql, false).await.unwrap();+ let result = execute_approval(®istry, None, &target, &approval, sql).await;+ assert!(result.verified(), "{}", result.failure_message());+ assert!(result.readback.unwrap().package_companion.unwrap().source.unwrap().contains("g NUMBER := 1"));+ assert_eq!(target.writes.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn ordinary_specification_save_reports_old_body_invalidation_and_body_save_keeps_actual_invalid_spec_result() {+ let mut target = PackageIo::new("OWNER", true);+ target.forbid_global_incoming = true;+ target.invalidate_old_body = true;+ let registry = RoutineOperationRegistry::default();+ let spec = target.programs.lock().unwrap()["PACKAGE"].source.replace("g NUMBER := 1", "g NUMBER := 2");+ let approval = save_approval(®istry, &target, db::ObjectSourceKind::Package, &spec, false).await.unwrap();+ let result = execute_approval(®istry, None, &target, &approval, &spec).await;+ assert!(result.verified());+ assert_eq!(result.readback.unwrap().package_companion.unwrap().state, RoutineReadbackState::Invalid);+ target.programs.lock().unwrap().get_mut("PACKAGE").unwrap().invalid = true;+ let body = target.programs.lock().unwrap()["PACKAGE BODY"].source.clone();+ let approval = save_approval(®istry, &target, db::ObjectSourceKind::PackageBody, &body, false).await.unwrap();+ let result = execute_approval(®istry, None, &target, &approval, &body).await;+ assert!(result.dispatched && result.acknowledged);+ assert!(!result.verified());+ assert_eq!(result.readback.unwrap().package_companion.unwrap().state, RoutineReadbackState::Invalid);+ assert_eq!(target.writes.lock().unwrap().len(), 2);+}++#[tokio::test]+async fn ordinary_save_detects_companion_change_and_save_as_absence_does_not_overwrite_existing_or_orphan_pair() {+ let target = PackageIo::new("OWNER", true);+ let registry = RoutineOperationRegistry::default();+ let body = target.programs.lock().unwrap()["PACKAGE BODY"].source.clone();+ let approval = save_approval(®istry, &target, db::ObjectSourceKind::PackageBody, &body, false).await.unwrap();+ target.programs.lock().unwrap().get_mut("PACKAGE").unwrap().source.push_str(" -- third party");+ let result = execute_approval(®istry, None, &target, &approval, &body).await;+ assert!(!result.dispatched);+ let spec = "CREATE PACKAGE \"OWNER\".PKG AS g NUMBER := 1; END PKG;";+ assert!(save_approval(®istry, &target, db::ObjectSourceKind::Package, spec, true).await.is_err());+ target.programs.lock().unwrap().remove("PACKAGE");+ assert!(save_approval(®istry, &target, db::ObjectSourceKind::Package, spec, true).await.is_err());+ assert!(target.writes.lock().unwrap().is_empty());+}++#[tokio::test]+async fn ordinary_package_creation_freezes_empty_pair_and_supports_legacy_save_request_shape() {+ let mut target = PackageIo::new("OWNER", false);+ target.forbid_global_incoming = true;+ let registry = RoutineOperationRegistry::default();+ let sql = "CREATE PACKAGE \"OWNER\".PKG AS g NUMBER := 1; END PKG;";+ let input: OracleRoutineSaveInput = serde_json::from_value(json!({"connectionId":"OWNER","database":"tenant","identity":{"owner":"OWNER","name":"PKG","kind":"PACKAGE"},"sql":sql})).unwrap();+ assert!(!input.require_absent);+ let approval = save_approval(®istry, &target, db::ObjectSourceKind::Package, sql, true).await.unwrap();+ assert!(execute_approval(®istry, None, &target, &approval, sql).await.verified());+ assert_eq!(target.writes.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn save_as_body_binds_the_original_verified_specification_not_a_changed_spec_captured_during_preparation() {+ for change in [false, true] {+ let target = PackageIo::new("OWNER", false);+ let registry = RoutineOperationRegistry::default();+ let spec_sql = "CREATE PACKAGE \"OWNER\".PKG AS g NUMBER := 1; FUNCTION f(p NUMBER) RETURN NUMBER; END PKG;";+ let specification =+ save_approval(®istry, &target, db::ObjectSourceKind::Package, spec_sql, true).await.unwrap();+ let specification = execute_approval(®istry, None, &target, &specification, spec_sql).await;+ assert!(specification.verified());+ if change {+ let mut programs = target.programs.lock().unwrap();+ let source = programs["PACKAGE"].source.replace("g NUMBER := 1", "g NUMBER := 9");+ programs.get_mut("PACKAGE").unwrap().source = source;+ }+ let body_sql = "CREATE PACKAGE BODY \"OWNER\".PKG AS FUNCTION f(p NUMBER) RETURN NUMBER IS BEGIN RETURN p + g; END f; END PKG;";+ let body = prepare_package_definition(+ ®istry,+ &target,+ OracleRoutineSaveInput {+ connection_id: target.owner.into(),+ database: "tenant".into(),+ identity: RoutineIdentity {+ owner: "OWNER".into(),+ name: "PKG".into(),+ kind: db::ObjectSourceKind::PackageBody,+ },+ sql: body_sql.into(),+ require_absent: true,+ prerequisite_operation_id: Some(specification.operation_id.clone()),+ supersedes_operation_id: None,+ },+ &target.endpoint(),+ &target.config(),+ true,+ )+ .await+ .unwrap();+ let result = execute_approval(®istry, None, &target, &body, body_sql).await;+ assert_eq!(result.dispatched, !change, "{}", result.failure_message());+ assert_eq!(result.verified(), !change);+ assert_eq!(target.writes.lock().unwrap().len(), if change { 1 } else { 2 });+ }+}++#[tokio::test]+async fn a_new_pair_dispatches_each_approved_statement_once_without_replaying_specification() {+ let source = PackageIo::new("SOURCE", true);+ let target = PackageIo::new("OWNER", false);+ let registry = RoutineOperationRegistry::default();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: target.snapshot(),+ drafts: drafts(RoutinePlanAction::Create),+ },+ )+ .await;+ assert!(plan.ready, "{:?}", plan.steps);+ assert!(execute(®istry, &source, &target, &plan.steps[0]).await.verified());+ assert!(execute(®istry, &source, &target, &plan.steps[1]).await.verified());+ assert!(execute(®istry, &source, &target, &plan.steps[0]).await.verified());+ assert_eq!(target.writes.lock().unwrap().len(), 2);+}++#[tokio::test]+async fn cross_product_packages_require_final_target_drafts_and_keep_full_validation_in_both_directions() {+ for (source_type, target_type) in+ [(DatabaseType::Oracle, DatabaseType::OceanbaseOracle), (DatabaseType::OceanbaseOracle, DatabaseType::Oracle)]+ {+ let mut source = PackageIo::new("SOURCE", true);+ source.database_type = source_type;+ let mut target = PackageIo::new("OWNER", false);+ target.database_type = target_type;+ let registry = RoutineOperationRegistry::default();+ let initial = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: target.snapshot(),+ drafts: drafts(RoutinePlanAction::Create),+ },+ )+ .await;+ assert!(!initial.ready);+ assert!(initial.steps.iter().all(|step| step.operation.is_none()+ && step.source_original.is_some()+ && step.issues.iter().any(|issue| issue.message.contains("explicitly reviewed target draft"))));+ assert!(target.writes.lock().unwrap().is_empty());+ let mut invalid = drafts(RoutinePlanAction::Create);+ for (draft, step) in invalid.iter_mut().zip(&initial.steps) {+ draft.sql = Some(step.sql.clone());+ }+ invalid[1].sql.as_mut().unwrap().push_str(" BEGIN NULL; END;");+ let rejected = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput { source: source.snapshot(), target: target.snapshot(), drafts: invalid },+ )+ .await;+ assert!(!rejected.ready);+ assert!(rejected.steps.iter().all(|step| step.operation.is_none()));+ let mut reviewed = drafts(RoutinePlanAction::Create);+ for (draft, step) in reviewed.iter_mut().zip(&initial.steps) {+ draft.sql = Some(step.sql.clone());+ }+ let approved = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput { source: source.snapshot(), target: target.snapshot(), drafts: reviewed },+ )+ .await;+ assert!(approved.ready, "{:?}", approved.steps);+ for step in &approved.steps {+ let result = execute(®istry, &source, &target, step).await;+ assert!(result.verified(), "{}", result.failure_message());+ }+ assert_eq!(target.writes.lock().unwrap().len(), 2);+ }+}++#[tokio::test]+async fn cross_product_package_attributes_remain_copyable_and_do_not_become_silent_semantic_conversions() {+ for clause in ["AUTHID CURRENT_USER", "ACCESSIBLE BY (PROCEDURE CALLER)", "SHARING = METADATA", "EDITIONABLE"] {+ let mut source = PackageIo::new("SOURCE", true);+ source.database_type = DatabaseType::Oracle;+ let original = {+ let mut programs = source.programs.lock().unwrap();+ let spec = programs.get_mut("PACKAGE").unwrap();+ spec.source = if clause == "EDITIONABLE" {+ spec.source.replace("REPLACE PACKAGE", "REPLACE EDITIONABLE PACKAGE")+ } else {+ spec.source.replace(" AS ", &format!(" {clause} AS "))+ };+ spec.source.clone()+ };+ let target = PackageIo::new("OWNER", false);+ let registry = RoutineOperationRegistry::default();+ let result = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: target.snapshot(),+ drafts: drafts(RoutinePlanAction::Create),+ },+ )+ .await;+ assert!(!result.ready);+ assert!(result.steps.iter().all(|step| step.operation.is_none()));+ let spec = result.steps.iter().find(|step| step.identity.kind == db::ObjectSourceKind::Package).unwrap();+ assert_eq!(spec.source_original.as_deref(), Some(original.as_str()));+ assert!(spec.sql.contains(clause), "The editable target draft lost {clause}: {}", spec.sql);+ assert!(!spec.issues.is_empty());+ let mut reviewed = drafts(RoutinePlanAction::Create);+ for (draft, step) in reviewed.iter_mut().zip(&result.steps) {+ draft.sql = Some(step.sql.clone());+ }+ let manual = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput { source: source.snapshot(), target: target.snapshot(), drafts: reviewed },+ )+ .await;+ assert!(!manual.ready, "Manual review does not establish unknown {clause} capabilities");+ assert!(manual.steps.iter().all(|step| step.operation.is_none()));+ assert!(target.writes.lock().unwrap().is_empty());+ }+}++async fn recovery(+ registry: &RoutineOperationRegistry,+ target: &PackageIo,+ id: &str,+) -> Result<OracleRoutinePlan, String> {+ plan::prepare_package_recovery(registry, id, target, &target.config(), SourceOrigin::OceanBaseDictionary).await+}++#[tokio::test]+async fn recovery_of_a_repaired_orphan_retains_its_original_body_without_approving_a_destructive_drop() {+ let source = PackageIo::new("SOURCE", true);+ let target = PackageIo::new("OWNER", true);+ let original_body = {+ let mut programs = target.programs.lock().unwrap();+ programs.remove("PACKAGE");+ let body = programs.get_mut("PACKAGE BODY").unwrap();+ body.invalid = true;+ body.source = body.source.replace("p + g", "p + g + 55");+ body.source.clone()+ };+ let registry = RoutineOperationRegistry::default();+ let mut selected = drafts(RoutinePlanAction::Create);+ selected[1].action = RoutinePlanAction::Replace;+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput { source: source.snapshot(), target: target.snapshot(), drafts: selected },+ )+ .await;+ assert!(plan.ready, "{:?}", plan.steps);+ let specification = execute(®istry, &source, &target, &plan.steps[0]).await;+ assert!(specification.verified(), "{}", specification.failure_message());+ assert!(execute(®istry, &source, &target, &plan.steps[1]).await.verified());+ let restored = recovery(®istry, &target, &specification.operation_id).await.unwrap();+ assert!(!restored.ready, "Orphan recovery must not approve dropping its backed-up body");+ assert!(restored.steps.iter().all(|step| step.operation.is_none() && !step.recovery_complete));+ let body = restored.steps.iter().find(|step| step.identity.kind == db::ObjectSourceKind::PackageBody).unwrap();+ assert_eq!(body.source_original.as_deref(), Some(original_body.as_str()));+ assert!(body.sql.contains("p + g + 55"));+ assert_eq!(target.writes.lock().unwrap().len(), 2);+}++fn grant() -> plan::PackageGrant {+ plan::PackageGrant {+ grantor: "OWNER".into(),+ grantee: "READER".into(),+ privilege: "EXECUTE".into(),+ grantable: false,+ }+}++#[tokio::test]+async fn new_pair_recovery_uses_known_body_receipt_and_dispatches_only_one_package_drop() {+ for fail in [false, true] {+ let source = PackageIo::new("SOURCE", true);+ let target = PackageIo::new("OWNER", false);+ *target.fail_body.lock().unwrap() = fail;+ let registry = RoutineOperationRegistry::default();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: target.snapshot(),+ drafts: drafts(RoutinePlanAction::Create),+ },+ )+ .await;+ let spec = execute(®istry, &source, &target, &plan.steps[0]).await;+ execute(®istry, &source, &target, &plan.steps[1]).await;+ let undo = recovery(®istry, &target, &spec.operation_id).await.unwrap();+ assert!(undo.ready, "{:?}", undo.steps);+ assert_eq!(undo.steps.len(), 1);+ assert_eq!(undo.steps[0].identity.kind, db::ObjectSourceKind::Package);+ assert_eq!(undo.steps[0].action, RoutinePlanAction::Delete);+ assert!(execute(®istry, &source, &target, &undo.steps[0]).await.verified());+ assert!(target.programs.lock().unwrap().is_empty());+ assert_eq!(target.writes.lock().unwrap().len(), 3);+ }+}++#[tokio::test]+async fn replacement_recovery_reuses_pair_contract_and_restores_both_old_definitions_without_copying_grants() {+ let source = PackageIo::new("SOURCE", true);+ {+ let mut programs = source.programs.lock().unwrap();+ programs.get_mut("PACKAGE").unwrap().source =+ programs["PACKAGE"].source.replace("g NUMBER := 1", "g NUMBER := 2");+ programs.get_mut("PACKAGE BODY").unwrap().source =+ programs["PACKAGE BODY"].source.replace("p + g", "p + g + 2");+ }+ let target = PackageIo::new("OWNER", true);+ target.grants.lock().unwrap().push(grant());+ let before = target.snapshot();+ let registry = RoutineOperationRegistry::default();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: before.clone(),+ drafts: drafts(RoutinePlanAction::Replace),+ },+ )+ .await;+ let spec = execute(®istry, &source, &target, &plan.steps[0]).await;+ assert!(spec.verified());+ assert!(execute(®istry, &source, &target, &plan.steps[1]).await.verified());+ let undo = recovery(®istry, &target, &spec.operation_id).await.unwrap();+ assert!(undo.ready, "{:?}", undo.steps);+ assert_eq!(undo.steps.len(), 2);+ assert_eq!(undo.steps[0].identity.kind, db::ObjectSourceKind::Package);+ for step in &undo.steps {+ assert!(execute(®istry, &source, &target, step).await.verified());+ }+ let after = target.snapshot();+ for old in before.objects {+ let current = after.objects.iter().find(|object| object.version.identity == old.version.identity).unwrap();+ let comparable = |object: &RoutineObjectSnapshot| {+ dbx_sql::object_source_sql::comparable_oracle_routine_definition(+ dbx_sql::object_source_sql::OracleRoutineDefinitionInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: object.version.identity.kind.clone(),+ source_owner: "OWNER".into(),+ target_owner: "OWNER".into(),+ name: "PKG".into(),+ source: object.source.clone().unwrap(),+ replace: true,+ },+ )+ .unwrap()+ };+ assert_eq!(comparable(current), comparable(&old));+ }+ assert_eq!(*target.grants.lock().unwrap(), vec![grant()]);+ assert_eq!(target.writes.lock().unwrap().len(), 4);+}++#[tokio::test]+async fn recovery_cannot_claim_a_third_party_pair_even_after_successful_readonly_observation() {+ let source = PackageIo::new("SOURCE", true);+ let target = PackageIo::new("OWNER", false);+ let registry = RoutineOperationRegistry::default();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: target.snapshot(),+ drafts: drafts(RoutinePlanAction::Create),+ },+ )+ .await;+ execute(®istry, &source, &target, &plan.steps[0]).await;+ let body = execute(®istry, &source, &target, &plan.steps[1]).await;+ target.programs.lock().unwrap().get_mut("PACKAGE BODY").unwrap().source.push_str(" -- third party");+ let binding = registry.binding_for_readback(&body.operation_id).unwrap();+ let now =+ current_readback(®istry, &body.operation_id, &binding, &target, SourceOrigin::OceanBaseDictionary).await;+ registry.update_readback(&body.operation_id, now);+ assert!(recovery(®istry, &target, &body.operation_id).await.is_err());+ assert_eq!(target.writes.lock().unwrap().len(), 2);+}++#[tokio::test]+async fn unknown_related_body_blocks_recovery_and_new_grants_block_recovery_deletion() {+ for unknown in [false, true] {+ let source = PackageIo::new("SOURCE", true);+ let mut target = PackageIo::new("OWNER", false);+ target.unknown_body = unknown;+ let registry = RoutineOperationRegistry::default();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: target.snapshot(),+ drafts: drafts(RoutinePlanAction::Create),+ },+ )+ .await;+ let spec = execute(®istry, &source, &target, &plan.steps[0]).await;+ execute(®istry, &source, &target, &plan.steps[1]).await;+ if unknown {+ assert!(recovery(®istry, &target, &spec.operation_id).await.is_err());+ } else {+ target.grants.lock().unwrap().push(grant());+ let undo = recovery(®istry, &target, &spec.operation_id).await.unwrap();+ assert!(!undo.ready);+ assert!(undo.steps[0].issues.iter().any(|issue| issue.message.contains("New grants")));+ assert!(undo.steps[0].operation.is_none());+ }+ assert_eq!(target.writes.lock().unwrap().len(), 2);+ }+}++#[tokio::test]+async fn dropped_pair_recovery_restores_empty_grant_pair_but_preserves_nonempty_grant_gap() {+ for has_grant in [false, true] {+ let source = PackageIo::new("SOURCE", false);+ let target = PackageIo::new("OWNER", true);+ if has_grant {+ target.grants.lock().unwrap().push(grant());+ }+ let registry = RoutineOperationRegistry::default();+ let spec = drafts(RoutinePlanAction::Delete).remove(0);+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput { source: source.snapshot(), target: target.snapshot(), drafts: vec![spec] },+ )+ .await;+ let dropped = execute(®istry, &source, &target, &plan.steps[0]).await;+ assert!(dropped.verified());+ let undo = recovery(®istry, &target, &dropped.operation_id).await.unwrap();+ assert_eq!(undo.steps.len(), 2);+ assert_eq!(undo.ready, !has_grant, "{:?}", undo.steps);+ if has_grant {+ assert!(undo.steps.iter().all(|step| step.operation.is_none() && !step.recovery_complete));+ assert!(undo.steps[0].package_impact.as_ref().unwrap().grants.as_ref().unwrap().grants.contains(&grant()));+ } else {+ for step in &undo.steps {+ assert!(execute(®istry, &source, &target, step).await.verified());+ }+ assert_eq!(target.programs.lock().unwrap().len(), 2);+ }+ }+}++#[tokio::test]+async fn recovery_after_spec_only_success_rebuilds_old_body_and_rejects_changes_after_approval() {+ for invalidate in [false, true] {+ let source = PackageIo::new("SOURCE", true);+ {+ let mut programs = source.programs.lock().unwrap();+ let definition = programs["PACKAGE"].source.replace("g NUMBER := 1", "g NUMBER := 2");+ programs.get_mut("PACKAGE").unwrap().source = definition;+ }+ let mut target = PackageIo::new("OWNER", true);+ target.invalidate_old_body = invalidate;+ let registry = RoutineOperationRegistry::default();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: target.snapshot(),+ drafts: drafts(RoutinePlanAction::Replace),+ },+ )+ .await;+ let spec = execute(®istry, &source, &target, &plan.steps[0]).await;+ assert!(spec.verified());+ let undo = recovery(®istry, &target, &spec.operation_id).await.unwrap();+ assert!(undo.ready, "{:?}", undo.steps);+ assert_eq!(undo.steps.len(), 2);+ if invalidate {+ target.programs.lock().unwrap().get_mut("PACKAGE BODY").unwrap().source.push_str(" -- concurrent");+ let stopped = execute(®istry, &source, &target, &undo.steps[0]).await;+ assert!(!stopped.dispatched);+ assert_eq!(target.writes.lock().unwrap().len(), 1);+ } else {+ for step in &undo.steps {+ assert!(execute(®istry, &source, &target, step).await.verified());+ }+ assert_eq!(target.writes.lock().unwrap().len(), 3);+ }+ }+}++#[tokio::test]+async fn known_spec_post_state_allows_old_body_invalidation_but_not_unapproved_definition_changes() {+ for invalidate in [false, true] {+ let source = PackageIo::new("SOURCE", true);+ let mut target = PackageIo::new("OWNER", true);+ target.invalidate_old_body = invalidate;+ let registry = RoutineOperationRegistry::default();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: target.snapshot(),+ drafts: drafts(RoutinePlanAction::Replace),+ },+ )+ .await;+ assert!(plan.ready, "{:?}", plan.steps);+ assert!(execute(®istry, &source, &target, &plan.steps[0]).await.verified());+ assert!(execute(®istry, &source, &target, &plan.steps[1]).await.verified());+ assert_eq!(target.writes.lock().unwrap().len(), 2);+ }+}++#[tokio::test]+async fn companion_edit_after_specification_stops_body_before_dispatch() {+ let source = PackageIo::new("SOURCE", true);+ let target = PackageIo::new("OWNER", true);+ let registry = RoutineOperationRegistry::default();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: target.snapshot(),+ drafts: drafts(RoutinePlanAction::Replace),+ },+ )+ .await;+ assert!(execute(®istry, &source, &target, &plan.steps[0]).await.verified());+ target.programs.lock().unwrap().get_mut("PACKAGE BODY").unwrap().source.push_str(" -- third party");+ let body = execute(®istry, &source, &target, &plan.steps[1]).await;+ assert!(!body.dispatched);+ assert_eq!(body.lifecycle, RoutineOperationLifecycle::Terminal);+ assert_eq!(target.writes.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn body_failure_preserves_verified_spec_and_correction_only_dispatches_a_new_body() {+ let source = PackageIo::new("SOURCE", true);+ let target = PackageIo::new("OWNER", false);+ *target.fail_body.lock().unwrap() = true;+ let registry = RoutineOperationRegistry::default();+ let before = target.snapshot();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: before.clone(),+ drafts: drafts(RoutinePlanAction::Create),+ },+ )+ .await;+ let spec = execute(®istry, &source, &target, &plan.steps[0]).await;+ assert!(spec.verified());+ let failed = execute(®istry, &source, &target, &plan.steps[1]).await;+ assert!(failed.dispatched && failed.acknowledged);+ assert_eq!(failed.readback.as_ref().unwrap().state, RoutineReadbackState::Invalid);+ *target.fail_body.lock().unwrap() = false;+ let mut correction = drafts(RoutinePlanAction::Replace).pop().unwrap();+ correction.baseline_operation_id = Some(failed.operation_id.clone());+ let corrected = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput { source: source.snapshot(), target: before, drafts: vec![correction] },+ )+ .await;+ assert!(corrected.ready, "{:?}", corrected.steps);+ assert!(execute(®istry, &source, &target, &corrected.steps[0]).await.verified());+ let writes = target.writes.lock().unwrap();+ assert_eq!(writes.len(), 3);+ assert_eq!(writes.iter().filter(|sql| !sql.contains("PACKAGE BODY")).count(), 1);+}++#[tokio::test]+async fn specification_change_during_body_write_is_kept_in_readback_but_never_reported_verified() {+ let source = PackageIo::new("SOURCE", true);+ let mut target = PackageIo::new("OWNER", true);+ target.change_spec_during_body = true;+ let registry = RoutineOperationRegistry::default();+ let body = drafts(RoutinePlanAction::Replace).pop().unwrap();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput { source: source.snapshot(), target: target.snapshot(), drafts: vec![body] },+ )+ .await;+ assert!(plan.ready, "{:?}", plan.steps);+ let result = execute(®istry, &source, &target, &plan.steps[0]).await;+ assert!(result.dispatched && result.acknowledged);+ assert!(!result.verified());+ let readback = result.readback.unwrap();+ assert_eq!(readback.state, RoutineReadbackState::ReadbackFailed);+ assert!(readback.package_companion.unwrap().source.unwrap().contains("g NUMBER := 9"));+ let binding = registry.binding_for_readback(&result.operation_id).unwrap();+ let refreshed =+ current_readback(®istry, &result.operation_id, &binding, &target, SourceOrigin::OceanBaseDictionary).await;+ assert_eq!(refreshed.state, RoutineReadbackState::ReadbackFailed);+ assert!(refreshed.package_companion.as_ref().unwrap().source.as_ref().unwrap().contains("g NUMBER := 9"));+ registry.update_readback(&result.operation_id, refreshed);+ assert!(!registry.observe(&result.operation_id).operation.unwrap().verified());+ assert_eq!(target.writes.lock().unwrap().len(), 1);+}++#[tokio::test]+async fn unknown_body_outcome_is_not_unlocked_by_matching_readback_or_a_new_specification_id() {+ let source = PackageIo::new("SOURCE", true);+ let mut target = PackageIo::new("OWNER", false);+ target.unknown_body = true;+ let registry = RoutineOperationRegistry::default();+ let plan = prepare(+ ®istry,+ &source,+ &target,+ OracleRoutinePlanInput {+ source: source.snapshot(),+ target: target.snapshot(),+ drafts: drafts(RoutinePlanAction::Create),+ },+ )+ .await;+ assert!(execute(®istry, &source, &target, &plan.steps[0]).await.verified());+ let unknown = execute(®istry, &source, &target, &plan.steps[1]).await;+ assert_eq!(unknown.lifecycle, RoutineOperationLifecycle::Unproven);+ assert!(unknown.dispatched && !unknown.acknowledged);+ let body_binding = registry.binding_for_readback(&unknown.operation_id).unwrap();+ let current = readback::readback(+ &target,+ &target.endpoint(),+ body_binding.identity,+ &body_binding.goal,+ SourceOrigin::OceanBaseDictionary,+ )+ .await;+ assert_eq!(current.state, RoutineReadbackState::Verified);+ registry.update_readback(&unknown.operation_id, current);+ assert_eq!(+ execute(®istry, &source, &target, &plan.steps[1]).await.lifecycle,+ RoutineOperationLifecycle::Unproven+ );+ let mut retry = registry.binding_for_readback(&plan.steps[0].operation.as_ref().unwrap().operation_id).unwrap();+ retry.package_effect_operation_ids.clear();+ retry.prerequisite_operation_ids.clear();+ let retry = registry.prepare(retry);+ assert!(+ matches!(registry.begin(&retry.operation_id,&plan.steps[0].sql).unwrap(),BeginRoutineOperation::Existing(record) if !record.dispatched)+ );+ assert_eq!(target.writes.lock().unwrap().len(), 2);+}diff --git a/crates/dbx-core/src/schema/oracle_routines/execution/tests.rs b/crates/dbx-core/src/schema/oracle_routines/execution/tests.rsindex 03290eab25..edf5dc42b3 100644--- a/crates/dbx-core/src/schema/oracle_routines/execution/tests.rs+++ b/crates/dbx-core/src/schema/oracle_routines/execution/tests.rs@@ -5,6 +5,26 @@ use std::sync::Mutex;const SOURCE: &str = "CREATE OR REPLACE FUNCTION \"Read.Func\" RETURN NUMBER AS BEGIN RETURN 1; END";+#[tokio::test]+async fn definition_grammar_extension_does_not_enable_unpaired_controlled_package_saves() {+ let dir = tempfile::tempdir().unwrap();+ let storage = crate::persistence::test_storage::open(&dir.path().join("storage.db")).await.unwrap();+ let state = AppState::new(storage);+ for kind in [db::ObjectSourceKind::Package, db::ObjectSourceKind::PackageBody] {+ let input = OracleRoutineSaveInput {+ connection_id: "target".into(),+ database: "tenant".into(),+ identity: RoutineIdentity { owner: "OWNER".into(), name: "P".into(), kind: kind.clone() },+ sql: format!("CREATE OR REPLACE {} \"OWNER\".P AS END P;", kind_name(&kind)),+ require_absent: false,+ prerequisite_operation_id: None,+ supersedes_operation_id: None,+ };+ let result = prepare_bound_definition(&state, input, binding().expected_config, 1, false);+ assert!(result.is_err(), "package approval needs its frozen pair lifecycle");+ }+}+#[tokio::test]async fn actual_execute_entry_pins_terminal_readback_through_cancel_or_final_response() {use crate::db::agent_driver::{AgentDriverClient, AgentLaunchSpec, AgentRuntimeClient};@@ -102,6 +122,8 @@ for line in sys.stdin:database: "tenant".into(),identity: bound.identity,sql: SOURCE.into(),+ require_absent: false,+ prerequisite_operation_id: None,supersedes_operation_id: None,},)@@ -270,7 +292,7 @@ fn binding() -> RoutineWriteBinding {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(),+ compare: None, prerequisite_operation_ids: Vec::new(), package_effect_operation_ids:Vec::new(),}}@@ -278,7 +300,7 @@ 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;+ run_write(®istry, &operation.operation_id, &binding, io, None::<&Io>, SourceOrigin::OceanBaseDictionary).await;registry.observe(&operation.operation_id).operation.unwrap()}@@ -354,9 +376,9 @@ async fn an_abandoned_worker_does_not_release_a_possibly_dispatched_target() {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 },- )+ tokio::spawn(async move {+ run_write(®istry, &id, &bound, io.as_ref(), None::<&Io>, SourceOrigin::OceanBaseDictionary).await+ })};io.entered.notified().await;worker.abort();@@ -400,9 +422,9 @@ async fn losing_only_the_readback_preserves_the_original_terminal_write_receipt(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 },- )+ tokio::spawn(async move {+ run_write(®istry, &id, &bound, io.as_ref(), None::<&Io>, SourceOrigin::OceanBaseDictionary).await+ })};io.readback_entered.notified().await;worker.abort();@@ -459,7 +481,15 @@ async fn review_regression_completed_prerequisite_is_rechecked_before_the_next_dlet 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;+ run_write(+ ®istry,+ &first.operation_id,+ &previous,+ &original_io,+ None::<&Io>,+ SourceOrigin::OceanBaseDictionary,+ )+ .await;assert!(registry.observe(&first.operation_id).operation.unwrap().verified());let prerequisite = Io {@@ -498,7 +528,7 @@ async fn review_regression_completed_prerequisite_is_rechecked_before_the_next_dprerequisite,next: Io { name: "Next.Func".into(), source_text: next_source, ..Default::default() },};- run_write(®istry, &operation.operation_id, &next, &io, SourceOrigin::OceanBaseDictionary).await;+ run_write(®istry, &operation.operation_id, &next, &io, None::<&Io>, SourceOrigin::OceanBaseDictionary).await;let result = registry.observe(&operation.operation_id).operation.unwrap();if change == "unchanged" {assert!(result.verified(), "{}", result.failure_message());diff --git a/crates/dbx-core/src/schema/oracle_routines/operations.rs b/crates/dbx-core/src/schema/oracle_routines/operations.rsindex 47030e98a3..a8b7381ab1 100644--- a/crates/dbx-core/src/schema/oracle_routines/operations.rs+++ b/crates/dbx-core/src/schema/oracle_routines/operations.rs@@ -20,6 +20,7 @@ pub(super) struct RoutineWriteBinding {pub require_absent: bool,pub compare: Option<super::plan::ComparePreflight>,pub prerequisite_operation_ids: Vec<String>,+ pub package_effect_operation_ids: Vec<String>,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]@@ -66,6 +67,13 @@ impl RoutineOperationRecord {format!("{} {}:{} {}", message.attribute, message.line, message.position, message.text)}));details.extend(readback.issues.iter().map(|issue| issue.message.clone()));+ if let Some(companion) = &readback.package_companion {+ details.push(format!("Package companion {:?}: {:?}", companion.identity.kind, companion.state));+ details.extend(companion.compiler_messages.iter().map(|message| {+ format!("{} {}:{} {}", message.attribute, message.line, message.position, message.text)+ }));+ details.extend(companion.issues.iter().map(|issue| issue.message.clone()));+ }}details.join("\n")}@@ -85,6 +93,7 @@ struct StoredOperation {// 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>,+ acknowledged_post_state: Option<RoutineReadback>,// Web session tokens remain private, in memory, and outside Debug/Serialize.owner_scope: Option<String>,client_retained: bool,@@ -262,6 +271,38 @@ impl RoutineOperationRegistry {}).collect()}+ pub(super) fn package_effects_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 package operation is unavailable; do not replay the write")?;+ let mut effects = Vec::new();+ for id in &operation.binding.package_effect_operation_ids {+ let related = operations+ .get(id)+ .filter(|related| {+ related.owner_scope == operation.owner_scope+ && related.binding.target == operation.binding.target+ && related.binding.expected_config == operation.binding.expected_config+ })+ .ok_or(+ "An approved package step is unavailable on the original target; validate the remaining draft",+ )?;+ match related.record.lifecycle {+ RoutineOperationLifecycle::Prepared => {},+ RoutineOperationLifecycle::Running | RoutineOperationLifecycle::Unproven => return Err("An approved related package step has not established its terminal result; observe its original operation ID".into()),+ RoutineOperationLifecycle::Terminal if !related.record.dispatched => return Err("A related package approval did not complete; validate the remaining plan without replaying completed steps".into()),+ RoutineOperationLifecycle::Terminal if related.record.verified() => effects.push((related.binding.clone(),related.verified_post_state.clone().ok_or("The related package step has no immutable verified pair result")?)),+ RoutineOperationLifecycle::Terminal => return Err("An approved package step failed verification; correct its body or refresh the remaining plan without replaying completed steps".into()),+ }+ }+ Ok(effects)+ }+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")?;@@ -279,7 +320,8 @@ impl RoutineOperationRegistry {readback: Option<RoutineReadback>,error: Option<String>,) {- self.update_record(operation_id, |record| {+ let mut operations = self.operations.lock().unwrap_or_else(|error| error.into_inner());+ self.update_record_locked_with_receipt(&mut operations, operation_id, true, |record| {record.lifecycle = RoutineOperationLifecycle::Terminal;record.acknowledged = acknowledged;record.readback = readback;@@ -287,6 +329,24 @@ impl RoutineOperationRegistry {});}+ pub(super) fn recovery_post_state(&self, operation_id: &str) -> Result<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 operation is unavailable; only observe its original ID")?;+ if operation.record.lifecycle != RoutineOperationLifecycle::Terminal+ || !operation.record.dispatched+ || !operation.record.acknowledged+ {+ return Err("Recovery requires an acknowledged terminal write on the original target".into());+ }+ operation+ .acknowledged_post_state+ .clone()+ .ok_or("The acknowledged write has no immutable post-state; refresh and review the target instead".into())+ }+pub(super) fn not_started(&self, operation_id: &str, error: String) {self.update_record(operation_id, |record| {record.lifecycle = RoutineOperationLifecycle::Terminal;@@ -325,7 +385,7 @@ mod tests {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() }+ 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(), package_effect_operation_ids:Vec::new() }}pub(super) fn verified_readback() -> RoutineReadback {@@ -335,12 +395,38 @@ mod tests {exists: Some(true),version: None,source: Some("expected source".into()),+ source_origin: None,+ package_companion: None,definition_matches: Some(true),compiler_messages: Vec::new(),issues: Vec::new(),}}+ #[test]+ fn package_and_body_share_the_existing_physical_namespace_lock_without_a_second_lock_key() {+ let registry = RoutineOperationRegistry::default();+ let mut specification = binding();+ specification.identity.kind = crate::db::ObjectSourceKind::Package;+ let specification = registry.prepare(specification);+ registry.begin(&specification.operation_id, "approved SQL").unwrap();+ let mut body = binding();+ body.identity.kind = crate::db::ObjectSourceKind::PackageBody;+ body.target.connection_id = "another-connection".into();+ body.expected_config.id = "another-connection".into();+ body.expected_config.username = "ANOTHER_LOGIN".into();+ for unknown in [false, true] {+ if unknown {+ registry.mark_dispatched(&specification.operation_id).unwrap();+ registry.waiting_lost(&specification.operation_id, "outcome unknown".into());+ }+ let body = registry.prepare(body.clone());+ assert!(+ matches!(registry.begin(&body.operation_id, "approved SQL").unwrap(), BeginRoutineOperation::Existing(record) if record.lifecycle == RoutineOperationLifecycle::Terminal && !record.dispatched && record.error.as_deref().is_some_and(|error| error.contains("held")))+ );+ }+ }+#[test]fn oversized_approval_is_rejected_without_retaining_its_payload() {let registry = RoutineOperationRegistry::default();diff --git a/crates/dbx-core/src/schema/oracle_routines/operations/retention.rs b/crates/dbx-core/src/schema/oracle_routines/operations/retention.rsindex e72ab50e2f..007f15764d 100644--- a/crates/dbx-core/src/schema/oracle_routines/operations/retention.rs+++ b/crates/dbx-core/src/schema/oracle_routines/operations/retention.rs@@ -75,6 +75,8 @@ fn fallback_readback(identity: &RoutineIdentity) -> RoutineReadback {exists: None,version: None,source: None,+ source_origin: None,+ package_companion: None,definition_matches: None,compiler_messages: Vec::new(),issues: vec![super::super::issue("capacity", RESULT_CAPACITY_ERROR)],@@ -85,6 +87,7 @@ fn charge(operation: &StoredOperation,record: &RoutineOperationRecord,verified: &Option<RoutineReadback>,+ acknowledged: &Option<RoutineReadback>,limit: usize,) -> Result<usize, String> {let parts = [@@ -94,6 +97,7 @@ fn charge(json_bytes(&operation.binding, limit)?,json_bytes(record, limit)?.max(operation.receipt_floor),json_bytes(verified, limit)?,+ json_bytes(acknowledged, limit)?,];parts.into_iter().try_fold(0usize, |total, value| {total.checked_add(value).filter(|total| *total <= limit).ok_or_else(|| CAPACITY_ERROR.into())@@ -119,7 +123,12 @@ fn sweep(operations: &mut HashMap<String, StoredOperation>, additional_roots: &Hpending.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 {+ for prerequisite in operation+ .binding+ .prerequisite_operation_ids+ .iter()+ .chain(&operation.binding.package_effect_operation_ids)+ {if keep.insert(prerequisite.clone()) {pending.push(prerequisite.clone());}@@ -216,6 +225,7 @@ impl RoutineOperationRegistry {binding: request.binding,record,verified_post_state: None,+ acknowledged_post_state: None,owner_scope: owner_scope.clone(),client_retained: false,unclaimed_until: (pins == 0).then(|| Instant::now() + Duration::from_secs(60)),@@ -223,7 +233,7 @@ impl RoutineOperationRegistry {charge: 0,receipt_floor: floor,};- operation.charge = charge(&operation, &operation.record, &None, self.limits.single)?;+ operation.charge = charge(&operation, &operation.record, &None, &None, self.limits.single)?;candidates.push((operation, request.supersedes));}let mut operations = self.operations.lock().unwrap_or_else(|error| error.into_inner());@@ -250,7 +260,13 @@ impl RoutineOperationRegistry {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)?;+ let bytes = charge(+ original,+ &record,+ &original.verified_post_state,+ &original.acknowledged_post_state,+ self.limits.single,+ )?;replacements.insert(id.clone(), (record, bytes));}}@@ -261,12 +277,21 @@ impl RoutineOperationRegistry {return Err("Routine prerequisite approval is unavailable".into());}}+ if operation+ .binding+ .package_effect_operation_ids+ .iter()+ .any(|id| !new_ids.contains(id) || id == &operation.record.operation_id)+ {+ return Err("Package effects must refer to other approvals in the same atomic preparation batch".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());+ inputs.extend(operation.binding.package_effect_operation_ids.iter().cloned());}sweep(&mut operations, &inputs);let total = operations@@ -306,6 +331,16 @@ impl RoutineOperationRegistry {operations: &mut HashMap<String, StoredOperation>,id: &str,update: impl FnOnce(&mut RoutineOperationRecord),+ ) {+ self.update_record_locked_with_receipt(operations, id, false, update);+ }++ pub(super) fn update_record_locked_with_receipt(+ &self,+ operations: &mut HashMap<String, StoredOperation>,+ id: &str,+ capture_receipt: bool,+ update: impl FnOnce(&mut RoutineOperationRecord),) {sweep(operations, &HashSet::from([id.to_owned()]));let other_bytes = operations@@ -323,11 +358,22 @@ impl RoutineOperationRegistry {} else {operation.verified_post_state.clone()};+ let acknowledged = if capture_receipt+ && operation.acknowledged_post_state.is_none()+ && record.lifecycle == RoutineOperationLifecycle::Terminal+ && record.dispatched+ && record.acknowledged+ {+ record.readback.clone()+ } else {+ operation.acknowledged_post_state.clone()+ };let limit = self.limits.single.min(self.limits.total.saturating_sub(other_bytes));- match charge(operation, &record, &verified, limit) {+ match charge(operation, &record, &verified, &acknowledged, limit) {Ok(bytes) => {operation.record = record;operation.verified_post_state = verified;+ operation.acknowledged_post_state = acknowledged;operation.charge = bytes;}Err(_) => {@@ -335,8 +381,14 @@ impl RoutineOperationRegistry {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.charge = charge(+ operation,+ &record,+ &operation.verified_post_state,+ &operation.acknowledged_post_state,+ self.limits.single,+ )+ .expect("bounded receipt fits the approval's reserved floor");operation.record = record;}}@@ -352,6 +404,32 @@ mod tests {PreparedRoutineWrite { operation_id: id.into(), binding: binding(), supersedes: supersedes.map(str::to_owned) }}+ #[tokio::test]+ async fn related_package_cycles_are_retained_from_live_roots_and_reclaimed_together() {+ let registry = RoutineOperationRegistry::default();+ let mut spec = request("spec", None);+ spec.binding.identity.kind = crate::db::ObjectSourceKind::Package;+ spec.binding.package_effect_operation_ids = vec!["body".into()];+ let mut body = request("body", None);+ body.binding.identity.kind = crate::db::ObjectSourceKind::PackageBody;+ body.binding.package_effect_operation_ids = vec!["spec".into()];+ registry.prepare_batch(vec![spec, body], 0).unwrap();+ registry.update_references(&["body".into()], &["spec".into()]).unwrap();+ assert!(registry.observe("spec").operation.is_some());+ registry.update_references(&[], &["body".into()]).unwrap();+ assert!(registry.operations.lock().unwrap().is_empty());+ }++ #[test]+ fn package_effect_ids_cannot_borrow_an_unrelated_preparation_batch() {+ let registry = RoutineOperationRegistry::default();+ registry.prepare_batch(vec![request("original", None)], 0).unwrap();+ let mut body = request("body", None);+ body.binding.package_effect_operation_ids = vec!["original".into()];+ assert!(registry.prepare_batch(vec![body], 0).is_err());+ assert!(registry.observe("original").operation.is_some());+ }+#[tokio::test]async fn reference_updates_are_owner_isolated_and_invalid_retains_are_atomic() {use crate::connection::session_credentials::with_credential_owner;@@ -532,6 +610,44 @@ mod tests {assert!(operation.charge <= before);}+ #[test]+ fn recovery_keeps_acknowledged_invalid_post_state_instead_of_later_observations() {+ 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, None, None);+ assert!(registry.recovery_post_state(&record.operation_id).is_err());+ let mut original = verified_readback();+ original.state = RoutineReadbackState::Invalid;+ registry.terminal(&record.operation_id, true, Some(original.clone()), None);+ let mut later = verified_readback();+ later.source = Some("third-party definition".into());+ registry.update_readback(&record.operation_id, later);+ assert_eq!(registry.recovery_post_state(&record.operation_id).unwrap(), original);+ assert_eq!(+ registry.observe(&record.operation_id).operation.unwrap().readback.unwrap().source.as_deref(),+ Some("third-party definition")+ );+ }++ #[test]+ fn observation_cannot_create_recovery_receipt_for_unknown_or_rejected_write() {+ for rejected in [false, true] {+ let registry = RoutineOperationRegistry::default();+ let record = registry.prepare(binding());+ registry.begin(&record.operation_id, "approved SQL").unwrap();+ registry.mark_dispatched(&record.operation_id).unwrap();+ if rejected {+ registry.terminal(&record.operation_id, false, Some(verified_readback()), None);+ } else {+ registry.waiting_lost(&record.operation_id, "unknown".into());+ }+ registry.update_readback(&record.operation_id, verified_readback());+ assert!(registry.recovery_post_state(&record.operation_id).is_err());+ }+ }+#[test]fn private_binding_duplicates_and_nested_credentials_count_without_logging_them() {let registry = RoutineOperationRegistry::default();diff --git a/crates/dbx-core/src/schema/oracle_routines/plan.rs b/crates/dbx-core/src/schema/oracle_routines/plan.rsindex 92e8adc9ec..275281e5f8 100644--- a/crates/dbx-core/src/schema/oracle_routines/plan.rs+++ b/crates/dbx-core/src/schema/oracle_routines/plan.rs@@ -1,5 +1,8 @@use super::operations::RoutineWriteBinding;-use super::references::{resolve_draft, CatalogReadProof, ResolvedRoutineReference, SelectedFinalDraft};+use super::references::{+ reference_proof_manifest, resolve_draft, resolve_draft_with_tables, CatalogReadProof, PlannedRelation,+ ReferenceProofGroup, ReferenceProofPurpose, ResolvedRoutineReference, SelectedFinalDraft,+};use super::*;use dbx_sql::object_source_sql::{analyze_oracle_routine_draft, prepare_oracle_routine_definition, validate_oracle_routine_target_definition,@@ -7,8 +10,17 @@ use dbx_sql::object_source_sql::{};use std::collections::BTreeSet;+mod package;mod recovery;+pub(super) use package::{+ effective_preflight, effective_prerequisite, observed_body_preflight, package_save_preflight, same_observation,+ validate_post_state,+};+use package::{ExpectedPackagePair, PackagePreflight, RoutineBaseline};+pub use package::{PackageBodySource, PackageContractChoice, PackageGrant, PackageGrantSnapshot, PackagePlanImpact};pub use recovery::prepare_oracle_routine_recovery_core;+#[cfg(test)]+pub(super) use recovery::prepare_package_recovery;#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "kebab-case")]@@ -18,7 +30,7 @@ pub enum RoutinePlanAction {Delete,}-#[derive(Debug, Clone, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct RoutinePlanDraft {pub identity: RoutineIdentity,@@ -29,9 +41,13 @@ pub struct RoutinePlanDraft {pub sql: Option<String>,pub baseline_operation_id: Option<String>,pub supersedes_operation_id: Option<String>,+ pub package_body_source: Option<PackageBodySource>,+ pub package_contract: Option<PackageContractChoice>,+ #[serde(default)]+ pub confirm_package_pair: bool,}-#[derive(Debug, Clone, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct OracleRoutinePlanInput {pub source: RoutineSnapshot,@@ -53,6 +69,8 @@ pub struct OracleRoutinePlanStep {pub incoming_callers: Vec<RoutineDependency>,pub issues: Vec<OracleDraftIssue>,pub operation: Option<RoutineOperationRecord>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub package_impact: Option<PackagePlanImpact>,}#[derive(Debug, Clone, Serialize)]@@ -83,6 +101,7 @@ pub(super) struct SourcePreflight {pub endpoint: RoutineEndpoint,pub config: ConnectionConfig,pub expected: ExpectedRoutine,+ pub package_pair: Option<ExpectedPackagePair>,}#[derive(Clone, Serialize)]@@ -92,6 +111,7 @@ pub(super) struct ComparePreflight {pub proofs: Vec<CatalogReadProof>,pub incoming: Option<Vec<RoutineDependency>>,pub selected: Vec<RoutineIdentity>,+ pub package: Option<PackagePreflight>,}fn problem(message: impl Into<String>) -> OracleDraftIssue {@@ -188,14 +208,29 @@ pub(super) async fn verify_expected(expected: &ExpectedRoutine,origin: SourceOrigin,) -> Result<(), String> {+ if matches!(expected, ExpectedRoutine::Present(object) if matches!(object.version.identity.kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody) && object.source_origin.is_none())+ {+ return Err("Refresh the complete package snapshot with its actual source origin before approval".into());+ }let current =readback::readback(catalog, endpoint, expected.identity().clone(), &RoutineReadbackGoal::Inspect, origin).await;+ verify_observation(catalog, expected, ¤t).await+}++async fn verify_observation(+ catalog: &impl RoutineCatalog,+ expected: &ExpectedRoutine,+ current: &RoutineReadback,+) -> Result<(), String> {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.source_origin.is_some() && current.source_origin != before.source_origin {+ return Err("The package source origin changed since preview; refresh and validate the preserved draft".into());+ }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());}@@ -219,6 +254,40 @@ fn external_incoming(values: &[RoutineDependency], selected: &[RoutineIdentity]).collect()}+pub(super) async fn verify_transfer_preflights(+ writes: &[(String, RoutineWriteBinding)],+ source: &impl RoutineCatalog,+ target: &impl RoutineCatalog,+ origin: SourceOrigin,+) -> Result<(), String> {+ for (index, (_, binding)) in writes.iter().enumerate() {+ let compare = binding.compare.as_ref().ok_or("The original package preflight is missing")?;+ let mut initial_pair = None;+ if binding.identity.kind == db::ObjectSourceKind::PackageBody {+ if let Some(package) = &compare.package {+ if matches!(&package.pair.specification, ExpectedRoutine::Absent(specification)+ if writes[..index].iter().any(|(id, before)| binding.prerequisite_operation_ids.contains(id)+ && before.require_absent && before.target == binding.target && before.identity == *specification+ && before.identity.kind == db::ObjectSourceKind::Package))+ {+ let mut initial = compare.clone();+ initial.package.as_mut().unwrap().require_valid_specification = false;+ initial_pair = Some(initial);+ }+ }+ }+ verify_compare_preflight(+ Some(source),+ target,+ &binding.target,+ initial_pair.as_ref().unwrap_or(compare),+ origin,+ )+ .await?;+ }+ Ok(())+}+pub(super) async fn verify_compare_preflight(source: Option<&impl RoutineCatalog>,target: &impl RoutineCatalog,@@ -229,9 +298,22 @@ pub(super) async fn verify_compare_preflight(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?;+ if let Some(pair) = &before.package_pair {+ package::verify_pair(source, &before.endpoint, pair, origin).await?;+ } else {+ verify_expected(source, &before.endpoint, &before.expected, origin).await?;+ }+ }+ if let Some(package) = &preflight.package {+ let current = package::verify_pair(target, endpoint, &package.pair, target_origin).await?;+ if package.require_valid_specification && current.state != RoutineReadbackState::Present {+ return Err(+ "The body dispatch requires its current complete VALID specification without compiler errors".into()+ );+ }+ } else {+ verify_expected(target, endpoint, &preflight.target, target_origin).await?;}- verify_expected(target, endpoint, &preflight.target, target_origin).await?;for proof in &preflight.proofs {proof.verify(target).await?;}@@ -244,7 +326,7 @@ pub(super) async fn verify_compare_preflight(Ok(())}-async fn checked_endpoint(state: &AppState, endpoint: &RoutineEndpoint) -> Result<ConnectionConfig, String> {+pub(super) 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() {@@ -254,7 +336,11 @@ async fn checked_endpoint(state: &AppState, endpoint: &RoutineEndpoint) -> ResulOk(config)}-fn snapshot_object(snapshot: &RoutineSnapshot, name: &str) -> Result<Option<RoutineObjectSnapshot>, String> {+fn snapshot_object(+ snapshot: &RoutineSnapshot,+ name: &str,+ kind: &db::ObjectSourceKind,+) -> Result<Option<RoutineObjectSnapshot>, String> {let objects: Vec<_> = snapshot.objects.iter()@@ -262,25 +348,50 @@ fn snapshot_object(snapshot: &RoutineSnapshot, name: &str) -> Result<Option<Routobject.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()),+ let counterpart = match kind {+ db::ObjectSourceKind::Package => Some(db::ObjectSourceKind::PackageBody),+ db::ObjectSourceKind::PackageBody => Some(db::ObjectSourceKind::Package),+ _ => None,+ };+ let mut found = None;+ let mut companion = false;+ for object in objects {+ if object.version.identity.kind == *kind {+ if found.replace(object.clone()).is_some() {+ return Err("Routine snapshot has duplicate exact object identities".into());+ }+ } else if counterpart.as_ref() == Some(&object.version.identity.kind) && !companion {+ companion = true;+ } else {+ return Err("Routine snapshot has conflicting namespace identities".into());+ }}+ Ok(found)}-fn terminal_baseline(- state: &AppState,+fn terminal_plan_baseline(+ registry: &RoutineOperationRegistry,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)+) -> Result<RoutineBaseline, String> {+ let record =+ registry.observe(id).operation.ok_or("Original operation is unavailable; only observe its original ID")?;+ let selected = correction_baseline(record.clone(), endpoint, identity)?;+ let companion = if package::is_package(&identity.kind) {+ let companion = record+ .readback+ .as_ref()+ .and_then(|readback| readback.package_companion.as_ref())+ .ok_or("Read the original operation's complete package pair before correction")?;+ if companion.identity != package::counterpart(identity) {+ return Err("The original operation returned another package companion identity".into());+ }+ Some(package::observation_baseline(companion)?)+ } else {+ None+ };+ Ok(RoutineBaseline { selected, companion })}fn correction_baseline(@@ -307,6 +418,7 @@ fn correction_baseline((Some(true), Some(version), Some(source)) => Ok(ExpectedRoutine::Present(RoutineObjectSnapshot {version,source: Some(source),+ source_origin: readback.source_origin,source_complete: true,dependencies: Vec::new(),dependencies_complete: false,@@ -316,43 +428,252 @@ fn correction_baseline(}}+fn check_plan_selection(input: &OracleRoutinePlanInput) -> Result<(), String> {+ if input.source.endpoint.database_type != input.target.endpoint.database_type+ && (![input.source.endpoint.database_type, input.target.endpoint.database_type]+ .into_iter()+ .all(|product| matches!(product, DatabaseType::Oracle | DatabaseType::OceanbaseOracle))+ || input.drafts.iter().any(|draft| !package::is_package(&draft.identity.kind)))+ {+ 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+ | db::ObjectSourceKind::Package+ | db::ObjectSourceKind::PackageBody+ )+ }) {+ return Err("Routine plans accept only exact procedure, function, package and package body identities".into());+ }+ Ok(())+}+pub async fn prepare_oracle_routine_plan_core(state: &AppState,input: OracleRoutinePlanInput,) -> Result<OracleRoutinePlan, String> {+ let input = package::normalize_input(input)?;+ check_plan_selection(&input)?;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| {+ let built = build_plan(Some(&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))+ .map(|id| terminal_plan_baseline(&state.routine_operations, id, &input.target.endpoint, &draft.identity)).transpose()}).await;+ prepare_built_plan(&state.routine_operations, &input, built, Some(&source_config), &target_config)+}++pub(super) async fn prepare_transfer_plan_with_tables(+ state: &AppState,+ input: OracleRoutinePlanInput,+ tables: &[PlannedRelation],+ defer_admission: bool,+) -> Result<(OracleRoutinePlan, BTreeSet<usize>, Value), String> {+ let input = package::normalize_input(input)?;+ check_plan_selection(&input)?;+ let _replacements = pin_transfer_replacements(&state.routine_operations, &input)?;+ 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 built =+ build_plan_with_tables(Some(&source), &target, &input, source_origin, target_origin, |_| Ok(None), tables)+ .await;+ let used = built.planned_table_dependencies.iter().flatten().copied().collect::<BTreeSet<_>>();+ let manifest = transfer_dependency_manifest(&built, tables);+ let positions = built.order_position.clone();+ let mut plan = if defer_admission {+ let mut plan = built.plan;+ plan.ready = false;+ plan+ } else {+ prepare_built_plan(&state.routine_operations, &input, built, Some(&source_config), &target_config)?+ };+ if !used.is_empty() {+ plan = ordered_transfer_preview(plan, &positions);+ }+ Ok((plan, used, manifest))+}++fn pin_transfer_replacements<'a>(+ registry: &'a RoutineOperationRegistry,+ input: &OracleRoutinePlanInput,+) -> Result<Vec<super::operations::RoutineOperationPin<'a>>, String> {+ let mut pins = Vec::new();+ for draft in &input.drafts {+ if draft.action != RoutinePlanAction::Create+ || draft.baseline_operation_id.is_some()+ || !matches!(draft.identity.kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody)+ {+ return Err("Pending table dependencies accept only new transfer package drafts".into());+ }+ if let Some(id) = &draft.supersedes_operation_id {+ let pin = registry.pin(id)?;+ let before = registry.observe(id).operation.ok_or("The original package preview is unavailable")?;+ let binding = registry.binding_for_readback(id)?;+ if before.lifecycle != RoutineOperationLifecycle::Prepared+ || before.dispatched+ || binding.target != input.target.endpoint+ || binding.identity != draft.identity+ || !binding.require_absent+ {+ return Err(+ "Only the original unexecuted new-package preview can be replaced by a pending-table draft".into(),+ );+ }+ pins.push(pin);+ }+ }+ Ok(pins)+}++fn ordered_transfer_preview(mut plan: OracleRoutinePlan, positions: &[usize]) -> OracleRoutinePlan {+ if positions.len() != plan.steps.len()+ || positions.contains(&usize::MAX)+ || plan.steps.iter().any(|step| !step.issues.is_empty())+ {+ return plan;+ }+ let mut steps = plan.steps.into_iter().enumerate().collect::<Vec<_>>();+ steps.sort_by_key(|(index, _)| positions[*index]);+ plan.steps = steps.into_iter().map(|(_, step)| step).collect();+ plan+}++fn transfer_dependency_manifest(built: &BuiltPlan, pending_tables: &[PlannedRelation]) -> Value {+ let steps = built+ .plan+ .steps+ .iter()+ .enumerate()+ .map(|(index, step)| {+ // ComparePreflight.source is populated only at registry admission; its+ // connection config must never be part of a client confirmation payload.+ let preflight = built.preflights[index].as_ref();+ serde_json::json!({+ "identity": step.identity, "action": step.action, "sql": step.sql,+ "references": step.references, "dependencies": built.dependencies[index],+ "pendingTables": step.references.iter().filter(|reference| reference.kind == "TABLE"+ && pending_tables.iter().any(|table| table.owner == reference.owner && table.name == reference.name))+ .map(|reference| (&reference.owner, &reference.name)).collect::<BTreeSet<_>>()+ .into_iter().map(|(owner, name)| serde_json::json!({"owner":owner,"name":name})).collect::<Vec<_>>(),+ "target": preflight.map(|before| &before.target),+ "proofGroups": reference_proof_manifest(&built.proof_groups[index],+ preflight.map(|before| before.proofs.as_slice()).unwrap_or_default(), pending_tables),+ "incoming": preflight.and_then(|before| before.incoming.as_ref()),+ "package": preflight.and_then(|before| before.package.as_ref()),+ "source": built.source_expected[index], "sourcePair": built.source_pairs[index],+ })+ })+ .collect::<Vec<_>>();+ serde_json::json!({ "steps": steps, "order": built.order })+}++pub(super) async fn prepare_completed_transfer<'a>(+ state: &'a AppState,+ transfer_id: &str,+ input: &OracleRoutinePlanInput,+ tables: &[PlannedRelation],+ manifest: &Value,+ table_proofs: Vec<CatalogReadProof>,+) -> Result<(OracleRoutinePlan, Vec<super::operations::RoutineOperationPin<'a>>), String> {+ let input = package::normalize_input(input.clone())?;+ check_plan_selection(&input)?;+ if input.drafts.iter().any(|draft| {+ draft.sql.is_none()+ || draft.action != RoutinePlanAction::Create+ || draft.baseline_operation_id.is_some()+ || draft.supersedes_operation_id.is_some()+ }) {+ return Err("The completed table stage requires the exact frozen new package SQL".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 built = build_plan(Some(&source), &target, &input, source_origin, target_origin, |_| Ok(None)).await;+ if crate::data::transfer::is_cancelled(transfer_id).await {+ return Err("Cancelled before package approval; no package statement was dispatched".into());+ }+ finish_completed_transfer(+ &state.routine_operations,+ &input,+ built,+ tables,+ manifest,+ table_proofs,+ &source_config,+ &target_config,+ )+}++#[allow(clippy::too_many_arguments)]+fn finish_completed_transfer<'a>(+ registry: &'a RoutineOperationRegistry,+ input: &OracleRoutinePlanInput,+ mut built: BuiltPlan,+ tables: &[PlannedRelation],+ manifest: &Value,+ table_proofs: Vec<CatalogReadProof>,+ source_config: &ConnectionConfig,+ target_config: &ConnectionConfig,+) -> Result<(OracleRoutinePlan, Vec<super::operations::RoutineOperationPin<'a>>), String> {+ if transfer_dependency_manifest(&built, tables) != *manifest {+ built.plan.ready = false;+ for step in &mut built.plan.steps {+ step.issues.push(problem("A nonpending dependency, complete source, final SQL or execution order changed during table transfer; retain completed tables and refresh the package drafts"));+ }+ }+ if !built.plan.ready {+ return Ok((built.plan, Vec::new()));+ }+ for before in built.preflights.iter_mut().flatten() {+ before.proofs.extend(table_proofs.iter().cloned());+ }+ let plan = prepare_built_plan(registry, input, built, Some(source_config), target_config)?;+ let pins = plan+ .steps+ .iter()+ .filter_map(|step| step.operation.as_ref())+ .map(|operation| registry.pin(&operation.operation_id))+ .collect::<Result<Vec<_>, _>>()?;+ Ok((plan, pins))+}++fn prepare_built_plan(+ registry: &RoutineOperationRegistry,+ input: &OracleRoutinePlanInput,+ mut built: BuiltPlan,+ source_config: Option<&ConnectionConfig>,+ target_config: &ConnectionConfig,+) -> Result<OracleRoutinePlan, String> {+ if built.planned_table_dependencies.iter().any(|tables| !tables.is_empty()) {+ built.plan.ready = false;+ }if !built.plan.ready {return Ok(built.plan);}@@ -366,11 +687,16 @@ pub async fn prepare_oracle_routine_plan_core(.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 source_preflight = source_config+ .map(|source_config| {+ Ok::<_, String>(SourcePreflight {+ endpoint: input.source.endpoint.clone(),+ config: source_config.clone(),+ expected: built.source_expected[index].clone().ok_or("Source snapshot is unavailable")?,+ package_pair: built.source_pairs[index].clone(),+ })+ })+ .transpose()?;let operation_id = uuid::Uuid::new_v4().to_string();requests.push(super::operations::PreparedRoutineWrite {operation_id: operation_id.clone(),@@ -385,15 +711,39 @@ pub async fn prepare_oracle_routine_plan_core(},expected_config: target_config.clone(),require_absent: step.action == RoutinePlanAction::Create,- compare: Some(ComparePreflight { source: Some(source_preflight), ..preflight }),+ compare: Some(ComparePreflight { source: source_preflight, ..preflight }),prerequisite_operation_ids: dependencies,+ package_effect_operation_ids: Vec::new(),},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)?;+ let package_steps = requests+ .iter()+ .filter(|request| package::is_package(&request.binding.identity.kind))+ .map(|request| (request.operation_id.clone(), request.binding.identity.clone()))+ .collect::<Vec<_>>();+ for request in &mut requests {+ let mut namespaces = BTreeSet::new();+ if package::is_package(&request.binding.identity.kind) {+ namespaces.insert((request.binding.identity.owner.clone(), request.binding.identity.name.clone()));+ }+ for (id, identity) in &package_steps {+ if request.binding.prerequisite_operation_ids.contains(id) {+ namespaces.insert((identity.owner.clone(), identity.name.clone()));+ }+ }+ request.binding.package_effect_operation_ids = package_steps+ .iter()+ .filter(|(id, identity)| {+ *id != request.operation_id && namespaces.contains(&(identity.owner.clone(), identity.name.clone()))+ })+ .map(|(id, _)| id.clone())+ .collect();+ }+ let prepared = registry.prepare_batch(requests, 0)?;for (index, operation) in indices.into_iter().zip(prepared) {built.plan.steps[index].operation = Some(operation);}@@ -412,27 +762,67 @@ pub async fn prepare_oracle_routine_plan_core(Ok(built.plan)}+#[cfg(test)]+pub(super) async fn prepare_with_catalogs(+ registry: &RoutineOperationRegistry,+ source: &impl RoutineCatalog,+ target: &impl RoutineCatalog,+ input: OracleRoutinePlanInput,+ source_config: &ConnectionConfig,+ target_config: &ConnectionConfig,+) -> Result<OracleRoutinePlan, String> {+ let input = package::normalize_input(input)?;+ check_plan_selection(&input)?;+ let (_, source_origin) = routine_source_origin(source_config)?;+ let (_, target_origin) = routine_source_origin(target_config)?;+ let built = build_plan(Some(source), target, &input, source_origin, target_origin, |draft| {+ draft+ .baseline_operation_id+ .as_deref()+ .map(|id| terminal_plan_baseline(registry, id, &input.target.endpoint, &draft.identity))+ .transpose()+ })+ .await;+ prepare_built_plan(registry, &input, built, Some(source_config), target_config)+}+struct BuiltPlan {plan: OracleRoutinePlan,preflights: Vec<Option<ComparePreflight>>,source_expected: Vec<Option<ExpectedRoutine>>,+ source_pairs: Vec<Option<ExpectedPackagePair>>,dependencies: Vec<BTreeSet<usize>>,order: Vec<usize>,order_position: Vec<usize>,+ planned_table_dependencies: Vec<BTreeSet<usize>>,+ proof_groups: Vec<Vec<ReferenceProofGroup>>,}async fn build_plan(- source: &impl RoutineCatalog,+ source: Option<&impl RoutineCatalog>,+ target: &impl RoutineCatalog,+ input: &OracleRoutinePlanInput,+ source_origin: SourceOrigin,+ target_origin: SourceOrigin,+ baseline: impl Fn(&RoutinePlanDraft) -> Result<Option<RoutineBaseline>, String>,+) -> BuiltPlan {+ build_plan_with_tables(source, target, input, source_origin, target_origin, baseline, &[]).await+}++async fn build_plan_with_tables(+ source: Option<&impl RoutineCatalog>,target: &impl RoutineCatalog,input: &OracleRoutinePlanInput,source_origin: SourceOrigin,target_origin: SourceOrigin,- baseline: impl Fn(&RoutinePlanDraft) -> Result<Option<ExpectedRoutine>, String>,+ baseline: impl Fn(&RoutinePlanDraft) -> Result<Option<RoutineBaseline>, String>,+ planned_tables: &[PlannedRelation],) -> 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 source_pairs = Vec::new();let mut seen = BTreeSet::new();for draft in &input.drafts {let mut step = OracleRoutinePlanStep {@@ -447,34 +837,49 @@ async fn build_plan(incoming_callers: Vec::new(),issues: Vec::new(),operation: None,+ package_impact: None,};let mut source_before = None;let mut before = None;+ let mut source_pair = None;+ let mut target_pair = 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()); }+ if draft.identity.owner != input.target.endpoint.schema || draft.identity.name.is_empty() || !matches!(draft.identity.kind, db::ObjectSourceKind::Function | db::ObjectSourceKind::Procedure | db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody) { return Err("Every step must retain its exact selected target identity".into()); }+ let namespace = (draft.identity.owner.clone(), draft.identity.name.clone());+ let key = (namespace.clone(), kind_name(&draft.identity.kind));+ if !seen.insert(key) || input.drafts.iter().any(|other| other.identity.owner == namespace.0 && other.identity.name == namespace.1 && other.identity.kind != draft.identity.kind && !(package::is_package(&other.identity.kind) && package::is_package(&draft.identity.kind))) { return Err("The same shared namespace target has duplicate or conflicting selected kinds".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)?;+ let source_object = snapshot_object(&input.source, source_name, &draft.identity.kind)?;+ let target_object = snapshot_object(&input.target, &draft.identity.name, &draft.identity.kind)?;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 if draft.package_body_source == Some(PackageBodySource::Target) {+ match source_object { Some(object) if object.source_complete => ExpectedRoutine::Present(object), None if input.source.enumeration_complete => ExpectedRoutine::Absent(RoutineIdentity { owner:input.source.endpoint.schema.clone(), ..draft.identity.clone() }), _ => return Err("Refresh complete source evidence before retaining the target body".into()) }} 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,+ let correction = baseline(draft)?;+ let mut expected = match &correction {+ Some(expected) => expected.selected.clone(),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()),},};+ if package::is_package(&draft.identity.kind) {+ source_pair = Some(ExpectedPackagePair::from_snapshot(&input.source, source_name)?);+ let mut pair = ExpectedPackagePair::from_snapshot(&input.target, &draft.identity.name)?;+ pair.set(expected.clone());+ if let Some(companion) = correction.and_then(|baseline| baseline.companion) { pair.set(companion); }+ target_pair = Some(pair);+ }match (&expected, draft.action) {(ExpectedRoutine::Absent(_), RoutinePlanAction::Create) => {}(ExpectedRoutine::Present(object), RoutinePlanAction::Replace | RoutinePlanAction::Delete) => {@@ -493,7 +898,8 @@ async fn build_plan(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)?+ let (owner, source) = if draft.package_body_source == Some(PackageBodySource::Target) { (&draft.identity.owner, step.target_original.as_deref().ok_or("The retained target body is unavailable")?) } else { (&input.source.endpoint.schema, step.source_original.as_deref().ok_or("Complete source is unavailable")?) };+ adapted(&input.target.endpoint, &draft.identity, owner, source, replace)?};}step.recovery_sql = match &expected {@@ -501,8 +907,12 @@ async fn build_plan(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 Some(source) = source {+ if let Some(pair) = &source_pair { package::verify_pair(source, &input.source.endpoint, pair, source_origin).await?; }+ else { verify_expected(source, &input.source.endpoint, source_before.as_ref().unwrap(), source_origin).await?; }+ }+ if let Some(pair) = &target_pair { package::verify_pair(target, &input.target.endpoint, pair, target_origin).await?; }+ else { 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?;@@ -510,19 +920,21 @@ async fn build_plan(}}before = Some(expected);+ if let Some(pair) = &mut target_pair { pair.set(before.as_ref().unwrap().clone()); }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)- };+ let analysis =+ if draft.action == RoutinePlanAction::Delete || draft.identity.kind == db::ObjectSourceKind::PackageBody {+ 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,@@ -530,31 +942,91 @@ async fn build_plan(proofs: Vec::new(),incoming: None,selected: input.drafts.iter().map(|draft| draft.identity.clone()).collect(),+ package: target_pair.map(|pair| PackagePreflight {+ pair,+ grants: None,+ require_valid_specification: draft.identity.kind == db::ObjectSourceKind::PackageBody+ && draft.action != RoutinePlanAction::Delete,+ }),}));source_expected.push(source_before);+ source_pairs.push(source_pair);plan.steps.push(step);}+ package::prepare_package_drafts(+ target,+ input,+ &mut plan,+ &mut selected,+ &mut preflights,+ &source_pairs,+ target_origin,+ )+ .await;let mut dependencies = vec![BTreeSet::new(); plan.steps.len()];+ let mut planned_table_dependencies = vec![BTreeSet::new(); plan.steps.len()];+ let mut proof_groups = preflights+ .iter()+ .map(|before| {+ before+ .as_ref()+ .filter(|before| !before.proofs.is_empty())+ .map(|before| {+ vec![ReferenceProofGroup {+ purpose: ReferenceProofPurpose::PackagePreflight,+ start: 0,+ end: before.proofs.len(),+ }]+ })+ .unwrap_or_default()+ })+ .collect::<Vec<_>>();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;+ let resolution = if planned_tables.is_empty() {+ resolve_draft(target, &input.target.endpoint, &selected, index).await+ } else {+ resolve_draft_with_tables(target, &input.target.endpoint, &selected, index, planned_tables).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;+ planned_table_dependencies[index] = resolution.planned_table_dependencies;+ let offset = preflights[index].as_ref().unwrap().proofs.len();+ proof_groups[index].extend(resolution.proof_groups.into_iter().map(|mut group| {+ group.start += offset;+ group.end += offset;+ group+ }));+ preflights[index].as_mut().unwrap().proofs.extend(resolution.proofs);}- if plan.steps[index].action != RoutinePlanAction::Create {+ if plan.steps[index].action != RoutinePlanAction::Create+ && plan.steps[index].identity.kind != db::ObjectSourceKind::PackageBody+ {match incoming_dependencies(target, &plan.steps[index].identity).await {Ok(incoming) => {plan.steps[index].incoming_callers = incoming.clone();+ if plan.steps[index].identity.kind == db::ObjectSourceKind::Package+ && plan.steps[index].action == RoutinePlanAction::Replace+ && !input.drafts[index].confirm_package_pair+ && !external_incoming(+ &incoming,+ &input.drafts.iter().map(|draft| draft.identity.clone()).collect::<Vec<_>>(),+ )+ .is_empty()+ {+ plan.steps[index].issues.push(problem("Confirm the specification's external caller contract and invalidation risk before approval; VALID callers do not prove compatibility"));+ }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)+ && (caller.kind == kind_name(&plan.steps[index].identity.kind)+ || (plan.steps[index].identity.kind == db::ObjectSourceKind::Package+ && caller.kind == "PACKAGE BODY")){continue;}@@ -571,6 +1043,16 @@ async fn build_plan())),}}+ if plan.steps[index].identity.kind == db::ObjectSourceKind::Package+ && plan.steps[index].action != RoutinePlanAction::Delete+ {+ if let Some(body) = plan.steps.iter().position(|step| {+ step.identity == package::counterpart(&plan.steps[index].identity)+ && step.action == RoutinePlanAction::Delete+ }) {+ dependencies[index].insert(body);+ }+ }}let mut order = Vec::new();let mut remaining: BTreeSet<_> = (0..plan.steps.len()).collect();@@ -587,13 +1069,34 @@ async fn build_plan("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();+ if input.source.endpoint.database_type != input.target.endpoint.database_type {+ for (draft, step) in input.drafts.iter().zip(&mut plan.steps) {+ if draft.sql.is_none() {+ step.issues.push(problem(format!("Cross-product package conversion from {:?} to {:?} requires an explicitly reviewed target draft; retain the original source, review or edit this draft and validate it again", input.source.endpoint.database_type, input.target.endpoint.database_type)));+ }+ }+ }+ plan.ready = plan.steps.iter().all(|step| step.issues.is_empty())+ && order.len() == plan.steps.len()+ && planned_table_dependencies.iter().all(BTreeSet::is_empty);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 }+ BuiltPlan {+ plan,+ preflights,+ source_expected,+ source_pairs,+ dependencies,+ order,+ order_position,+ planned_table_dependencies,+ proof_groups,+ }}+#[cfg(test)]+mod package_tests;#[cfg(test)]mod tests;diff --git a/crates/dbx-core/src/schema/oracle_routines/plan/package.rs b/crates/dbx-core/src/schema/oracle_routines/plan/package.rsnew file mode 100644index 0000000000..6ef4da85a6--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/plan/package.rs@@ -0,0 +1,560 @@+use super::*;+use dbx_sql::object_source_sql::{+ analyze_oracle_package_body_draft, comparable_oracle_routine_definition, OracleDraftPackageMemberKind,+};++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum PackageBodySource {+ Source,+ Target,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum PackageContractChoice {+ Source,+ Target,+}++#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PackageGrant {+ pub grantor: String,+ pub grantee: String,+ pub privilege: String,+ pub grantable: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PackageGrantSnapshot {+ pub grants: Vec<PackageGrant>,+ pub complete: bool,+ pub issue: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PackagePlanImpact {+ pub companion: RoutineIdentity,+ pub companion_action: Option<RoutinePlanAction>,+ pub implicit_companion_delete: bool,+ pub retains_target_body: bool,+ pub body_pending: bool,+ pub may_initialize: bool,+ pub grants: Option<PackageGrantSnapshot>,+}++#[derive(Clone, Serialize)]+pub(in super::super) struct ExpectedPackagePair {+ pub specification: ExpectedRoutine,+ pub body: ExpectedRoutine,+}++#[derive(Clone, Serialize)]+pub(in super::super) struct PackagePreflight {+ pub pair: ExpectedPackagePair,+ pub grants: Option<PackageGrantSnapshot>,+ pub require_valid_specification: bool,+}++pub(super) struct RoutineBaseline {+ pub selected: ExpectedRoutine,+ pub companion: Option<ExpectedRoutine>,+}++pub(super) fn is_package(kind: &db::ObjectSourceKind) -> bool {+ matches!(kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody)+}++pub(super) fn counterpart(identity: &RoutineIdentity) -> RoutineIdentity {+ RoutineIdentity {+ kind: if identity.kind == db::ObjectSourceKind::Package {+ db::ObjectSourceKind::PackageBody+ } else {+ db::ObjectSourceKind::Package+ },+ ..identity.clone()+ }+}++impl ExpectedPackagePair {+ pub fn from_readback(readback: &RoutineReadback) -> Result<Self, String> {+ let companion =+ readback.package_companion.as_deref().ok_or("The complete recorded package pair is unavailable")?;+ if companion.identity != counterpart(&readback.identity) {+ return Err("The recorded package companion has a different identity".into());+ }+ let selected = observation_baseline(readback)?;+ let companion = observation_baseline(companion)?;+ Ok(if readback.identity.kind == db::ObjectSourceKind::Package {+ Self { specification: selected, body: companion }+ } else {+ Self { specification: companion, body: selected }+ })+ }++ fn get(&self, kind: &db::ObjectSourceKind) -> &ExpectedRoutine {+ if *kind == db::ObjectSourceKind::Package {+ &self.specification+ } else {+ &self.body+ }+ }+ pub fn from_snapshot(snapshot: &RoutineSnapshot, name: &str) -> Result<Self, String> {+ let expected =+ |kind| -> Result<ExpectedRoutine, String> {+ match snapshot_object(snapshot, name, &kind)? {+ Some(object) if object.source_complete && object.source.is_some() && object.source_origin.is_some() => {+ Ok(ExpectedRoutine::Present(object))+ }+ Some(_) => {+ Err("Both package definitions and their actual source origins must be completely read before approval"+ .into())+ }+ None if snapshot.enumeration_complete => Ok(ExpectedRoutine::Absent(RoutineIdentity {+ owner: snapshot.endpoint.schema.clone(),+ name: name.into(),+ kind,+ })),+ None => Err("Both package kinds require complete namespace visibility before absence can be used".into()),+ }+ };+ Ok(Self {+ specification: expected(db::ObjectSourceKind::Package)?,+ body: expected(db::ObjectSourceKind::PackageBody)?,+ })+ }++ pub fn set(&mut self, expected: ExpectedRoutine) {+ if expected.identity().kind == db::ObjectSourceKind::Package {+ self.specification = expected;+ } else {+ self.body = expected;+ }+ }+}++pub(in super::super) async fn package_save_preflight(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ identity: &RoutineIdentity,+ origin: SourceOrigin,+) -> Result<ComparePreflight, String> {+ let current = readback::readback(catalog, endpoint, identity.clone(), &RoutineReadbackGoal::Inspect, origin).await;+ let pair = ExpectedPackagePair::from_readback(¤t)?;+ Ok(ComparePreflight {+ source: None,+ target: pair.get(&identity.kind).clone(),+ proofs: Vec::new(),+ incoming: None,+ selected: vec![identity.clone()],+ package: Some(PackagePreflight { pair, grants: None, require_valid_specification: false }),+ })+}++pub(super) fn definition_identity_matches(expected: &ExpectedRoutine, observed: &RoutineReadback) -> bool {+ if expected.identity() != &observed.identity || !observed.issues.is_empty() {+ return false;+ }+ match expected {+ ExpectedRoutine::Absent(_) => {+ observed.exists == Some(false) && observed.version.is_none() && observed.source.is_none()+ }+ ExpectedRoutine::Present(before) => {+ observed.exists == Some(true)+ && before.source_complete+ && before.source == observed.source+ && before.source_origin == observed.source_origin+ && observed.version.as_ref().is_some_and(|version| {+ version.identity == before.version.identity && version.object_id == before.version.object_id+ })+ }+ }+}++fn same_namespace(left: &RoutineIdentity, right: &RoutineIdentity) -> bool {+ is_package(&left.kind) && is_package(&right.kind) && left.owner == right.owner && left.name == right.name+}++pub(in super::super) fn effective_preflight(+ binding: &RoutineWriteBinding,+ effects: &[(RoutineWriteBinding, RoutineReadback)],+) -> Result<Option<ComparePreflight>, String> {+ let Some(mut compare) = binding.compare.clone() else {+ return Ok(None);+ };+ if let Some(package) = &mut compare.package {+ for (_, post) in effects.iter().filter(|(effect, _)| {+ same_namespace(&effect.identity, &binding.identity) && effect.identity.kind != binding.identity.kind+ }) {+ let companion = post+ .package_companion+ .as_ref()+ .ok_or("The verified package step has no complete companion post-state")?;+ if !definition_identity_matches(package.pair.get(&binding.identity.kind), companion) {+ return Err("The completed package step cannot explain a changed companion definition, identity or source origin; refresh the remaining draft".into());+ }+ package.pair.set(observation_baseline(post)?);+ package.pair.set(observation_baseline(companion)?);+ }+ compare.target = package.pair.get(&binding.identity.kind).clone();+ }+ Ok(Some(compare))+}++pub(in super::super) fn observed_body_preflight(+ binding: &RoutineWriteBinding,+ effects: &[(RoutineWriteBinding, RoutineReadback)],+) -> Result<Option<ComparePreflight>, String> {+ let Some(mut compare) = binding.compare.clone() else {+ return Ok(None);+ };+ if let Some(package) = &mut compare.package {+ for (_, post) in effects.iter().filter(|(effect, _)| {+ same_namespace(&effect.identity, &binding.identity) && effect.identity.kind == db::ObjectSourceKind::Package+ }) {+ package.pair.specification = observation_baseline(post)?;+ }+ }+ Ok(Some(compare))+}++pub(in super::super) fn effective_prerequisite(+ binding: &RoutineWriteBinding,+ before: &RoutineReadback,+ effects: &[(RoutineWriteBinding, RoutineReadback)],+) -> Result<RoutineReadback, String> {+ let mut expected = before.clone();+ if !is_package(&binding.identity.kind) {+ return Ok(expected);+ }+ for (_, post) in effects.iter().filter(|(effect, _)| {+ same_namespace(&effect.identity, &binding.identity) && effect.identity.kind != binding.identity.kind+ }) {+ let companion =+ post.package_companion.as_ref().ok_or("The related verified package result has no companion")?;+ let previous = observation_baseline(&expected)?;+ if !definition_identity_matches(&previous, companion) {+ return Err("The related package step changed the prerequisite definition, identity or origin; validate the remaining draft".into());+ }+ let mut peer = post.clone();+ peer.package_companion = None;+ let original_state = expected.state.clone();+ let original_match = expected.definition_matches;+ expected = companion.as_ref().clone();+ expected.state = original_state;+ expected.definition_matches = original_match;+ expected.package_companion = Some(Box::new(peer));+ }+ Ok(expected)+}++pub(in super::super) fn same_observation(left: &RoutineReadback, right: &RoutineReadback) -> bool {+ left.identity == right.identity+ && left.exists == right.exists+ && left.version == right.version+ && left.source == right.source+ && left.source_origin == right.source_origin+ && left.compiler_messages == right.compiler_messages+ && left.issues == right.issues+ && match (&left.package_companion, &right.package_companion) {+ (None, None) => true,+ (Some(left), Some(right)) => same_observation(left, right),+ _ => false,+ }+}++pub(in super::super) fn validate_post_state(+ binding: &RoutineWriteBinding,+ compare: Option<&ComparePreflight>,+ current: &mut RoutineReadback,+) {+ if !is_package(&binding.identity.kind) {+ return;+ }+ let check: Result<(), String> = (|| {+ let pair = &compare+ .and_then(|compare| compare.package.as_ref())+ .ok_or("The package write has no frozen pair preflight")?+ .pair;+ let companion =+ current.package_companion.as_ref().ok_or("The package write returned no complete companion observation")?;+ if binding.identity.kind == db::ObjectSourceKind::Package && binding.goal == RoutineReadbackGoal::Absent {+ return Ok(());+ }+ let expected = pair.get(&counterpart(&binding.identity).kind);+ if !definition_identity_matches(expected, companion) {+ return Err(+ "The package write's companion definition, identity or actual origin changed unexpectedly".into()+ );+ }+ if binding.identity.kind == db::ObjectSourceKind::PackageBody {+ if let ExpectedRoutine::Present(before) = expected {+ if companion.version.as_ref() != Some(&before.version) {+ return Err(+ "The package body write unexpectedly changed its specification status or DDL version".into()+ );+ }+ }+ }+ Ok(())+ })();+ if let Err(error) = check {+ current.state = RoutineReadbackState::ReadbackFailed;+ current.issues.push(issue("package-post-state", error));+ }+}++pub(super) fn normalize_input(mut input: OracleRoutinePlanInput) -> Result<OracleRoutinePlanInput, String> {+ for draft in &input.drafts {+ if !matches!(+ draft.identity.kind,+ db::ObjectSourceKind::Procedure+ | db::ObjectSourceKind::Function+ | db::ObjectSourceKind::Package+ | db::ObjectSourceKind::PackageBody+ ) {+ return Err("Program plans require exact supported procedure, function, package or body identities".into());+ }+ if draft.identity.kind != db::ObjectSourceKind::PackageBody+ && (draft.package_body_source.is_some() || draft.package_contract.is_some())+ {+ return Err("Body source and specification choices apply only to PACKAGE_BODY steps".into());+ }+ if !is_package(&draft.identity.kind) && draft.confirm_package_pair {+ return Err("Package pair confirmation cannot change standalone routine semantics".into());+ }+ if draft.identity.kind == db::ObjectSourceKind::Package && draft.action == RoutinePlanAction::Delete {+ for body in input.drafts.iter().filter(|body| body.identity == counterpart(&draft.identity)) {+ if body.action != RoutinePlanAction::Delete {+ return Err("A whole-package deletion cannot be combined with a body write".into());+ }+ if body.source_name.as_ref().is_some_and(|name| name != &body.identity.name)+ || body.sql.as_ref().is_some_and(|sql| sql.trim() != drop_sql(&body.identity))+ {+ return Err("The implicit body deletion must retain its exact identity and DROP statement".into());+ }+ if !input.source.enumeration_complete+ || snapshot_object(&input.source, &body.identity.name, &body.identity.kind)?.is_some()+ {+ return Err(+ "An explicitly selected body deletion requires its confirmed absence in the source".into()+ );+ }+ }+ }+ }+ let drops = input+ .drafts+ .iter()+ .filter(|draft| {+ draft.identity.kind == db::ObjectSourceKind::Package && draft.action == RoutinePlanAction::Delete+ })+ .map(|draft| counterpart(&draft.identity))+ .collect::<Vec<_>>();+ input.drafts.retain(|draft| !drops.contains(&draft.identity));+ Ok(input)+}++pub(super) async fn verify_pair(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ pair: &ExpectedPackagePair,+ origin: SourceOrigin,+) -> Result<RoutineReadback, String> {+ let current = readback::readback(+ catalog,+ endpoint,+ pair.specification.identity().clone(),+ &RoutineReadbackGoal::Inspect,+ origin,+ )+ .await;+ verify_observation(catalog, &pair.specification, ¤t).await?;+ let body = current.package_companion.as_ref().ok_or("The package pair observation is incomplete")?;+ verify_observation(catalog, &pair.body, body).await?;+ Ok(current)+}++fn complete_specification(expected: &ExpectedRoutine) -> Result<&RoutineObjectSnapshot, String> {+ match expected {+ ExpectedRoutine::Present(object) if object.source_complete && object.source.is_some() && object.source_origin.is_some() => Ok(object),+ _ => Err("The final package body needs its completely read specification; retain the draft and refresh or select the specification".into()),+ }+}++fn comparable_specification(endpoint: &RoutineEndpoint, object: &RoutineObjectSnapshot) -> Result<String, String> {+ comparable_oracle_routine_definition(OracleRoutineDefinitionInput {+ database_type: endpoint.database_type,+ object_type: db::ObjectSourceKind::Package,+ source_owner: object.version.identity.owner.clone(),+ target_owner: endpoint.schema.clone(),+ name: object.version.identity.name.clone(),+ source: object.source.clone().ok_or("Complete package specification is unavailable")?,+ replace: true,+ })+}++pub(super) async fn prepare_package_drafts(+ target: &impl RoutineCatalog,+ input: &OracleRoutinePlanInput,+ plan: &mut OracleRoutinePlan,+ selected: &mut [SelectedFinalDraft],+ preflights: &mut [Option<ComparePreflight>],+ source_pairs: &[Option<ExpectedPackagePair>],+ origin: SourceOrigin,+) {+ for index in 0..plan.steps.len() {+ if plan.steps[index].identity.kind != db::ObjectSourceKind::PackageBody+ || plan.steps[index].action == RoutinePlanAction::Delete+ || !plan.steps[index].issues.is_empty()+ {+ continue;+ }+ let prepared: Result<(), String> = async {+ let specification_identity = counterpart(&plan.steps[index].identity);+ let selected_specification = plan.steps.iter().position(|step| step.identity == specification_identity);+ let specification = if let Some(specification) = selected_specification {+ if input.drafts[index].package_contract.is_some() { return Err("A BODY-only contract choice cannot override the selected final specification draft".into()); }+ if plan.steps[specification].action == RoutinePlanAction::Delete || !plan.steps[specification].issues.is_empty() { return Err("The selected body requires a valid final specification draft, not a deletion or unreadable draft".into()); }+ plan.steps[specification].sql.clone()+ } else {+ let target_pair = &preflights[index].as_ref().and_then(|preflight| preflight.package.as_ref()).ok_or("The target package pair is unavailable")?.pair;+ let target_specification = complete_specification(&target_pair.specification)?;+ if target_specification.version.status != "VALID" { return Err("BODY-only approval requires a VALID target specification; correct and select that specification first".into()); }+ let current = verify_pair(target, &input.target.endpoint, target_pair, origin).await?;+ if current.state != RoutineReadbackState::Present { return Err("BODY-only approval requires a complete VALID specification without compiler errors".into()); }+ if input.drafts[index].package_contract != Some(PackageContractChoice::Target) {+ let source_specification = complete_specification(&source_pairs[index].as_ref().ok_or("The source package pair is unavailable")?.specification)?;+ if comparable_specification(&input.target.endpoint, source_specification)? != comparable_specification(&input.target.endpoint, target_specification)? {+ return Err("The complete source and target specifications differ; select the specification or explicitly use the target specification as the body contract and validate this draft again".into());+ }+ }+ adapted(+ &input.target.endpoint,+ &specification_identity,+ &target_specification.version.identity.owner,+ target_specification.source.as_deref().unwrap(),+ true,+ )?+ };+ let analysis = analyze_oracle_package_body_draft(+ ddl_input(&input.target.endpoint, &plan.steps[index].identity, plan.steps[index].sql.clone()),+ ddl_input(&input.target.endpoint, &specification_identity, specification),+ );+ plan.steps[index].issues.extend(analysis.issues.clone());+ selected[index].analysis = Some(analysis);+ Ok(())+ }.await;+ if let Err(error) = prepared {+ plan.steps[index].issues.push(problem(error));+ }+ }+ for index in 0..plan.steps.len() {+ if !is_package(&plan.steps[index].identity.kind) || !plan.steps[index].issues.is_empty() {+ continue;+ }+ let prepared: Result<(), String> = async {+ let pair = preflights[index].as_ref().and_then(|preflight| preflight.package.as_ref()).ok_or("The original target pair is unavailable")?.pair.clone();+ let companion = counterpart(&plan.steps[index].identity);+ let companion_index = plan.steps.iter().position(|step| step.identity == companion);+ let mut impact = PackagePlanImpact { companion:companion.clone(), companion_action:companion_index.map(|index| plan.steps[index].action), implicit_companion_delete:false,+ retains_target_body:input.drafts[index].package_body_source == Some(PackageBodySource::Target), body_pending:false,+ may_initialize:selected[index].analysis.as_ref().is_some_and(|analysis| analysis.has_package_initialization)+ || companion_index.and_then(|index| selected[index].analysis.as_ref()).is_some_and(|analysis| analysis.has_package_initialization), grants:None };+ if plan.steps[index].identity.kind == db::ObjectSourceKind::Package {+ let source_has_body = source_pairs[index].as_ref().is_some_and(|pair| matches!(&pair.body, ExpectedRoutine::Present(_)));+ let needs_body = selected[index].analysis.as_ref().is_some_and(|analysis| analysis.package_members.iter().any(|member| matches!(member.kind, OracleDraftPackageMemberKind::Function | OracleDraftPackageMemberKind::Procedure)));+ impact.body_pending = plan.steps[index].action != RoutinePlanAction::Delete && companion_index.is_none_or(|index| plan.steps[index].action == RoutinePlanAction::Delete) && (source_has_body || needs_body);+ if plan.steps[index].action == RoutinePlanAction::Delete {+ impact.implicit_companion_delete = matches!(&pair.body, ExpectedRoutine::Present(_));+ if impact.implicit_companion_delete && !input.drafts[index].confirm_package_pair { plan.steps[index].issues.push(problem("DROP PACKAGE also deletes its existing body; confirm this complete pair impact before approval")); }+ } else if matches!(&pair.body, ExpectedRoutine::Present(_)) {+ if companion_index.is_none() { plan.steps[index].issues.push(problem("Replacing or creating this specification requires an explicit source body, retained target body rebuild, or body deletion step; its old VALID state does not prove compatibility")); }+ if !input.drafts[index].confirm_package_pair { plan.steps[index].issues.push(problem("Confirm the specification and existing body impact before approval")); }+ } else if companion_index.is_none() && impact.body_pending && !input.drafts[index].confirm_package_pair {+ plan.steps[index].issues.push(problem("This is specification-only: the source body or callable implementations are not transferred; confirm that incomplete package scope before approval"));+ }+ if plan.steps[index].action != RoutinePlanAction::Create {+ let (grants, proofs) = read_grants(target, &plan.steps[index].identity).await;+ plan.steps[index].recovery_complete &= grants.complete;+ if !grants.complete && !input.drafts[index].confirm_package_pair { plan.steps[index].issues.push(problem("The original package grants cannot be completely backed up; review and confirm the recovery limitation before approval")); }+ preflights[index].as_mut().unwrap().proofs.extend(proofs);+ preflights[index].as_mut().unwrap().package.as_mut().unwrap().grants = Some(grants.clone());+ impact.grants = Some(grants);+ }+ } else if input.drafts[index].package_body_source == Some(PackageBodySource::Target) && plan.steps[index].action != RoutinePlanAction::Replace {+ return Err("Retaining the target body requires an explicit replace/rebuild of an existing body".into());+ }+ plan.steps[index].package_impact = Some(impact);+ Ok(())+ }.await;+ if let Err(error) = prepared {+ plan.steps[index].issues.push(problem(error));+ }+ }+}++pub(super) async fn read_grants(+ catalog: &impl RoutineCatalog,+ identity: &RoutineIdentity,+) -> (PackageGrantSnapshot, Vec<CatalogReadProof>) {+ let mut snapshot = PackageGrantSnapshot { grants: Vec::new(), complete: false, issue: None };+ let mut proofs = Vec::new();+ let read: Result<(), String> = async {+ let login_sql = "SELECT USER AS LOGIN_OWNER FROM DUAL".to_string();+ let login = catalog.query(&login_sql).await?;+ login.flags.check()?;+ if login.rows.len() != 1 { return Err("Package grant visibility is unknown".into()); }+ let owner_visible = login.text(&login.rows[0], "LOGIN_OWNER")? == identity.owner;+ proofs.push(CatalogReadProof::Query {sql:login_sql,columns:login.columns,rows:login.rows});+ loop {+ let offset = snapshot.grants.len();+ let sql = format!("SELECT * FROM (SELECT GRANTOR, GRANTEE, PRIVILEGE, GRANTABLE, ROW_NUMBER() OVER (ORDER BY GRANTOR, GRANTEE, PRIVILEGE, GRANTABLE) RN FROM ALL_TAB_PRIVS WHERE TABLE_SCHEMA = {} AND TABLE_NAME = {}) WHERE RN > {offset} AND RN <= {} ORDER BY RN", literal(&identity.owner), literal(&identity.name), offset + PAGE_SIZE);+ let reply = catalog.query(&sql).await?;+ reply.flags.check()?;+ if reply.rows.len() > PAGE_SIZE { return Err("Package grants exceeded the verified page size".into()); }+ for (index, row) in reply.rows.iter().enumerate() {+ if reply.integer(row,"RN")? != (offset+index+1) as u64 { return Err("Package grant pagination is incomplete".into()); }+ let grantable = reply.text(row,"GRANTABLE")?;+ if !matches!(grantable.as_str(),"YES"|"NO") { return Err("Package grant option is unknown".into()); }+ snapshot.grants.push(PackageGrant {grantor:reply.text(row,"GRANTOR")?,grantee:reply.text(row,"GRANTEE")?,privilege:reply.text(row,"PRIVILEGE")?,grantable:grantable=="YES"});+ }+ let finished = reply.rows.len() < PAGE_SIZE;+ proofs.push(CatalogReadProof::Query {sql,columns:reply.columns,rows:reply.rows});+ if finished { break; }+ }+ let unique = snapshot.grants.iter().collect::<BTreeSet<_>>();+ if unique.len() != snapshot.grants.len() { return Err("Package grants contain duplicate identities".into()); }+ if !owner_visible { return Err("Visible grants for another owner are not proof of a complete original grant backup".into()); }+ snapshot.complete = true;+ Ok(())+ }.await;+ if let Err(error) = read {+ snapshot.issue = Some(error);+ }+ (snapshot, proofs)+}++pub(super) fn observation_baseline(readback: &RoutineReadback) -> Result<ExpectedRoutine, String> {+ if !readback.issues.is_empty() {+ return Err("The package pair's recorded post-state is incomplete; observe the original operation again".into());+ }+ match (&readback.version, &readback.source, readback.exists) {+ (None, None, Some(false)) => Ok(ExpectedRoutine::Absent(readback.identity.clone())),+ (Some(version), Some(source), Some(true)) if readback.source_origin.is_some() => {+ Ok(ExpectedRoutine::Present(RoutineObjectSnapshot {+ version: version.clone(),+ source: Some(source.clone()),+ source_origin: readback.source_origin,+ source_complete: true,+ dependencies: Vec::new(),+ dependencies_complete: false,+ issues: Vec::new(),+ }))+ }+ _ => Err("The package pair has no complete exact-kind post-state for correction".into()),+ }+}diff --git a/crates/dbx-core/src/schema/oracle_routines/plan/package_tests.rs b/crates/dbx-core/src/schema/oracle_routines/plan/package_tests.rsnew file mode 100644index 0000000000..287f6e0a4f--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/plan/package_tests.rs@@ -0,0 +1,651 @@+use super::tests::{endpoint, object, snapshot, Catalog};+use super::*;+use std::sync::atomic::Ordering;++fn program(owner: &str, name: &str, kind: db::ObjectSourceKind, source: &str) -> RoutineObjectSnapshot {+ let mut result = object(owner, name, "1");+ result.version.identity.kind = kind.clone();+ result.version.object_id = if kind == db::ObjectSourceKind::PackageBody { "81" } else { "80" }.into();+ result.source = Some(source.into());+ result.source_origin = Some(SourceOrigin::OceanBaseDictionary);+ result+}++fn specification(owner: &str, initial: u8) -> RoutineObjectSnapshot {+ program(owner,"PKG",db::ObjectSourceKind::Package,&format!("CREATE OR REPLACE PACKAGE \"{owner}\".PKG AS g NUMBER := {initial}; FUNCTION f(p NUMBER DEFAULT 1) RETURN NUMBER; END PKG;"))+}++fn body(owner: &str) -> RoutineObjectSnapshot {+ program(owner,"PKG",db::ObjectSourceKind::PackageBody,&format!("CREATE OR REPLACE PACKAGE BODY \"{owner}\".PKG AS FUNCTION f(p NUMBER) RETURN NUMBER IS BEGIN RETURN p + g; END f; END PKG;"))+}++fn draft(kind: db::ObjectSourceKind, action: RoutinePlanAction) -> RoutinePlanDraft {+ RoutinePlanDraft {+ identity: RoutineIdentity { owner: "OWNER".into(), name: "PKG".into(), kind },+ action,+ source_name: None,+ sql: None,+ baseline_operation_id: None,+ supersedes_operation_id: None,+ package_body_source: None,+ package_contract: None,+ confirm_package_pair: false,+ }+}++async fn build(source: &Catalog, target: &Catalog, drafts: Vec<RoutinePlanDraft>) -> BuiltPlan {+ let input =+ package::normalize_input(OracleRoutinePlanInput { source: snapshot(source), target: snapshot(target), drafts })+ .unwrap();+ build_plan(+ Some(source),+ target,+ &input,+ SourceOrigin::OceanBaseDictionary,+ SourceOrigin::OceanBaseDictionary,+ |_| Ok(None),+ )+ .await+}++#[tokio::test]+async fn transfer_batch_checks_the_initial_absent_pair_without_requiring_its_future_specification() {+ let source = Catalog::new("SOURCE", vec![specification("SOURCE", 1), body("SOURCE")]);+ let target = Catalog::new("OWNER", vec![]);+ let input = OracleRoutinePlanInput {+ source: snapshot(&source),+ target: snapshot(&target),+ drafts: vec![+ draft(db::ObjectSourceKind::Package, RoutinePlanAction::Create),+ draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Create),+ ],+ };+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({"id":"target","name":"test","db_type":"oceanbase-oracle","host":"localhost","port":2881,"username":"OWNER","password":""})).unwrap();+ let registry = RoutineOperationRegistry::default();+ let plan = prepare_with_catalogs(®istry, &source, &target, input, &config, &config).await.unwrap();+ assert!(plan.ready, "{:?}", plan.steps);+ let writes = plan+ .steps+ .iter()+ .map(|step| {+ let id = step.operation.as_ref().unwrap().operation_id.clone();+ let binding = registry.binding_for_readback(&id).unwrap();+ (id, binding)+ })+ .collect::<Vec<_>>();+ verify_transfer_preflights(&writes, &source, &target, SourceOrigin::OceanBaseDictionary).await.unwrap();+ let body = writes.iter().find(|(_, binding)| binding.identity.kind == db::ObjectSourceKind::PackageBody).unwrap();+ assert!(body.1.compare.as_ref().unwrap().package.as_ref().unwrap().require_valid_specification);+ assert!(+ verify_compare_preflight(+ Some(&source),+ &target,+ &body.1.target,+ body.1.compare.as_ref().unwrap(),+ SourceOrigin::OceanBaseDictionary+ )+ .await+ .is_err(),+ "Actual BODY dispatch must still wait for the verified VALID specification"+ );+ assert!(writes.iter().all(|(id, _)| registry+ .observe(id)+ .operation+ .is_some_and(|record| record.lifecycle == RoutineOperationLifecycle::Prepared && !record.dispatched)));+}++#[tokio::test]+async fn transfer_claim_rechecks_frozen_approvals_before_any_table_stage_without_reapproval() {+ for changed in ["source", "external", "target"] {+ let original = program(+ "SOURCE",+ "PKG",+ db::ObjectSourceKind::Package,+ "CREATE OR REPLACE PACKAGE \"SOURCE\".PKG AS n NUMBER := Q.g; END PKG;",+ );+ let source = Catalog::new("SOURCE", vec![original]);+ let external = program(+ "OWNER",+ "Q",+ db::ObjectSourceKind::Package,+ "CREATE OR REPLACE PACKAGE \"OWNER\".Q AS g NUMBER := 1; END Q;",+ );+ let mut target = Catalog::new("OWNER", vec![external]);+ let input = OracleRoutinePlanInput {+ source: snapshot(&source),+ target: snapshot(&target),+ drafts: vec![draft(db::ObjectSourceKind::Package, RoutinePlanAction::Create)],+ };+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({"id":"target","name":"test","db_type":"oceanbase-oracle","host":"localhost","port":2881,"username":"OWNER","password":""})).unwrap();+ let registry = RoutineOperationRegistry::default();+ let plan = prepare_with_catalogs(®istry, &source, &target, input, &config, &config).await.unwrap();+ assert!(plan.ready, "{:?}", plan.steps);+ let id = plan.steps[0].operation.as_ref().unwrap().operation_id.clone();+ let writes = vec![(id.clone(), registry.binding_for_readback(&id).unwrap())];+ verify_transfer_preflights(&writes, &source, &target, SourceOrigin::OceanBaseDictionary).await.unwrap();+ match changed {+ "source" => source.changed_source.store(true, Ordering::SeqCst),+ "external" => target.objects[0].source.as_mut().unwrap().push_str(" -- changed compatible dependency"),+ _ => target.objects.push(program(+ "OWNER",+ "PKG",+ db::ObjectSourceKind::Package,+ "CREATE OR REPLACE PACKAGE \"OWNER\".PKG AS n NUMBER; END PKG;",+ )),+ }+ assert!(+ verify_transfer_preflights(&writes, &source, &target, SourceOrigin::OceanBaseDictionary).await.is_err(),+ "{changed}"+ );+ let record = registry.observe(&id).operation.unwrap();+ assert_eq!(record.lifecycle, RoutineOperationLifecycle::Prepared);+ assert!(!record.dispatched);+ assert_eq!(record.operation_id, id);+ }+}++#[tokio::test]+async fn pending_table_edits_only_supersede_the_original_pinned_prepared_new_package() {+ let original = program(+ "SOURCE",+ "PKG",+ db::ObjectSourceKind::Package,+ "CREATE OR REPLACE PACKAGE \"SOURCE\".PKG AS n NUMBER; END PKG;",+ );+ let source = Catalog::new("SOURCE", vec![original]);+ let target = Catalog::new("OWNER", vec![]);+ let mut input = OracleRoutinePlanInput {+ source: snapshot(&source),+ target: snapshot(&target),+ drafts: vec![draft(db::ObjectSourceKind::Package, RoutinePlanAction::Create)],+ };+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({"id":"target","name":"test","db_type":"oceanbase-oracle","host":"localhost","port":2881,"username":"OWNER","password":""})).unwrap();+ let registry = RoutineOperationRegistry::default();+ let plan = prepare_with_catalogs(®istry, &source, &target, input.clone(), &config, &config).await.unwrap();+ assert!(plan.ready, "{:?}", plan.steps);+ let id = plan.steps[0].operation.as_ref().unwrap().operation_id.clone();+ input.drafts[0].supersedes_operation_id = Some(id.clone());+ let pins = pin_transfer_replacements(®istry, &input).unwrap();+ registry.update_references(&[], std::slice::from_ref(&id)).unwrap();+ assert!(+ registry.observe(&id).operation.is_some(),+ "Validation pins preserve the original ID across preview release"+ );+ for case in 0..4 {+ let mut changed = input.clone();+ match case {+ 0 => changed.target.endpoint.generation += 1,+ 1 => changed.drafts[0].identity.name = "OTHER".into(),+ 2 => changed.drafts[0].action = RoutinePlanAction::Replace,+ _ => changed.drafts[0].baseline_operation_id = Some(id.clone()),+ }+ assert!(pin_transfer_replacements(®istry, &changed).is_err(), "case {case}");+ }+ registry.begin(&id, &plan.steps[0].sql).unwrap();+ assert!(pin_transfer_replacements(®istry, &input).is_err());+ registry.mark_dispatched(&id).unwrap();+ registry.waiting_lost(&id, "Original completion is unknown".into());+ assert!(pin_transfer_replacements(®istry, &input).is_err());+ drop(pins);+ assert_eq!(registry.observe(&id).operation.unwrap().lifecycle, RoutineOperationLifecycle::Unproven);+}++#[tokio::test]+async fn completed_mixed_batch_registers_and_pins_once_without_rebaselining_compatible_external_changes() {+ let spec = specification("SOURCE", 1);+ let implementation = program("SOURCE", "PKG", db::ObjectSourceKind::PackageBody,+ "CREATE OR REPLACE PACKAGE BODY \"SOURCE\".PKG AS FUNCTION f(p NUMBER) RETURN NUMBER IS n NUMBER; BEGIN SELECT a.TARGET_N INTO n FROM PENDING_REL a; RETURN n+p+g+Q.g; END f; END PKG;");+ let source = Catalog::new("SOURCE", vec![spec, implementation]);+ let external = program(+ "OWNER",+ "Q",+ db::ObjectSourceKind::Package,+ "CREATE OR REPLACE PACKAGE \"OWNER\".Q AS g NUMBER := 1; END Q;",+ );+ let mut target = Catalog::new("OWNER", vec![external]);+ let mut input = package::normalize_input(OracleRoutinePlanInput {+ source: snapshot(&source),+ target: snapshot(&target),+ drafts: vec![+ draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Create),+ draft(db::ObjectSourceKind::Package, RoutinePlanAction::Create),+ ],+ })+ .unwrap();+ let tables = vec![PlannedRelation {+ owner: "OWNER".into(),+ name: "PENDING_REL".into(),+ columns: BTreeSet::from(["TARGET_N".into()]),+ }];+ let initial = build_plan_with_tables(+ Some(&source),+ &target,+ &input,+ SourceOrigin::OceanBaseDictionary,+ SourceOrigin::OceanBaseDictionary,+ |_| Ok(None),+ &tables,+ )+ .await;+ assert!(initial.plan.steps.iter().all(|step| step.issues.is_empty()), "{:?}", initial.plan.steps);+ assert!(!initial.plan.ready);+ let public_preview = ordered_transfer_preview(initial.plan.clone(), &initial.order_position);+ assert!(!public_preview.ready);+ assert!(public_preview.steps.iter().all(|step| step.operation.is_none()));+ assert_eq!(+ public_preview.steps.iter().map(|step| step.identity.kind.clone()).collect::<Vec<_>>(),+ vec![db::ObjectSourceKind::Package, db::ObjectSourceKind::PackageBody],+ "The pending preview must show the same dependency order as final admission"+ );+ let manifest = transfer_dependency_manifest(&initial, &tables);+ for (draft, step) in input.drafts.iter_mut().zip(&initial.plan.steps) {+ draft.sql = Some(step.sql.clone());+ }+ target.tables.insert("PENDING_REL".into(), vec!["TARGET_N".into()]);+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({"id":"target","name":"test","db_type":"oceanbase-oracle","host":"localhost","port":2881,"username":"OWNER","password":""})).unwrap();+ for external_changed in [false, true] {+ target.changed_source.store(external_changed, Ordering::SeqCst);+ let actual = build_plan(+ Some(&source),+ &target,+ &input,+ SourceOrigin::OceanBaseDictionary,+ SourceOrigin::OceanBaseDictionary,+ |_| Ok(None),+ )+ .await;+ assert!(+ actual.plan.ready,+ "A compatible external text change still passes fresh analysis: {:?}",+ actual.plan.steps+ );+ let registry = RoutineOperationRegistry::default();+ let (plan, pins) =+ finish_completed_transfer(®istry, &input, actual, &tables, &manifest, vec![], &config, &config).unwrap();+ if external_changed {+ assert!(!plan.ready);+ assert!(pins.is_empty());+ assert!(plan.steps.iter().all(|step| step.operation.is_none()));+ assert!(plan.steps.iter().any(|step| step.issues.iter().any(|issue| issue.message.contains("dependency"))));+ } else {+ assert!(plan.ready);+ assert_eq!(+ plan.steps.iter().map(|step| step.identity.kind.clone()).collect::<Vec<_>>(),+ vec![db::ObjectSourceKind::Package, db::ObjectSourceKind::PackageBody]+ );+ let ids =+ plan.steps.iter().map(|step| step.operation.as_ref().unwrap().operation_id.clone()).collect::<Vec<_>>();+ assert_eq!(pins.len(), 2);+ let binding = registry.binding_for_readback(&ids[1]).unwrap();+ assert_eq!(binding.prerequisite_operation_ids, vec![ids[0].clone()]);+ assert!(binding+ .compare+ .as_ref()+ .unwrap()+ .proofs+ .iter()+ .any(|proof| matches!(proof, CatalogReadProof::Query { sql, .. } if sql.contains("ALL_TAB_COLUMNS"))));+ registry.update_references(&[], &ids).unwrap();+ assert!(+ ids.iter().all(|id| registry.observe(id).operation.is_some()),+ "Backend pins own the batch before any approval event"+ );+ drop(pins);+ assert!(ids.iter().all(|id| registry.observe(id).operation.is_none()));+ }+ }+}++#[tokio::test]+async fn pending_table_plan_keeps_complete_pair_and_order_without_registering_approval() {+ let spec = specification("SOURCE", 1);+ let implementation = program("SOURCE", "PKG", db::ObjectSourceKind::PackageBody,+ "CREATE OR REPLACE PACKAGE BODY \"SOURCE\".PKG AS FUNCTION f(p NUMBER) RETURN NUMBER IS n NUMBER; BEGIN SELECT a.TARGET_N INTO n FROM PENDING_REL a; RETURN n+p+g; END f; END PKG;");+ let source = Catalog::new("SOURCE", vec![spec, implementation]);+ let target = Catalog::new("OWNER", Vec::new());+ let input = package::normalize_input(OracleRoutinePlanInput {+ source: snapshot(&source),+ target: snapshot(&target),+ drafts: vec![+ draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Create),+ draft(db::ObjectSourceKind::Package, RoutinePlanAction::Create),+ ],+ })+ .unwrap();+ let tables = vec![super::super::references::PlannedRelation {+ owner: "OWNER".into(),+ name: "PENDING_REL".into(),+ columns: BTreeSet::from(["TARGET_N".into()]),+ }];+ let mut built = build_plan_with_tables(+ Some(&source),+ &target,+ &input,+ SourceOrigin::OceanBaseDictionary,+ SourceOrigin::OceanBaseDictionary,+ |_| Ok(None),+ &tables,+ )+ .await;+ assert!(built.plan.steps.iter().all(|step| step.issues.is_empty()), "{:?}", built.plan.steps);+ assert_eq!(built.order, [1, 0]);+ assert!(!built.plan.ready, "A pending table is not an approved existing relation");+ assert_eq!(built.planned_table_dependencies, [BTreeSet::from([0]), BTreeSet::new()]);+ let manifest = transfer_dependency_manifest(&built, &tables);+ assert_eq!(manifest["order"], serde_json::json!([1, 0]));+ assert_eq!(manifest["steps"][0]["pendingTables"], serde_json::json!([{"owner":"OWNER","name":"PENDING_REL"}]));+ assert_eq!(manifest["steps"][1]["pendingTables"], serde_json::json!([]));+ assert!(manifest["steps"][0]["proofGroups"].as_array().unwrap().iter().any(|group| {+ group["use"]["purpose"] == "loginOwner"+ && group["proofs"].as_array().unwrap().iter().any(|proof| {+ proof+ .get("Query")+ .and_then(|query| query["sql"].as_str())+ .is_some_and(|sql| sql.contains("LOGIN_OWNER"))+ })+ }));+ assert!(!manifest.to_string().contains("expected_config"));+ assert!(built.plan.steps[0].sql.contains("SELECT a.TARGET_N INTO n FROM PENDING_REL a"));+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({"id":"target","name":"test","db_type":"oceanbase-oracle","host":"localhost","port":2881,"username":"OWNER","password":""})).unwrap();+ let registry = RoutineOperationRegistry::default();+ built.plan.ready = true;+ let plan = prepare_built_plan(®istry, &input, built, None, &config).unwrap();+ assert!(!plan.ready);+ assert!(plan.steps.iter().all(|step| step.operation.is_none()));+}++#[tokio::test]+async fn preserved_flow_pair_plans_specification_before_body_without_global_incoming_permissions() {+ let spec = program("SOURCE","PKG_FLOW",db::ObjectSourceKind::Package,"CREATE OR REPLACE PACKAGE PKG_FLOW AS g_bias NUMBER := 1; FUNCTION score(p NUMBER) RETURN NUMBER; END PKG_FLOW;");+ let body_source = include_str!("../../../../../dbx-sql-core/tests/fixtures/oracle_package_flow_body.sql");+ let body = program("SOURCE", "PKG_FLOW", db::ObjectSourceKind::PackageBody, body_source);+ let source = Catalog::new("SOURCE", vec![spec, body]);+ let mut target = Catalog::new("OWNER", Vec::new());+ target.deny_incoming = true;+ let mut body_draft = draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Create);+ body_draft.identity.name = "PKG_FLOW".into();+ let mut spec_draft = draft(db::ObjectSourceKind::Package, RoutinePlanAction::Create);+ spec_draft.identity.name = "PKG_FLOW".into();+ let result = build(&source, &target, vec![body_draft, spec_draft]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert_eq!(result.order, vec![1, 0]);+ assert_eq!(result.plan.steps[0].source_original.as_deref(), Some(body_source));+ for fragment in+ ["IF p < 0 THEN RAISE e_negative", "FOR i IN 1..3 LOOP", "EXCEPTION WHEN VALUE_ERROR", "WHEN OTHERS THEN RAISE"]+ {+ assert!(result.plan.steps[0].sql.contains(fragment));+ }+ assert!(result.plan.steps.iter().all(|step| step.package_impact.as_ref().unwrap().may_initialize));+}++#[tokio::test]+async fn constant_specification_only_is_complete_but_omitted_callable_body_is_explicit() {+ let constant = program(+ "SOURCE",+ "PKG",+ db::ObjectSourceKind::Package,+ "CREATE OR REPLACE PACKAGE \"SOURCE\".PKG AS g NUMBER := 1; END PKG;",+ );+ let source = Catalog::new("SOURCE", vec![constant]);+ let target = Catalog::new("OWNER", Vec::new());+ let result = build(&source, &target, vec![draft(db::ObjectSourceKind::Package, RoutinePlanAction::Create)]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert!(!result.plan.steps[0].package_impact.as_ref().unwrap().body_pending);+ let source = Catalog::new("SOURCE", vec![specification("SOURCE", 1), body("SOURCE")]);+ let mut spec = draft(db::ObjectSourceKind::Package, RoutinePlanAction::Create);+ assert!(!build(&source, &target, vec![spec.clone()]).await.plan.ready);+ spec.confirm_package_pair = true;+ let result = build(&source, &target, vec![spec]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert!(result.plan.steps[0].package_impact.as_ref().unwrap().body_pending);+}++#[tokio::test]+async fn body_only_uses_matching_complete_spec_and_target_contract_is_an_explicit_choice() {+ let source = Catalog::new("SOURCE", vec![specification("SOURCE", 1), body("SOURCE")]);+ let mut target = Catalog::new("OWNER", vec![specification("OWNER", 1)]);+ target.deny_incoming = true;+ let body = draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Create);+ assert!(build(&source, &target, vec![body.clone()]).await.plan.ready);+ target.objects[0].source = Some(target.objects[0].source.as_ref().unwrap().replace("DEFAULT 1", "DEFAULT 2"));+ let result = build(&source, &target, vec![body.clone()]).await;+ assert!(!result.plan.ready);+ assert!(result.plan.steps[0].issues.iter().any(|issue| issue.message.contains("specifications differ")));+ let mut explicit = body;+ explicit.package_contract = Some(PackageContractChoice::Target);+ let result = build(&source, &target, vec![explicit]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert!(result.plan.steps[0].package_impact.as_ref().unwrap().may_initialize);+}++#[tokio::test]+async fn body_only_repairs_an_invalid_body_with_unterminated_dictionary_specification() {+ let mut source_spec = specification("SOURCE", 1);+ source_spec.source = source_spec.source.map(|sql| sql.trim_end_matches(';').to_string());+ let source = Catalog::new("SOURCE", vec![source_spec, body("SOURCE")]);+ let mut target_spec = specification("OWNER", 1);+ target_spec.source = target_spec.source.map(|sql| sql.trim_end_matches(';').to_string());+ let mut invalid_body = body("OWNER");+ invalid_body.version.status = "INVALID".into();+ invalid_body.source = invalid_body.source.map(|sql| sql.replace("RETURN NUMBER IS", "RETURN VARCHAR2 IS"));+ let target = Catalog::new("OWNER", vec![target_spec, invalid_body]);+ let result =+ build(&source, &target, vec![draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Replace)]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert_eq!(result.plan.steps.len(), 1);+ assert_eq!(result.plan.steps[0].identity.kind, db::ObjectSourceKind::PackageBody);+ assert_eq!(result.plan.steps[0].target_original, target.objects[1].source);+ assert!(result.plan.steps[0].recovery_sql.as_deref().unwrap().contains("RETURN VARCHAR2 IS"));+ let mut wrong = draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Replace);+ wrong.sql = Some(+ source.objects[1]+ .source+ .as_ref()+ .unwrap()+ .replace("\"SOURCE\"", "\"OWNER\"")+ .replace("RETURN NUMBER IS", "RETURN VARCHAR2 IS"),+ );+ let rejected = build(&source, &target, vec![wrong]).await;+ assert!(!rejected.plan.ready);+ assert!(+ rejected.plan.steps[0]+ .issues+ .iter()+ .any(|issue| issue.message.contains("does not match its final specification signature")),+ "{:?}",+ rejected.plan.steps+ );+}++#[tokio::test]+async fn body_only_cannot_create_without_a_target_specification_or_match_a_wrong_public_return_type() {+ let source = Catalog::new("SOURCE", vec![specification("SOURCE", 1), body("SOURCE")]);+ let missing = build(+ &source,+ &Catalog::new("OWNER", Vec::new()),+ vec![draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Create)],+ )+ .await;+ assert!(!missing.plan.ready);+ let mut body = draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Create);+ body.sql = Some(+ source.objects[1]+ .source+ .as_ref()+ .unwrap()+ .replace("\"SOURCE\"", "\"OWNER\"")+ .replace("RETURN NUMBER IS", "RETURN VARCHAR2 IS"),+ );+ let target = Catalog::new("OWNER", vec![specification("OWNER", 1)]);+ assert!(!build(&source, &target, vec![body]).await.plan.ready);+}++#[tokio::test]+async fn specification_replacement_requires_an_explicit_body_action_even_when_old_body_is_valid() {+ let source = Catalog::new("SOURCE", vec![specification("SOURCE", 2)]);+ let target = Catalog::new("OWNER", vec![specification("OWNER", 1), body("OWNER")]);+ let mut spec = draft(db::ObjectSourceKind::Package, RoutinePlanAction::Replace);+ spec.confirm_package_pair = true;+ let result = build(&source, &target, vec![spec.clone()]).await;+ assert!(!result.plan.ready);+ assert!(result.plan.steps[0].issues.iter().any(|issue| issue.message.contains("explicit source body")));+ let mut retained = draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Replace);+ retained.package_body_source = Some(PackageBodySource::Target);+ let result = build(&source, &target, vec![spec, retained]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert_eq!(result.order, vec![0, 1]);+ assert_eq!(result.plan.steps[1].source_original, None);+ assert_eq!(result.plan.steps[1].target_original, target.objects[1].source);+ assert!(result.plan.steps[1].package_impact.as_ref().unwrap().retains_target_body);+}++#[tokio::test]+async fn specification_with_explicit_body_deletion_records_the_specification_only_scope() {+ let source = Catalog::new("SOURCE", vec![specification("SOURCE", 2)]);+ let target = Catalog::new("OWNER", vec![specification("OWNER", 1), body("OWNER")]);+ let mut spec = draft(db::ObjectSourceKind::Package, RoutinePlanAction::Replace);+ spec.confirm_package_pair = true;+ let result =+ build(&source, &target, vec![spec, draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Delete)]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert_eq!(result.order, vec![1, 0]);+ assert!(result.plan.steps[0].package_impact.as_ref().unwrap().body_pending);+}++#[tokio::test]+async fn retained_body_is_checked_against_new_specification_not_its_old_valid_status() {+ let mut new_spec = specification("SOURCE", 2);+ new_spec.source = Some(new_spec.source.unwrap().replace("RETURN NUMBER", "RETURN VARCHAR2"));+ let source = Catalog::new("SOURCE", vec![new_spec]);+ let target = Catalog::new("OWNER", vec![specification("OWNER", 1), body("OWNER")]);+ let mut spec = draft(db::ObjectSourceKind::Package, RoutinePlanAction::Replace);+ spec.confirm_package_pair = true;+ let mut retained = draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Replace);+ retained.package_body_source = Some(PackageBodySource::Target);+ let result = build(&source, &target, vec![spec, retained]).await;+ assert!(!result.plan.ready);+ assert!(result.plan.steps[1].issues.iter().any(|issue| issue.message.contains("final specification")));+}++#[tokio::test]+async fn whole_package_delete_collapses_body_drop_and_never_confirms_away_external_callers() {+ let source = Catalog::new("SOURCE", Vec::new());+ let mut target = Catalog::new("OWNER", vec![specification("OWNER", 1), body("OWNER")]);+ target.incoming.insert(+ "PKG".into(),+ vec![RoutineDependency {+ owner: "OWNER".into(),+ name: "PKG".into(),+ kind: "PACKAGE BODY".into(),+ database_link: None,+ dependency_type: "HARD".into(),+ }],+ );+ let mut spec = draft(db::ObjectSourceKind::Package, RoutinePlanAction::Delete);+ spec.confirm_package_pair = true;+ let result = build(+ &source,+ &target,+ vec![spec.clone(), draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Delete)],+ )+ .await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert_eq!(result.plan.steps.len(), 1);+ assert_eq!(result.plan.steps[0].sql, "DROP PACKAGE \"OWNER\".\"PKG\";");+ assert!(result.plan.steps[0].package_impact.as_ref().unwrap().implicit_companion_delete);+ target.incoming.get_mut("PKG").unwrap().push(RoutineDependency {+ owner: "OUTSIDE".into(),+ name: "CALLER".into(),+ kind: "FUNCTION".into(),+ database_link: None,+ dependency_type: "HARD".into(),+ });+ assert!(!build(&source, &target, vec![spec]).await.plan.ready);+}++#[tokio::test]+async fn body_delete_keeps_the_specification_without_requiring_global_caller_visibility() {+ let source = Catalog::new("SOURCE", vec![specification("SOURCE", 1)]);+ let mut target = Catalog::new("OWNER", vec![specification("OWNER", 1), body("OWNER")]);+ target.deny_incoming = true;+ let result =+ build(&source, &target, vec![draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Delete)]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert_eq!(result.plan.steps[0].sql, "DROP PACKAGE BODY \"OWNER\".\"PKG\";");+ assert!(result.preflights[0].as_ref().unwrap().incoming.is_none());+}++#[tokio::test]+async fn target_grants_are_backed_up_and_rechecked_without_copying_source_privileges() {+ let source = Catalog::new("SOURCE", Vec::new());+ let mut target = Catalog::new("OWNER", vec![specification("OWNER", 1), body("OWNER")]);+ target.grants.push(PackageGrant {+ grantor: "OWNER".into(),+ grantee: "READER".into(),+ privilege: "EXECUTE".into(),+ grantable: true,+ });+ let mut spec = draft(db::ObjectSourceKind::Package, RoutinePlanAction::Delete);+ spec.confirm_package_pair = true;+ let result = build(&source, &target, vec![spec]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ let grants = result.plan.steps[0].package_impact.as_ref().unwrap().grants.as_ref().unwrap();+ assert!(grants.complete);+ assert_eq!(grants.grants, target.grants);+ let preflight = result.preflights[0].as_ref().unwrap();+ verify_compare_preflight(+ None::<&Catalog>,+ &target,+ &endpoint("OWNER"),+ preflight,+ SourceOrigin::OceanBaseDictionary,+ )+ .await+ .unwrap();+ target.changed_grants.store(true, Ordering::SeqCst);+ assert!(verify_compare_preflight(+ None::<&Catalog>,+ &target,+ &endpoint("OWNER"),+ preflight,+ SourceOrigin::OceanBaseDictionary+ )+ .await+ .is_err());+}++#[tokio::test]+async fn complete_pair_preflight_rejects_companion_only_edits_with_unchanged_specification_version() {+ let source = Catalog::new("SOURCE", vec![specification("SOURCE", 2)]);+ let target = Catalog::new("OWNER", vec![specification("OWNER", 1), body("OWNER")]);+ let mut spec = draft(db::ObjectSourceKind::Package, RoutinePlanAction::Replace);+ spec.confirm_package_pair = true;+ let mut retained = draft(db::ObjectSourceKind::PackageBody, RoutinePlanAction::Replace);+ retained.package_body_source = Some(PackageBodySource::Target);+ let result = build(&source, &target, vec![spec, retained]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ target.changed_body.store(true, Ordering::SeqCst);+ assert!(verify_compare_preflight(+ None::<&Catalog>,+ &target,+ &endpoint("OWNER"),+ result.preflights[0].as_ref().unwrap(),+ SourceOrigin::OceanBaseDictionary+ )+ .await+ .is_err());+}++#[tokio::test]+async fn unreadable_grants_are_an_explicit_recovery_gap_not_a_complete_empty_backup() {+ let source = Catalog::new("SOURCE", Vec::new());+ let mut target = Catalog::new("OWNER", vec![specification("OWNER", 1), body("OWNER")]);+ target.deny_grants = true;+ let mut spec = draft(db::ObjectSourceKind::Package, RoutinePlanAction::Delete);+ spec.confirm_package_pair = true;+ let result = build(&source, &target, vec![spec]).await;+ assert!(result.plan.ready, "{:?}", result.plan.steps);+ assert!(!result.plan.steps[0].recovery_complete);+ let grants = result.plan.steps[0].package_impact.as_ref().unwrap().grants.as_ref().unwrap();+ assert!(!grants.complete && grants.issue.is_some());+}diff --git a/crates/dbx-core/src/schema/oracle_routines/plan/recovery.rs b/crates/dbx-core/src/schema/oracle_routines/plan/recovery.rsindex c319987abe..15b9fa1fd0 100644--- a/crates/dbx-core/src/schema/oracle_routines/plan/recovery.rs+++ b/crates/dbx-core/src/schema/oracle_routines/plan/recovery.rs@@ -1,5 +1,8 @@use super::*;+mod package_recovery;+pub(in crate::schema::oracle_routines) use package_recovery::prepare_package_recovery;+/// 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(@@ -7,7 +10,7 @@ pub async fn prepare_oracle_routine_recovery_core(operation_id: &str,) -> Result<OracleRoutinePlan, String> {let _original_pin = state.routine_operations.pin(operation_id)?;- let original = state+ let mut original = state.routine_operations.observe(operation_id).operation@@ -16,10 +19,17 @@ pub async fn prepare_oracle_routine_recovery_core(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)?;+ if package::is_package(&original.identity.kind) {+ let config = checked_endpoint(state, &original.target).await?;+ let catalog = LiveCatalog { state, endpoint: &original.target, config: &config };+ let (_, origin) = routine_source_origin(&config)?;+ return prepare_package_recovery(&state.routine_operations, operation_id, &catalog, &config, origin).await;+ }+ original.readback = Some(state.routine_operations.recovery_post_state(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 current = correction_baseline(original.clone(), &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)?;@@ -40,6 +50,7 @@ pub async fn prepare_oracle_routine_recovery_core(require_absent: step.action == RoutinePlanAction::Create,compare: result.preflight.take(),prerequisite_operation_ids: Vec::new(),+ package_effect_operation_ids: Vec::new(),},None,)?);@@ -101,6 +112,7 @@ async fn recovery_plan(incoming_callers: Vec::new(),issues: Vec::new(),operation: None,+ package_impact: None,};let mut preflight = None;let prepared: Result<(), String> = async {@@ -130,7 +142,7 @@ async fn recovery_plan(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()] });+ preflight = Some(ComparePreflight { source: None, target: current.clone(), proofs, incoming: Some(incoming), selected: vec![identity.clone()], package:None });Ok(())}.await;if let Err(error) = prepared {@@ -216,6 +228,8 @@ mod tests {exists: Some(true),version: None,source: Some("approved".into()),+ source_origin: None,+ package_companion: None,definition_matches: Some(true),compiler_messages: Vec::new(),issues: Vec::new(),diff --git a/crates/dbx-core/src/schema/oracle_routines/plan/recovery/package_recovery.rs b/crates/dbx-core/src/schema/oracle_routines/plan/recovery/package_recovery.rsnew file mode 100644index 0000000000..efb9d74479--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/plan/recovery/package_recovery.rs@@ -0,0 +1,235 @@+use super::*;++fn acknowledged_record(registry: &RoutineOperationRegistry, id: &str) -> Result<RoutineOperationRecord, String> {+ let mut record = registry.observe(id).operation.ok_or("Original package operation is unavailable")?;+ let binding = registry.binding_for_readback(id)?;+ record.readback = Some(registry.recovery_post_state(id)?);+ check_recovery_receipt(&record, &binding.goal)?;+ Ok(record)+}++fn snapshot(endpoint: &RoutineEndpoint, pair: &ExpectedPackagePair) -> RoutineSnapshot {+ RoutineSnapshot {+ endpoint: endpoint.clone(),+ state: RoutineReadState::Complete,+ enumeration_complete: true,+ objects: [&pair.specification, &pair.body]+ .into_iter()+ .filter_map(|expected| match expected {+ ExpectedRoutine::Present(object) => Some(object.clone()),+ ExpectedRoutine::Absent(_) => None,+ })+ .collect(),+ issues: Vec::new(),+ }+}++fn same_definition(before: &ExpectedRoutine, current: &ExpectedRoutine) -> bool {+ match (before, current) {+ (ExpectedRoutine::Absent(left), ExpectedRoutine::Absent(right)) => left == right,+ (ExpectedRoutine::Present(left), ExpectedRoutine::Present(right)) => {+ left.version.identity == right.version.identity+ && left.version.status == right.version.status+ && left.source == right.source+ && left.source_origin == right.source_origin+ }+ _ => false,+ }+}++fn draft(before: &ExpectedRoutine, current: &ExpectedRoutine) -> Option<RoutinePlanDraft> {+ let action = match (before, current) {+ (ExpectedRoutine::Absent(_), ExpectedRoutine::Absent(_)) => return None,+ (ExpectedRoutine::Absent(_), ExpectedRoutine::Present(_)) => RoutinePlanAction::Delete,+ (ExpectedRoutine::Present(_), ExpectedRoutine::Absent(_)) => RoutinePlanAction::Create,+ _ => RoutinePlanAction::Replace,+ };+ Some(RoutinePlanDraft {+ identity: before.identity().clone(),+ action,+ source_name: None,+ sql: None,+ baseline_operation_id: None,+ supersedes_operation_id: None,+ package_body_source: None,+ package_contract: None,+ confirm_package_pair: true,+ })+}++pub(in crate::schema::oracle_routines) async fn prepare_package_recovery(+ registry: &RoutineOperationRegistry,+ operation_id: &str,+ catalog: &impl RoutineCatalog,+ config: &ConnectionConfig,+ origin: SourceOrigin,+) -> Result<OracleRoutinePlan, String> {+ let _pin = registry.pin(operation_id)?;+ let original = acknowledged_record(registry, operation_id)?;+ let binding = registry.binding_for_readback(operation_id)?;+ let backup = binding+ .compare+ .as_ref()+ .and_then(|compare| compare.package.as_ref())+ .ok_or("The original package write has no frozen pair recovery material")?;+ let mut current = ExpectedPackagePair::from_readback(original.readback.as_ref().unwrap())?;+ let mut grants = backup.grants.clone();+ for related_id in &binding.package_effect_operation_ids {+ let related_binding = registry.binding_for_readback(related_id)?;+ if related_binding.identity.owner != binding.identity.owner+ || related_binding.identity.name != binding.identity.name+ {+ continue;+ }+ if related_binding.target != binding.target || related_binding.expected_config != binding.expected_config {+ return Err("Related package recovery material belongs to another target".into());+ }+ if related_binding.identity.kind == db::ObjectSourceKind::Package && grants.is_none() {+ grants = related_binding+ .compare+ .as_ref()+ .and_then(|compare| compare.package.as_ref())+ .and_then(|package| package.grants.clone());+ }+ let related = registry.observe(related_id).operation.ok_or("A related package operation is unavailable")?;+ if related.lifecycle == RoutineOperationLifecycle::Prepared+ || (related.lifecycle == RoutineOperationLifecycle::Terminal && !related.dispatched)+ {+ continue;+ }+ let related = acknowledged_record(registry, related_id)?;+ if binding.prerequisite_operation_ids.contains(related_id) {+ continue;+ }+ if !related_binding.prerequisite_operation_ids.iter().any(|id| id == operation_id) {+ return Err("The related package write has no proven execution order for recovery".into());+ }+ let post = related.readback.as_ref().unwrap();+ let companion =+ post.package_companion.as_deref().ok_or("The related package write has no complete pair receipt")?;+ let expected = if companion.identity.kind == db::ObjectSourceKind::Package {+ ¤t.specification+ } else {+ ¤t.body+ };+ if !package::definition_identity_matches(expected, companion) {+ return Err(+ "The related package write cannot explain a changed definition, identity or actual origin".into()+ );+ }+ current = ExpectedPackagePair::from_readback(post)?;+ }+ package::verify_pair(catalog, &original.target, ¤t, origin).await?;+ let before = &backup.pair;+ let restore_spec = !same_definition(&before.specification, ¤t.specification);+ if matches!(&before.specification, ExpectedRoutine::Absent(_))+ && matches!(&before.body, ExpectedRoutine::Present(_))+ {+ let mut steps = Vec::new();+ for (saved, actual) in [(&before.specification, ¤t.specification), (&before.body, ¤t.body)] {+ let Some(mut proposed) = draft(saved, actual) else { continue };+ if saved.identity().kind == db::ObjectSourceKind::PackageBody && restore_spec {+ proposed.action = RoutinePlanAction::Create;+ }+ let mut step = OracleRoutinePlanStep {+ identity: saved.identity().clone(),+ action: proposed.action,+ sql: String::new(),+ source_original: match saved { ExpectedRoutine::Present(object) => object.source.clone(), _ => None },+ target_original: match actual { ExpectedRoutine::Present(object) => object.source.clone(), _ => None },+ recovery_sql: None,+ recovery_complete: false,+ references: Vec::new(),+ incoming_callers: Vec::new(),+ issues: vec![problem("The original package had a body without a specification. Retain its complete definition and review recovery manually; dropping the specification also deletes the current body, and recreating the original orphan is not a verified package recovery")],+ operation: None,+ package_impact: None,+ };+ match saved {+ ExpectedRoutine::Absent(identity) => step.sql = drop_sql(identity),+ ExpectedRoutine::Present(object) => {+ match adapted(+ &original.target,+ saved.identity(),+ &saved.identity().owner,+ object.source.as_deref().ok_or("Original complete package body is unavailable")?,+ proposed.action == RoutinePlanAction::Replace,+ ) {+ Ok(sql) => step.sql = sql,+ Err(error) => step.issues.push(problem(error)),+ }+ }+ }+ steps.push(step);+ }+ return Ok(OracleRoutinePlan { target: original.target, steps, ready: false });+ }+ let mut drafts = Vec::new();+ if restore_spec {+ if let Some(step) = draft(&before.specification, ¤t.specification) {+ drafts.push(step);+ }+ }+ if (!matches!(&before.specification, ExpectedRoutine::Absent(_)) || !restore_spec)+ && (restore_spec || !same_definition(&before.body, ¤t.body))+ {+ if let Some(step) = draft(&before.body, ¤t.body) {+ drafts.push(step);+ }+ }+ if drafts.is_empty() {+ return Err("The recorded package pair already has its backed-up definitions; no recovery DDL is needed".into());+ }+ let mut target = snapshot(&original.target, ¤t);+ for object in &mut target.objects {+ object.dependencies = dependencies(catalog, &object.version.identity).await?;+ object.dependencies_complete = true;+ }+ let input = package::normalize_input(OracleRoutinePlanInput {+ source: snapshot(&original.target, before),+ target,+ drafts,+ })?;+ let mut built = build_plan(None::<&LiveCatalog<'_>>, catalog, &input, origin, origin, |_| Ok(None)).await;+ if restore_spec {+ let (observed, proofs) = package::read_grants(catalog, before.specification.identity()).await;+ let issue = if !observed.complete {+ Some("Current package grants cannot be completely verified; keep the recovery drafts and refresh with sufficient visibility")+ } else if matches!(&before.specification, ExpectedRoutine::Absent(_)) {+ (!observed.grants.is_empty())+ .then_some("New grants exist on the deployed package; recovery deletion would lose them")+ } else {+ match &grants {+ Some(grants) if grants.complete && grants.grants == observed.grants => None,+ Some(grants) if grants.complete => {+ Some(if matches!(¤t.specification, ExpectedRoutine::Absent(_)) {+ "The dropped package's original grants are not restored by recreating definitions; restore and review those grants explicitly before claiming complete recovery"+ } else {+ "Package grants changed after the original approval; retain the drafts and review the target instead"+ })+ }+ _ => Some(+ "Original package grants were not completely backed up; complete one-click recovery is unavailable",+ ),+ }+ };+ for (step, preflight) in built.plan.steps.iter_mut().zip(&mut built.preflights) {+ if let Some(preflight) = preflight {+ preflight.proofs.extend(proofs.clone());+ }+ if let Some(issue) = issue {+ step.issues.push(problem(issue));+ step.recovery_complete = false;+ }+ if let Some(impact) = &mut step.package_impact {+ if step.identity.kind == db::ObjectSourceKind::Package {+ impact.grants = grants.clone().or_else(|| Some(observed.clone()));+ }+ }+ }+ if issue.is_some() {+ built.plan.ready = false;+ }+ }+ prepare_built_plan(registry, &input, built, None, config)+}diff --git a/crates/dbx-core/src/schema/oracle_routines/plan/tests.rs b/crates/dbx-core/src/schema/oracle_routines/plan/tests.rsindex 225252066b..b0078d23c4 100644--- a/crates/dbx-core/src/schema/oracle_routines/plan/tests.rs+++ b/crates/dbx-core/src/schema/oracle_routines/plan/tests.rs@@ -3,19 +3,38 @@ 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) owner: &'static str,+ pub(super) objects: Vec<RoutineObjectSnapshot>,+ pub(super) incoming: BTreeMap<String, Vec<RoutineDependency>>,+ pub(super) deny_incoming: bool,+ pub(super) grants: Vec<PackageGrant>,+ pub(super) deny_grants: bool,+ pub(super) changed_body: AtomicBool,+ pub(super) changed_grants: AtomicBool,pub(super) changed_source: AtomicBool,+ pub(super) tables: BTreeMap<String, Vec<String>>,}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) }+ Self {+ owner,+ objects,+ incoming: BTreeMap::new(),+ deny_incoming: false,+ changed_source: AtomicBool::new(false),+ grants: Vec::new(),+ deny_grants: false,+ changed_body: AtomicBool::new(false),+ changed_grants: AtomicBool::new(false),+ tables: BTreeMap::new(),+ }}fn source_text(&self, object: &RoutineObjectSnapshot) -> String {let source = object.source.as_ref().unwrap();- if self.changed_source.load(Ordering::SeqCst) {+ if self.changed_source.load(Ordering::SeqCst)+ || (object.version.identity.kind == db::ObjectSourceKind::PackageBody+ && self.changed_body.load(Ordering::SeqCst))+ {format!("{source} -- concurrent edit")} else {source.clone()@@ -34,7 +53,7 @@ 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())+ Ok(serde_json::from_value(json!({"name":identity.name,"schema":identity.owner,"object_type":identity.kind,"source":self.source_text(object),"source_origin":matches!(identity.kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody).then_some("oceanbase-dictionary")})).unwrap())}async fn query(&self, sql: &str) -> Result<CatalogReply, String> {if sql.contains("LOGIN_OWNER") {@@ -43,7 +62,7 @@ impl RoutineCatalog for Catalog {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+ let mut rows: Vec<Vec<Value>> = self.objects.iter().filter(|object| object.version.identity.owner == owner && object.version.identity.name == name)@@ -59,14 +78,67 @@ impl RoutineCatalog for Catalog {]}).collect();+ if owner == self.owner && self.tables.contains_key(&name) {+ rows.push(vec![+ json!(owner),+ json!(name),+ json!("TABLE"),+ json!(100),+ json!("VALID"),+ json!("2026-10-23T00:00:00"),+ ]);+ }return Ok(reply(&["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "STATUS", "LAST_DDL_TIME"], rows));}+ if sql.contains("ALL_TAB_COLUMNS") {+ let table = name_from(sql, "TABLE_NAME");+ let columns = self.tables.get(&table).ok_or("Target table is unavailable")?;+ let rows = columns+ .iter()+ .enumerate()+ .map(|(index, name)| vec![json!(index + 16), json!(name), json!(index + 1)])+ .collect();+ return Ok(reply(&["COLUMN_ID", "COLUMN_NAME", "RN"], rows));+ }if sql.contains("ALL_ERRORS") {return Ok(reply(&["SEQUENCE", "ATTRIBUTE", "LINE", "POSITION", "TEXT"], Vec::new()));}+ if sql.contains("ALL_TAB_PRIVS") {+ if self.deny_grants {+ return Err("ORA-00942: grant visibility unavailable".into());+ }+ let offset =+ sql.split("WHERE RN > ").nth(1).unwrap().split_whitespace().next().unwrap().parse::<usize>().unwrap();+ let rows = self+ .grants+ .iter()+ .enumerate()+ .skip(offset)+ .take(PAGE_SIZE)+ .map(|(index, grant)| {+ vec![+ json!(grant.grantor),+ json!(grant.grantee),+ json!(if self.changed_grants.load(Ordering::SeqCst) {+ "DEBUG"+ } else {+ grant.privilege.as_str()+ }),+ json!(if grant.grantable { "YES" } else { "NO" }),+ json!(index + 1),+ ]+ })+ .collect();+ return Ok(reply(&["GRANTOR", "GRANTEE", "PRIVILEGE", "GRANTABLE", "RN"], rows));+ }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 kind = name_from(sql, "TYPE");+ let object = self+ .objects+ .iter()+ .find(|object| object.version.identity.name == name && kind_name(&object.version.identity.kind) == kind)+ .unwrap();let source = self.source_text(object);let body = source.strip_prefix("CREATE OR REPLACE ").unwrap();return Ok(reply(@@ -108,7 +180,12 @@ impl RoutineCatalog for Catalog {}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 kind = name_from(sql, "TYPE");+ let object = self+ .objects+ .iter()+ .find(|object| object.version.identity.name == name && kind_name(&object.version.identity.kind) == kind)+ .unwrap();let rows = object.dependencies.iter()@@ -158,13 +235,14 @@ pub(super) fn object(owner: &str, name: &str, expression: &str) -> RoutineObjectlast_ddl_time: "2026-10-21T00:00:00".into(),},source: Some(format!("CREATE OR REPLACE FUNCTION \"{name}\" RETURN NUMBER AS BEGIN RETURN {expression}; END")),+ source_origin: None,source_complete: true,dependencies: Vec::new(),dependencies_complete: true,issues: Vec::new(),}}-fn snapshot(catalog: &Catalog) -> RoutineSnapshot {+pub(super) fn snapshot(catalog: &Catalog) -> RoutineSnapshot {RoutineSnapshot {endpoint: endpoint(catalog.owner),state: RoutineReadState::Complete,@@ -173,7 +251,7 @@ fn snapshot(catalog: &Catalog) -> RoutineSnapshot {issues: Vec::new(),}}-fn draft(name: &str, action: RoutinePlanAction) -> RoutinePlanDraft {+pub(super) fn draft(name: &str, action: RoutinePlanAction) -> RoutinePlanDraft {RoutinePlanDraft {identity: object("OWNER", name, "1").version.identity,action,@@ -181,16 +259,117 @@ fn draft(name: &str, action: RoutinePlanAction) -> RoutinePlanDraft {sql: None,baseline_operation_id: None,supersedes_operation_id: None,+ package_body_source: None,+ package_contract: None,+ confirm_package_pair: false,}}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)- })+ build_plan(+ Some(source),+ target,+ input,+ SourceOrigin::OceanBaseDictionary,+ SourceOrigin::OceanBaseDictionary,+ |_| Ok(None),+ )+ .await+}++#[test]+fn snapshot_lookup_distinguishes_package_kinds_but_retains_shared_namespace_conflicts() {+ let mut spec = object("OWNER", "Pkg.With.Dot", "1");+ spec.version.identity.kind = db::ObjectSourceKind::Package;+ let mut body = spec.clone();+ body.version.identity.kind = db::ObjectSourceKind::PackageBody;+ body.version.object_id = "999".into();+ let mut snapshot = snapshot(&Catalog::new("OWNER", vec![spec.clone(), body.clone()]));+ assert_eq!(+ snapshot_object(&snapshot, "Pkg.With.Dot", &db::ObjectSourceKind::Package).unwrap().unwrap().version,+ spec.version+ );+ assert_eq!(+ snapshot_object(&snapshot, "Pkg.With.Dot", &db::ObjectSourceKind::PackageBody).unwrap().unwrap().version,+ body.version+ );+ snapshot.objects.pop();+ assert!(snapshot_object(&snapshot, "Pkg.With.Dot", &db::ObjectSourceKind::PackageBody).unwrap().is_none());+ snapshot.objects.push(spec.clone());+ assert!(snapshot_object(&snapshot, "Pkg.With.Dot", &db::ObjectSourceKind::Package).is_err());+ snapshot.objects.pop();+ snapshot.objects.push(object("OWNER", "Pkg.With.Dot", "1"));+ assert!(snapshot_object(&snapshot, "Pkg.With.Dot", &db::ObjectSourceKind::Package).is_err());+ assert!(snapshot_object(&snapshot, "Pkg.With.Dot", &db::ObjectSourceKind::Function).is_err());+}++#[test]+fn public_plan_selection_allows_exact_package_kinds_without_expanding_cross_product_or_other_kind_selection() {+ let catalog = Catalog::new("OWNER", Vec::new());+ let mut input = OracleRoutinePlanInput {+ source: snapshot(&catalog),+ target: snapshot(&catalog),+ drafts: vec![RoutinePlanDraft {+ identity: RoutineIdentity {+ owner: "OWNER".into(),+ name: "PKG".into(),+ kind: db::ObjectSourceKind::Package,+ },+ action: RoutinePlanAction::Create,+ source_name: None,+ sql: None,+ baseline_operation_id: None,+ supersedes_operation_id: None,+ package_body_source: None,+ package_contract: None,+ confirm_package_pair: false,+ }],+ };+ for kind in [+ db::ObjectSourceKind::Procedure,+ db::ObjectSourceKind::Function,+ db::ObjectSourceKind::Package,+ db::ObjectSourceKind::PackageBody,+ ] {+ input.drafts[0].identity.kind = kind;+ assert!(check_plan_selection(&input).is_ok());+ }+ input.drafts[0].identity.kind = db::ObjectSourceKind::Type;+ assert!(check_plan_selection(&input).is_err());+ input.drafts[0].identity.kind = db::ObjectSourceKind::Package;+ input.target.endpoint.database_type = DatabaseType::Oracle;+ assert!(check_plan_selection(&input).is_ok());+ input.drafts[0].identity.kind = db::ObjectSourceKind::Function;+ assert!(check_plan_selection(&input).unwrap_err().contains("Cross-product"));+ input.drafts.clear();+ input.target.endpoint.database_type = input.source.endpoint.database_type;+ assert!(check_plan_selection(&input).is_err());+}++#[tokio::test]+async fn package_preflight_requires_the_actual_preview_origin_even_when_text_and_version_match() {+ let mut specification = object("OWNER", "PKG", "1");+ specification.version.identity.kind = db::ObjectSourceKind::Package;+ specification.source = Some("CREATE OR REPLACE PACKAGE \"OWNER\".PKG AS g NUMBER; END PKG;".into());+ specification.source_origin = Some(SourceOrigin::OceanBaseDictionary);+ let catalog = Catalog::new("OWNER", vec![specification.clone()]);+ verify_expected(+ &catalog,+ &endpoint("OWNER"),+ &ExpectedRoutine::Present(specification.clone()),+ SourceOrigin::OceanBaseDictionary,+ ).await+ .unwrap();+ for source_origin in [None, Some(SourceOrigin::OracleMetadata)] {+ let expected = ExpectedRoutine::Present(RoutineObjectSnapshot { source_origin, ..specification.clone() });+ assert!(verify_expected(&catalog, &endpoint("OWNER"), &expected, SourceOrigin::OceanBaseDictionary)+ .await+ .unwrap_err()+ .contains("origin"));+ }}#[tokio::test]@@ -385,12 +564,14 @@ async fn terminal_invalid_create_can_be_corrected_as_an_explicit_new_replace_appinput.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,+ Some(&source),&target,&input,SourceOrigin::OceanBaseDictionary,SourceOrigin::OceanBaseDictionary,- |_| Ok(Some(ExpectedRoutine::Present(target.objects[0].clone()))),+ |_| {+ Ok(Some(RoutineBaseline { selected: ExpectedRoutine::Present(target.objects[0].clone()), companion: None }))+ },).await;assert!(result.plan.ready, "{:?}", result.plan.steps);@@ -418,6 +599,8 @@ fn correction_record() -> RoutineOperationRecord {exists: Some(true),version: Some(object.version),source: object.source,+ source_origin: None,+ package_companion: None,definition_matches: Some(true),compiler_messages: Vec::new(),issues: Vec::new(),diff --git a/crates/dbx-core/src/schema/oracle_routines/readback.rs b/crates/dbx-core/src/schema/oracle_routines/readback.rsindex 5f71643483..cc2af0e103 100644--- a/crates/dbx-core/src/schema/oracle_routines/readback.rs+++ b/crates/dbx-core/src/schema/oracle_routines/readback.rs@@ -29,7 +29,7 @@ pub enum RoutineReadbackGoal {Inspect,}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "camelCase")]pub struct RoutineReadback {pub identity: RoutineIdentity,@@ -37,6 +37,10 @@ pub struct RoutineReadback {pub exists: Option<bool>,pub version: Option<RoutineVersion>,pub source: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub source_origin: Option<SourceOrigin>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub package_companion: Option<Box<RoutineReadback>>,pub definition_matches: Option<bool>,pub compiler_messages: Vec<RoutineCompilerMessage>,pub issues: Vec<RoutineReadIssue>,@@ -82,11 +86,16 @@ pub(super) async fn read_namespace(dba: bool,) -> Result<CatalogReply, String> {let view = if dba { "SYS.DBA_OBJECTS" } else { "ALL_OBJECTS" };+ let body_kind = if matches!(identity.kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody) {+ ",'PACKAGE BODY'"+ } else {+ ""+ };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",+ ('TABLE','VIEW','SEQUENCE','PROCEDURE','FUNCTION','PACKAGE','MATERIALIZED VIEW','TYPE','SYNONYM'{body_kind}) ORDER BY OBJECT_ID",literal(&identity.owner), literal(&identity.name),)).await?;reply.flags.check()?;@@ -94,22 +103,40 @@ pub(super) async fn read_namespace(}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());+ namespace_version(reply, identity)?+ .ok_or_else(|| "Routine namespace does not contain the requested object kind".into())+}++fn namespace_version(reply: &CatalogReply, identity: &RoutineIdentity) -> Result<Option<RoutineVersion>, String> {+ let counterpart = match identity.kind {+ db::ObjectSourceKind::Package => Some("PACKAGE BODY"),+ db::ObjectSourceKind::PackageBody => Some("PACKAGE"),+ _ => None,+ };+ let mut matched = None;+ let mut has_counterpart = false;+ for row in &reply.rows {+ if reply.text(row, "OWNER")? != identity.owner || reply.text(row, "OBJECT_NAME")? != identity.name {+ return Err("Routine namespace contains a different owner or name".into());+ }+ let kind = reply.text(row, "OBJECT_TYPE")?;+ if kind == kind_name(&identity.kind) {+ if matched.replace(row).is_some() {+ return Err("Routine namespace contains duplicate exact identities".into());+ }+ } else if counterpart == Some(kind.as_str()) && !has_counterpart {+ has_counterpart = true;+ } else {+ return Err("Routine namespace is ambiguous or has a different object kind".into());+ }}- Ok(RoutineVersion {+ let Some(row) = matched else { return Ok(None) };+ Ok(Some(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(@@ -174,6 +201,94 @@ pub(super) async fn readback(identity: RoutineIdentity,goal: &RoutineReadbackGoal,origin: SourceOrigin,+) -> RoutineReadback {+ let counterpart = match identity.kind {+ db::ObjectSourceKind::Package => Some(db::ObjectSourceKind::PackageBody),+ db::ObjectSourceKind::PackageBody => Some(db::ObjectSourceKind::Package),+ _ => None,+ };+ let mut result = readback_single(catalog, endpoint, identity.clone(), goal, origin).await;+ let Some(kind) = counterpart else {+ return result;+ };+ let companion_goal = if identity.kind == db::ObjectSourceKind::Package && *goal == RoutineReadbackGoal::Absent {+ RoutineReadbackGoal::Absent+ } else {+ RoutineReadbackGoal::Inspect+ };+ let companion =+ readback_single(catalog, endpoint, RoutineIdentity { kind, ..identity.clone() }, &companion_goal, origin).await;+ let check: Result<(), String> = async {+ if !result.issues.is_empty() || !companion.issues.is_empty() {+ return Err(format!(+ "Package pair readback is incomplete: {}",+ result+ .issues+ .iter()+ .chain(&companion.issues)+ .map(|issue| issue.message.as_str())+ .collect::<Vec<_>>()+ .join("; ")+ ));+ }+ let login = catalog.query("SELECT USER AS LOGIN_OWNER FROM DUAL").await?;+ login.flags.check()?;+ if login.rows.len() != 1 {+ return Err("Package pair namespace visibility is unknown".into());+ }+ let other_owner = login.text(&login.rows[0], "LOGIN_OWNER")? != identity.owner;+ for before in [&result, &companion] {+ match before.exists {+ Some(true) => {+ let source = catalog.source(&before.identity).await?;+ source.flags.check()?;+ if source.object.name != before.identity.name+ || source.object.schema.as_deref() != Some(&before.identity.owner)+ || source.object.object_type != before.identity.kind+ || before.source.as_ref() != Some(&source.object.source)+ || source.source_origin != before.source_origin+ {+ return Err("Package pair definition or actual source origin changed during collection".into());+ }+ }+ Some(false) => {}+ None => return Err("Package pair existence is not fully observed".into()),+ }+ }+ for before in [&result, &companion] {+ let namespace =+ read_namespace(catalog, &before.identity, other_owner && before.exists == Some(false)).await?;+ let version = namespace_version(&namespace, &before.identity)?;+ if version != before.version || version.is_some() != (before.exists == Some(true)) {+ return Err("Package pair identity, status or namespace changed during collection".into());+ }+ }+ Ok(())+ }+ .await;+ if let Err(error) = check {+ result.state = RoutineReadbackState::ReadbackFailed;+ result.issues.push(issue("package-pair", error));+ } else if (identity.kind == db::ObjectSourceKind::Package+ && *goal == RoutineReadbackGoal::Absent+ && companion.exists != Some(false))+ || (identity.kind == db::ObjectSourceKind::PackageBody+ && matches!(goal, RoutineReadbackGoal::Definition { .. })+ && companion.state != RoutineReadbackState::Present+ && result.state == RoutineReadbackState::Verified)+ {+ result.state = RoutineReadbackState::DefinitionMismatch;+ }+ result.package_companion = Some(Box::new(companion));+ result+}++async fn readback_single(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ identity: RoutineIdentity,+ goal: &RoutineReadbackGoal,+ origin: SourceOrigin,) -> RoutineReadback {let mut result = RoutineReadback {identity,@@ -181,6 +296,8 @@ pub(super) async fn readback(exists: None,version: None,source: None,+ source_origin: None,+ package_companion: None,definition_matches: None,compiler_messages: Vec::new(),issues: Vec::new(),@@ -194,25 +311,27 @@ pub(super) async fn readback(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?;+ let mut version = namespace_version(&namespace, &result.identity)?;// 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 {+ if version.is_none() && other_owner {dba = true;namespace = read_namespace(catalog, &result.identity, true).await?;+ version = namespace_version(&namespace, &result.identity)?;}- result.exists = Some(!namespace.rows.is_empty());- if namespace.rows.is_empty() {+ result.exists = Some(version.is_some());+ let Some(version) = version else {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());+ result.source_origin = source.source_origin;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?;@@ -220,6 +339,7 @@ pub(super) async fn readback(if second.object.name != source.object.name|| second.object.schema != source.object.schema|| second.object.object_type != source.object.object_type+ || second.source_origin != source.source_origin|| second.object.source != source.object.source{return Err("Routine definition changed during readback".into());@@ -255,6 +375,9 @@ pub(super) async fn readback(result}+#[cfg(test)]+mod package_tests;+#[cfg(test)]mod tests {use super::*;@@ -272,6 +395,7 @@ mod tests {incomplete_errors: bool,source_changes: bool,source_reads: AtomicUsize,+ namespace_rows: Option<Vec<Vec<Value>>>,}impl Default for Catalog {@@ -287,6 +411,7 @@ mod tests {incomplete_errors: false,source_changes: false,source_reads: AtomicUsize::new(0),+ namespace_rows: None,}}}@@ -295,6 +420,49 @@ mod tests {serde_json::from_value(json!({"columns":columns,"rows":rows})).unwrap()}+ #[test]+ fn package_namespace_resolves_each_kind_without_treating_its_pair_as_a_conflict() {+ let mut reply = reply(+ &["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "STATUS", "LAST_DDL_TIME"],+ vec![+ vec![+ json!("OWNER"),+ json!("Pkg.With.Dot"),+ json!("PACKAGE"),+ json!(12),+ json!("VALID"),+ json!("2026-10-23T01:00:00"),+ ],+ vec![+ json!("OWNER"),+ json!("Pkg.With.Dot"),+ json!("PACKAGE BODY"),+ json!(13),+ json!("VALID"),+ json!("2026-10-23T01:00:00"),+ ],+ ],+ );+ let specification =+ RoutineIdentity { owner: "OWNER".into(), name: "Pkg.With.Dot".into(), kind: db::ObjectSourceKind::Package };+ let body = RoutineIdentity { kind: db::ObjectSourceKind::PackageBody, ..specification.clone() };+ assert!(exact_version(&reply, &specification).is_ok(), "the specification must be resolved by exact kind");+ assert!(exact_version(&reply, &body).is_ok(), "the body must be resolved by exact kind");+ assert_eq!(exact_version(&reply, &specification).unwrap().object_id, "12");+ assert_eq!(exact_version(&reply, &body).unwrap().object_id, "13");+ let standalone = RoutineIdentity { kind: db::ObjectSourceKind::Function, ..specification.clone() };+ assert!(exact_version(&reply, &standalone).is_err());+ reply.rows[0][0] = json!("ANOTHER_OWNER");+ assert!(exact_version(&reply, &body).is_err());+ reply.rows[0][0] = json!("OWNER");+ reply.rows.push(reply.rows[1].clone());+ assert!(exact_version(&reply, &body).is_err());+ reply.rows.remove(2);+ reply.rows.remove(0);+ assert_eq!(exact_version(&reply, &body).unwrap().object_id, "13");+ assert!(exact_version(&reply, &specification).is_err());+ }+#[async_trait::async_trait]impl RoutineCatalog for Catalog {async fn query(&self, sql: &str) -> Result<CatalogReply, String> {@@ -344,7 +512,9 @@ mod tests {}Ok(reply(&["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "STATUS", "LAST_DDL_TIME"],- if self.exists {+ if let Some(rows) = &self.namespace_rows {+ rows.clone()+ } else if self.exists {vec![vec![json!("OWNER"),json!("Read.Func"),@@ -358,7 +528,7 @@ mod tests {},))}- async fn source(&self, _identity: &RoutineIdentity) -> Result<SourceReply, String> {+ 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")@@ -366,7 +536,7 @@ mod tests {self.source.clone()};Ok(serde_json::from_value(- json!({"name":"Read.Func","schema":"OWNER","object_type":"FUNCTION","source":text}),+ json!({"name":identity.name,"schema":identity.owner,"object_type":identity.kind,"source":text,"source_origin":matches!(identity.kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody).then_some("oceanbase-dictionary")}),).unwrap())}@@ -473,6 +643,57 @@ mod tests {assert_eq!(run(&denied, RoutineReadbackGoal::Absent).await.state, RoutineReadbackState::ReadbackFailed);}+ #[tokio::test]+ async fn body_absence_is_kind_specific_and_requires_full_owner_visibility() {+ let rows = vec![vec![+ json!("OWNER"),+ json!("Read.Func"),+ json!("PACKAGE"),+ json!(12),+ json!("VALID"),+ json!("2026-10-23T01:00:00"),+ ]];+ let endpoint = RoutineEndpoint {+ connection_id: "target".into(),+ database: "tenant".into(),+ schema: "OWNER".into(),+ database_type: DatabaseType::OceanbaseOracle,+ generation: 1,+ };+ let identity = RoutineIdentity {+ owner: "OWNER".into(),+ name: "Read.Func".into(),+ kind: db::ObjectSourceKind::PackageBody,+ };+ let specification = "CREATE OR REPLACE PACKAGE \"Read.Func\" AS g NUMBER; END \"Read.Func\";";+ let catalog =+ Catalog { source: specification.into(), namespace_rows: Some(rows.clone()), ..Default::default() };+ let result = readback(+ &catalog,+ &endpoint,+ identity.clone(),+ &RoutineReadbackGoal::Absent,+ SourceOrigin::OceanBaseDictionary,+ )+ .await;+ assert_eq!(result.state, RoutineReadbackState::Verified);+ assert_eq!(result.exists, Some(false));+ assert_eq!(catalog.source_reads.load(Ordering::SeqCst), 3);+ assert_eq!(result.package_companion.as_ref().unwrap().source.as_deref(), Some(specification));+ let catalog = Catalog {+ source: specification.into(),+ login: "OTHER_LOGIN",+ fail: "SYS.DBA_OBJECTS",+ namespace_rows: Some(rows),+ ..Default::default()+ };+ let result =+ readback(&catalog, &endpoint, identity, &RoutineReadbackGoal::Absent, SourceOrigin::OceanBaseDictionary)+ .await;+ assert_eq!(result.state, RoutineReadbackState::ReadbackFailed);+ assert_eq!(result.exists, None);+ }+#[tokio::test]async fn definition_mismatch_and_shared_namespace_collision_are_not_success() {let catalog =diff --git a/crates/dbx-core/src/schema/oracle_routines/readback/package_tests.rs b/crates/dbx-core/src/schema/oracle_routines/readback/package_tests.rsnew file mode 100644index 0000000000..f919446dd3--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/readback/package_tests.rs@@ -0,0 +1,249 @@+use super::*;+use serde_json::json;+use std::sync::atomic::{AtomicBool, Ordering};++struct PackageCatalog {+ specification: Option<String>,+ body: Option<String>,+ invalid_body: bool,+ invalid_specification: bool,+ fail_body_source: bool,+ change_spec_on_body: bool,+ changed: AtomicBool,+}++impl Default for PackageCatalog {+ fn default() -> Self {+ Self {+ specification: Some(+ "CREATE OR REPLACE PACKAGE APP.\"Pkg.With.Dot\" AS g NUMBER := 1; END \"Pkg.With.Dot\";".into(),+ ),+ body: Some(+ "CREATE OR REPLACE PACKAGE BODY APP.\"Pkg.With.Dot\" AS BEGIN NULL; END \"Pkg.With.Dot\";".into(),+ ),+ invalid_body: false,+ invalid_specification: false,+ fail_body_source: false,+ change_spec_on_body: false,+ changed: AtomicBool::new(false),+ }+ }+}++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 PackageCatalog {+ async fn source(&self, identity: &RoutineIdentity) -> Result<SourceReply, String> {+ let source = match identity.kind {+ db::ObjectSourceKind::Package => {+ let source = self.specification.as_ref().expect("absent specifications must not be fetched");+ if self.changed.load(Ordering::SeqCst) {+ source.replace("g NUMBER := 1", "g NUMBER := 2")+ } else {+ source.clone()+ }+ }+ db::ObjectSourceKind::PackageBody => {+ if self.fail_body_source {+ return Err("ORA-01031: insufficient privileges".into());+ }+ if self.change_spec_on_body {+ self.changed.store(true, Ordering::SeqCst);+ }+ self.body.as_ref().expect("absent bodies must not be fetched").clone()+ }+ _ => panic!("package readback must preserve exact kinds"),+ };+ Ok(serde_json::from_value(json!({"name":identity.name,"schema":identity.owner,"object_type":identity.kind,"source":source,"source_origin":"oceanbase-dictionary"})).unwrap())+ }++ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ assert!(sql.starts_with("SELECT "), "readback may only observe dictionary state");+ if sql.contains("LOGIN_OWNER") {+ return Ok(reply(&["LOGIN_OWNER"], vec![vec![json!("APP")]]));+ }+ let body = sql.contains("TYPE = 'PACKAGE BODY'");+ if sql.contains("SOURCE_ROWS") {+ let source = if body { self.body.as_ref() } else { self.specification.as_ref() }.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!(source.chars().count()),+ json!(0),+ json!(0),+ json!("CREATE PACKAGE"),+ ]],+ ));+ }+ if sql.contains("ALL_ERRORS") {+ return Ok(reply(+ &["SEQUENCE", "ATTRIBUTE", "LINE", "POSITION", "TEXT"],+ if body && self.invalid_body {+ vec![vec![+ json!(0),+ json!("ERROR"),+ json!(1),+ json!(0),+ json!(if self.specification.is_none() {+ "PLS-00304: specification does not exist"+ } else {+ "PLS-00323: member does not match specification"+ }),+ ]]+ } else {+ Vec::new()+ },+ ));+ }+ if sql.contains("OBJECTS") {+ let mut rows = Vec::new();+ if self.specification.is_some() {+ rows.push(vec![+ json!("APP"),+ json!("Pkg.With.Dot"),+ json!("PACKAGE"),+ json!(11),+ json!(if self.invalid_specification { "INVALID" } else { "VALID" }),+ json!("2026-10-23T01:00:00"),+ ]);+ }+ if self.body.is_some() {+ rows.push(vec![+ json!("APP"),+ json!("Pkg.With.Dot"),+ json!("PACKAGE BODY"),+ json!(12),+ json!(if self.invalid_body { "INVALID" } else { "VALID" }),+ json!("2026-10-23T01:00:00"),+ ]);+ }+ return Ok(reply(&["OWNER", "OBJECT_NAME", "OBJECT_TYPE", "OBJECT_ID", "STATUS", "LAST_DDL_TIME"], rows));+ }+ panic!("Unexpected package observation: {sql}")+ }+}++async fn run(catalog: &PackageCatalog, kind: db::ObjectSourceKind, goal: RoutineReadbackGoal) -> RoutineReadback {+ readback(+ catalog,+ &RoutineEndpoint {+ connection_id: "target".into(),+ database: "tenant".into(),+ schema: "APP".into(),+ database_type: DatabaseType::OceanbaseOracle,+ generation: 1,+ },+ RoutineIdentity { owner: "APP".into(), name: "Pkg.With.Dot".into(), kind },+ &goal,+ SourceOrigin::OceanBaseDictionary,+ )+ .await+}++#[tokio::test]+async fn a_verified_specification_keeps_the_actual_invalid_body_and_its_errors() {+ let catalog = PackageCatalog { invalid_body: true, ..Default::default() };+ let result = run(+ &catalog,+ db::ObjectSourceKind::Package,+ RoutineReadbackGoal::Definition { sql: catalog.specification.clone().unwrap() },+ )+ .await;+ assert_eq!(result.state, RoutineReadbackState::Verified);+ let wire = serde_json::to_value(&result).unwrap();+ assert_eq!(wire["sourceOrigin"], "oceanbase-dictionary");+ assert_eq!(wire["packageCompanion"]["identity"]["kind"], "PACKAGE_BODY");+ assert_eq!(wire["packageCompanion"]["state"], "invalid");+ assert_eq!(wire["packageCompanion"]["source"], catalog.body.unwrap());+ assert_eq!(wire["packageCompanion"]["compilerMessages"][0]["position"], 0);+}++#[tokio::test]+async fn a_body_definition_is_not_verified_against_an_invalid_specification() {+ let catalog = PackageCatalog { invalid_specification: true, ..Default::default() };+ let result = run(+ &catalog,+ db::ObjectSourceKind::PackageBody,+ RoutineReadbackGoal::Definition { sql: catalog.body.clone().unwrap() },+ )+ .await;+ assert_eq!(result.exists, Some(true));+ assert_eq!(result.state, RoutineReadbackState::DefinitionMismatch);+ assert_eq!(result.package_companion.as_ref().unwrap().state, RoutineReadbackState::Invalid);+}++#[tokio::test]+async fn whole_package_absence_requires_both_kinds_to_be_absent() {+ let orphan = PackageCatalog { specification: None, invalid_body: true, ..Default::default() };+ let result = run(&orphan, db::ObjectSourceKind::Package, RoutineReadbackGoal::Absent).await;+ assert_ne!(result.state, RoutineReadbackState::Verified);+ assert_eq!(result.exists, Some(false));+ let wire = serde_json::to_value(&result).unwrap();+ assert_eq!(wire["packageCompanion"]["exists"], true);+ assert_eq!(wire["packageCompanion"]["source"], orphan.body.unwrap());+ let empty = PackageCatalog { specification: None, body: None, ..Default::default() };+ let result = run(&empty, db::ObjectSourceKind::Package, RoutineReadbackGoal::Absent).await;+ assert_eq!(result.state, RoutineReadbackState::Verified);+ assert_eq!(serde_json::to_value(&result).unwrap()["packageCompanion"]["exists"], false);+}++#[tokio::test]+async fn dropping_only_the_body_retains_complete_specification_evidence() {+ let catalog = PackageCatalog { body: None, ..Default::default() };+ let result = run(&catalog, db::ObjectSourceKind::PackageBody, RoutineReadbackGoal::Absent).await;+ assert_eq!(result.state, RoutineReadbackState::Verified);+ let wire = serde_json::to_value(&result).unwrap();+ assert_eq!(wire["packageCompanion"]["identity"]["kind"], "PACKAGE");+ assert_eq!(wire["packageCompanion"]["source"], catalog.specification.unwrap());+}++#[tokio::test]+async fn an_orphan_invalid_body_remains_present_with_its_actual_missing_specification() {+ let catalog = PackageCatalog { specification: None, invalid_body: true, ..Default::default() };+ let result = run(+ &catalog,+ db::ObjectSourceKind::PackageBody,+ RoutineReadbackGoal::Definition { sql: catalog.body.clone().unwrap() },+ )+ .await;+ assert_eq!(result.state, RoutineReadbackState::Invalid);+ assert_eq!(result.exists, Some(true));+ assert_eq!(result.source, catalog.body);+ assert_eq!(result.package_companion.as_ref().unwrap().exists, Some(false));+}++#[tokio::test]+async fn same_second_spec_mutation_while_reading_body_cannot_be_a_verified_pair() {+ let catalog = PackageCatalog { change_spec_on_body: true, ..Default::default() };+ let result = run(+ &catalog,+ db::ObjectSourceKind::Package,+ RoutineReadbackGoal::Definition { sql: catalog.specification.clone().unwrap() },+ )+ .await;+ assert_eq!(result.state, RoutineReadbackState::ReadbackFailed);+ assert!(!result.issues.is_empty());+ assert_eq!(result.source, catalog.specification);+}++#[tokio::test]+async fn companion_read_failure_retains_the_selected_definition_without_reporting_verified() {+ let catalog = PackageCatalog { fail_body_source: true, ..Default::default() };+ let result = run(+ &catalog,+ db::ObjectSourceKind::Package,+ RoutineReadbackGoal::Definition { sql: catalog.specification.clone().unwrap() },+ )+ .await;+ assert_eq!(result.state, RoutineReadbackState::ReadbackFailed);+ assert_eq!(result.source, catalog.specification);+ let wire = serde_json::to_value(&result).unwrap();+ assert_eq!(wire["packageCompanion"]["exists"], true);+ assert_eq!(wire["packageCompanion"]["state"], "readback-failed");+}diff --git a/crates/dbx-core/src/schema/oracle_routines/references.rs b/crates/dbx-core/src/schema/oracle_routines/references.rsindex 8b9c91fa12..9f9cddc8fb 100644--- a/crates/dbx-core/src/schema/oracle_routines/references.rs+++ b/crates/dbx-core/src/schema/oracle_routines/references.rs@@ -3,28 +3,71 @@//! 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,+ analyze_oracle_routine_draft, EditableObjectSourceSqlInput, OracleDraftIssue, OracleDraftPackageMemberKind,+ 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>>,+pub(super) enum CatalogReadProof {+ Query { sql: String, columns: Vec<String>, rows: Vec<Vec<Value>> },+ Source { endpoint: RoutineEndpoint, identity: RoutineIdentity, source: String, origin: SourceOrigin },}impl CatalogReadProof {+ fn manifest_value(&self) -> Value {+ match self {+ Self::Query { sql, columns, rows } => serde_json::json!({ "Query": {+ "sql": sql, "columns": columns,+ "rows": rows.iter().map(|row| row.iter().map(lossless_catalog_value).collect::<Vec<_>>()).collect::<Vec<_>>(),+ }}),+ Self::Source { .. } => serde_json::json!(self),+ }+ }+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());+ match self {+ Self::Query { sql, columns, rows } => {+ let current = catalog.query(sql).await?;+ current.flags.check()?;+ if ¤t.columns != columns || ¤t.rows != rows {+ return Err("Referenced object, name resolution, signature, columns or direct privileges changed; validate the draft again".into());+ }+ }+ Self::Source { endpoint, identity, source, origin } => {+ let current = catalog.source(identity).await?;+ check_source(catalog, endpoint, identity, ¤t, *origin).await?;+ if current.object.source != *source || current.source_origin != Some(*origin) {+ return Err(+ "Referenced package specification or its source origin changed; validate the draft again"+ .into(),+ );+ }+ }}Ok(())}}+pub(super) fn lossless_catalog_value(value: &Value) -> Value {+ match value {+ Value::Null => serde_json::json!(["null"]),+ Value::Bool(value) => serde_json::json!(["boolean", value]),+ Value::Number(value) => serde_json::json!(["number", value.to_string()]),+ Value::String(value) => serde_json::json!(["string", value]),+ Value::Array(values) => {+ serde_json::json!(["array", values.iter().map(lossless_catalog_value).collect::<Vec<_>>()])+ }+ Value::Object(values) => serde_json::json!([+ "object",+ values+ .iter()+ .map(|(key, value)| (key.clone(), lossless_catalog_value(value)))+ .collect::<serde_json::Map<_, _>>()+ ]),+ }+}+#[derive(Clone)]pub(super) struct SelectedFinalDraft {pub identity: RoutineIdentity,@@ -49,6 +92,62 @@ pub(super) struct DraftResolution {pub selected_dependencies: BTreeSet<usize>,pub proofs: Vec<CatalogReadProof>,pub issues: Vec<OracleDraftIssue>,+ pub planned_table_dependencies: BTreeSet<usize>,+ pub proof_groups: Vec<ReferenceProofGroup>,+}++#[derive(Clone, Serialize)]+#[serde(tag = "purpose", rename_all = "camelCase")]+pub(super) enum ReferenceProofPurpose {+ PackagePreflight,+ LoginOwner,+ Reference {+ index: usize,+ reference: OracleDraftReference,+ query: Option<dbx_sql::object_source_sql::OracleDraftQuery>,+ resolved: Option<Box<ResolvedRoutineReference>>,+ },+}++#[derive(Clone)]+pub(super) struct ReferenceProofGroup {+ pub purpose: ReferenceProofPurpose,+ pub start: usize,+ pub end: usize,+}++pub(super) fn reference_proof_manifest(+ groups: &[ReferenceProofGroup],+ proofs: &[CatalogReadProof],+ pending_tables: &[PlannedRelation],+) -> Vec<Value> {+ // This projection is not approval: registry admission still requires a+ // complete typed readback of every precisely registered pending table.+ groups+ .iter()+ .map(|group| {+ let pending_relation = match &group.purpose {+ ReferenceProofPurpose::Reference { reference, resolved: Some(resolved), .. }+ if reference.role == OracleDraftReferenceRole::Relation && resolved.kind == "TABLE" =>+ {+ pending_tables.iter().any(|table| table.owner == resolved.owner && table.name == resolved.name)+ }+ _ => false,+ };+ serde_json::json!({+ "use": group.purpose,+ "proofs": if pending_relation { Vec::new() } else {+ proofs[group.start..group.end].iter().map(CatalogReadProof::manifest_value).collect::<Vec<_>>()+ },+ })+ })+ .collect()+}++pub(super) struct PlannedRelation {+ pub owner: String,+ pub name: String,+ pub columns: BTreeSet<String>,}#[derive(Clone)]@@ -66,7 +165,10 @@ struct Resolver<'a, C> {endpoint: &'a RoutineEndpoint,login: String,selected: &'a [SelectedFinalDraft],+ planned_tables: &'a [PlannedRelation],output: DraftResolution,+ strict_packages: bool,+ package_contracts: BTreeMap<(String, String), OracleRoutineDraftAnalysis>,}impl<C: RoutineCatalog> Resolver<'_, C> {@@ -76,7 +178,11 @@ impl<C: RoutineCatalog> Resolver<'_, C> {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() });+ self.output.proofs.push(CatalogReadProof::Query {+ sql,+ columns: reply.columns.clone(),+ rows: reply.rows.clone(),+ });Ok(reply)}@@ -110,12 +216,14 @@ impl<C: RoutineCatalog> Resolver<'_, C> {}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 self.planned_tables.iter().any(|table| table.owner == owner && table.name == name) {+ return Err("This name is captured by a planned table, not an existing callable object".into());+ }+ if let Some((index, selected)) = self.selected.iter().enumerate().find(|(_, draft)| {+ draft.identity.owner == owner+ && draft.identity.name == name+ && draft.identity.kind != db::ObjectSourceKind::PackageBody+ }) {if selected.analysis.is_none() {return Err(format!("Reference {owner}.{name} is selected for deletion"));}@@ -258,6 +366,15 @@ impl<C: RoutineCatalog> Resolver<'_, C> {member: Option<&str>,reference: &OracleDraftReference,) -> Result<(), String> {+ if object.kind == "PACKAGE"+ && (self.strict_packages+ || object.selected.is_some()+ || reference.role == OracleDraftReferenceRole::Exception)+ {+ let member = member.ok_or("An explicit public package member is required")?;+ let contract = self.package_contract(object).await?;+ return check_package_member(&contract, member, reference);+ }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());@@ -338,6 +455,68 @@ impl<C: RoutineCatalog> Resolver<'_, C> {check_arguments(parameters.iter().map(|(mode, default)| (mode.as_str(), *default)), reference)}+ async fn package_contract(&mut self, object: &Object) -> Result<OracleRoutineDraftAnalysis, String> {+ if let Some(index) = object.selected {+ let analysis =+ self.selected[index].analysis.as_ref().ok_or("The final package specification is deleted")?;+ if !analysis.complete {+ return Err("The final package specification is not completely analyzed".into());+ }+ return Ok(analysis.clone());+ }+ let key = (object.owner.clone(), object.name.clone());+ if let Some(contract) = self.package_contracts.get(&key) {+ return Ok(contract.clone());+ }+ self.accessible(object, false).await?;+ let identity = RoutineIdentity {+ owner: object.owner.clone(),+ name: object.name.clone(),+ kind: db::ObjectSourceKind::Package,+ };+ let source = self.catalog.source(&identity).await?;+ let origin = source+ .source_origin+ .ok_or("A referenced package requires its actual complete specification source origin")?;+ check_source(self.catalog, self.endpoint, &identity, &source, origin).await?;+ let again = self.catalog.source(&identity).await?;+ again.flags.check()?;+ if again.object.name != identity.name+ || again.object.schema.as_deref() != Some(&identity.owner)+ || again.object.object_type != identity.kind+ || again.object.source != source.object.source+ || again.source_origin != Some(origin)+ {+ return Err("The referenced package specification changed while being read".into());+ }+ let contract = analyze_oracle_routine_draft(EditableObjectSourceSqlInput {+ database_type: self.endpoint.database_type,+ object_type: identity.kind.clone(),+ schema: Some(identity.owner.clone()),+ name: identity.name.clone(),+ source: source.object.source.clone(),+ });+ if !contract.complete {+ return Err(format!(+ "Referenced package specification requires manual correction: {}",+ contract+ .issues+ .iter()+ .map(|issue| format!("{}:{} {}", issue.line, issue.column, issue.message))+ .collect::<Vec<_>>()+ .join("; ")+ ));+ }+ self.output.proofs.push(CatalogReadProof::Source {+ endpoint: self.endpoint.clone(),+ identity,+ source: source.object.source,+ origin,+ });+ self.package_contracts.insert(key, contract.clone());+ Ok(contract)+ }+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();@@ -367,6 +546,40 @@ impl<C: RoutineCatalog> Resolver<'_, C> {}}+fn check_package_member(+ contract: &OracleRoutineDraftAnalysis,+ name: &str,+ reference: &OracleDraftReference,+) -> Result<(), String> {+ let member = contract+ .package_members+ .iter()+ .find(|member| member.public && member.name.value == name)+ .ok_or_else(|| format!("Package member {name} is not public in the final specification"))?;+ match member.kind {+ OracleDraftPackageMemberKind::Variable | OracleDraftPackageMemberKind::Constant+ if reference.role == OracleDraftReferenceRole::Value =>+ {+ return Ok(())+ }+ OracleDraftPackageMemberKind::Exception if reference.role == OracleDraftReferenceRole::Exception => {+ return Ok(())+ }+ OracleDraftPackageMemberKind::Function+ if matches!(reference.role, OracleDraftReferenceRole::Function | OracleDraftReferenceRole::Value) => {}+ OracleDraftPackageMemberKind::Procedure if reference.role == OracleDraftReferenceRole::Procedure => {}+ _ => {+ return Err(format!(+ "Package member {name} has another scalar, exception or call role in the final specification"+ ))+ }+ }+ check_arguments(+ member.parameters.iter().map(|parameter| (parameter.mode.as_str(), parameter.has_default)),+ reference,+ )+}+fn scalar_argument_type(value: &str) -> bool {matches!(value,@@ -411,17 +624,35 @@ pub(super) async fn resolve_draft(endpoint: &RoutineEndpoint,selected: &[SelectedFinalDraft],index: usize,+) -> DraftResolution {+ resolve_draft_with_tables(catalog, endpoint, selected, index, &[]).await+}++pub(super) async fn resolve_draft_with_tables(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ selected: &[SelectedFinalDraft],+ index: usize,+ planned_tables: &[PlannedRelation],) -> DraftResolution {let mut resolver = Resolver {catalog,endpoint,login: String::new(),selected,+ planned_tables,+ strict_packages: matches!(+ selected[index].identity.kind,+ db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody+ ),+ package_contracts: BTreeMap::new(),output: DraftResolution {references: Vec::new(),selected_dependencies: BTreeSet::new(),proofs: Vec::new(),issues: Vec::new(),+ planned_table_dependencies: BTreeSet::new(),+ proof_groups: Vec::new(),},};let Some(analysis) = &selected[index].analysis else {@@ -431,6 +662,40 @@ pub(super) async fn resolve_draft(resolver.output.issues = analysis.issues.clone();return resolver.output;}+ if planned_tables.iter().enumerate().any(|(index, table)| {+ !resolver.strict_packages+ || table.owner != endpoint.schema+ || table.columns.is_empty()+ || planned_tables[..index].iter().any(|other| other.owner == table.owner && other.name == table.name)+ || selected.iter().any(|draft| draft.identity.owner == table.owner && draft.identity.name == table.name)+ }) {+ resolver.output.issues.push(OracleDraftIssue {+ code: "pending-table-scope".into(),+ message: "Planned relations require a unique, complete table contract in the package target namespace"+ .into(),+ line: 1,+ column: 1,+ });+ return resolver.output;+ }+ if selected[index].identity.kind == db::ObjectSourceKind::PackageBody {+ if let Some((specification, draft)) = selected.iter().enumerate().find(|(_, draft)| {+ draft.identity.kind == db::ObjectSourceKind::Package+ && draft.identity.owner == selected[index].identity.owner+ && draft.identity.name == selected[index].identity.name+ }) {+ if draft.analysis.is_none() {+ resolver.output.issues.push(OracleDraftIssue {+ code: "unresolved-reference".into(),+ message: "The package body cannot depend on a deleted final specification".into(),+ line: 1,+ column: 1,+ });+ return resolver.output;+ }+ resolver.output.selected_dependencies.insert(specification);+ }+ }let login = async {let reply = resolver.query("SELECT USER AS LOGIN_OWNER FROM DUAL".into()).await?;if reply.rows.len() != 1 {@@ -451,11 +716,33 @@ pub(super) async fn resolve_draft(return resolver.output;}}- let mut relations: BTreeMap<usize, (Object, BTreeSet<String>)> = BTreeMap::new();+ resolver.output.proof_groups.push(ReferenceProofGroup {+ purpose: ReferenceProofPurpose::LoginOwner,+ start: 0,+ end: resolver.output.proofs.len(),+ });+ let mut relations: BTreeMap<usize, (String, BTreeSet<String>)> = BTreeMap::new();for (reference_index, reference) in analysis.references.iter().enumerate() {+ let proof_start = resolver.output.proofs.len();+ let resolved_start = resolver.output.references.len();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 identity = match parts.as_slice() {+ [name] => (endpoint.schema.as_str(), *name),+ [owner, name] => (*owner, *name),+ _ => return Err("A relation needs an exact local or owner.table name".into()),+ };+ if let Some((table_index, table)) = planned_tables.iter().enumerate().find(|(_, table)|+ table.owner == identity.0 && table.name == identity.1) {+ resolver.output.planned_table_dependencies.insert(table_index);+ resolver.output.references.push(ResolvedRoutineReference {+ owner: table.owner.clone(), name: table.name.clone(), kind: "TABLE".into(), member: None,+ selected_index: None, line: reference.line, column: reference.column,+ });+ relations.insert(reference_index, (table.name.clone(), table.columns.clone()));+ return Ok(None);+ }let object = match parts.as_slice() {[name] => resolver.object(&endpoint.schema, name, true).await?,[owner, name] => resolver.object(owner, name, false).await?,@@ -466,7 +753,7 @@ pub(super) async fn resolve_draft(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));+ relations.insert(reference_index, (object.name.clone(), columns));return Ok(Some((object, None)));}if let Some(query) = reference.query {@@ -478,7 +765,7 @@ pub(super) async fn resolve_draft(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)+ if query.alias.as_ref().map(|alias| alias.value.as_str()).unwrap_or(relation)== *qualifier =>{return if columns.contains(*column) {@@ -502,6 +789,21 @@ pub(super) async fn resolve_draft(Err("A local scalar shadows this routine prefix; calls or member access are not supported on scalar bindings".into())};}+ if let Some(binding) = reference.package_binding {+ match binding {+ OracleDraftPackageMemberKind::Variable | OracleDraftPackageMemberKind::Constant => return Ok(None),+ OracleDraftPackageMemberKind::Function => {+ let name = &reference.parts.last().ok_or("Package SQL value has no member identity")?.value;+ let member = analysis.package_members.iter().find(|member| member.name.value == *name && member.kind == OracleDraftPackageMemberKind::Function).ok_or("The package SQL function has no final member declaration")?;+ check_arguments(member.parameters.iter().map(|parameter| (parameter.mode.as_str(), parameter.has_default)), reference)?;+ return Ok(None);+ }+ _ => return Err("A package exception or procedure cannot be used as a scalar SQL value when no column binds this name".into()),+ }+ }+ if reference.out_of_scope_binding {+ return Err("The SQL name is not a relation column and its local binding is outside the lexical scope; qualify an intended external reference".into());+ }}resolver.resolve_call(reference).await.map(Some)}@@ -529,6 +831,17 @@ pub(super) async fn resolve_draft(column: reference.column,}),}+ resolver.output.proof_groups.push(ReferenceProofGroup {+ purpose: ReferenceProofPurpose::Reference {+ index: reference_index,+ reference: reference.clone(),+ query: reference.query.and_then(|index| analysis.queries.get(index)).cloned(),+ resolved: (resolver.output.references.len() > resolved_start)+ .then(|| Box::new(resolver.output.references.last().unwrap().clone())),+ },+ start: proof_start,+ end: resolver.output.proofs.len(),+ });}resolver.output}diff --git a/crates/dbx-core/src/schema/oracle_routines/references/tests.rs b/crates/dbx-core/src/schema/oracle_routines/references/tests.rsindex 609de39b62..8d3d9f6863 100644--- a/crates/dbx-core/src/schema/oracle_routines/references/tests.rs+++ b/crates/dbx-core/src/schema/oracle_routines/references/tests.rs@@ -38,6 +38,8 @@ struct Catalog {dba_denied: bool,incomplete_columns: bool,changed: AtomicBool,+ specifications: BTreeMap<(String, String), String>,+ source_changed: AtomicBool,}fn value_after(sql: &str, field: &str) -> String {@@ -55,10 +57,41 @@ fn page(columns: &[&str], mut rows: Vec<Vec<Value>>) -> CatalogReply {reply(&columns, rows)}+#[test]+fn confirmation_proofs_preserve_catalog_number_precision_and_cell_types_across_javascript() {+ let id = json!(9_007_199_254_740_993u64);+ let encoded = lossless_catalog_value(&id);+ assert_eq!(encoded, json!(["number", "9007199254740993"]));+ assert_ne!(encoded, lossless_catalog_value(&json!("9007199254740993")));+ assert_ne!(encoded, lossless_catalog_value(&json!(["number", "9007199254740993"])));+ let nested = lossless_catalog_value(&json!({"objectId":[18_446_744_073_709_551_615u64]}));+ assert_eq!(nested, json!(["object", {"objectId":["array", [["number","18446744073709551615"]]]}]));+ let proof = CatalogReadProof::Query {+ sql: "SELECT OBJECT_ID FROM ALL_OBJECTS".into(),+ columns: vec!["OBJECT_ID".into()],+ rows: vec![vec![id]],+ };+ assert_eq!(proof.manifest_value()["Query"]["rows"][0][0], encoded);+}+#[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 source(&self, identity: &RoutineIdentity) -> Result<SourceReply, String> {+ assert_eq!(+ identity.kind,+ db::ObjectSourceKind::Package,+ "Resolution must never read or invoke a package implementation"+ );+ let source = self+ .specifications+ .get(&(identity.owner.clone(), identity.name.clone()))+ .expect("Only explicit strict package references may fetch a specification");+ let source = if self.source_changed.load(Ordering::SeqCst) {+ source.replace("g NUMBER := 1", "g NUMBER := 2")+ } else {+ source.clone()+ };+ Ok(serde_json::from_value(json!({ "name": identity.name, "schema": identity.owner, "object_type": "PACKAGE", "source": source, "source_origin": "oceanbase-dictionary" })).unwrap())}async fn query(&self, sql: &str) -> Result<CatalogReply, String> {if sql.contains("LOGIN_OWNER") {@@ -68,6 +101,22 @@ impl RoutineCatalog for Catalog {return Err("ORA-00942: dictionary unavailable".into());}let owner = value_after(sql, "OWNER");+ if sql.contains("SOURCE_CHARS") {+ let name = value_after(sql, "NAME");+ let source = &self.specifications[&(owner.clone(), name)];+ 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!(source.chars().count()),+ json!(0),+ json!(0),+ json!("CREATE PACKAGE"),+ ]],+ ));+ }let name = value_after(sql, "OBJECT_NAME");if sql.contains("ALL_OBJECTS") || sql.contains("DBA_OBJECTS") {let rows = self@@ -210,6 +259,323 @@ fn draft(name: &str, body: &str) -> SelectedFinalDraft {SelectedFinalDraft { identity, analysis: Some(analysis) }}+fn package_draft(source: &str) -> SelectedFinalDraft {+ let identity = RoutineIdentity { owner: "OWNER".into(), name: "PKG".into(), kind: db::ObjectSourceKind::Package };+ 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: source.into(),+ });+ assert!(analysis.complete, "{:?}", analysis.issues);+ SelectedFinalDraft { identity, analysis: Some(analysis) }+}++fn table_dependent_body(column: &str) -> SelectedFinalDraft {+ package_body(&format!(+ "FUNCTION f RETURN NUMBER IS n NUMBER; BEGIN SELECT a.{column} INTO n FROM TARGET_REL a; RETURN n; END f;"+ ))+}++fn package_body(body: &str) -> SelectedFinalDraft {+ let specification = "CREATE PACKAGE \"OWNER\".PKG AS FUNCTION f RETURN NUMBER; END PKG;";+ let input = EditableObjectSourceSqlInput {+ database_type: endpoint().database_type,+ object_type: db::ObjectSourceKind::Package,+ schema: Some("OWNER".into()),+ name: "PKG".into(),+ source: specification.into(),+ };+ let analysis = dbx_sql::object_source_sql::analyze_oracle_package_body_draft(+ EditableObjectSourceSqlInput {+ object_type: db::ObjectSourceKind::PackageBody,+ source: format!("CREATE PACKAGE BODY \"OWNER\".PKG AS {body} END PKG;"),+ ..input.clone()+ },+ input,+ );+ assert!(analysis.complete, "{:?}", analysis.issues);+ SelectedFinalDraft {+ identity: RoutineIdentity {+ owner: "OWNER".into(),+ name: "PKG".into(),+ kind: db::ObjectSourceKind::PackageBody,+ },+ analysis: Some(analysis),+ }+}++#[tokio::test]+async fn table_proofs_carry_server_generated_reference_provenance_and_exact_ranges() {+ let selected = vec![table_dependent_body("TARGET_N")];+ let tables = vec![PlannedRelation {+ owner: "OWNER".into(),+ name: "TARGET_REL".into(),+ columns: BTreeSet::from(["TARGET_N".into()]),+ }];+ let pending = resolve_draft_with_tables(&Catalog::default(), &endpoint(), &selected, 0, &tables).await;+ let mut entry = Entry::object("OWNER", "TARGET_REL", "TABLE");+ entry.columns = vec!["TARGET_N"];+ let catalog = Catalog { entries: vec![entry], ..Default::default() };+ let actual = resolve_draft(&catalog, &endpoint(), &selected, 0).await;+ assert!(actual.issues.is_empty(), "{:?}", actual.issues);+ assert_eq!(pending.proof_groups.len(), actual.proof_groups.len());+ assert_eq!(+ reference_proof_manifest(&pending.proof_groups, &pending.proofs, &tables),+ reference_proof_manifest(&actual.proof_groups, &actual.proofs, &tables),+ "Only the precisely registered pending relation changes catalog source"+ );+ assert_ne!(+ reference_proof_manifest(&actual.proof_groups, &actual.proofs, &tables),+ reference_proof_manifest(&actual.proof_groups, &actual.proofs, &[]),+ "Ordinary relation namespace and column proofs must remain in the frozen manifest"+ );+ let mut table_groups = 0;+ for (before, after) in pending.proof_groups.iter().zip(&actual.proof_groups) {+ assert_eq!(serde_json::to_value(&before.purpose).unwrap(), serde_json::to_value(&after.purpose).unwrap());+ if let ReferenceProofPurpose::Reference { reference, resolved: Some(resolved), query: Some(query), index } =+ &after.purpose+ {+ if reference.role == OracleDraftReferenceRole::Relation {+ table_groups += 1;+ assert_eq!(resolved.owner, "OWNER");+ assert_eq!(resolved.name, "TARGET_REL");+ assert_eq!(resolved.kind, "TABLE");+ assert_eq!(query.relation_reference, *index);+ assert_eq!(before.start, before.end, "Pending tables have no invented catalog proofs");+ assert!(after.end > after.start, "The real table contributes its own namespace and column reads");+ }+ }+ }+ assert_eq!(table_groups, 1);+ for result in [&pending, &actual] {+ let mut covered = 0;+ for group in &result.proof_groups {+ assert_eq!(group.start, covered);+ assert!(group.end >= group.start && group.end <= result.proofs.len());+ covered = group.end;+ }+ assert_eq!(covered, result.proofs.len(), "Every real query/source proof has exactly one provenance");+ }+}++#[tokio::test]+async fn planned_table_columns_bind_without_fabricating_catalog_rows() {+ let selected = vec![table_dependent_body("TARGET_N")];+ let tables = vec![PlannedRelation {+ owner: "OWNER".into(),+ name: "TARGET_REL".into(),+ columns: BTreeSet::from(["TARGET_N".into()]),+ }];+ let result = resolve_draft_with_tables(&Catalog::default(), &endpoint(), &selected, 0, &tables).await;+ assert!(result.issues.is_empty(), "{:?}", result.issues);+ assert_eq!(result.references.len(), 1);+ assert_eq!(result.references[0].name, "TARGET_REL");+ assert_eq!(result.planned_table_dependencies, BTreeSet::from([0]));+ assert_eq!(+ result.proofs.len(),+ 1,+ "Only the real login query is observed; a planned relation is not a fake catalog query"+ );+ let old_name = vec![table_dependent_body("SOURCE_N")];+ let rejected = resolve_draft_with_tables(&Catalog::default(), &endpoint(), &old_name, 0, &tables).await;+ assert!(rejected.issues.iter().any(|issue| issue.message.contains("column")));+ let public = Catalog { entries: vec![Entry::object("PUBLIC", "TARGET_REL", "TABLE")], ..Default::default() };+ let result = resolve_draft_with_tables(&public, &endpoint(), &selected, 0, &tables).await;+ assert!(result.issues.is_empty(), "The planned local table must precede any PUBLIC object");+ assert_eq!(result.references[0].owner, "OWNER");+}++#[tokio::test]+async fn pending_relations_do_not_bypass_external_resolution_or_become_callable() {+ let tables = vec![PlannedRelation {+ owner: "OWNER".into(),+ name: "TARGET_REL".into(),+ columns: BTreeSet::from(["TARGET_N".into()]),+ }];+ let callable = vec![package_body("FUNCTION f RETURN NUMBER IS BEGIN RETURN TARGET_REL(); END f;")];+ let result = resolve_draft_with_tables(&Catalog::default(), &endpoint(), &callable, 0, &tables).await;+ assert!(result.issues.iter().any(|issue| issue.message.contains("planned table")));+ let missing = vec![package_body("FUNCTION f RETURN NUMBER IS n NUMBER; BEGIN SELECT a.TARGET_N INTO n FROM TARGET_REL a; RETURN MISSING_HELPER(); END f;")];+ let result = resolve_draft_with_tables(&Catalog::default(), &endpoint(), &missing, 0, &tables).await;+ assert_eq!(result.planned_table_dependencies, BTreeSet::from([0]));+ assert!(!result.issues.is_empty());+ for invalid in [+ vec![PlannedRelation {+ owner: "OTHER".into(),+ name: "TARGET_REL".into(),+ columns: BTreeSet::from(["TARGET_N".into()]),+ }],+ vec![PlannedRelation { owner: "OWNER".into(), name: "TARGET_REL".into(), columns: BTreeSet::new() }],+ vec![PlannedRelation {+ owner: "OWNER".into(),+ name: "PKG".into(),+ columns: BTreeSet::from(["TARGET_N".into()]),+ }],+ ] {+ let result = resolve_draft_with_tables(&Catalog::default(), &endpoint(), &missing, 0, &invalid).await;+ assert!(result.issues.iter().any(|issue| issue.code == "pending-table-scope"));+ }+ let ordinary = vec![draft("CALLER", "BEGIN RETURN 1; END;")];+ assert!(resolve_draft_with_tables(&Catalog::default(), &endpoint(), &ordinary, 0, &tables)+ .await+ .issues+ .iter()+ .any(|issue| issue.code == "pending-table-scope"));+ assert!(resolve_draft(&Catalog::default(), &endpoint(), &ordinary, 0).await.issues.is_empty());+}++#[tokio::test]+async fn selected_package_calls_bind_to_final_public_specification_not_body_or_old_dictionary() {+ let specification = package_draft(+ "CREATE PACKAGE \"OWNER\".PKG AS n NUMBER; e EXCEPTION; FUNCTION f(p NUMBER DEFAULT 2) RETURN NUMBER; END PKG;",+ );+ let deleted_body = SelectedFinalDraft {+ identity: RoutineIdentity {+ owner: "OWNER".into(),+ name: "PKG".into(),+ kind: db::ObjectSourceKind::PackageBody,+ },+ analysis: None,+ };+ let selected = vec![deleted_body, draft("CALLER", "BEGIN RETURN \"OWNER\".PKG.f(); END;"), specification];+ let catalog = Catalog::default();+ let result = resolve_draft(&catalog, &endpoint(), &selected, 1).await;+ assert!(result.issues.is_empty(), "{:?}", result.issues);+ assert_eq!(result.references[0].kind, "PACKAGE");+ assert_eq!(result.references[0].member.as_deref(), Some("F"));+ assert_eq!(result.selected_dependencies, BTreeSet::from([2]));+ let mut missing = selected.clone();+ missing[2] = package_draft("CREATE PACKAGE \"OWNER\".PKG AS n NUMBER; END PKG;");+ assert!(!resolve_draft(&catalog, &endpoint(), &missing, 1).await.issues.is_empty());+}++#[tokio::test]+async fn selected_package_scalar_value_is_not_mistaken_for_a_function_signature() {+ let selected = vec![+ draft("CALLER", "BEGIN RETURN \"OWNER\".PKG.n; END;"),+ package_draft("CREATE PACKAGE \"OWNER\".PKG AS n NUMBER; END PKG;"),+ ];+ let result = resolve_draft(&Catalog::default(), &endpoint(), &selected, 0).await;+ assert!(result.issues.is_empty(), "{:?}", result.issues);+ assert_eq!(result.references[0].member.as_deref(), Some("N"));+}++#[tokio::test]+async fn unselected_package_contract_uses_complete_specification_and_rechecks_same_length_changes() {+ let mut entry = Entry::object("OTHER", "P", "PACKAGE");+ entry.grant = true;+ entry.member = Some("F");+ entry.function = true;+ let catalog = Catalog {+ entries: vec![entry],+ specifications: BTreeMap::from([(+ ("OTHER".into(), "P".into()),+ "CREATE PACKAGE \"OTHER\".P AS g NUMBER := 1; FUNCTION f RETURN NUMBER; END P;".into(),+ )]),+ ..Default::default()+ };+ let selected = vec![package_draft("CREATE PACKAGE \"OWNER\".PKG AS n NUMBER := OTHER.P.f(); END PKG;")];+ let result = resolve_draft(&catalog, &endpoint(), &selected, 0).await;+ assert!(result.issues.is_empty(), "{:?}", result.issues);+ let proof = result.proofs.iter().find(|proof| matches!(proof, CatalogReadProof::Source { .. })).unwrap();+ proof.verify(&catalog).await.unwrap();+ let frozen = reference_proof_manifest(&result.proof_groups, &result.proofs, &[]);+ catalog.source_changed.store(true, Ordering::SeqCst);+ assert!(proof.verify(&catalog).await.unwrap_err().contains("specification"));+ let compatible_change = resolve_draft(&catalog, &endpoint(), &selected, 0).await;+ assert!(compatible_change.issues.is_empty(), "The changed specification still has the same usable member");+ assert_ne!(+ frozen,+ reference_proof_manifest(&compatible_change.proof_groups, &compatible_change.proofs, &[]),+ "Reanalysis success must not silently replace a complete external source proof"+ );+ let missing = Catalog {+ specifications: BTreeMap::from([(+ ("OTHER".into(), "P".into()),+ "CREATE PACKAGE \"OTHER\".P AS g NUMBER := 1; END P;".into(),+ )]),+ ..catalog+ };+ assert!(!resolve_draft(&missing, &endpoint(), &selected, 0).await.issues.is_empty());+}++#[tokio::test]+async fn package_body_depends_on_final_spec_and_resolves_external_exception_role() {+ let spec = EditableObjectSourceSqlInput {+ database_type: endpoint().database_type,+ object_type: db::ObjectSourceKind::Package,+ schema: Some("OWNER".into()),+ name: "PKG".into(),+ source: "CREATE PACKAGE \"OWNER\".PKG AS PROCEDURE run; END PKG;".into(),+ };+ let analysis = dbx_sql::object_source_sql::analyze_oracle_package_body_draft(EditableObjectSourceSqlInput {+ object_type: db::ObjectSourceKind::PackageBody, source: "CREATE PACKAGE BODY \"OWNER\".PKG AS PROCEDURE run IS BEGIN NULL; EXCEPTION WHEN OTHER.P.e THEN RAISE OTHER.P.e; END run; END PKG;".into(), ..spec.clone()+ }, spec.clone());+ assert!(analysis.complete, "{:?}", analysis.issues);+ let body = SelectedFinalDraft {+ identity: RoutineIdentity {+ owner: "OWNER".into(),+ name: "PKG".into(),+ kind: db::ObjectSourceKind::PackageBody,+ },+ analysis: Some(analysis),+ };+ let selected = vec![body, package_draft(&spec.source)];+ let mut external = Entry::object("OTHER", "P", "PACKAGE");+ external.grant = true;+ let catalog = Catalog {+ entries: vec![external],+ specifications: BTreeMap::from([(+ ("OTHER".into(), "P".into()),+ "CREATE PACKAGE \"OTHER\".P AS e EXCEPTION; END P;".into(),+ )]),+ ..Default::default()+ };+ let result = resolve_draft(&catalog, &endpoint(), &selected, 0).await;+ assert!(result.issues.is_empty(), "{:?}", result.issues);+ assert_eq!(result.selected_dependencies, BTreeSet::from([1]));+ assert_eq!(result.references.len(), 2);+ assert!(result.references.iter().all(|reference| reference.member.as_deref() == Some("E")));+ assert_eq!(result.proofs.iter().filter(|proof| matches!(proof, CatalogReadProof::Source { .. })).count(), 1);+}++#[tokio::test]+async fn package_sql_columns_precede_member_roles_and_expired_locals_but_do_not_hide_missing_bindings() {+ let spec = EditableObjectSourceSqlInput { database_type: endpoint().database_type, object_type: db::ObjectSourceKind::Package,+ schema: Some("OWNER".into()), name: "PKG".into(), source: "CREATE PACKAGE \"OWNER\".PKG AS PROCEDURE run; FUNCTION f(x NUMBER) RETURN NUMBER; e EXCEPTION; v NUMBER; END PKG;".into() };+ let analysis = dbx_sql::object_source_sql::analyze_oracle_package_body_draft(EditableObjectSourceSqlInput {+ object_type: db::ObjectSourceKind::PackageBody,+ source: "CREATE PACKAGE BODY \"OWNER\".PKG AS FUNCTION f(x NUMBER) RETURN NUMBER IS BEGIN RETURN x; END f; PROCEDURE run IS n NUMBER; BEGIN DECLARE retired NUMBER; BEGIN NULL; END; SELECT f,e,v,retired INTO n,n,n,n FROM T; END run; END PKG;".into(), ..spec.clone()+ }, spec.clone());+ assert!(analysis.complete, "{:?}", analysis.issues);+ let selected = vec![+ SelectedFinalDraft {+ identity: RoutineIdentity {+ owner: "OWNER".into(),+ name: "PKG".into(),+ kind: db::ObjectSourceKind::PackageBody,+ },+ analysis: Some(analysis),+ },+ package_draft(&spec.source),+ ];+ for missing in [None, Some("F"), Some("E"), Some("RETIRED"), Some("V")] {+ let mut table = Entry::object("OWNER", "T", "TABLE");+ table.columns = ["F", "E", "V", "RETIRED"].into_iter().filter(|column| Some(*column) != missing).collect();+ let catalog =+ Catalog { entries: vec![table, Entry::object("OWNER", "RETIRED", "FUNCTION")], ..Default::default() };+ let result = resolve_draft(&catalog, &endpoint(), &selected, 0).await;+ if missing.is_none() || missing == Some("V") {+ assert!(result.issues.is_empty(), "{missing:?}: {:?}", result.issues);+ assert_eq!(result.references.len(), 1);+ } else {+ assert!(!result.issues.is_empty(), "incorrect fallback for {missing:?}");+ }+ }+}+#[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;")];@@ -230,6 +596,7 @@ async fn final_parameter_defaults_and_out_positions_are_checked_not_only_requiremode: mode.into(),data_type: "NUMBER".into(),has_default,+ default_expression: None,};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()];@@ -358,8 +725,15 @@ async fn selected_deletion_is_unavailable_and_external_evidence_is_rechecked_befproof.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!(result+ .proofs+ .iter()+ .any(|proof| matches!(proof, CatalogReadProof::Query { sql, .. } if sql.contains("ALL_OBJECTS"))));+ let proof = result+ .proofs+ .iter()+ .find(|proof| matches!(proof, CatalogReadProof::Query { sql, .. } if sql.contains("ALL_OBJECTS")))+ .unwrap();assert!(proof.verify(&catalog).await.is_err());let mut deleted = draft("F", "BEGIN RETURN 1; END;");deleted.analysis = None;diff --git a/crates/dbx-core/src/schema/oracle_routines/tests.rs b/crates/dbx-core/src/schema/oracle_routines/tests.rsindex b0c8e0e668..de124da889 100644--- a/crates/dbx-core/src/schema/oracle_routines/tests.rs+++ b/crates/dbx-core/src/schema/oracle_routines/tests.rs@@ -1,12 +1,225 @@use super::*;use serde_json::json;use std::sync::{- atomic::{AtomicUsize, Ordering},+ atomic::{AtomicBool, AtomicUsize, Ordering},Mutex,};const BODY: &str = "FUNCTION \"Quoted.Func\" RETURN VARCHAR2 IS BEGIN RETURN 'a b'; END";+struct PackageCatalog {+ inner: FakeCatalog,+ fail_body: bool,+ change_spec_during_body: bool,+ spec_changed: AtomicBool,+}++impl PackageCatalog {+ fn new() -> Self {+ Self {+ inner: FakeCatalog {+ objects: vec![+ object_row(12, "Pkg.With.Dot", "PACKAGE"),+ object_row(13, "Pkg.With.Dot", "PACKAGE BODY"),+ ],+ ..Default::default()+ },+ fail_body: false,+ change_spec_during_body: false,+ spec_changed: AtomicBool::new(false),+ }+ }++ fn body(kind: &db::ObjectSourceKind) -> String {+ format!("{} \"Pkg.With.Dot\" AS END;", kind_name(kind))+ }+}++#[async_trait::async_trait]+impl RoutineCatalog for PackageCatalog {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ if sql.contains("SOURCE_ROWS") {+ self.inner.queries.lock().unwrap().push(sql.into());+ let kind = if sql.contains("TYPE = 'PACKAGE BODY'") {+ db::ObjectSourceKind::PackageBody+ } else {+ db::ObjectSourceKind::Package+ };+ let body = Self::body(&kind);+ 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(&kind)),+ ]],+ &json!({}),+ ));+ }+ self.inner.query(sql).await+ }++ async fn source(&self, identity: &RoutineIdentity) -> Result<SourceReply, String> {+ if self.fail_body && identity.kind == db::ObjectSourceKind::PackageBody {+ return Err("body source permission denied".into());+ }+ self.inner.source_calls.fetch_add(1, Ordering::SeqCst);+ if self.change_spec_during_body && identity.kind == db::ObjectSourceKind::PackageBody {+ self.spec_changed.store(true, Ordering::SeqCst);+ }+ let mut body = Self::body(&identity.kind);+ if self.change_spec_during_body+ && identity.kind == db::ObjectSourceKind::Package+ && self.spec_changed.load(Ordering::SeqCst)+ {+ body = body.replace("AS END;", "AS c CONSTANT NUMBER := 2; END;");+ }+ Ok(serde_json::from_value(json!({"name":identity.name,"schema":identity.owner,"object_type":identity.kind,"source":format!("CREATE OR REPLACE {body}"),"source_origin":"oceanbase-dictionary"})).unwrap())+ }+}++#[tokio::test]+async fn same_second_specification_change_during_body_read_does_not_make_a_mixed_pair_complete() {+ let catalog = PackageCatalog { change_spec_during_body: true, ..PackageCatalog::new() };+ let options = RoutineReadOptions {+ object_kinds: Some(vec![db::ObjectSourceKind::Package, db::ObjectSourceKind::PackageBody]),+ ..Default::default()+ };+ let snapshot =+ collect_snapshot_with_options(&catalog, endpoint(), SourceOrigin::OceanBaseDictionary, &options).await;+ assert_eq!(snapshot.state, RoutineReadState::Partial);+ assert!(snapshot.enumeration_complete, "the catalog IDs and second-resolution DDL times did not change");+ let specification =+ snapshot.objects.iter().find(|object| object.version.identity.kind == db::ObjectSourceKind::Package).unwrap();+ assert!(!specification.source_complete);+ assert!(specification.source.as_ref().unwrap().ends_with("AS END;"), "retain the original text for review");+ assert!(specification.issues.iter().any(|issue| issue.message.contains("changed")));+}++#[tokio::test]+async fn typed_body_selection_reads_the_pair_without_adding_a_specification_selection() {+ let catalog = PackageCatalog::new();+ let selected = RoutineSelection { name: "Pkg.With.Dot".into(), kind: db::ObjectSourceKind::PackageBody };+ let options = RoutineReadOptions {+ object_kinds: Some(vec![db::ObjectSourceKind::PackageBody]),+ selected_objects: Some(vec![selected.clone()]),+ ..Default::default()+ };+ options.validate().unwrap();+ let snapshot =+ collect_snapshot_with_options(&catalog, endpoint(), SourceOrigin::OceanBaseDictionary, &options).await;+ assert_eq!(snapshot.state, RoutineReadState::Complete);+ assert_eq!(snapshot.objects.len(), 2);+ assert_eq!(snapshot.objects[0].version.identity.kind, db::ObjectSourceKind::Package);+ assert_eq!(snapshot.objects[1].version.identity.kind, db::ObjectSourceKind::PackageBody);+ assert!(snapshot.objects.iter().all(|object| object.source_complete && object.dependencies_complete));+ assert!(snapshot.objects.iter().all(|object| object.source_origin == Some(SourceOrigin::OceanBaseDictionary)));+ assert_eq!(serde_json::to_value(&snapshot).unwrap()["objects"][0]["sourceOrigin"], "oceanbase-dictionary");+ assert_eq!(catalog.inner.source_calls.load(Ordering::SeqCst), 4);+ assert_eq!(options.selected_objects, Some(vec![selected]));+ assert!(catalog+ .inner+ .queries+ .lock()+ .unwrap()+ .iter()+ .filter(|sql| sql.contains("OBJECT_ID >"))+ .all(|sql| sql.contains("'PACKAGE BODY'") && sql.contains("'PACKAGE'")));+}++#[tokio::test]+async fn typed_standalone_selection_enriches_the_other_kind_as_read_only_conflict_evidence() {+ let catalog = FakeCatalog::default();+ let selected = RoutineSelection { name: "Quoted.Func".into(), kind: db::ObjectSourceKind::Procedure };+ let options = RoutineReadOptions { selected_objects: Some(vec![selected.clone()]), ..Default::default() };+ options.validate().unwrap();+ let snapshot =+ collect_snapshot_with_options(&catalog, endpoint(), SourceOrigin::OceanBaseDictionary, &options).await;+ assert_eq!(snapshot.state, RoutineReadState::Complete);+ assert_eq!(snapshot.objects[0].version.identity.kind, db::ObjectSourceKind::Function);+ assert!(snapshot.objects[0].source_complete);+ assert_eq!(options.selected_objects, Some(vec![selected]));+}++#[tokio::test]+async fn a_failed_body_read_retains_both_exact_objects_without_inventing_absence() {+ let catalog = PackageCatalog { fail_body: true, ..PackageCatalog::new() };+ let options = RoutineReadOptions {+ object_kinds: Some(vec![db::ObjectSourceKind::Package, db::ObjectSourceKind::PackageBody]),+ ..Default::default()+ };+ let snapshot =+ collect_snapshot_with_options(&catalog, endpoint(), SourceOrigin::OceanBaseDictionary, &options).await;+ assert_eq!(snapshot.state, RoutineReadState::Partial);+ assert!(snapshot.enumeration_complete);+ assert_eq!(snapshot.objects.len(), 2);+ assert!(snapshot.objects[0].source_complete);+ assert!(!snapshot.objects[1].source_complete);+ assert!(!snapshot.objects[1].issues.is_empty());+}++#[test]+fn legacy_inventory_remains_procedure_function_only_and_new_selections_are_explicit() {+ let options = RoutineReadOptions::default();+ options.validate().unwrap();+ let sql = inventory_sql("Owner.Mixed", false, 0, &options.inventory_kinds());+ assert!(sql.contains("IN ('PROCEDURE', 'FUNCTION')"));+ assert!(!sql.contains("'PACKAGE'"));+ let package = vec![db::ObjectSourceKind::Package];+ assert!(RoutineReadOptions {+ object_kinds: Some(package),+ selected_routines: Some(vec!["Pkg.With.Dot".into()]),+ ..Default::default()+ }+ .validate()+ .is_err());+ assert!(RoutineReadOptions { object_kinds: Some(vec![db::ObjectSourceKind::View]), ..Default::default() }+ .validate()+ .is_err());+ assert!(RoutineReadOptions {+ selected_objects: Some(vec![RoutineSelection { name: "P".into(), kind: db::ObjectSourceKind::Package }]),+ ..Default::default()+ }+ .validate()+ .is_err());+ let decoded: RoutineReadOptions = serde_json::from_value(json!({"objectKinds":["PACKAGE","PACKAGE_BODY"],"selectedObjects":[{"name":"Pkg.With.Dot","kind":"PACKAGE_BODY"}]})).unwrap();+ decoded.validate().unwrap();+ assert_eq!(decoded.selected_objects.unwrap()[0].kind, db::ObjectSourceKind::PackageBody);+}++#[tokio::test]+async fn package_source_checks_the_reported_metadata_origin_and_exact_metadata_kind() {+ for (kind, keyword, metadata_kind) in [+ (db::ObjectSourceKind::Package, "PACKAGE", "PACKAGE_SPEC"),+ (db::ObjectSourceKind::PackageBody, "PACKAGE BODY", "PACKAGE_BODY"),+ ] {+ let source = format!("CREATE OR REPLACE {keyword} \"P\" AS c CONSTANT VARCHAR2(10) := q'[中文😀]'; END;");+ let catalog = FakeCatalog { length: source.chars().count() as u64, ..Default::default() };+ let identity = RoutineIdentity { owner: "Owner.Mixed".into(), name: "P".into(), kind };+ let reply: SourceReply = serde_json::from_value(json!({"name":"P","schema":"Owner.Mixed","object_type":identity.kind,"source":source,"source_origin":"oracle-metadata"})).unwrap();+ let result = check_source(&catalog, &endpoint(), &identity, &reply, SourceOrigin::OceanBaseDictionary).await;+ assert!(result.is_ok(), "metadata fallback must use its own source evidence: {result:?}");+ assert!(catalog.queries.lock().unwrap().iter().any(|sql| sql.contains(&format!("GET_DDL('{metadata_kind}'"))));+ }+}++#[tokio::test]+async fn package_source_without_actual_origin_cannot_be_marked_complete() {+ let body = "PACKAGE \"P\" AS END;";+ let catalog = FakeCatalog { length: body.chars().count() as u64, ..Default::default() };+ let identity =+ RoutineIdentity { owner: "Owner.Mixed".into(), name: "P".into(), kind: db::ObjectSourceKind::Package };+ let reply: SourceReply = serde_json::from_value(+ json!({"name":"P","schema":"Owner.Mixed","object_type":"PACKAGE","source":format!("CREATE OR REPLACE {body}")}),+ )+ .unwrap();+ assert!(check_source(&catalog, &endpoint(), &identity, &reply, SourceOrigin::OceanBaseDictionary).await.is_err());+}+struct FakeCatalog {login: String,objects: Vec<Vec<Value>>,diff --git a/crates/dbx-core/src/schema/oracle_routines/transfer.rs b/crates/dbx-core/src/schema/oracle_routines/transfer.rsindex 76a00d27f2..9cfc24974b 100644--- a/crates/dbx-core/src/schema/oracle_routines/transfer.rs+++ b/crates/dbx-core/src/schema/oracle_routines/transfer.rs@@ -2,6 +2,10 @@ 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};+mod packages;+pub(crate) use packages::{claim_transfer_packages, prepare_transfer_packages, PackageTransferPreflightError};+pub use packages::{OraclePackageTransferPreview, OraclePackageTransferRequest};+pub(crate) struct RoutineTransferInput {pub source_connection_id: String,pub source_database: String,@@ -126,6 +130,8 @@ pub(crate) async fn transfer_oracle_routine_core(database: input.target_database,identity: RoutineIdentity { owner: input.target_owner, ..input.identity },sql: sql.clone(),+ require_absent: false,+ prerequisite_operation_id: None,supersedes_operation_id: None,},context.target_config.clone(),diff --git a/crates/dbx-core/src/schema/oracle_routines/transfer/packages.rs b/crates/dbx-core/src/schema/oracle_routines/transfer/packages.rsnew file mode 100644index 0000000000..2550239b0a--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/transfer/packages.rs@@ -0,0 +1,1394 @@+use super::super::operations::{RoutineOperationPin, RoutineWriteBinding};+use super::*;+use crate::data::transfer::oracle_table_contract::{self, FrozenTableDdl, LengthSemantics};+use crate::data::transfer::{+ validate_transfer_database_pair, validate_transfer_request, TransferContent, TransferRequest,+};+use std::collections::HashSet;++mod external_types;+mod pending;+pub(crate) use pending::PackageTransfer;++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OraclePackageTransferRequest {+ pub input: Option<OracleRoutinePlanInput>,+ #[serde(default)]+ pub operation_ids: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub pending_tables: Option<PendingPackageTables>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct OraclePackageTransferPreview {+ pub input: OracleRoutinePlanInput,+ pub plan: OracleRoutinePlan,+ pub skipped: Vec<RoutineIdentity>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub pending_tables: Option<PendingPackageTables>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PendingPackageTables {+ pub source: RoutineEndpoint,+ pub target: RoutineEndpoint,+ pub tables: Vec<FrozenTableDdl>,+ pub dependency_manifest: Value,+ pub table_evidence: Vec<Value>,+}++#[derive(Debug)]+pub(crate) struct PackageTransferPreflightError {+ message: String,+ preview: Option<Box<OraclePackageTransferPreview>>,+}++impl From<String> for PackageTransferPreflightError {+ fn from(message: String) -> Self {+ Self { message, preview: None }+ }+}++impl From<&str> for PackageTransferPreflightError {+ fn from(message: &str) -> Self {+ message.to_owned().into()+ }+}++impl PackageTransferPreflightError {+ pub(crate) fn into_progress(self, request: &TransferRequest) -> crate::data::transfer::TransferProgress {+ use crate::data::transfer::{TransferProgress, TransferStatus};+ TransferProgress {+ oracle_package_approval: None,+ oracle_routine_operation: None,+ oracle_package_preflight: self.preview.map(|preview| *preview),+ transfer_id: request.transfer_id.clone(),+ table: "schema objects".into(),+ table_index: 0,+ total_tables: request.tables.len(),+ rows_transferred: 0,+ total_rows: None,+ status: TransferStatus::Error,+ error: Some(self.message),+ terminal: true,+ }+ }+}++pub(crate) struct ApprovedPackageTransfer<'a> {+ writes: Vec<(String, RoutineWriteBinding)>,+ skipped: Vec<RoutineIdentity>,+ _pins: Vec<RoutineOperationPin<'a>>,+}++impl ApprovedPackageTransfer<'_> {+ fn identities(&self) -> impl Iterator<Item = &RoutineIdentity> {+ self.writes.iter().map(|(_, binding)| &binding.identity)+ }++ fn skipped(&self) -> &[RoutineIdentity] {+ &self.skipped+ }++ async fn execute(&self, state: &AppState, index: usize) -> Result<RoutineOperationRecord, String> {+ let (id, binding) = self.writes.get(index).ok_or("The approved package step is unavailable")?;+ execution::execute_prepared_inline(state, id, &binding.sql).await+ }++ pub(crate) async fn run<F>(+ &self,+ state: &AppState,+ request: &TransferRequest,+ prerequisites_succeeded: bool,+ mut progress: F,+ ) -> (crate::data::transfer::TransferObjectOutcome, bool)+ where+ F: FnMut(crate::data::transfer::TransferProgress),+ {+ use crate::data::transfer::{is_cancelled, TransferObjectOutcome, TransferProgress, TransferStatus};+ let label = |identity: &RoutineIdentity| {+ format!(+ "{}:{}",+ if identity.kind == db::ObjectSourceKind::Package { "Package" } else { "PackageBody" },+ identity.name+ )+ };+ let mut outcome =+ TransferObjectOutcome { skipped: self.skipped().iter().map(label).collect(), ..Default::default() };+ if !prerequisites_succeeded {+ return (outcome, false);+ }+ for (index, identity) in self.identities().enumerate() {+ if is_cancelled(&request.transfer_id).await {+ return (outcome, true);+ }+ let item = label(identity);+ let (operation, error) = match self.execute(state, index).await {+ Ok(record) => {+ let error = if record.verified() {+ outcome.transferred.push(item.clone());+ None+ } else {+ Some(record.failure_message())+ };+ (Some(record), error)+ }+ Err(error) => (None, Some(error)),+ };+ progress(TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: operation,+ transfer_id: request.transfer_id.clone(),+ table: item.clone(),+ table_index: request.tables.len(),+ total_tables: request.tables.len(),+ rows_transferred: 0,+ total_rows: None,+ status: if error.is_some() { TransferStatus::Error } else { TransferStatus::TableDone },+ error: error.clone(),+ terminal: false,+ });+ if error.is_some() {+ outcome.failed.push(item);+ break;+ }+ }+ (outcome, false)+ }+}++fn claim_approvals<'a>(+ registry: &'a RoutineOperationRegistry,+ input: &OracleRoutinePlanInput,+ operation_ids: &[String],+) -> Result<ApprovedPackageTransfer<'a>, String> {+ let selected = input.drafts.iter().map(|draft| draft.identity.clone()).collect::<Vec<_>>();+ if operation_ids.len() != selected.len() {+ return Err("Every selected new package kind requires its original approved operation ID".into());+ }+ let ids = operation_ids.iter().collect::<HashSet<_>>();+ if ids.len() != operation_ids.len() {+ return Err("A package transfer cannot consume an approval twice".into());+ }+ let pins = operation_ids.iter().map(|id| registry.pin(id)).collect::<Result<Vec<_>, _>>()?;+ let mut writes = Vec::new();+ let mut seen = HashSet::new();+ for id in operation_ids {+ let binding = registry.binding_for_readback(id)?;+ let draft = input+ .drafts+ .iter()+ .find(|draft| draft.identity == binding.identity)+ .ok_or("The package approval belongs to an unselected identity")?;+ let compare =+ binding.compare.as_ref().ok_or("A package transfer requires its reviewed comparison preflight")?;+ let source = compare.source.as_ref().ok_or("The package approval has no original source evidence")?;+ if binding.target != input.target.endpoint+ || source.endpoint != input.source.endpoint+ || !binding.require_absent+ || !matches!(&binding.goal, RoutineReadbackGoal::Definition { sql } if *sql == binding.sql)+ || draft.action != RoutinePlanAction::Create+ || draft.baseline_operation_id.is_some()+ || !matches!(binding.identity.kind, db::ObjectSourceKind::Package | db::ObjectSourceKind::PackageBody)+ || !matches!(&compare.target, plan::ExpectedRoutine::Absent(identity) if *identity == binding.identity)+ || compare.selected.len() != selected.len()+ || compare.selected.iter().any(|identity| !selected.contains(identity))+ {+ return Err("The package approval does not match this exact source, target and new-object selection".into());+ }+ let source_name = draft.source_name.as_deref().unwrap_or(&draft.identity.name);+ if !matches!(&source.expected, plan::ExpectedRoutine::Present(object)+ if object.version.identity.owner == input.source.endpoint.schema+ && object.version.identity.name == source_name+ && object.version.identity.kind == draft.identity.kind)+ {+ return Err("The package approval belongs to a different original source object".into());+ }+ if let Some(sql) = &draft.sql {+ dbx_sql::object_source_sql::validate_oracle_routine_target_definition(+ dbx_sql::object_source_sql::EditableObjectSourceSqlInput {+ database_type: input.target.endpoint.database_type,+ object_type: draft.identity.kind.clone(),+ schema: Some(draft.identity.owner.clone()),+ name: draft.identity.name.clone(),+ source: sql.clone(),+ },+ Some(false),+ )?;+ let approved = prepare_oracle_routine_definition(OracleRoutineDefinitionInput {+ database_type: input.target.endpoint.database_type,+ object_type: draft.identity.kind.clone(),+ source_owner: draft.identity.owner.clone(),+ target_owner: draft.identity.owner.clone(),+ name: draft.identity.name.clone(),+ source: sql.clone(),+ replace: false,+ })?;+ if approved != binding.sql {+ return Err("The package target draft changed after approval; retain it and validate again".into());+ }+ }+ if binding.prerequisite_operation_ids.iter().any(|before| !ids.contains(before) || !seen.contains(before))+ || binding.package_effect_operation_ids.iter().any(|other| !ids.contains(other))+ {+ return Err("Package approvals must retain the reviewed dependency order".into());+ }+ let record = registry.observe(id).operation.ok_or("Original package approval is unavailable")?;+ if record.lifecycle != RoutineOperationLifecycle::Prepared && !record.verified() {+ return Err(record.failure_message());+ }+ seen.insert(id.clone());+ writes.push((id.clone(), binding));+ }+ Ok(ApprovedPackageTransfer { writes, skipped: Vec::new(), _pins: pins })+}++fn selections(request: &TransferRequest) -> Vec<RoutineSelection> {+ let mut selected = Vec::new();+ for selection in request.objects.iter().flatten() {+ let kind = match selection.object_type {+ TransferObjectKind::Package => db::ObjectSourceKind::Package,+ TransferObjectKind::PackageBody => db::ObjectSourceKind::PackageBody,+ _ => continue,+ };+ for name in &selection.names {+ let identity = RoutineSelection { name: name.clone(), kind: kind.clone() };+ if !selected.contains(&identity) {+ selected.push(identity);+ }+ }+ }+ selected+}++fn transfer_input(+ source: RoutineSnapshot,+ target: RoutineSnapshot,+ selected: &[RoutineSelection],+ provided: Option<&[RoutinePlanDraft]>,+) -> Result<(OracleRoutinePlanInput, Vec<RoutineIdentity>), String> {+ let mut skipped = Vec::new();+ let mut drafts = Vec::new();+ if let Some(provided) = provided {+ for (index, draft) in provided.iter().enumerate() {+ if draft.identity.owner != target.endpoint.schema+ || !selected+ .iter()+ .any(|selection| selection.name == draft.identity.name && selection.kind == draft.identity.kind)+ || provided[..index].iter().any(|other| other.identity == draft.identity)+ || draft.action != RoutinePlanAction::Create+ || draft.baseline_operation_id.is_some()+ {+ return Err("Transfer package drafts must retain the exact selected new identities; compare existing objects before replacing or deleting them".into());+ }+ }+ }+ for selection in selected {+ let identity = RoutineIdentity {+ owner: target.endpoint.schema.clone(),+ name: selection.name.clone(),+ kind: selection.kind.clone(),+ };+ let existing = target.objects.iter().filter(|object| object.version.identity == identity).collect::<Vec<_>>();+ if existing.len() > 1 {+ return Err("The selected target package identity is ambiguous; refresh its complete inventory".into());+ }+ let supplied = provided.and_then(|drafts| drafts.iter().find(|draft| draft.identity == identity));+ if !existing.is_empty() {+ if supplied.is_some() {+ return Err("The target package kind already exists and must be skipped; open its comparison to review a replacement".into());+ }+ skipped.push(identity);+ } else if let Some(provided) = provided {+ drafts.push(+ provided+ .iter()+ .find(|draft| draft.identity == identity)+ .ok_or("The reviewed transfer omits a selected new package kind; refresh its preview")?+ .clone(),+ );+ } else {+ drafts.push(RoutinePlanDraft {+ identity,+ action: RoutinePlanAction::Create,+ source_name: Some(selection.name.clone()),+ sql: None,+ baseline_operation_id: None,+ supersedes_operation_id: None,+ package_body_source: None,+ package_contract: None,+ confirm_package_pair: false,+ });+ }+ }+ Ok((OracleRoutinePlanInput { source, target, drafts }, skipped))+}++async fn read_transfer_package_input(+ state: &AppState,+ request: &TransferRequest,+) -> Result<Option<(OracleRoutinePlanInput, Vec<RoutineIdentity>)>, String> {+ if !request.has_package_selection() {+ return Ok(None);+ }+ let source_product = crate::data::transfer::get_db_type(state, &request.source_connection_id).await?;+ let target_product = crate::data::transfer::get_db_type(state, &request.target_connection_id).await?;+ validate_transfer_database_pair(request, &source_product, &target_product)?;+ if source_product == DatabaseType::Xugu && target_product == DatabaseType::Xugu && request.oracle_packages.is_none()+ {+ return Ok(None);+ }+ validate_transfer_request(request)?;+ if matches!(request.content, TransferContent::DataOnly) {+ return Err("Data-only transfer does not execute package DDL".into());+ }+ let selected = selections(request);+ let previous = request.oracle_packages.as_ref().and_then(|package| package.input.as_ref());+ let (source, target) = if let Some(input) = previous {+ for (endpoint, connection, database, schema, product) in [+ (+ &input.source.endpoint,+ &request.source_connection_id,+ &request.source_database,+ &request.source_schema,+ source_product,+ ),+ (+ &input.target.endpoint,+ &request.target_connection_id,+ &request.target_database,+ &request.target_schema,+ target_product,+ ),+ ] {+ if endpoint.connection_id != *connection+ || endpoint.database != *database+ || endpoint.schema != *schema+ || endpoint.database_type != product+ {+ return Err("The package transfer preview belongs to different source or target identities; retain the drafts and refresh it".into());+ }+ plan::checked_endpoint(state, endpoint).await?;+ }+ (input.source.clone(), input.target.clone())+ } else {+ let options = RoutineReadOptions {+ object_kinds: Some(selected.iter().map(|selection| selection.kind.clone()).fold(+ Vec::new(),+ |mut kinds, kind| {+ if !kinds.contains(&kind) {+ kinds.push(kind);+ }+ kinds+ },+ )),+ selected_objects: Some(selected.clone()),+ selected_routines: None,+ };+ let source = load_schema_diff_routines_with_options_core(+ state,+ &request.source_connection_id,+ &request.source_database,+ &request.source_schema,+ options.clone(),+ )+ .await?;+ let target = load_schema_diff_routines_with_options_core(+ state,+ &request.target_connection_id,+ &request.target_database,+ &request.target_schema,+ options,+ )+ .await?;+ (source, target)+ };+ let (input, skipped) = transfer_input(source, target, &selected, previous.map(|input| input.drafts.as_slice()))?;+ let target_config = plan::checked_endpoint(state, &input.target.endpoint).await?;+ let target_catalog = LiveCatalog { state, endpoint: &input.target.endpoint, config: &target_config };+ for identity in &skipped {+ let before = &input.target.objects.iter().find(|object| object.version.identity == *identity).unwrap().version;+ let current =+ readback::exact_version(&readback::read_namespace(&target_catalog, identity, false).await?, identity)?;+ if *before != current {+ return Err(+ "An existing package selected for skipping changed; refresh before starting any transfer writes".into(),+ );+ }+ }+ Ok(Some((input, skipped)))+}++pub(crate) async fn prepare_transfer_packages(+ state: &AppState,+ request: &TransferRequest,+ structure: Option<&mut crate::data::transfer::TransferStructurePreview>,+) -> Result<Option<OraclePackageTransferPreview>, String> {+ let Some((mut input, skipped)) = read_transfer_package_input(state, request).await? else {+ return Ok(None);+ };+ let mut pending_tables = None;+ let plan = if input.drafts.is_empty() {+ OracleRoutinePlan { target: input.target.endpoint.clone(), steps: Vec::new(), ready: true }+ } else if let Some(structure) = structure.filter(|_| request.create_table) {+ let candidates = structure+ .tables+ .iter()+ .enumerate()+ .filter_map(|(index, table)| {+ let prepared = table.oracle_plan.as_ref()?;+ let columns = oracle_table_contract::planned_columns(+ &prepared.ddl,+ &input.target.endpoint.schema,+ &table.target_table,+ )+ .ok()?;+ Some((+ index,+ super::super::references::PlannedRelation {+ owner: input.target.endpoint.schema.clone(),+ name: table.target_table.clone(),+ columns,+ },+ ))+ })+ .collect::<Vec<_>>();+ if candidates.is_empty() {+ if request.oracle_packages.as_ref().is_some_and(|packages| packages.pending_tables.is_some()) {+ plan::prepare_transfer_plan_with_tables(state, input.clone(), &[], true).await?.0+ } else {+ prepare_oracle_routine_plan_core(state, input.clone()).await?+ }+ } else {+ let relations = candidates+ .iter()+ .map(|(_, table)| super::super::references::PlannedRelation {+ owner: table.owner.clone(),+ name: table.name.clone(),+ columns: table.columns.clone(),+ })+ .collect::<Vec<_>>();+ let (mut plan, used, dependency_manifest) = plan::prepare_transfer_plan_with_tables(+ state,+ input.clone(),+ &relations,+ request.oracle_packages.as_ref().is_some_and(|packages| packages.pending_tables.is_some()),+ )+ .await?;+ if !used.is_empty() && plan.steps.iter().all(|step| step.issues.is_empty()) {+ let config = plan::checked_endpoint(state, &input.target.endpoint).await?;+ let catalog = LiveCatalog { state, endpoint: &input.target.endpoint, config: &config };+ let pending = prepare_pending_tables(+ &catalog,+ request,+ &input.target.endpoint,+ &input.source.endpoint,+ structure,+ &candidates,+ &used,+ dependency_manifest,+ )+ .await;+ match pending {+ Ok(pending) => pending_tables = Some(pending),+ Err(message) => {+ for step in &mut plan.steps {+ step.issues.push(dbx_sql::object_source_sql::OracleDraftIssue {+ code: "pending-table-preflight".into(),+ message: message.clone(),+ line: 1,+ column: 1,+ });+ }+ }+ }+ }+ plan+ }+ } else {+ prepare_oracle_routine_plan_core(state, input.clone()).await?+ };+ if pending_tables.is_some() {+ for draft in &mut input.drafts {+ draft.supersedes_operation_id = None;+ draft.sql = Some(+ plan.steps+ .iter()+ .find(|step| step.identity == draft.identity)+ .ok_or("The final package draft is unavailable")?+ .sql+ .clone(),+ );+ }+ }+ Ok(Some(OraclePackageTransferPreview { input, plan, skipped, pending_tables }))+}++async fn prepare_pending_tables(+ catalog: &impl RoutineCatalog,+ request: &TransferRequest,+ endpoint: &RoutineEndpoint,+ source: &RoutineEndpoint,+ structure: &mut crate::data::transfer::TransferStructurePreview,+ candidates: &[(usize, super::super::references::PlannedRelation)],+ used: &std::collections::BTreeSet<usize>,+ dependency_manifest: Value,+) -> Result<PendingPackageTables, String> {+ let login = catalog.query("SELECT USER AS LOGIN_OWNER FROM DUAL").await?;+ login.flags.check()?;+ if login.rows.len() != 1 {+ return Err("The target table namespace owner is unknown; retain the package drafts".into());+ }+ let dba = login.text(&login.rows[0], "LOGIN_OWNER")? != endpoint.schema;+ let mut tables = Vec::new();+ let mut table_evidence = Vec::new();+ let mut updates = Vec::new();+ let mut default_length = None;+ for &used_index in used {+ let &(index, ref relation) = candidates.get(used_index).ok_or("The pending table identity is unavailable")?;+ let table = &structure.tables[index];+ let prepared = table.oracle_plan.as_ref().ok_or("The final target table plan is unavailable")?;+ let namespace = readback::read_namespace(+ catalog,+ &RoutineIdentity {+ owner: relation.owner.clone(),+ name: relation.name.clone(),+ kind: db::ObjectSourceKind::Package,+ },+ dba,+ )+ .await?;+ if !namespace.rows.is_empty() {+ if !request.drop_target_before_create || namespace.rows.len() != 1 {+ return Err(format!(+ "The planned table {} no longer has an empty target namespace; refresh before writing",+ relation.name+ ));+ }+ let row = &namespace.rows[0];+ if namespace.text(row, "OWNER")? != relation.owner+ || namespace.text(row, "OBJECT_NAME")? != relation.name+ || namespace.text(row, "OBJECT_TYPE")? != "TABLE"+ {+ return Err(format!("The rebuild table {} has a different namespace identity", relation.name));+ }+ namespace.integer(row, "OBJECT_ID")?;+ namespace.text(row, "STATUS")?;+ namespace.text(row, "LAST_DDL_TIME")?;+ }+ let confirmed = request+ .oracle_packages+ .as_ref()+ .and_then(|packages| packages.pending_tables.as_ref())+ .map(|pending| {+ pending+ .tables+ .iter()+ .find(|frozen| {+ frozen.source_table() == table.source_table+ && frozen.owner() == endpoint.schema+ && frozen.name() == table.target_table+ })+ .ok_or("The confirmed pending table selection changed; retain drafts and refresh")+ })+ .transpose()?;+ let choice = if let Some(confirmed) = confirmed {+ confirmed.length_choice()+ } else if oracle_table_contract::needs_length_choice(&prepared.ddl)? {+ if default_length.is_none() {+ default_length = Some(read_target_length_choice(catalog).await?);+ }+ default_length+ } else {+ None+ };+ let frozen = FrozenTableDdl::from_server_plan(+ &table.source_table,+ &endpoint.schema,+ &table.target_table,+ &prepared.ddl,+ prepared.source_evidence.clone().ok_or("The complete original table evidence is missing")?,+ choice,+ )?;+ let final_ddl = frozen.final_ddl();+ let base = prepared.ddl.trim().trim_end_matches(';');+ if table.sql.matches(base).count() != 1 || structure.sql.matches(&table.sql).count() != 1 {+ return Err("The complete table preview does not contain its unique prepared CREATE statement".into());+ }+ let sql = table.sql.replacen(base, final_ddl.trim().trim_end_matches(';'), 1);+ if let Some(confirmed) = confirmed {+ confirmed.verify_server_plan(+ &table.source_table,+ &endpoint.schema,+ &table.target_table,+ &prepared.ddl,+ prepared.source_evidence.clone().unwrap(),+ )?;+ }+ let type_proofs = external_types::read(catalog, endpoint, &frozen).await?;+ table_evidence.push(serde_json::json!({ "sourceTable": table.source_table,+ "externalTypeProofs": external_types::manifest(&type_proofs),+ "targetTable": table.target_table, "namespaceColumns": namespace.columns,+ "namespaceRows": namespace.rows.iter().map(|row| row.iter().map(super::super::references::lossless_catalog_value).collect::<Vec<_>>()).collect::<Vec<_>>(), "sql": sql }));+ updates.push((index, sql));+ tables.push(frozen);+ }+ // Apply only after the whole batch has retained complete, typed evidence.+ for (index, sql) in updates {+ structure.sql = structure.sql.replacen(&structure.tables[index].sql, &sql, 1);+ structure.tables[index].sql = sql;+ }+ Ok(PendingPackageTables {+ source: source.clone(),+ target: endpoint.clone(),+ tables,+ dependency_manifest,+ table_evidence,+ })+}++async fn read_target_length_choice(catalog: &impl RoutineCatalog) -> Result<LengthSemantics, String> {+ let reply =+ catalog.query("SELECT VALUE FROM NLS_SESSION_PARAMETERS WHERE PARAMETER = 'NLS_LENGTH_SEMANTICS'").await?;+ reply.flags.check()?;+ if reply.rows.len() != 1 {+ return Err(+ "The target character length unit is not uniquely readable; retain the table and package drafts".into()+ );+ }+ match reply.text(&reply.rows[0], "VALUE")?.as_str() {+ "BYTE" => Ok(LengthSemantics::Bytes),+ "CHAR" => Ok(LengthSemantics::Characters),+ _ => Err("The target character length unit is unknown; retain the table and package drafts".into()),+ }+}++pub(crate) async fn claim_transfer_packages<'a>(+ state: &'a AppState,+ request: &TransferRequest,+ structure: Option<&mut crate::data::transfer::TransferStructurePreview>,+) -> Result<Option<PackageTransfer<'a>>, PackageTransferPreflightError> {+ if !request.has_package_selection() {+ return Ok(None);+ }+ if let Some(packages) = &request.oracle_packages {+ if packages.input.is_none() {+ return Err("The reviewed package transfer input is missing; refresh its preview".into());+ }+ if let Some(confirmed) = &packages.pending_tables {+ if !packages.operation_ids.is_empty() || confirmed.tables.is_empty() {+ return Err("Pending table confirmation cannot carry previously approved package operation IDs".into());+ }+ let structure = structure.ok_or("Pending table confirmation requires the original table transfer stage; refresh the complete transfer preview")?;+ let preview = prepare_transfer_packages(state, request, Some(structure))+ .await?+ .ok_or("The confirmed mixed package selection is unavailable")?;+ let preview = confirm_pending_preview(preview, confirmed)?;+ return Ok(Some(PackageTransfer::AwaitingTables(Box::new(pending::PendingClaim { preview }))));+ }+ // Pin before any asynchronous reads: closing the preview cannot discard+ // approvals already claimed by this server-side transfer.+ let input = packages.input.as_ref().unwrap();+ let mut approved = claim_approvals(&state.routine_operations, input, &packages.operation_ids)?;+ let (_, skipped) =+ read_transfer_package_input(state, request).await?.ok_or("The reviewed package selection is missing")?;+ let source_config = plan::checked_endpoint(state, &input.source.endpoint).await?;+ let target_config = plan::checked_endpoint(state, &input.target.endpoint).await?;+ let (_, origin) = routine_source_origin(&target_config)?;+ plan::verify_transfer_preflights(+ &approved.writes,+ &LiveCatalog { state, endpoint: &input.source.endpoint, config: &source_config },+ &LiveCatalog { state, endpoint: &input.target.endpoint, config: &target_config },+ origin,+ )+ .await?;+ approved.skipped = skipped;+ return Ok(Some(PackageTransfer::Approved(approved)));+ }+ let Some(preview) = prepare_transfer_packages(state, request, None).await? else {+ return Ok(None);+ };+ let preview = require_ready_transfer_preview(preview)?;+ let ids = preview+ .plan+ .steps+ .iter()+ .filter_map(|step| step.operation.as_ref().map(|operation| operation.operation_id.clone()))+ .collect::<Vec<_>>();+ let mut approved = claim_approvals(&state.routine_operations, &preview.input, &ids)?;+ approved.skipped = preview.skipped;+ Ok(Some(PackageTransfer::Approved(approved)))+}++fn require_ready_transfer_preview(+ preview: OraclePackageTransferPreview,+) -> Result<OraclePackageTransferPreview, PackageTransferPreflightError> {+ if !preview.plan.ready {+ return Err(PackageTransferPreflightError {+ message: "Package transfer requires target-draft corrections; open its structure preview and retain the original source before any writes".into(),+ preview: Some(Box::new(preview)),+ });+ }+ Ok(preview)+}++fn confirm_pending_preview(+ preview: OraclePackageTransferPreview,+ confirmed: &PendingPackageTables,+) -> Result<OraclePackageTransferPreview, PackageTransferPreflightError> {+ if preview.pending_tables.as_ref() != Some(confirmed)+ || preview.plan.ready+ || preview.plan.steps.is_empty()+ || preview.plan.steps.iter().any(|step| !step.issues.is_empty() || step.operation.is_some())+ {+ return Err(PackageTransferPreflightError { message: "The complete source, table SQL, namespace or package dependency evidence changed after confirmation; retain drafts and refresh before any writes".into(), preview: Some(Box::new(preview)) });+ }+ Ok(preview)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ struct TableCatalog {+ replies: std::sync::Mutex<std::collections::VecDeque<(&'static str, Result<CatalogReply, String>)>>,+ }++ #[async_trait::async_trait]+ impl RoutineCatalog for TableCatalog {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ let (expected, reply) = self.replies.lock().unwrap().pop_front().expect("Unexpected catalog read");+ assert!(sql.contains(expected), "{sql}");+ reply+ }+ async fn source(&self, _: &RoutineIdentity) -> Result<SourceReply, String> {+ panic!("Table planning never reads or invokes a package")+ }+ }++ fn reply(columns: &[&str], rows: Vec<Vec<Value>>) -> Result<CatalogReply, String> {+ Ok(CatalogReply {+ columns: columns.iter().map(|name| (*name).into()).collect(),+ rows,+ flags: ReadFlags::default(),+ })+ }++ fn table_catalog(nls: Option<&str>) -> TableCatalog {+ let mut replies = std::collections::VecDeque::from([+ ("LOGIN_OWNER", reply(&["LOGIN_OWNER"], vec![vec![json!("T")]])),+ ("FROM ALL_OBJECTS", reply(&[], vec![])),+ ]);+ if let Some(nls) = nls {+ replies.push_back(("NLS_SESSION_PARAMETERS", reply(&["VALUE"], vec![vec![json!(nls)]])));+ }+ TableCatalog { replies: std::sync::Mutex::new(replies) }+ }++ fn pending_fixture(+ sql: &str,+ ) -> (+ TransferRequest,+ crate::data::transfer::TransferStructurePreview,+ Vec<(usize, super::super::super::references::PlannedRelation)>,+ ) {+ use crate::data::transfer::{TransferStructurePreview, TransferStructurePreviewTable};+ let request = serde_json::from_value(json!({+ "transferId":"mixed", "sourceConnectionId":"S", "sourceDatabase":"tenant", "sourceSchema":"S",+ "targetConnectionId":"T", "targetDatabase":"tenant", "targetSchema":"T", "tables":["ORIGINAL"],+ "createTable":true, "batchSize":100, "objects":[{"objectType":"PACKAGE", "names":["P"]}]+ }))+ .unwrap();+ let section = format!("-- ORIGINAL -> FINAL\n{sql};");+ let structure = TransferStructurePreview { sql: section.clone(), operations: vec![], schema_objects_expanded: false,+ tables: vec![TransferStructurePreviewTable {+ source_table: "ORIGINAL".into(), target_table: "FINAL".into(), preexisting: false, sql: section,+ oracle_plan: Some(serde_json::from_value(json!({"ddl":sql,"reused_source_ddl":true,+ "deferred_fk_alters":[],"deferred_fk_names":[],+ "source_evidence":{"sourceDdl":"CREATE TABLE ORIGINAL(V VARCHAR2(20))","columns":["source_column"]}})).unwrap()),+ }],+ };+ let columns = oracle_table_contract::planned_columns(sql, "T", "FINAL").unwrap();+ (+ request,+ structure,+ vec![(+ 0,+ super::super::super::references::PlannedRelation { owner: "T".into(), name: "FINAL".into(), columns },+ )],+ )+ }++ #[tokio::test]+ async fn mixed_preview_uses_actual_prepared_sql_and_freezes_a_visible_explicit_unit() {+ let (request, mut structure, candidates) =+ pending_fixture("CREATE TABLE \"T\".FINAL(V VARCHAR2(20)) COMPRESS FOR ARCHIVE");+ let catalog = table_catalog(Some("CHAR"));+ let pending = prepare_pending_tables(+ &catalog,+ &request,+ &snapshot("T").endpoint,+ &snapshot("S").endpoint,+ &mut structure,+ &candidates,+ &std::collections::BTreeSet::from([0]),+ json!({"serverProof":"retained"}),+ )+ .await+ .unwrap();+ assert_eq!(pending.tables[0].final_ddl(), "CREATE TABLE \"T\".FINAL(V VARCHAR2(20 CHAR)) COMPRESS FOR ARCHIVE");+ assert!(structure.sql.contains("VARCHAR2(20 CHAR)"));+ assert_eq!(structure.sql, structure.tables[0].sql);+ assert_eq!(pending.dependency_manifest, json!({"serverProof":"retained"}));+ assert_eq!(pending.table_evidence[0]["sql"], structure.sql);+ assert!(catalog.replies.lock().unwrap().is_empty());+ let encoded = serde_json::to_value(pending).unwrap();+ assert_eq!(encoded["tables"][0]["sourceTable"], "ORIGINAL");+ assert_eq!(encoded["tables"][0]["sourceEvidence"]["columns"][0], "source_column");+ assert_eq!(encoded["tables"][0]["insertedUnits"][0]["semantics"], "characters");+ }++ #[tokio::test]+ async fn explicit_table_units_do_not_read_a_pool_default_or_modify_other_tables() {+ let (request, mut structure, candidates) = pending_fixture("CREATE TABLE FINAL(V VARCHAR2(20 BYTE))");+ let original = structure.sql.clone();+ let catalog = table_catalog(None);+ let pending = prepare_pending_tables(+ &catalog,+ &request,+ &snapshot("T").endpoint,+ &snapshot("S").endpoint,+ &mut structure,+ &candidates,+ &std::collections::BTreeSet::from([0]),+ json!({}),+ )+ .await+ .unwrap();+ assert_eq!(structure.sql, original);+ assert_eq!(pending.tables.len(), 1);+ assert!(catalog.replies.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn confirmed_units_are_reapplied_without_reading_a_new_pool_default() {+ let (mut request, mut structure, candidates) = pending_fixture("CREATE TABLE FINAL(V VARCHAR2(20))");+ let original = structure.clone();+ let confirmed = prepare_pending_tables(+ &table_catalog(Some("CHAR")),+ &request,+ &snapshot("T").endpoint,+ &snapshot("S").endpoint,+ &mut structure,+ &candidates,+ &std::collections::BTreeSet::from([0]),+ json!({"proof":"original"}),+ )+ .await+ .unwrap();+ request.oracle_packages =+ Some(OraclePackageTransferRequest { pending_tables: Some(confirmed.clone()), ..Default::default() });+ let mut current = original;+ let catalog = table_catalog(None);+ let regenerated = prepare_pending_tables(+ &catalog,+ &request,+ &snapshot("T").endpoint,+ &snapshot("S").endpoint,+ &mut current,+ &candidates,+ &std::collections::BTreeSet::from([0]),+ json!({"proof":"original"}),+ )+ .await+ .unwrap();+ assert_eq!(regenerated, confirmed);+ assert_eq!(current.sql, structure.sql);+ assert!(catalog.replies.lock().unwrap().is_empty());+ }++ fn pending_preview_fixture() -> OraclePackageTransferPreview {+ let (_, mut input, _) = approval_fixture();+ input.drafts.truncate(1);+ let draft = &input.drafts[0];+ let step = OracleRoutinePlanStep {+ identity: draft.identity.clone(),+ action: RoutinePlanAction::Create,+ sql: draft.sql.clone().unwrap(),+ source_original: Some("完整原文 中文😀".into()),+ target_original: None,+ recovery_sql: None,+ recovery_complete: true,+ references: vec![],+ incoming_callers: vec![],+ issues: vec![],+ operation: None,+ package_impact: None,+ };+ let pending = PendingPackageTables {+ source: input.source.endpoint.clone(),+ target: input.target.endpoint.clone(),+ tables: vec![FrozenTableDdl::from_server_plan(+ "SOURCE",+ "T",+ "FINAL",+ "CREATE TABLE FINAL(N NUMBER)",+ json!({"original":"source"}),+ None,+ )+ .unwrap()],+ dependency_manifest: json!({"steps":["frozen"]}),+ table_evidence: vec![json!({"sql":"CREATE TABLE FINAL(N NUMBER)","namespaceRows":[]})],+ };+ OraclePackageTransferPreview {+ plan: OracleRoutinePlan { target: input.target.endpoint.clone(), steps: vec![step], ready: false },+ input,+ skipped: vec![],+ pending_tables: Some(pending),+ }+ }++ #[test]+ fn pending_claim_requires_exact_endpoint_generation_source_sql_manifest_and_unapproved_plan() {+ let preview = pending_preview_fixture();+ let confirmed = preview.pending_tables.as_ref().unwrap();+ assert!(confirm_pending_preview(preview.clone(), confirmed).is_ok());+ for case in 0..7 {+ let mut current = preview.clone();+ match case {+ 0 => current.pending_tables.as_mut().unwrap().source.connection_id = "different-source".into(),+ 1 => current.pending_tables.as_mut().unwrap().target.generation += 1,+ 2 => current.pending_tables.as_mut().unwrap().dependency_manifest = json!({"steps":[]}),+ 3 => {+ current.pending_tables.as_mut().unwrap().table_evidence[0]["sql"] =+ json!("CREATE TABLE OTHER(N NUMBER)")+ }+ 4 => current.pending_tables.as_mut().unwrap().tables.clear(),+ 5 => current.plan.ready = true,+ _ => current.plan.steps[0].issues.push(dbx_sql::object_source_sql::OracleDraftIssue {+ code: "changed".into(),+ message: "source changed".into(),+ line: 3,+ column: 7,+ }),+ }+ let error = confirm_pending_preview(current, confirmed).unwrap_err();+ let retained = error.preview.unwrap();+ assert_eq!(retained.plan.steps[0].source_original.as_deref(), Some("完整原文 中文😀"), "case {case}");+ assert_eq!(retained.input.drafts[0].sql, preview.input.drafts[0].sql);+ }+ let request = OraclePackageTransferRequest {+ input: Some(preview.input.clone()),+ operation_ids: vec![],+ pending_tables: Some(confirmed.clone()),+ };+ let roundtrip: OraclePackageTransferRequest =+ serde_json::from_value(serde_json::to_value(request).unwrap()).unwrap();+ assert_eq!(roundtrip.pending_tables.as_ref(), Some(confirmed));+ }++ #[tokio::test]+ async fn pending_stage_does_not_approve_or_dispatch_after_table_failure_or_cancellation() {+ let packages =+ PackageTransfer::AwaitingTables(Box::new(pending::PendingClaim { preview: pending_preview_fixture() }));+ let directory = tempfile::tempdir().unwrap();+ let storage = crate::persistence::test_storage::open(&directory.path().join("storage.db")).await.unwrap();+ let state = AppState::new_with_plugin_dir(storage, directory.path().join("plugins"));+ let (mut request, _, _) = pending_fixture("CREATE TABLE FINAL(N NUMBER)");+ request.transfer_id = uuid::Uuid::new_v4().to_string();+ let (outcome, cancelled, error) =+ packages.run(&state, &request, false, |_| panic!("Failed tables cannot emit package approval")).await;+ assert!(!cancelled && error.is_none());+ assert!(outcome.transferred.is_empty() && outcome.failed.is_empty());+ crate::data::transfer::set_cancelled(&request.transfer_id).await;+ let (outcome, cancelled, error) =+ packages.run(&state, &request, true, |_| panic!("Cancellation cannot emit package approval")).await;+ crate::data::transfer::clear_cancelled(&request.transfer_id).await;+ assert!(cancelled && error.is_none());+ assert!(outcome.transferred.is_empty() && outcome.failed.is_empty());+ }++ #[tokio::test]+ async fn namespace_or_length_visibility_failure_preserves_the_original_table_preview() {+ for failure in ["namespace", "unit", "unknown-unit"] {+ let (request, mut structure, candidates) = pending_fixture("CREATE TABLE FINAL(V VARCHAR2(20))");+ let original = structure.sql.clone();+ let catalog = table_catalog(Some("CHAR"));+ {+ let mut replies = catalog.replies.lock().unwrap();+ match failure {+ "namespace" => replies[1].1 = Err("permission denied".into()),+ "unit" => replies[2].1 = reply(&["VALUE"], vec![vec![json!("BYTE")], vec![json!("CHAR")]]),+ _ => replies[2].1 = reply(&["VALUE"], vec![vec![json!("UNKNOWN")]]),+ }+ }+ assert!(+ prepare_pending_tables(+ &catalog,+ &request,+ &snapshot("T").endpoint,+ &snapshot("S").endpoint,+ &mut structure,+ &candidates,+ &std::collections::BTreeSet::from([0]),+ json!({})+ )+ .await+ .is_err(),+ "{failure}"+ );+ assert_eq!(structure.sql, original);+ assert_eq!(structure.tables[0].sql, original);+ }+ }++ #[test]+ fn direct_transfer_preflight_retains_editable_draft_and_structured_issues_before_claim() {+ let (registry, input, ids) = approval_fixture();+ let identity = input.drafts[1].identity.clone();+ let preview = OraclePackageTransferPreview {+ pending_tables: None,+ plan: OracleRoutinePlan {+ target: input.target.endpoint.clone(),+ ready: false,+ steps: vec![OracleRoutinePlanStep {+ identity,+ action: RoutinePlanAction::Create,+ sql: input.drafts[1].sql.clone().unwrap(),+ source_original: Some("original body 中文😀".into()),+ target_original: None,+ recovery_sql: None,+ recovery_complete: false,+ references: vec![],+ incoming_callers: vec![],+ issues: vec![dbx_sql::object_source_sql::OracleDraftIssue {+ code: "missing-reference".into(),+ message: "Missing column 中文😀".into(),+ line: 3,+ column: 7,+ }],+ operation: None,+ package_impact: None,+ }],+ },+ input,+ skipped: vec![],+ };+ let expected = serde_json::to_value(&preview).unwrap();+ let request: TransferRequest = serde_json::from_value(json!({+ "transferId":"preflight", "sourceConnectionId":"S", "sourceDatabase":"tenant", "sourceSchema":"S",+ "targetConnectionId":"T", "targetDatabase":"tenant", "targetSchema":"T", "tables":["not_written"],+ "createTable":true, "batchSize":100+ }))+ .unwrap();+ let progress = require_ready_transfer_preview(preview).unwrap_err().into_progress(&request);+ assert!(progress.terminal);+ assert!(matches!(progress.status, crate::data::transfer::TransferStatus::Error));+ assert_eq!(progress.table_index, 0);+ assert_eq!(progress.rows_transferred, 0);+ assert_eq!(serde_json::to_value(progress).unwrap()["oraclePackagePreflight"], expected);+ assert!(ids.iter().all(|id| registry+ .observe(id)+ .operation+ .is_some_and(|record| record.lifecycle == RoutineOperationLifecycle::Prepared && !record.dispatched)));+ let plain = PackageTransferPreflightError::from("old error").into_progress(&request);+ let plain = serde_json::to_value(plain).unwrap();+ assert_eq!(plain["error"], "old error");+ assert!(plain.get("oraclePackagePreflight").is_none());+ }++ fn approval_fixture() -> (RoutineOperationRegistry, OracleRoutinePlanInput, Vec<String>) {+ let source = snapshot("S");+ let target = snapshot("T");+ let selected = [db::ObjectSourceKind::Package, db::ObjectSourceKind::PackageBody]+ .into_iter()+ .map(|kind| RoutineIdentity { owner: "T".into(), name: "P".into(), kind })+ .collect::<Vec<_>>();+ let config: ConnectionConfig = serde_json::from_value(json!({"id":"T", "name":"test", "db_type":DatabaseType::OceanbaseOracle, "host":"localhost", "port":2881, "username":"T", "password":"", "database":null})).unwrap();+ let mut input = OracleRoutinePlanInput { source, target, drafts: Vec::new() };+ let mut requests = Vec::new();+ for (index, identity) in selected.iter().enumerate() {+ let sql = if index == 0 {+ "CREATE PACKAGE \"T\".\"P\" AS n NUMBER; END;"+ } else {+ "CREATE PACKAGE BODY \"T\".\"P\" AS END;"+ };+ let mut original = identity.clone();+ original.owner = "S".into();+ let object = RoutineObjectSnapshot {+ version: RoutineVersion {+ identity: original,+ object_id: "source".into(),+ status: "VALID".into(),+ last_ddl_time: "1".into(),+ },+ source: Some(sql.into()),+ source_origin: None,+ source_complete: true,+ dependencies: Vec::new(),+ dependencies_complete: true,+ issues: Vec::new(),+ };+ input.source.objects.push(object.clone());+ input.drafts.push(RoutinePlanDraft {+ identity: identity.clone(),+ action: RoutinePlanAction::Create,+ source_name: Some("P".into()),+ sql: Some(sql.into()),+ baseline_operation_id: None,+ supersedes_operation_id: None,+ package_body_source: None,+ package_contract: None,+ confirm_package_pair: false,+ });+ requests.push(super::super::super::operations::PreparedRoutineWrite {+ operation_id: format!("package-{index}"),+ supersedes: None,+ binding: RoutineWriteBinding {+ target: input.target.endpoint.clone(),+ identity: identity.clone(),+ sql: sql.into(),+ goal: RoutineReadbackGoal::Definition { sql: sql.into() },+ expected_config: config.clone(),+ require_absent: true,+ compare: Some(plan::ComparePreflight {+ source: Some(plan::SourcePreflight {+ endpoint: input.source.endpoint.clone(),+ config: config.clone(),+ expected: plan::ExpectedRoutine::Present(object),+ package_pair: None,+ }),+ target: plan::ExpectedRoutine::Absent(identity.clone()),+ proofs: Vec::new(),+ incoming: None,+ selected: selected.clone(),+ package: None,+ }),+ prerequisite_operation_ids: if index == 1 { vec!["package-0".into()] } else { Vec::new() },+ package_effect_operation_ids: Vec::new(),+ },+ });+ }+ let registry = RoutineOperationRegistry::default();+ let records = registry.prepare_batch(requests, 0).unwrap();+ let ids = records.into_iter().map(|record| record.operation_id).collect::<Vec<_>>();+ registry.update_references(&ids, &[]).unwrap();+ (registry, input, ids)+ }++ #[test]+ fn transfer_claim_consumes_original_ids_and_pins_them_across_preview_release() {+ let (registry, input, ids) = approval_fixture();+ let approved = claim_approvals(®istry, &input, &ids).unwrap();+ assert_eq!(+ approved.identities().map(|identity| identity.kind.clone()).collect::<Vec<_>>(),+ vec![db::ObjectSourceKind::Package, db::ObjectSourceKind::PackageBody]+ );+ registry.update_references(&[], &ids).unwrap();+ assert!(ids.iter().all(|id| registry.observe(id).operation.is_some()));+ drop(approved);+ assert!(ids.iter().all(|id| registry.observe(id).operation.is_none()));+ }++ #[tokio::test]+ async fn native_xugu_packages_keep_their_existing_transfer_stage_without_oracle_preflight() {+ let directory = tempfile::tempdir().unwrap();+ let storage = crate::persistence::test_storage::open(&directory.path().join("storage.db")).await.unwrap();+ let state = AppState::new_with_plugin_dir(storage, directory.path().join("plugins"));+ for id in ["xugu-source", "xugu-target"] {+ let config: ConnectionConfig = serde_json::from_value(json!({"id":id,"name":id,"db_type":"xugu","host":"localhost","port":1,"username":"fixture","password":""})).unwrap();+ state.configs.write().await.insert(id.into(), config);+ }+ let mut request: TransferRequest = serde_json::from_value(json!({+ "transferId":"xugu-native", "sourceConnectionId":"xugu-source", "sourceDatabase":"APP", "sourceSchema":"APP",+ "targetConnectionId":"xugu-target", "targetDatabase":"APP", "targetSchema":"APP", "tables":[],+ "createTable":true, "content":"structureOnly", "batchSize":100,+ "objects":[{"objectType":"PACKAGE","names":["P"]},{"objectType":"SYNONYM","names":["S"]}]+ })).unwrap();+ assert!(prepare_transfer_packages(&state, &request, None).await.unwrap().is_none());+ assert!(claim_transfer_packages(&state, &request, None).await.unwrap().is_none());+ request.objects.as_mut().unwrap().push(crate::data::transfer::TransferObjectSelection {+ object_type: TransferObjectKind::PackageBody,+ names: vec!["P".into()],+ });+ assert!(prepare_transfer_packages(&state, &request, None).await.is_err());+ assert!(claim_transfer_packages(&state, &request, None).await.is_err());+ }++ #[test]+ fn transfer_claim_rejects_changed_sql_identity_endpoint_selection_and_order() {+ let (registry, input, ids) = approval_fixture();+ for mutation in 0..6 {+ let mut changed = input.clone();+ match mutation {+ 0 => changed.drafts[0].sql = Some("CREATE PACKAGE \"T\".\"P\" AS n VARCHAR2(20); END;".into()),+ 1 => changed.source.endpoint.connection_id = "another-source".into(),+ 2 => changed.target.endpoint.generation += 1,+ 3 => changed.drafts[0].source_name = Some("Another.P".into()),+ 4 => changed.drafts[0].action = RoutinePlanAction::Replace,+ _ => {+ changed.drafts.remove(0);+ }+ }+ assert!(claim_approvals(®istry, &changed, &ids).is_err(), "mutation {mutation}");+ }+ assert!(claim_approvals(®istry, &input, &[ids[0].clone(), ids[0].clone()]).is_err());+ assert!(claim_approvals(®istry, &input, &[ids[1].clone(), ids[0].clone()]).is_err());+ assert!(claim_approvals(®istry, &input, &[]).is_err());+ assert!(claim_approvals(®istry, &input, &ids).is_ok());+ }++ #[test]+ fn transfer_claim_cannot_mix_sibling_approvals_from_different_prepared_plans() {+ let (registry, input, ids) = approval_fixture();+ let mut requests = Vec::new();+ for (index, id) in ids.iter().enumerate() {+ let mut binding = registry.binding_for_readback(id).unwrap();+ if index == 1 {+ binding.prerequisite_operation_ids = vec!["second-0".into()];+ }+ requests.push(super::super::super::operations::PreparedRoutineWrite {+ operation_id: format!("second-{index}"),+ binding,+ supersedes: None,+ });+ }+ let second = registry+ .prepare_batch(requests, 0)+ .unwrap()+ .into_iter()+ .map(|record| record.operation_id)+ .collect::<Vec<_>>();+ registry.update_references(&second, &[]).unwrap();+ assert!(claim_approvals(®istry, &input, &[ids[0].clone(), second[1].clone()]).is_err());+ assert!(claim_approvals(®istry, &input, &second).is_ok());+ }++ #[tokio::test]+ async fn shared_package_stage_preserves_skips_and_does_not_dispatch_after_failed_tables_or_cancellation() {+ let (registry, input, ids) = approval_fixture();+ let mut approved = claim_approvals(®istry, &input, &ids).unwrap();+ approved.skipped.push(RoutineIdentity {+ owner: "T".into(),+ name: "Existing.With.Dot😀".into(),+ kind: db::ObjectSourceKind::Package,+ });+ let directory = tempfile::tempdir().unwrap();+ let storage = crate::persistence::test_storage::open(&directory.path().join("storage.db")).await.unwrap();+ let state = AppState::new_with_plugin_dir(storage, directory.path().join("plugins"));+ let request: TransferRequest = serde_json::from_value(json!({+ "transferId": uuid::Uuid::new_v4().to_string(), "sourceConnectionId":"S", "sourceDatabase":"tenant", "sourceSchema":"S",+ "targetConnectionId":"T", "targetDatabase":"tenant", "targetSchema":"T", "tables":["pending_table"],+ "createTable":true, "content":"structureAndData", "objects":[{"objectType":"PACKAGE", "names":["P"]}], "batchSize":100+ })).unwrap();+ let (outcome, cancelled) = approved+ .run(&state, &request, false, |_| panic!("A failed table prerequisite must prevent all package dispatch"))+ .await;+ assert!(!cancelled);+ assert_eq!(outcome.skipped, vec!["Package:Existing.With.Dot😀"]);+ assert!(outcome.transferred.is_empty() && outcome.failed.is_empty());+ crate::data::transfer::set_cancelled(&request.transfer_id).await;+ let (outcome, cancelled) =+ approved.run(&state, &request, true, |_| panic!("Cancellation must prevent package dispatch")).await;+ crate::data::transfer::clear_cancelled(&request.transfer_id).await;+ assert!(cancelled);+ assert!(outcome.transferred.is_empty() && outcome.failed.is_empty());+ assert!(ids.iter().all(|id| registry.observe(id).operation.is_some_and(|operation| operation.lifecycle+ == RoutineOperationLifecycle::Prepared+ && !operation.dispatched)));+ }++ fn snapshot(owner: &str) -> RoutineSnapshot {+ RoutineSnapshot {+ endpoint: RoutineEndpoint {+ connection_id: owner.into(),+ database: "tenant".into(),+ schema: owner.into(),+ database_type: DatabaseType::OceanbaseOracle,+ generation: 1,+ },+ state: RoutineReadState::Complete,+ enumeration_complete: true,+ objects: Vec::new(),+ issues: Vec::new(),+ }+ }+ fn selected(kind: db::ObjectSourceKind) -> RoutineSelection {+ RoutineSelection { name: "Pkg.With.Dot😀".into(), kind }+ }+ fn existing(kind: db::ObjectSourceKind) -> RoutineObjectSnapshot {+ RoutineObjectSnapshot {+ version: RoutineVersion {+ identity: RoutineIdentity {+ owner: "Target".into(), name: "Pkg.With.Dot😀".into(), kind: kind.clone()+ },+ object_id: "1".into(),+ status: "VALID".into(),+ last_ddl_time: "1".into(),+ },+ source: Some(format!(+ "CREATE {} \"Target\".\"Pkg.With.Dot😀\" AS END \"Pkg.With.Dot😀\";",+ kind_name(&kind)+ )),+ source_origin: Some(SourceOrigin::OceanBaseDictionary),+ source_complete: true,+ dependencies: Vec::new(),+ dependencies_complete: true,+ issues: Vec::new(),+ }+ }++ #[test]+ fn explicit_transfer_selection_keeps_body_only_and_deduplicates_exact_kind_name_pairs() {+ let request: TransferRequest = serde_json::from_value(json!({"transferId":"test", "sourceConnectionId":"source", "sourceDatabase":"tenant", "sourceSchema":"Source", "targetConnectionId":"target", "targetDatabase":"tenant", "targetSchema":"Target", "tables":[], "createTable":false, "batchSize":100, "dropTargetBeforeCreate":false, "dropTargetConfirmed":false,+ "objects":[{"objectType":"PACKAGE_BODY", "names":["Pkg.With.Dot😀", "Pkg.With.Dot😀"]}]})).unwrap();+ assert_eq!(selections(&request), vec![selected(db::ObjectSourceKind::PackageBody)]);+ let (input, skipped) =+ transfer_input(snapshot("Source"), snapshot("Target"), &selections(&request), None).unwrap();+ assert!(skipped.is_empty());+ assert_eq!(input.drafts.len(), 1);+ assert_eq!(input.drafts[0].identity.kind, db::ObjectSourceKind::PackageBody);+ assert_eq!(input.drafts[0].action, RoutinePlanAction::Create);+ }++ #[test]+ fn existing_specification_is_readonly_while_a_new_body_is_planned_and_never_replaced_by_transfer() {+ let mut target = snapshot("Target");+ target.objects.push(existing(db::ObjectSourceKind::Package));+ let selected = vec![selected(db::ObjectSourceKind::Package), selected(db::ObjectSourceKind::PackageBody)];+ let (input, skipped) = transfer_input(snapshot("Source"), target.clone(), &selected, None).unwrap();+ assert_eq!(skipped, vec![target.objects[0].version.identity.clone()]);+ assert_eq!(input.target.objects[0].source, target.objects[0].source);+ assert_eq!(input.drafts.len(), 1);+ assert_eq!(input.drafts[0].identity.kind, db::ObjectSourceKind::PackageBody);+ let mut replacement = input.drafts[0].clone();+ replacement.identity.kind = db::ObjectSourceKind::Package;+ replacement.action = RoutinePlanAction::Replace;+ assert!(transfer_input(snapshot("Source"), target, &selected, Some(&[replacement])).is_err());+ }++ #[test]+ fn editable_inputs_cannot_omit_new_selected_kinds_or_add_unselected_or_duplicate_writes() {+ let selected = vec![selected(db::ObjectSourceKind::PackageBody)];+ let (input, _) = transfer_input(snapshot("Source"), snapshot("Target"), &selected, None).unwrap();+ assert!(transfer_input(snapshot("Source"), snapshot("Target"), &selected, Some(&[])).is_err());+ let draft = input.drafts[0].clone();+ assert!(transfer_input(+ snapshot("Source"),+ snapshot("Target"),+ &selected,+ Some(&[draft.clone(), draft.clone()])+ )+ .is_err());+ let mut unselected = draft.clone();+ unselected.identity.name = "Other".into();+ assert!(transfer_input(snapshot("Source"), snapshot("Target"), &selected, Some(&[unselected])).is_err());+ let (restored, _) = transfer_input(snapshot("Source"), snapshot("Target"), &selected, Some(&[draft])).unwrap();+ assert_eq!(restored.drafts.len(), 1);+ }+}diff --git a/crates/dbx-core/src/schema/oracle_routines/transfer/packages/external_types.rs b/crates/dbx-core/src/schema/oracle_routines/transfer/packages/external_types.rsnew file mode 100644index 0000000000..5d9797ea9b--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/transfer/packages/external_types.rs@@ -0,0 +1,272 @@+use super::super::super::references::{lossless_catalog_value, CatalogReadProof};+use super::*;++pub(super) fn manifest(proofs: &[CatalogReadProof]) -> Value {+ Value::Array(proofs.iter().map(|proof| match proof {+ CatalogReadProof::Query { sql, columns, rows } => serde_json::json!({+ "sql": sql, "columns": columns,+ "rows": rows.iter().map(|row| row.iter().map(lossless_catalog_value).collect::<Vec<_>>()).collect::<Vec<_>>()+ }),+ CatalogReadProof::Source { .. } => unreachable!("External table types retain only server catalog reads"),+ }).collect())+}++pub(super) async fn read(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ table: &FrozenTableDdl,+) -> Result<Vec<CatalogReadProof>, String> {+ let mut proofs = Vec::new();+ let types = table.external_types();+ for (owner, name) in &types {+ let result = read_type(catalog, endpoint, owner, name, &mut proofs).await;+ result.map_err(|error| format!("External column type {owner}.{name}: {error}"))?;+ }+ if !types.is_empty() && endpoint.database_type == DatabaseType::OceanbaseOracle {+ return Err("The target TYPE is visible, but SQL object-type columns are not verified for OceanBase Oracle (the available target rejects this CREATE TABLE form); retain the table draft and use a supported target column type. No TYPE is migrated automatically".into());+ }+ Ok(proofs)+}++async fn read_type(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ owner: &str,+ name: &str,+ proofs: &mut Vec<CatalogReadProof>,+) -> Result<(), String> {+ let namespace_sql = 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 ALL_OBJECTS 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 before = pending::observed(catalog, namespace_sql.clone(), proofs).await?;+ if before.rows.len() != 1 {+ return Err("the exact target TYPE is not uniquely visible; create or expose the required type and validate again (it is not migrated automatically)".into());+ }+ let row = &before.rows[0];+ if before.text(row, "OWNER")? != owner+ || before.text(row, "OBJECT_NAME")? != name+ || before.text(row, "OBJECT_TYPE")? != "TYPE"+ || before.text(row, "STATUS")? != "VALID"+ {+ return Err("the target namespace is not the exact VALID TYPE".into());+ }+ before.integer(row, "OBJECT_ID")?;+ before.text(row, "LAST_DDL_TIME")?;+ let definition = pending::observed(+ catalog,+ format!("SELECT * FROM ALL_TYPES WHERE OWNER = {} AND TYPE_NAME = {}", literal(owner), literal(name)),+ proofs,+ )+ .await?;+ if definition.rows.len() != 1 {+ return Err("the complete target type definition is not visible".into());+ }+ let row = &definition.rows[0];+ if definition.text(row, "OWNER")? != owner+ || definition.text(row, "TYPE_NAME")? != name+ || definition.text(row, "TYPECODE")? != "OBJECT"+ || definition.text(row, "INCOMPLETE")? != "NO"+ || definition.text(row, "INSTANTIABLE")? != "YES"+ || definition.integer(row, "METHODS")? != 0+ || !definition.cell(row, "SUPERTYPE_OWNER")?.is_null()+ || !definition.cell(row, "SUPERTYPE_NAME")?.is_null()+ {+ return Err("only complete, instantiable object types without methods or inheritance have a verified table-column contract; retain the draft for manual correction".into());+ }+ let expected = definition.integer(row, "ATTRIBUTES")?;+ if expected == 0 {+ return Err("the object type has no complete attribute list".into());+ }+ let mut count = 0u64;+ let mut names = HashSet::new();+ loop {+ let attributes = pending::observed(catalog, format!("SELECT * FROM (SELECT A.*, ROW_NUMBER() OVER (ORDER BY ATTR_NO, ATTR_NAME) RN FROM ALL_TYPE_ATTRS A WHERE OWNER = {} AND TYPE_NAME = {}) WHERE RN > {count} AND RN <= {} ORDER BY RN", literal(owner), literal(name), count + PAGE_SIZE as u64), proofs).await?;+ if attributes.rows.len() > PAGE_SIZE {+ return Err("the type attribute page is incomplete".into());+ }+ for row in &attributes.rows {+ count += 1;+ if count > expected+ || attributes.integer(row, "RN")? != count+ || attributes.integer(row, "ATTR_NO")? != count+ || attributes.text(row, "OWNER")? != owner+ || attributes.text(row, "TYPE_NAME")? != name+ || !names.insert(attributes.text(row, "ATTR_NAME")?)+ || !attributes.cell(row, "ATTR_TYPE_OWNER")?.is_null()+ || attributes.text(row, "INHERITED")? != "NO"+ || !attributes.cell(row, "ATTR_TYPE_MOD")?.is_null()+ || !matches!(+ attributes.text(row, "ATTR_TYPE_NAME")?.as_str(),+ "NUMBER"+ | "FLOAT"+ | "VARCHAR2"+ | "CHAR"+ | "NVARCHAR2"+ | "NCHAR"+ | "RAW"+ | "DATE"+ | "BINARY_FLOAT"+ | "BINARY_DOUBLE"+ | "CLOB"+ | "NCLOB"+ | "BLOB"+ )+ {+ return Err(+ "the ordered scalar type attributes are incomplete or contain an unverified nested type".into()+ );+ }+ }+ if attributes.rows.len() < PAGE_SIZE {+ break;+ }+ }+ if count != expected {+ return Err("the complete type attribute count does not match ALL_TYPES".into());+ }+ if owner != endpoint.schema {+ let grants = pending::observed(catalog, format!("SELECT GRANTEE, PRIVILEGE FROM SYS.ALL_TAB_PRIVS WHERE TABLE_SCHEMA = {} AND TABLE_NAME = {} AND GRANTEE IN ({}, 'PUBLIC') AND PRIVILEGE = 'EXECUTE' ORDER BY GRANTEE, PRIVILEGE", literal(owner), literal(name), literal(&endpoint.schema)), proofs).await?;+ if grants.rows.is_empty() {+ if owner == "SYS" {+ return Err("a direct or PUBLIC EXECUTE grant is required for a SYS type".into());+ }+ let login = pending::observed(catalog, "SELECT USER AS LOGIN_OWNER FROM DUAL".into(), proofs).await?;+ if login.rows.len() != 1 {+ return Err("the defining owner's direct system grants are unknown".into());+ }+ let from = if login.text(&login.rows[0], "LOGIN_OWNER")? == endpoint.schema {+ "USER_SYS_PRIVS WHERE PRIVILEGE = 'EXECUTE ANY TYPE'".into()+ } else {+ format!(+ "SYS.DBA_SYS_PRIVS WHERE GRANTEE = {} AND PRIVILEGE = 'EXECUTE ANY TYPE'",+ literal(&endpoint.schema)+ )+ };+ let system =+ pending::observed(catalog, format!("SELECT PRIVILEGE FROM {from} ORDER BY PRIVILEGE"), proofs).await?;+ if system.rows.is_empty() {+ return Err("a direct or PUBLIC EXECUTE grant, or direct EXECUTE ANY TYPE, is required; enabled roles and EXECUTE ANY PROCEDURE do not authorize a column TYPE".into());+ }+ }+ }+ let after = pending::observed(catalog, namespace_sql, proofs).await?;+ if before.columns != after.columns || before.rows != after.rows {+ return Err("the target type changed while its definition was read".into());+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;+ struct Catalog(std::sync::Mutex<std::collections::VecDeque<(&'static str, Value)>>);+ #[async_trait::async_trait]+ impl RoutineCatalog for Catalog {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ let (expected, value) = self.0.lock().unwrap().pop_front().expect("unexpected type query");+ assert!(sql.contains(expected), "{sql}");+ serde_json::from_value(value).map_err(|error| error.to_string())+ }+ async fn source(&self, _: &RoutineIdentity) -> Result<SourceReply, String> {+ panic!("Type verification must not invoke or fetch a user routine")+ }+ }+ fn fixture(owner: &str, direct: bool) -> (Catalog, RoutineEndpoint, FrozenTableDdl) {+ let namespace = json!({"columns":["OWNER","OBJECT_NAME","OBJECT_TYPE","OBJECT_ID","STATUS","LAST_DDL_TIME"],"rows":[[owner,"SHAPE","TYPE",9007199254740993u64,"VALID","2026-10-23T00:00:00"]]});+ let mut replies = std::collections::VecDeque::from([+ ("FROM ALL_OBJECTS", namespace.clone()),+ (+ "FROM ALL_TYPES",+ json!({"columns":["OWNER","TYPE_NAME","TYPECODE","INCOMPLETE","INSTANTIABLE","METHODS","SUPERTYPE_OWNER","SUPERTYPE_NAME","ATTRIBUTES"],"rows":[[owner,"SHAPE","OBJECT","NO","YES",0,null,null,1]]}),+ ),+ (+ "FROM ALL_TYPE_ATTRS",+ json!({"columns":["OWNER","TYPE_NAME","ATTR_NAME","ATTR_TYPE_MOD","ATTR_TYPE_OWNER","ATTR_TYPE_NAME","ATTR_NO","INHERITED","RN","LENGTH","NUMBER_PRECISION","SCALE"],"rows":[[owner,"SHAPE","N",null,null,"NUMBER",1,"NO",1,22,12,3]]}),+ ),+ ]);+ if owner != "T" {+ replies.push_back(("SYS.ALL_TAB_PRIVS", json!({"columns":["GRANTEE","PRIVILEGE"],"rows":if direct {vec![json!(["T","EXECUTE"])]} else {vec![]}})));+ if !direct && owner != "SYS" {+ replies.push_back(("LOGIN_OWNER", json!({"columns":["LOGIN_OWNER"],"rows":[["T"]]})));+ replies.push_back((+ "USER_SYS_PRIVS WHERE PRIVILEGE = 'EXECUTE ANY TYPE'",+ json!({"columns":["PRIVILEGE"],"rows":[["EXECUTE ANY TYPE"]]}),+ ));+ }+ }+ replies.push_back(("FROM ALL_OBJECTS", namespace));+ let endpoint = RoutineEndpoint {+ connection_id: "target".into(),+ database: "tenant".into(),+ schema: "T".into(),+ database_type: DatabaseType::Oracle,+ generation: 1,+ };+ let table = FrozenTableDdl::from_server_plan(+ "SOURCE",+ "T",+ "FINAL",+ &format!("CREATE TABLE FINAL (V \"{owner}\".SHAPE)"),+ json!({}),+ None,+ )+ .unwrap();+ (Catalog(std::sync::Mutex::new(replies)), endpoint, table)+ }+ #[tokio::test]+ async fn exact_owned_direct_and_any_type_grants_retain_complete_lossless_read_proofs() {+ for (owner, direct, count) in [("T", true, 4), ("EXT", true, 5), ("EXT", false, 7), ("SYS", true, 5)] {+ let (catalog, endpoint, table) = fixture(owner, direct);+ let proofs = read(&catalog, &endpoint, &table).await.unwrap();+ assert_eq!(proofs.len(), count);+ assert!(catalog.0.lock().unwrap().is_empty());+ let encoded = serde_json::to_string(&manifest(&proofs)).unwrap();+ assert!(encoded.contains("9007199254740993"));+ assert!(!encoded.contains("9007199254740992"));+ }+ }+ #[tokio::test]+ async fn visible_ob_type_does_not_prove_sql_object_column_support() {+ let (catalog, mut endpoint, table) = fixture("EXT", true);+ endpoint.database_type = DatabaseType::OceanbaseOracle;+ let error = read(&catalog, &endpoint, &table).await.err().unwrap();+ assert!(error.contains("SQL object-type columns"));+ assert!(catalog.0.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn absent_invalid_partial_nested_changed_or_unauthorized_types_block_without_writes() {+ for case in [+ "absent",+ "invalid",+ "methods",+ "incomplete",+ "nested",+ "missing",+ "order",+ "truncated",+ "concurrent",+ "sys-grant",+ "any-procedure",+ ] {+ let owner = if case == "sys-grant" { "SYS" } else { "EXT" };+ let (catalog, endpoint, table) = fixture(owner, false);+ {+ let mut replies = catalog.0.lock().unwrap();+ match case {+ "absent" => replies[0].1["rows"] = json!([]),+ "invalid" => replies[0].1["rows"][0][4] = json!("INVALID"),+ "methods" => replies[1].1["rows"][0][5] = json!(1),+ "incomplete" => replies[1].1["rows"][0][3] = json!("YES"),+ "nested" => replies[2].1["rows"][0][4] = json!("EXT"),+ "missing" => replies[2].1["rows"] = json!([]),+ "order" => replies[2].1["rows"][0][8] = json!(2),+ "truncated" => replies[2].1["truncated"] = json!(true),+ "concurrent" => replies.back_mut().unwrap().1["rows"][0][3] = json!(77),+ "any-procedure" => replies[5].1["rows"] = json!([]),+ _ => (),+ }+ }+ assert!(read(&catalog, &endpoint, &table).await.is_err(), "{case}");+ }+ }+}diff --git a/crates/dbx-core/src/schema/oracle_routines/transfer/packages/pending.rs b/crates/dbx-core/src/schema/oracle_routines/transfer/packages/pending.rsnew file mode 100644index 0000000000..00805c74b9--- /dev/null+++ b/crates/dbx-core/src/schema/oracle_routines/transfer/packages/pending.rs@@ -0,0 +1,367 @@+use super::super::super::references::{CatalogReadProof, PlannedRelation};+use super::*;+use crate::data::transfer::{TransferObjectOutcome, TransferProgress, TransferStatus};++pub(crate) enum PackageTransfer<'a> {+ Approved(ApprovedPackageTransfer<'a>),+ AwaitingTables(Box<PendingClaim>),+}++pub(crate) struct PendingClaim {+ pub(super) preview: OraclePackageTransferPreview,+}++impl PackageTransfer<'_> {+ pub(crate) async fn run<F>(+ &self,+ state: &AppState,+ request: &TransferRequest,+ prerequisites_succeeded: bool,+ mut progress: F,+ ) -> (TransferObjectOutcome, bool, Option<String>)+ where+ F: FnMut(TransferProgress),+ {+ match self {+ Self::Approved(approved) => {+ let (outcome, cancelled) = approved.run(state, request, prerequisites_succeeded, progress).await;+ (outcome, cancelled, None)+ }+ Self::AwaitingTables(pending) => {+ let outcome = TransferObjectOutcome {+ skipped: pending+ .preview+ .skipped+ .iter()+ .map(|identity| {+ format!(+ "{}:{}",+ if identity.kind == db::ObjectSourceKind::Package { "Package" } else { "PackageBody" },+ identity.name+ )+ })+ .collect(),+ ..Default::default()+ };+ if !prerequisites_succeeded {+ return (outcome, false, None);+ }+ if crate::data::transfer::is_cancelled(&request.transfer_id).await {+ return (outcome, true, None);+ }+ match pending.approve(state, request).await {+ Ok((approved, preview)) => {+ // approve() pins the whole batch before returning or emitting IDs.+ progress(TransferProgress {+ oracle_package_approval: Some(preview),+ oracle_package_preflight: None,+ oracle_routine_operation: None,+ transfer_id: request.transfer_id.clone(),+ table: "package objects".into(),+ table_index: request.tables.len(),+ total_tables: request.tables.len(),+ rows_transferred: 0,+ total_rows: None,+ status: TransferStatus::Running,+ error: None,+ terminal: false,+ });+ let (outcome, cancelled) = approved.run(state, request, true, progress).await;+ (outcome, cancelled, None)+ }+ Err(error) => {+ if crate::data::transfer::is_cancelled(&request.transfer_id).await {+ return (outcome, true, None);+ }+ let message = error.message.clone();+ let mut event = error.into_progress(request);+ event.terminal = false;+ event.table_index = request.tables.len();+ progress(event);+ (outcome, false, Some(message))+ }+ }+ }+ }+ }+}++impl PendingClaim {+ fn failure(&self, message: String) -> PackageTransferPreflightError {+ let mut preview = self.preview.clone();+ preview.plan.ready = false;+ for step in &mut preview.plan.steps {+ step.issues.push(dbx_sql::object_source_sql::OracleDraftIssue {+ code: "pending-table-readback".into(),+ message: message.clone(),+ line: 1,+ column: 1,+ });+ }+ PackageTransferPreflightError { message, preview: Some(Box::new(preview)) }+ }++ async fn approve<'a>(+ &self,+ state: &'a AppState,+ request: &TransferRequest,+ ) -> Result<(ApprovedPackageTransfer<'a>, OraclePackageTransferPreview), PackageTransferPreflightError> {+ let frozen =+ self.preview.pending_tables.as_ref().ok_or("The original pending table confirmation is unavailable")?;+ let input = &self.preview.input;+ let config =+ plan::checked_endpoint(state, &input.target.endpoint).await.map_err(|error| self.failure(error))?;+ let catalog = LiveCatalog { state, endpoint: &input.target.endpoint, config: &config };+ let mut proofs = Vec::new();+ let mut tables = Vec::new();+ for (index, table) in frozen.tables.iter().enumerate() {+ let type_proofs = external_types::read(&catalog, &input.target.endpoint, table)+ .await+ .map_err(|error| self.failure(error))?;+ if frozen.table_evidence.get(index).and_then(|value| value.get("externalTypeProofs"))+ != Some(&external_types::manifest(&type_proofs))+ {+ return Err(self.failure("External table-column type identity, shape or direct privileges changed; retain completed tables and refresh the package drafts".into()));+ }+ proofs.extend(type_proofs);+ proofs.extend(+ read_completed_table(&catalog, &input.target.endpoint, table)+ .await+ .map_err(|error| self.failure(error))?,+ );+ tables.push(PlannedRelation {+ owner: table.owner().into(),+ name: table.name().into(),+ columns: table.columns(),+ });+ }+ if crate::data::transfer::is_cancelled(&request.transfer_id).await {+ return Err(self.failure("Cancelled before package approval; no package statement was dispatched".into()));+ }+ let (plan, pins) = plan::prepare_completed_transfer(+ state,+ &request.transfer_id,+ input,+ &tables,+ &frozen.dependency_manifest,+ proofs,+ )+ .await+ .map_err(|error| self.failure(error))?;+ let preview = OraclePackageTransferPreview {+ input: input.clone(),+ plan,+ skipped: self.preview.skipped.clone(),+ pending_tables: None,+ };+ if !preview.plan.ready {+ return Err(PackageTransferPreflightError { message: "The completed table stage did not satisfy the original package preflight; retain completed tables and correct the drafts".into(), preview: Some(Box::new(preview)) });+ }+ let ids = preview+ .plan+ .steps+ .iter()+ .filter_map(|step| step.operation.as_ref().map(|operation| operation.operation_id.clone()))+ .collect::<Vec<_>>();+ let mut approved =+ claim_approvals(&state.routine_operations, input, &ids).map_err(|error| self.failure(error))?;+ approved.skipped = preview.skipped.clone();+ drop(pins);+ Ok((approved, preview))+ }+}++pub(super) async fn observed(+ catalog: &impl RoutineCatalog,+ sql: String,+ proofs: &mut Vec<CatalogReadProof>,+) -> Result<CatalogReply, String> {+ let reply = catalog.query(&sql).await?;+ reply.flags.check()?;+ proofs.push(CatalogReadProof::Query { sql, columns: reply.columns.clone(), rows: reply.rows.clone() });+ Ok(reply)+}++async fn read_completed_table(+ catalog: &impl RoutineCatalog,+ endpoint: &RoutineEndpoint,+ table: &FrozenTableDdl,+) -> Result<Vec<CatalogReadProof>, String> {+ use crate::data::transfer::oracle_table_contract::CatalogTableColumn;+ let mut proofs = Vec::new();+ let login = observed(catalog, "SELECT USER AS LOGIN_OWNER FROM DUAL".into(), &mut proofs).await?;+ if login.rows.len() != 1 {+ return Err("The completed table owner visibility is unknown".into());+ }+ let view =+ if login.text(&login.rows[0], "LOGIN_OWNER")? == endpoint.schema { "ALL_OBJECTS" } else { "SYS.DBA_OBJECTS" };+ let namespace_sql = 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','PACKAGE BODY','MATERIALIZED VIEW','TYPE','SYNONYM') ORDER BY OBJECT_ID", literal(table.owner()), literal(table.name()));+ let before = observed(catalog, namespace_sql.clone(), &mut proofs).await?;+ if before.rows.len() != 1 {+ return Err("The completed table namespace is missing or ambiguous".into());+ }+ let row = &before.rows[0];+ if before.text(row, "OWNER")? != table.owner()+ || before.text(row, "OBJECT_NAME")? != table.name()+ || before.text(row, "OBJECT_TYPE")? != "TABLE"+ || before.text(row, "STATUS")? != "VALID"+ {+ return Err("The completed dependency is not the exact VALID target table".into());+ }+ before.integer(row, "OBJECT_ID")?;+ before.text(row, "LAST_DDL_TIME")?;+ let mut columns = Vec::new();+ loop {+ let offset = columns.len();+ let sql = format!("SELECT * FROM (SELECT OWNER, TABLE_NAME, COLUMN_ID, COLUMN_NAME, DATA_TYPE, DATA_TYPE_OWNER, DATA_LENGTH, CHAR_LENGTH, CHAR_USED, DATA_PRECISION, DATA_SCALE, ROW_NUMBER() OVER (ORDER BY COLUMN_ID, COLUMN_NAME) RN FROM ALL_TAB_COLUMNS WHERE OWNER = {} AND TABLE_NAME = {}) WHERE RN > {offset} AND RN <= {} ORDER BY RN", literal(table.owner()), literal(table.name()), offset + PAGE_SIZE);+ let reply = observed(catalog, sql, &mut proofs).await?;+ if reply.rows.len() > PAGE_SIZE {+ return Err("Completed table columns exceeded the verified page size".into());+ }+ for row in &reply.rows {+ if reply.integer(row, "RN")? != columns.len() as u64 + 1+ || reply.text(row, "OWNER")? != table.owner()+ || reply.text(row, "TABLE_NAME")? != table.name()+ {+ return Err("Completed table column pagination or identity is incomplete".into());+ }+ let optional_text = |name: &str| -> Result<Option<String>, String> {+ match reply.cell(row, name)? {+ Value::Null => Ok(None),+ _ => reply.text(row, name).map(Some),+ }+ };+ let precision = optional_text("DATA_PRECISION")?+ .map(|value| value.parse::<u64>().map_err(|_| "The catalog precision is invalid"))+ .transpose()?;+ let scale = optional_text("DATA_SCALE")?+ .map(|value| value.parse::<i64>().map_err(|_| "The catalog scale is invalid"))+ .transpose()?;+ columns.push(CatalogTableColumn {+ id: reply.integer(row, "COLUMN_ID")?,+ name: reply.text(row, "COLUMN_NAME")?,+ data_type: reply.text(row, "DATA_TYPE")?,+ data_type_owner: optional_text("DATA_TYPE_OWNER")?,+ data_length: reply.integer(row, "DATA_LENGTH")?,+ char_length: reply.integer(row, "CHAR_LENGTH")?,+ char_used: optional_text("CHAR_USED")?,+ precision,+ scale,+ });+ }+ if reply.rows.len() < PAGE_SIZE {+ break;+ }+ }+ table.verify_catalog_columns(&columns)?;+ let after = observed(catalog, namespace_sql, &mut proofs).await?;+ if before.columns != after.columns || before.rows != after.rows {+ return Err("The table changed while its complete typed structure was read".into());+ }+ Ok(proofs)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ struct Catalog {+ replies: std::sync::Mutex<std::collections::VecDeque<(&'static str, Value)>>,+ }+ #[async_trait::async_trait]+ impl RoutineCatalog for Catalog {+ async fn query(&self, sql: &str) -> Result<CatalogReply, String> {+ let (expected, reply) = self.replies.lock().unwrap().pop_front().expect("Unexpected metadata read");+ assert!(sql.contains(expected), "{sql}");+ serde_json::from_value(reply).map_err(|error| error.to_string())+ }+ async fn source(&self, _: &RoutineIdentity) -> Result<SourceReply, String> {+ panic!("No package invocation/source probe is needed for typed table readback")+ }+ }++ fn fixture() -> (Catalog, RoutineEndpoint, FrozenTableDdl) {+ let namespace = json!({"columns":["OWNER","OBJECT_NAME","OBJECT_TYPE","OBJECT_ID","STATUS","LAST_DDL_TIME"],+ "rows":[["T","FINAL","TABLE",99,"VALID","2026-10-23T00:00:00"]]});+ let columns = json!({"columns":["OWNER","TABLE_NAME","COLUMN_ID","COLUMN_NAME","DATA_TYPE","DATA_TYPE_OWNER","DATA_LENGTH","CHAR_LENGTH","CHAR_USED","DATA_PRECISION","DATA_SCALE","RN"],+ "rows":[["T","FINAL",16,"V","VARCHAR2",null,80,20,"C",null,null,1],+ ["T","FINAL",17,"N","NUMBER",null,22,0,null,12,3,2]]});+ let catalog = Catalog {+ replies: std::sync::Mutex::new(std::collections::VecDeque::from([+ ("LOGIN_OWNER", json!({"columns":["LOGIN_OWNER"],"rows":[["T"]]})),+ ("FROM ALL_OBJECTS", namespace.clone()),+ ("FROM ALL_TAB_COLUMNS", columns),+ ("FROM ALL_OBJECTS", namespace),+ ])),+ };+ let endpoint = RoutineEndpoint {+ connection_id: "T".into(),+ database: "tenant".into(),+ schema: "T".into(),+ database_type: DatabaseType::OceanbaseOracle,+ generation: 1,+ };+ let table = FrozenTableDdl::from_server_plan(+ "SOURCE",+ "T",+ "FINAL",+ "CREATE TABLE FINAL(V VARCHAR2(20 CHAR), N NUMBER(12,3))",+ json!({}),+ None,+ )+ .unwrap();+ (catalog, endpoint, table)+ }++ #[tokio::test]+ async fn completed_table_retains_real_typed_proofs_with_nonconsecutive_origin_ids() {+ let (catalog, endpoint, table) = fixture();+ let proofs = read_completed_table(&catalog, &endpoint, &table).await.unwrap();+ assert_eq!(proofs.len(), 4);+ assert!(catalog.replies.lock().unwrap().is_empty());+ assert!(proofs.iter().any(|proof| matches!(proof, CatalogReadProof::Query { sql, rows, .. }+ if sql.contains("DATA_PRECISION") && rows.len() == 2)));+ }++ #[tokio::test]+ async fn completed_table_rejects_partial_wrong_changed_and_incompatible_directory_facts() {+ for case in [+ "truncated",+ "wrong-owner",+ "wrong-kind",+ "missing-column",+ "extra-column",+ "type",+ "unit",+ "order",+ "page",+ "concurrent",+ ] {+ let (catalog, endpoint, table) = fixture();+ {+ let mut replies = catalog.replies.lock().unwrap();+ match case {+ "truncated" => replies[2].1["truncated"] = json!(true),+ "wrong-owner" => replies[2].1["rows"][0][0] = json!("OTHER"),+ "wrong-kind" => replies[1].1["rows"][0][2] = json!("VIEW"),+ "missing-column" => {+ replies[2].1["rows"].as_array_mut().unwrap().pop();+ }+ "extra-column" => {+ replies[2].1["rows"]+ .as_array_mut()+ .unwrap()+ .push(json!(["T", "FINAL", 18, "EXTRA", "NUMBER", null, 22, 0, null, null, null, 3]));+ }+ "type" => replies[2].1["rows"][1][10] = json!(2),+ "unit" => replies[2].1["rows"][0][8] = json!("B"),+ "order" => replies[2].1["rows"][1][2] = json!(16),+ "page" => replies[2].1["rows"][1][11] = json!(3),+ _ => replies[3].1["rows"][0][3] = json!(100),+ }+ }+ assert!(read_completed_table(&catalog, &endpoint, &table).await.is_err(), "{case}");+ }+ }+}diff --git a/crates/dbx-core/tests/live_mysql_transfer.rs b/crates/dbx-core/tests/live_mysql_transfer.rsindex d7c6bd39c9..b0781ccb78 100644--- a/crates/dbx-core/tests/live_mysql_transfer.rs+++ b/crates/dbx-core/tests/live_mysql_transfer.rs@@ -89,6 +89,7 @@ fn transfer_request(create_table: false,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode,@@ -197,6 +198,7 @@ async fn run_live_mysql_cross_version_transfer_completes_on_small_stack() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -354,6 +356,7 @@ async fn live_mysql_transfer_keeps_columns_whose_comment_mentions_foreign_key()create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -515,6 +518,7 @@ async fn live_mysql_transfer_downgrades_unsupported_source_collations() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -581,6 +585,7 @@ async fn live_mysql_transfer_downgrades_unsupported_source_collations() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -890,6 +895,7 @@ async fn live_mysql_transfer_structure_overwrite_rejects_incompatible_target_colcreate_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Overwrite,@@ -948,6 +954,7 @@ async fn live_mysql_transfer_structure_overwrite_rejects_incompatible_target_colcreate_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Overwrite,@@ -1047,6 +1054,7 @@ async fn live_mysql_transfer_structure_only_rejects_incompatible_target_columns(create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::StructureOnly,objects: Some(Vec::new()),mode: TransferMode::Append,@@ -1148,6 +1156,7 @@ async fn live_mysql_transfer_drop_target_parent_child_foreign_key() {create_table: true,drop_target_before_create: true,drop_target_confirmed: true,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -1343,6 +1352,7 @@ async fn live_mysql_transfer_drop_target_rebuilds_incompatible_structure() {create_table: true,drop_target_before_create: true,drop_target_confirmed: true,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -1533,6 +1543,7 @@ async fn live_mysql_transfer_drop_target_rejects_external_incoming_fk() {create_table: true,drop_target_before_create: true,drop_target_confirmed: true,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -1626,6 +1637,7 @@ async fn live_mysql_transfer_drop_target_circular_foreign_keys() {create_table: true,drop_target_before_create: true,drop_target_confirmed: true,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -1857,6 +1869,7 @@ async fn live_mysql_transfer_drop_target_retains_backup_on_failure() {create_table: true,drop_target_before_create: true,drop_target_confirmed: true,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -2037,6 +2050,7 @@ async fn live_mysql_keyset_pagination_copies_every_row() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -2163,6 +2177,7 @@ async fn live_mysql_progress_read_survives_total_duration_beyond_timeout() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -2265,6 +2280,7 @@ async fn live_mysql_transfer_drop_target_inspects_dependent_views_without_the_uscreate_table: true,drop_target_before_create: true,drop_target_confirmed: true,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,diff --git a/crates/dbx-core/tests/live_oracle_transfer.rs b/crates/dbx-core/tests/live_oracle_transfer.rsindex f4e2e75513..17796bf97b 100644--- a/crates/dbx-core/tests/live_oracle_transfer.rs+++ b/crates/dbx-core/tests/live_oracle_transfer.rs@@ -107,6 +107,7 @@ async fn live_oracle_transfer_creates_table_with_index_comment_and_trigger() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::StructureAndData,objects: Some(vec![TransferObjectSelection { object_type: TransferObjectKind::Sequence, names: vec![sequence.clone()] },@@ -234,6 +235,7 @@ async fn live_oracle_transfer_places_tables_in_target_default_tablespace() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::StructureAndData,objects: None,mode: TransferMode::Append,diff --git a/crates/dbx-core/tests/live_postgres_transfer.rs b/crates/dbx-core/tests/live_postgres_transfer.rsindex d219bb13da..744eb8b30e 100644--- a/crates/dbx-core/tests/live_postgres_transfer.rs+++ b/crates/dbx-core/tests/live_postgres_transfer.rs@@ -262,6 +262,7 @@ async fn live_postgres_transfer_upserts_generated_always_identity_values() {create_table: false,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: dbx_core::transfer::TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Upsert,@@ -441,6 +442,7 @@ async fn live_postgres_structure_only_preserves_table_indexes() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: dbx_core::transfer::TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -727,6 +729,7 @@ async fn live_postgres_transfer_preserves_data_and_schema_objects() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: dbx_core::transfer::TransferContent::default(),objects: None,mode: TransferMode::Append,@@ -1031,6 +1034,7 @@ async fn live_postgres_transfer_skips_create_ddl_for_existing_target_table() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: dbx_core::transfer::TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -1157,6 +1161,7 @@ async fn live_postgres_transfer_creates_selected_sequence_before_referencing_tabcreate_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: dbx_core::transfer::TransferContent::default(),objects: Some(vec![TransferObjectSelection { object_type: TransferObjectKind::Table, names: vec!["biz_banner".to_string()] },@@ -1350,6 +1355,7 @@ async fn live_postgres_transfer_drop_target_rebuilds_structure_and_indexes() {create_table: true,drop_target_before_create: true,drop_target_confirmed: true,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -1553,6 +1559,7 @@ impl PostgresRebuildFixture {create_table: true,drop_target_before_create: true,drop_target_confirmed: true,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -1878,6 +1885,7 @@ async fn live_postgres_keyset_pagination_copies_every_row() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -1992,6 +2000,7 @@ async fn live_postgres_progress_read_survives_total_duration_beyond_timeout() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -2100,6 +2109,7 @@ async fn live_postgres_keyset_large_batch_copies_every_row() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -2214,6 +2224,7 @@ async fn live_postgres_structure_only_preview_renders_ddl_without_touching_the_tcreate_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::StructureOnly,// A selected non-table object must be disclosed as not expanded, never silently dropped.objects: Some(vec![TransferObjectSelection {diff --git a/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rs b/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rsindex 30931aaf22..47f6092765 100644--- a/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rs+++ b/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rs@@ -174,6 +174,7 @@ async fn live_sqlite_to_sqlserver_keeps_sixty_four_bit_integer_values() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,diff --git a/crates/dbx-core/tests/live_sqlserver_completion.rs b/crates/dbx-core/tests/live_sqlserver_completion.rsindex 6cb71697bf..f7d986bb72 100644--- a/crates/dbx-core/tests/live_sqlserver_completion.rs+++ b/crates/dbx-core/tests/live_sqlserver_completion.rs@@ -1421,6 +1421,7 @@ async fn live_sqlserver_transfer_table_skips_rowversion_insert_column() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: dbx_core::transfer::TransferContent::default(),objects: Some(Vec::new()),mode: dbx_core::transfer::TransferMode::Append,diff --git a/crates/dbx-core/tests/live_sqlserver_transfer.rs b/crates/dbx-core/tests/live_sqlserver_transfer.rsindex a9d73da264..5a6de0977e 100644--- a/crates/dbx-core/tests/live_sqlserver_transfer.rs+++ b/crates/dbx-core/tests/live_sqlserver_transfer.rs@@ -186,6 +186,7 @@ async fn live_sqlserver_transfer_rebuild_releases_constraint_and_index_names() {create_table: true,drop_target_before_create: true,drop_target_confirmed: true,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -349,6 +350,7 @@ async fn live_sqlserver_transfer_overwrite_handles_existing_identity_target() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Overwrite,@@ -468,6 +470,7 @@ async fn live_sqlserver_keyset_pagination_copies_every_row() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -591,6 +594,7 @@ async fn live_sqlserver_progress_read_survives_total_duration_beyond_timeout() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -712,6 +716,7 @@ async fn live_sqlserver_keyset_uniqueidentifier_datetime2_composite_key() {create_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -826,6 +831,7 @@ async fn live_sqlserver_transfer_new_identity_target_keeps_explicit_identity_valcreate_table: true,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::default(),objects: Some(Vec::new()),mode: TransferMode::Append,@@ -1072,6 +1078,7 @@ async fn live_sqlserver_transfer_overwrite_replaces_tables_linked_by_foreign_keycreate_table: false,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::DataOnly,objects: Some(Vec::new()),mode: TransferMode::Overwrite,diff --git a/crates/dbx-driver-agent/src/agent_driver.rs b/crates/dbx-driver-agent/src/agent_driver.rsindex 8f4b367d3b..8c237cd78d 100644--- a/crates/dbx-driver-agent/src/agent_driver.rs+++ b/crates/dbx-driver-agent/src/agent_driver.rs@@ -2417,6 +2417,22 @@ impl AgentDriverClient {.await}+ pub async fn get_object_source_with_origin<T: DeserializeOwned + Send + 'static, K: Serialize>(+ &mut self,+ database: &str,+ schema: &str,+ name: &str,+ object_type: &K,+ signature: Option<&str>,+ relation_name: Option<&str>,+ timeout_duration: Option<Duration>,+ ) -> Result<T, String> {+ let mut params =+ agent_object_source_params_with_identity(database, schema, name, object_type, signature, relation_name);+ params["include_source_origin"] = serde_json::json!(true);+ self.call_method_with_timeout(AgentMethod::GetObjectSource, params, timeout_duration).await+ }+pub async fn get_columns<T: DeserializeOwned + Send + 'static>(&mut self,database: &str,diff --git a/crates/dbx-sql-core/src/object_source_sql.rs b/crates/dbx-sql-core/src/object_source_sql.rsindex 45e046f82b..081645e3e6 100644--- a/crates/dbx-sql-core/src/object_source_sql.rs+++ b/crates/dbx-sql-core/src/object_source_sql.rs@@ -10,8 +10,9 @@ 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,+ analyze_oracle_package_body_draft, analyze_oracle_routine_draft, comparable_oracle_routine_definition,+ prepare_oracle_routine_definition, validate_oracle_routine_target_definition, OracleDraftIssue, OracleDraftName,+ OracleDraftPackageCall, OracleDraftPackageMember, OracleDraftPackageMemberKind, OracleDraftParameter,OracleDraftQuery, OracleDraftReference, OracleDraftReferenceRole, OracleRoutineDefinitionInput,OracleRoutineDraftAnalysis,};@@ -628,9 +629,15 @@ pub fn validate_oracle_executable_object_source(input: OracleObjectSourceValidatpub fn fingerprint_oracle_routine_object_source(input: EditableObjectSourceSqlInput) -> Result<String, String> {if !matches!(input.database_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle)- || !matches!(input.object_type, ObjectSourceKind::Procedure | ObjectSourceKind::Function)+ || !matches!(+ input.object_type,+ ObjectSourceKind::Procedure+ | ObjectSourceKind::Function+ | ObjectSourceKind::Package+ | ObjectSourceKind::PackageBody+ ){- return Err("Routine source fingerprinting is supported only for Oracle procedures and functions.".into());+ return Err("Routine source fingerprinting is supported only for Oracle routines and packages.".into());}validate_oracle_object_source(input.database_type,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.rsindex c874327841..a2e5b70de8 100644--- a/crates/dbx-sql-core/src/object_source_sql/oracle_routines.rs+++ b/crates/dbx-sql-core/src/object_source_sql/oracle_routines.rs@@ -2,8 +2,9 @@ use super::*;mod analysis;pub use analysis::{- analyze_oracle_routine_draft, OracleDraftIssue, OracleDraftName, OracleDraftParameter, OracleDraftQuery,- OracleDraftReference, OracleDraftReferenceRole, OracleRoutineDraftAnalysis,+ analyze_oracle_package_body_draft, analyze_oracle_routine_draft, OracleDraftIssue, OracleDraftName,+ OracleDraftPackageCall, OracleDraftPackageMember, OracleDraftPackageMemberKind, OracleDraftParameter,+ OracleDraftQuery, OracleDraftReference, OracleDraftReferenceRole, OracleRoutineDraftAnalysis,};#[derive(Debug, Clone, Serialize, Deserialize)]@@ -22,8 +23,14 @@ 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());+ if !matches!(+ input.object_type,+ ObjectSourceKind::Procedure+ | ObjectSourceKind::Function+ | ObjectSourceKind::Package+ | ObjectSourceKind::PackageBody+ ) {+ return Err("The approved statement must define one routine or package".into());}validate_oracle_executable_object_source(OracleObjectSourceValidationInput {database_type: input.database_type,@@ -54,9 +61,15 @@ pub fn validate_oracle_routine_target_definition(/// 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)+ || !matches!(+ input.object_type,+ ObjectSourceKind::Procedure+ | ObjectSourceKind::Function+ | ObjectSourceKind::Package+ | ObjectSourceKind::PackageBody+ ){- return Err("Oracle routine adaptation requires a standalone procedure or function".into());+ return Err("Oracle routine adaptation requires a procedure, function or package".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());@@ -95,11 +108,13 @@ pub fn prepare_oracle_routine_definition(input: OracleRoutineDefinitionInput) ->}) {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());+ for keyword in object_type_keyword(&input.object_type).split_whitespace() {+ if !token_at(position).is_some_and(|token| token_unquoted_word_is(token, keyword)) {+ return Err("Routine declaration kind must use its exact unquoted keywords".into());+ }+ edits.push((significant[position].span, keyword.to_string()));+ position += 1;}- 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)));@@ -292,4 +307,54 @@ BEGIN RETURN q'[Source.Owner.Mixed.Func text]'; END;assert!(check(create.strip_prefix("CREATE ").unwrap(), None).is_err());assert!(check(&create.replacen("CREATE", "CREATE OR REPLACE", 1), None).is_ok());}++ #[test]+ fn package_body_adaptation_preserves_the_complete_static_business_body() {+ let source = include_str!("../../tests/fixtures/oracle_package_flow_body.sql");+ let mut definition = input(source);+ definition.object_type = ObjectSourceKind::PackageBody;+ definition.name = "PKG_FLOW".into();+ let sql = prepare_oracle_routine_definition(definition).unwrap();+ assert!(sql.contains("PACKAGE BODY \"Target.Owner\".\"PKG_FLOW\" AS"));+ assert_eq!(sql[sql.find('\n').unwrap()..].trim_end(), source[source.find('\n').unwrap()..].trim_end());+ }++ #[test]+ fn package_specification_comparison_preserves_literals_and_kind() {+ let mut source = input("CREATE PACKAGE \"Source.Owner\".\"Mixed.Func\" AS label CONSTANT VARCHAR2(50) := q'[Source.Owner 中文😀]'; END \"Mixed.Func\";");+ source.object_type = ObjectSourceKind::Package;+ let mut target = source.clone();+ target.source_owner = "Target.Owner".into();+ target.source = target.source.replacen("\"Source.Owner\".", "\"Target.Owner\".", 1);+ assert_eq!(+ comparable_oracle_routine_definition(source.clone()).unwrap(),+ comparable_oracle_routine_definition(target.clone()).unwrap()+ );+ target.source = target.source.replace("中文😀", "changed");+ assert_ne!(+ comparable_oracle_routine_definition(source).unwrap(),+ comparable_oracle_routine_definition(target).unwrap()+ );+ }++ #[test]+ fn package_target_validation_rejects_wrong_kind_and_additional_statements() {+ let source = "CREATE PACKAGE \"Target.Owner\".\"Mixed.Func\" AS n NUMBER; END \"Mixed.Func\";";+ let check = |source: &str, kind| {+ validate_oracle_routine_target_definition(+ EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: kind,+ schema: Some("Target.Owner".into()),+ name: "Mixed.Func".into(),+ source: source.into(),+ },+ Some(false),+ )+ };+ assert!(check(source, ObjectSourceKind::Package).is_ok());+ assert!(check(source, ObjectSourceKind::PackageBody).is_err());+ assert!(check(source.strip_prefix("CREATE ").unwrap(), ObjectSourceKind::Package).is_err());+ assert!(check(&format!("{source}\nBEGIN NULL; END;"), ObjectSourceKind::Package).is_err());+ }}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.rsindex 7bb4444dbe..2dbf9d2cb6 100644--- 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.rs@@ -9,6 +9,8 @@ use sqlparser::parser::Parser;use sqlparser::tokenizer::{Location, TokenWithSpan};use std::collections::BTreeMap;+mod package;+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]#[serde(rename_all = "camelCase")]pub struct OracleDraftName {@@ -23,6 +25,42 @@ pub struct OracleDraftParameter {pub mode: String,pub data_type: String,pub has_default: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub default_expression: Option<String>,+}++#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+pub enum OracleDraftPackageMemberKind {+ Variable,+ Constant,+ Exception,+ Procedure,+ Function,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleDraftPackageMember {+ pub name: OracleDraftName,+ pub kind: OracleDraftPackageMemberKind,+ pub parameters: Vec<OracleDraftParameter>,+ pub return_type: Option<String>,+ pub data_type: Option<String>,+ pub default_expression: Option<String>,+ pub public: bool,+ pub defined: bool,+ pub line: u64,+ pub column: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct OracleDraftPackageCall {+ pub caller: Option<OracleDraftName>,+ pub callee: OracleDraftName,+ pub line: u64,+ pub column: u64,}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]@@ -32,6 +70,7 @@ pub enum OracleDraftReferenceRole {Value,Function,Procedure,+ Exception,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -42,6 +81,10 @@ pub struct OracleDraftReference {pub argument_writable: Vec<bool>,pub query: Option<usize>,pub local_binding: Option<bool>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub package_binding: Option<OracleDraftPackageMemberKind>,+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub out_of_scope_binding: bool,pub line: u64,pub column: u64,}@@ -70,6 +113,12 @@ pub struct OracleRoutineDraftAnalysis {pub references: Vec<OracleDraftReference>,pub queries: Vec<OracleDraftQuery>,pub issues: Vec<OracleDraftIssue>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub package_members: Vec<OracleDraftPackageMember>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub package_calls: Vec<OracleDraftPackageCall>,+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub has_package_initialization: bool,}fn canonical(ident: &Ident) -> String {@@ -97,6 +146,7 @@ struct Analysis<'a> {bindings: BTreeMap<String, bool>,output: OracleRoutineDraftAnalysis,issue_position: Option<Location>,+ package_context: Option<package::PackageContext>,}impl Analysis<'_> {@@ -256,26 +306,49 @@ impl Analysis<'_> {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();+ self.check_package_lexical_reference(parts, &role, query)?;+ let mut local = self.bindings.get(&canonical(&parts[0])).copied();+ let mut package_binding = None;+ if query.is_some() && role == OracleDraftReferenceRole::Value && self.package_local_exception(parts) {+ package_binding = Some(OracleDraftPackageMemberKind::Exception);+ local = None;+ }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());}+ if local.is_none() && package_binding.is_none() {+ match self.package_reference(parts, &role, &arguments, query)? {+ package::PackageReference::Closed => return Ok(()),+ package::PackageReference::SqlValue(kind) => package_binding = Some(kind),+ package::PackageReference::External => {}+ }+ }self.output.references.push(OracleDraftReference {parts: parts.iter().map(name).collect(),role,argument_writable: arguments,query,local_binding: local,+ package_binding,+ out_of_scope_binding: query.is_some()+ && local.is_none()+ && package_binding.is_none()+ && self.package_exited_binding(parts),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))+ if let Expr::Identifier(ident) = expr {+ if let Some(writable) = self.bindings.get(&canonical(ident)) {+ return *writable;+ }+ }+ self.package_writable(expr)}fn call(&mut self,@@ -329,6 +402,7 @@ impl Analysis<'_> {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) if self.package_context.is_some() && ident.quote_style.is_none() && matches!(canonical(ident).as_str(), "TRUE" | "FALSE") => 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),@@ -345,6 +419,12 @@ impl Analysis<'_> {Ok(())}fn parse(&mut self) -> Result<(), String> {+ if self.input.object_type == ObjectSourceKind::Package {+ return package::parse_specification(self);+ }+ if self.input.object_type == ObjectSourceKind::PackageBody {+ return Err("Package body analysis requires its complete final specification".into());+ }self.expect_word("CREATE")?;if self.consume_word("OR") {self.expect_word("REPLACE")?;@@ -381,6 +461,7 @@ impl Analysis<'_> {mode: mode.into(),data_type,has_default,+ default_expression: None,});if self.consume(Token::RParen) {break;@@ -467,14 +548,20 @@ impl Analysis<'_> {return Ok(());}if is_word(0, "RETURN") {+ if self.package_context.as_ref().is_some_and(|context| context.current_kind().is_none()) {+ return Err("Package initialization cannot RETURN a member result".into());+ }+ let procedure = self+ .package_context+ .as_ref()+ .and_then(|context| context.current_kind())+ .map_or(self.input.object_type == ObjectSourceKind::Procedure, |kind| {+ kind == OracleDraftPackageMemberKind::Procedure+ });if tokens.len() == 1 {- return if self.input.object_type == ObjectSourceKind::Procedure {- Ok(())- } else {- Err("A scalar function RETURN needs an expression".into())- };+ return if procedure { Ok(()) } else { Err("A scalar function RETURN needs an expression".into()) };}- if self.input.object_type != ObjectSourceKind::Function {+ if procedure || (self.package_context.is_none() && self.input.object_type != ObjectSourceKind::Function) {return Err("A procedure RETURN cannot return a value".into());}self.expression(tokens[1..].to_vec(), None)?;@@ -511,12 +598,24 @@ impl Analysis<'_> {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) {+ if !self.writable(&Expr::Identifier(ident)) {return Err("Assignment target is not a writable local scalar".into());}self.expression(tokens[2..].to_vec(), None)?;return Ok(());}+ if self.package_context.is_some() {+ if let Some(assignment) = tokens.iter().position(|token| token.token == Token::Assignment) {+ let mut parser =+ Parser::new(&OracleDialect {}).with_tokens_with_locations(tokens[..assignment].to_vec());+ let target = parser.parse_expr().map_err(|error| error.to_string())?;+ if parser.peek_token_ref().token != Token::EOF || !self.writable(&target) {+ return Err("Assignment target is not a writable scalar in this package scope".into());+ }+ self.expression(tokens[assignment + 1..].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 {@@ -568,7 +667,7 @@ impl Analysis<'_> {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) {+ if !self.writable(&Expr::Identifier(ident)) {return Err("INTO target is not a writable local scalar".into());}count += 1;@@ -676,6 +775,43 @@ impl Analysis<'_> {}pub fn analyze_oracle_routine_draft(input: EditableObjectSourceSqlInput) -> OracleRoutineDraftAnalysis {+ analyze_draft(input, None)+}++pub fn analyze_oracle_package_body_draft(+ input: EditableObjectSourceSqlInput,+ specification: EditableObjectSourceSqlInput,+) -> OracleRoutineDraftAnalysis {+ if input.object_type != ObjectSourceKind::PackageBody+ || specification.object_type != ObjectSourceKind::Package+ || input.database_type != specification.database_type+ || input.schema != specification.schema+ || input.name != specification.name+ {+ return OracleRoutineDraftAnalysis {+ issues: vec![OracleDraftIssue {+ code: "manual-static-correction".into(),+ message: "The body requires its exact final specification identity and product".into(),+ line: 1,+ column: 1,+ }],+ ..Default::default()+ };+ }+ let contract = analyze_oracle_routine_draft(specification);+ if !contract.complete {+ return contract;+ }+ let has_package_initialization = contract.has_package_initialization;+ let mut analysis = analyze_draft(input, Some(contract.package_members));+ analysis.has_package_initialization |= has_package_initialization;+ analysis+}++fn analyze_draft(+ input: EditableObjectSourceSqlInput,+ contract: Option<Vec<OracleDraftPackageMember>>,+) -> OracleRoutineDraftAnalysis {let mut analysis = Analysis {input: &input,tokens: Vec::new(),@@ -683,6 +819,7 @@ pub fn analyze_oracle_routine_draft(input: EditableObjectSourceSqlInput) -> Oracbindings: BTreeMap::new(),output: OracleRoutineDraftAnalysis::default(),issue_position: None,+ package_context: None,};let parsed: Result<(), String> = (|| {validate_oracle_routine_target_definition(input.clone(), None)?;@@ -692,7 +829,11 @@ pub fn analyze_oracle_routine_draft(input: EditableObjectSourceSqlInput) -> Orac.into_iter().filter(|token| !matches!(token.token, Token::Whitespace(_) | Token::EOF)).collect();- analysis.parse()+ if let Some(contract) = contract {+ package::parse_body(&mut analysis, contract)+ } else {+ analysis.parse()+ }})();match parsed {Ok(()) => analysis.output.complete = true,diff --git a/crates/dbx-sql-core/src/object_source_sql/oracle_routines/analysis/package.rs b/crates/dbx-sql-core/src/object_source_sql/oracle_routines/analysis/package.rsnew file mode 100644index 0000000000..822151ab3f--- /dev/null+++ b/crates/dbx-sql-core/src/object_source_sql/oracle_routines/analysis/package.rs@@ -0,0 +1,853 @@+use super::*;+use std::collections::BTreeSet;++pub(super) struct PackageContext {+ owner: Option<String>,+ name: String,+ members: BTreeMap<String, OracleDraftPackageMember>,+ available_values: Option<BTreeSet<String>>,+ current_member: Option<OracleDraftName>,+ local_exceptions: BTreeSet<String>,+ exited_bindings: BTreeSet<String>,+}++pub(super) enum PackageReference {+ External,+ Closed,+ SqlValue(OracleDraftPackageMemberKind),+}++struct DeferredExpression {+ tokens: Vec<TokenWithSpan>,+ bindings: BTreeMap<String, bool>,+ values: BTreeSet<String>,+ caller: Option<OracleDraftName>,+}++impl PackageContext {+ pub(super) fn current_kind(&self) -> Option<OracleDraftPackageMemberKind> {+ self.current_member.as_ref().and_then(|member| self.members.get(&member.value)).map(|member| member.kind)+ }+ fn member<'a>(&'a self, parts: &[Ident]) -> Result<Option<&'a OracleDraftPackageMember>, String> {+ let qualified = match parts {+ [_] => false,+ [package, _] if canonical(package) == self.name => true,+ [owner, package, _]+ if self.owner.as_deref() == Some(canonical(owner).as_str()) && canonical(package) == self.name =>+ {+ true+ }+ _ => return Ok(None),+ };+ let key = canonical(parts.last().ok_or("A package member identity is required")?);+ let member = self.members.get(&key);+ if qualified && member.is_none() {+ return Err(format!("Package member {key} is not declared in the final package draft"));+ }+ Ok(member)+ }+}++pub(super) fn parse_body(analysis: &mut Analysis<'_>, contract: Vec<OracleDraftPackageMember>) -> Result<(), String> {+ let public = contract.iter().cloned().map(|member| (member.name.value.clone(), member)).collect::<BTreeMap<_, _>>();+ analysis.package_context = Some(PackageContext {+ owner: analysis.input.schema.clone(),+ name: analysis.input.name.clone(),+ members: public.clone(),+ available_values: None,+ current_member: None,+ local_exceptions: BTreeSet::new(),+ exited_bindings: BTreeSet::new(),+ });+ body_pass(analysis, &public)?;+ let collected = analysis.package_context.as_ref().expect("body scope was collected").members.clone();+ analysis.pos = 0;+ analysis.bindings.clear();+ analysis.output = OracleRoutineDraftAnalysis::default();+ analysis.package_context = Some(PackageContext {+ owner: analysis.input.schema.clone(),+ name: analysis.input.name.clone(),+ members: collected,+ available_values: None,+ current_member: None,+ local_exceptions: BTreeSet::new(),+ exited_bindings: BTreeSet::new(),+ });+ body_pass(analysis, &public)?;+ analysis.output.package_members =+ analysis.package_context.as_ref().expect("body scope was checked").members.values().cloned().collect();+ Ok(())+}++fn matching_signature(implementation: &OracleDraftPackageMember, contract: &OracleDraftPackageMember) -> bool {+ implementation.kind == contract.kind+ && implementation.return_type == contract.return_type+ && implementation.parameters.len() == contract.parameters.len()+ && implementation.parameters.iter().zip(&contract.parameters).all(|(body, spec)| {+ body.name.value == spec.name.value+ && body.mode == spec.mode+ && body.data_type == spec.data_type+ && body.default_expression.as_ref().is_none_or(|value| spec.default_expression.as_ref() == Some(value))+ })+}++fn body_pass(analysis: &mut Analysis<'_>, public: &BTreeMap<String, OracleDraftPackageMember>) -> Result<(), String> {+ analysis.expect_word("CREATE")?;+ if analysis.consume_word("OR") {+ analysis.expect_word("REPLACE")?;+ }+ if analysis.word("EDITIONABLE") || analysis.word("NONEDITIONABLE") {+ return Err("Package edition options require verified target edition identity and capabilities; retain or explicitly revise this target draft".into());+ }+ analysis.expect_word("PACKAGE")?;+ analysis.expect_word("BODY")?;+ analysis.parts()?;+ if !analysis.consume_word("AS") && !analysis.consume_word("IS") {+ return Err("Expected the package body AS or IS declaration".into());+ }+ let mut declared = BTreeSet::new();+ while !analysis.word("END") && !analysis.word("BEGIN") {+ let kind = if analysis.consume_word("FUNCTION") {+ Some(OracleDraftPackageMemberKind::Function)+ } else if analysis.consume_word("PROCEDURE") {+ Some(OracleDraftPackageMemberKind::Procedure)+ } else {+ None+ };+ if kind.is_none() && ["TYPE", "SUBTYPE", "CURSOR", "PRAGMA"].iter().any(|word| analysis.word(word)) {+ return Err("Package TYPE, cursor and pragma declarations require manual correction".into());+ }+ let ident = analysis.ident()?;+ let key = canonical(&ident);+ if !declared.insert(key.clone()) {+ return Err("Package overloads and duplicate body declarations are not supported".into());+ }+ if let Some(kind) = kind {+ let mut defaults = Vec::new();+ let mut member = OracleDraftPackageMember {+ name: name(&ident),+ kind,+ parameters: parameters(analysis, &BTreeSet::new(), &name(&ident), &mut defaults)?,+ return_type: None,+ data_type: None,+ default_expression: None,+ public: public.contains_key(&key),+ defined: true,+ line: ident.span.start.line,+ column: ident.span.start.column,+ };+ if kind == OracleDraftPackageMemberKind::Function {+ analysis.expect_word("RETURN")?;+ member.return_type = Some(analysis.scalar_type()?);+ }+ if let Some(contract) = public.get(&key) {+ if !matching_signature(&member, contract) {+ return Err(format!(+ "Package member {key} does not match its final specification signature or defaults"+ ));+ }+ member.parameters = contract.parameters.clone();+ }+ analysis.package_context.as_mut().expect("body context exists").members.insert(key.clone(), member.clone());+ analysis.package_context.as_mut().expect("body context exists").current_member = Some(member.name.clone());+ if !analysis.consume_word("IS") && !analysis.consume_word("AS") {+ return Err("A package member needs a complete implementation, not a forward declaration".into());+ }+ analysis.bindings = member+ .parameters+ .iter()+ .map(|parameter| (parameter.name.value.clone(), parameter.mode != "IN"))+ .collect();+ for expression in defaults {+ let bindings = std::mem::replace(&mut analysis.bindings, expression.bindings);+ analysis.expression(expression.tokens, None)?;+ analysis.bindings = bindings;+ }+ scalar_declarations(analysis, false)?;+ analysis.expect_word("BEGIN")?;+ block_contents(analysis, 0, false)?;+ analysis.expect_word("END")?;+ if !analysis.consume(Token::SemiColon) {+ if canonical(&analysis.ident()?) != key {+ return Err("Package member END name does not match its declaration".into());+ }+ analysis.expect(Token::SemiColon)?;+ }+ analysis.bindings.clear();+ analysis.package_context.as_mut().expect("body context exists").local_exceptions.clear();+ analysis.package_context.as_mut().expect("body context exists").exited_bindings.clear();+ analysis.package_context.as_mut().expect("body context exists").current_member = None;+ } else {+ if public.contains_key(&key) {+ return Err(format!("Package body redeclares public member {key}"));+ }+ let mut member = OracleDraftPackageMember {+ name: name(&ident),+ kind: OracleDraftPackageMemberKind::Variable,+ parameters: Vec::new(),+ return_type: None,+ data_type: None,+ default_expression: None,+ public: false,+ defined: true,+ line: ident.span.start.line,+ column: ident.span.start.column,+ };+ if analysis.consume_word("EXCEPTION") {+ member.kind = OracleDraftPackageMemberKind::Exception;+ } else {+ let constant = analysis.consume_word("CONSTANT");+ if constant {+ member.kind = OracleDraftPackageMemberKind::Constant;+ }+ member.data_type = Some(analysis.scalar_type()?);+ if analysis.consume_word("NOT") {+ analysis.expect_word("NULL")?;+ }+ if analysis.consume(Token::Assignment) || analysis.consume_word("DEFAULT") {+ let tokens = analysis.expression_tokens_until(&[Token::SemiColon])?;+ member.default_expression = Some(expression_key(&tokens));+ analysis.output.has_package_initialization = true;+ analysis.expression(tokens, None)?;+ } else if constant {+ return Err("Package constants require a complete initializer".into());+ }+ }+ analysis.expect(Token::SemiColon)?;+ analysis.package_context.as_mut().expect("body context exists").members.insert(key, member);+ }+ }+ if analysis.consume_word("BEGIN") {+ analysis.output.has_package_initialization = true;+ block_contents(analysis, 0, false)?;+ }+ analysis.expect_word("END")?;+ if !analysis.consume(Token::SemiColon) {+ if canonical(&analysis.ident()?) != analysis.input.name {+ return Err("The package body END name does not match its identity".into());+ }+ analysis.expect(Token::SemiColon)?;+ }+ if analysis.pos != analysis.tokens.len() {+ return Err("Extra package body statements or trailing syntax are not approved".into());+ }+ for member in public.values().filter(|member| !member.defined) {+ if !declared.contains(&member.name.value) {+ return Err(format!("Public package member {} has no body implementation", member.name.value));+ }+ }+ Ok(())+}++fn scalar_declarations(analysis: &mut Analysis<'_>, shadow: bool) -> Result<(), String> {+ let mut declared: BTreeSet<_> = if shadow { BTreeSet::new() } else { analysis.bindings.keys().cloned().collect() };+ while !analysis.word("BEGIN") {+ if ["FUNCTION", "PROCEDURE", "TYPE", "SUBTYPE", "CURSOR", "PRAGMA"].iter().any(|word| analysis.word(word)) {+ return Err("Nested routines, TYPE, cursor and pragma declarations require manual correction".into());+ }+ let ident = analysis.ident()?;+ let key = canonical(&ident);+ if !declared.insert(key.clone()) {+ return Err("Duplicate local declaration in the same package member or block".into());+ }+ if analysis.consume_word("EXCEPTION") {+ analysis.expect(Token::SemiColon)?;+ analysis.bindings.insert(key.clone(), false);+ analysis.package_context.as_mut().expect("package scope exists").local_exceptions.insert(key);+ continue;+ }+ let constant = analysis.consume_word("CONSTANT");+ analysis.scalar_type()?;+ if analysis.consume_word("NOT") {+ analysis.expect_word("NULL")?;+ }+ if analysis.consume(Token::Assignment) || analysis.consume_word("DEFAULT") {+ let tokens = analysis.expression_tokens_until(&[Token::SemiColon])?;+ analysis.expression(tokens, None)?;+ } else if constant {+ return Err("A scalar constant requires an initializer".into());+ }+ analysis.expect(Token::SemiColon)?;+ analysis.package_context.as_mut().expect("package scope exists").local_exceptions.remove(&key);+ analysis.bindings.insert(key, !constant);+ }+ Ok(())+}++fn statements(analysis: &mut Analysis<'_>, stops: &[&str], loops: usize, handler: bool) -> Result<(), String> {+ let start = analysis.pos;+ while !stops.iter().any(|stop| analysis.word(stop)) {+ let position = analysis.current().map(|token| token.span.start);+ if analysis.consume_word("IF") {+ condition_until(analysis, "THEN")?;+ statements(analysis, &["ELSIF", "ELSE", "END"], loops, handler)?;+ while analysis.consume_word("ELSIF") {+ condition_until(analysis, "THEN")?;+ statements(analysis, &["ELSIF", "ELSE", "END"], loops, handler)?;+ }+ if analysis.consume_word("ELSE") {+ statements(analysis, &["END"], loops, handler)?;+ }+ analysis.expect_word("END")?;+ analysis.expect_word("IF")?;+ analysis.expect(Token::SemiColon)?;+ continue;+ }+ if analysis.word("LOOP") || analysis.word("WHILE") || analysis.word("FOR") {+ let mut old_index = None;+ let mut index_name = None;+ let mut old_exception = false;+ if analysis.consume_word("WHILE") {+ condition_until(analysis, "LOOP")?;+ } else if analysis.consume_word("FOR") {+ let index = analysis.ident()?;+ analysis.expect_word("IN")?;+ let _ = analysis.consume_word("REVERSE");+ let bounds = tokens_until_word(analysis, "LOOP")?;+ let (lower, upper) = range_bounds(bounds)?;+ analysis.expression(lower, None)?;+ analysis.expression(upper, None)?;+ analysis.expect_word("LOOP")?;+ let key = canonical(&index);+ old_index = analysis.bindings.insert(key.clone(), false);+ old_exception =+ analysis.package_context.as_mut().expect("package context exists").local_exceptions.remove(&key);+ index_name = Some(key);+ } else {+ analysis.expect_word("LOOP")?;+ }+ statements(analysis, &["END"], loops + 1, handler)?;+ analysis.expect_word("END")?;+ analysis.expect_word("LOOP")?;+ analysis.expect(Token::SemiColon)?;+ if let Some(key) = index_name {+ if let Some(value) = old_index {+ analysis.bindings.insert(key.clone(), value);+ } else {+ analysis.bindings.remove(&key);+ analysis+ .package_context+ .as_mut()+ .expect("package context exists")+ .exited_bindings+ .insert(key.clone());+ }+ if old_exception {+ analysis.package_context.as_mut().expect("package context exists").local_exceptions.insert(key);+ }+ }+ continue;+ }+ if analysis.consume_word("EXIT") || analysis.consume_word("CONTINUE") {+ if loops == 0 {+ return Err("EXIT and CONTINUE require a surrounding loop".into());+ }+ if analysis.consume_word("WHEN") {+ let tokens = analysis.expression_tokens_until(&[Token::SemiColon])?;+ analysis.expression(tokens, None)?;+ }+ analysis.expect(Token::SemiColon)?;+ continue;+ }+ if analysis.word("DECLARE") || analysis.word("BEGIN") {+ let saved_bindings = analysis.bindings.clone();+ let saved_exceptions =+ analysis.package_context.as_ref().expect("package context exists").local_exceptions.clone();+ if analysis.consume_word("DECLARE") {+ scalar_declarations(analysis, true)?;+ }+ analysis.expect_word("BEGIN")?;+ block_contents(analysis, loops, handler)?;+ analysis.expect_word("END")?;+ analysis.expect(Token::SemiColon)?;+ let exited =+ analysis.bindings.keys().filter(|key| !saved_bindings.contains_key(*key)).cloned().collect::<Vec<_>>();+ analysis.package_context.as_mut().expect("package context exists").exited_bindings.extend(exited);+ analysis.bindings = saved_bindings;+ analysis.package_context.as_mut().expect("package context exists").local_exceptions = saved_exceptions;+ continue;+ }+ if analysis.consume_word("RAISE") {+ if !analysis.current().is_some_and(|token| token.token == Token::SemiColon) {+ let parts = analysis.parts()?;+ exception_reference(analysis, &parts)?;+ } else if !handler {+ return Err("Bare RAISE is valid only inside an exception handler".into());+ }+ analysis.expect(Token::SemiColon)?;+ continue;+ }+ let tokens = analysis.expression_tokens_until(&[Token::SemiColon])?;+ analysis.expect(Token::SemiColon)?;+ if let Err(error) = analysis.statement(tokens) {+ analysis.issue_position = analysis.issue_position.or(position);+ return Err(error);+ }+ }+ if analysis.pos == start {+ return Err("A package block or control-flow branch requires at least one statement".into());+ }+ Ok(())+}++fn tokens_until_word(analysis: &mut Analysis<'_>, word: &str) -> Result<Vec<TokenWithSpan>, String> {+ let start = analysis.pos;+ let mut depth = 0isize;+ while let Some(token) = analysis.current() {+ if depth == 0 && analysis.word(word) {+ break;+ }+ match token.token {+ Token::LParen => depth += 1,+ Token::RParen => depth -= 1,+ Token::SemiColon if depth == 0 => break,+ _ => {}+ }+ if depth < 0 {+ return Err("Unmatched closing parenthesis in package control flow".into());+ }+ analysis.pos += 1;+ }+ if depth != 0 || analysis.pos == start || !analysis.word(word) {+ return Err(format!("A complete expression followed by {word} is required"));+ }+ Ok(analysis.tokens[start..analysis.pos].to_vec())+}++fn condition_until(analysis: &mut Analysis<'_>, word: &str) -> Result<(), String> {+ let tokens = tokens_until_word(analysis, word)?;+ analysis.expression(tokens, None)?;+ analysis.expect_word(word)+}++fn range_bounds(mut tokens: Vec<TokenWithSpan>) -> Result<(Vec<TokenWithSpan>, Vec<TokenWithSpan>), String> {+ for index in 0..tokens.len().saturating_sub(1) {+ let left = tokens[index].token.to_string();+ let right = tokens[index + 1].token.to_string();+ let left_dot = tokens[index].token == Token::Period+ || matches!(&tokens[index].token, Token::Number(value, _) if value.ends_with('.'));+ let right_dot = tokens[index + 1].token == Token::Period+ || matches!(&tokens[index + 1].token, Token::Number(value, _) if value.starts_with('.'));+ if !left_dot || !right_dot {+ continue;+ }+ let mut upper = tokens.split_off(index + 2);+ let right_token = tokens.pop().expect("range right delimiter exists");+ let left_token = tokens.pop().expect("range left delimiter exists");+ if left != "." {+ let mut token = left_token;+ token.token = Token::Number(left[..left.len() - 1].into(), false);+ token.span.end.column -= 1;+ tokens.push(token);+ }+ if right != "." {+ let mut token = right_token;+ token.token = Token::Number(right[1..].into(), false);+ token.span.start.column += 1;+ upper.insert(0, token);+ }+ if tokens.is_empty() || upper.is_empty() {+ break;+ }+ return Ok((tokens, upper));+ }+ Err("A numeric FOR requires complete lower..upper bounds; cursor loops require manual correction".into())+}++fn exception_reference(analysis: &mut Analysis<'_>, parts: &[Ident]) -> Result<(), String> {+ let context = analysis.package_context.as_ref().expect("package context exists");+ if let [ident] = parts {+ let key = canonical(ident);+ if context.local_exceptions.contains(&key) {+ return Ok(());+ }+ if analysis.bindings.contains_key(&key) {+ return Err(format!("Scalar {key} is not an exception"));+ }+ if ident.quote_style.is_none()+ && [+ "ACCESS_INTO_NULL",+ "CASE_NOT_FOUND",+ "COLLECTION_IS_NULL",+ "CURSOR_ALREADY_OPEN",+ "DUP_VAL_ON_INDEX",+ "INVALID_CURSOR",+ "INVALID_NUMBER",+ "LOGIN_DENIED",+ "NO_DATA_FOUND",+ "NOT_LOGGED_ON",+ "PROGRAM_ERROR",+ "ROWTYPE_MISMATCH",+ "SELF_IS_NULL",+ "STORAGE_ERROR",+ "SUBSCRIPT_BEYOND_COUNT",+ "SUBSCRIPT_OUTSIDE_LIMIT",+ "SYS_INVALID_ROWID",+ "TIMEOUT_ON_RESOURCE",+ "TOO_MANY_ROWS",+ "VALUE_ERROR",+ "ZERO_DIVIDE",+ ]+ .contains(&key.as_str())+ {+ return Ok(());+ }+ }+ if context.member(parts)?.is_some_and(|member| member.kind == OracleDraftPackageMemberKind::Exception) {+ return Ok(());+ }+ if parts.len() >= 2 {+ return analysis.reference(parts, OracleDraftReferenceRole::Exception, Vec::new(), None);+ }+ Err("The exception name is not bound in the final package or lexical scope".into())+}++fn block_contents(analysis: &mut Analysis<'_>, loops: usize, handler: bool) -> Result<(), String> {+ statements(analysis, &["EXCEPTION", "END"], loops, handler)?;+ if analysis.consume_word("EXCEPTION") {+ let mut others = false;+ analysis.expect_word("WHEN")?;+ loop {+ if others {+ return Err("WHEN OTHERS must be the final exception handler".into());+ }+ if analysis.consume_word("OTHERS") {+ others = true;+ } else {+ loop {+ let parts = analysis.parts()?;+ exception_reference(analysis, &parts)?;+ if !analysis.consume_word("OR") {+ break;+ }+ }+ }+ analysis.expect_word("THEN")?;+ statements(analysis, &["WHEN", "END"], loops, true)?;+ if !analysis.consume_word("WHEN") {+ break;+ }+ }+ }+ Ok(())+}++impl Analysis<'_> {+ pub(super) fn check_package_lexical_reference(+ &self,+ parts: &[Ident],+ role: &OracleDraftReferenceRole,+ query: Option<usize>,+ ) -> Result<(), String> {+ let Some(context) = &self.package_context else {+ return Ok(());+ };+ if query.is_some() && *role == OracleDraftReferenceRole::Value {+ return Ok(());+ }+ let key = canonical(&parts[0]);+ if context.local_exceptions.contains(&key) && *role != OracleDraftReferenceRole::Exception {+ return Err(format!("Exception {key} cannot be used as a scalar value or call qualifier"));+ }+ if parts.len() == 1+ && !self.bindings.contains_key(&key)+ && !context.members.contains_key(&key)+ && context.exited_bindings.contains(&key)+ {+ return Err(format!(+ "Local binding {key} is outside its lexical block or loop; qualify an intended external reference"+ ));+ }+ Ok(())+ }++ pub(super) fn package_local_exception(&self, parts: &[Ident]) -> bool {+ parts.len() == 1+ && self+ .package_context+ .as_ref()+ .is_some_and(|context| context.local_exceptions.contains(&canonical(&parts[0])))+ }++ pub(super) fn package_exited_binding(&self, parts: &[Ident]) -> bool {+ parts.len() == 1+ && self+ .package_context+ .as_ref()+ .is_some_and(|context| context.exited_bindings.contains(&canonical(&parts[0])))+ }+ pub(super) fn package_reference(+ &mut self,+ parts: &[Ident],+ role: &OracleDraftReferenceRole,+ arguments: &[bool],+ query: Option<usize>,+ ) -> Result<PackageReference, String> {+ if *role == OracleDraftReferenceRole::Relation {+ return Ok(PackageReference::External);+ }+ if parts.len() > 1+ && query+ .and_then(|query| self.output.queries.get(query))+ .and_then(|query| query.alias.as_ref())+ .is_some_and(|alias| alias.value == canonical(&parts[0]))+ {+ return Ok(PackageReference::External);+ }+ let Some(context) = &self.package_context else { return Ok(PackageReference::External) };+ let Some(member) = context.member(parts)? else { return Ok(PackageReference::External) };+ if matches!(+ member.kind,+ OracleDraftPackageMemberKind::Variable+ | OracleDraftPackageMemberKind::Constant+ | OracleDraftPackageMemberKind::Exception+ ) && context.available_values.as_ref().is_some_and(|values| !values.contains(&member.name.value))+ {+ return Err(format!("Package value {} is used before its declaration", member.name.value));+ }+ if query.is_some() && *role == OracleDraftReferenceRole::Value {+ return Ok(PackageReference::SqlValue(member.kind));+ }+ match member.kind {+ OracleDraftPackageMemberKind::Exception if *role == OracleDraftReferenceRole::Exception => {+ return Ok(PackageReference::Closed)+ }+ OracleDraftPackageMemberKind::Variable | OracleDraftPackageMemberKind::Constant+ if *role == OracleDraftReferenceRole::Value =>+ {+ return Ok(PackageReference::Closed)+ }+ OracleDraftPackageMemberKind::Function+ if matches!(role, OracleDraftReferenceRole::Function | OracleDraftReferenceRole::Value) => {}+ OracleDraftPackageMemberKind::Procedure if *role == OracleDraftReferenceRole::Procedure => {}+ _ => return Err(format!("Package member {} has an incompatible scalar or call role", member.name.value)),+ }+ if arguments.len() > member.parameters.len()+ || member.parameters[arguments.len()..].iter().any(|parameter| !parameter.has_default)+ {+ return Err(format!("Package member {} arguments do not match its final declaration", member.name.value));+ }+ if member.parameters.iter().zip(arguments).any(|(parameter, writable)| parameter.mode != "IN" && !writable) {+ return Err(format!("Package member {} OUT arguments require writable scalar targets", member.name.value));+ }+ self.output.package_calls.push(OracleDraftPackageCall {+ caller: context.current_member.clone(),+ callee: member.name.clone(),+ line: parts[0].span.start.line,+ column: parts[0].span.start.column,+ });+ Ok(PackageReference::Closed)+ }++ pub(super) fn package_writable(&self, expr: &Expr) -> bool {+ let parts = match expr {+ Expr::Identifier(ident) => std::slice::from_ref(ident),+ Expr::CompoundIdentifier(parts) => parts,+ _ => return false,+ };+ if parts.first().is_some_and(|ident| self.bindings.contains_key(&canonical(ident))) {+ return false;+ }+ self.package_context+ .as_ref()+ .and_then(|context| context.member(parts).ok().flatten())+ .is_some_and(|member| member.kind == OracleDraftPackageMemberKind::Variable)+ }+}++fn expression_key(tokens: &[TokenWithSpan]) -> String {+ tokens+ .iter()+ .map(|token| match &token.token {+ Token::Word(word) if word.quote_style.is_none() => word.value.to_uppercase(),+ _ => token.token.to_string(),+ })+ .collect::<Vec<_>>()+ .join(" ")+}++fn parameters(+ analysis: &mut Analysis<'_>,+ values: &BTreeSet<String>,+ caller: &OracleDraftName,+ deferred: &mut Vec<DeferredExpression>,+) -> Result<Vec<OracleDraftParameter>, String> {+ let mut parameters = Vec::new();+ let mut bindings = BTreeMap::new();+ if !analysis.consume(Token::LParen) || analysis.consume(Token::RParen) {+ return Ok(parameters);+ }+ loop {+ let ident = analysis.ident()?;+ if bindings.contains_key(&canonical(&ident)) {+ return Err("Duplicate package parameter names are not supported".into());+ }+ let mode = if analysis.consume_word("IN") {+ if analysis.consume_word("OUT") {+ "IN OUT"+ } else {+ "IN"+ }+ } else if analysis.consume_word("OUT") {+ "OUT"+ } else {+ "IN"+ };+ let data_type = analysis.scalar_type()?;+ let has_default = analysis.consume_word("DEFAULT") || analysis.consume(Token::Assignment);+ let default_expression = if has_default {+ if mode != "IN" {+ return Err("Only IN parameters can have package defaults".into());+ }+ let tokens = analysis.expression_tokens_until(&[Token::Comma, Token::RParen])?;+ let expression = expression_key(&tokens);+ deferred.push(DeferredExpression {+ tokens,+ bindings: bindings.clone(),+ values: values.clone(),+ caller: Some(caller.clone()),+ });+ Some(expression)+ } else {+ None+ };+ bindings.insert(canonical(&ident), mode != "IN");+ parameters.push(OracleDraftParameter {+ name: name(&ident),+ mode: mode.into(),+ data_type,+ has_default,+ default_expression,+ });+ if analysis.consume(Token::RParen) {+ return Ok(parameters);+ }+ analysis.expect(Token::Comma)?;+ }+}++pub(super) fn parse_specification(analysis: &mut Analysis<'_>) -> Result<(), String> {+ analysis.expect_word("CREATE")?;+ if analysis.consume_word("OR") {+ analysis.expect_word("REPLACE")?;+ }+ if analysis.word("EDITIONABLE") || analysis.word("NONEDITIONABLE") {+ return Err("Package edition options require verified target edition identity and capabilities; retain or explicitly revise this target draft".into());+ }+ analysis.expect_word("PACKAGE")?;+ let declaration = analysis.parts()?;+ let owner = analysis.input.schema.clone().or_else(|| (declaration.len() == 2).then(|| canonical(&declaration[0])));+ if analysis.consume_word("AUTHID") {+ analysis.expect_word("DEFINER")?;+ }+ if !analysis.consume_word("AS") && !analysis.consume_word("IS") {+ return Err("Package headers support only the static AUTHID DEFINER form; retain and revise this draft".into());+ }+ let mut members = Vec::new();+ let mut names = BTreeSet::new();+ let mut values = BTreeSet::new();+ let mut deferred = Vec::new();+ while !analysis.word("END") {+ if analysis.current().is_none() {+ return Err("The package specification needs a complete END".into());+ }+ let method = if analysis.consume_word("FUNCTION") {+ Some(OracleDraftPackageMemberKind::Function)+ } else if analysis.consume_word("PROCEDURE") {+ Some(OracleDraftPackageMemberKind::Procedure)+ } else {+ None+ };+ if method.is_none()+ && ["TYPE", "SUBTYPE", "CURSOR", "PRAGMA", "BEGIN"].iter().any(|keyword| analysis.word(keyword))+ {+ return Err(+ "Package TYPE, cursors, pragmas and additional declaration forms require manual correction".into()+ );+ }+ let ident = analysis.ident()?;+ let member_name = name(&ident);+ if !names.insert(member_name.value.clone()) {+ return Err("Package overloads or duplicate declarations are not supported by this automatic plan".into());+ }+ let mut member = OracleDraftPackageMember {+ name: member_name.clone(),+ kind: OracleDraftPackageMemberKind::Variable,+ parameters: Vec::new(),+ return_type: None,+ data_type: None,+ default_expression: None,+ public: true,+ defined: true,+ line: ident.span.start.line,+ column: ident.span.start.column,+ };+ if let Some(kind) = method {+ member.kind = kind;+ member.defined = false;+ member.parameters = parameters(analysis, &values, &member_name, &mut deferred)?;+ if kind == OracleDraftPackageMemberKind::Function {+ analysis.expect_word("RETURN")?;+ member.return_type = Some(analysis.scalar_type()?);+ }+ } else if analysis.consume_word("EXCEPTION") {+ member.kind = OracleDraftPackageMemberKind::Exception;+ values.insert(member_name.value.clone());+ } else {+ let constant = analysis.consume_word("CONSTANT");+ if constant {+ member.kind = OracleDraftPackageMemberKind::Constant;+ }+ member.data_type = Some(analysis.scalar_type()?);+ if analysis.consume_word("NOT") {+ analysis.expect_word("NULL")?;+ }+ if analysis.consume(Token::Assignment) || analysis.consume_word("DEFAULT") {+ let tokens = analysis.expression_tokens_until(&[Token::SemiColon])?;+ member.default_expression = Some(expression_key(&tokens));+ analysis.output.has_package_initialization = true;+ deferred.push(DeferredExpression {+ tokens,+ bindings: BTreeMap::new(),+ values: values.clone(),+ caller: None,+ });+ } else if constant {+ return Err("Package constants require a complete initializer".into());+ }+ values.insert(member_name.value.clone());+ }+ analysis.expect(Token::SemiColon)?;+ members.push(member);+ }+ analysis.expect_word("END")?;+ if !analysis.current().is_some_and(|token| token.token == Token::SemiColon) {+ let end = analysis.ident()?;+ if canonical(&end) != analysis.input.name {+ return Err("The package END name does not match its exact identity".into());+ }+ }+ analysis.expect(Token::SemiColon)?;+ if analysis.pos != analysis.tokens.len() {+ return Err("Extra package statements or trailing syntax are not approved".into());+ }+ analysis.package_context = Some(PackageContext {+ owner,+ name: analysis.input.name.clone(),+ members: members.iter().cloned().map(|member| (member.name.value.clone(), member)).collect(),+ available_values: None,+ current_member: None,+ local_exceptions: BTreeSet::new(),+ exited_bindings: BTreeSet::new(),+ });+ analysis.output.package_members = members;+ for expression in deferred {+ analysis.bindings = expression.bindings;+ let context = analysis.package_context.as_mut().expect("package declaration was collected");+ context.available_values = Some(expression.values);+ context.current_member = expression.caller;+ analysis.expression(expression.tokens, None)?;+ }+ analysis.bindings.clear();+ Ok(())+}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.rsindex 3dffbafb44..8ccf13af20 100644--- 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.rs@@ -19,6 +19,284 @@ fn function(source: &str) -> OracleRoutineDraftAnalysis {})}+#[test]+fn a_package_specification_reports_public_scalar_exception_and_non_overloaded_signatures() {+ let result = analyze_oracle_routine_draft(EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle, object_type: ObjectSourceKind::Package,+ schema: Some("OWNER".into()), name: "P".into(),+ source: "CREATE PACKAGE \"OWNER\".P AUTHID DEFINER AS g NUMBER := 1; e EXCEPTION; FUNCTION f(p NUMBER DEFAULT 2) RETURN NUMBER; PROCEDURE step(p IN OUT NUMBER); END P;".into(),+ });+ assert!(result.complete, "{:?}", result.issues);+ let value = serde_json::to_value(&result).unwrap();+ assert_eq!(value["packageMembers"].as_array().unwrap().len(), 4);+ assert_eq!(value["packageMembers"][2]["parameters"][0]["name"]["value"], "P");+ assert_eq!(value["packageMembers"][2]["parameters"][0]["defaultExpression"], "2");+ assert_eq!(value["packageMembers"][3]["parameters"][0]["mode"], "IN OUT");+ assert_eq!(value["hasPackageInitialization"], true);+ assert!(result.references.is_empty());+}++#[test]+fn package_default_expressions_keep_internal_calls_out_of_schema_dependencies() {+ let result = analyze_oracle_routine_draft(EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: ObjectSourceKind::Package,+ schema: Some("OWNER".into()),+ name: "P".into(),+ source:+ "CREATE PACKAGE \"OWNER\".P AS FUNCTION seed RETURN NUMBER; g NUMBER := seed + OWNER.external_seed(); END P;"+ .into(),+ });+ assert!(result.complete, "{:?}", result.issues);+ assert_eq!(result.references.len(), 1);+ assert_eq!(result.references[0].parts.last().unwrap().value, "EXTERNAL_SEED");+ assert_eq!(serde_json::to_value(&result).unwrap()["packageCalls"][0]["callee"]["value"], "SEED");+}++#[test]+fn package_edition_attributes_require_target_evidence_without_changing_standalone_routine_analysis() {+ for option in ["EDITIONABLE", "NONEDITIONABLE"] {+ let specification = EditableObjectSourceSqlInput {+ database_type: DatabaseType::Oracle,+ object_type: ObjectSourceKind::Package,+ schema: Some("OWNER".into()),+ name: "P".into(),+ source: "CREATE PACKAGE \"OWNER\".P AS g NUMBER := 1; END P;".into(),+ };+ let spec_source = format!("CREATE {option} PACKAGE \"OWNER\".P AS g NUMBER := 1; END P;");+ let spec = analyze_oracle_routine_draft(EditableObjectSourceSqlInput {+ source: spec_source.clone(),+ ..specification.clone()+ });+ let body_source = format!("CREATE {option} PACKAGE BODY \"OWNER\".P AS END P;");+ let body = analyze_oracle_package_body_draft(+ EditableObjectSourceSqlInput {+ object_type: ObjectSourceKind::PackageBody,+ source: body_source.clone(),+ ..specification.clone()+ },+ specification,+ );+ for (result, source) in [(spec, spec_source), (body, body_source)] {+ assert!(!result.complete);+ let issue = result+ .issues+ .iter()+ .find(|issue| issue.message.contains("edition identity and capabilities"))+ .unwrap_or_else(|| panic!("{source}: {:?}", result.issues));+ assert_eq!(issue.line, 1);+ assert_eq!(issue.column, source.find(option).unwrap() as u64 + 1);+ }+ assert!(+ function(&format!("CREATE {option} FUNCTION \"OWNER\".F RETURN NUMBER AS BEGIN RETURN 1; END;")).complete+ );+ }+}++#[test]+fn body_analysis_requires_its_final_specification_instead_of_guessing_package_bindings() {+ let result = analyze_oracle_routine_draft(EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: ObjectSourceKind::PackageBody,+ schema: Some("OWNER".into()),+ name: "P".into(),+ source: "CREATE PACKAGE BODY \"OWNER\".P AS FUNCTION f RETURN NUMBER IS BEGIN RETURN g; END; END P;".into(),+ });+ assert!(!result.complete);+ assert!(result.issues.iter().any(|issue| issue.message.contains("final specification")));+}++#[test]+fn package_body_binds_public_contract_and_private_forward_calls_without_schema_dependencies() {+ let specification = EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: ObjectSourceKind::Package,+ schema: Some("APP".into()),+ name: "P".into(),+ source: "CREATE PACKAGE APP.P AS g NUMBER := 1; FUNCTION f(p NUMBER DEFAULT 2) RETURN NUMBER; END P;".into(),+ };+ let body = EditableObjectSourceSqlInput {+ object_type: ObjectSourceKind::PackageBody,+ source: "CREATE PACKAGE BODY APP.P AS FUNCTION f(p NUMBER) RETURN NUMBER IS BEGIN RETURN helper(p) + g; END f; FUNCTION helper(x NUMBER) RETURN NUMBER IS BEGIN RETURN x; END helper; END P;".into(),+ ..specification.clone()+ };+ let result = analyze_oracle_package_body_draft(body.clone(), specification.clone());+ assert!(result.complete, "{:?}", result.issues);+ assert!(result.references.is_empty());+ assert_eq!(result.package_calls.len(), 1);+ assert_eq!(result.package_calls[0].callee.value, "HELPER");+ let public = result.package_members.iter().find(|member| member.name.value == "F").unwrap();+ assert!(public.parameters[0].has_default);+ assert!(public.defined && public.public);+ for (from, to) in [+ ("f(p NUMBER)", "f(x NUMBER)"),+ ("f(p NUMBER)", "f(p NUMBER DEFAULT 3)"),+ ("RETURN NUMBER IS", "RETURN VARCHAR2 IS"),+ ] {+ let invalid = EditableObjectSourceSqlInput { source: body.source.replacen(from, to, 1), ..body.clone() };+ assert!(!analyze_oracle_package_body_draft(invalid, specification.clone()).complete);+ }+}++#[test]+fn preserved_package_flow_body_is_fully_analyzed_with_its_final_specification() {+ let spec = EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: ObjectSourceKind::Package,+ schema: Some("APP".into()),+ name: "PKG_FLOW".into(),+ source: "CREATE PACKAGE PKG_FLOW AS g_bias NUMBER := 1; FUNCTION score(p NUMBER) RETURN NUMBER; END PKG_FLOW;"+ .into(),+ };+ let body = EditableObjectSourceSqlInput {+ object_type: ObjectSourceKind::PackageBody,+ source: include_str!("../../../../tests/fixtures/oracle_package_flow_body.sql").into(),+ ..spec.clone()+ };+ let result = analyze_oracle_package_body_draft(body, spec);+ assert!(result.complete, "{:?}", result.issues);+ assert!(result.references.is_empty(), "{:?}", result.references);+ assert_eq!(+ result.package_calls.iter().map(|call| call.line).collect::<Vec<_>>(),+ vec![9, 13, 17, 20, 21, 23, 24, 26, 28]+ );+ assert!(result.package_calls.iter().all(|call| call.callee.value == "STEP"));+}++fn package_procedure(body: &str) -> OracleRoutineDraftAnalysis {+ let specification = EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: ObjectSourceKind::Package,+ schema: Some("APP".into()),+ name: "P".into(),+ source: "CREATE PACKAGE APP.P AS PROCEDURE run; END P;".into(),+ };+ analyze_oracle_package_body_draft(+ EditableObjectSourceSqlInput {+ object_type: ObjectSourceKind::PackageBody,+ source: format!(+ "CREATE PACKAGE BODY APP.P AS PROCEDURE run IS n NUMBER; e EXCEPTION; BEGIN {body} END run; END P;"+ ),+ ..specification.clone()+ },+ specification,+ )+}++#[test]+fn package_control_flow_visits_every_condition_bound_branch_and_handler_without_evaluation() {+ let result = package_procedure("IF APP.a() > 0 AND NOT (n IS NULL) THEN NULL; ELSIF APP.b() = 0 THEN NULL; ELSE n := APP.c(); END IF; FOR i IN REVERSE APP.lo()..APP.hi() LOOP CONTINUE WHEN APP.skip() = i; END LOOP; WHILE APP.more() > 0 LOOP EXIT WHEN APP.stop() = 1; END LOOP; IF FALSE THEN n := APP.unreachable(); END IF; DECLARE n NUMBER := APP.initial(); e EXCEPTION; BEGIN n := APP.inner(); EXCEPTION WHEN e OR VALUE_ERROR THEN n := APP.handler(); WHEN OTHERS THEN RAISE; END; n := APP.restored(); EXCEPTION WHEN e THEN n := APP.outer_handler();");+ assert!(result.complete, "{:?}", result.issues);+ assert_eq!(+ result.references.iter().map(|reference| reference.parts.last().unwrap().value.as_str()).collect::<Vec<_>>(),+ vec![+ "A",+ "B",+ "C",+ "LO",+ "HI",+ "SKIP",+ "MORE",+ "STOP",+ "UNREACHABLE",+ "INITIAL",+ "INNER",+ "HANDLER",+ "RESTORED",+ "OUTER_HANDLER"+ ]+ );+}++#[test]+fn package_control_flow_rejects_incomplete_scopes_jumps_and_hidden_dynamic_sql() {+ for body in [+ "IF TRUE THEN NULL; END;",+ "LOOP NULL; END;",+ "EXIT;",+ "CONTINUE WHEN TRUE;",+ "RAISE;",+ "RAISE missing;",+ "RAISE n;",+ "IF TRUE THEN END IF;",+ "FOR i IN (SELECT n FROM t) LOOP NULL; END LOOP;",+ "FOR i IN 1..3 LOOP i := 2; END LOOP;",+ "NULL; EXCEPTION WHEN OTHERS THEN NULL; WHEN VALUE_ERROR THEN NULL;",+ "NULL; EXCEPTION WHEN e THEN EXECUTE IMMEDIATE 'SELECT 1';",+ ] {+ let result = package_procedure(body);+ assert!(!result.complete, "accepted: {body}");+ assert!(result.issues[0].line > 0 && result.issues[0].column > 0);+ }+}++#[test]+fn package_initialization_is_analyzed_but_cannot_return_a_member_result() {+ let spec = EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: ObjectSourceKind::Package,+ schema: Some("APP".into()),+ name: "P".into(),+ source: "CREATE PACKAGE APP.P AS g NUMBER; END P;".into(),+ };+ let body = EditableObjectSourceSqlInput {+ object_type: ObjectSourceKind::PackageBody,+ source: "CREATE PACKAGE BODY APP.P AS BEGIN g := APP.seed(); END P;".into(),+ ..spec.clone()+ };+ let result = analyze_oracle_package_body_draft(body.clone(), spec.clone());+ assert!(result.complete, "{:?}", result.issues);+ assert!(result.has_package_initialization);+ assert_eq!(result.references[0].parts.last().unwrap().value, "SEED");+ let invalid = EditableObjectSourceSqlInput { source: body.source.replace("g := APP.seed()", "RETURN 1"), ..body };+ assert!(!analyze_oracle_package_body_draft(invalid, spec).complete);+}++#[test]+fn package_lexical_values_and_exceptions_restore_outer_bindings_and_reject_escaped_names() {+ let result = package_procedure("DECLARE e NUMBER; BEGIN e := 1; END; RAISE e;");+ assert!(result.complete, "{:?}", result.issues);+ for body in [+ "FOR i IN 1..3 LOOP NULL; END LOOP; n := i;",+ "DECLARE v NUMBER; BEGIN NULL; END; n := v;",+ "n := e;",+ "FOR e IN 1..3 LOOP RAISE e; END LOOP;",+ ] {+ let result = package_procedure(body);+ assert!(!result.complete, "accepted invalid lexical binding: {body}");+ }+}++#[test]+fn package_self_qualified_assignment_and_external_exception_keep_exact_binding_roles() {+ let specification = EditableObjectSourceSqlInput {+ database_type: DatabaseType::OceanbaseOracle,+ object_type: ObjectSourceKind::Package,+ schema: Some("APP".into()),+ name: "P".into(),+ source: "CREATE PACKAGE APP.P AS g NUMBER; PROCEDURE run; END P;".into(),+ };+ let body = EditableObjectSourceSqlInput { object_type: ObjectSourceKind::PackageBody,+ source: "CREATE PACKAGE BODY APP.P AS PROCEDURE run IS BEGIN P.g := APP.seed(); APP.P.g := g; EXCEPTION WHEN APP.OTHER.bad THEN RAISE APP.OTHER.bad; END run; END P;".into(), ..specification.clone() };+ let result = analyze_oracle_package_body_draft(body, specification);+ assert!(result.complete, "{:?}", result.issues);+ let roles =+ result.references.iter().map(|reference| serde_json::to_value(&reference.role).unwrap()).collect::<Vec<_>>();+ assert_eq!(+ roles,+ vec![serde_json::json!("function"), serde_json::json!("exception"), serde_json::json!("exception")]+ );+}++#[test]+fn package_sql_column_candidates_keep_exception_and_expired_local_evidence_for_target_binding() {+ let result = package_procedure("DECLARE retired NUMBER; BEGIN NULL; END; SELECT retired,e INTO n,n FROM APP.t;");+ assert!(result.complete, "{:?}", result.issues);+ let references = serde_json::to_value(&result.references).unwrap();+ assert_eq!(references[1]["outOfScopeBinding"], true);+ assert_eq!(references[2]["packageBinding"], "exception");+}+#[test]fn constant_and_unicode_comment_bodies_are_fully_consumed_without_changing_the_source() {let comment = "-- 原文🙂 Source.Owner.f; EXECUTE IMMEDIATE\n".repeat(140);diff --git a/crates/dbx-sql-core/tests/fixtures/oracle_package_flow_body.sql b/crates/dbx-sql-core/tests/fixtures/oracle_package_flow_body.sqlnew file mode 100644index 0000000000..7b0a2a6d5c--- /dev/null+++ b/crates/dbx-sql-core/tests/fixtures/oracle_package_flow_body.sql@@ -0,0 +1,31 @@+CREATE OR REPLACE PACKAGE BODY PKG_FLOW AS+ FUNCTION step(x NUMBER) RETURN NUMBER IS+ BEGIN RETURN x + g_bias; END step;+ FUNCTION score(p NUMBER) RETURN NUMBER IS+ total NUMBER := 0;+ e_negative EXCEPTION;+ BEGIN+ IF p < 0 THEN RAISE e_negative;+ ELSIF p = 0 THEN RETURN step(0);+ ELSE+ FOR i IN 1..3 LOOP+ IF i = 2 THEN CONTINUE; END IF;+ total := total + step(i);+ END LOOP;+ END IF;+ WHILE total < 10 LOOP+ total := step(total);+ EXIT WHEN total >= 10;+ END LOOP;+ LOOP EXIT WHEN total >= 12; total := step(total); END LOOP;+ DECLARE total NUMBER := step(1);+ BEGIN+ IF total > 0 THEN total := step(total); END IF;+ EXCEPTION WHEN VALUE_ERROR THEN total := step(0);+ END;+ RETURN step(total);+ EXCEPTION+ WHEN e_negative THEN RETURN step(-p);+ WHEN OTHERS THEN RAISE;+ END score;+END PKG_FLOW;diff --git a/crates/dbx-sql-schema/src/schema_diff.rs b/crates/dbx-sql-schema/src/schema_diff.rsindex 902cadf423..8ba1179ace 100644--- a/crates/dbx-sql-schema/src/schema_diff.rs+++ b/crates/dbx-sql-schema/src/schema_diff.rs@@ -20,12 +20,15 @@ use crate::table_structure_sql::{build_sqlserver_drop_default_constraint_sql, build_sqlserver_table_comment_sql, sqlserver_unicode_string_literal,};use crate::types::{- ColumnInfo, ForeignKeyInfo, FunctionInfo, IndexInfo, OwnerInfo, RuleInfo, SequenceInfo, TableInfo, TriggerInfo,+ ColumnInfo, ForeignKeyInfo, FunctionInfo, IndexInfo, ObjectSourceKind, OwnerInfo, RuleInfo, SequenceInfo,+ TableInfo, TriggerInfo,};mod oracle_routines;mod sqlserver_dependencies;-pub use oracle_routines::{diff_oracle_routines, oracle_routine_diff_sql, OracleRoutineCompareContext};+pub use oracle_routines::{+ diff_oracle_routines, oracle_routine_diff_sql, OracleRoutineCompareContext, OracleRoutineCompareIdentity,+};use sqlserver_dependencies::build_dependency_aware_alter_column_batch;@@ -168,6 +171,8 @@ pub struct FunctionDiff {#[serde(rename = "type")]pub diff_type: String,pub name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub program_kind: Option<ObjectSourceKind>,#[serde(skip_serializing_if = "Option::is_none")]pub source: Option<FunctionInfo>,#[serde(skip_serializing_if = "Option::is_none")]@@ -2236,6 +2241,16 @@ pub fn prepare_schema_diff(options: SchemaDiffPreparationOptions) -> SchemaDiffP);if let Some(context) = &options.oracle_routines {for diff in &function_diffs {+ if diff.diff_type == "removed"+ && diff.program_kind == Some(ObjectSourceKind::PackageBody)+ && function_diffs.iter().any(|other| {+ other.name == diff.name+ && other.diff_type == "removed"+ && other.program_kind == Some(ObjectSourceKind::Package)+ })+ {+ continue;+ }if let Ok(sql) = oracle_routine_diff_sql(diff, context) {if !sql.is_empty() {if !sync_sql.is_empty() {@@ -4067,6 +4082,7 @@ pub fn diff_functions(source: &[FunctionInfo], target: &[FunctionInfo]) -> Vec<Flet Some(target_fn) = target_map.get(&key) else {diffs.push(FunctionDiff {diff_type: "added".to_string(),+ program_kind: None,name: source_fn.name.clone(),source: Some(source_fn.clone()),target: None,@@ -4088,6 +4104,7 @@ pub fn diff_functions(source: &[FunctionInfo], target: &[FunctionInfo]) -> Vec<Fif !changes.is_empty() {diffs.push(FunctionDiff {diff_type: "modified".to_string(),+ program_kind: None,name: source_fn.name.clone(),source: Some(source_fn.clone()),target: Some((*target_fn).clone()),@@ -4101,6 +4118,7 @@ pub fn diff_functions(source: &[FunctionInfo], target: &[FunctionInfo]) -> Vec<Fif !source_map.contains_key(&key) {diffs.push(FunctionDiff {diff_type: "removed".to_string(),+ program_kind: None,name: target_fn.name.clone(),source: None,target: Some(target_fn.clone()),@@ -6904,6 +6922,10 @@ fn generate_schema_sync_sql_inner(lines.push(String::new());lines.push("-- Functions".to_string());for diff in function_diffs {+ if matches!(diff.program_kind, Some(ObjectSourceKind::Package | ObjectSourceKind::PackageBody)) {+ lines.push("-- Package DDL requires a reviewed package plan.".into());+ continue;+ }match diff.diff_type.as_str() {"added" | "modified" => {if let Some(source) = &diff.source {@@ -8372,6 +8394,7 @@ mod tests {fn sqlserver_function_and_sequence_changes_use_tsql_verbs() {let function = FunctionDiff {diff_type: "modified".into(),+ program_kind: None,name: "next_value".into(),source: Some(FunctionInfo {name: "next_value".into(),@@ -8385,6 +8408,7 @@ mod tests {};let removed_function = FunctionDiff {diff_type: "removed".into(),+ program_kind: None,name: "old_value".into(),source: None,target: None,@@ -8723,6 +8747,7 @@ mod tests {let native_function = FunctionDiff {diff_type: "modified".into(),+ program_kind: None,name: "next_value".into(),source: Some(FunctionInfo {name: "next_value".into(),@@ -8770,6 +8795,7 @@ mod tests {let foreign_function = FunctionDiff {diff_type: "added".into(),+ program_kind: None,name: "pg_only".into(),source: Some(FunctionInfo {name: "pg_only".into(),@@ -15473,6 +15499,7 @@ mod tests {fn postgres_function_sequence_rule_owner_use_profile_templates() {let fn_diff = FunctionDiff {diff_type: "added".into(),+ program_kind: None,name: "f1".into(),source: Some(FunctionInfo {name: "f1".into(),@@ -15543,6 +15570,7 @@ mod tests {fn postgres_function_sync_reuses_native_functiondef_header_once() {let function = |arguments: &str, definition: &str| FunctionDiff {diff_type: "added".into(),+ program_kind: None,name: "armor".into(),source: Some(FunctionInfo {name: "armor".into(),@@ -15588,6 +15616,7 @@ mod tests {fn mysql_skips_function_sequence_when_templates_absent() {let fn_diff = FunctionDiff {diff_type: "added".into(),+ program_kind: None,name: "f1".into(),source: Some(FunctionInfo {name: "f1".into(),diff --git a/crates/dbx-sql-schema/src/schema_diff/oracle_routines.rs b/crates/dbx-sql-schema/src/schema_diff/oracle_routines.rsindex a9c1830bd7..b5a1c19d85 100644--- a/crates/dbx-sql-schema/src/schema_diff/oracle_routines.rs+++ b/crates/dbx-sql-schema/src/schema_diff/oracle_routines.rs@@ -17,6 +17,18 @@ pub struct OracleRoutineCompareContext {pub target_enumeration_complete: bool,pub source_incomplete_names: Vec<String>,pub target_incomplete_names: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub object_kinds: Option<Vec<ObjectSourceKind>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub source_incomplete_objects: Option<Vec<OracleRoutineCompareIdentity>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub target_incomplete_objects: Option<Vec<OracleRoutineCompareIdentity>>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct OracleRoutineCompareIdentity {+ pub name: String,+ pub kind: ObjectSourceKind,}impl OracleRoutineCompareContext {@@ -26,16 +38,63 @@ impl OracleRoutineCompareContext {&& !self.source_schema.is_empty()&& !self.target_schema.is_empty()}++ fn package_enabled(&self, kind: &ObjectSourceKind) -> bool {+ is_package(kind) && self.object_kinds.as_ref().is_some_and(|kinds| kinds.contains(kind))+ }++ fn readable(&self, kind: &ObjectSourceKind) -> bool {+ if is_package(kind) && !self.package_enabled(kind) {+ return false;+ }+ self.supported()+ || (self.package_enabled(kind)+ && matches!(self.source_database_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle)+ && matches!(self.target_database_type, DatabaseType::Oracle | DatabaseType::OceanbaseOracle)+ && !self.source_schema.is_empty()+ && !self.target_schema.is_empty())+ }+}++fn is_package(kind: &ObjectSourceKind) -> bool {+ matches!(kind, ObjectSourceKind::Package | ObjectSourceKind::PackageBody)}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()),+ "PACKAGE" => Ok(ObjectSourceKind::Package),+ "PACKAGE_BODY" => Ok(ObjectSourceKind::PackageBody),+ _ => Err("Program kind must be exactly PROCEDURE, FUNCTION, PACKAGE or PACKAGE_BODY".into()),}}+fn comparison_key(function: &FunctionInfo, typed: bool) -> (&'static str, &str) {+ let namespace = if typed {+ match function.function_type.as_str() {+ "PACKAGE" => "PACKAGE",+ "PACKAGE_BODY" => "PACKAGE_BODY",+ _ => "ROUTINE",+ }+ } else {+ "ROUTINE"+ };+ (namespace, function.name.as_str())+}++fn incomplete(+ objects: Option<&[OracleRoutineCompareIdentity]>,+ names: &[String],+ name: &str,+ kind: &ObjectSourceKind,+) -> bool {+ objects.map_or_else(+ || names.iter().any(|candidate| candidate == name),+ |objects| objects.iter().any(|object| object.name == name && object.kind == *kind),+ )+}+fn definition_input(function: &FunctionInfo,context: &OracleRoutineCompareContext,@@ -60,32 +119,66 @@ pub fn diff_oracle_routines(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 typed = context.object_kinds.is_some();+ let included = |function: &&FunctionInfo| {+ context.object_kinds.as_ref().is_none_or(|kinds| kind(function).map_or(true, |kind| kinds.contains(&kind)))+ };+ let source_map = source+ .iter()+ .filter(included)+ .map(|function| (comparison_key(function, typed), function))+ .collect::<BTreeMap<_, _>>();+ let target_map = target+ .iter()+ .filter(included)+ .map(|function| (comparison_key(function, typed), 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();+ .map(|key| {+ let name = key.1;+ let source = source_map.get(&key).copied();+ let target = target_map.get(&key).copied();+ let object_kind = kind(source.or(target).expect("comparison keys have an object"));let mut diff = FunctionDiff {diff_type: "unreadable".into(),+ program_kind: if typed { object_kind.as_ref().ok().cloned() } else { None },name: name.into(),source: source.cloned(),target: target.cloned(),changes: Vec::new(),};let compared = (|| {- if !context.supported() {+ let object_kind = object_kind.as_ref().map_err(Clone::clone)?;+ if !context.readable(object_kind) {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 let Some(source) = source {+ if incomplete(+ if typed { context.source_incomplete_objects.as_deref() } else { None },+ &context.source_incomplete_names,+ name,+ &kind(source)?,+ ) {+ 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 let Some(target) = target {+ if incomplete(+ if typed { context.target_incomplete_objects.as_deref() } else { None },+ &context.target_incomplete_names,+ name,+ &kind(target)?,+ ) {+ 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());@@ -93,6 +186,18 @@ pub fn diff_oracle_routines(if target.is_none() && !context.target_enumeration_complete {return Err("Target inventory is incomplete; absence and creation are not established".into());}+ if typed+ && source_map.values().filter(|object| object.name == name).any(|source| {+ target_map.values().filter(|object| object.name == name).any(|target| {+ kind(source)+ .ok()+ .zip(kind(target).ok())+ .is_some_and(|(source, target)| is_package(&source) != is_package(&target))+ })+ })+ {+ return Ok("conflict");+ }match (source, target) {(Some(source), Some(target)) => {if kind(source)? != kind(target)? {@@ -139,6 +244,17 @@ pub fn oracle_routine_diff_sql(diff: &FunctionDiff, context: &OracleRoutineCompaif !context.supported() {return Err("Oracle routine target adaptation requires the same product type".into());}+ if let Some(function) = diff.source.as_ref().or(diff.target.as_ref()) {+ let object_kind = kind(function)?;+ if is_package(&object_kind)+ && (!context.package_enabled(&object_kind) || diff.program_kind.as_ref() != Some(&object_kind))+ {+ return Err("Package target SQL requires its explicit program kind and comparison scope".into());+ }+ if diff.program_kind.as_ref().is_some_and(|kind| *kind != object_kind || function.name != diff.name) {+ return Err("Program diff identity does not match its definition".into());+ }+ }match diff.diff_type.as_str() {"added" | "modified" => {let source = diff.source.as_ref().ok_or("Routine source is unavailable")?;@@ -153,7 +269,10 @@ pub fn oracle_routine_diff_sql(diff: &FunctionDiff, context: &OracleRoutineCompalet target = diff.target.as_ref().ok_or("Routine target is unavailable")?;let keyword = match kind(target)? {ObjectSourceKind::Procedure => "PROCEDURE",- _ => "FUNCTION",+ ObjectSourceKind::Function => "FUNCTION",+ ObjectSourceKind::Package => "PACKAGE",+ ObjectSourceKind::PackageBody => "PACKAGE BODY",+ _ => return Err("Unsupported program kind".into()),};Ok(format!("DROP {keyword} \"{}\".\"{}\";",@@ -181,6 +300,9 @@ mod tests {target_enumeration_complete: true,source_incomplete_names: Vec::new(),target_incomplete_names: Vec::new(),+ object_kinds: None,+ source_incomplete_objects: None,+ target_incomplete_objects: None,}}@@ -198,6 +320,153 @@ mod tests {}}+ fn package_context() -> OracleRoutineCompareContext {+ let mut value = serde_json::to_value(context()).unwrap();+ value["objectKinds"] = serde_json::json!(["PROCEDURE", "FUNCTION", "PACKAGE", "PACKAGE_BODY"]);+ serde_json::from_value(value).unwrap()+ }++ fn package(name: &str, body: bool, value: u32) -> FunctionInfo {+ let quoted_name = name.replace('"', "\"\"");+ FunctionInfo {+ name: name.into(),+ function_type: if body { "PACKAGE_BODY" } else { "PACKAGE" }.into(),+ data_type: String::new(),+ arguments: String::new(),+ definition: if body {+ format!("PACKAGE BODY \"{quoted_name}\" AS FUNCTION f RETURN NUMBER IS BEGIN RETURN {value}; END; END;")+ } else {+ format!("PACKAGE \"{quoted_name}\" AS c CONSTANT NUMBER := {value}; FUNCTION f RETURN NUMBER; END;")+ },+ }+ }++ #[test]+ fn package_specification_and_body_have_explicit_separate_identities_in_every_state() {+ let context = package_context();+ for state in ["equal", "modified", "added", "removed"] {+ let source = if state == "removed" {+ vec![]+ } else {+ vec![package("Pkg.With.Dot", false, 2), package("Pkg.With.Dot", true, 2)]+ };+ let target = if state == "added" {+ vec![]+ } else {+ let value = if state == "modified" { 1 } else { 2 };+ vec![package("Pkg.With.Dot", false, value), package("Pkg.With.Dot", true, value)]+ };+ let diffs = diff_oracle_routines(&source, &target, &context);+ assert_eq!(diffs.len(), 2, "{state}: a pair must not collapse by name");+ assert!(diffs.iter().all(|diff| diff.diff_type == state), "{state}: {diffs:?}");+ let kinds = diffs+ .iter()+ .map(|diff| serde_json::to_value(diff).unwrap()["programKind"].as_str().unwrap().to_string())+ .collect::<BTreeSet<_>>();+ assert_eq!(kinds, BTreeSet::from(["PACKAGE".into(), "PACKAGE_BODY".into()]));+ }+ }++ #[test]+ fn a_body_read_failure_does_not_mark_its_same_name_specification_unreadable() {+ let mut value = serde_json::to_value(package_context()).unwrap();+ value["sourceIncompleteNames"] = serde_json::json!(["P"]);+ value["sourceIncompleteObjects"] = serde_json::json!([{"name":"P","kind":"PACKAGE_BODY"}]);+ let context = serde_json::from_value(value).unwrap();+ let pair = vec![package("P", false, 1), package("P", true, 1)];+ let diffs = diff_oracle_routines(&pair, &pair, &context);+ assert_eq!(diffs.len(), 2);+ for diff in diffs {+ let kind = serde_json::to_value(&diff).unwrap()["programKind"].as_str().unwrap().to_string();+ assert_eq!(diff.diff_type, if kind == "PACKAGE" { "equal" } else { "unreadable" });+ }+ }++ #[test]+ fn kind_scoped_read_failures_follow_each_actual_side_of_a_standalone_conflict() {+ let mut value = serde_json::to_value(package_context()).unwrap();+ value["targetIncompleteNames"] = serde_json::json!(["P"]);+ value["targetIncompleteObjects"] = serde_json::json!([{"name":"P","kind":"FUNCTION"}]);+ let context = serde_json::from_value(value).unwrap();+ let source = FunctionInfo {+ function_type: "PROCEDURE".into(),+ definition: "PROCEDURE P AS BEGIN NULL; END;".into(),+ ..function("P", "")+ };+ let target = function("P", "retained target");+ let diffs = diff_oracle_routines(&[source], std::slice::from_ref(&target), &context);+ assert_eq!(diffs.len(), 1);+ assert_eq!(diffs[0].diff_type, "unreadable");+ assert_eq!(diffs[0].target.as_ref().unwrap().definition, target.definition);+ assert!(oracle_routine_diff_sql(&diffs[0], &context).is_err());+ }++ #[test]+ fn cross_product_packages_are_readable_but_never_automatic_target_sql() {+ let mut context = package_context();+ context.source_database_type = DatabaseType::Oracle;+ let source = vec![package("P", false, 1), function("Standalone", "v")];+ let diffs = diff_oracle_routines(&source, &[], &context);+ assert_eq!(diffs.iter().find(|diff| diff.name == "P").unwrap().diff_type, "added");+ assert_eq!(diffs.iter().find(|diff| diff.name == "Standalone").unwrap().diff_type, "unreadable");+ assert!(diffs.iter().all(|diff| oracle_routine_diff_sql(diff, &context).is_err()));+ }++ #[test]+ fn package_deletion_sql_distinguishes_body_only_and_the_implicit_pair_drop() {+ let context = package_context();+ let pair = vec![package("P", false, 1), package("P", true, 1)];+ let diffs = diff_oracle_routines(&pair[..1], &pair, &context);+ let body = diffs.iter().find(|diff| diff.diff_type == "removed").unwrap();+ assert_eq!(oracle_routine_diff_sql(body, &context).unwrap(), "DROP PACKAGE BODY \"Target.Owner\".\"P\";");+ let prepared = prepare_schema_diff(SchemaDiffPreparationOptions {+ target_functions: pair,+ database_type: DatabaseType::OceanbaseOracle,+ oracle_routines: Some(context),+ ..Default::default()+ });+ assert_eq!(prepared.sync_sql.trim(), "DROP PACKAGE \"Target.Owner\".\"P\";");+ }++ #[test]+ fn package_namespace_conflicts_and_legacy_routine_kind_conflicts_remain_unresolved() {+ let context = package_context();+ let diffs = diff_oracle_routines(&[package("P", false, 1)], &[function("P", "v")], &context);+ assert!(!diffs.is_empty());+ assert!(diffs.iter().all(|diff| diff.diff_type == "conflict"));+ assert!(diffs.iter().all(|diff| oracle_routine_diff_sql(diff, &context).is_err()));+ let procedure = FunctionInfo {+ function_type: "PROCEDURE".into(),+ definition: "PROCEDURE P AS BEGIN NULL; END;".into(),+ ..function("P", "")+ };+ let diffs = diff_oracle_routines(&[procedure], &[function("P", "v")], &context);+ assert_eq!(diffs.len(), 1);+ assert_eq!(diffs[0].diff_type, "conflict");+ }++ #[test]+ fn a_package_never_falls_through_generic_function_ddl_templates() {+ let diff: FunctionDiff = serde_json::from_value(+ serde_json::json!({"type":"removed","name":"P","programKind":"PACKAGE_BODY","target":package("P",true,1)}),+ )+ .unwrap();+ let sql = crate::schema_diff::generate_schema_sync_sql(+ &[],+ &[diff],+ &[],+ &[],+ &[],+ DatabaseType::Mysql,+ Some("T"),+ false,+ None,+ &[],+ );+ assert!(!sql.contains("DROP FUNCTION"));+ assert!(sql.contains("reviewed package plan"));+ }+#[test]fn real_preparation_keeps_all_four_states_and_kind() {let source = vec![diff --git a/crates/dbx-tauri-schema/src/commands.rs b/crates/dbx-tauri-schema/src/commands.rsindex 5f7d555801..5514e4817a 100644--- a/crates/dbx-tauri-schema/src/commands.rs+++ b/crates/dbx-tauri-schema/src/commands.rs@@ -789,13 +789,15 @@ pub async fn load_schema_diff_routines(database: String,schema: String,selected_routines: Option<Vec<String>>,+ object_kinds: Option<Vec<db::ObjectSourceKind>>,+ selected_objects: Option<Vec<dbx_core::schema::oracle_routines::RoutineSelection>>,) -> Result<dbx_core::schema::oracle_routines::RoutineSnapshot, String> {- dbx_core::schema::oracle_routines::load_selected_schema_diff_routines_core(+ dbx_core::schema::oracle_routines::load_schema_diff_routines_with_options_core(&state,&connection_id,&database,&schema,- selected_routines.as_deref(),+ dbx_core::schema::oracle_routines::RoutineReadOptions { object_kinds, selected_objects, selected_routines },).await}diff --git a/crates/dbx-web/src/routes/schema.rs b/crates/dbx-web/src/routes/schema.rsindex b54897ceaa..d76f5e6ab6 100644--- a/crates/dbx-web/src/routes/schema.rs+++ b/crates/dbx-web/src/routes/schema.rs@@ -998,6 +998,8 @@ pub struct RoutineSnapshotQuery {#[serde(flatten)]scope: SchemaQuery,selected_routines: Option<String>,+ object_kinds: Option<String>,+ selected_objects: Option<String>,}pub async fn load_schema_diff_routines(@@ -1011,12 +1013,24 @@ pub async fn load_schema_diff_routines(.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(+ let object_kinds = query+ .object_kinds+ .as_deref()+ .map(serde_json::from_str::<Vec<dbx_core::db::ObjectSourceKind>>)+ .transpose()+ .map_err(|error| AppError::from(format!("Invalid program object kinds: {error}")))?;+ let selected_objects = query+ .selected_objects+ .as_deref()+ .map(serde_json::from_str::<Vec<dbx_core::schema::oracle_routines::RoutineSelection>>)+ .transpose()+ .map_err(|error| AppError::from(format!("Invalid selected program identities: {error}")))?;+ let snapshot = dbx_core::schema::oracle_routines::load_schema_diff_routines_with_options_core(&state.app,&q.connection_id,q.database.as_deref().unwrap_or(""),q.schema.as_deref().unwrap_or(""),- selected_routines.as_deref(),+ dbx_core::schema::oracle_routines::RoutineReadOptions { object_kinds, selected_objects, selected_routines },).await.map_err(AppError::from)?;diff --git a/crates/dbx-web/src/routes/transfer.rs b/crates/dbx-web/src/routes/transfer.rsindex 7a5a90c4f2..fc5996e3c1 100644--- a/crates/dbx-web/src/routes/transfer.rs+++ b/crates/dbx-web/src/routes/transfer.rs@@ -33,6 +33,9 @@ fn send_transfer_progress(channel: &TransferProgressChannel, progress: &transferfn terminal_transfer_error(req: &TransferRequest, error: impl ToString) -> transfer::TransferProgress {transfer::TransferProgress {+ oracle_package_approval: None,+ oracle_package_preflight: None,+ oracle_routine_operation: None,transfer_id: req.transfer_id.clone(),table: String::new(),table_index: 0,@@ -425,6 +428,7 @@ mod tests {create_table: false,drop_target_before_create: false,drop_target_confirmed: false,+ oracle_packages: None,content: TransferContent::DataOnly,objects: Some(Vec::new()),mode: TransferMode::Append,diff --git a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.javaindex 9d063808fb..91ba7263d6 100644--- a/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java+++ b/plugins/jdbc/src/main/java/app/dbx/jdbc/DbxJdbcPlugin.java@@ -901,7 +901,8 @@ public final class DbxJdbcPlugin {database,metadataText(params, "schema", exactIdentity),exactIdentity ? metadataText(params, "name", true) : requireText(params, "name"),- requireText(params, "object_type"), exactIdentity+ requireText(params, "object_type"), exactIdentity,+ params.path("include_source_origin").asBoolean(false));case "getColumns" -> getColumns(connection,@@ -5316,6 +5317,11 @@ public final class DbxJdbcPlugin {}private static JsonNode getObjectSource(JsonNode connection, String database, String schema, String name, String objectType, boolean exactIdentity)+ throws SQLException {+ return getObjectSource(connection, database, schema, name, objectType, exactIdentity, false);+ }++ private static JsonNode getObjectSource(JsonNode connection, String database, String schema, String name, String objectType, boolean exactIdentity, boolean includeOrigin)throws SQLException {Connection conn = openConnection(connection);if (driverQuirks(connection).useOracleMetadata()) {@@ -5325,6 +5331,9 @@ public final class DbxJdbcPlugin {return oracleTypeSource(conn, owner, name, metadataType);}String owner = exactIdentity ? schema : oracleEffectiveSchema(conn, schema);+ if (includeOrigin && "PACKAGE".equals(metadataType)) {+ metadataType = "PACKAGE_SPEC";+ }String sql = "SELECT DBMS_METADATA.GET_DDL(?, ?, ?) FROM DUAL";try (PreparedStatement ps = conn.prepareStatement(sql)) {ps.setString(1, metadataType);@@ -5339,6 +5348,9 @@ public final class DbxJdbcPlugin {item.put("object_type", objectType);putNullable(item, "schema", owner);putNullable(item, "source", rs.getString(1));+ if (includeOrigin) {+ item.put("source_origin", "oracle-metadata");+ }return item;}}diff --git a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.javaindex b3133cd756..9e1fe4af36 100644--- a/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java+++ b/plugins/jdbc/src/test/java/app/dbx/jdbc/DbxJdbcPluginTest.java@@ -2283,13 +2283,13 @@ final class DbxJdbcPluginTest {request("executeQuery", """{"connection": %s,- "sql": "CREATE SCHEMA IF NOT EXISTS app"+ "sql": "CREATE SCHEMA IF NOT EXISTS catalog_fallback"}""".formatted(CONNECTION));request("executeQuery", """{"connection": %s,- "sql": "CREATE TABLE IF NOT EXISTS app.people (id INT PRIMARY KEY, name VARCHAR(30))"+ "sql": "CREATE TABLE IF NOT EXISTS catalog_fallback.people (id INT PRIMARY KEY, name VARCHAR(30))"}""".formatted(CONNECTION));@@ -2297,7 +2297,7 @@ final class DbxJdbcPluginTest {{"connection": %s,"database": "UNRELATED_CATALOG",- "schema": "APP"+ "schema": "CATALOG_FALLBACK"}""".formatted(CONNECTION));@@ -3780,6 +3780,43 @@ final class DbxJdbcPluginTest {}}+ @Test+ void strictOraclePackageSourceCarriesMetadataOriginWithoutChangingOrdinarySource() throws Exception {+ List<String> metadataKinds = new ArrayList<>();+ Connection conn = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[]{Connection.class}, (proxy, method, args) -> {+ if (method.getName().equals("getAutoCommit")) return true;+ if (method.getName().equals("prepareStatement")) {+ String sql = (String) args[0];+ return Proxy.newProxyInstance(PreparedStatement.class.getClassLoader(), new Class<?>[]{PreparedStatement.class}, (statement, invoked, values) -> {+ if (invoked.getName().equals("setString") && sql.contains("GET_DDL") && values[0].equals(1)) metadataKinds.add((String) values[1]);+ if (invoked.getName().equals("executeQuery")) return rowsResultSet(new String[]{"VALUE"}, new Object[][]{{sql.contains("all_users") ? "APP" : "CREATE OR REPLACE PACKAGE APP.P AS END;"}});+ return defaultValue(invoked.getReturnType());+ });+ }+ return defaultValue(method.getReturnType());+ });+ Driver driver = (Driver) Proxy.newProxyInstance(Driver.class.getClassLoader(), new Class<?>[]{Driver.class}, (proxy, method, args) -> {+ if (method.getName().equals("acceptsURL")) return ((String) args[0]).startsWith("jdbc:oracle:dbx-package-source:");+ if (method.getName().equals("connect")) return ((String) args[0]).startsWith("jdbc:oracle:dbx-package-source:") ? conn : null;+ return defaultValue(method.getReturnType());+ });+ String connection = "{\"connection_string\":\"jdbc:oracle:dbx-package-source:test\",\"username\":\"APP\"}";+ DriverManager.registerDriver(driver);+ try {+ for (boolean strict : new boolean[]{false, true}) {+ JsonNode response = request("getObjectSource", "{\"connection\":" + connection + ",\"schema\":\"APP\",\"name\":\"P\",\"object_type\":\"PACKAGE\",\"include_source_origin\":" + strict + "}");+ assertFalse(response.has("error"), response.toString());+ JsonNode result = response.path("result");+ assertEquals("PACKAGE", result.path("object_type").asText());+ assertEquals(strict, result.has("source_origin"));+ if (strict) assertEquals("oracle-metadata", result.path("source_origin").asText());+ }+ assertEquals(List.of("PACKAGE", "PACKAGE_SPEC"), metadataKinds);+ } finally {+ closeAndDeregister(connection, driver);+ }+ }+@Testvoid oracleResolveTableUsesExactNameBeforeUppercaseFallback() throws Exception {Method method = DbxJdbcPlugin.class.getDeclaredMethod("oracleResolveTable", Connection.class, String.class, String.class);